mcp-server
Server: high-level MCP SDK v2 servers with McpServer—capabilities, stdio/HTTP hosting, scaling, or packaging; low-level JSON-RPC and custom transports use mcp-protocol.
- License 许可
- MIT
- 最近更新
- 2026-11-15
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- mcp-server
- metadata
- { "category": "technique" }
- description
- Server: high-level MCP SDK v2 servers with McpServer—capabilities, stdio/HTTP hosting, scaling, or packaging; low-level JSON-RPC and custom transports use mcp-protocol.
- user-invocable
- false
03 SKILL.md 正文
MCP SDK v2 Servers
Cover @modelcontextprotocol/server SDK v2 (protocol revision 2026-07-28) on Node.js ≥ 20. Start new design with mcp-planning, then validate built server with mcp-test. Reference: https://ts.sdk.modelcontextprotocol.io/v2/
Minimal stdio stub (Step 5 has full transport picture):
serveStdio(() => {
const server = new McpServer({ name: 'app', version: '1.0.0' });
server.registerTool(
'hello',
{ inputSchema: z.object({ name: z.string() }) },
async ({ name }) => ({ content: [{ type: 'text', text: `Hi ${name}` }] }),
);
return server;
});
Steps
-
Configure module resolution: Use
"type": "module"with"NodeNext"resolutions for ESM projects. SDK v2 also resolves native CommonJSrequire()for CommonJS projects.- [ ] Project's ESM or CommonJS entrypoints resolve every MCP SDK import.
-
Initialize Server: instantiate
McpServerwith stable identifier, declare optional constructor behavior up front.const server = new McpServer( { name: 'catalog', version: '1.0.0' }, { capabilities: { logging: {}, resources: { subscribe: true } }, instructions: 'Call list-trips before book-trip.', enforceStrictCapabilities: true, cacheHints: { 'tools/list': { ttlMs: 60_000, cacheScope: 'public' } }, // SEP-2549 freshness hints for client caches }, );capabilities: { logging: {} }enables deprecated MCP logging subsystem (SEP-2577) — preferconsole.error(stderr) or OpenTelemetry for new servers.resources: { subscribe: true }not deprecated.- [ ]
name/versionstable identifiers, matchpackage.jsonexactly. - [ ] Optional constructor behavior (capabilities, instructions, enforceStrictCapabilities, cacheHints) declared wherever server relies on it.
- [ ]
-
Register Capabilities: register tools via
.registerTool(), dynamic resource templates via.registerResource(), prompts via.registerPrompt().inputSchema/outputSchema/argsSchemaaccept any Standard Schema (Zod v4 or ArkType as-is, Valibot viatoStandardJsonSchemafrom@valibot/to-json-schema, raw JSON Schema viafromJsonSchema()). Gateway/proxy and custom (vendor-prefixed) JSON-RPC methods: see mcp-protocol.server.registerTool( 'search', { description: 'Search catalog', inputSchema: z.object({ query: z.string().describe('Query'), limit: z.number().int().max(50).optional(), }), outputSchema: z.object({ names: z.array(z.string()) }), annotations: { readOnlyHint: true, idempotentHint: true }, }, async ({ query, limit }, ctx) => { const names = await lookupNames(query, { signal: ctx.mcpReq.signal }); // forward abort on client cancel/disconnect return { content: [{ type: 'text', text: names.join('\n') }], structuredContent: { names } }; }, ); server.registerResource( 'user-profile', new ResourceTemplate('users://{userId}/profile', { list: undefined, complete: { userId: async (v) => lookupIds(v) }, // argument completion for the URI's {userId} param }), { description: 'Profile', mimeType: 'application/json' }, async (uri, { userId }) => ({ contents: [{ uri: uri.href, text: JSON.stringify({ userId }) }], }), ); server.registerPrompt( 'review-code', { description: 'Review code', argsSchema: z.object({ code: z.string().describe('Code') }) }, ({ code }) => ({ messages: [{ role: 'user', content: { type: 'text', text: `Review:\n\n${code}` } }], }), );Wrap prompt
argsSchemafield incompletable(schema, async (value, ctx) => candidates)for argument completion —ctx?.argumentsexposes sibling arguments already filled, useful for dependent fields (e.g. filterbranchfield candidates by already-chosenrepo). Resource template URI variables complete through template'scompletemap instead (shown above).Gotcha — zod version pin: pin
zod ^4.2.0, import viaimport * as z from 'zod/v4'; self-converts via~standard.jsonSchema. Zod 3 typechecks clean under v2 peer range but fails only at runtime — registration swallows conversion failure, server starts and connects, firsttools/listerrors out offromJsonSchema(). Zod 4.0–4.1 lacks~standard.jsonSchema: bareimport { z } from 'zod'falls back to bundled Zod'sz.toJSONSchema()with one-time[mcp-sdk]warning and drops.describe()field descriptions — silent degradation, not failure. Namespaceimport * as z from 'zod/v4'works; namedimport { z } from 'zod/v4'fails compile (TS2769 No overload matches this call). Other schema libs (or older zod): usefromJsonSchema()from@modelcontextprotocol/server.- [ ] Each capability registered via matching
.registerTool()/.registerResource()/.registerPrompt()method with Standard Schema. - [ ] Resource template URIs resolved and boundary-checked against root before serving.
- [ ] Tool handlers return or throw business failures; SDK wraps ordinary exceptions into
{ isError: true }. - [ ] Every cancellable operation receives
ctx.mcpReq.signal; every identity-sensitive operation reads verifiedctx.http?.authInfo.
- [ ] Each capability registered via matching
-
Handle Errors: two channels, picked by audience.
Channel Shape Audience Produced by Tool error Result with isError: trueThe model — reads message, retries Tool handlers: return it, or throwanythingProtocol error JSON-RPC { code, message, data? }The caller's code Resource/prompt/completion callbacks: throw ProtocolError// Tool error — put the recovery hint in the text: return { content: [{ type: 'text', text: `No note "${id}". Known ids: ${ids.join(', ')}` }], isError: true, }; // Resource/prompt/completion callbacks: import { ProtocolError, ProtocolErrorCode, ResourceNotFoundError, } from '@modelcontextprotocol/server'; throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Note ids are lowercase, got "${id}"`); throw new ResourceNotFoundError(uri.href); // -32602 with data: { uri }Tool handlers cannot emit protocol error — every throw (even
ProtocolError) becomesisError: true; sole exceptionUrlElicitationRequiredError, which propagates (-32042). Full code tables in mcp-test.Gotcha — caller side: unknown or disabled tool name rejects
callTool()promise withProtocolError(InvalidParams)(-32602) — does not resolve{ isError: true }. Catch promise, inspecterror.code; registered tool's own business failure still returnsisError: true.- [ ] Tool handlers return or throw business failures; SDK emits their tool-error result.
- [ ] Resource, prompt, completion callbacks throw
ProtocolErroror subclass for caller-facing failures.
-
Serve & Secure a Transport: stdio for local/CLI use, HTTP for networked/hosted use.
-
stdio:
serveStdio(factory); JSON-RPC owns stdout, so diagnostics go toconsole.error().const handle = serveStdio(() => buildServer()); console.error('listening on stdio'); // stderr process.on('SIGINT', () => void handle.close()); -
HTTP:
createMcpHandler(factory, options)returns a web-standardhandler.fetch; the factory must build a fresh server per request.const handler = createMcpHandler(() => new McpServer({ name: 'notes', version: '1.0.0' }), { responseMode: 'json', // 'json' | 'sse' — 'json' never streams (drops mid-call notifications); 'sse' always streams. Omit to auto-upgrade to SSE when a notification precedes the result. legacy: 'stateless', // 'stateless' (default, serves 2025-era clients) | 'reject' });Mount on plain
node:httpviatoNodeHandler(handler)from@modelcontextprotocol/node, on a Web Standard runtime (Workers/Deno/Bun) by exportinghandler.fetchdirectly, or on a framework adapter below.handler.close()aborts in-flight exchanges. Auth is pass-through: verify the bearer token in front, thenhandler.fetch(request, { authInfo }). -
Host/Origin security (DNS-rebinding + CSRF): app factories (
createMcpExpressApp/createMcpFastifyApp/createMcpHonoApp) arm Host/Origin validation by default on localhost. Binding beyond localhost: pass{ host, allowedHosts, allowedOrigins }. A bare Web Standard runtime with no app factory gets no automatic protection — wire it in yourself:import { createMcpHandler, hostHeaderValidationResponse, originValidationResponse, } from '@modelcontextprotocol/server'; export default { async fetch(request: Request) { return ( hostHeaderValidationResponse(request, allowedHosts) ?? originValidationResponse(request, allowedOrigins) ?? handler.fetch(request) ); }, }; -
Framework adapters — one factory function per framework, same pattern:
import { createMcpExpressApp } from '@modelcontextprotocol/express'; import { toNodeHandler } from '@modelcontextprotocol/node'; const app = createMcpExpressApp(); const nodeHandler = toNodeHandler(handler); app.all('/mcp', (req, res) => void nodeHandler(req, res, req.body)); app.listen(3000, '127.0.0.1');Framework Install App factory Mount delta Express @modelcontextprotocol/server @modelcontextprotocol/express express @modelcontextprotocol/nodecreateMcpExpressApp()as above; also ships OAuth Resource Server helpers ( requireBearerAuth,mcpAuthMetadataRouter) — see mcp-authFastify @modelcontextprotocol/server @modelcontextprotocol/fastify @modelcontextprotocol/node fastifycreateMcpFastifyApp()app.all('/mcp', async (req, reply) => nodeHandler(req.raw, reply.raw, req.body))Hono @modelcontextprotocol/server @modelcontextprotocol/hono honocreateMcpHonoApp()app.all('/mcp', (c: Context) => handler.fetch(c.req.raw, { parsedBody: c.get('parsedBody') }))— annotatec: Contextexplicitly, else the compiler mis-narrows the key; runs on Node (@hono/node-server'sserve({ fetch: app.fetch })), Bun, Deno, and Cloudflare Workers -
Legacy (2025-era) clients:
createMcpHandler(factory, { legacy: 'stateless' })orserveStdio(factory, { legacy: 'serve' }). SSE is deprecated for migration-only use; its frozen v1 transport lives in@modelcontextprotocol/server-legacy/sse. Each era returns415for a POST whose parsedContent-Typediffers fromapplication/json. -
[ ] Stdio servers route every diagnostic to
console.error(). -
[ ] HTTP factories instantiate a fresh server per request.
-
[ ] A server bound beyond localhost, or on a bare runtime, has Host/Origin validation wired.
-
[ ] Public HTTP endpoints verify bearer tokens through mcp-auth.
-
-
Manage Sessions & Scale:
-
Stateless default: fresh instance per request, nothing held → any load balancer, no affinity.
-
Sessions (2025-era only): hand-wire
NodeStreamableHTTPServerTransportwithsessionIdGeneratorand aMap<sessionId, transport>. The 2026-07-28 revision is per-request — state lives inrequestState, not a session. -
Resumability: pass an
eventStore(storeEvent(streamId, message)/replayEventsAfter(lastEventId, { send })) so clients can reconnect viaLast-Event-ID. -
Cross-node notifications: implement a
ServerEventBus(publish/subscribe) over external pub/sub (e.g. Redis) and pass it in:createMcpHandler(factory, { bus: redisBus }). -
Notifications: most servers notify automatically via a registration handle (
update()/enable()/disable()/remove()). BehindcreateMcpHandler(stateless per-request), publish through the handler facade instead:handler.notify.resourceUpdated(uri),.toolsChanged(),.promptsChanged(),.resourcesChanged(). On stdio,server.send*routes directly onto the stdio stream. -
[ ] Cross-node deployments pass a shared
ServerEventBusso every node receives notifications. -
[ ] Stateless serving remains the default; 2025-era sessions use
NodeStreamableHTTPServerTransportwithsessionIdGenerator, while 2026-era state usesrequestState. -
[ ]
eventStorepassed when clients must reconnect viaLast-Event-ID.
-
-
Distribute: ship only after testing with mcp-test.
-
stdio via npm/npx: entry file's first line must be exactly
#!/usr/bin/env node;package.jsonneeds"type": "module"plus the standard npmbin/files/enginesfields. Pin the@modelcontextprotocol/*packages together with an exact version (no^) so the split packages never drift apart. Smoke-test the packed artifact before publishing:npm pack && npx @modelcontextprotocol/inspector npx -y ./example-mcp-0.1.0.tgz. -
HTTP: protect every public endpoint through mcp-auth.
-
Host registration (copy into the README):
App How to connect Claude Code claude mcp add example -- npx -y example-mcpVS Code .vscode/mcp.json:{ "servers": { "example": { "type": "stdio", "command": "npx", "args": ["-y", "example-mcp"] } } }Cursor .cursor/mcp.json:{ "mcpServers": { "example": { "command": "npx", "args": ["-y", "example-mcp"] } } } -
Versioning: changing what a tool requires is a breaking change — prefer adding optional fields; otherwise bump the major version.
-
[ ] Packed artifacts pass the inspector smoke test, public endpoints use mcp-auth, and host-registration instructions match the released package.
-
Handler Context (ctx)
Every handler receives context as its second argument:
| Member | Purpose |
|---|---|
ctx.mcpReq.signal |
AbortSignal — aborts on client cancel/disconnect; check in loops, forward to fetch |
ctx.mcpReq.id / ctx.mcpReq._meta |
JSON-RPC request id / request _meta (e.g. progressToken) |
ctx.mcpReq.notify(n) / ctx.mcpReq.log(level, data) |
Send notification / emit a notifications/message log from this handler |
ctx.mcpReq.elicitInput(params) |
Ask user mid-call (2025-era; throws on 2026-era) |
ctx.mcpReq.inputResponses / requestState() |
2026-era multi-round-trip surfaces |
ctx.sessionId |
Session id when transport has one |
ctx.http?.authInfo / ctx.http?.req |
Verified AuthInfo / inbound Request (HTTP only — undefined on stdio) |
Match each handler to the context members it needs; Step 3 verifies cancellation propagation and caller identity handling.
See Also
- Writing/running tests, inspector sessions: mcp-test
- Custom transports, gateways, raw wire messages: mcp-protocol
- OAuth/bearer-token wiring for HTTP servers: mcp-auth
04 同仓库更多 Skills
unslop
Use when writing or editing prose a person will read, or when text sounds AI-generated.
show-me
Use when asked to show, diagram, or walk through how code fits together or what a change does, or before explaining a multi-file flow in prose.
pr
Use when writing or updating a pull request description, or before running `gh pr create`.
commit
Use when writing a commit message, or before running `git commit`.
write-specs
Spec a feature's observable behavior. Use when asked for requirements, when a request says what the system should do but not how, or to capture what a built system already guarantees. Not for how to build it (write-plan).
write-skills
Write, fix, or audit a skill's frontmatter, trigger description, and body. Use when a skill is asked for, never fires, or fires at the wrong moment. Not for a hook (write-hooks) or the plugin manifest and catalog.