Spec Registry
Help your agents use open-source better. Learn more.
Find usage specs for your project’s dependencies
- Author
- tessl
- Last updated
- Spec files
pypi-fastmcp
Describes: pypi/fastmcp
- Description
- The fast, Pythonic way to build MCP servers and clients with minimal boilerplate code.
- Author
- tessl
- Last updated
index.md docs/
1# FastMCP23The fast, Pythonic way to build MCP servers and clients. FastMCP is a comprehensive framework for building Model Context Protocol (MCP) servers and clients with minimal boilerplate code, providing a clean, Pythonic API for creating tools, exposing resources, defining prompts, and connecting components in the MCP ecosystem.45## Package Information67- **Package Name**: fastmcp8- **Language**: Python9- **Installation**: `pip install fastmcp`10- **Python Requirements**: >=3.101112## Core Imports1314```python15from fastmcp import FastMCP, Context, Client16```1718## Basic Usage1920### Creating a Simple MCP Server2122```python23from fastmcp import FastMCP2425# Create a server instance26mcp = FastMCP("Demo Server")2728@mcp.tool29def add(a: int, b: int) -> int:30"""Add two numbers."""31return a + b3233@mcp.resource("config://version")34def get_version():35"""Get server version."""36return "1.0.0"3738@mcp.prompt39def summarize_request(text: str) -> str:40"""Generate a prompt asking for a summary."""41return f"Please summarize the following text:\n\n{text}"4243if __name__ == "__main__":44mcp.run() # Run with stdio transport45```4647### Creating a Client4849```python50from fastmcp import Client5152async def main():53# Connect to a server via stdio54async with Client("server.py") as client:55# List available tools56tools = await client.list_tools()5758# Call a tool59result = await client.call_tool("add", {"a": 5, "b": 3})60print(result.text)6162# Read a resource63resource = await client.read_resource("config://version")64print(resource.content)65```6667## Architecture6869FastMCP is built around several core components that work together to provide a complete MCP framework:7071- **FastMCP Server**: The main server class that manages tools, resources, prompts, and handles MCP protocol communication72- **Context**: Execution context providing capabilities like logging, LLM sampling, and HTTP requests to tools/resources/prompts73- **Client**: Full-featured client supporting multiple transports and authentication methods74- **Component System**: Modular architecture for tools, resources, and prompts with both decorator and class-based approaches75- **Transport Layer**: Multiple transport protocols (stdio, HTTP, SSE, WebSocket) for flexible deployment76- **Authentication**: Comprehensive auth system supporting OAuth, JWT, Bearer tokens, and custom providers77- **Middleware**: Extensible middleware system for request/response processing7879## Capabilities8081### Server Implementation8283Core server functionality for creating MCP servers with decorators, managing components, and handling protocol communication.8485```python { .api }86class FastMCP:87def __init__(88self,89name: str,90version: str = "0.1.0",91instructions: str | None = None,92auth_provider: AuthProvider | None = None,93middlewares: list[Middleware] | None = None,94settings: Settings | None = None95): ...9697def tool(self, func: Callable | None = None, *, name: str | None = None) -> Callable: ...98def resource(self, uri: str) -> Callable: ...99def prompt(self, func: Callable | None = None, *, name: str | None = None) -> Callable: ...100def run(101self,102transport: Literal["stdio", "sse", "http"] = "stdio",103host: str = "127.0.0.1",104port: int = 8000,105**kwargs106) -> None: ...107```108109[Server Implementation](./server.md)110111### Client Library112113Full-featured MCP client supporting multiple transports, authentication, and advanced features like LLM sampling.114115```python { .api }116class Client:117def __init__(118self,119server_or_config: str | FastMCP | dict,120transport: ClientTransport | None = None,121auth: BearerAuth | OAuth | None = None,122sampling_handler: SamplingHandler | None = None,123elicitation_handler: ElicitationHandler | None = None124): ...125126async def list_tools(self) -> list: ...127async def call_tool(self, name: str, arguments: dict | None = None): ...128async def list_resources(self) -> list: ...129async def read_resource(self, uri: str): ...130async def list_prompts(self) -> list: ...131async def get_prompt(self, name: str, arguments: dict | None = None): ...132```133134[Client Library](./client.md)135136### Tools System137138Tools allow LLMs to perform actions by executing Python functions, with automatic schema generation and flexible return types.139140```python { .api }141class Tool:142def __init__(143self,144name: str,145description: str,146func: Callable,147schema: dict | None = None148): ...149150class FunctionTool(Tool): ...151152class ToolManager:153def add_tool(self, tool: Tool) -> None: ...154def remove_tool(self, name: str) -> None: ...155def get_tool(self, name: str) -> Tool | None: ...156```157158[Tools System](./tools.md)159160### Resources System161162Resources expose read-only data sources with support for static resources and dynamic templates with URI parameters.163164```python { .api }165class Resource:166def __init__(167self,168uri: str,169name: str,170description: str,171mime_type: str | None = None172): ...173174class ResourceTemplate:175def __init__(176self,177uri_template: str,178name: str,179description: str,180mime_type: str | None = None181): ...182183class ResourceManager:184def add_resource(self, resource: Resource) -> None: ...185def add_template(self, template: ResourceTemplate) -> None: ...186```187188[Resources System](./resources.md)189190### Prompts System191192Prompts define reusable message templates to guide LLM interactions with parameter support and message formatting.193194```python { .api }195class Prompt:196def __init__(197self,198name: str,199description: str,200func: Callable,201schema: dict | None = None202): ...203204class PromptManager:205def add_prompt(self, prompt: Prompt) -> None: ...206def get_prompt(self, name: str) -> Prompt | None: ...207208def Message(209role: Literal["user", "assistant", "system"],210content: str | dict,211name: str | None = None212): ...213```214215[Prompts System](./prompts.md)216217### Context and Dependencies218219Execution context providing capabilities like logging, LLM sampling, HTTP requests, and resource access to tools/resources/prompts.220221```python { .api }222class Context:223async def info(self, message: str) -> None: ...224async def error(self, message: str) -> None: ...225async def debug(self, message: str) -> None: ...226async def sample(227self,228messages: list[dict],229params: dict | None = None230): ...231async def read_resource(self, uri: str): ...232async def http_request(233self,234method: str,235url: str,236headers: dict | None = None,237data: Any | None = None238): ...239async def report_progress(self, progress: int, total: int | None = None) -> None: ...240```241242[Context and Dependencies](./context.md)243244### Transport Layer245246Multiple transport protocols for flexible server deployment and client connections.247248```python { .api }249class ClientTransport: ...250class StdioTransport(ClientTransport): ...251class SSETransport(ClientTransport): ...252class StreamableHttpTransport(ClientTransport): ...253class WSTransport(ClientTransport): ...254class FastMCPTransport(ClientTransport): ...255```256257[Transport Layer](./transports.md)258259### Authentication260261Comprehensive authentication system supporting multiple providers and tokens for secure server and client connections.262263```python { .api }264class AuthProvider: ...265class OAuthProvider(AuthProvider): ...266class JWTVerifier(AuthProvider): ...267class TokenVerifier(AuthProvider): ...268class StaticTokenVerifier(AuthProvider): ...269class RemoteAuthProvider(AuthProvider): ...270271class BearerAuth: ...272class OAuth: ...273class AccessToken: ...274```275276[Authentication](./authentication.md)277278### Utilities and Types279280Helper classes and utility functions for enhanced functionality and type support.281282```python { .api }283class Image:284def __init__(285self,286data: bytes | str,287mime_type: str = "image/png"288): ...289290class Audio:291def __init__(292self,293data: bytes | str,294mime_type: str = "audio/wav"295): ...296297class File:298def __init__(299self,300data: bytes | str,301name: str,302mime_type: str | None = None303): ...304305class Settings: ...306class MCPConfig: ...307```308309[Utilities and Types](./utilities.md)310311## Types312313```python { .api }314# Core types315from typing import Callable, Any, Literal316from pydantic import BaseModel317318class FastMCPBaseModel(BaseModel): ...319320# Function signatures for decorators321ToolFunction = Callable[..., Any]322ResourceFunction = Callable[..., str | bytes | dict]323PromptFunction = Callable[..., str | list[dict]]324325# Transport types326TransportType = Literal["stdio", "sse", "http", "ws"]327328# Authentication types329SamplingHandler = Callable[[list[dict]], Any]330ElicitationHandler = Callable[[dict], Any]331332# Component types333class MCPMixin: ...334ComponentFn = Callable[..., Any]335```