0
0

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 MCP(Model Context Protocol)入門|AIにツールを持たせる新標準をPythonで実装する

0
Posted at

はじめに

2024〜2025年にかけてAI業界で最も注目を集めたキーワードの一つが**MCP(Model Context Protocol)**です。

Anthropicが策定したこのオープンプロトコルは、「AIに外部ツールを持たせる」ための標準仕様として急速に普及しています。

本記事では、MCPの仕組みをゼロから解説し、Pythonで実際に動くMCPサーバーを30分で作る手順を紹介します。


MCPとは何か

**MCP(Model Context Protocol)**とは、AIモデル(ClaudeなどのLLM)と外部ツール・データソースをつなぐための標準プロトコルです。

従来:
Claude ← プロンプトのみ ← ユーザー

MCP導入後:
Claude ← プロンプト + ツール実行結果 ← MCP Server ← 外部サービス
                                                    (DB / API / ファイル等)

MCPが解決する問題

課題 MCPなし MCPあり
最新情報の取得 Claudeの学習データに依存 リアルタイムでAPIから取得
社内データの参照 プロンプトに貼り付けが必要 DBやファイルを直接参照
アクション実行 AIが提案→人間が実行 Claudeが直接ツールを操作
複数ツールの連携 都度プロンプトで制御 MCPサーバーで統合管理

MCPのアーキテクチャ

┌─────────────────────────────────────┐
│           MCP Host                  │
│   (Claude Desktop / Claude Code)    │
└───────────────┬─────────────────────┘
                │ MCP Protocol
    ┌───────────┼────────────┐
    ↓           ↓            ↓
┌───────┐  ┌───────┐  ┌──────────┐
│ MCP   │  │ MCP   │  │  MCP     │
│Server │  │Server │  │ Server   │
│(DB)   │  │(API)  │  │(ファイル)│
└───────┘  └───────┘  └──────────┘

MCPには3つのコンポーネントがあります:

  • MCP Host:ClaudeなどのAIが動作するクライアント
  • MCP Server:外部ツールやデータを提供するサーバー(自作可能)
  • MCP Protocol:両者をつなぐ標準通信仕様(JSON-RPC 2.0ベース)

環境構築

pip install mcp anthropic

PythonでMCPサーバーを作る

① シンプルなツールを持つMCPサーバー

# server.py
from mcp.server import FastMCP

mcp = FastMCP("my-tools")

@mcp.tool()
def get_current_time() -> str:
    from datetime import datetime
    now = datetime.now()
    return f"現在時刻: {now.strftime('%Y年%m月%d日 %H:%M:%S')}"

@mcp.tool()
def calculate(expression: str) -> str:
    try:
        result = eval(expression, {"__builtins__": {}})
        return f"{expression} = {result}"
    except Exception as e:
        return f"計算エラー: {e}"

@mcp.tool()
def search_it_terms(keyword: str) -> str:
    terms = {
        "PD試験": "プロフェッショナルデジタルスキル試験。2027年度開始予定のIPA新資格体系。",
        "RAG": "Retrieval-Augmented Generation。外部文書をAIの回答生成に活用する手法。",
        "MCP": "Model Context Protocol。AIに外部ツールを持たせるAnthropicの標準プロトコル。",
        "FAISS": "Facebook AI Similarity Search。高速なベクトル類似検索ライブラリ。",
    }
    result = terms.get(keyword, f"'{keyword}'は登録されていません。")
    return result

if __name__ == "__main__":
    mcp.run()

② Claudeからツールを呼び出す(API経由)

MCPサーバーを経由せず、Claude APIのTool Useで同等の動作を確認する例:

import anthropic

client = anthropic.Anthropic()

tools = [
    {
        "name": "get_current_time",
        "description": "現在の日時を返します",
        "input_schema": {
            "type": "object",
            "properties": {},
            "required": []
        }
    },
    {
        "name": "search_it_terms",
        "description": "IT用語を検索して説明を返します",
        "input_schema": {
            "type": "object",
            "properties": {
                "keyword": {
                    "type": "string",
                    "description": "検索するIT用語"
                }
            },
            "required": ["keyword"]
        }
    }
]

def handle_tool_call(tool_name: str, tool_input: dict) -> str:
    from datetime import datetime

    if tool_name == "get_current_time":
        now = datetime.now()
        return f"現在時刻: {now.strftime('%Y年%m月%d日 %H:%M:%S')}"

    elif tool_name == "search_it_terms":
        terms = {
            "PD試験": "プロフェッショナルデジタルスキル試験。2027年度開始予定。",
            "RAG": "Retrieval-Augmented Generation。外部文書を参照して回答する手法。",
            "MCP": "Model Context Protocol。AIにツールを持たせるプロトコル。",
        }
        keyword = tool_input.get("keyword", "")
        return terms.get(keyword, f"'{keyword}'は未登録です。")

    return "ツールが見つかりません"


def chat_with_tools(user_message: str) -> str:
    messages = [{"role": "user", "content": user_message}]

    while True:
        response = client.messages.create(
            model="claude-sonnet-5",
            max_tokens=1024,
            tools=tools,
            messages=messages
        )

        # ツール呼び出しがない場合は回答を返す
        if response.stop_reason == "end_turn":
            return response.content[0].text

        # ツール呼び出しがある場合は処理して続行
        tool_results = []
        for block in response.content:
            if block.type == "tool_use":
                result = handle_tool_call(block.name, block.input)
                tool_results.append({
                    "type": "tool_result",
                    "tool_use_id": block.id,
                    "content": result
                })

        messages.append({"role": "assistant", "content": response.content})
        messages.append({"role": "user", "content": tool_results})


# 実行例
print(chat_with_tools("今何時ですか?また、PD試験について教えてください。"))

Claude Desktopへの組み込み方

作成したMCPサーバーをClaude Desktopで使うには、設定ファイルに追加します。

設定ファイルの場所:

  • Mac: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Windows: %APPDATA%\Claude\claude_desktop_config.json

設定内容:

{
  "mcpServers": {
    "my-tools": {
      "command": "python",
      "args": ["/path/to/server.py"]
    }
  }
}

設定後にClaude Desktopを再起動すると、ツールが使えるようになります。


既存の公開MCPサーバー

自作しなくても、以下の公開MCPサーバーがすぐに使えます:

サーバー 機能
@modelcontextprotocol/server-filesystem ローカルファイルの読み書き
@modelcontextprotocol/server-github GitHub API連携
@modelcontextprotocol/server-postgres PostgreSQL接続
@modelcontextprotocol/server-brave-search Web検索
@modelcontextprotocol/server-slack Slack連携
# npmで一発インストール
npx @modelcontextprotocol/server-filesystem /path/to/dir

PD試験との関連

2027年度開始の**PD試験(プロフェッショナルデジタルスキル試験)**では、PD(D)区分(データ・AI)においてAI活用スキルが出題範囲に含まれています。

MCPのようなエージェント連携技術の概念を理解しておくことは、試験対策としてだけでなく、実務でのAI活用スキルとして直接役立ちます。


まとめ

項目 内容
MCPとは AIと外部ツールをつなぐAnthropicの標準プロトコル
実装方法 Python + mcpライブラリで30分で作れる
活用場面 DB連携・API連携・ファイル操作・社内ツール自動化
試験との関連 PD(D)のAI活用スキルと直結

MCPは2025〜2026年のAI実装の標準になりつつあります。今のうちに触っておくことをお勧めします。


PD試験・IT資格の情報発信:

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?