mirror of
https://github.com/PrefectHQ/fastmcp.git
synced 2026-08-09 07:09:11 +02:00
* Update repository references from jlowin/fastmcp to prefecthq/fastmcp * Retrigger CI after repo transfer * chore: Update SDK documentation * Only run deep triage on bug issues for jlowin --------- Co-authored-by: marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com>
286 lines
11 KiB
Text
286 lines
11 KiB
Text
---
|
|
title: client
|
|
sidebarTitle: client
|
|
---
|
|
|
|
# `fastmcp.client.client`
|
|
|
|
## Classes
|
|
|
|
### `ClientSessionState` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L95" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
|
|
Holds all session-related state for a Client instance.
|
|
|
|
This allows clean separation of configuration (which is copied) from
|
|
session state (which should be fresh for each new client instance).
|
|
|
|
|
|
### `CallToolResult` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L112" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
|
|
Parsed result from a tool call.
|
|
|
|
|
|
### `Client` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L122" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
|
|
MCP client that delegates connection management to a Transport instance.
|
|
|
|
The Client class is responsible for MCP protocol logic, while the Transport
|
|
handles connection establishment and management. Client provides methods for
|
|
working with resources, prompts, tools and other MCP capabilities.
|
|
|
|
This client supports reentrant context managers (multiple concurrent
|
|
`async with client:` blocks) using reference counting and background session
|
|
management. This allows efficient session reuse in any scenario with
|
|
nested or concurrent client usage.
|
|
|
|
MCP SDK 1.10 introduced automatic list_tools() calls during call_tool()
|
|
execution. This created a race condition where events could be reset while
|
|
other tasks were waiting on them, causing deadlocks. The issue was exposed
|
|
in proxy scenarios but affects any reentrant usage.
|
|
|
|
The solution uses reference counting to track active context managers,
|
|
a background task to manage the session lifecycle, events to coordinate
|
|
between tasks, and ensures all session state changes happen within a lock.
|
|
Events are only created when needed, never reset outside locks.
|
|
|
|
This design prevents race conditions where tasks wait on events that get
|
|
replaced by other tasks, ensuring reliable coordination in concurrent scenarios.
|
|
|
|
**Args:**
|
|
- `transport`:
|
|
Connection source specification, which can be\:
|
|
|
|
- ClientTransport\: Direct transport instance
|
|
- FastMCP\: In-process FastMCP server
|
|
- AnyUrl or str\: URL to connect to
|
|
- Path\: File path for local socket
|
|
- MCPConfig\: MCP server configuration
|
|
- dict\: Transport configuration
|
|
- `roots`: Optional RootsList or RootsHandler for filesystem access
|
|
- `sampling_handler`: Optional handler for sampling requests
|
|
- `log_handler`: Optional handler for log messages
|
|
- `message_handler`: Optional handler for protocol messages
|
|
- `progress_handler`: Optional handler for progress notifications
|
|
- `timeout`: Optional timeout for requests (seconds or timedelta)
|
|
- `init_timeout`: Optional timeout for initial connection (seconds or timedelta).
|
|
Set to 0 to disable. If None, uses the value in the FastMCP global settings.
|
|
|
|
**Examples:**
|
|
|
|
```python
|
|
# Connect to FastMCP server
|
|
client = Client("http://localhost:8080")
|
|
|
|
async with client:
|
|
# List available resources
|
|
resources = await client.list_resources()
|
|
|
|
# Call a tool
|
|
result = await client.call_tool("my_tool", {"param": "value"})
|
|
```
|
|
|
|
|
|
**Methods:**
|
|
|
|
#### `session` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L343" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
session(self) -> ClientSession
|
|
```
|
|
|
|
Get the current active session. Raises RuntimeError if not connected.
|
|
|
|
|
|
#### `initialize_result` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L353" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
initialize_result(self) -> mcp.types.InitializeResult | None
|
|
```
|
|
|
|
Get the result of the initialization request.
|
|
|
|
|
|
#### `set_roots` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L357" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
set_roots(self, roots: RootsList | RootsHandler) -> None
|
|
```
|
|
|
|
Set the roots for the client. This does not automatically call `send_roots_list_changed`.
|
|
|
|
|
|
#### `set_sampling_callback` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L361" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
set_sampling_callback(self, sampling_callback: SamplingHandler, sampling_capabilities: mcp.types.SamplingCapability | None = None) -> None
|
|
```
|
|
|
|
Set the sampling callback for the client.
|
|
|
|
|
|
#### `set_elicitation_callback` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L377" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
set_elicitation_callback(self, elicitation_callback: ElicitationHandler) -> None
|
|
```
|
|
|
|
Set the elicitation callback for the client.
|
|
|
|
|
|
#### `is_connected` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L385" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
is_connected(self) -> bool
|
|
```
|
|
|
|
Check if the client is currently connected.
|
|
|
|
|
|
#### `new` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L389" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
new(self) -> Client[ClientTransportT]
|
|
```
|
|
|
|
Create a new client instance with the same configuration but fresh session state.
|
|
|
|
This creates a new client with the same transport, handlers, and configuration,
|
|
but with no active session. Useful for creating independent sessions that don't
|
|
share state with the original client.
|
|
|
|
**Returns:**
|
|
- A new Client instance with the same configuration but disconnected state.
|
|
|
|
|
|
#### `initialize` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L434" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
initialize(self, timeout: datetime.timedelta | float | int | None = None) -> mcp.types.InitializeResult
|
|
```
|
|
|
|
Send an initialize request to the server.
|
|
|
|
This method performs the MCP initialization handshake with the server,
|
|
exchanging capabilities and server information. It is idempotent - calling
|
|
it multiple times returns the cached result from the first call.
|
|
|
|
The initialization happens automatically when entering the client context
|
|
manager unless `auto_initialize=False` was set during client construction.
|
|
Manual calls to this method are only needed when auto-initialization is disabled.
|
|
|
|
**Args:**
|
|
- `timeout`: Optional timeout for the initialization request (seconds or timedelta).
|
|
If None, uses the client's init_timeout setting.
|
|
|
|
**Returns:**
|
|
- The server's initialization response containing server info,
|
|
capabilities, protocol version, and optional instructions.
|
|
|
|
**Raises:**
|
|
- `RuntimeError`: If the client is not connected or initialization times out.
|
|
|
|
|
|
#### `close` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L735" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
close(self)
|
|
```
|
|
|
|
#### `ping` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L741" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
ping(self) -> bool
|
|
```
|
|
|
|
Send a ping request.
|
|
|
|
|
|
#### `cancel` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L746" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
cancel(self, request_id: str | int, reason: str | None = None) -> None
|
|
```
|
|
|
|
Send a cancellation notification for an in-progress request.
|
|
|
|
|
|
#### `progress` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L763" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
progress(self, progress_token: str | int, progress: float, total: float | None = None, message: str | None = None) -> None
|
|
```
|
|
|
|
Send a progress notification.
|
|
|
|
|
|
#### `set_logging_level` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L775" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
set_logging_level(self, level: mcp.types.LoggingLevel) -> None
|
|
```
|
|
|
|
Send a logging/setLevel request.
|
|
|
|
|
|
#### `send_roots_list_changed` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L779" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
send_roots_list_changed(self) -> None
|
|
```
|
|
|
|
Send a roots/list_changed notification.
|
|
|
|
|
|
#### `complete_mcp` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L785" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
complete_mcp(self, ref: mcp.types.ResourceTemplateReference | mcp.types.PromptReference, argument: dict[str, str], context_arguments: dict[str, Any] | None = None) -> mcp.types.CompleteResult
|
|
```
|
|
|
|
Send a completion request and return the complete MCP protocol result.
|
|
|
|
**Args:**
|
|
- `ref`: The reference to complete.
|
|
- `argument`: Arguments to pass to the completion request.
|
|
- `context_arguments`: Optional context arguments to
|
|
include with the completion request. Defaults to None.
|
|
|
|
**Returns:**
|
|
- mcp.types.CompleteResult: The complete response object from the protocol,
|
|
containing the completion and any additional metadata.
|
|
|
|
**Raises:**
|
|
- `RuntimeError`: If called while the client is not connected.
|
|
- `McpError`: If the request results in a TimeoutError | JSONRPCError
|
|
|
|
|
|
#### `complete` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L816" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
complete(self, ref: mcp.types.ResourceTemplateReference | mcp.types.PromptReference, argument: dict[str, str], context_arguments: dict[str, Any] | None = None) -> mcp.types.Completion
|
|
```
|
|
|
|
Send a completion request to the server.
|
|
|
|
**Args:**
|
|
- `ref`: The reference to complete.
|
|
- `argument`: Arguments to pass to the completion request.
|
|
- `context_arguments`: Optional context arguments to
|
|
include with the completion request. Defaults to None.
|
|
|
|
**Returns:**
|
|
- mcp.types.Completion: The completion object.
|
|
|
|
**Raises:**
|
|
- `RuntimeError`: If called while the client is not connected.
|
|
- `McpError`: If the request results in a TimeoutError | JSONRPCError
|
|
|
|
|
|
#### `generate_name` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L843" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
generate_name(cls, name: str | None = None) -> str
|
|
```
|