mcp-ksef-pl
This server enables AI agents to work with Polish electronic invoicing (KSeF) and cross-border Peppol invoices, and to validate Polish tax identifiers.
Generate FA(2) invoices (
generate_fa2_invoice): Create KSeF-compliant FA(2) XML invoices from structured data (seller/buyer info, line items, VAT summary, payment details)Generate FA(3) invoices (
generate_fa3_invoice): Create KSeF-compliant FA(3) XML invoices required for KSeF API v2 submissions, supporting Polish NIP, EU VAT numbers, and absent buyer IDsValidate FA(2) invoices (
validate_fa2_invoice): Run XSD schema validation and Polish business rule checks, returning errors and warningsParse FA(2) invoices (
parse_fa2_invoice): Parse FA(2) XML into a structured dictionary (header, seller, buyer, line items)Submit invoices to KSeF (
submit_invoice_to_ksef): Send FA(3) XML to the KSeF platform (API v2) and receive a reference number (requires an external session token)Check KSeF invoice status (
get_ksef_invoice_status): Retrieve the processing status of a submitted invoice by reference numberSearch KSeF invoices (
search_ksef_invoices): Query invoices in KSeF by date range and subject type (seller/buyer direction)Validate Polish NIP (
validate_polish_nip): Verify a 10-digit Polish tax identification number using the official checksum algorithmValidate Polish REGON (
validate_polish_regon): Verify a 9- or 14-digit Polish business registry number using the official checksum algorithmGenerate Peppol invoices (
generate_peppol_invoice): Create Peppol BIS Billing 3.0 / EN 16931 compliant UBL 2.1 XML invoices for cross-border B2B invoicing
mcp-ksef-pl ๐ต๐ฑ
A Python MCP server providing tools for Polish electronic invoicing compliant with KSeF (FA(2)) and Peppol BIS Billing 3.0 / EN 16931. It enables AI agents (Claude, IDEs) to generate, validate, and submit invoices to the Krajowy System e-Faktur (KSeF), as well as validate Polish tax identifiers (NIP and REGON).
Introduction
This package is built on mcp-einvoicing-core, the shared base library for European e-invoicing MCP servers. It provides an OAuth2 HTTP client, token cache, data models, logging utilities, and an exception hierarchy.
mcp-einvoicing-core is installed automatically as a dependency, no additional step is required.
Related MCP server: mcp-fattura-elettronica-it
Installation
Via PyPI (recommended)
pip install mcp-ksef-plOr without prior installation using uvx:
uvx mcp-ksef-plFrom source
git clone https://github.com/cmendezs/mcp-ksef-pl.git
cd mcp-ksef-pl
uv sync --all-extrasConfiguration (environment variables)
Variable | Default | Description |
|
| KSeF environment: |
| โ | KSeF session token (obtained through the challenge-response flow with MF) |
| โ | NIP of the entity submitting invoices |
|
| HTTP request timeout in seconds |
|
| Enforce SPKI SHA-256 pinning on the MF encryption certificate. No-op until fingerprints are populated for the active environment, even when set to |
| โ | Local directory containing your own copy of the OpenPeppol eDEC Code Lists, required by the Peppol codelist tools (not bundled with this package; see |
| โ | Local directory containing your own copy of the CEF "Digital Building Blocks" EN 16931 semantic code lists, required by the EN 16931 codelist tools (not bundled; see |
The EUSR/TSR reporting and MLS tools additionally require the [xslt2] extra (pip install "mcp-ksef-pl[xslt2]") for Schematron validation.
Claude Desktop integration
Add the following configuration to your claude_desktop_config.json file:
{
"mcpServers": {
"ksef-pl": {
"command": "uvx",
"args": ["mcp-ksef-pl"],
"env": {
"KSEF_ENVIRONMENT": "test",
"KSEF_SESSION_TOKEN": "<your-ksef-session-token>",
"KSEF_NIP": "<your-nip>"
}
}
}
}Cursor integration
Cursor supports MCP servers via stdio. Add the configuration to:
Globally (all projects):
~/.cursor/mcp.jsonPer project (this repository only):
.cursor/mcp.json
{
"mcpServers": {
"ksef-pl": {
"command": "uvx",
"args": ["mcp-ksef-pl"],
"env": {
"KSEF_ENVIRONMENT": "test",
"KSEF_SESSION_TOKEN": "<your-ksef-session-token>",
"KSEF_NIP": "<your-nip>"
}
}
}
}Reload the Cursor window (Ctrl+Shift+P โ Reload Window) after saving changes.
Kiro integration
Kiro supports MCP servers through a dedicated configuration file:
Globally:
~/.kiro/settings/mcp.jsonWorkspace:
.kiro/settings/mcp.json
{
"mcpServers": {
"ksef-pl": {
"command": "uvx",
"args": ["mcp-ksef-pl"],
"env": {
"KSEF_ENVIRONMENT": "test",
"KSEF_SESSION_TOKEN": "<your-ksef-session-token>",
"KSEF_NIP": "<your-nip>"
},
"disabled": false,
"autoApprove": []
}
}
}Security tip: instead of entering the token directly, use the syntax
"KSEF_SESSION_TOKEN": "${KSEF_SESSION_TOKEN}", as Kiro resolves shell environment variables at startup.
Available tools
FA(3) / FA(2) invoice handling
Tool | Description |
| Generates a KSeF-compliant FA(3) XML invoice (required for KSeF API v2 submissions) |
| Generates a KSeF-compliant FA(2) XML invoice (legacy format, read-only use) |
| Validates FA(3) XML: XSD validation and FA(3)-specific business rules |
| Validates FA(2) XML: XSD validation (if the schema is available) and business rules |
| Parses FA(2) XML into a structured dictionary |
The official FA(2) and FA(3) XSD schemas ship inside the package (src/mcp_ksef_pl/schemas/)
and are loaded automatically via importlib.resources โ no manual download or configuration
is required. validate_fa2_invoice and validate_fa3_invoice run full XSD validation out
of the box for every installation.
KSeF lifecycle
Tool | Description |
| Submits an FA(3) invoice to the KSeF platform and returns a reference number |
| Retrieves the processing status of an invoice by its reference number |
| Searches invoices in KSeF by date range and direction (seller/buyer) |
Identifier validation
Tool | Description |
| Validates a NIP (10-digit tax identification number) using a checksum algorithm |
| Validates a REGON (9- or 14-digit registry number) using a checksum algorithm |
Peppol / EN 16931
Tool | Description |
| Generates a UBL 2.1 invoice compliant with Peppol BIS Billing 3.0 / EN 16931 |
| Validates a UBL 2.1 Peppol invoice against the CEN EN 16931 base Schematron rules ( |
Peppol network tools
Peppol participant lookup, service-endpoint lookup, a DNS-only diagnostic, AS4 send, Peppol Directory search, and the OpenPeppol eDEC codelist tools are provided by the shared core Peppol tool plugin (mcp_einvoicing_core.peppol.tools.register_peppol_tools), mounted in server.py with a Poland-specific identifier adapter: a bare NIP (e.g. 1234563218) is normalized to the 9945:<digits> Peppol scheme (PL:VAT, per the OpenPeppol eDEC Participant Identifier Schemes code list); an already scheme-qualified identifier (e.g. 9945:1234563218) passes through unchanged. Use these tools to check PEF (Poland's Peppol Access Point for public-procurement B2G invoicing) registration status ahead of generate_peppol_invoice.
peppol_send signs outbound messages with a real wsse:Security signature as of mcp-einvoicing-core v1.20.0 (previously computed and discarded โ see CHANGELOG.md v0.8.0).
Tool | Description |
| Check whether a business is registered on the Peppol network; returns registration status and supported document types |
| Fetch the AS4 endpoint for a participant's document type |
| DNS-only (SML) diagnostic, independent of SMP reachability |
| Transmit a UBL/CII invoice via AS4 |
| Search the public Peppol Directory by participant, name, country, or document type |
| OpenPeppol eDEC codelist lookups (require |
| OpenPeppol eDEC codelist checks and version reporting |
See the mcp-einvoicing-core README for full parameter documentation on these tools.
Peppol reporting and status tools
Added in v0.8.0 via three opt-in core plugins, mounted unconditionally in server.py. Each raises a clear error at call time (not at registration) if its extra or data directory is missing.
Tool | Plugin | Description |
|
| Validate an End User Statistics Report (XSD, then Schematron). Requires the |
|
| Validate a Transaction Statistics Report (XSD, then Schematron). Requires the |
|
| Validate a Message Level Status document (UBL |
|
| Build a document-level MLS response. Requires the |
13 |
| EN 16931 semantic code list lookups/checks (units, VAT categories, etc.). Require |
See the mcp-einvoicing-core README for full parameter documentation on these tools.
KSeF authentication
KSeF API v2 uses a multi-step challenge/redeem flow to issue an AccessToken. This MCP server accepts an already-obtained token and cannot automate the signing step (it requires a qualified electronic signature).
Step-by-step flow
Account setup. Register at the KSeF portal: https://ksef.mf.gov.pl/. Select the target environment (test or production). The test environment is at
https://ksef-test.mf.gov.pl/.Request a challenge. Call the KSeF API to obtain a challenge XML envelope:
curl -s https://ksef-test.mf.gov.pl/auth/challenge \ -H "Accept: application/json" \ -d '{"contextIdentifier": {"type": "onip", "identifier": "YOUR_NIP"}}' \ -H "Content-Type: application/json"The response contains a
challengestring and atimestamp.Sign the challenge. Build an
<InitSessionTokenRequest>XML envelope containing the challenge, then sign it with your qualified e-signature. Accepted signing tools:Qualified e-signature providers: KIR (Szafir), Certum, Sigillum
podpis.gov.pl(government signing portal)Profil Zaufany (Trusted Profile): https://www.podatki.gov.pl/ksef/
Example using
xmlsec1with a PKCS#12 certificate:# Build the challenge XML (template at specs/przyklad-wyzwania.xml) xmlsec1 --sign --pkcs12 your-cert.p12 --pwd "password" \ --output signed-challenge.xml challenge-template.xmlSubmit the signed challenge. POST the signed XML to receive an
authOperationreference:curl -s https://ksef-test.mf.gov.pl/auth/xades-signature \ -H "Content-Type: application/octet-stream" \ --data-binary @signed-challenge.xmlRedeem the AccessToken. Exchange the authenticated operation for an AccessToken:
curl -s https://ksef-test.mf.gov.pl/auth/token/redeem \ -H "Content-Type: application/json" \ -H "Authorization: Bearer <referenceNumber-or-authOperation-token-from-step-4>"The response contains
accessToken.tokenandaccessToken.context.referenceNumber.Set the token. Export the token for this MCP server:
export KSEF_SESSION_TOKEN="<the AccessToken from step 5>"The token is valid for approximately 2 hours from issuance (per MF documentation). After expiry, repeat steps 2-5.
References
KSeF technical documentation: https://www.podatki.gov.pl/ksef/dokumentacja-techniczna-ksef/
Authentication spec (CIRFMF): https://github.com/CIRFMF/ksef-docs/blob/main/uwierzytelnianie.md
Interactive session spec (CIRFMF): https://github.com/CIRFMF/ksef-docs/blob/main/sesja-interaktywna.md
FA(3) migration announcement:
specs/ksef-v2-fa3-migration-announcement-20250630.pdf
Architecture
The server acts as an intelligent communication interface between the AI agent and the KSeF platform and the Peppol network:
[ ERP System / Application ] <--> [ MCP Server ] <--> [ KSeF (MF) / Peppol Network ]
^ |
| v
[ AI Agent (Claude) ] <--- (FA(2) / EN 16931)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.
Invoices go directly to KSeF with your own authentication token; no intermediary is involved.
Tests
# Run unit tests
uv run pytest tests/ -vContributing
Contributions are welcome โ see CONTRIBUTING.md for guidelines.
Other e-invoicing MCP servers
Country | Server |
๐ Global | |
๐ง๐ช Belgium | |
๐ง๐ท Brazil | |
๐ซ๐ท France | |
๐ฉ๐ช Germany | |
๐ฎ๐ณ India | |
๐ฎ๐น Italy | |
๐ฒ๐ฝ Mexico | |
๐ต๐ฑ Poland | |
๐ธ๐ฌ Singapore | |
๐ช๐ธ Spain | |
๐ฆ๐ช United Arab Emirates |
License
This project is distributed under the Apache 2.0 license. See the LICENSE file for details. For the full version history, see CHANGELOG.md.
Available Tools
10 toolsgenerate_fa2_invoiceGenerate Fa2 InvoiceA
Generate a KSeF-compliant FA(2) XML invoice from structured invoice data.
Returns the FA(2) XML string ready for submission to KSeF. The seller's tax_id must be a Polish NIP (10 digits).
Inputs: invoice (required). Returns: result
generate_fa3_invoiceGenerate Fa3 InvoiceA
Generate a KSeF-compliant FA(3) XML invoice from structured invoice data.
FA(3) is required for all new invoice submissions via KSeF API v2. Use this tool โ not generate_fa2_invoice โ before calling submit_invoice_to_ksef.
The seller's tax_id must be a Polish NIP (10 digits). The buyer's tax_id may be a Polish NIP, a EU VAT number (set alt_tax_id), or absent (leave tax_id.identifier empty to emit ).
Returns the FA(3) XML string ready for submit_invoice_to_ksef.
Inputs: invoice (required). Returns: result
generate_peppol_invoiceGenerate Peppol InvoiceA
Generate a Peppol BIS Billing 3.0 / EN 16931 UBL 2.1 XML invoice.
Use this for cross-border B2B invoicing via the Peppol network. For domestic Polish invoicing, use generate_fa2_invoice instead.
Inputs: invoice (required). Returns: result
get_ksef_invoice_statusGet Ksef Invoice StatusA
Retrieve the processing status of a submitted KSeF invoice (API v2).
Inputs: reference_number (required). Returns: object
parse_fa2_invoiceParse Fa2 InvoiceA
Parse a KSeF FA(2) XML invoice into a structured dictionary.
Returns a nested dict with 'header', 'seller', 'buyer', 'invoice', and 'lines' keys.
Inputs: xml_content (required). Returns: object
search_ksef_invoicesSearch Ksef InvoicesC
Query invoices stored in KSeF for a date range.
Inputs: date_to (required), date_from (required), subject_type. Returns: result
submit_invoice_to_ksefSubmit Invoice To KsefA
Submit a FA(3) XML invoice to the KSeF platform (API v2).
KSeF API v2 requires FA(3) format for submission. Use generate_fa2_invoice only for validation or parsing; it produces FA(2) XML which KSeF v2 does not accept. FA(3) generation is tracked in roadmap-2026.md.
Inputs: xml_content (required), session_token. Returns: object
validate_fa2_invoiceValidate Fa2 InvoiceA
Validate a KSeF FA(2) XML invoice.
Runs XSD validation (when the official schema is present) and Polish business-rule checks. Returns a DocumentValidationResult with errors and warnings.
Inputs: xml_content (required). Returns: Output of BaseDocumentValidator.validate(). valid: True if the document passedโฆ
validate_polish_nipValidate Polish NipA
Validate a Polish NIP (tax identification number).
Applies the official 10-digit checksum algorithm. Accepts NIP with or without dashes/spaces.
Returns {'valid': bool, 'nip': str, 'normalized': str}.
Inputs: nip (required). Returns: object
validate_polish_regonValidate Polish RegonA
Validate a Polish REGON (business registry number โ 9 or 14 digits).
Returns {'valid': bool, 'regon': str, 'length': int}.
Inputs: regon (required). Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogโฆ
TDQS
Scored across 10 tools
Most tools target clearly distinct resources and actions, and descriptions explicitly disambiguate the risky pairs (generate_fa2_invoice vs generate_fa3_invoice vs generate_peppol_invoice; submit vs status vs search). However, the presence of both FA(2) and FA(3) generators plus a FA(2)-only validator/parser creates a residual confusion risk for an agent that must remember FA(3) is the submission format.
All names follow a strict snake_case verb_noun pattern (generate_*, validate_*, parse_*, search_*, submit_*, get_*). Verb choice is predictable and resource suffixes are consistent across the FA2/FA3/Peppol variants.
Ten tools is well within the appropriate range and each earns its place: three generation formats, submission, status, search, parsing, validation, and two identifier validators. No obviously redundant or filler tools.
The core lifecycle (generate, validate, submit, status, search, parse) is covered, but coverage is asymmetric: parsing and validation exist only for FA(2) while FA(3) is the only format KSeF v2 accepts, so agents can submit but cannot inspect or validate what they submitted. There is also no fetch-by-KSeF-number/download tool and no UPO/confirmation retrieval, leaving dead ends after submission.
Maintenance
Related MCP Connectors
MCP Spec Compliance MCP โ audits any MCP server.json against the official Model Context Protocol
MCP server for Codat โ companies, connections, invoices, bills and financial statements.
Model Context Protocol server for the Apideck Unified API. Connect any MCP-compatible agent framework to 100+ accounting systems, HRIS platforms, file storage providers, and more through one integration. More information https://www.apideck.com/mcp-server
MCP server for the PDFGate API. Generate PDFs, manage documents and handle e-signatures.
Related MCP Servers
- AlicenseAqualityBmaintenanceModel Context Protocol (MCP) server for French Electronic Invoicing (NF XP Z12-013). Provide tools to validate, generate, and explore API specifications for PDP/OD interoperability.34Apache 2.0
- AlicenseAqualityBmaintenanceModel Context Protocol (MCP) server for Italian Electronic Invoicing (FatturaPA / SDI). Provide tools to validate, generate, and explore API specifications for Sistema di Interscambio (SDI) interoperability.4393 PyPI2Apache 2.0
- AlicenseAqualityBmaintenanceModel Context Protocol (MCP) server for Spanish Electronic Invoicing. Provides tools to generate, validate, and submit invoices across VERI\*FACTU, Facturae/FACe, SII, TicketBAI, and Crea y Crece B2B.2042 PyPI3Apache 2.0
- AlicenseAqualityBmaintenanceModel Context Protocol (MCP) server for Singapore Electronic Invoicing (InvoiceNow / PINT-SG / Peppol 5-Corner Model). Provides tools to validate, generate, and explore API specifications for IRAS / Peppol interoperability.1755 PyPIApache 2.0