BizMCP
by CMB2002
README.md
# BizMCP: LLM-Powered MCP Server
> A production-style **Model Context Protocol (MCP) server** that lets Claude, GPT or any MCP client **ground their answers in live business data**. It ships with a web console, a full test suite and hardened Kubernetes manifests.






BizMCP exposes **database, API and file tools** plus **FAISS semantic search** over documents *and* database rows. LLMs can query real data through it without being trusted with it. Every tool is read-only and returns typed, structured output. Each tool family is guarded by several independent safety layers, so no single check has to be perfect.
```text
You: "Why is order ORD-10118 late?"
Agent ├─ run_sql → shipped 2026-11-20, promised 2026-11-25, still in transit, tracking PP675046498849
├─ call_api → logistics.track_shipment: status=exception, "Weather delay at regional hub" (Louisville, KY)
├─ semantic_search → runbooks/carrier-delay-triage.md#step-2-classify-the-exception (score 0.40)
└─ run_sql → open ticket T-5263 (high priority, in progress)
Answer: The SLA is breached. Carrier weather exception at the Louisville hub. Per the triage
runbook, send a proactive delay notice and apply the shipping-charge breach credit.
```
---
## Table of contents
1. [Highlights](#highlights)
2. [Screenshots](#screenshots)
3. [Architecture](#architecture)
4. [Quick start](#quick-start)
5. [Ways to use it](#ways-to-use-it)
6. [Tools, resources & prompts](#tools-resources--prompts)
7. [Security model](#security-model)
8. [Semantic search: how "live" works](#semantic-search-how-live-works)
9. [Demo dataset](#demo-dataset)
10. [Testing](#testing)
11. [Deploying to Kubernetes](#deploying-to-kubernetes)
12. [Configuration](#configuration)
13. [Project layout](#project-layout)
14. [Design decisions](#design-decisions)
15. [Known limitations & roadmap](#known-limitations--roadmap)
---
## Highlights
- **10 MCP tools across 4 families:** SQL, files, business APIs and semantic search. Each returns a Pydantic model, so clients get an `outputSchema` and `structuredContent`, not just text.
- **Read-only by construction:**
- A SQLite authorizer means the *database engine itself* refuses writes.
- APIs are an allowlist of named endpoints, so the model never sends a URL (no SSRF).
- Files are sandboxed against traversal and symlink escapes.
- **Live semantic search:** FAISS `IndexIDMap2` with incremental re-indexing. Edit a policy doc or insert a DB row, and only the changed chunks are re-embedded on the next search.
- **Two transports:** stdio (Claude Desktop / Claude Code) and streamable HTTP. HTTP adds bearer auth, DNS-rebinding protection, stateless mode for horizontal scaling, `/healthz`, `/readyz` and Prometheus `/metrics`.
- **Web console:** a browser UI that is itself an MCP client. Every click is a real `tools/call` through the same guardrails an LLM hits.
- **Observability:** a JSON audit log of every tool call, plus per-tool call counters and latency histograms.
- **123 tests:** unit tests, protocol-level tests with a real MCP client, real stdio/HTTP server processes, the UI and the deployment manifests. Also ruff and mypy clean.
- **Kubernetes-ready:** non-root, read-only rootfs, dropped capabilities, probes, HPA, PDB and NetworkPolicy.
---
## Screenshots
| Investigate an order | Live carrier timeline + policy search | SQL guardrail in action |
|---|---|---|
|  |  |  |
*Captured in a narrow side panel (mobile layout). On a desktop browser the tool-call log sits beside the main panel.*
---
## Architecture
```mermaid
flowchart LR
subgraph Clients
A[Claude Desktop / Claude Code<br/>stdio]
B[Agents / GPT tool calling<br/>streamable HTTP + Bearer]
C[Web console<br/>in-process MCP client]
end
subgraph BizMCP["BizMCP server (MCPServer, mcp 2.x)"]
W[Tool wrapper<br/>audit log · metrics · safe errors]
DB[ReadOnlyDatabase<br/>authorizer · mode=ro · limits]
FS[FileSandbox<br/>no traversal · no symlink escape]
API[ApiClient<br/>allowlist · retries · size caps]
IDX[KnowledgeIndex<br/>FAISS IndexIDMap2 · incremental sync]
end
A --> W
B --> W
C --> W
W --> DB & FS & API & IDX
DB --> SQL[(SQLite business DB)]
FS --> DOCS[/Markdown policies & runbooks/]
IDX --> SQL
IDX --> DOCS
API --> LOG[Logistics API<br/>mock carrier service]
```
**Request path:**
1. A client issues `tools/call`.
2. The MCP SDK validates the arguments against the tool's input schema.
3. The BizMCP wrapper starts an audit/metrics span.
4. The service runs its own validation plus engine-level guards.
5. It returns a Pydantic result that becomes `structuredContent`.
The tool backends (`tools/`, `retrieval/`) are plain Python with **no MCP imports**, so they can be unit-tested and reused independently.
---
## Quick start
**Requirements:** Python 3.11+ and macOS or Linux. The `make` targets assume a `.venv` in the repo.
```bash
make install # create .venv and install with dev extras
make seed # build the deterministic demo database → data/business.db
make ui # web console → http://localhost:8090
```
Then open **http://localhost:8090**, click **Show late orders**, and pick one.
Run the full quality gate:
```bash
make check # ruff + format check + mypy + 123 tests (about 11 s)
```
> **Behind a corporate proxy?** If `pip install` cannot reach PyPI, point `PIP_INDEX_URL` at your organisation's package mirror before running `make install`.
---
## Ways to use it
### 1. Web console (best for demos)
```bash
make ui # mock carrier API runs in-process
python -m bizmcp ui --external-api # or use LOGISTICS_API_URL instead
```
| Tab | What it shows |
|---|---|
| **Investigate** | Pick a late order and watch the agent-style chain: SQL → live carrier API → SLA verdict → runbook search → tickets. Each step shows the tool used and its latency. |
| **Semantic search** | FAISS results with score bars, sources and citations (`ref`). Example queries included. |
| **SQL** | Read-only queries with a results table. Includes a *"Try a write (blocked)"* example. |
| **Tools** | The exact tool list, descriptions and input schemas an LLM receives. Call any tool with raw JSON. |
| **Tool-call log** | A live list of every call: green = success, red = blocked, with duration and arguments. |
The console binds to `127.0.0.1` and has no authentication. It's a local developer tool, not something to deploy.
### 2. Claude Desktop / Claude Code (stdio)
Copy [`examples/claude_desktop_config.json`](examples/claude_desktop_config.json) into your MCP client config and replace the absolute paths. Then ask questions in plain English: *"Which carriers have the most late deliveries, and what does our policy say about breach credits?"*
For live carrier data, also run `make mock-api` (port 8081).
### 3. Streamable HTTP (deployment mode)
```bash
BIZMCP_AUTH_TOKEN=change-me make serve-http # http://127.0.0.1:8000/mcp
make mock-api # in another terminal
python examples/client_demo.py --http http://127.0.0.1:8000/mcp --token change-me
```
### 4. Scripted terminal demo (stdio)
```bash
make mock-api & # carrier API on :8081
make demo # runs the multi-tool investigation and prints each step
pkill -f "bizmcp mock-api"
```
### CLI reference
| Command | Purpose |
|---|---|
| `bizmcp serve [--transport stdio\|http] [--host] [--port]` | Run the MCP server |
| `bizmcp ui [--host] [--port] [--external-api]` | Run the web console (default port 8090) |
| `bizmcp seed [--db PATH] [--force] [--if-missing]` | Create the synthetic database |
| `bizmcp mock-api [--host] [--port] [--db]` | Run the mock logistics API (default port 8081) |
| `bizmcp index` | Build and persist the FAISS index to `BIZMCP_INDEX_DIR` |
---
## Tools, resources & prompts
### Tools
All tools are annotated `readOnlyHint=true` and `idempotentHint=true`. `call_api` is additionally `openWorldHint=true`.
| Family | Tool | What it does |
|---|---|---|
| Database | `list_tables` | Tables and views with row counts |
| | `describe_table` | Columns, types, PK/FKs, three sample rows |
| | `run_sql` | One read-only `SELECT`/`WITH` with `?` parameters. Row-capped and time-limited |
| Files | `list_files` | List the documents knowledge base (glob, recursive) |
| | `read_file` | Read a document or a line range |
| | `search_files` | Literal (non-regex) text search with line numbers |
| APIs | `list_api_endpoints` | The allowlisted endpoints and their parameters |
| | `call_api` | Call an endpoint by id, e.g. `logistics.track_shipment` |
| Search | `semantic_search` | FAISS vector search over docs, products and tickets, with citations |
| | `index_status` | Index readiness, embedder, chunk counts, last sync |
### Resources
| URI | Content |
|---|---|
| `bizmcp://schema` | `CREATE` statements for every table |
| `bizmcp://docs/{+path}` | Any knowledge-base document by relative path |
### Prompts
| Prompt | Purpose |
|---|---|
| `grounded_answer(question)` | Instructs the model to answer only from tool evidence, with citations |
| `investigate_order(order_id)` | Step-by-step order investigation across SQL, API and policy search |
### HTTP endpoints (HTTP transport only)
| Path | Auth | Purpose |
|---|---|---|
| `/mcp` | Bearer token | MCP streamable-HTTP endpoint |
| `/healthz` | none | Liveness |
| `/readyz` | none | Readiness. Returns 503 until the FAISS index has warmed up |
| `/metrics` | none | Prometheus metrics (restrict with NetworkPolicy) |
---
## Security model
Each threat is covered by layers that work independently, so bypassing one is not enough.
| Threat | Mitigations |
|---|---|
| **SQL writes / DDL** | (1) Lexical check: exactly one statement starting with `SELECT`/`WITH`. (2) A **SQLite authorizer** that denies every engine action except reads, so even `WITH x AS (…) DELETE …` fails. (3) Connection opened `mode=ro` with `PRAGMA query_only`. |
| **Runaway / abusive queries** | Wall-clock timeout via a progress handler. Row cap with a `truncated` flag. SQL-length and value-size limits (`zeroblob(5e8)` refused). `load_extension` denied. |
| **Path traversal** | Relative paths only. Rejects `..`, absolute paths, `~`, drive letters, NUL bytes and hidden files. A post-`resolve()` containment check blocks **symlink escapes**. Extension allowlist and binary-file detection. |
| **SSRF / API abuse** | The model never sends a URL, only a registered `service.endpoint` id. Path params are allowlisted (`[A-Za-z0-9._-]`, so `..`, `/` and `%2e%2e` are rejected) and URL-encoded. Only declared query params are accepted, with type and pattern checks. GET only, **redirects never followed**, response size capped, retries limited to transient 5xx/timeouts. |
| **Secret leakage** | API keys come from env vars (`${VAR}` expansion in `apis.yaml`), are sent as headers, and are never echoed in results. |
| **Transport** | Constant-time bearer-token comparison. DNS-rebinding protection with an explicit `allowed_hosts` list. Kubernetes NetworkPolicy limits which pods can connect. |
| **Error leakage** | Only curated `BizMCPError` messages reach the model. Unexpected exceptions are logged server-side and reported generically. |
| **UI injection** | The console renders server data with `textContent` only (never `innerHTML`). |
Every row above has tests (see [Testing](#testing)).
---
## Semantic search: how "live" works
```text
search(query) ─► fingerprint check (cheap file stats) ─► changed? ─► reload source ─► diff by SHA-256
└─► embed ONLY new/changed chunks
└─► FAISS remove_ids / add_with_ids
```
- **Sources:**
- Markdown docs, chunked by heading with overlap. Each chunk carries its heading path as context.
- Database rows (`products`, `support_tickets`), declared in [`config/index.yaml`](config/index.yaml) as format templates. Point it at your own tables.
- **Change detection:** each source exposes a cheap fingerprint (file mtimes/sizes, DB + WAL stats). Checks are rate-limited by `BIZMCP_INDEX_MIN_CHECK_INTERVAL_S`.
- **Incremental updates:** vectors live in a FAISS `IndexIDMap2` keyed by a stable 63-bit hash of the chunk key. Inserts, updates and deletes cost O(changed) and never rebuild the index.
- **Filtered search:** source filters use FAISS `IDSelectorBatch`, so filtering happens inside the search rather than after it.
- **Persistence:** with `BIZMCP_INDEX_DIR`, the index and metadata are written atomically. On restart it loads without re-embedding, and rebuilds automatically if the embedder changes.
**Embedders:**
| Embedder | When to use |
|---|---|
| `hashing` (default) | Deterministic, offline, zero dependencies. Signed feature hashing of word uni/bi-grams + character n-grams. **Lexical:** matches *refund/refunded* but not *broken/damaged*. |
| `sentence-transformers` | `pip install 'bizmcp[semantic]'` and `BIZMCP_EMBEDDER=sentence-transformers`. True synonym-level matching with the same index and API. |
---
## Demo dataset
`bizmcp seed` builds a **deterministic** synthetic e-commerce fulfillment dataset (fixed RNG seed, "as of" 2026-11-28 12:00):
| Table | Rows | Notes |
|---|---|---|
| `warehouses` | 5 | Fulfillment centers |
| `sellers` | 20 | Tiers, on-time ship rates, statuses |
| `products` | 92 | Titles and descriptions (embedded for search) |
| `inventory` | 188 | On-hand, reserved, reorder points, some low stock |
| `orders` | 800 | About 36% of shipped orders are late (delivered late or still in transit past the promise date) |
| `order_items` | 1,266 | Line items |
| `support_tickets` | 282 | Late delivery, damage, returns, billing, inventory (embedded) |
The knowledge base in [`data/docs/`](data/docs) holds the returns policy, shipping SLA, fee schedule, carrier-delay and inventory runbooks, and seller performance standards.
The **mock logistics API** derives tracking timelines from the same orders. A late order in SQL therefore shows a matching carrier exception in the API, which makes multi-tool reasoning demonstrable.
---
## Testing
```bash
make check # ruff + ruff format --check + mypy + pytest
make test-fast # skip the e2e tests that spawn processes
```
| Suite | What it proves |
|---|---|
| `test_database.py` | 15 write/DDL/ATTACH/PRAGMA attacks blocked, including ones that pass the lexical check. Timeout, row cap, value limits, schema introspection. |
| `test_files.py` | 7 traversal vectors, symlink escape, hidden files, binary/type rejection, truncation on line boundaries, literal search. |
| `test_api.py` | SQL↔API consistency, 8 path-injection payloads, schema validation, retry/backoff, timeouts, truncation, no redirects, no secret echo. |
| `test_retrieval.py` | Embedding determinism across processes, chunking, policy-retrieval accuracy, **live incremental re-indexing** (exact add/update/remove counts), persistence. |
| `test_server.py` | Real MCP client (in-memory): tool schemas and annotations, structured output, error reporting, resources, prompts, metrics, a full multi-tool investigation. |
| `test_transports.py` | Real processes over **stdio** and **streamable HTTP**: auth (401s), probes, live mock API, Prometheus counters. |
| `test_ui.py` | Console serves assets, routes tool calls through MCP, surfaces guardrail errors, logs calls, rejects bad input. |
| `test_deploy.py` | Renders kustomize offline. Checks non-root, read-only rootfs, dropped caps, probes, resources, secret wiring, config↔service consistency. |
CI ([`.github/workflows/ci.yml`](.github/workflows/ci.yml)) runs the suite on Python 3.11 and 3.13. It also builds the Docker image and smoke-tests `/readyz` and the 401 on `/mcp`.
---
## Deploying to Kubernetes
```bash
docker build -t <your-registry>/bizmcp:0.1.0 . && docker push <your-registry>/bizmcp:0.1.0
# set the image in deploy/k8s/kustomization.yaml (images: newName/newTag)
kubectl create namespace bizmcp
kubectl -n bizmcp create secret generic bizmcp-auth --from-literal=token="$(openssl rand -hex 32)"
kubectl apply -k deploy/k8s
```
| Manifest | Highlights |
|---|---|
| `bizmcp.yaml` | Deployment with 2+ replicas, startup/readiness/liveness probes, `runAsNonRoot`, read-only rootfs, `drop: [ALL]`, seccomp `RuntimeDefault`, Prometheus annotations, topology spread, emptyDir for the index cache. Plus a Service. |
| `logistics-api.yaml` | Mock carrier API with the same hardening |
| `configmap.yaml` | Stateless HTTP, allowed hosts, index dir, API URL |
| `hpa.yaml` / `pdb.yaml` | Scales 2–6 replicas at 70% CPU; at least 1 pod always available |
| `networkpolicy.yaml` | Only pods labelled `bizmcp-client=true` (plus monitoring) may reach the server |
`BIZMCP_STATELESS_HTTP=true` lets any replica serve any request, with no sticky sessions. Readiness stays false until the FAISS index has warmed up, so rolling updates never route traffic to a cold pod.
Render the manifests offline (no cluster contact) with `make k8s-render`.
---
## Configuration
Every setting is a `BIZMCP_*` environment variable (see [`src/bizmcp/config.py`](src/bizmcp/config.py)).
| Variable | Default | Purpose |
|---|---|---|
| `BIZMCP_DB_PATH` | `data/business.db` | SQLite database |
| `BIZMCP_DOCS_ROOT` | `data/docs` | Knowledge-base root (file sandbox) |
| `BIZMCP_API_CONFIG` | `config/apis.yaml` | API endpoint allowlist |
| `BIZMCP_INDEX_CONFIG` | `config/index.yaml` | What to embed |
| `BIZMCP_EMBEDDER` | `hashing` | `hashing` or `sentence-transformers` |
| `BIZMCP_INDEX_DIR` | unset | Persist the FAISS index here |
| `BIZMCP_INDEX_MIN_CHECK_INTERVAL_S` | `2.0` | Minimum seconds between freshness checks |
| `BIZMCP_SQL_MAX_ROWS` / `BIZMCP_SQL_TIMEOUT_S` | `200` / `5` | Query guardrails |
| `BIZMCP_FILE_MAX_BYTES` | `256000` | Max bytes read per file |
| `BIZMCP_API_TIMEOUT_S` / `BIZMCP_API_MAX_RETRIES` | `10` / `2` | Upstream API limits |
| `BIZMCP_HOST` / `BIZMCP_PORT` | `127.0.0.1` / `8000` | HTTP bind address |
| `BIZMCP_AUTH_TOKEN` | unset | Bearer token for `/mcp` (warns if unset) |
| `BIZMCP_ALLOWED_HOSTS` | `[]` | DNS-rebinding allowlist (JSON list) |
| `BIZMCP_STATELESS_HTTP` | `true` | Stateless streamable HTTP |
| `LOGISTICS_API_URL` / `LOGISTICS_API_KEY` | `http://127.0.0.1:8081` / empty | Expanded into `apis.yaml` |
---
## Project layout
```text
llm-mcp-server/
├── src/bizmcp/
│ ├── server.py MCP wiring: tools, resources, prompts, routes, bearer auth
│ ├── tools/ database.py · files.py · api.py (pure Python, no MCP imports)
│ ├── retrieval/ embeddings.py · chunking.py · index.py (FAISS)
│ ├── ui.py, ui_static/ web console (MCP client + vanilla JS, no build step)
│ ├── observability.py audit log + Prometheus metrics
│ ├── seed.py deterministic synthetic dataset
│ ├── mock_api.py carrier API consistent with the DB
│ ├── config.py BIZMCP_* settings
│ └── cli.py `bizmcp` command
├── config/ apis.yaml (endpoint allowlist) · index.yaml (embedding sources)
├── data/docs/ policies, runbooks, guides (knowledge base)
├── deploy/k8s/ kustomize manifests
├── examples/ client_demo.py · claude_desktop_config.json
├── docs/screenshots/ console screenshots
├── tests/ 123 tests
├── Dockerfile · Makefile · pyproject.toml · .github/workflows/ci.yml
```
---
## Design decisions
- **Guard at the engine, not with regex.** SQL safety comes from SQLite's authorizer and a read-only connection. The lexical check only exists to give friendlier error messages.
- **Named endpoints instead of URLs.** Giving an LLM a generic HTTP tool invites SSRF. A registry of typed endpoints is safer and also easier for the model to use.
- **Structured outputs everywhere.** Pydantic return types give clients machine-readable schemas, which reduces parsing errors in agent loops.
- **Incremental indexing over periodic rebuilds.** Stable IDs plus content digests keep freshness cheap: O(changed), not O(corpus).
- **Stateless HTTP by default.** It trades server-initiated requests (unused here) for trivial horizontal scaling behind a plain Service.
- **Backends independent of MCP.** `tools/` and `retrieval/` have no MCP imports, so they are easy to test and reusable behind other interfaces.
- **The UI is a real MCP client.** The demo exercises the actual protocol path, so what you see is what an LLM gets.
---
## Known limitations & roadmap
- The default `hashing` embedder is lexical. Use `sentence-transformers` for synonym-level search.
- SQLite is used for a self-contained demo. A Postgres backend would enforce read-only access via a read-only role and `SET TRANSACTION READ ONLY`.
- The bearer token is a single static secret. OAuth 2.1 / per-client tokens (supported by the MCP SDK) are a natural next step.
- The web console is a local developer tool with no authentication.
- Possible additions: hybrid BM25 + vector retrieval, OpenTelemetry tracing, and an LLM-driven agent loop in the console.
---
Built with the [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) 2.x (`MCPServer`), FAISS, Pydantic and Starlette. Licensed under MIT.
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues