Skip to content

fastmcp tool func block asyncio #1839

Description

@archever

Initial Checks

Description

unlike fastapi, fastmcp run sync tool func directly. this may block async loop if the func uses block io like requests

fastmcp

classFuncMetadata(BaseModel):
...
asyncdefcall_fn_with_arg_validation(
self,
fn: Callable[..., Any|Awaitable[Any]],
fn_is_async: bool,
arguments_to_validate: dict[str, Any],
arguments_to_pass_directly: dict[str, Any] |None,
) ->Any:
"""Call the given function with arguments validated and injected. Arguments are first attempted to be parsed from JSON, then validated against the argument model, before being passed to the function. """arguments_pre_parsed=self.pre_parse_json(arguments_to_validate)
arguments_parsed_model=self.arg_model.model_validate(arguments_pre_parsed)
arguments_parsed_dict=arguments_parsed_model.model_dump_one_level()
arguments_parsed_dict|=arguments_to_pass_directlyor {}
iffn_is_async:
returnawaitfn(**arguments_parsed_dict)
else:
returnfn(**arguments_parsed_dict)

fastapi

asyncdefrun_endpoint_function(
*, dependant: Dependant, values: dict[str, Any], is_coroutine: bool
) ->Any:
# Only called by get_request_handler. Has been split into its own function to# facilitate profiling endpoints, since inner functions are harder to profile.assertdependant.callisnotNone, "dependant.call must be a function"ifis_coroutine:
returnawaitdependant.call(**values)
else:
returnawaitrun_in_threadpool(dependant.call, **values)

Example Code

importtimefrommcp.server.fastmcpimportFastMCPmcp=FastMCP("Demo", json_response=True, stateless_http=True)
@mcp.tool()defwait() ->str:
"""Add two numbers"""time.sleep(10)
return"ok"mcp.run()
# call wait tool, any call will be blocked until the sleep is done

Python & MCP Python SDK

python=3.12
mcp=latest

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2Moderate issues affecting some users, edge cases, potentially valuable featureenhancementRequest for a new feature that's not currently supportedneeds confirmationNeeds confirmation that the PR is actually required or needed.v2Ideas, requests and plans for v2 of the SDK which will incorporate major changes and fixes

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions