diff options
| author | Felix Weinberger <3823880+felixweinberger@users.noreply.github.com> | 2026-10-28 19:37:43 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-28 19:37:43 +0000 |
| commit | 37d985a4578433d8aab35983c124184d3e087838 (patch) | |
| tree | bd84baf6327a3af7626899de7d717f344170014a | |
| parent | f8c5e7a1dcb71b10cb74586224b5401f3de5db28 (diff) | |
mcp-server-dev: move the TypeScript examples to MCP SDK v2mcp-server-dev-ts-sdk-v2
The three skills taught @modelcontextprotocol/sdk (v1). New servers should use
v2 (@modelcontextprotocol/server), and several examples no longer worked:
- The HTTP scaffolds connected one shared McpServer per request, so overlapping
requests failed with HTTP 500. They now use createMcpHandler with a factory.
- The Cloudflare page used McpAgent with a Durable Object binding, which the
current template no longer ships. It now matches the template.
- The MCPB server used top-level await, which the documented esbuild command
rejects. serveStdio needs none.
Also: z.object schemas, ctx instead of extra, input_required for elicitation,
deprecation notes for sampling, roots and logging, and the v2 auth helpers.
15 files changed, 310 insertions, 260 deletions
diff --git a/plugins/mcp-server-dev/skills/build-mcp-app/SKILL.md b/plugins/mcp-server-dev/skills/build-mcp-app/SKILL.md index c400abdb..142b4b39 100644 --- a/plugins/mcp-server-dev/skills/build-mcp-app/SKILL.md +++ b/plugins/mcp-server-dev/skills/build-mcp-app/SKILL.md @@ -99,10 +99,10 @@ A widget-enabled tool has **two separate registrations**: When Claude calls the tool, the host sees `_meta.ui.resourceUri`, fetches that resource, renders it in an iframe, and pipes the tool's return value into the iframe via the `ontoolresult` event. ```typescript -import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { McpServer } from "@modelcontextprotocol/server"; import { registerAppTool, registerAppResource, RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server"; -import { z } from "zod"; +import * as z from "zod/v4"; const server = new McpServer({ name: "contacts", version: "1.0.0" }); @@ -110,7 +110,7 @@ const server = new McpServer({ name: "contacts", version: "1.0.0" }); registerAppTool(server, "pick_contact", { description: "Open an interactive contact picker", annotations: { title: "Pick Contact", readOnlyHint: true }, - inputSchema: { filter: z.string().optional() }, + inputSchema: z.object({ filter: z.string().optional() }), _meta: { ui: { resourceUri: "ui://widgets/contact-picker.html" } }, }, async ({ filter }) => { const contacts = await db.contacts.search(filter); @@ -200,29 +200,29 @@ Keep widgets **small and single-purpose**. A picker picks. A chart displays. Don **Install:** ```bash -npm install @modelcontextprotocol/sdk @modelcontextprotocol/ext-apps zod express +npm pkg set type=module +npm install @modelcontextprotocol/server @modelcontextprotocol/express @modelcontextprotocol/node @modelcontextprotocol/ext-apps zod express ``` **Server (`src/server.ts`):** ```typescript -import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; -import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; +import { createMcpExpressApp } from "@modelcontextprotocol/express"; import { registerAppTool, registerAppResource, RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server"; -import express from "express"; +import { toNodeHandler } from "@modelcontextprotocol/node"; +import { McpServer, createMcpHandler } from "@modelcontextprotocol/server"; import { readFileSync } from "node:fs"; import { createRequire } from "node:module"; -import { z } from "zod"; +import * as z from "zod/v4"; const require = createRequire(import.meta.url); -const server = new McpServer({ name: "contact-picker", version: "1.0.0" }); // Inline the ext-apps browser bundle into the widget HTML. // The iframe CSP blocks CDN script fetches — bundling is mandatory. const bundle = readFileSync( require.resolve("@modelcontextprotocol/ext-apps/app-with-deps"), "utf8", -).replace(/export\{([^}]+)\};?\s*$/, (_, body) => +).replace(/export\{([^}]+)\};?\s*$/, (_, body: string) => "globalThis.ExtApps={" + body.split(",").map((p) => { const [local, exported] = p.split(" as ").map((s) => s.trim()); @@ -232,34 +232,39 @@ const bundle = readFileSync( const pickerHtml = readFileSync("./widgets/picker.html", "utf8") .replace("/*__EXT_APPS_BUNDLE__*/", () => bundle); -registerAppTool(server, "pick_contact", { - description: "Open an interactive contact picker. User selects one contact.", - annotations: { title: "Pick Contact", readOnlyHint: true }, - inputSchema: { filter: z.string().optional().describe("Name/email prefix filter") }, - _meta: { ui: { resourceUri: "ui://widgets/picker.html" } }, -}, async ({ filter }) => { - const contacts = await db.contacts.search(filter ?? ""); - return { content: [{ type: "text", text: JSON.stringify(contacts) }] }; -}); - -registerAppResource(server, "Contact Picker", "ui://widgets/picker.html", {}, - async () => ({ - contents: [{ uri: "ui://widgets/picker.html", mimeType: RESOURCE_MIME_TYPE, text: pickerHtml }], - }), -); +// Called once per HTTP request. Always build a new McpServer here: +// a shared instance fails as soon as two requests overlap. +function createServer(): McpServer { + const server = new McpServer({ name: "contact-picker", version: "1.0.0" }); + + registerAppTool(server, "pick_contact", { + description: "Open an interactive contact picker. User selects one contact.", + annotations: { title: "Pick Contact", readOnlyHint: true }, + inputSchema: z.object({ filter: z.string().optional().describe("Name/email prefix filter") }), + _meta: { ui: { resourceUri: "ui://widgets/picker.html" } }, + }, async ({ filter }) => { + const contacts = await db.contacts.search(filter ?? ""); + return { content: [{ type: "text", text: JSON.stringify(contacts) }] }; + }); + + registerAppResource(server, "Contact Picker", "ui://widgets/picker.html", {}, + async () => ({ + contents: [{ uri: "ui://widgets/picker.html", mimeType: RESOURCE_MIME_TYPE, text: pickerHtml }], + }), + ); + + return server; +} -const app = express(); -app.use(express.json()); -app.post("/mcp", async (req, res) => { - const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined }); - res.on("close", () => transport.close()); - await server.connect(transport); - await transport.handleRequest(req, res, req.body); -}); -app.listen(process.env.PORT ?? 3000); +// Local dev: accepts only localhost Host/Origin headers (DNS-rebinding protection). +// Deployed: createMcpExpressApp({ host: "0.0.0.0", allowedHosts: ["mcp.example.com"] }) +const app = createMcpExpressApp(); +const handler = toNodeHandler(createMcpHandler(createServer)); +app.all("/mcp", (req, res) => void handler(req, res, req.body)); +app.listen(Number(process.env.PORT ?? 3000)); ``` -For local-only widget apps (driving a desktop app, reading local files), swap the transport to `StdioServerTransport` and package via the `build-mcpb` skill. +For local-only widget apps (driving a desktop app, reading local files), replace the last four lines with `serveStdio(createServer)` from `@modelcontextprotocol/server/stdio` and package via the `build-mcpb` skill. **Widget (`widgets/picker.html`):** diff --git a/plugins/mcp-server-dev/skills/build-mcp-app/references/apps-sdk-messages.md b/plugins/mcp-server-dev/skills/build-mcp-app/references/apps-sdk-messages.md index fc1fdbba..637a876f 100644 --- a/plugins/mcp-server-dev/skills/build-mcp-app/references/apps-sdk-messages.md +++ b/plugins/mcp-server-dev/skills/build-mcp-app/references/apps-sdk-messages.md @@ -152,11 +152,11 @@ For long-running operations, emit progress notifications. The client sends a `pr ```typescript // In the tool handler -async ({ query }, extra) => { - const token = extra._meta?.progressToken; +async ({ query }, ctx) => { + const token = ctx.mcpReq._meta?.progressToken; for (let i = 0; i < steps.length; i++) { if (token !== undefined) { - await extra.sendNotification({ + await ctx.mcpReq.notify({ method: "notifications/progress", params: { progressToken: token, progress: i, total: steps.length, message: steps[i].name }, }); @@ -167,7 +167,7 @@ async ({ query }, extra) => { } ``` -No `{ notify }` destructure — `extra` is `RequestHandlerExtra`; progress goes through `sendNotification`. +The second handler argument is the SDK's `ServerContext`; progress goes through `ctx.mcpReq.notify`. --- diff --git a/plugins/mcp-server-dev/skills/build-mcp-app/references/iframe-sandbox.md b/plugins/mcp-server-dev/skills/build-mcp-app/references/iframe-sandbox.md index 6a7e2a14..5c693b1e 100644 --- a/plugins/mcp-server-dev/skills/build-mcp-app/references/iframe-sandbox.md +++ b/plugins/mcp-server-dev/skills/build-mcp-app/references/iframe-sandbox.md @@ -36,7 +36,7 @@ const require = createRequire(import.meta.url); const bundle = readFileSync( require.resolve("@modelcontextprotocol/ext-apps/app-with-deps"), "utf8", -).replace(/export\{([^}]+)\};?\s*$/, (_, body) => +).replace(/export\{([^}]+)\};?\s*$/, (_, body: string) => "globalThis.ExtApps={" + body.split(",").map((pair) => { const [local, exported] = pair.split(" as ").map((s) => s.trim()); diff --git a/plugins/mcp-server-dev/skills/build-mcp-app/references/widget-templates.md b/plugins/mcp-server-dev/skills/build-mcp-app/references/widget-templates.md index c07bef2d..e3051edd 100644 --- a/plugins/mcp-server-dev/skills/build-mcp-app/references/widget-templates.md +++ b/plugins/mcp-server-dev/skills/build-mcp-app/references/widget-templates.md @@ -19,7 +19,7 @@ const require = createRequire(import.meta.url); const bundle = readFileSync( require.resolve("@modelcontextprotocol/ext-apps/app-with-deps"), "utf8", -).replace(/export\{([^}]+)\};?\s*$/, (_, body) => +).replace(/export\{([^}]+)\};?\s*$/, (_, body: string) => "globalThis.ExtApps={" + body.split(",").map((p) => { const [local, exported] = p.split(" as ").map((s) => s.trim()); @@ -171,7 +171,7 @@ const { App } = globalThis.ExtApps; </script> ``` -Server side, emit progress via `extra.sendNotification({ method: "notifications/progress", ... })` — see `apps-sdk-messages.md`. +Server side, emit progress via `ctx.mcpReq.notify({ method: "notifications/progress", ... })` — see `apps-sdk-messages.md`. --- @@ -182,7 +182,7 @@ Display widgets don't call `sendMessage` — they render and sit there. The tool ```typescript registerAppTool(server, "show_chart", { description: "Render a revenue chart", - inputSchema: { range: z.enum(["week", "month", "year"]) }, + inputSchema: z.object({ range: z.enum(["week", "month", "year"]) }), _meta: { ui: { resourceUri: "ui://widgets/chart.html" } }, }, async ({ range }) => { const data = await fetchRevenue(range); diff --git a/plugins/mcp-server-dev/skills/build-mcp-server/SKILL.md b/plugins/mcp-server-dev/skills/build-mcp-server/SKILL.md index 5ab19c3a..d4e015fd 100644 --- a/plugins/mcp-server-dev/skills/build-mcp-server/SKILL.md +++ b/plugins/mcp-server-dev/skills/build-mcp-server/SKILL.md @@ -76,7 +76,7 @@ A hosted service speaking MCP over streamable HTTP. This is the **recommended pa If a tool just needs the user to confirm, pick an option, or fill a short form, **elicitation** does it with zero UI code. The server sends a flat JSON schema; the host renders a native form. Spec-native, no extra packages. -**Caveat:** Host support is new (Claude Code shipped it in v2.1.76; Desktop unconfirmed). The SDK throws if the client doesn't advertise the capability. Always check `clientCapabilities.elicitation` first and have a fallback — see `references/elicitation.md` for the canonical pattern. This is the right spec-correct approach; host coverage will catch up. +**Caveat:** Host support is new (Claude Code shipped it in v2.1.76; Desktop unconfirmed). The SDK rejects the call if the client doesn't advertise the capability. Always check the client's `elicitation` capability first and have a fallback — see `references/elicitation.md` for the canonical pattern. This is the right spec-correct approach; host coverage will catch up. Escalate to `build-mcp-app` widgets when you need: nested/complex data, scrollable/searchable lists, visual previews, live updates. @@ -149,11 +149,13 @@ Recommend one of these two. Others exist but these have the best MCP-spec covera | Framework | Language | Use when | |---|---|---| -| **Official TypeScript SDK** (`@modelcontextprotocol/sdk`) | TS/JS | Default choice. Best spec coverage, first to get new features. | +| **Official TypeScript SDK v2** (`@modelcontextprotocol/server`) | TS/JS | Default choice. Best spec coverage, first to get new features. | | **FastMCP 3.x** (`fastmcp` on PyPI) | Python | User prefers Python, or wrapping a Python library. Decorator-based, very low boilerplate. This is jlowin's package — not the frozen FastMCP 1.0 bundled in the official `mcp` SDK. | If the user already has a language/stack in mind, go with it — both produce identical wire protocol. +**Existing TypeScript project on `@modelcontextprotocol/sdk`?** That package is SDK v1, which now gets only bug and security fixes. Its imports, raw-shape schemas and `extra` handler argument differ from the v2 code in these references. Say so once, then stay on v1 unless the user wants to migrate: `npx @modelcontextprotocol/codemod@latest v1-to-v2 .` does most of it ([upgrade guide](https://ts.sdk.modelcontextprotocol.io/v2/migration/upgrade-to-v2)). + --- ## Phase 5 — Scaffold and hand off @@ -178,7 +180,7 @@ Tools are one of three server primitives. Most servers start with tools and neve | **Resources** | Host app (not Claude) | Exposing docs/files/data as browsable context | | **Prompts** | User (slash command) | Canned workflows ("/summarize-thread") | | **Elicitation** | Server, mid-tool | Asking user for input without building UI | -| **Sampling** | Server, mid-tool | Need LLM inference in your tool logic | +| **Sampling** (deprecated) | Server, mid-tool | Older hosts only — new servers call their LLM provider directly | → `references/resources-and-prompts.md`, `references/elicitation.md`, `references/server-capabilities.md` diff --git a/plugins/mcp-server-dev/skills/build-mcp-server/references/auth.md b/plugins/mcp-server-dev/skills/build-mcp-server/references/auth.md index 56fcefbb..07d381c5 100644 --- a/plugins/mcp-server-dev/skills/build-mcp-server/references/auth.md +++ b/plugins/mcp-server-dev/skills/build-mcp-server/references/auth.md @@ -76,7 +76,7 @@ Local stdio servers **can** do OAuth (open a browser, catch the redirect on a lo - Every user re-does the dance - No central token refresh or revocation -If OAuth is required, lean hard toward remote HTTP. If you *must* ship local + OAuth, the `@modelcontextprotocol/sdk` includes a localhost-redirect helper, and MCPB is the right packaging so at least the runtime is predictable. +If OAuth is required, lean hard toward remote HTTP. If you *must* ship local + OAuth, MCPB is the right packaging so at least the runtime is predictable. --- @@ -100,9 +100,12 @@ Validating "is this a valid bearer token" isn't enough. The spec requires valida ## SDK helpers — don't hand-roll -`@modelcontextprotocol/sdk/server/auth` ships: -- `mcpAuthRouter()` — Express router for the full OAuth AS surface (metadata, authorize, token) -- `bearerAuth` — middleware that validates bearer tokens against your verifier -- `proxyProvider` — forward auth to an upstream IdP +Your MCP server is an OAuth **resource server**: it verifies tokens, it doesn't issue them. `@modelcontextprotocol/express` ships: +- `requireBearerAuth({ verifier, requiredScopes, expectedResource })` — middleware that validates bearer tokens against your verifier. `expectedResource` is the audience check above. Your verifier must set `expiresAt`; tokens without it are rejected +- `mcpAuthMetadataRouter({ oauthMetadata, resourceServerUrl })` — serves the RFC 9728 protected-resource metadata that the `401` challenge points at + +On fetch-style hosts (Workers, Deno, Bun, Hono), `requireBearerAuth` from `@modelcontextprotocol/server` is the same gate without Express. The verified token reaches tool handlers as `ctx.http?.authInfo`. + +The v1 authorization-server helpers (`mcpAuthRouter`, `ProxyOAuthServerProvider`) are frozen in `@modelcontextprotocol/server-legacy/auth`. Use a dedicated identity provider for new servers. If you're wiring auth from scratch, check these first. diff --git a/plugins/mcp-server-dev/skills/build-mcp-server/references/deploy-cloudflare-workers.md b/plugins/mcp-server-dev/skills/build-mcp-server/references/deploy-cloudflare-workers.md index 2df110a0..5aa74d3e 100644 --- a/plugins/mcp-server-dev/skills/build-mcp-server/references/deploy-cloudflare-workers.md +++ b/plugins/mcp-server-dev/skills/build-mcp-server/references/deploy-cloudflare-workers.md @@ -14,78 +14,73 @@ npm create cloudflare@latest -- my-mcp-server \ cd my-mcp-server ``` -This pulls a minimal template with the right deps (`agents`, `zod`) and a working `wrangler.jsonc`. +This pulls a minimal template with the right deps (`@modelcontextprotocol/server`, `agents`, `zod`) and a working `wrangler.jsonc`. --- ## `src/index.ts` -Replace the template's calculator example with your tools. Use `registerTool()` (same API as the Express scaffold — the `McpServer` instance is identical): +Replace the template's calculator example with your tools. Use `registerTool()` (same API as the Express scaffold — the `McpServer` class is identical): ```typescript -import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; -import { McpAgent } from "agents/mcp"; +import { McpServer } from "@modelcontextprotocol/server"; +import { createMcpHandler } from "agents/mcp/server"; import { z } from "zod"; -export class MyMCP extends McpAgent { - server = new McpServer( +// Called once per request. Always build a new McpServer here. +function createServer() { + const server = new McpServer( { name: "my-service", version: "0.1.0" }, { instructions: "Prefer search_items before get_item — IDs aren't guessable." }, ); - async init() { - this.server.registerTool( - "search_items", - { - description: "Search items by keyword. Returns up to `limit` matches.", - inputSchema: { - query: z.string().describe("Search keywords"), - limit: z.number().int().min(1).max(50).default(10), - }, - annotations: { readOnlyHint: true }, - }, - async ({ query, limit }) => { - const results = await upstreamApi.search(query, limit); - return { content: [{ type: "text", text: JSON.stringify(results, null, 2) }] }; - }, - ); - } + server.registerTool( + "search_items", + { + description: "Search items by keyword. Returns up to `limit` matches.", + inputSchema: z.object({ + query: z.string().describe("Search keywords"), + limit: z.number().int().min(1).max(50).default(10), + }), + annotations: { readOnlyHint: true }, + }, + async ({ query, limit }) => { + const results = await upstreamApi.search(query, limit); + return { content: [{ type: "text", text: JSON.stringify(results, null, 2) }] }; + }, + ); + + return server; } +const handler = createMcpHandler(createServer); // serves /mcp + export default { fetch(request: Request, env: Env, ctx: ExecutionContext) { - const url = new URL(request.url); - if (url.pathname === "/mcp") { - return MyMCP.serve("/mcp").fetch(request, env, ctx); - } - return new Response("Not found", { status: 404 }); + return handler(request, env, ctx); }, -}; +} satisfies ExportedHandler<Env>; ``` -`McpAgent` is Cloudflare's wrapper — it handles the streamable-HTTP transport, session routing, and Durable Object plumbing. Your code only touches `this.server`, which is the same `McpServer` class from the SDK. Everything in `tool-design.md` and `server-capabilities.md` applies unchanged. +`createMcpHandler` from `agents/mcp/server` is Cloudflare's wrapper around the SDK's stateless handler — it adds the `/mcp` route, CORS, and Host/Origin checks. No sessions and no Durable Objects. Everything in `tool-design.md` and `server-capabilities.md` applies unchanged. + +Older versions of this template used `McpAgent` with a Durable Object binding and SDK v1. Don't mix the two: `McpAgent` takes a v1 `McpServer` from `@modelcontextprotocol/sdk`. --- ## `wrangler.jsonc` -The template ships this. The Durable Objects block is **boilerplate** — `McpAgent` uses DO for session state. You don't interact with it directly. +The template ships this. Nothing MCP-specific in it. ```jsonc { "name": "my-mcp-server", "main": "src/index.ts", - "compatibility_date": "2025-03-10", - "compatibility_flags": ["nodejs_compat"], - "migrations": [{ "new_sqlite_classes": ["MyMCP"], "tag": "v1" }], - "durable_objects": { - "bindings": [{ "class_name": "MyMCP", "name": "MCP_OBJECT" }] - } + "compatibility_date": "2026-07-02", + "compatibility_flags": ["nodejs_compat"] } ``` -If you rename the `MyMCP` class, update both `new_sqlite_classes` and `class_name` to match. - --- ## Run and deploy @@ -97,10 +92,10 @@ npx wrangler deploy # → https://my-mcp-server.<account>.workers.dev/mcp `wrangler deploy` prints the live URL. That's the URL users paste into Claude. -Secrets (upstream API keys): `npx wrangler secret put UPSTREAM_API_KEY`, then read `env.UPSTREAM_API_KEY` inside `init()`. +Secrets (upstream API keys): `npx wrangler secret put UPSTREAM_API_KEY`, then `import { env } from "cloudflare:workers"` and read `env.UPSTREAM_API_KEY`. --- ## OAuth -Cloudflare ships `@cloudflare/workers-oauth-provider` — a drop-in that handles the authorization server side (CIMD/DCR endpoints, token issuance, consent UI). It wraps your `McpAgent` and gates `/mcp` behind a token check. See `auth.md` for the protocol details; the CF template `cloudflare/ai/demos/remote-mcp-github-oauth` shows the wiring. +Cloudflare ships `@cloudflare/workers-oauth-provider` — a drop-in that handles the authorization server side (CIMD/DCR endpoints, token issuance, consent UI). It wraps your handler and gates `/mcp` behind a token check; `getMcpAuthContext()` from `agents/mcp/server` gives the factory the signed-in user's props. See `auth.md` for the protocol details; the CF template `cloudflare/ai/demos/remote-mcp-github-oauth` shows the wiring. diff --git a/plugins/mcp-server-dev/skills/build-mcp-server/references/elicitation.md b/plugins/mcp-server-dev/skills/build-mcp-server/references/elicitation.md index d1fede66..fd18883a 100644 --- a/plugins/mcp-server-dev/skills/build-mcp-server/references/elicitation.md +++ b/plugins/mcp-server-dev/skills/build-mcp-server/references/elicitation.md @@ -16,37 +16,62 @@ Host support is very recent: | Claude Desktop | Unconfirmed — likely not yet or very recent | | claude.ai | Unknown | -**The SDK throws `CapabilityNotSupported` if the client doesn't advertise elicitation.** There is no graceful degradation built in. You MUST check and have a fallback. +**The call fails if the client doesn't advertise elicitation.** The TypeScript SDK fails it — protocol error `-32021` on 2026-07-28 connections, an `isError` result on older ones; fastmcp throws `CapabilityNotSupported`. There is no graceful degradation built in. You MUST check and have a fallback. ### The canonical pattern ```typescript +import { + CLIENT_CAPABILITIES_META_KEY, acceptedContent, inputRequired, inputResponse, + type CallToolResult, type ClientCapabilities, type InputRequiredResult, type ServerContext, +} from "@modelcontextprotocol/server"; + +const confirmSchema = z.object({ confirm: z.boolean().meta({ title: "Confirm deletion" }) }); + +// 2026-07-28 requests carry the client's capabilities; older connections declare them once at initialize +function clientCapabilities(ctx: ServerContext): ClientCapabilities | undefined { + const perRequest = (ctx.mcpReq.envelope as Record<string, unknown> | undefined)?.[CLIENT_CAPABILITIES_META_KEY]; + return (perRequest as ClientCapabilities | undefined) ?? server.server.getClientCapabilities(); +} + server.registerTool("delete_all", { description: "Delete all items after confirmation", - inputSchema: {}, -}, async ({}, extra) => { - const caps = server.getClientCapabilities(); - if (caps?.elicitation) { - const r = await server.elicitInput({ - mode: "form", - message: "Delete all items? This cannot be undone.", - requestedSchema: { - type: "object", - properties: { confirm: { type: "boolean", title: "Confirm deletion" } }, - required: ["confirm"], + inputSchema: z.object({}), +}, async (_args, ctx): Promise<CallToolResult | InputRequiredResult> => { + if (!clientCapabilities(ctx)?.elicitation) { + // Fallback: return text asking Claude to relay the question + return { content: [{ type: "text", text: "Confirmation required. Please ask the user: 'Delete all items? This cannot be undone.' Then call this tool again with their answer." }] }; + } + + // The handler runs again once the user has answered, so read the answer first + const answer = inputResponse(ctx.mcpReq.inputResponses, "confirm"); + if (answer.kind === "elicit" && answer.action !== "accept") { + return { content: [{ type: "text", text: "Cancelled." }] }; + } + const confirmed = acceptedContent(ctx.mcpReq.inputResponses, "confirm", confirmSchema); + if (confirmed === undefined) { + return inputRequired({ + inputRequests: { + confirm: inputRequired.elicit({ + message: "Delete all items? This cannot be undone.", + requestedSchema: confirmSchema, + }), }, }); - if (r.action === "accept" && r.content?.confirm) { - await deleteAll(); - return { content: [{ type: "text", text: "Deleted." }] }; - } - return { content: [{ type: "text", text: "Cancelled." }] }; } - // Fallback: return text asking Claude to relay the question - return { content: [{ type: "text", text: "Confirmation required. Please ask the user: 'Delete all items? This cannot be undone.' Then call this tool again with their answer." }] }; + if (!confirmed.confirm) return { content: [{ type: "text", text: "Cancelled." }] }; + + await deleteAll(); + return { content: [{ type: "text", text: "Deleted." }] }; }); ``` +**How the TypeScript flow works:** the handler *returns* the question instead of awaiting it. The client asks the user and retries the call with the answer in `ctx.mcpReq.inputResponses`. Nothing survives between the two runs, so do no work with side effects before the answer is in. + +- One handler serves every client. On 2025-era connections the SDK sends a classic `elicitation/create` request for you and re-enters the handler with the answer. +- `ctx.mcpReq.elicitInput()` (v1's `server.elicitInput()`) works only on 2025-era connections and throws on 2026-07-28 ones. Don't use it in new code. +- A 2025-era client on a stateless HTTP server (`createMcpHandler`) has no channel for the question. The capability check comes back empty there, so the fallback runs. + ```python # fastmcp from fastmcp import Context @@ -89,7 +114,7 @@ If your data doesn't fit these constraints, that's the signal to escalate to a w Treat `decline` and `cancel` differently if it matters — `decline` is intentional, `cancel` might be accidental. -The TS SDK's `server.elicitInput()` auto-validates `accept` responses against your schema via Ajv. fastmcp's `ctx.elicit()` returns a typed discriminated union (`AcceptedElicitation[T] | DeclinedElicitation | CancelledElicitation`). +The TS SDK's `acceptedContent()` validates an `accept` response against the schema you pass it. fastmcp's `ctx.elicit()` returns a typed discriminated union (`AcceptedElicitation[T] | DeclinedElicitation | CancelledElicitation`). --- diff --git a/plugins/mcp-server-dev/skills/build-mcp-server/references/remote-http-scaffold.md b/plugins/mcp-server-dev/skills/build-mcp-server/references/remote-http-scaffold.md index 7a9afbb0..7905bcbf 100644 --- a/plugins/mcp-server-dev/skills/build-mcp-server/references/remote-http-scaffold.md +++ b/plugins/mcp-server-dev/skills/build-mcp-server/references/remote-http-scaffold.md @@ -4,77 +4,81 @@ Minimal working servers in both recommended frameworks. Start here, then add too --- -## TypeScript SDK (`@modelcontextprotocol/sdk`) +## TypeScript SDK v2 (`@modelcontextprotocol/server`) ```bash npm init -y -npm install @modelcontextprotocol/sdk zod express +npm pkg set type=module +npm install @modelcontextprotocol/server @modelcontextprotocol/express @modelcontextprotocol/node zod express npm install -D typescript @types/express @types/node tsx ``` **`src/server.ts`** ```typescript -import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; -import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; -import express from "express"; -import { z } from "zod"; - -const server = new McpServer( - { name: "my-service", version: "0.1.0" }, - { instructions: "Prefer search_items before calling get_item directly — IDs aren't guessable." }, -); - -// Pattern A: one tool per action -server.registerTool( - "search_items", - { - description: "Search items by keyword. Returns up to `limit` matches ranked by relevance.", - inputSchema: { - query: z.string().describe("Search keywords"), - limit: z.number().int().min(1).max(50).default(10), +import { createMcpExpressApp } from "@modelcontextprotocol/express"; +import { toNodeHandler } from "@modelcontextprotocol/node"; +import { McpServer, createMcpHandler } from "@modelcontextprotocol/server"; +import * as z from "zod/v4"; + +// Called once per HTTP request. Always build a new McpServer here: +// a shared instance fails as soon as two requests overlap. +function createServer(): McpServer { + const server = new McpServer( + { name: "my-service", version: "0.1.0" }, + { instructions: "Prefer search_items before calling get_item directly — IDs aren't guessable." }, + ); + + // Pattern A: one tool per action + server.registerTool( + "search_items", + { + description: "Search items by keyword. Returns up to `limit` matches ranked by relevance.", + inputSchema: z.object({ + query: z.string().describe("Search keywords"), + limit: z.number().int().min(1).max(50).default(10), + }), + annotations: { readOnlyHint: true }, }, - annotations: { readOnlyHint: true }, - }, - async ({ query, limit }, extra) => { - // extra.signal is an AbortSignal — check it in long loops for cancellation - const results = await upstreamApi.search(query, limit); - return { - content: [{ type: "text", text: JSON.stringify(results, null, 2) }], - }; - }, -); + async ({ query, limit }, ctx) => { + // ctx.mcpReq.signal is an AbortSignal — check it in long loops for cancellation + const results = await upstreamApi.search(query, limit); + return { + content: [{ type: "text", text: JSON.stringify(results, null, 2) }], + }; + }, + ); + + server.registerTool( + "get_item", + { + description: "Fetch a single item by its ID.", + inputSchema: z.object({ id: z.string() }), + annotations: { readOnlyHint: true }, + }, + async ({ id }) => { + const item = await upstreamApi.get(id); + return { content: [{ type: "text", text: JSON.stringify(item) }] }; + }, + ); -server.registerTool( - "get_item", - { - description: "Fetch a single item by its ID.", - inputSchema: { id: z.string() }, - annotations: { readOnlyHint: true }, - }, - async ({ id }) => { - const item = await upstreamApi.get(id); - return { content: [{ type: "text", text: JSON.stringify(item) }] }; - }, -); + return server; +} -// Streamable HTTP transport (stateless mode — simplest) -const app = express(); -app.use(express.json()); +// Local dev: accepts only localhost Host/Origin headers (DNS-rebinding protection). +// Deployed: createMcpExpressApp({ host: "0.0.0.0", allowedHosts: ["mcp.example.com"] }) +const app = createMcpExpressApp(); -app.post("/mcp", async (req, res) => { - const transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: undefined, // stateless - }); - res.on("close", () => transport.close()); - await server.connect(transport); - await transport.handleRequest(req, res, req.body); -}); +// Streamable HTTP, stateless +const handler = toNodeHandler(createMcpHandler(createServer)); +app.all("/mcp", (req, res) => void handler(req, res, req.body)); -app.listen(process.env.PORT ?? 3000); +app.listen(Number(process.env.PORT ?? 3000)); ``` -**Stateless vs stateful:** The snippet above creates a fresh transport per request (stateless). Fine for most API-wrapping servers. If tools need to share state across calls in a session (rare), use a session-keyed transport map — see the SDK's `examples/server/simpleStreamableHttp.ts`. +**Stateless by design:** `createMcpHandler` builds a fresh server per request and keeps no sessions, so it scales horizontally as-is. It serves clients on the 2026-07-28 protocol revision and older 2025-era clients from the same factory. Create API clients, pools and caches once at module scope and close over them. If tools need to share state across calls, key it on the authenticated user or an ID the tool returns — see the SDK's [sessions, state and scaling](https://ts.sdk.modelcontextprotocol.io/v2/serving/sessions-state-scaling) page. + +**Schemas are `z.object(...)`**, not raw `{ key: z.string() }` shapes, and Zod must be `^4.2.0`. --- @@ -123,7 +127,7 @@ server.registerTool( "search_actions", { description: "Find available actions matching an intent. Call this first to discover what's possible. Returns action IDs, descriptions, and parameter schemas.", - inputSchema: { intent: z.string().describe("What you want to do, in plain English") }, + inputSchema: z.object({ intent: z.string().describe("What you want to do, in plain English") }), annotations: { readOnlyHint: true }, }, async ({ intent }) => { @@ -136,10 +140,10 @@ server.registerTool( "execute_action", { description: "Execute an action by ID. Get the ID and params schema from search_actions first.", - inputSchema: { + inputSchema: z.object({ action_id: z.string(), - params: z.record(z.unknown()), - }, + params: z.record(z.string(), z.unknown()), + }), }, async ({ action_id, params }) => { const action = CATALOG.find(a => a.id === action_id); diff --git a/plugins/mcp-server-dev/skills/build-mcp-server/references/resources-and-prompts.md b/plugins/mcp-server-dev/skills/build-mcp-server/references/resources-and-prompts.md index 52749dd3..ca499ea0 100644 --- a/plugins/mcp-server-dev/skills/build-mcp-server/references/resources-and-prompts.md +++ b/plugins/mcp-server-dev/skills/build-mcp-server/references/resources-and-prompts.md @@ -30,7 +30,7 @@ A resource is data identified by a URI. Unlike a tool, it's not *called* — it' server.registerResource( "config", "config://app/settings", - { name: "App Settings", description: "Current configuration", mimeType: "application/json" }, + { title: "App Settings", description: "Current configuration", mimeType: "application/json" }, async (uri) => ({ contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify(config) }], }), @@ -50,14 +50,14 @@ def get_settings() -> str: RFC 6570 templates let one registration serve many URIs: ```typescript -import { ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { ResourceTemplate } from "@modelcontextprotocol/server"; server.registerResource( "file", new ResourceTemplate("file:///{path}", { list: undefined }), - { name: "File", description: "Read a file from the workspace" }, + { title: "File", description: "Read a file from the workspace" }, async (uri, { path }) => ({ - contents: [{ uri: uri.href, text: await fs.readFile(path, "utf8") }], + contents: [{ uri: uri.href, text: await fs.readFile(String(path), "utf8") }], }), ); ``` @@ -86,7 +86,7 @@ server.registerPrompt( { title: "Summarize document", description: "Generate a concise summary of the given text", - argsSchema: { text: z.string(), max_words: z.string().optional() }, + argsSchema: z.object({ text: z.string(), max_words: z.string().optional() }), }, ({ text, max_words }) => ({ messages: [{ diff --git a/plugins/mcp-server-dev/skills/build-mcp-server/references/server-capabilities.md b/plugins/mcp-server-dev/skills/build-mcp-server/references/server-capabilities.md index b797f054..fd01e00b 100644 --- a/plugins/mcp-server-dev/skills/build-mcp-server/references/server-capabilities.md +++ b/plugins/mcp-server-dev/skills/build-mcp-server/references/server-capabilities.md @@ -25,17 +25,24 @@ This is the highest-leverage one-liner in the spec. If Claude keeps misusing you ## Sampling — delegate LLM calls to the host -If your tool logic needs LLM inference (summarize, classify, generate), don't ship your own model client. Ask the host to do it. +> **Deprecated** as of protocol revision 2026-07-28 (SEP-2577). It keeps working during the deprecation window, but new servers should call their LLM provider's API directly. + +If your tool logic needs LLM inference (summarize, classify, generate), you can ask the host to do it. Same return-and-retry flow as `elicitation.md`: ```typescript // Inside a tool handler -const result = await extra.sendRequest({ - method: "sampling/createMessage", - params: { - messages: [{ role: "user", content: { type: "text", text: `Summarize: ${doc}` } }], - maxTokens: 500, - }, -}, CreateMessageResultSchema); +const summary = inputResponse(ctx.mcpReq.inputResponses, "summary"); +if (summary.kind !== "sampling") { + return inputRequired({ + inputRequests: { + summary: inputRequired.createMessage({ + messages: [{ role: "user", content: { type: "text", text: `Summarize: ${doc}` } }], + maxTokens: 500, + }), + }, + }); +} +// summary.result is the CreateMessageResult ``` ```python @@ -43,20 +50,23 @@ const result = await extra.sendRequest({ response = await ctx.sample("Summarize this document", context=doc) ``` -**Requires client support** — check `clientCapabilities.sampling` first. Model preference hints are substring-matched (`"claude-3-5"` matches any Claude 3.5 variant). +**Requires client support** — check the client's `sampling` capability first. Model preference hints are substring-matched (`"claude-3-5"` matches any Claude 3.5 variant). --- ## Roots — query workspace boundaries -Instead of hardcoding a root directory, ask the host which directories the user approved. +> **Deprecated** as of protocol revision 2026-07-28 (SEP-2577). Prefer a tool argument, a resource URI, or host configuration (MCPB `user_config`) for directories. + +Ask the host which directories the user approved: ```typescript -const caps = server.getClientCapabilities(); -if (caps?.roots) { - const { roots } = await server.server.listRoots(); - // roots: [{ uri: "file:///home/user/project", name: "My Project" }] +// Inside a tool handler +const answer = inputResponse(ctx.mcpReq.inputResponses, "roots"); +if (answer.kind !== "roots") { + return inputRequired({ inputRequests: { roots: inputRequired.listRoots() } }); } +// answer.roots: [{ uri: "file:///home/user/project", name: "My Project" }] ``` ```python @@ -69,14 +79,13 @@ Particularly relevant for MCPB local servers — see `build-mcpb/references/loca ## Logging — structured, level-aware -Better than stderr for remote servers. Client can filter by level. +> **Deprecated** as of protocol revision 2026-07-28 (SEP-2577). Log to stderr (stdio servers) or to your own observability stack instead. + +Client can filter by level. Declare `capabilities: { logging: {} }` in the `McpServer` options first. ```typescript // In a tool handler -await extra.sendNotification({ - method: "notifications/message", - params: { level: "info", logger: "my-tool", data: { msg: "Processing", count: 42 } }, -}); +await ctx.mcpReq.log("info", { msg: "Processing", count: 42 }, "my-tool"); ``` ```python @@ -92,11 +101,11 @@ Levels follow syslog: `debug`, `info`, `notice`, `warning`, `error`, `critical`, Client sends a `progressToken` in request `_meta`. Server emits progress notifications against it. ```typescript -async (args, extra) => { - const token = extra._meta?.progressToken; +async (args, ctx) => { + const token = ctx.mcpReq._meta?.progressToken; for (let i = 0; i < 100; i++) { if (token !== undefined) { - await extra.sendNotification({ + await ctx.mcpReq.notify({ method: "notifications/progress", params: { progressToken: token, progress: i, total: 100, message: `Step ${i}` }, }); @@ -122,9 +131,9 @@ async def long_task(ctx: Context) -> str: Long tools should check the SDK-provided `AbortSignal`: ```typescript -async (args, extra) => { +async (args, ctx) => { for (const item of items) { - if (extra.signal.aborted) throw new Error("Cancelled"); + if (ctx.mcpReq.signal.aborted) throw new Error("Cancelled"); await process(item); } } @@ -140,9 +149,9 @@ If you've registered prompts or resource templates with arguments, you can offer ```typescript server.registerPrompt("query", { - argsSchema: { + argsSchema: z.object({ table: completable(z.string(), async (partial) => tables.filter(t => t.startsWith(partial))), - }, + }), }, ...); ``` @@ -161,4 +170,4 @@ Low priority unless your prompts have many valid values. | Elicitation | — | `elicitation: {}` | return text, ask Claude to relay | | Roots | — | `roots: {}` | config env var | -Check client caps via `server.getClientCapabilities()` (TS) or `ctx.session.client_params.capabilities` (fastmcp) before using the bottom three. +Check client caps via the `clientCapabilities(ctx)` helper in `elicitation.md` (TS) or `ctx.session.client_params.capabilities` (fastmcp) before using the bottom three. diff --git a/plugins/mcp-server-dev/skills/build-mcp-server/references/tool-design.md b/plugins/mcp-server-dev/skills/build-mcp-server/references/tool-design.md index 8d4a4c54..1a8b8c76 100644 --- a/plugins/mcp-server-dev/skills/build-mcp-server/references/tool-design.md +++ b/plugins/mcp-server-dev/skills/build-mcp-server/references/tool-design.md @@ -137,7 +137,7 @@ Hints the host uses for UX — red confirm button for destructive, auto-approve ```typescript server.registerTool("delete_file", { description: "Delete a file", - inputSchema: { path: z.string() }, + inputSchema: z.object({ path: z.string() }), annotations: { destructiveHint: true, idempotentHint: false }, }, handler); ``` @@ -159,8 +159,8 @@ Pair with the read/write split advice in `build-mcpb/references/local-security.m ```typescript server.registerTool("get_weather", { description: "Get current weather", - inputSchema: { city: z.string() }, - outputSchema: { temp: z.number(), conditions: z.string() }, + inputSchema: z.object({ city: z.string() }), + outputSchema: z.object({ temp: z.number(), conditions: z.string() }), }, async ({ city }) => { const data = await fetchWeather(city); return { diff --git a/plugins/mcp-server-dev/skills/build-mcp-server/references/versions.md b/plugins/mcp-server-dev/skills/build-mcp-server/references/versions.md index 81e2110a..22d96176 100644 --- a/plugins/mcp-server-dev/skills/build-mcp-server/references/versions.md +++ b/plugins/mcp-server-dev/skills/build-mcp-server/references/versions.md @@ -4,17 +4,20 @@ Every version-sensitive claim in this skill, in one place. When updating the ski | Claim | Where stated | Last verified | |---|---|---| +| TypeScript SDK v2: `@modelcontextprotocol/server` 2.4.0, `/express` 2.0.2, `/node` 2.1.2, Zod `^4.2.0` | every TypeScript block in all three skills | 2026-10 | +| `@modelcontextprotocol/ext-apps` 2.x server helpers (peer: SDK v2) | `build-mcp-app/SKILL.md`, `build-mcp-app/references/widget-templates.md` | 2026-10 | | `@modelcontextprotocol/ext-apps@1.2.2` CDN pin | `build-mcp-app/SKILL.md`, `build-mcp-app/references/widget-templates.md` (4×) | 2026-03 | | Claude Code ≥2.1.76 for elicitation | `elicitation.md:15`, `build-mcp-server/SKILL.md:43,76` | 2026-03 | | MCP spec 2025-11-25 CIMD/DCR status | `auth.md:20,24,41` | 2026-03 | | MCPB manifest schema v0.4 | `build-mcpb/references/manifest-schema.md` | 2026-03 | -| CF `agents` SDK / `McpAgent` API | `deploy-cloudflare-workers.md` | 2026-03 | -| CF template path `cloudflare/ai/demos/remote-mcp-authless` | `deploy-cloudflare-workers.md` | 2026-03 | +| CF `agents/mcp/server` `createMcpHandler` API | `deploy-cloudflare-workers.md` | 2026-10 | +| CF template path `cloudflare/ai/demos/remote-mcp-authless` | `deploy-cloudflare-workers.md` | 2026-10 | ## How to verify ```bash -# ext-apps latest +# SDK and ext-apps latest +npm view @modelcontextprotocol/server version npm view @modelcontextprotocol/ext-apps version # CF template still exists diff --git a/plugins/mcp-server-dev/skills/build-mcpb/SKILL.md b/plugins/mcp-server-dev/skills/build-mcpb/SKILL.md index 772097dd..09212b1d 100644 --- a/plugins/mcp-server-dev/skills/build-mcpb/SKILL.md +++ b/plugins/mcp-server-dev/skills/build-mcpb/SKILL.md @@ -79,9 +79,9 @@ The host reads `manifest.json`, launches `server.mcp_config.command` as a **stdi The server itself is a standard stdio MCP server. Nothing MCPB-specific in the tool logic. ```typescript -import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; -import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; -import { z } from "zod"; +import { McpServer } from "@modelcontextprotocol/server"; +import { serveStdio } from "@modelcontextprotocol/server/stdio"; +import * as z from "zod/v4"; import { readFile, readdir } from "node:fs/promises"; import { join } from "node:path"; import { homedir } from "node:os"; @@ -89,42 +89,45 @@ import { homedir } from "node:os"; // ROOT_DIR comes from what you put in manifest's server.mcp_config.env — no auto-prefix const ROOT = (process.env.ROOT_DIR ?? join(homedir(), "Documents")); -const server = new McpServer({ name: "local-files", version: "0.1.0" }); - -server.registerTool( - "list_files", - { - description: "List files in a directory under the configured root.", - inputSchema: { path: z.string().default(".") }, - annotations: { readOnlyHint: true }, - }, - async ({ path }) => { - const entries = await readdir(join(ROOT, path), { withFileTypes: true }); - const list = entries.map(e => ({ name: e.name, dir: e.isDirectory() })); - return { content: [{ type: "text", text: JSON.stringify(list, null, 2) }] }; - }, -); - -server.registerTool( - "read_file", - { - description: "Read a file's contents. Path is relative to the configured root.", - inputSchema: { path: z.string() }, - annotations: { readOnlyHint: true }, - }, - async ({ path }) => { - const text = await readFile(join(ROOT, path), "utf8"); - return { content: [{ type: "text", text }] }; - }, -); +function createServer(): McpServer { + const server = new McpServer({ name: "local-files", version: "0.1.0" }); + + server.registerTool( + "list_files", + { + description: "List files in a directory under the configured root.", + inputSchema: z.object({ path: z.string().default(".") }), + annotations: { readOnlyHint: true }, + }, + async ({ path }) => { + const entries = await readdir(join(ROOT, path), { withFileTypes: true }); + const list = entries.map(e => ({ name: e.name, dir: e.isDirectory() })); + return { content: [{ type: "text", text: JSON.stringify(list, null, 2) }] }; + }, + ); + + server.registerTool( + "read_file", + { + description: "Read a file's contents. Path is relative to the configured root.", + inputSchema: z.object({ path: z.string() }), + annotations: { readOnlyHint: true }, + }, + async ({ path }) => { + const text = await readFile(join(ROOT, path), "utf8"); + return { content: [{ type: "text", text }] }; + }, + ); + + return server; +} -const transport = new StdioServerTransport(); -await server.connect(transport); +serveStdio(createServer); // never console.log — stdout carries the protocol ``` **Sandboxing is entirely your job.** There is no manifest-level sandbox — the process runs with full user privileges. Validate paths, refuse to escape `ROOT`, allowlist spawns. See `references/local-security.md`. -Before hardcoding `ROOT` from a config env var, check if the host supports `roots/list` — the spec-native way to get user-approved directories. See `references/local-security.md` for the pattern. +Take `ROOT` from a `user_config` directory picker rather than a hardcoded path. See `references/local-security.md`. --- diff --git a/plugins/mcp-server-dev/skills/build-mcpb/references/local-security.md b/plugins/mcp-server-dev/skills/build-mcpb/references/local-security.md index 6fd756f7..6a977bfb 100644 --- a/plugins/mcp-server-dev/skills/build-mcpb/references/local-security.md +++ b/plugins/mcp-server-dev/skills/build-mcpb/references/local-security.md @@ -41,25 +41,26 @@ def safe_join(root: Path, user_path: str) -> Path: --- -## Roots — ask the host, don't hardcode +## Allowed directories — let the user pick, don't hardcode -Before hardcoding `ROOT` from a config env var, check if the host supports `roots/list`. This is the spec-native way to get user-approved workspace boundaries. +Declare a `user_config` entry of `type: "directory"` in the manifest and pass it to the server through `mcp_config.env`. The host shows a native folder picker at install time, and the user can change it later. ```typescript -import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; - -const server = new McpServer({ name: "...", version: "..." }); - -let allowedRoots: string[] = []; -server.server.oninitialized = async () => { - const caps = server.getClientCapabilities(); - if (caps?.roots) { - const { roots } = await server.server.listRoots(); - allowedRoots = roots.map(r => new URL(r.uri).pathname); - } else { - allowedRoots = [process.env.ROOT_DIR ?? process.cwd()]; - } -}; +const allowedRoots = [process.env.ROOT_DIR ?? process.cwd()]; +``` + +**`roots/list` is deprecated** as of protocol revision 2026-07-28 (SEP-2577), so don't build on it. If you need it for an older host, ask inside a tool handler and keep the env var as the fallback: + +```typescript +import { inputRequired, inputResponse } from "@modelcontextprotocol/server"; + +// Inside a tool handler, after checking the client's `roots` capability +// (see the clientCapabilities(ctx) helper in build-mcp-server/references/elicitation.md) +const answer = inputResponse(ctx.mcpReq.inputResponses, "roots"); +if (answer.kind !== "roots") { + return inputRequired({ inputRequests: { roots: inputRequired.listRoots() } }); +} +const allowedRoots = answer.roots.map(r => fileURLToPath(r.uri)); ``` ```python @@ -72,7 +73,7 @@ async def my_tool(ctx: Context) -> str: allowed = [os.environ.get("ROOT_DIR", os.getcwd())] ``` -If roots are available, use them. If not, fall back to config. Either way, validate every path against the allowed set. +Either way, validate every path against the allowed set. --- |
