MCPサーバーとクライアントを構築するための高速でPythonicなオープンソースフレームワーク

Apache-2.0Pythonfastmcpjlowin 15.8k Last Updated: August 06, 2025

FastMCP - 高速にMCPサーバーとクライアントを構築するPythonフレームワーク

プロジェクト概要

FastMCPは、Model Context Protocol (MCP) サーバーとクライアントを構築するための高度なPythonフレームワークであり、開発者がツールを迅速かつ簡潔に作成し、リソースを公開し、プロンプトを定義し、コンポーネントを接続できるようにすることを目的としています。このプロジェクトは、GitHubユーザーjlowinによって開発・メンテナンスされており、MCPエコシステムにおける重要な構成要素となっています。

FastMCPを選ぶ理由

MCPプロトコルは強力ですが、それを実装するには、サーバー設定、プロトコルハンドラー、コンテンツタイプ、エラー管理など、大量のボイラープレートコードが必要です。FastMCPは、複雑なプロトコルの詳細とサーバー管理をすべて処理し、優れたツールの構築に集中できるようにします。

FastMCPの設計目標:

  • 🚀 高速:高度なインターフェースは、より少ないコードとより迅速な開発を意味します
  • 🍀 シンプル:最小限のボイラープレートコードでMCPサーバーを構築
  • 🐍 Pythonic:Python開発者にとって自然に感じられる
  • 🔍 完全:MCPコア仕様の完全な実装を提供し、サーバーとクライアントをサポート

コア機能特性

基本機能

  • 直感的なデコレーターを使用してサーバーを作成し、ボイラープレートコードを最小限に抑えます
  • 既存のサーバーをプロキシして、構成または転送方法を変更します
  • サーバーを組み合わせて複雑なアプリケーションを作成します
  • OpenAPI仕様またはFastAPIオブジェクトからサーバーを生成します
  • プログラムでMCPサーバーと対話します
  • 任意の転送プロトコルを使用して任意のMCPサーバーに接続します
  • 手動で介入することなくサーバーをテストします
  • LLMサンプリングなどのコアMCP機能を活用します

バージョン進化

FastMCP 1.0は、MCPサーバーの構築を非常に簡単にしたため、公式のModel Context Protocol Python SDKの一部になりました!

FastMCP 2.0は、これに加えて、いくつかの新機能を導入しました。

  • MCPサーバーのプロキシと組み合わせなどの高度な機能
  • OpenAPI仕様またはFastAPIオブジェクトからのサーバーの自動生成
  • LLMサンプリングなどのクライアント機能の導入

インストール方法

uvを使用してFastMCPをインストールすることをお勧めします。

uv pip install fastmcp

開発インストール:


git clone https://github.com/jlowin/fastmcp.git
cd fastmcp

uv sync

クイックスタート例

基本的なサーバーの例

# server.py
from fastmcp import FastMCP


mcp = FastMCP("Demo")


@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two numbers"""
    return a + b

@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
    """Get a personalized greeting"""
    return f"Hello, {name}!"

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

Claude Desktopへのインストール:

fastmcp install server.py

コア概念の詳細

1. FastMCPインスタンス

MCPアプリケーションの中心となるオブジェクトを表し、接続、プロトコルの詳細、およびルーティングを処理します。

from fastmcp import FastMCP


mcp = FastMCP("My App")


mcp = FastMCP("My App", dependencies=["pandas", "numpy"])

2. ツール(Tools)

LLMがPython関数を実行して操作を実行できるようにします。計算、外部API呼び出し、または副作用に適しています。

import httpx
from pydantic import BaseModel

class UserInfo(BaseModel):
    user_id: int
    notify: bool = False

@mcp.tool()
async def send_notification(user: UserInfo, message: str) -> dict:
    """Sends a notification to a user if requested."""
    if user.notify:

        print(f"Notifying user {user.user_id}: {message}")
        return {"status": "sent", "user_id": user.user_id}
    return {"status": "skipped", "user_id": user.user_id}

@mcp.tool()
def get_stock_price(ticker: str) -> float:
    """Gets the current price for a stock ticker."""

    prices = {"AAPL": 180.50, "GOOG": 140.20}
    return prices.get(ticker.upper(), 0.0)

3. リソース(Resources)

LLMにデータを公開します。主に、重要な計算や副作用なしに情報を提供します。


@mcp.resource("config://app-version")
def get_app_version() -> str:
    """Returns the application version."""
    return "v2.1.0"


@mcp.resource("db://users/{user_id}/email")
async def get_user_email(user_id: str) -> str:
    """Retrieves the email address for a given user ID."""

    emails = {"123": "alice@example.com", "456": "bob@example.com"}
    return emails.get(user_id, "not_found@example.com")

4. プロンプト(Prompts)

再利用可能なテンプレートまたはインタラクションパターンを定義します。

from fastmcp.prompts.base import UserMessage, AssistantMessage

@mcp.prompt()
def ask_review(code_snippet: str) -> str:
    """Generates a standard code review request."""
    return f"Please review the following code snippet for potential bugs and style issues:\n```python\n{code_snippet}\n```"

@mcp.prompt()
def debug_session_start(error_message: str) -> list[Message]:
    """Initiates a debugging help session."""
    return [
        UserMessage(f"I encountered an error:\n{error_message}"),
        AssistantMessage("Okay, I can help with that. Can you provide the full traceback and tell me what you were trying to do?")
    ]

高度な機能

1. プロキシサーバー

別のMCPエンドポイントへのリクエストをプロキシする仲介役として機能するFastMCPサーバーを作成します。

import asyncio
from fastmcp import FastMCP, Client
from fastmcp.client.transports import PythonStdioTransport


proxy_client = Client(
    transport=PythonStdioTransport('path/to/original_stdio_server.py'),
)


proxy = FastMCP.from_client(proxy_client, name="Stdio-to-SSE Proxy")

if __name__ == "__main__":
    proxy.run(transport='sse')

2. サーバーの組み合わせ

モジュール化されたFastMCPサーバーを作成し、それらを親サーバーに「マウント」することで、大規模なMCPアプリケーションを構築します。

from fastmcp import FastMCP


weather_mcp = FastMCP("Weather Service")

@weather_mcp.tool()
def get_forecast(city: str):
    return f"Sunny in {city}"


news_mcp = FastMCP("News Service")

@news_mcp.tool()
def fetch_headlines():
    return ["Big news!", "Other news"]


mcp = FastMCP("Composite")
mcp.mount("weather", weather_mcp) 
mcp.mount("news", news_mcp)        

3. APIからのサーバー生成

既存のWeb APIからFastMCPサーバーを自動的に生成します。

from fastapi import FastAPI
from fastmcp import FastMCP


fastapi_app = FastAPI(title="My Existing API")

@fastapi_app.get("/status")
def get_status():
    return {"status": "running"}


mcp_server = FastMCP.from_fastapi(fastapi_app)

4. クライアント機能

任意のMCPサーバーと対話します。

from fastmcp import Client

async with Client("path/to/server") as client:

    result = await client.call_tool("weather", {"location": "San Francisco"})
    print(result)
    

    res = await client.read_resource("db://users/123/profile")
    print(res)

サーバーの実行

開発モード

fastmcp dev your_server_file.py

本番環境へのインストール

fastmcp install your_server_file.py

直接実行

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

サンプルプロジェクト

プロジェクトには、複数のサンプルファイルが含まれています。

  • simple_echo.py: 基本的なツール、リソース、およびプロンプト
  • complex_inputs.py: Pydanticモデルをツールの入力として使用
  • mount_example.py: 複数のFastMCPサーバーをマウント
  • sampling.py: MCPサーバーでLLM補完を使用
  • screenshot.py: Imageオブジェクトを返すツール
  • text_me.py: 外部APIと対話するツール
  • memory.py: データベースとの対話を含む複雑な例

貢献ガイド

FastMCPはコミュニティからの貢献を歓迎します。

環境要件

  • Python 3.10+
  • uvパッケージマネージャー

開発設定

git clone https://github.com/jlowin/fastmcp.git && cd fastmcp
uv venv && uv sync

テスト

uv run pytest -vv

コード品質

ruffpre-commitを使用します。

pre-commit install
pre-commit run --all-files

プロジェクトの意義

FastMCPは、MCPプロトコルの実装と実際のアプリケーション開発の間のギャップを埋め、開発者が以下を可能にします。

  1. MCPサーバーを迅速にプロトタイプ化およびデプロイする
  2. 既存のAPIとデータソースを簡単に統合する
  3. モジュール化された、スケーラブルなAIアプリケーションアーキテクチャを構築する
  4. プロトコルの実装の詳細ではなく、ビジネスロジックに集中する

Star History Chart