随着大语言模型(LLM)的快速发展,AI Agent 已成为连接 AI 与现实世界的桥梁。AI Agent 能够理解用户意图,自主规划任务,并通过调用外部工具完成复杂操作。然而,传统的工具集成方式存在诸多问题:接口不统一、上下文管理困难、工具描述标准化缺失等。
Anthropic 提出的 MCP(Model Context Protocol)协议为解决这些问题提供了标准化方案。本文将深入探讨 AI Agent 的核心概念、MCP 协议的设计原理,以及如何构建一个完整的智能工具调用系统。
AI Agent 是一个能够自主执行任务的智能体,它具备以下核心能力:
典型的 AI Agent 架构包含以下组件:
┌─────────────────────────────────────────┐ │ 用户输入 │ └─────────────────┬───────────────────────┘ ▼ ┌─────────────────────────────────────────┐ │ 意图理解模块 │ │ (LLM + Prompt Engineering) │ └─────────────────┬───────────────────────┘ ▼ ┌─────────────────────────────────────────┐ │ 任务规划模块 │ │ (ReAct / Plan-and-Execute) │ └─────────────────┬───────────────────────┘ ▼ ┌─────────────────────────────────────────┐ │ 工具调用模块 │ │ (Function Calling) │ └─────────────────┬───────────────────────┘ ▼ ┌─────────────────────────────────────────┐ │ 结果整合模块 │ │ (Response Synthesis) │ └─────────────────────────────────────────┘
在传统实现中,工具调用面临以下挑战:
MCP(Model Context Protocol)是由 Anthropic 提出的开放协议,旨在标准化 AI 应用与外部数据源、工具之间的连接方式。它提供:
MCP 采用客户端-服务器架构:
┌──────────────────────────────────────────────────────┐ │ MCP Host (AI 应用) │ │ ┌────────────────────────────────────────────────┐ │ │ │ MCP Client │ │ │ │ - 管理连接 │ │ │ │ - 协议处理 │ │ │ │ - 上下文聚合 │ │ │ └────────────────────────────────────────────────┘ │ └──────────────────────┬───────────────────────────────┘ │ JSON-RPC 2.0 ┌─────────────┼─────────────┐ ▼ ▼ ▼ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ MCP Server │ │ MCP Server │ │ MCP Server │ │ (文件系统) │ │ (数据库) │ │ (API 服务) │ └──────────────┘ └──────────────┘ └──────────────┘
资源是 MCP 服务器可以提供的只读数据,例如:
typescript// 资源定义示例
interface Resource {
uri: string; // 资源唯一标识
name: string; // 资源名称
description?: string; // 资源描述
mimeType?: string; // MIME 类型
}
工具是 MCP 服务器提供的可执行操作:
typescript// 工具定义示例
interface Tool {
name: string; // 工具名称
description: string; // 工具描述
inputSchema: JSONSchema; // 输入参数 Schema
}
// 工具调用示例
interface ToolCall {
name: string;
arguments: Record<string, any>;
}
MCP 支持预定义的提示词模板:
typescriptinterface Prompt {
name: string;
description: string;
arguments?: PromptArgument[];
}
MCP 使用 JSON-RPC 2.0 进行通信:
json// 请求示例
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "read_file",
"arguments": {
"path": "/data/config.json"
}
}
}
// 响应示例
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"content": [
{
"type": "text",
"text": "{ \"key\": \"value\" }"
}
]
}
}
以 Python FastMCP 为例:
pythonfrom mcp import FastMCP
# 创建 MCP 服务器实例
mcp = FastMCP("my-server")
# 定义资源
@mcp.resource("config://app")
def get_config() -> str:
"""获取应用配置"""
return open("config.json").read()
# 定义工具
@mcp.tool()
def read_file(path: str) -> str:
"""读取文件内容
Args:
path: 文件路径
Returns:
文件内容
"""
with open(path) as f:
return f.read()
@mcp.tool()
def write_file(path: str, content: str) -> bool:
"""写入文件内容
Args:
path: 文件路径
content: 要写入的内容
Returns:
是否成功
"""
with open(path, 'w') as f:
f.write(content)
return True
# 启动服务器
if __name__ == "__main__":
mcp.run()
在 Claude Desktop 中配置 MCP:
json{
"mcpServers": {
"my-server": {
"command": "python",
"args": ["server.py"]
}
}
}
ReAct(Reasoning + Acting)是一种常用的 Agent 工作模式:
用户输入 → 思考 → 行动 → 观察 → 循环...
示例流程:
用户: 帮我分析 /data 目录下的所有 Python 文件 思考: 我需要先列出目录中的文件,然后筛选出 Python 文件,最后分析每个文件 行动: 调用 list_directory("/data") 观察: 找到文件 [a.py, b.py, data.txt, c.py] 思考: 筛选出 Python 文件: [a.py, b.py, c.py] 行动: 调用 read_file 分析每个文件 观察: 获取到所有文件内容 思考: 整合分析结果,生成报告 行动: 返回分析结果给用户
适用于复杂任务的分步执行:
1. 规划阶段:生成任务步骤列表 2. 执行阶段:按顺序执行每个步骤 3. 调整阶段:根据执行结果调整计划
typescript// 维护对话上下文
interface ConversationContext {
messages: Message[];
tools: Tool[];
resources: Resource[];
metadata: Record<string, any>;
}
python@mcp.tool()
def search_code(query: str, directory: str) -> list[dict]:
"""搜索代码
Args:
query: 搜索关键词
directory: 搜索目录
Returns:
匹配的代码片段列表
"""
# 使用 ripgrep 搜索
import subprocess
result = subprocess.run(
['rg', '-n', query, directory],
capture_output=True, text=True
)
return parse_results(result.stdout)
@mcp.tool()
def run_tests(test_path: str) -> dict:
"""运行测试
Args:
test_path: 测试文件路径
Returns:
测试结果
"""
import subprocess
result = subprocess.run(
['pytest', test_path, '-v'],
capture_output=True, text=True
)
return {
'passed': 'passed' in result.stdout,
'output': result.stdout
}
python@mcp.tool()
def query_database(sql: str) -> list[dict]:
"""执行 SQL 查询
Args:
sql: SQL 查询语句
Returns:
查询结果
"""
import sqlite3
conn = sqlite3.connect('data.db')
cursor = conn.execute(sql)
return [dict(row) for row in cursor.fetchall()]
@mcp.tool()
def create_chart(data: list, chart_type: str) -> str:
"""创建图表
Args:
data: 数据列表
chart_type: 图表类型 (bar/line/pie)
Returns:
图表文件路径
"""
import matplotlib.pyplot as plt
# 生成图表...
return '/output/chart.png'
AI Agent 与 MCP 的结合为构建智能应用提供了强大基础:
随着生态的发展,MCP 有望成为 AI 应用连接外部世界的通用协议。
本文作者:yowayimono
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!