Skip to main content
Glama
README.md
# toy-mcp

Two small MCP servers for studying the Model Context Protocol on the wire, and for seeing what changed in the 2026-07-28 revision. Both are short enough to read in an afternoon.

[MCP](https://modelcontextprotocol.io) is an open protocol that lets an AI application call tools and read data that a server offers. The messages are JSON-RPC 2.0, and here they travel over HTTP.

|                     | Code               | Port | Protocol                                                     | Built with                                           |
| ------------------- | ------------------ | ---- | ------------------------------------------------------------ | ---------------------------------------------------- |
| SDK server          | `src/sdk-server/`  | 3333 | 2025-11-25 (the latest that v1 of the official SDK supports) | Version 1 of the official TypeScript SDK             |
| Hand-written server | `src/server-2026/` | 3334 | 2026-07-28                                                   | Node's `http` module, no MCP SDK, built step by step |

They can run side by side, so the same kind of request can be sent to each and the answers compared.

This is a learning project. Neither server is meant for production: see [Known gaps](#known-gaps).

## Quick start

Requires Node 20.19+, 22.13+ or 24+.

```bash
npm install
```

Then start each server in its own terminal:

```bash
npm start            # SDK server           http://127.0.0.1:3333/mcp and /mcp-session
```

```bash
npm run start:2026   # hand-written server  http://127.0.0.1:3334/mcp
```

Three environment variables configure a server (`src/http/config.ts`):

| Variable          | Default                                                  | What it sets                                                                                                                                                                       |
| ----------------- | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `HOST`            | `127.0.0.1`                                              | The interface to listen on. The default is reachable from this machine only. There is no authentication, so any other value exposes every tool to whoever can reach that interface |
| `PORT`            | `3333` (SDK server), `3334` (hand-written)               | The port to listen on, for example `PORT=4000 npm start`                                                                                                                           |
| `ALLOWED_ORIGINS` | The server's own origin, such as `http://localhost:3334` | The `Origin` values that are not refused, separated by commas. A client that is not a browser sends no `Origin` and is not affected                                                |

The `Origin` check only refuses. It does not make a server callable from a web page: that also takes CORS, which neither server implements (see [Known gaps](#known-gaps)).

Each server prints one line for every request that reaches its code, including the ones it refuses or that fail. A request that Node's HTTP parser answers by itself, such as text that is not HTTP (`400`) or headers that are too large (`431`), never reaches that code and is not logged. This is the hand-written server after a valid request, a request without the MCP headers, a request from a page on another site, and a client that hung up in the middle of its body:

```
2026-07-28 server on http://127.0.0.1:3334/mcp
server/discover -> 200
server/discover -> 400 -32020 Header mismatch: MCP-Protocol-Version header is missing
(refused) -> 403 Origin "http://evil.example"
(client aborted)
```

To send requests, see [Try it](#try-it).

## Where to start reading

The whole of `src/` is about 2290 lines, comments included.

1. This README, then [docs/how-it-works.md](docs/how-it-works.md), which walks through both servers with the responses they return.
2. `src/catalog/tools.ts`: the six tools, defined once for both servers.
3. `src/sdk-server/`: `server.ts` registers the tools, `http.ts` is the HTTP transport and `sessions.ts` adds session mode.
4. `src/server-2026/handler.ts` and `tools.ts`, then the functions in `src/protocol/` that they call.
5. `test/`: the test names list the behaviors, one per line.
6. [docs/spec-2026-07-28.md](docs/spec-2026-07-28.md): the parts of the specification that the hand-written server implements, with sources.

## Project layout

```
src/
  protocol/     JSON-RPC types, type guards and reply builders, error codes, per-request validation, result builders, the signed request state, showing untrusted values, server/discover (pure functions)
  http/         what both servers' front doors share: the configuration, the guard for Origin, path and method, body reading with a size limit, and the listener that logs every failure
  catalog/      the toy marketplace behind both servers' tools: items, input validation, job store, shared tool definitions
  sdk-server/   the SDK-based server: tool registration, HTTP transport and session mode
  server-2026/  the hand-written server: request handler, tools and HTTP transport
test/           Vitest tests, mirroring src/
postman/        a Postman collection: ready-made requests for both servers
docs/           how it works, and the wire shapes of the 2026-07-28 spec
```

The hand-written server keeps its protocol rules in plain functions (the request handler from `createHandler`, `validateRequest`, `callTool`) with the HTTP layer kept thin, so the rules can be read and tested without a network. Both servers expose the same tools: each one is defined once in `src/catalog/tools.ts`, and a server only turns the definition into its own wire format.

## Scripts

| Script                 | What it does                                                                                                                                                                          |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `npm test`             | Vitest: unit tests plus end-to-end tests that boot each server on a random port                                                                                                       |
| `npm run typecheck`    | `tsc -p .`                                                                                                                                                                            |
| `npm run lint`         | ESLint: recommended rules, rules that use type information in `src/`, single quotes, a TSDoc comment on every exported symbol in `src/`, and no SDK import in the hand-written server |
| `npm run format`       | Prettier: rewrite files to the project style                                                                                                                                          |
| `npm run format:check` | Prettier: report files that differ from the project style, without changing them                                                                                                      |
| `npm run check`        | typecheck, lint, formatting check and tests                                                                                                                                           |

GitHub Actions runs `npm run check` on Node 20, 22, 24 and 26 for every push to `main` and every pull request (`.github/workflows/check.yml`).

## Try it

### Postman

`postman/toy-mcp.postman_collection.json` is a Postman collection (v2.1) with 59 requests, in one folder for each server and one for the SDK server's session mode. Every request has a description that says what it demonstrates and what to look for in the reply.

1. Start the server you want to try (see [Quick start](#quick-start)).
2. In Postman, select **Import** and choose the file. The collection needs no environment and no authorization.
3. Open the folder of that server and send its requests from top to bottom.

| Folder                                            | Start the server with | URL variable | Default value                       |
| ------------------------------------------------- | --------------------- | ------------ | ----------------------------------- |
| `SDK server :3333 (protocol 2025-11-25)`          | `npm start`           | `sdk`        | `http://127.0.0.1:3333/mcp`         |
| `SDK server :3333, session mode (/mcp-session)`   | `npm start`           | `sdkSession` | `http://127.0.0.1:3333/mcp-session` |
| `Hand-written server :3334 (protocol 2026-07-28)` | `npm run start:2026`  | `s2026`      | `http://127.0.0.1:3334/mcp`         |

`sdk`, `sdkSession` and `s2026` are collection variables that hold the whole URL. If you started a server with another `PORT`, change the port in its variable (open the collection, then its **Variables** tab).

The SDK server answers every request in its first folder but the last with HTTP 200 and an SSE frame: the JSON-RPC message is on the `data:` line. The session folder is numbered 1 to 9 and must be sent in order: request 4 stays open until request 7 answers it, so send 5, 6 and 7 from other tabs. The hand-written server's requests are numbered 01 to 36: 01 to 20 cover the envelope, the per-request rules and the transport, 21 to 29 cover the tools, and 30 to 36 cover the tool that asks the user. In every folder a request's name ends with the HTTP status to expect and, where there is one, the JSON-RPC error code or `isError`.

`get_result` reads a job id from a collection variable: `jobId` in the SDK folder and `jobId2026` in the hand-written folder, because each server has its own job store. A script on each `start_job` request stores the `jobId` from the reply in that variable. If `get_result` answers `No job`, send `start_job` on the same server first. Two more variables are filled in the same way: `sessionId` by the `initialize` request of the session folder, and `requestState` by request 30 of the hand-written folder.

### curl

Every call is one JSON-RPC POST, so plain curl works too. Write each header out in full.

The hand-written server:

```bash
curl -X POST 'http://127.0.0.1:3334/mcp' -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' -H 'MCP-Protocol-Version: 2026-07-28' -H 'Mcp-Method: server/discover' -d '{"jsonrpc":"2.0","id":"d1","method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}'
```

It replies with one line of JSON, shown here on several lines:

```json
{
  "jsonrpc": "2.0",
  "id": "d1",
  "result": {
    "resultType": "complete",
    "supportedVersions": ["2026-07-28"],
    "capabilities": { "tools": {} },
    "instructions": "Hand-written MCP server for the 2026-07-28 revision.",
    "_meta": {
      "io.modelcontextprotocol/serverInfo": { "name": "toy-marketplace-2026", "version": "0.1.0" }
    },
    "ttlMs": 3600000,
    "cacheScope": "public"
  }
}
```

The SDK server:

```bash
curl -X POST 'http://127.0.0.1:3333/mcp' -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
```

The SDK server needs the `Accept` header shown here. curl's default, `Accept: */*`, is answered with `406`.

A client that opens with `initialize` (any client written for an earlier revision, including one built on v1 of the SDK) gets `400` with `-32020` from the hand-written server, because it sends none of the new headers, and the error lists the supported versions so that the client can tell why. That is the intended behavior of a server that speaks 2026-07-28 only. Postman and curl are the way to talk to it.

## The SDK server

A small marketplace with a catalog of three fake items. The hand-written server exposes the same six tools.

| Tool                          | What it demonstrates                                                                                                                          |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `echo`                        | The minimal tool: name, description, JSON-Schema input, typed content result                                                                  |
| `search_catalog`, `call_item` | The marketplace pattern: search, then one generic call. A validation failure names every failing field                                        |
| `start_job`, `get_result`     | A server-minted handle in place of a session. `idempotencyKey` deduplicates retries and `maxCostUsd` is a cost cap checked before work starts |
| `confirm_purchase`            | A tool that asks the user a question in the middle of a call (elicitation). On this server it works only in session mode                      |

Behaviors worth knowing:

- It is built on v1 of the official TypeScript SDK (the `@modelcontextprotocol/sdk` package), which supports protocol 2025-11-25 at most, so `server/discover` returns `-32601`. Version 2 of the SDK (the `@modelcontextprotocol/server` and `@modelcontextprotocol/client` packages) implements the 2026-07-28 revision. This project does not use it: the second server is written by hand, so that every rule of the 2026-07-28 wire format is visible in the code.
- Stateless mode on `/mcp`: a fresh server per request, no `Mcp-Session-Id`, and `tools/list` works without `initialize`.
- Session mode on `/mcp-session`: `initialize` opens a session and returns an `Mcp-Session-Id`, every later request must carry it, and `DELETE` ends it. The server keeps one server object per session in memory. This is what lets `confirm_purchase` ask the user: the question travels on the open stream of the tool call, and the answer, a separate POST, finds the waiting call through the session id. On `/mcp` the same tool fails, and an answer sent there is accepted with `202` and dropped.
- Replies are SSE frames (`event: message`, `data: {...}`) even for a single response.
- A request whose `Origin` header is not on the allow-list gets `403` on both routes, before the SDK sees it. See [the hand-written server](#the-hand-written-server) for why.
- Argument-validation failures and unknown tools come back as a normal result with `isError: true`. Unknown methods come back as a JSON-RPC `error`.
- The SDK's transport refuses some requests before any tool runs: `406` unless `Accept` lists both `application/json` and `text/event-stream`, `415` unless `Content-Type` is `application/json`, `400` for an `MCP-Protocol-Version` header that names a version it does not support (such as `2026-07-28`), and `400` with `-32700` for a body that is JSON but not a JSON-RPC message. It acknowledges a notification with `202` and no body.
- Jobs live in memory and a timer stands in for the work, so a restart loses them. A real deployment needs a database, a queue and workers; `docs/how-it-works.md` lists what stands in for what.

## The hand-written server

Built one step at a time; each step is runnable and each rejection is visible in the server log.

| Step | What it adds                                                                                        | Status |
| ---- | --------------------------------------------------------------------------------------------------- | ------ |
| 1    | JSON-RPC envelope, `server/discover`, `404` with `-32601` for removed or unknown methods            | Done   |
| 2    | Per-request rules: required headers, required `_meta`, version check, an error old clients can read | Done   |
| 3    | `tools/list` and `tools/call` with `resultType`, plus `ttlMs` and `cacheScope` on the list          | Done   |
| 4    | The handle, idempotency and cost-cap tools from the SDK server                                      | Done   |
| 5    | Multi round-trip requests: `input_required`, `requestState` and `inputResponses`                    | Done   |

A tool that fails, or is given arguments its schema rejects, answers with HTTP 200 and a normal result carrying `isError: true`. An unknown tool is a protocol error: `400` with `-32602`.

`confirm_purchase` must ask the user, and it takes two requests. The first gets a result with `resultType: "input_required"`: the question under `inputRequests`, and a signed `requestState`. The client asks the user and sends the same call again, with the answer in `inputResponses` and the state unchanged. The server stores nothing in between. A retry that brings the state but no answer is asked again.

Every result carries the server's name and version under `_meta`, as the specification recommends.

A message without an `id` is a notification. The server acknowledges it with `202` and no body, and runs nothing.

Errors it returns today:

| Code     | HTTP | Meaning                                                                                                                                      | Example trigger                                                                                                                                                                                                                                                              |
| -------- | ---- | -------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `-32700` | 400  | Body is not valid JSON                                                                                                                       | Body `not json`                                                                                                                                                                                                                                                              |
| `-32600` | 400  | Not a JSON-RPC 2.0 request; answered with `id: null`                                                                                         | Body `null`; a `method` that is not a string; an `id` that is `null`, a fraction such as `1.5`, or anything but a string or an integer                                                                                                                                       |
| `-32020` | 400  | A required header is missing, or a header contradicts the body                                                                               | No `MCP-Protocol-Version`; header version differs from `_meta`; `Mcp-Method` or `Mcp-Name` differs from the body; an `Mcp-Name` in the Base64 form that is not canonical Base64 of valid UTF-8; an `initialize` from a client of an earlier revision (with `data.supported`) |
| `-32602` | 400  | Invalid params: `_meta` lacks a protocol version (a string) or client capabilities (an object), or a `tools/call` cannot be accepted         | Headers present, no `_meta`; `tools/call` naming an unknown tool; `arguments` that is not an object; `params` nested more than 64 levels deep; a `tools/list` with a `cursor`; a retry whose `requestState` is missing, changed, expired or from another call                |
| `-32021` | 400  | The request needs a client capability that `_meta` does not declare, with `data.requiredCapabilities`                                        | `confirm_purchase` from a client that declares no form `elicitation`                                                                                                                                                                                                         |
| `-32022` | 400  | Unsupported protocol version, with `data.supported` and `data.requested`                                                                     | Version `1900-01-01`                                                                                                                                                                                                                                                         |
| `-32603` | 500  | Internal error: the handler failed in a way no rule foresaw. The reply keeps the request's id and shows no detail; the cause goes to the log | No request is known to reach it; a test forces it                                                                                                                                                                                                                            |
| `-32601` | 404  | Method not found                                                                                                                             | `resources/read`, or any other method not implemented; `initialize` sent with this revision's headers (with `data.supported`)                                                                                                                                                |

Outside JSON-RPC, an `Origin` header that is not on the allow-list gets `403`, a path other than `/mcp` gets `404`, a method other than `POST` on `/mcp` gets `405` with `Allow: POST`, and a body over 1 MB gets `413`. All four have an empty body and leave one line in the log. Each of these replies can be sent before the request's body has arrived. The rest of the body is then read and discarded, so that a client that reads only after sending still gets its reply; a client still sending a second later is disconnected. A client that sends `Expect: 100-continue` is told to continue only after these checks have passed. The `Origin` check is the specification's defense against DNS rebinding, where a web page on another site reaches a server on `127.0.0.1`. A request without the header passes, because a client that is not a browser sends none. The allow-list holds exact origins and comes from `ALLOWED_ORIGINS`; by default it holds only the server's own origin. The header is compared as the text the client sent, so a spelling no browser produces, such as a trailing slash or an uppercase scheme, is refused.

The handler never throws. Three limits keep input within what the code can process: a body over 1 MB gets `413` (one that declares its size is refused before any of it is read; one sent in chunks is read up to the limit, and the rest is discarded), `params` nested more than 64 levels deep are refused before any rule walks them, and values repeated in a message or in the log are cut to 100 characters. Behind those, a `try`/`catch` around every rule turns anything unforeseen into `500` with `-32603`, and every failure is logged with its cause. A test places hostile values in each position of a request, and in the retry of each call that was handed a `requestState`.

The specification does not give an HTTP status for `-32700` and `-32600`, so 400 is this project's choice. The order of the checks, the nesting and size limits, and reading "invalid characters" in a header as "not canonical Base64" are also implementation choices rather than spec text.

## Known gaps

Both servers are for learning on a local machine. These things are missing, some on purpose and some because they are not built yet:

- **No authentication or authorization.** Anyone who can reach the port can call every tool.
- **No TLS.** Both servers speak plain `http`, which is acceptable only on the loopback address, where traffic never leaves the machine. A deployed server is reached over `https`, usually with TLS ended by a reverse proxy or a load balancer in front of it.
- **No CORS.** A browser page cannot call either server, even from an allowed origin: a preflight `OPTIONS` gets `405`, and replies carry no `Access-Control-Allow-Origin`. The `Origin` check decides who is refused, not who is served.
- **A slow upload that was already answered is cut off.** When a reply is sent before the body has arrived (a refusal, or a `413`), the server reads the rest for one second and then closes the connection. A client on a slow connection that is still sending a large body then sees a reset and not its reply.
- **What Node's HTTP parser rejects is not logged.** Malformed HTTP, oversized headers and an unknown `Expect` value are answered by Node before either server's code runs.
- **Paths must match exactly.** `/mcp/` and `/mcp?x=1` get `404` from both servers.
- **No web framework.** Both servers use plain `node:http` so that every status code and header is visible. A real service would use a framework such as Express, Fastify or Hono for routing, body parsing and middleware.
- **The hand-written server does not check `Accept` or `Content-Type`**, and it does not implement the `Mcp-Param-*` headers that a tool's schema can ask for.
- **A request state can be used more than once** until it expires after five minutes, and its signing key is random per process. A restart invalidates open questions, and several instances would need one shared key. The state proves which call a question belonged to. It does not prove that a person answered, and it is not bound to a caller, because there are no callers to tell apart without authentication.
- **Sessions never expire.** A session on `/mcp-session` lives until the client sends `DELETE` or the server restarts. A real server would drop idle sessions, and would need sticky routing or a shared store to run more than one process.
- **`start_job` compares only the idempotency key.** A second call with the same key and different arguments returns the first job. A production API would refuse it. The keys are also shared by all callers: with authentication they would be kept per caller.
- **The cost cap is checked only before a job starts**, and jobs live in memory, where nothing ever removes them.
- **The SDK server advertises `tools.listChanged`**, which the SDK sets by default, although neither route can deliver that notification: the tool list never changes.

## Documentation

- [docs/how-it-works.md](docs/how-it-works.md): what each part demonstrates, with real responses, and exercises.
- [docs/spec-2026-07-28.md](docs/spec-2026-07-28.md): the wire shapes this project implements, with sources.
- [AGENTS.md](AGENTS.md): guidance for coding agents and contributors.

## License

MIT. See [LICENSE](LICENSE).

## Notes

- TypeScript is pinned to 6.0.x because `typescript-eslint` supports TypeScript below 6.1 only. Raise it when typescript-eslint supports a newer release.
- Formatting: single quotes. `.prettierrc.json` configures Prettier and the ESLint `quotes` rule enforces it.