mcpField
M
mcp-ksef-pl

mcp-ksef-pl

Local
github.com/cmendezsFinance3Updated 7w ago

About mcp-ksef-pl

mcp-ksef-pl is a Python MCP server for Polish electronic invoicing, covering KSeF and Peppol standards. It generates, validates, and submits invoices, and checks Polish tax and registry identifiers.

Key features

  1. 01Generate and validate FA(3) and FA(2) XML
  2. 02Submit, inspect, and search KSeF invoices
  3. 03Generate and validate Peppol UBL invoices
  4. 04Check Polish NIP and REGON identifiers
  5. 05Look up Peppol participants and endpoints

Use cases

  1. 01Prepare FA(3) invoices for KSeF API v2
  2. 02Check invoice formats and business rules before submission
  3. 03Validate Polish business tax and registry numbers
  4. 04Find Peppol participants and transmit invoices

MCP support

The MCP server exposes invoice generation, validation, KSeF lifecycle, identifier checks, and Peppol network tools to AI agents and other MCP clients. KSeF submissions use a previously obtained session token; the server does not automate the signing-based authentication flow.

Configuration

Local server config is the same for every client. Copy it into your client’s MCP config file.

mcp.json · Universal config
{
"mcpServers": {
"cmendezs-mcp-ksef-pl": {
"command": "uvx",
"args": [
"mcp-ksef-pl"
],
"env": {
"KSEF_SESSION_TOKEN": "<KSEF_SESSION_TOKEN>",
"KSEF_NIP": "<KSEF_NIP>",
"KSEF_ENVIRONMENT": "<KSEF_ENVIRONMENT>",
"KSEF_TIMEOUT": "<KSEF_TIMEOUT>"
}
}
}
}
Run commanduvx mcp-ksef-pl
Environment variables to set
KSEF_SESSION_TOKENSecretKSeF v2 AccessToken obtained via the challenge/redeem auth flow. Required for submit_invoice_to_ksef.
KSEF_NIPNIP (Polish tax identifier, 10 digits) of the entity submitting invoices.
KSEF_ENVIRONMENTTarget KSeF environment: 'production' or 'test' (default: test).
KSEF_TIMEOUTHTTP request timeout in seconds (default: 30).

Local servers need a runtime on your machine (e.g. Node.js 18+). Config file locations differ by client; see your client’s docs.

Packages
pypimcp-ksef-pl0.10.1

Tools

56

Saved tool list · updated 2w ago

ParameterTypeRequiredDescription
invoiceobjectYesEN 16931 invoice extended for KSeF FA(2)/FA(3) submission. National extensions: numer_ksef — KSeF reference number, assigned by the platform post-clearance. Not present on the outbound document; populated from the clearance response and stored here for tracking. The _allowed_profiles class variable is left as None because KSeF does not use EN 16931 GuidelineID URNs. The profile field should be set to the KSeF schema identifier or left to the generating tool's convention.
invoice.noteanyNoInvoice note / reason (BT-22)
invoice.buyerobjectYesBuyer / customer (BG-7)
invoice.buyer.glnanyNoGS1 Global Location Number
invoice.buyer.nipanyNoPolish NIP (10 digits)
invoice.buyer.namestringYesLegal entity name (BT-27 / BT-44)
invoice.buyer.vat_idanyNoVAT number (BT-31 / BT-48)
invoice.buyer.addressanyNo
invoice.buyer.eu_vat_idanyNoEU VAT number for non-PL sellers/buyers
invoice.buyer.contact_nameanyNoContact person name (BT-41 / BT-56)
invoice.buyer.contact_emailanyNoContact email (BT-43 / BT-58)
invoice.buyer.contact_phoneanyNoContact phone (BT-42 / BT-57)
invoice.buyer.eu_vat_countryanyNoEU VAT country code for non-PL sellers/buyers
invoice.buyer.electronic_addressanyNoPeppol / EAS electronic address (BT-34 / BT-49)
invoice.buyer.electronic_address_schemeanyNoEAS scheme code, e.g. '0088' for GLN (BT-34-SchemeID / BT-49-SchemeID)
invoice.sellerobjectYesSeller / supplier (BG-4)
invoice.seller.glnanyNoGS1 Global Location Number
invoice.seller.nipanyNoPolish NIP (10 digits)
invoice.seller.namestringYesLegal entity name (BT-27 / BT-44)
invoice.seller.vat_idanyNoVAT number (BT-31 / BT-48)
invoice.seller.addressanyNo
invoice.seller.eu_vat_idanyNoEU VAT number for non-PL sellers/buyers
invoice.seller.contact_nameanyNoContact person name (BT-41 / BT-56)
invoice.seller.contact_emailanyNoContact email (BT-43 / BT-58)
invoice.seller.contact_phoneanyNoContact phone (BT-42 / BT-57)
invoice.seller.eu_vat_countryanyNoEU VAT country code for non-PL sellers/buyers
invoice.seller.electronic_addressanyNoPeppol / EAS electronic address (BT-34 / BT-49)
invoice.seller.electronic_address_schemeanyNoEAS scheme code, e.g. '0088' for GLN (BT-34-SchemeID / BT-49-SchemeID)
invoice.profilestringYesGuidelineID / profile URN (BT-24). Constrain to a typed enum in each country subclass by setting _allowed_profiles = frozenset({MyEnum.member.value, ...}).
invoice.due_dateanyNoPayment due date (BT-9)
invoice.tax_linesarrayNoVAT breakdown lines (BG-23). EN 16931 requires at least one.
invoice.tax_totalanyYesTotal VAT amount (BT-110)
invoice.amount_dueanyYesAmount due for payment (BT-115)
invoice.line_itemsarrayNoInvoice lines (BG-25). Required for BASIC, EN_16931, EXTENDED, XRechnung profiles. Absent in MINIMUM and BASIC WL.
invoice.numer_ksefanyNoKSeF reference number assigned by the platform after clearance. Format: NIP(10) + date(8) + sequence(20) + checksum(2). Not emitted in the outbound XML; used for lifecycle tracking.
invoice.invoice_datestringYesInvoice issue date (BT-2)
invoice.charges_totalanyNoTotal document-level charges (BT-108)
invoice.currency_codestringNoISO 4217 invoice currency code (BT-5)
invoice.delivery_dateanyNoActual delivery date (BT-72)
invoice.document_uuidanyNoUniversally unique document identifier, emitted as <cbc:UUID> — a sibling element immediately after <cbc:ID>. Not a formal EN 16931 BT; several Peppol jurisdiction CIUS profiles mandate it (e.g. PINT AE BTAE-07, PINT-SG BT-SG-003). Optional in the base model since most EN 16931 profiles do not require it; country subclasses that require it should re-declare it as required.
invoice.payment_meansanyNoPayment instructions (BG-16)
invoice.payment_termsanyNoPayment terms free text (BT-20)
invoice.invoice_numberstringYesInvoice number (BT-1)
invoice.prepaid_amountanyNoPrepaid amount (BT-113)
invoice.buyer_referenceanyNoBuyer reference / routing ID (BT-10). Mandatory for XRechnung and public-sector buyers.
invoice.rounding_amountanyNoRounding amount (BT-114)
invoice.allowances_totalanyNoTotal document-level allowances (BT-107)
invoice.business_processanyNoBT-23 Business process type. In UBL emitted as <cbc:ProfileID>; in CII as <ram:BusinessProcessSpecifiedDocumentContextParameter><ram:ID>. Distinct from `profile` which holds BT-24 (Specification identifier).
invoice.invoice_type_codestringNoUNCL1001 document type code (BT-3). 380=Invoice, 381=Credit Note
invoice.project_referenceanyNoProject reference (BT-11)
invoice.allowances_chargesarrayNoDocument-level allowances (BG-20) and charges (BG-21)
invoice.billing_period_endanyNoBilling period end date (BT-74)
invoice.contract_referenceanyNoContract reference (BT-12)
invoice.billing_period_startanyNoBilling period start date (BT-73)
invoice.tax_exclusive_amountanyYesInvoice total without VAT (BT-109)
invoice.tax_inclusive_amountanyYesInvoice total with VAT (BT-112)
invoice.preceding_invoice_dateanyNoPreceding invoice issue date (BT-26)
invoice.sum_of_line_net_amountsanyYesSum of invoice line net amounts (BT-106)
invoice.purchase_order_referenceanyNoPurchase order reference (BT-13)
invoice.preceding_invoice_referenceanyNoPreceding invoice reference for credit notes (BT-25)

Details

From the project README

mcp-ksef-pl 🇵🇱

English | Polski

License PyPI version Python mcp-ksef-pl MCP server

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.

Installation

Via PyPI (recommended)
pip install mcp-ksef-pl

Or without prior installation using uvx:

uvx mcp-ksef-pl
From source
git clone https://github.com/cmendezs/mcp-ksef-pl.git
cd mcp-ksef-pl
uv sync --all-extras

Configuration (environment variables)

VariableDefaultDescription
KSEF_ENVIRONMENTtestKSeF environment: production or test
KSEF_SESSION_TOKEN—KSeF session token (obtained through the challenge-response flow with MF)
KSEF_NIP—NIP of the entity submitting invoices
KSEF_TIMEOUT30HTTP request timeout in seconds
KSEF_VERIFY_MF_KEY_PINNINGfalseEnforce SPKI SHA-256 pinning on the MF encryption certificate. No-op until fingerprints are populated for the active environment, even when set to true
EINVOICING_PEPPOL_CODELIST_DIR—Local directory containing your own copy of the OpenPeppol eDEC Code Lists, required by the Peppol codelist tools (not bundled with this package; see mcp-einvoicing-core README)
EINVOICING_EN16931_CODELIST_DIR—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 mcp-einvoicing-core README)

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.json
  • Per 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.json
  • Workspace: .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
ToolDescription
generate_fa3_invoiceGenerates a KSeF-compliant FA(3) XML invoice (required for KSeF API v2 submissions)
generate_fa2_invoiceGenerates a KSeF-compliant FA(2) XML invoice (legacy format, read-only use)
validate_fa3_invoiceValidates FA(3) XML: XSD validation and FA(3)-specific business rules
validate_fa2_invoiceValidates FA(2) XML: XSD validation (if the schema is available) and business rules
parse_fa2_invoiceParses 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
ToolDescription
submit_invoice_to_ksefSubmits an FA(3) invoice to the KSeF platform and returns a reference number
get_ksef_invoice_statusRetrieves the processing status of an invoice by its reference number
search_ksef_invoicesSearches invoices in KSeF by date range and direction (seller/buyer)
Identifier validation
ToolDescription
validate_polish_nipValidates a NIP (10-digit tax identification number) using a checksum algorithm
validate_polish_regonValidates a REGON (9- or 14-digit registry number) using a checksum algorithm
Peppol / EN 16931
ToolDescription
generate_peppol_invoiceGenerates a UBL 2.1 invoice compliant with Peppol BIS Billing 3.0 / EN 16931
validate_peppol_invoiceValidates a UBL 2.1 Peppol invoice against the CEN EN 16931 base Schematron rules (en16931-base-only scope — does not check the Peppol-specific overlay)
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).

ToolDescription
peppol_lookup_participantCheck whether a business is registered on the Peppol network; returns registration status and supported document types
peppol_get_service_endpointFetch the AS4 endpoint for a participant's document type
resolve_peppol_dnsDNS-only (SML) diagnostic, independent of SMP reachability
peppol_sendTransmit a UBL/CII invoice via AS4
peppol_directory_searchSearch the public Peppol Directory by participant, name, country, or document type
list_participant_id_schemes, list_document_type_ids, list_process_ids, list_spis_use_case_idsOpenPeppol eDEC codelist lookups (require EINVOICING_PEPPOL_CODELIST_DIR)
check_document_type_id_in_codelist, check_process_id_in_codelist, check_participant_id_scheme_in_codelist, get_peppol_codelist_versionOpenPeppol 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.

ToolPluginDescription
validate_eusr_reportregister_peppol_reporting_toolsValidate an End User Statistics Report (XSD, then Schematron). Requires the [xslt2] extra.
validate_tsr_reportregister_peppol_reporting_toolsValidate a Transaction Statistics Report (XSD, then Schematron). Requires the [xslt2] extra.
validate_mls_messageregister_peppol_mls_toolsValidate a Message Level Status document (UBL ApplicationResponse-2 subset). Requires the [xslt2] extra.
build_mls_messageregister_peppol_mls_toolsBuild a document-level MLS response. Requires the [xslt2] extra.
13 list_*/check_* pairs, get_en16931_codelist_versionregister_en16931_codelist_toolsEN 16931 semantic code list lookups/checks (units, VAT categories, etc.). Require EINVOICING_EN16931_CODELIST_DIR.

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
  1. 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/.

  2. 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 challenge string and a timestamp.

  3. 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 xmlsec1 with 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.xml
    
  4. Submit the signed challenge. POST the signed XML to receive an authOperation reference:

    curl -s https://ksef-test.mf.gov.pl/auth/xades-signature \
      -H "Content-Type: application/octet-stream" \
      --data-binary @signed-challenge.xml
    
  5. Redeem 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.token and accessToken.context.referenceNumber.

  6. 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

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/ -v

Contributing

Contributions are welcome — see CONTRIBUTING.md for guidelines.

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

This project is distributed under the Apache 2.0 license. See the LICENSE file for details. For the full version history, see CHANGELOG.md.

Comments

Markdown supported

New to MCP?

From what the protocol is to installing your first server, these answers cover most first questions.

An open protocol that defines how AI applications connect to external tools and data in a uniform way. Clients talk to the model; MCP servers provide tools, resources and prompt templates. They exchange standard messages, so one server can be reused by many clients.