☰
mcp-for-beginners 实战:使用 TypeScript 与官方 SDK 构建可扩展的 MCP Server 示例
2026/10/8 18:44:34 网站建设 项目流程
  • 教程
  • 文档
  • 人工智能

【免费下载链接】mcp-for-beginners

This open-source curriculum introduces the fundamentals of Model Context Protocol (MCP) through real-world, cross-language examples in .NET, Java, TypeScript, JavaScript, Rust and Python. Designed for developers, it focuses on practical techniques for building modular, scalable, and secure AI workflows from session setup to service orchestration.

项目地址:https://gitcode.com/GitHub_Trending/mc/mcp-for-beginners
点击查看免费下载

本文围绕 mcp-for-beginners 仓库中 04-PracticalImplementation/samples/typescript 的 TypeScript MCP Server 示例展开,结合其完整源码,讲解如何用@modelcontextprotocol/sdk与 Zod 定义类型安全的 Tool 和 Resource,并通过 stdio 传输启动服务。读完本文,你将掌握 MCP Server 在 TypeScript 下的工程结构、工具注册、资源暴露、事件埋点与本地运行验证的全套方法。

示例概览:一个 TypeScript 版 MCP Server

该示例位于仓库的 04-PracticalImplementation/samples/typescript 目录,是第四章「Practical Implementation」中按语言组织的多语言示例之一(另有 C#、Java with Spring、JavaScript、Python 版本,见 04-PracticalImplementation/README.md)。示例通过官方 TypeScript SDK 实现了一个完整的 MCP Server,主要包含两类核心能力:

  • Tool(工具):一个名为completion的补全工具,接收model、prompt与可选options参数,返回模拟的 LLM 补全结果;
  • Resource(资源):一个名为search的资源,使用ResourceTemplate暴露test://{query}形式的动态资源地址,返回模拟搜索结果。

整个示例以「先 mock、后接入真实模型」的渐进思路编写,非常适合作为学习 MCP Server 的第一个 TypeScript 参考实现。

工程结构解析

示例的完整文件结构如下(均在仓库根目录下):

04-PracticalImplementation/samples/typescript/ ├── src/ │ └── index.ts # 服务端核心实现 ├── README.md # 示例说明文档 ├── package.json # 依赖与脚本定义 ├── package-lock.json # 依赖锁定文件 └── tsconfig.json # TypeScript 编译配置

依赖清单(package.json)

查看 package.json 可以看到示例的关键依赖:

{ "name": "tutorial-mcp", "version": "1.0.0", "type": "module", "scripts": { "start": "tsc && node ./build/index.js", "build": "tsc && node ./build/index.js" }, "dependencies": { "@modelcontextprotocol/sdk": "^1.26.0", "openai": "^4.95.0", "zod": "^3.24.2" }, "devDependencies": { "@types/node": "^22.13.17", "typescript": "^5.8.2" } }

这里有三点值得注意:

  • @modelcontextprotocol/sdk(^1.26.0)是 MCP 官方 TypeScript SDK,提供McpServer、StdioServerTransport、ResourceTemplate等核心构件;
  • zod(^3.24.2)用于声明工具参数的运行时校验 Schema——这是 MCP TypeScript 生态的标准做法;
  • openai(^4.95.0)已作为依赖声明,对应源码中「真实实现中应调用 AI 模型」的演进方向,示例当前以 mock 响应代替真实调用。

编译配置(tsconfig.json)

tsconfig.json 采用 ES2022 目标与 Node16 模块解析,rootDir指向./src,编译产物输出到./build,并开启了strict严格模式。由于package.json中声明了"type": "module",源码使用 ESM 风格的import语法。

用 Zod 注册类型安全的 completion 工具

示例文档 04-PracticalImplementation/samples/typescript/README.md 给出了工具注册的核心片段,即通过this.mcpServer.tool(...)注册completion工具:

this.mcpServer.tool( 'completion', { model: z.string(), prompt: z.string(), options: z.object({ temperature: z.number().optional(), max_tokens: z.number().optional(), stream: z.boolean().optional() }).optional() }, async ({ model, prompt, options }) => { console.log(`Processing completion request for model: ${model}`); // Validate model if (!this.models.includes(model)) { throw new Error(`Model ${model} not supported`); } // Emit event for monitoring/metrics this.events.emit('request', { type: 'completion', model, timestamp: new Date() }); // In a real implementation, this would call an AI model // Here we just echo back parts of the request with a mock response const response = { id: `mcp-resp-${Date.now()}`, model, text: `This is a response to: ${prompt.substring(0, 30)}...`, usage: { promptTokens: prompt.split(' ').length, completionTokens: 20, totalTokens: prompt.split(' ').length + 20 } }; // Simulate network delay await new Promise(resolve => setTimeout(resolve, 500)); // Emit completion event this.events.emit('completion', { model, timestamp: new Date() }); return { content: [ { type: 'text', text: JSON.stringify(response) } ] }; } );

参数 Schema 与 MCP 类型映射

mcpServer.tool()的第二个参数使用 Zod Schema 描述工具入参,SDK 会自动将其转换为 MCP 协议要求的 JSON Schema:

参数类型是否必填说明
modelz.string()必填目标模型名称,需在服务端支持列表中
promptz.string()必填用户输入提示词
options.temperaturez.number()可选采样温度
options.max_tokensz.number()可选最大生成 token 数
options.streamz.boolean()可选是否流式返回

处理函数的关键设计

从源码(src/index.ts)可以看到处理函数内部的三段式逻辑,这也是生产级 MCP 工具可复用的骨架:

  1. 模型校验:if (!this.models.includes(model))抛错拒绝不支持的模型,保证失败快速暴露;
  2. 事件埋点:通过 Node 内置EventEmitter分别发出request与completion事件,为监控/指标采集预留接口;
  3. 返回 MCP 标准内容块:返回值遵循 MCP 的content数组约定,此处使用type: 'text'的文本内容块,将 mock 响应以JSON.stringify形式返回。模拟的 500ms 网络延迟则对应真实场景中调用远端模型的开销。

源码纵深:ExtendedMcpServer 类的完整实现

示例文档只展示了工具注册片段,而其完整实现位于 src/index.ts。源码将能力封装为ExtendedMcpServer类,构造函数接受{ serverName?, version?, models? }三个可选配置项,并完成三件事:

  • 用new McpServer({ name, version })创建核心 MCP 服务器实例;
  • 调用registerCompletionTool()注册上文讲解的 completion 工具;
  • 调用registerSearchResource()注册 search 资源。

通过 ResourceTemplate 暴露动态资源

在registerSearchResource()(src/index.ts)中,示例展示了 Resource 的注册方式:

this.mcpServer.resource( 'search', new ResourceTemplate("test://{query}", { list: undefined }), async (uri, { query }) => { // Simulate search processing await new Promise(resolve => setTimeout(resolve, 300)); const results = [ { title: 'Result 1', snippet: `Related to ${query}...` }, { title: 'Result 2', snippet: `Information about ${query}...` }, { title: 'Result 3', snippet: `More details on ${query}...` } ]; return { contents: [ { uri: uri.href, text: JSON.stringify(results) } ] }; } );

与 Tool 不同,Resource 面向「提供上下文与数据」的场景。这里使用ResourceTemplate定义带 URI 参数模板的地址模式(test://{query}),当客户端读取匹配该模板的 URI 时,回调收到解析出的{ query }参数,返回contents数组作为资源内容。{ list: undefined }表明该模板不参与资源列表枚举。

基于 stdio 的传输连接

connect()方法(src/index.ts)负责将服务器绑定到标准输入输出传输:

public async connect(): Promise<void> { const transport = new StdioServerTransport(); await this.mcpServer.connect(transport); console.log(`Server connected via stdio transport`); }

StdioServerTransport是 MCP 最常见的本地传输方式:服务器通过 stdin/stdout 与宿主(如 VS Code、Claude Desktop 或自定义客户端)通信,非常适合本地开发和调试。

可观测性与对外访问接口

类还提供了on(event, listener)事件监听注册、getMcpServer()获取底层实例、getSupportedModels()返回受支持模型列表等公开方法。文件末尾的演示代码展示了完整的启动序列(src/index.ts):

const server = new ExtendedMcpServer({ serverName: 'TypeScript MCP Demo Server', version: '1.0.0' }); server.on('request', (data) => { console.log(`Request received: ${JSON.stringify(data)}`); }); server.on('completion', (data) => { console.log(`Completion finished: ${JSON.stringify(data)}`); }); server.connect().catch(error => { console.error('Failed to connect server:', error); process.exit(1); });

从源码结构可以推断,这套「类封装 + 事件埋点 + 模块化注册方法」的设计意在将 MCP Server 的初始化、工具/资源注册与传输连接解耦,方便后续扩展更多工具与资源。

安装与运行

安装依赖

在示例目录下执行(对应文档中的 Install 步骤):

npm install

该命令会依据 package.json 与package-lock.json安装@modelcontextprotocol/sdk、zod、openai及 TypeScript 工具链。

启动服务

npm start

需要注意start脚本的真实行为是tsc && node ./build/index.js(package.json):先由 TypeScript 编译器将src/编译到build/,再直接运行编译产物。因此首次运行会自动完成编译,启动后控制台会依次输出服务器初始化信息、受支持模型列表,随后通过 stdio 传输等待客户端连接。

快速验证思路

启动后可用 MCP Inspector(npx @modelcontextprotocol/inspector)以 stdio 方式连接本服务,或在宿主机(如 VS Code Agent 模式)中将其注册为 MCP Server,进而调用completion工具并读取test://{query}资源——这与仓库中 04-PracticalImplementation/README.md 介绍的 MCP Inspector 测试方法一致。若传入不在支持列表中的模型名,服务端会按设计抛出Model ... not supported错误,可作为校验 Zod Schema 与业务校验链路的测试用例。

延伸阅读

  • 多语言对照实现:C#、Java with Spring、JavaScript、Python
  • 分页与大数据集处理:04-PracticalImplementation/pagination/README.md
  • 章节总览与实战目标:04-PracticalImplementation/README.md
  • 教程
  • 文档
  • 人工智能

【免费下载链接】mcp-for-beginners

This open-source curriculum introduces the fundamentals of Model Context Protocol (MCP) through real-world, cross-language examples in .NET, Java, TypeScript, JavaScript, Rust and Python. Designed for developers, it focuses on practical techniques for building modular, scalable, and secure AI workflows from session setup to service orchestration.

项目地址:https://gitcode.com/GitHub_Trending/mc/mcp-for-beginners
点击查看免费下载

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询