KSeF MCP
KSeF MCP is a Model Context Protocol server for end-to-end Polish KSeF e-invoice workflows, covering draft creation through submission and retrieval.
Session & Configuration
Check KSeF environment/authentication status, retrieve server capabilities, and test connection readiness before generating XML.
Invoice Draft Management
Create, update, and validate SQLite-backed invoice drafts with missing-field checklists.
Invoice Preparation & Submission
Build and offline-validate FA(3) XML from a draft (generates a confirmation token) without contacting KSeF.
Irreversibly submit legally binding invoices to KSeF TEST or PROD (requires confirmation token; marked destructive).
Invoice Retrieval & UPO
List, fetch, and download KSeF invoices and Official Receipt Confirmations (UPOs).
Validation & Lookup
Validate Polish NIP checksums and FA(3) XML against the official XSD schema offline.
Look up counterparty data from MF VAT whitelist, VIES, KRS, and GUS REGON.
Fetch official NBP exchange rates; check FA(3) attachment permissions.
VAT Advisory
Get advisory VAT treatment suggestions and identify missing facts (read-only, never mutates drafts).
Source Document & Knowledge Management
Store, index, and search local source documents (FTS/vector/hybrid).
Use a local LLM to extract invoice field candidates from source documents with provenance tracking, requiring user confirmation before use.
Preview & Deployment
Generate local KSeF-like PDF previews from prepared FA(3) XML without contacting KSeF.
Supports local
stdioand remote HTTPS deployment with external OAuth/JWKS token validation.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@KSeF MCP list my last 5 sales invoices"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
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-checklistand thefirst-use-setupprompt, 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.
uvfor 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 syncCreate local configuration:
cp .env.example .env
cp seller_profile.example.yaml seller_profile.yamlEdit .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=stdioEdit 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-smokeThe 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-smokeYou 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.jsonThe 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-previewThe 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.mdBefore 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.mdFirst Invoice Flow
Run
ksef-mcp-test-readiness-smoke.Start a draft with
ksef_start_invoice_draft.Patch missing fields with
ksef_update_invoice_draft.Confirm advisory/source-derived fields when required.
Run
ksef_validate_invoice_draftuntilready_for_prepare=true.Call
ksef_prepare_invoiceto build FA(3) XML and create a confirmation token.Optionally call
ksef_render_invoice_pdffor a local preview.Call
ksef_submit_invoiceonly after reviewing the prepared XML/preview and confirming the write.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-testRemote 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=falseRun locally:
UV_CACHE_DIR=/tmp/uv-cache uv run ksef-mcpOr with Docker Compose:
cp .env.example .env
# Fill KSEF_*, MCP_PUBLIC_URL, and OAuth values.
docker compose up --build ksef-mcpBefore giving the URL to users or clients, run:
UV_CACHE_DIR=/tmp/uv-cache uv run ksef-mcp-remote-preflightExpected 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=trueKeep 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 mypyMore Documentation
docs/CLAUDE_DESKTOP.md - local Claude Desktop setup.
docs/REMOTE_DEPLOYMENT.md - Streamable HTTP and OAuth deployment.
docs/MANUAL_SMOKE_RUNBOOK.md - manual validation evidence.
docs/READINESS_AUDIT.md - current status and remaining gates.
docs/LOCAL_KNOWLEDGE.md - local FTS/vector/LLM source extraction.
docs/main_spec.md - implementation source spec.
CHANGELOG.md - release history.
Available Tools
23 toolsksef_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_basisCRead-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_treatmentBRead-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_permissionARead-onlyIdempotent
Check whether the current KSeF context may issue invoices with FA(3) attachments.
Inputs: no named parameters. Returns: object
ksef_download_upoCRead-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_sourceBRead-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_capabilitiesARead-onlyIdempotent
Report supported, advisory, unsupported, and manual-smoke workflow capabilities.
Inputs: no named parameters. Returns: object
ksef_get_invoiceBRead-onlyIdempotent
Fetch a KSeF invoice by reference number.
Inputs: ksef_reference_number (required), include_xml. Returns: object
ksef_list_invoicesBRead-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_counterpartyBRead-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_rateARead-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_documentsBRead-onlyIdempotent
Search local source documents; returned matches are advisory provenance only.
Inputs: query (required), limit, search_mode. Returns: object
ksef_session_statusARead-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_invoiceADestructiveIdempotent
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_checkCRead-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_xmlBRead-onlyIdempotent
Validate FA(3) XML against the vendored official XSD.
Inputs: xml (required). Returns: object
ksef_validate_invoice_draftBRead-onlyIdempotent
Validate invoice draft completeness before XML preparation.
Inputs: draft_id (required). Returns: object
ksef_validate_nipARead-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
Scored across 23 tools
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.
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.
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.
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
Related MCP Connectors
MCP server for Codat — companies, connections, invoices, bills and financial statements.
Brazilian fiscal MCP server - issue NF-e, NFC-e, NFS-e, CT-e, MDF-e and DC-e via SEFAZ.
MCP server for ABRA Flexi — accounting, contacts, stock and draft-checked invoice creation.
Polish e-invoices (faktury) in KSeF: clients, products, drafts, validation and confirmed issuing.
Related MCP Servers
- AlicenseNot gradedqualityFmaintenanceFree Polish VAT invoice generation MCP server with PDF output and preview. No API key required.1MIT
- AlicenseAqualityDmaintenanceMCP 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.650 npm2MIT
- AlicenseAqualityBmaintenanceModel Context Protocol (MCP) server for Polish Electronic Invoicing (KSeF / FA(2)). Provides tools to validate, generate, and explore API specifications for KSeF interoperability.10102 PyPI3Apache 2.0
- AlicenseBqualityBmaintenanceModel 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.203Apache 2.0