[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7ABHWT573MDSJZ0VVW44E93":3,"skill-same:01M7ABHWT573MDSJZ0VVW44E93":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":26,"commitSha":27,"skillDirectory":28,"forksCount":14,"repositoryHtmlUrl":29,"repositoryHomepageUrl":30,"ownerHtmlUrl":31,"ownerBlogUrl":32,"ownerDescription":6,"updatedAt":33,"install":34,"resources":47},"01M7ABHWT573MDSJZ0VVW44E93","mcp-server",null,"Server: high-level MCP SDK v2 servers with McpServer—capabilities, stdio\u002FHTTP hosting, scaling, or packaging; low-level JSON-RPC and custom transports use mcp-protocol.","j0hanz\u002Fj0hanz-marketplace","j0hanz","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F159924955?v=4","01M7ABFK415CKHXYV9GZRJ16T7","Linus Johansson","01M7ABFK52FCPP2PNBH1YR7ZPA",0,"MIT","https:\u002F\u002Fgithub.com\u002Fj0hanz\u002Fj0hanz-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fmcp-hub\u002Fskills\u002Fmcp-server\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: mcp-server\ndescription: 'Server: high-level MCP SDK v2 servers with McpServer—capabilities, stdio\u002FHTTP hosting, scaling, or packaging; low-level JSON-RPC and custom transports use mcp-protocol.'\nuser-invocable: false\nmetadata:\n  category: technique\n---\n\n# MCP SDK v2 Servers\n\nCover `@modelcontextprotocol\u002Fserver` SDK v2 (protocol revision `2026-07-28`) on Node.js ≥ 20. Start new design with [mcp-planning](..\u002Fmcp-planning\u002FSKILL.md), then validate built server with [mcp-test](..\u002Fmcp-test\u002FSKILL.md). Reference: https:\u002F\u002Fts.sdk.modelcontextprotocol.io\u002Fv2\u002F\n\nMinimal stdio stub (Step 5 has full transport picture):\n\n```ts\nserveStdio(() => {\n  const server = new McpServer({ name: 'app', version: '1.0.0' });\n  server.registerTool(\n    'hello',\n    { inputSchema: z.object({ name: z.string() }) },\n    async ({ name }) => ({ content: [{ type: 'text', text: `Hi ${name}` }] }),\n  );\n  return server;\n});\n```\n\n## Steps\n\n1. **Configure module resolution**: Use `\"type\": \"module\"` with `\"NodeNext\"` resolutions for ESM projects. SDK v2 also resolves native CommonJS `require()` for CommonJS projects.\n\n   - [ ] Project's ESM or CommonJS entrypoints resolve every MCP SDK import.\n\n2. **Initialize Server**: instantiate `McpServer` with stable identifier, declare optional constructor behavior up front.\n\n   ```ts\n   const server = new McpServer(\n     { name: 'catalog', version: '1.0.0' },\n     {\n       capabilities: { logging: {}, resources: { subscribe: true } },\n       instructions: 'Call list-trips before book-trip.',\n       enforceStrictCapabilities: true,\n       cacheHints: { 'tools\u002Flist': { ttlMs: 60_000, cacheScope: 'public' } }, \u002F\u002F SEP-2549 freshness hints for client caches\n     },\n   );\n   ```\n\n   > `capabilities: { logging: {} }` enables **deprecated** MCP logging subsystem (SEP-2577) — prefer `console.error` (stderr) or OpenTelemetry for new servers. `resources: { subscribe: true }` not deprecated.\n   - [ ] `name`\u002F`version` stable identifiers, match `package.json` exactly.\n   - [ ] Optional constructor behavior (capabilities, instructions, enforceStrictCapabilities, cacheHints) declared wherever server relies on it.\n\n3. **Register Capabilities**: register tools via `.registerTool()`, dynamic resource templates via `.registerResource()`, prompts via `.registerPrompt()`. `inputSchema`\u002F`outputSchema`\u002F`argsSchema` accept any **Standard Schema** (Zod v4 or ArkType as-is, Valibot via `toStandardJsonSchema` from `@valibot\u002Fto-json-schema`, raw JSON Schema via `fromJsonSchema()`). Gateway\u002Fproxy and custom (vendor-prefixed) JSON-RPC methods: see [mcp-protocol](..\u002Fmcp-protocol\u002FSKILL.md).\n\n   ```ts\n   server.registerTool(\n     'search',\n     {\n       description: 'Search catalog',\n       inputSchema: z.object({\n         query: z.string().describe('Query'),\n         limit: z.number().int().max(50).optional(),\n       }),\n       outputSchema: z.object({ names: z.array(z.string()) }),\n       annotations: { readOnlyHint: true, idempotentHint: true },\n     },\n     async ({ query, limit }, ctx) => {\n       const names = await lookupNames(query, { signal: ctx.mcpReq.signal }); \u002F\u002F forward abort on client cancel\u002Fdisconnect\n       return { content: [{ type: 'text', text: names.join('\\n') }], structuredContent: { names } };\n     },\n   );\n\n   server.registerResource(\n     'user-profile',\n     new ResourceTemplate('users:\u002F\u002F{userId}\u002Fprofile', {\n       list: undefined,\n       complete: { userId: async (v) => lookupIds(v) }, \u002F\u002F argument completion for the URI's {userId} param\n     }),\n     { description: 'Profile', mimeType: 'application\u002Fjson' },\n     async (uri, { userId }) => ({\n       contents: [{ uri: uri.href, text: JSON.stringify({ userId }) }],\n     }),\n   );\n\n   server.registerPrompt(\n     'review-code',\n     { description: 'Review code', argsSchema: z.object({ code: z.string().describe('Code') }) },\n     ({ code }) => ({\n       messages: [{ role: 'user', content: { type: 'text', text: `Review:\\n\\n${code}` } }],\n     }),\n   );\n   ```\n\n   > Wrap **prompt `argsSchema`** field in `completable(schema, async (value, ctx) => candidates)` for argument completion — `ctx?.arguments` exposes sibling arguments already filled, useful for dependent fields (e.g. filter `branch` field candidates by already-chosen `repo`). Resource template URI variables complete through template's `complete` map instead (shown above).\n\n   > **Gotcha — zod version pin:** pin `zod ^4.2.0`, import via `import * as z from 'zod\u002Fv4'`; 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, first `tools\u002Flist` errors out of `fromJsonSchema()`. Zod 4.0–4.1 lacks `~standard.jsonSchema`: bare `import { z } from 'zod'` falls back to bundled Zod's `z.toJSONSchema()` with one-time `[mcp-sdk]` warning and **drops `.describe()` field descriptions** — silent degradation, not failure. Namespace `import * as z from 'zod\u002Fv4'` works; named `import { z } from 'zod\u002Fv4'` fails compile (`TS2769 No overload matches this call`). Other schema libs (or older zod): use `fromJsonSchema()` from `@modelcontextprotocol\u002Fserver`.\n   - [ ] Each capability registered via matching `.registerTool()` \u002F `.registerResource()` \u002F `.registerPrompt()` method with Standard Schema.\n   - [ ] Resource template URIs resolved and boundary-checked against root before serving.\n   - [ ] Tool handlers return or throw business failures; SDK wraps ordinary exceptions into `{ isError: true }`.\n   - [ ] Every cancellable operation receives `ctx.mcpReq.signal`; every identity-sensitive operation reads verified `ctx.http?.authInfo`.\n\n4. **Handle Errors**: two channels, picked by audience.\n\n   | Channel            | Shape                               | Audience                               | Produced by                                                 |\n   | ------------------ | ----------------------------------- | -------------------------------------- | ----------------------------------------------------------- |\n   | **Tool error**     | Result with `isError: true`         | The **model** — reads message, retries | Tool handlers: return it, or `throw` anything               |\n   | **Protocol error** | JSON-RPC `{ code, message, data? }` | The **caller's code**                  | Resource\u002Fprompt\u002Fcompletion callbacks: `throw ProtocolError` |\n\n   ```ts\n   \u002F\u002F Tool error — put the recovery hint in the text:\n   return {\n     content: [{ type: 'text', text: `No note \"${id}\". Known ids: ${ids.join(', ')}` }],\n     isError: true,\n   };\n\n   \u002F\u002F Resource\u002Fprompt\u002Fcompletion callbacks:\n   import {\n     ProtocolError,\n     ProtocolErrorCode,\n     ResourceNotFoundError,\n   } from '@modelcontextprotocol\u002Fserver';\n   throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Note ids are lowercase, got \"${id}\"`);\n   throw new ResourceNotFoundError(uri.href); \u002F\u002F -32602 with data: { uri }\n   ```\n\n   Tool handlers **cannot** emit protocol error — every throw (even `ProtocolError`) becomes `isError: true`; sole exception `UrlElicitationRequiredError`, which propagates (`-32042`). Full code tables in [mcp-test](..\u002Fmcp-test\u002FSKILL.md).\n\n   > **Gotcha — caller side:** unknown or disabled tool name rejects `callTool()` promise with `ProtocolError(InvalidParams)` (`-32602`) — does **not** resolve `{ isError: true }`. Catch promise, inspect `error.code`; registered tool's own business failure still returns `isError: true`.\n   - [ ] Tool handlers return or throw business failures; SDK emits their tool-error result.\n   - [ ] Resource, prompt, completion callbacks throw `ProtocolError` or subclass for caller-facing failures.\n\n5. **Serve & Secure a Transport**: stdio for local\u002FCLI use, HTTP for networked\u002Fhosted use.\n\n   - **stdio**: `serveStdio(factory)`; JSON-RPC owns stdout, so diagnostics go to `console.error()`.\n\n     ```ts\n     const handle = serveStdio(() => buildServer());\n     console.error('listening on stdio'); \u002F\u002F stderr\n     process.on('SIGINT', () => void handle.close());\n     ```\n\n   - **HTTP**: `createMcpHandler(factory, options)` returns a web-standard `handler.fetch`; the factory must build a fresh server per request.\n\n     ```ts\n     const handler = createMcpHandler(() => new McpServer({ name: 'notes', version: '1.0.0' }), {\n       responseMode: 'json', \u002F\u002F 'json' | 'sse' — 'json' never streams (drops mid-call notifications); 'sse' always streams. Omit to auto-upgrade to SSE when a notification precedes the result.\n       legacy: 'stateless', \u002F\u002F 'stateless' (default, serves 2025-era clients) | 'reject'\n     });\n     ```\n\n     Mount on plain `node:http` via `toNodeHandler(handler)` from `@modelcontextprotocol\u002Fnode`, on a Web Standard runtime (Workers\u002FDeno\u002FBun) by exporting `handler.fetch` directly, or on a framework adapter below. `handler.close()` aborts in-flight exchanges. Auth is pass-through: verify the bearer token in front, then `handler.fetch(request, { authInfo })`.\n\n   - **Host\u002FOrigin security** (DNS-rebinding + CSRF): app factories (`createMcpExpressApp`\u002F`createMcpFastifyApp`\u002F`createMcpHonoApp`) arm Host\u002FOrigin 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:\n\n     ```ts\n     import {\n       createMcpHandler,\n       hostHeaderValidationResponse,\n       originValidationResponse,\n     } from '@modelcontextprotocol\u002Fserver';\n     export default {\n       async fetch(request: Request) {\n         return (\n           hostHeaderValidationResponse(request, allowedHosts) ??\n           originValidationResponse(request, allowedOrigins) ??\n           handler.fetch(request)\n         );\n       },\n     };\n     ```\n\n   - **Framework adapters** — one factory function per framework, same pattern:\n\n     ```ts\n     import { createMcpExpressApp } from '@modelcontextprotocol\u002Fexpress';\n     import { toNodeHandler } from '@modelcontextprotocol\u002Fnode';\n\n     const app = createMcpExpressApp();\n     const nodeHandler = toNodeHandler(handler);\n     app.all('\u002Fmcp', (req, res) => void nodeHandler(req, res, req.body));\n     app.listen(3000, '127.0.0.1');\n     ```\n\n     | Framework | Install                                                                                         | App factory             | Mount delta                                                                                                                                                                                                                                                                       |\n     | --------- | ----------------------------------------------------------------------------------------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n     | Express   | `@modelcontextprotocol\u002Fserver @modelcontextprotocol\u002Fexpress express @modelcontextprotocol\u002Fnode` | `createMcpExpressApp()` | as above; also ships OAuth Resource Server helpers (`requireBearerAuth`, `mcpAuthMetadataRouter`) — see [mcp-auth](..\u002Fmcp-auth\u002FSKILL.md)                                                                                                                                          |\n     | Fastify   | `@modelcontextprotocol\u002Fserver @modelcontextprotocol\u002Ffastify @modelcontextprotocol\u002Fnode fastify` | `createMcpFastifyApp()` | `app.all('\u002Fmcp', async (req, reply) => nodeHandler(req.raw, reply.raw, req.body))`                                                                                                                                                                                                |\n     | Hono      | `@modelcontextprotocol\u002Fserver @modelcontextprotocol\u002Fhono hono`                                  | `createMcpHonoApp()`    | `app.all('\u002Fmcp', (c: Context) => handler.fetch(c.req.raw, { parsedBody: c.get('parsedBody') }))` — annotate `c: Context` explicitly, else the compiler mis-narrows the key; runs on Node (`@hono\u002Fnode-server`'s `serve({ fetch: app.fetch })`), Bun, Deno, and Cloudflare Workers |\n\n   - **Legacy (2025-era) clients**: `createMcpHandler(factory, { legacy: 'stateless' })` or `serveStdio(factory, { legacy: 'serve' })`. SSE is deprecated for migration-only use; its frozen v1 transport lives in `@modelcontextprotocol\u002Fserver-legacy\u002Fsse`. Each era returns `415` for a POST whose parsed `Content-Type` differs from `application\u002Fjson`.\n\n   - [ ] Stdio servers route every diagnostic to `console.error()`.\n   - [ ] HTTP factories instantiate a fresh server per request.\n   - [ ] A server bound beyond localhost, or on a bare runtime, has Host\u002FOrigin validation wired.\n   - [ ] Public HTTP endpoints verify bearer tokens through [mcp-auth](..\u002Fmcp-auth\u002FSKILL.md).\n\n6. **Manage Sessions & Scale**:\n\n   - **Stateless default**: fresh instance per request, nothing held → any load balancer, no affinity.\n   - **Sessions (2025-era only)**: hand-wire `NodeStreamableHTTPServerTransport` with `sessionIdGenerator` and a `Map\u003CsessionId, transport>`. The 2026-07-28 revision is per-request — state lives in `requestState`, not a session.\n   - **Resumability**: pass an `eventStore` (`storeEvent(streamId, message)` \u002F `replayEventsAfter(lastEventId, { send })`) so clients can reconnect via `Last-Event-ID`.\n   - **Cross-node notifications**: implement a `ServerEventBus` (`publish`\u002F`subscribe`) over external pub\u002Fsub (e.g. Redis) and pass it in: `createMcpHandler(factory, { bus: redisBus })`.\n   - **Notifications**: most servers notify automatically via a registration handle (`update()`\u002F`enable()`\u002F`disable()`\u002F`remove()`). Behind `createMcpHandler` (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.\n\n   - [ ] Cross-node deployments pass a shared `ServerEventBus` so every node receives notifications.\n   - [ ] Stateless serving remains the default; 2025-era sessions use `NodeStreamableHTTPServerTransport` with `sessionIdGenerator`, while 2026-era state uses `requestState`.\n   - [ ] `eventStore` passed when clients must reconnect via `Last-Event-ID`.\n\n7. **Distribute**: ship only after testing with [mcp-test](..\u002Fmcp-test\u002FSKILL.md).\n\n   - **stdio via npm\u002Fnpx**: entry file's first line must be exactly `#!\u002Fusr\u002Fbin\u002Fenv node`; `package.json` needs `\"type\": \"module\"` plus the standard npm `bin`\u002F`files`\u002F`engines` fields. Pin the `@modelcontextprotocol\u002F*` 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\u002Finspector npx -y .\u002Fexample-mcp-0.1.0.tgz`.\n   - **HTTP**: protect every public endpoint through [mcp-auth](..\u002Fmcp-auth\u002FSKILL.md).\n   - **Host registration** (copy into the README):\n\n     | App         | How to connect                                                                                                           |\n     | ----------- | ------------------------------------------------------------------------------------------------------------------------ |\n     | Claude Code | `claude mcp add example -- npx -y example-mcp`                                                                           |\n     | VS Code     | `.vscode\u002Fmcp.json`: `{ \"servers\": { \"example\": { \"type\": \"stdio\", \"command\": \"npx\", \"args\": [\"-y\", \"example-mcp\"] } } }` |\n     | Cursor      | `.cursor\u002Fmcp.json`: `{ \"mcpServers\": { \"example\": { \"command\": \"npx\", \"args\": [\"-y\", \"example-mcp\"] } } }`               |\n\n   - **Versioning**: changing what a tool requires is a breaking change — prefer adding optional fields; otherwise bump the major version.\n\n   - [ ] Packed artifacts pass the inspector smoke test, public endpoints use [mcp-auth](..\u002Fmcp-auth\u002FSKILL.md), and host-registration instructions match the released package.\n\n## Handler Context (`ctx`)\n\nEvery handler receives context as its second argument:\n\n| Member                                                 | Purpose                                                                                |\n| ------------------------------------------------------ | -------------------------------------------------------------------------------------- |\n| `ctx.mcpReq.signal`                                    | `AbortSignal` — aborts on client cancel\u002Fdisconnect; check in loops, forward to `fetch` |\n| `ctx.mcpReq.id` \u002F `ctx.mcpReq._meta`                   | JSON-RPC request id \u002F request `_meta` (e.g. `progressToken`)                           |\n| `ctx.mcpReq.notify(n)` \u002F `ctx.mcpReq.log(level, data)` | Send notification \u002F emit a `notifications\u002Fmessage` log from this handler               |\n| `ctx.mcpReq.elicitInput(params)`                       | Ask user mid-call (2025-era; throws on 2026-era)                                       |\n| `ctx.mcpReq.inputResponses` \u002F `requestState()`         | 2026-era multi-round-trip surfaces                                                     |\n| `ctx.sessionId`                                        | Session id when transport has one                                                      |\n| `ctx.http?.authInfo` \u002F `ctx.http?.req`                 | Verified `AuthInfo` \u002F inbound `Request` (HTTP only — `undefined` on stdio)             |\n\nMatch each handler to the context members it needs; Step 3 verifies cancellation propagation and caller identity handling.\n\n## See Also\n\n- Writing\u002Frunning tests, inspector sessions: [mcp-test](..\u002Fmcp-test\u002FSKILL.md)\n- Custom transports, gateways, raw wire messages: [mcp-protocol](..\u002Fmcp-protocol\u002FSKILL.md)\n- OAuth\u002Fbearer-token wiring for HTTP servers: [mcp-auth](..\u002Fmcp-auth\u002FSKILL.md)\n","# MCP SDK v2 Servers\n\nCover `@modelcontextprotocol\u002Fserver` SDK v2 (protocol revision `2026-07-28`) on Node.js ≥ 20. Start new design with [mcp-planning](..\u002Fmcp-planning\u002FSKILL.md), then validate built server with [mcp-test](..\u002Fmcp-test\u002FSKILL.md). Reference: https:\u002F\u002Fts.sdk.modelcontextprotocol.io\u002Fv2\u002F\n\nMinimal stdio stub (Step 5 has full transport picture):\n\n```ts\nserveStdio(() => {\n  const server = new McpServer({ name: 'app', version: '1.0.0' });\n  server.registerTool(\n    'hello',\n    { inputSchema: z.object({ name: z.string() }) },\n    async ({ name }) => ({ content: [{ type: 'text', text: `Hi ${name}` }] }),\n  );\n  return server;\n});\n```\n\n## Steps\n\n1. **Configure module resolution**: Use `\"type\": \"module\"` with `\"NodeNext\"` resolutions for ESM projects. SDK v2 also resolves native CommonJS `require()` for CommonJS projects.\n\n   - [ ] Project's ESM or CommonJS entrypoints resolve every MCP SDK import.\n\n2. **Initialize Server**: instantiate `McpServer` with stable identifier, declare optional constructor behavior up front.\n\n   ```ts\n   const server = new McpServer(\n     { name: 'catalog', version: '1.0.0' },\n     {\n       capabilities: { logging: {}, resources: { subscribe: true } },\n       instructions: 'Call list-trips before book-trip.',\n       enforceStrictCapabilities: true,\n       cacheHints: { 'tools\u002Flist': { ttlMs: 60_000, cacheScope: 'public' } }, \u002F\u002F SEP-2549 freshness hints for client caches\n     },\n   );\n   ```\n\n   > `capabilities: { logging: {} }` enables **deprecated** MCP logging subsystem (SEP-2577) — prefer `console.error` (stderr) or OpenTelemetry for new servers. `resources: { subscribe: true }` not deprecated.\n   - [ ] `name`\u002F`version` stable identifiers, match `package.json` exactly.\n   - [ ] Optional constructor behavior (capabilities, instructions, enforceStrictCapabilities, cacheHints) declared wherever server relies on it.\n\n3. **Register Capabilities**: register tools via `.registerTool()`, dynamic resource templates via `.registerResource()`, prompts via `.registerPrompt()`. `inputSchema`\u002F`outputSchema`\u002F`argsSchema` accept any **Standard Schema** (Zod v4 or ArkType as-is, Valibot via `toStandardJsonSchema` from `@valibot\u002Fto-json-schema`, raw JSON Schema via `fromJsonSchema()`). Gateway\u002Fproxy and custom (vendor-prefixed) JSON-RPC methods: see [mcp-protocol](..\u002Fmcp-protocol\u002FSKILL.md).\n\n   ```ts\n   server.registerTool(\n     'search',\n     {\n       description: 'Search catalog',\n       inputSchema: z.object({\n         query: z.string().describe('Query'),\n         limit: z.number().int().max(50).optional(),\n       }),\n       outputSchema: z.object({ names: z.array(z.string()) }),\n       annotations: { readOnlyHint: true, idempotentHint: true },\n     },\n     async ({ query, limit }, ctx) => {\n       const names = await lookupNames(query, { signal: ctx.mcpReq.signal }); \u002F\u002F forward abort on client cancel\u002Fdisconnect\n       return { content: [{ type: 'text', text: names.join('\\n') }], structuredContent: { names } };\n     },\n   );\n\n   server.registerResource(\n     'user-profile',\n     new ResourceTemplate('users:\u002F\u002F{userId}\u002Fprofile', {\n       list: undefined,\n       complete: { userId: async (v) => lookupIds(v) }, \u002F\u002F argument completion for the URI's {userId} param\n     }),\n     { description: 'Profile', mimeType: 'application\u002Fjson' },\n     async (uri, { userId }) => ({\n       contents: [{ uri: uri.href, text: JSON.stringify({ userId }) }],\n     }),\n   );\n\n   server.registerPrompt(\n     'review-code',\n     { description: 'Review code', argsSchema: z.object({ code: z.string().describe('Code') }) },\n     ({ code }) => ({\n       messages: [{ role: 'user', content: { type: 'text', text: `Review:\\n\\n${code}` } }],\n     }),\n   );\n   ```\n\n   > Wrap **prompt `argsSchema`** field in `completable(schema, async (value, ctx) => candidates)` for argument completion — `ctx?.arguments` exposes sibling arguments already filled, useful for dependent fields (e.g. filter `branch` field candidates by already-chosen `repo`). Resource template URI variables complete through template's `complete` map instead (shown above).\n\n   > **Gotcha — zod version pin:** pin `zod ^4.2.0`, import via `import * as z from 'zod\u002Fv4'`; 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, first `tools\u002Flist` errors out of `fromJsonSchema()`. Zod 4.0–4.1 lacks `~standard.jsonSchema`: bare `import { z } from 'zod'` falls back to bundled Zod's `z.toJSONSchema()` with one-time `[mcp-sdk]` warning and **drops `.describe()` field descriptions** — silent degradation, not failure. Namespace `import * as z from 'zod\u002Fv4'` works; named `import { z } from 'zod\u002Fv4'` fails compile (`TS2769 No overload matches this call`). Other schema libs (or older zod): use `fromJsonSchema()` from `@modelcontextprotocol\u002Fserver`.\n   - [ ] Each capability registered via matching `.registerTool()` \u002F `.registerResource()` \u002F `.registerPrompt()` method with Standard Schema.\n   - [ ] Resource template URIs resolved and boundary-checked against root before serving.\n   - [ ] Tool handlers return or throw business failures; SDK wraps ordinary exceptions into `{ isError: true }`.\n   - [ ] Every cancellable operation receives `ctx.mcpReq.signal`; every identity-sensitive operation reads verified `ctx.http?.authInfo`.\n\n4. **Handle Errors**: two channels, picked by audience.\n\n   | Channel            | Shape                               | Audience                               | Produced by                                                 |\n   | ------------------ | ----------------------------------- | -------------------------------------- | ----------------------------------------------------------- |\n   | **Tool error**     | Result with `isError: true`         | The **model** — reads message, retries | Tool handlers: return it, or `throw` anything               |\n   | **Protocol error** | JSON-RPC `{ code, message, data? }` | The **caller's code**                  | Resource\u002Fprompt\u002Fcompletion callbacks: `throw ProtocolError` |\n\n   ```ts\n   \u002F\u002F Tool error — put the recovery hint in the text:\n   return {\n     content: [{ type: 'text', text: `No note \"${id}\". Known ids: ${ids.join(', ')}` }],\n     isError: true,\n   };\n\n   \u002F\u002F Resource\u002Fprompt\u002Fcompletion callbacks:\n   import {\n     ProtocolError,\n     ProtocolErrorCode,\n     ResourceNotFoundError,\n   } from '@modelcontextprotocol\u002Fserver';\n   throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Note ids are lowercase, got \"${id}\"`);\n   throw new ResourceNotFoundError(uri.href); \u002F\u002F -32602 with data: { uri }\n   ```\n\n   Tool handlers **cannot** emit protocol error — every throw (even `ProtocolError`) becomes `isError: true`; sole exception `UrlElicitationRequiredError`, which propagates (`-32042`). Full code tables in [mcp-test](..\u002Fmcp-test\u002FSKILL.md).\n\n   > **Gotcha — caller side:** unknown or disabled tool name rejects `callTool()` promise with `ProtocolError(InvalidParams)` (`-32602`) — does **not** resolve `{ isError: true }`. Catch promise, inspect `error.code`; registered tool's own business failure still returns `isError: true`.\n   - [ ] Tool handlers return or throw business failures; SDK emits their tool-error result.\n   - [ ] Resource, prompt, completion callbacks throw `ProtocolError` or subclass for caller-facing failures.\n\n5. **Serve & Secure a Transport**: stdio for local\u002FCLI use, HTTP for networked\u002Fhosted use.\n\n   - **stdio**: `serveStdio(factory)`; JSON-RPC owns stdout, so diagnostics go to `console.error()`.\n\n     ```ts\n     const handle = serveStdio(() => buildServer());\n     console.error('listening on stdio'); \u002F\u002F stderr\n     process.on('SIGINT', () => void handle.close());\n     ```\n\n   - **HTTP**: `createMcpHandler(factory, options)` returns a web-standard `handler.fetch`; the factory must build a fresh server per request.\n\n     ```ts\n     const handler = createMcpHandler(() => new McpServer({ name: 'notes', version: '1.0.0' }), {\n       responseMode: 'json', \u002F\u002F 'json' | 'sse' — 'json' never streams (drops mid-call notifications); 'sse' always streams. Omit to auto-upgrade to SSE when a notification precedes the result.\n       legacy: 'stateless', \u002F\u002F 'stateless' (default, serves 2025-era clients) | 'reject'\n     });\n     ```\n\n     Mount on plain `node:http` via `toNodeHandler(handler)` from `@modelcontextprotocol\u002Fnode`, on a Web Standard runtime (Workers\u002FDeno\u002FBun) by exporting `handler.fetch` directly, or on a framework adapter below. `handler.close()` aborts in-flight exchanges. Auth is pass-through: verify the bearer token in front, then `handler.fetch(request, { authInfo })`.\n\n   - **Host\u002FOrigin security** (DNS-rebinding + CSRF): app factories (`createMcpExpressApp`\u002F`createMcpFastifyApp`\u002F`createMcpHonoApp`) arm Host\u002FOrigin 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:\n\n     ```ts\n     import {\n       createMcpHandler,\n       hostHeaderValidationResponse,\n       originValidationResponse,\n     } from '@modelcontextprotocol\u002Fserver';\n     export default {\n       async fetch(request: Request) {\n         return (\n           hostHeaderValidationResponse(request, allowedHosts) ??\n           originValidationResponse(request, allowedOrigins) ??\n           handler.fetch(request)\n         );\n       },\n     };\n     ```\n\n   - **Framework adapters** — one factory function per framework, same pattern:\n\n     ```ts\n     import { createMcpExpressApp } from '@modelcontextprotocol\u002Fexpress';\n     import { toNodeHandler } from '@modelcontextprotocol\u002Fnode';\n\n     const app = createMcpExpressApp();\n     const nodeHandler = toNodeHandler(handler);\n     app.all('\u002Fmcp', (req, res) => void nodeHandler(req, res, req.body));\n     app.listen(3000, '127.0.0.1');\n     ```\n\n     | Framework | Install                                                                                         | App factory             | Mount delta                                                                                                                                                                                                                                                                       |\n     | --------- | ----------------------------------------------------------------------------------------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n     | Express   | `@modelcontextprotocol\u002Fserver @modelcontextprotocol\u002Fexpress express @modelcontextprotocol\u002Fnode` | `createMcpExpressApp()` | as above; also ships OAuth Resource Server helpers (`requireBearerAuth`, `mcpAuthMetadataRouter`) — see [mcp-auth](..\u002Fmcp-auth\u002FSKILL.md)                                                                                                                                          |\n     | Fastify   | `@modelcontextprotocol\u002Fserver @modelcontextprotocol\u002Ffastify @modelcontextprotocol\u002Fnode fastify` | `createMcpFastifyApp()` | `app.all('\u002Fmcp', async (req, reply) => nodeHandler(req.raw, reply.raw, req.body))`                                                                                                                                                                                                |\n     | Hono      | `@modelcontextprotocol\u002Fserver @modelcontextprotocol\u002Fhono hono`                                  | `createMcpHonoApp()`    | `app.all('\u002Fmcp', (c: Context) => handler.fetch(c.req.raw, { parsedBody: c.get('parsedBody') }))` — annotate `c: Context` explicitly, else the compiler mis-narrows the key; runs on Node (`@hono\u002Fnode-server`'s `serve({ fetch: app.fetch })`), Bun, Deno, and Cloudflare Workers |\n\n   - **Legacy (2025-era) clients**: `createMcpHandler(factory, { legacy: 'stateless' })` or `serveStdio(factory, { legacy: 'serve' })`. SSE is deprecated for migration-only use; its frozen v1 transport lives in `@modelcontextprotocol\u002Fserver-legacy\u002Fsse`. Each era returns `415` for a POST whose parsed `Content-Type` differs from `application\u002Fjson`.\n\n   - [ ] Stdio servers route every diagnostic to `console.error()`.\n   - [ ] HTTP factories instantiate a fresh server per request.\n   - [ ] A server bound beyond localhost, or on a bare runtime, has Host\u002FOrigin validation wired.\n   - [ ] Public HTTP endpoints verify bearer tokens through [mcp-auth](..\u002Fmcp-auth\u002FSKILL.md).\n\n6. **Manage Sessions & Scale**:\n\n   - **Stateless default**: fresh instance per request, nothing held → any load balancer, no affinity.\n   - **Sessions (2025-era only)**: hand-wire `NodeStreamableHTTPServerTransport` with `sessionIdGenerator` and a `Map\u003CsessionId, transport>`. The 2026-07-28 revision is per-request — state lives in `requestState`, not a session.\n   - **Resumability**: pass an `eventStore` (`storeEvent(streamId, message)` \u002F `replayEventsAfter(lastEventId, { send })`) so clients can reconnect via `Last-Event-ID`.\n   - **Cross-node notifications**: implement a `ServerEventBus` (`publish`\u002F`subscribe`) over external pub\u002Fsub (e.g. Redis) and pass it in: `createMcpHandler(factory, { bus: redisBus })`.\n   - **Notifications**: most servers notify automatically via a registration handle (`update()`\u002F`enable()`\u002F`disable()`\u002F`remove()`). Behind `createMcpHandler` (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.\n\n   - [ ] Cross-node deployments pass a shared `ServerEventBus` so every node receives notifications.\n   - [ ] Stateless serving remains the default; 2025-era sessions use `NodeStreamableHTTPServerTransport` with `sessionIdGenerator`, while 2026-era state uses `requestState`.\n   - [ ] `eventStore` passed when clients must reconnect via `Last-Event-ID`.\n\n7. **Distribute**: ship only after testing with [mcp-test](..\u002Fmcp-test\u002FSKILL.md).\n\n   - **stdio via npm\u002Fnpx**: entry file's first line must be exactly `#!\u002Fusr\u002Fbin\u002Fenv node`; `package.json` needs `\"type\": \"module\"` plus the standard npm `bin`\u002F`files`\u002F`engines` fields. Pin the `@modelcontextprotocol\u002F*` 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\u002Finspector npx -y .\u002Fexample-mcp-0.1.0.tgz`.\n   - **HTTP**: protect every public endpoint through [mcp-auth](..\u002Fmcp-auth\u002FSKILL.md).\n   - **Host registration** (copy into the README):\n\n     | App         | How to connect                                                                                                           |\n     | ----------- | ------------------------------------------------------------------------------------------------------------------------ |\n     | Claude Code | `claude mcp add example -- npx -y example-mcp`                                                                           |\n     | VS Code     | `.vscode\u002Fmcp.json`: `{ \"servers\": { \"example\": { \"type\": \"stdio\", \"command\": \"npx\", \"args\": [\"-y\", \"example-mcp\"] } } }` |\n     | Cursor      | `.cursor\u002Fmcp.json`: `{ \"mcpServers\": { \"example\": { \"command\": \"npx\", \"args\": [\"-y\", \"example-mcp\"] } } }`               |\n\n   - **Versioning**: changing what a tool requires is a breaking change — prefer adding optional fields; otherwise bump the major version.\n\n   - [ ] Packed artifacts pass the inspector smoke test, public endpoints use [mcp-auth](..\u002Fmcp-auth\u002FSKILL.md), and host-registration instructions match the released package.\n\n## Handler Context (`ctx`)\n\nEvery handler receives context as its second argument:\n\n| Member                                                 | Purpose                                                                                |\n| ------------------------------------------------------ | -------------------------------------------------------------------------------------- |\n| `ctx.mcpReq.signal`                                    | `AbortSignal` — aborts on client cancel\u002Fdisconnect; check in loops, forward to `fetch` |\n| `ctx.mcpReq.id` \u002F `ctx.mcpReq._meta`                   | JSON-RPC request id \u002F request `_meta` (e.g. `progressToken`)                           |\n| `ctx.mcpReq.notify(n)` \u002F `ctx.mcpReq.log(level, data)` | Send notification \u002F emit a `notifications\u002Fmessage` log from this handler               |\n| `ctx.mcpReq.elicitInput(params)`                       | Ask user mid-call (2025-era; throws on 2026-era)                                       |\n| `ctx.mcpReq.inputResponses` \u002F `requestState()`         | 2026-era multi-round-trip surfaces                                                     |\n| `ctx.sessionId`                                        | Session id when transport has one                                                      |\n| `ctx.http?.authInfo` \u002F `ctx.http?.req`                 | Verified `AuthInfo` \u002F inbound `Request` (HTTP only — `undefined` on stdio)             |\n\nMatch each handler to the context members it needs; Step 3 verifies cancellation propagation and caller identity handling.\n\n## See Also\n\n- Writing\u002Frunning tests, inspector sessions: [mcp-test](..\u002Fmcp-test\u002FSKILL.md)\n- Custom transports, gateways, raw wire messages: [mcp-protocol](..\u002Fmcp-protocol\u002FSKILL.md)\n- OAuth\u002Fbearer-token wiring for HTTP servers: [mcp-auth](..\u002Fmcp-auth\u002FSKILL.md)\n",{"name":5,"metadata":24,"description":7,"user-invocable":20},{"category":25},"technique","main","534498267dccbe415f22f31fceac9da6771c195f","plugins\u002Fmcp-hub\u002Fskills\u002Fmcp-server","https:\u002F\u002Fgithub.com\u002Fj0hanz\u002Fj0hanz-marketplace","https:\u002F\u002Fj0hanz-marketplace.vercel.app","https:\u002F\u002Fgithub.com\u002Fj0hanz","linus-johansson-cv-d308be9b73e1.herokuapp.com","2026-11-15 02:42:07",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add j0hanz\u002Fj0hanz-marketplace --skill mcp-server",{"tool":40,"command":41},"bunx","bunx skills add j0hanz\u002Fj0hanz-marketplace --skill mcp-server",{"tool":43,"command":44},"pnpm","pnpm dlx skills add j0hanz\u002Fj0hanz-marketplace --skill mcp-server","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fj0hanz\u002Fj0hanz-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fmcp-hub\u002Fskills\u002Fmcp-server\u002FSKILL.md",true,[],[49,56,63,70,77,84],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M7ABP78JFYBMCXJ9GMETCYZM","unslop","Use when writing or editing prose a person will read, or when text sounds AI-generated.","https:\u002F\u002Fgithub.com\u002Fj0hanz\u002Fj0hanz-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fwriteup\u002Fskills\u002Funslop\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M7ABP52BNV7NRPNBR6PCNZWC","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.","https:\u002F\u002Fgithub.com\u002Fj0hanz\u002Fj0hanz-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fwriteup\u002Fskills\u002Fshow-me\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M7ABP3EPN4KFB4HPJNMY31NR","pr","Use when writing or updating a pull request description, or before running `gh pr create`.","https:\u002F\u002Fgithub.com\u002Fj0hanz\u002Fj0hanz-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fwriteup\u002Fskills\u002Fpr\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M7ABP08MXTHPZYTG4HKEP7WQ","commit","Use when writing a commit message, or before running `git commit`.","https:\u002F\u002Fgithub.com\u002Fj0hanz\u002Fj0hanz-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fwriteup\u002Fskills\u002Fcommit\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M7ABNV9J7DN1AFRBGDBHVBY2","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).","https:\u002F\u002Fgithub.com\u002Fj0hanz\u002Fj0hanz-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fworkbench\u002Fskills\u002Fwrite-specs\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M7ABNPK2GVG8EB3SSEAMK4FZ","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.","https:\u002F\u002Fgithub.com\u002Fj0hanz\u002Fj0hanz-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fworkbench\u002Fskills\u002Fwrite-skills\u002FSKILL.md",[],[]]