Skip to main content

Overview

MCPHandler is the recommended way to connect to a single MCP server. It provides more control and flexibility than the class-based approach.

Basic Usage

Command String

Server Parameters

Parameters

  • command (str): Command string to run MCP server
  • server_params: Pre-configured server parameters (StdioServerParameters, SSEClientParams, or StreamableHTTPClientParams)
  • timeout_seconds (int): Connection timeout in seconds (default: 5)
  • include_tools (List[str]): Optional list of tool names to include
  • exclude_tools (List[str]): Optional list of tool names to exclude
  • tool_name_prefix (str): Optional prefix to add to all tool names from this handler (useful for preventing tool name collisions)

Features

  • Automatic Tool Discovery: Discovers all available tools from the server
  • Resource Management: Automatically cleans up connections after task completion
  • Error Handling: Graceful error handling with proper cleanup
  • Tool Filtering: Include or exclude specific tools

MCP Types

MCPHandler supports every MCP transport type. Below are real-world examples for each.

Stdio: UVX Command

The simplest way to run a Python-based MCP server. Pass a command string and MCPHandler handles the rest.

Stdio: NPX Command

Run Node.js-based MCP servers with npx. This example uses the official filesystem server.

Stdio: StdioServerParameters

For full control over the subprocess, pass StdioServerParameters directly. Useful when you need custom environment variables.

SSE: URL Shorthand

Connect to a remote MCP server over Server-Sent Events. Pass the SSE endpoint URL and set transport="sse".

SSE: SSEClientParams

For authenticated SSE connections with custom headers and timeout control.
SSEClientParams fields:

Streamable HTTP: URL Shorthand

Connect to a remote MCP server using the Streamable HTTP transport. This is the newest MCP transport and is stateless by design.

Streamable HTTP: StreamableHTTPClientParams

For authenticated connections with custom headers, timeouts, and HTTP auth.
StreamableHTTPClientParams fields:

Example with Structured Output

Tool Name Prefix

When working with multiple MCP handlers that expose tools with the same names, use tool_name_prefix to prevent tool name collisions:
The tool_name_prefix is especially useful when:
  • Multiple MCP servers expose tools with identical names
  • You need to clearly distinguish which server’s tool to use
  • Working with multiple instances of the same server type (e.g., multiple databases)

When to Use

  • Single MCP server connection
  • Need more control over connection parameters
  • Want automatic resource cleanup
  • Need tool filtering capabilities
  • Need to prevent tool name collisions with tool_name_prefix