Skip to content

🚀 The fast, Pythonic way to build MCP servers and clients.

Remove server-initiated sampling and roots from the server API

Jeremiah Lowine056a3946e01
diff --git a/docs/servers/sampling.mdx b/docs/servers/sampling.mdx
deleted file mode 100644
index 4dd2886d9..000000000
--- a/docs/servers/sampling.mdx
+++ /dev/null
@@ -1,591 +0,0 @@
----
-title: Sampling
-sidebarTitle: Sampling
-description: Request LLM text generation from the client or a configured provider through the MCP context.
-icon: robot
----
-
-import { VersionBadge } from "/snippets/version-badge.mdx"
-
-<VersionBadge version="2.0.0" />
-
-<Warning>
-**Sampling is deprecated and will be removed in a future FastMCP release.**
-
-`ctx.sample()` and `ctx.sample_step()` rely on server-initiated `createMessage`
-requests, which MCP removed as of the 2026-07-28 protocol (SEP-2577). They work
-only on session-based (handshake-era) connections; on a 2026-07-28 connection
-they raise a clear error rather than reaching the client.
-
-**Migration:** call an LLM directly from your server using your own API key and
-provider SDK instead of borrowing the client's model. There is no drop-in
-replacement on modern connections — this architectural shift is the intended
-answer.
-</Warning>
-
-<Note>
-This page covers `ctx.sample()`, which requests generation over the handshake-era back-channel. The modern protocol's guard mechanism can structurally carry a sampling request in its `input_requests` map, but SEP-2577 deprecated server-initiated sampling as a pattern rather than only the `ctx.sample()` spelling of it, so that is not a supported migration path. Use the guard mechanism for [elicitation](/servers/elicitation#elicitation-on-the-modern-protocol) and roots, and call an LLM directly from your server for generation.
-</Note>
-
-LLM sampling allows your MCP tools to request text generation from an LLM during execution. This enables tools to leverage AI capabilities for analysis, generation, reasoning, and more—without the client needing to orchestrate multiple calls.
-
-By default, sampling requests are routed to the client's LLM. You can also configure a fallback handler to use a specific provider (like OpenAI) when the client doesn't support sampling, or to always use your own LLM regardless of client capabilities.
-
-## Overview
-
-The simplest use of sampling is passing a prompt string to `ctx.sample()`. The method sends the prompt to the LLM, waits for the complete response, and returns a `SamplingResult`. You can access the generated text through the `.text` attribute.
-
-```python
-from fastmcp import FastMCP, Context
-
-mcp = FastMCP()
-
-async def summarize(content: str, ctx: Context) -> str:
- """Generate a summary of the provided content."""
- result = await ctx.sample(f"Please summarize this:\n\n{content}")
- return result.text or ""
-```
-
-The `SamplingResult` also provides `.result` (identical to `.text` for plain text responses) and `.history` containing the full message exchange—useful if you need to continue the conversation or debug the interaction.
-
-### System Prompts
-
-System prompts let you establish the LLM's role and behavioral guidelines before it processes your request. This is useful for controlling tone, enforcing constraints, or providing context that shouldn't clutter the user-facing prompt.
-
-````python
-from fastmcp import FastMCP, Context
-
-mcp = FastMCP()
-
-async def generate_code(concept: str, ctx: Context) -> str:
- """Generate a Python code example for a concept."""
- result = await ctx.sample(
- messages=f"Write a Python example demonstrating '{concept}'.",
- system_prompt=(
- "You are an expert Python programmer. "
- "Provide concise, working code without explanations."
- ),
- temperature=0.7,
- max_tokens=300
- )
- return f"```python\n{result.text}\n```"
-````
-
-The `temperature` parameter controls randomness—higher values (up to 1.0) produce more varied outputs, while lower values make responses more deterministic. The `max_tokens` parameter limits response length.
-
-### Model Preferences
-
-Model preferences let you hint at which LLM the client should use for a request. You can pass a single model name or a list of preferences in priority order. These are hints rather than requirements—the actual model used depends on what the client has available.
-
-```python
-from fastmcp import FastMCP, Context
-
-mcp = FastMCP()
-
-async def technical_analysis(data: str, ctx: Context) -> str:
- """Analyze data using a reasoning-focused model."""
- result = await ctx.sample(
- messages=f"Analyze this data:\n\n{data}",
- model_preferences=["claude-opus-4-5", "gpt-5-2"],
- temperature=0.2,
- )
- return result.text or ""
-```
-
-Use model preferences when different tasks benefit from different model characteristics. Creative writing might prefer faster models with higher temperature, while complex analysis might benefit from larger reasoning-focused models.
-
-### Multi-Turn Conversations
-
-For requests that need conversational context, construct a list of `SamplingMessage` objects representing the conversation history. Each message has a `role` ("user" or "assistant") and `content` (a `TextContent` object).
-
-```python
-from mcp_types import SamplingMessage, TextContent
-from fastmcp import FastMCP, Context
-
-mcp = FastMCP()
-
-async def contextual_analysis(query: str, data: str, ctx: Context) -> str:
- """Analyze data with conversational context."""
- messages = [
- SamplingMessage(
- role="user",
- content=TextContent(type="text", text=f"Here's my data: {data}"),
- ),
- SamplingMessage(
- role="assistant",
- content=TextContent(type="text", text="I see the data. What would you like to know?"),
- ),
- SamplingMessage(
- role="user",
- content=TextContent(type="text", text=query),
- ),
- ]
- result = await ctx.sample(messages=messages)
- return result.text or ""
-```
-
-The LLM receives the full conversation thread and responds with awareness of the preceding context.
-
-### Fallback Handlers
-
-Client support for sampling is optional—some clients may not implement it. To ensure your tools work regardless of client capabilities, configure a `sampling_handler` that sends requests directly to an LLM provider.
-
-FastMCP provides built-in handlers for [OpenAI and Anthropic APIs](/clients/sampling#built-in-handlers). These handlers support the full sampling API including tools, automatically converting your Python functions to each provider's format.
-
-<Note>
-Install handlers with `pip install 'fastmcp[openai]'` or `pip install 'fastmcp[anthropic]'`.
-</Note>
-
-```python
-from fastmcp import FastMCP
-from fastmcp.client.sampling.handlers.openai import OpenAISamplingHandler
-
-server = FastMCP(
- name="My Server",
- sampling_handler=OpenAISamplingHandler(default_model="gpt-4o-mini"),
- sampling_handler_behavior="fallback",
-)
-```
-
-The `sampling_handler_behavior` parameter controls when the handler is used:
-
-- **`"fallback"`** (default): Use the handler only when the client doesn't support sampling. This lets capable clients use their own LLM while ensuring your tools still work with clients that lack sampling support.
-- **`"always"`**: Always use the handler, bypassing the client entirely. Use this when you need guaranteed control over which LLM processes requests—for cost control, compliance requirements, or when specific model characteristics are essential.
-
-## Structured Output
-
-<VersionBadge version="2.14.1" />
-
-When you need validated, typed data instead of free-form text, use the `result_type` parameter. FastMCP ensures the LLM returns data matching your type, handling validation and retries automatically.
-
-The `result_type` parameter accepts Pydantic models, dataclasses, and basic types like `int`, `list[str]`, or `dict[str, int]`. When you specify a result type, FastMCP automatically creates a `final_response` tool that the LLM calls to provide its response. If validation fails, the error is sent back to the LLM for retry.
-
-```python
-from pydantic import BaseModel
-from fastmcp import FastMCP, Context
-
-mcp = FastMCP()
-
-class SentimentResult(BaseModel):
- sentiment: str
- confidence: float
- reasoning: str
-
-async def analyze_sentiment(text: str, ctx: Context) -> SentimentResult:
- """Analyze text sentiment with structured output."""
- result = await ctx.sample(
- messages=f"Analyze the sentiment of: {text}",
- result_type=SentimentResult,
- )
- return result.result # A validated SentimentResult object
-```
-
-When you call this tool, the LLM returns a structured response that FastMCP validates against your Pydantic model. You access the validated object through `result.result`, while `result.text` contains the JSON representation.
-
-### Structured Output with Tools
-
-Combine structured output with tools for agentic workflows that return validated data. The LLM uses your tools to gather information, then returns a response matching your type.
-
-```python
-from pydantic import BaseModel
-from fastmcp import FastMCP, Context
-
-mcp = FastMCP()
-
-def search(query: str) -> str:
- """Search the web for information."""
- return f"Results for: {query}"
-
-def fetch_url(url: str) -> str:
- """Fetch content from a URL."""
- return f"Content from: {url}"
-
-class ResearchResult(BaseModel):
- summary: str
- sources: list[str]
- confidence: float
-
-async def research(topic: str, ctx: Context) -> ResearchResult:
- """Research a topic and return structured findings."""
- result = await ctx.sample(
- messages=f"Research: {topic}",
- tools=[search, fetch_url],
- result_type=ResearchResult,
- )
- return result.result
-```
-
-<Note>
-Structured output with automatic validation only applies to `sample()`. With `sample_step()`, you must manage structured output yourself.
-</Note>
-
-## Tool Use
-
-<VersionBadge version="2.14.1" />
-
-Sampling with tools enables agentic workflows where the LLM can call functions to gather information before responding. This implements [SEP-1577](https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1577), allowing the LLM to autonomously orchestrate multi-step operations.
-
-Pass Python functions to the `tools` parameter, and FastMCP handles the execution loop automatically—calling tools, returning results to the LLM, and continuing until the LLM provides a final response.
-
-### Defining Tools
-
-Define regular Python functions with type hints and docstrings. FastMCP extracts the function's name, docstring, and parameter types to create tool schemas that the LLM can understand.
-
-```python
-from fastmcp import FastMCP, Context
-
-def search(query: str) -> str:
- """Search the web for information."""
- return f"Results for: {query}"
-
-def get_time() -> str:
- """Get the current time."""
- from datetime import datetime
- return datetime.now().strftime("%H:%M:%S")
-
-mcp = FastMCP()
-
-async def research(question: str, ctx: Context) -> str:
- """Answer questions using available tools."""
- result = await ctx.sample(
- messages=question,
- tools=[search, get_time],
- )
- return result.text or ""
-```
-
-The LLM sees each function's signature and docstring, using this information to decide when and how to call them. Tool errors are caught and sent back to the LLM, allowing it to recover gracefully. An internal safety limit prevents infinite loops.
-
-### Custom Tool Definitions
-
-For custom names or descriptions, use `SamplingTool.from_function()`:
-
-```python
-from fastmcp.server.sampling import SamplingTool
-
-tool = SamplingTool.from_function(
- my_func,
- name="custom_name",
- description="Custom description"
-)
-
-result = await ctx.sample(messages="...", tools=[tool])
-```
-
-### Error Handling
-
-By default, when a sampling tool raises an exception, the error message (including details) is sent back to the LLM so it can attempt recovery. To prevent sensitive information from leaking to the LLM, use the `mask_error_details` parameter:
-
-```python
-result = await ctx.sample(
- messages=question,
- tools=[search],
- mask_error_details=True, # Generic error messages only
-)
-```
-
-When `mask_error_details=True`, tool errors become generic messages like `"Error executing tool 'search'"` instead of exposing stack traces or internal details.
-
-To intentionally provide specific error messages to the LLM regardless of masking, raise `ToolError`:
-
-```python
-from fastmcp.exceptions import ToolError
-
-def search(query: str) -> str:
- """Search for information."""
- if not query.strip():
- raise ToolError("Search query cannot be empty")
- return f"Results for: {query}"
-```
-
-`ToolError` messages always pass through to the LLM, making it the escape hatch for errors you want the LLM to see and handle.
-
-### Concurrent Tool Execution
-
-By default, tools execute sequentially — one at a time, in order. When your tools are independent (no shared state between them), you can execute them in parallel with `tool_concurrency`:
-
-```python
-result = await ctx.sample(
- messages="Research these three topics",
- tools=[search, fetch_url],
- tool_concurrency=0, # Unlimited parallel execution
-)
-```
-
-The `tool_concurrency` parameter controls how many tools run at once:
-
-- **`None`** (default): Sequential execution
-- **`0`**: Unlimited parallel execution
-- **`N > 0`**: Execute at most N tools concurrently
-
-For tools that must not run concurrently (file writes, shared state mutations, etc.), mark them as `sequential` when creating the `SamplingTool`:
-
-```python
-from fastmcp.server.sampling import SamplingTool
-
-db_writer = SamplingTool.from_function(
- write_to_db,
- sequential=True, # Forces all tools in the batch to run sequentially
-)
-
-result = await ctx.sample(
- messages="Process this data",
- tools=[search, db_writer],
- tool_concurrency=0, # Would be parallel, but db_writer forces sequential
-)
-```
-
-<Note>
-When any tool in a batch has `sequential=True`, the entire batch executes sequentially regardless of `tool_concurrency`. This is a conservative guarantee — if one tool needs ordering, all tools in that batch respect it.
-</Note>
-
-### Client Requirements
-
-<Note>
-Sampling with tools requires the client to advertise the `sampling.tools` capability. FastMCP clients do this automatically. For external clients that don't support tool-enabled sampling, configure a fallback handler with `sampling_handler_behavior="always"`.
-</Note>
-
-## Advanced Control
-
-<VersionBadge version="2.14.1" />
-
-While `sample()` handles the tool execution loop automatically, some scenarios require fine-grained control over each step. The `sample_step()` method makes a single LLM call and returns a `SampleStep` containing the response and updated history.
-
-Unlike `sample()`, `sample_step()` is stateless—it doesn't remember previous calls. You control the conversation by passing the full message history each time. The returned `step.history` includes all messages up through the current response, making it easy to continue the loop.
-
-Use `sample_step()` when you need to:
-
-- Inspect tool calls before they execute
-- Implement custom termination conditions
-- Add logging, metrics, or checkpointing between steps
-- Build custom agentic loops with domain-specific logic
-
-### Basic Loop
-
-By default, `sample_step()` executes any tool calls and includes the results in the history. Call it in a loop, passing the updated history each time, until a stop condition is met.
-
-```python
-from mcp_types import SamplingMessage
-from fastmcp import FastMCP, Context
-
-mcp = FastMCP()
-
-def search(query: str) -> str:
- return f"Results for: {query}"
-
-def get_time() -> str:
- return "12:00 PM"
-
-async def controlled_agent(question: str, ctx: Context) -> str:
- """Agent with manual loop control."""
- messages: list[str | SamplingMessage] = [question]
-
- while True:
- step = await ctx.sample_step(
- messages=messages,
- tools=[search, get_time],
- )
-
- if step.is_tool_use:
- # Tools already executed (execute_tools=True by default)
- for call in step.tool_calls:
- print(f"Called tool: {call.name}")
-
- if not step.is_tool_use:
- return step.text or ""
-
- messages = step.history
-```
-
-### SampleStep Properties
-
-Each `SampleStep` provides information about what the LLM returned:
-
-| Property | Description |
-|----------|-------------|
-| `step.is_tool_use` | True if the LLM requested tool calls |
-| `step.tool_calls` | List of tool calls requested (if any) |
-| `step.text` | The text content (if any) |
-| `step.history` | All messages exchanged so far |
-
-The contents of `step.history` depend on `execute_tools`:
-- **`execute_tools=True`** (default): Includes tool results, ready for the next iteration
-- **`execute_tools=False`**: Includes the assistant's tool request, but you add results yourself
-
-### Manual Tool Execution
-
-Set `execute_tools=False` to handle tool execution yourself. When disabled, `step.history` contains the user message and the assistant's response with tool calls—but no tool results. You execute the tools and append the results as a user message.
-
-```python
-from mcp_types import SamplingMessage, ToolResultContent, TextContent
-from fastmcp import FastMCP, Context
-
-mcp = FastMCP()
-
-async def research(question: str, ctx: Context) -> str:
- """Research with manual tool handling."""
-
- def search(query: str) -> str:
- return f"Results for: {query}"
-
- def get_time() -> str:
- return "12:00 PM"
-
- tools = {"search": search, "get_time": get_time}
- messages: list[SamplingMessage] = [question]
-
- while True:
- step = await ctx.sample_step(
- messages=messages,
- tools=list(tools.values()),
- execute_tools=False,
- )
-
- if not step.is_tool_use:
- return step.text or ""
-
- # Execute tools and collect results
- tool_results = []
- for call in step.tool_calls:
- fn = tools[call.name]
- result = fn(**call.input)
- tool_results.append(
- ToolResultContent(
- type="tool_result",
- tool_use_id=call.id,
- content=[TextContent(type="text", text=result)],
- )
- )
-
- messages = list(step.history)
- messages.append(SamplingMessage(role="user", content=tool_results))
-```
-
-To report an error to the LLM, set `is_error=True` on the tool result:
-
-```python
-tool_result = ToolResultContent(
- type="tool_result",
- tool_use_id=call.id,
- content=[TextContent(type="text", text="Permission denied")],
- is_error=True,
-)
-```
-
-## Method Reference
-
-<Card icon="code" title="ctx.sample()">
-<ResponseField name="ctx.sample" type="async method">
- Request text generation from the LLM, running to completion automatically.
-
- <Expandable title="Parameters">
- <ResponseField name="messages" type="str | list[str | SamplingMessage]">
- The prompt to send. Can be a simple string or a list of messages for multi-turn conversations.
- </ResponseField>
-
- <ResponseField name="system_prompt" type="str | None" default="None">
- Instructions that establish the LLM's role and behavior.
- </ResponseField>
-
- <ResponseField name="temperature" type="float | None" default="None">
- Controls randomness (0.0 = deterministic, 1.0 = creative).
- </ResponseField>
-
- <ResponseField name="max_tokens" type="int | None" default="512">
- Maximum tokens to generate.
- </ResponseField>
-
- <ResponseField name="model_preferences" type="str | list[str] | None" default="None">
- Hints for which model the client should use.
- </ResponseField>
-
- <ResponseField name="tools" type="list[Callable] | None" default="None">
- Functions the LLM can call during sampling.
- </ResponseField>
-
- <ResponseField name="result_type" type="type[T] | None" default="None">
- A type for validated structured output. Supports Pydantic models, dataclasses, and basic types like `int`, `list[str]`, or `dict[str, int]`.
- </ResponseField>
-
- <ResponseField name="mask_error_details" type="bool | None" default="None">
- If True, mask detailed error messages from tool execution. When None (default), uses the global `settings.mask_error_details` value. Tools can raise `ToolError` to bypass masking and provide specific error messages to the LLM.
- </ResponseField>
-
- <ResponseField name="tool_concurrency" type="int | None" default="None">
- Controls parallel execution of tools. `None` (default) for sequential, `0` for unlimited parallel, or a positive integer for bounded concurrency. If any tool has `sequential=True`, all tools execute sequentially regardless.
- </ResponseField>
-
- </Expandable>
-
- <Expandable title="Response">
- <ResponseField name="SamplingResult[T]" type="dataclass">
- - `.text`: The raw text response (or JSON for structured output)
- - `.result`: The typed result—same as `.text` for plain text, or a validated Pydantic object for structured output
- - `.history`: All messages exchanged during sampling
- </ResponseField>
- </Expandable>
-</ResponseField>
-</Card>
-
-<Card icon="code" title="ctx.sample_step()">
-<ResponseField name="ctx.sample_step" type="async method">
- Make a single LLM sampling call. Use this for fine-grained control over the sampling loop.
-
- <Expandable title="Parameters">
- <ResponseField name="messages" type="str | list[str | SamplingMessage]">
- The prompt or conversation history.
- </ResponseField>
-
- <ResponseField name="system_prompt" type="str | None" default="None">
- Instructions that establish the LLM's role and behavior.
- </ResponseField>
-
- <ResponseField name="temperature" type="float | None" default="None">
- Controls randomness (0.0 = deterministic, 1.0 = creative).
- </ResponseField>
-
- <ResponseField name="max_tokens" type="int | None" default="512">
- Maximum tokens to generate.
- </ResponseField>
-
- <ResponseField name="tools" type="list[Callable] | None" default="None">
- Functions the LLM can call during sampling.
- </ResponseField>
-
- <ResponseField name="tool_choice" type="str | None" default="None">
- Controls tool usage: `"auto"`, `"required"`, or `"none"`.
- </ResponseField>
-
- <ResponseField name="execute_tools" type="bool" default="True">
- If True, execute tool calls and append results to history. If False, return immediately with tool calls available for manual execution.
- </ResponseField>
-
- <ResponseField name="mask_error_details" type="bool | None" default="None">
- If True, mask detailed error messages from tool execution.
- </ResponseField>
-
- <ResponseField name="tool_concurrency" type="int | None" default="None">
- Controls parallel execution of tools. `None` (default) for sequential, `0` for unlimited parallel, or a positive integer for bounded concurrency.
- </ResponseField>
- </Expandable>
-
- <Expandable title="Response">
- <ResponseField name="SampleStep" type="dataclass">
- - `.response`: The raw LLM response
- - `.history`: Messages including input, assistant response, and tool results
- - `.is_tool_use`: True if the LLM requested tool execution
- - `.tool_calls`: List of tool calls (if any)
- - `.text`: The text content (if any)
- </ResponseField>
- </Expandable>
-</ResponseField>
-</Card>
diff --git a/examples/sampling/README.md b/examples/sampling/README.md
deleted file mode 100644
index d23a595ec..000000000
--- a/examples/sampling/README.md
+++ /dev/null
@@ -1,62 +0,0 @@
-# Sampling Examples
-
-These examples demonstrate FastMCP's sampling API, which allows server tools to request LLM completions from the client.
-
-## Prerequisites
-
-```bash
-pip install 'fastmcp[anthropic]'
-export ANTHROPIC_API_KEY=your-key
-```
-
-Or run directly with `uv`:
-
-```bash
-uv run examples/sampling/text.py
-```
-
-## Examples
-
-### Simple Text Sampling (`text.py`)
-
-Basic sampling flow where a server tool requests an LLM completion:
-
-```bash
-uv run examples/sampling/text.py
-```
-
-### Structured Output (`structured_output.py`)
-
-Uses `result_type` to get validated Pydantic models from the LLM:
-
-```bash
-uv run examples/sampling/structured_output.py
-```
-
-### Tool Use (`tool_use.py`)
-
-Gives the LLM tools to use during sampling (calculator, time, dice):
-
-```bash
-uv run examples/sampling/tool_use.py
-```
-
-### Server Fallback (`server_fallback.py`)
-
-Configures a fallback sampling handler on the server, enabling sampling even when clients don't support it:
-
-```bash
-uv run examples/sampling/server_fallback.py
-```
-
-## Using OpenAI Instead
-
-To use OpenAI instead of Anthropic, change the handler:
-
-```python
-from fastmcp.client.sampling.handlers.openai import OpenAISamplingHandler
-
-handler = OpenAISamplingHandler(default_model="gpt-4o-mini")
-```
-
-And install with `pip install 'fastmcp[openai]'`.
diff --git a/examples/sampling/server_fallback.py b/examples/sampling/server_fallback.py
deleted file mode 100644
index 1c3fb10af..000000000
--- a/examples/sampling/server_fallback.py
+++ /dev/null
@@ -1,88 +0,0 @@
-# /// script
-# dependencies = ["anthropic", "fastmcp", "rich"]
-# ///
-"""
-Server-Side Fallback Handler
-
-Demonstrates configuring a sampling handler on the server. This ensures
-sampling works even when the client doesn't provide a handler.
-
-The server runs as an HTTP server that can be connected to by any MCP client.
-
-Run:
- uv run examples/sampling/server_fallback.py
-
-Then connect with any MCP client (e.g., Claude Desktop) or test with:
- curl http://localhost:8000/mcp/
-"""
-
-import asyncio
-
-from rich.console import Console
-from rich.panel import Panel
-
-from fastmcp import FastMCP
-from fastmcp.client.sampling.handlers.anthropic import AnthropicSamplingHandler
-from fastmcp.server.context import Context
-
-console = Console()
-
-
-# Create server with a fallback sampling handler
-# This handler is used when the client doesn't support sampling
-mcp = FastMCP(
- "Server with Fallback Handler",
- sampling_handler=AnthropicSamplingHandler(default_model="claude-sonnet-4-5"),
- sampling_handler_behavior="fallback", # Use only if client lacks sampling
-)
-
-
-async def summarize(text: str, ctx: Context) -> str:
- """Summarize the given text."""
- console.print(f"[bold cyan]SERVER[/] Summarizing text ({len(text)} chars)...")
-
- result = await ctx.sample(
- messages=f"Summarize this text in 1-2 sentences:\n\n{text}",
- system_prompt="You are a concise summarizer.",
- max_tokens=150,
- )
-
- console.print("[bold cyan]SERVER[/] Summary complete")
- return result.text or ""
-
-
-async def translate(text: str, target_language: str, ctx: Context) -> str:
- """Translate text to the target language."""
- console.print(f"[bold cyan]SERVER[/] Translating to {target_language}...")
-
- result = await ctx.sample(
- messages=f"Translate to {target_language}:\n\n{text}",
- system_prompt=f"You are a translator. Output only the {target_language} translation.",
- max_tokens=500,
- )
-
- console.print("[bold cyan]SERVER[/] Translation complete")
- return result.text or ""
-
-
-async def main():
- console.print(
- Panel.fit(
- "[bold]Server-Side Fallback Handler Demo[/]\n\n"
- "This server has a built-in Anthropic handler that activates\n"
- "when clients don't provide their own sampling support.",
- subtitle="server_fallback.py",
- )
- )
- console.print()
- console.print("[bold yellow]Starting HTTP server on http://localhost:8000[/]")
- console.print("Connect with an MCP client or press Ctrl+C to stop")
- console.print()
-
- await mcp.run_http_async(host="localhost", port=8000)
-
-
-if __name__ == "__main__":
- asyncio.run(main())
diff --git a/examples/sampling/structured_output.py b/examples/sampling/structured_output.py
deleted file mode 100644
index fa7afe7ad..000000000
--- a/examples/sampling/structured_output.py
+++ /dev/null
@@ -1,110 +0,0 @@
-# /// script
-# dependencies = ["anthropic", "fastmcp", "rich"]
-# ///
-"""
-Structured Output Sampling
-
-Demonstrates using `result_type` to get validated Pydantic models from an LLM.
-The server exposes a sentiment analysis tool that returns structured data.
-
-Run:
- uv run examples/sampling/structured_output.py
-"""
-
-import asyncio
-
-from pydantic import BaseModel
-from rich.console import Console
-from rich.panel import Panel
-from rich.table import Table
-
-from fastmcp import Client, Context, FastMCP
-from fastmcp.client.sampling import SamplingMessage, SamplingParams
-from fastmcp.client.sampling.handlers.anthropic import AnthropicSamplingHandler
-
-console = Console()
-
-
-class LoggingAnthropicHandler(AnthropicSamplingHandler):
- async def __call__(
- self, messages: list[SamplingMessage], params: SamplingParams, context
- ): # type: ignore[override]
- console.print(" [bold blue]SAMPLING[/] Calling Claude API...")
- result = await super().__call__(messages, params, context)
- console.print(" [bold blue]SAMPLING[/] Response received")
- return result
-
-
-# Define a structured output model
-class SentimentAnalysis(BaseModel):
- sentiment: str # "positive", "negative", or "neutral"
- confidence: float # 0.0 to 1.0
- keywords: list[str] # Keywords that influenced the analysis
- explanation: str # Brief explanation of the analysis
-
-
-# Create the MCP server
-mcp = FastMCP("Sentiment Analyzer")
-
-
-async def analyze_sentiment(text: str, ctx: Context) -> dict:
- """Analyze the sentiment of the given text."""
- console.print(" [bold cyan]SERVER[/] Analyzing sentiment...")
-
- result = await ctx.sample(
- messages=f"Analyze the sentiment of this text:\n\n{text}",
- system_prompt="You are a sentiment analysis expert. Analyze text carefully.",
- result_type=SentimentAnalysis,
- )
-
- console.print(" [bold cyan]SERVER[/] Analysis complete")
- return result.result.model_dump() # type: ignore[attr-defined]
-
-
-async def main():
- console.print(
- Panel.fit("[bold]MCP Sampling Flow Demo[/]", subtitle="structured_output.py")
- )
- console.print()
-
- handler = LoggingAnthropicHandler(default_model="claude-sonnet-4-5")
-
- async with Client(mcp, sampling_handler=handler) as client:
- texts = [
- "I absolutely love this product! It exceeded all my expectations.",
- "The service was okay, nothing special but got the job done.",
- "This is the worst experience I've ever had. Never again.",
- ]
-
- for text in texts:
- console.print(f"[bold green]CLIENT[/] Analyzing: [italic]{text[:50]}...[/]")
- console.print()
-
- result = await client.call_tool("analyze_sentiment", {"text": text})
- data = result.data
-
- # Display results in a table
- table = Table(show_header=False, box=None, padding=(0, 2))
- table.add_column(style="bold")
- table.add_column()
-
- sentiment_color = {
- "positive": "green",
- "negative": "red",
- "neutral": "yellow",
- }.get(
- data["sentiment"],
- "white", # type: ignore[union-attr]
- )
- table.add_row("Sentiment", f"[{sentiment_color}]{data['sentiment']}[/]") # type: ignore[index]
- table.add_row("Confidence", f"{data['confidence']:.0%}") # type: ignore[index]
- table.add_row("Keywords", ", ".join(data["keywords"])) # type: ignore[index]
- table.add_row("Explanation", data["explanation"]) # type: ignore[index]
-
- console.print(Panel(table, border_style=sentiment_color))
- console.print()
-
-
-if __name__ == "__main__":
- asyncio.run(main())
diff --git a/examples/sampling/text.py b/examples/sampling/text.py
deleted file mode 100644
index 6d354e7c2..000000000
--- a/examples/sampling/text.py
+++ /dev/null
@@ -1,78 +0,0 @@
-# /// script
-# dependencies = ["anthropic", "fastmcp", "rich"]
-# ///
-"""
-Simple Text Sampling
-
-Demonstrates the basic MCP sampling flow where a server tool requests
-an LLM completion from the client.
-
-Run:
- uv run examples/sampling/text.py
-"""
-
-import asyncio
-
-from rich.console import Console
-from rich.panel import Panel
-
-from fastmcp import Client, Context, FastMCP
-from fastmcp.client.sampling import SamplingMessage, SamplingParams
-from fastmcp.client.sampling.handlers.anthropic import AnthropicSamplingHandler
-
-console = Console()
-
-
-# Create a wrapper handler that logs when the LLM is called
-class LoggingAnthropicHandler(AnthropicSamplingHandler):
- async def __call__(
- self, messages: list[SamplingMessage], params: SamplingParams, context
- ): # type: ignore[override]
- console.print(" [bold blue]SAMPLING[/] Calling Claude API...")
- result = await super().__call__(messages, params, context)
- console.print(" [bold blue]SAMPLING[/] Response received")
- return result
-
-
-# Create the MCP server
-mcp = FastMCP("Haiku Generator")
-
-
-async def write_haiku(topic: str, ctx: Context) -> str:
- """Write a haiku about any topic."""
- console.print(
- f" [bold cyan]SERVER[/] Tool 'write_haiku' called with topic: {topic}"
- )
-
- result = await ctx.sample(
- messages=f"Write a haiku about: {topic}",
- system_prompt="You are a poet. Write only the haiku, nothing else.",
- max_tokens=100,
- )
-
- console.print(" [bold cyan]SERVER[/] Returning haiku to client")
- return result.text or ""
-
-
-async def main():
- console.print(Panel.fit("[bold]MCP Sampling Flow Demo[/]", subtitle="text.py"))
- console.print()
-
- # Create the sampling handler
- handler = LoggingAnthropicHandler(default_model="claude-sonnet-4-5")
-
- # Connect client to server with the sampling handler
- async with Client(mcp, sampling_handler=handler) as client:
- console.print("[bold green]CLIENT[/] Calling tool 'write_haiku'...")
- console.print()
-
- result = await client.call_tool("write_haiku", {"topic": "Python programming"})
-
- console.print()
- console.print("[bold green]CLIENT[/] Received result:")
- console.print(Panel(result.data, title="Haiku", border_style="green")) # type: ignore[arg-type]
-
-
-if __name__ == "__main__":
- asyncio.run(main())
diff --git a/examples/sampling/tool_use.py b/examples/sampling/tool_use.py
deleted file mode 100644
index e7869a16c..000000000
--- a/examples/sampling/tool_use.py
+++ /dev/null
@@ -1,125 +0,0 @@
-# /// script
-# dependencies = ["anthropic", "fastmcp", "rich"]
-# ///
-"""
-Sampling with Tools
-
-Demonstrates giving an LLM tools to use during sampling. The LLM can call
-helper functions to gather information before responding.
-
-Run:
- uv run examples/sampling/tool_use.py
-"""
-
-import asyncio
-import random
-from datetime import datetime
-
-from pydantic import BaseModel, Field
-from rich.console import Console
-from rich.panel import Panel
-
-from fastmcp import Client, Context, FastMCP
-from fastmcp.client.sampling import SamplingMessage, SamplingParams
-from fastmcp.client.sampling.handlers.anthropic import AnthropicSamplingHandler
-
-console = Console()
-
-
-class LoggingAnthropicHandler(AnthropicSamplingHandler):
- async def __call__(
- self, messages: list[SamplingMessage], params: SamplingParams, context
- ): # type: ignore[override]
- console.print(" [bold blue]SAMPLING[/] Calling Claude API...")
- result = await super().__call__(messages, params, context)
- console.print(" [bold blue]SAMPLING[/] Response received")
- return result
-
-
-# Define tools available to the LLM during sampling
-def add(a: float, b: float) -> str:
- """Add two numbers together."""
- result = a + b
- console.print(f" [bold magenta]TOOL[/] add({a}, {b}) = {result}")
- return str(result)
-
-
-def multiply(a: float, b: float) -> str:
- """Multiply two numbers together."""
- result = a * b
- console.print(f" [bold magenta]TOOL[/] multiply({a}, {b}) = {result}")
- return str(result)
-
-
-def get_current_time() -> str:
- """Get the current date and time."""
- console.print(" [bold magenta]TOOL[/] get_current_time()")
- return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
-
-
-def roll_dice(sides: int = 6) -> str:
- """Roll a die with the specified number of sides."""
- result = random.randint(1, sides)
- console.print(f" [bold magenta]TOOL[/] roll_dice({sides}) = {result}")
- return str(result)
-
-
-# Structured output for the response
-class AssistantResponse(BaseModel):
- answer: str = Field(description="The answer to the user's question")
- tools_used: list[str] = Field(description="List of tools that were used")
- reasoning: str = Field(
- description="Brief explanation of how the answer was determined"
- )
-
-
-# Create the MCP server
-mcp = FastMCP("Smart Assistant")
-
-
-async def ask_assistant(question: str, ctx: Context) -> dict:
- """Ask the assistant a question. It can use tools to help answer."""
- console.print(" [bold cyan]SERVER[/] Processing question...")
-
- result = await ctx.sample(
- messages=question,
- system_prompt="You are a helpful assistant with access to tools. Use them when needed to answer questions accurately.",
- tools=[add, multiply, get_current_time, roll_dice],
- result_type=AssistantResponse,
- )
-
- console.print(" [bold cyan]SERVER[/] Response ready")
- return result.result.model_dump() # type: ignore[attr-defined]
-
-
-async def main():
- console.print(Panel.fit("[bold]MCP Sampling Flow Demo[/]", subtitle="tool_use.py"))
- console.print()
-
- handler = LoggingAnthropicHandler(default_model="claude-sonnet-4-5")
-
- async with Client(mcp, sampling_handler=handler) as client:
- questions = [
- "What is 15 times 7, plus 23?",
- "Roll a 20-sided dice for me",
- "What time is it right now?",
- ]
-
- for question in questions:
- console.print(f"[bold green]CLIENT[/] Question: {question}")
- console.print()
-
- result = await client.call_tool("ask_assistant", {"question": question})
- data = result.data
-
- console.print(f"[bold green]CLIENT[/] Answer: {data['answer']}") # type: ignore[index]
- console.print(
- f" Tools used: {', '.join(data['tools_used']) or 'none'}"
- ) # type: ignore[index]
- console.print(f" Reasoning: {data['reasoning']}") # type: ignore[index]
- console.print()
-
-
-if __name__ == "__main__":
- asyncio.run(main())
diff --git a/fastmcp_slim/fastmcp/server/context.py b/fastmcp_slim/fastmcp/server/context.py
index c0977e7aa..df43d32f4 100644
--- a/fastmcp_slim/fastmcp/server/context.py
+++ b/fastmcp_slim/fastmcp/server/context.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import logging
import warnings
import weakref
-from collections.abc import Callable, Generator, Mapping, Sequence
+from collections.abc import Callable, Generator, Mapping
from contextlib import contextmanager
from contextvars import ContextVar, Token
from dataclasses import dataclass
@@ -16,9 +16,6 @@ from mcp import LoggingLevel, ServerSession
from mcp.server.context import ServerRequestContext
from mcp_types import (
GetPromptResult,
- ModelPreferences,
- Root,
- SamplingMessage,
)
from mcp_types import Prompt as SDKPrompt
from mcp_types import Resource as SDKResource
@@ -42,11 +39,6 @@ from fastmcp.server.elicitation import (
parse_elicit_response_type,
)
from fastmcp.server.low_level import client_supports_extension
-from fastmcp.server.sampling import SampleStep, SamplingResult, SamplingTool
-from fastmcp.server.sampling.run import (
- sample_impl,
- sample_step_impl,
-)
from fastmcp.server.server import FastMCP, StateValue
from fastmcp.server.transforms.visibility import (
Visibility,
@@ -79,30 +71,6 @@ _clamp_logger(logger=to_client_logger, max_level="DEBUG")
T = TypeVar("T", default=Any)
-ResultT = TypeVar("ResultT", default=str)
-
-# Import ToolChoiceOption from sampling module (after other imports)
-from fastmcp.server.sampling.run import ToolChoiceOption # noqa: E402
-
-# Warn-once guard for the sampling deprecation. Server-initiated createMessage
-# was removed from MCP as of 2026-07-28 (SEP-2577); the warning fires a single
-# time per process to flag that ctx.sample/ctx.sample_step are on their way out.
-# A mutable set (mutated in place, never rebound) rather than a `global` boolean
-# so the warn-once state is unambiguously read and written from the module.
-_sample_deprecation_warned: set[bool] = set()
-
-_SAMPLING_DEPRECATION_MESSAGE = (
- "ctx.sample() and ctx.sample_step() are deprecated and will be removed in a "
- "future FastMCP release. They rely on server-initiated createMessage "
- "requests, which were removed from MCP as of 2026-07-28 (SEP-2577), so they "
- "work only on session-based (handshake-era) connections. Call an LLM "
- "directly from your server instead."
-)
-
-_SAMPLING_MODERN_ERROR = (
- "server-initiated sampling is not available on MCP 2026-07-28 connections; "
- "SEP-2577 removed it — call an LLM from your server instead."
-)
_ELICIT_MODERN_ERROR = (
"elicitation via server-initiated requests is unavailable on 2026-07-28 "
@@ -110,22 +78,6 @@ _ELICIT_MODERN_ERROR = (
)
-def _warn_sampling_deprecated() -> None:
- """Emit the sampling deprecation warning once per process.
-
- Gated on ``settings.deprecation_warnings`` like every other FastMCP
- deprecation; fires a single time (module-level flag) rather than per call.
- """
- if _sample_deprecation_warned or not fastmcp.settings.deprecation_warnings:
- return
- _sample_deprecation_warned.add(True)
- warnings.warn(
- _SAMPLING_DEPRECATION_MESSAGE,
- FastMCPDeprecationWarning,
- stacklevel=3,
- )
-
-
_current_context: ContextVar[Context | None] = ContextVar("context", default=None)
@@ -278,9 +230,8 @@ class Context:
def is_background_task(self) -> bool:
"""True when this context is running in a background task (Docket worker).
- When True, certain operations like elicit() and sample() will use
- task-aware implementations that can pause the task and wait for
- client input.
+ When True, certain operations like elicit() will use task-aware
+ implementations that can pause the task and wait for client input.
Example:
```python
@@ -936,13 +887,6 @@ class Context:
extra=extra,
)
- async def list_roots(self) -> list[Root]:
- """List the roots available to the server, as indicated by the client."""
- # Deprecated upstream in SDK v2 but deliberately kept per compat directive;
- # removed with the multi-round-trip follow-up.
- result = await self.session.list_roots() # ty: ignore[deprecated]
- return result.roots
-
async def send_notification(
self, notification: mcp_types.ServerNotification
) -> None:
@@ -1008,227 +952,6 @@ class Context:
return False
return rc.protocol_version in MODERN_PROTOCOL_VERSIONS
- def _server_can_sample(self) -> bool:
- """True when a server-configured sampling handler can serve the request
- without the client back-channel.
-
- FastMCP supports a server-side sampling handler (``FastMCP(sampling_handler=...)``).
- With ``sampling_handler_behavior="always"`` the handler always answers;
- with ``"fallback"`` it answers whenever the client cannot. On modern
- connections the client back-channel is gone, so either configuration lets
- the server answer entirely server-side as long as a handler is set. (For
- ``"always"`` without a handler the sampling implementation raises its own
- clear "no handler configured" error, which is not an era concern.)
- """
- fastmcp = self.fastmcp
- if fastmcp.sampling_handler_behavior == "always":
- return True
- return fastmcp.sampling_handler is not None
-
- async def sample_step(
- self,
- messages: str | Sequence[str | SamplingMessage],
- *,
- system_prompt: str | None = None,
- temperature: float | None = None,
- max_tokens: int | None = None,
- model_preferences: ModelPreferences | str | list[str] | None = None,
- tools: Sequence[SamplingTool | Callable[..., Any]] | None = None,
- tool_choice: ToolChoiceOption | str | None = None,
- execute_tools: bool = True,
- mask_error_details: bool | None = None,
- tool_concurrency: int | None = None,
- ) -> SampleStep:
- """
- Make a single LLM sampling call.
-
- This is a stateless function that makes exactly one LLM call and optionally
- executes any requested tools. Use this for fine-grained control over the
- sampling loop.
-
- Args:
- messages: The message(s) to send. Can be a string, list of strings,
- or list of SamplingMessage objects.
- system_prompt: Optional system prompt for the LLM.
- temperature: Optional sampling temperature.
- max_tokens: Maximum tokens to generate. Defaults to 512.
- model_preferences: Optional model preferences.
- tools: Optional list of tools the LLM can use.
- tool_choice: Tool choice mode ("auto", "required", or "none").
- execute_tools: If True (default), execute tool calls and append results
- to history. If False, return immediately with tool_calls available
- in the step for manual execution.
- mask_error_details: If True, mask detailed error messages from tool
- execution. When None (default), uses the global settings value.
- Tools can raise ToolError to bypass masking.
- 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 concurrently
- If any tool has sequential=True, all tools execute sequentially
- regardless of this setting.
-
- Returns:
- SampleStep containing:
- - .response: The raw LLM response
- - .history: Messages including input, assistant response, and tool results
- - .is_tool_use: True if the LLM requested tool execution
- - .tool_calls: List of tool calls (if any)
- - .text: The text content (if any)
-
- Example:
- messages = "Research X"
-
- while True:
- step = await ctx.sample_step(messages, tools=[search])
-
- if not step.is_tool_use:
- print(step.text)
- break
-
- # Continue with tool results
- messages = step.history
- """
- _warn_sampling_deprecated()
- # On modern (2026-07-28) connections the client back-channel is gone
- # (SEP-2577). A server-configured sampling handler can still answer
- # entirely server-side; only raise the era error when nothing can serve
- # the request. When modern, force the handler path (never attempt the
- # dead client) by passing client_available=False.
- client_available = not self._is_modern_protocol()
- if not client_available and not self._server_can_sample():
- raise ToolError(_SAMPLING_MODERN_ERROR)
- return await sample_step_impl(
- self,
- messages=messages,
- system_prompt=system_prompt,
- temperature=temperature,
- max_tokens=max_tokens,
- model_preferences=model_preferences,
- tools=tools,
- tool_choice=tool_choice,
- auto_execute_tools=execute_tools,
- mask_error_details=mask_error_details,
- tool_concurrency=tool_concurrency,
- client_available=client_available,
- )
-
- @overload
- async def sample(
- self,
- messages: str | Sequence[str | SamplingMessage],
- *,
- system_prompt: str | None = None,
- temperature: float | None = None,
- max_tokens: int | None = None,
- model_preferences: ModelPreferences | str | list[str] | None = None,
- tools: Sequence[SamplingTool | Callable[..., Any]] | None = None,
- result_type: type[ResultT],
- mask_error_details: bool | None = None,
- tool_concurrency: int | None = None,
- ) -> SamplingResult[ResultT]:
- """Overload: With result_type, returns SamplingResult[ResultT]."""
-
- @overload
- async def sample(
- self,
- messages: str | Sequence[str | SamplingMessage],
- *,
- system_prompt: str | None = None,
- temperature: float | None = None,
- max_tokens: int | None = None,
- model_preferences: ModelPreferences | str | list[str] | None = None,
- tools: Sequence[SamplingTool | Callable[..., Any]] | None = None,
- result_type: None = None,
- mask_error_details: bool | None = None,
- tool_concurrency: int | None = None,
- ) -> SamplingResult[str]:
- """Overload: Without result_type, returns SamplingResult[str]."""
-
- async def sample(
- self,
- messages: str | Sequence[str | SamplingMessage],
- *,
- system_prompt: str | None = None,
- temperature: float | None = None,
- max_tokens: int | None = None,
- model_preferences: ModelPreferences | str | list[str] | None = None,
- tools: Sequence[SamplingTool | Callable[..., Any]] | None = None,
- result_type: type[ResultT] | None = None,
- mask_error_details: bool | None = None,
- tool_concurrency: int | None = None,
- ) -> SamplingResult[ResultT] | SamplingResult[str]:
- """
- Send a sampling request to the client and await the response.
-
- This method runs to completion automatically. When tools are provided,
- it executes a tool loop: if the LLM returns a tool use request, the tools
- are executed and the results are sent back to the LLM. This continues
- until the LLM provides a final text response.
-
- When result_type is specified, a synthetic `final_response` tool is
- created. The LLM calls this tool to provide the structured response,
- which is validated against the result_type and returned as `.result`.
-
- For fine-grained control over the sampling loop, use sample_step() instead.
-
- Args:
- messages: The message(s) to send. Can be a string, list of strings,
- or list of SamplingMessage objects.
- system_prompt: Optional system prompt for the LLM.
- temperature: Optional sampling temperature.
- max_tokens: Maximum tokens to generate. Defaults to 512.
- model_preferences: Optional model preferences.
- tools: Optional list of tools the LLM can use. Accepts plain
- functions or SamplingTools.
- result_type: Optional type for structured output. When specified,
- a synthetic `final_response` tool is created and the LLM's
- response is validated against this type.
- mask_error_details: If True, mask detailed error messages from tool
- execution. When None (default), uses the global settings value.
- Tools can raise ToolError to bypass masking.
- 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 concurrently
- If any tool has sequential=True, all tools execute sequentially
- regardless of this setting.
-
- Returns:
- SamplingResult[T] containing:
- - .text: The text representation (raw text or JSON for structured)
- - .result: The typed result (str for text, parsed object for structured)
- - .history: All messages exchanged during sampling
-
- Deprecated:
- Server-initiated sampling relies on the createMessage back-channel,
- which MCP removed as of 2026-07-28 (SEP-2577). This method works only
- on session-based (handshake-era) connections and will be removed in a
- future FastMCP release. Call an LLM directly from your server instead.
- """
- _warn_sampling_deprecated()
- # On modern (2026-07-28) connections the client back-channel is gone
- # (SEP-2577). A server-configured sampling handler can still answer
- # entirely server-side; only raise the era error when nothing can serve
- # the request. When modern, force the handler path (never attempt the
- # dead client) by passing client_available=False.
- client_available = not self._is_modern_protocol()
- if not client_available and not self._server_can_sample():
- raise ToolError(_SAMPLING_MODERN_ERROR)
- return await sample_impl( # ty: ignore[invalid-return-type]
- self,
- messages=messages,
- system_prompt=system_prompt,
- temperature=temperature,
- max_tokens=max_tokens,
- model_preferences=model_preferences,
- tools=tools,
- result_type=result_type,
- mask_error_details=mask_error_details,
- tool_concurrency=tool_concurrency,
- client_available=client_available,
- )
-
@overload
async def elicit(
self,
diff --git a/fastmcp_slim/fastmcp/server/providers/proxy.py b/fastmcp_slim/fastmcp/server/providers/proxy.py
index 78f1b1f17..60c71e961 100644
--- a/fastmcp_slim/fastmcp/server/providers/proxy.py
+++ b/fastmcp_slim/fastmcp/server/providers/proxy.py
@@ -1207,9 +1207,19 @@ class FastMCPProxy(FastMCP):
async def default_proxy_roots_handler(
context: ServerRequestContext[Any, Any],
) -> RootsList:
- """Forward list roots request from remote server to proxy's connected clients."""
+ """Forward list roots request from remote server to proxy's connected clients.
+
+ A handshake-era backend can still issue `roots/list`, and the proxy is that
+ backend's client, so it relays the request onto its own front session. This
+ reaches the wire through the SDK session rather than a `Context` method:
+ `ctx.list_roots()` is not part of FastMCP's server-authoring API, because
+ SEP-2577 removed server-initiated requests from the modern protocol. The
+ relay exists only for handshake-era interop on both legs.
+ """
ctx = get_context()
- return await ctx.list_roots()
+ # Deprecated upstream in SDK v2; the handshake-era relay is the one caller.
+ result = await ctx.session.list_roots() # ty: ignore[deprecated]
+ return result.roots
async def default_proxy_sampling_handler(
@@ -1217,16 +1227,27 @@ async def default_proxy_sampling_handler(
params: mcp_types.CreateMessageRequestParams,
context: ServerRequestContext[Any, Any],
) -> mcp_types.CreateMessageResult:
- """Forward sampling request from remote server to proxy's connected clients."""
+ """Forward sampling request from remote server to proxy's connected clients.
+
+ Relays through the SDK session for the same reason as
+ `default_proxy_roots_handler`: server-initiated sampling is not part of
+ FastMCP's server-authoring API, and this path only ever runs when both legs
+ of the proxy speak the handshake era.
+ """
ctx = get_context()
- result = await ctx.sample(
- list(messages),
+ # Deprecated upstream in SDK v2; the handshake-era relay is the one caller.
+ result = await ctx.session.create_message( # ty: ignore[deprecated]
+ messages=list(messages),
system_prompt=params.system_prompt,
temperature=params.temperature,
max_tokens=params.max_tokens,
model_preferences=params.model_preferences,
+ related_request_id=ctx.origin_request_id,
+ )
+ text = (
+ result.content.text if isinstance(result.content, mcp_types.TextContent) else ""
)
- content = mcp_types.TextContent(type="text", text=result.text or "")
+ content = mcp_types.TextContent(type="text", text=text)
return mcp_types.CreateMessageResult(
role="assistant",
model="fastmcp-client",
diff --git a/fastmcp_slim/fastmcp/server/sampling/__init__.py b/fastmcp_slim/fastmcp/server/sampling/__init__.py
deleted file mode 100644
index 392326d35..000000000
--- a/fastmcp_slim/fastmcp/server/sampling/__init__.py
+++ /dev/null
@@ -1,10 +0,0 @@
-"""Sampling module for FastMCP servers."""
-
-from fastmcp.server.sampling.run import SampleStep, SamplingResult
-from fastmcp.server.sampling.sampling_tool import SamplingTool
-
-__all__ = [
- "SampleStep",
- "SamplingResult",
- "SamplingTool",
-]
diff --git a/fastmcp_slim/fastmcp/server/sampling/run.py b/fastmcp_slim/fastmcp/server/sampling/run.py
deleted file mode 100644
index ed959ed60..000000000
--- a/fastmcp_slim/fastmcp/server/sampling/run.py
+++ /dev/null
@@ -1,836 +0,0 @@
-"""Sampling types and helper functions for FastMCP servers."""
-
-from __future__ import annotations
-
-import inspect
-import json
-from collections.abc import Callable, Sequence
-from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any, Generic, Literal, cast
-
-import anyio
-from mcp_types import (
- ClientCapabilities,
- CreateMessageResult,
- CreateMessageResultWithTools,
- ModelHint,
- ModelPreferences,
- SamplingCapability,
- SamplingMessage,
- SamplingMessageContentBlock,
- SamplingToolsCapability,
- TextContent,
- ToolChoice,
- ToolResultContent,
- ToolUseContent,
-)
-from mcp_types import CreateMessageRequestParams as SamplingParams
-from mcp_types import Tool as SDKTool
-from opentelemetry.trace import SpanKind, Status, StatusCode
-from pydantic import ValidationError
-from typing_extensions import TypeVar
-
-from fastmcp import settings
-from fastmcp.exceptions import ToolError
-from fastmcp.server.sampling.sampling_tool import SamplingTool
-from fastmcp.telemetry import get_tracer, restore_dropped_attributes
-from fastmcp.tools.function_tool import FunctionTool
-from fastmcp.tools.tool_transform import TransformedTool
-from fastmcp.utilities.async_utils import gather
-from fastmcp.utilities.json_schema import compress_schema
-from fastmcp.utilities.logging import get_logger
-from fastmcp.utilities.types import get_cached_typeadapter
-
-logger = get_logger(__name__)
-
-if TYPE_CHECKING:
- from fastmcp.server.context import Context
-
-ResultT = TypeVar("ResultT")
-
-# Maximum number of consecutive final_response validation retries (not
-# counting the initial attempt) before aborting. Total attempts = N + 1.
-_MAX_VALIDATION_RETRIES = 3
-
-# Simplified tool choice type - just the mode string instead of the full MCP object
-ToolChoiceOption = Literal["auto", "required", "none"]
-
-# How many times we retry when the LLM returns text instead of calling final_response
-_MAX_TEXT_RESPONSE_RETRIES = 3
-
-
-@dataclass
-class SamplingResult(Generic[ResultT]):
- """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.
- """
-
- text: str | None
- result: ResultT
- history: list[SamplingMessage]
-
-
-@dataclass
-class SampleStep:
- """Result of a single sampling call.
-
- Represents what the LLM returned in this step plus the message history.
- """
-
- response: CreateMessageResult | CreateMessageResultWithTools
- history: list[SamplingMessage]
-
- @property
- def is_tool_use(self) -> bool:
- """True if the LLM is requesting tool execution."""
- if isinstance(self.response, CreateMessageResultWithTools):
- return self.response.stop_reason == "toolUse"
- return False
-
- @property
- def text(self) -> str | None:
- """Extract text from the response, if available."""
- content = self.response.content
- if isinstance(content, list):
- for block in content:
- if isinstance(block, TextContent):
- return block.text
- return None
- elif isinstance(content, TextContent):
- return content.text
- return None
-
- @property
- def tool_calls(self) -> list[ToolUseContent]:
- """Get the list of tool calls from the response."""
- content = self.response.content
- if isinstance(content, list):
- return [c for c in content if isinstance(c, ToolUseContent)]
- elif isinstance(content, ToolUseContent):
- return [content]
- return []
-
-
-def _parse_model_preferences(
- model_preferences: ModelPreferences | str | list[str] | None,
-) -> ModelPreferences | None:
- """Convert model preferences to ModelPreferences object."""
- if model_preferences is None:
- return None
- elif isinstance(model_preferences, ModelPreferences):
- return model_preferences
- elif isinstance(model_preferences, str):
- return ModelPreferences(hints=[ModelHint(name=model_preferences)])
- elif isinstance(model_preferences, list):
- if not all(isinstance(h, str) for h in model_preferences):
- raise ValueError("All elements of model_preferences list must be strings.")
- return ModelPreferences(hints=[ModelHint(name=h) for h in model_preferences])
- else:
- raise ValueError(
- "model_preferences must be one of: ModelPreferences, str, list[str], or None."
- )
-
-
-# --- Standalone functions for sample_step() ---
-
-
-def determine_handler_mode(
- context: Context, needs_tools: bool, *, client_available: bool = True
-) -> 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.
- client_available: Whether the client back-channel can be reached at all.
- On modern (2026-07-28) connections the server-initiated createMessage
- back-channel was removed (SEP-2577), so the client can never serve a
- sampling request; pass False there to force the server-side handler
- path (``"fallback"`` behaves like ``"always"`` when a handler exists).
-
- Returns:
- True if fallback handler should be used, False to use client.
-
- Raises:
- ValueError: If client lacks required capability and no fallback configured.
- """
- fastmcp = context.fastmcp
- session = context.session
-
- # Check what capabilities the client has. On connections without a
- # back-channel the client can never serve the request regardless of the
- # capabilities it advertised, so treat both as unavailable.
- has_sampling = client_available and session.check_client_capability(
- capability=ClientCapabilities(sampling=SamplingCapability())
- )
- has_tools_capability = client_available and session.check_client_capability(
- capability=ClientCapabilities(
- sampling=SamplingCapability(tools=SamplingToolsCapability())
- )
- )
-
- if fastmcp.sampling_handler_behavior == "always":
- if fastmcp.sampling_handler is None:
- raise ValueError(
- "sampling_handler_behavior is 'always' but no handler configured"
- )
- return True
- elif fastmcp.sampling_handler_behavior == "fallback":
- client_sufficient = has_sampling and (not needs_tools or has_tools_capability)
- if not client_sufficient:
- if fastmcp.sampling_handler is None:
- if needs_tools and has_sampling and not has_tools_capability:
- raise ValueError(
- "Client does not support sampling with tools. "
- "The client must advertise the sampling.tools capability."
- )
- raise ValueError("Client does not support sampling")
- return True
- elif fastmcp.sampling_handler_behavior is not None:
- raise ValueError(
- f"Invalid sampling_handler_behavior: {fastmcp.sampling_handler_behavior!r}. "
- "Must be 'always', 'fallback', or None."
- )
- elif not has_sampling:
- raise ValueError("Client does not support sampling")
- elif needs_tools and not has_tools_capability:
- raise ValueError(
- "Client does not support sampling with tools. "
- "The client must advertise the sampling.tools capability."
- )
-
- return False
-
-
-async def call_sampling_handler(
- context: Context,
- messages: list[SamplingMessage],
- *,
- system_prompt: str | None,
- temperature: float | None,
- max_tokens: int,
- model_preferences: ModelPreferences | str | list[str] | None,
- sdk_tools: list[SDKTool] | None,
- tool_choice: ToolChoice | None,
-) -> CreateMessageResult | CreateMessageResultWithTools:
- """Make LLM call using the fallback handler.
-
- Note: This function expects the caller (sample_step) to have validated that
- sampling_handler is set via determine_handler_mode(). The checks below are
- safeguards against internal misuse.
- """
- if context.fastmcp.sampling_handler is None:
- raise RuntimeError("sampling_handler is None")
- if context.request_context is None:
- raise RuntimeError("request_context is None")
-
- result = context.fastmcp.sampling_handler(
- messages,
- SamplingParams(
- system_prompt=system_prompt,
- messages=messages,
- temperature=temperature,
- max_tokens=max_tokens,
- model_preferences=_parse_model_preferences(model_preferences),
- tools=sdk_tools,
- tool_choice=tool_choice,
- ),
- # SamplingHandler is typed against the SDK's RequestContext placeholder,
- # but FastMCP hands handlers its own FastMCPRequestContext wrapper at
- # runtime; the two aren't structurally related in the type system.
- context.request_context, # ty: ignore[invalid-argument-type]
- )
-
- if inspect.isawaitable(result):
- result = await result
-
- result = cast("str | CreateMessageResult | CreateMessageResultWithTools", result)
-
- # Convert string to CreateMessageResult
- if isinstance(result, str):
- return CreateMessageResult(
- role="assistant",
- content=TextContent(type="text", text=result),
- model="unknown",
- stop_reason="endTurn",
- )
-
- return result
-
-
-async def execute_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 want
- to 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 concurrently
- If any tool has sequential=True, all tools execute sequentially
- regardless of this setting.
-
- Returns:
- List of tool result content blocks in the same order as tool_calls.
- """
- if tool_concurrency is not None and tool_concurrency < 0:
- raise ValueError(
- f"tool_concurrency must be None, 0 (unlimited), or a positive integer, "
- f"got {tool_concurrency}"
- )
-
- async def _execute_single_tool(tool_use: ToolUseContent) -> ToolResultContent:
- """Execute a single tool and return its result."""
- tool = tool_map.get(tool_use.name)
- if tool is None:
- return ToolResultContent(
- type="tool_result",
- tool_use_id=tool_use.id,
- content=[
- TextContent(
- type="text",
- text=f"Error: Unknown tool '{tool_use.name}'",
- )
- ],
- is_error=True,
- )
-
- tracer = get_tracer()
- span_attrs = {
- "gen_ai.tool.name": tool_use.name,
- "fastmcp.tool.use_id": tool_use.id,
- }
- with tracer.start_as_current_span(
- f"sampling tool {tool_use.name}",
- kind=SpanKind.INTERNAL,
- attributes=span_attrs,
- ) as span:
- # Restore: `attributes=span_attrs` above lets on_start hooks and
- # the sampler see these values at creation time. But OTel's
- # Tracer.start_span builds the span from
- # `sampling_result.attributes`, not the `attributes` kwarg
- # directly — a custom Sampler whose SamplingResult.attributes
- # defaults to None silently drops everything we passed. This
- # only fires when the span ends up with no attributes at all, so
- # any sampler that supplied attributes of its own — forwarding
- # ours, redacting or replacing some, or substituting entirely its
- # own — is left untouched, as is an SDK attribute limit that
- # evicted some.
- if span.is_recording():
- restore_dropped_attributes(span, span_attrs)
- try:
- result_value = await tool.run(tool_use.input)
- return ToolResultContent(
- type="tool_result",
- tool_use_id=tool_use.id,
- content=[TextContent(type="text", text=str(result_value))],
- )
- except ToolError as e:
- if span.is_recording():
- span.set_attribute("error.type", "tool_error")
- span.record_exception(e)
- span.set_status(Status(StatusCode.ERROR, str(e)))
- logger.log(
- e.log_level,
- f"Error calling sampling tool '{tool_use.name}'",
- exc_info=True,
- )
- return ToolResultContent(
- type="tool_result",
- tool_use_id=tool_use.id,
- content=[TextContent(type="text", text=str(e))],
- is_error=True,
- )
- except Exception as e:
- if span.is_recording():
- span.set_attribute("error.type", type(e).__qualname__)
- span.record_exception(e)
- span.set_status(Status(StatusCode.ERROR, str(e)))
- logger.exception(f"Error calling sampling tool '{tool_use.name}'")
- if mask_error_details:
- error_text = f"Error executing tool '{tool_use.name}'"
- else:
- error_text = f"Error executing tool '{tool_use.name}': {e}"
- return ToolResultContent(
- type="tool_result",
- tool_use_id=tool_use.id,
- content=[TextContent(type="text", text=error_text)],
- is_error=True,
- )
-
- # Check if any tool requires sequential execution
- requires_sequential = any(
- tool.sequential
- for tool_use in tool_calls
- if (tool := tool_map.get(tool_use.name)) is not None
- )
-
- # Execute sequentially if required or if concurrency is None (default)
- if tool_concurrency is None or requires_sequential:
- tool_results: list[ToolResultContent] = []
- for tool_use in tool_calls:
- result = await _execute_single_tool(tool_use)
- tool_results.append(result)
- return tool_results
-
- # Execute in parallel
- if tool_concurrency == 0:
- # Unlimited parallel execution
- return await gather(_execute_single_tool(tc) for tc in tool_calls)
- else:
- # Bounded parallel execution with semaphore
- semaphore = anyio.Semaphore(tool_concurrency)
-
- async def bounded_execute(tool_use: ToolUseContent) -> ToolResultContent:
- async with semaphore:
- return await _execute_single_tool(tool_use)
-
- return await gather(bounded_execute(tc) for tc in tool_calls)
-
-
-# --- Helper functions for sampling ---
-
-
-def prepare_messages(
- messages: str | Sequence[str | SamplingMessage],
-) -> list[SamplingMessage]:
- """Convert various message formats to a list of SamplingMessage objects."""
- if isinstance(messages, str):
- return [
- SamplingMessage(
- content=TextContent(text=messages, type="text"), role="user"
- )
- ]
- else:
- return [
- SamplingMessage(content=TextContent(text=m, type="text"), role="user")
- if isinstance(m, str)
- else m
- for m in messages
- ]
-
-
-def prepare_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 using
- from_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.
- """
- if tools is None:
- return None
-
- sampling_tools: list[SamplingTool] = []
- for t in tools:
- if isinstance(t, SamplingTool):
- sampling_tools.append(t)
- elif isinstance(t, (FunctionTool, TransformedTool)):
- sampling_tools.append(SamplingTool.from_callable_tool(t))
- elif callable(t):
- sampling_tools.append(SamplingTool.from_function(t))
- else:
- raise TypeError(
- f"Expected SamplingTool, FunctionTool, TransformedTool, or callable, got {type(t)}"
- )
-
- return sampling_tools if sampling_tools else None
-
-
-def extract_tool_calls(
- response: CreateMessageResult | CreateMessageResultWithTools,
-) -> list[ToolUseContent]:
- """Extract tool calls from a response."""
- content = response.content
- if isinstance(content, list):
- return [c for c in content if isinstance(c, ToolUseContent)]
- elif isinstance(content, ToolUseContent):
- return [content]
- return []
-
-
-def create_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.
- """
- type_adapter = get_cached_typeadapter(result_type)
- schema = type_adapter.json_schema()
- schema = compress_schema(schema, prune_titles=True)
-
- # Tool parameters must be object-shaped. Wrap primitives in {"value": <schema>}
- if schema.get("type") != "object":
- schema = {
- "type": "object",
- "properties": {"value": schema},
- "required": ["value"],
- }
-
- # The fn just returns the input as-is (validation happens in the loop)
- def final_response(**kwargs: Any) -> dict[str, Any]:
- return kwargs
-
- return SamplingTool(
- name="final_response",
- description=(
- "Call this tool to provide your final response. "
- "Use this when you have completed the task and are ready to return the result."
- ),
- parameters=schema,
- fn=final_response,
- )
-
-
-# --- Implementation functions for Context methods ---
-
-
-async def sample_step_impl(
- context: Context,
- messages: str | Sequence[str | SamplingMessage],
- *,
- system_prompt: str | None = None,
- temperature: float | None = None,
- max_tokens: int | None = None,
- model_preferences: ModelPreferences | str | list[str] | None = None,
- tools: Sequence[SamplingTool | FunctionTool | TransformedTool | Callable[..., Any]]
- | None = None,
- tool_choice: ToolChoiceOption | str | None = None,
- auto_execute_tools: bool = True,
- mask_error_details: bool | None = None,
- tool_concurrency: int | None = None,
- client_available: bool = True,
-) -> SampleStep:
- """Implementation of Context.sample_step().
-
- Make a single LLM sampling call. This is a stateless function that makes
- exactly one LLM call and optionally executes any requested tools.
-
- When ``client_available`` is False (e.g. a modern 2026-07-28 connection with
- no back-channel), the client is never used and a configured sampling handler
- serves the request; the caller is responsible for raising a clear era error
- when no handler can serve it.
- """
- # Convert messages to SamplingMessage objects
- current_messages = prepare_messages(messages)
-
- # Convert tools to SamplingTools
- sampling_tools = prepare_tools(tools)
- sdk_tools: list[SDKTool] | None = (
- [t._to_sdk_tool() for t in sampling_tools] if sampling_tools else None
- )
- tool_map: dict[str, SamplingTool] = (
- {t.name: t for t in sampling_tools} if sampling_tools else {}
- )
-
- # Determine whether to use fallback handler or client
- use_fallback = determine_handler_mode(
- context, bool(sampling_tools), client_available=client_available
- )
-
- # Build tool choice
- effective_tool_choice: ToolChoice | None = None
- if tool_choice is not None:
- if tool_choice not in ("auto", "required", "none"):
- raise ValueError(
- f"Invalid tool_choice: {tool_choice!r}. "
- "Must be 'auto', 'required', or 'none'."
- )
- effective_tool_choice = ToolChoice.model_validate({"mode": tool_choice})
-
- # Effective max_tokens
- effective_max_tokens = max_tokens if max_tokens is not None else 512
-
- # Make the LLM call
- tracer = get_tracer()
- span_attrs = {
- "mcp.method.name": "sampling/createMessage",
- "fastmcp.server.name": context.fastmcp.name,
- }
- with tracer.start_as_current_span(
- "sampling create_message",
- kind=SpanKind.CLIENT,
- attributes=span_attrs,
- record_exception=False,
- set_status_on_exception=False,
- ) as span:
- # Restore: `attributes=span_attrs` above lets on_start hooks and the
- # sampler see these values at creation time. But OTel's
- # Tracer.start_span builds the span from
- # `sampling_result.attributes`, not the `attributes` kwarg directly —
- # a custom Sampler whose SamplingResult.attributes defaults to None
- # silently drops everything we passed. This only fires when the span
- # ends up with no attributes at all, so any sampler that supplied
- # attributes of its own — forwarding ours, redacting or replacing
- # some, or substituting entirely its own — is left untouched, as is
- # an SDK attribute limit that evicted some.
- if span.is_recording():
- restore_dropped_attributes(span, span_attrs)
- try:
- if use_fallback:
- response = await call_sampling_handler(
- context,
- current_messages,
- system_prompt=system_prompt,
- temperature=temperature,
- max_tokens=effective_max_tokens,
- model_preferences=model_preferences,
- sdk_tools=sdk_tools,
- tool_choice=effective_tool_choice,
- )
- else:
- # Deprecated upstream in SDK v2 but deliberately kept per compat
- # directive; removed with the multi-round-trip follow-up.
- response = await context.session.create_message( # ty: ignore[deprecated]
- messages=current_messages,
- system_prompt=system_prompt,
- temperature=temperature,
- max_tokens=effective_max_tokens,
- model_preferences=_parse_model_preferences(model_preferences),
- tools=sdk_tools,
- tool_choice=effective_tool_choice,
- related_request_id=context.origin_request_id,
- )
- except Exception as e:
- if span.is_recording():
- span.set_attribute("error.type", type(e).__qualname__)
- span.record_exception(e)
- span.set_status(Status(StatusCode.ERROR, str(e)))
- raise
-
- # Check if this is a tool use response
- is_tool_use_response = (
- isinstance(response, CreateMessageResultWithTools)
- and response.stop_reason == "toolUse"
- )
-
- # Always include the assistant response in history
- current_messages.append(SamplingMessage(role="assistant", content=response.content))
-
- # If not a tool use, return immediately
- if not is_tool_use_response:
- return SampleStep(response=response, history=current_messages)
-
- # If not executing tools, return with assistant message but no tool results
- if not auto_execute_tools:
- return SampleStep(response=response, history=current_messages)
-
- # Execute tools and add results to history
- step_tool_calls = extract_tool_calls(response)
- if step_tool_calls:
- effective_mask = (
- mask_error_details
- if mask_error_details is not None
- else settings.mask_error_details
- )
- tool_results: list[ToolResultContent] = await execute_tools(
- step_tool_calls,
- tool_map,
- mask_error_details=effective_mask,
- tool_concurrency=tool_concurrency,
- )
-
- if tool_results:
- current_messages.append(
- SamplingMessage(
- role="user",
- content=cast(list[SamplingMessageContentBlock], tool_results),
- )
- )
-
- return SampleStep(response=response, history=current_messages)
-
-
-async def sample_impl(
- context: Context,
- messages: str | Sequence[str | SamplingMessage],
- *,
- system_prompt: str | None = None,
- temperature: float | None = None,
- max_tokens: int | None = None,
- model_preferences: ModelPreferences | str | list[str] | None = None,
- tools: Sequence[SamplingTool | FunctionTool | TransformedTool | Callable[..., Any]]
- | None = None,
- result_type: type[ResultT] | None = None,
- mask_error_details: bool | None = None,
- tool_concurrency: int | None = None,
- client_available: bool = True,
-) -> SamplingResult[ResultT]:
- """Implementation of Context.sample().
-
- Send a sampling request to the client and await the response. This method
- runs to completion automatically, executing a tool loop until the LLM
- provides a final text response.
-
- When ``client_available`` is False (e.g. a modern 2026-07-28 connection with
- no back-channel), the client is never used and a configured sampling handler
- serves the request; the caller is responsible for raising a clear era error
- when no handler can serve it.
- """
- # Safety limit to prevent infinite loops
- max_iterations = 100
-
- # Convert tools to SamplingTools
- sampling_tools = prepare_tools(tools)
-
- # Handle structured output with result_type
- tool_choice: str | None = None
- if result_type is not None and result_type is not str:
- final_response_tool = create_final_response_tool(result_type)
- sampling_tools = list(sampling_tools) if sampling_tools else []
- sampling_tools.append(final_response_tool)
-
- # Always require tool calls when result_type is set - the LLM must
- # eventually call final_response (text responses are not accepted)
- tool_choice = "required"
-
- # Convert messages for the loop
- current_messages: str | Sequence[str | SamplingMessage] = messages
-
- text_response_retries = 0
- consecutive_validation_failures = 0
-
- for _iteration in range(max_iterations):
- step = await sample_step_impl(
- context,
- messages=current_messages,
- system_prompt=system_prompt,
- temperature=temperature,
- max_tokens=max_tokens,
- model_preferences=model_preferences,
- tools=sampling_tools,
- tool_choice=tool_choice,
- mask_error_details=mask_error_details,
- tool_concurrency=tool_concurrency,
- client_available=client_available,
- )
-
- # Check for final_response tool call for structured output
- had_final_response = False
- if result_type is not None and result_type is not str and step.is_tool_use:
- for tool_call in step.tool_calls:
- if tool_call.name == "final_response":
- had_final_response = True
- # Validate and return the structured result
- type_adapter = get_cached_typeadapter(result_type)
-
- # Unwrap if we wrapped primitives (non-object schemas)
- input_data = tool_call.input
- original_schema = compress_schema(
- type_adapter.json_schema(), prune_titles=True
- )
- if (
- original_schema.get("type") != "object"
- and isinstance(input_data, dict)
- and "value" in input_data
- ):
- input_data = input_data["value"]
-
- try:
- validated_result = type_adapter.validate_python(input_data)
- text = json.dumps(
- type_adapter.dump_python(validated_result, mode="json")
- )
- return SamplingResult(
- text=text,
- result=validated_result,
- history=step.history,
- )
- except ValidationError as e:
- consecutive_validation_failures += 1
- if consecutive_validation_failures > _MAX_VALIDATION_RETRIES:
- raise RuntimeError(
- f"Structured output validation failed "
- f"{consecutive_validation_failures} consecutive "
- f"times for type {result_type.__name__}: {e}"
- ) from e
- # Validation failed - add error as tool result
- step.history.append(
- SamplingMessage(
- role="user",
- content=[
- ToolResultContent(
- type="tool_result",
- tool_use_id=tool_call.id,
- content=[
- TextContent(
- type="text",
- text=(
- f"Validation error: {e}. "
- "Please try again with valid data."
- ),
- )
- ],
- is_error=True,
- )
- ],
- )
- )
-
- # The LLM called tools but not final_response — reset validation counter
- if not had_final_response:
- consecutive_validation_failures = 0
-
- # If not a tool use response, we're done
- if not step.is_tool_use:
- # For structured output, the LLM must use the final_response tool
- if result_type is not None and result_type is not str:
- text_response_retries += 1
- if text_response_retries > _MAX_TEXT_RESPONSE_RETRIES:
- raise RuntimeError(
- f"Expected structured output of type {result_type.__name__}, "
- "but the LLM returned a text response instead of calling "
- f"the final_response tool ({text_response_retries} attempts)."
- )
- # Nudge the LLM to use the tool
- step.history.append(
- SamplingMessage(
- role="user",
- content=TextContent(
- type="text",
- text=(
- "You must call the `final_response` tool to provide "
- "your answer. Do not respond with text — use the tool."
- ),
- ),
- )
- )
- current_messages = step.history
- continue
- return SamplingResult(
- text=step.text,
- result=cast(ResultT, step.text if step.text else ""),
- history=step.history,
- )
-
- # Continue with the updated history
- current_messages = step.history
-
- # After first iteration, reset tool_choice to auto (unless structured output is required)
- if result_type is None or result_type is str:
- tool_choice = None
-
- raise RuntimeError(f"Sampling exceeded maximum iterations ({max_iterations})")
diff --git a/fastmcp_slim/fastmcp/server/sampling/sampling_tool.py b/fastmcp_slim/fastmcp/server/sampling/sampling_tool.py
deleted file mode 100644
index 05063dc53..000000000
--- a/fastmcp_slim/fastmcp/server/sampling/sampling_tool.py
+++ /dev/null
@@ -1,204 +0,0 @@
-"""SamplingTool for use during LLM sampling requests."""
-
-from __future__ import annotations
-
-import inspect
-from collections.abc import Callable
-from typing import Any
-
-from mcp_types import TextContent
-from mcp_types import Tool as SDKTool
-from pydantic import ConfigDict
-
-from fastmcp.exceptions import AuthorizationError
-from fastmcp.server.auth.authorization import AuthContext, run_auth_checks
-from fastmcp.server.dependencies import get_access_token
-from fastmcp.tools.base import ToolResult
-from fastmcp.tools.function_parsing import ParsedFunction
-from fastmcp.tools.function_tool import FunctionTool
-from fastmcp.tools.tool_transform import TransformedTool
-from fastmcp.utilities.types import FastMCPBaseModel
-
-
-class SamplingTool(FastMCPBaseModel):
- """A tool that can be used during LLM sampling.
-
- SamplingTools bundle a tool's schema (name, description, parameters) with
- an executor function, enabling servers to execute agentic workflows where
- the LLM can request tool calls during sampling.
-
- In most cases, pass functions directly to ctx.sample():
-
- def search(query: str) -> str:
- '''Search the web.'''
- return web_search(query)
-
- result = await context.sample(
- messages="Find info about Python",
- tools=[search], # Plain functions work directly
- )
-
- Create a SamplingTool explicitly when you need custom name/description:
-
- tool = SamplingTool.from_function(search, name="web_search")
- """
-
- name: str
- description: str | None = None
- parameters: dict[str, Any]
- fn: Callable[..., Any]
- sequential: bool = False
-
- model_config = ConfigDict(arbitrary_types_allowed=True)
-
- async def run(self, arguments: dict[str, Any] | None = None) -> Any:
- """Execute the tool with the given arguments.
-
- Args:
- arguments: Dictionary of arguments to pass to the tool function.
-
- Returns:
- The result of executing the tool function.
- """
- if arguments is None:
- arguments = {}
-
- result = self.fn(**arguments)
- if inspect.isawaitable(result):
- result = await result
- return result
-
- def _to_sdk_tool(self) -> SDKTool:
- """Convert to an mcp_types.Tool for SDK compatibility.
-
- This is used internally when passing tools to the MCP SDK's
- create_message() method.
- """
- return SDKTool(
- name=self.name,
- description=self.description,
- input_schema=self.parameters,
- )
-
- @classmethod
- def from_function(
- cls,
- fn: Callable[..., Any],
- *,
- name: str | None = None,
- description: str | None = None,
- sequential: bool = False,
- ) -> SamplingTool:
- """Create a SamplingTool from a function.
-
- The function's signature is analyzed to generate a JSON schema for
- the tool's parameters. Type hints are used to determine parameter types.
-
- Args:
- fn: The function to create a tool from.
- name: Optional name override. Defaults to the function's name.
- description: Optional description override. Defaults to the function's docstring.
- sequential: If True, this tool requires sequential execution and prevents
- parallel execution of all tools in the batch. Set to True for tools
- with shared state, file writes, or other operations that cannot run
- concurrently. Defaults to False.
-
- Returns:
- A SamplingTool wrapping the function.
-
- Raises:
- ValueError: If the function is a lambda without a name override.
- """
- parsed = ParsedFunction.from_function(fn, validate=True)
-
- if name is None and parsed.name == "<lambda>":
- raise ValueError("You must provide a name for lambda functions")
-
- return cls(
- name=name or parsed.name,
- description=description if description is not None else parsed.description,
- parameters=parsed.input_schema,
- fn=parsed.fn,
- sequential=sequential,
- )
-
- @classmethod
- def from_callable_tool(
- cls,
- tool: FunctionTool | TransformedTool,
- *,
- name: str | None = None,
- description: str | None = None,
- ) -> SamplingTool:
- """Create a SamplingTool from a FunctionTool or TransformedTool.
-
- Reuses existing server tools in sampling contexts. For TransformedTool,
- the tool's .run() method is used to ensure proper argument transformation,
- and the ToolResult is automatically unwrapped.
-
- Args:
- tool: A FunctionTool or TransformedTool to convert.
- name: Optional name override. Defaults to tool.name.
- description: Optional description override. Defaults to tool.description.
-
- Raises:
- TypeError: If the tool is not a FunctionTool or TransformedTool.
- """
- # Validate that the tool is a supported type
- if not isinstance(tool, (FunctionTool, TransformedTool)):
- raise TypeError(
- f"Expected FunctionTool or TransformedTool, got {type(tool).__name__}. "
- "Only callable tools can be converted to SamplingTools."
- )
-
- # Both FunctionTool and TransformedTool need .run() to ensure proper
- # result processing (serializers, output_schema, wrap-result flags)
- async def wrapper(**kwargs: Any) -> Any:
- # Enforce per-tool auth checks, mirroring what the server
- # dispatcher does for direct tool calls. Without this, an
- # auth-protected tool wrapped as a SamplingTool could be
- # invoked by the LLM during sampling without authorization.
- if tool.auth is not None:
- # Late import to avoid circular import with context.py
- from fastmcp.server.context import _current_transport
-
- is_stdio = _current_transport.get() == "stdio"
- if not is_stdio:
- token = get_access_token()
- ctx = AuthContext(token=token, component=tool)
- if not await run_auth_checks(tool.auth, ctx):
- raise AuthorizationError(
- f"Authorization failed for tool '{tool.name}': "
- "insufficient permissions"
- )
-
- result = await tool.run(kwargs)
- # Unwrap ToolResult - extract the actual value
- if isinstance(result, ToolResult):
- # If there's structured_content, use that
- if result.structured_content is not None:
- # Check tool's schema - this is the source of truth
- if tool.output_schema and tool.output_schema.get(
- "x-fastmcp-wrap-result"
- ):
- # Tool wraps results: {"result": value} -> value
- return result.structured_content.get("result")
- else:
- # No wrapping: use structured_content directly
- return result.structured_content
- # Otherwise, extract from text content
- if result.content and len(result.content) > 0:
- first_content = result.content[0]
- if isinstance(first_content, TextContent):
- return first_content.text
- return result
-
- fn = wrapper
-
- # Extract the callable function, name, description, and parameters
- return cls(
- name=name or tool.name,
- description=description or tool.description,
- parameters=tool.parameters,
- fn=fn,
- )
diff --git a/fastmcp_slim/fastmcp/server/server.py b/fastmcp_slim/fastmcp/server/server.py
index 15e03c5f2..4c4426282 100644
--- a/fastmcp_slim/fastmcp/server/server.py
+++ b/fastmcp_slim/fastmcp/server/server.py
@@ -102,7 +102,6 @@ from fastmcp.utilities.versions import (
if TYPE_CHECKING:
from fastmcp.client import Client
from fastmcp.client.client import SDKServer
- from fastmcp.client.sampling import SamplingHandler
from fastmcp.client.transports import ClientTransport, ClientTransportT
from fastmcp.server.extensions import ServerExtension
from fastmcp.server.providers.openapi import ComponentFn as OpenAPIComponentFn
@@ -178,11 +177,13 @@ _REMOVED_KWARGS: dict[str, str] = {
"include_tags": "Use `server.enable(tags=..., only=True)` after creating the server.",
"exclude_tags": "Use `server.disable(tags=...)` after creating the server.",
"tool_transformations": "Use `server.add_transform(ToolTransform(...))` after creating the server.",
+ "sampling_handler": "Server-initiated sampling was removed from MCP by SEP-2577. Call an LLM directly from your tool.",
+ "sampling_handler_behavior": "Server-initiated sampling was removed from MCP by SEP-2577. Call an LLM directly from your tool.",
}
def _check_removed_kwargs(kwargs: dict[str, Any]) -> None:
- """Raise helpful TypeErrors for kwargs removed in v3."""
+ """Raise helpful TypeErrors for kwargs FastMCP no longer accepts."""
for key in kwargs:
if key in _REMOVED_KWARGS:
raise TypeError(
@@ -355,8 +356,6 @@ class FastMCP(
cache_scope: Literal["public", "private"] | None = None,
tasks: bool | None = None,
session_state_store: AsyncKeyValue | None = None,
- sampling_handler: SamplingHandler | None = None,
- sampling_handler_behavior: Literal["always", "fallback"] | None = None,
client_log_level: mcp_types.LoggingLevel | None = None,
experimental_capabilities: dict[str, dict[str, Any]] | None = None,
**kwargs: Any,
@@ -538,11 +537,6 @@ class FastMCP(
# Set up MCP protocol handlers
self._setup_handlers()
- self.sampling_handler: SamplingHandler | None = sampling_handler
- self.sampling_handler_behavior: Literal["always", "fallback"] = (
- sampling_handler_behavior or "fallback"
- )
-
def __repr__(self) -> str:
return f"{type(self).__name__}({self.name!r})"
diff --git a/tests/client/test_sampling_result_types.py b/tests/client/test_sampling_result_types.py
deleted file mode 100644
index e581e2582..000000000
--- a/tests/client/test_sampling_result_types.py
+++ /dev/null
@@ -1,681 +0,0 @@
-import pytest
-from mcp_types import CreateMessageResultWithTools, TextContent, ToolUseContent
-
-from fastmcp import Client, Context, FastMCP
-from fastmcp.client.sampling import RequestContext, SamplingMessage, SamplingParams
-
-
-class TestSamplingResultType:
- """Tests for result_type parameter (structured output)."""
-
- async def test_result_type_creates_final_response_tool(self):
- """Test that result_type creates a synthetic final_response tool."""
- from mcp_types import CreateMessageResultWithTools, ToolUseContent
- from pydantic import BaseModel
-
- class MathResult(BaseModel):
- answer: int
- explanation: str
-
- received_tools: list = []
-
- def sampling_handler(
- messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext
- ) -> CreateMessageResultWithTools:
- received_tools.extend(params.tools or [])
-
- # Return the final_response tool call
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_1",
- name="final_response",
- input={"answer": 42, "explanation": "The meaning of life"},
- )
- ],
- model="test-model",
- stop_reason="toolUse",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def math_tool(context: Context) -> str:
- result = await context.sample(
- messages="What is 6 * 7?",
- result_type=MathResult,
- )
- # result.result should be a MathResult object
- assert isinstance(result.result, MathResult)
- return f"{result.result.answer}: {result.result.explanation}"
-
- async with Client(mcp) as client:
- result = await client.call_tool("math_tool", {})
-
- # Check that final_response tool was added
- tool_names = [t.name for t in received_tools]
- assert "final_response" in tool_names
-
- # Check the result
- assert result.data == "42: The meaning of life"
-
- async def test_result_type_with_user_tools(self):
- """Test result_type works alongside user-provided tools."""
- from mcp_types import CreateMessageResultWithTools, ToolUseContent
- from pydantic import BaseModel
-
- class SearchResult(BaseModel):
- summary: str
- sources: list[str]
-
- def search(query: str) -> str:
- """Search for information."""
- return f"Found info about: {query}"
-
- call_count = 0
- tool_was_called = False
-
- def sampling_handler(
- messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext
- ) -> CreateMessageResultWithTools:
- nonlocal call_count, tool_was_called
- call_count += 1
-
- if call_count == 1:
- # First call: use the search tool
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_1",
- name="search",
- input={"query": "Python tutorials"},
- )
- ],
- model="test-model",
- stop_reason="toolUse",
- )
- else:
- # Second call: call final_response
- tool_was_called = True
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_2",
- name="final_response",
- input={
- "summary": "Python is great",
- "sources": ["python.org", "docs.python.org"],
- },
- )
- ],
- model="test-model",
- stop_reason="toolUse",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def research(context: Context) -> str:
- result = await context.sample(
- messages="Research Python",
- tools=[search],
- result_type=SearchResult,
- )
- assert isinstance(result.result, SearchResult)
- return f"{result.result.summary} - {len(result.result.sources)} sources"
-
- async with Client(mcp) as client:
- result = await client.call_tool("research", {})
-
- assert tool_was_called
- assert result.data == "Python is great - 2 sources"
-
- async def test_result_type_validation_error_retries(self):
- """Test that validation errors are sent back to LLM for retry."""
- from mcp_types import (
- CreateMessageResultWithTools,
- ToolResultContent,
- ToolUseContent,
- )
- from pydantic import BaseModel
-
- class StrictResult(BaseModel):
- value: int # Must be an int
-
- messages_received: list[list[SamplingMessage]] = []
-
- def sampling_handler(
- messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext
- ) -> CreateMessageResultWithTools:
- messages_received.append(list(messages))
-
- if len(messages_received) == 1:
- # First call: invalid type
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_1",
- name="final_response",
- input={"value": "not_an_int"}, # Wrong type
- )
- ],
- model="test-model",
- stop_reason="toolUse",
- )
- else:
- # Second call: valid type after seeing error
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_2",
- name="final_response",
- input={"value": 42}, # Correct type
- )
- ],
- model="test-model",
- stop_reason="toolUse",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def validate_tool(context: Context) -> str:
- result = await context.sample(
- messages="Give me a number",
- result_type=StrictResult,
- )
- assert isinstance(result.result, StrictResult)
- return str(result.result.value)
-
- async with Client(mcp) as client:
- result = await client.call_tool("validate_tool", {})
-
- # Should have retried after validation error
- assert len(messages_received) == 2
-
- # Check that error was passed back
- last_messages = messages_received[1]
- # Find the tool result in list content
- tool_result = None
- for msg in last_messages:
- # Tool results are now in a list
- if isinstance(msg.content, list):
- for item in msg.content:
- if isinstance(item, ToolResultContent):
- tool_result = item
- break
- elif isinstance(msg.content, ToolResultContent):
- tool_result = msg.content
- break
- assert tool_result is not None
- assert tool_result.is_error is True
- assert isinstance(tool_result.content[0], TextContent)
- error_text = tool_result.content[0].text
- assert "Validation error" in error_text
-
- # Final result should be correct
- assert result.data == "42"
-
- async def test_sampling_result_has_text_and_history(self):
- """Test that SamplingResult has text, result, and history attributes."""
- from mcp_types import CreateMessageResultWithTools
-
- def sampling_handler(
- messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext
- ) -> CreateMessageResultWithTools:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text="Hello world")],
- model="test-model",
- stop_reason="endTurn",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def check_result(context: Context) -> str:
- result = await context.sample(messages="Say hello")
- # Check all attributes exist
- assert result.text == "Hello world"
- assert result.result == "Hello world"
- assert len(result.history) >= 1
- return "ok"
-
- async with Client(mcp) as client:
- result = await client.call_tool("check_result", {})
-
- assert result.data == "ok"
-
-
-class TestSampleStep:
- """Tests for ctx.sample_step() - single LLM call with manual control."""
-
- async def test_sample_step_basic(self):
- """Test basic sample_step returns text response."""
- from mcp_types import CreateMessageResultWithTools
-
- def sampling_handler(
- messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext
- ) -> CreateMessageResultWithTools:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text="Hello from step")],
- model="test-model",
- stop_reason="endTurn",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def test_step(context: Context) -> str:
- step = await context.sample_step(messages="Hi")
- assert not step.is_tool_use
- assert step.text == "Hello from step"
- return step.text or ""
-
- async with Client(mcp) as client:
- result = await client.call_tool("test_step", {})
-
- assert result.data == "Hello from step"
-
- async def test_sample_step_with_tool_execution(self):
- """Test sample_step executes tools by default."""
- from mcp_types import CreateMessageResultWithTools, ToolUseContent
-
- call_count = 0
-
- def my_tool(x: int) -> str:
- """A test tool."""
- return f"result:{x}"
-
- def sampling_handler(
- messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext
- ) -> CreateMessageResultWithTools:
- nonlocal call_count
- call_count += 1
-
- if call_count == 1:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_1",
- name="my_tool",
- input={"x": 42},
- )
- ],
- model="test-model",
- stop_reason="toolUse",
- )
- else:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text="Done")],
- model="test-model",
- stop_reason="endTurn",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def test_step(context: Context) -> str:
- messages: str | list[SamplingMessage] = "Run tool"
-
- while True:
- step = await context.sample_step(messages=messages, tools=[my_tool])
-
- if not step.is_tool_use:
- return step.text or ""
-
- # History should include tool results when execute_tools=True
- messages = step.history
-
- async with Client(mcp) as client:
- result = await client.call_tool("test_step", {})
-
- assert result.data == "Done"
- assert call_count == 2
-
- async def test_sample_step_execute_tools_false(self):
- """Test sample_step with execute_tools=False doesn't execute tools."""
- from mcp_types import CreateMessageResultWithTools, ToolUseContent
-
- tool_executed = False
-
- def my_tool() -> str:
- """A test tool."""
- nonlocal tool_executed
- tool_executed = True
- return "executed"
-
- def sampling_handler(
- messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext
- ) -> CreateMessageResultWithTools:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_1",
- name="my_tool",
- input={},
- )
- ],
- model="test-model",
- stop_reason="toolUse",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def test_step(context: Context) -> str:
- step = await context.sample_step(
- messages="Run tool",
- tools=[my_tool],
- execute_tools=False,
- )
- assert step.is_tool_use
- assert len(step.tool_calls) == 1
- assert step.tool_calls[0].name == "my_tool"
- # History should include assistant message but no tool results
- assert len(step.history) == 2 # user + assistant
- return "ok"
-
- async with Client(mcp) as client:
- result = await client.call_tool("test_step", {})
-
- assert result.data == "ok"
- assert not tool_executed # Tool should not have been executed
-
- async def test_sample_step_history_includes_assistant_message(self):
- """Test that history includes assistant message when execute_tools=False."""
- from mcp_types import CreateMessageResultWithTools, ToolUseContent
-
- def sampling_handler(
- messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext
- ) -> CreateMessageResultWithTools:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_1",
- name="my_tool",
- input={"query": "test"},
- )
- ],
- model="test-model",
- stop_reason="toolUse",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- def my_tool(query: str) -> str:
- return f"result for {query}"
-
- @mcp.tool
- async def test_step(context: Context) -> str:
- step = await context.sample_step(
- messages="Search",
- tools=[my_tool],
- execute_tools=False,
- )
- # History should have: user message + assistant message
- assert len(step.history) == 2
- assert step.history[0].role == "user"
- assert step.history[1].role == "assistant"
- return "ok"
-
- async with Client(mcp) as client:
- result = await client.call_tool("test_step", {})
-
- assert result.data == "ok"
-
-
-class TestTextResponseRetry:
- """Tests for retry logic when LLM returns text instead of calling final_response."""
-
- @staticmethod
- def _text_reply(text: str = "some text"):
- from mcp_types import CreateMessageResultWithTools
-
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text=text)],
- model="m",
- stop_reason="endTurn",
- )
-
- @staticmethod
- def _tool_reply(value: int):
- from mcp_types import CreateMessageResultWithTools, ToolUseContent
-
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="c1",
- name="final_response",
- input={"value": value},
- )
- ],
- model="m",
- stop_reason="toolUse",
- )
-
- async def test_text_response_then_success(self):
- """Text on first call, final_response on second -- verify call_count == 2."""
- from pydantic import BaseModel
-
- class R(BaseModel):
- value: int
-
- call_count = 0
-
- def handler(messages, params, ctx):
- nonlocal call_count
- call_count += 1
- return self._text_reply() if call_count == 1 else self._tool_reply(42)
-
- mcp = FastMCP(sampling_handler=handler)
-
- @mcp.tool
- async def t(context: Context) -> str:
- return str((await context.sample(messages="q", result_type=R)).result.value)
-
- async with Client(mcp) as client:
- result = await client.call_tool("t", {})
-
- assert call_count == 2
- assert result.data == "42"
-
- async def test_text_response_exceeds_max_retries(self):
- """Always text, never tool -- verify error after _MAX_TEXT_RESPONSE_RETRIES+1 calls."""
- from pydantic import BaseModel
-
- from fastmcp.exceptions import ToolError
- from fastmcp.server.sampling.run import _MAX_TEXT_RESPONSE_RETRIES
-
- class R(BaseModel):
- value: int
-
- call_count = 0
-
- def handler(messages, params, ctx):
- nonlocal call_count
- call_count += 1
- return self._text_reply()
-
- mcp = FastMCP(sampling_handler=handler)
-
- @mcp.tool
- async def t(context: Context) -> str:
- return str((await context.sample(messages="q", result_type=R)).result)
-
- async with Client(mcp) as client:
- with pytest.raises(ToolError, match="attempts"):
- await client.call_tool("t", {})
-
- assert call_count == _MAX_TEXT_RESPONSE_RETRIES + 1
-
- async def test_no_retry_when_result_type_is_none(self):
- """Text response with no result_type -- single call, normal return."""
- call_count = 0
-
- def handler(messages, params, ctx):
- nonlocal call_count
- call_count += 1
- return self._text_reply("hello")
-
- mcp = FastMCP(sampling_handler=handler)
-
- @mcp.tool
- async def t(context: Context) -> str:
- return (await context.sample(messages="q")).text or ""
-
- async with Client(mcp) as client:
- result = await client.call_tool("t", {})
-
- assert call_count == 1
- assert result.data == "hello"
-
-
-def _final_response(call_id: str, input_data: dict) -> CreateMessageResultWithTools:
- """Build a final_response tool-use reply."""
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use", id=call_id, name="final_response", input=input_data
- )
- ],
- model="test-model",
- stop_reason="toolUse",
- )
-
-
-def _tool_call(
- call_id: str, name: str, input_data: dict
-) -> CreateMessageResultWithTools:
- """Build a regular tool-use reply."""
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(type="tool_use", id=call_id, name=name, input=input_data)
- ],
- model="test-model",
- stop_reason="toolUse",
- )
-
-
-class TestValidationRetryCap:
- """Tests for the consecutive validation retry cap (PR #3851)."""
-
- async def test_validation_failures_within_cap_then_success(self):
- """Two consecutive failures followed by a valid response succeeds."""
- from pydantic import BaseModel
-
- class R(BaseModel):
- value: int
-
- call_count = 0
-
- def handler(messages, params, ctx):
- nonlocal call_count
- call_count += 1
- if call_count <= 2:
- return _final_response(f"c{call_count}", {"value": "bad"})
- return _final_response(f"c{call_count}", {"value": 99})
-
- mcp = FastMCP(sampling_handler=handler)
-
- @mcp.tool
- async def t(context: Context) -> str:
- r = await context.sample(messages="go", result_type=R)
- return str(r.result.value)
-
- async with Client(mcp) as client:
- result = await client.call_tool("t", {})
-
- assert call_count == 3
- assert result.data == "99"
-
- async def test_consecutive_validation_failures_exceed_cap(self):
- """Always-invalid responses raise ToolError after exceeding the cap."""
- from pydantic import BaseModel
-
- from fastmcp.exceptions import ToolError
- from fastmcp.server.sampling.run import _MAX_VALIDATION_RETRIES
-
- class R(BaseModel):
- value: int
-
- call_count = 0
-
- def handler(messages, params, ctx):
- nonlocal call_count
- call_count += 1
- return _final_response(f"c{call_count}", {"value": "wrong"})
-
- mcp = FastMCP(sampling_handler=handler)
-
- @mcp.tool
- async def t(context: Context) -> str:
- return str((await context.sample(messages="go", result_type=R)).result)
-
- async with Client(mcp) as client:
- with pytest.raises(ToolError, match="consecutive"):
- await client.call_tool("t", {})
-
- # 1 initial attempt + _MAX_VALIDATION_RETRIES retries
- assert call_count == _MAX_VALIDATION_RETRIES + 1
-
- async def test_validation_counter_resets_after_other_tool_call(self):
- """A tool call between validation failures resets the counter."""
- from pydantic import BaseModel
-
- class R(BaseModel):
- value: int
-
- def helper_tool(x: int) -> str:
- """A helper tool."""
- return f"result:{x}"
-
- call_count = 0
-
- def handler(messages, params, ctx):
- nonlocal call_count
- call_count += 1
- # fail -> other tool (resets counter) -> fail -> succeed
- if call_count == 1:
- return _final_response("c1", {"value": "bad"})
- if call_count == 2:
- return _tool_call("c2", "helper_tool", {"x": 1})
- if call_count == 3:
- return _final_response("c3", {"value": "bad"})
- return _final_response("c4", {"value": 42})
-
- mcp = FastMCP(sampling_handler=handler)
-
- @mcp.tool
- async def t(context: Context) -> str:
- r = await context.sample(messages="go", tools=[helper_tool], result_type=R)
- return str(r.result.value)
-
- async with Client(mcp) as client:
- result = await client.call_tool("t", {})
-
- assert call_count == 4
- assert result.data == "42"
diff --git a/tests/client/test_sampling_tool_loop.py b/tests/client/test_sampling_tool_loop.py
deleted file mode 100644
index 0e18bd25f..000000000
--- a/tests/client/test_sampling_tool_loop.py
+++ /dev/null
@@ -1,811 +0,0 @@
-from typing import cast
-
-from mcp_types import TextContent
-
-from fastmcp import Client, Context, FastMCP
-from fastmcp.client.sampling import RequestContext, SamplingMessage, SamplingParams
-from fastmcp.server.sampling import SamplingTool
-
-
-class TestAutomaticToolLoop:
- """Tests for automatic tool execution loop in ctx.sample()."""
-
- async def test_automatic_tool_loop_executes_tools(self):
- """Test that ctx.sample() automatically executes tool calls."""
- from mcp_types import CreateMessageResultWithTools, ToolUseContent
-
- call_count = 0
- tool_was_called = False
-
- def get_weather(city: str) -> str:
- """Get weather for a city."""
- nonlocal tool_was_called
- tool_was_called = True
- return f"Weather in {city}: sunny, 72°F"
-
- def sampling_handler(
- messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext
- ) -> CreateMessageResultWithTools:
- nonlocal call_count
- call_count += 1
-
- if call_count == 1:
- # First call: return tool use
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_1",
- name="get_weather",
- input={"city": "Seattle"},
- )
- ],
- model="test-model",
- stop_reason="toolUse",
- )
- else:
- # Second call: return final response
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text="The weather is sunny!")],
- model="test-model",
- stop_reason="endTurn",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def weather_assistant(question: str, context: Context) -> str:
- result = await context.sample(
- messages=question,
- tools=[get_weather],
- )
- # Get text from SamplingResult
- return result.text or ""
-
- async with Client(mcp) as client:
- result = await client.call_tool(
- "weather_assistant", {"question": "What's the weather?"}
- )
-
- assert tool_was_called
- assert call_count == 2
- assert result.data == "The weather is sunny!"
-
- async def test_automatic_tool_loop_multiple_tools(self):
- """Test that multiple tool calls in one response are all executed."""
- from mcp_types import CreateMessageResultWithTools, ToolUseContent
-
- executed_tools: list[str] = []
-
- def tool_a(x: int) -> int:
- """Tool A."""
- executed_tools.append(f"tool_a({x})")
- return x * 2
-
- def tool_b(y: int) -> int:
- """Tool B."""
- executed_tools.append(f"tool_b({y})")
- return y + 10
-
- call_count = 0
-
- def sampling_handler(
- messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext
- ) -> CreateMessageResultWithTools:
- nonlocal call_count
- call_count += 1
-
- if call_count == 1:
- # Return multiple tool calls
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use", id="call_a", name="tool_a", input={"x": 5}
- ),
- ToolUseContent(
- type="tool_use", id="call_b", name="tool_b", input={"y": 3}
- ),
- ],
- model="test-model",
- stop_reason="toolUse",
- )
- else:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text="Done!")],
- model="test-model",
- stop_reason="endTurn",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def multi_tool(context: Context) -> str:
- result = await context.sample(messages="Run tools", tools=[tool_a, tool_b])
- return result.text or ""
-
- async with Client(mcp) as client:
- result = await client.call_tool("multi_tool", {})
-
- assert executed_tools == ["tool_a(5)", "tool_b(3)"]
- assert result.data == "Done!"
-
- async def test_automatic_tool_loop_handles_unknown_tool(self):
- """Test that unknown tool names result in error being passed to LLM."""
- from mcp_types import (
- CreateMessageResultWithTools,
- ToolResultContent,
- ToolUseContent,
- )
-
- def known_tool() -> str:
- """A known tool."""
- return "known result"
-
- messages_received: list[list[SamplingMessage]] = []
-
- def sampling_handler(
- messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext
- ) -> CreateMessageResultWithTools:
- messages_received.append(list(messages))
-
- if len(messages_received) == 1:
- # Request unknown tool
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_1",
- name="unknown_tool",
- input={},
- )
- ],
- model="test-model",
- stop_reason="toolUse",
- )
- else:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text="Handled error")],
- model="test-model",
- stop_reason="endTurn",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def test_unknown(context: Context) -> str:
- result = await context.sample(messages="Test", tools=[known_tool])
- return result.text or ""
-
- async with Client(mcp) as client:
- result = await client.call_tool("test_unknown", {})
-
- # Check that error was passed back in messages
- assert len(messages_received) == 2
- last_messages = messages_received[1]
- # Find the tool result in list content
- tool_result = None
- for msg in last_messages:
- # Tool results are now in a list
- if isinstance(msg.content, list):
- for item in msg.content:
- if isinstance(item, ToolResultContent):
- tool_result = item
- break
- elif isinstance(msg.content, ToolResultContent):
- tool_result = msg.content
- break
- assert tool_result is not None
- assert tool_result.is_error is True
- # Content is list of TextContent objects
- assert isinstance(tool_result.content[0], TextContent)
- error_text = tool_result.content[0].text
- assert "Unknown tool" in error_text
- assert result.data == "Handled error"
-
- async def test_automatic_tool_loop_handles_tool_exception(self):
- """Test that tool exceptions are caught and passed to LLM as errors."""
- from mcp_types import (
- CreateMessageResultWithTools,
- ToolResultContent,
- ToolUseContent,
- )
-
- def failing_tool() -> str:
- """A tool that raises an exception."""
- raise ValueError("Tool failed intentionally")
-
- messages_received: list[list[SamplingMessage]] = []
-
- def sampling_handler(
- messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext
- ) -> CreateMessageResultWithTools:
- messages_received.append(list(messages))
-
- if len(messages_received) == 1:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_1",
- name="failing_tool",
- input={},
- )
- ],
- model="test-model",
- stop_reason="toolUse",
- )
- else:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text="Handled error")],
- model="test-model",
- stop_reason="endTurn",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def test_exception(context: Context) -> str:
- result = await context.sample(messages="Test", tools=[failing_tool])
- return result.text or ""
-
- async with Client(mcp) as client:
- result = await client.call_tool("test_exception", {})
-
- # Check that error was passed back
- assert len(messages_received) == 2
- last_messages = messages_received[1]
- # Find the tool result in list content
- tool_result = None
- for msg in last_messages:
- # Tool results are now in a list
- if isinstance(msg.content, list):
- for item in msg.content:
- if isinstance(item, ToolResultContent):
- tool_result = item
- break
- elif isinstance(msg.content, ToolResultContent):
- tool_result = msg.content
- break
- assert tool_result is not None
- assert tool_result.is_error is True
- # Content is list of TextContent objects
- assert isinstance(tool_result.content[0], TextContent)
- error_text = tool_result.content[0].text
- assert "Tool failed intentionally" in error_text
- assert result.data == "Handled error"
-
- async def test_concurrent_tool_execution_default_sequential(self):
- """Test that tools execute sequentially by default."""
- import asyncio
-
- from mcp_types import CreateMessageResultWithTools, ToolUseContent
-
- # Ordering is guaranteed structurally (the loop awaits each tool call
- # to completion before starting the next when tool_concurrency is
- # None), so no real delay is needed to prove it - a single
- # `asyncio.sleep(0)` still yields control to the event loop.
- execution_order: list[str] = []
-
- async def slow_tool_a(x: int) -> int:
- """Slow tool A."""
- execution_order.append("tool_a_start")
- await asyncio.sleep(0)
- execution_order.append("tool_a_end")
- return x * 2
-
- async def slow_tool_b(y: int) -> int:
- """Slow tool B."""
- execution_order.append("tool_b_start")
- await asyncio.sleep(0)
- execution_order.append("tool_b_end")
- return y + 10
-
- call_count = 0
-
- def sampling_handler(
- messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext
- ) -> CreateMessageResultWithTools:
- nonlocal call_count
- call_count += 1
-
- if call_count == 1:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_a",
- name="slow_tool_a",
- input={"x": 5},
- ),
- ToolUseContent(
- type="tool_use",
- id="call_b",
- name="slow_tool_b",
- input={"y": 3},
- ),
- ],
- model="test-model",
- stop_reason="toolUse",
- )
- else:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text="Done!")],
- model="test-model",
- stop_reason="endTurn",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def test_tool(context: Context) -> str:
- result = await context.sample(
- messages="Run tools",
- tools=[slow_tool_a, slow_tool_b],
- # Default: tool_concurrency=None (sequential)
- )
- return result.text or ""
-
- async with Client(mcp) as client:
- result = await client.call_tool("test_tool", {})
-
- assert result.data == "Done!"
- # Verify sequential execution: tool_a must complete before tool_b starts
- assert execution_order == [
- "tool_a_start",
- "tool_a_end",
- "tool_b_start",
- "tool_b_end",
- ]
-
- async def test_concurrent_tool_execution_unlimited(self):
- """Test unlimited parallel tool execution with tool_concurrency=0."""
- import asyncio
-
- from mcp_types import CreateMessageResultWithTools, ToolUseContent
-
- # tool_a blocks on an event that only tool_b sets. This is only
- # satisfiable if both tools are genuinely running concurrently: under
- # sequential execution tool_b would never start (tool_a would never
- # finish awaiting it) and the test would fail via the wait_for
- # timeout rather than racing on wall-clock timestamps.
- execution_order: list[str] = []
- tool_b_started = asyncio.Event()
-
- async def slow_tool_a(x: int) -> int:
- """Slow tool A."""
- execution_order.append("tool_a_start")
- await asyncio.wait_for(tool_b_started.wait(), timeout=1.0)
- execution_order.append("tool_a_end")
- return x * 2
-
- async def slow_tool_b(y: int) -> int:
- """Slow tool B."""
- execution_order.append("tool_b_start")
- tool_b_started.set()
- execution_order.append("tool_b_end")
- return y + 10
-
- call_count = 0
-
- def sampling_handler(
- messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext
- ) -> CreateMessageResultWithTools:
- nonlocal call_count
- call_count += 1
-
- if call_count == 1:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_a",
- name="slow_tool_a",
- input={"x": 5},
- ),
- ToolUseContent(
- type="tool_use",
- id="call_b",
- name="slow_tool_b",
- input={"y": 3},
- ),
- ],
- model="test-model",
- stop_reason="toolUse",
- )
- else:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text="Done!")],
- model="test-model",
- stop_reason="endTurn",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def test_tool(context: Context) -> str:
- result = await context.sample(
- messages="Run tools",
- tools=[slow_tool_a, slow_tool_b],
- tool_concurrency=0, # Unlimited parallel
- )
- return result.text or ""
-
- async with Client(mcp) as client:
- result = await client.call_tool("test_tool", {})
-
- assert result.data == "Done!"
- # Verify parallel execution: tool_b started and finished entirely
- # inside tool_a's blocked wait, which is only possible if the two
- # tools were running concurrently.
- assert execution_order == [
- "tool_a_start",
- "tool_b_start",
- "tool_b_end",
- "tool_a_end",
- ]
-
- async def test_concurrent_tool_execution_bounded(self):
- """Test bounded parallel execution with tool_concurrency=2."""
- import asyncio
-
- from mcp_types import CreateMessageResultWithTools, ToolUseContent
-
- # tool_1 and tool_2 each block until *both* have started, which is
- # only possible if two slots are occupied simultaneously (proving
- # concurrency=2 admits two tools at once). tool_3 has no blocking
- # branch, so its appearance in the log tells us when the real
- # semaphore in the implementation let it in - only after a slot
- # frees, i.e. after tool_1 or tool_2 finishes.
- execution_order: list[str] = []
- both_started = asyncio.Event()
- started_names: set[str] = set()
-
- async def slow_tool(name: str) -> str:
- """Generic tool used to observe bounded concurrency."""
- execution_order.append(f"{name}_start")
- if name in ("tool_1", "tool_2"):
- started_names.add(name)
- if {"tool_1", "tool_2"} <= started_names:
- both_started.set()
- await asyncio.wait_for(both_started.wait(), timeout=1.0)
- execution_order.append(f"{name}_end")
- return f"{name} done"
-
- call_count = 0
-
- def sampling_handler(
- messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext
- ) -> CreateMessageResultWithTools:
- nonlocal call_count
- call_count += 1
-
- if call_count == 1:
- # Request 3 tools (with concurrency=2, first 2 run parallel, then 3rd)
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_1",
- name="slow_tool",
- input={"name": "tool_1"},
- ),
- ToolUseContent(
- type="tool_use",
- id="call_2",
- name="slow_tool",
- input={"name": "tool_2"},
- ),
- ToolUseContent(
- type="tool_use",
- id="call_3",
- name="slow_tool",
- input={"name": "tool_3"},
- ),
- ],
- model="test-model",
- stop_reason="toolUse",
- )
- else:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text="Done!")],
- model="test-model",
- stop_reason="endTurn",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def test_tool(context: Context) -> str:
- result = await context.sample(
- messages="Run tools",
- tools=[slow_tool],
- tool_concurrency=2, # Max 2 concurrent
- )
- return result.text or ""
-
- async with Client(mcp) as client:
- result = await client.call_tool("test_tool", {})
-
- assert result.data == "Done!"
- # Verify that at most 2 tools run concurrently
- # First 2 tools should start before either ends
- assert execution_order[0] in ["tool_1_start", "tool_2_start"]
- assert execution_order[1] in ["tool_1_start", "tool_2_start"]
- # Third tool should start after at least one of the first two finishes
- tool_3_start_idx = execution_order.index("tool_3_start")
- assert (
- "tool_1_end" in execution_order[:tool_3_start_idx]
- or "tool_2_end" in execution_order[:tool_3_start_idx]
- )
-
- async def test_sequential_tool_forces_sequential_execution(self):
- """Test that sequential=True forces all tools to execute sequentially."""
- import asyncio
-
- from mcp_types import CreateMessageResultWithTools, ToolUseContent
-
- # A sequential=True tool in the batch forces the whole batch through
- # the plain for-loop path (see run.py's `requires_sequential`), so
- # ordering is guaranteed structurally and no real delay is needed.
- execution_order: list[str] = []
-
- async def normal_tool(x: int) -> int:
- """Normal tool."""
- execution_order.append("normal_start")
- await asyncio.sleep(0)
- execution_order.append("normal_end")
- return x * 2
-
- async def sequential_tool(y: int) -> int:
- """Sequential tool."""
- execution_order.append("sequential_start")
- await asyncio.sleep(0)
- execution_order.append("sequential_end")
- return y + 10
-
- call_count = 0
-
- def sampling_handler(
- messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext
- ) -> CreateMessageResultWithTools:
- nonlocal call_count
- call_count += 1
-
- if call_count == 1:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_1",
- name="normal_tool",
- input={"x": 5},
- ),
- ToolUseContent(
- type="tool_use",
- id="call_2",
- name="sequential_tool",
- input={"y": 3},
- ),
- ],
- model="test-model",
- stop_reason="toolUse",
- )
- else:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text="Done!")],
- model="test-model",
- stop_reason="endTurn",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def test_tool(context: Context) -> str:
- # Create tools with sequential=True for one of them
- normal = SamplingTool.from_function(normal_tool, sequential=False)
- sequential = SamplingTool.from_function(sequential_tool, sequential=True)
-
- result = await context.sample(
- messages="Run tools",
- tools=[normal, sequential],
- tool_concurrency=0, # Request unlimited, but sequential tool forces sequential
- )
- return result.text or ""
-
- async with Client(mcp) as client:
- result = await client.call_tool("test_tool", {})
-
- assert result.data == "Done!"
- # Verify sequential execution: first tool must complete before second starts
- assert execution_order[0] in ["normal_start", "sequential_start"]
- assert execution_order[1] in ["normal_end", "sequential_end"]
- # Ensure the second tool starts after the first ends
- if execution_order[0] == "normal_start":
- assert execution_order[1] == "normal_end"
- assert execution_order[2] == "sequential_start"
- else:
- assert execution_order[1] == "sequential_end"
- assert execution_order[2] == "normal_start"
-
- async def test_concurrent_tool_execution_error_handling(self):
- """Test that errors are captured per-tool in parallel execution."""
- from mcp_types import (
- CreateMessageResultWithTools,
- ToolResultContent,
- ToolUseContent,
- )
-
- def good_tool() -> str:
- return "success"
-
- def bad_tool() -> str:
- raise ValueError("Tool error")
-
- messages_received: list[list[SamplingMessage]] = []
-
- def sampling_handler(
- messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext
- ) -> CreateMessageResultWithTools:
- messages_received.append(list(messages))
-
- if len(messages_received) == 1:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use", id="call_1", name="good_tool", input={}
- ),
- ToolUseContent(
- type="tool_use", id="call_2", name="bad_tool", input={}
- ),
- ],
- model="test-model",
- stop_reason="toolUse",
- )
- else:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text="Handled errors")],
- model="test-model",
- stop_reason="endTurn",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def test_tool(context: Context) -> str:
- result = await context.sample(
- messages="Run tools",
- tools=[good_tool, bad_tool],
- tool_concurrency=0, # Parallel execution
- )
- return result.text or ""
-
- async with Client(mcp) as client:
- result = await client.call_tool("test_tool", {})
-
- assert result.data == "Handled errors"
- # Check that tool results include both success and error
- tool_result_message = messages_received[1][-1]
- assert tool_result_message.role == "user"
- tool_results = cast(list[ToolResultContent], tool_result_message.content)
- assert len(tool_results) == 2
- # One should be success, one should be error
- assert any(not r.is_error for r in tool_results)
- assert any(r.is_error for r in tool_results)
-
- async def test_concurrent_tool_result_order_preserved(self):
- """Test that tool results maintain the same order as tool calls."""
- import asyncio
-
- from mcp_types import (
- CreateMessageResultWithTools,
- ToolResultContent,
- ToolUseContent,
- )
-
- # Chain events so the tools finish in a different order (2, 3, 1)
- # than they were called (1, 2, 3), without depending on real delays:
- # tool 2 finishes immediately and unblocks tool 3, which finishes and
- # unblocks tool 1. This only resolves if all three run concurrently -
- # under sequential execution tool 1 would deadlock waiting on tool 3,
- # which itself would never have been started yet.
- tool_2_done = asyncio.Event()
- tool_3_done = asyncio.Event()
-
- async def tool_with_delay(value: int) -> int:
- """Tool that finishes out of call order."""
- if value == 1:
- await asyncio.wait_for(tool_3_done.wait(), timeout=1.0)
- elif value == 3:
- await asyncio.wait_for(tool_2_done.wait(), timeout=1.0)
-
- if value == 2:
- tool_2_done.set()
- elif value == 3:
- tool_3_done.set()
- return value
-
- messages_received: list[list[SamplingMessage]] = []
-
- def sampling_handler(
- messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext
- ) -> CreateMessageResultWithTools:
- messages_received.append(list(messages))
-
- if len(messages_received) == 1:
- # Call order is 1, 2, 3 but they finish out of order (2, 3, 1)
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_1",
- name="tool_with_delay",
- input={"value": 1},
- ),
- ToolUseContent(
- type="tool_use",
- id="call_2",
- name="tool_with_delay",
- input={"value": 2},
- ),
- ToolUseContent(
- type="tool_use",
- id="call_3",
- name="tool_with_delay",
- input={"value": 3},
- ),
- ],
- model="test-model",
- stop_reason="toolUse",
- )
- else:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text="Done!")],
- model="test-model",
- stop_reason="endTurn",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def test_tool(context: Context) -> str:
- result = await context.sample(
- messages="Run tools",
- tools=[tool_with_delay],
- tool_concurrency=0, # Parallel execution
- )
- return result.text or ""
-
- async with Client(mcp) as client:
- result = await client.call_tool("test_tool", {})
-
- assert result.data == "Done!"
- # Check that results are in the correct order (1, 2, 3) despite finishing order (2, 3, 1)
- tool_result_message = messages_received[1][-1]
- tool_results = cast(list[ToolResultContent], tool_result_message.content)
- assert len(tool_results) == 3
- assert tool_results[0].tool_use_id == "call_1"
- assert tool_results[1].tool_use_id == "call_2"
- assert tool_results[2].tool_use_id == "call_3"
- # Check values are correct
- result_texts = [cast(TextContent, r.content[0]).text for r in tool_results]
- assert result_texts == ["1", "2", "3"]
diff --git a/tests/server/sampling/__init__.py b/tests/server/sampling/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/tests/server/sampling/test_prepare_tools.py b/tests/server/sampling/test_prepare_tools.py
deleted file mode 100644
index b0639b492..000000000
--- a/tests/server/sampling/test_prepare_tools.py
+++ /dev/null
@@ -1,111 +0,0 @@
-"""Tests for prepare_tools helper function."""
-
-import pytest
-
-from fastmcp.server.sampling.run import prepare_tools
-from fastmcp.server.sampling.sampling_tool import SamplingTool
-from fastmcp.tools.function_tool import FunctionTool
-from fastmcp.tools.tool_transform import ArgTransform, TransformedTool
-
-
-class TestPrepareTools:
- """Tests for prepare_tools()."""
-
- def test_prepare_tools_with_none(self):
- """Test that None returns None."""
- result = prepare_tools(None)
- assert result is None
-
- def test_prepare_tools_with_sampling_tool(self):
- """Test that SamplingTool instances pass through."""
-
- def search(query: str) -> str:
- return f"Results: {query}"
-
- sampling_tool = SamplingTool.from_function(search)
- result = prepare_tools([sampling_tool])
-
- assert result is not None
- assert len(result) == 1
- assert result[0] is sampling_tool
-
- def test_prepare_tools_with_function(self):
- """Test that plain functions are converted."""
-
- def search(query: str) -> str:
- """Search function."""
- return f"Results: {query}"
-
- result = prepare_tools([search])
-
- assert result is not None
- assert len(result) == 1
- assert isinstance(result[0], SamplingTool)
- assert result[0].name == "search"
-
- def test_prepare_tools_with_function_tool(self):
- """Test that FunctionTool instances are converted."""
-
- def search(query: str) -> str:
- """Search the web."""
- return f"Results: {query}"
-
- function_tool = FunctionTool.from_function(search)
- result = prepare_tools([function_tool])
-
- assert result is not None
- assert len(result) == 1
- assert isinstance(result[0], SamplingTool)
- assert result[0].name == "search"
- assert result[0].description == "Search the web."
-
- def test_prepare_tools_with_transformed_tool(self):
- """Test that TransformedTool instances are converted."""
-
- def original(query: str) -> str:
- """Original tool."""
- return f"Results: {query}"
-
- function_tool = FunctionTool.from_function(original)
- transformed_tool = TransformedTool.from_tool(
- function_tool,
- name="search_v2",
- transform_args={"query": ArgTransform(name="q")},
- )
-
- result = prepare_tools([transformed_tool])
-
- assert result is not None
- assert len(result) == 1
- assert isinstance(result[0], SamplingTool)
- assert result[0].name == "search_v2"
- assert "q" in result[0].parameters.get("properties", {})
-
- def test_prepare_tools_with_mixed_types(self):
- """Test that mixed tool types are all converted."""
-
- def plain_fn(x: int) -> int:
- return x * 2
-
- def fn_for_tool(y: int) -> int:
- return y * 3
-
- function_tool = FunctionTool.from_function(fn_for_tool)
- sampling_tool = SamplingTool.from_function(lambda z: z * 4, name="lambda_tool")
-
- result = prepare_tools([plain_fn, function_tool, sampling_tool])
-
- assert result is not None
- assert len(result) == 3
- assert all(isinstance(t, SamplingTool) for t in result)
-
- def test_prepare_tools_with_invalid_type(self):
- """Test that invalid types raise TypeError."""
-
- with pytest.raises(TypeError, match="Expected SamplingTool, FunctionTool"):
- prepare_tools(["not a tool"]) # type: ignore[arg-type] # ty:ignore[invalid-argument-type]
-
- def test_prepare_tools_empty_list(self):
- """Test that empty list returns None."""
- result = prepare_tools([])
- assert result is None
diff --git a/tests/server/sampling/test_sampling_tool.py b/tests/server/sampling/test_sampling_tool.py
deleted file mode 100644
index 792161ea3..000000000
--- a/tests/server/sampling/test_sampling_tool.py
+++ /dev/null
@@ -1,440 +0,0 @@
-"""Tests for SamplingTool."""
-
-import pytest
-from mcp.server.auth.middleware.auth_context import auth_context_var
-from mcp.server.auth.middleware.bearer_auth import AuthenticatedUser
-
-from fastmcp.exceptions import AuthorizationError
-from fastmcp.server.auth import AccessToken, require_scopes
-from fastmcp.server.context import _current_transport
-from fastmcp.server.sampling import SamplingTool
-from fastmcp.tools.function_tool import FunctionTool
-from fastmcp.tools.tool_transform import ArgTransform, TransformedTool
-
-
-class TestSamplingToolFromFunction:
- """Tests for SamplingTool.from_function()."""
-
- def test_from_simple_function(self):
- def search(query: str) -> str:
- """Search the web."""
- return f"Results for: {query}"
-
- tool = SamplingTool.from_function(search)
-
- assert tool.name == "search"
- assert tool.description == "Search the web."
- assert "query" in tool.parameters.get("properties", {})
- assert tool.fn is search
-
- def test_from_function_with_overrides(self):
- def search(query: str) -> str:
- return f"Results for: {query}"
-
- tool = SamplingTool.from_function(
- search,
- name="web_search",
- description="Search the internet",
- )
-
- assert tool.name == "web_search"
- assert tool.description == "Search the internet"
-
- def test_from_lambda_requires_name(self):
- with pytest.raises(ValueError, match="must provide a name for lambda"):
- SamplingTool.from_function(lambda x: x)
-
- def test_from_lambda_with_name(self):
- tool = SamplingTool.from_function(lambda x: x * 2, name="double")
-
- assert tool.name == "double"
-
- def test_from_async_function(self):
- async def async_search(query: str) -> str:
- """Async search."""
- return f"Async results for: {query}"
-
- tool = SamplingTool.from_function(async_search)
-
- assert tool.name == "async_search"
- assert tool.description == "Async search."
-
- def test_multiple_parameters(self):
- def search(query: str, limit: int = 10, include_images: bool = False) -> str:
- """Search with options."""
- return f"Results for: {query}"
-
- tool = SamplingTool.from_function(search)
- props = tool.parameters.get("properties", {})
-
- assert "query" in props
- assert "limit" in props
- assert "include_images" in props
-
-
-class TestSamplingToolRun:
- """Tests for SamplingTool.run()."""
-
- async def test_run_sync_function(self):
- def add(a: int, b: int) -> int:
- """Add two numbers."""
- return a + b
-
- tool = SamplingTool.from_function(add)
- result = await tool.run({"a": 2, "b": 3})
- assert result == 5
-
- async def test_run_async_function(self):
- async def async_add(a: int, b: int) -> int:
- """Add two numbers asynchronously."""
- return a + b
-
- tool = SamplingTool.from_function(async_add)
- result = await tool.run({"a": 2, "b": 3})
- assert result == 5
-
- async def test_run_with_no_arguments(self):
- def get_value() -> str:
- """Return a fixed value."""
- return "hello"
-
- tool = SamplingTool.from_function(get_value)
- result = await tool.run()
- assert result == "hello"
-
- async def test_run_with_none_arguments(self):
- def get_value() -> str:
- """Return a fixed value."""
- return "hello"
-
- tool = SamplingTool.from_function(get_value)
- result = await tool.run(None)
- assert result == "hello"
-
-
-class TestSamplingToolSDKConversion:
- """Tests for SamplingTool._to_sdk_tool() internal method."""
-
- def test_to_sdk_tool(self):
- def search(query: str) -> str:
- """Search the web."""
- return f"Results for: {query}"
-
- tool = SamplingTool.from_function(search)
- sdk_tool = tool._to_sdk_tool()
-
- assert sdk_tool.name == "search"
- assert sdk_tool.description == "Search the web."
- assert "query" in sdk_tool.input_schema.get("properties", {})
-
-
-class TestSamplingToolFromCallableTool:
- """Tests for SamplingTool.from_callable_tool()."""
-
- def test_from_function_tool(self):
- """Test converting a FunctionTool to SamplingTool."""
-
- def search(query: str) -> str:
- """Search the web."""
- return f"Results for: {query}"
-
- function_tool = FunctionTool.from_function(search)
- sampling_tool = SamplingTool.from_callable_tool(function_tool)
-
- assert sampling_tool.name == "search"
- assert sampling_tool.description == "Search the web."
- assert "query" in sampling_tool.parameters.get("properties", {})
- # fn is now a wrapper that calls tool.run() for proper result processing
- assert callable(sampling_tool.fn)
-
- def test_from_function_tool_with_overrides(self):
- """Test converting FunctionTool with name/description overrides."""
-
- def search(query: str) -> str:
- """Search the web."""
- return f"Results for: {query}"
-
- function_tool = FunctionTool.from_function(search)
- sampling_tool = SamplingTool.from_callable_tool(
- function_tool,
- name="web_search",
- description="Search the internet",
- )
-
- assert sampling_tool.name == "web_search"
- assert sampling_tool.description == "Search the internet"
-
- def test_from_transformed_tool(self):
- """Test converting a TransformedTool to SamplingTool."""
-
- def original(query: str, limit: int) -> str:
- """Original tool."""
- return f"Results for: {query} (limit: {limit})"
-
- function_tool = FunctionTool.from_function(original)
- transformed_tool = TransformedTool.from_tool(
- function_tool,
- name="search_transformed",
- transform_args={"query": ArgTransform(name="q")},
- )
-
- sampling_tool = SamplingTool.from_callable_tool(transformed_tool)
-
- assert sampling_tool.name == "search_transformed"
- assert sampling_tool.description == "Original tool."
- # The transformed tool should have 'q' instead of 'query'
- assert "q" in sampling_tool.parameters.get("properties", {})
- assert "limit" in sampling_tool.parameters.get("properties", {})
-
- async def test_from_function_tool_execution(self):
- """Test that converted FunctionTool executes correctly."""
-
- def add(a: int, b: int) -> int:
- """Add two numbers."""
- return a + b
-
- function_tool = FunctionTool.from_function(add)
- sampling_tool = SamplingTool.from_callable_tool(function_tool)
-
- result = await sampling_tool.run({"a": 2, "b": 3})
- assert result == 5
-
- async def test_from_transformed_tool_execution(self):
- """Test that converted TransformedTool executes correctly."""
-
- def multiply(x: int, y: int) -> int:
- """Multiply two numbers."""
- return x * y
-
- function_tool = FunctionTool.from_function(multiply)
- transformed_tool = TransformedTool.from_tool(
- function_tool,
- transform_args={"x": ArgTransform(name="a"), "y": ArgTransform(name="b")},
- )
-
- sampling_tool = SamplingTool.from_callable_tool(transformed_tool)
-
- # Use the transformed parameter names
- result = await sampling_tool.run({"a": 3, "b": 4})
- # Result should be unwrapped from ToolResult
- assert result == 12
-
- def test_from_invalid_tool_type(self):
- """Test that from_callable_tool rejects non-tool objects."""
-
- class NotATool:
- pass
-
- with pytest.raises(
- TypeError,
- match="Expected FunctionTool or TransformedTool",
- ):
- SamplingTool.from_callable_tool(NotATool()) # type: ignore[arg-type] # ty:ignore[invalid-argument-type]
-
- def test_from_plain_function_fails(self):
- """Test that plain functions are rejected by from_callable_tool."""
-
- def my_function():
- pass
-
- with pytest.raises(TypeError, match="Expected FunctionTool or TransformedTool"):
- SamplingTool.from_callable_tool(my_function) # type: ignore[arg-type] # ty:ignore[invalid-argument-type]
-
- async def test_from_function_tool_with_output_schema(self):
- """Test that FunctionTool with output_schema is handled correctly."""
-
- def search(query: str) -> dict:
- """Search for something."""
- return {"results": ["item1", "item2"], "count": 2}
-
- # Create FunctionTool with x-fastmcp-wrap-result
- function_tool = FunctionTool.from_function(
- search,
- output_schema={
- "type": "object",
- "properties": {
- "results": {"type": "array"},
- "count": {"type": "integer"},
- },
- "x-fastmcp-wrap-result": True,
- },
- )
-
- sampling_tool = SamplingTool.from_callable_tool(function_tool)
-
- # Run the tool - should unwrap the {"result": {...}} wrapper
- result = await sampling_tool.run({"query": "test"})
-
- # Should get the unwrapped dict, not ToolResult
- assert isinstance(result, dict)
- assert result == {"results": ["item1", "item2"], "count": 2}
-
- async def test_from_function_tool_without_wrap_result(self):
- """Test that FunctionTool without x-fastmcp-wrap-result is handled correctly."""
-
- def get_data() -> dict:
- """Get some data."""
- return {"status": "ok", "value": 42}
-
- # Create FunctionTool with output_schema but no wrap-result flag
- function_tool = FunctionTool.from_function(
- get_data,
- output_schema={
- "type": "object",
- "properties": {
- "status": {"type": "string"},
- "value": {"type": "integer"},
- },
- },
- )
-
- sampling_tool = SamplingTool.from_callable_tool(function_tool)
-
- # Run the tool - should return structured_content directly
- result = await sampling_tool.run({})
-
- assert isinstance(result, dict)
- assert result == {"status": "ok", "value": 42}
-
-
-class TestSamplingToolAuthEnforcement:
- """Tests that auth-protected tools enforce auth when used via sampling."""
-
- async def test_auth_protected_tool_blocked_without_token(self):
- """An auth-protected tool wrapped as SamplingTool must reject
- calls when no valid token is present in a non-stdio transport."""
-
- def secret_action() -> str:
- """Do something privileged."""
- return "secret"
-
- function_tool = FunctionTool.from_function(
- secret_action,
- auth=require_scopes("admin"),
- )
- sampling_tool = SamplingTool.from_callable_tool(function_tool)
-
- transport_token = _current_transport.set("streamable-http")
- try:
- with pytest.raises(AuthorizationError, match="insufficient permissions"):
- await sampling_tool.run({})
- finally:
- _current_transport.reset(transport_token)
-
- async def test_auth_protected_tool_blocked_with_wrong_scopes(self):
- """An auth-protected tool rejects calls when the token lacks
- the required scopes."""
-
- def secret_action() -> str:
- """Do something privileged."""
- return "secret"
-
- function_tool = FunctionTool.from_function(
- secret_action,
- auth=require_scopes("admin"),
- )
- sampling_tool = SamplingTool.from_callable_tool(function_tool)
-
- token = AccessToken(
- token="test",
- client_id="c",
- scopes=["read"],
- expires_at=None,
- claims={},
- )
- transport_token = _current_transport.set("streamable-http")
- auth_token = auth_context_var.set(AuthenticatedUser(token))
- try:
- with pytest.raises(AuthorizationError, match="insufficient permissions"):
- await sampling_tool.run({})
- finally:
- auth_context_var.reset(auth_token)
- _current_transport.reset(transport_token)
-
- async def test_auth_protected_tool_allowed_with_correct_scopes(self):
- """An auth-protected tool succeeds when the token has the
- required scopes."""
-
- def secret_action() -> str:
- """Do something privileged."""
- return "secret"
-
- function_tool = FunctionTool.from_function(
- secret_action,
- auth=require_scopes("admin"),
- )
- sampling_tool = SamplingTool.from_callable_tool(function_tool)
-
- token = AccessToken(
- token="test",
- client_id="c",
- scopes=["admin"],
- expires_at=None,
- claims={},
- )
- transport_token = _current_transport.set("streamable-http")
- auth_token = auth_context_var.set(AuthenticatedUser(token))
- try:
- result = await sampling_tool.run({})
- assert result == "secret"
- finally:
- auth_context_var.reset(auth_token)
- _current_transport.reset(transport_token)
-
- async def test_auth_protected_tool_skipped_on_stdio(self):
- """Auth checks are skipped for stdio transport, matching
- server dispatcher behavior."""
-
- def secret_action() -> str:
- """Do something privileged."""
- return "secret"
-
- function_tool = FunctionTool.from_function(
- secret_action,
- auth=require_scopes("admin"),
- )
- sampling_tool = SamplingTool.from_callable_tool(function_tool)
-
- transport_token = _current_transport.set("stdio")
- try:
- result = await sampling_tool.run({})
- assert result == "secret"
- finally:
- _current_transport.reset(transport_token)
-
- async def test_tool_without_auth_runs_normally(self):
- """Tools without auth still run without any auth context."""
-
- def public_action() -> str:
- """Do something public."""
- return "public"
-
- function_tool = FunctionTool.from_function(public_action)
- sampling_tool = SamplingTool.from_callable_tool(function_tool)
-
- result = await sampling_tool.run({})
- assert result == "public"
-
- async def test_auth_protected_transformed_tool_blocked(self):
- """Auth checks also apply to TransformedTools with auth."""
-
- def secret_action(x: int) -> int:
- """Privileged computation."""
- return x * 2
-
- function_tool = FunctionTool.from_function(
- secret_action,
- auth=require_scopes("compute"),
- )
- transformed_tool = TransformedTool.from_tool(
- function_tool,
- transform_args={"x": ArgTransform(name="value")},
- )
- sampling_tool = SamplingTool.from_callable_tool(transformed_tool)
-
- transport_token = _current_transport.set("streamable-http")
- try:
- with pytest.raises(AuthorizationError, match="insufficient permissions"):
- await sampling_tool.run({"value": 5})
- finally:
- _current_transport.reset(transport_token)
diff --git a/tests/server/telemetry/test_sampling_tracing.py b/tests/server/telemetry/test_sampling_tracing.py
deleted file mode 100644
index ffd3f19f8..000000000
--- a/tests/server/telemetry/test_sampling_tracing.py
+++ /dev/null
@@ -1,881 +0,0 @@
-"""Tracing coverage for sampling create_message and tool-execution spans.
-
-Regression focus: the `sampling create_message` span is created with
-`record_exception=False, set_status_on_exception=False` and records the
-exception manually in its `except` block. A failed sampling call must
-therefore produce exactly ONE exception event, not two.
-
-`ctx.sample` requires the server to send a request down to the client, which
-only the older protocol's back-channel supports, so every client below pins
-`mode="legacy"`.
-"""
-
-from __future__ import annotations
-
-import pytest
-from mcp_types import TextContent
-from opentelemetry.context import Context as OTelContext
-from opentelemetry.sdk.trace import (
- ReadableSpan,
- Span,
- SpanLimits,
- SpanProcessor,
- TracerProvider,
-)
-from opentelemetry.sdk.trace.export import SimpleSpanProcessor
-from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
-from opentelemetry.sdk.trace.sampling import Decision, Sampler, SamplingResult
-from opentelemetry.trace import StatusCode
-from opentelemetry.util import types as otel_types
-
-from fastmcp import Client, Context, FastMCP
-from fastmcp.client.sampling import RequestContext, SamplingMessage, SamplingParams
-
-
-class OnStartRecorder(SpanProcessor):
- def __init__(self) -> None:
- self.attributes: dict[str, dict[str, object]] = {}
-
- def on_start(self, span: Span, parent_context: OTelContext | None = None) -> None:
- self.attributes[span.name] = dict(span.attributes or {})
-
-
-class NonForwardingSampler(Sampler):
- """Samples every span but never forwards the attributes it was handed.
-
- See `tests/telemetry/test_span_attributes.py` for the full explanation:
- OTel's `Tracer.start_span` builds the finished span from
- `sampling_result.attributes`, not from the `attributes` kwarg passed to
- `start_as_current_span`, so a custom sampler like this one reproduces the
- regression where a non-forwarding sampler silently drops FastMCP's
- attributes.
- """
-
- def should_sample(
- self,
- parent_context: OTelContext | None,
- trace_id: int,
- name: str,
- kind: object = None,
- attributes: object = None,
- links: object = None,
- trace_state: object = None,
- ) -> SamplingResult:
- return SamplingResult(Decision.RECORD_AND_SAMPLE)
-
- def get_description(self) -> str:
- return "NonForwardingSampler"
-
-
-class RedactingSampler(Sampler):
- """Forwards the attributes it receives, but replaces `mcp.method.name`.
-
- See `tests/telemetry/test_span_attributes.py` for the full explanation:
- a sampler can legitimately keep an attribute FastMCP set while replacing
- its value (e.g. redacting the method name for privacy), and that decision
- must survive the restore step.
- """
-
- def should_sample(
- self,
- parent_context: OTelContext | None,
- trace_id: int,
- name: str,
- kind: object = None,
- attributes: otel_types.Attributes = None,
- links: object = None,
- trace_state: object = None,
- ) -> SamplingResult:
- forwarded = dict(attributes or {})
- forwarded["mcp.method.name"] = "REDACTED"
- return SamplingResult(Decision.RECORD_AND_SAMPLE, attributes=forwarded)
-
- def get_description(self) -> str:
- return "RedactingSampler"
-
-
-class AttributeAddingSampler(Sampler):
- """Forwards the attributes it receives unchanged and adds its own."""
-
- def should_sample(
- self,
- parent_context: OTelContext | None,
- trace_id: int,
- name: str,
- kind: object = None,
- attributes: otel_types.Attributes = None,
- links: object = None,
- trace_state: object = None,
- ) -> SamplingResult:
- forwarded = dict(attributes or {})
- forwarded["sampling.policy"] = "always_on"
- return SamplingResult(Decision.RECORD_AND_SAMPLE, attributes=forwarded)
-
- def get_description(self) -> str:
- return "AttributeAddingSampler"
-
-
-class FilteringSampler(Sampler):
- """Discards every attribute it receives and substitutes its own.
-
- See `tests/telemetry/test_span_attributes.py` for the full explanation:
- a sampler can legitimately supply only its own attributes (e.g. to strip
- component names or resource URIs for privacy or cardinality control),
- and the restore step must not reintroduce FastMCP's attributes in that
- case — doing so would defeat the filter.
- """
-
- def should_sample(
- self,
- parent_context: OTelContext | None,
- trace_id: int,
- name: str,
- kind: object = None,
- attributes: otel_types.Attributes = None,
- links: object = None,
- trace_state: object = None,
- ) -> SamplingResult:
- return SamplingResult(
- Decision.RECORD_AND_SAMPLE, attributes={"sampling.policy": "filtered"}
- )
-
- def get_description(self) -> str:
- return "FilteringSampler"
-
-
-def on_start_recorder(
- monkeypatch: pytest.MonkeyPatch,
- trace_exporter: InMemorySpanExporter,
-) -> OnStartRecorder:
- recorder = OnStartRecorder()
- provider = TracerProvider()
- provider.add_span_processor(recorder)
- provider.add_span_processor(SimpleSpanProcessor(trace_exporter))
- tracer = provider.get_tracer("test")
- monkeypatch.setattr("fastmcp.server.sampling.run.get_tracer", lambda: tracer)
- return recorder
-
-
-def _spans_named(exporter: InMemorySpanExporter, name: str):
- return [s for s in exporter.get_finished_spans() if s.name == name]
-
-
-def _exception_events(span):
- return [e for e in span.events if e.name == "exception"]
-
-
-class TestSamplingCreateMessageSpan:
- async def test_success_creates_span_with_attributes(
- self,
- trace_exporter: InMemorySpanExporter,
- on_start_recorder: OnStartRecorder,
- ):
- def sampling_handler(
- messages: list[SamplingMessage],
- params: SamplingParams,
- ctx: RequestContext,
- ) -> str:
- return "sampled-text"
-
- mcp = FastMCP("sampling-server")
-
- @mcp.tool
- async def ask(question: str, context: Context) -> str:
- result = await context.sample(messages=question)
- return result.text or ""
-
- async with Client(
- mcp, mode="legacy", sampling_handler=sampling_handler
- ) as client:
- await client.call_tool("ask", {"question": "hi"})
-
- spans = _spans_named(trace_exporter, "sampling create_message")
- assert len(spans) == 1
- span = spans[0]
- assert span.attributes is not None
- assert span.attributes["mcp.method.name"] == "sampling/createMessage"
- assert span.attributes["fastmcp.server.name"] == "sampling-server"
- assert on_start_recorder.attributes["sampling create_message"] == {
- "mcp.method.name": "sampling/createMessage",
- "fastmcp.server.name": "sampling-server",
- }
- # Success path must not record any exception.
- assert _exception_events(span) == []
- assert span.status.status_code != StatusCode.ERROR
-
- async def test_failure_records_exception_exactly_once(
- self, trace_exporter: InMemorySpanExporter
- ):
- """Regression: span created with record_exception=False so the manual
- record_exception in the except block fires exactly once (no duplicate
- exception events from OTel auto-recording on `with` exit)."""
-
- def sampling_handler(
- messages: list[SamplingMessage],
- params: SamplingParams,
- ctx: RequestContext,
- ) -> str:
- raise RuntimeError("sampling boom")
-
- mcp = FastMCP("sampling-server")
-
- @mcp.tool
- async def ask(question: str, context: Context) -> str:
- result = await context.sample(messages=question)
- return result.text or ""
-
- with pytest.raises(Exception):
- async with Client(
- mcp, mode="legacy", sampling_handler=sampling_handler
- ) as client:
- await client.call_tool("ask", {"question": "hi"})
-
- spans = _spans_named(trace_exporter, "sampling create_message")
- assert len(spans) == 1
- span = spans[0]
- assert span.status.status_code == StatusCode.ERROR
- assert span.attributes is not None
- assert "error.type" in span.attributes
- # The whole point of the fix: exactly one exception event.
- assert len(_exception_events(span)) == 1
-
-
-class TestSamplingToolSpan:
- async def test_tool_error_span_records_exception_once(
- self,
- trace_exporter: InMemorySpanExporter,
- on_start_recorder: OnStartRecorder,
- ):
- from mcp_types import CreateMessageResultWithTools, ToolUseContent
-
- call_count = 0
-
- def boom_tool() -> str:
- raise ValueError("tool exploded")
-
- def sampling_handler(
- messages: list[SamplingMessage],
- params: SamplingParams,
- ctx: RequestContext,
- ) -> CreateMessageResultWithTools:
- nonlocal call_count
- call_count += 1
- if call_count == 1:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_1",
- name="boom_tool",
- input={},
- )
- ],
- model="test-model",
- stop_reason="toolUse",
- )
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text="done")],
- model="test-model",
- stop_reason="endTurn",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def driver(context: Context) -> str:
- result = await context.sample(messages="go", tools=[boom_tool])
- return result.text or ""
-
- async with Client(mcp) as client:
- await client.call_tool("driver", {})
-
- spans = _spans_named(trace_exporter, "sampling tool boom_tool")
- assert len(spans) == 1
- span = spans[0]
- assert span.status.status_code == StatusCode.ERROR
- assert span.attributes is not None
- assert span.attributes["gen_ai.tool.name"] == "boom_tool"
- assert on_start_recorder.attributes["sampling tool boom_tool"] == {
- "gen_ai.tool.name": "boom_tool",
- "fastmcp.tool.use_id": "call_1",
- }
- assert "error.type" in span.attributes
- # Tool spans catch-and-convert (no re-raise), so OTel auto-recording
- # never fires; the manual record_exception must fire exactly once.
- assert len(_exception_events(span)) == 1
-
-
-class TestAttributesSurviveANonForwardingSampler:
- """Regression: `sampling create_message` and `sampling tool ...` spans
- must keep FastMCP's attributes even when the configured Sampler doesn't
- forward the `attributes` it was handed to its `SamplingResult`.
- """
-
- @pytest.fixture
- def non_forwarding_recorder(
- self,
- monkeypatch: pytest.MonkeyPatch,
- trace_exporter: InMemorySpanExporter,
- ) -> OnStartRecorder:
- recorder = OnStartRecorder()
- provider = TracerProvider(sampler=NonForwardingSampler())
- provider.add_span_processor(recorder)
- provider.add_span_processor(SimpleSpanProcessor(trace_exporter))
- tracer = provider.get_tracer("test")
- monkeypatch.setattr("fastmcp.server.sampling.run.get_tracer", lambda: tracer)
- return recorder
-
- async def test_create_message_span_keeps_attributes(
- self,
- trace_exporter: InMemorySpanExporter,
- non_forwarding_recorder: OnStartRecorder,
- ):
- def sampling_handler(
- messages: list[SamplingMessage],
- params: SamplingParams,
- ctx: RequestContext,
- ) -> str:
- return "sampled-text"
-
- mcp = FastMCP("sampling-server")
-
- @mcp.tool
- async def ask(question: str, context: Context) -> str:
- result = await context.sample(messages=question)
- return result.text or ""
-
- async with Client(
- mcp, mode="legacy", sampling_handler=sampling_handler
- ) as client:
- await client.call_tool("ask", {"question": "hi"})
-
- spans = _spans_named(trace_exporter, "sampling create_message")
- assert len(spans) == 1
- span = spans[0]
- assert span.attributes is not None
- assert span.attributes["mcp.method.name"] == "sampling/createMessage"
- assert span.attributes["fastmcp.server.name"] == "sampling-server"
- # The sampler never forwards attributes, so on_start legitimately sees
- # none — this documents that limitation rather than asserting around it.
- assert non_forwarding_recorder.attributes["sampling create_message"] == {}
-
- async def test_sampling_tool_span_keeps_attributes(
- self,
- trace_exporter: InMemorySpanExporter,
- non_forwarding_recorder: OnStartRecorder,
- ):
- from mcp_types import CreateMessageResultWithTools, ToolUseContent
-
- def echo_tool(text: str) -> str:
- return text
-
- call_count = 0
-
- def sampling_handler(
- messages: list[SamplingMessage],
- params: SamplingParams,
- ctx: RequestContext,
- ) -> CreateMessageResultWithTools:
- nonlocal call_count
- call_count += 1
- if call_count == 1:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_1",
- name="echo_tool",
- input={"text": "hi"},
- )
- ],
- model="test-model",
- stop_reason="toolUse",
- )
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text="done")],
- model="test-model",
- stop_reason="endTurn",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def driver(context: Context) -> str:
- result = await context.sample(messages="go", tools=[echo_tool])
- return result.text or ""
-
- async with Client(mcp) as client:
- await client.call_tool("driver", {})
-
- spans = _spans_named(trace_exporter, "sampling tool echo_tool")
- assert len(spans) == 1
- span = spans[0]
- assert span.attributes is not None
- assert span.attributes["gen_ai.tool.name"] == "echo_tool"
- assert span.attributes["fastmcp.tool.use_id"] == "call_1"
- # The sampler never forwards attributes, so on_start legitimately sees
- # none — this documents that limitation rather than asserting around it.
- assert non_forwarding_recorder.attributes["sampling tool echo_tool"] == {}
-
-
-class TestAttributeRestoreRespectsSampler:
- """Restoring missing attributes must not clobber attributes a sampler
- deliberately kept and modified, must coexist with attributes a sampler
- adds of its own, and must not fire at all when a sampler supplies only
- its own attributes and drops FastMCP's entirely."""
-
- @pytest.fixture
- def redacting_tracer(
- self, monkeypatch: pytest.MonkeyPatch, trace_exporter: InMemorySpanExporter
- ) -> None:
- provider = TracerProvider(sampler=RedactingSampler())
- provider.add_span_processor(SimpleSpanProcessor(trace_exporter))
- tracer = provider.get_tracer("test")
- monkeypatch.setattr("fastmcp.server.sampling.run.get_tracer", lambda: tracer)
-
- @pytest.fixture
- def attribute_adding_tracer(
- self, monkeypatch: pytest.MonkeyPatch, trace_exporter: InMemorySpanExporter
- ) -> None:
- provider = TracerProvider(sampler=AttributeAddingSampler())
- provider.add_span_processor(SimpleSpanProcessor(trace_exporter))
- tracer = provider.get_tracer("test")
- monkeypatch.setattr("fastmcp.server.sampling.run.get_tracer", lambda: tracer)
-
- @pytest.fixture
- def filtering_tracer(
- self, monkeypatch: pytest.MonkeyPatch, trace_exporter: InMemorySpanExporter
- ) -> None:
- provider = TracerProvider(sampler=FilteringSampler())
- provider.add_span_processor(SimpleSpanProcessor(trace_exporter))
- tracer = provider.get_tracer("test")
- monkeypatch.setattr("fastmcp.server.sampling.run.get_tracer", lambda: tracer)
-
- async def test_create_message_span_keeps_redacted_value(
- self,
- trace_exporter: InMemorySpanExporter,
- redacting_tracer: None,
- ):
- def sampling_handler(
- messages: list[SamplingMessage],
- params: SamplingParams,
- ctx: RequestContext,
- ) -> str:
- return "sampled-text"
-
- mcp = FastMCP("sampling-server")
-
- @mcp.tool
- async def ask(question: str, context: Context) -> str:
- result = await context.sample(messages=question)
- return result.text or ""
-
- async with Client(
- mcp, mode="legacy", sampling_handler=sampling_handler
- ) as client:
- await client.call_tool("ask", {"question": "hi"})
-
- spans = _spans_named(trace_exporter, "sampling create_message")
- assert len(spans) == 1
- span = spans[0]
- assert span.attributes is not None
- # The redaction survives — it must not be overwritten by a restore.
- assert span.attributes["mcp.method.name"] == "REDACTED"
- # Attributes the sampler didn't touch are still present.
- assert span.attributes["fastmcp.server.name"] == "sampling-server"
-
- async def test_create_message_span_keeps_sampler_added_attribute(
- self,
- trace_exporter: InMemorySpanExporter,
- attribute_adding_tracer: None,
- ):
- def sampling_handler(
- messages: list[SamplingMessage],
- params: SamplingParams,
- ctx: RequestContext,
- ) -> str:
- return "sampled-text"
-
- mcp = FastMCP("sampling-server")
-
- @mcp.tool
- async def ask(question: str, context: Context) -> str:
- result = await context.sample(messages=question)
- return result.text or ""
-
- async with Client(
- mcp, mode="legacy", sampling_handler=sampling_handler
- ) as client:
- await client.call_tool("ask", {"question": "hi"})
-
- spans = _spans_named(trace_exporter, "sampling create_message")
- assert len(spans) == 1
- span = spans[0]
- assert span.attributes is not None
- assert span.attributes["sampling.policy"] == "always_on"
- assert span.attributes["mcp.method.name"] == "sampling/createMessage"
- assert span.attributes["fastmcp.server.name"] == "sampling-server"
-
- async def test_tool_span_keeps_redacted_value(
- self,
- trace_exporter: InMemorySpanExporter,
- redacting_tracer: None,
- ):
- from mcp_types import CreateMessageResultWithTools, ToolUseContent
-
- def echo_tool(text: str) -> str:
- return text
-
- call_count = 0
-
- def sampling_handler(
- messages: list[SamplingMessage],
- params: SamplingParams,
- ctx: RequestContext,
- ) -> CreateMessageResultWithTools:
- nonlocal call_count
- call_count += 1
- if call_count == 1:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_1",
- name="echo_tool",
- input={"text": "hi"},
- )
- ],
- model="test-model",
- stop_reason="toolUse",
- )
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text="done")],
- model="test-model",
- stop_reason="endTurn",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def driver(context: Context) -> str:
- result = await context.sample(messages="go", tools=[echo_tool])
- return result.text or ""
-
- async with Client(mcp) as client:
- await client.call_tool("driver", {})
-
- spans = _spans_named(trace_exporter, "sampling tool echo_tool")
- assert len(spans) == 1
- span = spans[0]
- assert span.attributes is not None
- # RedactingSampler only touches mcp.method.name, which this span
- # doesn't set — its attributes are forwarded unchanged, confirming
- # the restore step doesn't disturb them either.
- assert span.attributes["gen_ai.tool.name"] == "echo_tool"
- assert span.attributes["fastmcp.tool.use_id"] == "call_1"
-
- async def test_tool_span_keeps_sampler_added_attribute(
- self,
- trace_exporter: InMemorySpanExporter,
- attribute_adding_tracer: None,
- ):
- from mcp_types import CreateMessageResultWithTools, ToolUseContent
-
- def echo_tool(text: str) -> str:
- return text
-
- call_count = 0
-
- def sampling_handler(
- messages: list[SamplingMessage],
- params: SamplingParams,
- ctx: RequestContext,
- ) -> CreateMessageResultWithTools:
- nonlocal call_count
- call_count += 1
- if call_count == 1:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_1",
- name="echo_tool",
- input={"text": "hi"},
- )
- ],
- model="test-model",
- stop_reason="toolUse",
- )
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text="done")],
- model="test-model",
- stop_reason="endTurn",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def driver(context: Context) -> str:
- result = await context.sample(messages="go", tools=[echo_tool])
- return result.text or ""
-
- async with Client(mcp) as client:
- await client.call_tool("driver", {})
-
- spans = _spans_named(trace_exporter, "sampling tool echo_tool")
- assert len(spans) == 1
- span = spans[0]
- assert span.attributes is not None
- assert span.attributes["sampling.policy"] == "always_on"
- assert span.attributes["gen_ai.tool.name"] == "echo_tool"
- assert span.attributes["fastmcp.tool.use_id"] == "call_1"
-
- async def test_create_message_span_filtered_attributes_are_not_restored(
- self,
- trace_exporter: InMemorySpanExporter,
- filtering_tracer: None,
- ):
- """Regression: a sampler that intentionally supplies only its own
- attributes must not have FastMCP's attributes restored on top."""
-
- def sampling_handler(
- messages: list[SamplingMessage],
- params: SamplingParams,
- ctx: RequestContext,
- ) -> str:
- return "sampled-text"
-
- mcp = FastMCP("sampling-server")
-
- @mcp.tool
- async def ask(question: str, context: Context) -> str:
- result = await context.sample(messages=question)
- return result.text or ""
-
- async with Client(
- mcp, mode="legacy", sampling_handler=sampling_handler
- ) as client:
- await client.call_tool("ask", {"question": "hi"})
-
- spans = _spans_named(trace_exporter, "sampling create_message")
- assert len(spans) == 1
- span = spans[0]
- assert dict(span.attributes or {}) == {"sampling.policy": "filtered"}
-
- async def test_tool_span_filtered_attributes_are_not_restored(
- self,
- trace_exporter: InMemorySpanExporter,
- filtering_tracer: None,
- ):
- """Regression: a sampler that intentionally supplies only its own
- attributes must not have FastMCP's attributes restored on top."""
- from mcp_types import CreateMessageResultWithTools, ToolUseContent
-
- def echo_tool(text: str) -> str:
- return text
-
- call_count = 0
-
- def sampling_handler(
- messages: list[SamplingMessage],
- params: SamplingParams,
- ctx: RequestContext,
- ) -> CreateMessageResultWithTools:
- nonlocal call_count
- call_count += 1
- if call_count == 1:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_1",
- name="echo_tool",
- input={"text": "hi"},
- )
- ],
- model="test-model",
- stop_reason="toolUse",
- )
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text="done")],
- model="test-model",
- stop_reason="endTurn",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def driver(context: Context) -> str:
- result = await context.sample(messages="go", tools=[echo_tool])
- return result.text or ""
-
- async with Client(mcp) as client:
- await client.call_tool("driver", {})
-
- spans = _spans_named(trace_exporter, "sampling tool echo_tool")
- assert len(spans) == 1
- span = spans[0]
- assert dict(span.attributes or {}) == {"sampling.policy": "filtered"}
-
-
-class TestRestoreDoesNotChurnAttributeLimitEvictions:
- """Regression: under a low `OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT`, the restore
- step in `fastmcp.server.sampling.run` must not reinsert an attribute the
- SDK's bounded attribute map already evicted.
-
- See `tests/telemetry/test_span_attributes.py::
- test_restore_does_not_churn_sdk_attribute_limit_evictions` for the full
- explanation: an evicted key looks identical to a sampler-omitted one from
- inside the restore helper, so reinserting it churns which attributes the
- SDK ultimately retains and inflates `dropped_attributes` beyond what the
- limit alone already cost. This proves the same discriminator holds
- end-to-end through the real sampling call path, not just at the helper
- level.
- """
-
- @staticmethod
- async def _run_create_message(
- span_limits: SpanLimits, *, stub_restore: bool
- ) -> ReadableSpan:
- with pytest.MonkeyPatch.context() as mp:
- exporter = InMemorySpanExporter()
- provider = TracerProvider(span_limits=span_limits)
- provider.add_span_processor(SimpleSpanProcessor(exporter))
- tracer = provider.get_tracer("test")
- mp.setattr("fastmcp.server.sampling.run.get_tracer", lambda: tracer)
- if stub_restore:
- mp.setattr(
- "fastmcp.server.sampling.run.restore_dropped_attributes",
- lambda span, attrs: None,
- )
-
- def sampling_handler(
- messages: list[SamplingMessage],
- params: SamplingParams,
- ctx: RequestContext,
- ) -> str:
- return "sampled-text"
-
- mcp = FastMCP("sampling-server")
-
- @mcp.tool
- async def ask(question: str, context: Context) -> str:
- result = await context.sample(messages=question)
- return result.text or ""
-
- async with Client(
- mcp, mode="legacy", sampling_handler=sampling_handler
- ) as client:
- await client.call_tool("ask", {"question": "hi"})
-
- spans = _spans_named(exporter, "sampling create_message")
- assert len(spans) == 1
- return spans[0]
-
- @staticmethod
- async def _run_tool_span(
- span_limits: SpanLimits, *, stub_restore: bool
- ) -> ReadableSpan:
- from mcp_types import CreateMessageResultWithTools, ToolUseContent
-
- with pytest.MonkeyPatch.context() as mp:
- exporter = InMemorySpanExporter()
- provider = TracerProvider(span_limits=span_limits)
- provider.add_span_processor(SimpleSpanProcessor(exporter))
- tracer = provider.get_tracer("test")
- mp.setattr("fastmcp.server.sampling.run.get_tracer", lambda: tracer)
- if stub_restore:
- mp.setattr(
- "fastmcp.server.sampling.run.restore_dropped_attributes",
- lambda span, attrs: None,
- )
-
- def echo_tool(text: str) -> str:
- return text
-
- call_count = 0
-
- def sampling_handler(
- messages: list[SamplingMessage],
- params: SamplingParams,
- ctx: RequestContext,
- ) -> CreateMessageResultWithTools:
- nonlocal call_count
- call_count += 1
- if call_count == 1:
- return CreateMessageResultWithTools(
- role="assistant",
- content=[
- ToolUseContent(
- type="tool_use",
- id="call_1",
- name="echo_tool",
- input={"text": "hi"},
- )
- ],
- model="test-model",
- stop_reason="toolUse",
- )
- return CreateMessageResultWithTools(
- role="assistant",
- content=[TextContent(type="text", text="done")],
- model="test-model",
- stop_reason="endTurn",
- )
-
- mcp = FastMCP(sampling_handler=sampling_handler)
-
- @mcp.tool
- async def driver(context: Context) -> str:
- result = await context.sample(messages="go", tools=[echo_tool])
- return result.text or ""
-
- async with Client(mcp) as client:
- await client.call_tool("driver", {})
-
- spans = _spans_named(exporter, "sampling tool echo_tool")
- assert len(spans) == 1
- return spans[0]
-
- async def test_create_message_span(self, monkeypatch: pytest.MonkeyPatch):
- # Two attributes on this span (`mcp.method.name`, `fastmcp.server.name`)
- # — a limit of 1 guarantees eviction.
- monkeypatch.setenv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT", "1")
- span_limits = SpanLimits()
- assert span_limits.max_span_attributes == 1
-
- baseline = await self._run_create_message(span_limits, stub_restore=True)
- # The whole test is moot if the limit didn't actually bind.
- assert baseline.dropped_attributes > 0
-
- with_restore = await self._run_create_message(span_limits, stub_restore=False)
-
- assert dict(with_restore.attributes or {}) == dict(baseline.attributes or {})
- assert with_restore.dropped_attributes == baseline.dropped_attributes
-
- async def test_tool_span(self, monkeypatch: pytest.MonkeyPatch):
- # Two attributes on this span (`gen_ai.tool.name`, `fastmcp.tool.use_id`)
- # — a limit of 1 guarantees eviction.
- monkeypatch.setenv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT", "1")
- span_limits = SpanLimits()
- assert span_limits.max_span_attributes == 1
-
- baseline = await self._run_tool_span(span_limits, stub_restore=True)
- # The whole test is moot if the limit didn't actually bind.
- assert baseline.dropped_attributes > 0
-
- with_restore = await self._run_tool_span(span_limits, stub_restore=False)
-
- assert dict(with_restore.attributes or {}) == dict(baseline.attributes or {})
- assert with_restore.dropped_attributes == baseline.dropped_attributes