AI Agent with MCP Demo
这是一个完整的 AI Agent 示例项目,展示如何集成外部 LLM 和 MCP (Model Context Protocol) 工具服务器。
🏗️ 架构说明
核心组件
┌─────────────┐
│ 用户输入 │
└──────┬──────┘
│
▼
┌─────────────────────────────────────┐
│ AI Agent (agent.js) │
│ ┌───────────────────────────────┐ │
│ │ 对话循环 (Agentic Loop) │ │
│ │ 1. 调用 LLM │ │
│ │ 2. 检查是否需要工具 │ │
│ │ 3. 执行工具 │ │
│ │ 4. 返回结果给 LLM │ │
│ │ 5. 重复直到得到最终答案 │ │
│ └───────────────────────────────┘ │
└────────┬──────────────────┬─────────┘
│ │
▼ ▼
┌─────────────────┐ ┌──────────────────┐
│ LLM API │ │ MCP Client │
│ (ollama) │ │ (mcp-client.js) │
└─────────────────┘ └────────┬─────────┘
│
▼
┌──────────────────┐
│ MCP Server │
│ (mcp-server.js) │
│ │
│ - Calculator │
│ - Weather Tool │
└──────────────────┘技术栈
- 运行时: Node.js (ESM 模块)
- LLM SDK: @anthropic-ai/sdk (可替换为 OpenAI SDK 等)
- MCP SDK: @modelcontextprotocol/sdk
- 环境变量: dotenv
📁 项目结构
ai-agent-demo/
├── src/
│ ├── index.js # 主入口 (ollama)
│ ├── agent.js # ollama Agent 实现
│ ├── mcp-client.js # MCP 客户端
│ └── mcp-server.js # MCP 工具服务器
├── package.json
├── .env # 环境变量配置
├── README.md # 主文档🚀 快速开始
1. 安装依赖
cd ai-agent-demo
npm install2. 配置环境变量
复制 .env.example 为 .env,并填入你的 API Key:
cp .env.example .env使用 Ollama 本地模型 (免费、无需 API Key):
# 1. 安装 Ollama
curl -fsSL https://ollama.com/install.sh | sh
# 2. 下载模型
ollama pull qwen2.5:7b
# 3. 启动服务
ollama serve详见: OLLAMA.md
3. 运行示例
npm run start💡 核心原理详解
1. MCP 协议
MCP (Model Context Protocol) 是一个标准化的协议,让 AI 模型能够安全地使用外部工具。
工具定义示例:
{
name: 'calculator',
description: '执行基本数学运算',
inputSchema: {
type: 'object',
properties: {
operation: { type: 'string', enum: ['add', 'subtract'] },
a: { type: 'number' },
b: { type: 'number' }
}
}
}2. Agent 循环 (Agentic Loop)
这是 AI Agent 的核心工作流程:
while (未完成任务) {
// 1. 调用 LLM,提供可用工具列表
response = await callLLM(messages, tools);
// 2. 检查 LLM 是否想使用工具
if (response.包含工具调用) {
// 3. 执行工具
toolResults = await executeTools(response.工具调用);
// 4. 将工具结果添加到对话历史
messages.push(toolResults);
// 5. 继续循环,让 LLM 基于工具结果继续思考
} else {
// 6. LLM 给出最终答案,结束循环
return response.最终答案;
}
}3. LLM 工具调用流程
第 1 轮:
用户: 帮我计算 123 加 456
LLM 返回:
{
content: [
{ type: "tool_use", name: "calculator", input: { operation: "add", a: 123, b: 456 } }
]
}执行工具,得到结果: "计算结果: 123 add 456 = 579"
第 2 轮:
(自动将工具结果发送回 LLM)
LLM 返回:
{
content: [
{ type: "text", text: "123 加 456 等于 579" }
]
}🔧 自定义和扩展
添加新工具
在 src/mcp-server.js 中添加工具定义:
{
name: 'my_new_tool',
description: '我的新工具',
inputSchema: {
type: 'object',
properties: {
param1: { type: 'string', description: '参数1' }
},
required: ['param1']
}
}然后在 CallToolRequestSchema 处理器中添加执行逻辑:
if (name === 'my_new_tool') {
return {
content: [{ type: 'text', text: '工具执行结果' }]
};
}连接到远程 MCP 服务器
MCP 支持多种传输方式(stdio、HTTP、WebSocket)。修改 src/mcp-client.js:
// 使用 HTTP 传输
import { HTTPClientTransport } from '@modelcontextprotocol/sdk/client/http.js';
const transport = new HTTPClientTransport({
url: 'http://localhost:3000/mcp'
});🎯 关键概念总结
- 工具调用 (Tool Calling): LLM 可以请求执行外部函数/工具
- MCP 协议: 标准化的工具定义和调用协议
- Agent 循环: 通过多轮对话实现复杂任务
- 上下文管理: 维护对话历史和工具执行结果
- 异步流程: 所有 I/O 操作都是异步的
- 工具扩展: 支持外部 API、本地接口、数据库等集成
支持的功能:
- 💾 数据库查询(MySQL)
- 🐙 GitHub 集成
- 🌤️ 真实天气 API
详细文档:
- MCP_QUICKSTART.md - 5分钟快速上手
- MCP_EXTENSION_GUIDE.md - 完整扩展指南
