CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-fastmcp

The fast, Pythonic way to build MCP servers and clients with minimal boilerplate code.

Pending
Overview
Eval results
Files

server.mddocs/

Server Implementation

Core 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.

Capabilities

FastMCP Server Class

The main server class that manages tools, resources, prompts, middleware, authentication, and protocol communication.

class FastMCP:
    def __init__(
        self,
        name: str,
        version: str = "0.1.0",
        instructions: str | None = None,
        auth_provider: AuthProvider | None = None,
        middlewares: list[Middleware] | None = None,
        settings: Settings | None = None
    ):
        """
        Create a FastMCP server instance.
        
        Parameters:
        - name: Server name for identification
        - version: Server version string
        - instructions: Optional instructions for LLM interaction
        - auth_provider: Authentication provider for server security
        - middlewares: List of middleware for request/response processing
        - settings: Server settings and configuration
        """

Tool Registration

Register functions as tools that LLMs can call to perform actions.

def tool(
    self,
    func: Callable | None = None,
    *,
    name: str | None = None
) -> Callable:
    """
    Decorator to register a function as a tool.
    
    Parameters:
    - func: Function to register as tool
    - name: Optional custom tool name (defaults to function name)
    
    Returns:
    Decorated function
    """

def add_tool(self, tool: Tool) -> None:
    """
    Add a tool instance programmatically.
    
    Parameters:
    - tool: Tool instance to add
    """

def remove_tool(self, name: str) -> None:
    """
    Remove a tool by name.
    
    Parameters:
    - name: Name of tool to remove
    """

Resource Registration

Register functions as resources that provide read-only data access.

def resource(self, uri: str) -> Callable:
    """
    Decorator to register a function as a resource.
    
    Parameters:
    - uri: Resource URI, can include {parameters} for templates
    
    Returns:
    Decorated function
    """

def add_resource(self, resource: Resource) -> None:
    """
    Add a resource instance programmatically.
    
    Parameters:
    - resource: Resource instance to add
    """

def add_template(self, template: ResourceTemplate) -> None:
    """
    Add a resource template for dynamic resources.
    
    Parameters:
    - template: ResourceTemplate instance to add
    """

Prompt Registration

Register functions as prompts that provide reusable message templates.

def prompt(
    self,
    func: Callable | None = None,
    *,
    name: str | None = None
) -> Callable:
    """
    Decorator to register a function as a prompt.
    
    Parameters:
    - func: Function to register as prompt
    - name: Optional custom prompt name (defaults to function name)
    
    Returns:
    Decorated function
    """

def add_prompt(self, prompt: Prompt) -> None:
    """
    Add a prompt instance programmatically.
    
    Parameters:
    - prompt: Prompt instance to add
    """

Server Execution

Run the server with specified transport and configuration.

def run(
    self,
    transport: Literal["stdio", "sse", "http"] = "stdio",
    host: str = "127.0.0.1",
    port: int = 8000,
    path: str = "/mcp",
    **kwargs
) -> None:
    """
    Run the MCP server.
    
    Parameters:
    - transport: Transport protocol ("stdio", "sse", "http")
    - host: Host address for network transports
    - port: Port number for network transports
    - path: URL path for HTTP transport
    - **kwargs: Additional transport-specific options
    """

Middleware and Custom Routes

Add middleware and custom HTTP routes for extended functionality.

def add_middleware(self, middleware: Middleware) -> None:
    """
    Add middleware for request/response processing.
    
    Parameters:
    - middleware: Middleware instance to add
    """

def custom_route(
    self,
    path: str,
    methods: list[str] | None = None
) -> Callable:
    """
    Decorator to add custom HTTP routes.
    
    Parameters:
    - path: URL path for the route
    - methods: HTTP methods supported (defaults to ["GET"])
    
    Returns:
    Decorated function
    """

Tool Transformations

Add transformations to modify tool behavior dynamically.

def add_tool_transformation(self, transform: Callable) -> None:
    """
    Add a tool transformation function.
    
    Parameters:
    - transform: Function that transforms tool calls
    """

Server Properties

Access server configuration and state.

@property
def name(self) -> str:
    """Server name."""

@property
def version(self) -> str:
    """Server version."""

@property
def instructions(self) -> str | None:
    """Server instructions for LLM interaction."""

@property
def settings(self) -> Settings:
    """Server settings and configuration."""

Usage Examples

Basic Server with Multiple Components

from fastmcp import FastMCP, Context

mcp = FastMCP(
    name="My Assistant Server",
    version="1.0.0",
    instructions="A helpful assistant server"
)

@mcp.tool
def calculate(expression: str) -> float:
    """Safely evaluate a mathematical expression."""
    # Safe evaluation logic here
    return eval(expression)  # Note: Use safe_eval in production

@mcp.resource("config://{key}")
def get_config(key: str) -> dict:
    """Get configuration value by key."""
    config = {"version": "1.0.0", "name": "My Server"}
    return {"key": key, "value": config.get(key)}

@mcp.prompt
def analyze_data(data_description: str) -> str:
    """Generate analysis prompt for data."""
    return f"Please analyze the following data: {data_description}"

# Run with different transports
if __name__ == "__main__":
    # Default stdio transport
    mcp.run()
    
    # HTTP transport
    # mcp.run(transport="http", port=8080)
    
    # SSE transport  
    # mcp.run(transport="sse", port=8080)

Server with Authentication and Middleware

from fastmcp import FastMCP
from fastmcp.server.auth import JWTVerifier
from fastmcp.server.middleware import Middleware

# Configure authentication
auth_provider = JWTVerifier(
    secret="your-secret-key",
    algorithms=["HS256"]
)

# Custom middleware
class LoggingMiddleware(Middleware):
    async def __call__(self, request, call_next):
        print(f"Processing request: {request}")
        response = await call_next(request)
        print(f"Response: {response}")
        return response

mcp = FastMCP(
    name="Secure Server",
    auth_provider=auth_provider,
    middlewares=[LoggingMiddleware()]
)

@mcp.tool
def sensitive_operation(data: str) -> str:
    """Perform a sensitive operation (requires authentication)."""
    return f"Processed: {data}"

mcp.run(transport="http", port=8080)

Server with Context Usage

from fastmcp import FastMCP, Context

mcp = FastMCP("Context Demo Server")

@mcp.tool
async def process_with_context(data: str, ctx: Context) -> str:
    """Process data with context capabilities."""
    # Log to client
    await ctx.info(f"Processing data: {data}")
    
    # Make HTTP request
    response = await ctx.http_request(
        "GET", 
        "https://api.example.com/data",
        headers={"Authorization": "Bearer token"}
    )
    
    # Sample from LLM
    summary = await ctx.sample([
        {"role": "user", "content": f"Summarize: {response}"}
    ])
    
    # Report progress
    await ctx.report_progress(100, 100)
    
    return summary.text

mcp.run()

Install with Tessl CLI

npx tessl i tessl/pypi-fastmcp

docs

authentication.md

client.md

context.md

index.md

prompts.md

resources.md

server.md

tools.md

transports.md

utilities.md

tile.json