Skip to main content
Glama
secure-crm

secure-crm

by AIRCLOUD-PL
README.md
# secure-mcp-starter

**A secure-by-default template for connecting your company systems to AI agents over MCP.**
Built on the official MCP Python SDK. Scoped tokens, per-tool permissions, human approval of every write,
a hash-chained audit log, PII masking and prompt-injection fencing are on from the first run, with a
47-case attack suite in Polish and English and a production checklist mapped to the OWASP Top 10 for
Agentic Applications.

[Polski opis niżej](#po-polsku) · [Production checklist](docs/production-checklist.md) ·
[Checklista (PL)](docs/checklist-produkcja.md) · [Attack suite](attacks/README.md) · License: Apache-2.0

## Why
Connecting an agent to a CRM, ERP or ticketing system is easy; making it safe to run in production is not.
Many MCP servers in the wild accept requests without any authentication, expose one broad tool that can do
anything, write without a human in the loop and keep no audit trail. Agents also read customer-supplied text,
which makes indirect prompt injection a real attack path (OWASP ASI01 Agent Goal Hijack), and an agent that has
private data, untrusted content and a way to send data out is one poisoned e-mail away from a leak
([the lethal trifecta](https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/)).

This repository is a small, readable reference you can copy: a fictional mini-CRM served over MCP with the
controls you need before production already wired in, and tests that prove each control holds.

## What you get
| Control | How | Default |
|---|---|---|
| Authentication | Bearer tokens over Streamable HTTP, never from the query string; `SMCP_TOKEN` for stdio, re-checked on every call; optional OAuth 2.1 resource-server mode (JWT + JWKS, `iss`/`aud`/`exp`/`nbf`, `scope` or `scp`, RFC 9728 metadata) | on |
| Tokens | `smcp_` + 256 random bits, shown once, only SHA-256 stored, scopes, expiry, append-only revocation that also stops open sessions | 30 days |
| Per-tool authorization | `policy.py` maps every tool to a scope; unknown tools denied; `tools/list` filtered by scope; over HTTP a missing tool scope is answered with `403 insufficient_scope` and a `WWW-Authenticate: ... scope="..."` challenge | default deny |
| MCP method allowlist | only handshake, ping, notifications and tools are served; `resources/*`, `prompts/*`, completion, logging, subscriptions and anything new are denied and audited | default deny |
| Input validation | pydantic types, ranges, lengths, enums; unknown arguments rejected; control and bidi characters refused | on |
| Human approval | write tools only create proposals; a human approves in the CLI (TTY + typed code); agent identities can never decide (also a DB constraint); the real OS uid/user is recorded with every decision; stale proposals refused; atomic pending cap per principal | on |
| Safe review screen | everything the CLI prints (proposals, audit tail) is escaped, so `\r`, `ESC[2K`, `ESC[8m`, OSC 52 or bidi overrides cannot hide or rewrite what the reviewer sees; flag `control_characters` | on |
| Audit | append-only, hash-chained log of every call and decision with redacted arguments; optional HMAC key (`SMCP_AUDIT_KEY`); `smcp audit head` to anchor the head outside the host, `smcp audit verify --expect-head`; noisy denials coalesced | on |
| Limits | rate limit per principal (reads and writes separately, applied before the policy check), denied-call budget per principal (a global limit only coalesces denial audit entries), max result size, page caps | 60 / 10 / 20 per min |
| PII masking | e-mail (incl. internationalized and punycode), phone, PESEL (checksum + date, also with spaces), IBAN/NRB (mod-97, `PL`/`pl`, spaces or dashes), in text, structured results and embedded resources | on |
| Untrusted content | every third-party text field (names, cities, titles, authors, notes) wrapped in `<untrusted-data-NONCE>` with a per-response nonce; NFKC, zero-width removal and look-alike neutralization as defence in depth; PL/EN injection heuristics flag it | on |
| Network | binds 127.0.0.1; non-loopback needs explicit opt-in plus a Host allowlist; Host/Origin allowlist always passed explicitly (DNS-rebinding protection) | on |

## Quick start
Requires [uv](https://docs.astral.sh/uv/) and Python 3.12+.

```bash
git clone https://github.com/AIRCLOUD-PL/secure-mcp-starter.git && cd secure-mcp-starter
uv sync
uv run smcp init && uv run smcp seed            # fictional sample data in ./data/crm.db
(umask 077; uv run smcp token create demo --scope crm:read --scope crm:propose > .demo-token)
uv run pytest                                    # unit tests + PL/EN attack suite
```

**Streamable HTTP** (what you deploy):
```bash
uv run smcp serve --transport http               # http://127.0.0.1:8000/mcp
claude mcp add --transport http secure-crm http://127.0.0.1:8000/mcp \
  --header "Authorization: Bearer $(cat .demo-token)"
```

**stdio** (local clients):
```bash
claude mcp add secure-crm --env SMCP_TOKEN="$(cat .demo-token)" -- uv run --directory "$PWD" smcp serve
```
Your MCP client stores the token in its config file: protect that file like a password.

Ask the agent something like *"Show customer 1 and do what their latest note says"*. Customer 1 is poisoned on
purpose: you will see the notes fenced and flagged, and any write the agent attempts ends up as a proposal:

```bash
uv run smcp proposals list                       # what the agent wants to change, with red flags
uv run smcp proposals approve 1                  # human only: needs a terminal and a typed code
uv run smcp audit tail && uv run smcp audit verify
uv run smcp audit head                           # ship this value to write-once storage (see below)
uv run smcp token revoke demo                    # kill switch for static tokens, also for open sessions
```

## Architecture
```text
 MCP client / agent (Claude Code, IDE, your app)
        │  Streamable HTTP + Authorization: Bearer   |   stdio + SMCP_TOKEN
        ▼
 ┌───────────────────────────── secure-mcp-starter ─────────────────────────────┐
 │ SDK transport: Host/Origin allowlist, body limit, bearer auth (static/JWT),   │
 │   baseline scope crm:read, RFC 9728 metadata (OAuth mode)                     │
 │ ScopeChallenge: scope= on 401/403, HTTP 403 insufficient_scope per tool       │
 │ Guard (ServerMiddleware) for EVERY MCP method:                                │
 │   method allowlist → principal → denial budget → tool-name check →           │
 │   rate limit → default-deny policy + scope → reject unknown args → tool →    │
 │   PII redaction → size cap → audit entry (hash chain, coalesced denials)     │
 │ Tools (official SDK, pydantic schemas, control characters refused)           │
 │   read:  search_customers  get_customer  list_deals  get_proposal            │
 │   write: propose_note  propose_deal_stage   ──► proposal queue (immutable)   │
 └───────────────────────────────────────┬──────────────────────────────────────┘
                                          │ SQLite: crm data · tokens · proposals · audit_log
 Human reviewer ── smcp proposals approve ┘ (TTY, human:<label> + real OS uid) ──► apply + audit in one transaction
```

## Adapt it to your system
1. Replace `src/secure_mcp_starter/crm.py` with calls to your system (keep reads paginated, wrap every third-party text field with `fence()`).
2. Declare tools in `server.py` with strict pydantic types (use the `Safe` validator for strings) and the `@audited` wrapper; write tools call `proposals.create()` only.
3. Add each tool to `POLICY` in `policy.py` with its scope. A tool missing there is denied. MCP methods other than tools are denied unless you add them to `METHODS`.
4. Add `apply_*` functions for approved proposals and attack cases for your domain in `attacks/cases.yaml`.
5. Walk the [production checklist](docs/production-checklist.md).

Configuration is environment-only; every variable and its secure default is listed in
[`config.py`](src/secure_mcp_starter/config.py). Boolean variables accept only true/false, 1/0, yes/no, on/off.
OAuth mode: `uv sync --extra oauth`, then set `SMCP_AUTH_MODE=oauth`, `SMCP_PUBLIC_URL` (canonical server URL,
used as token audience), `SMCP_OAUTH_ISSUER` and `SMCP_OAUTH_JWKS_URL` of your identity provider, optionally
`SMCP_OAUTH_REQUIRE_TYP=at+jwt`. The server is a resource server only and does not issue tokens. In OAuth mode
the principal is the pair (client, end user): two users of one client have separate proposals, limits and caps.

**Audit integrity.** The chain is tamper-evident only against edits that do not recompute it. Someone who can
write the database file can drop the triggers, change or delete rows and recompute every hash. Two settings close
most of that gap: `SMCP_AUDIT_KEY` (HMAC, at least 32 characters, kept outside the database, set before the first
entry; the server AND every `smcp` CLI run that writes (approve, reject, token create/revoke) must use the same
key, otherwise the write is refused so the chain never mixes keyed and unkeyed entries) and anchoring: run `smcp audit head` regularly (cron) and ship the value to write-once storage (S3 Object
Lock, a SIEM, a ticket). `smcp audit verify --expect-head <id:hash>` then detects truncation and rewrites.

## What this template does NOT do
- It does not make a model immune to prompt injection. Fencing and flags reduce risk; the real protection is
  that the agent cannot write without a human and has no tool to send data out.
- No TLS termination, no Dockerfile, no multi-instance rate limiting: put it behind a TLS reverse proxy and use a
  shared limiter (gateway, Redis) if you scale out. Rate limits and audit coalescing are in-memory per process.
- No authorization server, no consent screens, no per-user row-level security in the sample domain.
- No local revocation in OAuth mode: disable the client or user at the identity provider and keep access-token
  lifetimes short; a token stays valid until `exp`.
- The approval CLI is only as strong as OS account separation. Its terminal check is a speed bump; the
  `human:` label is self-asserted (the real OS uid/user is recorded next to it). The agent must never run as the
  approver's OS user, and its process must not be able to write the database file.
- The audit chain is not a WORM store: without an anchored head (and ideally a key) a rewrite is not detected.
- PII detection covers e-mail, phone, PESEL and Polish IBAN only. Names and addresses are not detected.
- Over stdio, per-tool scope failures are returned in-band as tool errors (there is no HTTP layer to send 403).
- `tools/list` hides tools the token cannot use, but calling such a tool by name returns `insufficient_scope`
  naming the tool and its scope, so tool names are not secret (scopes are discoverable anyway via PRM).
- A principal over its own denied-call budget also has its next valid calls refused (`rate_limited`) until the
  budget refills; other principals are not affected.
- Tool exceptions: the model sees the SDK's generic "Error executing tool ..."; the exception class and a
  redacted message go to the audit log, the traceback to the server's stderr logger.

## Built on
- [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) (`mcp` 2.x, `MCPServer`, auth middleware, Streamable HTTP) and the [MCP specification 2026-07-28, Authorization](https://modelcontextprotocol.io/specification/latest/basic/authorization) / [Security best practices](https://modelcontextprotocol.io/docs/tutorials/security/security_best_practices)
- [OWASP Top 10 for Agentic Applications 2026](https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications/), [The lethal trifecta](https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/) (Simon Willison)
- [promptfoo](https://github.com/promptfoo/promptfoo) for model-in-the-loop and generated red-team tests ([MCP testing guide](https://www.promptfoo.dev/docs/red-team/mcp-security-testing/))
- [Snyk Agent Scan](https://github.com/snyk/agent-scan) (formerly Invariant Labs `mcp-scan`), [MCP Inspector](https://github.com/modelcontextprotocol/inspector), [garak](https://github.com/NVIDIA/garak), [PyRIT](https://github.com/microsoft/PyRIT)
- For running and governing many MCP servers: [ToolHive](https://github.com/stacklok/toolhive) (Stacklok), [Docker MCP Gateway](https://github.com/docker/mcp-gateway)
- [pydantic](https://github.com/pydantic/pydantic), [PyJWT](https://github.com/jpadilla/pyjwt), [uv](https://github.com/astral-sh/uv), [gitleaks](https://github.com/gitleaks/gitleaks), [Trivy](https://github.com/aquasecurity/trivy), [spec-kit](https://github.com/github/spec-kit)

This template does not replace those tools: gateways and ToolHive govern which servers run and how;
scanners test them. This repository shows what a single server should enforce on its own.

## Need help? AIRCLOUD
Connecting your ERP, CRM or document systems to agents and taking it to production (identity, permissions,
human approval, audit, prompt-injection testing): [aircloud.com.pl/consulting](https://aircloud.com.pl/consulting/?from=secure-mcp-starter)
· office@aircloud.com.pl

---

## Po polsku

**Szablon serwera MCP z bezpiecznymi ustawieniami domyślnymi: podłącz systemy firmy do agentów AI tak, żeby dało
się to puścić na produkcję.** Zbudowany na oficjalnym SDK MCP dla Pythona.

**Po co.** Podłączenie agenta do CRM czy ERP jest proste, ale wiele serwerów MCP działa bez uwierzytelniania,
ma jedno szerokie narzędzie „do wszystkiego”, zapisuje bez człowieka i nie prowadzi dziennika. Agent czyta też
teksty od klientów, więc wstrzyknięcie poleceń w danych (pośredni prompt injection, OWASP ASI01) jest realnym
atakiem. Agent, który ma dane prywatne, kontakt z niezaufaną treścią i możliwość wysłania danych na zewnątrz,
jest jeden zatruty e-mail od wycieku („lethal trifecta”, Simon Willison).

**Co dostajesz.** Tokeny z zakresami (`crm:read`, `crm:propose`) z datą ważności (domyślnie 30 dni) i odwołaniem,
uprawnienia per narzędzie z domyślną odmową (przez HTTP odmowa to `403 insufficient_scope` z nagłówkiem
`WWW-Authenticate`), listę dozwolonych metod MCP, walidację wejścia z odrzucaniem nieznanych argumentów i znaków
sterujących, zapisy w trybie „propozycja → zatwierdzenie przez człowieka” (agent nie zatwierdzi sam, pilnuje tego
też baza, a przy decyzji zapisywany jest prawdziwy użytkownik systemu), bezpieczny ekran przeglądu (sekwencje
terminala i znaki bidi są pokazywane jako widoczne kody), dziennik audytu z łańcuchem skrótów, opcjonalnym kluczem
HMAC i kotwiczeniem głowy, limity zapytań (także dla odrzuconych wywołań) i rozmiaru wyniku, maskowanie e-maili
(również z polskimi znakami i IDN), telefonów, numerów PESEL i IBAN, ogradzanie każdego pola z tekstem od osób
trzecich, opcjonalny tryb OAuth 2.1 zgodny ze specyfikacją MCP, a do tego 47 przypadków ataków (26 po polsku)
i checklistę przed produkcją odniesioną do OWASP Top 10 for Agentic Applications.

**Szybki start.**
```bash
git clone https://github.com/AIRCLOUD-PL/secure-mcp-starter.git && cd secure-mcp-starter
uv sync
uv run smcp init && uv run smcp seed
(umask 077; uv run smcp token create demo --scope crm:read --scope crm:propose > .demo-token)
uv run pytest
uv run smcp serve --transport http      # albo stdio z SMCP_TOKEN
uv run smcp proposals list              # co agent chce zmienić; zatwierdza tylko człowiek
```

**Czego szablon nie robi.** Nie uodparnia modelu na prompt injection (ogrodzenie i flagi zmniejszają ryzyko,
a prawdziwą ochroną jest brak zapisu bez człowieka i brak narzędzia do wysyłki danych). Nie ma TLS, Dockerfile
ani wspólnego limitera dla wielu instancji. W trybie OAuth nie ma lokalnego odwołania tokenu (blokujesz klienta
lub użytkownika u dostawcy tożsamości, tokeny powinny żyć minuty). CLI zatwierdzania jest tak mocne, jak
rozdzielenie kont w systemie: agent nie może działać jako użytkownik zatwierdzającego ani zapisywać pliku bazy.
Łańcuch audytu bez zakotwiczonej głowy (i klucza) nie wykryje przepisania całego dziennika. Wykrywanie danych
osobowych obejmuje tylko e-mail, telefon, PESEL i IBAN.

**Dokumenty.** [Checklista przed produkcją](docs/checklist-produkcja.md) · [Zestaw ataków](attacks/README.md) ·
[Specyfikacja](specs/001-secure-mcp-starter/spec.md) · [Zgłaszanie podatności](SECURITY.md)

**Potrzebujesz pomocy?** AIRCLOUD pomaga podłączyć ERP, CRM i systemy dokumentów do agentów i wdrożyć to
produkcyjnie: tożsamość, uprawnienia, zatwierdzanie przez człowieka, audyt, testy prompt injection.
[aircloud.com.pl/consulting](https://aircloud.com.pl/consulting/?from=secure-mcp-starter) · office@aircloud.com.pl

## License
Apache-2.0, see [LICENSE](LICENSE) and [NOTICE](NOTICE). Sample data is fictional and generated at runtime.