本文へスキップ
← ブログチュートリアル

外部ツールを使う最初の AI エージェントを作る

MCP ツールを使い、ウェブ検索、コード実行、メール送信ができるエージェントを作る手順を解説します。

·読了まで約 4 分

このチュートリアルでは、ウェブ検索、隔離環境でのコード実行、メール送信など、外部ツールを使うエージェントを作ります。4agent カタログの MCP 対応ツールを利用します。

前提条件

  • Node.js 20+
  • 利用する LLM 提供元の API キー
  • TypeScript の基礎知識

ステップ 1:ツールを選ぶ

タスクに適したツールを揃えます。今回の例は、情報を探して要約する調査アシスタントなので、次が必要です。

  1. ウェブ検索:最新情報を探す
  2. コード実行:データを処理・分析する
  3. メール:結果を届ける
E
E2B

AI エージェントがコードを実行するクラウドサンドボックス

ステップ 2:プロジェクトを準備する

mkdir my-agent && cd my-agent
npm init -y
npm install @anthropic-ai/sdk @e2b/code-interpreter

ESM のモジュール解決を設定した tsconfig.json と、入口となる src/index.ts を作成します。

ステップ 3:エージェントのループを定義する

エージェントの中心は、次のツール利用ループです。

  1. 利用可能なツールとメッセージを LLM に送る
  2. LLM がツールを呼ぶか、どれを呼ぶか判断する
  3. ツールを実行し、結果を返す
  4. 最終回答が得られるまで繰り返す
import Anthropic from "@anthropic-ai/sdk";
 
const client = new Anthropic();
 
async function runAgent(task: string) {
  const messages: Anthropic.MessageParam[] = [
    { role: "user", content: task },
  ];
 
  while (true) {
    const response = await client.messages.create({
      model: "claude-sonnet-4-6",
      max_tokens: 4096,
      tools: toolDefinitions,
      messages,
    });
 
    // Check if the model wants to use a tool
    if (response.stop_reason === "tool_use") {
      const toolUse = response.content.find(
        (c) => c.type === "tool_use"
      );
      const result = await executeTool(
        toolUse.name,
        toolUse.input
      );
      messages.push(
        { role: "assistant", content: response.content },
        { role: "user", content: [{ type: "tool_result", tool_use_id: toolUse.id, content: result }] },
      );
    } else {
      // Final response
      return response.content;
    }
  }
}

ステップ 4:ツールの実行を実装する

各ツールには、LLM の要求を API 呼び出しに変換する処理が必要です。

async function executeTool(
  name: string,
  input: Record<string, unknown>
): Promise<string> {
  switch (name) {
    case "run_code":
      return await runCodeInSandbox(input.code as string);
    case "search_web":
      return await searchWeb(input.query as string);
    default:
      return `Unknown tool: ${name}`;
  }
}

E2B でコードを実行する

import { Sandbox } from "@e2b/code-interpreter";
 
async function runCodeInSandbox(code: string) {
  const sandbox = await Sandbox.create();
  const result = await sandbox.runCode(code);
  await sandbox.kill();
  return JSON.stringify(result);
}

ステップ 5:エージェントを動かす

const result = await runAgent(
  "Find the top 5 trending AI tools this week and create a summary table."
);
console.log(result);

エージェントがウェブを検索し、隔離環境で結果を処理して、構造化された回答を返します。

次のステップ

  • 会話をまたいでコンテキストを保持するメモリを追加する
  • ツールの失敗に備えてエラー処理と再試行を追加する
  • 4agent でほかのツールを探し、機能を広げる
ヒント

モデルが生成した引数は信頼できない入力として扱います。外部サービスに渡す前に検証し、プロンプト、ツール結果、ログにシークレットを含めないでください。

情報源

tutorialagentsmcpgetting-started