如何在 10 分钟内为你的 API 配置 MCP 服务器
Source: Dev.to
请提供您希望翻译的完整文本内容,我将按照要求进行翻译并保留原始的格式、Markdown 语法以及技术术语。谢谢!
您正在构建的内容
MCP 服务器是一个小型适配层,位于您现有的 API 与希望使用它的任何 AI 代理之间。它将您 API 的功能以 工具 的形式公开——即具名、带类型、可描述的操作,供代理发现并调用。
您并不是在重写 API;而是对其进行包装。
AI Agent → MCP Server → Your Existing APIMCP 服务器负责协议转换,而您的 API 保持原样。
第一步:安装 MCP SDK(2 分钟)
Anthropic 发布了官方的 TypeScript SDK:
npm install @modelcontextprotocol/sdk还有一个 Python SDK:
pip install mcp第2步:定义您的工具(5 分钟)
每个工具对应一个 API 端点。您需要定义:
- Name – snake_case,具描述性
- Description – 普通英文;代理会读取此描述以决定何时使用该工具
- Input schema – JSON Schema
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const server = new Server(
{ name: "my-api", version: "1.0.0" },
{ capabilities: { tools: {} } }
);
server.setRequestHandler("tools/list", async () => ({
tools: [
{
name: "create_task",
description:
"Create a new task in the workspace. Use when the user wants to add a task, to‑do, or action item.",
inputSchema: {
type: "object",
properties: {
title: { type: "string", description: "Task title" },
assignee_email: { type: "string", description: "Email of assignee" },
due_date: { type: "string", description: "Due date (YYYY‑MM‑DD)" }
},
required: ["title"]
}
}
]
}));提示: 描述的重要性超出您的想象。仅写“创建任务”这种模糊描述很弱;更丰富的描述能够为模型提供何时使用该工具的上下文。
第三步:处理工具调用(2 分钟)
server.setRequestHandler("tools/call", async (request) => {
const { name, arguments: args } = request.params;
if (name === "create_task") {
const response = await fetch("https://api.yourapp.com/tasks", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.API_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify(args)
});
const task = await response.json();
return {
content: [{ type: "text", text: `Task created: "${task.title}" (ID: ${task.id})` }]
};
}
throw new Error(`Unknown tool: ${name}`);
});
const transport = new StdioServerTransport();
await server.connect(transport);响应内容是代理看到的内容。请保持事实准确——代理会将其合成为自然语言供用户使用。
第4步:测试(1 分钟)
npx @modelcontextprotocol/inspector node your-server.js这将打开本地 UI,以便在将任何真实 AI 指向它之前手动调用你的工具。
部署方式
- 选项 A: 在
/mcp路由上通过 HTTP(SSE 传输)暴露,与你现有的服务器并行。 - 选项 B: 部署为独立服务——Firebase Functions、AWS Lambda、Railway 等。
对于身份验证,通过 MCP 的 Authorization 头或环境变量传递你的 API 密钥。不要通过工具界面暴露凭证。
更大的图景
为你的 API 添加 MCP 支持今天只需 10 分钟的投入,但回报会不断累积。每一个添加了 MCP 支持的 AI 助手、代理框架和编码工具,都可能成为你 API 的潜在分发渠道。那些从未阅读过你的文档的用户,现在可以通过他们已经信任的 AI 使用你的产品。
现在已具备代理能力的产品,在 AI 驱动的工作流成为默认时将拥有显著的先发优势。未做好准备的产品则会被淹没在视野之外。
如果你想完全省去服务器设置,Botlington MCP Host 为你的 API 托管并管理 MCP 服务器——你定义工具,他们负责基础设施、认证和路由。