8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Claude Code × MCPサーバー実践 — 外部APIを自然言語で操作する設計パターン

8
Posted at

はじめに

MCPサーバー(Model Context Protocol Server)が注目を集めています。Claude Codeをはじめとするエージェント系ツールに「外部APIと会話する能力」を追加する仕組みです。

この記事では、MCPサーバーを実際にClaude Codeと組み合わせて使う場合の設計パターンを、実装例を交えて解説します。

MCPサーバーとは何か

MCPサーバーは、AIエージェントが外部システムと連携するための標準化されたインターフェースです。

[Claude Code] ←→ [MCPサーバー] ←→ [外部API/DB/サービス]

従来のAPI連携との違いは、AIが「ツール」として認識し、自然言語の指示で呼び出せる点です。

基本構成:MCPサーバーの最小実装

TypeScriptでの最小構成を見てみましょう。

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({
  name: "weather-server",
  version: "1.0.0",
});

// ツール定義
server.tool(
  "get-weather",
  "指定した都市の天気を取得する",
  { city: z.string().describe("都市名(例: Tokyo)") },
  async ({ city }) => {
    const res = await fetch(
      `https://api.weatherapi.com/v1/current.json?key=YOUR_KEY&q=${city}`
    );
    const data = await res.json();
    return {
      content: [
        {
          type: "text",
          text: `${city}: ${data.current.condition.text}, ${data.current.temp_c}°C`,
        },
      ],
    };
  }
);

const transport = new StdioServerTransport();
await server.connect(transport);

これだけで、Claude Codeから「東京の天気を教えて」と言うだけで天気情報を取得できます。

設計パターン1: 業務データ検索型

最もよく使うパターンです。社内データベースや管理画面のデータを自然言語で検索できるようにします。

server.tool(
  "search-users",
  "ユーザーを条件で検索する",
  {
    query: z.string().describe("検索キーワード"),
    status: z.enum(["active", "inactive", "all"]).optional(),
  },
  async ({ query, status }) => {
    const users = await db.users.findMany({
      where: {
        name: { contains: query },
        ...(status !== "all" ? { status } : {}),
      },
      take: 10,
    });
    return {
      content: [{ type: "text", text: JSON.stringify(users, null, 2) }],
    };
  }
);

ポイント: 検索結果は必ず件数制限をかけます。AIのコンテキストウィンドウを圧迫しないためです。

設計パターン2: CRUD操作型

読み取りだけでなく、作成・更新・削除もツール化できます。ただし、破壊的操作には注意が必要です。

server.tool(
  "create-task",
  "新しいタスクを作成する(確認プロンプトあり)",
  {
    title: z.string(),
    assignee: z.string().optional(),
    priority: z.enum(["low", "medium", "high"]).default("medium"),
  },
  async ({ title, assignee, priority }) => {
    const task = await db.tasks.create({
      data: { title, assignee, priority, status: "open" },
    });
    return {
      content: [
        { type: "text", text: `タスク #${task.id} を作成しました: ${title}` },
      ],
    };
  }
);

ポイント: Claude Codeはデフォルトでツール実行前にユーザー確認を求めるため、意図しない操作が実行されるリスクは低いです。

設計パターン3: 集約・分析型

複数のデータソースからデータを集め、分析用の情報を返すパターンです。

server.tool(
  "daily-report",
  "今日のビジネスメトリクスを集約する",
  {},
  async () => {
    const [sales, users, errors] = await Promise.all([
      getSalesToday(),
      getNewUsersToday(),
      getErrorsToday(),
    ]);
    return {
      content: [
        {
          type: "text",
          text: `売上: ¥${sales}\n新規ユーザー: ${users}人\nエラー: ${errors}件`,
        },
      ],
    };
  }
);

Claude Codeとの接続設定

.claude/settings.json にMCPサーバーを登録します。

{
  "mcpServers": {
    "weather": {
      "command": "npx",
      "args": ["tsx", "./mcp-servers/weather.ts"]
    }
  }
}

起動すると、Claude Codeのツール一覧に mcp__weather__get-weather として表示されます。

設計時の注意点

1. ツールの粒度

1つのツールに詰め込みすぎないことが重要です。「ユーザー検索」と「ユーザー作成」は別ツールにしましょう。AIがどのツールを使うか判断しやすくなります。

2. descriptionの品質

description はAIがツール選択の根拠にする情報です。何ができるかだけでなく、「いつ使うべきか」を書くと精度が上がります。

3. エラーハンドリング

MCPツール内でthrowすると、AIにエラーメッセージが渡されます。人間が読むメッセージではなく、AIが対処法を判断できるメッセージを返しましょう。

まとめ

MCPサーバーは、Claude Codeに「外の世界とのつながり」を与える仕組みです。小さなツールから始めて、業務に合わせて拡張していくのがおすすめです。


この記事の筆者はMENTAでAI駆動開発のメンタリングを提供しています。→ https://menta.work/plan/20251
YouTubeでもAI×プログラミングの情報を発信中 → https://www.youtube.com/channel/UC1rXVD9WYsQPQEWZyd-A1KA/

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?