Skip to main content
Glama
README.md
# 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.

## 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](docs/MANUAL_SMOKE_RUNBOOK.md) when completing those external
gates.

## Requirements

- Python 3.12 or 3.13.
- [`uv`](https://docs.astral.sh/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:

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

Create local configuration:

```bash
cp .env.example .env
cp seller_profile.example.yaml seller_profile.yaml
```

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

```env
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:

```bash
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:

```bash
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:

```bash
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:

```bash
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](docs/CLAUDE_DESKTOP.md) for the full first-use flow.

## Manual Evidence Notes

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

```bash
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:

```bash
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:

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

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

```json
{
  "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:

```bash
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:

```env
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:

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

Or with Docker Compose:

```bash
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:

```bash
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](docs/REMOTE_DEPLOYMENT.md) for provider notes and
the smoke checklist.

## Production Safety

Production sends require both:

```env
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

```bash
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

- [docs/CLAUDE_DESKTOP.md](docs/CLAUDE_DESKTOP.md) - local Claude Desktop setup.
- [docs/REMOTE_DEPLOYMENT.md](docs/REMOTE_DEPLOYMENT.md) - Streamable HTTP and OAuth deployment.
- [docs/MANUAL_SMOKE_RUNBOOK.md](docs/MANUAL_SMOKE_RUNBOOK.md) - manual validation evidence.
- [docs/READINESS_AUDIT.md](docs/READINESS_AUDIT.md) - current status and remaining gates.
- [docs/LOCAL_KNOWLEDGE.md](docs/LOCAL_KNOWLEDGE.md) - local FTS/vector/LLM source extraction.
- [docs/main_spec.md](docs/main_spec.md) - implementation source spec.
- [CHANGELOG.md](CHANGELOG.md) - release history.

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
ResponsivenessNo issues