Communitygithub.com

MCP服务器构建模式

使用 Node/TypeScript SDK 构建 MCP 服务器,包括工具、资源、提示、Zod 验证以及 stdio 与 Streamable HTTP 传输。适用于构建或调试 MCP 服务器的场景。

MCP服务器构建模式 是什么?

本技能指导如何使用 Node/TypeScript 的 @modelcontextprotocol/sdk 包构建 MCP 服务器。它覆盖了 MCP 服务器的核心概念:工具(可调用操作)、资源(只读数据获取)和提示(可复用的提示模板),并解释了 stdio(本地客户端,如 Claude Desktop)和 Streamable HTTP(远程客户端,如 Cursor 或云端)两种传输方式的选择。技能强调使用 Zod 进行输入验证、遵循 Schema First 的最佳实践、处理错误以及确保工具的幂等性。由于官方 SDK 的 API 会随时间变化,建议开发者通过 Context7 查询“MCP”文档或查阅官方 MCP 文档来获取最新的方法名和签名。

兼容平台✓Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/mcp-server-patterns

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

MCP 服务器构建模式

模型上下文协议(MCP)允许 AI 助手调用你的服务器上的工具、读取资源以及使用提示。在构建或维护 MCP 服务器时使用本技能。SDK 的 API 会不断演进;请使用 Context7(查询文档中的 "MCP")或查阅官方 MCP 文档来获取当前的方法名和签名。

关于更广泛的路由决策(即某个能力应作为规则、技能、MCP 还是普通的 CLI/API 工作流),请参见 docs/capability-surface-selection.md。

何时使用

适用于:实现新的 MCP 服务器、添加工具或资源、选择 stdio 还是 HTTP 传输、升级 SDK,或调试 MCP 注册与传输问题。

工作原理

核心概念

  • 工具:模型可以调用的操作(例如搜索、运行命令)。根据 SDK 版本使用 registerTool() 或 tool() 注册。
  • 资源:模型可以获取的只读数据(例如文件内容、API 响应)。使用 registerResource() 或 resource() 注册。处理函数通常接收一个 uri 参数。
  • 提示:可复用的、参数化的提示模板,客户端可以将其呈现给用户(例如在 Claude Desktop 中)。使用 registerPrompt() 或等效方法注册。
  • 传输:本地客户端(如 Claude Desktop)使用 stdio;远程客户端(Cursor、云端)推荐使用 Streamable HTTP。传统的 HTTP/SSE 用于向后兼容。

Node/TypeScript SDK 可能暴露 tool() / resource() 或 registerTool() / registerResource();官方 SDK 会随时间变化。请始终对照当前的 MCP 文档 或 Context7 进行验证。

使用 stdio 连接

对于本地客户端,创建一个 stdio 传输并将其传递给服务器的 connect 方法。确切的 API 因 SDK 版本而异(例如构造函数 vs 工厂方法)。请参阅官方 MCP 文档或查询 Context7 中的 "MCP stdio server" 以获取当前模式。

保持服务器逻辑(工具 + 资源)与传输无关,这样你可以在入口点灵活地插入 stdio 或 HTTP。

远程连接(Streamable HTTP)

对于 Cursor、云端或其他远程客户端,请使用 Streamable HTTP(根据当前规范,单个 MCP HTTP 端点)。仅当需要向后兼容时才支持传统的 HTTP/SSE。

示例

安装与服务器设置

npm install @modelcontextprotocol/sdk zod
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";

const server = new McpServer({ name: "my-server", version: "1.0.0" });

根据你的 SDK 版本使用相应的 API 注册工具和资源:某些版本使用 server.tool(name, description, schema, handler)(位置参数),其他版本使用 server.tool({ name, description, inputSchema }, handler) 或 registerTool()。资源同理——如果 API 提供了 uri,则在处理函数中包含它。为了避免复制粘贴错误,请查阅官方 MCP 文档或 Context7 以获取当前 @modelcontextprotocol/sdk 的签名。

使用 Zod(或 SDK 首选的模式格式)进行输入验证。

最佳实践

  • 模式优先:为每个工具定义输入模式;记录参数和返回形状。
  • 错误处理:返回模型可以解释的结构化错误或消息;避免暴露原始堆栈跟踪。
  • 幂等性:尽可能设计幂等的工具,确保重试是安全的。
  • 速率与成本:对于调用外部 API 的工具,考虑速率限制和成本;在工具描述中加以说明。
  • 版本管理:在 package.json 中固定 SDK 版本;升级时检查发行说明。

官方 SDK 与文档

  • JavaScript/TypeScript:@modelcontextprotocol/sdk(npm)。使用 Context7 并设置库名为 "MCP" 以获取当前的注册和传输模式。
  • Go:GitHub 上的官方 Go SDK(modelcontextprotocol/go-sdk)。
  • C#:用于 .NET 的官方 C# SDK。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

相关技能