FastMCP
FastMCP упрощает создание серверов Model Context Protocol (MCP) с помощью Pythonic-интерфейса. Разрабатывайте инструменты, ресурсы и промпты для LLM с лёгкостью. Теперь часть официального MCP SDK!
FastMCP упрощает разработку серверов Model Context Protocol (MCP), предлагая высокоуровневый, Pythonic-способ предоставления данных и функциональности LLM-приложениям. Он обрабатывает сложные детали протокола, позволяя разработчикам сосредоточиться на создании инструментов, предоставлении ресурсов и определении промптов с помощью чистого, интуитивно понятного кода на Python.
Ключевые особенности
Варианты использования
You can now find FastMCP as part of the official Model Context Protocol Python SDK:
👉 github.com/modelcontextprotocol/python-sdk
Please note: this repository is no longer maintained.
Model Context Protocol (MCP) servers are a new, standardized way to provide context and tools to your LLMs, and FastMCP makes building MCP servers simple and intuitive. Create tools, expose resources, and define prompts with clean, Pythonic code:
# demo.py
from fastmcp import FastMCP
mcp = FastMCP("Demo 🚀")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + bThat's it! Give Claude access to the server by running:
fastmcp install demo.pyFastMCP handles all the complex protocol details and server management, so you can focus on building great tools. It's designed to be high-level and Pythonic - in most cases, decorating a function is all you need.
- Fast: High-level interface means less code and faster development
- Simple: Build MCP servers with minimal boilerplate
- Pythonic: Feels natural to Python developers
- Complete*: FastMCP aims to provide a full implementation of the core MCP specification
(*emphasis on aims)
🚨 🚧 🏗️ FastMCP is under active development, as is the MCP specification itself. Core features are working but some advanced capabilities are still in progress.
We strongly recommend installing FastMCP with uv, as it is required for deploying servers:
uv pip install fastmcpNote: on macOS, uv may need to be installed with Homebrew (brew install uv) in order to make it available to the Claude Desktop app.
Alternatively, to use the SDK without deploying, you may use pip:
pip install fastmcpLet's create a simple MCP server that exposes a calculator tool and some data:
# server.py
from fastmcp import FastMCP
# Create an MCP server
mcp = FastMCP("Demo")
# Add an addition tool
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
# Add a dynamic greeting resource
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
"""Get a personalized greeting"""
return f"Hello, {name}!"You can install this server in Claude Desktop and interact with it right away by running:
fastmcp install server.pyAlternatively, you can test it with the MCP Inspector:
fastmcp dev server.pyThe Model Context Protocol (MCP) lets you build servers that expose data and functionality to LLM applications in a secure, standardized way. Think of it like a web API, but specifically designed for LLM interactions. MCP servers can:
- Expose data through Resources (think of these sort of like GET endpoints; they are used to load information into the LLM's context)
- Provide functionality through Tools (sort of like POST endpoints; they are used to execute code or otherwise produce a side effect)
- Define interaction patterns through Prompts (reusable templates for LLM interactions)
- And more!
There is a low-level Python SDK available for implementing the protocol directly, but FastMCP aims to make that easier by providing a high-level, Pythonic interface.
The FastMCP server is your core interface to the MCP protocol. It handles connection management, protocol compliance, and message routing:
from fastmcp import FastMCP
# Create a named server
mcp = FastMCP("My App")
# Specify dependencies for deployment and development
mcp = FastMCP("My App", dependencies=["pandas", "numpy"])Resources are how you expose data to LLMs. They're similar to GET endpoints in a REST API - they provide data but shouldn't perform significant computation or have side effects. Some examples:
- File contents
- Database schemas
- API responses
- System information
Resources can be static:
@mcp.resource("config://app")
def get_config() -> str:
"""Static configuration data"""
return "App configuration here"Or dynamic with parameters (FastMCP automatically handles these as MCP templates):
@mcp.resource("users://{user_id}/profile")
def get_user_profile(user_id: str) -> str:
"""Dynamic user data"""
return f"Profile data for user {user_id}"Tools let LLMs take actions through your server. Unlike resources, tools are expected to perform computation and have side effects. They're similar to POST endpoints in a REST API.
Simple calculation example:
@mcp.tool()
def calculate_bmi(weight_kg: float, height_m: float) -> float:
"""Calculate BMI given weight in kg and height in meters"""
return weight_kg / (height_m ** 2)HTTP request example:
import httpx
@mcp.tool()
async def fetch_weather(city: str) -> str:
"""Fetch current weather for a city"""
async with httpx.AsyncClient() as client:
response = await client.get(
f"https://api.weather.com/{city}"
)
return response.textComplex input handling example:
from pydantic import BaseModel, Field
from typing import Annotated
class ShrimpTank(BaseModel):
class Shrimp(BaseModel):
name: Annotated[str, Field(max_length=10)]
shrimp: list[Shrimp]
@mcp.tool()
def name_shrimp(
tank: ShrimpTank,
# You can use pydantic Field in function signatures for validation.
extra_names: Annotated[list[str], Field(max_length=10)],
) -> list[str]:
"""List all shrimp names in the tank"""
return [shrimp.name for shrimp in tank.shrimp] + extra_namesPrompts are reusable templates that help LLMs interact with your server effectively. They're like "best practices" encoded into your server. A prompt can be as simple as a string:
@mcp.prompt()
def review_code(code: str) -> str:
return f"Please review this code:\n\n{code}"Or a more structured sequence of messages:
from fastmcp.prompts.base import UserMessage, AssistantMessage
@mcp.prompt()
def debug_error(error: str) -> list[Message]:
return [
UserMessage("I'm seeing this error:"),
UserMessage(error),
AssistantMessage("I'll help debug that. What have you tried so far?")
]FastMCP provides an Image class that automatically handles image data in your server:
from fastmcp import FastMCP, Image
from PIL import Image as PILImage
@mcp.tool()
def create_thumbnail(image_path: str) -> Image:
"""Create a thumbnail from an image"""
img = PILImage.open(image_path)
img.thumbnail((100, 100))
# FastMCP automatically handles conversion and MIME types
return Image(data=img.tobytes(), format="png")
@mcp.tool()
def load_image(path: str) -> Image:
"""Load an image from disk"""
# FastMCP handles reading and format detection
return Image(path=path)Images can be used as the result of both tools and resources.
The Context object gives your tools and resources access to MCP capabilities. To use it, add a parameter annotated with fastmcp.Context:
from fastmcp import FastMCP, Context
@mcp.tool()
async def long_task(files: list[str], ctx: Context) -> str:
"""Process multiple files with progress tracking"""
for i, file in enumerate(files):
ctx.info(f"Processing {file}")
await ctx.report_progress(i, len(files))
# Read another resource if needed
data = await ctx.read_resource(f"file://{file}")
return "Processing complete"The Context object provides:
- Progress reporting through
report_progress() - Logging via
debug(),info(),warning(), anderror() - Resource access through
read_resource() - Request metadata via
request_idandclient_id
There are three main ways to use your FastMCP server, each suited for different stages of development:
The fastest way to test and debug your server is with the MCP Inspector:
fastmcp dev server.pyThis launches a web interface where you can:
- Test your tools and resources interactively
- See detailed logs and error messages
- Monitor server performance
- Set environment variables for testing
During development, you can:
- Add dependencies with
--with:fastmcp dev server.py --with pandas --with numpy
- Mount your local code for live updates:
fastmcp dev server.py --with-editable .
Once your server is ready, install it in Claude Desktop to use it with Claude:
fastmcp install server.pyYour server will run in an isolated environment with:
- Automatic installation of dependencies specified in your FastMCP instance:
mcp = FastMCP("My App", dependencies=["pandas", "numpy"])
- Custom naming via
--name:fastmcp install server.py --name "My Analytics Server" - Environment variable management:
# Set variables individually fastmcp install server.py -e API_KEY=abc123 -e DB_URL=postgres://... # Or load from a .env file fastmcp install server.py -f .env
For advanced scenarios like custom deployments or running without Claude, you can execute your server directly:
from fastmcp import FastMCP
mcp = FastMCP("My App")
if __name__ == "__main__":
mcp.run()Run it with:
# Using the FastMCP CLI
fastmcp run server.py
# Or with Python/uv directly
python server.py
uv run python server.pyNote: When running directly, you are responsible for ensuring all dependencies are available in your environment. Any dependencies specified on the FastMCP instance are ignored.
Choose this method when you need:
- Custom deployment configurations
- Integration with other services
- Direct control over the server lifecycle
All FastMCP commands will look for a server object called mcp, app, or server in your file. If you have a different object name or multiple servers in one file, use the syntax server.py:my_server:
# Using a standard name
fastmcp run server.py
# Using a custom name
fastmcp run server.py:my_custom_serverHere are a few examples of FastMCP servers. For more, see the examples/ directory.
A simple server demonstrating resources, tools, and prompts:
from fastmcp import FastMCP
mcp = FastMCP("Echo")
@mcp.resource("echo://{message}")
def echo_resource(message: str) -> str:
"""Echo a message as a resource"""
return f"Resource echo: {message}"
@mcp.tool()
def echo_tool(message: str) -> str:
"""Echo a message as a tool"""
return f"Tool echo: {message}"
@mcp.prompt()
def echo_prompt(message: str) -> str:
"""Create an echo prompt"""
return f"Please process this message: {message}"A more complex example showing database integration:
from fastmcp import FastMCP
import sqlite3
mcp = FastMCP("SQLite Explorer")
@mcp.resource("schema://main")
def get_schema() -> str:
"""Provide the database schema as a resource"""
conn = sqlite3.connect("database.db")
schema = conn.execute(
"SELECT sql FROM sqlite_master WHERE type='table'"
).fetchall()
return "\n".join(sql[0] for sql in schema if sql[0])
@mcp.tool()
def query_data(sql: str) -> str:
"""Execute SQL queries safely"""
conn = sqlite3.connect("database.db")
try:
result = conn.execute(sql).fetchall()
return "\n".join(str(row) for row in result)
except Exception as e:
return f"Error: {str(e)}"
@mcp.prompt()
def analyze_table(table: str) -> str:
"""Create a prompt template for analyzing tables"""
return f"""Please analyze this database table:
Table: {table}
Schema:
{get_schema()}
What insights can you provide about the structure and relationships?"""FastMCP requires Python 3.10+ and uv.
For development, we recommend installing FastMCP with development dependencies, which includes various utilities the maintainers find useful.
git clone https://github.com/jlowin/fastmcp.git
cd fastmcp
uv sync --frozen --extra devFor running tests only (e.g., in CI), you only need the testing dependencies:
uv sync --frozen --extra testsPlease make sure to test any new functionality. Your tests should be simple and atomic and anticipate change rather than cement complex patterns.
Run tests from the root directory:
pytest -vvFastMCP enforces a variety of required formats, which you can automatically enforce with pre-commit.
Install the pre-commit hooks:
pre-commit installThe hooks will now run on every commit (as well as on every PR). To run them manually:
pre-commit run --all-filesFork the repository and create a new branch:
git checkout -b my-branchMake your changes and commit them:
git add . && git commit -m "My changes"Push your changes to your fork:
git push origin my-branchFeel free to reach out in a GitHub issue or discussion if you have any questions!
FastMCP
Внимание: Этот репозиторий больше не поддерживается. FastMCP теперь является частью официального Python SDK для Model Context Protocol: github.com/modelcontextprotocol/python-sdk.
FastMCP — это быстрый и Pythonic-ориентированный способ создания серверов Model Context Protocol (MCP). MCP позволяет предоставлять LLM-приложениям контекст и инструменты через стандартизированный интерфейс. FastMCP берёт на себя сложную работу по реализации протокола и управлению сервером, чтобы вы сосредоточились на разработке.
Ключевые возможности:
- Высокоуровневый, минимальный код.
- Интуитивные декораторы для создания инструментов, ресурсов и промптов.
- Полная реализация базовых функций MCP (возможны изменения по мере развития протокола).
- Интеграция с инспектором MCP и Claude Desktop.
Установка
Рекомендуемый способ — с помощью uv (необходим для развёртывания серверов):
uv pip install fastmcp
На macOS для использования с Claude Desktop может потребоваться установка uv через Homebrew: brew install uv.
Если развёртывание не требуется, можно установить через pip:
pip install fastmcp
Быстрый старт
Создайте файл server.py и добавьте простой сервер с инструментом и ресурсом:
from fastmcp import FastMCP
# Создаём сервер
mcp = FastMCP("Demo")
# Инструмент сложения
@mcp.tool()
def add(a: int, b: int) -> int:
"""Складывает два числа"""
return a + b
# Ресурс с приветствием
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
"""Персонализированное приветствие"""
return f"Hello, {name}!"
Установите сервер в Claude Desktop:
fastmcp install server.py
Или протестируйте через MCP Inspector:
fastmcp dev server.py
Основные концепции
Сервер
Создаётся экземпляр FastMCP с именем и опциональными зависимостями для развёртывания:
mcp = FastMCP("My App", dependencies=["pandas", "numpy"])
Ресурсы (Resources)
Ресурсы предоставляют данные LLM, аналогично GET-запросам. Они могут быть статическими или динамическими:
# Статический ресурс
@mcp.resource("config://app")
def get_config() -> str:
return "App configuration"
# Динамический ресурс (шаблон)
@mcp.resource("users://{user_id}/profile")
def get_profile(user_id: str) -> str:
return f"Profile for {user_id}"
Инструменты (Tools)
Инструменты выполняют действия и могут иметь побочные эффекты. Используйте декоратор @mcp.tool():
@mcp.tool()
def calculate_bmi(weight_kg: float, height_m: float) -> float:
"""Расчёт ИМТ"""
return weight_kg / (height_m ** 2)
Для асинхронных вызовов используйте async и await. Для сложных входных данных можно применять Pydantic-модели.
Промпты (Prompts)
Промпты — это шаблоны для взаимодействия с LLM. Простейший вариант — функция, возвращающая строку:
@mcp.prompt()
def review_code(code: str) -> str:
return f"Please review this code:\n\n{code}"
Более структурированный вариант — возвращать список сообщений.
Изображения (Images)
FastMCP предоставляет класс Image для лёгкой работы с изображениями:
from fastmcp import FastMCP, Image
@mcp.tool()
def load_image(path: str) -> Image:
return Image(path=path)
Контекст (Context)
Объект Context позволяет инструментам и ресурсам получать доступ к возможностям MCP (прогресс, логирование, чтение ресурсов). Для его использования добавьте параметр с аннотацией Context:
from fastmcp import FastMCP, Context
@mcp.tool()
async def long_task(files: list[str], ctx: Context) -> str:
for i, file in enumerate(files):
ctx.info(f"Processing {file}")
await ctx.report_progress(i, len(files))
return "Complete"
Запуск сервера
Режим разработки (рекомендуется для сборки и тестирования)
fastmcp dev server.py
Открывает веб-интерфейс для интерактивного тестирования инструментов и ресурсов, просмотра логов и мониторинга.
Добавить зависимости: fastmcp dev server.py --with pandas --with numpy.
Интеграция с Claude Desktop (регулярное использование)
fastmcp install server.py
Можно задать имя сервера (--name) и переменные окружения (-e или -f .env).
Прямой запуск (продвинутые сценарии)
if __name__ == "__main__":
mcp.run()
Затем:
fastmcp run server.py
# или
python server.py
При прямом запуске зависимости указываются вручную (аргумент dependencies игнорируется).
Имена серверных объектов
По умолчанию команды ищут объекты с именем mcp, app или server. Если имя другое, укажите его через двоеточие: fastmcp run server.py:my_custom_server.
Примеры
Эхо-сервер
Демонстрирует ресурсы, инструменты и промпты:
from fastmcp import FastMCP
mcp = FastMCP("Echo")
@mcp.resource("echo://{message}")
def echo_resource(message: str) -> str:
return f"Resource echo: {message}"
@mcp.tool()
def echo_tool(message: str) -> str:
return f"Tool echo: {message}"
@mcp.prompt()
def echo_prompt(message: str) -> str:
return f"Please process this message: {message}"
SQLite Explorer
Пример интеграции с базой данных:
from fastmcp import FastMCP
import sqlite3
mcp = FastMCP("SQLite Explorer")
@mcp.resource("schema://main")
def get_schema() -> str:
conn = sqlite3.connect("database.db")
schema = conn.execute("SELECT sql FROM sqlite_master WHERE type='table'").fetchall()
return "\n".join(sql[0] for sql in schema if sql[0])
@mcp.tool()
def query_data(sql: str) -> str:
conn = sqlite3.connect("database.db")
try:
return "\n".join(str(row) for row in conn.execute(sql).fetchall())
except Exception as e:
return f"Error: {e}"
Заключение
FastMCP — это удобный инструмент для быстрой разработки MCP-серверов на Python. Используйте официальный SDK для последних версий.
Каковы ключевые особенности FastMCP?
FastMCP предлагает высокоуровневый Pythonic-интерфейс, упрощает создание MCP-серверов, стремится к полной реализации спецификации MCP и поддерживает создание инструментов, ресурсов и промптов. Он предназначен для более быстрой разработки с минимальным шаблонным кодом.
Что такое ресурсы и инструменты в контексте MCP?
Ресурсы используются для предоставления данных LLM (как GET-запросы), а инструменты позволяют LLM выполнять действия (как POST-запросы). FastMCP упрощает создание и тех, и других.
Что такое FastMCP?
FastMCP — это Python-библиотека, которая упрощает создание серверов Model Context Protocol (MCP), позволяя создавать инструменты, ресурсы и промпты для взаимодействия с LLM с помощью Pythonic-интерфейса.
Что такое Model Context Protocol (MCP)?
MCP — это стандартизированный способ безопасного и чётко определённого предоставления контекста и инструментов LLM-приложениям. Он облегчает связь между LLM и внешними источниками данных и функциональными возможностями.
Можно ли продолжать использовать FastMCP, или он устарел?
FastMCP теперь является частью официального Python SDK Model Context Protocol. Этот репозиторий больше не поддерживается, поэтому для получения последних обновлений и функций используйте официальный SDK. Он находится по адресу github.com/modelcontextprotocol/python-sdk.
Echo
Echo the provided text back to the user.
Parameters
1textstringAdd
Add two numbers together.
Parameters
2aintegerbintegerИсточник: https://mcpmarket.com/server/fastmcp
Комментарии
Комментариев пока нет. Будьте первым.