通过简单示例了解MCP:实用导论

发布: (2026年1月18日 GMT+8 02:41)
7 min read
原文: Dev.to

看起来您只提供了来源链接。如果您能把需要翻译的正文内容贴在这里,我就可以帮您把它翻译成简体中文。

个人观点先行

当新的协议和框架出现时,我想回答一个问题:

“这实际上解决了什么问题?”

这个货币转换器准确地展示了 MCP 的工作原理,这值得分享。


学习目标

在编写任何代码之前,先理解一件特定的事:

AI 实际上是如何通过 MCP 与外部工具进行通信的?

MCP 实际作用

没有 MCP

You: "Is ¥10,000 enough to buy a $60 game?"
AI: "I don't have access to current exchange rates, but you can check [some website]."

有 MCP

You: "Is ¥10,000 enough to buy a $60 game?"
AI:
1. Realizes it needs an exchange rate  
2. Sees there's a `get_exchange_rate` tool available  
3. Calls: get_exchange_rate(from="JPY", to="USD", amount=10000)  
4. Gets: 10000 JPY = 65.83 USD  
5. Responds: "Yes, ¥10,000 is approximately $65.83 USD, so you'd have $5.83 left after buying the game."

关键洞察: MCP 只是一种标准化的方式,让 AI 能够发现并使用你的工具。

示例架构

我的简单实现如下:

  1. 用户 发送自然语言提示。
  2. Hono API 接收该提示。
  3. API 获取提供的 MCP 服务器工具列表(get_exchange_rate)。
  4. API 将提示 以及 工具列表发送给 Claude AI。
  5. Claude AI 决定何时使用工具。
  6. 在拦截步骤中,API 调用 MCP 工具并获取实际汇率。
  7. API 再次向 Claude AI 发送请求,包含实际汇率 原始提示。
  8. 用户 收到最终答案。

它很基础,这正是它对学习有用的原因。

MCP 工具定义

{
  "name": "get_exchange_rate",
  "description": "Get exchange rate between currencies",
  "inputSchema": {
    "type": "object",
    "properties": {
      "from_currency": { "type": "string" },
      "to_currency":   { "type": "string" },
      "amount":        { "type": "number", "optional": true }
    }
  }
}

此工具仅返回汇率数据;AI 负责处理其他所有事务。


实现步骤

1️⃣ 用户发送自然语言提示

"Is ¥10,000 enough to buy a $60 game?"

2️⃣ API 接收请求

app.post('/api/chat', async c => {
  const { prompt } = await c.req.json();
  // …
});

3️⃣ API 获取 MCP 工具列表

const tools = await mcpClient.listTools();   // returns [{ name: "get_exchange_rate", … }]

4️⃣ API 将提示和工具发送给 Claude AI

let response = await anthropic.messages.create({
  tools,
  messages: [{ role: 'user', content: prompt }]
});

5️⃣ Claude 判断需要使用工具

while (response.stop_reason === 'tool_use') {
  const toolUse = response.content.find(b => b.type === 'tool_use');
  // …
}

6️⃣ API 调用 MCP 工具

const toolResult = await mcpClient.callTool({
  name: toolUse.name,
  arguments: toolUse.input
});

7️⃣ API 发送包含工具结果的第二次请求

response = await anthropic.messages.create({
  tools,
  messages: [
    { role: 'user', content: prompt },               // original prompt
    {
      role: 'user',
      content: [{
        type: 'tool_result',
        tool_use_id: toolUse.id,
        content: JSON.stringify(toolResult.content) // rate info
      }]
    }
  ]
});

8️⃣ 将最终答案返回给用户

const finalText = response.content;
return finalText;   // "Yes, ¥10,000 is approximately $65.83 USD, so you'd have $5.83 left..."

为什么这个简单示例很重要

  1. 工具发现 – AI 能看到可用的工具,并根据描述知道何时使用它们。

  2. 参数提取 – AI 自动从混乱的自然语言中提取结构化参数:

    “Is ¥10,000 enough for $60?” → from="JPY", to="USD", amount=10000
    “How many dollars is 50 euros?” → from="EUR", to="USD", amount=50
  3. 上下文感知 – AI 能处理多步骤查询:

    “I have 5 euros in cash and 20 in my bank, total in USD?”
    → AI adds 5 + 20 = 25 EUR, then calls the tool with 25 EUR.
  4. 自然响应 – AI 以对话方式格式化工具的响应,而不是直接输出原始 JSON。

观看效果

我录制了一个快速演示,展示了不同类型的查询是如何处理的:

Demo GIF

(点击图片查看全尺寸。)

![Currency Exchange Demo](https://media2.dev.to/dynamic/image/width=800,height=,fit=scale-down,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6die6pigf3m6qlkdj5ou.gif)

Nothing fancy, just the basic flow working as expected.

没什么花哨的,只是基本流程按预期工作。

设置(用于学习目的)

如果你想自己尝试以了解 MCP:

git clone https://github.com/hshoja/Currency-Exchange-MCP-Service
npm install
cp env.example .env
# Add your API keys to .env
npm run dev

你需要

然后只需发送带有自然语言提示的 POST 请求:

{
  "prompt": "What is 100 USD in EUR?"
}

实际要点

在构建了这个简单示例后,我们现在明白:

  • MCP 并不是 为了构建更智能的 API。
  • 它是关于构建简单、专注的工具,并让 AI 成为将它们与人类意图连接的智能层。

你的工具可以很笨。它应该是笨的。专注做好一件事,让 AI 处理其余的。


潜在用例(超出此简单示例)

虽然货币转换器很基础,但该模式可以扩展到更有趣的问题。请看以下示例:

复杂性不在于 MCP 本身,而在于你构建和连接的工具。


查看代码

完整的 full repository 包含了你所需的一切。随意克隆它、修改它,或在学习 MCP 时将其作为参考使用。

你也在学习 MCP 吗?你是否已经构建了简单的示例来了解新技术?我很想听听你的经验——欢迎留言!

P.S. — 如果这帮助你更好地理解了 MCP,请点个赞!并且记住:简单的示例也是有效的示例。

Back to Blog

相关文章

阅读更多 »

Rapg:基于 TUI 的密钥管理器

我们都有这种经历。你加入一个新项目,首先听到的就是:“在 Slack 的置顶消息里查找 .env 文件”。或者你有多个 .env …

技术是赋能者,而非救世主

为什么思考的清晰度比你使用的工具更重要。Technology 常被视为一种魔法开关——只要打开,它就能让一切改善。新的 software,...

踏入 agentic coding

使用 Copilot Agent 的经验 我主要使用 GitHub Copilot 进行 inline edits 和 PR reviews,让我的大脑完成大部分思考。最近我决定 t...