Skip to main content

Overview

The Fast Agent MCP client APIs provide powerful tools for connecting to MCP (Model Context Protocol) servers, managing persistent connections, and handling server lifecycle. These APIs enable you to integrate external tools, resources, and prompts into your agent applications.

Client Session

MCPAgentClientSession

Extended MCP client session with enhanced features for agent frameworks.
from fast_agent.mcp import MCPAgentClientSession
from fast_agent.mcp.gen_client import connect

# Connect to an MCP server
session = await connect(
    server_name="filesystem",
    server_registry=registry,
    client_session_factory=MCPAgentClientSession
)
server_name
string
required
Name of the MCP server to connect to (must be configured in registry)
server_registry
ServerRegistryProtocol
required
Server registry containing server configurations
client_session_factory
Callable
default:"MCPAgentClientSession"
Factory function to create client session instances
session
ClientSession
Initialized MCP client session ready for communication

Session Methods

call_tool()

Call a tool provided by the MCP server.
result = await session.call_tool(
    name="read_file",
    arguments={"path": "/path/to/file.txt"},
    progress_callback=lambda progress: print(progress)
)
name
string
required
Name of the tool to call
arguments
dict[str, Any] | None
Arguments to pass to the tool
read_timeout_seconds
timedelta | None
Timeout for reading the tool response
progress_callback
ProgressFnT | None
Callback function for progress updates
meta
dict[str, Any] | None
Optional metadata to include in the request
result
CallToolResult
Tool execution result containing output content

read_resource()

Read a resource from the MCP server.
result = await session.read_resource(
    uri="file:///path/to/document.txt"
)
text = result.contents[0].text
uri
AnyUrl | str
required
URI of the resource to read
_meta
dict | None
Optional metadata for the request
result
ReadResourceResult
Resource contents (text or binary data)

get_prompt()

Retrieve a prompt from the MCP server.
result = await session.get_prompt(
    name="code_review",
    arguments={"language": "python"}
)
messages = result.messages
name
string
required
Name of the prompt to retrieve
arguments
dict | None
Arguments for prompt templating
_meta
dict | None
Optional metadata for the request
result
GetPromptResult
Prompt with messages and optional description

ping()

Check server liveness with a ping request.
await session.ping(read_timeout_seconds=timedelta(seconds=5))
read_timeout_seconds
timedelta | None
Timeout for the ping response
result
EmptyResult
Empty result indicating successful ping

Connection Management

connect()

Create a persistent connection to an MCP server.
from fast_agent.mcp.gen_client import connect

session = await connect(
    server_name="github",
    server_registry=registry
)
server_name
string
required
Name of the server to connect to
server_registry
ServerRegistryProtocol
required
Server registry instance
client_session_factory
Callable
default:"MCPAgentClientSession"
Factory for creating session instances
session
ClientSession
Persistent client session

disconnect()

Disconnect from an MCP server or all servers.
from fast_agent.mcp.gen_client import disconnect

# Disconnect from specific server
await disconnect(server_name="github", server_registry=registry)

# Disconnect from all servers
await disconnect(server_name=None, server_registry=registry)
server_name
string | None
required
Name of server to disconnect from, or None to disconnect all
server_registry
ServerRegistryProtocol
required
Server registry instance

gen_client()

Context manager for temporary server connections.
from fast_agent.mcp.gen_client import gen_client

async with gen_client("filesystem", registry) as session:
    result = await session.call_tool("read_file", {"path": "data.txt"})
    # Session automatically closed on exit
server_name
string
required
Name of the server to connect to
server_registry
ServerRegistryProtocol
required
Server registry instance
client_session_factory
Callable
default:"MCPAgentClientSession"
Factory for creating session instances
session
ClientSession
Temporary client session (auto-closed on exit)

Connection Manager

MCPConnectionManager

Manages the lifecycle of multiple MCP server connections.
from fast_agent.mcp.mcp_connection_manager import MCPConnectionManager

manager = MCPConnectionManager(server_registry=registry)

async with manager:
    # Get or create server connection
    conn = await manager.get_server(
        server_name="github",
        client_session_factory=MCPAgentClientSession,
        startup_timeout_seconds=30.0
    )
    session = conn.session

get_server()

Get a running server instance, launching it if needed.
server_name
string
required
Name of the server to get or launch
client_session_factory
Callable
required
Factory function for creating client sessions
startup_timeout_seconds
float | None
Maximum time to wait for server startup (excluding OAuth)
trigger_oauth
bool
default:"True"
Whether to trigger OAuth flow if configured
oauth_event_handler
OAuthEventHandler | None
Custom handler for OAuth events
allow_oauth_paste_fallback
bool
default:"True"
Allow manual token paste if OAuth flow fails
connection
ServerConnection
Server connection object with session and metadata

disconnect_server()

Disconnect a specific server.
await manager.disconnect_server("github")
server_name
string
required
Name of the server to disconnect

reconnect_server()

Force reconnection to a server (useful after errors).
conn = await manager.reconnect_server(
    server_name="github",
    client_session_factory=MCPAgentClientSession
)
server_name
string
required
Name of the server to reconnect
client_session_factory
Callable
required
Factory function for creating client sessions
startup_timeout_seconds
float | None
Maximum time to wait for reconnection
connection
ServerConnection
New server connection instance

disconnect_all()

Disconnect all running servers.
await manager.disconnect_all()

Server Connection

ServerConnection

Represents a long-lived MCP server connection.
conn = await manager.get_server("filesystem", MCPAgentClientSession)

# Access session
session = conn.session

# Check health
if conn.is_healthy():
    result = await session.call_tool(...)

# Access server metadata
print(conn.server_instructions)
print(conn.server_capabilities)
print(conn.session_id)
session
ClientSession | None
Active MCP client session
server_name
string
Name of the connected server
server_config
MCPServerSettings
Server configuration settings
server_capabilities
ServerCapabilities | None
Capabilities advertised by the server
server_instructions
string | None
Instructions provided by the server (if enabled)
server_implementation
Implementation | None
Server implementation information
session_id
string | None
Current session identifier

is_healthy()

Check if the connection is healthy and ready to use.
if conn.is_healthy():
    # Safe to use the session
    pass
healthy
bool
True if connection is active and error-free

Error Handling

ServerInitializationError

Raised when server initialization fails.
from fast_agent.core.exceptions import ServerInitializationError

try:
    conn = await manager.get_server("myserver", MCPAgentClientSession)
except ServerInitializationError as e:
    print(f"Failed to initialize: {e}")
    print(f"Details: {e.details}")

ServerSessionTerminatedError

Raised when a server session is terminated (e.g., 404 from server restart).
from fast_agent.core.exceptions import ServerSessionTerminatedError

try:
    result = await session.call_tool("my_tool", {})
except ServerSessionTerminatedError:
    # Reconnect to server
    conn = await manager.reconnect_server("myserver", MCPAgentClientSession)
    session = conn.session

Best Practices

Use persistent connections with connect() for long-running applications. For one-off operations, use the gen_client() context manager to ensure proper cleanup.
Always check is_healthy() before using a server connection, especially after catching exceptions. Use reconnect_server() to recover from connection errors.
The connection manager automatically handles OAuth flows, server lifecycle, and ping monitoring. Configure these settings in your server registry.

Example: Complete MCP Integration

from fast_agent import ServerRegistry
from fast_agent.mcp.gen_client import connect, disconnect
from fast_agent.mcp import MCPAgentClientSession

# Initialize registry
registry = ServerRegistry()
registry.add_server(
    name="github",
    url="https://github-mcp.example.com",
    transport="sse"
)

# Connect to server
session = await connect("github", registry)

try:
    # List available tools
    tools_result = await session.list_tools()
    
    # Call a tool
    result = await session.call_tool(
        name="create_issue",
        arguments={
            "repo": "owner/repo",
            "title": "Bug report",
            "body": "Description of the issue"
        }
    )
    
    # Read a resource
    resource = await session.read_resource(
        uri="github://owner/repo/README.md"
    )
    
finally:
    # Clean up
    await disconnect("github", registry)

Prompts

Load and manage MCP prompts

Resources

Work with MCP resources

Build docs developers (and LLMs) love