mcp-builder
FastMCPを使ってPythonでMCPサーバーを構築するスキルです。ツール・リソース・プロンプトの定義からサーバーのビルド、ローカルテスト、FastMCP CloudやDockerへのデプロイまでをサポートします。MCPサーバーの構築、LLMへのツール公開、FastMCP、Claude連携の実装、またはモジュールレベルのサーバー・ストレージ・ライフスパン・ミドルウェア・OAuth・デプロイに関するエラーのトラブルシューティングが必要な際に活用してください。
description の原文を見る
Build MCP servers in Python with FastMCP. Define tools / resources / prompts, build the server, test locally, deploy to FastMCP Cloud or Docker. Use whenever the user mentions building an MCP server, exposing tools to LLMs, FastMCP, building a Claude integration, or troubleshooting FastMCP module-level server, storage, lifespan, middleware, OAuth, or deployment errors.
SKILL.md 本文
MCP ビルダー
ツール説明からワーキング MCP サーバーを構築します。FastMCP を使用してデプロイ可能な Python サーバーを作成します。
ワークフロー
ステップ 1: 公開する内容を定義
サーバーが提供する必要があるものを確認します:
- ツール -- Claude が呼び出せる関数 (API ラッパー、計算、ファイル操作)
- リソース -- Claude が読み取れるデータ (データベースレコード、設定、ドキュメント)
- プロンプト -- パラメータ付きの再利用可能なプロンプトテンプレート
「顧客データベースをクエリするための MCP サーバー」程度のブリーフがあれば十分です。
ステップ 2: サーバーをスキャフォルド
pip install fastmcp
サーバーファイルを作成します。サーバーインスタンスはモジュールレベルに配置する必要があります:
from fastmcp import FastMCP
# FastMCP Cloud 用にモジュールレベルに配置する必須
mcp = FastMCP("My Server")
@mcp.tool()
async def search_customers(query: str) -> str:
"""Search customers by name or email."""
# Implementation here
return f"Found customers matching: {query}"
@mcp.resource("customers://{customer_id}")
async def get_customer(customer_id: str) -> str:
"""Get customer details by ID."""
return f"Customer {customer_id} details"
if __name__ == "__main__":
mcp.run()
ステップ 3: コンパニオン CLI スクリプトを追加 (オプション)
Claude Code ターミナル使用時のため、MCP サーバーの横にスクリプトを追加します:
my-mcp-server/
├── src/index.ts # MCP server (for Claude.ai)
├── scripts/
│ ├── search.ts # CLI version of search tool
│ └── _shared.ts # Shared auth/config
├── SCRIPTS.md # Documents available scripts
└── package.json
CLI スクリプトはファイル I/O、バッチ処理、MCP ではサポートされないより豊富な出力を提供します。
assets/SCRIPTS-TEMPLATE.md と assets/script-template.ts で TypeScript テンプレートを参照してください。
ステップ 4: ローカルテスト
クイックテスト -- 直接実行:
python server.py
インスペクター UI を備えたデブモード (推奨):
fastmcp dev server.py
# Opens inspector at http://localhost:5173
# Hot reload, detailed logging, tool/resource inspection
リモートクライアント用 HTTP モード:
python server.py --transport http --port 8000
FastMCP Client を使用した自動テストスクリプト:
import asyncio
from fastmcp import Client
async def test_server(server_path):
async with Client(server_path) as client:
# List everything
tools = await client.list_tools()
resources = await client.list_resources()
prompts = await client.list_prompts()
print(f"Tools: {[t.name for t in tools]}")
print(f"Resources: {[r.uri for r in resources]}")
print(f"Prompts: {[p.name for p in prompts]}")
# Call first tool
if tools:
result = await client.call_tool(tools[0].name, {})
print(f"Tool result: {result}")
# Read first resource
if resources:
data = await client.read_resource(resources[0].uri)
print(f"Resource data: {data}")
asyncio.run(test_server("server.py"))
ステップ 5: デプロイ前チェックリスト
デプロイ前にこれらのチェックを実行します。すべての必須チェックが合格する必要があります。
必須 (デプロイ失敗の原因になります):
- サーバーファイルが存在する
- Python 構文が有効:
python3 -m py_compile server.py - モジュールレベルのサーバーオブジェクト (関数内ではない):
grep -q "^mcp = FastMCP\|^server = FastMCP\|^app = FastMCP" server.py requirements.txtが存在し PyPI パッケージのみを含む (git+、-e、.whl、.tar.gzなし)- ハードコードされたシークレットなし (
os.getenv/os.environを除くapi_key = "..."パターンをチェック)
警告 (アドバイザリ):
requirements.txtにfastmcpが記載されている.gitignoreが.envを含む- 循環インポートなし
- Git リポジトリがリモート付きで初期化されている
- サーバーがロードできる:
timeout 5 fastmcp inspect server.py
ステップ 6: デプロイ
FastMCP Cloud (最も簡単):
git add . && git commit -m "Ready for deployment"
git push -u origin main
# Visit https://fastmcp.cloud, connect repo, add env vars, deploy
# URL: https://your-project.fastmcp.app/mcp
Cloud 要件:
mcp、server、またはappという名前のモジュールレベルのサーバーオブジェクトrequirements.txt内の PyPI 依存関係のみ- パブリック GitHub リポジトリ
- シークレット用の環境変数 (ハードコード値なし)
- main へのプッシュ時に自動デプロイ、PR プレビュー デプロイ
Docker (自己ホスト):
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "server.py", "--transport", "http", "--port", "8000"]
Cloudflare Workers (エッジ): Workers ベースの MCP サーバーについては、cloudflare-worker-builder スキルを参照してください。
重要なパターン
モジュールレベルのサーバーインスタンス
FastMCP Cloud ではサーバーインスタンスがモジュールレベルに必要です:
# 正しい
mcp = FastMCP("My Server")
@mcp.tool()
def my_tool(): ...
# 間違い -- Cloud がサーバーを見つけられない
def create_server():
mcp = FastMCP("My Server")
return mcp
# ファクトリパターンの修正 -- モジュールレベルでエクスポート
def create_server() -> FastMCP:
mcp = FastMCP("server")
return mcp
mcp = create_server()
型アノテーションが必須
FastMCP は型アノテーションを使用してツールスキーマを生成します:
@mcp.tool()
async def search(
query: str, # Required parameter
limit: int = 10, # Optional with default
tags: list[str] = [] # Complex types supported
) -> str:
"""Docstring becomes the tool description."""
...
エラーハンドリング
例外を発生させるのではなく、エラーを文字列として返します:
@mcp.tool()
async def get_data(id: str) -> str:
try:
result = await fetch_data(id)
return json.dumps(result)
except NotFoundError:
return f"Error: No data found for ID {id}"
Cloud 対応サーバーパターン
import os
from fastmcp import FastMCP
mcp = FastMCP("production-server")
API_KEY = os.getenv("API_KEY")
@mcp.tool()
async def production_tool(data: str) -> dict:
if not API_KEY:
return {"error": "API_KEY not configured"}
return {"status": "success", "data": data}
if __name__ == "__main__":
mcp.run()
よくあるエラーと修正
これらはあなたが遭遇するエラーです。デプロイ前に修正してください。
| エラー | 原因 | 修正 |
|---|---|---|
RuntimeError: No server object found at module level | サーバーが関数内に存在 | mcp = FastMCP(...) をモジュールレベルでエクスポート |
RuntimeError: no running event loop | 非同期/待機がない | 非同期操作に async def を使用 |
TypeError: missing required argument 'context' | Context が型ヒントされていない | context: Context を型ヒント付きで追加 |
ValueError: Invalid resource URI | URI スキームがない | data://、file://、info://、api:// を使用 |
| リソーステンプレートパラメータ不一致 | 名前の不一致 | user://{user_id} は def get_user(user_id: str) が必要 |
| Pydantic 検証エラー | 型ヒントが間違っている | ヒントが実際のデータ型と一致することを確認 |
| トランスポート不一致 | クライアント/サーバープロトコルが異なる | 両方を stdio または両方を http に一致させる |
| 編集可能パッケージでインポートエラー | パッケージがインストールされていない | pip install -e . または PYTHONPATH に追加 |
DeprecationWarning: mcp.settings | 古い API | 代わりに os.getenv() を使用 |
| ポートが既に使用中 | 古いプロセス | lsof -ti:8000 | xargs kill -9 |
| スキーマ生成失敗 | JSON 非互換型 | JSON 互換型を使用 (NumPy 配列なし) |
| JSON シリアル化エラー | レスポンス内の datetime/bytes | .isoformat() または文字列に変換 |
| 循環インポート | __init__.py のファクトリ | 直接インポートを使用、ファクトリパターンを回避 |
| Python 3.12+ datetime 警告 | datetime.utcnow() が非推奨 | datetime.now(timezone.utc) を使用 |
| インポート時実行 | モジュールレベルの非同期リソース | 遅延初期化パターンを使用 |
プロダクションパターン
自己完結したサーバー
循環インポートを避けるため、すべてのユーティリティを 1 つのファイルに保ちます:
from fastmcp import FastMCP
import os
mcp = FastMCP("my-server")
# Config
class Config:
API_KEY = os.getenv("API_KEY", "")
BASE_URL = os.getenv("BASE_URL", "https://api.example.com")
# Helpers
def format_success(data): return {"status": "success", "data": data}
def format_error(msg): return {"status": "error", "message": msg}
@mcp.tool()
async def my_tool(query: str) -> dict:
if not Config.API_KEY:
return format_error("API_KEY not configured")
return format_success({"query": query})
遅延初期化
モジュールレベルで非同期リソースを作成しないでください。最初の使用時に初期化します:
_db = None
async def get_db():
global _db
if _db is None:
_db = await create_connection(Config.DB_URL)
return _db
ヘルスチェックリソース
@mcp.resource("health://status")
async def health_check() -> dict:
return {
"status": "healthy",
"version": "1.0.0",
"checks": {
"api": "connected",
"database": "connected"
}
}
コネクションプーリング
import httpx
_client = None
def get_client() -> httpx.AsyncClient:
global _client
if _client is None:
_client = httpx.AsyncClient(
base_url=Config.BASE_URL,
headers={"Authorization": f"Bearer {Config.API_KEY}"},
limits=httpx.Limits(max_connections=20, max_keepalive_connections=5),
timeout=30.0
)
return _client
バックオフ付き再試行
async def retry_with_backoff(func, max_retries=3, initial_delay=1.0):
for attempt in range(max_retries):
try:
return await func()
except Exception as e:
if attempt == max_retries - 1:
raise
delay = initial_delay * (2 ** attempt)
await asyncio.sleep(delay)
Context 機能 (高度)
Context インジェクション
from fastmcp import Context
@mcp.tool()
async def tool_with_context(param: str, context: Context) -> dict:
# Context parameter MUST have type hint
pass
進捗追跡
@mcp.tool()
async def long_task(items: list[str], context: Context) -> str:
for i, item in enumerate(items):
await context.report_progress(i + 1, len(items), f"Processing {item}")
await process(item)
return "Done"
サンプリング (ツール内からの LLM)
@mcp.tool()
async def summarise(text: str, context: Context) -> str:
result = await context.request_sampling(
messages=[{"role": "user", "content": f"Summarise: {text}"}],
max_tokens=200
)
return result
CLI クイックリファレンス
fastmcp dev server.py # Dev mode with inspector UI
fastmcp run server.py # Run (stdio)
fastmcp run server.py --transport http --port 8000 # Run (HTTP)
fastmcp inspect server.py # Inspect without running
fastmcp install server.py # Install to Claude Desktop
fastmcp deploy server.py --name my-server # Deploy to Cloud
環境変数: FASTMCP_LOG_LEVEL (DEBUG/INFO/WARNING/ERROR)、FASTMCP_ENV (development/staging/production)。
インテグレーションパターン (オプション)
具体的なインテグレーションアプローチについては、references/integration-patterns.md を参照してください:
- 手動 API -- 再利用可能なクライアント付き
httpx.AsyncClient - OpenAPI 自動生成 --
FastMCP.from_openapi(spec, client, route_maps=[...]) - FastAPI 変換 --
FastMCP.from_fastapi(app)
アセットファイル
assets/basic-server.py-- 最小限の FastMCP サーバーテンプレートassets/self-contained-server.py-- ストレージとミドルウェア付きのサーバーassets/tools-examples.py-- ツールパターンと型アノテーションassets/resources-examples.py-- リソース URI パターンassets/prompts-examples.py-- プロンプトテンプレートパターンassets/client-example.py-- MCP クライアント使用法assets/SCRIPTS-TEMPLATE.md-- CLI コンパニオンドキュメントテンプレートassets/script-template.ts-- TypeScript CLI スクリプトテンプレート
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- jezweb
- リポジトリ
- jezweb/claude-skills
- ライセンス
- MIT
- 最終更新
- 不明
Source: https://github.com/jezweb/claude-skills / ライセンス: MIT
関連スキル
agent-browser
AI エージェント向けのブラウザ自動化 CLI です。ウェブサイトとの対話が必要な場合に使用します。ページ遷移、フォーム入力、ボタンクリック、スクリーンショット取得、データ抽出、ウェブアプリのテスト、ブラウザ操作の自動化など、あらゆるブラウザタスクに対応できます。「ウェブサイトを開く」「フォームに記入する」「ボタンをクリックする」「スクリーンショットを取得する」「ページからデータを抽出する」「このウェブアプリをテストする」「サイトにログインする」「ブラウザ操作を自動化する」といった要求や、プログラマティックなウェブ操作が必要なタスクで起動します。
anyskill
AnySkill — あなたのプライベート・スキルクラウド。GitHubを基盤としたリポジトリからエージェントスキルを管理、同期、動的にロードできます。自然言語でクラウドスキルを検索し、オンデマンドでプロンプトを自動ロード、カスタムスキルのアップロードと共有、スキルバンドルの一括インストールが可能です。OpenClaw、Antigravity、Claude Code、Cursorに対応しています。
engram
AIエージェント向けの永続的なメモリシステムです。バグ修正、意思決定、発見、設定変更の後はmem_saveを使用してください。ユーザーが「覚えている」「記憶している」と言及した場合、または以前のセッションと重複する作業を開始する際はmem_searchを使用します。セッション終了前にmem_session_summaryを使用して、コンテキストを保持してください。
skyvern
AI駆動のブラウザ自動化により、任意のウェブサイトを自動化できます。フォーム入力、データ抽出、ファイルダウンロード、ログイン、複数ステップのワークフロー実行など、ユーザーがウェブサイトと連携する必要があるときに使用します。Skyvernは、LLMとコンピュータビジョンを活用して、未知のサイトも自動操作可能です。Python SDK、TypeScript SDK、REST API、MCPサーバー、またはCLIを通じて統合できます。
pinchbench
PinchBenchベンチマークを実行して、OpenClawエージェントの実世界タスクにおけるパフォーマンスを評価できます。モデルの機能テスト、モデル間の比較、ベンチマーク結果のリーダーボード提出、またはOpenClawのセットアップがカレンダー、メール、リサーチ、コーディング、複数ステップのワークフローにどの程度対応しているかを確認する際に使用します。
openui
OpenUIとOpenUI Langを使用してジェネレーティブUIアプリを構築できます。これらはLLM生成インターフェースのためのトークン効率的なオープン標準です。OpenUI、@openuidev、ジェネレーティブUI、LLMからのストリーミングUI、AI向けコンポーネントライブラリ、またはjson-render/A2UIの置き換えについて述べる際に使用します。スキャフォルディング、defineComponent、システムプロンプト、Renderer、およびOpenUI Lang出力のデバッグに対応しています。