/ MCP  AI工具  Claude  API集成  LLM工具开发  Model Context Protocol  大模型  实战教程 

MCP 工具开发实战:10步给 AI 接入任意外部 API


什么是 MCP?

2024 年底,Anthropic 开源了 Model Context Protocol(MCP)——一个让 AI 大模型能够直接调用外部工具、读取数据源的开放协议。它解决了一个核心痛点:如何让 AI 和你的真实世界连通?

比较一下两种方式:

  • 之前:Function Calling —— 每个模型各定一套,接口不通,维护成本高

  • 现在:MCP —— 标准协议,写一次 Server,所有支持 MCP 的 AI 都能用

MCP 的核心优势:

  • 跨模型通用:Clauде、GPT-4、Gemini 共用一套工具

  • 进程隔离:Server 独立运行,崩溃不影响主程序

  • 双向通信:Server 可以主动向 AI 推送消息

  • 生态成熟:GitHub、Slack、PostgreSQL 都已有官方 MCP Server

本文目标:10 步完成一个真实可用的 MCP Server,接入天气 API,在 Claude Desktop 里直接用自然语言查询天气。

环境准备(Step 1-2)

Step 1:确认运行环境

# 需要 Node.js 18+ 或 Python 3.10+
node -v      # v18.0.0 或以上
python3 --version  # 3.10+

本文选用 TypeScript + Node.js(官方 SDK 支持最完善)。

Step 2:创建项目

mkdir weather-mcp-server
cd weather-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk axios
npm install -D typescript @types/node ts-node
npx tsc --init

修改 tsconfig.json

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "node16",
    "moduleResolution": "node16",
    "outDir": "./dist",
    "strict": true
  }
}

申请天气 API Key(Step 3)

Step 3:获取 OpenWeatherMap API Key

  1. 登录 openweathermap.org

  2. 免费注册账号 → 进入 My API keys 页面

  3. 复制默认生成的 Key(或点 Generate New Key)

免费额度:60 次/分钟,个人使用完全够用。

编写核心代码(Step 4-6)

Step 4:创建 Server 入口文件

新建 src/index.ts

import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import axios from "axios";

const server = new Server(
  { name: "weather-mcp-server", version: "1.0.0" },
  { capabilities: { tools: {} } }
);

Step 5:注册工具列表

server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [
    {
      name: "get_weather",
      // 关键:description 要写清楚触发条件,AI 才知道何时调用它
      description:
        "当用户询问某个城市的天气、气温、湿度、风力时调用。返回实时天气数据。",
      inputSchema: {
        type: "object",
        properties: {
          city: {
            type: "string",
            description: "城市名称,支持中文或英文,如:北京、Shanghai、广州",
          },
        },
        required: ["city"],
      },
    },
  ],
}));

Step 6:实现工具逻辑

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (request.params.name !== "get_weather") {
    throw new Error("未知工具");
  }

  const city = request.params.arguments?.city as string;
  const apiKey = process.env.WEATHER_API_KEY;

  if (!apiKey) {
    return {
      content: [{ type: "text", text: "错误:WEATHER_API_KEY 未设置" }],
      isError: true,
    };
  }

  try {
    const { data } = await axios.get(
      "https://api.openweathermap.org/data/2.5/weather",
      {
        params: { q: city, appid: apiKey, units: "metric", lang: "zh_cn" },
        timeout: 5000,
      }
    );

    const result = {
      城市: data.name,
      天气: data.weather[0].description,
      温度: `${data.main.temp}°C`,
      湿度: `${data.main.humidity}%`,
      风速: `${data.wind.speed} m/s`,
      气压: `${data.main.pressure} hPa`,
    };

    return {
      content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
    };
  } catch (err: any) {
    const msg = err.response?.status === 404
      ? `找不到城市: ${city}`
      : `查询失败: ${err.message}`;
    return { content: [{ type: "text", text: msg }], isError: true };
  }
});

async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("Weather MCP Server 已启动");
}

main().catch(console.error);

编译与本地测试(Step 7)

Step 7:编译并运行

npx tsc
WEATHER_API_KEY=your_api_key node dist/index.js

启动成功应输出:Weather MCP Server 已启动(输到 stderr)

验证工具注册(新开一个终端):

# 发送一个 ListTools 请求
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | WEATHER_API_KEY=xxx node dist/index.js

接入 Claude Desktop(Step 8-9)

Step 8:找到配置文件

  • macOS~/Library/Application Support/Claude/claude_desktop_config.json

  • Windows%APPDATA%Claudeclaude_desktop_config.json

Step 9:添加 Server 配置

{
  "mcpServers": {
    "weather": {
      "command": "node",
      "args": ["/绝对路径/weather-mcp-server/dist/index.js"],
      "env": {
        "WEATHER_API_KEY": "你的_API_KEY"
      }
    }
  }
}

保存后 重启 Claude Desktop,在输入框左下角能看到工具图标,点开可看到 get_weather 已注册。

现在对 Claude 说“北京今天天气怎么样?”,它会自动调用你写的 MCP Server。

验证与排错(Step 10)

Step 10:常见问题排查

工具图标不出现:配置文件路径错误,或 JSON 格式有问题。用 JSON 校验器检查。

Server 启动报错但 Claude 无提示

# 单独运行查报错
node dist/index.js

# 查看 Claude 日志
# macOS
tail -f ~/Library/Logs/Claude/main.log

AI 不调用工具:这通常是 description 写得不够清楚。要明确写出触发条件,比如“当用户询问某城市天气时调用”。

返回内容太长导致对话卡顿:MCP 返回内容会进入上下文。只返回关键字段,不要把整个原始 API 响应招过来。

进阶扩展

掌握基础后,MCP 还支持更多能力:

  • Resources(资源):让 AI 读取文件、数据库,适合大量数据场景

  • Prompts(模板):预置常用 Prompt,用户可直接调用

  • Sampling(采样):Server 主动让 AI 生成内容(高级用法)

建议从一个你日常需要的 API 开始实践:公司内部系统、个人数据库、家庭自动化接口……把它接入 AI,你会发现工作效率就是不一样。

发布评论

热门评论区: