# MCP

The [Model Context Protocol](https://modelcontextprotocol.io) over
Streamable HTTP, both ways: the program as an **MCP server**, so that Claude,
an IDE's assistant or any other MCP client can call its typed fns as tools
and read its rows as resources; and the program as an **MCP client** of
other servers, whose tools the [ai](ai.md) extension's tool loop offers a
model beside the program's own. An [extension](../extensions/README.md):
ordinary Mote in `extensions/mcp/`. Back to the [map](README.md).

```mote
use "pkg:mcp/server.mote"

model Note
  title: string key
  body: string

// The weather in a city now.
fn weatherIn(city: string): string = `18°C in ${city}`

// A note, read whole.
shape NoteOut
  title: string
  body: string

// The note of a title.
fn noteOf(title: string): NoteOut
  let n = Note.get(title)?
  if n == none fail(`There is no note ${title}.`)?
  return {title, body: n?.body ?? ""}

// The tools: made from the fns, their schemas from their parameters' types, their
// descriptions from the comments above them.
fn mcpTools(who: string): McpTool[] = [
  mcpToolFor("weather", schema(weatherIn)),
  {...mcpToolFor("note", schema(noteOf)), outputSchema: schema(NoteOut)}
]

// A call of one: a `match` on its name into the program's own fns.
fn mcpCall(call: McpCall, tell: (done: number, total: number, words: string) => bool): McpResult
  if call.name == "weather" return mcpText(weatherIn(`${call.input.city}`))
  if call.name == "note" return mcpValue(noteOf(`${call.input.title}`)?)
  return fail(`no tool ${call.name}`)?

fn mcpResources(who: string): McpResource[] = Note.find({})?.map(n => ({uri: `note://${n.title}`, name: n.title, mimeType: "text/plain"}))

fn mcpRead(uri: string, who: string): McpRead[]
  let n = Note.get(uri.replace("note://", ""))?
  if n == none fail("no such note")?
  return [{uri, mimeType: "text/plain", text: n?.body ?? ""}]
```

```toml
[packages]
mcp = "../mote/extensions/mcp"
```

```sh
MCP_TOKEN=a-long-random-token bun dist/server/main.js
claude mcp add --transport http notes http://localhost:4870/mcp --header "Authorization: Bearer a-long-random-token"
```

**No other implementation has met it yet.** Both sides are written from the
protocol's specification (version `2025-06-18`, with `2025-03-26` and
`2025-11-25` taken), and checked against each other and against a plain
fetch client written from the same pages (`tests/all.sh real_svc_mcp`). The
steps to check it with real clients and servers are
[below](#checking-it-against-other-implementations).

## The server

`use "pkg:mcp/server.mote"` adds three routes at `/mcp`: `POST` for every
message, `GET` (405: the server sends nothing unasked) and `DELETE` (the
client ends its session). What the server offers is the program's to say,
each optional:

| | |
|---|---|
| `fn mcpTools(who: string): McpTool[]` | The tools, for whoever `who` is. `mcpToolFor(name, schema(aFn))` makes one from a fn: its `inputSchema` is the fn's parameters (a parameter of a fn's type, like `tell`, is left out), its `description` the comment above it. Add `outputSchema: schema(AShape)` for a typed result, `annotations: {readOnlyHint: true}` and the like for the client. |
| `fn mcpCall(call: McpCall, tell): McpResult` | A tool called: `call.name`, `call.input` (already checked against its `inputSchema`), `call.user` (what `mcpWho` said), `call.session`. `tell(done, total, words)` says how far it is; it reaches a client that asked to be told. |
| `fn mcpResources(who): McpResource[]` · `fn mcpRead(uri, who): McpRead[]` | What may be read, and one read: text, or bytes (`data`), with its `mimeType`. |
| `fn mcpPrompts(who): McpPrompt[]` · `fn mcpPrompt(name, args, who): McpMessage[]` | Prompts with their arguments (`required` ones are checked before `mcpPrompt` is asked). |
| `fn mcpWho(token: string): string` | Who a bearer token is: `""` for nobody, who is then answered 401. Unsaid, `MCP_TOKEN` (a [secret](back-end.md#secrets)) is the one token, compared in constant time, and its holder is `"token"`. A program with accounts checks its own (a token kept in a model, by its hash). |
| `fn mcpOriginOk(origin: string): bool` | A browser's `Origin` that may call (unsaid: those `MCP_ORIGINS` lists, with commas between). A request with no `Origin` (not from a browser) is not asked. |
| `fn mcpName(): string` · `fn mcpInstructions(): string` | What initialize says of the server. |

A tool's result is `mcpText(text)`, `mcpValue(v)` (a value in the shape of
its `outputSchema`, and its JSON as text beside it, as the protocol asks),
or `mcpFailed(why)`; or an `McpResult` of its own: `content` (texts,
pictures and sounds as bytes, resources, links) and `structured`.

**What a client sees, and why:**

- **A tool that fails** (`fail(…)` in `mcpCall`, an input that does not
  hold to the schema, a value that does not hold to `outputSchema`) is a
  result with `isError: true` and the words, not a protocol error: the model
  reads it and can try again. A tool that is not there, a method that is
  not, a prompt without its required argument and a resource that cannot be
  read are JSON-RPC errors (`-32602`, `-32601`, `-32602`, `-32002`).
- **The door**, before anything is read: an `Origin` that may not is 403
  (against a page elsewhere pointing a browser at a server on
  `localhost`: DNS rebinding); no token, or one `mcpWho` does not know, is
  401 with `WWW-Authenticate: Bearer`; a `MCP-Protocol-Version` header of
  a version it does not speak is 400; a body that is not JSON is 400 with
  `-32700`.
- **Sessions**: initialize (alone, with an id) makes one, named in the
  answer's `Mcp-Session-Id`, which every request after carries. One not
  sent is 400; one that is over (a day unused, or ended with `DELETE`) or
  another token's is 404, and the client begins again.
- **The answer** is JSON, unless the request is a tool's call with a
  `progressToken` from a client that reads events: then it is a stream of
  events (`text/event-stream`), each `tell` a `notifications/progress`, the
  result last ([events out of a route](back-end.md#events-out-of-a-route)).
- Notifications and responses from the client are taken with 202 and no
  body; `notifications/cancelled` is logged (the call goes on: a fn cannot
  be stopped from outside). A batch (a list of messages) is answered with
  a list.
- **Limits**: the route has `limit 1200 per minute by ip`; a tool that does
  something costly says its own `limit` on the `server fn` it calls, or
  counts per `call.user`.

## The client

`use "pkg:mcp/client.mote"`, from the back end:

```mote
server fn search(q: string): string requires signedIn
  let docs = mcpServer(env("DOCS_MCP"), secret("DOCS_MCP_TOKEN"))?
  let r = mcpCallTool(docs, "search", {query: q})?
  return mcpResultText(r)
```

| | |
|---|---|
| `mcpServer(url, token)` | The server, with a session: the one kept (`McpLink`, by a hash of the address and the token; the token itself is not kept), or one begun now. `token` `""` for a server that takes none. |
| `mcpConnect(url, token)` | A session begun now: initialize, then `notifications/initialized`. A server of a version this client does not speak is refused. |
| `mcpListTools(s)` · `mcpCallTool(s, name, input)` · `mcpCallToolEach(s, name, input, tell)` | The tools (every page, by `nextCursor`), a call, and a call told how far it is (`tell(done, total, words)` for each `notifications/progress`). |
| `mcpListResources(s)` · `mcpReadResource(s, uri)` · `mcpListPrompts(s)` · `mcpGetPrompt(s, name, args)` · `mcpPing(s)` | The rest. |
| `mcpResultText(r)` | What a result says, as one text. |
| `mcpClose(s)` | The session ended (`DELETE`) and forgotten. |

Each request is sent with `Accept: application/json, text/event-stream`;
an answer as events is read to its response, the notifications on the way
handed to `mcpRequestEach`'s `heard`. A 404 for the session begins another
and sends the request once more.

| Kind | |
|---|---|
| `"mcp"` | The server's JSON-RPC error: its words, and `data.code`. |
| `"auth"` (401, 403), `"invalid"` (another 4xx, or what is not MCP), `"server"` (5xx), `"offline"` | |

A tool that says it failed (`isError`) is **not** a failure of the call: it
is a result, `r.isError`, for the model to read.

## Another server's tools in the tool loop

`use "pkg:mcp/ai.mote"` (it takes `pkg:ai/ai.mote`: the program's
`mote.toml` says where both packages are):

```mote
fn docs(): McpServer = mcpServer(env("DOCS_MCP"), secret("DOCS_MCP_TOKEN"))?

// A call the model makes: the program's own tools first, then the servers'.
fn aiTool(name: string, input: json): string
  if name == "weather" return weatherIn(`${input.city}`)
  return mcpAiCall([docs()?], name, input)?

server fn ask(q: string): string requires signedIn
  let tools = [...mcpAiTools(docs()?)?, aiToolFor("weather", schema(weatherIn))]
  return aiRun({messages: [{role: "user", text: q}], tools}, 6, "", "")?.text
```

`mcpAiTools(s)` gives a server's tools as `AiTool`s (their names, their
descriptions, their `inputSchema`); `mcpAiCall(servers, name, input)`
sends a call to the first of `servers` that has the tool, and gives what it
said as text. A tool that says it failed is a failure there, which `aiRun`
sends back to the model as one. Two servers with a tool of one name: the
first given wins.

## Signing in by OAuth, for later

A server for people beyond its own program (a public MCP server that
Claude's users add by its address) is meant to be reached with OAuth 2.1,
and that side is not here yet. What it needs:

- **Protected resource metadata** (RFC 9728): a `GET
  /.well-known/oauth-protected-resource` route answering `{resource,
  authorization_servers: [...], bearer_methods_supported: ["header"]}`, and
  its address in the 401's `WWW-Authenticate` (`resource_metadata="…"`:
  `MCP_RESOURCE_METADATA` says it already, for when it exists).
- **An authorization server** (or another one named there): authorization
  server metadata (RFC 8414), dynamic client registration (RFC 7591) or
  client ID metadata documents, the authorization code flow with PKCE
  (S256), and tokens bound to this server's address as their audience
  (resource indicators, RFC 8707).
- **Checking a token**: `fn mcpWho` taking a JWT with
  [`crypto.jwt.verify`](data.md#signatures-with-a-key-pair) against the
  authorization server's keys, with `aud` this server's address; or asking
  the authorization server (token introspection, RFC 7662).
- Sign-in, consent and the grants kept are what an `oauth` extension (being
  written separately) is for; the client side's `token` is then
  `oauthToken(provider, user)`.

## Checking it against other implementations

1. **The MCP Inspector** (`npx @modelcontextprotocol/inspector`, on a
   machine that may download it): transport "Streamable HTTP", address
   `http://localhost:4870/mcp`, header `Authorization: Bearer <MCP_TOKEN>`.
   Connect: the server's name and instructions show; list the tools (each
   schema as `schema` wrote it), call one, call one that fails
   (`isError`), list and read the resources, get a prompt.
2. **Claude Code**: `claude mcp add --transport http notes
   http://localhost:4870/mcp --header "Authorization: Bearer <MCP_TOKEN>"`,
   then ask it something only a tool knows; `/mcp` shows the server
   connected and its tools.
3. **The client against another server**: `mcpServer("<a public MCP
   server's address>", "<its token or "">")?`, `mcpListTools`, one
   `mcpCallTool`; a server that answers tool calls with events (most of the
   official SDKs' servers do when asked with both types in `Accept`) is
   read the same.
4. **The tool loop**: `aiRun` with `mcpAiTools` of that server and a real
   model key ([ai.md](ai.md)): the model calls a tool of the server's, and
   its answer uses what the tool said.

Recorded in `tests/expect/real_svc_mcp.txt`: the door (no token, a wrong
one, another origin, not JSON), initialize and the session, every method,
a tool's failures, an input not of its schema, a typed value, progress as
events and the same as JSON, a batch, notifications and responses taken,
unknown versions, sessions, GET and DELETE; then the extension's client of
the same server (a session the server forgot begun again), the ai
extension's tool loop calling one of its tools, and the extension's own
`mote test`.

Source: `extensions/mcp/` (`mcp.mote`, `server.mote`, `client.mote`,
`ai.mote`, `tests.mote`).
