Mcp Facturacion Electronica Es

io.github.cmendezs由 GitHub 帳號 cmendezs 發布v0.11.0更新於 Nov 22, 2026

Spanish e-invoicing MCP server: VERI*FACTU, Facturae/FACe, SII, Crea y Crece B2B.

已驗證STDIO僅桌面金融商業與電商

概覽

AI 產生的概覽

面向西班牙電子發票的在地 MCP 伺服器:產生、驗證、簽章並向 AEAT 與 FACe 提交 VERI*FACTU、SII、Facturae/FACe 及 B2B 發票。

可以做什麼
  • 依省份、營業額與 SII 登記情況判斷適用稅制並查詢 B2B 強制實施期限
  • 產生、驗證與作廢帶 SHA-256 雜湊鏈的 VERI*FACTU 紀錄,並產生強制 QR 碼
  • 透過 MTLS 向 AEAT 提交 VERI*FACTU 紀錄並查詢登記狀態
  • 建構、簽章與驗證 Facturae 3.2.2 XML(XAdES),提交至 FACe 並查詢處理狀態
  • 建構 SII 紀錄與更正紀錄、批次提交並查詢已申報發票
  • 產生 UBL 或 Facturae 格式的 EN 16931 B2B 發票,並把 AEAT 原始 XML 回應解析為 JSON
適用情境
適用於需要開立合規電子發票並向 AEAT、FACe 或 SII 申報的西班牙企業、會計或軟體團隊。當希望由助理草擬、檢查或提交發票紀錄並追蹤受理狀態時值得加入。
執行需求
以 Python 套件形式在地執行(pip 或 uvx)。必須設定 AEAT_ENV;提交還需 AEAT_CERTIFICATE_PATH(FNMT-RCM PKCS#12 憑證)、AEAT_CERTIFICATE_PASSWORD 與 AEAT_NIF,FACe 需 FACE_ENV。完整 XSD 驗證需要連網取得遠端結構定義。
安裝前請注意
提交會向 AEAT、FACe 或 SII 報送真實稅務資料,驗證前請將 AEAT_ENV 與 FACE_ENV 設為 sandbox。憑證路徑與其密碼屬敏感憑證,密碼應放在環境變數而非提示詞中。多個工具標註為待監管確認,部分提交路徑尚未實作。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 Mcp Facturacion Electronica Es,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。

其他 MCP 客戶端

參照 儲存庫 中的啟動說明。

README

mcp-facturacion-electronica-es 🇪🇸

English | Espanol

[License] [PyPI version] [Python] [mcp-facturacion-electronica-es MCP server]


Introduction

mcp-facturacion-electronica-es is an MCP (Model Context Protocol) server specialized in Spanish e-invoicing. It provides tools to generate, validate, and submit electronic invoices under the six coexisting systems in Spain: VERI*FACTU, Facturae/FACe, SII, TicketBAI (Basque Country), NaTicket (Navarre), and the B2B obligations of Ley 18/2022 "Crea y Crece". The server is built on mcp-einvoicing-core, the shared base library used by mcp-facture-electronique-fr (France, XP Z12-013) and mcp-einvoicing-be (Belgium, Peppol BIS 3.0), which provides common models, validation abstractions, XML utilities, and the exception hierarchy. mcp-einvoicing-core is installed automatically as a transitive dependency, no additional steps are required.

Spain operates one of the most complex e-invoicing landscapes in Europe, with six overlapping systems that apply depending on taxpayer size, sector, and region. VERI*FACTU (Royal Decree 1007/2023, Order HAC/1177/2024) is the forthcoming mandatory real-time invoice registry for non-SII taxpayers, with hard deadlines in January and July 2027 (RD-ley 15/2025). SII (Suministro Inmediato de Informacion, Immediate Information Supply) already applies to large taxpayers (>6M EUR turnover). The Basque Country runs TicketBAI and Navarre runs NaTicket, both independent of the national AEAT framework. B2G invoicing via Facturae XML on the FACe portal has been mandatory since 2015 (Ley 25/2013).

Installation

From PyPI (recommended)

bash
pip install mcp-facturacion-electronica-es

Without prior installation, using uvx:

bash
uvx mcp-facturacion-electronica-es

From source

bash
git clone https://github.com/cmendezs/mcp-facturacion-electronica-es.gitcd mcp-facturacion-electronica-esuv sync --all-extras

Configuration

All configuration is done through environment variables or a .env file.

AEAT / VERI*FACTU / SII

VariableDescriptionRequired
AEAT_ENVsandbox or productionYes
AEAT_CERTIFICATE_PATHPath to FNMT-RCM PKCS#12 certificateFor submission
AEAT_CERTIFICATE_PASSWORDCertificate passwordFor submission
AEAT_NIFTaxpayer NIFFor submission

FACe

VariableDescriptionRequired
FACE_ENVsandbox or productionYes

FACe authenticates via JWS using the same AEAT_CERTIFICATE_PATH / AEAT_CERTIFICATE_PASSWORD certificate as VERI*FACTU/SII (see the AEAT section above); no separate FACe credentials are required.

Common (inherited from mcp-einvoicing-core)

VariableDescriptionDefault
LOG_LEVELDEBUG, INFO, WARNING, ERRORINFO

Claude Desktop integration

To use this server with Claude, add this configuration to your claude_desktop_config.json file:

json
{  "mcpServers": {    "facturacion-es": {      "command": "uvx",      "args": ["mcp-facturacion-electronica-es"],      "env": {        "AEAT_ENV": "sandbox",        "AEAT_CERTIFICATE_PATH": "/path/to/cert.p12",        "AEAT_CERTIFICATE_PASSWORD": "certificate-password"      }    }  }}

Cursor integration

Cursor supports MCP servers via stdio. Add the configuration in:

  • Global (all projects): ~/.cursor/mcp.json
  • Project (this repository only): .cursor/mcp.json
json
{  "mcpServers": {    "facturacion-es": {      "command": "uvx",      "args": ["mcp-facturacion-electronica-es"],      "env": {        "AEAT_ENV": "sandbox",        "AEAT_CERTIFICATE_PATH": "/path/to/cert.p12",        "AEAT_CERTIFICATE_PASSWORD": "certificate-password"      }    }  }}

Reload the Cursor window (Ctrl+Shift+P then Reload Window) to apply the changes.

Kiro integration

Kiro supports MCP servers via its dedicated configuration file. Two levels are available:

  • Global (all projects): ~/.kiro/settings/mcp.json
  • Workspace (this repository only): .kiro/settings/mcp.json
json
{  "mcpServers": {    "facturacion-es": {      "command": "uvx",      "args": ["mcp-facturacion-electronica-es"],      "env": {        "AEAT_ENV": "sandbox",        "AEAT_CERTIFICATE_PATH": "/path/to/cert.p12",        "AEAT_CERTIFICATE_PASSWORD": "certificate-password"      },      "disabled": false,      "autoApprove": []    }  }}

The file is automatically reloaded on save. You can also open the config via the command palette (Cmd+Shift+P / Ctrl+Shift+P) then MCP.

Kiro security tip: rather than writing secrets in plain text, use the syntax "AEAT_CERTIFICATE_PASSWORD": "${AEAT_CERTIFICATE_PASSWORD}", Kiro resolves shell environment variables at startup.

Available tools

VERI*FACTU

es__generate_verifactu_record

Generates a tamper-proof invoice record (Orden HAC/1177/2024) with SHA-256 Huella chaining that links it to the previous record.

ParameterTypeRequiredDescription
invoiceInvoiceDocumentYesCore invoice model (seller, buyer, lines, VAT)
previous_hashstringNoSHA-256 Huella of the preceding record (null = first in chain)
software_idstringYesIDSistemaInformatico of the certified software
software_nifstringYesNIF of the software manufacturer
invoice_typestringYesF1, F2, R1-R5 or F3
json
{  "tool": "es__generate_verifactu_record",  "arguments": {    "invoice": { "date": "2025-03-15", "number": "2025-0042", "currency": "EUR",      "seller": { "tax_id": { "country_code": "ES", "identifier": "B12345678" }, "name": "Empresa SL" },      "buyer":  { "tax_id": { "country_code": "ES", "identifier": "A98765432" }, "name": "Cliente SA" },      "lines": [{ "line_number": 1, "description": "Servicios", "quantity": 10, "unit_price": 100.00, "vat_rate": 21.0 }]    },    "previous_hash": "3C4A9B...", "software_id": "SW-001", "software_nif": "B87654321", "invoice_type": "F1"  }}

The Huella chaining algorithm (SHA-256 over the keyed campo=valor& canonical string) is confirmed byte-for-byte against AEAT's own huella specification and its worked examples (specs/verifactu/documentation/Veri-Factu_especificaciones_huella_hash_registros.pdf). Generated records validate against the bundled XSD v1.0 (SuministroLR and SuministroInformacion, with the W3C XML-DSig schema resolved locally). ⚠️ Still pending: a live AEAT test-environment acknowledgement.


es__validate_verifactu_record

Validates a VERI*FACTU XML record against the official XSD published with Orden HAC/1177/2024 (BOE-A-2024-22138).

ParameterTypeRequiredDescription
xmlstringYesRaw VERI*FACTU XML record
schema_versionstringNoSchema version (default: "1.0")
json
{ "tool": "es__validate_verifactu_record", "arguments": { "xml": "<RegistroFacturacion>...</RegistroFacturacion>" } }

Structural checks now branch correctly on RegistroAlta vs. RegistroAnulacion (a prior version false-flagged valid RegistroAnulacion documents as missing TipoFactura/CuotaTotal/ImporteTotal, fields that only apply to RegistroAlta). Full XSD-mode validation (SuministroLR.xsd, bundled under resources/verifactu/) requires network access at runtime — it imports the W3C xmldsig-core schema by remote URL — and falls back to the structural checks above when that import can't resolve.


es__submit_verifactu_to_aeat

Submits a signed VERI*FACTU record to the AEAT real-time endpoint via MTLS (FNMT-RCM Class 1 certificate) or, if EINVOICING_SIGNER_SOCKET is configured, via the signer microservice. Respects AEAT_ENV=sandbox|production. The submission endpoint (.../SistemaFacturacion/VerifactuSOAP) is confirmed from the official AEAT WSDL and shared by both the alta/anulación submission and the es__query_verifactu_status query operation.

ParameterTypeRequiredDescription
xmlstringYesSigned VERI*FACTU XML
nifstringYesSender NIF
json
{ "tool": "es__submit_verifactu_to_aeat", "arguments": { "xml": "<RegistroFacturacion>...</RegistroFacturacion>", "nif": "B12345678" } }

The response includes a chain object implementing the accepted-only chain contract: chain.safe_to_chain_from (the submitted record's own emisor_nif/num_serie/fecha/huella) is populated only when AEAT's EstadoRegistro is Correcto or AceptadoConErrores — both mean the record was actually stored under that Huella. Otherwise safe_to_chain_from is null with an explicit warning not to use this record's Huella as the next record's previous_hash, or (for a deferred result) a note to call es__query_verifactu_status first.


es__generate_qr_verifactu

Generates the mandatory VERI*FACTU QR code (HAC/1177/2024 Art. 10) as a base64-encoded PNG. Encodes the AEAT verification URL with the text "Factura verificable en la sede electronica de la AEAT". Candidate for promotion to mcp-einvoicing-core (QR generation). URL format (host, path, nif/numserie/fecha/importe query parameters, and per-parameter URL-encoding) is confirmed against the official AEAT QR specification (specs/verifactu/documentation/DetalleEspecificacTecnCodigoQRfactura.pdf); the URL switches between the sandbox and production ValidarQR host based on AEAT_ENV.

ParameterTypeRequiredDescription
nifstringYesIssuer NIF
invoice_numberstringYesNumSerieFactura
invoice_datestringYesFechaExpedicionFactura (YYYY-MM-DD)
total_amountnumberYesInvoice total including VAT
size_pxintegerNoQR size in pixels (default: 200)
json
{ "tool": "es__generate_qr_verifactu", "arguments": { "nif": "B12345678", "invoice_number": "2025-0042", "invoice_date": "2025-03-15", "total_amount": 1210.00 } }

es__cancel_verifactu_record

Generates a VERI*FACTU cancellation record (RegistroAnulacion, TipoHuella=01) chained to the current fingerprint sequence. Both the anulación Huella (SHA-256 over IDEmisorFacturaAnulada/NumSerieFacturaAnulada/FechaExpedicionFacturaAnulada/Huella/ FechaHoraHusoGenRegistro — a distinct field set from RegistroAlta's, not a reduced copy of it) and the top-level <IDFactura> block's element names are confirmed against the official AEAT huella specification and SuministroInformacion.xsd.

ParameterTypeRequiredDescription
original_invoice_numberstringYesNumSerieFactura to cancel
original_invoice_datestringYesFechaExpedicionFactura (YYYY-MM-DD)
issuer_nifstringYesIssuer NIF
previous_hashstringYesHuella of the last record in the chain
json
{ "tool": "es__cancel_verifactu_record", "arguments": { "original_invoice_number": "2025-0042", "original_invoice_date": "2025-03-15", "issuer_nif": "B12345678", "previous_hash": "3C4A9B..." } }

es__query_verifactu_status

Queries the EstadoRegistro of an already-submitted VERI*FACTU record (ConsultaFactuSistemaFacturacion / ConsultaLR.xsd). Use after a deferred result from es__submit_verifactu_to_aeat: wait retry_after_seconds, then call this tool to confirm the final state (Correcto / AceptadoConErrores / Anulado) before chaining the next record. Requires AEAT_ENV, AEAT_CERTIFICATE_PATH, and AEAT_CERTIFICATE_PASSWORD, same as es__submit_verifactu_to_aeat.

ParameterTypeRequiredDescription
nifstringYesNIF of the ObligadoEmision
namestringYesName/razón social of the ObligadoEmision
invoice_datestringYesInvoice date being queried, YYYY-MM-DD (determines PeriodoImputacion)
num_serie_facturastringNoNumSerieFactura filter (omit to query the whole period)
json
{ "tool": "es__query_verifactu_status", "arguments": { "nif": "B12345678", "name": "Empresa SL", "invoice_date": "2025-03-15", "num_serie_factura": "2025-0042" } }

Root element name (ConsultaFactuSistemaFacturacion) and endpoint — the same .../SistemaFacturacion/VerifactuSOAP URL used by es__submit_verifactu_to_aeat, per the official WSDL — are both confirmed. ⚠️ Still pending: response parsing has not been validated against a live AEAT sandbox acknowledgement.


Facturae / FACe

es__generate_facturae_xml

Generates a Facturae 3.2.2 compliant XML invoice for B2G submission. Uses InvoiceDocument from mcp-einvoicing-core.

ParameterTypeRequiredDescription
invoiceInvoiceDocumentYesCore invoice model
schema_versionstringNoFacturae schema version (default: "3.2.2")
tax_typestringNoIndirect tax regime: IVA (peninsula/Baleares), IPSI (Ceuta/Melilla), or IGIC (Canarias). Mixing tax types on one invoice is not supported. Default: "IVA"
recargo_equivalencia_ratenumberNoRecargo de Equivalencia rate (%), if applicable
recargo_equivalencia_amountnumberNoExplicit Recargo de Equivalencia amount; if omitted, computed as base_imponible * recargo_equivalencia_rate / 100
irpf_ratenumberNoIRPF withholding rate (%), emitted in TaxesWithheld
json
{ "tool": "es__generate_facturae_xml", "arguments": { "invoice": { "date": "2025-03-15", "number": "2025-0042", "seller": { "tax_id": { "country_code": "ES", "identifier": "B12345678" }, "name": "Proveedor SL" }, "buyer": { "tax_id": { "country_code": "ES", "identifier": "S2800000D" }, "name": "Ayuntamiento de Madrid" }, "lines": [{ "line_number": 1, "description": "Suministro", "quantity": 5, "unit_price": 200.00, "vat_rate": 21.0 }] } } }

⚠️ Pending regulatory confirmation


es__sign_facturae_xades

Applies an XAdES-EPES digital signature (ETSI EN 319 132-1) to a Facturae XML document. Candidate for promotion to mcp-einvoicing-core (XAdES signing, score 3/3).

ParameterTypeRequiredDescription
xmlstringYesUnsigned Facturae XML
cert_pathstringYesPath to PKCS#12 certificate (.p12 / .pfx)
signature_policy_idstringNoSignature policy OID (default: Facturae standard)

The certificate password is not accepted as a tool argument (ES-SH-6, avoids plaintext credential exposure in LLM context/logs); set AEAT_CERTIFICATE_PASSWORD instead.

json
{ "tool": "es__sign_facturae_xades", "arguments": { "xml": "<Facturae>...</Facturae>", "cert_path": "/certs/empresa.p12" } }

⚠️ Pending regulatory confirmation


es__submit_to_face

Submits a signed Facturae XML to FACe (Punto General de Entrada de Facturas Electronicas) via the FACe integrator REST API. Authenticates with a JWS-signed JWT (RS256, x5c header) minted from the same AEAT_CERTIFICATE_PATH / AEAT_CERTIFICATE_PASSWORD certificate used for VERI*FACTU/SII, per FACe-manual-api-integradores.pdf s2.3.

ParameterTypeRequiredDescription
xmlstringYesFacturae XML with XAdES signature
administrative_unitstringYesFACe UnidadTramitadora code
accounting_officestringYesFACe OficinasContables code
management_bodystringYesFACe OrganoGestor code
json
{ "tool": "es__submit_to_face", "arguments": { "xml": "<Facturae>...</Facturae>", "administrative_unit": "U00000038", "accounting_office": "U00000038", "management_body": "U00000038" } }

⚠️ Pending regulatory confirmation


es__get_face_invoice_status

Queries the processing status of an invoice on FACe. Returns standard status codes: 1200 (Registered), 2400 (Acknowledged), 3100 (Rejected), 4100 (Paid). The raw FACe response is never echoed to the LLM; only a structured, non-sensitive subset (status_code, codigo, descripcion, numeroRegistro) is returned (ES-SH-7).

ParameterTypeRequiredDescription
invoice_idstringYesFACe registration number
json
{ "tool": "es__get_face_invoice_status", "arguments": { "invoice_id": "FAC-2025-00012345" } }

⚠️ Pending regulatory confirmation


es__validate_facturae_schema

Runs the structural field checklist against a Facturae XML, then attempts full XSD-mode validation against the official Facturae 3.2.2 schema using lxml.

ParameterTypeRequiredDescription
xmlstringYesFacturae XML to validate
schema_versionstringNoSchema version (default: "3.2.2")
json
{ "tool": "es__validate_facturae_schema", "arguments": { "xml": "<Facturae>...</Facturae>" } }

Full XSD-mode validation (Facturaev3_2_2.xml, bundled under resources/facturae/) requires network access at runtime — it imports the W3C xmldsig-core schema by remote URL — and falls back to the structural checks above when that import can't resolve.

⚠️ Pending regulatory confirmation


SII (Suministro Inmediato de Informacion)

es__build_sii_invoice_record

Builds an AEAT SII XML record (issued FacturaExpedida or received FacturaRecibida) conforming to the AEAT SII technical guide v3.0 (April 2024). Supports TipoComunicacion A0/A1/A4.

ParameterTypeRequiredDescription
invoiceInvoiceDocumentYesCore invoice model
record_typestringYes"issued" or "received"
communication_typestringNo"A0" new (default), "A1" modification, "A4" cancellation
json
{ "tool": "es__build_sii_invoice_record", "arguments": { "invoice": { "date": "2025-03-15", "number": "2025-0042" }, "record_type": "issued", "communication_type": "A0" } }

⚠️ Pending regulatory confirmation


es__submit_sii_batch

Submits a batch of invoices (up to 10,000 records) to the AEAT SII SOAP endpoint. Requires MTLS.

ParameterTypeRequiredDescription
recordsarrayYesList of XML strings from es__build_sii_invoice_record
record_typestringYes"issued" or "received"
fiscal_yearintegerYesFiscal year (YYYY)
json
{ "tool": "es__submit_sii_batch", "arguments": { "records": ["<RegistroLRFacturasEmitidas>...</RegistroLRFacturasEmitidas>"], "record_type": "issued", "fiscal_year": 2025 } }

⚠️ Pending regulatory confirmation: AuthMode.MTLS is not yet implemented in mcp-einvoicing-core.


es__query_sii_status

Queries the status of a submitted SII batch via ConsultaFactInformadasEmitidas or ConsultaFactInformadasRecibidas.

ParameterTypeRequiredDescription
nif_titularstringYesNIF of the SII titular (obligado tributario)
nombre_titularstringYesName or company name of the titular
fiscal_yearintegerYesFiscal year (YYYY)
periodstringYesSettlement period: "01".."12" for monthly, or "0A" for annual
record_typestringNo"issued" or "received" (default: "issued")
invoice_numberstringNoNumSerieFacturaEmisor to filter by a specific invoice
emisor_nifstringNoIssuer NIF to filter by (only applies to "received")
json
{ "tool": "es__query_sii_status", "arguments": { "nif_titular": "B12345674", "nombre_titular": "Ejemplo SL", "fiscal_year": 2025, "period": "03", "record_type": "issued" } }

⚠️ Pending regulatory confirmation


es__generate_sii_correction

Generates an SII modification (A1) or cancellation (A4) record referencing the original invoice via IDFactura. The credit note builder is a candidate for mcp-einvoicing-core (score 3/3).

ParameterTypeRequiredDescription
original_invoiceInvoiceDocumentYesInvoice being corrected
corrected_invoiceInvoiceDocumentNoCorrected data (null for A4)
correction_typestringYes"A1" or "A4"
record_typestringYes"issued" or "received"
json
{ "tool": "es__generate_sii_correction", "arguments": { "original_invoice": { "number": "2025-0042" }, "correction_type": "A1", "record_type": "issued" } }

⚠️ Pending regulatory confirmation


Crea y Crece / B2B

es__generate_b2b_einvoice_es

Generates a B2B invoice conforming to EN 16931 in UBL (AEAT public solution profile) or Facturae 3.2.2 format per Ley 18/2022, developed by RD 238/2026 (BOE-A-2026-7295).

ParameterTypeRequiredDescription
invoiceInvoiceDocumentYesCore invoice model
formatstringNo"ubl" (default) or "facturae"
is_copybooleanNoUBL only. Annex I BT-ES-1: true marks a faithful copy (default: original)
json
{ "tool": "es__generate_b2b_einvoice_es", "arguments": { "invoice": { "date": "2025-03-15", "number": "2025-0042" }, "format": "ubl" } }

⚠️ RD 238/2026 confirms the admitted formats (EN 16931: CII/UBL/EDIFACT/Facturae; this tool implements UBL and Facturae). Orden HAC/1028/2026 (BOE-A-2026-20587, in force 2026-10-06) regulates the public e-invoicing solution. The UBL output follows Annex I (BT-23 and BT-24 values, NIF/NIF-IVA party identification, mandatory postal address) and validates against the OASIS UBL 2.5 schema; it covers an ordinary type 380 invoice with one S VAT category per line and none of the Spanish BG-ES groups. The AEAT Schematron rules for EN 16931:2026 are not published, so they are not run [Unverified]. es__check_b2b_mandate_applicability reports the application dates (2027-10-06 for taxpayers above €8M, 2028-10-06 for all others).


es__check_b2b_mandate_applicability

Determines the applicable regime (VERI*FACTU or SII) based on turnover, province code, and SII enrollment. Foral provinces (TicketBAI, NaTicket) are flagged as out of scope. Applies the mutual exclusion logic of Real Decreto 254/2025.

ParameterTypeRequiredDescription
annual_turnover_eurnumberYesAnnual VAT turnover in EUR
tax_address_province_codestringYesINE province code (e.g., "28" Madrid)
enrolled_in_siibooleanNoSII enrollment (default: false)
entity_typestringNo"IS" (Impuesto sobre Sociedades) or "IRPF"
json
{ "tool": "es__check_b2b_mandate_applicability", "arguments": { "annual_turnover_eur": 2500000, "tax_address_province_code": "28", "enrolled_in_sii": false, "entity_type": "IS" } }

⚠️ Pending regulatory confirmation


Utility tools

es__detect_regional_regime

Detects the applicable e-invoicing regime based on the INE province code. Returns VERIFACTU or VERIFACTU+SII.

For the foral provinces (01 Araba, 20 Gipuzkoa, 48 Bizkaia, 31 Navarre), whose TicketBAI and NaTicket systems are out of scope for this package, the response also carries an out_of_scope_warning. All other provinces return VERIFACTU without a warning. Candidate for promotion to mcp-einvoicing-core.

ParameterTypeRequiredDescription
province_codestringYesTwo-digit INE province code
enrolled_in_siibooleanNoSII enrollment (default: false)
json
{ "tool": "es__detect_regional_regime", "arguments": { "province_code": "20", "enrolled_in_sii": false } }

⚠️ Pending regulatory confirmation


es__get_compliance_status

Returns the current mandate deadlines and operating system for a business profile. Reflects RD-ley 15/2025, subject to changes by subsequent legislation. Candidate for promotion to mcp-einvoicing-core (generic deadline registry).

ParameterTypeRequiredDescription
entity_typestringYes"IS" or "IRPF"
province_codestringYesINE province code
annual_turnover_eurnumberNoFor SII threshold check (6M EUR)
enrolled_in_siibooleanNoSII enrollment
json
{ "tool": "es__get_compliance_status", "arguments": { "entity_type": "IS", "province_code": "28", "annual_turnover_eur": 1000000, "enrolled_in_sii": false } }

⚠️ Pending regulatory confirmation


es__parse_aeat_response

Parses and normalizes an AEAT XML response (VERI*FACTU or SII) into structured JSON. Extracts EstadoEnvio (Correcto/AceptadoConErrores/Incorrecto), CSV (secure verification code), and error details. Candidate for promotion to mcp-einvoicing-core (generic vendor XML response parser, score 2/3).

ParameterTypeRequiredDescription
xmlstringYesRaw AEAT XML response
response_typestringNo"verifactu" (default) or "sii"
json
{ "tool": "es__parse_aeat_response", "arguments": { "xml": "<RespuestaRegFactuSistemaFacturacion>...</RespuestaRegFactuSistemaFacturacion>", "response_type": "verifactu" } }

⚠️ Pending regulatory confirmation

Architecture

mcp-facturacion-electronica-es is a country adapter within the mcp-einvoicing family, built on mcp-einvoicing-core.

mcp-einvoicing-core (v0.1.0+)│   BaseDocumentGenerator, BaseDocumentValidator, BaseLifecycleManager│   InvoiceDocument, InvoiceParty, InvoiceLineItem, VATSummary, PaymentTerms│   EInvoicingError, ValidationError, XSDValidationError, PlatformError│   BaseEInvoicingClient, OAuthConfig, AuthMode (OAUTH2 / BEARER / MTLS)│   get_logger, format_amount, xml_element, format_error│├── mcp-facture-electronique-fr    (France — XP Z12-013, Chorus Pro)├── mcp-einvoicing-be              (Belgium — Peppol BIS 3.0, PINT-BE, Mercurius)├── mcp-facturacion-electronica-es (Spain — this package)│   ├── verifactu/   record generation, hash chain, QR, cancellation│   ├── facturae/    Facturae 3.2.2 XML, XAdES-EPES, FACe submission│   ├── sii/         batch building, AEAT SOAP, corrections│   ├── ticketbai/   XML generation, provincial routing, validation│   ├── b2b/         UBL/Facturae Crea y Crece, mandate detector│   └── utils/       regime detection, AEAT response parser, deadline registry├── mcp-fattura-elettronica-it     (Italy — FatturaPA / SDI)└── mcp-ksef-pl                    (Poland — KSeF / FA(2))

Vendor neutrality

This server implements the standard itself: it builds, validates, and signs the document locally. It is not a client for a commercial invoicing platform, and your signing keys and credentials never leave your own infrastructure.

Records and invoices go directly to the tax authority — the AEAT (SII, VeriFactu) or FACe — using your own certificate; no intermediary is involved.

Supported standards

The Spanish e-invoicing ecosystem has six coexisting systems with distinct scopes, formats, and timelines. VERI*FACTU introduces tamper-proof chained invoice records submitted in real time to the AEAT (Agencia Estatal de Administracion Tributaria), applicable to most businesses from 2027 (RD-ley 15/2025). SII is already mandatory for large taxpayers under a 4-day communication window. Facturae XML with XAdES-EPES signing covers all B2G invoicing through the FACe portal. The Basque Country applies TicketBAI independently, with three provincial authorities each maintaining their own XSD schemas and endpoints. Navarre operates NaTicket. The Ley Crea y Crece mandates B2B e-invoicing for all businesses; RD 238/2026 (BOE-A-2026-7295) confirms the admitted formats (EN 16931: CII/UBL/EDIFACT/Facturae), and Orden HAC/1028/2026 regulates the public e-invoicing solution (UBL output follows its Annex I; the AEAT Schematron rules are not yet published). Regime detection based on tax domicile and turnover is a prerequisite to all other operations: use es__detect_regional_regime first.

Regulatory coverage

SystemScopeFormatMandatory fromStatus
VERI*FACTUAll non-SII businessesProprietary XML (XSD v1.0 HAC/1177/2024)IS: Jan 2027 / Others: Jul 2027 (RD-ley 15/2025)Implemented (pending regulatory confirmation)
Facturae / FACeB2G (public sector)Facturae 3.2.2 + XAdES-EPESMandatory since 2015 (Ley 25/2013)Implemented (pending regulatory confirmation)
SIITurnover >6M EUR, VAT groups, REDEMEXML SOAP/REST AEATAlready mandatory (RD 596/2016)Implemented (pending regulatory confirmation)
TicketBAIAraba, Gipuzkoa, BizkaiaProvincial XML + XAdES + QRBy province, 2022-2023Removed from scope (v0.2.0)
Crea y Crece (B2B)All businesses (12/24 months after OM, by turnover)UBL 2.1 or Facturae 3.2.2 (EN 16931); CII/EDIFACT also admitted, not implementedRD 238/2026 published; Orden Ministerial (public solution) pendingImplemented (formats confirmed by RD 238/2026; public-solution wiring deferred to OM)
NaTicketNavarreForal XML + signatureForal mandate (phased rollout)Partial (via es__detect_regional_regime)

SII / VERI*FACTU mutual exclusion (Real Decreto 254/2025): Taxpayers enrolled in SII are exempt from VERI*FACTU. Use es__check_b2b_mandate_applicability before generating any record.

Compliance notes

Notice: Mandate dates reflect RD-ley 15/2025 (December 2025) and are subject to changes by subsequent legislation or AEAT administrative instructions. This software does not constitute legal or tax advice.

Mandate timeline

SystemTargetsDeadline
SIITurnover >6M EUR / VAT groups / REDEMEAlready mandatory (RD 596/2016)
Facturae/FACeAll B2G suppliersAlready mandatory (Ley 25/2013)
TicketBAIAll businesses in the Basque CountryPhased rollout by sector 2022-2023
VERI*FACTUIS (Impuesto sobre Sociedades) taxpayersJanuary 2027 (RD-ley 15/2025)
VERI*FACTUIRPF + other non-SIIJuly 2027 (RD-ley 15/2025)
Crea y Crece B2BTurnover >8M EUR (art. 121 Ley 37/1992)12 months after the Orden Ministerial's entry into force [Unverified date]
Crea y Crece B2BAll other businesses24 months after the Orden Ministerial's entry into force [Unverified date]

Regional exceptions

  • Basque Country: TicketBAI applies instead of VERI*FACTU. Each of the three provinces (Araba, Gipuzkoa, Bizkaia) has a different XSD, endpoint, and software certification process. National AEAT endpoints do not apply.
  • Navarre: NaTicket applies (Hacienda Foral de Navarra). VERI*FACTU does not apply.
  • Ceuta / Melilla: IPSI (not VAT); SII/VERI*FACTU applicability differs, verify with the AEAT.
  • SII / VERI*FACTU mutual exclusion: Real Decreto 254/2025 makes these systems mutually exclusive. Taxpayers enrolled in SII do not submit VERI*FACTU records.

All AEAT submission endpoints require an FNMT-RCM certificate or one from an accredited CA. The AEAT provides a free test environment at prewww2.aeat.es.

Tests

bash
# Install development dependenciesuv sync --all-extras
# Run the full test suiteuv run pytest tests/ -v
# With coverage reportuv run pytest --cov=mcp_facturacion_electronica_es --cov-report=term-missing

Contributing

Open an issue before starting significant work. For reusable utility logic across country adapters, open a core-promotion issue in mcp-einvoicing-core before implementing it: use the scoring rubric (3 = MUST promote, 2 = SHOULD, 1 = keep here).

bash
git clone https://github.com/cmendezs/mcp-facturacion-electronica-es.gitcd mcp-facturacion-electronica-esuv sync --all-extrasuv run pytestmake audit

All regulatory assertions must reference a specific BOE publication, an official XSD version, or an AEAT technical guide version. Do not remove ⚠️ Pending regulatory confirmation without linking the verified source in the PR description.

Other e-invoicing MCP servers

CountryServer
🌍 Globalmcp-einvoicing-core
🇧🇪 Belgiummcp-einvoicing-be
🇧🇷 Brazilmcp-nfe-br
🇫🇷 Francemcp-facture-electronique-fr
🇩🇪 Germanymcp-einvoicing-de
🇮🇳 Indiamcp-einvoicing-in
🇮🇹 Italymcp-fattura-elettronica-it
🇲🇽 Mexicomcp-cfdi-mx
🇵🇱 Polandmcp-ksef-pl
🇸🇬 Singaporemcp-invoicenow-sg
🇪🇸 Spainmcp-facturacion-electronica-es
🇦🇪 United Arab Emiratesmcp-einvoicing-ae

License

Released under the Apache License 2.0. For the full version history, see CHANGELOG.md.

來源:README.md,提交 1b118c6

工具

20

es__generate_verifactu_record

Es Generate Verifactu Record

Genera un registro de factura VERI*FACTU (Orden HAC/1177/2024) con cadena SHA-256 Huella. Devuelve el XML del registro y la Huella para encadenar con el siguiente registro. Llame a es__detect_regional_regime antes para confirmar que el régimen es VERIFACTU.

輸入參數invoice必填impuestosoftware_id必填invoice_typesoftware_nif必填clave_regimenprevious_hashprevious_fechaprevious_num_serieprevious_emisor_nifcalificacion_operacion

es__validate_verifactu_record

Es Validate Verifactu Record

Valida un registro VERI*FACTU XML. Realiza validación estructural y, si el XSD v1.0 (HAC/1177/2024) está disponible en resources/verifactu/, también validación de esquema.

輸入參數xml必填schema_version

es__submit_verifactu_to_aeat

Es Submit Verifactu To Aeat

Envía un registro VERI*FACTU firmado al endpoint en tiempo real de la AEAT mediante MTLS. Usa el certificado FNMT-RCM. Requiere AEAT_ENV, AEAT_CERTIFICATE_PATH y AEAT_CERTIFICATE_PASSWORD. Si la respuesta trae parsed_response.status == 'deferred' (TiempoEsperaEnvio), espere retry_after_seconds y llame a es__query_verifactu_status para confirmar el EstadoRegistro final antes de encadenar el siguiente registro. HUMAN-IN-THE-LOOP: llame sin confirmation_token para recibir un resumen de confirmación y un token; muéstrelo al usuario y vuelva a llamar con confirmation_token para ejecutar el envío real.

輸入參數nif必填xml必填confirmation_token

es__query_verifactu_status

Es Query Verifactu Status

Consulta el EstadoRegistro de un registro VERI*FACTU ya enviado. (ConsultaFactuSistemaFacturacion / ConsultaLR.xsd). Use esta tool tras un resultado 'deferred' de es__submit_verifactu_to_aeat, esperando retry_after_seconds, para confirmar el estado final (Correcto / AceptadoConErrores / Anulado) antes de encadenar el siguiente registro. Requiere AEAT_ENV, AEAT_CERTIFICATE_PATH y AEAT_CERTIFICATE_PASSWORD, igual que es__submit_verifactu_to_aeat.

輸入參數nif必填name必填invoice_date必填num_serie_factura

es__generate_qr_verifactu

Es Generate Qr Verifactu

Genera el código QR obligatorio VERI*FACTU (HAC/1177/2024 Art. 10) como PNG en base64. Encodes la URL de verificación de la AEAT: https://www2.agenciatributaria.gob.es/wlpl/TIKE-CONT/ValidarQR?...

輸入參數nif必填size_pxinvoice_date必填total_amount必填invoice_number必填

es__cancel_verifactu_record

Es Cancel Verifactu Record

Genera un registro de anulacion VERI*FACTU (TipoHuella=01). Encadenado a la secuencia de huellas actual.

輸入參數issuer_nif必填issuer_name必填previous_hash必填previous_fechaprevious_num_serieprevious_emisor_niforiginal_invoice_date必填original_invoice_number必填

es__generate_facturae_xml

Es Generate Facturae Xml

Genera una factura XML conforme a Facturae 3.2.2 para envío B2G al portal FACe. El documento generado está sin firmar; use es__sign_facturae_xades para firmarlo.

輸入參數invoice必填tax_typeirpf_rateirpf_amountschema_versioninvoice_issuer_typeresolution_referencerecargo_equivalencia_raterecargo_equivalencia_amountreceiver_transaction_reference

es__sign_facturae_xades

Es Sign Facturae Xades

Aplica una firma digital XAdES-EPES (ETSI EN 319 132-1) a un documento Facturae XML. Usa el certificado PKCS#12 indicado para firmar con SHA-256 + RSA. La política de firma por defecto es la de Facturae (Orden EHA/962/2007). HUMAN-IN-THE-LOOP: llame sin confirmation_token para recibir un resumen de confirmación y un token; muéstrelo al usuario y vuelva a llamar con confirmation_token para aplicar la firma real.

輸入參數xml必填cert_pathconfirmation_tokensignature_policy_idsignature_policy_hash

es__submit_to_face

Es Submit To Face

Envía un XML Facturae firmado con XAdES a FACe a través de la API REST B2B de FACe v2. FACe = Punto General de Entrada de Facturas Electrónicas. Autenticación JWS (RS256 + x5c) per FACe-manual-api-integradores.pdf s2.3: requiere FACE_ENV y AEAT_CERTIFICATE_PATH (+ AEAT_CERTIFICATE_PASSWORD). HUMAN-IN-THE-LOOP: llame sin confirmation_token para recibir un resumen de confirmación y un token; muéstrelo al usuario y vuelva a llamar con confirmation_token para ejecutar el envío real.

輸入參數xml必填management_body必填accounting_office必填confirmation_tokenadministrative_unit必填

es__get_face_invoice_status

Es Get Face Invoice Status

Consulta el estado de tramitación de una factura en FACe. Códigos: 1200 Registrada, 2400 Reconocida, 3100 Rechazada, 4100 Pagada.

輸入參數invoice_id必填

es__validate_facturae_schema

Es Validate Facturae Schema

Valida un XML Facturae contra el XSD oficial 3.2.2. Realiza validación estructural y, si el XSD está disponible en resources/facturae/, también validación de esquema completa.

輸入參數xml必填schema_version

es__build_sii_invoice_record

Es Build Sii Invoice Record

Construye un registro XML AEAT SII en formato SOAP. Emisión FacturaExpedida o recepción FacturaRecibida, conforme a la guía técnica SII v3.0 (abril 2024). Soporta TipoComunicacion A0 (alta), A1 (modificación) y A4 (baja).

輸入參數invoice必填record_type必填clave_regimencommunication_type

es__submit_sii_batch

Es Submit Sii Batch

Envía un lote de facturas (máximo 10.000 registros) al endpoint SOAP SII de la AEAT. Requiere AEAT_ENV, AEAT_CERTIFICATE_PATH y AEAT_CERTIFICATE_PASSWORD (MTLS). HUMAN-IN-THE-LOOP: llame sin confirmation_token para recibir un resumen de confirmación y un token; muéstrelo al usuario y vuelva a llamar con confirmation_token para ejecutar el envío real.

輸入參數records必填fiscal_year必填record_type必填confirmation_token

es__query_sii_status

Es Query Sii Status

Consulta el estado de facturas en el SII mediante ConsultaFactInformadasEmitidas/Recibidas (SOAP). ES-LC-2: reemplaza el REST GET no funcional por el envelope SOAP correcto. Filtra por ejercicio, periodo y, opcionalmente, por NIF del emisor y numero de factura.

輸入參數period必填emisor_niffiscal_year必填nif_titular必填record_typeinvoice_numbernombre_titular必填

es__generate_sii_correction

Es Generate Sii Correction

Genera un registro de modificación SII (A1) o baja (A4). Referencia la factura original mediante IDFactura.

輸入參數record_type必填correction_type必填original_invoice必填corrected_invoice

es__generate_b2b_einvoice_es

Es Generate B2B Einvoice Es

Genera una factura B2B conforme a EN 16931 en formato UBL o Facturae 3.2.2. Según la Ley 18/2022 'Crea y Crece'. El formato UBL sigue el anexo I de la Orden HAC/1028/2026 (identificador de especificación y tipo de proceso de la solución pública de la AEAT, identificación fiscal del vendedor y del comprador, dirección postal obligatoria) y se valida contra el esquema OASIS UBL 2.5.

輸入參數formatinvoice必填is_copy

es__check_b2b_mandate_applicability

Es Check B2B Mandate Applicability

Determina el régimen de facturación electrónica aplicable. VERI*FACTU o SII, a partir del volumen de operaciones, código de provincia y enrolamiento en SII. Las provincias forales (TicketBAI, NaTicket) se señalan como fuera de alcance. Aplica la lógica de exclusión mutua del Real Decreto 254/2025.

輸入參數entity_typeenrolled_in_siiannual_turnover_eur必填tax_address_province_code必填

es__detect_regional_regime

Es Detect Regional Regime

Detecta el régimen de facturación electrónica aplicable. A partir del código de provincia INE de dos dígitos. Devuelve VERIFACTU o VERIFACTU+SII. Para las provincias forales (Álava, Gipuzkoa, Bizkaia y Navarra), cuyos sistemas TicketBAI y NaTicket quedan fuera del alcance de este servidor, añade además un aviso `out_of_scope_warning`. Usar siempre antes de llamar a cualquier otra herramienta de este servidor.

輸入參數province_code必填enrolled_in_sii

es__get_compliance_status

Es Get Compliance Status

Devuelve los plazos de mandato vigentes y el sistema operativo para un perfil de empresa. Refleja el RD-ley 15/2025 — sujeto a cambios por legislación posterior.

輸入參數entity_type必填province_code必填enrolled_in_siiannual_turnover_eur

es__parse_aeat_response

Es Parse Aeat Response

Analiza y normaliza una respuesta XML de la AEAT (VERI*FACTU o SII) a JSON estructurado. Extrae EstadoEnvio, CSV (código seguro de verificación) y detalle de errores.

輸入參數xml必填response_type

版本歷史

3
  1. v0.11.0最新Nov 22, 2026
  2. v0.10.2Nov 17, 2026
  3. v0.10.1Sep 16, 2026

評分

已滿足適用檢查項的 90%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通25 分
  • 已宣告認證方式10 分

    請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。

  • 已列出工具必需15 分
  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分