Skip to content

MCPClient

datapizza.tools.mcp_client.MCPClient

Helper for interacting with Model Context Protocol servers.

Can be used in two modes:

  1. Stateless mode (default): Each operation creates a new session. Good for HTTP-based MCP servers that don't require persistence.
client = MCPClient(url="https://example.com/mcp")
tools = client.list_tools()
# Each tool call creates a new session
  1. Persistent mode: Use as an async context manager to keep the session alive across multiple operations. Required for stdio-based servers or servers that maintain state.
async with MCPClient(command="uvx", args=["my-mcp-server"]) as client:
    tools = await client.a_list_tools()
    # All tool calls share the same session
    agent = Agent(tools=tools)
    await agent.a_run("do something")

Parameters:

Name Type Description Default
url str | None

The URL of the MCP server.

None
command str | None

The command to run the MCP server.

None
headers dict[str, str] | None

The headers to pass to the MCP server.

None
args list[str] | None

The arguments to pass to the MCP server.

None
env dict[str, str] | None

The environment variables to pass to the MCP server.

None
timeout int

The timeout for the MCP server.

30
sampling_callback SamplingFnT | None

The sampling callback to pass to the MCP server.

None

is_persistent property

is_persistent

Return True if the client is in persistent session mode.

__aenter__ async

__aenter__()

Enter persistent session mode.

__aexit__ async

__aexit__(exc_type, exc_val, exc_tb)

Exit persistent session mode and cleanup resources.

a_list_prompts async

a_list_prompts()

List the prompts available on the MCP server.

Returns:

Name Type Description
A ListPromptsResult

class:types.ListPromptsResult object.

a_list_tools async

a_list_tools()

List the tools available on the MCP server.

Returns:

Type Description
list[Tool]

A list of :class:Tool objects.

call_tool async

call_tool(
    tool_name, arguments=None, progress_callback=None
)

Call a tool on the MCP server.

Parameters:

Name Type Description Default
tool_name str

The name of the tool to call.

required
arguments dict[str, Any] | None

The arguments to pass to the tool.

None
progress_callback ProgressFnT | None

The progress callback to pass to the tool.

None

Returns:

Type Description
CallToolResult

The result of the tool call.

get_prompt async

get_prompt(prompt_name, arguments=None)

Get a prompt from the MCP server.

list_prompts

list_prompts()

List the prompts available on the MCP server.

Returns:

Name Type Description
A ListPromptsResult

class:types.ListPromptsResult object.

list_resources async

list_resources()

List the resources available on the MCP server.

Returns:

Name Type Description
A ListResourcesResult

class:types.ListResourcesResult object.

list_tools

list_tools()

List the tools available on the MCP server.

Returns:

Type Description
list[Tool]

A list of :class:Tool objects.