Guides
Model Context Protocol
Connect Sofuu to MCP servers over stdio, Streamable HTTP, or SSE, or serve tools and resources to any MCP client.
On this page8 sections
Sofuu includes a native Model Context Protocol client and server; no external SDK is required inside the runtime. The client connects to local or remote servers, and the server exposes tools, resources, and prompts over stdio, HTTP, or an in-process transport from the same JavaScript surface.
Client
// stdio: a command string, or {command, args, env, cwd}
const client = await sofuu.mcp.connect(
"npx -y @modelcontextprotocol/server-filesystem /tmp",
);
// Streamable HTTP
const httpClient = await sofuu.mcp.connect({
url: "http://127.0.0.1:9000/mcp",
transport: "http", // "auto" also selects Streamable HTTP
});
const tools = await client.listTools();
const result = await client.call("read_file", { path: "/tmp/data.txt" });
// The raw MCP result is normalized by the same mapper the agent loop uses.
console.log(sofuu.tools.mcpResult(result).text);
client.disconnect();
client.listTools() and client.listResources() follow nextCursor until the inventory is complete. A repeated cursor, or more than 32 pages, stops the walk instead of looping. client.protocolVersion() reports the version the server negotiated, and client.onNotification(handler) receives server notifications such as notifications/tools/list_changed.
client.call(method, params, { timeoutMs }) accepts a bare tool name, which is wrapped into tools/call, or a protocol method such as ping, which is sent verbatim. On a stdio deadline the client sends notifications/cancelled and frees the pending slot. Cancellation does not prove the server stopped. After a potentially effectful request has been dispatched, a lost reply or deadline is reported as E_MCP_OUTCOME_UNKNOWN; check the real effect before retrying. Requests that time out while still queued for reconnection were never dispatched. Reconnection rechecks the server policy before starting a new transport, and a denied or unavailable policy rejects queued calls.
Transports and protocol versions
transport | Behavior |
|---|---|
stdio (default) | Spawns a command and speaks newline-delimited JSON-RPC over stdin/stdout. |
direct | Connects an in-process server object to a client without process spawning. A direct client can be passed to agent.define({ tools: [directClient] }). |
http / auto | Streamable HTTP: POST JSON-RPC, carry Mcp-Session-Id, accept JSON or SSE response bodies, and DELETE the session on disconnect. |
sse | Legacy HTTP+SSE: GET the URL as an event stream, read the endpoint event, then POST messages to that URI. |
The client offers protocol version 2025-06-18, and protocolVersion() returns the server's choice. A bare {url} means Streamable HTTP; the client never infers legacy HTTP+SSE from a URL. Under transport: "http" or "auto", a legacy endpoint is a typed refusal rather than a silent downgrade. Request transport: "sse" explicitly to use the legacy transport, which carries protocol 2024-11-05. The server's initialize negotiates 2025-06-18 or 2024-11-05 and advertises only the capabilities it implements.
A server can also answer ping, and server-to-client requests are handled: roots/list answers with the policy fs.roots, and an undeclared request is answered with -32601.
Configuration
sofuu.mcp.loadConfig() is the loader for ~/.sofuu/mcp.json; SOFUU_MCP_CONFIG overrides the path. The file is a JSON array:
[
{
"name": "fs",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
"env": { "TOKEN": { "secret": "MCP_TOKEN" } },
"cwd": "/tmp",
"enabled": true,
"tools": { "allow": ["read_file"], "deny": ["write_file"] }
}
]
A remote entry supplies url and an optional transport ("http" by default, or "sse"); command then becomes optional. A missing file means no servers. A corrupt file is reported as {ok:false} and left in place, never silently overwritten.
The child environment stays the functional allowlist: env can add or remove names, never inherit everything, and null removes a name. A {"secret":"NAME"} value is resolved at spawn time through policy.secret; the config and loader see only the name, and a missing secret refuses the connect. tools{allow,deny} filters the inventory before names are assigned, and deny wins. A filtered tool cannot claim a name slot or reach the model. A tool whose name collides with a builtin or inline tool is exposed as <server>__<tool> instead of shadowing the existing tool.
Server
const server = sofuu.mcp.serve({ name: "math-service", version: "1.0.0" });
server.tool(
"add",
{
description: "Add two numbers",
schema: {
type: "object",
properties: { a: { type: "number" }, b: { type: "number" } },
required: ["a", "b"],
},
},
({ a, b }) => ({ result: a + b }),
);
server.resource(
"note://hello",
{ name: "Hello", mimeType: "text/plain" },
() => "HELLO",
);
server.prompt("greet", { description: "A greeting" }, ({ name }) => `Hello ${name}`);
server.start(); // stdio on fd 0/1
// server.stop(); // idempotent; close() is an alias
server.tool, server.resource, server.prompt, server.start, and server.stop are the registration and lifecycle surface. server.use(fn) adds middleware in onion order, running on both tools and requests.
initialize negotiates the client's protocol version, and ping answers {}. tools/list, resources/list, and prompts/list paginate at 50 entries per page. resources/read and prompts/get route to their handlers, which must be synchronous; an async resource or prompt handler is a typed error. A throwing or rejecting tool handler answers in-band with {content:[{type:'text',text}], isError:true}, not a JSON-RPC error. Object results also carry structuredContent, with a text mirror kept. Registering a tool after the first tools/list emits notifications/tools/list_changed.
An HTTP server mode is available with sofuu.mcp.serve({ transport: "http", port: 19842 }); close() stops it.
Build a standalone server
sofuu mcp build server.ts -o dist/my-server
sofuu mcp inspect ./dist/my-server --call add --args '{"a":1,"b":2}'
The build targets the dedicated micro-runtime base and can remove unused subsystems. A supported server binary does not need a separate Node.js or Python installation, but OS libraries and services used by the server may still be required. Measure startup, memory, and size for your own binary rather than assuming a fixed footprint.
CLI
| Command | Purpose |
|---|---|
sofuu mcp list | Lists configured servers from ~/.sofuu/mcp.json. |
sofuu mcp test "<cmd>" | Tests the handshake, protocol negotiation, and tool/resource counts. |
sofuu mcp inspect "<cmd>" --call <tool> --args '{...}' | Inspects schemas and invokes a tool directly. |
sofuu mcp add, sofuu mcp remove | Validate before writing, then replace the file atomically. |
sofuu mcp init <name> | Scaffolds a new server with an idiomatic schema. |
sofuu mcp build <entry> -o <out> | Compiles a standalone micro-server. |
sofuu mcp link cursor | Synchronizes server definitions into the target client. |
Trust boundaries
sofuu.tools.mcpResult(result, meta) is the single mapper used by the agent loop. It normalizes every content block, structuredContent, and isError into the uniform tool contract {ok, text, data?, error?, meta}. MCP annotations (readOnlyHint and destructiveHint) steer the approval risk flag.