fastmcp/tests/server/tasks/test_server_tasks_parameter.py
Jeremiah Lowin 3a9717e6be
Publish docs for v3.2.0 (#3713)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Jeremiah Lowin <jlowin@users.noreply.github.com>
Co-authored-by: Marvin Context Protocol <41898282+Marvin Context Protocol@users.noreply.github.com>
Co-authored-by: voidborne-d <voidborne-d@users.noreply.github.com>
Co-authored-by: marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: d 🔹 <258577966+voidborne-d@users.noreply.github.com>
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
Co-authored-by: nightcityblade <nightcityblade@gmail.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Bill Easton <strawgate@users.noreply.github.com>
Co-authored-by: Sumanshu Nankana <sumanshunankana@gmail.com>
Co-authored-by: Eric Robinson <ericrobinson@indeed.com>
Co-authored-by: Martim Santos <martimfasantos@gmail.com>
Co-authored-by: d 🔹 <liusway405@gmail.com>
Co-authored-by: Matthieu B <66959271+mtthidoteu@users.noreply.github.com>
Co-authored-by: Sascha Buehrle <47737812+saschabuehrle@users.noreply.github.com>
Co-authored-by: Hakancan <142545736+hkc5@users.noreply.github.com>
Co-authored-by: nightcityblade <jackchen@haloailabs.com>
Co-authored-by: Matt Hallowell <17804673+mhallo@users.noreply.github.com>
Co-authored-by: nate nowack <thrast36@gmail.com>
Co-authored-by: Bill Easton <williamseaston@gmail.com>
Co-authored-by: Marcus Shu <46469249+shulkx@users.noreply.github.com>
Co-authored-by: Rushabh Doshi <radoshi@gmail.com>
Co-authored-by: AIKAWA Shigechika <shige@aikawa.jp>
Co-authored-by: Jeremy Simon <simonjer805@gmail.com>
Co-authored-by: Miguel Miranda Dias <7780875+pandego@users.noreply.github.com>
Co-authored-by: Anthony James Padavano <padavano.anthony@gmail.com>
Co-authored-by: Mostafa Kamal <hiremostafa@gmail.com>
Fix auto-close MRE script posting comment without closing (#3386)
Fix WorkOS token scope verification bypass 🤖 Generated with Codex (#3407)
Fix initialize McpError fallthrough 🤖 Generated with Codex (#3413)
Fix transform arg collisions with passthrough params (#3431)
Fix get_* returning None when latest version is disabled (#3439)
Fix get_* returning None when latest version is disabled (#3421)
Fix server lifespan overlap teardown (#3415)
Fix $ref output schema object detection regression (#3420)
resolved annotations (#3429)
Fix async partial callables rejected by iscoroutinefunction (#3438)
Fix async partial callables rejected by iscoroutinefunction (#3423)
fix: add version to components (#3458)
fix: use intent-based flag for OIDC scope patch in load_access_token (#3465)
Fixes #3461
fix: normalize Google scope shorthands and surface valid_scopes (#3477)
fix: resolve ty 0.0.23 type-checking errors and bump pin (#3481)
fix: shield lifespan teardown from cancellation (#3480)
fix: forward custom_route endpoints from mounted servers (#3462)
fix updates _get_additional_http_routes() to traverse providers,
Fixes #3457
fix: remove hardcoded version from CLI help text (#3456)
fix: monty 0.0.8 compatibility, drop external_functions from constructor (#3468)
fix: task test teardown hanging 5s per test (#3499)
Closes #3498
fix: validate workspace path is a directory before cursor install (#3440)
Fixes #3426
fix: handle re.error from malformed URI templates in build_regex (#3501)
fix: reject empty/OIDC-only required_scopes in AzureProvider (#3503)
fix: restrict $ref resolution to local refs only (SSRF/LFI) (#3502)
fix warnings and timeouts (#3504)
close upgrade check issue when build passes (#3505)
Closes #3484
fix: URL-encode path params to prevent SSRF/path traversal (GHSA-vv7q-7jx5-f767) (#3507)
fix: prevent path traversal in skill download (#3493)
fix: prefer IdP-granted scopes over client-requested scopes in OAuthProxy (#3492)
fix: remove unrelated transform and http.py changes from PR scope
fix: remove forced follow_redirects from httpx_client_factory calls (#3496)
fix: stop passing follow_redirects to httpx_client_factory
fix: restore follow_redirects=True for custom httpx client factories
Closes #3509
fix: CSRF double-submit cookie check in consent flow (#3519)
fix: validate server names in install commands (#3522)
fix: use raw strings for regex in pytest.raises match (#3523)
fix: reject refresh tokens used as Bearer access tokens (#3524)
fix: route ResourcesAsTools/PromptsAsTools through server middleware (#3495)
fix: resolve Pyright "Module is not callable" on @tool, @resource, @prompt decorators (#3540)
fix: filter warnings by message in KEY_PREFIX test (#3549)
fix: suppress output schema for ToolResult subclass annotations (#3548)
fix: increase sleep duration in proxy cache tests (#3567)
fix: store absolute token expiry to prevent stale expires_in on reload (#3572)
fix: preserve tool properties named 'title' during schema compression (#3582)
Fix loopback redirect URI port matching per RFC 8252 §7.3 (#3589)
Fix app tool routing: visibility check and middleware propagation (#3591)
Fix query parameter serialization to respect OpenAPI explode/style settings (#3595)
Fix dev apps form: union types, textarea support, JSON parsing (#3597)
fix(google): replace deprecated /oauth2/v1/tokeninfo with /oauth2/v3/userinfo (#3603)
fix: resolve EntraOBOToken dependency injection through MultiAuth (#3609)
fix(docs): correct misleading stateless_http header (#3622)
fix: filesystem provider import machinery (#3626)
Closes #3625 (issues 2, 3, 6)
fix: recover StdioTransport after subprocess exits (#3630)
fix(server): preserve mounted tool task metadata (#3632)
fix: scope deprecation warning filter to FastMCPDeprecationWarning (#3649)
fix imports, add PrefabAppConfig (#3650)
fix: resolve CurrentFastMCP/ctx.fastmcp to child server in mounted background tasks (#3651)
Fix blocking docs issues: chart imports, Select API, Rx consistency (#3652)
closed by default (#3657)
Fix prompt caching middleware missing wrap/unwrap round-trip (#3666)
fix: serialize object query params per OpenAPI style/explode rules (#3662)
Fixes #2857
fix: HTTP request headers not accessible in background task workers (#3631)
fix: restore HTTP headers in worker execution path for background tasks (#3681)
fix: strip discriminator after dereferencing schemas (#3682)
fix: remove stale ty:ignore directives for ty 0.0.26 (#3684)
Fix docs gaps in app provider pages (#3690)
fix: dev apps log panel UX improvements (#3698)
fix dev server empty string args (#3700)
2026-03-30 16:48:30 -04:00

391 lines
14 KiB
Python

"""
Tests for server `tasks` parameter default inheritance.
Verifies that the server's `tasks` parameter correctly sets defaults for all
components (tools, prompts, resources), and that explicit component-level
settings properly override the server default.
"""
import pytest
from fastmcp import FastMCP
from fastmcp.client import Client
@pytest.mark.timeout(10)
async def test_server_tasks_true_defaults_all_components():
"""Server with tasks=True makes all components default to supporting tasks."""
mcp = FastMCP("test", tasks=True)
@mcp.tool()
async def my_tool() -> str:
return "tool result"
@mcp.prompt()
async def my_prompt() -> str:
return "prompt result"
@mcp.resource("test://resource")
async def my_resource() -> str:
return "resource result"
async with Client(mcp) as client:
# Verify all task-enabled components are registered with docket
# Components use prefixed keys: tool:name, prompt:name, resource:uri
docket = mcp.docket
assert docket is not None
assert "tool:my_tool@" in docket.tasks
assert "prompt:my_prompt@" in docket.tasks
assert "resource:test://resource@" in docket.tasks
# Tool should support background execution
tool_task = await client.call_tool("my_tool", task=True)
assert not tool_task.returned_immediately
# Prompt should support background execution
prompt_task = await client.get_prompt("my_prompt", task=True)
assert not prompt_task.returned_immediately
# Resource should support background execution
resource_task = await client.read_resource("test://resource", task=True)
assert not resource_task.returned_immediately
async def test_server_tasks_false_defaults_all_components():
"""Server with tasks=False makes all components default to mode=forbidden."""
import pytest
from mcp.shared.exceptions import McpError
mcp = FastMCP("test", tasks=False)
@mcp.tool()
async def my_tool() -> str:
return "tool result"
@mcp.prompt()
async def my_prompt() -> str:
return "prompt result"
@mcp.resource("test://resource")
async def my_resource() -> str:
return "resource result"
async with Client(mcp) as client:
# Tool with mode="forbidden" returns error when called with task=True
tool_task = await client.call_tool("my_tool", task=True)
assert tool_task.returned_immediately
result = await tool_task.result()
assert result.is_error
assert "does not support task-augmented execution" in str(result)
# Prompt with mode="forbidden" raises McpError when called with task=True
with pytest.raises(McpError):
await client.get_prompt("my_prompt", task=True)
# Resource with mode="forbidden" raises McpError when called with task=True
with pytest.raises(McpError):
await client.read_resource("test://resource", task=True)
async def test_server_tasks_none_defaults_to_false():
"""Server with tasks=None (or omitted) defaults to False."""
mcp = FastMCP("test") # tasks=None, defaults to False
@mcp.tool()
async def my_tool() -> str:
return "tool result"
async with Client(mcp) as client:
# Tool should NOT support background execution (mode="forbidden" from default)
tool_task = await client.call_tool("my_tool", task=True)
assert tool_task.returned_immediately
result = await tool_task.result()
assert result.is_error
assert "does not support task-augmented execution" in str(result)
async def test_component_explicit_false_overrides_server_true():
"""Component with task=False overrides server default of tasks=True."""
mcp = FastMCP("test", tasks=True)
@mcp.tool(task=False)
async def no_task_tool() -> str:
return "immediate result"
@mcp.tool()
async def default_tool() -> str:
return "background result"
async with Client(mcp) as client:
# Verify docket registration matches task settings (prefixed keys)
docket = mcp.docket
assert docket is not None
assert (
"tool:no_task_tool@" not in docket.tasks
) # task=False means not registered
assert "tool:default_tool@" in docket.tasks # Inherits tasks=True
# Explicit False (mode="forbidden") returns error when called with task=True
no_task = await client.call_tool("no_task_tool", task=True)
assert no_task.returned_immediately
result = await no_task.result()
assert result.is_error
assert "does not support task-augmented execution" in str(result)
# Default should support background execution
default_task = await client.call_tool("default_tool", task=True)
assert not default_task.returned_immediately
async def test_component_explicit_true_overrides_server_false():
"""Component with task=True overrides server default of tasks=False."""
mcp = FastMCP("test", tasks=False)
@mcp.tool(task=True)
async def task_tool() -> str:
return "background result"
@mcp.tool()
async def default_tool() -> str:
return "immediate result"
async with Client(mcp) as client:
# Verify docket registration matches task settings (prefixed keys)
docket = mcp.docket
assert docket is not None
assert "tool:task_tool@" in docket.tasks # task=True means registered
assert "tool:default_tool@" not in docket.tasks # Inherits tasks=False
# Explicit True should support background execution despite server default
task = await client.call_tool("task_tool", task=True)
assert not task.returned_immediately
# Default (mode="forbidden") returns error when called with task=True
default = await client.call_tool("default_tool", task=True)
assert default.returned_immediately
result = await default.result()
assert result.is_error
async def test_mixed_explicit_and_inherited():
"""Mix of explicit True/False/None on different components."""
import pytest
from mcp.shared.exceptions import McpError
mcp = FastMCP("test", tasks=True) # Server default is True
@mcp.tool()
async def inherited_tool() -> str:
return "inherits True"
@mcp.tool(task=True)
async def explicit_true_tool() -> str:
return "explicit True"
@mcp.tool(task=False)
async def explicit_false_tool() -> str:
return "explicit False"
@mcp.prompt()
async def inherited_prompt() -> str:
return "inherits True"
@mcp.prompt(task=False)
async def explicit_false_prompt() -> str:
return "explicit False"
@mcp.resource("test://inherited")
async def inherited_resource() -> str:
return "inherits True"
@mcp.resource("test://explicit_false", task=False)
async def explicit_false_resource() -> str:
return "explicit False"
async with Client(mcp) as client:
# Verify docket registration matches task settings
# Components use prefixed keys: tool:name, prompt:name, resource:uri
docket = mcp.docket
assert docket is not None
# task=True (explicit or inherited) means registered (with prefixed keys)
assert "tool:inherited_tool@" in docket.tasks
assert "tool:explicit_true_tool@" in docket.tasks
assert "prompt:inherited_prompt@" in docket.tasks
assert "resource:test://inherited@" in docket.tasks
# task=False means NOT registered
assert "tool:explicit_false_tool@" not in docket.tasks
assert "prompt:explicit_false_prompt@" not in docket.tasks
assert "resource:test://explicit_false@" not in docket.tasks
# Tools
inherited = await client.call_tool("inherited_tool", task=True)
assert not inherited.returned_immediately
explicit_true = await client.call_tool("explicit_true_tool", task=True)
assert not explicit_true.returned_immediately
# Explicit False (mode="forbidden") returns error
explicit_false = await client.call_tool("explicit_false_tool", task=True)
assert explicit_false.returned_immediately
result = await explicit_false.result()
assert result.is_error
# Prompts
inherited_prompt_task = await client.get_prompt("inherited_prompt", task=True)
assert not inherited_prompt_task.returned_immediately
# Explicit False prompt (mode="forbidden") raises McpError
with pytest.raises(McpError):
await client.get_prompt("explicit_false_prompt", task=True)
# Resources
inherited_resource_task = await client.read_resource(
"test://inherited", task=True
)
assert not inherited_resource_task.returned_immediately
# Explicit False resource (mode="forbidden") raises McpError
with pytest.raises(McpError):
await client.read_resource("test://explicit_false", task=True)
async def test_server_tasks_parameter_sets_component_defaults():
"""Server tasks parameter sets component defaults."""
# Server tasks=True sets component defaults
mcp = FastMCP("test", tasks=True)
@mcp.tool()
async def tool_inherits_true() -> str:
return "tool result"
async with Client(mcp) as client:
# Tool inherits tasks=True from server
tool_task = await client.call_tool("tool_inherits_true", task=True)
assert not tool_task.returned_immediately
# Server tasks=False sets component defaults
mcp2 = FastMCP("test2", tasks=False)
@mcp2.tool()
async def tool_inherits_false() -> str:
return "tool result"
async with Client(mcp2) as client:
# Tool inherits tasks=False (mode="forbidden") - returns error
tool_task = await client.call_tool("tool_inherits_false", task=True)
assert tool_task.returned_immediately
result = await tool_task.result()
assert result.is_error
async def test_resource_template_inherits_server_tasks_default():
"""Resource templates inherit server tasks default."""
mcp = FastMCP("test", tasks=True)
@mcp.resource("test://{item_id}")
async def templated_resource(item_id: str) -> str:
return f"resource {item_id}"
async with Client(mcp) as client:
# Template should support background execution
resource_task = await client.read_resource("test://123", task=True)
assert not resource_task.returned_immediately
async def test_multiple_components_same_name_different_tasks():
"""Different component types with same name can have different task settings."""
import pytest
from mcp.shared.exceptions import McpError
mcp = FastMCP("test", tasks=False)
@mcp.tool(task=True)
async def shared_name() -> str:
return "tool result"
@mcp.prompt()
async def shared_name_prompt() -> str:
return "prompt result"
async with Client(mcp) as client:
# Tool with explicit True should support background execution
tool_task = await client.call_tool("shared_name", task=True)
assert not tool_task.returned_immediately
# Prompt inheriting False (mode="forbidden") raises McpError
with pytest.raises(McpError):
await client.get_prompt("shared_name_prompt", task=True)
async def test_task_with_custom_tool_name():
"""Tools with custom names work correctly as tasks (issue #2642).
When a tool is registered with a custom name different from the function
name, task execution should use the custom name for Docket lookup.
"""
mcp = FastMCP("test", tasks=True)
async def my_function() -> str:
return "result from custom-named tool"
mcp.tool(my_function, name="custom-tool-name")
async with Client(mcp) as client:
# Verify the tool is registered with its custom name in Docket (prefixed key)
docket = mcp.docket
assert docket is not None
assert "tool:custom-tool-name@" in docket.tasks
# Call the tool as a task using its custom name
task = await client.call_tool("custom-tool-name", task=True)
assert not task.returned_immediately
result = await task
assert result.data == "result from custom-named tool"
async def test_task_with_custom_resource_name():
"""Resources with custom names work correctly as tasks.
Resources are registered/looked up by their .key (URI), not their name.
"""
mcp = FastMCP("test", tasks=True)
@mcp.resource("test://resource", name="custom-resource-name")
async def my_resource_func() -> str:
return "result from custom-named resource"
async with Client(mcp) as client:
# Verify the resource is registered with its key (prefixed URI) in Docket
docket = mcp.docket
assert docket is not None
assert "resource:test://resource@" in docket.tasks
# Call the resource as a task
task = await client.read_resource("test://resource", task=True)
assert not task.returned_immediately
result = await task.result()
assert result[0].text == "result from custom-named resource"
async def test_task_with_custom_template_name():
"""Resource templates with custom names work correctly as tasks.
Templates are registered/looked up by their .key (uri_template), not their name.
"""
mcp = FastMCP("test", tasks=True)
@mcp.resource("test://{item_id}", name="custom-template-name")
async def my_template_func(item_id: str) -> str:
return f"result for {item_id}"
async with Client(mcp) as client:
# Verify the template is registered with its key (prefixed uri_template) in Docket
docket = mcp.docket
assert docket is not None
assert "template:test://{item_id}@" in docket.tasks
# Call the template as a task
task = await client.read_resource("test://123", task=True)
assert not task.returned_immediately
result = await task.result()
assert result[0].text == "result for 123"