在 20 分钟内搭建你的第一个 MCP 服务器(TypeScript)
发布: (2026年3月8日 GMT+8 13:28)
4 分钟阅读
原文: Dev.to
Source: Dev.to
请提供您希望翻译的具体文本内容,我将为您翻译成简体中文并保留原始的格式、Markdown 语法以及技术术语。仅需粘贴您想要翻译的段落或章节即可。
概述
MCP(模型上下文协议)允许 AI 助手直接调用外部工具。本指南展示了如何使用 TypeScript 构建一个简单的 MCP 服务器,以从文本中提取结构化数据。
先决条件
- Node.js 18+
- TypeScript
- 兼容 MCP 的客户端(例如 Claude Desktop、Cursor)
项目设置
mkdir my-mcp-server && cd my-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node
tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "Node16",
"moduleResolution": "Node16",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"declaration": true
},
"include": ["src/**/*"]
}
注意: MCP SDK 需要
module: "Node16"和moduleResolution: "Node16"。
服务器实现 (src/index.ts)
#!/usr/bin/env node
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: "my-tool",
version: "1.0.0",
});
// -------------------------------------------------------------------
// 工具定义
// -------------------------------------------------------------------
server.tool(
"my_tool_name",
"Description of what this tool does",
{
// Parameters defined with Zod
input_text: z.string().describe("The text to process"),
format: z.enum(["json", "csv"]).optional().describe("Output format"),
},
async ({ input_text, format }) => {
// Your logic here
const result = await processText(input_text, format);
return {
content: [
{
type: "text" as const,
text: JSON.stringify(result, null, 2),
},
],
};
}
);
// -------------------------------------------------------------------
// 服务器启动
// -------------------------------------------------------------------
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
}
main().catch(console.error);
工具定义拆解
| 部分 | 目的 |
|---|---|
| 名称 | AI 用来调用工具的标识符 |
| 描述 | 帮助 AI 决定何时使用该工具 |
| 模式 | 描述参数的 Zod schema |
| 处理函数 | 执行实际工作的异步函数 |
构建并运行
npx tsc
node dist/index.js
服务器现在在 stdin 上监听 MCP 消息。
使用 MCP Inspector 进行测试
npx @modelcontextprotocol/inspector node dist/index.js
将服务器注册到 Claude Desktop
在 ~/Library/Application Support/Claude/claude_desktop_config.json 中添加以下条目:
{
"mcpServers": {
"my-tool": {
"command": "node",
"args": ["/absolute/path/to/dist/index.js"]
}
}
}
重新启动 Claude Desktop;该工具将出现在工具菜单中。
将 REST API 包装为 MCP 工具
server.tool(
"extract_data",
"Extract structured JSON from unstructured text",
{
text: z.string().describe("Text to extract from"),
schema: z.enum(["receipt", "invoice", "email", "resume"]),
},
async ({ text, schema }) => {
const response = await fetch("https://your-api.com/extract", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text, schema }),
});
const result = await response.json();
return {
content: [
{
type: "text" as const,
text: JSON.stringify(result.data, null, 2),
},
],
};
}
);
最佳实践
- 具体 在工具描述中;AI 使用它们来选择正确的工具。
- 在每个参数上使用
zod .describe()来指导 AI。 - 返回结果时使用
type: "text";AI 可以从纯文本解析 JSON。 - 优雅地处理错误:返回错误信息为文本,而不是抛出异常。
跳过教程 – 使用现成服务器
git clone https://github.com/avatrix1/structureai-mcp.git
cd structureai-mcp && npm install && npm run build
此预构建服务器可从收据、发票、电子邮件等中提取结构化数据。它包含 10 次免费请求,且无需 API 密钥。
由 Avatrix LLC 构建。 完整源码: