mcp
Model Context Protocol, both directions: call an MCP server's tools over stdio or HTTP, or be one.
ecko get github.com/ecko-lang/mcp
import mcp
Declares net and exec. A capability is only advisory in the manifest: what the package actually gets is the grant you give it when you import it.
Version 0.56.0 - source - MIT.
PROTOCOL_VERSION
The MCP protocol version this package speaks, in both directions.
Shared rather than declared per side: a client and a server that disagree about it fail a handshake, and two constants drift the moment MCP revs.
request(id, method, params = {})
Build a JSON-RPC request object. id correlates the reply; MCP requires it to be unique within a connection and never null.
errors: bug when id is not a String or an Int, or method is not a String.
mcp.request(1, "tools/list") # {id: 1, jsonrpc: 2.0, method: tools/list, params: {}}
notification(method, params = {})
Build a JSON-RPC notification: a request with no id, which the receiver must not reply to. MCP uses these for notifications/initialized and cancellation.
errors: bug when method is not a String.
mcp.notification("notifications/initialized")
encode(message)
Encode a request or notification as JSON text for the wire.
errors: bug when the message holds a value JSON cannot carry (a function).
mcp.encode(mcp.request(1, "ping")) # {"id":1,"jsonrpc":"2.0","method":"ping","params":{}}
http_transport(url, headers = {})
An HTTP transport, MCP's "Streamable HTTP" shape: every message is a POST, and the reply comes back in the response body as JSON or as an SSE stream.
headers are added to every request (for Authorization, which is how hosted MCP servers authenticate). The transport sends the MCP-Protocol-Version header, and when the server hands out an Mcp-Session-Id it echoes it on every later request and ends the session with a DELETE on close. A notification answered 202 with an empty body is accepted as the spec describes.
Needs the net capability.
errors: bug when url is not a String or headers is not a Map. Each send raises mcp/http_status on a non-2xx answer and mcp/bad_reply when the body holds no reply to the request; network failures surface as net.
mcp.http_transport("https://mcp.example.com/", headers: { Authorization: "Bearer t" })
fake(handler)
A transport backed by a function, for tests and examples. Needs no capability.
handler takes the decoded request map and returns the reply map. It is called for notifications too, and what it returns for one is ignored.
errors: bug when handler is not a function.
t = mcp.fake(fn(req) { jsonrpc: "2.0", id: get(req, "id"), result: {} })
stdio_transport(command, args = [], timeout_ms = 30000)
A stdio transport: spawn the server and talk to it over its pipes, one JSON message per line.
This is how almost every MCP server ships - the client starts the process and uses the pipes it already has, so there is no port, no URL and nothing to authenticate. timeout_ms bounds the wait for each reply.
Messages the server sends between a request and its reply are dealt with rather than mistaken for the reply: notifications (logging, progress) are skipped, a ping is answered, and any other server request is answered with JSON-RPC error -32601, since this client offers no server-side features.
Needs the exec capability to start the process. Nothing here touches the network.
errors: bug when command is not a String, args is not a List or timeout_ms is not a positive Int. Each send raises mcp/no_reply when the server does not answer in time or exits, and mcp/bad_reply when it writes a line that is not JSON.
mcp.stdio_transport("npx", ["-y", "@modelcontextprotocol/server-everything"], timeout_ms: 10000)
connect(transport, name = "ecko", version = "0.1.0")
Open a session: send initialize, then the notifications/initialized the spec requires before any other call. Returns a session value carrying the transport, the server's reply and the request-id counter - pass it to every call below.
name and version identify this client to the server (clientInfo).
errors: bug when transport is not a transport value; otherwise whatever the first call raises (mcp/server_error, mcp/bad_reply, the transport's own errors).
session = mcp.connect(mcp.stdio_transport("my-server"), name: "app", version: "2.0")
server_version(session)
The protocol version the server answered with, or null if it did not say. Worth checking: a server that does not speak our version says so here rather than failing later on a call it does not implement.
server_capabilities(session)
What the server says it can do - tools, resources, prompts are the keys worth looking for. Calling into a section the server did not advertise is a protocol error, so branch on this rather than catching.
call(session, method, params = {})
Send one request and return its result. For any method the wrappers below do not cover.
errors: mcp/server_error (carrying the server's code) when the server answers with a JSON-RPC error; mcp/bad_reply or mcp/id_mismatch when the reply is malformed or answers another request; the transport's own errors.
mcp.call(session, "completion/complete", { ref: ref, argument: arg })
notify(session, method, params = {})
Send a notification: no id, no reply, nothing to wait for. Returns null.
errors: the transport's own errors (mcp/http_status, net).
mcp.notify(session, "notifications/roots/list_changed")
close(session)
Close the transport: stop a stdio server's process, or end an HTTP session the server opened. Returns null.
tools(session)
The tools the server offers, [{ name, description, inputSchema }], following pagination to the end.
errors: mcp/repeated_cursor or mcp/too_many_pages when the server's pagination never ends; mcp/bad_reply when tools is not a list; and what call raises.
for t in mcp.tools(session) { print(t.name) }
call_tool(session, name, args = {})
Call a tool by name. args is the argument map its inputSchema describes.
Returns the raw result, which carries content and may carry isError (a tool that ran and failed, which is data, not an error). Use text_of for the common case of a tool that answers with text.
errors: mcp/server_error when the server rejects the call (an unknown tool is -32602), and what call raises.
mcp.text_of(mcp.call_tool(session, "search", { query: "ecko" }))
text_of(result)
The text parts of a tool result, joined into one String ("" when there are none).
MCP returns content as a list of typed parts (text, image, resource); this takes the text ones and leaves the rest, because a caller that wants an image should reach into content deliberately rather than get a surprise.
is_error(result)
True when the server flagged the tool result as an error. This is not a JSON-RPC error - the call succeeded and the tool itself failed, which the spec models as data so a model can read the failure and retry.
resources(session)
The resources the server exposes, [{ uri, name, mimeType }], following pagination to the end.
errors: as tools.
read_resource(session, uri)
Read one resource by URI. Returns its contents, [{ uri, mimeType, text }].
errors: mcp/server_error when the server refuses (an unknown URI is -32602), and what call raises.
mcp.read_resource(session, "memo://readme")[0].text
prompts(session)
The prompt templates the server offers, [{ name, description, arguments }], following pagination to the end.
errors: as tools.
get_prompt(session, name, args = {})
Render a prompt template. Returns the server's messages list.
errors: mcp/server_error when the server refuses (an unknown prompt is -32602), and what call raises.
mcp.get_prompt(session, "review", { code: "fn f() = 1" })
MAX_PAGES
How many pages of a */list the client follows (1000) before giving up on a server that never stops paginating.
as_tools(session)
The server's tools as specs ai ... using can take.
This is the point of the package: the model picks a tool, Ecko calls it over MCP, and the result goes back into the conversation. Without it a caller has to wire each tool up by hand.
The parameter names come from the tool's own inputSchema, so the model is told what the server says it accepts.
errors: as tools.
answer = ai "what changed in the changelog?" using mcp.as_tools(session)
as_tool(session, t)
One declared tool (an entry of tools(session)) as a spec. Useful when a server offers fifty and the program should only expose three. The spec's call holds the session, so invoking the tool is a round trip to the server.
errors: bug when t is not a Map with a String name.
search = mcp.as_tool(session, find(mcp.tools(session), fn(t) t.name == "search"))
cancel(session, request_id, reason = "")
Tell the server to stop working on a request. Returns null.
MCP models cancellation as a notification, not a request: there is nothing to wait for and no acknowledgement. The server may already have finished, in which case it ignores this - which is why a caller must not treat sending it as proof the work stopped.
errors: the transport's own errors.
id = mcp.next_request_id(session) # the id of the call about to be made
mcp.cancel(session, id, "user pressed stop")
next_request_id(session)
The id the next call on this session will use, an Int.
Needed to cancel: the id has to be known before the request is sent, and call allocates it internally.
tool(name, description, schema, handler)
Declare a tool: a name, a description the model reads, a JSON Schema for its arguments, and the function to run.
handler takes the decoded argument map and returns either a string (the common case), a content list built with text, or a full result map. A handler that throws becomes a tool error (isError: true) carrying its message, not a dead server.
errors: bug when name or description is not a String, schema is not a Map, or handler is not a function.
mcp.tool("echo", "Repeat the text", { type: "object" }, fn(args) args.text)
text(value)
Wrap a value as MCP text content: [{ type: "text", text: ... }].
MCP returns content as a list of typed parts, so even a one-line answer is a list. handle wraps a bare string for you; this is for a handler returning several parts deliberately.
mcp.text(42) # [{text: 42, type: text}]
tool_error(message)
A tool result reporting failure: { content, isError: true }.
This is not a JSON-RPC error. The call succeeded and the tool failed, which MCP models as data on purpose so a model can read the failure and try something else. A JSON-RPC error means the call was rejected outright.
fn(args) if args.n < 0 { mcp.tool_error("n must not be negative") } else { string(args.n) }
resource(uri, name, mime_type, reader)
Declare a resource: something a client can read by URI.
reader takes no arguments and returns the body as a string. Lazy on purpose - a server listing fifty documents should not read fifty files to answer resources/list. A reader that throws is answered as JSON-RPC error -32603.
errors: bug when uri, name or mime_type is not a String, or reader is not a function.
mcp.resource("memo://readme", "readme", "text/plain", fn() "the body")
prompt(name, description, arguments, renderer)
Declare a prompt template.
arguments is the list MCP describes ([{ name, description, required }]). renderer takes the decoded argument map and returns either a string (which becomes one user message) or a full messages list. A renderer that throws is answered as JSON-RPC error -32603.
errors: bug when name or description is not a String, arguments is not a List, or renderer is not a function.
mcp.prompt("review", "Review some code", [{ name: "code", required: true }], fn(a) "review: {a.code}")
handle(request, offer, name = "ecko", version = "0.1.0")
Answer one decoded JSON-RPC request. Returns the reply map, or null for a notification, which by definition gets no reply. It answers initialize, ping (with {}) and the tools, resources and prompts methods; any other method is error -32601.
offer is what this server exposes: { tools, resources, prompts }, each optional. A bare list is taken as the tools, which is what almost every server offers and keeps the common call short. name and version are the serverInfo sent in the initialize reply.
Nothing a client sends makes this throw: a request that is not an object or has no method is -32600, a bad parameter or cursor is -32602, and a failure inside the server itself is -32603 (its detail goes to standard error, not to the client).
errors: bug when offer is neither a List nor a Map.
mcp.handle({ jsonrpc: "2.0", id: 1, method: "ping" }, []) # {id: 1, jsonrpc: 2.0, result: {}}
PAGE_SIZE
How many entries one */list page carries when serving (100).
MCP leaves the size to the server. Small enough that pagination is exercised rather than theoretical, large enough that an ordinary server sends one page.
progress(token, done, total = null)
A progress notification for a long-running request, or null when token is null (the client did not ask for progress, so nobody is listening).
token is the progressToken the client sent in the request's _meta (progress_token reads it). Note that a tool handler receives only its arguments, so serve_stdio and serve_http give it no way to send this; it is for a server built directly on handle.
errors: bug when done (or a non-null total) is not a number.
mcp.progress("tok", 3, 10) # a notifications/progress message with progress 3 of 10
progress_token(request)
The progress token a request carries, or null if the client did not ask.
mcp.progress_token(request) # the value of params._meta.progressToken
tools_changed()
The notification announcing that the tool list changed, so a client can re-read it.
A session holds whatever tools/list returned when it connected; without this a server that gains or loses a tool is talking to a stale client.
resources_changed()
The notification announcing that the resource list changed.
prompts_changed()
The notification announcing that the prompt list changed.
serve_stdio(offer, name = "ecko", version = "0.1.0")
Serve over stdio: one JSON-RPC message per line on standard input, one reply per line on standard output. Blocks until standard input closes, which is how the client says goodbye, then returns null.
This is the transport Claude Desktop and most local MCP clients use - the client spawns the program and talks to it over the pipes it already has, so there is no port, no URL and nothing to authenticate. A malformed or failing request is answered with a JSON-RPC error and the server carries on.
Needs no capability: standard input is handed to the process by whoever started it.
errors: bug when offer is neither a List nor a Map.
mcp.serve_stdio([mcp.tool("echo", "Repeat", { type: "object" }, fn(a) a.text)], name: "echo")
serve_http(port, offer, name = "ecko", version = "0.1.0", host = "127.0.0.1", origins = [])
Serve over HTTP: one JSON-RPC message per POST body, the reply in the response body. MCP's Streamable HTTP shape, minus the optional SSE channel (a GET is answered 405, which the spec allows). Blocks until the server stops.
Binds host, 127.0.0.1 by default, as the spec asks of a local server; pass host: "0.0.0.0" to listen on every interface. A browser request whose Origin is not loopback or listed in origins is refused with 403, which is the spec's guard against DNS rebinding; a request with no Origin (any non-browser client) is served.
Needs the net capability.
errors: bug when offer is neither a List nor a Map, or origins is not a List; what http.serve raises when it cannot bind.
mcp.serve_http(8080, tools, name: "search", origins: ["https://app.example.com"])
handle_text(text, offer, name = "ecko", version = "0.1.0")
Decode one message, answer it with handle, and encode the reply. null when the message was a notification.
Never throws on what a client sends: malformed JSON is error -32700, and a result that cannot be encoded as JSON is error -32603.
errors: bug when offer is neither a List nor a Map.
mcp.handle_text(r"""{"jsonrpc":"2.0","id":1,"method":"ping"}""", []) # {"id":1,"jsonrpc":"2.0","result":{}}