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
client.md docs/
1# Client Library23Full-featured MCP client supporting multiple transports, authentication, and advanced features like LLM sampling. The FastMCP client allows you to connect to and interact with any MCP server programmatically.45## Capabilities67### Client Class89Main client implementation for connecting to MCP servers with support for multiple transports and authentication methods.1011```python { .api }12class Client:13def __init__(14self,15server_or_config: str | FastMCP | dict,16transport: ClientTransport | None = None,17auth: BearerAuth | OAuth | None = None,18sampling_handler: SamplingHandler | None = None,19elicitation_handler: ElicitationHandler | None = None,20timeout: float = 30.021):22"""23Create a client to connect to an MCP server.2425Parameters:26- server_or_config: Server script path, FastMCP instance, or MCP config27- transport: Specific transport to use (auto-detected if None)28- auth: Authentication for secured servers29- sampling_handler: Handler for server LLM sampling requests30- elicitation_handler: Handler for server elicitation requests31- timeout: Request timeout in seconds32"""33```3435### Tool Operations3637List and call tools available on the connected MCP server.3839```python { .api }40async def list_tools(self) -> list[dict]:41"""42List all available tools on the server.4344Returns:45List of tool metadata dictionaries with name, description, and schema46"""4748async def call_tool(49self,50name: str,51arguments: dict | None = None52) -> ToolResult:53"""54Call a tool on the server.5556Parameters:57- name: Tool name to call58- arguments: Tool arguments as dictionary5960Returns:61Tool execution result with text content and optional metadata62"""63```6465### Resource Operations6667List and read resources available on the connected MCP server.6869```python { .api }70async def list_resources(self) -> list[dict]:71"""72List all available resources on the server.7374Returns:75List of resource metadata dictionaries with uri, name, description, and mime_type76"""7778async def read_resource(self, uri: str) -> ResourceResult:79"""80Read a resource from the server.8182Parameters:83- uri: Resource URI to read8485Returns:86Resource content with text/binary data and metadata87"""8889async def list_resource_templates(self) -> list[dict]:90"""91List all available resource templates on the server.9293Returns:94List of resource template metadata with uri_template, name, and description95"""96```9798### Prompt Operations99100List and get prompts available on the connected MCP server.101102```python { .api }103async def list_prompts(self) -> list[dict]:104"""105List all available prompts on the server.106107Returns:108List of prompt metadata dictionaries with name, description, and schema109"""110111async def get_prompt(112self,113name: str,114arguments: dict | None = None115) -> PromptResult:116"""117Get a prompt from the server.118119Parameters:120- name: Prompt name to retrieve121- arguments: Prompt arguments as dictionary122123Returns:124Prompt result with formatted messages125"""126```127128### Connection Management129130Context manager support for automatic connection lifecycle management.131132```python { .api }133async def __aenter__(self) -> "Client":134"""Enter async context manager."""135136async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:137"""Exit async context manager."""138139async def close(self) -> None:140"""Close the client connection."""141```142143## Usage Examples144145### Basic Client Usage146147```python148from fastmcp import Client149import asyncio150151async def main():152# Connect to a server via stdio153async with Client("my_server.py") as client:154# List available capabilities155tools = await client.list_tools()156resources = await client.list_resources()157prompts = await client.list_prompts()158159print(f"Available tools: {[t['name'] for t in tools]}")160print(f"Available resources: {[r['uri'] for r in resources]}")161print(f"Available prompts: {[p['name'] for p in prompts]}")162163# Call a tool164result = await client.call_tool("add", {"a": 5, "b": 3})165print(f"Tool result: {result.text}")166167# Read a resource168resource = await client.read_resource("config://version")169print(f"Resource content: {resource.content}")170171# Get a prompt172prompt = await client.get_prompt("summarize", {"text": "Hello world"})173print(f"Prompt messages: {prompt.messages}")174175asyncio.run(main())176```177178### Client with Different Transports179180```python181from fastmcp import Client182183async def stdio_client():184"""Connect via stdio transport."""185async with Client("python server.py") as client:186result = await client.call_tool("hello", {"name": "World"})187return result.text188189async def sse_client():190"""Connect via SSE transport."""191async with Client("http://localhost:8000/sse") as client:192tools = await client.list_tools()193return tools194195async def http_client():196"""Connect via HTTP transport."""197async with Client("http://localhost:8000/mcp") as client:198resources = await client.list_resources()199return resources200201# Auto-detection also works202async def auto_detect():203"""Client auto-detects transport type."""204clients = [205Client("./server.py"), # stdio206Client("http://localhost:8000/sse"), # SSE207Client("http://localhost:8000/mcp"), # HTTP208]209210for client in clients:211async with client:212tools = await client.list_tools()213print(f"Connected with {len(tools)} tools")214```215216### Client with Authentication217218```python219from fastmcp import Client220from fastmcp.client.auth import BearerAuth, OAuth221222async def authenticated_client():223"""Connect to secured server with Bearer token."""224auth = BearerAuth("your-bearer-token")225226async with Client(227"https://secure-server.com/mcp",228auth=auth229) as client:230result = await client.call_tool("secure_operation", {})231return result.text232233async def oauth_client():234"""Connect with OAuth authentication."""235oauth = OAuth(236client_id="your-client-id",237client_secret="your-client-secret",238token_url="https://auth.example.com/token"239)240241async with Client(242"https://api.example.com/mcp",243auth=oauth244) as client:245result = await client.call_tool("api_operation", {})246return result.text247```248249### Client with LLM Sampling Handler250251```python252from fastmcp import Client253254async def sampling_handler(messages):255"""Handle server LLM sampling requests."""256# This would typically connect to your LLM257# For example, OpenAI GPT, Claude, etc.258response = "This is a sample response"259return {"text": response}260261async def client_with_sampling():262"""Client that can handle server sampling requests."""263async with Client(264"intelligent_server.py",265sampling_handler=sampling_handler266) as client:267# Server can now request LLM completions via ctx.sample()268result = await client.call_tool("analyze_data", {269"data": "Some complex data to analyze"270})271return result.text272```273274### Multi-Server Client Configuration275276```python277from fastmcp import Client278279async def multi_server_client():280"""Connect to multiple servers with unified client."""281config = {282"mcpServers": {283"weather": {284"url": "https://weather-api.example.com/mcp"285},286"assistant": {287"command": "python",288"args": ["./assistant_server.py"]289},290"database": {291"url": "http://localhost:8080/mcp",292"auth": {"type": "bearer", "token": "db-token"}293}294}295}296297async with Client(config) as client:298# Tools are prefixed with server names299forecast = await client.call_tool(300"weather_get_forecast",301{"city": "London"}302)303304answer = await client.call_tool(305"assistant_answer_question",306{"query": "What is MCP?"}307)308309data = await client.call_tool(310"database_query",311{"sql": "SELECT * FROM users LIMIT 10"}312)313314return {315"forecast": forecast.text,316"answer": answer.text,317"data": data.text318}319```320321### In-Memory Testing with FastMCP322323```python324from fastmcp import FastMCP, Client325326async def test_server_with_client():327"""Test a FastMCP server using in-memory client."""328# Create server329mcp = FastMCP("Test Server")330331@mcp.tool332def multiply(a: int, b: int) -> int:333"""Multiply two numbers."""334return a * b335336# Connect via in-memory transport (no subprocess)337async with Client(mcp) as client:338# Test the server directly339result = await client.call_tool("multiply", {"a": 6, "b": 7})340assert result.text == "42"341342tools = await client.list_tools()343assert len(tools) == 1344assert tools[0]["name"] == "multiply"345```346347## Result Types348349```python { .api }350class ToolResult:351"""Result from calling a tool."""352text: str353content: list[dict] | None354is_error: bool355356class ResourceResult:357"""Result from reading a resource."""358content: str | bytes359mime_type: str | None360uri: str361362class PromptResult:363"""Result from getting a prompt."""364messages: list[dict]365description: str | None366```