fix(mcp): trace fastmcp 3 background (task) tool executions
Problem
Since #4710, fastmcp 3 server-side tool calls are traced by wrapping Tool._run. When a tool is called as a background task (task_meta set), _run only submits the task and returns a CreateTaskResult, so the wrapper deliberately skips it to avoid recording a submission as a tool run.
The tool then runs later in the docket worker, which does not go through Tool._run:
FunctionTool.register_with_docketregisters the underlying function:docket.register(self.fn, names=[self.key])(fastmcp 3.2.0 and 3.4.11).- The base
Tool.register_with_docketregistersself.run.
So a tool executed as a background task produces no mcp.server / <tool>.tool span pair. Its duration, output and failures go unrecorded.
This is a gap, not a regression. fastmcp 3 wasn't traced at all before #4710, and background tasks need fastmcp's optional tasks extra (pydocket).
Proposed fix
- Hook worker-side execution, for example by wrapping
register_with_docket/docket.registerso the registered callable runs inside_trace_tool_call. Do this for bothFunctionTool(registersfn) and the baseTool(registersrun). - Keep task submission (
Tool._runwithtask_meta) untraced, as it is now. - Attribute the spans to the right server and propagate trace context from the submitting request if possible.
- Add a test for a background task that completes, not just the rejected-submission case in
test_fastmcp_task_submission_is_not_traced_as_a_tool_run.
Raised by CodeRabbit on #4710: https://github.com/traceloop/openllmetry/pull/4710#discussion_r4590071640
🤖 Generated with Claude Code
I'd like to pick this up.
My plan is to hook worker-side execution (register_with_docket / docket.register) for both FunctionTool and base Tool so background runs execute inside _trace_tool_call while keeping Tool._run task submission untraced, propagate trace context from submission if pydocket supports it, and add a test covering a completed background task.
Since #4710 is still open, I'll prototype off its branch and open the PR once #4710 lands (unless you'd prefer a stacked PR targeting #4710's branch).