Something went wrong. Try again.
mirror of github.com/PrefectHQ/fastmcp
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204---title: runsidebarTitle: run---
# `fastmcp.server.sampling.run`
Sampling types and helper functions for FastMCP servers.
## Functions
### `determine_handler_mode` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/sampling/run.py#L132" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythondetermine_handler_mode(context: Context, needs_tools: bool) -> bool```
Determine whether to use fallback handler or client for sampling.
**Args:**- `context`: The MCP context.- `needs_tools`: Whether the sampling request requires tool support.
**Returns:**- True if fallback handler should be used, False to use client.
**Raises:**- `ValueError`: If client lacks required capability and no fallback configured.
### `call_sampling_handler` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/sampling/run.py#L191" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythoncall_sampling_handler(context: Context, messages: list[SamplingMessage]) -> CreateMessageResult | CreateMessageResultWithTools```
Make LLM call using the fallback handler.
Note: This function expects the caller (sample_step) to have validated thatsampling_handler is set via determine_handler_mode(). The checks below aresafeguards against internal misuse.
### `execute_tools` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/sampling/run.py#L244" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonexecute_tools(tool_calls: list[ToolUseContent], tool_map: dict[str, SamplingTool], mask_error_details: bool = False, tool_concurrency: int | None = None) -> list[ToolResultContent]```
Execute tool calls and return results.
**Args:**- `tool_calls`: List of tool use requests from the LLM.- `tool_map`: Mapping from tool name to SamplingTool.- `mask_error_details`: If True, mask detailed error messages from tool execution.When masked, only generic error messages are returned to the LLM.Tools can explicitly raise ToolError to bypass masking when they wantto provide specific error messages to the LLM.- `tool_concurrency`: Controls parallel execution of tools\:- None (default)\: Sequential execution (one at a time)- 0\: Unlimited parallel execution- N > 0\: Execute at most N tools concurrentlyIf any tool has sequential=True, all tools execute sequentiallyregardless of this setting.
**Returns:**- List of tool result content blocks in the same order as tool_calls.
### `prepare_messages` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/sampling/run.py#L354" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonprepare_messages(messages: str | Sequence[str | SamplingMessage]) -> list[SamplingMessage]```
Convert various message formats to a list of SamplingMessage objects.
### `prepare_tools` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/sampling/run.py#L373" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonprepare_tools(tools: Sequence[SamplingTool | FunctionTool | TransformedTool | Callable[..., Any]] | None) -> list[SamplingTool] | None```
Convert tools to SamplingTool objects.
Accepts SamplingTool instances, FunctionTool instances, TransformedTool instances,or plain callable functions. FunctionTool and TransformedTool are converted usingfrom_callable_tool(), while plain functions use from_function().
**Args:**- `tools`: Sequence of tools to prepare. Can be SamplingTool, FunctionTool,TransformedTool, or plain callable functions.
**Returns:**- List of SamplingTool instances, or None if tools is None.
### `extract_tool_calls` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/sampling/run.py#L409" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonextract_tool_calls(response: CreateMessageResult | CreateMessageResultWithTools) -> list[ToolUseContent]```
Extract tool calls from a response.
### `create_final_response_tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/sampling/run.py#L421" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythoncreate_final_response_tool(result_type: type) -> SamplingTool```
Create a synthetic 'final_response' tool for structured output.
This tool is used to capture structured responses from the LLM.The tool's schema is derived from the result_type.
### `sample_step_impl` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/sampling/run.py#L457" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonsample_step_impl(context: Context, messages: str | Sequence[str | SamplingMessage]) -> SampleStep```
Implementation of Context.sample_step().
Make a single LLM sampling call. This is a stateless function that makesexactly one LLM call and optionally executes any requested tools.
### `sample_impl` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/sampling/run.py#L574" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonsample_impl(context: Context, messages: str | Sequence[str | SamplingMessage]) -> SamplingResult[ResultT]```
Implementation of Context.sample().
Send a sampling request to the client and await the response. This methodruns to completion automatically, executing a tool loop until the LLMprovides a final text response.
## Classes
### `SamplingResult` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/sampling/run.py#L54" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Result of a sampling operation.
**Attributes:**- `text`: The text representation of the result (raw text or JSON for structured).- `result`: The typed result (str for text, parsed object for structured output).- `history`: All messages exchanged during sampling.
### `SampleStep` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/sampling/run.py#L69" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Result of a single sampling call.
Represents what the LLM returned in this step plus the message history.
**Methods:**
#### `is_tool_use` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/sampling/run.py#L79" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonis_tool_use(self) -> bool```
True if the LLM is requesting tool execution.
#### `text` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/sampling/run.py#L86" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythontext(self) -> str | None```
Extract text from the response, if available.
#### `tool_calls` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/sampling/run.py#L99" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythontool_calls(self) -> list[ToolUseContent]```
Get the list of tool calls from the response.