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
server.md docs/
1# Server Implementation23Core server functionality for creating MCP servers with decorators, managing components, and handling protocol communication. The FastMCP server provides a high-level interface for building MCP servers with minimal boilerplate.45## Capabilities67### FastMCP Server Class89The main server class that manages tools, resources, prompts, middleware, authentication, and protocol communication.1011```python { .api }12class FastMCP:13def __init__(14self,15name: str,16version: str = "0.1.0",17instructions: str | None = None,18auth_provider: AuthProvider | None = None,19middlewares: list[Middleware] | None = None,20settings: Settings | None = None21):22"""23Create a FastMCP server instance.2425Parameters:26- name: Server name for identification27- version: Server version string28- instructions: Optional instructions for LLM interaction29- auth_provider: Authentication provider for server security30- middlewares: List of middleware for request/response processing31- settings: Server settings and configuration32"""33```3435### Tool Registration3637Register functions as tools that LLMs can call to perform actions.3839```python { .api }40def tool(41self,42func: Callable | None = None,43*,44name: str | None = None45) -> Callable:46"""47Decorator to register a function as a tool.4849Parameters:50- func: Function to register as tool51- name: Optional custom tool name (defaults to function name)5253Returns:54Decorated function55"""5657def add_tool(self, tool: Tool) -> None:58"""59Add a tool instance programmatically.6061Parameters:62- tool: Tool instance to add63"""6465def remove_tool(self, name: str) -> None:66"""67Remove a tool by name.6869Parameters:70- name: Name of tool to remove71"""72```7374### Resource Registration7576Register functions as resources that provide read-only data access.7778```python { .api }79def resource(self, uri: str) -> Callable:80"""81Decorator to register a function as a resource.8283Parameters:84- uri: Resource URI, can include {parameters} for templates8586Returns:87Decorated function88"""8990def add_resource(self, resource: Resource) -> None:91"""92Add a resource instance programmatically.9394Parameters:95- resource: Resource instance to add96"""9798def add_template(self, template: ResourceTemplate) -> None:99"""100Add a resource template for dynamic resources.101102Parameters:103- template: ResourceTemplate instance to add104"""105```106107### Prompt Registration108109Register functions as prompts that provide reusable message templates.110111```python { .api }112def prompt(113self,114func: Callable | None = None,115*,116name: str | None = None117) -> Callable:118"""119Decorator to register a function as a prompt.120121Parameters:122- func: Function to register as prompt123- name: Optional custom prompt name (defaults to function name)124125Returns:126Decorated function127"""128129def add_prompt(self, prompt: Prompt) -> None:130"""131Add a prompt instance programmatically.132133Parameters:134- prompt: Prompt instance to add135"""136```137138### Server Execution139140Run the server with specified transport and configuration.141142```python { .api }143def run(144self,145transport: Literal["stdio", "sse", "http"] = "stdio",146host: str = "127.0.0.1",147port: int = 8000,148path: str = "/mcp",149**kwargs150) -> None:151"""152Run the MCP server.153154Parameters:155- transport: Transport protocol ("stdio", "sse", "http")156- host: Host address for network transports157- port: Port number for network transports158- path: URL path for HTTP transport159- **kwargs: Additional transport-specific options160"""161```162163### Middleware and Custom Routes164165Add middleware and custom HTTP routes for extended functionality.166167```python { .api }168def add_middleware(self, middleware: Middleware) -> None:169"""170Add middleware for request/response processing.171172Parameters:173- middleware: Middleware instance to add174"""175176def custom_route(177self,178path: str,179methods: list[str] | None = None180) -> Callable:181"""182Decorator to add custom HTTP routes.183184Parameters:185- path: URL path for the route186- methods: HTTP methods supported (defaults to ["GET"])187188Returns:189Decorated function190"""191```192193### Tool Transformations194195Add transformations to modify tool behavior dynamically.196197```python { .api }198def add_tool_transformation(self, transform: Callable) -> None:199"""200Add a tool transformation function.201202Parameters:203- transform: Function that transforms tool calls204"""205```206207### Server Properties208209Access server configuration and state.210211```python { .api }212@property213def name(self) -> str:214"""Server name."""215216@property217def version(self) -> str:218"""Server version."""219220@property221def instructions(self) -> str | None:222"""Server instructions for LLM interaction."""223224@property225def settings(self) -> Settings:226"""Server settings and configuration."""227```228229## Usage Examples230231### Basic Server with Multiple Components232233```python234from fastmcp import FastMCP, Context235236mcp = FastMCP(237name="My Assistant Server",238version="1.0.0",239instructions="A helpful assistant server"240)241242@mcp.tool243def calculate(expression: str) -> float:244"""Safely evaluate a mathematical expression."""245# Safe evaluation logic here246return eval(expression) # Note: Use safe_eval in production247248@mcp.resource("config://{key}")249def get_config(key: str) -> dict:250"""Get configuration value by key."""251config = {"version": "1.0.0", "name": "My Server"}252return {"key": key, "value": config.get(key)}253254@mcp.prompt255def analyze_data(data_description: str) -> str:256"""Generate analysis prompt for data."""257return f"Please analyze the following data: {data_description}"258259# Run with different transports260if __name__ == "__main__":261# Default stdio transport262mcp.run()263264# HTTP transport265# mcp.run(transport="http", port=8080)266267# SSE transport268# mcp.run(transport="sse", port=8080)269```270271### Server with Authentication and Middleware272273```python274from fastmcp import FastMCP275from fastmcp.server.auth import JWTVerifier276from fastmcp.server.middleware import Middleware277278# Configure authentication279auth_provider = JWTVerifier(280secret="your-secret-key",281algorithms=["HS256"]282)283284# Custom middleware285class LoggingMiddleware(Middleware):286async def __call__(self, request, call_next):287print(f"Processing request: {request}")288response = await call_next(request)289print(f"Response: {response}")290return response291292mcp = FastMCP(293name="Secure Server",294auth_provider=auth_provider,295middlewares=[LoggingMiddleware()]296)297298@mcp.tool299def sensitive_operation(data: str) -> str:300"""Perform a sensitive operation (requires authentication)."""301return f"Processed: {data}"302303mcp.run(transport="http", port=8080)304```305306### Server with Context Usage307308```python309from fastmcp import FastMCP, Context310311mcp = FastMCP("Context Demo Server")312313@mcp.tool314async def process_with_context(data: str, ctx: Context) -> str:315"""Process data with context capabilities."""316# Log to client317await ctx.info(f"Processing data: {data}")318319# Make HTTP request320response = await ctx.http_request(321"GET",322"https://api.example.com/data",323headers={"Authorization": "Bearer token"}324)325326# Sample from LLM327summary = await ctx.sample([328{"role": "user", "content": f"Summarize: {response}"}329])330331# Report progress332await ctx.report_progress(100, 100)333334return summary.text335336mcp.run()337```