MCP Server Development Framework について
FastAPI と FastAPI-MCP をベースにした、エンタープライズ向けMCPサーバー開発のためのPythonフレームワークです。既存のAPIエンドポイントをAIモデルから呼び出し可能なツールに変換し、開発プロセスを標準化したいチームに向いています。
主な機能
- 01FastAPI エンドポイントの MCP ツールへの自動変換
- 02インターフェースと実装の分離
- 03依存性注入によるコンポーネント構成
- 04Mock と本番実装の切り替え
- 05サンプルサービスと開発ツールチェーン
活用シーン
- 01既存APIのAIツール化
- 02チーム内でのMCPサーバー開発標準の統一
- 03MCP ツールのユニットテストおよび統合テストの作成
MCP 対応
本フレームワークは FastAPI-MCP を使って FastAPI エンドポイントを MCP エンドポイントとして公開し、Cursor や Claude Desktop などの MCP クライアントから接続できます。
設定
ローカルサーバーの設定はどのクライアントでも共通です。コピーしてクライアントの MCP 設定ファイルに貼り付けてください。
このサーバーのパッケージやリモートエンドポイントはまだ取得できていません。プロジェクトの README の手順に従ってください。
ツール
ローカルサーバーのツールはマシン上で起動して初めて取得できます。メンテナーはまだツール一覧を提供していません。
詳細
MCP サーバー開発フレームワーク
概要
エンタープライズレベルの Model Context Protocol(MCP)ツール開発向けに設計された、プロフェッショナルなフレームワークです。MCP サーバーの開発プロセスを標準化し、開発者が高品質な AI ツールを迅速に構築できるよう支援します。FastAPI と FastAPI-MCP を統合することで、従来の API から AI が呼び出せるツールへのシームレスな変換を実現します。
主な機能
- MCP ツールの標準化:従来の FastAPI エンドポイントを AI モデルから呼び出せる MCP ツールに自動変換します
- インターフェースと実装の分離:インターフェース定義と実装を明確に分離でき、テストや環境の切り替えが容易になります
- 依存性注入の設計:FastAPI の依存性注入メカニズムを活用し、柔軟なコンポーネント構成と疎結合を実現します
- 包括的な開発パイプライン:開発からテスト、デプロイまでを支援する包括的なツールチェーンを提供します
- 実例に基づくドキュメント:実践的な例を通じてベストプラクティスを示し、導入を促進します
このフレームワークは、特に次のような用途に適しています。
- AI ツール開発チーム
- 既存の API を AI ツールに変換したい開発者
- 標準化されたマイクロサービスアーキテクチャを導入する組織
アーキテクチャ
コアアーキテクチャ
┌─────────────┐ ┌───────────────┐ ┌─────────────────┐
│ API Layer │ ──→ │ Service Layer │ ──→ │ Implementation │
└─────────────┘ └───────────────┘ └─────────────────┘
↓
┌─────────────┐
│ MCP Endpoint│ ←── FastAPI-MCP Auto-Conversion
└─────────────┘
主なコンポーネント
- FastAPI アプリケーション:HTTP API サービスの基盤を提供します
- FastAPI-MCP:API エンドポイントを MCP ツールに変換します
- サービスインターフェース層:抽象基底クラスを通じてサービスの契約を定義します
- 依存性注入プロバイダー:サービスインスタンスの生成と注入を管理します
- 実装クラス:Mock と Real の実装を含み、環境に応じて切り替えます
技術スタック
- Python 3.10+:最新の言語機能と型アノテーションを活用します
- FastAPI:高性能な非同期 Web フレームワークです
- FastAPI-MCP:FastAPI エンドポイントを MCP ツールとして自動的に公開します
- 開発ツールチェーン:コード品質チェックとテストのツールを含みます
クイックスタート
環境のセットアップ
このフレームワークでは、パッケージマネージャーとして uv を使用し、依存関係の解決と仮想環境の管理を高速化します。インストール方法については、uv 公式ドキュメントを参照してください。
# Install dependencies and set up the development environment
make install
サンプルサービスの起動
# Start the development server
make dev
サービスの起動後、次の操作ができます。
http://localhost:5000/docsで API ドキュメントにアクセスします- MCP クライアント(Cursor、Claude Desktop など)を使用して、
http://localhost:5000/mcpの MCP エンドポイントに接続します
プロジェクト構成
.
├── main.py # Application entry point and route definitions
├── services/ # Service layer implementations
│ └── parking_service.py # Example service (replaceable with custom services)
├── pyproject.toml # Project configuration and dependency definitions
└── Makefile # Development and build tasks
MCP ツール開発ガイド
開発プロセスの概要
- サービスインターフェースの定義:抽象基底クラスを作成して、サービスの契約を定義します
- サービスの実装:要件に応じて Mock または Real の実装を開発します
- API エンドポイントの作成:FastAPI を使用して API インターフェースを開発します
- MCP サービスの有効化:FastAPI-MCP を通じてエンドポイントを AI ツールとして公開します
サービスインターフェースと実装
# 1. Service Interface Definition
from abc import ABC, abstractmethod
from typing import Dict, Any
class DataService(ABC):
@abstractmethod
def get_data(self, id: str) -> Dict[str, Any]:
"""Data retrieval interface"""
pass
# 2A. Mock Implementation - for development and testing
class DataServiceMockImpl(DataService):
def get_data(self, id: str) -> Dict[str, Any]:
return {"id": id, "name": "Test Data", "mock": True}
# 2B. Real Implementation - for production environment
class DataServiceImpl(DataService):
def __init__(self, database_url: str):
self.db = Database(database_url)
def get_data(self, id: str) -> Dict[str, Any]:
return self.db.query("SELECT * FROM data WHERE id = :id", {"id": id})
# 3. Dependency Injection Configuration
def get_data_service() -> DataService:
# Choose implementation based on environment
return DataServiceMockImpl() # or return DataServiceImpl(settings.DATABASE_URL)
API と MCP ツールの定義
from fastapi import FastAPI, Depends
from fastapi_mcp import FastApiMCP
from pydantic import BaseModel, Field
app = FastAPI()
# Request model
class ItemRequest(BaseModel):
query: str = Field(..., description="Search query parameter")
limit: int = Field(10, description="Result limit")
# API endpoint - automatically converted to an MCP tool
@app.post("/items/search", operation_id="search_items")
async def search_items(
request: ItemRequest,
service: DataService = Depends(get_data_service)
):
result = service.search_items(request.query, request.limit)
return {"items": result["items"], "total": len(result["items"])}
# Create and mount MCP service
mcp = FastApiMCP(
app,
name="example-service",
description="Example MCP service",
base_url="http://localhost:5000",
include_operations=["search_items"]
)
# Mount MCP service at specified path
mcp.mount(mount_path="/mcp")
依存性注入の解説
FastAPI の依存性注入システムはこのフレームワークの重要な要素であり、強力で柔軟な依存関係管理機能を提供します。
依存性注入の基本
依存性注入とは、コンポーネントが依存関係を自ら作成・管理するのではなく、依存関係(サービス、データベース接続など)をそれらを使用するコンポーネントに注入する設計パターンです。FastAPI では、依存性注入は Depends 関数を通じて実装されます。
from fastapi import Depends
def get_db():
"""Database connection provider"""
db = connect_to_db()
try:
yield db # Using yield enables lifecycle management of dependencies
finally:
db.close()
@app.get("/items/")
async def get_items(db = Depends(get_db)):
return db.query(Item).all()
依存関係の種類
FastAPI は、次の種類の依存性注入をサポートしています。
- 関数の依存関係:上記のように、関数を依存関係プロバイダーとして使用します
- クラスの依存関係:より複雑な依存関係の管理に、クラスを依存関係として使用します
class DatabaseDependency:
def __init__(self, settings = Depends(get_settings)):
self.settings = settings
def __call__(self):
db = connect_to_db(self.settings.db_url)
try:
yield db
finally:
db.close()
@app.get("/users/")
async def get_users(db = Depends(DatabaseDependency())):
return db.query(User).all()
- ネストされた依存関係:依存関係がほかの依存関係に依存でき、依存関係ツリーを形成します
MCP ツール開発での活用
このフレームワークでは、依存性注入を主に次の用途に使用します。
- サービスインスタンスの管理:サービスの実装を API エンドポイントに注入します
- 環境への適応:実行時の環境に基づいて、異なるサービス実装を選択します
- リソースのライフサイクル管理:データベース接続などのリソースの作成と解放を管理します
FastAPI-MCP の機能
MCP ツールの自動生成
FastAPI-MCP は、FastAPI のエンドポイントを MCP ツールに自動変換できます。
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP
app = FastAPI()
# Define a standard FastAPI endpoint
@app.post("/predict", operation_id="predict_sentiment")
async def predict_sentiment(text: str):
return {"sentiment": "positive", "confidence": 0.92}
# Create and mount MCP service - automatically converts the above endpoint to an MCP tool
mcp = FastApiMCP(
app,
name="sentiment-analysis",
description="Sentiment analysis service",
base_url="http://localhost:5000",
include_operations=["predict_sentiment"]
)
# Mount MCP service at specified path
mcp.mount(mount_path="/mcp")
ツールの命名に関するベストプラクティス
MCP ツール名には、デフォルトで API エンドポイントの operation_id が使用されます。次の命名規則に従うことをおすすめします。
- 明確で説明的な名前を使用します
- 動詞_名詞の形式を採用します(例:
predict_sentiment、find_nearby_parking) - 自動生成に頼らず、
operation_idを明示的に設定します
# Recommended: Explicitly set operation_id
@app.post("/parking/nearby", operation_id="find_nearby_parking")
async def find_nearby(request: NearbyRequest):
# Implementation logic...
pass
# Not recommended: Relying on auto-generated operation_id (generates something like "find_nearby_parking_nearby_post")
@app.post("/parking/nearby")
async def find_nearby(request: NearbyRequest):
# Implementation logic...
pass
テストと品質保証
このフレームワークは、複数レベルのテスト戦略をサポートしています。
# Run code quality checks
make check
# Run test suite
make test
テスト戦略
- ユニットテスト:Mock サービスの実装を使用して個々のコンポーネントをテストします
- 統合テスト:コンポーネント間の連携をテストします
- API テスト:HTTP インターフェースの動作を検証します
- MCP ツールのテスト:AI ツールの機能を検証します
パフォーマンスの最適化
MCP ツールの高いパフォーマンスを確保するため、次のことをおすすめします。
- 非同期処理:FastAPI の非同期機能を活用して、リクエストを並行処理します
- キャッシュ戦略:頻繁に要求されるデータにキャッシュを実装します
- バッチ処理:呼び出し頻度を減らすため、バッチ操作をサポートする API を設計します
貢献ガイドライン
このフレームワークへの貢献を歓迎します。
- リポジトリをフォークします
- 機能ブランチを作成します(
git checkout -b feature/amazing-feature) - 変更をコミットします(
git commit -m 'Add amazing feature') - ブランチにプッシュします(
git push origin feature/amazing-feature) - プルリクエストを作成します
ライセンス
参考資料
- FastAPI - 高パフォーマンスなウェブフレームワーク
- FastAPI-MCP - MCP ツール自動生成ライブラリ
コメント
AI アプリケーションが外部のツールやデータソースに統一的な方法で接続するためのオープンなプロトコルです。クライアントはモデルとの対話を担い、MCP サーバーはツール・リソース・プロンプトテンプレートを提供します。標準メッセージでやり取りするため、1 つのサーバーを複数のクライアントで再利用できます。