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
transports.md docs/
1# Transport Layer23Multiple transport protocols for flexible server deployment and client connections. FastMCP supports various transport mechanisms to accommodate different deployment scenarios and client environments.45## Capabilities67### Base Transport Classes89Abstract base classes for implementing transport protocols.1011```python { .api }12class ClientTransport:13"""Base class for client transport implementations."""1415async def connect(self) -> None:16"""Establish connection to the server."""1718async def disconnect(self) -> None:19"""Close connection to the server."""2021async def send_request(self, request: dict) -> dict:22"""Send request and return response."""23```2425### Standard I/O Transports2627Transport implementations for standard input/output communication with subprocesses.2829```python { .api }30class StdioTransport(ClientTransport):31"""Standard I/O transport for subprocess communication."""3233def __init__(34self,35command: str,36args: list[str] | None = None,37env: dict[str, str] | None = None,38cwd: str | None = None39):40"""41Initialize stdio transport.4243Parameters:44- command: Command to execute45- args: Command arguments46- env: Environment variables47- cwd: Working directory48"""4950class PythonStdioTransport(StdioTransport):51"""Stdio transport specifically for Python scripts."""5253def __init__(54self,55script_path: str,56python_executable: str = "python",57args: list[str] | None = None58):59"""60Initialize Python stdio transport.6162Parameters:63- script_path: Path to Python script64- python_executable: Python interpreter to use65- args: Additional script arguments66"""6768class NodeStdioTransport(StdioTransport):69"""Stdio transport for Node.js scripts."""7071def __init__(72self,73script_path: str,74node_executable: str = "node",75args: list[str] | None = None76):77"""78Initialize Node.js stdio transport.7980Parameters:81- script_path: Path to Node.js script82- node_executable: Node.js interpreter to use83- args: Additional script arguments84"""8586class UvStdioTransport(StdioTransport):87"""Stdio transport using uv Python package manager."""8889class UvxStdioTransport(StdioTransport):90"""Stdio transport using uvx for package execution."""9192class NpxStdioTransport(StdioTransport):93"""Stdio transport using npx for Node.js packages."""94```9596### Network Transports9798Transport implementations for network-based communication.99100```python { .api }101class SSETransport(ClientTransport):102"""Server-Sent Events transport for HTTP streaming."""103104def __init__(105self,106url: str,107headers: dict[str, str] | None = None,108timeout: float = 30.0109):110"""111Initialize SSE transport.112113Parameters:114- url: SSE endpoint URL115- headers: Optional HTTP headers116- timeout: Connection timeout117"""118119class StreamableHttpTransport(ClientTransport):120"""Streamable HTTP transport for request/response."""121122def __init__(123self,124url: str,125headers: dict[str, str] | None = None,126timeout: float = 30.0127):128"""129Initialize streamable HTTP transport.130131Parameters:132- url: HTTP endpoint URL133- headers: Optional HTTP headers134- timeout: Request timeout135"""136137class WSTransport(ClientTransport):138"""WebSocket transport for real-time communication."""139140def __init__(141self,142url: str,143headers: dict[str, str] | None = None,144ping_interval: float = 30.0145):146"""147Initialize WebSocket transport.148149Parameters:150- url: WebSocket URL151- headers: Optional connection headers152- ping_interval: Ping interval for keepalive153"""154```155156### FastMCP-Specific Transport157158In-memory transport for direct FastMCP server connection.159160```python { .api }161class FastMCPTransport(ClientTransport):162"""In-memory transport for direct FastMCP server connection."""163164def __init__(self, server: FastMCP):165"""166Initialize FastMCP transport.167168Parameters:169- server: FastMCP server instance to connect to170"""171```172173## Usage Examples174175### Basic Transport Usage176177```python178from fastmcp import Client179from fastmcp.client import (180StdioTransport,181SSETransport,182StreamableHttpTransport,183WSTransport184)185186async def stdio_example():187"""Connect via stdio transport."""188transport = StdioTransport("python", ["server.py"])189190async with Client(transport=transport) as client:191tools = await client.list_tools()192result = await client.call_tool("hello", {"name": "World"})193return result.text194195async def sse_example():196"""Connect via Server-Sent Events."""197transport = SSETransport(198url="http://localhost:8000/sse",199headers={"Authorization": "Bearer token"}200)201202async with Client(transport=transport) as client:203resources = await client.list_resources()204return resources205206async def http_example():207"""Connect via HTTP transport."""208transport = StreamableHttpTransport(209url="http://localhost:8000/mcp",210timeout=60.0211)212213async with Client(transport=transport) as client:214prompts = await client.list_prompts()215return prompts216217async def websocket_example():218"""Connect via WebSocket."""219transport = WSTransport(220url="ws://localhost:8000/ws",221ping_interval=20.0222)223224async with Client(transport=transport) as client:225result = await client.call_tool("process_data", {"data": "example"})226return result.text227```228229### Auto-Detection Examples230231```python232from fastmcp import Client233234async def auto_detection_examples():235"""Client automatically detects appropriate transport."""236237# Auto-detects stdio transport238async with Client("python server.py") as client:239result1 = await client.call_tool("test", {})240241# Auto-detects SSE transport242async with Client("http://localhost:8000/sse") as client:243result2 = await client.call_tool("test", {})244245# Auto-detects HTTP transport246async with Client("http://localhost:8000/mcp") as client:247result3 = await client.call_tool("test", {})248249# Auto-detects WebSocket transport250async with Client("ws://localhost:8000/ws") as client:251result4 = await client.call_tool("test", {})252253return [result1, result2, result3, result4]254```255256### Language-Specific Transports257258```python259from fastmcp import Client260from fastmcp.client import (261PythonStdioTransport,262NodeStdioTransport,263UvStdioTransport,264NpxStdioTransport265)266267async def python_transport():268"""Connect to Python MCP server."""269transport = PythonStdioTransport(270script_path="./servers/python_server.py",271python_executable="python3.11"272)273274async with Client(transport=transport) as client:275return await client.list_tools()276277async def node_transport():278"""Connect to Node.js MCP server."""279transport = NodeStdioTransport(280script_path="./servers/node_server.js",281node_executable="node"282)283284async with Client(transport=transport) as client:285return await client.list_tools()286287async def uv_transport():288"""Connect using uv package manager."""289transport = UvStdioTransport(290command="uv",291args=["run", "python", "server.py"]292)293294async with Client(transport=transport) as client:295return await client.list_tools()296297async def npx_transport():298"""Connect using npx package runner."""299transport = NpxStdioTransport(300command="npx",301args=["@modelcontextprotocol/server-example"]302)303304async with Client(transport=transport) as client:305return await client.list_tools()306```307308### Advanced Transport Configuration309310```python311from fastmcp import Client312from fastmcp.client import SSETransport, StreamableHttpTransport313from fastmcp.client.auth import BearerAuth314315async def authenticated_transport():316"""Transport with authentication."""317auth = BearerAuth("your-access-token")318319transport = SSETransport(320url="https://secure-api.example.com/sse",321headers={322"User-Agent": "MyApp/1.0",323"X-Client-Version": "2.0"324},325timeout=120.0326)327328async with Client(transport=transport, auth=auth) as client:329return await client.call_tool("secure_operation", {})330331async def custom_headers_transport():332"""Transport with custom headers."""333transport = StreamableHttpTransport(334url="http://api.example.com/mcp",335headers={336"Authorization": "Bearer custom-token",337"X-API-Version": "v2",338"Accept": "application/json",339"Content-Type": "application/json"340}341)342343async with Client(transport=transport) as client:344return await client.list_resources()345346async def resilient_transport():347"""Transport with error handling and retries."""348import asyncio349from fastmcp.exceptions import ClientError350351transport = SSETransport(352url="http://sometimes-unreliable.example.com/sse",353timeout=10.0354)355356max_retries = 3357for attempt in range(max_retries):358try:359async with Client(transport=transport) as client:360return await client.call_tool("operation", {})361except ClientError as e:362if attempt == max_retries - 1:363raise364await asyncio.sleep(2 ** attempt) # Exponential backoff365```366367### In-Memory Testing Transport368369```python370from fastmcp import FastMCP, Client371from fastmcp.client import FastMCPTransport372373async def in_memory_testing():374"""Test server using in-memory transport."""375# Create server376server = FastMCP("Test Server")377378@server.tool379def add(a: int, b: int) -> int:380"""Add two numbers."""381return a + b382383@server.resource("config://test")384def get_config():385"""Get test configuration."""386return {"test": True, "env": "development"}387388# Connect via in-memory transport (no subprocess)389transport = FastMCPTransport(server)390391async with Client(transport=transport) as client:392# Test tools393tools = await client.list_tools()394assert len(tools) == 1395assert tools[0]["name"] == "add"396397result = await client.call_tool("add", {"a": 5, "b": 3})398assert result.text == "8"399400# Test resources401resources = await client.list_resources()402assert len(resources) == 1403404config = await client.read_resource("config://test")405assert "test" in config.content406407return "All tests passed"408409# Usage in test suite410async def test_server_functionality():411"""Integration test using in-memory transport."""412result = await in_memory_testing()413print(result)414```415416### Server Transport Configuration417418```python419from fastmcp import FastMCP420421mcp = FastMCP("Multi-Transport Server")422423@mcp.tool424def hello(name: str) -> str:425"""Say hello."""426return f"Hello, {name}!"427428# Run with different transports429if __name__ == "__main__":430import sys431432if len(sys.argv) > 1:433transport = sys.argv[1]434else:435transport = "stdio"436437if transport == "stdio":438# Default stdio transport439mcp.run()440441elif transport == "http":442# HTTP transport443mcp.run(444transport="http",445host="0.0.0.0",446port=8080,447path="/mcp"448)449450elif transport == "sse":451# Server-Sent Events transport452mcp.run(453transport="sse",454host="0.0.0.0",455port=8080456)457458else:459print(f"Unknown transport: {transport}")460sys.exit(1)461```462463### Transport Error Handling464465```python466from fastmcp import Client467from fastmcp.client import SSETransport468from fastmcp.exceptions import ClientError, ConnectionError469import asyncio470import logging471472logging.basicConfig(level=logging.INFO)473logger = logging.getLogger(__name__)474475async def robust_client_connection():476"""Robust client with comprehensive error handling."""477transport = SSETransport(478url="http://api.example.com/sse",479timeout=30.0480)481482try:483async with Client(transport=transport) as client:484# Test connection485await client.list_tools()486logger.info("Successfully connected to server")487488# Perform operations489result = await client.call_tool("test_operation", {})490return result.text491492except ConnectionError as e:493logger.error(f"Failed to connect to server: {e}")494return "Connection failed"495496except ClientError as e:497logger.error(f"Client error: {e}")498return "Client error occurred"499500except asyncio.TimeoutError:501logger.error("Request timed out")502return "Request timeout"503504except Exception as e:505logger.error(f"Unexpected error: {e}")506return "Unexpected error occurred"507508async def connection_with_fallback():509"""Try multiple transports with fallback."""510transports = [511SSETransport("http://primary.example.com/sse"),512SSETransport("http://backup.example.com/sse"),513StreamableHttpTransport("http://fallback.example.com/mcp")514]515516for i, transport in enumerate(transports):517try:518logger.info(f"Trying transport {i+1}/{len(transports)}")519520async with Client(transport=transport) as client:521result = await client.call_tool("health_check", {})522logger.info(f"Successfully connected via transport {i+1}")523return result.text524525except Exception as e:526logger.warning(f"Transport {i+1} failed: {e}")527if i == len(transports) - 1:528logger.error("All transports failed")529raise530531return "No successful connection"532```533534## Transport Selection Guide535536### When to Use Each Transport537538**Stdio Transport:**539- Local development and testing540- Command-line tools and scripts541- Simple server deployment542- When subprocess management is acceptable543544**HTTP/SSE Transport:**545- Web deployments and cloud services546- When you need standard HTTP semantics547- Load balancing and reverse proxy scenarios548- Production deployments with monitoring549550**WebSocket Transport:**551- Real-time applications552- When you need bidirectional communication553- Long-lived connections554- Gaming or chat applications555556**FastMCP Transport:**557- Unit testing and integration testing558- Embedded scenarios where no network is needed559- High-performance local communication560- Development and debugging