Astreus

MCP

在 Astreus 文档中了解 MCP,获取用于构建智能体系统的设置指导、API 模式和实用示例。 了解构建可靠的 Astreus 智能体系统所需的设置模式、API 和实用示例。

用于将代理连接到外部工具和服务的 Model Context Protocol 集成

概述

MCP(Model Context Protocol)使 Astreus 代理能够无缝连接外部工具和服务。将 MCP 服务器定义为简单对象,支持自动加载环境变量,并可在不同层级——代理、任务或对话——中使用。

类型定义

MCPServerDefinition

interface MCPServerDefinition {
  name: string;           // Server name for identification (required)
  command?: string;       // Command to execute (for stdio servers)
  args?: string[];        // Command arguments
  env?: Record<string, string>;  // Environment variable overrides
  url?: string;           // URL for SSE servers
  cwd?: string;           // Working directory
}

MCPTool

interface MCPTool {
  name: string;
  description: string;
  inputSchema: MCPJsonSchema;
}

MCPToolResult

interface MCPToolResult {
  content: Array<{
    type: string;
    text?: string;
  }>;
  isError?: boolean;
}

MCPValue

type MCPPrimitive = string | number | boolean | null;
type MCPValue = MCPPrimitive | MCPPrimitive[] | { [key: string]: MCPValue };

创建 MCP 服务器

将 MCP 服务器定义为数组对象,支持自动加载环境变量:

import { Agent } from '@astreus-ai/astreus';

// Define MCP servers array
const mcpServers = [
  {
    name: 'github',
    command: "npx",
    args: ["-y", "@modelcontextprotocol/server-github"]
    // GITHUB_PERSONAL_ACCESS_TOKEN loaded from .env automatically
  },
  {
    name: 'filesystem', 
    command: "npx",
    args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/username/Documents"]
  }
];

const agent = await Agent.create({
  name: 'DevAgent',
  model: 'gpt-4'
});

// Add MCP servers to agent
await agent.addMCPServers(mcpServers);

// Use automatically in conversations
const response = await agent.ask("List my repositories and save to repos.txt");

示例

以下是一个展示 MCP 集成的完整示例:

import { Agent } from '@astreus-ai/astreus';

// Create agent
const agent = await Agent.create({
  name: 'DevAssistant',
  model: 'gpt-4',
  systemPrompt: 'You are a helpful development assistant with access to various tools.'
});

// Add MCP servers
await agent.addMCPServers([
  {
    name: 'github',
    command: "npx", 
    args: ["-y", "@modelcontextprotocol/server-github"]
  },
  {
    name: 'filesystem',
    command: "npx",
    args: ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/project"]
  },
  {
    name: 'search',
    command: "npx",
    args: ["-y", "@modelcontextprotocol/server-brave-search"]
  }
]);

// Agent now has access to GitHub, filesystem, and search tools
const response = await agent.ask(`
  Check my latest repositories, 
  create a summary file in my project directory,
  and search for TypeScript best practices
`);

console.log(response);

环境变量

MCP 服务器会自动从你的 .env 文件中加载环境变量:

# .env
GITHUB_PERSONAL_ACCESS_TOKEN=ghp_xxxxxxxxxxxx
BRAVE_API_KEY=your_brave_api_key
GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json

无需在代码中指定环境变量——它们会被自动、安全地加载。

服务器类型

本地服务器(stdio)

适用于以本地进程运行的服务器:

const localServers = [
  {
    name: 'sqlite',
    command: "npx",
    args: ["-y", "@modelcontextprotocol/server-sqlite", "--db-path", "/path/to/db.sqlite"],
    cwd: "/working/directory"
  }
];

远程服务器(SSE)

适用于通过 HTTP/SSE 连接的服务器:

const remoteServers = [
  {
    name: 'api-server',
    url: "https://api.example.com/mcp/events"
  }
];

多层级用法

代理层级

适用于所有任务和对话:

// Agent-level: Available everywhere 
await agent.addMCPServers([
  {
    name: 'filesystem',
    command: "npx",
    args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/username/Documents"]
  }
]);

任务层级

适用于特定任务:

// Task-level: Available for this task only
const task = await agent.createTask({
  prompt: "Analyze my GitHub repositories",
  mcpServers: [
    {
      name: 'github',
      command: "npx",
      args: ["-y", "@modelcontextprotocol/server-github"]
    }
  ]
});

对话层级

适用于单次对话:

// Conversation-level: Available for this conversation only
const response = await agent.ask("Search for TypeScript news", {
  mcpServers: [
    {
      name: 'search',
      command: "npx",
      args: ["-y", "@modelcontextprotocol/server-brave-search"]
    }
  ]
});

手动访问工具

以编程方式访问 MCP 工具:

// List available MCP tools
const tools: MCPTool[] = agent.getMCPTools();
console.log('Available MCP tools:', tools.map(t => t.name));

// Call specific MCP tool
// Tool name format: "server:tool_name" or just "tool_name" (auto-resolves server)
const result: MCPToolResult = await agent.callMCPTool('github:list_repos', {
  owner: 'username'
});

// Remove an MCP server by name (synchronous)
agent.removeMCPServer('github');

响应类型

callMCPTool 响应

const result: MCPToolResult = await agent.callMCPTool('github:list_repos', { owner: 'username' });

// Response structure (MCPToolResult):
{
  content: [
    { type: 'text', text: 'Repository list...' }
  ],
  isError?: boolean  // Optional error flag
}

getMCPTools 响应

const tools: MCPTool[] = agent.getMCPTools();

// Response structure (MCPTool[]):
[
  {
    name: 'list_repos',           // Tool name without server prefix
    description: 'List repositories for a user',
    inputSchema: {                // MCPJsonSchema
      type: 'object',
      properties: {
        owner: { type: 'string', description: 'Repository owner' }
      },
      required: ['owner']
    }
  }
]

API 参考

代理 MCP 方法

// Add a single MCP server (async)
async addMCPServer(serverDef: MCPServerDefinition): Promise<void>

// Add multiple MCP servers (async)
async addMCPServers(servers: MCPServerDefinition[]): Promise<void>

// Remove an MCP server by name (sync)
removeMCPServer(name: string): void

// Call an MCP tool (async)
async callMCPTool(
  toolName: string,                    // "server:tool" or just "tool"
  args: Record<string, MCPValue>       // Tool arguments
): Promise<MCPToolResult>

// Get all available MCP tools (sync)
getMCPTools(): MCPTool[]

MCP 集成在保持安全性和简洁性的同时,提供了强大的外部工具访问能力。

最后更新时间:2026年7月6日