一个使用 TypeScript 编写的库,使 AI 代理能够利用 MCP(模型上下文协议)服务器来增强其功能。该库与 AI SDK v5 集成,提供了一种无缝连接到 MCP 服务器并在 AI 应用程序中使用其工具的方法。
npm install mcp-ai-agent
要查看全面的示例实现,请访问 mcp-ai-agent-example 仓库。
这是使用预配置服务器的基本方式:
import { AIAgent, Servers } from "mcp-ai-agent";
import { openai } from "@ai-sdk/openai";
// 使用预配置服务器
const agent = new AIAgent({
name: "顺序思维代理",
description: "此代理可用于解决复杂任务",
model: openai("gpt-4o-mini"),
toolsConfigs: [Servers.sequentialThinking],
});
// 使用代理
const response = await agent.generateResponse({
prompt: "25 * 25 是多少?",
});
console.log(response.text);
您可以创建专门的代理并将它们组合成一个主代理,该主代理可以分配任务:
import { AIAgent, Servers } from "mcp-ai-agent";
import { openai } from "@ai-sdk/openai";
// 为不同任务创建专门的代理
const sequentialThinkingAgent = new AIAgent({
name: "顺序思考者",
description: "使用此代理进行顺序思考并解决复杂问题",
model: openai("gpt-4o-mini"),
toolsConfigs: [Servers.sequentialThinking],
});
const braveSearchAgent = new AIAgent({
name: "勇敢搜索",
description: "使用此代理在网络上搜索最新信息",
model: openai("gpt-4o-mini"),
toolsConfigs: [Servers.braveSearch],
});
const memoryAgent = new AIAgent({
name: "记忆代理",
description: "使用此代理存储和检索记忆",
model: openai("gpt-4o-mini"),
toolsConfigs: [
{
mcpServers: {
memory: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-memory"],
},
},
},
],
});
// 创建一个可以使用所有专门代理的主代理
const masterAgent = new AIAgent({
name: "主代理",
description: "一个可以管理和分配给专门代理的任务的代理",
model: openai("gpt-4o"),
toolsConfigs: [
{
type: "agent",
agent: sequentialThinkingAgent,
},
{
type: "agent",
agent: memoryAgent,
},
{
type: "agent",
agent: braveSearchAgent,
},
],
});
// 使用主代理
const response = await masterAgent.generateResponse({
prompt: "最新的比特币价格是多少?将答案存储在记忆中。",
});
console.log(response.text);
// 您可以询问记忆代理关于主代理存储的信息
const memoryResponse = await masterAgent.generateResponse({
prompt: "我们存储了哪些关于比特币价格的信息?",
});
console.log(memoryResponse.text);
MCP AI Agent 可用于创建一组协同工作的专门代理,类似于 Crew AI 模式。这里是一个使用多个专门代理设置项目管理流程的例子:
import { AIAgent, CrewStyleHelpers, Servers } from "mcp-ai-agent";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";
import * as dotenv from "dotenv";
// 加载环境变量
dotenv.config();
// 项目详情
const projectDetails = {
project: "网站",
industry: "科技",
team_members: [
"John Doe (项目经理)",
"Jane Doe (软件工程师)",
"Bob Smith (设计师)",
"Alice Johnson (质量保证工程师)",
"Tom Brown (质量保证工程师)",
],
project_requirements: [
"响应式设计桌面和移动设备",
"现代用户界面",
"直观的导航系统",
"关于我们页面",
"服务页面",
"带有表单的联系页面",
"博客部分",
"搜索引擎优化",
"社交媒体整合",
"客户评价部分",
],
};
// 定义任务
const tasks = {
task_breakdown: (details) => ({
description: `分解${details.project}项目的具体要求为单独的任务。`,
expected_output: `包含描述、时间线和依赖关系的详细任务列表。`,
}),
time_estimation: (details) => ({
description: `估计${details.project}项目中每个任务的时间和资源。`,
expected_output: `每个任务的详细估算报告。`,
}),
resource_allocation: (details) => ({
description: `根据技能和可用性将任务分配给团队成员。`,
expected_output: `包含分配和时间线的资源分配图表。`,
}),
};
// 创建代理
const agent = new AIAgent({
name: "顺序思维代理",
description: "顺序思维代理",
toolsConfigs: [Servers.sequentialThinking],
});
// 定义组员
const crew = {
planner: {
name: "项目规划师",
goal: "将项目分解为可操作的任务",
backstory: "具有细节关注经验的项目经理",
agent: agent,
model: openai("gpt-4o-mini"),
},
estimator: {
name: "估算分析师",
goal: "提供准确的时间和资源估算",
backstory: "采用数据驱动方法的项目估算专家",
agent: agent,
model: openai("gpt-4o-mini"),
},
allocator: {
name: "资源分配者",
goal: "优化团队成员之间的任务分配",
backstory: "团队动态和资源管理专家",
agent: agent,
model: openai("gpt-4o-mini"),
},
};
// 定义模式
const planSchema = z.object({
rationale: z.string(),
tasks: z.array(
z.object({
task_name: z.string(),
estimated_time_hours: z.number(),
required_resources: z.array(z.string()),
assigned_to: z.string(),
start_date: z.string(),
end_date: z.string(),
})
),
milestones: z.array(
z.object({
milestone_name: z.string(),
tasks: z.array(z.string()),
deadline: z.string(),
})
),
workload_distribution: z
.record(z.string(), z.number())
.describe("分配给每个团队成员的总小时数"),
});
async function runWorkflow() {
// 执行规划任务
const projectPlan = await CrewStyleHelpers.executeTask({
agent: crew.planner,
task: tasks.task_breakdown(projectDetails),
});
console.log("项目计划:", projectPlan.text);
// 执行估算任务
const timeEstimation = await CrewStyleHelpers.executeTask({
agent: crew.estimator,
task: tasks.time_estimation(projectDetails),
previousTasks: { projectPlan: projectPlan.text },
});
console.log("时间估算:", timeEstimation.text);
// 执行分配任务
const resourceAllocation = await CrewStyleHelpers.executeTask({
agent: crew.allocator,
task: tasks.resource_allocation(projectDetails),
previousTasks: {
projectPlan: projectPlan.text,
timeEstimation: timeEstimation.text,
},
schema: planSchema,
});
console.log(
"资源分配:",
JSON.stringify(resourceAllocation.object, null, 2)
);
// 清理
await agent.close();
}
runWorkflow().catch(console.error);
您可以通过以下方式轻松地向您的代理添加自定义工具:
import { AIAgent } from "mcp-ai-agent";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";
// 创建一个带有自定义工具的代理
const calculatorAgent = new AIAgent({
name: "计算器代理",
description: "一个可以执行数学运算的代理",
model: openai("gpt-4o-mini"),
toolsConfigs: [
{
type: "tool",
name: "乘法",
description: "两个数字相乘",
parameters: z.object({
number1: z.number(),
number2: z.number(),
}),
execute: async (args) => {
return args.number1 * args.number2;
},
},
{
type: "tool",
name: "加法",
description: "两个数字相加",
parameters: z.object({
number1: z.number(),
number2: z.number(),
}),
execute: async (args) => {
return args.number1 + args.number2;
},
},
],
});
// 使用带有自定义工具的代理
const response = await calculatorAgent.generateResponse({
prompt: "125 * 37 是多少?",
});
console.log(response.text);
MCP AI Agent 内置支持以下服务器:
您可以轻松地通过导入 Servers 命名空间来使用任何支持的服务器:
import { AIAgent, Servers } from "mcp-ai-agent";
// 使用单一服务器
const agent1 = new AIAgent({
name: "顺序思维代理",
description: "顺序思维代理",
toolsConfigs: [Servers.sequentialThinking],
});
// 组合多个服务器
const agent2 = new AIAgent({
name: "多功能代理",
description: "具有多种功能的代理",
toolsConfigs: [
Servers.sequentialThinking,
Servers.memory,
Servers.braveSearch,
],
});
我们欢迎贡献以增加对额外 MCP 服务器的支持!要添加新服务器:
src/servers 目录下按照现有模式创建一个新的文件src/servers/index.ts 导出中示例服务器配置格式:
import { MCPAutoConfig } from "../types.js";
export const yourServerName: MCPAutoConfig = {
type: "auto",
name: "your-server-name",
description: "您的服务器的功能描述",
toolsDescription: {
toolName1: "第一个工具的描述",
toolName2: "第二个工具的描述",
},
parameters: {
API_KEY: {
description: "您的服务的 API 密钥",
required: true,
},
},
mcpConfig: {
command: "npx",
args: ["-y", "@your-org/your-mcp-server-package"],
},
};
您可以使用多个服务器初始化代理:
import { AIAgent, Servers } from "mcp-ai-agent";
import { openai } from "@ai-sdk/openai";
// 组合多个预配置服务器
const agent = new AIAgent({
name: "多功能代理",
description: "具有多种专业功能的代理",
toolsConfigs: [Servers.sequentialThinking, Servers.memory, Servers.fetch],
});
const response = await agent.generateResponse({
prompt: "25 * 25 是多少?",
model: openai("gpt-4o-mini"),
});
console.log(response.text);
import { AIAgent } from "mcp-ai-agent";
import { openai } from "@ai-sdk/openai";
const agent = new AIAgent({
name: "自定义服务器代理",
description: "使用手动配置的顺序思维服务器的代理",
model: openai("gpt-4o-mini"),
toolsConfigs: [
{
mcpServers: {
"顺序思维": {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-sequential-thinking"],
},
},
},
],
});
const response = await agent.generateResponse({
prompt: "25 * 25 是多少?",
});
console.log(response.text);
您还可以使用服务器发送事件(SSE)传输连接到 MCP 服务器:
import { AIAgent } from "mcp-ai-agent";
import { openai } from "@ai-sdk/openai";
const agent = new AIAgent({
name: "SSE 传输代理",
description: "使用 SSE 传输连接远程服务器的代理",
model: openai("gpt-4o-mini"),
toolsConfigs: [
{
mcpServers: {
"顺序思维": {
type: "sse",
url: "https://your-mcp-server.com/sequential-thinking",
headers: {
"x-api-key": "your-api-key",
},
},
},
},
],
});
const response = await agent.generateResponse({
prompt: "25 * 25 是多少?",
});
console.log(response.text);
您可以在消息中包含图像:
import { AIAgent, Servers } from "mcp-ai-agent";
import { openai } from "@ai-sdk/openai";
import fs from "fs";
const agent = new AIAgent({
name: "图像处理代理",
description: "能够处理图像的代理",
model: openai("gpt-4o-mini"),
toolsConfigs: [Servers.sequentialThinking],
});
const response = await agent.generateResponse({
messages: [
{
role: "user",
content: [
{
type: "text",
text: "使用顺序思维解决以下方程",
},
{
type: "image",
image: fs.readFileSync("./path/to/equation.png"),
},
],
},
],
});
console.log(response.text);
await agent.close();
您也可以处理 PDF:
import { AIAgent, Servers } from "mcp-ai-agent";
import { openai } from "@ai-sdk/openai";
import fs from "fs";
const agent = new AIAgent({
name: "PDF 处理代理",
description: "能够处理 PDF 文档的代理",
model: openai("gpt-4o-mini"),
toolsConfigs: [Servers.sequentialThinking],
});
const response = await agent.generateResponse({
messages: [
{
role: "user",
content: [
{
type: "text",
text: "使用顺序思维解决以下方程",
},
{
type: "file",
data: fs.readFileSync("./path/to/equation.pdf"),
filename: "equation.pdf",
mediaType: "application/pdf",
},
],
},
],
});
console.log(response.text);
await agent.close();
您可以结合预配置服务器和手动配置的服务器:
import { AIAgent, Servers } from "mcp-ai-agent";
import { openai } from "@ai-sdk/openai";
// 创建一个同时包含预配置和自定义服务器的代理
const agent = new AIAgent({
name: "混合配置代理",
description: "结合预配置和自定义服务器配置的代理",
model: openai("gpt-4o"),
toolsConfigs: [
// 使用来自 Servers 命名空间的预配置服务器
Servers.sequentialThinking,
// 添加一个手动配置的服务器
{
mcpServers: {
"自定义 API 服务器": {
type: "sse",
url: "https://api.example.com/mcp-endpoint",
headers: {
Authorization: `Bearer ${process.env.API_TOKEN}`,
"Content-Type": "application/json",
},
},
},
},
// 添加另一个预配置服务器
Servers.memory,
],
});
const response = await agent.generateResponse({
prompt: "搜索有关 AI 代理的信息并将结果存储在内存中",
// 可选过滤要使用的工具
filterMCPTools: (tool) => {
// 只使用来自可用服务器的特定工具
return ["顺序思维", "记忆", "自定义 API 搜索"].includes(tool.name);
},
});
console.log(response.text);
await agent.close();
您还可以创建并使用自己的自动配置服务器库定义:
import { AIAgent, MCPAutoConfig } from "mcp-ai-agent";
import { openai } from "@ai-sdk/openai";
// 定义一个自定义服务器配置
const customVectorDB: MCPAutoConfig = {
type: "auto",
name: "向量数据库",
description: "向量数据库工具,用于语义搜索