关于 MCP AI Agent
MCP AI Agent 是一个 TypeScript 库,让 AI Agent 能够调用 MCP 服务提供的工具。它与 AI SDK v5 集成,适合需要连接多个 MCP 服务并在应用中组合 Agent 的开发者。库内置多种常用服务配置,并支持 Agent 之间的相互调用。
主要功能
- 01通过 STDIO 和 SSE 连接多个 MCP 服务
- 02自动发现并调用 MCP 服务的工具
- 03支持自定义工具与 MCP 工具组合过滤
- 04多 Agent 组合与 Agent 间调用
- 05内置多个预配置 MCP 服务
适用场景
- 01为 TypeScript 应用添加带工具调用的文本生成
- 02组合多个专业 Agent 完成项目管理等复合任务
- 03在 Agent 中接入检索、记忆或 SQLite 数据库工具
MCP 相关
该项目是一个 MCP 客户端库,负责连接 STDIO 或 SSE 类型的 MCP 服务,并将其工具提供给 AI SDK 驱动的 Agent。
详细介绍
MCP AI Agent
一个 TypeScript 库,可让 AI Agent 借助 MCP(Model Context Protocol)服务增强能力。该库与 AI SDK v5 集成,提供无缝方式连接 MCP 服务,并在 AI 驱动的应用中使用其工具。
功能
- 使用不同的传输方式(STDIO、SSE)连接多个 MCP 服务
- 自动发现并使用 MCP 服务中的工具
- 与 AI SDK 集成,通过工具使用生成文本
- 筛选并组合 MCP 工具与自定义工具
- 预配置服务,便于初始化
- 支持自动配置,简化设置
- Agent 可以为特定任务调用其他 Agent
- Agent 组合——创建专用 Agent 并将其组合起来
- 为 Agent 命名并添加描述,以便更好地识别
- 自动初始化 Agent(无需显式调用 initialize)
- 直接在 Agent 配置中定义自定义工具
- 支持默认模型,简化多 Agent 系统的搭建
- 集成系统提示词,实现专用行为
- 提供详细模式,便于调试
路线图
- 集成 MCP 工具的基础 Agent
- 自动处理 MCP 服务
- 多 Agent 工作流
- 基于函数的工具处理程序
- 自动将 Swagger/OpenAPI 转换为工具(无状态服务的简单集成)
- API 服务实现(在服务端调用你的 Agent)
- 可观测性系统
安装
npm install mcp-ai-agent
如需查看完整的示例实现,请访问 mcp-ai-agent-example 仓库。
最简示例
下面介绍使用预配置服务的 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);
多 Agent 工作流(Agent 组合)
你可以创建专用 Agent,并将它们组合成一个能够分派任务的主 Agent:
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);
Crew AI 风格的工作流
MCP AI Agent 可用于创建一组协同工作的专用 Agent,以完成复杂任务,类似于 Crew AI 模式。下面以使用多个专用 Agent 设置项目管理工作流为例:
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);
自定义工具
你可以轻松地将自定义工具直接添加到 Agent:
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 预配置支持以下服务:
- Sequential Thinking:将复杂问题分解为多个步骤
- Memory:为对话上下文提供持久记忆
- AWS KB Retrieval:从 AWS 知识库检索信息
- Brave Search:使用 Brave Search API 执行网页搜索
- Everart:使用 AI 创建和处理图像
- Fetch:从 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"],
},
};
使用多个服务
你可以使用多个服务初始化 Agent:
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
简化 Agent 配置并提供增强功能的主要类。
构造函数
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>>
使用 AI 模型和来自 MCP 服务及自定义工具的工具生成响应。
参数:
prompt- 用户要回复的消息model- 可选:覆盖默认模型system- 可选:覆盖默认系统提示词maxSteps- AI 执行的最大步数(默认值:20)tools- 向模型提供的其他工具filterMCPTools- 可选函数,用于筛选要使用的 MCP 工具onStepFinish- 可选回调函数,在每一步后调用messages- prompt 的替代方案,允许使用富内容消息
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; }
返回关于 Agent 的信息,包括其名称、描述、可用工具、Agent 和默认模型。
许可证
MIT
评论
一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。