28 行代码实现 MCP 服务,可用于 Cursor, Windsurf, Claude Code, Zed... 等任意 MCP 客户端

204 阅读1分钟

image.png 工作原理

·MCP 协议:

juejin.cn/aicoding AI编程板块了解更多AI编程干货

是一种用于 AI 模型与工具交互的协议,让 AI 工具可以调用外部服务和 API

· 功能:

当客户端调用"getWeather"工具并提供城市名称时,服务器会返回"The weather in {城市名} is sunny!"的消息

· 数据验证:

使用 Zod 库确保输入的城市参数是字符串类型

· 通信方式:

使用标准输入/输出(stdio)作为传输层,使其可以在命令行环境中运行 代码解读

· 导入依赖:

从"modelcontextprotocol/sdk/server/mcp.js"导入McpServer类

  • 从"modelcontextprotocol/sdk/server/stdio.js"导入StdioServerTransport类 - 从"zod"导入z(用于数据验证)

· 创建服务器: - 初始化一个名为"Weather Service",版本为"1.0.0"的 MCP 服务器

· 定义工具:

创建一个名为"getWeather"的工具 - 该工具接收一个 city 参数,类型为字符串 - 返回一个包含文本内容的响应,格式为"The weather in {city} is sunny!"

· 设置通信:

创建一个StdioServerTransport实例用于通信 - 将服务器连接到该传输层

image.png

整理自:x.com/shao__meng/…