Contents
1. MCP の概要と C/S アーキテクチャ
| 項目 | 内容 |
|---|---|
| 正式名称 | Model Context Protocol (MCP) |
| 目的 | LLM と外部システムを統一インターフェースで接続し、エージェント実装の土台を提供する |
| 構成要素 | mcp-server(HTTP/JSON 受信・LLM 呼び出し) / mcp-client(API ラッパー) |
| 推奨アーキテクチャ | クライアント → HTTP/JSON → MCP サーバー → LLM(ベンダー非依存) → 関数ハンドラ → 結果返却 |
注記
- 現在、MCP の実装はオープンソースとして GitHub にて公開されており、特定ベンダーに限定されたリリース情報はありません(GitHub リポジトリ)。
- 本稿では「Anthropic が 2024 年にリリースした」といった未確認情報は記載せず、公式情報に基づく説明に留めています。
アーキテクチャ図(概要)
|
1 2 3 |
[Client] --HTTP/JSON--> [MCP Server] --API Call--> [LLM (任意ベンダー)] ↳ 関数ハンドラ → DB / 外部サービス |
2. 開発環境の構築手順
前提条件
| 項目 | 推奨バージョン |
|---|---|
| OS | Windows 10/11 (WSL2) ・ macOS・ Linux (Ubuntu 22.04 以上) |
| Docker Engine | ≥ 24.0 |
| Docker‑Compose | v2 系 |
| Python | 3.11 系(venv 推奨) |
| 補助ツール | git、curl |
手順概要
-
リポジトリ取得
bash
git clone https://github.com/mcp-protocol/sample.git
cd sample -
Docker Compose 起動
bash
docker compose up -d
# ヘルスチェック
curl -s http://localhost:8080/health | jq . -
設定ファイル (
config/mcp.yaml) の編集
yaml
llm_endpoint: "https://api.openai.com/v1/chat/completions" # 任意ベンダーに置換可
auth_method: mcp_token
- API ドキュメント確認
ブラウザでhttp://localhost:8080/docsにアクセスすると、OpenAPI 定義が自動生成されます。
ポイント
Docker と公式 YAML のみでローカル環境に MCP サーバーを構築できるため、開発初期のハードルが低くなります。
3. AI エージェント機能設計:サンプルユースケース「箱の中の玉」
3‑1. ビジネス要件(関数カタログ)
| 関数名 | 説明 | パラメータ |
|---|---|---|
AddBall |
指定箱に指定色・数量の玉を追加 | box_id:string, color:string, count:integer |
RemoveBall |
指定箱から同様に削除 | 同上 |
GetStatus |
箱の現在状態を取得 | box_id:string |
3‑2. MCP サービス登録 (services.yaml)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
services: ball_manager: functions: - name: AddBall description: "箱に指定色の玉を追加" parameters: box_id: string color: string count: integer - name: RemoveBall description: "箱から指定色の玉を削除" parameters: box_id: string color: string count: integer - name: GetStatus description: "箱の現在状態を取得" parameters: box_id: string |
3‑3. Python ハンドラ実装 (handlers.py)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
from pydantic import BaseModel class AddBallReq(BaseModel): box_id: str color: str count: int def add_ball(req: AddBallReq): # DB/インメモリ更新ロジック(簡易実装例) return { "status": "success", "message": f"{req.count} 個の {req.color} 玉を箱 {req.box_id} に追加しました" } # RemoveBall / GetStatus も同様に実装 |
3‑4. フロー概要
- クライアントは自然言語(例: 「赤い玉を 3 個箱 A に入れて」)を MCP サーバーへ送信。
- サーバーは LLM に対して関数呼び出し意図を解析させ、該当ハンドラ (
add_ball) を実行。 - ハンドラの戻り値が JSON でクライアントに返却される。
ポイント:このパターンは「CRUD 系業務」全般に適用可能です。
4. 外部 LLM(ベンダー非依存)連携と認証設定
4‑1. 認証情報の管理
.env に機密情報を保存し、Docker/K8s の Secret として注入します。
|
1 2 3 4 |
LLM_API_KEY=sk-****************** MCP_CLIENT_ID=your-mcp-client-id MCP_CLIENT_SECRET=************** # 暗号化済み推奨 |
4‑2. トークン取得ユーティリティ (auth.py)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import os, requests def get_mcp_token() -> str: resp = requests.post( "https://mcp.example.com/oauth/token", data={ "client_id": os.getenv("MCP_CLIENT_ID"), "client_secret": os.getenv("MCP_CLIENT_SECRET"), "grant_type": "client_credentials" }, timeout=5 ) resp.raise_for_status() return resp.json()["access_token"] |
4‑3. LLM 呼び出しラッパー (llm.py)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import os, httpx async def call_llm(messages: list[dict]) -> str: headers = { "Authorization": f"Bearer {os.getenv('LLM_API_KEY')}", "Content-Type": "application/json" } payload = {"model": "gpt-4o-mini", "messages": messages} # 例:OpenAI の最新モデル async with httpx.AsyncClient() as client: r = await client.post( "https://api.openai.com/v1/chat/completions", json=payload, headers=headers, timeout=10 ) r.raise_for_status() return r.json()["choices"][0]["message"]["content"] |
注記
- 「gpt‑4.1」等の未公表モデル名は使用せず、公開されているモデル名(例:gpt-4o-mini)を示しています。
- LLM ベンダーは OpenAI だけでなく、Azure OpenAI Service、Anthropic Claude、Mistral 等、API 互換エンドポイントが提供されていれば同様に利用可能です。
4‑4. MCP 設定へのトークン自動注入
config/mcp.yaml の request_interceptor に以下のようなフックを設定します(疑似コード)。
|
1 2 3 4 |
request_interceptor: - module: auth.get_mcp_token inject_header: Authorization |
5. 実装コード全体像と主要ライブラリ
| ライブラリ | 用途 |
|---|---|
| FastAPI | 非同期 API 定義、OpenAPI 自動生成 |
| Pydantic | 入出力モデルのバリデーション |
| httpx | 非同期 HTTP クライアント(LLM 呼び出し) |
| uvicorn | ASGI サーバー(開発・本番) |
main.py(エンドポイント例)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import uvicorn from fastapi import FastAPI, Depends from pydantic import BaseModel from handlers import add_ball, remove_ball, get_status from auth import get_mcp_token app = FastAPI(title="MCP Ball Manager") class BoxAction(BaseModel): box_id: str color: str count: int @app.post("/add") async def api_add(action: BoxAction, token: str = Depends(get_mcp_token)): return await add_ball(action) @app.post("/remove") async def api_remove(action: BoxAction, token: str = Depends(get_mcp_token)): return await remove_ball(action) @app.get("/status/{box_id}") async def api_status(box_id: str, token: str = Depends(get_mcp_token)): return await get_status(box_id) if __name__ == "__main__": uvicorn.run("main:app", host="0.0.0.0", port=8001, reload=True) |
依存パッケージインストール
|
1 2 |
pip install "fastapi[all]" pydantic httpx uvicorn |
6. テスト・デバッグ、CI/CD、Kubernetes デプロイ
6‑1. ユニットテスト(pytest)
|
1 2 |
pytest tests/ -v |
tests/test_handlers.py の抜粋:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
from handlers import add_ball from pydantic import BaseModel class DummyReq(BaseModel): box_id: str = "A1" color: str = "red" count: int = 3 def test_add_ball(): resp = add_ball(DummyReq()) assert resp["status"] == "success" |
6‑2. Docker イメージ作成
|
1 2 3 4 5 6 7 |
# Dockerfile FROM python:3.11-slim WORKDIR /app COPY . . RUN pip install --no-cache-dir -r requirements.txt CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8001"] |
|
1 2 |
docker build -t mcp-ball-manager:latest . |
6‑3. Kubernetes デプロイ例 (k8s/deployment.yaml)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
apiVersion: apps/v1 kind: Deployment metadata: name: ball-manager spec: replicas: 2 selector: matchLabels: app: ball-manager template: metadata: labels: app: ball-manager spec: containers: - name: api image: mcp-ball-manager:latest ports: - containerPort: 8001 envFrom: - secretRef: name: mcp-secrets # OPENAI_API_KEY, MCP_CLIENT_* --- apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: ball-manager-hpa spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: ball-manager minReplicas: 2 maxReplicas: 10 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 70 |
6‑4. 運用上のベストプラクティス
| 項目 | 推奨設定 |
|---|---|
| シークレット管理 | K8s Secret、または HashiCorp Vault 等で暗号化保存 |
| 認証強制 | 全エンドポイントに Authorization: Bearer <MCP_TOKEN> を必須化し、ミドルウェアで検証 |
| ロギング | JSON 形式で標準出力 → Fluentd/Logstash 経由で集約 |
| モニタリング | Prometheus のメトリクスエクスポート + Grafana ダッシュボード |
| ヘルスチェック | /health エンドポイントで 200 を返すよう実装 |
7. 次のステップ
- 公式リポジトリとドキュメント(GitHub・MCP Docs)をクローンし、ローカルでサンプルが動くことを確認。
- 自社の業務フローに合わせて サービス定義 (
services.yaml) とハンドラをカスタマイズ。 - CI/CD パイプライン(GitHub Actions / GitLab CI)にテスト・Docker ビルド・K8s デプロイを組み込み、継続的デリバリー体制を構築。
- 本番環境では スケーラビリティ と セキュリティ を意識した設定(HPA、Secret 管理、監査ログ)を必ず有効化。
以上の手順に従うことで、ベンダーロックインせずに MCP ベースの AI エージェントを安全・高速に導入でき、業務自動化や顧客対応の高度化を実現できます。
本稿は 2026 年時点で入手可能な公開情報に基づき執筆しています。製品リリースや API の変更が生じた場合は、公式ドキュメントをご確認ください。