FastMCP

High-level framework for building Model Context Protocol servers and clients in Python and TypeScript, providing a simplified, Pythonic interface that handles protocol complexities automatically.

FastMCP

FastMCP is a high-level framework for building Model Context Protocol servers and clients that abstracts away protocol complexities and provides a clean, intuitive API. Originally developed as FastMCP 1.0 and later incorporated into the official MCP Python SDK, FastMCP 2.0 continues as an actively maintained, comprehensive toolkit for MCP development.

Key Features

Feature Purpose
High-Level API Decorator-based interface for tools, resources, and prompts
Multiple Transports Support for stdio, HTTP, SSE, and in-memory connections
Client Libraries Full-featured clients for connecting to any MCP server
Testing Framework In-memory testing without external processes
Production Ready Authentication, deployment tools, and monitoring

Python Implementation

FastMCP provides a Pythonic interface for building MCP servers with minimal boilerplate:

Basic Server Example

from fastmcp import FastMCP

# Create server instance
mcp = FastMCP("Demo Server")

@mcp.tool
def add(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b

@mcp.resource("config://settings")
def get_config() -> dict:
    """Get application configuration."""
    return {"version": "1.0", "debug": True}

@mcp.resource("user://{user_id}")
def get_user(user_id: str) -> dict:
    """Get user information by ID."""
    return {"id": user_id, "name": f"User {user_id}"}

# Run the server
if __name__ == "__main__":
    mcp.run()  # Default: stdio transport

Client Usage

from fastmcp import Client

async def test_server():
    # In-memory testing
    async with Client(mcp) as client:
        result = await client.call_tool("add", {"a": 5, "b": 3})
        print(f"Result: {result.text}")
        
    # Connect to remote server
    async with Client("http://localhost:8000/mcp") as client:
        tools = await client.list_tools()
        resources = await client.list_resources()

Advanced Features

from fastmcp import FastMCP, Context

mcp = FastMCP("Advanced Server")

@mcp.tool
async def process_with_progress(data: str, ctx: Context) -> str:
    """Process data with progress reporting."""
    await ctx.report_progress(0.5, "Processing...")
    # Simulate work
    await ctx.report_progress(1.0, "Complete!")
    return f"Processed: {data}"

# Multiple transport support
mcp.run(transport="http", host="0.0.0.0", port=8000)
mcp.run(transport="sse", host="127.0.0.1", port=8001)

TypeScript Implementation

The official MCP TypeScript SDK provides similar high-level abstractions:

Server Example

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({
  name: "demo-server",
  version: "1.0.0"
});

// Register a tool
server.registerTool(
  "add",
  {
    description: "Add two numbers",
    inputSchema: {
      a: z.number(),
      b: z.number()
    }
  },
  async ({ a, b }) => ({
    content: [{
      type: "text",
      text: String(a + b)
    }]
  })
);

// Register a resource
server.registerResource(
  "config",
  "config://settings",
  {
    description: "Application configuration"
  },
  async () => ({
    contents: [{
      uri: "config://settings",
      text: JSON.stringify({ version: "1.0", debug: true })
    }]
  })
);

// Connect and run
const transport = new StdioServerTransport();
await server.connect(transport);

Client Example

import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

const transport = new StdioClientTransport({
  command: "node",
  args: ["server.js"]
});

const client = new Client({
  name: "demo-client",
  version: "1.0.0"
});

await client.connect(transport);

// List and call tools
const tools = await client.listTools();
const result = await client.callTool({
  name: "add",
  arguments: { a: 5, b: 3 }
});

Transport Protocols

FastMCP supports multiple transport methods:

STDIO Transport

Best for command-line tools and local development:

# Python
mcp.run(transport="stdio")
// TypeScript
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const transport = new StdioServerTransport();

HTTP Transport

Ideal for web deployments and remote access:

# Python
mcp.run(transport="http", host="0.0.0.0", port=8000, path="/mcp")
// TypeScript
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";

SSE Transport

For Server-Sent Events compatibility:

# Python
mcp.run(transport="sse", host="127.0.0.1", port=8001)

Testing and Development

FastMCP provides powerful testing capabilities:

In-Memory Testing

import pytest
from fastmcp import FastMCP, Client

@pytest.fixture
def mcp_server():
    server = FastMCP("TestServer")
    
    @server.tool
    def greet(name: str) -> str:
        return f"Hello, {name}!"
        
    return server

async def test_tool_functionality(mcp_server):
    async with Client(mcp_server) as client:
        result = await client.call_tool("greet", {"name": "World"})
        assert "Hello, World!" in result.text

Integration Testing

from fastmcp.utilities.tests import run_server_in_process

async def test_http_server():
    async with run_server_in_process(mcp, transport="http") as url:
        async with Client(url) as client:
            tools = await client.list_tools()
            assert len(tools) > 0

Advanced Patterns

Server Composition

# Mount multiple servers
weather_server = FastMCP("Weather")
calendar_server = FastMCP("Calendar")

main_server = FastMCP("Main")
main_server.mount(weather_server, prefix="weather")
main_server.mount(calendar_server, prefix="calendar")

Proxy Servers

# Create proxy to remote server
proxy = FastMCP.as_proxy("http://remote-server.com/mcp")

# Add authentication layer
@proxy.middleware
async def add_auth(request, call_next):
    request.headers["Authorization"] = "Bearer token"
    return await call_next(request)

OpenAPI Integration

from fastapi import FastAPI

app = FastAPI()

# Convert FastAPI to MCP server
mcp_server = FastMCP.from_fastapi(app, name="API Server")

# Or generate from OpenAPI spec
mcp_server = FastMCP.from_openapi("https://api.example.com/openapi.json")

Production Deployment

FastMCP provides production-ready features:

Authentication

from fastmcp.auth import EnvBearerAuthProvider

mcp = FastMCP(
    "Secure Server",
    auth=EnvBearerAuthProvider()  # Uses BEARER_TOKEN env var
)

Monitoring and Logging

import logging
from fastmcp.utilities.logging import get_logger

logger = get_logger(__name__)

@mcp.tool
def monitored_operation(data: str) -> str:
    logger.info(f"Processing: {data}")
    return f"Processed: {data}"

CLI Tools

# Run server with CLI
fastmcp run server.py:mcp

# With custom transport
fastmcp run server.py:mcp --transport http --port 8000

# Development mode with auto-reload
fastmcp dev server.py:mcp

Comparison with Standard MCP

Aspect Standard MCP FastMCP
Setup Complexity Manual protocol handling Decorator-based
Boilerplate Extensive Minimal
Testing External processes In-memory
Type Safety Manual validation Automatic with Pydantic/Zod
Development Speed Slower Faster
Production Features Basic Comprehensive

Getting Started

Installation

# Python
pip install fastmcp

# TypeScript
npm install @modelcontextprotocol/sdk

Quick Start

from fastmcp import FastMCP

mcp = FastMCP("My Server")

@mcp.tool
def hello(name: str) -> str:
    return f"Hello, {name}!"

if __name__ == "__main__":
    mcp.run()

Installation in MCP Clients

Once you've built your FastMCP server, you can easily integrate it with various MCP clients. Here's how to install your server across different development environments:

Common Installation Pattern

Most MCP clients follow a similar configuration pattern. Add your server to the client's configuration file:

{
  "mcpServers": {
    "my-fastmcp-server": {
      "command": "python",
      "args": ["/path/to/your/server.py"],
      "env": {
        "API_KEY": "your-api-key-here"
      }
    }
  }
}

For packaged servers distributed via NPM:

{
  "mcpServers": {
    "my-fastmcp-server": {
      "command": "npx",
      "args": ["-y", "@mycompany/my-fastmcp-server"]
    }
  }
}

FastMCP transforms MCP development from a protocol-focused exercise into an intuitive, high-level programming experience, making it the preferred choice for developers building production MCP applications.

© 2025 👨‍💻 with ❤️ by Full Stack Craft
"Any sufficiently advanced technology is indistinguishable from magic."