FastMCP는 Model Context Protocol (MCP) 서버 및 클라이언트를 구축하기 위한 고급 Python 프레임워크로, 개발자가 도구를 빠르고 간결하게 생성하고, 리소스를 노출하고, 프롬프트를 정의하고, 컴포넌트를 연결할 수 있도록 설계되었습니다. 이 프로젝트는 GitHub 사용자 jlowin이 개발 및 유지 관리하며, MCP 생태계의 중요한 구성 요소가 되었습니다.
MCP 프로토콜은 강력하지만, 이를 구현하려면 많은 상용구 코드(boilerplate code) - 서버 설정, 프로토콜 처리기, 콘텐츠 유형, 오류 관리 등 - 가 필요합니다. FastMCP는 모든 복잡한 프로토콜 세부 사항과 서버 관리를 처리하여 사용자가 훌륭한 도구를 구축하는 데 집중할 수 있도록 합니다.
FastMCP의 설계 목표:
FastMCP 1.0은 MCP 서버 구축을 매우 간단하게 만들어 공식 Model Context Protocol Python SDK의 일부가 되었습니다!
FastMCP 2.0은 이를 기반으로 다음과 같은 다양한 새로운 기능을 도입했습니다.
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
MCP 애플리케이션의 중심 객체를 나타내며, 연결, 프로토콜 세부 사항 및 라우팅을 처리합니다.
from fastmcp import FastMCP
mcp = FastMCP("My App")
mcp = FastMCP("My App", dependencies=["pandas", "numpy"])
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)
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")
재사용 가능한 템플릿 또는 상호 작용 패턴을 정의합니다.
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?")
]
다른 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')
모듈식 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)
기존 웹 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)
모든 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는 커뮤니티 기여를 환영합니다.
git clone https://github.com/jlowin/fastmcp.git && cd fastmcp
uv venv && uv sync
uv run pytest -vv
ruff
및 pre-commit
사용:
pre-commit install
pre-commit run --all-files
FastMCP는 MCP 프로토콜 구현과 실제 애플리케이션 개발 간의 격차를 해소하여 개발자가 다음을 수행할 수 있도록 합니다.