从 REST 到 MCP:有什么变化
Source: Dev.to
介绍
REST 已经成为标准已有 20 年。你使用的每个 API、你构建的每个集成——很可能都是 REST。
但情况正在变化。AI 不想调用原始端点;它想调用 工具。这就是 MCP(Machine‑Callable Procedures)的用武之地。
REST:它的设计初衷
- 典型调用
GET /users/123
POST /orders
PUT /products/456
DELETE /comments/789
- 可预测、无状态,适用于任何环境。
- 假设调用者完全了解自己的需求:你编写代码去调用具有固定参数的特定端点。
为什么 REST 对 AI 来说很尴尬
当你向像 Claude 这样的 LLM 询问“给我用户最近的订单”,它会以动作而不是端点来思考:
- 我需要做什么? → 获取订单
- 我需要哪些信息? → 用户 ID
- 有什么约束? → 最近的订单
REST 迫使 AI 将自然语言映射到僵硬的端点,这虽然可行,但很笨拙。
MCP:以工具为中心的模型
与其暴露端点,你暴露 工具:
tools:
- name: get_user_orders
description: Get orders for a user, optionally filtered by date
parameters:
- name: user_id
type: string
required: true
- name: since
type: string
description: ISO date to filter orders from
AI 读取描述,理解参数,并决定何时使用该工具——无需解析文档或记住端点路径。
运行时发现工具
{
"tools": [
{
"name": "get_user_orders",
"description": "Get orders for a user",
"inputSchema": { /* ... */ }
},
{
"name": "create_order",
"description": "Create a new order",
"inputSchema": { /* ... */ }
}
]
}
AI 会询问:“你有什么工具?”并收到带有清晰描述的列表,从而实现无需硬编码的动态发现。
比较 REST 与 MCP 调用
REST 示例
GET /api/v2/users/123/orders?status=completed&limit=10&sort=desc
您必须了解确切的路径、查询参数和 API 版本。
MCP 示例
{
"tool": "get_user_orders",
"arguments": {
"user_id": "123",
"status": "completed",
"limit": 10
}
}
AI 直接从自然语言中提取参数(“展示约翰最近的 10 个已完成订单”)。
编写有效的工具描述
- Bad – 过于模糊,AI 不会知道何时使用它
- name: proc_txn
description: Process transaction
- Good – 明确的使用场景和必需参数
- name: process_payment
description: >-
Charge a customer's saved payment method. Use this when the user wants
to complete a purchase. Requires `order_id` and `payment_method_id`.
描述越丰富,AI 的表现越智能。
使用 MCP 流式结果
MCP 支持服务器发送事件(SSE)以实现增量输出:
AI: "Analyze this large dataset"
Tool: [streaming] Processing chunk 1/10...
Tool: [streaming] Processing chunk 2/10...
...
Tool: [complete] Analysis ready
这使得可以进行进度更新并处理长时间运行的操作。
跨调用保持上下文
REST 是无状态的;每个请求都是独立的。MCP 可以保持上下文,从而支持多步骤工作流:
- 调用
get_performance_metrics - 识别最慢的端点
- 使用该端点调用
get_logs - 总结发现
单个用户请求可以触发多个协调的工具调用,生成连贯的结果。
集成模型:REST + MCP
MCP 并不取代 REST。您的应用仍然以常规方式调用 API。MCP 作为包装层位于其上:
Your REST API → MCP Server → AI Agent
请从 工具 的角度思考,而不是 端点:
- 端点 – 存在哪些操作?
- 工具 – AI 可以用它做什么?
编写工具描述时,仿佛在向一位聪明的实习生解释系统一样。
MCP层的优势
- 将复杂性隐藏在简单工具后面
- 添加防护措施(例如,只读、速率限制)
- 塑造 AI 与系统交互的方式
新兴生态系统
- 现在:开发者手动将 REST API 与 AI 集成。
- 即将:为流行服务(Stripe、GitHub 等)提供 MCP 包装器。
- 之后:API 将随 MCP 服务器一起发布, alongside REST。
示例:使用 Gantz Run 包装 REST API
tools:
- name: get_weather
description: Get current weather for a city
parameters:
- name: city
type: string
required: true
http:
method: GET
url: "https://api.weather.com/current"
query:
q: "{{city}}"
用几行代码,传统的 REST 端点即可被 AI 访问。
结论
这不是 REST 与 MCP 的对立,而是 REST + MCP。
- REST 负责应用到服务器的通信。
- MCP 负责 AI 到工具的通信。
如果你在为 AI 为先的世界构建,MCP 接口才是关键。
已经在使用 MCP 包装 REST API 了吗?分享你的经验!