Skip to main content
Glama

KSeF MCP

KSeF MCP is a single-tenant Model Context Protocol server for Polish KSeF e-invoice workflows. It lets an MCP client help prepare, validate, preview, submit, and read FA(3) invoices while keeping the actual KSeF credentials and local invoice state under your control.

The default setup is local stdio for one operator. A remote HTTPS deployment is also available for services that need to expose the MCP over Streamable HTTP with external OAuth/JWKS token validation.

What It Can Do

  • Check KSeF TEST readiness before any invoice write flow.

  • Create, update, and validate SQLite-backed invoice drafts.

  • Build and offline-validate FA(3) XML from supported standard, simplified, advance, settlement, and correction invoice drafts.

  • Generate confirmation tokens before submission and enforce token expiry, production opt-in, and durable idempotency.

  • Submit invoices to KSeF TEST or PROD through the guarded write path.

  • List and download KSeF invoices and download UPOs.

  • Render a local KSeF-like PDF preview from prepared FA(3) XML without contacting KSeF.

  • Look up exchange rates from NBP and counterparties through MF VAT whitelist, VIES, KRS, and optional GUS REGON.

  • Store/search local source documents and optionally use local embeddings or a local LLM for advisory extraction.

  • Expose MCP resources and prompts for capabilities, schema, first-use setup, seller profile, glossary, and invoice field checklists.

  • Expose ksef://first-use-checklist and the first-use-setup prompt, plus a capabilities surface that lists supported resources and terminal preflight commands.

  • Ask for common primitive starter fields through bounded MCP form elicitation when a client supports it.

Related MCP server: einvoice-mcp

Current Release Status

This is a 0.1.0 release: useful for TEST-first personal and service evaluation, with production sends intentionally guarded.

Verified:

  • Automated unit and smoke coverage for configuration, MCP tool registration, draft validation, FA(3) generation, KSeF gateway boundaries, and local stdio startup.

  • Live KSeF TEST readiness, guarded TEST submit, invoice readback, and UPO readback with real TEST credentials.

  • Docker/Streamable HTTP startup shape and OAuth resource-server validation code paths.

Still pending:

  • Manual Claude Desktop stdio smoke from inside the Claude Desktop app.

  • Live hosted HTTP/OAuth smoke against a real public URL and OAuth provider.

Use docs/MANUAL_SMOKE_RUNBOOK.md when completing those external gates.

Requirements

  • Python 3.12 or 3.13.

  • uv for local development and command execution.

  • KSeF TEST token or certificate credentials.

  • A Polish NIP for the configured tenant.

  • Docker, only if you want the containerized HTTP deployment.

Local Setup

Clone the repository and install dependencies:

git clone https://github.com/olegtyshcneko/ksef-mcp.git
cd ksef-mcp
uv sync

Create local configuration:

cp .env.example .env
cp seller_profile.example.yaml seller_profile.yaml

Edit .env and replace the placeholder values. Start with:

KSEF_ENV=test
KSEF_AUTH_MODE=token
KSEF_NIP=REPLACE_WITH_YOUR_NIP
KSEF_TEST_NIP=REPLACE_WITH_TEST_NIP
KSEF_TOKEN=REPLACE_WITH_TEST_TOKEN
KSEF_ALLOW_PROD=false
MCP_TRANSPORT=stdio

Edit seller_profile.yaml with your seller and payment defaults. The real .env, seller_profile.yaml, and data/ directory are ignored by git.

Run the local checks:

UV_CACHE_DIR=/tmp/uv-cache uv run ksef-mcp-config-check
UV_CACHE_DIR=/tmp/uv-cache uv run ksef-mcp-local-preflight \
  --seed docs/examples/first_standard_invoice_seed.example.json
UV_CACHE_DIR=/tmp/uv-cache uv run ksef-mcp-stdio-smoke

The local preflight does not call KSeF and reports safety fields such as configured_ledger_may_be_touched_by_stdio=true.

Then prove KSeF TEST readiness:

UV_CACHE_DIR=/tmp/uv-cache uv run ksef-mcp-test-readiness-smoke

You can also validate the first invoice seed without touching your real ledger:

UV_CACHE_DIR=/tmp/uv-cache uv run ksef-mcp-first-draft-dry-run \
  --seed docs/examples/first_standard_invoice_seed.example.json

The dry run should report ready_for_prepare=true, real_ledger_touched=false, and no KSeF network use.

If KSEF_TEST_NIP intentionally equals KSEF_NIP, either set KSEF_ALLOW_REAL_NIP_IN_TEST=true or pass --use-real-nip-ack to the smoke commands.

Claude Desktop

Generate a redacted Claude Desktop config preview:

UV_CACHE_DIR=/tmp/uv-cache uv run ksef-mcp-claude-config-preview

The preview reports secrets_included=false. Paste the generated mcpServers block into claude_desktop_config.json, then restart Claude Desktop. Keep secrets in .env; do not paste KSeF tokens, certificate passwords, NIPs, or customer data into the desktop config.

See docs/CLAUDE_DESKTOP.md for the full first-use flow.

Manual Evidence Notes

For manual gates, create a private redaction-safe evidence template:

mkdir -p data
UV_CACHE_DIR=/tmp/uv-cache uv run ksef-mcp-manual-smoke-template --format markdown \
  > data/manual_smoke_evidence.md

Before sharing or committing filled notes, scan them:

UV_CACHE_DIR=/tmp/uv-cache uv run ksef-mcp-manual-smoke-evidence-check \
  --path data/manual_smoke_evidence.md

First Invoice Flow

  1. Run ksef-mcp-test-readiness-smoke.

  2. Start a draft with ksef_start_invoice_draft.

  3. Patch missing fields with ksef_update_invoice_draft.

  4. Confirm advisory/source-derived fields when required.

  5. Run ksef_validate_invoice_draft until ready_for_prepare=true.

  6. Call ksef_prepare_invoice to build FA(3) XML and create a confirmation token.

  7. Optionally call ksef_render_invoice_pdf for a local preview.

  8. Call ksef_submit_invoice only after reviewing the prepared XML/preview and confirming the write.

  9. Download the UPO with ksef_download_upo.

Minimal start call:

{
  "seed": {
    "...": "contents of docs/examples/first_standard_invoice_seed.example.json"
  }
}

If the response includes missing_fields, patch the draft and validate again:

{
  "draft_id": "returned-draft-id",
  "patch": {
    "buyer": {
      "name": "Corrected buyer name"
    }
  }
}

Only call ksef_prepare_invoice after ksef_validate_invoice_draft returns ready_for_prepare=true, missing_fields=[], and blocking_errors=[].

For a terminal-only TEST submit smoke:

UV_CACHE_DIR=/tmp/uv-cache uv run ksef-mcp-test-submit-smoke \
  --seed docs/examples/first_standard_invoice_seed.example.json \
  --confirm-submit-to-ksef-test

Remote HTTP Deployment

Use remote mode when a service, hosted agent, ChatGPT app, Claude.ai, or another cloud MCP client must reach the server over HTTPS.

This server is an OAuth resource server. It validates bearer JWTs against your configured issuer, audience, JWKS URL, and required scope. It does not issue tokens, host login pages, implement PKCE, or dynamically register clients. Put those responsibilities in an external OAuth/OIDC provider or platform gateway.

Minimal environment:

MCP_TRANSPORT=http
MCP_PUBLIC_URL=https://ksef-mcp.example.com/mcp
OAUTH_ISSUER=https://issuer.example.com/
OAUTH_AUDIENCE=https://ksef-mcp.example.com/mcp
OAUTH_JWKS_URL=https://issuer.example.com/.well-known/jwks.json
OAUTH_REQUIRED_SCOPES=ksef.mcp
KSEF_ENV=test
KSEF_ALLOW_PROD=false

Run locally:

UV_CACHE_DIR=/tmp/uv-cache uv run ksef-mcp

Or with Docker Compose:

cp .env.example .env
# Fill KSEF_*, MCP_PUBLIC_URL, and OAuth values.
docker compose up --build ksef-mcp

Before giving the URL to users or clients, run:

UV_CACHE_DIR=/tmp/uv-cache uv run ksef-mcp-remote-preflight

Expected success output includes oauth_network_used=false; this command does not fetch JWKS, call OAuth, start the hosted server, or touch KSeF. Then complete a live hosted OAuth smoke from the real client. See docs/REMOTE_DEPLOYMENT.md for provider notes and the smoke checklist.

Production Safety

Production sends require both:

KSEF_ENV=prod
KSEF_ALLOW_PROD=true

Keep KSEF_ALLOW_PROD=false until your TEST readiness, TEST submission, UPO download, client connection, and operational monitoring have all passed. ksef_submit_invoice is marked as a destructive MCP tool and also enforces confirmation-token and idempotency checks server-side.

Useful Commands

uv run ksef-mcp-config-check
uv run ksef-mcp-local-preflight --seed docs/examples/first_standard_invoice_seed.example.json
uv run ksef-mcp-stdio-smoke
uv run ksef-mcp-test-readiness-smoke
uv run ksef-mcp-first-draft-dry-run --seed docs/examples/first_standard_invoice_seed.example.json
uv run ksef-mcp-test-submit-smoke --seed docs/examples/first_standard_invoice_seed.example.json --confirm-submit-to-ksef-test
uv run ksef-mcp-remote-preflight
uv run pytest
uv run ruff check .
uv run mypy

More Documentation

Available Tools

23 tools
ksef_add_source_documentB

Store a local source document and index it for advisory retrieval.

Inputs: title (required), content (required), content_type, origin, +1 more. Returns: object

ksef_advise_exchange_rate_basisC
Read-onlyIdempotent

Suggest the advisory NBP average rate for a VAT exchange-rate basis date.

Inputs: currency (required), basis_date (required), basis_type (required), table. Returns: object

ksef_advise_vat_treatmentB
Read-onlyIdempotent

Suggest advisory VAT treatment candidates and missing facts; never mutates drafts.

Inputs: draft_id, line_index, transaction_type, seller_country_code, +9 more. Returns: object

ksef_attach_field_provenanceB

Attach source-backed field provenance to a draft and require confirmation.

Inputs: draft_id (required), field_path (required), suggested_value (required), source_document_id (required), +2 more. Returns: object

ksef_check_attachment_permissionA
Read-onlyIdempotent

Check whether the current KSeF context may issue invoices with FA(3) attachments.

Inputs: no named parameters. Returns: object

ksef_download_upoC
Read-onlyIdempotent

Retrieve invoice or session UPO for a known KSeF session.

Inputs: session_reference, ksef_reference_number, invoice_reference_number, upo_reference_number. Returns: object

ksef_extract_invoice_sourceB
Read-onlyIdempotent

Use a local LLM to propose source-backed invoice fields without mutating drafts.

Inputs: source_document_ids (required), draft_id, target_fields, max_candidates. Returns: object

ksef_get_capabilitiesA
Read-onlyIdempotent

Report supported, advisory, unsupported, and manual-smoke workflow capabilities.

Inputs: no named parameters. Returns: object

ksef_get_invoiceB
Read-onlyIdempotent

Fetch a KSeF invoice by reference number.

Inputs: ksef_reference_number (required), include_xml. Returns: object

ksef_list_invoicesB
Read-onlyIdempotent

Query KSeF invoice metadata for a date range and role.

Inputs: date_from (required), date_to (required), role (required), page, +1 more. Returns: object

ksef_lookup_counterpartyB
Read-onlyIdempotent

Look up advisory counterparty data from MF, VIES, KRS, or GUS sources.

Inputs: identifier_type (required), identifier_value (required), country_code, as_of_date, +1 more. Returns: object

ksef_lookup_exchange_rateA
Read-onlyIdempotent

Fetch official NBP exchange-rate data; advisory and requires basis confirmation.

Inputs: currency (required), target_date (required), table. Returns: object

ksef_prepare_invoiceA

Build and validate invoice XML without sending; refuses until TEST readiness passes.

Inputs: draft_id (required). Returns: object

ksef_render_invoice_pdfB

Render a local KSeF-like PDF from prepared FA(3) XML without sending to KSeF.

Inputs: confirmation_token (required), output_path, ksef_reference_number, verification_url. Returns: object

ksef_search_source_documentsB
Read-onlyIdempotent

Search local source documents; returned matches are advisory provenance only.

Inputs: query (required), limit, search_mode. Returns: object

ksef_session_statusA
Read-onlyIdempotent

Report configured KSeF environment and auth state without exposing secrets.

Inputs: no named parameters. Returns: object

ksef_start_invoice_draftC

Create an invoice draft and return the missing-field checklist.

Inputs: seed, source_document_ids. Returns: object

ksef_submit_invoiceA
DestructiveIdempotent

Irreversibly issues a legally binding invoice to KSeF. Requires a confirmation_token from ksef_prepare_invoice.

Inputs: confirmation_token (required). Returns: object

ksef_test_connection_checkC
Read-onlyIdempotent

Authenticate to KSeF TEST and persist readiness before invoice XML generation.

Inputs: use_real_nip_ack. Returns: object

ksef_update_invoice_draftC

Update an invoice draft with user-provided facts or confirmations.

Inputs: draft_id (required), patch (required), confirmations. Returns: object

ksef_validate_fa3_xmlB
Read-onlyIdempotent

Validate FA(3) XML against the vendored official XSD.

Inputs: xml (required). Returns: object

ksef_validate_invoice_draftB
Read-onlyIdempotent

Validate invoice draft completeness before XML preparation.

Inputs: draft_id (required). Returns: object

ksef_validate_nipA
Read-onlyIdempotent

Validate a Polish NIP checksum.

Inputs: nip (required). Returns: object

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3.2/5.0

    Scored across 23 tools

    Disambiguation4/5

    Most tools target distinct resources and actions, with clear workflow phases (drafting, validation, submission, retrieval). Minor overlap exists among source-document/provenance tools and between exchange-rate lookup/advice, but descriptions generally clarify boundaries.

    Naming Consistency4/5

    All tools share a ksef_ prefix and mostly follow verb_noun conventions (validate_nip, list_invoices, submit_invoice). A few names deviate, like ksef_session_status (missing verb) and ksef_test_connection_check (awkward phrasing), but the pattern remains predictable.

    Tool Count3/5

    23 tools fall in the heavy range for a single server, though the KSeF domain spans source documents, drafting, validation, and submission. The count is justifiable but leans high, with several advisory/provenance utilities that could potentially be consolidated.

    Completeness4/5

    The server covers a full invoice lifecycle: source ingestion, drafting, validation, XML preparation, submission, and retrieval/UPO download. Minor gaps exist (no source-document update/delete, no explicit draft retrieval/cancel), but agents can complete core workflows without dead ends.

    Maintenance

    ActivityInactive
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      MCP server for DACH e-invoicing. Create XRechnung (UBL) and ZUGFeRD 2.3 (Factur-X CII) invoices, validate against EN 16931 rules, extract data from XML, and convert between UBL, CII and JSON formats.
      6
      50 npm
      2
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Model Context Protocol (MCP) server for Polish Electronic Invoicing (KSeF / FA(2)). Provides tools to validate, generate, and explore API specifications for KSeF interoperability.
      10
      102 PyPI
      3
      Apache 2.0
    • A
      license
      B
      quality
      B
      maintenance
      Model 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.
      20
      3
      Apache 2.0