mcp-server
How to build, bundle, register, and test a minimal stdio MCP (Model Context Protocol) server in Node.js with the official @modelcontextprotocol/sdk. Load this when implementing or modifying an MCP server (src/mcp-server.js, .mcp.json), when wrapping internal functions as MCP tools, when bundling the SDK with esbuild into a CJS artifact, or when the eventual Atlassian-MCP migration swaps the task-store backend. Triggers on @modelcontextprotocol/sdk, McpServer, StdioServerTransport, registerTool, InMemoryTransport, or ${CLAUDE_PROJECT_DIR} in an MCP context.
- License 许可
- MIT
- 最近更新
- 2026-10-10
- Stars
- ★ 1
- Forks
- 0
01 前言 Front Matter
- name
- mcp-server
- description
- How to build, bundle, register, and test a minimal stdio MCP (Model Context Protocol) server in Node.js with the official @modelcontextprotocol/sdk. Load this when implementing or modifying an MCP server (src/mcp-server.js, .mcp.json), when wrapping internal functions as MCP tools, when bundling the SDK with esbuild into a CJS artifact, or when the eventual Atlassian-MCP migration swaps the task-store backend. Triggers on @modelcontextprotocol/sdk, McpServer, StdioServerTransport, registerTool, InMemoryTransport, or ${CLAUDE_PROJECT_DIR} in an MCP context.
02 资源文件 3
- 参考文档references/esbuild-and-mcp-json.md5.3 KB
- 参考文档references/in-memory-test-harness.md5.9 KB
- 参考文档references/tool-contract.md12.6 KB
03 SKILL.md 正文
MCP Server (Node.js, stdio) — Team Training Skill
Build a minimal stdio MCP server with the official TypeScript/JS SDK, bundle it
with esbuild into a committed CJS artifact (same pattern as the other plugin
entrypoints), register it in a plugin .mcp.json, and test it deterministically
with the SDK's in-memory transport — no live client needed.
When to Use This Skill
Use when authoring or editing src/mcp-server.js / dist/mcp-server.cjs /
.mcp.json; when wrapping existing functions as MCP tools; when adding
@modelcontextprotocol/sdk to esbuild's bundle; when writing a round-trip MCP
test; or when migrating the task-store MCP surface to a Jira/Atlassian backend
(the tool names stay; only the wrapped functions change).
Core Facts (pinned)
- Package:
@modelcontextprotocol/sdk— add as a devDependency (esbuild inlines it intodist/mcp-server.cjs, exactly likeajv/gray-matter). - Version: pin a stable
1.x(latest stable line is1.29.x). Do not use2.0.0-alpha.*(that is whatmainon GitHub now is — alpha, unstable). - Peer dep:
zod(usezod@^3.25— the SDK's documented compatible range; the quickstart installszod@3). esbuild bundles it too, so devDependency. - Runtime: SDK
engines: node >=20. We targetnode20. ESM source, bundled to CJS by esbuild — supported. - Current tool API:
server.registerTool(name, config, handler)onMcpServer. This is the current recommended high-level API (NOT the low-levelsetRequestHandler(ListToolsRequestSchema/CallToolRequestSchema), and NOT the olderserver.tool(...)overload). - inputSchema is a raw zod shape object —
{ key: z.string() }— NOT az.object({...})wrapper. The SDK wraps it for you. Args arrive already validated and destructured:async ({ key }) => ....
Core Workflows
-
Imports + construct (exact specifiers — the
.jssuffixes are required):import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; import { z } from 'zod'; const server = new McpServer({ name: 'hivemind-tasks', version: '0.1.0' }); -
Register a tool — config is
{ title?, description, inputSchema }; handler returns acontentarray:server.registerTool( 'transition_status', { description: 'Set a task status (todo|in_progress|in_review|blocked|done).', inputSchema: { key: z.string().describe('Task key, e.g. TASK-026'), status: z.enum(['todo', 'in_progress', 'in_review', 'blocked', 'done']), }, }, async ({ key, status }) => { await transitionStatus({ repoRoot: REPO_ROOT, key, status }); return { content: [{ type: 'text', text: JSON.stringify({ ok: true }) }] }; }, ); -
Resolve the project root at runtime. Bind once at module load:
const REPO_ROOT = process.env.CLAUDE_PROJECT_DIR ?? process.cwd();.mcp.jsonsubstitutes${CLAUDE_PROJECT_DIR}into the server'senv, so the env var is present in the spawned process. NEVER useprocess.cwd()of the bundle,import.meta.url, or${CLAUDE_PLUGIN_ROOT}for project I/O — those point at the immutable plugin cache, not the user's repo. -
Connect + start.
connect()begins listening; there is no separatestart(). Log only to stderr (stdout carries JSON-RPC):async function main() { const transport = new StdioServerTransport(); await server.connect(transport); console.error('hivemind-tasks MCP server on stdio'); } main().catch((e) => { console.error(e); process.exit(1); }); -
Bundle with esbuild — add a third entry to
scripts/build-plugin.mjs(src/mcp-server.js→dist/mcp-server.cjs,format: 'cjs',platform: 'node',target: 'node20',bundle: true). Then add"dist/mcp-server.cjs"to.claude-plugin/shipped-bin.json'sbinarray. -
Register in
.mcp.jsonat the plugin root, pointing at the bundle:{ "mcpServers": { "hivemind-tasks": { "command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/dist/mcp-server.cjs"], "env": { "CLAUDE_PROJECT_DIR": "${CLAUDE_PROJECT_DIR}" } } } }Because the SDK is bundled into the
.cjs, NONODE_PATHis needed (this supersedes the §E.1 spike sketch that used${CLAUDE_PLUGIN_DATA}/node_modules— that was the data-dir approach P3 replaced with esbuild bundling). Re-add"mcpServers": "./.mcp.json"toplugin.jsonin the same change. -
Test deterministically with the in-memory transport — see
references/in-memory-test-harness.md.InMemoryTransport.createLinkedPair()returns[clientTransport, serverTransport]; connect yourMcpServerto one and aClientto the other and callclient.callTool(...)in-process.
Best Practices
- Do bundle the SDK + zod into the committed
dist/*.cjs— because a git-URL plugin install runs nonpm install; ESMimportignoresNODE_PATH. - Do keep tool names = Jira-compatible field names — because the Atlassian migration swaps the wrapped function, not the tool surface.
- Do return every result as
{ content: [{ type: 'text', text: <JSON string> }] }— because MCP content is text/typed blocks, not raw objects. Stringify. - Don't write to stdout (
console.log) — because it corrupts JSON-RPC. Useconsole.error(stderr). - Don't wrap
inputSchemainz.object(...)— because the high-level API expects the raw shape; wrapping double-wraps and breaks arg parsing. - Don't resolve project paths from the plugin location — because the plugin
ships to an immutable cache dir; only
${CLAUDE_PROJECT_DIR}is the user repo.
Common Pitfalls
ERR_PACKAGE_PATH_NOT_EXPORTED/ cannot find@modelcontextprotocol/server. The package is@modelcontextprotocol/sdkwith subpath exports (/server/mcp.js,/server/stdio.js,/client/index.js,/inMemory.js). The bare@modelcontextprotocol/serverspecifier does not exist — it is a doc-summary abbreviation. Always use the/sdk/...form with the.jssuffix.- Tool returns nothing / client sees empty. The handler must return an
object with a
contentarray. To signal failure, throw (the SDK converts it to{ isError: true }) or return{ isError: true, content: [...] }. get_taskhas no task-store function.task-store.jsexports nogetTask/readTask; implementget_taskby readingtasks/<key>.jsonunderREPO_ROOTand returning the parsed object (ornullwhen absent). See references for the exact wrapper map.- Alpha SDK.
npm i @modelcontextprotocol/sdk@latestmay pull a2.xalpha if the dist-tag drifts. Pin an explicit1.xsemver.
Verification
- Unit/round-trip:
npm test— the in-memory harness round-tripscreate_task → list_todos → transition_status → get_taskagainst a temp repo. - Bundle sanity:
node scripts/build-plugin.mjsthennode dist/mcp-server.cjsshould start and print the stderr banner (Ctrl-C to stop); a crash on start means a bundling miss (externals, dynamic require). - Install sanity:
claude plugin details hivemindmust reportMCP servers (1)with no startup error.
References
references/in-memory-test-harness.md— full vitest round-trip harness (Client + InMemoryTransport linked pair).references/tool-contract.md— the seven task-store tool→args→returns→wraps rows (list_todos,list_ready,get_task,create_task,transition_status,append_comment,close_task) plus the extension tools —kb_lookup(TASK-106),kb_graph_query(TASK-168),mcp_build_status(TASK-204) — and the exacttask-store.js/knowledge.jssignatures. (No tool count stated here on purpose, TASK-208 fix round — the table there is the live source of truth.)references/esbuild-and-mcp-json.md— esbuild bundling gotchas + the.mcp.jsoninterpolation rules.
Provenance
- Authored by: Researcher subagent on behalf of ticket
TASK-026. - Primary sources:
- https://modelcontextprotocol.io/docs/develop/build-server (TypeScript tab)
- https://github.com/modelcontextprotocol/typescript-sdk (README + src/inMemory.ts)
- https://www.npmjs.com/package/@modelcontextprotocol/sdk
- Last verified: 2026-05-29 (SDK stable 1.29.x; main is 2.0.0-alpha.0).
04 同仓库更多 Skills
unknown-skill
A demo skill with no license signal at all, used to exercise the "unknown" classification branch of the human license gate (TASK-135).
spoofed-license-skill
A demo skill used to test TASK-150's SPDX-header-vs-LICENSE-file conflict surfacing.
permissive-skill
A demo skill used to test assimilation of a permissively-licensed third party skill.
malicious-skill
A fixture skill deliberately carrying risky content patterns, used only to exercise src/skill-scan.js (TASK-122). Never assimilated for real.
copyleft-skill
A demo skill used to test the human license gate for a copyleft third party skill.
watch
Watch a video (URL or local path). Downloads with yt-dlp, extracts auto-scaled frames with ffmpeg, pulls the transcript from captions (or Whisper API fallback), and hands the result to Claude so it can answer questions about what's in the video. (assimilated for Hivemind)