Home
Login

MCP 서버 및 클라이언트를 구축하는 빠르고 Pythonic한 방식의 오픈 소스 프레임워크

Apache-2.0Python 13.0kjlowin Last Updated: 2025-06-21

FastMCP - MCP 서버 및 클라이언트의 빠른 구축을 위한 Python 프레임워크

프로젝트 개요

FastMCP는 Model Context Protocol (MCP) 서버 및 클라이언트를 구축하기 위한 고급 Python 프레임워크로, 개발자가 도구를 빠르고 간결하게 생성하고, 리소스를 노출하고, 프롬프트를 정의하고, 컴포넌트를 연결할 수 있도록 설계되었습니다. 이 프로젝트는 GitHub 사용자 jlowin이 개발 및 유지 관리하며, MCP 생태계의 중요한 구성 요소가 되었습니다.

왜 FastMCP를 선택해야 할까요?

MCP 프로토콜은 강력하지만, 이를 구현하려면 많은 상용구 코드(boilerplate code) - 서버 설정, 프로토콜 처리기, 콘텐츠 유형, 오류 관리 등 - 가 필요합니다. 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에서 서버 생성

기존 웹 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. 프로토콜 구현 세부 사항이 아닌 비즈니스 로직에 집중합니다.