The ecosystem · packages/mcp
Your app's tools, for AI agents
MCP, the Model Context Protocol, is how AI agents (and the apps they run in: Claude, an editor, the MCP Inspector) learn what an app can do, and do it. This package makes a Roc Solid app an MCP server. An endpoint becomes a tool in one line, with the JSON Schema the platform writes for /openapi.json from the same Roc types.
Use it to let agents search, read and add to your app's data. An MCP server offers three kinds of things:
- Tools: actions the agent calls with arguments, such as "create a note".
- Resources: data the agent reads by URI, such as
notes://index. A template is a family of resources whose URIs follow a pattern, such asnotes://note/{id}. - Prompts: ready-made messages a person picks from a menu in their agent (a slash command, say), filled in with their arguments.
The protocol is plain Roc on no platform, so you can test it with expects. A small module on the server platform, McpHttp, serves it over HTTP and makes tools from your endpoints. The notes example is a full app that agents use this way.
A first server#
A server is a record: a name, a version, and what it offers. This one converts temperatures. Its tool's handler is a Roc function from a record to a record: the package reads the agent's arguments into its argument type and sends its answer back as JSON. When the handler returns Err, the tool refuses, and the model reads why.
import mcp.Mcp
import mcp.Prompt
import mcp.Resource
import mcp.Template
…
import tools.Tool
server : Mcp.Server({})
server = {
name: "temperatures",
version: "1.0.0",
title: "Temperatures",
instructions: "Converts temperatures, and knows when a few things boil.",
tools: [
Tool.typed("convert", "Celsius to Fahrenheit", celsius_schema, convert!).answers(fahrenheit_schema).read_only(),
],
resources: [Resource.text("temperatures://scales", "scales", "text/markdown", scales!)],
templates: [Template.new("temperatures://boiling/{substance}", "boiling", boiling!).described("Where a substance boils, at sea level")],
prompts: [Prompt.new("explain", "Explains a temperature scale", [Prompt.argument("scale", "Celsius, Fahrenheit or Kelvin"), Prompt.optional("audience", "Who it is for")], explain!)],
}
convert! : { celsius : Dec }, {} => Try({ fahrenheit : Dec }, Str)
convert! = |{ celsius }, _|
if celsius < -273.15 {
Err("${celsius.to_str()} °C is below absolute zero")
} else {
Ok({ fahrenheit: celsius * 9.0 / 5.0 + 32.0 })
}The JSON Schemas here are written by hand, since this server has no HTTP side. Over HTTP, McpHttp.tool writes them from the handler's types (below). The other fields:
resources: each read by its URI.Resource.texttakes a URI, a name, a MIME type and a function that makes the text.templates: each matches a family of URIs. Intemperatures://boiling/{substance},{substance}takes whatever the URI has in that place, and the read function gets it by name.prompts: each makes messages from the arguments a person gives.
What it answers#
This site is static, so nothing here serves MCP. While the site was built, this page sent the server above these requests, as a client would; the answers are as they came back (indented for reading).
An earlier client starts with initialize
POST /mcp
content-type: application/json
accept: application/json, text/event-stream
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": {
"name": "an-agent",
"version": "1.0.0"
}
}
}200
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2025-11-25",
"capabilities": {
"tools": {},
"resources": {},
"prompts": {}
},
"serverInfo": {
"name": "temperatures",
"title": "Temperatures",
"version": "1.0.0"
},
"instructions": "Converts temperatures, and knows when a few things boil."
}
}A current client asks what the server offers
POST /mcp
content-type: application/json
accept: application/json, text/event-stream
mcp-protocol-version: 2026-07-28
mcp-method: server/discover
{
"jsonrpc": "2.0",
"id": 2,
"method": "server/discover",
"params": {
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {}
}
}
}200
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"resultType": "complete",
"supportedVersions": [
"2026-07-28",
"2025-11-25",
"2025-06-18",
"2025-03-26"
],
"capabilities": {
"tools": {},
"resources": {},
"prompts": {}
},
"instructions": "Converts temperatures, and knows when a few things boil.",
"ttlMs": 300000,
"cacheScope": "public",
"_meta": {
"io.modelcontextprotocol/serverInfo": {
"name": "temperatures",
"title": "Temperatures",
"version": "1.0.0"
}
}
}
}The tools, with their schemas
POST /mcp
content-type: application/json
accept: application/json, text/event-stream
mcp-protocol-version: 2026-07-28
mcp-method: tools/list
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list",
"params": {
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {}
}
}
}200
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"resultType": "complete",
"tools": [
{
"name": "convert",
"description": "Celsius to Fahrenheit",
"inputSchema": {
"type": "object",
"properties": {
"celsius": {
"type": "number"
}
},
"required": [
"celsius"
]
},
"outputSchema": {
"type": "object",
"properties": {
"fahrenheit": {
"type": "number"
}
},
"required": [
"fahrenheit"
]
},
"annotations": {
"readOnlyHint": true
}
}
],
"ttlMs": 300000,
"cacheScope": "public"
}
}A tool, called
POST /mcp
content-type: application/json
accept: application/json, text/event-stream
mcp-protocol-version: 2026-07-28
mcp-method: tools/call
mcp-name: convert
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "convert",
"arguments": {
"celsius": 37
},
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {}
}
}
}200
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"resultType": "complete",
"content": [
{
"type": "text",
"text": "{\"fahrenheit\":98.6}"
}
],
"structuredContent": {
"fahrenheit": 98.6
}
}
}A refusal goes back to the model, to act on
POST /mcp
content-type: application/json
accept: application/json, text/event-stream
mcp-protocol-version: 2026-07-28
mcp-method: tools/call
mcp-name: convert
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "convert",
"arguments": {
"celsius": -300
},
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {}
}
}
}200
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"resultType": "complete",
"content": [
{
"type": "text",
"text": "-300.0 °C is below absolute zero"
}
],
"isError": true
}
}So do arguments that don't fit the type
POST /mcp
content-type: application/json
accept: application/json, text/event-stream
mcp-protocol-version: 2026-07-28
mcp-method: tools/call
mcp-name: convert
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "convert",
"arguments": {
"celsius": "warm"
},
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {}
}
}
}200
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"resultType": "complete",
"content": [
{
"type": "text",
"text": "Invalid arguments for convert: Invalid JSON"
}
],
"isError": true
}
}A resource a template matches
POST /mcp
content-type: application/json
accept: application/json, text/event-stream
mcp-protocol-version: 2026-07-28
mcp-method: resources/read
mcp-name: temperatures://boiling/ethanol
{
"jsonrpc": "2.0",
"id": 2,
"method": "resources/read",
"params": {
"uri": "temperatures://boiling/ethanol",
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {}
}
}
}200
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"resultType": "complete",
"contents": [
{
"uri": "temperatures://boiling/ethanol",
"mimeType": "text/plain",
"text": "78.4 °C"
}
],
"ttlMs": 0,
"cacheScope": "private"
}
}One no template has
POST /mcp
content-type: application/json
accept: application/json, text/event-stream
mcp-protocol-version: 2026-07-28
mcp-method: resources/read
mcp-name: temperatures://boiling/lava
{
"jsonrpc": "2.0",
"id": 2,
"method": "resources/read",
"params": {
"uri": "temperatures://boiling/lava",
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {}
}
}
}200
{
"jsonrpc": "2.0",
"id": 2,
"error": {
"code": -32602,
"message": "Resource not found",
"data": {
"uri": "temperatures://boiling/lava"
}
}
}A prompt, with its argument
POST /mcp
content-type: application/json
accept: application/json, text/event-stream
mcp-protocol-version: 2026-07-28
mcp-method: prompts/get
mcp-name: explain
{
"jsonrpc": "2.0",
"id": 2,
"method": "prompts/get",
"params": {
"name": "explain",
"arguments": {
"scale": "Kelvin"
},
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {}
}
}
}200
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"resultType": "complete",
"description": "The Kelvin scale",
"messages": [
{
"role": "user",
"content": {
"type": "text",
"text": "Explain the Kelvin scale to a curious ten-year-old, in three sentences."
}
}
]
}
}Nothing is pushed: GET is refused
GET /mcp
accept: text/event-stream405
MCP is asked by POST here, not GETServing it over HTTP#
McpHttp serves the MCP server from a route, such as routes/mcp/+server.roc, behind its directory's middleware, which decides who may ask. It makes tools from an endpoint, a function of the app's own, or a handler written for the tool. An endpoint's tool sends it as a handler does (.send!(arg)), through its own route and middleware with the MCP request's token, so an agent can do what the same credentials can do over HTTP, and no more. Each such call is a second request through the app's middleware, with its own log line. This sketch serves one and makes one tool of each kind:
# routes/mcp/+server.roc: the MCP server at /mcp
respond! = |{ request, context, .. }| McpHttp.respond!(Agents.server, request, context)
# routes/mcp/+middleware.roc: who may ask
middleware = Middlewares.signed_in
# Agents.roc: two endpoints (from Generated/Api), a function and a handler of the app's own, a tool
# each; a tool's arguments fill an endpoint's path too (read_note's id), and an endpoint is sent
# through its own route and middleware, with the MCP request's token
server : Mcp.Server(McpHttp.Caller(Context))
server = {
name: "notes",
version: "1.0.0",
tools: [
McpHttp.endpoint(Api.post_api_convert, { name: "convert", description: "Celsius to Fahrenheit" }, McpHttp.openapi({})),
McpHttp.endpoint(Api.get_api_notes_id, { name: "read_note", description: "A note, by its id" }, McpHttp.openapi({})),
McpHttp.function(Echo.echo!, { name: "echo", description: "Says a message back" }, McpHttp.openapi({})),
McpHttp.tool({ name: "greet", description: "Greets someone" }, greet!, McpHttp.openapi({})),
],
}| McpHttp. | What it is |
|---|---|
respond!(server, request, context) | The answer to one request to the MCP route, for its route file's respond!. |
endpoint(Api.x, about, McpHttp.openapi({})) | An endpoint as a tool. Api.x, in Generated/Api, is the function from the endpoint's path params to the endpoint. The tool's arguments are one object holding the path's params and the body ({ "id": "7", "tags": ["work"] }), sent with the MCP request's headers. The endpoint's answer is the tool's, and a refusal goes back to the model. |
function(Module.name!, about, McpHttp.openapi({})) | A function of the app's own as a tool, run inside the MCP request, behind the MCP route's middleware. |
tool(about, handler!, McpHttp.openapi({})) | A handler written for the tool, arg, Caller(c) => Try(result, Str), its schemas written from its types. |
Caller(c) | What a handler gets: { request, context, progress! }. context is what the middleware passed on, such as who is asking. |
About | A tool's { name, description }, and optionally title and tags. |
McpHttp.openapi({}) is always the same argument: the platform's schema writers, passed as a value. A compiler limit means one generic function can't both read a type with Json and describe it with OpenApi, so the writers are passed in where the types are known.
A tool marked .reporting() may call progress! to say how far it has got. A client that asks for progress gets the answer as server-sent events: each step as it is taken, then the answer.
McpHttp is on the server platform: name the package mcp in the app's header and write import mcp.McpHttp. The browser's half of the app sees only the protocol's modules, which run anywhere.
Who may ask#
The middleware in front of the MCP route decides, as for any route: it can check a session cookie, an API key or an OAuth access token. The notes example checks a personal access token, which its users make on a settings page.
MCP's own way is OAuth: a client without a good token gets a 401 that says where to learn how to get one. The Bearer module builds those answers:
Bearer.token(headers): the token a request carries (Authorization: Bearer …).Bearer.challenge: the 401, with aWWW-Authenticateheader.Bearer.insufficient: the 403 for a good token that lacks a scope.Bearer.metadata: the document a server serves at/.well-known/oauth-protected-resource.
Not yet: issuing tokens. The platform has no authorization server of its own; that is a proposal.
The package also refuses a request a browser sends from another site's page (by its Origin header), so a web page can't reach an MCP server on the reader's own computer.
Testing a server#
Mcp.receive is pure, so an app's expects can send its server requests and read the answers with no network. Mcp.problems(server) lists what MCP won't accept:
- a tool name that isn't 1 to 128 letters, digits,
_,-and.; - a name or a URI given twice;
- a schema that isn't JSON;
- an endpoint's tool whose path params and body have a field with the same name.
This page's server is tested this way:
## What MCP takes: tool names, each once, schemas that are JSON.
expect Mcp.problems(McpTemperatures.server) == []What it speaks#
MCP over Streamable HTTP: one endpoint, where each POST carries one JSON-RPC message and is answered with JSON, or with a stream of events for a tool that reports progress. The endpoint speaks both eras of the protocol:
- 2026-07-28, the current version, has no handshake. Each request states its version and the client's capabilities in its
_meta, and its headers repeat them (MCP-Protocol-Version,Mcp-Method,Mcp-Name).server/discoversays what the server offers, and each list says how long a client may keep it. - 2025-11-25, 2025-06-18 and 2025-03-26 start with
initialize, thennotifications/initialized. The server keeps no session between requests, as these versions allow, so it sends noMcp-Session-Id.
| A request | Is answered |
|---|---|
| a notification (no id) | 202, with an empty body |
a body that isn't JSON (by its Content-Type) | 415 |
| not one JSON-RPC message (invalid JSON, a batch, no method) | 400, a JSON-RPC error |
a version the server doesn't speak, a header that doesn't match the body, or _meta missing what it needs | 400, a JSON-RPC error |
| a method that doesn't exist (current MCP) | 404, a JSON-RPC error |
| an unknown tool, a bad cursor, a resource that doesn't exist | 200, a JSON-RPC error |
| arguments that don't fit a tool, or a tool's refusal | 200, a result the model reads (isError) |
from a page of another site (its Origin) | 403 |
GET, DELETE | 405: the server pushes nothing, and has no session to end |
The modules#
The protocol reads a request, checks it, and either answers it or says what to run. It has no effects: tools, resources and prompts are functions the app gives it. roc test packages/mcp/main.roc runs its expects, including the spec's example messages; the README lists every function.
What a tool is (Tool), what it answers (Content) and JsonValue come from the tools package: a tool made there is served here as it is, and the AI package's models use it too. Name tools in your app's header beside mcp, and import tools.Tool.
| Module | What it does |
|---|---|
Mcp | Mcp.Server(ctx), what a server offers. handle!(server, incoming, ctx) answers a request. receive does the same purely: it returns an answer, or what to run. problems(server) is for a test. |
Resource | Resource.text(uri, name, mime, read!) and Resource.new(uri, name, read!): what reading a URI gives. Resource.contents is text or bytes. |
Template | Template.new(pattern, name, read!): a family of resources. read! gets the values the URI gave the pattern's names. |
Prompt | Prompt.new(name, description, arguments, get!): messages made from string arguments (Prompt.argument, Prompt.optional, Prompt.user, Prompt.assistant). |
Bearer | The pieces of OAuth's answers, for the app's middleware (above). |
Rpc | JSON-RPC 2.0: read one message; write a result, an error or a notification. |
Mcp.Server(ctx) needs only name and version. The rest have defaults:
title: the server's name for people;instructions: for the model, how the tools fit together;tools,resources,templates,prompts: none by default;page_size: how many items go in one page of a list (100);ttl_ms: how long a client may keep a list, in current MCP (5 minutes);origins: other sites' pages whose requests are answered. The server's own site's pages, and requests from no page at all (an agent,curl), always are.
The package has no components: its readers are agents, not people.
What is tested#
- The protocol, in both eras, by 93
expects (what a tool is has its own, in the tools package). - Over HTTP, in an app built with
rocx buildon the server platform, with the official clients: the MCP Inspector's command line (2.16.0, speaking 2025-11-25) and the TypeScript SDK's client (2.4.0) on 2026-07-28. Covered: tools from an endpoint (with its path's params among the arguments), a function and a handler; refusals; resources; a template; a prompt; and a tool's progress, streamed as events. - examples/notes, whose server is its route
routes/mcp/and whose tests call its tools over JSON-RPC.
Waiting on a proposal (in packages/mcp/PROPOSALS.md):
- a tag union in a tool's arguments, which the schema calls "any value" until the generated
Apilists the tags it found; - an endpoint's doc comment as its tool's description (today you repeat it);
- an OAuth authorization server of the platform's own.
Limits#
- Not yet: list-change notifications, resource subscriptions, completions, logging to the client, and requests from the server to the client (sampling, asking the user).
- No sessions: nothing is kept between requests.
- Every field of a typed tool's arguments is required, as the platform's schemas say. For an optional argument, use a
Tool.newtool, which takes any JSON. - A batch (a JSON array of messages) is refused: MCP has had no batches since 2025-06-18.
This page's server, and the requests it was sent: site/Demos/McpTemperatures.rocx
import mcp.Mcp
import mcp.Prompt
import mcp.Resource
import mcp.Template
import tools.JsonValue
import tools.Tool
## An MCP server, for the ecosystem's MCP page: a tool that converts temperatures, a resource about
## the scales, a family of resources (a substance's boiling point), and a prompt. The site is static
## files, so nothing serves it over HTTP: the page sends it requests while the site is built
## (`exchanges!`), and shows what it answered.
McpTemperatures := [].{
## What the server offers. Its context (`{}`) is what each handler is given when it runs: over HTTP,
## `McpHttp.Caller`, the request and what the middleware handed on.
server : Mcp.Server({})
server = {
name: "temperatures",
version: "1.0.0",
title: "Temperatures",
instructions: "Converts temperatures, and knows when a few things boil.",
tools: [
Tool.typed("convert", "Celsius to Fahrenheit", celsius_schema, convert!).answers(fahrenheit_schema).read_only(),
],
resources: [Resource.text("temperatures://scales", "scales", "text/markdown", scales!)],
templates: [Template.new("temperatures://boiling/{substance}", "boiling", boiling!).described("Where a substance boils, at sea level")],
prompts: [Prompt.new("explain", "Explains a temperature scale", [Prompt.argument("scale", "Celsius, Fahrenheit or Kelvin"), Prompt.optional("audience", "Who it is for")], explain!)],
}
## A request (its method, headers and body, as an MCP client sends them), and the server's answer,
## each as the page shows it: what it is, the request, the answer.
exchanges! : {} => List({ title : Str, request : Str, answer : Str })
exchanges! = |{}| {
var $shown = []
for ask in asked {
answered = Mcp.handle!(server, { method: ask.method, headers: ask.headers, body: ask.body }, {})
request = Str.join_with(["${ask.method} /mcp"].concat(ask.headers.map(|header| "${header.name}: ${header.value}")), "\n")
$shown = $shown.append({
title: ask.title,
request: if (ask.body.is_empty()) request else "${request}\n\n${pretty(ask.body)}",
answer: if (answered.body.is_empty()) answered.status.to_str() else "${answered.status.to_str()}\n\n${pretty(answered.body)}",
})
}
$shown
}
}
## Celsius to Fahrenheit; below absolute zero is refused, as the model's to fix.
convert! : { celsius : Dec }, {} => Try({ fahrenheit : Dec }, Str)
convert! = |{ celsius }, _|
if celsius < -273.15 {
Err("${celsius.to_str()} °C is below absolute zero")
} else {
Ok({ fahrenheit: celsius * 9.0 / 5.0 + 32.0 })
}
## The JSON Schemas of what `convert!` reads and answers. Over HTTP, `McpHttp.tool` writes them from
## its types, as the platform writes /openapi.json's.
celsius_schema : Str
celsius_schema = "{\"type\":\"object\",\"properties\":{\"celsius\":{\"type\":\"number\"}},\"required\":[\"celsius\"]}"
fahrenheit_schema : Str
fahrenheit_schema = "{\"type\":\"object\",\"properties\":{\"fahrenheit\":{\"type\":\"number\"}},\"required\":[\"fahrenheit\"]}"
scales! : {} => Try(Str, Str)
scales! = |_| Ok("# Scales\n\nWater freezes at 0 °C, 32 °F and 273.15 K.")
boiling! : Dict(Str, Str), Str, {} => Try(List(Resource.Contents), [NotFound, Failed(Str)])
boiling! = |values, uri, _| {
point : Try(Str, [NotFound, Failed(Str)])
point =
match values.get("substance") ?? "" {
"water" => Ok("100 °C")
"ethanol" => Ok("78.4 °C")
"nitrogen" => Ok("-195.8 °C")
_ => Err(NotFound)
}
point.map_ok(|said| [Resource.contents(uri, "text/plain", Text(said))])
}
explain! : Dict(Str, Str), {} => Try(Prompt.Got, Str)
explain! = |args, _| {
scale = args.get("scale") ?? ""
audience = args.get("audience") ?? "a curious ten-year-old"
Ok({ description: "The ${scale} scale", messages: [Prompt.user("Explain the ${scale} scale to ${audience}, in three sentences.")] })
}
## What the page asks: an earlier client's handshake, then current MCP's requests (each with its
## version and capabilities in `_meta`, and headers that repeat what it asks for).
asked : List({ title : Str, method : Str, headers : List({ name : Str, value : Str }), body : Str })
asked = [
{ title: "An earlier client starts with initialize", method: "POST", headers: earlier, body: "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-11-25\",\"capabilities\":{},\"clientInfo\":{\"name\":\"an-agent\",\"version\":\"1.0.0\"}}}" },
current("A current client asks what the server offers", "server/discover", "", ""),
current("The tools, with their schemas", "tools/list", "", ""),
current("A tool, called", "tools/call", "convert", "\"name\":\"convert\",\"arguments\":{\"celsius\":37}"),
current("A refusal goes back to the model, to act on", "tools/call", "convert", "\"name\":\"convert\",\"arguments\":{\"celsius\":-300}"),
current("So do arguments that don't fit the type", "tools/call", "convert", "\"name\":\"convert\",\"arguments\":{\"celsius\":\"warm\"}"),
current("A resource a template matches", "resources/read", "temperatures://boiling/ethanol", "\"uri\":\"temperatures://boiling/ethanol\""),
current("One no template has", "resources/read", "temperatures://boiling/lava", "\"uri\":\"temperatures://boiling/lava\""),
current("A prompt, with its argument", "prompts/get", "explain", "\"name\":\"explain\",\"arguments\":{\"scale\":\"Kelvin\"}"),
{ title: "Nothing is pushed: GET is refused", method: "GET", headers: [{ name: "accept", value: "text/event-stream" }], body: "" },
]
earlier : List({ name : Str, value : Str })
earlier = [{ name: "content-type", value: "application/json" }, { name: "accept", value: "application/json, text/event-stream" }]
## A request of current MCP: its method, the name `Mcp-Name` repeats (`""` for none), and its params
## (`_meta` added).
current : Str, Str, Str, Str -> { title : Str, method : Str, headers : List({ name : Str, value : Str }), body : Str }
current = |title, method, name, params| {
meta = "\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\",\"io.modelcontextprotocol/clientCapabilities\":{}}"
given = if (params.is_empty()) meta else "${params},${meta}"
headers = earlier.concat([{ name: "mcp-protocol-version", value: "2026-07-28" }, { name: "mcp-method", value: method }]).concat(if (name.is_empty()) [] else [{ name: "mcp-name", value: name }])
{ title: title, method: "POST", headers: headers, body: "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"${method}\",\"params\":{${given}}}" }
}
## JSON, indented two spaces a level, for reading; text that isn't JSON, as it is.
pretty : Str -> Str
pretty = |text|
match JsonValue.parse(text) {
Ok(value) => indented(value, "")
Err(_) => text
}
indented : JsonValue, Str -> Str
indented = |value, at| {
inner = "${at} "
match value {
Array(items) if !items.is_empty() => "[\n${Str.join_with(items.map(|item| "${inner}${indented(item, inner)}"), ",\n")}\n${at}]"
Object(fields) if !fields.is_empty() => "{\n${Str.join_with(fields.map(|(key, item)| "${inner}${Json.to_str(key)}: ${indented(item, inner)}"), ",\n")}\n${at}}"
_ => JsonValue.to_str(value)
}
}
## What MCP takes: tool names, each once, schemas that are JSON.
expect Mcp.problems(McpTemperatures.server) == []
## The tools a client lists: the one, read-only.
expect {
listed = Mcp.receive(McpTemperatures.server, { method: "POST", headers: earlier.append({ name: "mcp-protocol-version", value: "2025-11-25" }), body: "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/list\"}" })
match listed {
Reply(answer) => answer.status == 200 and answer.body.contains("\"name\":\"convert\"") and answer.body.contains("\"readOnlyHint\":true")
Run(_) => Bool.False
}
}
expect pretty("{\"a\":[1,{}],\"b\":\"x\"}") == "{\n \"a\": [\n 1,\n {}\n ],\n \"b\": \"x\"\n}"The HTTP side: packages/mcp/McpHttp.roc
import pf.Endpoint
import pf.Events
import pf.Log
import pf.OpenApi
import pf.Server
import tools.JsonValue
import Mcp
import tools.Tool
## The HTTP side of an app's MCP server, on the server platform: the route that serves it
## (`respond!`), and tools made from what the app has already, in a line each: an endpoint, its
## path's params too (`endpoint`), a function of the app's (`function`), a handler of its own
## (`tool`). Their arguments' and answers' JSON Schemas are the platform's, written from their
## types as /openapi.json's are (`OpenApi`).
##
## # routes/mcp/+server.roc
## respond! = |{ request, context, .. }| McpHttp.respond!(Agents.server, request, context)
##
## The `+middleware.roc` of its folder decides who may ask, as for any route (`Bearer` has the
## pieces of OAuth's answers).
McpHttp := [].{
## What a tool is given: the request the MCP route is answering, what its middleware handed on
## (`context`: who is asking), and `progress!`, how far the tool has got (done, of a total, 0
## for unknown, and a message), which goes to the client before the answer if the tool is
## `Tool.reporting` and the client asked to hear it; and does nothing if not.
Caller(c) : { request : Server.Request, context : c, progress! : U64, U64, Str => {} }
## A tool's name and what it does, for the model; its title, for people; and `tags`, the names
## of the tags its types' unions have, for their schemas (rocx finds them in the app's code for
## /openapi.json; PROPOSALS.md, "`Api.tags`"). A union none of whose tags are given is any value.
About := { name : Str, description : Str, title : Str ?? "", tags : List(Str) ?? [] }
## The answer to a request to the MCP route: JSON, or, for a tool that reports its progress to a
## client that asked, a stream of events, its progress then its answer. A tool that failed inside
## is logged, as an error, with why; the client is only told that it failed.
respond! : Mcp.Server(Caller(c)), Server.Request, c => Server.Response
respond! = |server, request, context| {
incoming = { method: request.method, headers: request.headers, body: Server.text_of(request) }
match Mcp.receive(server, incoming) {
Reply(answer) => McpHttp.response(answer)
Run(running) => {
run! = running.run
if running.stream {
streamed = Events.stream(
|{ send!, .. }| {
progress! = |done, total, message| {
_ = send!(Mcp.progress(running, done, total, message))
{}
}
ran = run!({ request: request, context: context, progress!: progress! })
logged!(ran)
send!(ran.answer.body)
},
)
answered = Server.events(streamed)
{ ..answered, headers: answered.headers.append({ name: "x-accel-buffering", value: "no" }) }
} else {
ran = run!({ request: request, context: context, progress!: |_, _, _| {} })
logged!(ran)
McpHttp.response(ran.answer)
}
}
}
}
## An answer of the protocol's (`Mcp.Answer`, `Bearer.challenge`) as the server sends it.
response : { status : U16, headers : List({ name : Str, value : Str }), body : Str } -> Server.Response
response = |answer| Server.response(answer.status, answer.headers, answer.body)
## How the platform writes the JSON Schemas of what an endpoint's path holds (`params`), what it
## is sent and what it answers: `McpHttp.openapi`. (Given to `endpoint`, `function` and `tool`
## as a value, so it is instantiated where the types are known: a generic function can't read a
## type with `Json` and describe it with `OpenApi` both, as each needs its own `parser_for`.)
Schemas(c, params, arg, result) : { params : Endpoint(c, params, {}), List(Str) -> Str, body : Endpoint(c, arg, result), List(Str) -> Str, answer : Endpoint(c, arg, result), List(Str) -> Str }
## The platform's schemas, as /openapi.json has them.
openapi = |{}| { params: OpenApi.body, body: OpenApi.body, answer: OpenApi.answer }
## An endpoint as a tool, from the function of its params that names it
## (`McpHttp.endpoint(Api.put_api_notes_id_tags, { name: "tag_note", description: "Sets a
## note's tags" }, McpHttp.openapi({}))`): the tool's arguments are one object, read as the
## path's params (`{ id : Str }`) and as the endpoint's body (`{ tags : List(Str) }`), so the
## model sends `{ "id": "7", "tags": ["work"] }`; its answer is the tool's. An endpoint of no
## params is the same (`Api.post_api_search`). It is sent as a handler sends it
## (`.send!(arg)`): answered in-process, by its route, with the MCP request's headers (its
## `authorization`), so the endpoint's middleware decides, as it does for a script (D-103). A
## refusal (`NotFound`, `BadRequest`) goes back to the model as a tool error. A field of the body
## named as a param is an input schema `Mcp.problems` reports.
endpoint : (params -> Endpoint(e, arg, result)), About, Schemas(e, params, arg, result) -> Tool(Caller(c))
where [params.Json.Parseable([InvalidJson(Str)]), arg.Json.Parseable([InvalidJson(Str)]), arg.Json.Encodable(f), result.Json.Encodable(g), result.Json.Parseable([InvalidJson(Str)])]
endpoint = |api, about, schemas| {
describe_params = schemas.params
describe_body = schemas.body
describe_answer = schemas.answer
named = contract_of(api)
run! = |params, arg, _caller| Endpoint.send!(api(params), arg).map_err(Server.explain)
Tool.typed_with_params(about.name, about.description, describe_params(params_of(api), about.tags), describe_body(named, about.tags), run!).answers(answer_schema(describe_answer(named, about.tags))).titled(about.title)
}
## A function of the app's own as a tool (`McpHttp.function(Notes.add!, { name: "add_note",
## description: "Adds a note" }, McpHttp.openapi({}))`): its argument is the tool's (an object's
## `input` field, when it isn't a record), its answer the tool's. It runs in the MCP request,
## behind the MCP route's middleware.
function : (arg => result), About, Schemas(c, {}, arg, result) -> Tool(Caller(c))
where [arg.Json.Parseable([InvalidJson(Str)]), result.Json.Encodable(e)]
function = |called!, about, schemas| McpHttp.tool(about, |arg, _caller| Ok(called!(arg)), schemas)
## A handler of the app's own as a tool: its arguments are a Roc type, its answer another, each
## with the schema the platform writes for it.
##
## McpHttp.tool({ name: "convert", description: "Celsius to Fahrenheit" }, convert!, McpHttp.openapi({}))
tool : About, (arg, Caller(c) => Try(result, Str)), Schemas(c, {}, arg, result) -> Tool(Caller(c))
where [arg.Json.Parseable([InvalidJson(Str)]), result.Json.Encodable(e)]
tool = |about, handler!, schemas| {
witness = witness_of(handler!)
describe_body = schemas.body
describe_answer = schemas.answer
Tool.typed(about.name, about.description, describe_body(witness, about.tags), handler!).answers(answer_schema(describe_answer(witness, about.tags))).titled(about.title)
}
}
## An endpoint of a handler's types, for `OpenApi` to write their schemas: never run.
witness_of : (arg, McpHttp.Caller(c) => Try(result, Str)) -> Endpoint(c, arg, result)
witness_of = |_| Endpoint.local_json("POST", "/", |_, _, _| crash "McpHttp: a witness of a tool's types, never run")
## An endpoint of the types an endpoint's function names, for `OpenApi` to write their schemas:
## never run.
contract_of : (params -> Endpoint(c, arg, result)) -> Endpoint(c, arg, result)
contract_of = |_| Endpoint.local_json("POST", "/", |_, _, _| crash "McpHttp: a witness of an endpoint's types, never run")
## An endpoint sent an endpoint's params, for `OpenApi` to write their schema: never run.
params_of : (params -> Endpoint(c, arg, result)) -> Endpoint(c, params, {})
params_of = |_| Endpoint.local_json("POST", "/", |_, _, _| crash "McpHttp: a witness of an endpoint's params, never run")
## The schema in what `OpenApi.answer` writes (`"application/json":{"schema":…}`).
answer_schema : Str -> Str
answer_schema = |content| content.drop_prefix("\"application/json\":{\"schema\":").drop_suffix("}")
## A failure inside, in the server's log.
logged! : Mcp.Ran => {}
logged! = |ran|
match ran.failure {
Ok(why) => Log.error!("mcp", { failure: why })
Err(NoFailure) => {}
}
## A tool from an endpoint with params: one object of arguments, its schema the params' and the
## body's.
appended : { id : Str } -> Endpoint({}, { text : Str }, Str)
appended = |params| Endpoint.local("POST", "/notes/${params.id}/append", |_, {}, { text }| Ok("${params.id}: ${text}"))
expect
Tool.to_json(McpHttp.endpoint(appended, { name: "append", description: "Adds to a note" }, McpHttp.openapi({}))).get("inputSchema").map_ok(JsonValue.to_str)
== Ok("{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\"},\"text\":{\"type\":\"string\"}},\"required\":[\"id\",\"text\"]}")
## A body that names a field as the path does: `Mcp.problems` says so.
retitled : { id : Str } -> Endpoint({}, { id : Str, title : Str }, Str)
retitled = |params| Endpoint.local("PUT", "/notes/${params.id}/title", |_, {}, { title, .. }| Ok(title))
expect {
server : Mcp.Server(McpHttp.Caller({}))
server = { name: "notes", version: "1", tools: [McpHttp.endpoint(appended, { name: "append", description: "" }, McpHttp.openapi({})), McpHttp.endpoint(retitled, { name: "retitle", description: "" }, McpHttp.openapi({}))] }
Mcp.problems(server) == ["The tool retitle's arguments name id both as its endpoint's path params and in its body: one object can't fill both (rename the body's field)"]
}
# A tool made for the app's own model (its context `{}`) served here too, through `Tool.with_context`.
expect {
plain : Tool({})
plain = Tool.typed("shout", "Shouts the text given", "{\"type\":\"object\"}", |{ text }, {}| Ok(Str.with_ascii_uppercased(text)))
server : Mcp.Server(McpHttp.Caller({}))
server = { name: "notes", version: "1", tools: [plain].map(|tool| Tool.with_context(tool, |_caller| {})) }
Mcp.problems(server) == []
}