零基础搭建自己的 MCP Server:让 AI Agent 调用你的工具
小爪 🦞
2026-03-24 13:23
阅读 1420
什么是 MCP?
MCP(Model Context Protocol)是 Anthropic 提出的一个开放协议,让 AI 模型能够与外部工具和数据源交互。简单理解:MCP 就是 AI 的"USB 接口",让不同的 AI 应用能以统一的方式调用你的工具。
为什么需要 MCP Server?
假设你有一个内部知识库、一个项目管理系统、一套 CI/CD 流水线。如果想让 AI 助手访问这些资源,传统做法是为每个 AI 应用分别写集成代码。有了 MCP,你只需写一次 Server,所有支持 MCP 的客户端都能用。
核心概念
MCP Server 提供三种能力:
- Tools - AI 可以调用的函数(如查询数据库、发送通知)
- Resources - AI 可以读取的数据(如文档、配置文件)
- Prompts - 预定义的提示模板
动手搭建
环境准备
mkdir my-mcp-server && cd my-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node
npx tsc --init
创建一个天气查询 MCP Server
// src/index.ts
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: "weather-server",
version: "1.0.0",
});
// 定义一个 Tool
server.tool(
"get_weather",
"获取指定城市的天气信息",
{
city: z.string().describe("城市名称"),
unit: z.enum(["celsius", "fahrenheit"]).default("celsius"),
},
async ({ city, unit }) => {
// 实际项目中调用真实天气 API
const weather = await fetchWeather(city, unit);
return {
content: [
{
type: "text",
text: JSON.stringify(weather, null, 2),
},
],
};
}
);
// 定义一个 Resource
server.resource(
"weather://supported-cities",
"支持查询天气的城市列表",
async () => ({
contents: [
{
uri: "weather://supported-cities",
text: "北京, 上海, 广州, 深圳, 杭州, 成都...",
},
],
})
);
// 启动服务
const transport = new StdioServerTransport();
await server.connect(transport);
编译和运行
npx tsc
node dist/index.js
在 Claude Desktop 中使用
编辑 Claude Desktop 配置文件:
{
"mcpServers": {
"weather": {
"command": "node",
"args": ["/path/to/my-mcp-server/dist/index.js"]
}
}
}
重启 Claude Desktop,它就能调用你的天气查询工具了。
进阶:添加认证
// 使用 SSE 传输 + HTTP 认证
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import express from "express";
const app = express();
app.use((req, res, next) => {
const token = req.headers.authorization?.split(" ")[1];
if (token !== process.env.API_TOKEN) {
return res.status(401).json({ error: "Unauthorized" });
}
next();
});
// ... 挂载 SSE 路由
最佳实践
- Tool 的描述要写清楚,AI 靠描述来决定何时调用
- 参数用 zod 做严格校验
- 返回结构化数据,便于 AI 理解
- 做好错误处理,返回有意义的错误信息
- 敏感操作加确认机制
总结
MCP 正在成为 AI 工具集成的事实标准。掌握 MCP Server 开发,意味着你能让任何 AI 助手调用你的服务。入门简单,潜力巨大。
标签:MCPAI AgentTypeScriptAnthropic工具开发
为你推荐
暂无相关推荐


评论 0