MCP Python SDK は完全な MCP (Model Context Protocol) 仕様を実装しています。MCP はアプリケーションがコンテキストを LLM に提供する方法を標準化するオープン・プロトコルです。MCP はアプリケーションが標準化された方法でコンテキストを LLM に提供することを可能にし、コンテキストの提供の問題点を実際の LLM インタラクションから分離します。
MCP Python SDK : 概要
作成 : クラスキャット・セールスインフォメーション
作成日時 : 05/02/2025
* 本記事は github: modelcontextprotocol/python-sdk の以下のページを独自に翻訳した上でまとめ直し、補足説明を加えています :
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
◆ お問合せ : 下記までお願いします。
- クラスキャット セールス・インフォメーション
- sales-info@classcat.com
- ClassCatJP
MCP Python SDK : 概要
概要
Model Context Protocol はアプリケーションが標準化された方法でコンテキストを LLM に提供することを可能にし、コンテキストの提供の問題点を実際の LLM インタラクションから分離します。この Python SDK は完全な MCP 仕様を実装し、以下を簡単にします :
- 任意の MCP サーバに接続可能な MCP クライアントの構築
- リソース、プロンプトとツールを公開する MCP サーバの作成
- stdio と SSE のような標準トランスポートの使用
- すべての MCP プロトコルメッセージとライフサイクル・イベントの処理
インストール
MCP を python プロジェクトに追加
Python プロジェクトを管理するために uv の使用を勧めます。
uv-managed プロジェクトをまだ作成していない場合には、作成してください :
uv init mcp-server-demo
cd mcp-server-demo
そして MCP をプロジェクト依存関係に追加します :
uv add "mcp[cli]"
代わりに、依存関係に pip を使用するプロジェクトについて :
pip install "mcp[cli]"
スタンドアローン MCP 開発ツールの実行
uv で mcp コマンドを実行するには :
uv run mcp
クイックスタート
計算機ツールと幾つかのデータを公開する単純な MCP サーバを作成しましょう :
# server.py
from mcp.server.fastmcp import FastMCP
# Create an MCP server
mcp = FastMCP("Demo")
# Add an addition tool
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
# Add a dynamic greeting resource
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
"""Get a personalized greeting"""
return f"Hello, {name}!"
次を実行することで、このサーバを Claude Desktop にインストールしてすぐに操作することができます :
mcp install server.py
代わりに、MCP Inspector でそれをテストできます :
mcp dev server.py
What is MCP?
Model Context Protocol (MCP) は、LLM アプリケーションにデータと機能を安全に、標準化された方法で公開するサーバの構築を可能にします。LLM とのインタラクションに特別に設計された、web API のようなものと考えてください。MCP サーバは以下のことができます :
- リソース (これらを GET エンドポイントのようなものと考えてください ; 情報を LLM のコンテキストにロードするために使用されます) を通してデータを公開する
- ツール (POST エンドポイントのようなものです ; コードを実行したり、そうでないなら副作用を生成するために使用されます) を通して機能を提供する
- プロンプト (LLM インタラクション用の再利用可能なテンプレート) を通してインタラクション・パターンを定義する
- And more!
中核コンセプト
サーバ
FastMCP サーバは MCP プロトコルへのコア・インターフェイスです。接続管理、プロトコル準拠、そしてメッセージ・ルーティングを処理します :
# Add lifespan support for startup/shutdown with strong typing
from contextlib import asynccontextmanager
from collections.abc import AsyncIterator
from dataclasses import dataclass
from fake_database import Database # Replace with your actual DB type
from mcp.server.fastmcp import Context, FastMCP
# Create a named server
mcp = FastMCP("My App")
# Specify dependencies for deployment and development
mcp = FastMCP("My App", dependencies=["pandas", "numpy"])
@dataclass
class AppContext:
db: Database
@asynccontextmanager
async def app_lifespan(server: FastMCP) -> AsyncIterator[AppContext]:
"""Manage application lifecycle with type-safe context"""
# Initialize on startup
db = await Database.connect()
try:
yield AppContext(db=db)
finally:
# Cleanup on shutdown
await db.disconnect()
# Pass lifespan to server
mcp = FastMCP("My App", lifespan=app_lifespan)
# Access type-safe lifespan context in tools
@mcp.tool()
def query_db(ctx: Context) -> str:
"""Tool that uses initialized resources"""
db = ctx.request_context.lifespan_context.db
return db.query()
リソース
リソースはデータを LLM に公開する方法です。それらは REST API の GET エンドポイントに類似しています – それらはデータを提供しますが、大きな計算を実行したり副作用を持つべきではありません :
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("My App")
@mcp.resource("config://app")
def get_config() -> str:
"""Static configuration data"""
return "App configuration here"
@mcp.resource("users://{user_id}/profile")
def get_user_profile(user_id: str) -> str:
"""Dynamic user data"""
return f"Profile data for user {user_id}"
ツール
ツールは LLM がサーバを通してアクションを実行することを可能にします。リソースとは異なり、ツールは計算を実行したり副作用を持つことが想定されます :
import httpx
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("My App")
@mcp.tool()
def calculate_bmi(weight_kg: float, height_m: float) -> float:
"""Calculate BMI given weight in kg and height in meters"""
return weight_kg / (height_m**2)
@mcp.tool()
async def fetch_weather(city: str) -> str:
"""Fetch current weather for a city"""
async with httpx.AsyncClient() as client:
response = await client.get(f"https://api.weather.com/{city}")
return response.text
プロンプト
プロンプトは再利用可能なテンプレートで、LLM がサーバと効果的にやり取りするのに役立ちます :
from mcp.server.fastmcp import FastMCP
from mcp.server.fastmcp.prompts import base
mcp = FastMCP("My App")
@mcp.prompt()
def review_code(code: str) -> str:
return f"Please review this code:\n\n{code}"
@mcp.prompt()
def debug_error(error: str) -> list[base.Message]:
return [
base.UserMessage("I'm seeing this error:"),
base.UserMessage(error),
base.AssistantMessage("I'll help debug that. What have you tried so far?"),
]
イメージ
FastMCP は画像データを自動的に処理する Image クラスを提供します :
from mcp.server.fastmcp import FastMCP, Image
from PIL import Image as PILImage
mcp = FastMCP("My App")
@mcp.tool()
def create_thumbnail(image_path: str) -> Image:
"""Create a thumbnail from an image"""
img = PILImage.open(image_path)
img.thumbnail((100, 100))
return Image(data=img.tobytes(), format="png")
コンテキスト
Context オブジェクトはツールやリソースに MCP 機能へのアクセスを提供します :
from mcp.server.fastmcp import FastMCP, Context
mcp = FastMCP("My App")
@mcp.tool()
async def long_task(files: list[str], ctx: Context) -> str:
"""Process multiple files with progress tracking"""
for i, file in enumerate(files):
ctx.info(f"Processing {file}")
await ctx.report_progress(i, len(files))
data, mime_type = await ctx.read_resource(f"file://{file}")
return "Processing complete"
サーバの実行
開発モード
サーバをテストしてデバッグする最速の方法は MCP Inspector を使用することです :
mcp dev server.py
# Add dependencies
mcp dev server.py --with pandas --with numpy
# Mount local code
mcp dev server.py --with-editable .
以下は “mcp dev server.py” を実行して web ブラウザでアクセスした画面です :
Claude Desktop 統合
サーバが準備できたら、それを Claude Desktop にインストールします :
mcp install server.py
# Custom name
mcp install server.py --name "My Analytics Server"
# Environment variables
mcp install server.py -v API_KEY=abc123 -v DB_URL=postgres://...
mcp install server.py -f .env
直接実行
カスタム配備のような高度なシナリオの場合 :
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("My App")
if __name__ == "__main__":
mcp.run()
Run it with:
python server.py
# or
mcp run server.py
サンプル
Echo サーバ
リソース、ツールとプロンプトを実演する単純なサーバ :
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Echo")
@mcp.resource("echo://{message}")
def echo_resource(message: str) -> str:
"""Echo a message as a resource"""
return f"Resource echo: {message}"
@mcp.tool()
def echo_tool(message: str) -> str:
"""Echo a message as a tool"""
return f"Tool echo: {message}"
@mcp.prompt()
def echo_prompt(message: str) -> str:
"""Create an echo prompt"""
return f"Please process this message: {message}"
SQLite Explorer
データベース統合を示すより複雑な例 :
import sqlite3
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("SQLite Explorer")
@mcp.resource("schema://main")
def get_schema() -> str:
"""Provide the database schema as a resource"""
conn = sqlite3.connect("database.db")
schema = conn.execute("SELECT sql FROM sqlite_master WHERE type='table'").fetchall()
return "\n".join(sql[0] for sql in schema if sql[0])
@mcp.tool()
def query_data(sql: str) -> str:
"""Execute SQL queries safely"""
conn = sqlite3.connect("database.db")
try:
result = conn.execute(sql).fetchall()
return "\n".join(str(row) for row in result)
except Exception as e:
return f"Error: {str(e)}"
以上