使用说明
MCP AI代理
一个TypeScript库,使AI代理能够利用MCP(模型上下文协议)服务器来增强功能。该库与AI SDK v5集成,提供了一种无缝连接到MCP服务器并在AI驱动的应用程序中使用其工具的方法。
特性
- 使用不同的传输方法(STDIO、SSE)连接到多个MCP服务器
- 自动发现和使用MCP服务器中的工具
- 与AI SDK集成,使用工具生成文本
- 过滤MCP工具并将其与自定义工具组合
- 预配置的服务器,便于初始化
- 自动配置支持,简化设置
- 代理可以调用其他代理执行特定任务
- 代理组合-创建专门的代理并将其组合起来
- 带有描述的命名代理,以提高识别能力
- 自动初始化代理(无需显式调用initialize)
- 直接在代理配置中自定义工具定义
- 简化多代理系统的默认模型支持
- 专业行为的系统快速集成
- 详细调试模式
路线图
- [x] 集成MCP工具的基本代理
- [x] 自动处理MCP服务器
- [x] 多代理工作流
- [x] 基于函数的工具处理程序
- []自动Swagger/OpenAPI到工具的转换(无状态服务器简单集成)
- []API服务器实现(在服务器上调用代理)
- []观测系统
安装
npm install mcp-ai-agent
有关完整的示例实现,请查看 mcp-ai代理示例 存储库。
最小示例
以下是将AI Agent与预配置服务器一起使用的最基本方法:
import { AIAgent, Servers } from "mcp-ai-agent";
import { openai } from "@ai-sdk/openai";
// Use a preconfigured server
const agent = new AIAgent({
name: "Sequential Thinking Agent",
description: "This agent can be used to solve complex tasks",
model: openai("gpt-4o-mini"),
toolsConfigs: [Servers.sequentialThinking],
});
// Use the agent
const response = await agent.generateResponse({
prompt: "What is 25 * 25?",
});
console.log(response.text);
多代理工作流(代理组合)
您可以创建专门的代理,并将其组合成可以委派任务的主代理:
import { AIAgent, Servers } from "mcp-ai-agent";
import { openai } from "@ai-sdk/openai";
// Create specialized agents for different tasks
const sequentialThinkingAgent = new AIAgent({
name: "Sequential Thinker",
description:
"Use this agent to think sequentially and resolve complex problems",
model: openai("gpt-4o-mini"),
toolsConfigs: [Servers.sequentialThinking],
});
const braveSearchAgent = new AIAgent({
name: "Brave Search",
description: "Use this agent to search the web for the latest information",
model: openai("gpt-4o-mini"),
toolsConfigs: [Servers.braveSearch],
});
const memoryAgent = new AIAgent({
name: "Memory Agent",
description: "Use this agent to store and retrieve memories",
model: openai("gpt-4o-mini"),
toolsConfigs: [
{
mcpServers: {
memory: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-memory"],
},
},
},
],
});
// Create a master agent that can use all specialized agents
const masterAgent = new AIAgent({
name: "Master Agent",
description: "An agent that can manage and delegate to specialized agents",
model: openai("gpt-4o"),
toolsConfigs: [
{
type: "agent",
agent: sequentialThinkingAgent,
},
{
type: "agent",
agent: memoryAgent,
},
{
type: "agent",
agent: braveSearchAgent,
},
],
});
// Use the master agent
const response = await masterAgent.generateResponse({
prompt: "What is the latest Bitcoin price? Store the answer in memory.",
});
console.log(response.text);
// You can ask the memory agent about information stored by the master agent
const memoryResponse = await masterAgent.generateResponse({
prompt: "What information have we stored about Bitcoin price?",
});
console.log(memoryResponse.text);
船员AI风格的工作流程
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";
// Load environment variables
dotenv.config();
// Project details
const projectDetails = {
project: "Website",
industry: "Technology",
team_members: [
"John Doe (Project Manager)",
"Jane Doe (Software Engineer)",
"Bob Smith (Designer)",
"Alice Johnson (QA Engineer)",
"Tom Brown (QA Engineer)",
],
project_requirements: [
"Responsive design for desktop and mobile",
"Modern user interface",
"Intuitive navigation system",
"About Us page",
"Services page",
"Contact page with form",
"Blog section",
"SEO optimization",
"Social media integration",
"Testimonials section",
],
};
// Define tasks
const tasks = {
task_breakdown: (details) => ({
description: `Break down the ${details.project} project requirements into individual tasks.`,
expected_output: `A comprehensive list of tasks with descriptions, timelines, and dependencies.`,
}),
time_estimation: (details) => ({
description: `Estimate time and resources for each task in the ${details.project} project.`,
expected_output: `A detailed estimation report for each task.`,
}),
resource_allocation: (details) => ({
description: `Allocate tasks to team members based on skills and availability.`,
expected_output: `A resource allocation chart with assignments and timeline.`,
}),
};
// Create agent
const agent = new AIAgent({
name: "Sequential Thinking Agent",
description: "A sequential thinking agent",
toolsConfigs: [Servers.sequentialThinking],
});
// Define crew members
const crew = {
planner: {
name: "Project Planner",
goal: "Break down the project into actionable tasks",
backstory: "Experienced project manager with attention to detail",
agent: agent,
model: openai("gpt-4o-mini"),
},
estimator: {
name: "Estimation Analyst",
goal: "Provide accurate time and resource estimations",
backstory: "Expert in project estimation with data-driven approach",
agent: agent,
model: openai("gpt-4o-mini"),
},
allocator: {
name: "Resource Allocator",
goal: "Optimize task allocation among team members",
backstory: "Specialist in team dynamics and resource management",
agent: agent,
model: openai("gpt-4o-mini"),
},
};
// Define schema
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("Total hours allocated to each team member"),
});
async function runWorkflow() {
// Execute planning task
const projectPlan = await CrewStyleHelpers.executeTask({
agent: crew.planner,
task: tasks.task_breakdown(projectDetails),
});
console.log("Project Plan:", projectPlan.text);
// Execute estimation task
const timeEstimation = await CrewStyleHelpers.executeTask({
agent: crew.estimator,
task: tasks.time_estimation(projectDetails),
previousTasks: { projectPlan: projectPlan.text },
});
console.log("Time Estimation:", timeEstimation.text);
// Execute allocation task
const resourceAllocation = await CrewStyleHelpers.executeTask({
agent: crew.allocator,
task: tasks.resource_allocation(projectDetails),
previousTasks: {
projectPlan: projectPlan.text,
timeEstimation: timeEstimation.text,
},
schema: planSchema,
});
console.log(
"Resource Allocation:",
JSON.stringify(resourceAllocation.object, null, 2)
);
// Cleanup
await agent.close();
}
runWorkflow().catch(console.error);
自定义工具
您可以轻松地将自定义工具直接添加到您的代理中:
import { AIAgent } from "mcp-ai-agent";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";
// Create an agent with custom tools
const calculatorAgent = new AIAgent({
name: "Calculator Agent",
description: "An agent that can perform mathematical operations",
model: openai("gpt-4o-mini"),
toolsConfigs: [
{
type: "tool",
name: "multiply",
description: "Multiplies two numbers",
parameters: z.object({
number1: z.number(),
number2: z.number(),
}),
execute: async (args) => {
return args.number1 * args.number2;
},
},
{
type: "tool",
name: "add",
description: "Adds two numbers",
parameters: z.object({
number1: z.number(),
number2: z.number(),
}),
execute: async (args) => {
return args.number1 + args.number2;
},
},
],
});
// Use the agent with custom tools
const response = await calculatorAgent.generateResponse({
prompt: "What is 125 * 37?",
});
console.log(response.text);
支持的MCP服务器
MCP AI Agent附带了对以下服务器的预配置支持:
- 顺序思维:用于将复杂问题分解为步骤
- 记忆:对话上下文的持久记忆
- AWS知识库检索:从AWS知识库检索信息
- 勇敢的搜索:使用Brave Search API执行web搜索
- 埃弗拉特:使用AI创建和操作图像
- 获取:从URL检索数据
- Firecrawl MCP:网络爬行和检索功能
- SQLite:查询和操作SQLite数据库
使用支持的服务器
通过从导入,您可以轻松使用任何受支持的服务器 Servers 命名空间:
import { AIAgent, Servers } from "mcp-ai-agent";
// Use single server
const agent1 = new AIAgent({
name: "Sequential Thinking Agent",
description: "Agent for sequential thinking",
toolsConfigs: [Servers.sequentialThinking],
});
// Combine multiple servers
const agent2 = new AIAgent({
name: "Multi-Tool Agent",
description: "Agent with multiple capabilities",
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: "Description of what your server does",
toolsDescription: {
toolName1: "Description of first tool",
toolName2: "Description of second tool",
},
parameters: {
API_KEY: {
description: "API key for your service",
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";
// Combine multiple preconfigured servers
const agent = new AIAgent({
name: "Multi-Capability Agent",
description: "An agent with multiple specialized capabilities",
toolsConfigs: [Servers.sequentialThinking, Servers.memory, Servers.fetch],
});
const response = await agent.generateResponse({
prompt: "What is 25 * 25?",
model: openai("gpt-4o-mini"),
});
console.log(response.text);
手动使用Stdio工具
import { AIAgent } from "mcp-ai-agent";
import { openai } from "@ai-sdk/openai";
const agent = new AIAgent({
name: "Custom Server Agent",
description: "Agent using a manually configured sequential thinking server",
model: openai("gpt-4o-mini"),
toolsConfigs: [
{
mcpServers: {
"sequential-thinking": {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-sequential-thinking"],
},
},
},
],
});
const response = await agent.generateResponse({
prompt: "What is 25 * 25?",
});
console.log(response.text);
使用SSE传输
您还可以使用服务器发送事件(SSE)传输连接到MCP服务器:
import { AIAgent } from "mcp-ai-agent";
import { openai } from "@ai-sdk/openai";
const agent = new AIAgent({
name: "SSE Transport Agent",
description: "Agent using SSE transport for remote server connection",
model: openai("gpt-4o-mini"),
toolsConfigs: [
{
mcpServers: {
"sequential-thinking": {
type: "sse",
url: "https://your-mcp-server.com/sequential-thinking",
headers: {
"x-api-key": "your-api-key",
},
},
},
},
],
});
const response = await agent.generateResponse({
prompt: "What is 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: "Image Processing Agent",
description: "Agent capable of processing images",
model: openai("gpt-4o-mini"),
toolsConfigs: [Servers.sequentialThinking],
});
const response = await agent.generateResponse({
messages: [
{
role: "user",
content: [
{
type: "text",
text: "Use sequential thinking to solve the following equation",
},
{
type: "image",
image: fs.readFileSync("./path/to/equation.png"),
},
],
},
],
});
console.log(response.text);
await agent.close();
使用PDF
您还可以处理PDF:
import { AIAgent, Servers } from "mcp-ai-agent";
import { openai } from "@ai-sdk/openai";
import fs from "fs";
const agent = new AIAgent({
name: "PDF Processing Agent",
description: "Agent capable of processing PDF documents",
model: openai("gpt-4o-mini"),
toolsConfigs: [Servers.sequentialThinking],
});
const response = await agent.generateResponse({
messages: [
{
role: "user",
content: [
{
type: "text",
text: "Use sequential thinking to solve the following equation",
},
{
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";
// Create an agent with both preconfigured and custom servers
const agent = new AIAgent({
name: "Hybrid Configuration Agent",
description:
"Agent that combines preconfigured and custom server configurations",
model: openai("gpt-4o"),
toolsConfigs: [
// Use a preconfigured server from the Servers namespace
Servers.sequentialThinking,
// Add a manually configured server
{
mcpServers: {
"custom-api-server": {
type: "sse",
url: "https://api.example.com/mcp-endpoint",
headers: {
Authorization: `Bearer ${process.env.API_TOKEN}`,
"Content-Type": "application/json",
},
},
},
},
// Add another preconfigured server
Servers.memory,
],
});
const response = await agent.generateResponse({
prompt:
"Search for information about AI agents and store the results in memory",
// Optionally filter which tools to use
filterMCPTools: (tool) => {
// Only use specific tools from the available servers
return ["sequentialThinking", "memory", "customApiSearch"].includes(
tool.name
);
},
});
console.log(response.text);
await agent.close();
创建自定义自动配置服务器
您还可以创建和使用自己的自动配置服务器库定义:
import { AIAgent, MCPAutoConfig } from "mcp-ai-agent";
import { openai } from "@ai-sdk/openai";
// Define a custom server configuration
const customVectorDB: MCPAutoConfig = {
type: "auto",
name: "vector-db",
description: "Vector database tools for semantic search and retrieval",
toolsDescription: {
vectorSearch:
"Search for semantically similar documents in the vector database",
vectorStore: "Store documents in the vector database with embeddings",
vectorDelete: "Delete documents from the vector database",
},
parameters: {
VECTOR_DB_API_KEY: {
description: "API key for the vector database service",
required: true,
},
VECTOR_DB_URL: {
description: "URL of the vector database service",
required: true,
},
},
mcpConfig: {
command: "npx",
args: ["-y", "@your-org/vector-db-mcp-server"],
env: {
VECTOR_DB_API_KEY: process.env.VECTOR_DB_API_KEY || "",
VECTOR_DB_URL: process.env.VECTOR_DB_URL || "",
},
},
};
// Create an agent with the custom server and a preconfigured server
const agent = new AIAgent({
name: "Vector DB Agent",
description: "Agent with vector database capabilities",
model: openai("gpt-4o"),
toolsConfigs: [customVectorDB, Servers.sequentialThinking],
});
const response = await agent.generateResponse({
prompt:
"Use sequential thinking to analyze this document and store it in the vector database",
messages: [
{
role: "user",
content: [
{
type: "text",
text: "Analyze this document and store the key points in the vector database",
},
{
type: "file",
data: fs.readFileSync("./path/to/document.pdf"),
filename: "document.pdf",
mediaType: "application/pdf",
},
],
},
],
});
console.log(response.text);
await agent.close();
配置
这 AIAgent 构造函数接受一个名称、描述和多个配置对象:
/**
* Create a new AIAgent with a name, description, and one or more configurations
* @param name - The name of the agent
* @param description - A description of the agent's capabilities
* @param configs - Configuration objects for various MCP servers and sub-agents
*/
constructor(name: string, description: string, ...configs: WorkflowConfig[])
自动配置
这 MCPAutoConfig 接口定义了MCP服务器的自动配置:
/**
* Auto configuration for MCP servers
*/
interface MCPAutoConfig {
/**
* Type identifier for auto configuration
*/
type: "auto";
/**
* The name of the MCP server
*/
name: string;
/**
* The description of the MCP server
*/
description: string;
/**
* Optional GitHub repository URL for the MCP server
*/
gitHubRepo?: string;
/**
* The license of the MCP server
*/
license?: string;
/**
* Description of tools provided by the server
*/
toolsDescription: Record<string, string>;
/**
* Required parameters for the server
*/
parameters: Record<string, { description: string; required: boolean }>;
/**
* The configuration for the MCP server
*/
mcpConfig: MCPServerConfig | MCPServerConfig[];
}
标准配置
这 AIAgentConfig 接口定义了AIAgent的配置:
/**
* Full configuration for AIAgent
* Contains configuration for all MCP servers
*/
interface AIAgentConfig {
/**
* Map of server names to their configurations
*/
mcpServers: Record<string, MCPServerConfig | MCPAutoConfig>;
}
/**
* Union type for different MCP server configuration types
*/
type MCPServerConfig = StdioConfig | SSEConfig;
/**
* Configuration for running an MCP server via command line
*/
interface StdioConfig {
/**
* Command to execute
*/
command: string;
/**
* Command line arguments
*/
args?: string[];
/**
* Environment variables to set
*/
env?: Record<string, string>;
/**
* Standard error handling configuration
*/
stderr?: IOType | Stream | number;
/**
* Working directory for the command
*/
cwd?: string;
}
/**
* Type for handling I/O redirection
* - overlapped: Overlapped I/O mode
* - pipe: Pipe I/O to parent process
* - ignore: Ignore I/O
* - inherit: Inherit I/O from parent process
*/
type IOType = "overlapped" | "pipe" | "ignore" | "inherit";
/**
* Configuration for connecting to an MCP server via Server-Sent Events
*/
interface SSEConfig {
/**
* Type identifier for SSE configuration
*/
type: "sse";
/**
* URL to connect to
*/
url: string;
/**
* HTTP headers to include in the request
*/
headers?: Record<string, string>;
}
API类型
以下类型在整个API中使用:
/**
* Arguments for generating text using an AI model
*/
interface GenerateTextArgs<
TOOLS extends ToolSet = any,
OUTPUT = never,
OUTPUT_PARTIAL = never
> {
/**
* The language model to use
*/
model?: LanguageModel;
/**
* The tools that the model can call
*/
tools?: TOOLS;
/**
* The tool choice strategy. Default: 'auto'
*/
toolChoice?: ToolChoice<TOOLS>;
/**
* Maximum number of steps to take
*/
maxSteps?: number;
/**
* A system message that will be part of the prompt
*/
system?: string;
/**
* A simple text prompt. You can either use `prompt` or `messages` but not both
*/
prompt?: string | Array<ModelMessage>;
/**
* A list of messages. You can either use `prompt` or `messages` but not both
*/
messages?: Array<ModelMessage>;
/**
* Maximum number of tokens to generate
*/
maxOutputTokens?: number;
/**
* Temperature setting for randomness
*/
temperature?: number;
/**
* Nucleus sampling parameter
*/
topP?: number;
/**
* Top-K sampling parameter
*/
topK?: number;
/**
* Presence penalty setting
*/
presencePenalty?: number;
/**
* Frequency penalty setting
*/
frequencyPenalty?: number;
/**
* Stop sequences
*/
stopSequences?: string[];
/**
* Seed for deterministic results
*/
seed?: number;
/**
* Maximum number of retries
*/
maxRetries?: number;
/**
* Abort signal for cancellation
*/
abortSignal?: AbortSignal;
/**
* Additional HTTP headers
*/
headers?: Record<string, string>;
/**
* Stop conditions for multi-step generation
*/
stopWhen?: StopCondition<TOOLS> | Array<StopCondition<TOOLS>>;
/**
* Additional provider-specific options
*/
providerOptions?: ProviderOptions;
/**
* Callback function that is called when a step finishes
*/
onStepFinish?: GenerateTextOnStepFinishCallback<TOOLS>;
/**
* Function to filter which MCP tools should be available
* @param tool The tool to evaluate
* @returns Boolean indicating whether to include the tool
*/
filterMCPTools?: (tool: TOOLS[string]) => boolean;
}
/**
* Tool definition returned by MCP servers
* Represents a callable function that the agent can use
*/
interface MCPTool {
/**
* Name of the tool
*/
name: string;
/**
* Description of what the tool does
*/
description: string;
/**
* Parameter schema for the tool
*/
parameters: {
/**
* JSON Schema type
*/
type: string;
/**
* Properties of the tool parameters
*/
properties: Record<string, any>;
};
}
/**
* Type definition for a collection of tools
* Maps tool names to their definitions
*/
type ToolSet = Record<string, MCPTool>;
/**
* Generic type for tool configurations (AI SDK ToolSet)
*/
type TOOLS = AiToolSet;
/**
* AI response type to handle AI SDK responses
*/
type MCPResponse = GenerateTextResult<any, any>;
API
AIAgent
简化代理配置并提供增强功能的主类。
构造函数
constructor({
name,
description,
systemPrompt,
model,
verbose,
toolsConfigs
}: {
name: string;
description: string;
systemPrompt?: string;
model?: LanguageModel;
verbose?: boolean;
toolsConfigs?: WorkflowConfig[];
})
方法
generateResponse(args: GenerateTextArgs): Promise<GenerateTextResult<TOOLS, any>>
使用人工智能模型以及MCP服务器和自定义工具中的工具生成响应。
论据:
prompt-用户要回复的消息model-可选:覆盖默认模型system-可选:覆盖默认系统提示maxSteps-AI可执行的最大步数(默认值:20)tools-模型可用的其他工具filterMCPTools-可选功能,用于筛选要使用的MCP工具onStepFinish-每个步骤后调用的可选回调函数messages-提示的替代方案,允许内容丰富的消息
generateObject<T>(args: GenerateObjectArgs): Promise<GenerateObjectResult<TOOLS, T>>
使用架构生成结构化对象响应。
论据:
prompt-用户消息model-可选:覆盖默认模型schema-预期响应对象的Zod模式或JSON模式schemaName-架构的可选名称schemaDescription-架构的可选描述
close(): Promise<void>
关闭所有服务器连接。
getInfo(): { name: string; description: string; tools: string[]; agents?: string[]; model?: LanguageModel; }
返回有关代理的信息,包括其名称、描述、可用工具、代理和默认模型。
许可证
麻省理工学院
