π The fast, Pythonic way to build MCP servers and clients.
Fix sampling from background tasks (#4068)
cuyua90b59af94897b
diff --git a/src/fastmcp/server/sampling/run.py b/src/fastmcp/server/sampling/run.pyindex c45163fa7..385c2e315 100644--- a/src/fastmcp/server/sampling/run.py+++ b/src/fastmcp/server/sampling/run.py@@ -536,7 +536,7 @@ async def sample_step_impl(model_preferences=_parse_model_preferences(model_preferences),tools=sdk_tools,tool_choice=effective_tool_choice,- related_request_id=context.request_id,+ related_request_id=context.origin_request_id,)# Check if this is a tool use responsediff --git a/tests/server/tasks/test_context_background_task.py b/tests/server/tasks/test_context_background_task.pyindex 40e9ddb90..467668e6c 100644--- a/tests/server/tasks/test_context_background_task.py+++ b/tests/server/tasks/test_context_background_task.py@@ -15,6 +15,7 @@ import pytestfrom mcp import ServerSessionfrom mcp.server.auth.middleware.auth_context import auth_context_varfrom mcp.server.auth.middleware.bearer_auth import AuthenticatedUser+from mcp.types import CreateMessageResult, TextContentfrom pydantic import BaseModelfrom fastmcp import FastMCP@@ -283,6 +284,35 @@ class TestBackgroundTaskIntegration:result = await task.result()assert result.data == "ok"+ async def test_sample_uses_origin_request_id_in_background_task(self):+ """E2E: ctx.sample() works in a task without an active request context."""+ mcp = FastMCP("sample-background-test")+ captured: dict[str, object] = {}++ @mcp.tool(task=True)+ async def ask_client(ctx: Context) -> str:+ assert ctx.is_background_task is True+ assert ctx.request_context is None+ assert ctx.origin_request_id is not None+ result = await ctx.sample("Say hello")+ return result.text or ""++ def sampling_handler(messages, params, ctx):+ captured["called"] = True+ return CreateMessageResult(+ role="assistant",+ content=TextContent(type="text", text="hello from background"),+ model="test-model",+ stopReason="endTurn",+ )++ async with Client(mcp, sampling_handler=sampling_handler) as client:+ task = await client.call_tool("ask_client", {}, task=True)+ result = await task.result()++ assert result.data == "hello from background"+ assert captured["called"] is True+async def test_elicit_accept_flow(self):"""E2E: tool elicits input, client accepts via elicitation_handler."""mcp = FastMCP("elicit-accept-test")