mirror of
https://github.com/PrefectHQ/fastmcp.git
synced 2026-08-21 04:54:17 +02:00
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: Jeremiah Lowin <jlowin@users.noreply.github.com> Co-authored-by: Marvin Context Protocol <41898282+Marvin Context Protocol@users.noreply.github.com> Co-authored-by: voidborne-d <voidborne-d@users.noreply.github.com> Co-authored-by: marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com> Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: d 🔹 <258577966+voidborne-d@users.noreply.github.com> Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Co-authored-by: nightcityblade <nightcityblade@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> Co-authored-by: Bill Easton <strawgate@users.noreply.github.com> Co-authored-by: Sumanshu Nankana <sumanshunankana@gmail.com> Co-authored-by: Eric Robinson <ericrobinson@indeed.com> Co-authored-by: Martim Santos <martimfasantos@gmail.com> Co-authored-by: d 🔹 <liusway405@gmail.com> Co-authored-by: Matthieu B <66959271+mtthidoteu@users.noreply.github.com> Co-authored-by: Sascha Buehrle <47737812+saschabuehrle@users.noreply.github.com> Co-authored-by: Hakancan <142545736+hkc5@users.noreply.github.com> Co-authored-by: nightcityblade <jackchen@haloailabs.com> Co-authored-by: Matt Hallowell <17804673+mhallo@users.noreply.github.com> Co-authored-by: nate nowack <thrast36@gmail.com> Co-authored-by: Bill Easton <williamseaston@gmail.com> Co-authored-by: Marcus Shu <46469249+shulkx@users.noreply.github.com> Co-authored-by: Rushabh Doshi <radoshi@gmail.com> Co-authored-by: AIKAWA Shigechika <shige@aikawa.jp> Co-authored-by: Jeremy Simon <simonjer805@gmail.com> Co-authored-by: Miguel Miranda Dias <7780875+pandego@users.noreply.github.com> Co-authored-by: Anthony James Padavano <padavano.anthony@gmail.com> Co-authored-by: Mostafa Kamal <hiremostafa@gmail.com> Fix auto-close MRE script posting comment without closing (#3386) Fix WorkOS token scope verification bypass 🤖 Generated with Codex (#3407) Fix initialize McpError fallthrough 🤖 Generated with Codex (#3413) Fix transform arg collisions with passthrough params (#3431) Fix get_* returning None when latest version is disabled (#3439) Fix get_* returning None when latest version is disabled (#3421) Fix server lifespan overlap teardown (#3415) Fix $ref output schema object detection regression (#3420) resolved annotations (#3429) Fix async partial callables rejected by iscoroutinefunction (#3438) Fix async partial callables rejected by iscoroutinefunction (#3423) fix: add version to components (#3458) fix: use intent-based flag for OIDC scope patch in load_access_token (#3465) Fixes #3461 fix: normalize Google scope shorthands and surface valid_scopes (#3477) fix: resolve ty 0.0.23 type-checking errors and bump pin (#3481) fix: shield lifespan teardown from cancellation (#3480) fix: forward custom_route endpoints from mounted servers (#3462) fix updates _get_additional_http_routes() to traverse providers, Fixes #3457 fix: remove hardcoded version from CLI help text (#3456) fix: monty 0.0.8 compatibility, drop external_functions from constructor (#3468) fix: task test teardown hanging 5s per test (#3499) Closes #3498 fix: validate workspace path is a directory before cursor install (#3440) Fixes #3426 fix: handle re.error from malformed URI templates in build_regex (#3501) fix: reject empty/OIDC-only required_scopes in AzureProvider (#3503) fix: restrict $ref resolution to local refs only (SSRF/LFI) (#3502) fix warnings and timeouts (#3504) close upgrade check issue when build passes (#3505) Closes #3484 fix: URL-encode path params to prevent SSRF/path traversal (GHSA-vv7q-7jx5-f767) (#3507) fix: prevent path traversal in skill download (#3493) fix: prefer IdP-granted scopes over client-requested scopes in OAuthProxy (#3492) fix: remove unrelated transform and http.py changes from PR scope fix: remove forced follow_redirects from httpx_client_factory calls (#3496) fix: stop passing follow_redirects to httpx_client_factory fix: restore follow_redirects=True for custom httpx client factories Closes #3509 fix: CSRF double-submit cookie check in consent flow (#3519) fix: validate server names in install commands (#3522) fix: use raw strings for regex in pytest.raises match (#3523) fix: reject refresh tokens used as Bearer access tokens (#3524) fix: route ResourcesAsTools/PromptsAsTools through server middleware (#3495) fix: resolve Pyright "Module is not callable" on @tool, @resource, @prompt decorators (#3540) fix: filter warnings by message in KEY_PREFIX test (#3549) fix: suppress output schema for ToolResult subclass annotations (#3548) fix: increase sleep duration in proxy cache tests (#3567) fix: store absolute token expiry to prevent stale expires_in on reload (#3572) fix: preserve tool properties named 'title' during schema compression (#3582) Fix loopback redirect URI port matching per RFC 8252 §7.3 (#3589) Fix app tool routing: visibility check and middleware propagation (#3591) Fix query parameter serialization to respect OpenAPI explode/style settings (#3595) Fix dev apps form: union types, textarea support, JSON parsing (#3597) fix(google): replace deprecated /oauth2/v1/tokeninfo with /oauth2/v3/userinfo (#3603) fix: resolve EntraOBOToken dependency injection through MultiAuth (#3609) fix(docs): correct misleading stateless_http header (#3622) fix: filesystem provider import machinery (#3626) Closes #3625 (issues 2, 3, 6) fix: recover StdioTransport after subprocess exits (#3630) fix(server): preserve mounted tool task metadata (#3632) fix: scope deprecation warning filter to FastMCPDeprecationWarning (#3649) fix imports, add PrefabAppConfig (#3650) fix: resolve CurrentFastMCP/ctx.fastmcp to child server in mounted background tasks (#3651) Fix blocking docs issues: chart imports, Select API, Rx consistency (#3652) closed by default (#3657) Fix prompt caching middleware missing wrap/unwrap round-trip (#3666) fix: serialize object query params per OpenAPI style/explode rules (#3662) Fixes #2857 fix: HTTP request headers not accessible in background task workers (#3631) fix: restore HTTP headers in worker execution path for background tasks (#3681) fix: strip discriminator after dereferencing schemas (#3682) fix: remove stale ty:ignore directives for ty 0.0.26 (#3684) Fix docs gaps in app provider pages (#3690) fix: dev apps log panel UX improvements (#3698) fix dev server empty string args (#3700)
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#L97" 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#L114" 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#L124" 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#L371" 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#L381" 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#L385" 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#L389" 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#L404" 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#L412" 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#L416" 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#L461" 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#L762" 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#L768" 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#L773" 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#L790" 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#L802" 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#L806" 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#L812" 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#L843" 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#L870" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
generate_name(cls, name: str | None = None) -> str
|
|
```
|