mcp-kit
by tremen-dev
README.md
# `{tremen.dev}` / `mcp-kit` — Production-Grade Stateless MCP Reference Server
> **B2B Operations & CRM Connector over PostgreSQL**
> Built by [`{tremen.dev}`](https://tremen.dev/mcp) as an open-source reference architecture for secure, auditable, cost-optimized internal AI agents.
Most MCP demos break the moment they leave `stdio` on a laptop. This repository demonstrates what companies actually pay to put into production: a **stateless Streamable HTTP MCP server** (`2026-07-28` gateway headers, zero session state), **OAuth 2.1 / JWT audience enforcement** (blocking *token passthrough*), **explicit human confirmation on write actions**, **kill switches & rate limiting**, **EU AI Act Art. 12 structured audit logging**, and **compact tool schemas that cut LLM token bills by ~89%**.
---
## Architecture
```mermaid
flowchart LR
Client["Claude / AI Agent"] -->|"POST /mcp (Bearer JWT + Mcp-Protocol-Version)"| Gateway["Express Gateway & AuthZ (jose JWT + aud check)"]
Gateway -->|"Mcp-Method / Mcp-Name"| Transport["Stateless StreamableHTTPServerTransport"]
Transport --> Policy["Policy Layer: KillSwitch + RateLimiter + Scope + WriteConsent"]
Policy -->|"Parameterized Queries Only (No Raw SQL)"| Repo["CrmRepository (PostgreSQL / Memory)"]
Policy -->|"100% NDJSON Trail"| Audit["EU AI Act Art. 12 AuditLogger"]
```
### Key Production Guarantees
1. **Stateless Streamable HTTP (`2026-07-28`):** No Redis or sticky sessions required (`sessionIdGenerator: undefined`). Exposes `Mcp-Protocol-Version`, `Mcp-Method`, and `Mcp-Name` headers so API gateways can route, rate-limit, and audit without parsing JSON-RPC bodies.
2. **Zero Token Passthrough:** Rejects any JWT whose `aud` claim does not match `JWT_AUDIENCE` (`403 denied_audience`) and enforces per-tool OAuth scopes (`read:crm`, `write:billing`).
3. **Read-Generous / Write-Strict Policy:** 5 parameterized read tools vs. 1 strictly guarded write tool (`issue_credit_memo`) that requires `confirm_write=true`, an explicit human `confirmation_token`, a single-action EUR cap, and an `idempotency_key`.
4. **Kill Switches & Loop Protection:** Instant disablement per tool (`KILL_SWITCH_TOOLS`) or per user (`KILL_SWITCH_USERS`), plus sliding-window rate limiting per `(user_id, tool)`.
5. **100% Audit Coverage:** Every allowed, denied, and errored call emits sanitized JSON logs (`timestamp`, `request_id`, `user_id`, `agent_id`, `protocol_version`, `mcp_method`, `tool`, `args_sanitized`, `decision`, `status`, `error_code`, `latency_ms`).
---
## Narrow Tool Surface (6 Business Tools, 0 Raw SQL)
| Tool | Type | Required Scope | Purpose |
| :--- | :--- | :--- | :--- |
| `get_account_overview` | Read | `read:crm` | Account profile, primary contact, open tickets, overdue EUR, recent orders |
| `search_accounts` | Read | `read:crm` | Filtered account search (`query`, `tier`, `status`, `industry`, capped `limit`) |
| `list_open_tickets` | Read | `read:crm` | Unresolved support tickets ordered by priority and `sla_at_risk` |
| `get_order_status` | Read | `read:crm` | Order fulfillment status, tracking code, and line items |
| `get_invoice_summary` | Read | `read:crm` | Invoices and net outstanding/overdue balances |
| `issue_credit_memo` | Write | `write:billing` | Controlled credit memo with explicit confirmation token, EUR cap, and idempotency |
---
## Quickstart (60 Seconds, Zero External Dependencies)
```bash
git clone https://github.com/tremen-dev/mcp-kit.git
cd mcp-kit
npm install
npm test
npm run dev
```
Generate demo JWTs (`READ_ONLY_TOKEN`, `WRITE_TOKEN`, `WRONG_AUDIENCE_TOKEN`):
```bash
npm run mint-tokens
```
Run the live token-cost benchmark (`mcp-kit` 6 compact schemas + Prompt Caching + 70/30 Sonnet/Haiku routing vs. a bloated 40-tool CRUD server):
```bash
npm run benchmark
```
Measured output (Nov 2026 Anthropic API rates, 10 users × 15 queries/day = 3,300 queries/month):
| Configuration | Tools | Schema Tokens / Turn | Projected Monthly Spend |
| :--- | :--- | :--- | :--- |
| Naive 40-tool CRUD (Sonnet 5.5, no cache) | 40 | ~19,751 | **$487.10 / mo** |
| **`mcp-kit` (6 tools + Prompt Caching + 70/30 routing)** | **6** | **~1,589** | **$41.63 / mo (-91.5% · $5,345.59/yr saved)** |
### Full PostgreSQL Deployment (Docker Compose)
```bash
docker compose up --build
```
This provisions PostgreSQL 16 seeded with 100% synthetic B2B data (`db/init.sql`) and runs the MCP server in `STORAGE_MODE=postgres` on `http://localhost:3080/mcp`.
---
## Endpoints & Live Verification
- `POST /mcp` — Stateless JSON-RPC MCP endpoint (`tools/list`, `tools/call`)
- `GET /health` — Health & active storage mode
- `GET /metrics/summary` — Live tool calls, average latency, error rate, and audit coverage (`100%`)
---
## Production Runbook (Summary)
1. **Secret rotation:** Rotate `JWT_SECRET` (or swap to JWKS public key verification in `src/security/auth.ts`) without restarting stateful sessions because the server is stateless.
2. **Incident response:** Add a misbehaving tool or user to `KILL_SWITCH_TOOLS` / `KILL_SWITCH_USERS` to immediately block execution while keeping other tools live.
3. **Client API billing:** Always connect the client's agent runtime to the **client's own LLM API account** with spend caps enabled.
---
Need a custom, production-ready MCP connector for your internal CRM, ERP, or PostgreSQL database? Reach out via **[`tremen.dev/mcp`](https://tremen.dev/mcp)** (`hola@tremen.dev`).
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues