mcp speaks the Model Context Protocol (MCP), the protocol that lets an agent use the tools of a server. It is written in Agentica, with no C.

Status #

mcp-0.2.0 is the current release; mcp-0.1.0 was the first (packages#333), and 0.2.0 gives a tool the identity of its caller and caps the sessions of each identity (packages#342). It speaks the protocol versions 2025-11-25, 2025-06-18 and 2025-03-26, on stdio and Streamable HTTP:

  • the server: tools, resources, resource templates and prompts declared as plain functions, served over stdio or Streamable HTTP, alone or mounted in another app (pkg/mcp/server); a tool tells its progress, logs to the client and stops when the client cancels it; a live registry changes while it is served and tells its clients;
  • the client (pkg/mcp/mcp): it starts a server on stdio, or opens a session with one on Streamable HTTP, lists its tools (every page) and calls them; it passes on the progress and log lines of a call and the lists that changed, and cancels a call that times out or that its caller cancels;
  • the JSON-RPC 2.0 messages (pkg/mcp/jsonrpc) and the start of a session (pkg/mcp/lifecycle).

Not yet: the client lists and calls tools only (no resources or prompts), offers no sampling, roots or elicitation to its servers, and authorizes with fixed headers only (no OAuth). The server has no resources/subscribe or completion/complete, sends no requests to its clients, gives prompt messages as text only, and lists tools without outputSchema, title or annotations.

Install #

Needs Agentica 0.40.0 or later. Add it in a project with an agentica.toml:

agentica add mcp https://github.com/agentica-lang/packages --tag mcp-0.2.0 --subdir mcp

That writes this line of agentica.toml, and the entry of agentica.lock:

[dependencies]
mcp = { git = "https://github.com/agentica-lang/packages", tag = "mcp-0.2.0", subdir = "mcp" }

Getting started #

A client #

A client starts its server on the first use, and starts it again on the next use after it failed. Its notices (progress, log lines, lists that changed) come on a channel, read here by a task of its own:

import Mcp from "pkg/mcp/mcp"

def show(notices: Channel[Mcp.Notice]) -> Void
  notice = notices.recv(600_000)
  while notice.ok?
    case notice.unwrap!
      Mcp.Notice.Progressed(p) -> IO.warn("progress #{p.progress} #{p.message}")
      Mcp.Notice.Logged(entry) -> IO.warn("#{entry.level}: #{JSON.encode(entry.data)}")
      Mcp.Notice.Changed(list) -> IO.warn("the #{list} changed")
    end

    notice = notices.recv(600_000)
  end
end

def main() -> Void
  server = Mcp.Server(name: "files", command: "my-mcp-server", args: ["--root", "."])
  client = Mcp.start(server, Mcp.Options(timeout_ms: 10_000))
  notices = client.notices
  Task.spawn do show(notices) end
  none_yet: List[Mcp.Tool] = []
  for tool in Mcp.tools(client).unwrap_or(none_yet)
    puts(tool.name)
  end

  case Mcp.call(client, "read_file", JSON.object({"path": JSON.from("README.md")}))
    ok(output) if output.is_error -> puts("the tool failed: #{output.text}")
    ok(output) -> puts(output.text)
    error(e) -> puts("#{e.kind}: #{e.message}")
  end

  Mcp.stop(client)
end

A server on HTTP is a url, with the headers to send, such as a bearer token: Mcp.Server(name: "web", url: "https://example.com/mcp", headers: {"Authorization": "Bearer ..."}).

A server #

A tool is a function of a struct: JSON.schema of the struct is its input schema, and its codec reads the arguments. Arguments that do not read as the struct are a failed tool result that names the problem, so a model can correct them. Run the program as the command of a client, or serve it on HTTP with serve_http:

import Server from "pkg/mcp/server"

struct Echo
  text: String
end

def echo(args: Echo) -> Result[Server.ToolResult] = ok(Server.text(args.text))

def readme(_uri: String) -> Result[Server.Body] = ok(Server.Body.Text("Read me first."))

def main() -> Void
  registry = Server.registry("notes", "1.0.0")
    |> Server.tool("echo", "Gives the text back.", JSON.schema(Echo), Echo.codec, &echo)
    |> Server.resource(Server.Resource(uri: "note://readme", name: "readme", mime_type: "text/plain", read: &readme))

  case Server.serve_stdio(registry)
    ok(_) -> nil
    error(e) -> IO.warn(e.message)
  end
end

API of the server #

import Server from "pkg/mcp/server". The requests run at once: on stdio each in a task of its own (initialize and logging/setLevel in the order they come), on HTTP each in a task of its own. On stdio, stdout carries the messages and nothing else: a handler logs to the client with log, or to stderr (IO.warn). A handler gives its failures as error; one that halts (an unwrap! of an error) gets the answer -32603, and the server goes on.

Server.registry #

registry(name: String, version: String, instructions: String = "") -> Registry

A server with nothing in it yet: its name and version, as initialize gives them, and instructions for a model.

Server.Registry #

Registry(server: String, version: String, description: String = "", instructions: String = "", tools, resources, templates, prompts, page_size: Int = 100, live: Optional[Live] = none)

What a server offers. Build it with registry and the functions below; set the other fields with with: registry.with(page_size: 20, description: "Notes of the team."). page_size is how many items a page of a list holds, and description is for people, in serverInfo (2025-11-25).

Server.tool #

tool[T](registry: Registry, name: String, description: String, schema: JSON.Value, codec: Codec[T], handler: Fn[T, Result[ToolResult]]) -> Registry

Adds a tool; a call of a tool that is not there gets -32602, as does a prompt that is not there. A name has 1 to 128 letters, digits, _, - or .. schema and codec come from the same struct, JSON.schema(Args) and Args.codec: a generic function cannot make the schema from T. An error of the handler is a failed tool result with its message.

Server.context_tool and Server.Context #

context_tool[T](registry: Registry, name: String, description: String, schema: JSON.Value, codec: Codec[T], handler: Fn[Context, T, Result[ToolResult]]) -> Registry

Like tool, for a handler that also takes the Context of its request, to use with the functions below.

Server.progress #

progress(context: Context, done: Float, total: Float = 0.0, message: String = "") -> Void

Sends notifications/progress: done of total (left out when 0), with a message for people. It sends nothing when the client gave no progressToken in the _meta of its request.

Server.log and Server.LEVELS #

log(context: Context, level: String, data: JSON.Value, logger: String = "") -> Void

Sends notifications/message at level, one of LEVELS (debug, info, notice, warning, error, critical, alert, emergency), when the client asked for that level or a lower one with logging/setLevel (info until it asks). data is any JSON, and logger names its source. A level not in LEVELS is not sent.

Server.cancelled? #

cancelled?(context: Context) -> Bool

True once the client sent notifications/cancelled for the request, or its session ended. The handler should stop; whatever it returns, the request gets no answer.

Server.identity #

identity(context: Context) -> String

Who sent the request: over HTTP what the Auth of the endpoint gave ("" with no Auth, or with bearer), on stdio the identity that serve_stdio was given ("" unless given). A tool that acts for its caller (writes, scopes per key, limits per owner) reads it here.

import Server from "pkg/mcp/server"

struct Nothing
end

def whoami(context: Server.Context, _args: Nothing) -> Result[Server.ToolResult] = ok(Server.text(Server.identity(context)))

def main() -> Void
  registry = Server.registry("me", "1.0.0")
    |> Server.context_tool("whoami", "Who calls.", JSON.schema(Nothing), Nothing.codec, &whoami)

  puts(registry.tools[0].call.call(Server.detached("ana"), JSON.object({})).unwrap!.content[0])
end
Output
{"type":"text","text":"ana"}

Server.detached #

detached(identity: String = "") -> Context

A context with no client, for calling a handler in a test: it sends nothing, is never cancelled, and has identity.

import Server from "pkg/mcp/server"

struct Job
  steps: Int
end

def run(context: Server.Context, job: Job) -> Result[Server.ToolResult]
  for step in 1..job.steps
    return ok(Server.failure("cancelled")) if Server.cancelled?(context)

    Server.progress(context, step.to_f, job.steps.to_f, "step #{step}")
    Server.log(context, "debug", JSON.from("step #{step} done"))
  end

  ok(Server.text("ran #{job.steps} steps"))
end

def main() -> Void
  registry = Server.registry("jobs", "1.0.0")
    |> Server.context_tool("run", "Runs a job.", JSON.schema(Job), Job.codec, &run)

  puts(registry.tools[0].call.call(Server.detached(), JSON.parse("{\"steps\": 3}").unwrap!).unwrap!.content[0])
end
Output
{"type":"text","text":"ran 3 steps"}

Server.ToolResult #

ToolResult(content: List[JSON.Value], structured: Optional[JSON.Value] = none, is_error: Bool = false)

What a tool gives: its content parts, as MCP writes them (text, images and others), its structured content, and whether it failed. A failed result is for the model to read, not a protocol error.

Server.text, Server.json and Server.failure #

text(value: String) -> ToolResult is one text part; json(value: JSON.Value) -> ToolResult is structured content, with the same value as text for a client that reads only text; failure(message: String) -> ToolResult is a failed result.

import Server from "pkg/mcp/server"

def main() -> Void
  puts(Server.text("hi").content[0])
  sum = Server.json(JSON.object({"sum": JSON.from(5)}))
  puts("#{sum.content[0]} #{sum.structured.unwrap!}")
  failed = Server.failure("the disk is full")
  puts("#{failed.is_error} #{failed.content[0]}")
end
Output
{"type":"text","text":"hi"}
{"type":"text","text":"{\"sum\":5}"} {"sum":5}
true {"type":"text","text":"the disk is full"}

Server.resource #

resource(registry: Registry, resource: Resource) -> Registry

Adds a resource. An unknown URI is the error -32002, and an error of read -32603.

Server.Resource and Server.Body #

Resource(uri: String, name: String, description: String = "", mime_type: String = "", read: Fn[String, Result[Body]])

A resource: read gets the URI and gives a Body, Body.Text(String) or Body.Binary(Bytes); bytes are sent as base64.

Server.template and Server.Template #

template(registry: Registry, template: Template) -> Registry

Template(uri_template: String, name: String, description: String = "", mime_type: String = "", read: Fn[Map[String, String], Result[Body]])

Adds resources named by a URI template of level 1, such as note://days/{day}.txt. Each {name} (letters, digits and _, once each) stands for one percent-encoded part of the URI, and read gets the parts by name, decoded. A part is never empty, . or .., and has no /, \ or control character once decoded (a ? or # must come percent-encoded), but it is still text from the client: check it before it names a file or a key. Two names need text between them, and a part ends at the first text that follows it ({a}.txt does not match a.txt.txt). A template that breaks these rules is an mcp.registry error. resources/templates/list lists the templates. A read looks for a resource with the URI first, then for the first template that matches it.

import Server from "pkg/mcp/server"

def day(parts: Map[String, String]) -> Result[Server.Body] = ok(Server.Body.Text("notes of #{parts["day"]}"))

def main() -> Void
  registry = Server.registry("notes", "1.0.0")
    |> Server.template(Server.Template(uri_template: "note://days/{day}.txt", name: "day", read: &day))

  puts(registry.templates[0].read.call({"day": "monday"}).unwrap!)
end
Output
Body.Text("notes of monday")

Server.prompt #

prompt(registry: Registry, prompt: Prompt) -> Registry

Adds a prompt. A required argument that is missing is the error -32602, and an error of get -32603.

Server.Prompt, Server.Argument, Server.PromptMessage and Server.Role #

Prompt(name: String, description: String = "", arguments: List[Argument] = [], get: Fn[Map[String, String], Result[List[PromptMessage]]]) is a prompt: get takes the arguments a client gives and makes its messages. Argument(name: String, description: String = "", required: Bool = false) is one of its arguments. PromptMessage(role: Role, text: String) is one message, where Role is Role.User or Role.Assistant.

Server.live, Server.change, Server.close and Server.Live #

live(registry: Registry) -> Result[Registry]

change(registry: Registry, edit: Fn[Registry, Registry]) -> Result[Void]

close(registry: Registry) -> Void

live gives the registry held by a task of its own (its live field, a Live), so that it can change while it is served: each request is served with what it holds then, and waits while an edit runs. The holder stops with close, when the task that called live is cancelled or crashes, or with the program; a registry that is live already is given back as it is. change changes it with edit, one edit at a time; an edit that cannot be served (a bad name, a name twice), crashes or takes more than 5 s is an mcp.registry error and leaves it as it was, as does a registry that is not live. Requests wait while an edit runs, so an edit must not call change or serve a request. For each list whose items changed (tools, resources with the templates, prompts), the clients get notifications/tools/list_changed (or the one of the list): on stdio once the client sent notifications/initialized, and over HTTP on the GET stream of each session. The registry keeps the last 100 changes: a client that falls further behind gets a list_changed of each list instead of the changes it missed. The welcome of a live registry says listChanged for the three lists. close stops the task, as at the end of a test: then change fails, and the registry is served as live got it.

import Server from "pkg/mcp/server"

struct Echo
  text: String
end

def echo(args: Echo) -> Result[Server.ToolResult] = ok(Server.text(args.text))

def main() -> Void
  registry = Server.live(Server.registry("notes", "1.0.0")).unwrap!
  Server.change(registry, ->(r: Server.Registry) {
    Server.tool(r, "echo", "Gives the text back.", JSON.schema(Echo), Echo.codec, &echo)
  }).unwrap!
  puts(Server.change(registry, ->(r: Server.Registry) { r.with(tools: r.tools + r.tools) }).message)
  Server.close(registry)
end
Output
mcp: the tool "echo" is there twice

Server.serve_stdio #

serve_stdio(registry: Registry, identity: String = "") -> Result[Void]

Serves the registry on stdin and stdout until stdin ends. identity is who sends every request, as a tool reads it with identity: the one user that started the server, for example. At most MAX_RUNNING (64) requests run at once; past it, the next line waits. When stdin ends, the requests still running are cancelled, and it waits for them at most STOP_MS (5 s). A registry that cannot be served is an mcp.registry error before any message is read. Before initialize only ping is served; an unknown method is -32601, and a line that is no message -32700 or -32600.

Server.serve_http #

serve_http(registry: Registry, host: String, port: Int, options: HttpOptions = HttpOptions(), auth: Optional[Auth] = none) -> Result[HTTP.Server]

Serves the registry alone on Streamable HTTP, at options.path, and returns at once, as HTTP.serve does (port 0 picks a free one, HTTP.local_port tells which). The server belongs to the task that calls it. A registry that cannot be served is an mcp.registry error.

  • Each message is a POST whose Accept takes application/json and text/event-stream (else 406). A request is answered with JSON, or with SSE when options.stream is set; once its handler sends a notification, the answer is an SSE stream of the notifications and then the answer. A cancelled request gets an SSE stream with no answer. A notification or an answer gets 202. A body that is no message gets 400 with the JSON-RPC error.
  • initialize starts a session: its answer gives the id in Mcp-Session-Id, which each later request must carry (400 without it, 404 for an unknown one). An MCP-Protocol-Version that is not the agreed one is 400. A DELETE ends the session.
  • A GET with the session id (and Accept: text/event-stream) opens the stream of the session, for a live registry (else 405): each change of the registry, with its number as the event id. It opens with an event with no data, whose id is where it starts. With Last-Event-ID it starts after that change, else after the last change before the session started. A new GET stream of the session ends the one before it. The stream does not keep a session from idling out.
  • Before all that, an Origin that is not in options.origins is 403, and auth, when given, refuses with 401. A browser sends Origin with every POST, so a browser page can call only from an origin listed in origins (none unless given), and only from its own origin, since no CORS headers are sent. The check keeps out the pages of other sites and DNS rebinding.
  • A session ends with its DELETE, or when it has had no request for options.idle_ms; then it is 404, and a client starts a new one. Its requests still running are cancelled. A session belongs to who opened it, as auth tells: a request from someone else is 404.

Bind to 127.0.0.1 unless the server must be reached from other machines, and then set auth.

import HTTP from "std/http"
import Server from "pkg/mcp/server"

struct Echo
  text: String
end

def echo(args: Echo) -> Result[Server.ToolResult] = ok(Server.text(args.text))

def main() -> Void
  registry = Server.registry("notes", "1.0.0")
    |> Server.tool("echo", "Gives the text back.", JSON.schema(Echo), Echo.codec, &echo)

  options = Server.HttpOptions(origins: ["https://app.example.com"])
  server = Server.serve_http(registry, "127.0.0.1", 8080, options, some(Server.bearer("secret"))).unwrap!
  HTTP.wait(server).unwrap!
end

Server.HttpOptions #

HttpOptions(path: String = "/mcp", origins: List[String] = [], stream: Bool = false, max_body_bytes: Int = 4194304, max_sessions: Int = 1000, max_sessions_per_identity: Int = 100, idle_ms: Int = 1800000)

How the endpoint serves: its path; the Origin values that may call (a request with no Origin, from a program and not a browser, is served); SSE answers instead of JSON; the largest body of serve_http (a server that mounts the endpoint sets its own in HTTP.ServerOptions); the most sessions at once, past which an initialize gets 503 unless an idle session can end (it looks through all the sessions to find one, as each initialize of a named identity does to count its own, so keep max_sessions in the thousands); the most sessions of one identity (what Auth gives) at once, past which its initialize gets 429 once its own idle sessions ended, with Retry-After set to when its next session goes idle, while the other identities go on (the identity "", of no Auth or of bearer, has only max_sessions: an Auth that gives "" to anonymous callers lets them fill max_sessions); and how long a session lives with no request (30 minutes). max_sessions, max_sessions_per_identity or idle_ms under 1 is an mcp.options error.

Server.Auth and Server.bearer #

type Auth = Fn[HTTP.Request, Result[String]] checks each request before it is served. It gives who sent it, to whom the sessions it opens belong ("" for an auth that does not tell people apart), or an error, a 401 with its message. A tool reads it with identity, and max_sessions_per_identity counts the sessions of each.

bearer(token: String) -> Auth checks Authorization: Bearer TOKEN: the scheme in any case, the token in constant time. An empty token refuses every request. Everyone with the token is "".

import HTTP from "std/http"
import Server from "pkg/mcp/server"

def main() -> Void
  check = Server.bearer("secret")
  good = HTTP.Request(method: "POST", target: "/mcp", path: "/mcp", headers: [HTTP.Header(name: "authorization", value: "Bearer secret")], body: "".bytes)
  puts(check.call(good).ok?)
  puts(check.call(good.with(headers: [])).ok?)
end
Output
true
false

Server.http_app and Server.mount #

http_app(registry: Registry, options: HttpOptions = HttpOptions(), auth: Optional[Auth] = none) -> Result[HTTP.App]

mount(mcp: HTTP.App, path: String, rest: HTTP.App) -> HTTP.App

http_app is the endpoint as an HTTP.App, for a server that serves other things too: it answers 404 off options.path, so the path of mount is the same. mount sends the requests on path to it and every other request to rest, such as a Bond app (the package does not depend on Bond, so this example is not run here). Bond reads a body only once its filters let the request through when it serves itself, but it does not export that reading for another app, so rest here reads every body first (bond#115):

import Bond from "pkg/bond/bond"
import HTTP from "std/http"
import Server from "pkg/mcp/server"

def hello(conn: Bond.Conn) -> Result[Bond.Conn] = ok(Bond.text(conn, 200, "hello"))

def bonded(site: Bond.App, request: HTTP.Request, body: HTTP.RequestBody) -> Result[HTTP.Answer]
  data = try HTTP.read_all(body, 1_048_576)
  ok(HTTP.Answer.Stream(Bond.handle_stream(site, request.with(body: data))))
end

def main() -> Void
  site = Bond.app() |> Bond.get("/", &hello)
  rest = ->(request: HTTP.Request, body: HTTP.RequestBody) { bonded(site, request, body) }
  mcp = Server.http_app(Server.registry("notes", "1.0.0")).unwrap!
  server = HTTP.serve("127.0.0.1", 8080, Server.mount(mcp, "/mcp", rest)).unwrap!
  HTTP.wait(server).unwrap!
end

API of the client #

import Mcp from "pkg/mcp/mcp". A client and its server are a resource: stop each client you start. A client sends one request at a time.

Mcp.Client #

Client(server: Server, options: Options, actor, notices: Channel[Notice])

A client of one server, made by start. notices carries what the server tells besides its answers (see Mcp.Notice).

Mcp.Server #

Server(name: String, command: String = "", args: List[String] = [], env: Map[String, String] = {}, log: String = "", cwd: String = ".", url: String = "", headers: Map[String, String] = {})

How to reach a server: a command with its args, started on stdio in its own process group in the folder cwd, with env added to the environment and its stderr written to the file log ("" leaves it on ours); or a url on Streamable HTTP, with headers sent on each request. A header value is never shown in an error, and neither is the query of the url.

Mcp.Options #

Options(client_name: String = "agentica-mcp", start_ms: Int = 30_000, timeout_ms: Int = 60_000, max_message_bytes: Int = 4_194_304)

client_name is the name the client gives in initialize. start_ms bounds the start of the server and its initialize; timeout_ms bounds one request, after the start (all the pages of tools share it). max_message_bytes is the largest JSON answer or event over HTTP.

Mcp.start #

start(server: Server, options: Options = Options()) -> Client

Makes the client. Nothing starts until the first tools or call.

Mcp.tools #

tools(client: Client) -> Result[List[Tool]]

The tools of the server, every page of tools/list, at most 100 pages; a cursor seen before ends the list.

Mcp.call #

call(client: Client, name: String, arguments: JSON.Value, canceller: Optional[Canceller] = none) -> Result[Output]

Calls the tool name with the JSON object arguments. A canceller lets another task cancel the call (cancel).

Mcp.canceller, Mcp.cancel and Mcp.Canceller #

canceller() -> Canceller

cancel(canceller: Canceller) -> Void

canceller makes a handle for one call (once cancelled, it stays so: a call given it later fails at once); cancel, from another task, cancels that call. Once the call was sent, it fails with mcp.cancelled within about 50 ms, the server gets notifications/cancelled, and the server is kept for the next request. A call cancelled while it waits in the queue or while the server starts fails when its turn comes, and is never sent; one that already ended is left as it is. A request that times out is cancelled on the server too.

import Mcp from "pkg/mcp/mcp"

def main() -> Void
  client = Mcp.start(Mcp.Server(name: "files", command: "files-server"))
  canceller = Mcp.canceller()
  Task.spawn do
    Task.sleep(5000)
    Mcp.cancel(canceller)
  end

  case Mcp.call(client, "index", JSON.object({}), some(canceller))
    ok(output) -> puts(output.text)
    error(e) -> puts(e.kind)
  end

  Mcp.stop(client)
end

Mcp.Notice, Mcp.Progress and Mcp.LogEntry #

client.notices is a Channel[Notice] of what the server tells besides its answers. Read it in a task of your own; when 64 notices wait, newer ones are dropped, and stop closes it.

  • Notice.Progressed(Progress(progress: Float, total: Optional[Float] = none, message: String = "")): how far the call in flight is. Each call asks for its progress with a progressToken, and only the progress of that call comes.
  • Notice.Logged(LogEntry(level: String, logger: String = "", data: JSON.Value)): a log line of the server.

A text of a notice (message, level, logger) is cut at 4096 characters.

  • Notice.Changed(String): the list that changed, tools, resources or prompts, so that the next tools lists it again.

On stdio, notices come while a request runs; one sent between requests comes with the next. Over HTTP, those of a request come on its stream, and a server that says its lists may change (listChanged) gets a GET stream of its own, read by the client for as long as the session lasts: a stream that ends or cannot be opened is opened again, and any other answer than a stream, a 5xx, 408 or 429 ends it.

Mcp.stop #

stop(client: Client) -> Void

Stops the client, ends the HTTP session (a DELETE) or the server process and what it started.

Mcp.Tool and Mcp.Output #

Tool(name: String, description: String, input_schema: JSON.Value) is a tool of the server; a tool with no name is left out. Output(text: String, is_error: Bool) is what a call gave: the text parts joined by lines, other parts named ([image image/png]), or the structured content when there is no part, and whether the tool says it failed.

API of the messages #

import JsonRpc from "pkg/mcp/jsonrpc". Pure.

JsonRpc.Message #

Message.Request(Call), Message.Notification(Note) or Message.Response(Answer). Call(id: Id, method: String, params: Optional[JSON.Value] = none) waits for an answer with its id; Note(method: String, params: Optional[JSON.Value] = none) has none. params, when given, is an object or an array. Answer(id: Optional[Id], outcome: Outcome) carries Outcome.Success(JSON.Value) or Outcome.Failed(Failure), and has no id only when it answers a request that could not be read. Id is Id.Number(Int) or Id.Text(String). Failure(code: Int, message: String, data: Optional[JSON.Value] = none).

JsonRpc.request, notification, reply and refuse #

request(id: Int, method: String, params: JSON.Value) -> Message, notification(method: String) -> Message, reply(id: Id, result: JSON.Value) -> Message and refuse(id: Id, code: Int, message: String) -> Message build the common messages.

JsonRpc.encode and JsonRpc.decode #

encode(message: Message) -> String writes a message as JSON on one line; decode(text: String) -> Result[Message] reads one back. A text that is not JSON is an error of the kind mcp.jsonrpc with the code PARSE_ERROR (-32700), and JSON that is no message one with INVALID_REQUEST (-32600).

import JsonRpc from "pkg/mcp/jsonrpc"

def main() -> Void
  text = JsonRpc.encode(JsonRpc.refuse(JsonRpc.Id.Text("a"), JsonRpc.METHOD_NOT_FOUND, "no such method"))
  puts(text)
  puts(JsonRpc.decode(text) == ok(JsonRpc.refuse(JsonRpc.Id.Text("a"), -32601, "no such method")))
  case JsonRpc.decode("{\"id\": 1}")
    ok(_) -> puts("a message")
    error(e) -> puts("#{e.kind} #{e.code.unwrap_or(0)}")
  end
end
Output
{"jsonrpc":"2.0","id":"a","error":{"code":-32601,"message":"no such method"}}
true
mcp.jsonrpc -32600

The other codes are METHOD_NOT_FOUND (-32601), INVALID_PARAMS (-32602) and INTERNAL_ERROR (-32603). claims?, INVALID and RPC are for the client and the server of this package.

JsonRpc.outcome #

outcome(answer: Answer) -> Result[JSON.Value]

The result of an answer, or its failure as an error of the kind mcp.rpc with the failure's code as code.

API of the session start #

import Lifecycle from "pkg/mcp/lifecycle". Pure.

Lifecycle.Hello, Welcome and Implementation #

Hello(protocol_version: String = LATEST, capabilities: JSON.Value, client: Implementation) is the params of initialize, and Welcome(protocol_version: String, capabilities: JSON.Value, server: Implementation, instructions: String = "") its result. Implementation(name: String, version: String, description: String = "") names a client or a server, with a description for people (2025-11-25). hello_json and welcome_json write them; read_hello and read_welcome read them back. read_welcome refuses a version that is not spoken (kind mcp.lifecycle), and takes a missing capabilities or serverInfo as {} and ""; read_hello needs a capabilities object and a clientInfo with name and version. INITIALIZE, INITIALIZED and PING are the method names, and INVALID the kind of the errors.

Lifecycle.negotiate and supported? #

negotiate(wanted: String) -> String is the version a server answers: wanted when it is spoken (VERSIONS: 2025-11-25, 2025-06-18 and 2025-03-26), else LATEST. supported?(version: String) -> Bool says whether a version is spoken.

import Lifecycle from "pkg/mcp/lifecycle"

def main() -> Void
  puts(Lifecycle.negotiate("2025-03-26"))
  puts(Lifecycle.negotiate("2024-11-05"))
  puts(Lifecycle.supported?("2099-01-01"))
end
Output
2025-03-26
2025-11-25
false

Lifecycle.answer #

answer(call: JsonRpc.Call) -> JsonRpc.Message

What a client with no capability answers to a request of the server: {} to ping, and METHOD_NOT_FOUND to any other.

The other modules (client, http, sse, tools, notices, context, dispatch, registry, http_server) are the parts behind these and may change; use pkg/mcp/mcp, pkg/mcp/server, pkg/mcp/jsonrpc and pkg/mcp/lifecycle.

Errors #

KindWhen
mcp.unavailablethe server did not start, exited, could not be reached, answered nothing in time, speaks another protocol version or broke the protocol: it is stopped, and the next use starts it again
mcp.rpcthe server answered with a JSON-RPC error; its code is the code of the error
mcp.cancelledthe caller cancelled the call with cancel; the server is kept
mcp.registrya registry that cannot be served (a bad tool name or URI template, a name or URI twice, a page_size under 1), or a change that cannot be made: the registry is not live, or the edit crashes, takes more than 5 s or cannot be served
mcp.optionsHttpOptions that cannot be served (Server.OPTIONS)
mcp.jsonrpcJsonRpc.decode of a text that is no message, with its JSON-RPC code
mcp.lifecycleLifecycle.read_hello or read_welcome of params that cannot be read, or a welcome with a version that is not spoken

A tool that fails says so in Output.is_error, not as an error.