Skip to main content
Glama
README.md
# mcp-server-demo

A small [Model Context Protocol](https://modelcontextprotocol.io) server that runs: nine tools over a sample shop database (catalog, orders, sales report), API key auth, per-key scopes, a daily cost quota, rate limits and an audit log. It speaks stdio for local hosts and Streamable HTTP for remote ones, ships with a Dockerfile and a VPS install script (Caddy + systemd), and has unit and integration tests (43, all passing locally).

Built on the official TypeScript SDK v2 (`@modelcontextprotocol/server` 2.4) and the 2026-07-28 protocol revision. Clients on the 2025 revisions are still served; a test covers both.

All data is generated sample data. No real company, customer or product is in it.

## Tools

| Tool | Scope | Cost | What it does |
|---|---|---|---|
| `search_products` | `catalog:read` | 1 | Search by name or SKU, filter by category or stock |
| `get_product` | `catalog:read` | 1 | One product with price and stock |
| `check_stock` | `catalog:read` | 1 | Stock for up to 25 SKUs |
| `list_orders` | `orders:read` | 1 | Orders with totals, filter by status, customer, dates |
| `get_order` | `orders:read` | 1 | One order with its lines |
| `create_order` | `orders:write` | 5 | Place an order; all lines or nothing |
| `cancel_order` | `orders:write` | 5 | Cancel a placed order and restock it |
| `sales_report` | `reports:read` | 3 | Revenue, units and orders by day, week, product, category or customer |
| `get_usage` | any key | 0 | The key's scopes, quota, units used today, tool costs |

Cost is in quota units. Each key has a daily budget (default 500 units, resets 00:00 UTC).

## Run it locally

Needs Node.js 22.

```bash
npm ci
npm run keys -- create --name laptop
```

The second command prints a key starting with `mcpd_`. It is shown once; only its SHA-256 hash is stored.

```bash
npm run dev
```

The server listens on `http://127.0.0.1:3000/mcp` and creates `data/demo.db` with sample data on first start. To call every tool once from a real MCP client:

```bash
MCP_API_KEY=mcpd_... npm run smoke
```

Other key commands: `npm run keys -- list`, `revoke --name <name>`, `usage`, `audit --limit 20`. Scopes and quota are set at creation:

```bash
npm run keys -- create --name reporting-bot --scopes "reports:read" --quota 100
```

## Connect from Claude Code

Over HTTP, to a running server:

```bash
claude mcp add --transport http shop-demo http://127.0.0.1:3000/mcp --header "Authorization: Bearer mcpd_..."
```

Over stdio, Claude Code starts the process itself:

```bash
npm run build
claude mcp add shop-demo -e MCP_API_KEY=mcpd_... -e MCP_DB_PATH=/absolute/path/to/data/demo.db -- node /absolute/path/to/dist/stdio.js
```

`claude mcp list` should show `✔ Connected` for either one. Both commands were run against this repo during development.

## Connect from Claude Desktop

Add a stdio entry to `claude_desktop_config.json` (Settings → Developer → Edit Config) and restart the app:

```json
{
  "mcpServers": {
    "shop-demo": {
      "command": "node",
      "args": ["/absolute/path/to/dist/stdio.js"],
      "env": {
        "MCP_API_KEY": "mcpd_...",
        "MCP_DB_PATH": "/absolute/path/to/data/demo.db"
      }
    }
  }
}
```

For a remote deployment, the third-party [`mcp-remote`](https://www.npmjs.com/package/mcp-remote) bridge can forward stdio to the HTTP endpoint with `--header "Authorization: Bearer ..."`. The Desktop setup was not tested for this repo.

## Configuration

All settings are environment variables; see [`.env.example`](.env.example).

| Variable | Default | Meaning |
|---|---|---|
| `MCP_DB_PATH` | `data/demo.db` | SQLite file |
| `MCP_HOST` / `MCP_PORT` | `127.0.0.1` / `3000` | HTTP bind address |
| `MCP_ALLOWED_HOSTS` | `localhost,127.0.0.1,[::1]` | Accepted `Host` and `Origin` hostnames |
| `MCP_KEY_RPM` | `60` | Requests per minute per key (0 = off) |
| `MCP_IP_RPM` | `120` | Requests per minute per client IP (0 = off) |
| `MCP_TRUST_PROXY` | `0` | `1` = take the client IP from `X-Forwarded-For` |
| `MCP_API_KEY` | | stdio only: the key the process acts as |

## Tests

```bash
npm run typecheck
npm test
```

43 tests, about 1 second. Unit tests cover the rate limiter, the quota (limit, refund, UTC day rollover), key hashing and revocation, and the order logic (stock, rollback on a short line, cancel rules, report totals). Integration tests drive the server through a real MCP client: in-process over `fetch`, and as child processes over stdio and a real HTTP socket. They check 401 on missing or revoked keys, scope-based tool lists, every tool's output, quota refusal, 429 with `Retry-After`, audit rows, and the Host/Origin guards.

A GitHub Actions workflow (typecheck, tests and build on Node 22, then a Docker build and a `/healthz` check on the container) is written but not yet in this repository, so CI has not run. Until it is added, the results above are from local runs.

## Docker

```bash
docker build -t mcp-server-demo .
docker run -p 3000:3000 -v mcp-data:/data mcp-server-demo
docker exec -it <container> node dist/cli.js create --name laptop
```

The image runs as the `node` user and keeps the database in the `/data` volume. Docker was not installed on the machine this was written on, so the image has not been built yet; the CI workflow will build and check it once it is added.

## Deploy on a VPS

For Debian or Ubuntu with ports 80 and 443 open and a DNS record pointing at the server:

```bash
git clone <this repo> && cd mcp-server-demo
sudo ./deploy/install.sh mcp.example.com
sudo mcp-demo-keys create --name laptop
```

The script installs Node 22 and Caddy if missing, builds the app into `/opt/mcp-demo`, runs it as the unprivileged `mcp-demo` user under systemd ([`deploy/mcp-demo.service`](deploy/mcp-demo.service), with filesystem and kernel protections on), and adds a Caddy site ([`deploy/Caddyfile`](deploy/Caddyfile)) that terminates TLS and exposes only `/mcp` and `/healthz`. Settings live in `/etc/mcp-demo.env`. Running it again updates the app and keeps the config and database. Logs: `journalctl -u mcp-demo`.

If Caddy's stock `/etc/caddy/Caddyfile` still has the default `:80` welcome-page block, remove it so plain HTTP requests redirect to HTTPS.

The script has been syntax-checked but not yet run on a live VPS.

## Design decisions

**Stateless per request.** SDK v2 builds a fresh `McpServer` for every HTTP request from a factory. No session state lives in the process, so a restart or a second instance loses nothing but the in-memory rate-limit buckets.

**API keys, not OAuth.** The intended callers are agents and scripts, not people signing in, and an API key in a header is what Claude Code and most hosts can send without extra setup. OAuth would need a separate authorization server. The key check is plugged into the SDK's `requireBearerAuth` as a token verifier, so moving to OAuth or JWTs later means replacing one function (`verifyAccessToken` in [`src/app.ts`](src/app.ts)).

**Keys are hashed and checked on every request.** Keys are 32 random bytes, so SHA-256 is enough to store them (there is nothing to brute-force, unlike a password). There is no auth cache, so a revoked key stops working on its next request.

**Scopes decide which tools exist.** The per-request factory registers only the tools the key's scopes allow. A read-only key never sees `create_order` in `tools/list`, so the model cannot plan around a tool it is not allowed to use, and a call to it fails as "tool not found".

**Quota in cost units, stored in SQLite.** A daily request count would treat a report and a product lookup the same. Cost units let expensive or state-changing tools spend more, and map directly to real money if a tool ever calls a paid API. The check and the increment are a single `UPDATE ... WHERE units + cost <= limit`, so two parallel calls cannot both spend the last units. Calls that fail are refunded.

**Rate limits in memory, at the HTTP edge.** A token bucket per key (60/min) and per client IP (120/min) answers `429` with `Retry-After` before any MCP parsing. The per-IP limit also caps how fast anyone can guess keys. Keeping the buckets in memory is fine for one process; several instances would need a shared store such as Redis.

**Audit log in the same database.** Every tool call writes one row: time, key, tool, arguments (cut at 2,000 characters), outcome, cost and duration. Failed auth and rate-limit hits are logged too. Keys never travel in tool arguments, so the log holds no secrets.

**Errors the model can act on.** Expected failures (unknown SKU, not enough stock, shipped order) come back as tool results with `isError: true` and a message that says what to do next, such as "Use search_products to find valid SKUs". Unexpected exceptions return only an audit id; the details stay in the server log.

**Writes are transactions.** `create_order` checks every line before writing anything. If one SKU is short, no order is created and no stock moves.

**SQLite via better-sqlite3.** One file, a synchronous API, WAL mode, and no database server to run on a small VPS. With several writer processes, Postgres would be the next step.

**DNS rebinding guard.** The HTTP entry checks `Host` and `Origin` against `MCP_ALLOWED_HOSTS` using the SDK's Node helpers, so a web page cannot reach a server bound to localhost through a rebound domain.

## Layout

```text
src/
  app.ts      HTTP surface as a fetch handler: auth, per-key rate limit, MCP handler
  http.ts     Node entry: Host/Origin checks, per-IP limit, listen, graceful shutdown
  stdio.ts    stdio entry for local hosts
  server.ts   Tool definitions, scope filtering, quota and audit wrapper
  store.ts    Catalog, order and report queries
  keys.ts     Key creation, hashing, lookup, revocation
  limits.ts   Rate limiter and daily quota
  audit.ts    Audit log writes
  db.ts       Schema
  seed.ts     Deterministic sample data
  cli.ts      Key and audit admin commands
tests/        Unit and integration tests (vitest)
scripts/      smoke.ts: call every tool on a running server
deploy/       install.sh, systemd unit, Caddyfile, env example
```

## License

MIT