MCP
MCP server
An MCP server on SDK v2, one list and one call handler for every tool.
- title
- Text Slug
- hints
- readOnly, idempotent
- inputSchema
- text, separator
- failure
- isError: true
Access
- Import
import { createMcpServer } from "@agntn/tools/mcp" - Peer
@modelcontextprotocol/server >=2.2.0 <3 - Fails
isError: true
import { createMcpServer } from "@agntn/tools/mcp";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { tools } from "./tools.ts";
serveStdio(() =>
createMcpServer(
{
name: "mypackage",
version: "1.0.0",
title: "My Package",
description: "Turns titles into slugs.",
icons: [{ src: "https://example.com/mypackage/icon.svg", mimeType: "image/svg+xml", sizes: ["any"] }],
websiteUrl: "https://example.com/mypackage",
},
tools,
),
);
createMcpServer(info, tools) gives you an unconnected server. One tools/list handler, one tools/call handler, every tool in the list. Connect it to Streamable HTTP or to a pair in memory for tests. This site does the last one, in your tab.
Stdio wants a factory. Hand it to serveStdio and 2025 and 2026 clients both get in. Why a factory? Each connection gets a fresh server, and so does the throwaway discover probe. And plain server.connect(new StdioServerTransport())? It leaves the 2026 client at the door, or sends it back to 2025.
info needs a name and a version, that's it. Want a nicer label? title is the name a client can put on screen and websiteUrl is where it can link. A connector card wants more than a name, though. description gives it a line and icons give it a face. It all goes out exactly as you wrote it. name is still the word in the unknown tool error, so the pretty one never ends up there.
What the client sees
The schema goes out exactly as you wrote it, additionalProperties: false and pattern included. A tool's title goes out twice, beside the name and in the annotations. Why twice? Claude Code reads only the second one, so without it your nice Decode WIF shows up as keys_wif_decode. The rest of the annotations come from effect:
readOnlyHintwhen the effect isreaddestructiveHintwhen it'sdestructiveorexecidempotentHintfromidempotent, which defaults to readsopenWorldHintfromopenWorld, off unless you say so
Gave a tool its own icons? They ride along in tools/list. No icons, no icons key. Pi, OMP and the AI SDK draw no pictures, so they never see them.
By default details stays home and structuredContent is never set. Clients that see structured output tend to prefer it over the text and hide the readable answer, so the text is the answer. Everything the next call needs goes in it.
When a program reads the answer too
Sometimes the reader isn't a model. ChatGPT's mention search answers with structuredContent. So does its settings page, and there the read tool must declare an outputSchema. Give the tool an output schema. tools/list lists it as outputSchema. Every successful call sends details as structuredContent, right next to the text. A returned isError still goes out as text alone.
The details pass that schema before they leave. Renamed a field and forgot the schema? The client gets <tool> returned details that don't match its output schema, one line per problem. Not data that lies about its own shape. Better you hear it than ChatGPT.
meta goes out as the tool's _meta, as written. That's where ui and openai/extensions live. Pi, OMP and the AI SDK never see it.
Why not McpServer
SDK v2's McpServer.registerTool would take the schema. It also answers a call to toString, constructor or __proto__ with "Tool toString disabled", because its lookup reaches Object.prototype. It echoes a tool name with a newline and an escape code straight back to the client. It glues validation problems into one line and passes a thrown message through with its newline intact.
So the adapter sits on the low-level Server, which the SDK marks @deprecated, and does those parts itself. An unknown name, toString included, gets Unknown <server> tool: "<name>" with the name escaped. Validation gets one line per problem. A throw becomes <tool> failed: <message>, with a caused by: line under it for each cause.
When the error has a cause
A package that tries a second provider keeps the first failure as a cause. Show only the top message and the agent sees a rate limit. Is the only provider blocked? No, the first one was just down for a minute. That's worth a retry, not a eulogy.
mypackage_balance failed: Rate limited by provider-b
caused by: HTTP 502 from https://provider-a.example/REDACTED
Causes come outermost first. One that repeats the line above is skipped. An AggregateError without a cause goes on with its first error, which is how Node's fetch reports a refused connection. A cycle stops the chain. You get five cause lines at most, each cut at 300 characters.
Cause lines get scrubbed harder than the top one. A package cleans the message it throws, and nobody cleaned the raw error it kept.
A URL keeps its scheme and host, and everything after them becomes /REDACTED. Spot an @ past a URL and even the host goes. A password can hold anything, spaces too.
A field with a secret-looking name keeps its name and loses the rest of the line too. Where does a cookie header end? Nobody guesses here. The input JSON.parse quotes is dropped.
Pi, OMP and the AI SDK get the same scrubbed cause lines. One copy does the scrubbing, so no host is looser than this one. They skip the <tool> failed: prefix. They already know which tool they called.
Progress
Ask for progress, get progress. When a tools/call carries _meta.progressToken, each progress line from the tool goes out as notifications/progress, with total when the tool knows it. No token, no callback. The tool sees progress as undefined and doesn't waste a breath on it.
A notification that fails to send lands in server.onerror. The answer still arrives, and that's the part the model actually needs.
Questions
A client that declares elicitation gets ask. Any other client gets undefined there. A tool that calls it with ?. just carries on.
Under the hood it's the 2026 way. The call answers input_required with one elicitation/create inside. The answers so far ride along in requestState. On a 2025 connection the SDK plays the client's part. It sends a real elicitation/create and runs the handler again. Same code, both revisions. Each answer is checked against its form. One that doesn't fit gets asked again, a tampered requestState too. Same for an answer whose question changed in between. A yes to "Apply to A?" never turns into a yes to B.
Why no signature on that state? Whoever can forge it can forge the reply next to it. Nothing to protect.
Claude Code declares elicitation, so it gets the form. In claude -p there's nobody to fill it, and the tool reads cancel. An Elicitation hook can answer for the person there.
Who called?
One HTTP process can serve many clients. Environment variables describe the process, not the caller. Need a session? Look at the request or the call's _meta.
request is the Fetch Request, including headers and URL. meta holds whatever the client put in _meta. It can carry an opencode session ID.
| Adapter | request | meta |
|---|---|---|
createMcpServer over HTTP | The Request | When supplied |
createMcpServer over stdio | Absent | When supplied |
toH3Tools | From the H3 event | When supplied |
toToolkitTools | Rebuilt from URL and headers | When supplied |
Stdio has no HTTP envelope to rummage through. In-memory calls don't have a request either. With neither request nor _meta, host is undefined.
The toolkit runs SDK v1, which keeps the URL and the headers and drops the rest. So that Request is built from leftovers. URL and headers are the caller's. The method says GET for a POST and the body is null. Trust neither.
Narrow on mcp === true before reading MCP fields. Other hosts have their own shapes.
import type { McpHost } from "@agntn/tools/mcp";
async execute({ text }, { host }) {
const mcp = host as McpHost | undefined;
const session =
mcp?.mcp === true
? (mcp.request?.headers.get("x-session-id") ?? mcp.meta?.["ai.opencode/sessionID"])
: undefined;
return await remember(text, { session });
}
The client supplies both headers and _meta. They're clues, not permission. Check Host, Origin and the token before the handler.
With createMcpServer the SDK has already lifted its reserved io.modelcontextprotocol/* keys out of meta. h3-mcp passes the raw _meta object.
Errors
A bad input, a returned isError and a thrown error all come back as isError: true with text. Nothing escapes as a JSON-RPC error, so the model always gets something to read and a reason to try again.
No Server in sight
Some transports don't want a Server at all. They bring their own JSON-RPC and ask for a listing and a handler, that's it. So the two halves come out on their own:
import { callTool, listTools } from "@agntn/tools/mcp";
import { tools } from "./tools.ts";
const listing = listTools(tools);
const answer = await callTool({ name: "mypackage" }, tools, "mypackage_lookup", { word: "marmot" });
listTools(tools) is what tools/list answers. callTool(info, tools, name, args, context) is what tools/call answers, unknown names and bad input included. It never throws. Want the abort signal or progress to reach the executor? Pass { signal, progress } last.
createMcpServer is built on these two. Your stdio server and your docs page can't drift apart anymore, because there's nothing left to copy by hand.
On H3
h3-mcp speaks MCP over HTTP on its own, no SDK involved. It wants a list of its tool definitions, and toH3Tools hands it one:
import { H3, serve } from "h3";
import { defineMcpHandler } from "h3-mcp";
import { toH3Tools } from "@agntn/tools/h3";
import { tools } from "./tools.ts";
const app = new H3().all(
"/mcp",
defineMcpHandler({ name: "mypackage", version: "1.0.0", tools: toH3Tools({ name: "mypackage" }, tools) }),
);
serve(app);
Each entry is what listTools lists, and its handler is callTool. So the text, the validation lines and the cleaned up errors match the stdio server word for word. The request's abort signal reaches execute, and progress turns into notifications/progress when the client sent a token.
The schema goes to h3-mcp as plain JSON Schema. h3-mcp doesn't validate that, it just passes the arguments on, and the core checks them like on every other host.
Questions work on the 2026 revision only. h3-mcp has no 2025 fallback for input_required, so an older request gets ask as undefined.
One difference. An unknown tool name never reaches the adapter. h3-mcp answers it itself, with a JSON-RPC Tool not found error instead of the isError text.
@agntn/tools/h3 imports only types from h3-mcp. Install h3-mcp and h3, and the MCP SDK stays out of your node_modules.
On a Docus /mcp route
Docus serves MCP through @nuxtjs/mcp-toolkit. It wants its own tool definitions, and toToolkitTools builds them:
import { toToolkitTools } from "@agntn/tools/toolkit";
import { getMcpTools } from "@nuxtjs/mcp-toolkit/server";
import { tools } from "mypackage/tools";
const packageTools = toToolkitTools({ name: "mypackage" }, tools);
export default defineMcpHandler({
name: "mypackage",
version: "1.0.0",
tools: async (event) => [...(await getMcpTools({ event })), ...packageTools],
});
Why a function and not just the array? Because the toolkit takes an array as the whole list. Docus brings list-pages and get-page, and an array quietly kicks them out. No error, just two tools fewer. The function asks the toolkit for its own tools first, so the pages stay and yours come after.
Same deal as on H3. Each entry lists what listTools lists and answers through callTool, so the text and the error lines match stdio word for word. The abort signal reaches execute. output and meta ride along too, which hand copies of this route never bothered with.
Now the ugly part. The toolkit hands every schema to SDK v1's McpServer, and that one takes Zod or nothing. So each schema turns into a z.looseObject({}) that lists your JSON Schema as written and waves any object through. The core does the real checking, like everywhere else. Zod has no public hook for this, so the adapter pokes at _zod. Still ugly? Sure. But now it's ugly in one place, and the tests go red first when Zod moves things. Install zod next to the toolkit, it's a peer.
A few things the toolkit does its own way:
- SDK v1 adds
$schemato every listed schema andexecution: { taskSupport: "forbidden" }to every tool. Harmless, just don't be surprised. - Tool
iconsstay home. The toolkit never passes them to the SDK. Server icons go indefineMcpHandleras usual. - Progress needs sessions. The stateless default answers in plain JSON, so a notification has nowhere to ride. Set
mcp: { sessions: { enabled: true } }innuxt.config.tsandprogressshows up like on stdio. - An unknown name never reaches the adapter. SDK v1 answers it, and yes, it answers
toStringwith "Tool toString disabled". The bug from Why not McpServer, one major version older.
Can it ask the person?
It can. Hand it the toolkit's own useMcpElicitation:
const packageTools = toToolkitTools({ name: "mypackage" }, tools, { elicitation: useMcpElicitation });
export default defineMcpHandler({
name: "mypackage",
version: "1.0.0",
tools: async (event) => [...(await getMcpTools({ event })), ...packageTools],
});
SDK v1 has never heard of input_required. So the question goes out as a real elicitation/create on the call's own stream, and the call just waits for it. One run per call, like in Pi. Only supports("form") comes from the composable. The form is ours, built and checked the same way as on stdio.
It needs two switches in nuxt.config.ts:
export default defineNuxtConfig({
mcp: { sessions: { enabled: true } },
nitro: { experimental: { asyncContext: true } },
});
Forget sessions and every request gets a fresh server that never saw initialize. It can't know the client fills forms, so ask stays undefined. Quiet, and instant. No request hanging somewhere. Forget asyncContext and it gets loud. useMcpElicitation can't find the request, so every call answers "Nitro request context is not available". Annoying? Sure. But it names the flag.
The question follows the call's abort signal, so a cancelled call takes its form back. Unless the client runs SDK v1 and it's the session's first request. That client skips a cancel for request id 0, so the form stays up with nobody waiting for it. SDK v2 clients get it right. One more catch. SDK v1 gives every request 60 seconds, a form too. A person who thinks longer makes ask throw.