GitHub: modelcontextprotocol/typescript-sdk Stars: 12,700+ | Language: TypeScript (97.3%) | License: Apache 2.0 (新代码) / MIT (已有代码)最新版本: v1.29.0 (2026-03-30) | Commits: 1,514+官网: ts.sdk.modelcontextprotocol.io
目录
项目速览
功能概述
适用场景
快速上手
源码架构
实操 Demo
同类对比
参考资源
项目速览 MCP TypeScript SDK 是 Model Context Protocol 协议的官方 TypeScript/JavaScript 实现,由 Anthropic 维护。与 Python SDK 形成互补,它为 Node.js、Bun 和 Deno 三大运行时提供统一的 MCP 开发体验。项目采用 monorepo 架构,核心拆分为 @modelcontextprotocol/server 和 @modelcontextprotocol/client 两个独立包。
截至 2026 年 6 月,项目在 GitHub 上获得超过 12,700 颗 Star,累计 1,514 次提交。最新稳定版 v1.29.0 发布于 2026 年 3 月。SDK 的一大设计亮点是「Schema 无关」:工具和提示的输入验证不强制绑定任何验证库,而是采用 Standard Schema 接口规范,开发者可自由选择 Zod v4、Valibot、ArkType 等任何兼容库。
SDK 支持 Streamable HTTP (推荐)和 stdio 两种传输协议,并提供 Express、Hono 和原生 Node.js HTTP 三个薄中间件适配器。v2 pre-alpha 版本已在 main 分支上开发,v1.x 作为生产推荐分支,预计 2026 年 Q3 发布长期稳定版本。
功能概述 McpServer 核心 API McpServer 是构建 MCP 服务端的入口类,通过 registerTool、registerResource、registerPrompt 三个注册方法暴露能力:
import { McpServer } from '@modelcontextprotocol/server' ;import { StdioServerTransport } from '@modelcontextprotocol/server/stdio' ;import * as z from 'zod/v4' ;const server = new McpServer ({ name : 'greeting-server' , version : '1.0.0' }); server.registerTool ( 'greet' , { description : 'Greet someone by name' , inputSchema : z.object ({ name : z.string () }) }, async ({ name }) => ({ content : [{ type : 'text' , text : `Hello, ${name} !` }] }) ); async function main ( ) { const transport = new StdioServerTransport (); await server.connect (transport); } main ();
核心 API 清单:
API
类型
说明
new McpServer({ name, version })
构造函数
创建 MCP 服务端实例
server.registerTool(name, config, handler)
方法
注册工具,config 含 description、inputSchema
server.registerResource(name, uri, config, handler)
方法
注册资源
server.registerPrompt(name, config, handler)
方法
注册提示模板
server.connect(transport)
方法
连接到传输层
server.server.createMessage(params)
方法
LLM Sampling:服务端调用 LLM
Schema 无关验证 TypeScript SDK 不强制绑定 Zod,而是通过 Standard Schema 接口支持多种验证库:
import * as z from 'zod/v4' ;const schema = z.object ({ name : z.string (), age : z.number () });import * as v from 'valibot' ;const schema = v.object ({ name : v.string (), age : v.number () });import { type } from 'arktype' ;const schema = type ({ name : 'string' , age : 'number' });
SDK 内部从 zod/v4 导入并向后兼容 Zod v3.25+。
Sampling(服务端调用 LLM) McpServer 通过 server.server.createMessage() 支持服务端发起 LLM 调用,是构建 Agent 工具链的核心能力:
import { McpServer } from '@modelcontextprotocol/server' ;const mcpServer = new McpServer ({ name : 'tools-with-sample-server' , version : '1.0.0' }); mcpServer.registerTool ( 'summarize' , { description : 'Summarize any text using an LLM' , inputSchema : z.object ({ text : z.string ().describe ('Text to summarize' ) }) }, async ({ text }) => { const response = await mcpServer.server .createMessage ({ messages : [{ role : 'user' , content : { type : 'text' , text : `Please summarize the following text concisely:\n\n${text} ` } }], maxTokens : 500 }); return { content : [{ type : 'text' , text : response.content .type === 'text' ? response.content .text : 'Unable to generate summary' }] }; } );
传输协议支持
传输方式
包路径
说明
stdio
@modelcontextprotocol/server/stdio
标准输入输出,适合 Claude Desktop 等本地客户端
Streamable HTTP
内置于 server 包
推荐方式,支持完整的 HTTP 语义
中间件适配器 SDK 提供三个薄中间件包,将 MCP Server 无缝集成到主流 Node.js Web 框架:
包名
适配框架
核心能力
@modelcontextprotocol/node
Node.js 原生 HTTP
处理 IncomingMessage / ServerResponse
@modelcontextprotocol/express
Express
app 默认配置 + Host 头校验
@modelcontextprotocol/hono
Hono
app 默认配置 + JSON body 解析 + Host 头校验
OAuth 认证 Client 包内置 OAuth 2.1 helpers,服务端通过 jose 库实现 JWT 签名验证(auth-extensions.ts),支持动态客户端注册和 token 管理。
跨运行时支持 一套代码同时运行在 Node.js、Bun 和 Deno 上,无需修改。构建工具使用 tsx(TypeScript 执行器),包管理使用 pnpm workspace。
适用场景 Node.js 后端工具集成 将现有的 Node.js 业务逻辑(数据库查询、文件操作、API 调用)封装为 MCP 工具,供 Claude Code 等 AI 客户端调用。Express/Hono 中间件让已有 Web 服务零成本添加 MCP 能力。
前端工具链 通过 stdio 传输协议,将前端构建工具(ESLint、Prettier、TypeScript Compiler)包装为 MCP Server,让 AI 编程助手能直接调用类型检查、代码格式化等能力。
全栈 JavaScript 应用的 AI 集成 Next.js、Nuxt、SvelteKit 等全栈框架可通过 @modelcontextprotocol/express 或 @modelcontextprotocol/hono 中间件,将 API Routes 升级为 MCP 工具端点。
Agent 编排系统 利用 Sampling 能力构建可递归调用 LLM 的复合 Agent。TypeScript 的类型系统为复杂工具链提供编译期安全保障。
Browser Extension / Electron Deno/Bun 兼容性使 SDK 可在非 Node.js 环境运行,适合构建浏览器扩展或 Electron 桌面应用中的 MCP 能力。
快速上手 安装 npm install @modelcontextprotocol/sdk zod
注意:zod 是 peer dependency,推荐使用 Zod v4。
创建第一个 MCP Server mkdir mcp-demo && cd mcp-demonpm init -y npm install @modelcontextprotocol/sdk zod tsx
import { McpServer } from '@modelcontextprotocol/server' ;import { StdioServerTransport } from '@modelcontextprotocol/server/stdio' ;import * as z from 'zod/v4' ;const server = new McpServer ({ name : 'demo-server' , version : '1.0.0' }); server.registerTool ( 'add' , { description : 'Add two numbers' , inputSchema : z.object ({ a : z.number (), b : z.number () }) }, async ({ a, b }) => ({ content : [{ type : 'text' , text : `${a + b} ` }] }) ); async function main ( ) { const transport = new StdioServerTransport (); await server.connect (transport); console .error ('MCP Server running on stdio' ); } main ().catch (console .error );
启动服务 npx tsx src/examples/server/simpleStreamableHttp.ts npx tsx src/examples/client/simpleStreamableHttp.ts
配置 Claude Desktop { "mcpServers" : { "my-demo" : { "command" : "npx" , "args" : [ "tsx" , "/path/to/server.ts" ] } } }
源码架构 Monorepo 结构 packages/ ├── server/ # @modelcontextprotocol/server — 核心服务端 ├── client/ # @modelcontextprotocol/client — 核心客户端 ├── middleware/ # 框架中间件 │ ├── node/ # @modelcontextprotocol/node │ ├── express/ # @modelcontextprotocol/express │ └── hono/ # @modelcontextprotocol/hono ├── common/ # 共享类型与工具 └── .../ examples/ ├── server/ # 服务端示例(Streamable HTTP, SSE, OAuth 等) └── client/ # 客户端示例(交互式 CLI, 并行调用等) docs/ # 文档 test/ # 测试
核心设计模式 包分层 :Server 和 Client 完全独立,各自由专门团队(或贡献者)维护,降低耦合度。
Schema 抽象层 :通过 Standard Schema 接口将验证逻辑与 SDK 核心解耦,支持 Schema 库的即插即用。
中间件模式 :Express/Hono/Node 三个适配器采用一致的接口设计(app 默认配置 + 可选 Host 校验),保证不同框架下的开发体验一致。
双分支策略 :main 分支推进 v2 pre-alpha,v1.x 分支维护生产稳定版本,确保生态平稳过渡。
关键依赖
依赖
用途
zod (peer)
Schema 验证,内部从 zod/v4 导入
jose
JWT 签名/验证(OAuth 流程)
tsx
TypeScript 开发执行器
pnpm
Workspace 包管理
vitest
单元测试框架
changesets
版本管理和 changelog 生成
实操 Demo Demo 1: 天气查询 MCP Server (Express 挂载) import { McpServer } from '@modelcontextprotocol/server' ;import { express } from '@modelcontextprotocol/express' ;import * as z from 'zod/v4' ;import express from 'express' ;const mcpServer = new McpServer ({ name : 'weather-service' , version : '1.0.0' }); mcpServer.registerTool ( 'get_weather' , { description : 'Get current weather for a city' , inputSchema : z.object ({ city : z.string ().describe ('City name' ), unit : z.enum (['celsius' , 'fahrenheit' ]).default ('celsius' ) }) }, async ({ city, unit }) => { const temp = Math .round (Math .random () * 40 - 5 ); const conditions = ['sunny' , 'cloudy' , 'rainy' , 'partly cloudy' ]; const condition = conditions[Math .floor (Math .random () * conditions.length )]; return { content : [{ type : 'text' , text : `Weather in ${city} : ${temp} °${unit === 'celsius' ? 'C' : 'F' } , ${condition} ` }] }; } ); const app = express ();app.use ('/mcp' , express (mcpServer)); app.listen (3000 , () => { console .log ('MCP Weather Server running on http://localhost:3000/mcp' ); });
Demo 2: 文件系统工具 import { McpServer } from '@modelcontextprotocol/server' ;import { StdioServerTransport } from '@modelcontextprotocol/server/stdio' ;import * as z from 'zod/v4' ;import * as fs from 'node:fs/promises' ;import * as path from 'node:path' ;const server = new McpServer ({ name : 'filesystem-tools' , version : '1.0.0' }); server.registerTool ( 'read_file' , { description : 'Read contents of a file' , inputSchema : z.object ({ filepath : z.string ().describe ('Absolute path to the file' ) }) }, async ({ filepath }) => { const content = await fs.readFile (filepath, 'utf-8' ); return { content : [{ type : 'text' , text : content }] }; } ); server.registerTool ( 'list_directory' , { description : 'List files in a directory' , inputSchema : z.object ({ dirpath : z.string ().describe ('Absolute path to directory' ), pattern : z.string ().optional ().describe ('Glob pattern filter' ) }) }, async ({ dirpath, pattern }) => { const entries = await fs.readdir (dirpath, { withFileTypes : true }); const files = entries .filter (e => !pattern || e.name .includes (pattern)) .map (e => `${e.isDirectory() ? '[DIR]' : '[FILE]' } ${e.name} ` ); return { content : [{ type : 'text' , text : files.join ('\n' ) || 'No files found' }] }; } ); async function main ( ) { const transport = new StdioServerTransport (); await server.connect (transport); } main ().catch (console .error );
Demo 3: 带 Sampling 的文本分析工具 import { McpServer } from '@modelcontextprotocol/server' ;import { StdioServerTransport } from '@modelcontextprotocol/server/stdio' ;import * as z from 'zod/v4' ;const server = new McpServer ({ name : 'text-analyzer' , version : '1.0.0' }); server.registerTool ( 'analyze_sentiment' , { description : 'Analyze sentiment of text using LLM' , inputSchema : z.object ({ text : z.string ().describe ('Text to analyze' ) }) }, async ({ text }) => { const response = await server.server .createMessage ({ messages : [{ role : 'user' , content : { type : 'text' , text : `Analyze the sentiment (positive/negative/neutral) and provide a brief explanation for:\n\n${text} ` } }], maxTokens : 200 }); return { content : [{ type : 'text' , text : response.content .type === 'text' ? response.content .text : 'Analysis failed' }] }; } ); async function main ( ) { const transport = new StdioServerTransport (); await server.connect (transport); } main ().catch (console .error );
同类对比
维度
MCP TypeScript SDK
MCP Python SDK
LangChain Tools
协议标准化
MCP 标准协议
MCP 标准协议
LangChain 自定义格式
运行时
Node.js / Bun / Deno
CPython 3.10+
Python
Schema 验证
Zod/Valibot/ArkType(可选)
Pydantic/TypedDict(内置)
Pydantic
传输协议
stdio + Streamable HTTP
stdio + SSE + Streamable HTTP
仅函数调用
Web 框架集成
Express / Hono / Node 原生
Starlette / FastAPI Mount
LangServe
Sampling
内置 LLM 回叫能力
内置 LLM 回叫能力
通过 Chain 组合
生产就绪度
v1.x 稳定,Q3 2026 LTS
Beta 阶段快速迭代
成熟稳定
类型安全
TypeScript 原生类型系统
Python 类型提示
Python 类型提示
适合场景
Node.js 全栈/前端工具链
Python 数据/AI 工具链
复杂 LLM 工作流编排
参考资源