简打卡
51.76M · 2026-03-28
近年来,AI Agent 技术如雨后春笋般涌现,从千问点奶茶、豆包元宝等消费级应用,到 OpenClaw 等企业级解决方案,标志着人工智能从简单的问答系统向复杂任务自动化的重要转变。传统的 LLM(大语言模型)虽然具备强大的语言理解和生成能力,但在实际应用中却面临诸多挑战:无法记住历史对话、无法执行外部操作、缺乏领域专业知识等。正是在这样的背景下,AI Agent 的概念应运而生——通过为 LLM 扩展 Memory(记忆)、Tool(工具)、RAG(检索增强生成)等能力,使其能够自主完成复杂的任务。
本文将深入探讨 AI Agent 的核心组成部分之一——工具体系,特别是新兴的 MCP(Model Context Protocol)协议,以及如何通过 MCP 构建强大的 AI 工具生态系统。
AI Agent 本质上是对传统 LLM 的增强和扩展。它不再只是一个被动的问答机器人,而是一个能够主动思考、规划、记忆、行动的智能体。这种能力的提升主要来源于四个核心组件:
在 AI Agent 的四大支柱中,Tool 的作用尤为关键。LLM 本身只能处理文本信息,而 Tool 则是连接 LLM 与现实世界的桥梁。通过 Tool,Agent 可以:
随着 AI Agent 应用的日益复杂,开发者需要集成越来越多的外部工具。这些工具可能来自不同的语言(Java、Python、Rust)、不同的平台(本地、远程)、不同的供应商(企业内部、第三方服务商)。如果没有统一的标准,每个工具都需要单独的集成方式,这不仅增加了开发复杂度,也降低了系统的可维护性和可扩展性。
为了应对这一挑战,Anthropic 公司提出了 MCP(Model Context Protocol)协议。MCP 的目标是建立一个标准化的通信协议,让 LLM 能够以统一的方式发现、调用各种外部工具和服务。
MCP 协议的核心架构由三个关键组件构成:
Model 指的是大语言模型本身,如 OpenAI 的 GPT 系列、Anthropic 的 Claude 等。在 MCP 架构中,Model 是工具的使用者和调度者。它通过自然语言理解用户意图,然后决定需要调用哪些工具来完成任务,并处理工具返回的结果。
Context 是指 AI 模型在处理任务时所需的所有相关信息。根据行业实践,Context 通常由三个部分组成:
Protocol 指的是 MCP 协议本身,它定义了 Model 与外部服务之间的通信标准。MCP 协议支持多种通信方式,包括:
MCP 协议相比传统的工具集成方式具有显著优势:
MCP Server 是工具的提供方,负责实现具体的业务逻辑。它通过 MCP 协议向外界暴露可用的工具和服务。以下是 MCP Server 的核心实现:
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';
// 数据服务层
const database = {
users: {
"001": { id: "001", name: "张三", email: "zhangsan@example.com", role: "admin" },
"002": { id: "002", name: "李四", email: "lisi@example.com", role: "user" },
"003": { id: "003", name: "王五", email: "wangwu@example.com", role: "user" },
}
}
// 创建 MCP 服务器实例
const server = new McpServer({
name: 'my-mcp-server',
version: '1.0.0',
});
// 注册工具 - query-user
server.registerTool('query-user', {
description: '查询数据库中的用户信息。输入用户ID, 返回该用户的详细信息(姓名、邮箱、角色)。',
inputSchema: {
userId: z.string().describe("用户 ID, 例如:001, 002, 003")
}
}, async ({ userId }) => {
const user = database.users[userId];
if (!user) {
return {
content: [
{
type: 'text',
text: `用户ID ${userId} 不存在。可用的ID: 001, 002, 003`
}
]
}
} else {
return {
content: [
{
type: 'text',
text: `用户信息:n- ID: ${user.id}n- 姓名: ${user.name}n- 邮箱: ${user.email}n- 角色: ${user.role}`
}
]
}
}
});
// 注册资源 - 使用指南
server.registerResource('使用指南', 'docs://guide', {
description: 'MCP Server 使用文档',
mimeType: 'text/plain',
}, async () => {
return {
contents: [
{
uri: 'docs://guide',
mimeType: 'text/plain',
text: `MCP Server 使用指南
功能:提供用户查询等工具。
使用:在 Cursor 等 MCP Client 中通过自然语言对话,Cursor 会自动调用相应工具。`,
}
]
}
});
// 建立通信连接
const transport = new StdioServerTransport();
await server.connect(transport);
在这个例子中,MCP Server 注册了两个组件:
query-user 工具,用于查询用户信息。使用指南 资源,提供文档说明。MCP Client 是工具的消费者,负责连接 MCP Server 并获取可用的工具列表。以下是 MCP Client 的实现:
import 'dotenv/config';
import { MultiServerMCPClient } from '@langchain/mcp-adapters';
import { ChatOpenAI } from '@langchain/openai';
import { HumanMessage, ToolMessage } from '@langchain/core/messages';
import chalk from 'chalk';
// 创建 LLM 实例
const model = new ChatOpenAI({
modelName: process.env.MODEL_NAME,
apiKey: process.env.OPENAI_API_KEY,
configuration: {
baseURL: process.env.OPENAI_BASE_URL,
}
});
// 创建 MCP 客户端
const mcpClient = new MultiServerMCPClient({
mcpServers: {
'my-mcp-server': {
command: 'node',
args: ["D:/htmllearn/cssde/ai/agent/mini-cursor/mcp/my-mcp-server.mjs"],
},
},
});
// 获取可用工具
const tools = await mcpClient.getTools();
console.log(tools, '获取的工具列表');
// 将工具绑定到模型
const modelWithTools = model.bindTools(tools);
// Agent 执行函数
async function runAgentWithTools(query, maxIterations = 30) {
const messages = [new HumanMessage(query)];
for (let i = 0; i < maxIterations; i++) {
console.log(chalk.bgGreen('正在等待AI思考...'));
const response = await modelWithTools.invoke(messages);
messages.push(response);
// 检查是否有工具调用
if (!response.tool_calls || response.tool_calls.length === 0) {
console.log(`n AI 最终回复:n ${response.content}n`);
return response.content;
}
console.log(chalk.bgBlue(`检测到 ${response.tool_calls.length} 个工具调用`));
console.log(chalk.bgBlue(`工具调用: ${response.tool_calls.map(t => t.name).join(', ')}`));
// 执行工具调用
for (const toolCall of response.tool_calls) {
const foundTool = tools.find(t => t.name === toolCall.name);
if (foundTool) {
const toolResult = await foundTool.invoke(toolCall.args);
messages.push(new ToolMessage({
content: toolResult,
tool_call_id: toolCall.id
}));
}
}
}
return messages[messages.length - 1].content;
}
// 执行查询
const result = await runAgentWithTools("查一下用户 002 的信息");
console.log(result, '最终结果');
await mcpClient.close();
MCP Client 和 Server 之间通过标准化的通信方式进行交互:
在 Cursor、VS Code 等编程工具中,MCP 协议使得 AI 能够调用各种编程相关的工具:
MCP 协议的推广将促进 AI 工具生态系统的形成:
MCP 协议有望成为 AI Agent 工具集成的事实标准,推动以下发展:
MCP(Model Context Protocol)协议作为 AI Agent 工具集成的重要标准,解决了传统工具集成中的复杂性问题。通过标准化的通信协议,MCP 实现了 Model、Context、Protocol 三者的有机结合,使得 AI Agent 能够更加高效地利用外部工具,从而具备更强的实用性和扩展性。随着 MCP 生态的不断完善,我们有理由相信,未来的 AI Agent 将变得更加智能、强大和实用,真正实现人工智能技术的广泛应用。