mcpField
M
MCP AI Agent

MCP AI Agent

github.com/fkeshehフレームワーク・SDK2263 週間前に更新

MCP AI Agent について

MCP AI Agent は、AI エージェントが MCP サーバーのツールを呼び出せるようにする TypeScript ライブラリです。AI SDK v5 と統合されており、複数の MCP サーバーに接続してアプリケーション内でエージェントを組み合わせたい開発者に適しています。事前設定済みのサーバーや、エージェント同士の呼び出しに対応します。

主な機能

  1. 01STDIO および SSE 経由で複数の MCP サーバーに接続
  2. 02MCP サーバーのツールを自動で検出して利用
  3. 03MCP ツールのフィルタリングとカスタムツールとの併用
  4. 04複数エージェントの組み合わせと相互呼び出し
  5. 05事前設定済みの MCP サーバーを複数収録

活用シーン

  1. 01TypeScript アプリケーションへのツール連携付きテキスト生成の追加
  2. 02専門化したエージェントを組み合わせたプロジェクト管理ワークフローの構築
  3. 03検索、メモリ、SQLite などのツールをエージェントに接続

MCP 対応

本プロジェクトは MCP クライアントライブラリであり、STDIO または SSE で MCP サーバーに接続し、そのツールを AI SDK ベースのエージェントに提供します。

詳細

MCP AI Agent

AI エージェントが MCP(Model Context Protocol)サーバーを活用して機能を強化できる TypeScript ライブラリです。このライブラリは AI SDK v5 と統合されており、MCP サーバーへの接続や、そのツールを AI 搭載アプリケーションで利用するためのシームレスな方法を提供します。

Features

  • さまざまなトランスポート方式(STDIO、SSE)を使用して、複数の MCP サーバーに接続します
  • MCP サーバーからツールを自動的に検出して使用します
  • AI SDK と統合し、ツールを使用したテキスト生成を実現します
  • MCP ツールをカスタムツールとフィルタリングして組み合わせます
  • 初期化を簡単にする事前設定済みサーバーを提供します
  • セットアップを簡素化する自動設定に対応しています
  • エージェントが特定のタスクをほかのエージェントに依頼できます
  • エージェントを組み合わせて、専門エージェントを作成できます
  • 識別しやすいように、説明付きの名前付きエージェントを使用できます
  • エージェントを自動初期化します(明示的に initialize を呼び出す必要はありません)
  • エージェント設定内にカスタムツールを直接定義できます
  • マルチエージェントシステムを簡素化するデフォルトモデルに対応しています
  • 特化した動作のためのシステムプロンプトを統合できます
  • デバッグ用の詳細モードを備えています

Roadmap

  • MCP ツールと統合した基本的なエージェント
  • MCP サーバーの自動処理
  • マルチエージェントのワークフロー
  • 関数ベースのツールハンドラー
  • Swagger/OpenAPI からツールへの自動変換(ステートレスサーバーとの簡単な統合)
  • API サーバーの実装(サーバー上でエージェントを呼び出す)
  • 可観測性システム

Installation

npm install mcp-ai-agent

包括的な実装例については、mcp-ai-agent-example リポジトリをご覧ください。

Minimal 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);
Multi-Agent Workflows (Agent Composition)

専門エージェントを作成し、タスクを委任できるマスターエージェントに組み合わせることができます。

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 style workflow

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);
Custom Tools

エージェントにカスタムツールを直接簡単に追加できます。

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);

Supported MCP Servers

MCP AI Agent は、以下のサーバーに対応する事前設定を備えています。

  • Sequential Thinking:複雑な問題を手順に分解するために使用します
  • Memory:会話のコンテキストを保持する永続メモリです
  • AWS KB Retrieval:AWS Knowledge Bases から情報を取得します
  • Brave Search:Brave Search API を使用してウェブ検索を実行します
  • Everart:AI を使用して画像を作成、編集します
  • Fetch:URL からデータを取得します
  • Firecrawl MCP:ウェブクローリングと情報取得機能を提供します
  • SQLite:SQLite データベースを検索、操作します
Using Supported Servers

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,
  ],
});
Contributing New Servers

追加の MCP サーバーへの対応に向けた貢献を歓迎します。新しいサーバーを追加するには、次の手順に従ってください。

  1. 既存のパターンに従って、src/servers ディレクトリに新しいファイルを作成します
  2. ファイル内でサーバー設定をエクスポートします
  3. src/servers/index.ts のエクスポートにサーバーを追加します
  4. 変更を含むプルリクエストを送信します

サーバー設定の形式の例:

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"],
  },
};
Using Multiple Servers

複数のサーバーを使ってエージェントを初期化できます。

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);
Using Stdio Tools Manually
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);
Using SSE Transport

MCP サーバーへの接続には、Server-Sent Events(SSE)トランスポートも使用できます。

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);

Advanced Examples

Working with Images

メッセージに画像を含めることができます。

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();
Working with PDFs

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();
Mixing Preconfigured and Custom Server Configurations

事前設定済みサーバーと手動で設定したサーバーを組み合わせることができます。

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();
Creating a Custom Auto-Configured Server

独自の自動設定サーバーライブラリ定義を作成して使用することもできます。

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>>

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; }

名前、説明、利用可能なツール、エージェント、およびデフォルトモデルを含むエージェント情報を返します。

ライセンス

MIT

コメント

MCP は初めてですか?

プロトコルの概要から最初のサーバーの導入まで、よくある疑問にまとめて答えます。

AI アプリケーションが外部のツールやデータソースに統一的な方法で接続するためのオープンなプロトコルです。クライアントはモデルとの対話を担い、MCP サーバーはツール・リソース・プロンプトテンプレートを提供します。標準メッセージでやり取りするため、1 つのサーバーを複数のクライアントで再利用できます。