reference/node_mcp_server_v2.md · 24000
void nodeHandler(req, res, req.body));
- `expectedResource` accepts only tokens issued for this server, so a token meant for another service is refused
- The verified `AuthInfo` reaches the factory as `createMcpHandler(({ authInfo }) => ...)` and tool handlers as `ctx.http?.authInfo` (undefined on stdio)
- Serving OAuth discovery metadata and per-tool scopes are covered by the [oauth](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/oauth) and [scoped-tools](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/scoped-tools) examples and the [authorization docs](https://ts.sdk.modelcontextprotocol.io/v2/serving/authorization.md)
**Transport selection:** stdio for local tools a host launches as a subprocess; Streamable HTTP for remote services and multiple clients.
---
## Resources and Prompts
Resources expose read-only data at a URI that the client application reads and attaches as context. Prompts are message templates a user invokes by name. Tools are for anything the model should call, including operations with side effects.
```typescript
import { completable, ProtocolError, ProtocolErrorCode, ResourceNotFoundError, ResourceTemplate } from "@modelcontextprotocol/server";
// A resource at a fixed URI
server.registerResource(
"example-teams",
"example://teams",
{ title: "Teams", description: "Every team in the Example workspace", mimeType: "application/json" },
async (uri, ctx) => {
const teams = await apiRequest<unknown>("teams", {}, ctx.mcpReq.signal);
return { contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify(teams) }] };
}
);
// A URI template: the matched variables arrive as the second argument
server.registerResource(
"example-user",
new ResourceTemplate("example://users/{userId}", { list: undefined }),
{ title: "User profile", description: "One Example user by ID", mimeType: "application/json" },
async (uri, { userId }, ctx) => {
if (!/^U\d+$/.test(String(userId))) {
throw new ProtocolError(ProtocolErrorCode.InvalidParams, `User IDs look like U123, got "${userId}"`);
}
const user = await apiRequest<unknown>(`users/${userId}`, {}, ctx.mcpReq.signal).catch((error: unknown) => {
// Only a 404 means the resource is missing; a 401, 429, or timeout keeps its own error
if (error instanceof ApiError && error.status === 404) throw new ResourceNotFoundError(uri.href);
throw error;
});
return { contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify(user) }] };
}
);
// A prompt; completable() lets clients autocomplete the argument as the user types
const TEAMS = ["engineering", "marketing", "sales"];
server.registerPrompt(
"example_team_report",
{
title: "Team report",
description: "Summarize who is on a team",
argsSchema: z.object({
team: completable(z.string().describe("Team name"), value => TEAMS.filter(team => team.startsWith(value)))
})
},
async ({ team }) => ({
messages: [
{
role: "user",
content: { type: "text", text: `Use example_search_users to find everyone on the ${team} team, then summarize the team in a short table.` }
}
]
})
);
- Give a template a
listcallback that returns{ resources: [...] }to make its instances appear inresources/list;{ list: undefined }leaves them readable but unlisted - If a template variable becomes a filesystem path, resolve it with
realpathand reject anything outside your root before reading
Notifications
The handles returned by registerTool, registerResource, and registerPrompt send the matching list_changed notification when you change them:
const exportTool = server.registerTool(
"example_export_data",
{ description: "Export workspace data (export-enabled plans only)" },
async () => ({ content: [{ type: "text", text: "Export started" }] })
);
exportTool.disable(); // Sends notifications/tools/list_changed
exportTool.enable(); // So do enable(), update(), and remove()
Behind createMcpHandler each request has its own server instance, so publish changes through the handler instead: handler.notify.toolsChanged(), handler.notify.resourcesChanged(). Send notifications only when the server's capabilities actually change.
Verify Your Server
Write a self-check script that starts the built server, calls its tools as a client would, and exits non-zero on any failure. Run it after every change, along with npm run build; adapt the tool names and assertions to your server.
/**
* Self-check: starts the built server over stdio, calls its tools, and exits non-zero on any failure.
* Run with: npm run build && npm run smoke
*/
import { strict as assert } from "node:assert";
import { Client } from "@modelcontextprotocol/client";
import { getDefaultEnvironment, StdioClientTransport } from "@modelcontextprotocol/client/stdio";
const client = new Client({ name: "smoke-test", version: "1.0.0" });
await client.connect(
new StdioClientTransport({
command: "node",
args: ["dist/index.js"],
// The child gets only a safe default environment; pass the server's own variables explicitly
env: { ...getDefaultEnvironment(), EXAMPLE_API_KEY: process.env.EXAMPLE_API_KEY ?? "" }
})
);
const { tools } = await client.listTools();
assert.deepEqual(tools.map(tool => tool.name).sort(), ["example_get_user", "example_search_users"]);
const search = await client.callTool({
name: "example_search_users",
arguments: { query: "john", limit: 5, response_format: "json" }
});
assert.ok(!search.isError, `search failed: ${JSON.stringify(search.content)}`);
const page = search.structuredContent as { users: { id: string }[]; total: number };
assert.ok(Array.isArray(page.users), "search should return a users array");
if (page.users.length > 0) {
const user = await client.callTool({ name: "example_get_user", arguments: { user_id: page.users[0].id } });
assert.ok(!user.isError, `get_user failed: ${JSON.stringify(user.content)}`);
}
// Invalid arguments must come back as a tool error the model can read
const invalid = await client.callTool({ name: "example_search_users", arguments: { query: "j" } });
assert.equal(invalid.isError, true, "a one-character query should be rejected");
await client.close();
console.error("Smoke test passed");
- Call read-only tools with realistic arguments; check that one invalid input is rejected
StdioClientTransportgives the child process only a safe default environment (PATH,HOME, and similar), so pass API keys and other settings inenv- For an HTTP server, start it (
TRANSPORT=http npm start) and connect withnew StreamableHTTPClientTransport(new URL("http://127.0.0.1:3000/mcp"))from@modelcontextprotocol/clientinstead - For manual exploration,
npx @modelcontextprotocol/inspector node dist/index.jsopens an interactive UI - More test patterns, including in-process tests without a subprocess:
https://ts.sdk.modelcontextprotocol.io/v2/testing.md
More Features
Each linked example is a runnable server and client pair from the SDK repository:
| To... | See | |---|---| | Report progress, send log messages, and handle cancellation in long-running tools | streaming | | Ask the user for input mid-call (elicitation) | elicitation | | Notify subscribed clients when resources change | subscriptions | | Add OAuth login (authorization code flow) | oauth | | Accept machine-to-machine OAuth (client credentials) | oauth-client-credentials | | Require different scopes for different tools | scoped-tools | | Serve on Hono or another web-standard runtime | hono, bearer-auth-web | | Run sessionful 2025-era HTTP deployments | standalone-get, sse-polling | | See every server feature in one reference server | todos-server |
Migrating a v1 Server
To move an existing @modelcontextprotocol/sdk server to v2, run the official codemod at the package root, then fix what it marks:
npx @modelcontextprotocol/codemod@latest v1-to-v2 .
grep -rn '@mcp-codemod-error' . # Spots the codemod could not rewrite safely
npx tsc --noEmit
The codemod rewrites imports, package.json, registration calls, and handler context access. Check that zod ends up at ^4.2.0 or later, then run your formatter and tests. The full guide is at https://ts.sdk.modelcontextprotocol.io/v2/migration/upgrade-to-v2.md.
Quality Checklist
Tool Design
- [ ] Tools enable complete workflows, not just API endpoint wrappers
- [ ] Tool names are snake_case with a service prefix
- [ ] Every tool has a
title, adescriptionthat says when to use it, and correctannotations - [ ] Inputs are Zod object schemas with constraints and
.describe()text;z.strictObjectwhere unknown arguments should be rejected - [ ] List and search tools paginate with
limit/offsetand returnnext_offset - [ ] Responses stay under
CHARACTER_LIMITby returning fewer items - [ ] Results with
structuredContentalso include that data serialized as JSON text;outputSchemaonly on always-JSON tools - [ ] Error messages say what went wrong and how to recover
Implementation
- [ ]
createServer()returns a newMcpServeron every call, with everything registered inside it; shared clients live at module scope - [ ] Upstream requests pass
ctx.mcpReq.signaland have a timeout - [ ] Strict TypeScript; no
any; upstream data validated where it feedsstructuredContent - [ ] Nothing writes to stdout in a stdio server
- [ ] HTTP servers keep Host/Origin validation, and add bearer auth when exposed beyond localhost
Project
- [ ]
package.jsondepends on@modelcontextprotocol/server(not@modelcontextprotocol/sdk) andzod^4.2.0or later - [ ] No imports from
@modelcontextprotocol/sdk/...orzod/v3 - [ ]
binpoints atdist/index.js, andsrc/index.tsstarts with#!/usr/bin/env node
Verification
- [ ]
npm run buildcompletes without errors - [ ] The self-check script passes against the built server