sample_id stringlengths 21 196 | text stringlengths 105 936k | metadata dict | category stringclasses 6
values |
|---|---|---|---|
PrefectHQ/fastmcp:tests/server/transforms/test_resources_as_tools.py | """Tests for ResourcesAsTools transform."""
import base64
import json
import pytest
from fastmcp import FastMCP
from fastmcp.client import Client
from fastmcp.server.transforms import ResourcesAsTools
class TestResourcesAsToolsBasic:
"""Test basic ResourcesAsTools functionality."""
async def test_adds_list_resources_tool(self):
"""Transform adds list_resources tool."""
mcp = FastMCP("Test")
mcp.add_transform(ResourcesAsTools(mcp))
async with Client(mcp) as client:
tools = await client.list_tools()
tool_names = {t.name for t in tools}
assert "list_resources" in tool_names
async def test_adds_read_resource_tool(self):
"""Transform adds read_resource tool."""
mcp = FastMCP("Test")
mcp.add_transform(ResourcesAsTools(mcp))
async with Client(mcp) as client:
tools = await client.list_tools()
tool_names = {t.name for t in tools}
assert "read_resource" in tool_names
async def test_preserves_existing_tools(self):
"""Transform preserves existing tools."""
mcp = FastMCP("Test")
@mcp.tool
def my_tool() -> str:
return "result"
mcp.add_transform(ResourcesAsTools(mcp))
async with Client(mcp) as client:
tools = await client.list_tools()
tool_names = {t.name for t in tools}
assert "my_tool" in tool_names
assert "list_resources" in tool_names
assert "read_resource" in tool_names
class TestListResourcesTool:
"""Test the list_resources tool."""
async def test_lists_static_resources(self):
"""list_resources returns static resources with uri."""
mcp = FastMCP("Test")
@mcp.resource("config://app")
def app_config() -> str:
return "config data"
mcp.add_transform(ResourcesAsTools(mcp))
async with Client(mcp) as client:
result = await client.call_tool("list_resources", {})
resources = json.loads(result.data)
assert len(resources) == 1
assert resources[0]["uri"] == "config://app"
assert resources[0]["name"] == "app_config"
async def test_lists_resource_templates(self):
"""list_resources returns templates with uri_template."""
mcp = FastMCP("Test")
@mcp.resource("file://{path}")
def read_file(path: str) -> str:
return f"content of {path}"
mcp.add_transform(ResourcesAsTools(mcp))
async with Client(mcp) as client:
result = await client.call_tool("list_resources", {})
resources = json.loads(result.data)
assert len(resources) == 1
assert resources[0]["uri_template"] == "file://{path}"
assert "uri" not in resources[0]
async def test_lists_both_resources_and_templates(self):
"""list_resources returns both static and templated resources."""
mcp = FastMCP("Test")
@mcp.resource("config://app")
def app_config() -> str:
return "config"
@mcp.resource("file://{path}")
def read_file(path: str) -> str:
return f"content of {path}"
mcp.add_transform(ResourcesAsTools(mcp))
async with Client(mcp) as client:
result = await client.call_tool("list_resources", {})
resources = json.loads(result.data)
assert len(resources) == 2
# One has uri, one has uri_template
uris = [r.get("uri") for r in resources if r.get("uri")]
templates = [
r.get("uri_template") for r in resources if r.get("uri_template")
]
assert uris == ["config://app"]
assert templates == ["file://{path}"]
async def test_empty_when_no_resources(self):
"""list_resources returns empty list when no resources exist."""
mcp = FastMCP("Test")
mcp.add_transform(ResourcesAsTools(mcp))
async with Client(mcp) as client:
result = await client.call_tool("list_resources", {})
assert json.loads(result.data) == []
class TestReadResourceTool:
"""Test the read_resource tool."""
async def test_reads_static_resource(self):
"""read_resource reads a static resource by URI."""
mcp = FastMCP("Test")
@mcp.resource("config://app")
def app_config() -> str:
return "my config data"
mcp.add_transform(ResourcesAsTools(mcp))
async with Client(mcp) as client:
result = await client.call_tool("read_resource", {"uri": "config://app"})
assert result.data == "my config data"
async def test_reads_templated_resource(self):
"""read_resource reads a templated resource with parameters."""
mcp = FastMCP("Test")
@mcp.resource("user://{user_id}/profile")
def user_profile(user_id: str) -> str:
return f"Profile for user {user_id}"
mcp.add_transform(ResourcesAsTools(mcp))
async with Client(mcp) as client:
result = await client.call_tool(
"read_resource", {"uri": "user://123/profile"}
)
assert result.data == "Profile for user 123"
async def test_error_on_unknown_resource(self):
"""read_resource raises error for unknown URI."""
from fastmcp.exceptions import ToolError
mcp = FastMCP("Test")
mcp.add_transform(ResourcesAsTools(mcp))
async with Client(mcp) as client:
with pytest.raises(ToolError, match="Unknown resource"):
await client.call_tool("read_resource", {"uri": "unknown://resource"})
async def test_reads_binary_as_base64(self):
"""read_resource returns binary content as base64."""
mcp = FastMCP("Test")
@mcp.resource("data://binary", mime_type="application/octet-stream")
def binary_data() -> bytes:
return b"\x00\x01\x02\x03"
mcp.add_transform(ResourcesAsTools(mcp))
async with Client(mcp) as client:
result = await client.call_tool("read_resource", {"uri": "data://binary"})
# Should be base64 encoded
decoded = base64.b64decode(result.data)
assert decoded == b"\x00\x01\x02\x03"
class TestResourcesAsToolsWithNamespace:
"""Test ResourcesAsTools combined with other transforms."""
async def test_works_with_namespace_on_provider(self):
"""ResourcesAsTools works when provider has Namespace transform."""
from fastmcp.server.providers import FastMCPProvider
from fastmcp.server.transforms import Namespace
sub = FastMCP("Sub")
@sub.resource("config://app")
def app_config() -> str:
return "sub config"
main = FastMCP("Main")
provider = FastMCPProvider(sub)
provider.add_transform(Namespace("sub"))
main.add_provider(provider)
main.add_transform(ResourcesAsTools(main))
async with Client(main) as client:
result = await client.call_tool("list_resources", {})
resources = json.loads(result.data)
# Resource should have namespaced URI
assert len(resources) == 1
assert resources[0]["uri"] == "config://sub/app"
class TestResourcesAsToolsRepr:
"""Test ResourcesAsTools repr."""
def test_repr(self):
"""Transform has useful repr."""
mcp = FastMCP("Test")
transform = ResourcesAsTools(mcp)
assert "ResourcesAsTools" in repr(transform)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/transforms/test_resources_as_tools.py",
"license": "Apache License 2.0",
"lines": 166,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/client/client/test_auth.py | """Client authentication tests."""
import pytest
from mcp.client.auth import OAuthClientProvider
from fastmcp.client import Client
from fastmcp.client.auth.bearer import BearerAuth
from fastmcp.client.transports import (
SSETransport,
StdioTransport,
StreamableHttpTransport,
)
class TestAuth:
def test_default_auth_is_none(self):
client = Client(transport=StreamableHttpTransport("http://localhost:8000"))
assert client.transport.auth is None
def test_stdio_doesnt_support_auth(self):
with pytest.raises(ValueError, match="This transport does not support auth"):
Client(transport=StdioTransport("echo", ["hello"]), auth="oauth")
def test_oauth_literal_sets_up_oauth_shttp(self):
client = Client(
transport=StreamableHttpTransport("http://localhost:8000"), auth="oauth"
)
assert isinstance(client.transport, StreamableHttpTransport)
assert isinstance(client.transport.auth, OAuthClientProvider)
def test_oauth_literal_pass_direct_to_transport(self):
client = Client(
transport=StreamableHttpTransport("http://localhost:8000", auth="oauth"),
)
assert isinstance(client.transport, StreamableHttpTransport)
assert isinstance(client.transport.auth, OAuthClientProvider)
def test_oauth_literal_sets_up_oauth_sse(self):
client = Client(transport=SSETransport("http://localhost:8000"), auth="oauth")
assert isinstance(client.transport, SSETransport)
assert isinstance(client.transport.auth, OAuthClientProvider)
def test_oauth_literal_pass_direct_to_transport_sse(self):
client = Client(transport=SSETransport("http://localhost:8000", auth="oauth"))
assert isinstance(client.transport, SSETransport)
assert isinstance(client.transport.auth, OAuthClientProvider)
def test_auth_string_sets_up_bearer_auth_shttp(self):
client = Client(
transport=StreamableHttpTransport("http://localhost:8000"),
auth="test_token",
)
assert isinstance(client.transport, StreamableHttpTransport)
assert isinstance(client.transport.auth, BearerAuth)
assert client.transport.auth.token.get_secret_value() == "test_token"
def test_auth_string_pass_direct_to_transport_shttp(self):
client = Client(
transport=StreamableHttpTransport(
"http://localhost:8000", auth="test_token"
),
)
assert isinstance(client.transport, StreamableHttpTransport)
assert isinstance(client.transport.auth, BearerAuth)
assert client.transport.auth.token.get_secret_value() == "test_token"
def test_auth_string_sets_up_bearer_auth_sse(self):
client = Client(
transport=SSETransport("http://localhost:8000"),
auth="test_token",
)
assert isinstance(client.transport, SSETransport)
assert isinstance(client.transport.auth, BearerAuth)
assert client.transport.auth.token.get_secret_value() == "test_token"
def test_auth_string_pass_direct_to_transport_sse(self):
client = Client(
transport=SSETransport("http://localhost:8000", auth="test_token"),
)
assert isinstance(client.transport, SSETransport)
assert isinstance(client.transport.auth, BearerAuth)
assert client.transport.auth.token.get_secret_value() == "test_token"
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/client/client/test_auth.py",
"license": "Apache License 2.0",
"lines": 69,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/client/client/test_client.py | """Core client functionality: tools, resources, prompts."""
import asyncio
import contextlib
from collections.abc import AsyncIterator
from typing import Any, cast
import anyio
import pytest
from mcp import ClientSession, McpError
from mcp.types import TextContent
from pydantic import AnyUrl
import fastmcp
from fastmcp.client import Client
from fastmcp.client.transports import (
ClientTransport,
FastMCPTransport,
)
from fastmcp.server.server import FastMCP
async def test_list_tools(fastmcp_server):
"""Test listing tools with InMemoryClient."""
client = Client(transport=FastMCPTransport(fastmcp_server))
async with client:
result = await client.list_tools()
# Check that our tools are available
assert len(result) == 3
assert set(tool.name for tool in result) == {"greet", "add", "sleep"}
async def test_list_tools_mcp(fastmcp_server):
"""Test the list_tools_mcp method that returns raw MCP protocol objects."""
client = Client(transport=FastMCPTransport(fastmcp_server))
async with client:
result = await client.list_tools_mcp()
# Check that we got the raw MCP ListToolsResult object
assert hasattr(result, "tools")
assert len(result.tools) == 3
assert set(tool.name for tool in result.tools) == {"greet", "add", "sleep"}
async def test_call_tool(fastmcp_server):
"""Test calling a tool with InMemoryClient."""
client = Client(transport=FastMCPTransport(fastmcp_server))
async with client:
result = await client.call_tool("greet", {"name": "World"})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "Hello, World!"
assert result.structured_content == {"result": "Hello, World!"}
assert result.data == "Hello, World!"
assert result.is_error is False
async def test_call_tool_mcp(fastmcp_server):
"""Test the call_tool_mcp method that returns raw MCP protocol objects."""
client = Client(transport=FastMCPTransport(fastmcp_server))
async with client:
result = await client.call_tool_mcp("greet", {"name": "World"})
# Check that we got the raw MCP CallToolResult object
assert hasattr(result, "content")
assert hasattr(result, "isError")
assert result.isError is False
# The content is a list, so we'll check the first element
# by properly accessing it
content = result.content
assert len(content) > 0
first_content = content[0]
content_str = str(first_content)
assert "Hello, World!" in content_str
async def test_call_tool_with_meta():
"""Test that meta parameter is properly passed from client to server."""
server = FastMCP("MetaTestServer")
# Create a tool that accesses the meta from the request context
@server.tool
def check_meta() -> dict[str, Any]:
"""A tool that returns the meta from the request context."""
from fastmcp.server.dependencies import get_context
context = get_context()
assert context.request_context is not None
meta = context.request_context.meta
# Return the metadata as a dict
if meta is not None:
return {
"has_meta": True,
"user_id": getattr(meta, "user_id", None),
"trace_id": getattr(meta, "trace_id", None),
}
return {"has_meta": False}
client = Client(transport=FastMCPTransport(server))
async with client:
# Test with meta parameter - verify the server receives it
test_meta = {"user_id": "test-123", "trace_id": "abc-def"}
result = await client.call_tool("check_meta", {}, meta=test_meta)
assert result.data["has_meta"] is True
assert result.data["user_id"] == "test-123"
assert result.data["trace_id"] == "abc-def"
# Test without meta parameter - verify fields are not present
result_no_meta = await client.call_tool("check_meta", {})
# When meta is not provided, custom fields should not be present
assert result_no_meta.data.get("user_id") is None
assert result_no_meta.data.get("trace_id") is None
async def test_list_resources(fastmcp_server):
"""Test listing resources with InMemoryClient."""
client = Client(transport=FastMCPTransport(fastmcp_server))
async with client:
result = await client.list_resources()
# Check that our resource is available
assert len(result) == 1
assert str(result[0].uri) == "data://users"
async def test_list_resources_mcp(fastmcp_server):
"""Test the list_resources_mcp method that returns raw MCP protocol objects."""
client = Client(transport=FastMCPTransport(fastmcp_server))
async with client:
result = await client.list_resources_mcp()
# Check that we got the raw MCP ListResourcesResult object
assert hasattr(result, "resources")
assert len(result.resources) == 1
assert str(result.resources[0].uri) == "data://users"
async def test_list_prompts(fastmcp_server):
"""Test listing prompts with InMemoryClient."""
client = Client(transport=FastMCPTransport(fastmcp_server))
async with client:
result = await client.list_prompts()
# Check that our prompt is available
assert len(result) == 1
assert result[0].name == "welcome"
async def test_list_prompts_mcp(fastmcp_server):
"""Test the list_prompts_mcp method that returns raw MCP protocol objects."""
client = Client(transport=FastMCPTransport(fastmcp_server))
async with client:
result = await client.list_prompts_mcp()
# Check that we got the raw MCP ListPromptsResult object
assert hasattr(result, "prompts")
assert len(result.prompts) == 1
assert result.prompts[0].name == "welcome"
async def test_get_prompt(fastmcp_server):
"""Test getting a prompt with InMemoryClient."""
client = Client(transport=FastMCPTransport(fastmcp_server))
async with client:
result = await client.get_prompt("welcome", {"name": "Developer"})
# The result should contain our welcome message
assert isinstance(result.messages[0].content, TextContent)
assert result.messages[0].content.text == "Welcome to FastMCP, Developer!"
assert result.description == "Example greeting prompt."
async def test_get_prompt_mcp(fastmcp_server):
"""Test the get_prompt_mcp method that returns raw MCP protocol objects."""
client = Client(transport=FastMCPTransport(fastmcp_server))
async with client:
result = await client.get_prompt_mcp("welcome", {"name": "Developer"})
# The result should contain our welcome message
assert isinstance(result.messages[0].content, TextContent)
assert result.messages[0].content.text == "Welcome to FastMCP, Developer!"
assert result.description == "Example greeting prompt."
async def test_client_serializes_all_non_string_arguments():
"""Test that client always serializes non-string arguments to JSON, regardless of server types."""
server = FastMCP("TestServer")
@server.prompt
def echo_args(arg1: str, arg2: str, arg3: str) -> str:
"""Server accepts all string args but client sends mixed types."""
return f"arg1: {arg1}, arg2: {arg2}, arg3: {arg3}"
client = Client(transport=FastMCPTransport(server))
async with client:
result = await client.get_prompt(
"echo_args",
{
"arg1": "hello", # string - should pass through
"arg2": [1, 2, 3], # list - should be JSON serialized
"arg3": {"key": "value"}, # dict - should be JSON serialized
},
)
assert isinstance(result.messages[0].content, TextContent)
content = result.messages[0].content.text
assert "arg1: hello" in content
assert "arg2: [1,2,3]" in content # JSON serialized list
assert 'arg3: {"key":"value"}' in content # JSON serialized dict
async def test_client_server_type_conversion_integration():
"""Test that client serialization works with server-side type conversion."""
server = FastMCP("TestServer")
@server.prompt
def typed_prompt(numbers: list[int], config: dict[str, str]) -> str:
"""Server expects typed args - will convert from JSON strings."""
return f"Got {len(numbers)} numbers and {len(config)} config items"
client = Client(transport=FastMCPTransport(server))
async with client:
result = await client.get_prompt(
"typed_prompt",
{"numbers": [1, 2, 3, 4], "config": {"theme": "dark", "lang": "en"}},
)
assert isinstance(result.messages[0].content, TextContent)
content = result.messages[0].content.text
assert "Got 4 numbers and 2 config items" in content
async def test_client_serialization_error():
"""Test client error when object cannot be serialized."""
import pydantic_core
server = FastMCP("TestServer")
@server.prompt
def any_prompt(data: str) -> str:
return f"Got: {data}"
# Create an unserializable object
class UnserializableClass:
def __init__(self):
self.func = lambda x: x # functions can't be JSON serialized
client = Client(transport=FastMCPTransport(server))
async with client:
with pytest.raises(
pydantic_core.PydanticSerializationError, match="Unable to serialize"
):
await client.get_prompt("any_prompt", {"data": UnserializableClass()})
async def test_server_deserialization_error():
"""Test server error when JSON string cannot be converted to expected type."""
server = FastMCP("TestServer")
@server.prompt
def strict_typed_prompt(numbers: list[int]) -> str:
"""Expects list of integers but will receive invalid JSON."""
return f"Got {len(numbers)} numbers"
client = Client(transport=FastMCPTransport(server))
async with client:
with pytest.raises(McpError, match="Error rendering prompt"):
await client.get_prompt(
"strict_typed_prompt",
{
"numbers": "not valid json" # This will fail server-side conversion
},
)
async def test_read_resource_invalid_uri(fastmcp_server):
"""Test reading a resource with an invalid URI."""
client = Client(transport=FastMCPTransport(fastmcp_server))
with pytest.raises(ValueError, match="Provided resource URI is invalid"):
await client.read_resource("invalid_uri")
async def test_read_resource(fastmcp_server):
"""Test reading a resource with InMemoryClient."""
client = Client(transport=FastMCPTransport(fastmcp_server))
async with client:
# Use the URI from the resource we know exists in our server
uri = cast(
AnyUrl, "data://users"
) # Use cast for type hint only, the URI is valid
result = await client.read_resource(uri)
# The contents should include our user list
contents_str = str(result[0])
assert "Alice" in contents_str
assert "Bob" in contents_str
assert "Charlie" in contents_str
async def test_read_resource_mcp(fastmcp_server):
"""Test the read_resource_mcp method that returns raw MCP protocol objects."""
client = Client(transport=FastMCPTransport(fastmcp_server))
async with client:
# Use the URI from the resource we know exists in our server
uri = cast(
AnyUrl, "data://users"
) # Use cast for type hint only, the URI is valid
result = await client.read_resource_mcp(uri)
# Check that we got the raw MCP ReadResourceResult object
assert hasattr(result, "contents")
assert len(result.contents) > 0
contents_str = str(result.contents[0])
assert "Alice" in contents_str
assert "Bob" in contents_str
assert "Charlie" in contents_str
async def test_client_connection(fastmcp_server):
"""Test that connect is idempotent."""
client = Client(transport=FastMCPTransport(fastmcp_server))
# Connect idempotently
async with client:
assert client.is_connected()
# Make a request to ensure connection is working
await client.ping()
assert not client.is_connected()
async def test_initialize_called_once(fastmcp_server):
"""Test that initialization is called once and sets initialize_result."""
client = Client(transport=FastMCPTransport(fastmcp_server))
async with client:
# Verify that initialization succeeded by checking initialize_result
assert client.initialize_result is not None
assert client.initialize_result.serverInfo is not None
async def test_initialize_result_connected(fastmcp_server):
"""Test that initialize_result returns the correct result when connected."""
client = Client(transport=FastMCPTransport(fastmcp_server))
# Initialize result should be None before connection
assert client.initialize_result is None
async with client:
# Once connected, initialize_result should be available
result = client.initialize_result
# Verify the initialize result has expected properties
assert hasattr(result, "serverInfo")
assert result.serverInfo.name == "TestServer"
assert result.serverInfo.version is not None
async def test_initialize_result_disconnected(fastmcp_server):
"""Test that initialize_result is None when not connected."""
client = Client(transport=FastMCPTransport(fastmcp_server))
# Initialize result should be None before connection
assert client.initialize_result is None
# Connect and then disconnect
async with client:
assert client.is_connected()
# After disconnection, initialize_result should be None again
assert not client.is_connected()
assert client.initialize_result is None
async def test_server_info_custom_version():
"""Test that custom version is properly set in serverInfo."""
# Test with custom version
server_with_version = FastMCP("CustomVersionServer", version="1.2.3")
client = Client(transport=FastMCPTransport(server_with_version))
async with client:
result = client.initialize_result
assert result is not None
assert result.serverInfo.name == "CustomVersionServer"
assert result.serverInfo.version == "1.2.3"
# Test without version (backward compatibility)
server_without_version = FastMCP("DefaultVersionServer")
client = Client(transport=FastMCPTransport(server_without_version))
async with client:
result = client.initialize_result
assert result is not None
assert result.serverInfo.name == "DefaultVersionServer"
# Should fall back to FastMCP version
assert result.serverInfo.version == fastmcp.__version__
class _DelayedConnectTransport(ClientTransport):
def __init__(
self,
inner: ClientTransport,
connect_started: anyio.Event,
allow_connect: anyio.Event,
) -> None:
self._inner = inner
self._connect_started = connect_started
self._allow_connect = allow_connect
@contextlib.asynccontextmanager
async def connect_session(
self, **session_kwargs: Any
) -> AsyncIterator[ClientSession]:
self._connect_started.set()
await self._allow_connect.wait()
async with self._inner.connect_session(**session_kwargs) as session:
yield session
async def close(self) -> None:
await self._inner.close()
async def test_client_nested_context_manager(fastmcp_server):
"""Test that the client connects and disconnects once in nested context manager."""
client = Client(fastmcp_server)
# Before connection
assert not client.is_connected()
assert client._session_state.session is None
# During connection
async with client:
assert client.is_connected()
assert client._session_state.session is not None
session = client._session_state.session
# Reuse the same session
async with client:
assert client.is_connected()
assert client._session_state.session is session
# Reuse the same session
async with client:
assert client.is_connected()
assert client._session_state.session is session
# After connection
assert not client.is_connected()
assert client._session_state.session is None
async def test_client_context_entry_cancelled_starter_cleans_up(fastmcp_server):
connect_started = anyio.Event()
allow_connect = anyio.Event()
client = Client(
transport=_DelayedConnectTransport(
FastMCPTransport(fastmcp_server),
connect_started=connect_started,
allow_connect=allow_connect,
)
)
async def enter_and_never_reach_body() -> None:
async with client:
pytest.fail(
"Context body should not be reached when __aenter__ is cancelled"
)
task = asyncio.create_task(enter_and_never_reach_body())
await connect_started.wait()
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
# Connection startup was cancelled; session state should be fully reset.
assert client._session_state.session_task is None
assert client._session_state.session is None
assert client._session_state.nesting_counter == 0
# A future connection attempt should work normally.
allow_connect.set()
async with client:
tools = await client.list_tools()
assert len(tools) == 3
async def test_cancelled_context_entry_waiter_does_not_close_active_session(
fastmcp_server,
):
connect_started = anyio.Event()
allow_connect = anyio.Event()
client = Client(
transport=_DelayedConnectTransport(
FastMCPTransport(fastmcp_server),
connect_started=connect_started,
allow_connect=allow_connect,
)
)
b_done = asyncio.Event()
b_started = asyncio.Event()
async def task_a() -> int:
async with client:
await b_done.wait()
tools = await client.list_tools()
return len(tools)
async def task_b() -> None:
b_started.set()
async with client:
pytest.fail("This context should never be entered due to cancellation")
a = asyncio.create_task(task_a())
await connect_started.wait()
b = asyncio.create_task(task_b())
await b_started.wait()
await asyncio.sleep(0) # let task_b attempt to acquire the client lock
b.cancel()
allow_connect.set()
with pytest.raises(asyncio.CancelledError):
await b
# task_b is fully cancelled; allow task_a to exercise the connected session.
b_done.set()
assert await a == 3
async def test_concurrent_client_context_managers():
"""
Test that concurrent client usage doesn't cause cross-task cancel scope issues.
https://github.com/PrefectHQ/fastmcp/pull/643
"""
# Create a simple server
server = FastMCP("Test Server")
@server.tool
def echo(text: str) -> str:
"""Echo tool"""
return text
# Create client
client = Client(server)
# Track results
results = {}
errors = []
async def use_client(task_id: str, delay: float = 0):
"""Use the client with a small delay to ensure overlap"""
try:
async with client:
# Add a small delay to ensure contexts overlap
await asyncio.sleep(delay)
# Make an actual call to exercise the session
tools = await client.list_tools()
results[task_id] = len(tools)
except Exception as e:
errors.append((task_id, str(e)))
# Run multiple tasks concurrently
# The key is having them enter and exit the context at different times
await asyncio.gather(
use_client("task1", 0.0),
use_client("task2", 0.01), # Slight delay to ensure overlap
use_client("task3", 0.02),
return_exceptions=False,
)
assert len(errors) == 0, f"Errors occurred: {errors}"
assert len(results) == 3
assert all(count == 1 for count in results.values()) # All should see 1 tool
async def test_resource_template(fastmcp_server):
"""Test using a resource template with InMemoryClient."""
client = Client(transport=FastMCPTransport(fastmcp_server))
async with client:
# First, list templates
result = await client.list_resource_templates()
# Check that our template is available
assert len(result) == 1
assert "data://user/{user_id}" in result[0].uriTemplate
# Now use the template with a specific user_id
uri = cast(AnyUrl, "data://user/123")
result = await client.read_resource(uri)
# Check the content matches what we expect for the provided user_id
content_str = str(result[0])
assert '"id":"123"' in content_str
assert '"name":"User 123"' in content_str
assert '"active":true' in content_str
async def test_list_resource_templates_mcp(fastmcp_server):
"""Test the list_resource_templates_mcp method that returns raw MCP protocol objects."""
client = Client(transport=FastMCPTransport(fastmcp_server))
async with client:
result = await client.list_resource_templates_mcp()
# Check that we got the raw MCP ListResourceTemplatesResult object
assert hasattr(result, "resourceTemplates")
assert len(result.resourceTemplates) == 1
assert "data://user/{user_id}" in result.resourceTemplates[0].uriTemplate
async def test_mcp_resource_generation(fastmcp_server):
"""Test that resources are properly generated in MCP format."""
client = Client(transport=FastMCPTransport(fastmcp_server))
async with client:
resources = await client.list_resources()
assert len(resources) == 1
resource = resources[0]
# Verify resource has correct MCP format
assert hasattr(resource, "uri")
assert hasattr(resource, "name")
assert hasattr(resource, "description")
assert str(resource.uri) == "data://users"
async def test_mcp_template_generation(fastmcp_server):
"""Test that templates are properly generated in MCP format."""
client = Client(transport=FastMCPTransport(fastmcp_server))
async with client:
templates = await client.list_resource_templates()
assert len(templates) == 1
template = templates[0]
# Verify template has correct MCP format
assert hasattr(template, "uriTemplate")
assert hasattr(template, "name")
assert hasattr(template, "description")
assert "data://user/{user_id}" in template.uriTemplate
async def test_template_access_via_client(fastmcp_server):
"""Test that templates can be accessed through a client."""
client = Client(transport=FastMCPTransport(fastmcp_server))
async with client:
# Verify template works correctly when accessed
uri = cast(AnyUrl, "data://user/456")
result = await client.read_resource(uri)
content_str = str(result[0])
assert '"id":"456"' in content_str
async def test_tagged_resource_metadata(tagged_resources_server):
"""Test that resource metadata is preserved in MCP format."""
client = Client(transport=FastMCPTransport(tagged_resources_server))
async with client:
resources = await client.list_resources()
assert len(resources) == 1
resource = resources[0]
# Verify resource metadata is preserved
assert str(resource.uri) == "data://tagged"
assert resource.description == "A tagged resource"
async def test_tagged_template_metadata(tagged_resources_server):
"""Test that template metadata is preserved in MCP format."""
client = Client(transport=FastMCPTransport(tagged_resources_server))
async with client:
templates = await client.list_resource_templates()
assert len(templates) == 1
template = templates[0]
# Verify template metadata is preserved
assert "template://{id}" in template.uriTemplate
assert template.description == "A tagged template"
async def test_tagged_template_functionality(tagged_resources_server):
"""Test that tagged templates function correctly when accessed."""
client = Client(transport=FastMCPTransport(tagged_resources_server))
async with client:
# Verify template functionality
uri = cast(AnyUrl, "template://123")
result = await client.read_resource(uri)
content_str = str(result[0])
assert '"id":"123"' in content_str
assert '"type":"template_data"' in content_str
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/client/client/test_client.py",
"license": "Apache License 2.0",
"lines": 541,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/client/client/test_error_handling.py | """Client error handling tests."""
import pytest
from mcp.types import TextContent
from pydantic import AnyUrl
from fastmcp.client import Client
from fastmcp.client.transports import FastMCPTransport
from fastmcp.exceptions import ResourceError, ToolError
from fastmcp.server.server import FastMCP
class TestErrorHandling:
async def test_general_tool_exceptions_are_not_masked_by_default(self):
mcp = FastMCP("TestServer")
@mcp.tool
def error_tool():
raise ValueError("This is a test error (abc)")
client = Client(transport=FastMCPTransport(mcp))
async with client:
result = await client.call_tool_mcp("error_tool", {})
assert result.isError
assert isinstance(result.content[0], TextContent)
assert "test error" in result.content[0].text
assert "abc" in result.content[0].text
async def test_general_tool_exceptions_are_masked_when_enabled(self):
mcp = FastMCP("TestServer", mask_error_details=True)
@mcp.tool
def error_tool():
raise ValueError("This is a test error (abc)")
client = Client(transport=FastMCPTransport(mcp))
async with client:
result = await client.call_tool_mcp("error_tool", {})
assert result.isError
assert isinstance(result.content[0], TextContent)
assert "test error" not in result.content[0].text
assert "abc" not in result.content[0].text
async def test_validation_errors_are_not_masked_when_enabled(self):
mcp = FastMCP("TestServer", mask_error_details=True)
@mcp.tool
def validated_tool(x: int) -> int:
return x
async with Client(transport=FastMCPTransport(mcp)) as client:
result = await client.call_tool_mcp("validated_tool", {"x": "abc"})
assert result.isError
# Pydantic validation error message should NOT be masked
assert isinstance(result.content[0], TextContent)
assert "Input should be a valid integer" in result.content[0].text
async def test_specific_tool_errors_are_sent_to_client(self):
mcp = FastMCP("TestServer")
@mcp.tool
def custom_error_tool():
raise ToolError("This is a test error (abc)")
client = Client(transport=FastMCPTransport(mcp))
async with client:
result = await client.call_tool_mcp("custom_error_tool", {})
assert result.isError
assert isinstance(result.content[0], TextContent)
assert "test error" in result.content[0].text
assert "abc" in result.content[0].text
async def test_general_resource_exceptions_are_not_masked_by_default(self):
mcp = FastMCP("TestServer")
@mcp.resource(uri="exception://resource")
async def exception_resource():
raise ValueError("This is an internal error (sensitive)")
client = Client(transport=FastMCPTransport(mcp))
async with client:
with pytest.raises(Exception) as excinfo:
await client.read_resource(AnyUrl("exception://resource"))
assert "Error reading resource" in str(excinfo.value)
assert "sensitive" in str(excinfo.value)
assert "internal error" in str(excinfo.value)
async def test_general_resource_exceptions_are_masked_when_enabled(self):
mcp = FastMCP("TestServer", mask_error_details=True)
@mcp.resource(uri="exception://resource")
async def exception_resource():
raise ValueError("This is an internal error (sensitive)")
client = Client(transport=FastMCPTransport(mcp))
async with client:
with pytest.raises(Exception) as excinfo:
await client.read_resource(AnyUrl("exception://resource"))
assert "Error reading resource" in str(excinfo.value)
assert "sensitive" not in str(excinfo.value)
assert "internal error" not in str(excinfo.value)
async def test_resource_errors_are_sent_to_client(self):
mcp = FastMCP("TestServer")
@mcp.resource(uri="error://resource")
async def error_resource():
raise ResourceError("This is a resource error (xyz)")
client = Client(transport=FastMCPTransport(mcp))
async with client:
with pytest.raises(Exception) as excinfo:
await client.read_resource(AnyUrl("error://resource"))
assert "This is a resource error (xyz)" in str(excinfo.value)
async def test_general_template_exceptions_are_not_masked_by_default(self):
mcp = FastMCP("TestServer")
@mcp.resource(uri="exception://resource/{id}")
async def exception_resource(id: str):
raise ValueError("This is an internal error (sensitive)")
client = Client(transport=FastMCPTransport(mcp))
async with client:
with pytest.raises(Exception) as excinfo:
await client.read_resource(AnyUrl("exception://resource/123"))
assert "Error reading resource" in str(excinfo.value)
assert "sensitive" in str(excinfo.value)
assert "internal error" in str(excinfo.value)
async def test_general_template_exceptions_are_masked_when_enabled(self):
mcp = FastMCP("TestServer", mask_error_details=True)
@mcp.resource(uri="exception://resource/{id}")
async def exception_resource(id: str):
raise ValueError("This is an internal error (sensitive)")
client = Client(transport=FastMCPTransport(mcp))
async with client:
with pytest.raises(Exception) as excinfo:
await client.read_resource(AnyUrl("exception://resource/123"))
assert "Error reading resource" in str(excinfo.value)
assert "sensitive" not in str(excinfo.value)
assert "internal error" not in str(excinfo.value)
async def test_template_errors_are_sent_to_client(self):
mcp = FastMCP("TestServer")
@mcp.resource(uri="error://resource/{id}")
async def error_resource(id: str):
raise ResourceError("This is a resource error (xyz)")
client = Client(transport=FastMCPTransport(mcp))
async with client:
with pytest.raises(Exception) as excinfo:
await client.read_resource(AnyUrl("error://resource/123"))
assert "This is a resource error (xyz)" in str(excinfo.value)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/client/client/test_error_handling.py",
"license": "Apache License 2.0",
"lines": 124,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/client/client/test_initialize.py | """Client initialization tests."""
from fastmcp.client import Client
from fastmcp.server.server import FastMCP
class TestInitialize:
"""Tests for client initialization behavior."""
async def test_auto_initialize_default(self, fastmcp_server):
"""Test that auto_initialize=True is the default and works automatically."""
client = Client(fastmcp_server)
async with client:
# Should be automatically initialized
assert client.initialize_result is not None
assert client.initialize_result.serverInfo.name == "TestServer"
assert client.initialize_result.instructions is None
async def test_auto_initialize_explicit_true(self, fastmcp_server):
"""Test explicit auto_initialize=True."""
client = Client(fastmcp_server, auto_initialize=True)
async with client:
assert client.initialize_result is not None
assert client.initialize_result.serverInfo.name == "TestServer"
async def test_auto_initialize_false(self, fastmcp_server):
"""Test that auto_initialize=False prevents automatic initialization."""
client = Client(fastmcp_server, auto_initialize=False)
async with client:
# Should not be automatically initialized
assert client.initialize_result is None
async def test_manual_initialize(self, fastmcp_server):
"""Test manual initialization when auto_initialize=False."""
client = Client(fastmcp_server, auto_initialize=False)
async with client:
# Manually initialize
result = await client.initialize()
assert result is not None
assert result.serverInfo.name == "TestServer"
assert client.initialize_result is result
async def test_initialize_idempotent(self, fastmcp_server):
"""Test that calling initialize() multiple times returns cached result."""
client = Client(fastmcp_server, auto_initialize=False)
async with client:
result1 = await client.initialize()
result2 = await client.initialize()
result3 = await client.initialize()
# All should return the same cached result
assert result1 is result2
assert result2 is result3
async def test_initialize_with_instructions(self):
"""Test that server instructions are available via initialize_result."""
server = FastMCP("InstructionsServer", instructions="Use the greet tool!")
@server.tool
def greet(name: str) -> str:
return f"Hello, {name}!"
client = Client(server)
async with client:
result = client.initialize_result
assert result is not None
assert result.instructions == "Use the greet tool!"
async def test_initialize_timeout_custom(self, fastmcp_server):
"""Test custom timeout for initialize()."""
client = Client(fastmcp_server, auto_initialize=False)
async with client:
# Should succeed with reasonable timeout
result = await client.initialize(timeout=5.0)
assert result is not None
async def test_initialize_property_after_auto_init(self, fastmcp_server):
"""Test accessing initialize_result property after auto-initialization."""
client = Client(fastmcp_server, auto_initialize=True)
async with client:
# Access via property
result = client.initialize_result
assert result is not None
assert result.serverInfo.name == "TestServer"
# Call method - should return cached
result2 = await client.initialize()
assert result is result2
async def test_initialize_property_before_connect(self, fastmcp_server):
"""Test that initialize_result property is None before connection."""
client = Client(fastmcp_server)
# Not yet connected
assert client.initialize_result is None
async def test_manual_initialize_can_call_tools(self, fastmcp_server):
"""Test that manually initialized client can call tools."""
client = Client(fastmcp_server, auto_initialize=False)
async with client:
await client.initialize()
# Should be able to call tools after manual initialization
result = await client.call_tool("greet", {"name": "World"})
assert "Hello, World!" in str(result.content)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/client/client/test_initialize.py",
"license": "Apache License 2.0",
"lines": 86,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/client/client/test_session.py | """Client session and task error propagation tests."""
import asyncio
import pytest
from fastmcp.client import Client
class TestSessionTaskErrorPropagation:
"""Tests for ensuring session task errors propagate to client calls.
Regression tests for https://github.com/PrefectHQ/fastmcp/issues/2595
where the client would hang indefinitely when the session task failed
(e.g., due to HTTP 4xx/5xx errors) instead of raising an exception.
"""
async def test_session_task_error_propagates_to_call(self, fastmcp_server):
"""Test that errors in session task propagate to pending client calls.
When the session task fails (e.g., due to HTTP errors), pending
client operations should immediately receive the exception rather
than hanging indefinitely.
"""
client = Client(fastmcp_server)
async with client:
original_task = client._session_state.session_task
assert original_task is not None
async def never_complete():
"""A coroutine that will never complete normally."""
await asyncio.sleep(1000)
async def failing_session():
"""Simulates a session task that raises an error."""
raise ValueError("Simulated HTTP error")
# Replace session_task with one that will fail
client._session_state.session_task = asyncio.create_task(failing_session())
# The monitoring should detect the session task failure
with pytest.raises(ValueError, match="Simulated HTTP error"):
await client._await_with_session_monitoring(never_complete())
# Restore original task for cleanup
client._session_state.session_task = original_task
async def test_session_task_already_done_with_error(self, fastmcp_server):
"""Test that if session task is already done with error, calls fail immediately."""
client = Client(fastmcp_server)
async with client:
original_task = client._session_state.session_task
async def raise_error():
raise ValueError("Session failed")
# Replace session_task with one that has already failed
failed_task = asyncio.create_task(raise_error())
try:
await failed_task
except ValueError:
pass # Expected
client._session_state.session_task = failed_task
# New calls should fail immediately with the original error
async def simple_coro():
return "should not reach"
with pytest.raises(ValueError, match="Session failed"):
await client._await_with_session_monitoring(simple_coro())
# Restore original task for cleanup
client._session_state.session_task = original_task
async def test_session_task_already_done_no_error_raises_runtime_error(
self, fastmcp_server
):
"""Test that if session task completes without error, raises RuntimeError."""
client = Client(fastmcp_server)
async with client:
original_task = client._session_state.session_task
# Create a task that completes normally (unexpected for session task)
completed_task = asyncio.create_task(asyncio.sleep(0))
await completed_task
client._session_state.session_task = completed_task
async def simple_coro():
return "should not reach"
with pytest.raises(
RuntimeError, match="Session task completed unexpectedly"
):
await client._await_with_session_monitoring(simple_coro())
# Restore original task for cleanup
client._session_state.session_task = original_task
async def test_normal_operation_unaffected(self, fastmcp_server):
"""Test that normal operation is unaffected by the monitoring."""
client = Client(fastmcp_server)
async with client:
# These should all work normally
tools = await client.list_tools()
assert len(tools) > 0
result = await client.call_tool("greet", {"name": "Test"})
assert "Hello, Test!" in str(result.content)
resources = await client.list_resources()
assert len(resources) > 0
prompts = await client.list_prompts()
assert len(prompts) > 0
async def test_no_session_task_falls_back_to_direct_await(self, fastmcp_server):
"""Test that when no session task exists, it falls back to direct await."""
client = Client(fastmcp_server)
async with client:
# Temporarily remove session_task to test fallback
original_task = client._session_state.session_task
client._session_state.session_task = None
# Should work via direct await
async def simple_coro():
return "success"
result = await client._await_with_session_monitoring(simple_coro())
assert result == "success"
# Restore for cleanup
client._session_state.session_task = original_task
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/client/client/test_session.py",
"license": "Apache License 2.0",
"lines": 100,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/client/client/test_timeout.py | """Client timeout tests."""
import sys
import pytest
from mcp import McpError
from fastmcp.client import Client
from fastmcp.client.transports import FastMCPTransport
from fastmcp.server.server import FastMCP
class TestTimeout:
async def test_timeout(self, fastmcp_server: FastMCP):
async with Client(
transport=FastMCPTransport(fastmcp_server), timeout=0.05
) as client:
with pytest.raises(
McpError,
match="Timed out while waiting for response to ClientRequest. Waited 0.05 seconds",
):
await client.call_tool("sleep", {"seconds": 0.1})
async def test_timeout_tool_call(self, fastmcp_server: FastMCP):
async with Client(transport=FastMCPTransport(fastmcp_server)) as client:
with pytest.raises(McpError):
await client.call_tool("sleep", {"seconds": 0.1}, timeout=0.01)
async def test_timeout_tool_call_overrides_client_timeout(
self, fastmcp_server: FastMCP
):
async with Client(
transport=FastMCPTransport(fastmcp_server),
timeout=2,
) as client:
with pytest.raises(McpError):
await client.call_tool("sleep", {"seconds": 0.1}, timeout=0.01)
@pytest.mark.skipif(
sys.platform == "win32",
reason="This test is flaky on Windows. Sometimes the client timeout is respected and sometimes it is not.",
)
async def test_timeout_tool_call_overrides_client_timeout_even_if_lower(
self, fastmcp_server: FastMCP
):
async with Client(
transport=FastMCPTransport(fastmcp_server),
timeout=0.01,
) as client:
await client.call_tool("sleep", {"seconds": 0.1}, timeout=2)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/client/client/test_timeout.py",
"license": "Apache License 2.0",
"lines": 42,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/client/client/test_transport.py | """Client transport inference tests."""
import pytest
from fastmcp.client.transports import (
FastMCPTransport,
MCPConfigTransport,
SSETransport,
StdioTransport,
StreamableHttpTransport,
infer_transport,
)
class TestInferTransport:
"""Tests for the infer_transport function."""
@pytest.mark.parametrize(
"url",
[
"http://example.com/api/sse/stream",
"https://localhost:8080/mcp/sse/endpoint",
"http://example.com/api/sse",
"http://example.com/api/sse/",
"https://localhost:8080/mcp/sse/",
"http://example.com/api/sse?param=value",
"https://localhost:8080/mcp/sse/?param=value",
"https://localhost:8000/mcp/sse?x=1&y=2",
],
ids=[
"path_with_sse_directory",
"path_with_sse_subdirectory",
"path_ending_with_sse",
"path_ending_with_sse_slash",
"path_ending_with_sse_https",
"path_with_sse_and_query_params",
"path_with_sse_slash_and_query_params",
"path_with_sse_and_ampersand_param",
],
)
def test_url_returns_sse_transport(self, url):
"""Test that URLs with /sse/ pattern return SSETransport."""
assert isinstance(infer_transport(url), SSETransport)
@pytest.mark.parametrize(
"url",
[
"http://example.com/api",
"https://localhost:8080/mcp/",
"http://example.com/asset/image.jpg",
"https://localhost:8080/sservice/endpoint",
"https://example.com/assets/file",
],
ids=[
"regular_http_url",
"regular_https_url",
"url_with_unrelated_path",
"url_with_sservice_in_path",
"url_with_assets_in_path",
],
)
def test_url_returns_streamable_http_transport(self, url):
"""Test that URLs without /sse/ pattern return StreamableHttpTransport."""
assert isinstance(infer_transport(url), StreamableHttpTransport)
def test_infer_remote_transport_from_config(self):
config = {
"mcpServers": {
"test_server": {
"url": "http://localhost:8000/sse/",
"headers": {"Authorization": "Bearer 123"},
},
}
}
transport = infer_transport(config)
assert isinstance(transport, MCPConfigTransport)
assert isinstance(transport.transport, SSETransport)
assert transport.transport.url == "http://localhost:8000/sse/"
assert transport.transport.headers == {"Authorization": "Bearer 123"}
def test_infer_local_transport_from_config(self):
config = {
"mcpServers": {
"test_server": {
"command": "echo",
"args": ["hello"],
},
}
}
transport = infer_transport(config)
assert isinstance(transport, MCPConfigTransport)
assert isinstance(transport.transport, StdioTransport)
assert transport.transport.command == "echo"
assert transport.transport.args == ["hello"]
def test_config_with_no_servers(self):
"""Test that an empty MCPConfig raises a ValueError."""
config = {"mcpServers": {}}
with pytest.raises(ValueError, match="No MCP servers defined in the config"):
infer_transport(config)
def test_mcpconfigtransport_with_no_servers(self):
"""Test that MCPConfigTransport raises a ValueError when initialized with an empty config."""
config = {"mcpServers": {}}
with pytest.raises(ValueError, match="No MCP servers defined in the config"):
MCPConfigTransport(config=config)
def test_infer_composite_client(self):
config = {
"mcpServers": {
"local": {
"command": "echo",
"args": ["hello"],
},
"remote": {
"url": "http://localhost:8000/sse/",
"headers": {"Authorization": "Bearer 123"},
},
}
}
transport = infer_transport(config)
assert isinstance(transport, MCPConfigTransport)
# Multi-server configs create composite server at connect time
assert len(transport.config.mcpServers) == 2
def test_infer_fastmcp_server(self, fastmcp_server):
"""FastMCP server instances should infer to FastMCPTransport."""
transport = infer_transport(fastmcp_server)
assert isinstance(transport, FastMCPTransport)
def test_infer_fastmcp_v1_server(self):
"""FastMCP 1.0 server instances should infer to FastMCPTransport."""
from mcp.server.fastmcp import FastMCP as FastMCP1
server = FastMCP1()
transport = infer_transport(server)
assert isinstance(transport, FastMCPTransport)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/client/client/test_transport.py",
"license": "Apache License 2.0",
"lines": 123,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/auth/oauth_proxy/test_authorization.py | """Tests for OAuth proxy authorization flow."""
from urllib.parse import parse_qs, urlparse
import pytest
from key_value.aio.stores.memory import MemoryStore
from mcp.server.auth.provider import AuthorizationParams
from mcp.shared.auth import OAuthClientInformationFull
from pydantic import AnyUrl
from fastmcp.server.auth.oauth_proxy import OAuthProxy
class TestOAuthProxyAuthorization:
"""Tests for OAuth proxy authorization flow."""
async def test_authorize_creates_transaction(self, oauth_proxy):
"""Test that authorize creates transaction and redirects to consent."""
client = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:54321/callback")],
jwt_signing_key="test-secret", # type: ignore[call-arg] # Optional field in MCP SDK
)
# Register client first (required for consent flow)
await oauth_proxy.register_client(client)
params = AuthorizationParams(
redirect_uri=AnyUrl("http://localhost:54321/callback"),
redirect_uri_provided_explicitly=True,
state="client-state-123",
code_challenge="challenge-abc",
scopes=["read", "write"],
)
redirect_url = await oauth_proxy.authorize(client, params)
# Parse the redirect URL
parsed = urlparse(redirect_url)
query_params = parse_qs(parsed.query)
# Should redirect to consent page
assert "/consent" in redirect_url
assert "txn_id" in query_params
# Verify transaction was stored with correct data
txn_id = query_params["txn_id"][0]
transaction = await oauth_proxy._transaction_store.get(key=txn_id)
assert transaction is not None
assert transaction.client_id == "test-client"
assert transaction.code_challenge == "challenge-abc"
assert transaction.client_state == "client-state-123"
assert transaction.scopes == ["read", "write"]
class TestOAuthProxyPKCE:
"""Tests for OAuth proxy PKCE forwarding."""
@pytest.fixture
def proxy_with_pkce(self, jwt_verifier):
return OAuthProxy(
upstream_authorization_endpoint="https://oauth.example.com/authorize",
upstream_token_endpoint="https://oauth.example.com/token",
upstream_client_id="upstream-client",
upstream_client_secret="upstream-secret",
token_verifier=jwt_verifier,
base_url="https://proxy.example.com",
forward_pkce=True,
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
@pytest.fixture
def proxy_without_pkce(self, jwt_verifier):
from fastmcp.server.auth.oauth_proxy import OAuthProxy
return OAuthProxy(
upstream_authorization_endpoint="https://oauth.example.com/authorize",
upstream_token_endpoint="https://oauth.example.com/token",
upstream_client_id="upstream-client",
upstream_client_secret="upstream-secret",
token_verifier=jwt_verifier,
base_url="https://proxy.example.com",
forward_pkce=False,
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
async def test_pkce_forwarding_enabled(self, proxy_with_pkce):
"""Test that proxy generates and forwards its own PKCE."""
client = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:12345/callback")],
)
# Register client first
await proxy_with_pkce.register_client(client)
params = AuthorizationParams(
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
state="client-state",
code_challenge="client_challenge",
scopes=["read"],
)
redirect_url = await proxy_with_pkce.authorize(client, params)
query_params = parse_qs(urlparse(redirect_url).query)
# Should redirect to consent page
assert "/consent" in redirect_url
assert "txn_id" in query_params
# Transaction should store both challenges
txn_id = query_params["txn_id"][0]
transaction = await proxy_with_pkce._transaction_store.get(key=txn_id)
assert transaction is not None
assert transaction.code_challenge == "client_challenge" # Client's
assert transaction.proxy_code_verifier is not None # Proxy's verifier
# Proxy code challenge is computed from verifier when building upstream URL
# Just verify the verifier exists and is different from client's challenge
assert len(transaction.proxy_code_verifier) > 0
async def test_pkce_forwarding_disabled(self, proxy_without_pkce):
"""Test that PKCE is not forwarded when disabled."""
client = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:12345/callback")],
)
# Register client first
await proxy_without_pkce.register_client(client)
params = AuthorizationParams(
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
state="client-state",
code_challenge="client_challenge",
scopes=["read"],
)
redirect_url = await proxy_without_pkce.authorize(client, params)
query_params = parse_qs(urlparse(redirect_url).query)
# Should redirect to consent page
assert "/consent" in redirect_url
assert "txn_id" in query_params
# Client's challenge still stored, but no proxy PKCE
txn_id = query_params["txn_id"][0]
transaction = await proxy_without_pkce._transaction_store.get(key=txn_id)
assert transaction is not None
assert transaction.code_challenge == "client_challenge"
assert transaction.proxy_code_verifier is None # No proxy PKCE when disabled
class TestParameterForwarding:
"""Tests for parameter forwarding in OAuth proxy."""
async def test_extra_authorize_params_forwarded(self, jwt_verifier):
"""Test that extra authorize parameters are forwarded to upstream."""
proxy = OAuthProxy(
upstream_authorization_endpoint="https://oauth.example.com/authorize",
upstream_token_endpoint="https://oauth.example.com/token",
upstream_client_id="upstream-client",
upstream_client_secret="upstream-secret",
token_verifier=jwt_verifier,
base_url="https://proxy.example.com",
jwt_signing_key="test-secret",
extra_authorize_params={
"audience": "https://api.example.com",
"prompt": "consent",
"max_age": "3600",
},
client_storage=MemoryStore(),
)
client = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:12345/callback")],
)
await proxy.register_client(client)
params = AuthorizationParams(
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
state="client-state",
code_challenge="challenge",
scopes=["read"],
# No resource parameter
)
# Should succeed (no resource check needed)
redirect_url = await proxy.authorize(client, params)
assert "/consent" in redirect_url
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/auth/oauth_proxy/test_authorization.py",
"license": "Apache License 2.0",
"lines": 164,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/auth/oauth_proxy/test_client_registration.py | """Tests for OAuth proxy client registration (DCR)."""
from mcp.shared.auth import OAuthClientInformationFull
from pydantic import AnyUrl
class TestOAuthProxyClientRegistration:
"""Tests for OAuth proxy client registration (DCR)."""
async def test_register_client(self, oauth_proxy):
"""Test client registration creates ProxyDCRClient."""
client_info = OAuthClientInformationFull(
client_id="original-client",
client_secret="original-secret",
redirect_uris=[AnyUrl("http://localhost:12345/callback")],
)
await oauth_proxy.register_client(client_info)
# Client should be retrievable with original credentials
stored = await oauth_proxy.get_client("original-client")
assert stored is not None
assert stored.client_id == "original-client"
# Proxy uses token_endpoint_auth_method="none", so client_secret is not stored
assert stored.client_secret is None
async def test_get_registered_client(self, oauth_proxy):
"""Test retrieving a registered client."""
client_info = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:8080/callback")],
)
await oauth_proxy.register_client(client_info)
retrieved = await oauth_proxy.get_client("test-client")
assert retrieved is not None
assert retrieved.client_id == "test-client"
async def test_get_unregistered_client_returns_none(self, oauth_proxy):
"""Test that unregistered clients return None."""
client = await oauth_proxy.get_client("unknown-client")
assert client is None
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/auth/oauth_proxy/test_client_registration.py",
"license": "Apache License 2.0",
"lines": 34,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/auth/oauth_proxy/test_config.py | """Tests for OAuth proxy configuration and validation."""
import pytest
from key_value.aio.stores.memory import MemoryStore
from mcp.server.auth.provider import AuthorizationParams, AuthorizeError
from mcp.shared.auth import OAuthClientInformationFull
from pydantic import AnyHttpUrl, AnyUrl
from fastmcp.server.auth.oauth_proxy import OAuthProxy
from fastmcp.server.auth.oauth_proxy.proxy import (
_normalize_resource_url,
_server_url_has_query,
)
class TestNormalizeResourceUrl:
"""Unit tests for the _normalize_resource_url helper function."""
@pytest.mark.parametrize(
"url,expected",
[
# Basic URL unchanged
("https://example.com/mcp", "https://example.com/mcp"),
# Query parameters stripped
("https://example.com/mcp?foo=bar", "https://example.com/mcp"),
("https://example.com/mcp?a=1&b=2", "https://example.com/mcp"),
# Fragments stripped
("https://example.com/mcp#section", "https://example.com/mcp"),
# Both query and fragment stripped
("https://example.com/mcp?foo=bar#section", "https://example.com/mcp"),
# Trailing slash stripped
("https://example.com/mcp/", "https://example.com/mcp"),
# Trailing slash with query params
("https://example.com/mcp/?foo=bar", "https://example.com/mcp"),
# Preserves path structure
(
"https://example.com/api/v2/mcp?kb_name=test",
"https://example.com/api/v2/mcp",
),
# Preserves port
("https://example.com:8080/mcp?foo=bar", "https://example.com:8080/mcp"),
# Root path
("https://example.com/?foo=bar", "https://example.com"),
("https://example.com/", "https://example.com"),
],
)
def test_normalizes_urls_correctly(self, url: str, expected: str):
"""Test that URLs are normalized by stripping query params, fragments, and trailing slashes."""
assert _normalize_resource_url(url) == expected
@pytest.mark.parametrize(
"url,has_query",
[
("https://example.com/mcp", False),
("https://example.com/mcp?foo=bar", True),
("https://example.com/mcp?", False), # Empty query string
("https://example.com/mcp#fragment", False),
("https://example.com/mcp?a=1&b=2", True),
],
)
def test_server_url_has_query(self, url: str, has_query: bool):
"""Test detection of query parameters in server URLs."""
assert _server_url_has_query(url) == has_query
class TestResourceURLValidation:
"""Tests for OAuth Proxy resource URL validation (GHSA-5h2m-4q8j-pqpj fix)."""
@pytest.fixture
def proxy_with_resource_url(self, jwt_verifier):
"""Create an OAuthProxy with set_mcp_path called."""
proxy = OAuthProxy(
upstream_authorization_endpoint="https://oauth.example.com/authorize",
upstream_token_endpoint="https://oauth.example.com/token",
upstream_client_id="upstream-client",
upstream_client_secret="upstream-secret",
token_verifier=jwt_verifier,
base_url="https://proxy.example.com",
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
# Use non-default path to prove fix isn't relying on old hardcoded /mcp
proxy.set_mcp_path("/api/v2/mcp")
return proxy
async def test_authorize_rejects_mismatched_resource(self, proxy_with_resource_url):
"""Test that authorization rejects requests with mismatched resource."""
client = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:12345/callback")],
)
await proxy_with_resource_url.register_client(client)
# Client requests a different resource than the server's
params = AuthorizationParams(
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
state="client-state",
code_challenge="challenge",
scopes=["read"],
resource="https://malicious-server.com/mcp", # Wrong resource
)
with pytest.raises(AuthorizeError) as exc_info:
await proxy_with_resource_url.authorize(client, params)
assert exc_info.value.error == "invalid_target"
assert "Resource does not match" in exc_info.value.error_description
async def test_authorize_accepts_matching_resource(self, proxy_with_resource_url):
"""Test that authorization accepts requests with matching resource."""
client = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:12345/callback")],
)
await proxy_with_resource_url.register_client(client)
# Client requests the correct resource (must match /api/v2/mcp path)
params = AuthorizationParams(
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
state="client-state",
code_challenge="challenge",
scopes=["read"],
resource="https://proxy.example.com/api/v2/mcp", # Correct resource
)
# Should succeed (redirect to consent page)
redirect_url = await proxy_with_resource_url.authorize(client, params)
assert "/consent" in redirect_url
async def test_authorize_rejects_old_hardcoded_mcp_path(
self, proxy_with_resource_url
):
"""Test that old hardcoded /mcp path is rejected when server uses different path."""
client = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:12345/callback")],
)
await proxy_with_resource_url.register_client(client)
# Client requests the old hardcoded /mcp path (would have worked before fix)
params = AuthorizationParams(
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
state="client-state",
code_challenge="challenge",
scopes=["read"],
resource="https://proxy.example.com/mcp", # Old hardcoded path
)
# Should fail because server is at /api/v2/mcp, not /mcp
with pytest.raises(AuthorizeError) as exc_info:
await proxy_with_resource_url.authorize(client, params)
assert exc_info.value.error == "invalid_target"
async def test_authorize_accepts_no_resource(self, proxy_with_resource_url):
"""Test that authorization accepts requests without resource parameter."""
client = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:12345/callback")],
)
await proxy_with_resource_url.register_client(client)
# Client doesn't specify resource
params = AuthorizationParams(
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
state="client-state",
code_challenge="challenge",
scopes=["read"],
# No resource parameter
)
# Should succeed (no resource check needed)
redirect_url = await proxy_with_resource_url.authorize(client, params)
assert "/consent" in redirect_url
async def test_authorize_accepts_resource_with_query_params(
self, proxy_with_resource_url
):
"""Test that authorization accepts resource URLs with query parameters.
Per RFC 8707, clients may include query parameters in resource URLs.
ChatGPT sends resource URLs like ?kb_name=X, which should match the
server's resource URL that doesn't include query params.
"""
client = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:12345/callback")],
)
await proxy_with_resource_url.register_client(client)
# Client requests resource with query params (like ChatGPT does)
params = AuthorizationParams(
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
state="client-state",
code_challenge="challenge",
scopes=["read"],
resource="https://proxy.example.com/api/v2/mcp?kb_name=test",
)
# Should succeed - base URL matches, query params are normalized away
redirect_url = await proxy_with_resource_url.authorize(client, params)
assert "/consent" in redirect_url
async def test_authorize_rejects_different_path_with_query_params(
self, proxy_with_resource_url
):
"""Test that query param normalization doesn't bypass path validation."""
client = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:12345/callback")],
)
await proxy_with_resource_url.register_client(client)
# Client requests wrong path but with query params
params = AuthorizationParams(
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
state="client-state",
code_challenge="challenge",
scopes=["read"],
resource="https://proxy.example.com/wrong/path?kb_name=test",
)
# Should fail - path doesn't match even after normalizing query params
with pytest.raises(AuthorizeError) as exc_info:
await proxy_with_resource_url.authorize(client, params)
assert exc_info.value.error == "invalid_target"
async def test_authorize_requires_exact_match_when_server_has_query_params(
self, jwt_verifier
):
"""Test that when server URL has query params, exact match is required.
If a server configures its resource URL with query params (e.g., for
multi-tenant or per-KB scoping), clients must provide the exact same
query params. This prevents bypassing tenant isolation.
"""
proxy = OAuthProxy(
upstream_authorization_endpoint="https://oauth.example.com/authorize",
upstream_token_endpoint="https://oauth.example.com/token",
upstream_client_id="upstream-client",
upstream_client_secret="upstream-secret",
token_verifier=jwt_verifier,
base_url="https://proxy.example.com",
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
proxy.set_mcp_path("/mcp")
# Simulate server configured with query params for tenant scoping
proxy._resource_url = AnyHttpUrl("https://proxy.example.com/mcp?tenant=acme")
client = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:12345/callback")],
)
await proxy.register_client(client)
# Client requests with DIFFERENT query params - should fail
params = AuthorizationParams(
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
state="client-state",
code_challenge="challenge",
scopes=["read"],
resource="https://proxy.example.com/mcp?tenant=other", # Wrong tenant!
)
with pytest.raises(AuthorizeError) as exc_info:
await proxy.authorize(client, params)
assert exc_info.value.error == "invalid_target"
async def test_authorize_accepts_exact_match_when_server_has_query_params(
self, jwt_verifier
):
"""Test that exact query param match succeeds when server has query params."""
proxy = OAuthProxy(
upstream_authorization_endpoint="https://oauth.example.com/authorize",
upstream_token_endpoint="https://oauth.example.com/token",
upstream_client_id="upstream-client",
upstream_client_secret="upstream-secret",
token_verifier=jwt_verifier,
base_url="https://proxy.example.com",
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
proxy.set_mcp_path("/mcp")
# Simulate server configured with query params for tenant scoping
proxy._resource_url = AnyHttpUrl("https://proxy.example.com/mcp?tenant=acme")
client = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:12345/callback")],
)
await proxy.register_client(client)
# Client requests with SAME query params - should succeed
params = AuthorizationParams(
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
state="client-state",
code_challenge="challenge",
scopes=["read"],
resource="https://proxy.example.com/mcp?tenant=acme", # Exact match
)
redirect_url = await proxy.authorize(client, params)
assert "/consent" in redirect_url
async def test_authorize_rejects_no_query_when_server_has_query_params(
self, jwt_verifier
):
"""Test that missing query params are rejected when server requires them."""
proxy = OAuthProxy(
upstream_authorization_endpoint="https://oauth.example.com/authorize",
upstream_token_endpoint="https://oauth.example.com/token",
upstream_client_id="upstream-client",
upstream_client_secret="upstream-secret",
token_verifier=jwt_verifier,
base_url="https://proxy.example.com",
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
proxy.set_mcp_path("/mcp")
# Simulate server configured with query params for tenant scoping
proxy._resource_url = AnyHttpUrl("https://proxy.example.com/mcp?tenant=acme")
client = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:12345/callback")],
)
await proxy.register_client(client)
# Client requests WITHOUT query params - should fail
params = AuthorizationParams(
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
state="client-state",
code_challenge="challenge",
scopes=["read"],
resource="https://proxy.example.com/mcp", # Missing tenant param!
)
with pytest.raises(AuthorizeError) as exc_info:
await proxy.authorize(client, params)
assert exc_info.value.error == "invalid_target"
def test_set_mcp_path_creates_jwt_issuer_with_correct_audience(self, jwt_verifier):
"""Test that set_mcp_path creates JWTIssuer with correct audience."""
proxy = OAuthProxy(
upstream_authorization_endpoint="https://oauth.example.com/authorize",
upstream_token_endpoint="https://oauth.example.com/token",
upstream_client_id="upstream-client",
upstream_client_secret="upstream-secret",
token_verifier=jwt_verifier,
base_url="https://proxy.example.com",
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
# Before set_mcp_path, _jwt_issuer is None
assert proxy._jwt_issuer is None
# Call set_mcp_path with custom path
proxy.set_mcp_path("/custom/mcp")
# After set_mcp_path, _jwt_issuer should be created
assert proxy._jwt_issuer is not None
assert proxy.jwt_issuer.audience == "https://proxy.example.com/custom/mcp"
assert proxy.jwt_issuer.issuer == "https://proxy.example.com/"
def test_set_mcp_path_uses_base_url_if_no_path(self, jwt_verifier):
"""Test that set_mcp_path uses base_url as audience if no path provided."""
proxy = OAuthProxy(
upstream_authorization_endpoint="https://oauth.example.com/authorize",
upstream_token_endpoint="https://oauth.example.com/token",
upstream_client_id="upstream-client",
upstream_client_secret="upstream-secret",
token_verifier=jwt_verifier,
base_url="https://proxy.example.com",
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
proxy.set_mcp_path(None)
assert proxy.jwt_issuer.audience == "https://proxy.example.com/"
def test_jwt_issuer_property_raises_if_not_initialized(self, jwt_verifier):
"""Test that jwt_issuer property raises if set_mcp_path not called."""
proxy = OAuthProxy(
upstream_authorization_endpoint="https://oauth.example.com/authorize",
upstream_token_endpoint="https://oauth.example.com/token",
upstream_client_id="upstream-client",
upstream_client_secret="upstream-secret",
token_verifier=jwt_verifier,
base_url="https://proxy.example.com",
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
with pytest.raises(RuntimeError) as exc_info:
_ = proxy.jwt_issuer
assert "JWT issuer not initialized" in str(exc_info.value)
def test_get_routes_calls_set_mcp_path(self, jwt_verifier):
"""Test that get_routes() calls set_mcp_path() to initialize JWT issuer."""
proxy = OAuthProxy(
upstream_authorization_endpoint="https://oauth.example.com/authorize",
upstream_token_endpoint="https://oauth.example.com/token",
upstream_client_id="upstream-client",
upstream_client_secret="upstream-secret",
token_verifier=jwt_verifier,
base_url="https://proxy.example.com",
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
# Before get_routes, _jwt_issuer is None
assert proxy._jwt_issuer is None
# get_routes should call set_mcp_path internally
proxy.get_routes("/api/mcp")
# After get_routes, _jwt_issuer should be created with correct audience
assert proxy._jwt_issuer is not None
assert proxy.jwt_issuer.audience == "https://proxy.example.com/api/mcp"
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/auth/oauth_proxy/test_config.py",
"license": "Apache License 2.0",
"lines": 384,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/auth/oauth_proxy/test_e2e.py | """End-to-end tests for OAuth proxy using mock provider."""
import time
from unittest.mock import AsyncMock, patch
from urllib.parse import parse_qs, urlparse
import httpx
from key_value.aio.stores.memory import MemoryStore
from mcp.server.auth.provider import AuthorizationCode, AuthorizationParams
from mcp.shared.auth import OAuthClientInformationFull
from pydantic import AnyUrl
from fastmcp import FastMCP
from fastmcp.server.auth.auth import RefreshToken
from fastmcp.server.auth.oauth_proxy import OAuthProxy
from fastmcp.server.auth.oauth_proxy.models import ClientCode
from tests.server.auth.oauth_proxy.conftest import MockTokenVerifier
class TestOAuthProxyE2E:
"""End-to-end tests using mock OAuth provider."""
async def test_full_oauth_flow_with_mock_provider(self, mock_oauth_provider):
"""Test complete OAuth flow with mock provider."""
# Create proxy pointing to mock provider
proxy = OAuthProxy(
upstream_authorization_endpoint=mock_oauth_provider.authorize_endpoint,
upstream_token_endpoint=mock_oauth_provider.token_endpoint,
upstream_client_id="mock-client",
upstream_client_secret="mock-secret",
token_verifier=MockTokenVerifier(),
base_url="http://localhost:8000",
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
# Create FastMCP server with proxy
server = FastMCP("Test Server", auth=proxy)
@server.tool
def protected_tool() -> str:
return "Protected data"
# Start authorization flow
client_info = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:12345/callback")],
)
# Register client first
await proxy.register_client(client_info)
params = AuthorizationParams(
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
state="client-state",
code_challenge="", # Empty string for no PKCE
scopes=["read"],
)
# Get authorization URL (now returns consent redirect)
auth_url = await proxy.authorize(client_info, params)
# Should redirect to consent page
assert "/consent" in auth_url
query_params = parse_qs(urlparse(auth_url).query)
assert "txn_id" in query_params
# Verify transaction was created with correct configuration
txn_id = query_params["txn_id"][0]
transaction = await proxy._transaction_store.get(key=txn_id)
assert transaction is not None
assert transaction.client_id == "test-client"
assert transaction.scopes == ["read"]
# Transaction ID itself is used as upstream state parameter
assert transaction.txn_id == txn_id
async def test_token_refresh_with_mock_provider(self, mock_oauth_provider):
"""Test token refresh flow with mock provider."""
proxy = OAuthProxy(
upstream_authorization_endpoint=mock_oauth_provider.authorize_endpoint,
upstream_token_endpoint=mock_oauth_provider.token_endpoint,
upstream_client_id="mock-client",
upstream_client_secret="mock-secret",
token_verifier=MockTokenVerifier(),
base_url="http://localhost:8000",
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
# Initialize JWT issuer before token operations
proxy.set_mcp_path("/mcp")
client = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:12345/callback")],
)
# Register client first
await proxy.register_client(client)
# Set up initial upstream tokens in mock provider
upstream_refresh_token = "mock_refresh_initial"
mock_oauth_provider.refresh_tokens[upstream_refresh_token] = {
"client_id": "mock-client",
"scope": "read write",
}
with patch(
"fastmcp.server.auth.oauth_proxy.proxy.AsyncOAuth2Client"
) as MockClient:
mock_client = AsyncMock()
# Mock initial token exchange to get FastMCP tokens
mock_client.fetch_token = AsyncMock(
return_value={
"access_token": "upstream-access-initial",
"refresh_token": upstream_refresh_token,
"expires_in": 3600,
"token_type": "Bearer",
}
)
# Configure mock to call real provider for refresh
async def mock_refresh(*args, **kwargs):
async with httpx.AsyncClient() as http:
response = await http.post(
mock_oauth_provider.token_endpoint,
data={
"grant_type": "refresh_token",
"refresh_token": upstream_refresh_token,
},
)
return response.json()
mock_client.refresh_token = mock_refresh
MockClient.return_value = mock_client
# Store client code that would be created during OAuth callback
client_code = ClientCode(
code="test-auth-code",
client_id="test-client",
redirect_uri="http://localhost:12345/callback",
code_challenge="",
code_challenge_method="S256",
scopes=["read", "write"],
idp_tokens={
"access_token": "upstream-access-initial",
"refresh_token": upstream_refresh_token,
"expires_in": 3600,
"token_type": "Bearer",
},
expires_at=time.time() + 300,
created_at=time.time(),
)
await proxy._code_store.put(key=client_code.code, value=client_code)
# Exchange authorization code to get FastMCP tokens
auth_code = AuthorizationCode(
code="test-auth-code",
scopes=["read", "write"],
expires_at=time.time() + 300,
client_id="test-client",
code_challenge="",
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
)
initial_result = await proxy.exchange_authorization_code(
client=client,
authorization_code=auth_code,
)
# Now test refresh with the valid FastMCP refresh token
assert initial_result.refresh_token is not None
fastmcp_refresh = RefreshToken(
token=initial_result.refresh_token,
client_id="test-client",
scopes=["read"],
expires_at=None,
)
result = await proxy.exchange_refresh_token(
client, fastmcp_refresh, ["read"]
)
# Should return new FastMCP tokens (not upstream tokens)
assert result.access_token != "upstream-access-initial"
# FastMCP tokens are JWTs (have 3 segments)
assert len(result.access_token.split(".")) == 3
assert mock_oauth_provider.refresh_called
async def test_pkce_validation_with_mock_provider(self, mock_oauth_provider):
"""Test PKCE validation with mock provider."""
mock_oauth_provider.require_pkce = True
proxy = OAuthProxy(
upstream_authorization_endpoint=mock_oauth_provider.authorize_endpoint,
upstream_token_endpoint=mock_oauth_provider.token_endpoint,
upstream_client_id="mock-client",
upstream_client_secret="mock-secret",
token_verifier=MockTokenVerifier(),
base_url="http://localhost:8000",
forward_pkce=True, # Enable PKCE forwarding
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
client = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:12345/callback")],
)
# Register client first
await proxy.register_client(client)
params = AuthorizationParams(
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
state="client-state",
code_challenge="client_challenge_value",
scopes=["read"],
)
# Start authorization with PKCE
auth_url = await proxy.authorize(client, params)
query_params = parse_qs(urlparse(auth_url).query)
# Should redirect to consent page
assert "/consent" in auth_url
assert "txn_id" in query_params
# Transaction should have proxy's PKCE verifier (different from client's)
txn_id = query_params["txn_id"][0]
transaction = await proxy._transaction_store.get(key=txn_id)
assert transaction is not None
assert (
transaction.code_challenge == "client_challenge_value"
) # Client's challenge
assert transaction.proxy_code_verifier is not None # Proxy generated its own
# Proxy code challenge is computed from verifier when needed
assert len(transaction.proxy_code_verifier) > 0
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/auth/oauth_proxy/test_e2e.py",
"license": "Apache License 2.0",
"lines": 208,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/auth/oauth_proxy/test_oauth_proxy.py | """Tests for OAuth proxy initialization and configuration."""
import httpx
from key_value.aio.stores.memory import MemoryStore
from starlette.applications import Starlette
from fastmcp.server.auth.oauth_proxy import OAuthProxy
class TestOAuthProxyInitialization:
"""Tests for OAuth proxy initialization and configuration."""
def test_basic_initialization(self, jwt_verifier):
"""Test basic proxy initialization with required parameters."""
proxy = OAuthProxy(
upstream_authorization_endpoint="https://auth.example.com/authorize",
upstream_token_endpoint="https://auth.example.com/token",
upstream_client_id="client-123",
upstream_client_secret="secret-456",
token_verifier=jwt_verifier,
base_url="https://api.example.com",
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
assert (
proxy._upstream_authorization_endpoint
== "https://auth.example.com/authorize"
)
assert proxy._upstream_token_endpoint == "https://auth.example.com/token"
assert proxy._upstream_client_id == "client-123"
assert proxy._upstream_client_secret.get_secret_value() == "secret-456"
assert str(proxy.base_url) == "https://api.example.com/"
def test_all_optional_parameters(self, jwt_verifier):
"""Test initialization with all optional parameters."""
proxy = OAuthProxy(
upstream_authorization_endpoint="https://auth.example.com/authorize",
upstream_token_endpoint="https://auth.example.com/token",
upstream_client_id="client-123",
upstream_client_secret="secret-456",
upstream_revocation_endpoint="https://auth.example.com/revoke",
token_verifier=jwt_verifier,
base_url="https://api.example.com",
redirect_path="/custom/callback",
issuer_url="https://issuer.example.com",
service_documentation_url="https://docs.example.com",
allowed_client_redirect_uris=["http://localhost:*"],
valid_scopes=["custom", "scopes"],
forward_pkce=False,
token_endpoint_auth_method="client_secret_post",
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
assert proxy._upstream_revocation_endpoint == "https://auth.example.com/revoke"
assert proxy._redirect_path == "/custom/callback"
assert proxy._forward_pkce is False
assert proxy._token_endpoint_auth_method == "client_secret_post"
assert proxy.client_registration_options is not None
assert proxy.client_registration_options.valid_scopes == ["custom", "scopes"]
def test_redirect_path_normalization(self, jwt_verifier):
"""Test that redirect_path is normalized with leading slash."""
proxy = OAuthProxy(
upstream_authorization_endpoint="https://auth.com/authorize",
upstream_token_endpoint="https://auth.com/token",
upstream_client_id="client",
upstream_client_secret="secret",
token_verifier=jwt_verifier,
base_url="https://api.com",
redirect_path="auth/callback", # No leading slash
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
assert proxy._redirect_path == "/auth/callback"
async def test_metadata_advertises_cimd_support(self, jwt_verifier):
"""OAuth metadata should advertise CIMD support when enabled."""
proxy = OAuthProxy(
upstream_authorization_endpoint="https://auth.example.com/authorize",
upstream_token_endpoint="https://auth.example.com/token",
upstream_client_id="client-123",
upstream_client_secret="secret-456",
token_verifier=jwt_verifier,
base_url="https://api.example.com",
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
enable_cimd=True,
)
app = Starlette(routes=proxy.get_routes())
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(
transport=transport, base_url="https://api.example.com"
) as client:
response = await client.get("/.well-known/oauth-authorization-server")
assert response.status_code == 200
metadata = response.json()
assert metadata.get("client_id_metadata_document_supported") is True
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/auth/oauth_proxy/test_oauth_proxy.py",
"license": "Apache License 2.0",
"lines": 89,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/auth/oauth_proxy/test_tokens.py | """Tests for OAuth proxy token endpoint and handling."""
import time
from unittest.mock import AsyncMock, Mock, patch
import pytest
from key_value.aio.stores.memory import MemoryStore
from mcp.server.auth.handlers.token import TokenErrorResponse
from mcp.server.auth.handlers.token import TokenHandler as SDKTokenHandler
from mcp.server.auth.provider import AuthorizationCode
from mcp.shared.auth import OAuthClientInformationFull
from pydantic import AnyUrl
from fastmcp.server.auth.auth import RefreshToken, TokenHandler, TokenVerifier
from fastmcp.server.auth.oauth_proxy import OAuthProxy
from fastmcp.server.auth.oauth_proxy.models import (
DEFAULT_ACCESS_TOKEN_EXPIRY_NO_REFRESH_SECONDS,
DEFAULT_ACCESS_TOKEN_EXPIRY_SECONDS,
ClientCode,
)
from fastmcp.server.auth.providers.jwt import JWTVerifier
class TestOAuthProxyTokenEndpointAuth:
"""Tests for token endpoint authentication methods."""
def test_token_auth_method_initialization(self, jwt_verifier):
"""Test different token endpoint auth methods."""
# client_secret_post
proxy_post = OAuthProxy(
upstream_authorization_endpoint="https://oauth.example.com/authorize",
upstream_token_endpoint="https://oauth.example.com/token",
upstream_client_id="client",
upstream_client_secret="secret",
token_verifier=jwt_verifier,
base_url="https://proxy.example.com",
token_endpoint_auth_method="client_secret_post",
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
assert proxy_post._token_endpoint_auth_method == "client_secret_post"
# client_secret_basic (default)
proxy_basic = OAuthProxy(
upstream_authorization_endpoint="https://oauth.example.com/authorize",
upstream_token_endpoint="https://oauth.example.com/token",
upstream_client_id="client",
upstream_client_secret="secret",
token_verifier=jwt_verifier,
base_url="https://proxy.example.com",
token_endpoint_auth_method="client_secret_basic",
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
assert proxy_basic._token_endpoint_auth_method == "client_secret_basic"
# None (use authlib default)
proxy_default = OAuthProxy(
upstream_authorization_endpoint="https://oauth.example.com/authorize",
upstream_token_endpoint="https://oauth.example.com/token",
upstream_client_id="client",
upstream_client_secret="secret",
token_verifier=jwt_verifier,
base_url="https://proxy.example.com",
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
assert proxy_default._token_endpoint_auth_method is None
async def test_token_auth_method_passed_to_client(self, jwt_verifier):
"""Test that auth method is passed to AsyncOAuth2Client."""
proxy = OAuthProxy(
upstream_authorization_endpoint="https://oauth.example.com/authorize",
upstream_token_endpoint="https://oauth.example.com/token",
upstream_client_id="client-id",
upstream_client_secret="client-secret",
token_verifier=jwt_verifier,
base_url="https://proxy.example.com",
token_endpoint_auth_method="client_secret_post",
jwt_signing_key="test-secret",
client_storage=MemoryStore(),
)
# Initialize JWT issuer before token operations
proxy.set_mcp_path("/mcp")
# First, create a valid FastMCP token via full OAuth flow
client = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:12345/callback")],
)
# Mock the upstream OAuth provider response
with patch(
"fastmcp.server.auth.oauth_proxy.proxy.AsyncOAuth2Client"
) as MockClient:
mock_client = AsyncMock()
# Mock initial token exchange (authorization code flow)
mock_client.fetch_token = AsyncMock(
return_value={
"access_token": "upstream-access-token",
"refresh_token": "upstream-refresh-token",
"expires_in": 3600,
"token_type": "Bearer",
}
)
# Mock token refresh
mock_client.refresh_token = AsyncMock(
return_value={
"access_token": "new-upstream-token",
"refresh_token": "new-upstream-refresh",
"expires_in": 3600,
"token_type": "Bearer",
}
)
MockClient.return_value = mock_client
# Register client and do initial OAuth flow to get valid FastMCP tokens
await proxy.register_client(client)
# Store client code that would be created during OAuth callback
client_code = ClientCode(
code="test-auth-code",
client_id="test-client",
redirect_uri="http://localhost:12345/callback",
code_challenge="",
code_challenge_method="S256",
scopes=["read"],
idp_tokens={
"access_token": "upstream-access-token",
"refresh_token": "upstream-refresh-token",
"expires_in": 3600,
"token_type": "Bearer",
},
expires_at=time.time() + 300,
created_at=time.time(),
)
await proxy._code_store.put(key=client_code.code, value=client_code)
# Exchange authorization code to get FastMCP tokens
auth_code = AuthorizationCode(
code="test-auth-code",
scopes=["read"],
expires_at=time.time() + 300,
client_id="test-client",
code_challenge="",
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
)
result = await proxy.exchange_authorization_code(
client=client,
authorization_code=auth_code,
)
# Now test refresh with the valid FastMCP refresh token
assert result.refresh_token is not None
fastmcp_refresh = RefreshToken(
token=result.refresh_token,
client_id="test-client",
scopes=["read"],
expires_at=None,
)
# Reset mock to check refresh call
MockClient.reset_mock()
mock_client.refresh_token = AsyncMock(
return_value={
"access_token": "new-upstream-token-2",
"refresh_token": "new-upstream-refresh-2",
"expires_in": 3600,
"token_type": "Bearer",
}
)
MockClient.return_value = mock_client
await proxy.exchange_refresh_token(client, fastmcp_refresh, ["read"])
# Verify auth method was passed to OAuth client
MockClient.assert_called_with(
client_id="client-id",
client_secret="client-secret",
token_endpoint_auth_method="client_secret_post",
timeout=30.0,
)
class TestTokenHandlerErrorTransformation:
"""Tests for TokenHandler's OAuth 2.1 compliant error transformation."""
async def test_transforms_client_auth_failure_to_invalid_client_401(self):
"""Test that client authentication failures return invalid_client with 401."""
handler = TokenHandler(provider=Mock(), client_authenticator=Mock())
# Create a mock 401 response like the SDK returns for auth failures
mock_response = Mock()
mock_response.status_code = 401
mock_response.body = (
b'{"error":"unauthorized_client","error_description":"Invalid client_id"}'
)
# Patch the parent class's handle() to return our mock response
with patch.object(
SDKTokenHandler,
"handle",
new_callable=AsyncMock,
return_value=mock_response,
):
response = await handler.handle(Mock())
# Should transform to OAuth 2.1 compliant response
assert response.status_code == 401
assert b'"error":"invalid_client"' in response.body
assert b'"error_description":"Invalid client_id"' in response.body
def test_does_not_transform_grant_type_unauthorized_to_invalid_client(self):
"""Test that grant type authorization errors stay as unauthorized_client with 400."""
handler = TokenHandler(provider=Mock(), client_authenticator=Mock())
# Simulate error from grant_type not in client_info.grant_types
error_response = TokenErrorResponse(
error="unauthorized_client",
error_description="Client not authorized for this grant type",
)
response = handler.response(error_response)
# Should NOT transform - keep as 400 unauthorized_client
assert response.status_code == 400
assert b'"error":"unauthorized_client"' in response.body
async def test_transforms_invalid_grant_to_401(self):
"""Test that invalid_grant errors return 401 per MCP spec.
Per MCP spec: "Invalid or expired tokens MUST receive a HTTP 401 response."
The SDK incorrectly returns 400 for all TokenErrorResponse including invalid_grant.
"""
handler = TokenHandler(provider=Mock(), client_authenticator=Mock())
# Create a mock 400 response like the SDK returns for invalid_grant
mock_response = Mock()
mock_response.status_code = 400
mock_response.body = (
b'{"error":"invalid_grant","error_description":"refresh token has expired"}'
)
# Patch the parent class's handle() to return our mock response
with patch.object(
SDKTokenHandler,
"handle",
new_callable=AsyncMock,
return_value=mock_response,
):
response = await handler.handle(Mock())
# Should transform to MCP-compliant 401 response
assert response.status_code == 401
assert b'"error":"invalid_grant"' in response.body
assert b'"error_description":"refresh token has expired"' in response.body
def test_does_not_transform_other_400_errors(self):
"""Test that non-invalid_grant 400 errors pass through unchanged."""
handler = TokenHandler(provider=Mock(), client_authenticator=Mock())
# Test with invalid_request error (should stay 400)
error_response = TokenErrorResponse(
error="invalid_request",
error_description="Missing required parameter",
)
response = handler.response(error_response)
# Should pass through unchanged as 400
assert response.status_code == 400
assert b'"error":"invalid_request"' in response.body
class TestFallbackAccessTokenExpiry:
"""Test fallback access token expiry constants and configuration."""
def test_default_constants(self):
"""Verify the default expiry constants are set correctly."""
assert DEFAULT_ACCESS_TOKEN_EXPIRY_SECONDS == 60 * 60 # 1 hour
assert (
DEFAULT_ACCESS_TOKEN_EXPIRY_NO_REFRESH_SECONDS == 60 * 60 * 24 * 365
) # 1 year
def test_fallback_parameter_stored(self):
"""Verify fallback_access_token_expiry_seconds is stored on provider."""
provider = OAuthProxy(
upstream_authorization_endpoint="https://idp.example.com/authorize",
upstream_token_endpoint="https://idp.example.com/token",
upstream_client_id="test-client",
upstream_client_secret="test-secret",
token_verifier=JWTVerifier(
jwks_uri="https://idp.example.com/.well-known/jwks.json",
issuer="https://idp.example.com",
),
base_url="http://localhost:8000",
jwt_signing_key="test-signing-key",
fallback_access_token_expiry_seconds=86400,
client_storage=MemoryStore(),
)
assert provider._fallback_access_token_expiry_seconds == 86400
def test_fallback_parameter_defaults_to_none(self):
"""Verify fallback defaults to None (enabling smart defaults)."""
provider = OAuthProxy(
upstream_authorization_endpoint="https://idp.example.com/authorize",
upstream_token_endpoint="https://idp.example.com/token",
upstream_client_id="test-client",
upstream_client_secret="test-secret",
token_verifier=JWTVerifier(
jwks_uri="https://idp.example.com/.well-known/jwks.json",
issuer="https://idp.example.com",
),
base_url="http://localhost:8000",
jwt_signing_key="test-signing-key",
client_storage=MemoryStore(),
)
assert provider._fallback_access_token_expiry_seconds is None
class TestUpstreamTokenStorageTTL:
"""Tests for upstream token storage TTL calculation (issue #2670).
The TTL should use max(refresh_expires_in, expires_in) to handle cases where
the refresh token has a shorter lifetime than the access token (e.g., Keycloak
with sliding session windows).
"""
@pytest.fixture
def jwt_verifier(self):
"""Create a mock JWT verifier."""
verifier = Mock(spec=TokenVerifier)
verifier.required_scopes = ["read", "write"]
verifier.verify_token = AsyncMock(return_value=None)
return verifier
@pytest.fixture
def proxy(self, jwt_verifier):
"""Create an OAuth proxy for testing."""
proxy = OAuthProxy(
upstream_authorization_endpoint="https://idp.example.com/authorize",
upstream_token_endpoint="https://idp.example.com/token",
upstream_client_id="test-client",
upstream_client_secret="test-secret",
token_verifier=jwt_verifier,
base_url="https://proxy.example.com",
jwt_signing_key="test-secret-key",
client_storage=MemoryStore(),
)
proxy.set_mcp_path("/mcp")
return proxy
async def test_ttl_uses_max_when_refresh_shorter_than_access(self, proxy):
"""TTL should use access token expiry when refresh is shorter.
This is the xsreality case: Keycloak returns refresh_expires_in=120 (2 min)
but expires_in=28800 (8 hours). The upstream tokens should persist for
8 hours (the access token lifetime), not 2 minutes.
"""
# Register client
client = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:12345/callback")],
)
await proxy.register_client(client)
# Simulate xsreality's Keycloak setup: short refresh, long access
client_code = ClientCode(
code="test-auth-code",
client_id="test-client",
redirect_uri="http://localhost:12345/callback",
code_challenge="test-challenge",
code_challenge_method="S256",
scopes=["read", "write"],
idp_tokens={
"access_token": "upstream-access-token",
"refresh_token": "upstream-refresh-token",
"expires_in": 28800, # 8 hours (access token)
"refresh_expires_in": 120, # 2 minutes (refresh token) - SHORTER!
"token_type": "Bearer",
},
expires_at=time.time() + 300,
created_at=time.time(),
)
await proxy._code_store.put(key=client_code.code, value=client_code)
# Exchange the code
auth_code = AuthorizationCode(
code="test-auth-code",
scopes=["read", "write"],
expires_at=time.time() + 300,
client_id="test-client",
code_challenge="test-challenge",
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
)
result = await proxy.exchange_authorization_code(
client=client,
authorization_code=auth_code,
)
# Verify tokens were issued
assert result.access_token is not None
assert result.refresh_token is not None
# The key test: verify upstream tokens are stored with TTL=max(120, 28800)=28800
# We can verify this by checking the tokens are still accessible after 2 minutes
# would have passed (if TTL was incorrectly set to 120)
#
# Since we can't easily time-travel in tests, we verify the storage directly
# by checking that we can still look up the tokens for refresh purposes.
#
# Extract the JTI from the refresh token to look up the mapping
refresh_payload = proxy.jwt_issuer.verify_token(result.refresh_token)
refresh_jti = refresh_payload["jti"]
# The JTI mapping should exist
jti_mapping = await proxy._jti_mapping_store.get(key=refresh_jti)
assert jti_mapping is not None
# The upstream tokens should exist
upstream_tokens = await proxy._upstream_token_store.get(
key=jti_mapping.upstream_token_id
)
assert upstream_tokens is not None
assert upstream_tokens.access_token == "upstream-access-token"
assert upstream_tokens.refresh_token == "upstream-refresh-token"
async def test_ttl_uses_refresh_when_refresh_longer_than_access(self, proxy):
"""TTL should use refresh token expiry when refresh is longer.
This is the ianw case: IdP returns expires_in=300 (5 min) but
refresh_expires_in=32318 (9 hours). The upstream tokens should persist
for 9 hours (the refresh token lifetime).
"""
# Register client
client = OAuthClientInformationFull(
client_id="test-client",
client_secret="test-secret",
redirect_uris=[AnyUrl("http://localhost:12345/callback")],
)
await proxy.register_client(client)
# Simulate ianw's setup: short access, long refresh (typical)
client_code = ClientCode(
code="test-auth-code-2",
client_id="test-client",
redirect_uri="http://localhost:12345/callback",
code_challenge="test-challenge",
code_challenge_method="S256",
scopes=["read", "write"],
idp_tokens={
"access_token": "upstream-access-token-2",
"refresh_token": "upstream-refresh-token-2",
"expires_in": 300, # 5 minutes (access token)
"refresh_expires_in": 32318, # 9 hours (refresh token) - LONGER
"token_type": "Bearer",
},
expires_at=time.time() + 300,
created_at=time.time(),
)
await proxy._code_store.put(key=client_code.code, value=client_code)
# Exchange the code
auth_code = AuthorizationCode(
code="test-auth-code-2",
scopes=["read", "write"],
expires_at=time.time() + 300,
client_id="test-client",
code_challenge="test-challenge",
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
)
result = await proxy.exchange_authorization_code(
client=client,
authorization_code=auth_code,
)
# Verify tokens were issued
assert result.access_token is not None
assert result.refresh_token is not None
# Verify upstream tokens are accessible
refresh_payload = proxy.jwt_issuer.verify_token(result.refresh_token)
refresh_jti = refresh_payload["jti"]
jti_mapping = await proxy._jti_mapping_store.get(key=refresh_jti)
assert jti_mapping is not None
upstream_tokens = await proxy._upstream_token_store.get(
key=jti_mapping.upstream_token_id
)
assert upstream_tokens is not None
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/auth/oauth_proxy/test_tokens.py",
"license": "Apache License 2.0",
"lines": 433,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/auth/oauth_proxy/test_ui.py | """Tests for OAuth proxy UI and error page rendering."""
from unittest.mock import Mock
from key_value.aio.stores.memory import MemoryStore
from starlette.requests import Request
from starlette.responses import HTMLResponse
from fastmcp.server.auth.oauth_proxy import OAuthProxy
from fastmcp.server.auth.oauth_proxy.ui import create_consent_html, create_error_html
from fastmcp.server.auth.providers.jwt import JWTVerifier
class TestErrorPageRendering:
"""Test error page rendering for OAuth callback errors."""
def test_create_error_html_basic(self):
"""Test basic error page generation."""
html = create_error_html(
error_title="Test Error",
error_message="This is a test error message",
)
# Verify it's valid HTML
assert "<!DOCTYPE html>" in html
assert "<title>Test Error</title>" in html
assert "This is a test error message" in html
assert 'class="info-box error"' in html
def test_create_error_html_with_details(self):
"""Test error page with error details."""
html = create_error_html(
error_title="OAuth Error",
error_message="Authentication failed",
error_details={
"Error Code": "invalid_scope",
"Description": "Requested scope does not exist",
},
)
# Verify error details are included
assert "Error Details" in html
assert "Error Code" in html
assert "invalid_scope" in html
assert "Description" in html
assert "Requested scope does not exist" in html
def test_create_error_html_escapes_user_input(self):
"""Test that error page properly escapes HTML in user input."""
html = create_error_html(
error_title="Error <script>alert('xss')</script>",
error_message="Message with <b>HTML</b> tags",
error_details={"Key<script>": "Value<img>"},
)
# Verify HTML is escaped
assert "<script>alert('xss')</script>" not in html
assert "<script>" in html
assert "<b>HTML</b>" not in html
assert "<b>HTML</b>" in html
async def test_callback_error_returns_html_page(self):
"""Test that OAuth callback errors return styled HTML instead of data: URLs."""
# Create a minimal OAuth proxy
provider = OAuthProxy(
upstream_authorization_endpoint="https://idp.example.com/authorize",
upstream_token_endpoint="https://idp.example.com/token",
upstream_client_id="test-client",
upstream_client_secret="test-secret",
token_verifier=JWTVerifier(
jwks_uri="https://idp.example.com/.well-known/jwks.json",
issuer="https://idp.example.com",
audience="test-client",
),
base_url="http://localhost:8000",
jwt_signing_key="test-signing-key",
client_storage=MemoryStore(),
)
# Mock a request with an error from the IdP
mock_request = Mock(spec=Request)
mock_request.query_params = {
"error": "invalid_scope",
"error_description": "The application asked for scope 'read' that doesn't exist",
"state": "test-state",
}
# Call the callback handler
response = await provider._handle_idp_callback(mock_request)
# Verify we get an HTMLResponse, not a RedirectResponse
assert isinstance(response, HTMLResponse)
assert response.status_code == 400
# Verify the response contains the error message
assert b"invalid_scope" in response.body
assert b"doesn't exist" in response.body # HTML-escaped apostrophe
assert b"OAuth Error" in response.body
class TestConsentPageRendering:
"""Test consent page rendering and escaping."""
def test_create_consent_html_escapes_client_id_in_details(self):
"""Test that Application ID is escaped in advanced details."""
html = create_consent_html(
client_id='evil<img src=x onerror=alert("xss")>',
redirect_uri="https://example.com/callback",
scopes=["read"],
txn_id="txn",
csrf_token="csrf",
)
assert 'evil<img src=x onerror=alert("xss")>' not in html
assert "evil<img src=x onerror=alert("xss")>" in html
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/auth/oauth_proxy/test_ui.py",
"license": "Apache License 2.0",
"lines": 95,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/mount/test_advanced.py | """Advanced mounting scenarios."""
import pytest
from mcp.types import TextContent
from fastmcp import FastMCP
from fastmcp.client import Client
from fastmcp.server.providers import FastMCPProvider
from fastmcp.server.providers.wrapped_provider import _WrappedProvider
class TestDynamicChanges:
"""Test that changes to mounted servers are reflected dynamically."""
async def test_adding_tool_after_mounting(self):
"""Test that tools added after mounting are accessible."""
main_app = FastMCP("MainApp")
sub_app = FastMCP("SubApp")
# Mount the sub-app before adding any tools
main_app.mount(sub_app, "sub")
# Initially, there should be no tools from sub_app
tools = await main_app.list_tools()
assert not any(t.name.startswith("sub_") for t in tools)
# Add a tool to the sub-app after mounting
@sub_app.tool
def dynamic_tool() -> str:
return "Added after mounting"
# The tool should be accessible through the main app
tools = await main_app.list_tools()
assert any(t.name == "sub_dynamic_tool" for t in tools)
# Call the dynamically added tool
result = await main_app.call_tool("sub_dynamic_tool", {})
assert result.structured_content == {"result": "Added after mounting"}
async def test_removing_tool_after_mounting(self):
"""Test that tools removed from mounted servers are no longer accessible."""
main_app = FastMCP("MainApp")
sub_app = FastMCP("SubApp")
@sub_app.tool
def temp_tool() -> str:
return "Temporary tool"
# Mount the sub-app
main_app.mount(sub_app, "sub")
# Initially, the tool should be accessible
tools = await main_app.list_tools()
assert any(t.name == "sub_temp_tool" for t in tools)
# Remove the tool from sub_app
sub_app.local_provider.remove_tool("temp_tool")
# The tool should no longer be accessible
tools = await main_app.list_tools()
assert not any(t.name == "sub_temp_tool" for t in tools)
class TestCustomRouteForwarding:
"""Test that custom HTTP routes from mounted servers are forwarded."""
async def test_get_additional_http_routes_empty(self):
"""Test _get_additional_http_routes returns empty list for server with no routes."""
server = FastMCP("TestServer")
routes = server._get_additional_http_routes()
assert routes == []
async def test_get_additional_http_routes_with_custom_route(self):
"""Test _get_additional_http_routes returns server's own routes."""
server = FastMCP("TestServer")
@server.custom_route("/test", methods=["GET"])
async def test_route(request):
from starlette.responses import JSONResponse
return JSONResponse({"message": "test"})
routes = server._get_additional_http_routes()
assert len(routes) == 1
assert hasattr(routes[0], "path")
assert routes[0].path == "/test"
async def test_mounted_servers_tracking(self):
"""Test that providers list tracks mounted servers correctly."""
from fastmcp.server.providers.local_provider import LocalProvider
main_server = FastMCP("MainServer")
sub_server1 = FastMCP("SubServer1")
sub_server2 = FastMCP("SubServer2")
@sub_server1.tool
def tool1() -> str:
return "1"
@sub_server2.tool
def tool2() -> str:
return "2"
# Initially only LocalProvider
assert len(main_server.providers) == 1
assert isinstance(main_server.providers[0], LocalProvider)
# Mount first server
main_server.mount(sub_server1, "sub1")
assert len(main_server.providers) == 2
# LocalProvider is at index 0, mounted provider (wrapped) at index 1
provider1 = main_server.providers[1]
assert isinstance(provider1, _WrappedProvider)
assert isinstance(provider1._inner, FastMCPProvider)
assert provider1._inner.server == sub_server1
# Mount second server
main_server.mount(sub_server2, "sub2")
assert len(main_server.providers) == 3
provider2 = main_server.providers[2]
assert isinstance(provider2, _WrappedProvider)
assert isinstance(provider2._inner, FastMCPProvider)
assert provider2._inner.server == sub_server2
# Verify namespacing is applied by checking tool names
tools = await main_server.list_tools()
tool_names = {t.name for t in tools}
assert tool_names == {"sub1_tool1", "sub2_tool2"}
async def test_multiple_routes_same_server(self):
"""Test that multiple custom routes from same server are all included."""
server = FastMCP("TestServer")
@server.custom_route("/route1", methods=["GET"])
async def route1(request):
from starlette.responses import JSONResponse
return JSONResponse({"message": "route1"})
@server.custom_route("/route2", methods=["POST"])
async def route2(request):
from starlette.responses import JSONResponse
return JSONResponse({"message": "route2"})
routes = server._get_additional_http_routes()
assert len(routes) == 2
route_paths = [route.path for route in routes if hasattr(route, "path")]
assert "/route1" in route_paths
assert "/route2" in route_paths
class TestDeeplyNestedMount:
"""Test deeply nested mount scenarios (3+ levels deep).
This tests the fix for https://github.com/PrefectHQ/fastmcp/issues/2583
where tools/resources/prompts mounted more than 2 levels deep would fail
to invoke even though they were correctly listed.
"""
async def test_three_level_nested_tool_invocation(self):
"""Test invoking tools from servers mounted 3 levels deep."""
root = FastMCP("root")
middle = FastMCP("middle")
leaf = FastMCP("leaf")
@leaf.tool
def add(a: int, b: int) -> int:
return a + b
@middle.tool
def multiply(a: int, b: int) -> int:
return a * b
middle.mount(leaf, namespace="leaf")
root.mount(middle, namespace="middle")
# Tool at level 2 should work
result = await root.call_tool("middle_multiply", {"a": 3, "b": 4})
assert result.structured_content == {"result": 12}
# Tool at level 3 should also work (this was the bug)
result = await root.call_tool("middle_leaf_add", {"a": 5, "b": 7})
assert result.structured_content == {"result": 12}
async def test_three_level_nested_resource_invocation(self):
"""Test reading resources from servers mounted 3 levels deep."""
root = FastMCP("root")
middle = FastMCP("middle")
leaf = FastMCP("leaf")
@leaf.resource("leaf://data")
def leaf_data() -> str:
return "leaf data"
@middle.resource("middle://data")
def middle_data() -> str:
return "middle data"
middle.mount(leaf, namespace="leaf")
root.mount(middle, namespace="middle")
# Resource at level 2 should work
result = await root.read_resource("middle://middle/data")
assert result.contents[0].content == "middle data"
# Resource at level 3 should also work
result = await root.read_resource("leaf://middle/leaf/data")
assert result.contents[0].content == "leaf data"
async def test_three_level_nested_resource_template_invocation(self):
"""Test reading resource templates from servers mounted 3 levels deep."""
root = FastMCP("root")
middle = FastMCP("middle")
leaf = FastMCP("leaf")
@leaf.resource("leaf://item/{id}")
def leaf_item(id: str) -> str:
return f"leaf item {id}"
@middle.resource("middle://item/{id}")
def middle_item(id: str) -> str:
return f"middle item {id}"
middle.mount(leaf, namespace="leaf")
root.mount(middle, namespace="middle")
# Resource template at level 2 should work
result = await root.read_resource("middle://middle/item/42")
assert result.contents[0].content == "middle item 42"
# Resource template at level 3 should also work
result = await root.read_resource("leaf://middle/leaf/item/99")
assert result.contents[0].content == "leaf item 99"
async def test_three_level_nested_prompt_invocation(self):
"""Test getting prompts from servers mounted 3 levels deep."""
root = FastMCP("root")
middle = FastMCP("middle")
leaf = FastMCP("leaf")
@leaf.prompt
def leaf_prompt(name: str) -> str:
return f"Hello from leaf: {name}"
@middle.prompt
def middle_prompt(name: str) -> str:
return f"Hello from middle: {name}"
middle.mount(leaf, namespace="leaf")
root.mount(middle, namespace="middle")
# Prompt at level 2 should work
result = await root.render_prompt("middle_middle_prompt", {"name": "World"})
assert isinstance(result.messages[0].content, TextContent)
assert "Hello from middle: World" in result.messages[0].content.text
# Prompt at level 3 should also work
result = await root.render_prompt("middle_leaf_leaf_prompt", {"name": "Test"})
assert isinstance(result.messages[0].content, TextContent)
assert "Hello from leaf: Test" in result.messages[0].content.text
async def test_four_level_nested_tool_invocation(self):
"""Test invoking tools from servers mounted 4 levels deep."""
root = FastMCP("root")
level1 = FastMCP("level1")
level2 = FastMCP("level2")
level3 = FastMCP("level3")
@level3.tool
def deep_tool() -> str:
return "very deep"
level2.mount(level3, namespace="l3")
level1.mount(level2, namespace="l2")
root.mount(level1, namespace="l1")
# Verify tool is listed
tools = await root.list_tools()
tool_names = [t.name for t in tools]
assert "l1_l2_l3_deep_tool" in tool_names
# Tool at level 4 should work
result = await root.call_tool("l1_l2_l3_deep_tool", {})
assert result.structured_content == {"result": "very deep"}
class TestToolNameOverrides:
"""Test tool and prompt name overrides in mount() (issue #2596)."""
async def test_tool_names_override_via_transforms(self):
"""Test that tool_names renames tools via ToolTransform layer.
Tool renames are applied first, then namespace prefixing.
So original_tool → custom_name → prefix_custom_name.
"""
sub = FastMCP("Sub")
@sub.tool
def original_tool() -> str:
return "test"
main = FastMCP("Main")
# tool_names renames first, then namespace is applied
main.mount(
sub,
namespace="prefix",
tool_names={"original_tool": "custom_name"},
)
# Server introspection shows renamed + namespaced names
tools = await main.list_tools()
tool_names = [t.name for t in tools]
assert "prefix_custom_name" in tool_names
assert "original_tool" not in tool_names
assert "prefix_original_tool" not in tool_names
assert "custom_name" not in tool_names
async def test_tool_names_override_applied_in_list_tools(self):
"""Test that tool_names override is reflected in list_tools()."""
sub = FastMCP("Sub")
@sub.tool
def original_tool() -> str:
return "test"
main = FastMCP("Main")
main.mount(
sub,
namespace="prefix",
tool_names={"original_tool": "custom_name"},
)
tools = await main.list_tools()
tool_names = [t.name for t in tools]
assert "prefix_custom_name" in tool_names
assert "prefix_original_tool" not in tool_names
async def test_tool_call_with_overridden_name(self):
"""Test that overridden tool can be called by its new name."""
sub = FastMCP("Sub")
@sub.tool
def original_tool() -> str:
return "success"
main = FastMCP("Main")
main.mount(
sub,
namespace="prefix",
tool_names={"original_tool": "renamed"},
)
# Tool is renamed then namespaced: original_tool → renamed → prefix_renamed
result = await main.call_tool("prefix_renamed", {})
assert result.structured_content == {"result": "success"}
def test_duplicate_tool_rename_targets_raises_error(self):
"""Test that duplicate target names in tool_renames raises ValueError."""
sub = FastMCP("Sub")
main = FastMCP("Main")
with pytest.raises(ValueError, match="duplicate target name"):
main.mount(
sub,
tool_names={"tool_a": "same_name", "tool_b": "same_name"},
)
class TestMountedServerDocketBehavior:
"""Regression tests for mounted server lifecycle behavior.
These tests guard against architectural changes that could accidentally
start Docket instances for mounted servers. Mounted servers should only
run their user-defined lifespan, not the full _lifespan_manager which
includes Docket creation.
"""
async def test_mounted_server_does_not_have_docket(self):
"""Test that a mounted server doesn't create its own Docket.
MountedProvider.lifespan() should call only the server's _lifespan
(user-defined lifespan), not _lifespan_manager (which includes Docket).
"""
main_app = FastMCP("MainApp")
sub_app = FastMCP("SubApp")
# Need a task-enabled component to trigger Docket initialization
@main_app.tool(task=True)
async def _trigger_docket() -> str:
return "trigger"
@sub_app.tool
def my_tool() -> str:
return "test"
main_app.mount(sub_app, "sub")
# After running the main app's lifespan, the sub app should not have
# its own Docket instance
async with Client(main_app) as client:
# The main app should have a docket (created by _lifespan_manager)
# because it has a task-enabled component
assert main_app.docket is not None
# The mounted sub app should NOT have its own docket
# It uses the parent's docket for background tasks
assert sub_app.docket is None
# But the tool should still work (prefixed as sub_my_tool)
result = await client.call_tool("sub_my_tool", {})
assert result.data == "test"
class TestComponentServicePrefixLess:
"""Test that enable/disable works with prefix-less mounted servers."""
async def test_enable_tool_prefixless_mount(self):
"""Test enabling a tool on a prefix-less mounted server."""
main_app = FastMCP("MainApp")
sub_app = FastMCP("SubApp")
@sub_app.tool
def my_tool() -> str:
return "test"
# Mount without prefix
main_app.mount(sub_app)
# Initially the tool is enabled
tools = await main_app.list_tools()
assert any(t.name == "my_tool" for t in tools)
# Disable and re-enable
main_app.disable(names={"my_tool"}, components={"tool"})
# Verify tool is now disabled
tools = await main_app.list_tools()
assert not any(t.name == "my_tool" for t in tools)
main_app.enable(names={"my_tool"}, components={"tool"})
# Verify tool is now enabled
tools = await main_app.list_tools()
assert any(t.name == "my_tool" for t in tools)
async def test_enable_resource_prefixless_mount(self):
"""Test enabling a resource on a prefix-less mounted server."""
main_app = FastMCP("MainApp")
sub_app = FastMCP("SubApp")
@sub_app.resource(uri="data://test")
def my_resource() -> str:
return "test data"
# Mount without prefix
main_app.mount(sub_app)
# Disable and re-enable
main_app.disable(names={"data://test"}, components={"resource"})
# Verify resource is now disabled
resources = await main_app.list_resources()
assert not any(str(r.uri) == "data://test" for r in resources)
main_app.enable(names={"data://test"}, components={"resource"})
# Verify resource is now enabled
resources = await main_app.list_resources()
assert any(str(r.uri) == "data://test" for r in resources)
async def test_enable_prompt_prefixless_mount(self):
"""Test enabling a prompt on a prefix-less mounted server."""
main_app = FastMCP("MainApp")
sub_app = FastMCP("SubApp")
@sub_app.prompt
def my_prompt() -> str:
return "test prompt"
# Mount without prefix
main_app.mount(sub_app)
# Disable and re-enable
main_app.disable(names={"my_prompt"}, components={"prompt"})
# Verify prompt is now disabled
prompts = await main_app.list_prompts()
assert not any(p.name == "my_prompt" for p in prompts)
main_app.enable(names={"my_prompt"}, components={"prompt"})
# Verify prompt is now enabled
prompts = await main_app.list_prompts()
assert any(p.name == "my_prompt" for p in prompts)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/mount/test_advanced.py",
"license": "Apache License 2.0",
"lines": 374,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/mount/test_filtering.py | """Tests for tag filtering in mounted servers."""
import pytest
from fastmcp import FastMCP
from fastmcp.exceptions import NotFoundError
class TestParentTagFiltering:
"""Test that parent server tag filters apply recursively to mounted servers."""
async def test_parent_include_tags_filters_mounted_tools(self):
"""Test that parent include_tags filters out non-matching mounted tools."""
parent = FastMCP("Parent")
parent.enable(tags={"allowed"}, only=True)
mounted = FastMCP("Mounted")
@mounted.tool(tags={"allowed"})
def allowed_tool() -> str:
return "allowed"
@mounted.tool(tags={"blocked"})
def blocked_tool() -> str:
return "blocked"
parent.mount(mounted)
tools = await parent.list_tools()
tool_names = {t.name for t in tools}
assert "allowed_tool" in tool_names
assert "blocked_tool" not in tool_names
# Verify execution also respects filters
result = await parent.call_tool("allowed_tool", {})
assert result.structured_content == {"result": "allowed"}
with pytest.raises(NotFoundError, match="Unknown tool"):
await parent.call_tool("blocked_tool", {})
async def test_parent_exclude_tags_filters_mounted_tools(self):
"""Test that parent exclude_tags filters out matching mounted tools."""
parent = FastMCP("Parent")
parent.disable(tags={"blocked"})
mounted = FastMCP("Mounted")
@mounted.tool(tags={"production"})
def production_tool() -> str:
return "production"
@mounted.tool(tags={"blocked"})
def blocked_tool() -> str:
return "blocked"
parent.mount(mounted)
tools = await parent.list_tools()
tool_names = {t.name for t in tools}
assert "production_tool" in tool_names
assert "blocked_tool" not in tool_names
async def test_parent_filters_apply_to_mounted_resources(self):
"""Test that parent tag filters apply to mounted resources."""
parent = FastMCP("Parent")
parent.enable(tags={"allowed"}, only=True)
mounted = FastMCP("Mounted")
@mounted.resource("resource://allowed", tags={"allowed"})
def allowed_resource() -> str:
return "allowed"
@mounted.resource("resource://blocked", tags={"blocked"})
def blocked_resource() -> str:
return "blocked"
parent.mount(mounted)
resources = await parent.list_resources()
resource_uris = {str(r.uri) for r in resources}
assert "resource://allowed" in resource_uris
assert "resource://blocked" not in resource_uris
async def test_parent_filters_apply_to_mounted_prompts(self):
"""Test that parent tag filters apply to mounted prompts."""
parent = FastMCP("Parent")
parent.disable(tags={"blocked"})
mounted = FastMCP("Mounted")
@mounted.prompt(tags={"allowed"})
def allowed_prompt() -> str:
return "allowed"
@mounted.prompt(tags={"blocked"})
def blocked_prompt() -> str:
return "blocked"
parent.mount(mounted)
prompts = await parent.list_prompts()
prompt_names = {p.name for p in prompts}
assert "allowed_prompt" in prompt_names
assert "blocked_prompt" not in prompt_names
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/mount/test_filtering.py",
"license": "Apache License 2.0",
"lines": 75,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/mount/test_mount.py | """Basic mounting functionality tests."""
import logging
import sys
import pytest
from mcp.types import TextContent
from fastmcp import FastMCP
from fastmcp.client import Client
from fastmcp.client.transports import SSETransport
from fastmcp.tools.tool import Tool
from fastmcp.tools.tool_transform import TransformedTool
class TestBasicMount:
"""Test basic mounting functionality."""
async def test_mount_simple_server(self):
"""Test mounting a simple server and accessing its tool."""
# Create main app and sub-app
main_app = FastMCP("MainApp")
# Add a tool to the sub-app
def tool() -> str:
return "This is from the sub app"
sub_tool = Tool.from_function(tool)
transformed_tool = TransformedTool.from_tool(
name="transformed_tool", tool=sub_tool
)
sub_app = FastMCP("SubApp", tools=[transformed_tool, sub_tool])
# Mount the sub-app to the main app
main_app.mount(sub_app, "sub")
# Get tools from main app, should include sub_app's tools
tools = await main_app.list_tools()
assert any(t.name == "sub_tool" for t in tools)
assert any(t.name == "sub_transformed_tool" for t in tools)
result = await main_app.call_tool("sub_tool", {})
assert result.structured_content == {"result": "This is from the sub app"}
async def test_mount_with_custom_separator(self):
"""Test mounting with a custom tool separator (deprecated but still supported)."""
main_app = FastMCP("MainApp")
sub_app = FastMCP("SubApp")
@sub_app.tool
def greet(name: str) -> str:
return f"Hello, {name}!"
# Mount without custom separator - custom separators are deprecated
main_app.mount(sub_app, "sub")
# Tool should be accessible with the default separator
tools = await main_app.list_tools()
assert any(t.name == "sub_greet" for t in tools)
# Call the tool
result = await main_app.call_tool("sub_greet", {"name": "World"})
assert result.structured_content == {"result": "Hello, World!"}
@pytest.mark.parametrize("prefix", ["", None])
async def test_mount_with_no_prefix(self, prefix):
main_app = FastMCP("MainApp")
sub_app = FastMCP("SubApp")
@sub_app.tool
def sub_tool() -> str:
return "This is from the sub app"
# Mount with empty prefix but without deprecated separators
main_app.mount(sub_app, namespace=prefix)
tools = await main_app.list_tools()
# With empty prefix, the tool should keep its original name
assert any(t.name == "sub_tool" for t in tools)
async def test_mount_with_no_prefix_provided(self):
"""Test mounting without providing a prefix at all."""
main_app = FastMCP("MainApp")
sub_app = FastMCP("SubApp")
@sub_app.tool
def sub_tool() -> str:
return "This is from the sub app"
# Mount without providing a prefix (should be None)
main_app.mount(sub_app)
tools = await main_app.list_tools()
# Without prefix, the tool should keep its original name
assert any(t.name == "sub_tool" for t in tools)
# Call the tool to verify it works
result = await main_app.call_tool("sub_tool", {})
assert result.structured_content == {"result": "This is from the sub app"}
async def test_mount_tools_no_prefix(self):
"""Test mounting a server with tools without prefix."""
main_app = FastMCP("MainApp")
sub_app = FastMCP("SubApp")
@sub_app.tool
def sub_tool() -> str:
return "Sub tool result"
# Mount without prefix
main_app.mount(sub_app)
# Verify tool is accessible with original name
tools = await main_app.list_tools()
assert any(t.name == "sub_tool" for t in tools)
# Test actual functionality
tool_result = await main_app.call_tool("sub_tool", {})
assert tool_result.structured_content == {"result": "Sub tool result"}
async def test_mount_resources_no_prefix(self):
"""Test mounting a server with resources without prefix."""
main_app = FastMCP("MainApp")
sub_app = FastMCP("SubApp")
@sub_app.resource(uri="data://config")
def sub_resource():
return "Sub resource data"
# Mount without prefix
main_app.mount(sub_app)
# Verify resource is accessible with original URI
resources = await main_app.list_resources()
assert any(str(r.uri) == "data://config" for r in resources)
# Test actual functionality
resource_result = await main_app.read_resource("data://config")
assert resource_result.contents[0].content == "Sub resource data"
async def test_mount_resource_templates_no_prefix(self):
"""Test mounting a server with resource templates without prefix."""
main_app = FastMCP("MainApp")
sub_app = FastMCP("SubApp")
@sub_app.resource(uri="users://{user_id}/info")
def sub_template(user_id: str):
return f"Sub template for user {user_id}"
# Mount without prefix
main_app.mount(sub_app)
# Verify template is accessible with original URI template
templates = await main_app.list_resource_templates()
assert any(t.uri_template == "users://{user_id}/info" for t in templates)
# Test actual functionality
template_result = await main_app.read_resource("users://123/info")
assert template_result.contents[0].content == "Sub template for user 123"
async def test_mount_prompts_no_prefix(self):
"""Test mounting a server with prompts without prefix."""
main_app = FastMCP("MainApp")
sub_app = FastMCP("SubApp")
@sub_app.prompt
def sub_prompt() -> str:
return "Sub prompt content"
# Mount without prefix
main_app.mount(sub_app)
# Verify prompt is accessible with original name
prompts = await main_app.list_prompts()
assert any(p.name == "sub_prompt" for p in prompts)
# Test actual functionality
prompt_result = await main_app.render_prompt("sub_prompt")
assert prompt_result.messages is not None
class TestMultipleServerMount:
"""Test mounting multiple servers simultaneously."""
async def test_mount_multiple_servers(self):
"""Test mounting multiple servers with different prefixes."""
main_app = FastMCP("MainApp")
weather_app = FastMCP("WeatherApp")
news_app = FastMCP("NewsApp")
@weather_app.tool
def get_forecast() -> str:
return "Weather forecast"
@news_app.tool
def get_headlines() -> str:
return "News headlines"
# Mount both apps
main_app.mount(weather_app, "weather")
main_app.mount(news_app, "news")
# Check both are accessible
tools = await main_app.list_tools()
assert any(t.name == "weather_get_forecast" for t in tools)
assert any(t.name == "news_get_headlines" for t in tools)
# Call tools from both mounted servers
result1 = await main_app.call_tool("weather_get_forecast", {})
assert result1.structured_content == {"result": "Weather forecast"}
result2 = await main_app.call_tool("news_get_headlines", {})
assert result2.structured_content == {"result": "News headlines"}
async def test_mount_same_prefix(self):
"""Test that mounting with the same prefix replaces the previous mount."""
main_app = FastMCP("MainApp")
first_app = FastMCP("FirstApp")
second_app = FastMCP("SecondApp")
@first_app.tool
def first_tool() -> str:
return "First app tool"
@second_app.tool
def second_tool() -> str:
return "Second app tool"
# Mount first app
main_app.mount(first_app, "api")
tools = await main_app.list_tools()
assert any(t.name == "api_first_tool" for t in tools)
# Mount second app with same prefix
main_app.mount(second_app, "api")
tools = await main_app.list_tools()
# Both apps' tools should be accessible (new behavior)
assert any(t.name == "api_first_tool" for t in tools)
assert any(t.name == "api_second_tool" for t in tools)
@pytest.mark.skipif(
sys.platform == "win32", reason="Windows asyncio networking timeouts."
)
async def test_mount_with_unreachable_proxy_servers(self, caplog):
"""Test graceful handling when multiple mounted servers fail to connect."""
caplog.set_level(logging.DEBUG, logger="fastmcp")
main_app = FastMCP("MainApp")
working_app = FastMCP("WorkingApp")
@working_app.tool
def working_tool() -> str:
return "Working tool"
@working_app.resource(uri="working://data")
def working_resource():
return "Working resource"
@working_app.prompt
def working_prompt() -> str:
return "Working prompt"
# Mount the working server
main_app.mount(working_app, "working")
# Use an unreachable port
unreachable_client = Client(
transport=SSETransport("http://127.0.0.1:9999/sse/"),
name="unreachable_client",
)
# Create a proxy server that will fail to connect
unreachable_proxy = FastMCP.as_proxy(
unreachable_client, name="unreachable_proxy"
)
# Mount the unreachable proxy
main_app.mount(unreachable_proxy, "unreachable")
# All object types should work from working server despite unreachable proxy
async with Client(main_app, name="main_app_client") as client:
# Test tools
tools = await client.list_tools()
tool_names = [tool.name for tool in tools]
assert "working_working_tool" in tool_names
# Test calling a tool
result = await client.call_tool("working_working_tool", {})
assert result.data == "Working tool"
# Test resources
resources = await client.list_resources()
resource_uris = [str(resource.uri) for resource in resources]
assert "working://working/data" in resource_uris
# Test prompts
prompts = await client.list_prompts()
prompt_names = [prompt.name for prompt in prompts]
assert "working_working_prompt" in prompt_names
# Verify that errors were logged for the unreachable provider (at DEBUG level)
debug_messages = [
record.message for record in caplog.records if record.levelname == "DEBUG"
]
assert any(
"Error during list_tools from provider" in msg for msg in debug_messages
)
assert any(
"Error during list_resources from provider" in msg for msg in debug_messages
)
assert any(
"Error during list_prompts from provider" in msg for msg in debug_messages
)
class TestPrefixConflictResolution:
"""Test that first registered provider wins when there are conflicts.
Provider semantics: 'Providers are queried in registration order; first non-None wins'
"""
async def test_first_server_wins_tools_no_prefix(self):
"""Test that first mounted server wins for tools when no prefix is used."""
main_app = FastMCP("MainApp")
first_app = FastMCP("FirstApp")
second_app = FastMCP("SecondApp")
@first_app.tool(name="shared_tool")
def first_shared_tool() -> str:
return "First app tool"
@second_app.tool(name="shared_tool")
def second_shared_tool() -> str:
return "Second app tool"
# Mount both apps without prefix
main_app.mount(first_app)
main_app.mount(second_app)
# list_tools returns all components; execution uses first match
tools = await main_app.list_tools()
tool_names = [t.name for t in tools]
assert "shared_tool" in tool_names
# Test that calling the tool uses the first server's implementation
result = await main_app.call_tool("shared_tool", {})
assert result.structured_content == {"result": "First app tool"}
async def test_first_server_wins_tools_same_prefix(self):
"""Test that first mounted server wins for tools when same prefix is used."""
main_app = FastMCP("MainApp")
first_app = FastMCP("FirstApp")
second_app = FastMCP("SecondApp")
@first_app.tool(name="shared_tool")
def first_shared_tool() -> str:
return "First app tool"
@second_app.tool(name="shared_tool")
def second_shared_tool() -> str:
return "Second app tool"
# Mount both apps with same prefix
main_app.mount(first_app, "api")
main_app.mount(second_app, "api")
# list_tools returns all components; execution uses first match
tools = await main_app.list_tools()
tool_names = [t.name for t in tools]
assert "api_shared_tool" in tool_names
# Test that calling the tool uses the first server's implementation
result = await main_app.call_tool("api_shared_tool", {})
assert result.structured_content == {"result": "First app tool"}
async def test_first_server_wins_resources_no_prefix(self):
"""Test that first mounted server wins for resources when no prefix is used."""
main_app = FastMCP("MainApp")
first_app = FastMCP("FirstApp")
second_app = FastMCP("SecondApp")
@first_app.resource(uri="shared://data")
def first_resource():
return "First app data"
@second_app.resource(uri="shared://data")
def second_resource():
return "Second app data"
# Mount both apps without prefix
main_app.mount(first_app)
main_app.mount(second_app)
# list_resources returns all components; execution uses first match
resources = await main_app.list_resources()
resource_uris = [str(r.uri) for r in resources]
assert "shared://data" in resource_uris
# Test that reading the resource uses the first server's implementation
result = await main_app.read_resource("shared://data")
assert result.contents[0].content == "First app data"
async def test_first_server_wins_resources_same_prefix(self):
"""Test that first mounted server wins for resources when same prefix is used."""
main_app = FastMCP("MainApp")
first_app = FastMCP("FirstApp")
second_app = FastMCP("SecondApp")
@first_app.resource(uri="shared://data")
def first_resource():
return "First app data"
@second_app.resource(uri="shared://data")
def second_resource():
return "Second app data"
# Mount both apps with same prefix
main_app.mount(first_app, "api")
main_app.mount(second_app, "api")
# list_resources returns all components; execution uses first match
resources = await main_app.list_resources()
resource_uris = [str(r.uri) for r in resources]
assert "shared://api/data" in resource_uris
# Test that reading the resource uses the first server's implementation
result = await main_app.read_resource("shared://api/data")
assert result.contents[0].content == "First app data"
async def test_first_server_wins_resource_templates_no_prefix(self):
"""Test that first mounted server wins for resource templates when no prefix is used."""
main_app = FastMCP("MainApp")
first_app = FastMCP("FirstApp")
second_app = FastMCP("SecondApp")
@first_app.resource(uri="users://{user_id}/profile")
def first_template(user_id: str):
return f"First app user {user_id}"
@second_app.resource(uri="users://{user_id}/profile")
def second_template(user_id: str):
return f"Second app user {user_id}"
# Mount both apps without prefix
main_app.mount(first_app)
main_app.mount(second_app)
# list_resource_templates returns all components; execution uses first match
templates = await main_app.list_resource_templates()
template_uris = [t.uri_template for t in templates]
assert "users://{user_id}/profile" in template_uris
# Test that reading the resource uses the first server's implementation
result = await main_app.read_resource("users://123/profile")
assert result.contents[0].content == "First app user 123"
async def test_first_server_wins_resource_templates_same_prefix(self):
"""Test that first mounted server wins for resource templates when same prefix is used."""
main_app = FastMCP("MainApp")
first_app = FastMCP("FirstApp")
second_app = FastMCP("SecondApp")
@first_app.resource(uri="users://{user_id}/profile")
def first_template(user_id: str):
return f"First app user {user_id}"
@second_app.resource(uri="users://{user_id}/profile")
def second_template(user_id: str):
return f"Second app user {user_id}"
# Mount both apps with same prefix
main_app.mount(first_app, "api")
main_app.mount(second_app, "api")
# list_resource_templates returns all components; execution uses first match
templates = await main_app.list_resource_templates()
template_uris = [t.uri_template for t in templates]
assert "users://api/{user_id}/profile" in template_uris
# Test that reading the resource uses the first server's implementation
result = await main_app.read_resource("users://api/123/profile")
assert result.contents[0].content == "First app user 123"
async def test_first_server_wins_prompts_no_prefix(self):
"""Test that first mounted server wins for prompts when no prefix is used."""
main_app = FastMCP("MainApp")
first_app = FastMCP("FirstApp")
second_app = FastMCP("SecondApp")
@first_app.prompt(name="shared_prompt")
def first_shared_prompt() -> str:
return "First app prompt"
@second_app.prompt(name="shared_prompt")
def second_shared_prompt() -> str:
return "Second app prompt"
# Mount both apps without prefix
main_app.mount(first_app)
main_app.mount(second_app)
# list_prompts returns all components; execution uses first match
prompts = await main_app.list_prompts()
prompt_names = [p.name for p in prompts]
assert "shared_prompt" in prompt_names
# Test that getting the prompt uses the first server's implementation
result = await main_app.render_prompt("shared_prompt")
assert result.messages is not None
assert isinstance(result.messages[0].content, TextContent)
assert result.messages[0].content.text == "First app prompt"
async def test_first_server_wins_prompts_same_prefix(self):
"""Test that first mounted server wins for prompts when same prefix is used."""
main_app = FastMCP("MainApp")
first_app = FastMCP("FirstApp")
second_app = FastMCP("SecondApp")
@first_app.prompt(name="shared_prompt")
def first_shared_prompt() -> str:
return "First app prompt"
@second_app.prompt(name="shared_prompt")
def second_shared_prompt() -> str:
return "Second app prompt"
# Mount both apps with same prefix
main_app.mount(first_app, "api")
main_app.mount(second_app, "api")
# list_prompts returns all components; execution uses first match
prompts = await main_app.list_prompts()
prompt_names = [p.name for p in prompts]
assert "api_shared_prompt" in prompt_names
# Test that getting the prompt uses the first server's implementation
result = await main_app.render_prompt("api_shared_prompt")
assert result.messages is not None
assert isinstance(result.messages[0].content, TextContent)
assert result.messages[0].content.text == "First app prompt"
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/mount/test_mount.py",
"license": "Apache License 2.0",
"lines": 416,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/mount/test_prompts.py | """Tests for prompt mounting."""
from fastmcp import FastMCP
class TestPrompts:
"""Test mounting with prompts."""
async def test_mount_with_prompts(self):
"""Test mounting a server with prompts."""
main_app = FastMCP("MainApp")
assistant_app = FastMCP("AssistantApp")
@assistant_app.prompt
def greeting(name: str) -> str:
return f"Hello, {name}!"
# Mount the assistant app
main_app.mount(assistant_app, "assistant")
# Prompt should be accessible through main app
prompts = await main_app.list_prompts()
assert any(p.name == "assistant_greeting" for p in prompts)
# Render the prompt
result = await main_app.render_prompt("assistant_greeting", {"name": "World"})
assert result.messages is not None
# The message should contain our greeting text
async def test_adding_prompt_after_mounting(self):
"""Test adding a prompt after mounting."""
main_app = FastMCP("MainApp")
assistant_app = FastMCP("AssistantApp")
# Mount the assistant app before adding prompts
main_app.mount(assistant_app, "assistant")
# Add a prompt after mounting
@assistant_app.prompt
def farewell(name: str) -> str:
return f"Goodbye, {name}!"
# Prompt should be accessible through main app
prompts = await main_app.list_prompts()
assert any(p.name == "assistant_farewell" for p in prompts)
# Render the prompt
result = await main_app.render_prompt("assistant_farewell", {"name": "World"})
assert result.messages is not None
# The message should contain our farewell text
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/mount/test_prompts.py",
"license": "Apache License 2.0",
"lines": 37,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/mount/test_proxy.py | """Tests for proxy server mounting."""
import json
from contextlib import asynccontextmanager
from fastmcp import FastMCP
from fastmcp.client import Client
from fastmcp.client.transports import FastMCPTransport
from fastmcp.server.providers import FastMCPProvider
from fastmcp.server.providers.proxy import FastMCPProxy
from fastmcp.server.providers.wrapped_provider import _WrappedProvider
from fastmcp.server.transforms import Namespace
class TestProxyServer:
"""Test mounting a proxy server."""
async def test_mount_proxy_server(self):
"""Test mounting a proxy server."""
# Create original server
original_server = FastMCP("OriginalServer")
@original_server.tool
def get_data(query: str) -> str:
return f"Data for {query}"
# Create proxy server
proxy_server = FastMCP.as_proxy(FastMCPTransport(original_server))
# Mount proxy server
main_app = FastMCP("MainApp")
main_app.mount(proxy_server, "proxy")
# Tool should be accessible through main app
tools = await main_app.list_tools()
assert any(t.name == "proxy_get_data" for t in tools)
# Call the tool
result = await main_app.call_tool("proxy_get_data", {"query": "test"})
assert result.structured_content == {"result": "Data for test"}
async def test_dynamically_adding_to_proxied_server(self):
"""Test that changes to the original server are reflected in the mounted proxy."""
# Create original server
original_server = FastMCP("OriginalServer")
# Create proxy server
proxy_server = FastMCP.as_proxy(FastMCPTransport(original_server))
# Mount proxy server
main_app = FastMCP("MainApp")
main_app.mount(proxy_server, "proxy")
# Add a tool to the original server
@original_server.tool
def dynamic_data() -> str:
return "Dynamic data"
# Tool should be accessible through main app via proxy
tools = await main_app.list_tools()
assert any(t.name == "proxy_dynamic_data" for t in tools)
# Call the tool
result = await main_app.call_tool("proxy_dynamic_data", {})
assert result.structured_content == {"result": "Dynamic data"}
async def test_proxy_server_with_resources(self):
"""Test mounting a proxy server with resources."""
# Create original server
original_server = FastMCP("OriginalServer")
@original_server.resource(uri="config://settings")
def get_config() -> str:
return json.dumps({"api_key": "12345"})
# Create proxy server
proxy_server = FastMCP.as_proxy(FastMCPTransport(original_server))
# Mount proxy server
main_app = FastMCP("MainApp")
main_app.mount(proxy_server, "proxy")
# Resource should be accessible through main app
result = await main_app.read_resource("config://proxy/settings")
assert len(result.contents) == 1
config = json.loads(result.contents[0].content)
assert config["api_key"] == "12345"
async def test_proxy_server_with_prompts(self):
"""Test mounting a proxy server with prompts."""
# Create original server
original_server = FastMCP("OriginalServer")
@original_server.prompt
def welcome(name: str) -> str:
return f"Welcome, {name}!"
# Create proxy server
proxy_server = FastMCP.as_proxy(FastMCPTransport(original_server))
# Mount proxy server
main_app = FastMCP("MainApp")
main_app.mount(proxy_server, "proxy")
# Prompt should be accessible through main app
result = await main_app.render_prompt("proxy_welcome", {"name": "World"})
assert result.messages is not None
# The message should contain our welcome text
class TestAsProxyKwarg:
"""Test the as_proxy kwarg."""
async def test_as_proxy_defaults_false(self):
mcp = FastMCP("Main")
sub = FastMCP("Sub")
@sub.tool
def sub_tool() -> str:
return "test"
mcp.mount(sub, "sub")
# Index 1 because LocalProvider is at index 0
provider = mcp.providers[1]
# Provider is wrapped with Namespace transform
assert isinstance(provider, _WrappedProvider)
assert len(provider._transforms) == 1
assert isinstance(provider._transforms[0], Namespace)
# Inner provider is FastMCPProvider
assert isinstance(provider._inner, FastMCPProvider)
assert provider._inner.server is sub
# Verify namespace is applied
tools = await mcp.list_tools()
assert {t.name for t in tools} == {"sub_sub_tool"}
async def test_as_proxy_false(self):
mcp = FastMCP("Main")
sub = FastMCP("Sub")
@sub.tool
def sub_tool() -> str:
return "test"
mcp.mount(sub, "sub", as_proxy=False)
# Index 1 because LocalProvider is at index 0
provider = mcp.providers[1]
# Provider is wrapped with Namespace transform
assert isinstance(provider, _WrappedProvider)
assert len(provider._transforms) == 1
assert isinstance(provider._transforms[0], Namespace)
# Inner provider is FastMCPProvider
assert isinstance(provider._inner, FastMCPProvider)
assert provider._inner.server is sub
# Verify namespace is applied
tools = await mcp.list_tools()
assert {t.name for t in tools} == {"sub_sub_tool"}
async def test_as_proxy_true(self):
mcp = FastMCP("Main")
sub = FastMCP("Sub")
@sub.tool
def sub_tool() -> str:
return "test"
mcp.mount(sub, "sub", as_proxy=True)
# Index 1 because LocalProvider is at index 0
provider = mcp.providers[1]
# Provider is wrapped with Namespace transform
assert isinstance(provider, _WrappedProvider)
assert len(provider._transforms) == 1
assert isinstance(provider._transforms[0], Namespace)
# Inner provider is FastMCPProvider wrapping a proxy
assert isinstance(provider._inner, FastMCPProvider)
assert provider._inner.server is not sub
assert isinstance(provider._inner.server, FastMCPProxy)
# Verify namespace is applied
tools = await mcp.list_tools()
assert {t.name for t in tools} == {"sub_sub_tool"}
async def test_lifespan_server_mounted_directly(self):
"""Test that servers with lifespan are mounted directly (not auto-proxied).
Since FastMCPProvider now handles lifespan via the provider lifespan interface,
there's no need to auto-convert to a proxy. The server is mounted directly.
"""
@asynccontextmanager
async def server_lifespan(mcp: FastMCP):
yield
mcp = FastMCP("Main")
sub = FastMCP("Sub", lifespan=server_lifespan)
@sub.tool
def sub_tool() -> str:
return "test"
mcp.mount(sub, "sub")
# Server should be mounted directly without auto-proxying
# Index 1 because LocalProvider is at index 0
provider = mcp.providers[1]
# Provider is wrapped with Namespace transform
assert isinstance(provider, _WrappedProvider)
assert len(provider._transforms) == 1
assert isinstance(provider._transforms[0], Namespace)
# Inner provider is FastMCPProvider
assert isinstance(provider._inner, FastMCPProvider)
assert provider._inner.server is sub
# Verify namespace is applied
tools = await mcp.list_tools()
assert {t.name for t in tools} == {"sub_sub_tool"}
async def test_as_proxy_ignored_for_proxy_mounts_default(self):
mcp = FastMCP("Main")
sub = FastMCP("Sub")
sub_proxy = FastMCP.as_proxy(FastMCPTransport(sub))
mcp.mount(sub_proxy, "sub")
# Index 1 because LocalProvider is at index 0
provider = mcp.providers[1]
# Provider is wrapped with Namespace transform
assert isinstance(provider, _WrappedProvider)
assert len(provider._transforms) == 1
assert isinstance(provider._transforms[0], Namespace)
# Inner provider is FastMCPProvider
assert isinstance(provider._inner, FastMCPProvider)
assert provider._inner.server is sub_proxy
async def test_as_proxy_ignored_for_proxy_mounts_false(self):
mcp = FastMCP("Main")
sub = FastMCP("Sub")
sub_proxy = FastMCP.as_proxy(FastMCPTransport(sub))
mcp.mount(sub_proxy, "sub", as_proxy=False)
# Index 1 because LocalProvider is at index 0
provider = mcp.providers[1]
# Provider is wrapped with Namespace transform
assert isinstance(provider, _WrappedProvider)
assert len(provider._transforms) == 1
assert isinstance(provider._transforms[0], Namespace)
# Inner provider is FastMCPProvider
assert isinstance(provider._inner, FastMCPProvider)
assert provider._inner.server is sub_proxy
async def test_as_proxy_ignored_for_proxy_mounts_true(self):
mcp = FastMCP("Main")
sub = FastMCP("Sub")
sub_proxy = FastMCP.as_proxy(FastMCPTransport(sub))
mcp.mount(sub_proxy, "sub", as_proxy=True)
# Index 1 because LocalProvider is at index 0
provider = mcp.providers[1]
# Provider is wrapped with Namespace transform
assert isinstance(provider, _WrappedProvider)
assert len(provider._transforms) == 1
assert isinstance(provider._transforms[0], Namespace)
# Inner provider is FastMCPProvider
assert isinstance(provider._inner, FastMCPProvider)
assert provider._inner.server is sub_proxy
async def test_as_proxy_mounts_still_have_live_link(self):
mcp = FastMCP("Main")
sub = FastMCP("Sub")
mcp.mount(sub, "sub", as_proxy=True)
assert len(await mcp.list_tools()) == 0
@sub.tool
def hello():
return "hi"
assert len(await mcp.list_tools()) == 1
async def test_sub_lifespan_is_executed(self):
lifespan_check = []
@asynccontextmanager
async def lifespan(mcp: FastMCP):
lifespan_check.append("start")
yield
mcp = FastMCP("Main")
sub = FastMCP("Sub", lifespan=lifespan)
@sub.tool
def hello():
return "hi"
mcp.mount(sub, as_proxy=True)
assert lifespan_check == []
async with Client(mcp) as client:
await client.call_tool("hello", {})
# Lifespan is executed at least once (may be multiple times for proxy connections)
assert len(lifespan_check) >= 1
assert all(x == "start" for x in lifespan_check)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/mount/test_proxy.py",
"license": "Apache License 2.0",
"lines": 238,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/mount/test_resources.py | """Tests for resource and template mounting."""
import json
from fastmcp import FastMCP
class TestResourcesAndTemplates:
"""Test mounting with resources and resource templates."""
async def test_mount_with_resources(self):
"""Test mounting a server with resources."""
main_app = FastMCP("MainApp")
data_app = FastMCP("DataApp")
@data_app.resource(uri="data://users")
async def get_users() -> str:
return "user1, user2"
# Mount the data app
main_app.mount(data_app, "data")
# Resource should be accessible through main app
resources = await main_app.list_resources()
assert any(str(r.uri) == "data://data/users" for r in resources)
# Check that resource can be accessed
result = await main_app.read_resource("data://data/users")
assert len(result.contents) == 1
# Note: The function returns "user1, user2" which is not valid JSON
# This test should be updated to return proper JSON or check the string directly
assert result.contents[0].content == "user1, user2"
async def test_mount_with_resource_templates(self):
"""Test mounting a server with resource templates."""
main_app = FastMCP("MainApp")
user_app = FastMCP("UserApp")
@user_app.resource(uri="users://{user_id}/profile")
def get_user_profile(user_id: str) -> str:
return json.dumps({"id": user_id, "name": f"User {user_id}"})
# Mount the user app
main_app.mount(user_app, "api")
# Template should be accessible through main app
templates = await main_app.list_resource_templates()
assert any(t.uri_template == "users://api/{user_id}/profile" for t in templates)
# Check template instantiation
result = await main_app.read_resource("users://api/123/profile")
assert len(result.contents) == 1
profile = json.loads(result.contents[0].content)
assert profile["id"] == "123"
assert profile["name"] == "User 123"
async def test_adding_resource_after_mounting(self):
"""Test adding a resource after mounting."""
main_app = FastMCP("MainApp")
data_app = FastMCP("DataApp")
# Mount the data app before adding resources
main_app.mount(data_app, "data")
# Add a resource after mounting
@data_app.resource(uri="data://config")
def get_config() -> str:
return json.dumps({"version": "1.0"})
# Resource should be accessible through main app
resources = await main_app.list_resources()
assert any(str(r.uri) == "data://data/config" for r in resources)
# Check access to the resource
result = await main_app.read_resource("data://data/config")
assert len(result.contents) == 1
config = json.loads(result.contents[0].content)
assert config["version"] == "1.0"
class TestResourceUriPrefixing:
"""Test that resource and resource template URIs get prefixed when mounted (names are NOT prefixed)."""
async def test_resource_uri_prefixing(self):
"""Test that resource URIs are prefixed when mounted (names are NOT prefixed)."""
# Create a sub-app with a resource
sub_app = FastMCP("SubApp")
@sub_app.resource("resource://my_resource")
def my_resource() -> str:
return "Resource content"
# Create main app and mount sub-app with prefix
main_app = FastMCP("MainApp")
main_app.mount(sub_app, "prefix")
# Get resources from main app
resources = await main_app.list_resources()
# Should have prefixed key (using path format: resource://prefix/resource_name)
assert any(str(r.uri) == "resource://prefix/my_resource" for r in resources)
# The resource name should NOT be prefixed (only URI is prefixed)
resource = next(
r for r in resources if str(r.uri) == "resource://prefix/my_resource"
)
assert resource.name == "my_resource"
async def test_resource_template_uri_prefixing(self):
"""Test that resource template URIs are prefixed when mounted (names are NOT prefixed)."""
# Create a sub-app with a resource template
sub_app = FastMCP("SubApp")
@sub_app.resource("resource://user/{user_id}")
def user_template(user_id: str) -> str:
return f"User {user_id} data"
# Create main app and mount sub-app with prefix
main_app = FastMCP("MainApp")
main_app.mount(sub_app, "prefix")
# Get resource templates from main app
templates = await main_app.list_resource_templates()
# Should have prefixed key (using path format: resource://prefix/template_uri)
assert any(
t.uri_template == "resource://prefix/user/{user_id}" for t in templates
)
# The template name should NOT be prefixed (only URI template is prefixed)
template = next(
t for t in templates if t.uri_template == "resource://prefix/user/{user_id}"
)
assert template.name == "user_template"
class TestMountedResourceTemplateQueryParams:
"""Test that resource templates with query params work on mounted servers."""
async def test_mounted_template_with_query_param(self):
"""Query params in resource templates should work through mount."""
sub = FastMCP("Sub")
@sub.resource("resource://greet{?name}")
def greet(name: str = "World") -> str:
return f"Hello, {name}!"
main = FastMCP("Main")
main.mount(sub, "sub")
result = await main.read_resource("resource://sub/greet?name=Alice")
assert result.contents[0].content == "Hello, Alice!"
async def test_mounted_template_with_query_param_default(self):
"""Missing query params should use defaults through mount."""
sub = FastMCP("Sub")
@sub.resource("resource://greet{?name}")
def greet(name: str = "World") -> str:
return f"Hello, {name}!"
main = FastMCP("Main")
main.mount(sub, "sub")
result = await main.read_resource("resource://sub/greet")
assert result.contents[0].content == "Hello, World!"
async def test_mounted_template_with_multiple_query_params(self):
"""Multiple query params should all pass through mount correctly."""
sub = FastMCP("Sub")
@sub.resource("resource://data/{id}{?format,verbose}")
def get_data(id: str, format: str = "json", verbose: bool = False) -> str:
return f"id={id} format={format} verbose={verbose}"
main = FastMCP("Main")
main.mount(sub, "api")
result = await main.read_resource(
"resource://api/data/42?format=xml&verbose=true"
)
assert result.contents[0].content == "id=42 format=xml verbose=True"
async def test_mounted_template_with_partial_query_params(self):
"""Providing only some query params should use defaults for the rest."""
sub = FastMCP("Sub")
@sub.resource("resource://data/{id}{?format,limit}")
def get_data(id: str, format: str = "json", limit: int = 10) -> str:
return f"id={id} format={format} limit={limit}"
main = FastMCP("Main")
main.mount(sub, "api")
result = await main.read_resource("resource://api/data/42?limit=5")
assert result.contents[0].content == "id=42 format=json limit=5"
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/mount/test_resources.py",
"license": "Apache License 2.0",
"lines": 145,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/providers/local_provider_tools/test_context.py | """Tests for tool context injection."""
import functools
from dataclasses import dataclass
from pydantic import BaseModel
from typing_extensions import TypedDict
from fastmcp import Context, FastMCP
from fastmcp.tools.tool import Tool
def _normalize_anyof_order(schema):
"""Normalize the order of items in anyOf arrays for consistent comparison."""
if isinstance(schema, dict):
if "anyOf" in schema:
schema = schema.copy()
schema["anyOf"] = sorted(schema["anyOf"], key=str)
return {k: _normalize_anyof_order(v) for k, v in schema.items()}
elif isinstance(schema, list):
return [_normalize_anyof_order(item) for item in schema]
return schema
class PersonTypedDict(TypedDict):
name: str
age: int
class PersonModel(BaseModel):
name: str
age: int
@dataclass
class PersonDataclass:
name: str
age: int
class TestToolContextInjection:
"""Test context injection in tools."""
async def test_context_detection(self):
"""Test that context parameters are properly detected and excluded from schema."""
mcp = FastMCP()
@mcp.tool
def tool_with_context(x: int, ctx: Context) -> str:
return f"Request: {x}"
tools = await mcp.list_tools()
assert len(tools) == 1
assert tools[0].name == "tool_with_context"
# Context param should not appear in schema
assert "ctx" not in tools[0].parameters.get("properties", {})
async def test_context_injection_basic(self):
"""Test that context is properly injected into tool calls."""
mcp = FastMCP()
@mcp.tool
def tool_with_context(x: int, ctx: Context) -> str:
assert isinstance(ctx, Context)
return f"Got context with x={x}"
result = await mcp.call_tool("tool_with_context", {"x": 42})
assert result.structured_content == {"result": "Got context with x=42"}
async def test_async_context(self):
"""Test that context works in async functions."""
mcp = FastMCP()
@mcp.tool
async def async_tool(x: int, ctx: Context) -> str:
assert isinstance(ctx, Context)
return f"Async with x={x}"
result = await mcp.call_tool("async_tool", {"x": 42})
assert result.structured_content == {"result": "Async with x=42"}
async def test_optional_context(self):
"""Test that context is optional."""
mcp = FastMCP()
@mcp.tool
def no_context(x: int) -> int:
return x * 2
result = await mcp.call_tool("no_context", {"x": 21})
assert result.structured_content == {"result": 42}
async def test_context_resource_access(self):
"""Test that context can access resources."""
mcp = FastMCP()
@mcp.resource("test://data")
def test_resource() -> str:
return "resource data"
@mcp.tool
async def tool_with_resource(ctx: Context) -> str:
result = await ctx.read_resource("test://data")
assert len(result.contents) == 1
r = result.contents[0]
return f"Read resource: {r.content} with mime type {r.mime_type}"
result = await mcp.call_tool("tool_with_resource", {})
assert result.structured_content == {
"result": "Read resource: resource data with mime type text/plain"
}
async def test_tool_decorator_with_tags(self):
"""Test that the tool decorator properly sets tags."""
mcp = FastMCP()
@mcp.tool(tags={"example", "test-tag"})
def sample_tool(x: int) -> int:
return x * 2
tools = await mcp.list_tools()
assert len(tools) == 1
assert tools[0].tags == {"example", "test-tag"}
async def test_callable_object_with_context(self):
"""Test that a callable object can be used as a tool with context."""
mcp = FastMCP()
class MyTool:
async def __call__(self, x: int, ctx: Context) -> int:
assert isinstance(ctx, Context)
return x + 1
mcp.add_tool(Tool.from_function(MyTool(), name="MyTool"))
result = await mcp.call_tool("MyTool", {"x": 2})
assert result.structured_content == {"result": 3}
async def test_decorated_tool_with_functools_wraps(self):
"""Regression test for #2524: @mcp.tool with functools.wraps decorator."""
def custom_decorator(func):
@functools.wraps(func)
async def wrapper(*args, **kwargs):
return await func(*args, **kwargs)
return wrapper
mcp = FastMCP()
@mcp.tool
@custom_decorator
async def decorated_tool(ctx: Context, query: str) -> str:
assert isinstance(ctx, Context)
return f"query: {query}"
tools = await mcp.list_tools()
tool = next(t for t in tools if t.name == "decorated_tool")
assert "ctx" not in tool.parameters.get("properties", {})
result = await mcp.call_tool("decorated_tool", {"query": "test"})
assert result.structured_content == {"result": "query: test"}
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/providers/local_provider_tools/test_context.py",
"license": "Apache License 2.0",
"lines": 119,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/providers/local_provider_tools/test_decorator.py | """Tests for tool decorator patterns."""
from dataclasses import dataclass
from typing import Annotated
import pytest
from pydantic import BaseModel, Field
from typing_extensions import TypedDict
from fastmcp import FastMCP
from fastmcp.exceptions import NotFoundError
from fastmcp.tools.tool import Tool
def _normalize_anyof_order(schema):
"""Normalize the order of items in anyOf arrays for consistent comparison."""
if isinstance(schema, dict):
if "anyOf" in schema:
schema = schema.copy()
schema["anyOf"] = sorted(schema["anyOf"], key=str)
return {k: _normalize_anyof_order(v) for k, v in schema.items()}
elif isinstance(schema, list):
return [_normalize_anyof_order(item) for item in schema]
return schema
class PersonTypedDict(TypedDict):
name: str
age: int
class PersonModel(BaseModel):
name: str
age: int
@dataclass
class PersonDataclass:
name: str
age: int
class TestToolDecorator:
async def test_no_tools_before_decorator(self):
mcp = FastMCP()
with pytest.raises(NotFoundError, match="Unknown tool: 'add'"):
await mcp.call_tool("add", {"x": 1, "y": 2})
async def test_tool_decorator(self):
mcp = FastMCP()
@mcp.tool
def add(x: int, y: int) -> int:
return x + y
result = await mcp.call_tool("add", {"x": 1, "y": 2})
assert result.structured_content == {"result": 3}
async def test_tool_decorator_without_parentheses(self):
"""Test that @tool decorator works without parentheses."""
mcp = FastMCP()
@mcp.tool
def add(x: int, y: int) -> int:
return x + y
tools = await mcp.list_tools()
assert any(t.name == "add" for t in tools)
result = await mcp.call_tool("add", {"x": 1, "y": 2})
assert result.structured_content == {"result": 3}
async def test_tool_decorator_with_name(self):
mcp = FastMCP()
@mcp.tool(name="custom-add")
def add(x: int, y: int) -> int:
return x + y
result = await mcp.call_tool("custom-add", {"x": 1, "y": 2})
assert result.structured_content == {"result": 3}
async def test_tool_decorator_with_description(self):
mcp = FastMCP()
@mcp.tool(description="Add two numbers")
def add(x: int, y: int) -> int:
return x + y
tools = await mcp.list_tools()
assert len(tools) == 1
tool = tools[0]
assert tool.description == "Add two numbers"
async def test_tool_decorator_instance_method(self):
mcp = FastMCP()
class MyClass:
def __init__(self, x: int):
self.x = x
def add(self, y: int) -> int:
return self.x + y
obj = MyClass(10)
mcp.add_tool(Tool.from_function(obj.add))
result = await mcp.call_tool("add", {"y": 2})
assert result.structured_content == {"result": 12}
async def test_tool_decorator_classmethod(self):
mcp = FastMCP()
class MyClass:
x: int = 10
@classmethod
def add(cls, y: int) -> int:
return cls.x + y
mcp.add_tool(Tool.from_function(MyClass.add))
result = await mcp.call_tool("add", {"y": 2})
assert result.structured_content == {"result": 12}
async def test_tool_decorator_staticmethod(self):
mcp = FastMCP()
class MyClass:
@mcp.tool
@staticmethod
def add(x: int, y: int) -> int:
return x + y
result = await mcp.call_tool("add", {"x": 1, "y": 2})
assert result.structured_content == {"result": 3}
async def test_tool_decorator_async_function(self):
mcp = FastMCP()
@mcp.tool
async def add(x: int, y: int) -> int:
return x + y
result = await mcp.call_tool("add", {"x": 1, "y": 2})
assert result.structured_content == {"result": 3}
async def test_tool_decorator_classmethod_error(self):
mcp = FastMCP()
with pytest.raises(TypeError, match="classmethod"):
class MyClass:
@mcp.tool
@classmethod
def add(cls, y: int) -> None:
pass
async def test_tool_decorator_classmethod_async_function(self):
mcp = FastMCP()
class MyClass:
x = 10
@classmethod
async def add(cls, y: int) -> int:
return cls.x + y
mcp.add_tool(Tool.from_function(MyClass.add))
result = await mcp.call_tool("add", {"y": 2})
assert result.structured_content == {"result": 12}
async def test_tool_decorator_staticmethod_async_function(self):
mcp = FastMCP()
class MyClass:
@staticmethod
async def add(x: int, y: int) -> int:
return x + y
mcp.add_tool(Tool.from_function(MyClass.add))
result = await mcp.call_tool("add", {"x": 1, "y": 2})
assert result.structured_content == {"result": 3}
async def test_tool_decorator_staticmethod_order(self):
"""Test that the recommended decorator order works for static methods"""
mcp = FastMCP()
class MyClass:
@mcp.tool
@staticmethod
def add_v1(x: int, y: int) -> int:
return x + y
result = await mcp.call_tool("add_v1", {"x": 1, "y": 2})
assert result.structured_content == {"result": 3}
async def test_tool_decorator_with_tags(self):
"""Test that the tool decorator properly sets tags."""
mcp = FastMCP()
@mcp.tool(tags={"example", "test-tag"})
def sample_tool(x: int) -> int:
return x * 2
tools = await mcp.list_tools()
assert len(tools) == 1
assert tools[0].tags == {"example", "test-tag"}
async def test_add_tool_with_custom_name(self):
"""Test adding a tool with a custom name using server.add_tool()."""
mcp = FastMCP()
def multiply(a: int, b: int) -> int:
"""Multiply two numbers."""
return a * b
mcp.add_tool(Tool.from_function(multiply, name="custom_multiply"))
tools = await mcp.list_tools()
assert any(t.name == "custom_multiply" for t in tools)
result = await mcp.call_tool("custom_multiply", {"a": 5, "b": 3})
assert result.structured_content == {"result": 15}
assert not any(t.name == "multiply" for t in tools)
async def test_tool_with_annotated_arguments(self):
"""Test that tools with annotated arguments work correctly."""
mcp = FastMCP()
@mcp.tool
def add(
x: Annotated[int, Field(description="x is an int")],
y: Annotated[str, Field(description="y is not an int")],
) -> None:
pass
tools = await mcp.list_tools()
tool = next(t for t in tools if t.name == "add")
assert tool.parameters["properties"]["x"]["description"] == "x is an int"
assert tool.parameters["properties"]["y"]["description"] == "y is not an int"
async def test_tool_with_field_defaults(self):
"""Test that tools with annotated arguments work correctly."""
mcp = FastMCP()
@mcp.tool
def add(
x: int = Field(description="x is an int"),
y: str = Field(description="y is not an int"),
) -> None:
pass
tools = await mcp.list_tools()
tool = next(t for t in tools if t.name == "add")
assert tool.parameters["properties"]["x"]["description"] == "x is an int"
assert tool.parameters["properties"]["y"]["description"] == "y is not an int"
async def test_tool_direct_function_call(self):
"""Test that tools can be registered via direct function call."""
from typing import cast
from fastmcp.tools.function_tool import DecoratedTool
mcp = FastMCP()
def standalone_function(x: int, y: int) -> int:
"""A standalone function to be registered."""
return x + y
result_fn = mcp.tool(standalone_function, name="direct_call_tool")
# In new decorator mode, returns the function with metadata
decorated = cast(DecoratedTool, result_fn)
assert hasattr(result_fn, "__fastmcp__")
assert decorated.__fastmcp__.name == "direct_call_tool"
assert result_fn is standalone_function
tools = await mcp.list_tools()
tool = next(t for t in tools if t.name == "direct_call_tool")
# Tool is registered separately, not same object as decorated function
assert tool.name == "direct_call_tool"
result = await mcp.call_tool("direct_call_tool", {"x": 5, "y": 3})
assert result.structured_content == {"result": 8}
async def test_tool_decorator_with_string_name(self):
"""Test that @tool("custom_name") syntax works correctly."""
mcp = FastMCP()
@mcp.tool("string_named_tool")
def my_function(x: int) -> str:
"""A function with a string name."""
return f"Result: {x}"
tools = await mcp.list_tools()
assert any(t.name == "string_named_tool" for t in tools)
assert not any(t.name == "my_function" for t in tools)
result = await mcp.call_tool("string_named_tool", {"x": 42})
assert result.structured_content == {"result": "Result: 42"}
async def test_tool_decorator_conflicting_names_error(self):
"""Test that providing both positional and keyword name raises an error."""
mcp = FastMCP()
with pytest.raises(
TypeError,
match="Cannot specify both a name as first argument and as keyword argument",
):
@mcp.tool("positional_name", name="keyword_name")
def my_function(x: int) -> str:
return f"Result: {x}"
async def test_tool_decorator_with_output_schema(self):
mcp = FastMCP()
with pytest.raises(
ValueError, match="Output schemas must represent object types"
):
@mcp.tool(output_schema={"type": "integer"})
def my_function(x: int) -> str:
return f"Result: {x}"
async def test_tool_decorator_with_meta(self):
"""Test that meta parameter is passed through the tool decorator."""
mcp = FastMCP()
meta_data = {"version": "1.0", "author": "test"}
@mcp.tool(meta=meta_data)
def multiply(a: int, b: int) -> int:
"""Multiply two numbers."""
return a * b
tools = await mcp.list_tools()
tool = next(t for t in tools if t.name == "multiply")
assert tool.meta == meta_data
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/providers/local_provider_tools/test_decorator.py",
"license": "Apache License 2.0",
"lines": 249,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/providers/local_provider_tools/test_enabled.py | """Tests for tool enabled/disabled state."""
from dataclasses import dataclass
import pytest
from pydantic import BaseModel
from typing_extensions import TypedDict
from fastmcp import FastMCP
from fastmcp.exceptions import NotFoundError
def _normalize_anyof_order(schema):
"""Normalize the order of items in anyOf arrays for consistent comparison."""
if isinstance(schema, dict):
if "anyOf" in schema:
schema = schema.copy()
schema["anyOf"] = sorted(schema["anyOf"], key=str)
return {k: _normalize_anyof_order(v) for k, v in schema.items()}
elif isinstance(schema, list):
return [_normalize_anyof_order(item) for item in schema]
return schema
class PersonTypedDict(TypedDict):
name: str
age: int
class PersonModel(BaseModel):
name: str
age: int
@dataclass
class PersonDataclass:
name: str
age: int
class TestToolEnabled:
async def test_toggle_enabled(self):
mcp = FastMCP()
@mcp.tool
def sample_tool(x: int) -> int:
return x * 2
# Tool is enabled by default
tools = await mcp.list_tools()
assert any(t.name == "sample_tool" for t in tools)
# Disable via server
mcp.disable(names={"sample_tool"}, components={"tool"})
# Tool should not be in list when disabled
tools = await mcp.list_tools()
assert not any(t.name == "sample_tool" for t in tools)
# Re-enable via server
mcp.enable(names={"sample_tool"}, components={"tool"})
tools = await mcp.list_tools()
assert any(t.name == "sample_tool" for t in tools)
async def test_tool_disabled_via_server(self):
mcp = FastMCP()
@mcp.tool
def sample_tool(x: int) -> int:
return x * 2
mcp.disable(names={"sample_tool"}, components={"tool"})
tools = await mcp.list_tools()
assert len(tools) == 0
with pytest.raises(NotFoundError, match="Unknown tool"):
await mcp.call_tool("sample_tool", {"x": 5})
async def test_tool_toggle_enabled(self):
mcp = FastMCP()
@mcp.tool
def sample_tool(x: int) -> int:
return x * 2
mcp.disable(names={"sample_tool"}, components={"tool"})
mcp.enable(names={"sample_tool"}, components={"tool"})
tools = await mcp.list_tools()
assert len(tools) == 1
async def test_tool_toggle_disabled(self):
mcp = FastMCP()
@mcp.tool
def sample_tool(x: int) -> int:
return x * 2
mcp.disable(names={"sample_tool"}, components={"tool"})
tools = await mcp.list_tools()
assert len(tools) == 0
with pytest.raises(NotFoundError, match="Unknown tool"):
await mcp.call_tool("sample_tool", {"x": 5})
async def test_get_tool_and_disable(self):
mcp = FastMCP()
@mcp.tool
def sample_tool(x: int) -> int:
return x * 2
tool = await mcp.get_tool("sample_tool")
assert tool is not None
mcp.disable(names={"sample_tool"}, components={"tool"})
tools = await mcp.list_tools()
assert len(tools) == 0
with pytest.raises(NotFoundError, match="Unknown tool"):
await mcp.call_tool("sample_tool", {"x": 5})
async def test_cant_call_disabled_tool(self):
mcp = FastMCP()
@mcp.tool
def sample_tool(x: int) -> int:
return x * 2
mcp.disable(names={"sample_tool"}, components={"tool"})
with pytest.raises(NotFoundError, match="Unknown tool"):
await mcp.call_tool("sample_tool", {"x": 5})
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/providers/local_provider_tools/test_enabled.py",
"license": "Apache License 2.0",
"lines": 94,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/providers/local_provider_tools/test_local_provider_tools.py | """Core tool return types and serialization tests."""
import base64
import datetime
import json
import uuid
from dataclasses import dataclass
from pathlib import Path
from mcp.types import (
AudioContent,
EmbeddedResource,
ImageContent,
TextContent,
)
from pydantic import BaseModel
from typing_extensions import TypedDict
from fastmcp import FastMCP
from fastmcp.utilities.types import Audio, File, Image
def _normalize_anyof_order(schema):
"""Normalize the order of items in anyOf arrays for consistent comparison."""
if isinstance(schema, dict):
if "anyOf" in schema:
schema = schema.copy()
schema["anyOf"] = sorted(schema["anyOf"], key=str)
return {k: _normalize_anyof_order(v) for k, v in schema.items()}
elif isinstance(schema, list):
return [_normalize_anyof_order(item) for item in schema]
return schema
class PersonTypedDict(TypedDict):
name: str
age: int
class PersonModel(BaseModel):
name: str
age: int
@dataclass
class PersonDataclass:
name: str
age: int
class TestToolReturnTypes:
async def test_string(self):
mcp = FastMCP()
@mcp.tool
def string_tool() -> str:
return "Hello, world!"
result = await mcp.call_tool("string_tool", {})
assert result.structured_content == {"result": "Hello, world!"}
async def test_bytes(self, tmp_path: Path):
mcp = FastMCP()
@mcp.tool
def bytes_tool() -> bytes:
return b"Hello, world!"
result = await mcp.call_tool("bytes_tool", {})
assert result.structured_content == {"result": "Hello, world!"}
async def test_uuid(self):
mcp = FastMCP()
test_uuid = uuid.uuid4()
@mcp.tool
def uuid_tool() -> uuid.UUID:
return test_uuid
result = await mcp.call_tool("uuid_tool", {})
assert result.structured_content == {"result": str(test_uuid)}
async def test_path(self):
mcp = FastMCP()
test_path = Path("/tmp/test.txt")
@mcp.tool
def path_tool() -> Path:
return test_path
result = await mcp.call_tool("path_tool", {})
assert result.structured_content == {"result": str(test_path)}
async def test_datetime(self):
mcp = FastMCP()
dt = datetime.datetime(2025, 4, 25, 1, 2, 3)
@mcp.tool
def datetime_tool() -> datetime.datetime:
return dt
result = await mcp.call_tool("datetime_tool", {})
assert result.structured_content == {"result": dt.isoformat()}
async def test_image(self, tmp_path: Path):
mcp = FastMCP()
@mcp.tool
def image_tool(path: str) -> Image:
return Image(path)
image_path = tmp_path / "test.png"
image_path.write_bytes(b"fake png data")
result = await mcp.call_tool("image_tool", {"path": str(image_path)})
assert result.structured_content is None
assert isinstance(result.content, list)
content = result.content[0]
assert isinstance(content, ImageContent)
assert content.type == "image"
assert content.mimeType == "image/png"
decoded = base64.b64decode(content.data)
assert decoded == b"fake png data"
async def test_audio(self, tmp_path: Path):
mcp = FastMCP()
@mcp.tool
def audio_tool(path: str) -> Audio:
return Audio(path)
audio_path = tmp_path / "test.wav"
audio_path.write_bytes(b"fake wav data")
result = await mcp.call_tool("audio_tool", {"path": str(audio_path)})
assert isinstance(result.content, list)
content = result.content[0]
assert isinstance(content, AudioContent)
assert content.type == "audio"
assert content.mimeType == "audio/wav"
decoded = base64.b64decode(content.data)
assert decoded == b"fake wav data"
async def test_file(self, tmp_path: Path):
mcp = FastMCP()
@mcp.tool
def file_tool(path: str) -> File:
return File(path)
file_path = tmp_path / "test.bin"
file_path.write_bytes(b"test file data")
result = await mcp.call_tool("file_tool", {"path": str(file_path)})
assert isinstance(result.content, list)
content = result.content[0]
assert isinstance(content, EmbeddedResource)
assert content.type == "resource"
resource = content.resource
assert resource.mimeType == "application/octet-stream"
assert hasattr(resource, "blob")
blob_data = getattr(resource, "blob")
decoded = base64.b64decode(blob_data)
assert decoded == b"test file data"
assert str(resource.uri) == file_path.resolve().as_uri()
async def test_tool_mixed_content(self, tool_server: FastMCP):
result = await tool_server.call_tool("mixed_content_tool", {})
assert isinstance(result.content, list)
assert len(result.content) == 3
content1 = result.content[0]
content2 = result.content[1]
content3 = result.content[2]
assert isinstance(content1, TextContent)
assert content1.text == "Hello"
assert isinstance(content2, ImageContent)
assert content2.mimeType == "application/octet-stream"
assert content2.data == "abc"
assert isinstance(content3, EmbeddedResource)
assert content3.type == "resource"
resource = content3.resource
assert resource.mimeType == "application/octet-stream"
assert hasattr(resource, "blob")
blob_data = getattr(resource, "blob")
decoded = base64.b64decode(blob_data)
assert decoded == b"abc"
async def test_tool_mixed_list_with_image(
self, tool_server: FastMCP, tmp_path: Path
):
"""Test that lists containing Image objects and other types are handled
correctly. Items now preserve their original order."""
image_path = tmp_path / "test.png"
image_path.write_bytes(b"test image data")
result = await tool_server.call_tool(
"mixed_list_fn", {"image_path": str(image_path)}
)
assert isinstance(result.content, list)
assert len(result.content) == 4
content1 = result.content[0]
assert isinstance(content1, TextContent)
assert content1.text == "text message"
content2 = result.content[1]
assert isinstance(content2, ImageContent)
assert content2.mimeType == "image/png"
assert base64.b64decode(content2.data) == b"test image data"
content3 = result.content[2]
assert isinstance(content3, TextContent)
assert json.loads(content3.text) == {"key": "value"}
content4 = result.content[3]
assert isinstance(content4, TextContent)
assert content4.text == "direct content"
async def test_tool_mixed_list_with_audio(
self, tool_server: FastMCP, tmp_path: Path
):
"""Test that lists containing Audio objects and other types are handled
correctly. Items now preserve their original order."""
audio_path = tmp_path / "test.wav"
audio_path.write_bytes(b"test audio data")
result = await tool_server.call_tool(
"mixed_audio_list_fn", {"audio_path": str(audio_path)}
)
assert isinstance(result.content, list)
assert len(result.content) == 4
content1 = result.content[0]
assert isinstance(content1, TextContent)
assert content1.text == "text message"
content2 = result.content[1]
assert isinstance(content2, AudioContent)
assert content2.mimeType == "audio/wav"
assert base64.b64decode(content2.data) == b"test audio data"
content3 = result.content[2]
assert isinstance(content3, TextContent)
assert json.loads(content3.text) == {"key": "value"}
content4 = result.content[3]
assert isinstance(content4, TextContent)
assert content4.text == "direct content"
async def test_tool_mixed_list_with_file(
self, tool_server: FastMCP, tmp_path: Path
):
"""Test that lists containing File objects and other types are handled
correctly. Items now preserve their original order."""
file_path = tmp_path / "test.bin"
file_path.write_bytes(b"test file data")
result = await tool_server.call_tool(
"mixed_file_list_fn", {"file_path": str(file_path)}
)
assert isinstance(result.content, list)
assert len(result.content) == 4
content1 = result.content[0]
assert isinstance(content1, TextContent)
assert content1.text == "text message"
content2 = result.content[1]
assert isinstance(content2, EmbeddedResource)
assert content2.type == "resource"
resource = content2.resource
assert resource.mimeType == "application/octet-stream"
assert hasattr(resource, "blob")
blob_data = getattr(resource, "blob")
assert base64.b64decode(blob_data) == b"test file data"
content3 = result.content[2]
assert isinstance(content3, TextContent)
assert json.loads(content3.text) == {"key": "value"}
content4 = result.content[3]
assert isinstance(content4, TextContent)
assert content4.text == "direct content"
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/providers/local_provider_tools/test_local_provider_tools.py",
"license": "Apache License 2.0",
"lines": 225,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/providers/local_provider_tools/test_output_schema.py | """Tests for tool output schemas."""
from dataclasses import dataclass
from typing import Any, Literal
import pytest
from mcp.types import (
TextContent,
)
from pydantic import AnyUrl, BaseModel, TypeAdapter
from typing_extensions import TypeAliasType, TypedDict
from fastmcp import FastMCP
from fastmcp.tools.function_parsing import _is_object_schema
from fastmcp.tools.tool import ToolResult
from fastmcp.utilities.json_schema import compress_schema
def _normalize_anyof_order(schema):
"""Normalize the order of items in anyOf arrays for consistent comparison."""
if isinstance(schema, dict):
if "anyOf" in schema:
schema = schema.copy()
schema["anyOf"] = sorted(schema["anyOf"], key=str)
return {k: _normalize_anyof_order(v) for k, v in schema.items()}
elif isinstance(schema, list):
return [_normalize_anyof_order(item) for item in schema]
return schema
class PersonTypedDict(TypedDict):
name: str
age: int
class PersonModel(BaseModel):
name: str
age: int
@dataclass
class PersonDataclass:
name: str
age: int
class TestToolOutputSchema:
@pytest.mark.parametrize("annotation", [str, int, float, bool, list, AnyUrl])
async def test_simple_output_schema(self, annotation):
mcp = FastMCP()
@mcp.tool
def f() -> annotation:
return "hello"
tools = await mcp.list_tools()
assert len(tools) == 1
type_schema = TypeAdapter(annotation).json_schema()
type_schema = compress_schema(type_schema, prune_titles=True)
assert tools[0].output_schema == {
"type": "object",
"properties": {"result": type_schema},
"required": ["result"],
"x-fastmcp-wrap-result": True,
}
@pytest.mark.parametrize(
"annotation",
[dict[str, int | str], PersonTypedDict, PersonModel, PersonDataclass],
)
async def test_structured_output_schema(self, annotation):
mcp = FastMCP()
@mcp.tool
def f() -> annotation:
return {"name": "John", "age": 30}
tools = await mcp.list_tools()
type_schema = compress_schema(
TypeAdapter(annotation).json_schema(), prune_titles=True
)
assert len(tools) == 1
actual_schema = _normalize_anyof_order(tools[0].output_schema)
expected_schema = _normalize_anyof_order(type_schema)
assert actual_schema == expected_schema
async def test_disabled_output_schema_no_structured_content(self):
mcp = FastMCP()
@mcp.tool(output_schema=None)
def f() -> int:
return 42
result = await mcp.call_tool("f", {})
assert isinstance(result.content, list)
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "42"
assert result.structured_content is None
async def test_manual_structured_content(self):
from typing import cast
from fastmcp.tools.function_tool import DecoratedTool
mcp = FastMCP()
@mcp.tool
def f() -> ToolResult:
return ToolResult(
content="Hello, world!", structured_content={"message": "Hello, world!"}
)
# In new decorator mode, check metadata instead of attributes
from fastmcp.utilities.types import NotSet
decorated = cast(DecoratedTool, f)
assert hasattr(f, "__fastmcp__")
assert decorated.__fastmcp__.output_schema is NotSet
result = await mcp.call_tool("f", {})
assert isinstance(result.content, list)
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "Hello, world!"
assert result.structured_content == {"message": "Hello, world!"}
async def test_output_schema_none(self):
"""Test that output_schema=None works correctly."""
mcp = FastMCP()
@mcp.tool(output_schema=None)
def simple_tool() -> int:
return 42
tools = await mcp.list_tools()
tool = next(t for t in tools if t.name == "simple_tool")
assert tool.output_schema is None
result = await mcp.call_tool("simple_tool", {})
assert result.structured_content is None
assert isinstance(result.content, list)
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "42"
async def test_output_schema_explicit_object(self):
"""Test explicit object output schema."""
mcp = FastMCP()
@mcp.tool(
output_schema={
"type": "object",
"properties": {
"greeting": {"type": "string"},
"count": {"type": "integer"},
},
"required": ["greeting"],
}
)
def explicit_tool() -> dict[str, Any]:
return {"greeting": "Hello", "count": 42}
tools = await mcp.list_tools()
tool = next(t for t in tools if t.name == "explicit_tool")
expected_schema = {
"type": "object",
"properties": {
"greeting": {"type": "string"},
"count": {"type": "integer"},
},
"required": ["greeting"],
}
assert tool.output_schema == expected_schema
result = await mcp.call_tool("explicit_tool", {})
assert result.structured_content == {"greeting": "Hello", "count": 42}
async def test_output_schema_wrapped_primitive(self):
"""Test wrapped primitive output schema."""
mcp = FastMCP()
@mcp.tool
def primitive_tool() -> str:
return "Hello, primitives!"
tools = await mcp.list_tools()
tool = next(t for t in tools if t.name == "primitive_tool")
expected_schema = {
"type": "object",
"properties": {"result": {"type": "string"}},
"required": ["result"],
"x-fastmcp-wrap-result": True,
}
assert tool.output_schema == expected_schema
result = await mcp.call_tool("primitive_tool", {})
assert result.structured_content == {"result": "Hello, primitives!"}
async def test_output_schema_complex_type(self):
"""Test complex type output schema."""
mcp = FastMCP()
@mcp.tool
def complex_tool() -> list[dict[str, int]]:
return [{"a": 1, "b": 2}, {"c": 3, "d": 4}]
tools = await mcp.list_tools()
tool = next(t for t in tools if t.name == "complex_tool")
expected_inner_schema = compress_schema(
TypeAdapter(list[dict[str, int]]).json_schema(), prune_titles=True
)
expected_schema = {
"type": "object",
"properties": {"result": expected_inner_schema},
"required": ["result"],
"x-fastmcp-wrap-result": True,
}
assert tool.output_schema == expected_schema
result = await mcp.call_tool("complex_tool", {})
expected_data = [{"a": 1, "b": 2}, {"c": 3, "d": 4}]
assert result.structured_content == {"result": expected_data}
async def test_output_schema_dataclass(self):
"""Test dataclass output schema."""
mcp = FastMCP()
@dataclass
class User:
name: str
age: int
@mcp.tool
def dataclass_tool() -> User:
return User(name="Alice", age=30)
tools = await mcp.list_tools()
tool = next(t for t in tools if t.name == "dataclass_tool")
expected_schema = compress_schema(
TypeAdapter(User).json_schema(), prune_titles=True
)
assert tool.output_schema == expected_schema
assert tool.output_schema and "x-fastmcp-wrap-result" not in tool.output_schema
result = await mcp.call_tool("dataclass_tool", {})
assert result.structured_content == {"name": "Alice", "age": 30}
async def test_output_schema_mixed_content_types(self):
"""Test tools with mixed content and output schemas."""
mcp = FastMCP()
@mcp.tool
def mixed_output() -> list[Any]:
return [
"text message",
{"structured": "data"},
TextContent(type="text", text="direct MCP content"),
]
result = await mcp.call_tool("mixed_output", {})
assert isinstance(result.content, list)
assert len(result.content) == 3
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "text message"
assert isinstance(result.content[1], TextContent)
assert result.content[1].text == '{"structured":"data"}'
assert isinstance(result.content[2], TextContent)
assert result.content[2].text == "direct MCP content"
async def test_output_schema_serialization_edge_cases(self):
"""Test edge cases in output schema serialization."""
mcp = FastMCP()
@mcp.tool
def edge_case_tool() -> tuple[int, str]:
return (42, "hello")
tools = await mcp.list_tools()
tool = next(t for t in tools if t.name == "edge_case_tool")
assert tool.output_schema and "x-fastmcp-wrap-result" in tool.output_schema
result = await mcp.call_tool("edge_case_tool", {})
assert result.structured_content == {"result": [42, "hello"]}
async def test_output_schema_wraps_non_object_ref_schema(self):
"""Root $ref schemas should only skip wrapping when they resolve to objects."""
mcp = FastMCP()
AliasType = TypeAliasType("AliasType", Literal["foo", "bar"])
@mcp.tool
def alias_tool() -> AliasType:
return "foo"
tools = await mcp.list_tools()
tool = next(t for t in tools if t.name == "alias_tool")
expected_inner_schema = compress_schema(
TypeAdapter(AliasType).json_schema(mode="serialization"),
prune_titles=True,
)
assert tool.output_schema == {
"type": "object",
"properties": {"result": expected_inner_schema},
"required": ["result"],
"x-fastmcp-wrap-result": True,
}
result = await mcp.call_tool("alias_tool", {})
assert result.structured_content == {"result": "foo"}
class TestIsObjectSchemaRefResolution:
"""Tests for $ref resolution in _is_object_schema, including JSON Pointer
escaping and nested $defs paths."""
def test_simple_ref_to_object(self):
schema = {
"$ref": "#/$defs/MyModel",
"$defs": {
"MyModel": {"type": "object", "properties": {"x": {"type": "int"}}}
},
}
assert _is_object_schema(schema) is True
def test_simple_ref_to_non_object(self):
schema = {
"$ref": "#/$defs/MyEnum",
"$defs": {"MyEnum": {"enum": ["a", "b"]}},
}
assert _is_object_schema(schema) is False
def test_nested_defs_path(self):
"""Refs like #/$defs/Outer/$defs/Inner should walk into nested dicts."""
schema = {
"$ref": "#/$defs/Outer/$defs/Inner",
"$defs": {
"Outer": {
"$defs": {
"Inner": {
"type": "object",
"properties": {"y": {"type": "string"}},
},
},
},
},
}
assert _is_object_schema(schema) is True
def test_nested_defs_non_object(self):
schema = {
"$ref": "#/$defs/Outer/$defs/Inner",
"$defs": {
"Outer": {
"$defs": {
"Inner": {"type": "string"},
},
},
},
}
assert _is_object_schema(schema) is False
def test_json_pointer_tilde_escape(self):
"""~0 should unescape to ~ and ~1 should unescape to /."""
schema = {
"$ref": "#/$defs/has~1slash~0tilde",
"$defs": {"has/slash~tilde": {"type": "object", "properties": {}}},
}
assert _is_object_schema(schema) is True
def test_missing_nested_segment_returns_false(self):
schema = {
"$ref": "#/$defs/Outer/$defs/Missing",
"$defs": {
"Outer": {
"$defs": {},
},
},
}
assert _is_object_schema(schema) is False
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/providers/local_provider_tools/test_output_schema.py",
"license": "Apache License 2.0",
"lines": 308,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/providers/local_provider_tools/test_parameters.py | """Tests for tool parameters and validation."""
import base64
import datetime
import uuid
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import Annotated, Literal
import pytest
from mcp.types import (
ImageContent,
)
from pydantic import BaseModel, Field
from typing_extensions import TypedDict
from fastmcp import FastMCP
from fastmcp.utilities.types import Image
def _normalize_anyof_order(schema):
"""Normalize the order of items in anyOf arrays for consistent comparison."""
if isinstance(schema, dict):
if "anyOf" in schema:
schema = schema.copy()
schema["anyOf"] = sorted(schema["anyOf"], key=str)
return {k: _normalize_anyof_order(v) for k, v in schema.items()}
elif isinstance(schema, list):
return [_normalize_anyof_order(item) for item in schema]
return schema
class PersonTypedDict(TypedDict):
name: str
age: int
class PersonModel(BaseModel):
name: str
age: int
@dataclass
class PersonDataclass:
name: str
age: int
class TestToolParameters:
async def test_parameter_descriptions_with_field_annotations(self):
mcp = FastMCP("Test Server")
@mcp.tool
def greet(
name: Annotated[str, Field(description="The name to greet")],
title: Annotated[str, Field(description="Optional title", default="")],
) -> str:
"""A greeting tool"""
return f"Hello {title} {name}"
tools = await mcp.list_tools()
assert len(tools) == 1
tool = tools[0]
properties = tool.parameters["properties"]
assert "name" in properties
assert properties["name"]["description"] == "The name to greet"
assert "title" in properties
assert properties["title"]["description"] == "Optional title"
assert properties["title"]["default"] == ""
assert tool.parameters["required"] == ["name"]
async def test_parameter_descriptions_with_field_defaults(self):
mcp = FastMCP("Test Server")
@mcp.tool
def greet(
name: str = Field(description="The name to greet"),
title: str = Field(description="Optional title", default=""),
) -> str:
"""A greeting tool"""
return f"Hello {title} {name}"
tools = await mcp.list_tools()
assert len(tools) == 1
tool = tools[0]
properties = tool.parameters["properties"]
assert "name" in properties
assert properties["name"]["description"] == "The name to greet"
assert "title" in properties
assert properties["title"]["description"] == "Optional title"
assert properties["title"]["default"] == ""
assert tool.parameters["required"] == ["name"]
async def test_tool_with_bytes_input(self):
mcp = FastMCP()
@mcp.tool
def process_image(image: bytes) -> Image:
return Image(data=image)
result = await mcp.call_tool("process_image", {"image": b"fake png data"})
assert result.structured_content is None
assert isinstance(result.content, list)
assert isinstance(result.content[0], ImageContent)
assert result.content[0].mimeType == "image/png"
assert result.content[0].data == base64.b64encode(b"fake png data").decode()
async def test_tool_with_invalid_input(self):
from pydantic import ValidationError
mcp = FastMCP()
@mcp.tool
def my_tool(x: int) -> int:
return x + 1
with pytest.raises(
ValidationError,
match="Input should be a valid integer",
):
await mcp.call_tool("my_tool", {"x": "not an int"})
async def test_tool_int_coercion(self):
"""Test that string ints are coerced by default."""
mcp = FastMCP()
@mcp.tool
def add_one(x: int) -> int:
return x + 1
result = await mcp.call_tool("add_one", {"x": "42"})
assert result.structured_content == {"result": 43}
async def test_tool_bool_coercion(self):
"""Test that string bools are coerced by default."""
mcp = FastMCP()
@mcp.tool
def toggle(flag: bool) -> bool:
return not flag
result = await mcp.call_tool("toggle", {"flag": "true"})
assert result.structured_content == {"result": False}
result = await mcp.call_tool("toggle", {"flag": "false"})
assert result.structured_content == {"result": True}
async def test_annotated_field_validation(self):
from pydantic import ValidationError
mcp = FastMCP()
@mcp.tool
def analyze(x: Annotated[int, Field(ge=1)]) -> None:
pass
with pytest.raises(
ValidationError,
match="Input should be greater than or equal to 1",
):
await mcp.call_tool("analyze", {"x": 0})
async def test_default_field_validation(self):
from pydantic import ValidationError
mcp = FastMCP()
@mcp.tool
def analyze(x: int = Field(ge=1)) -> None:
pass
with pytest.raises(
ValidationError,
match="Input should be greater than or equal to 1",
):
await mcp.call_tool("analyze", {"x": 0})
async def test_default_field_is_still_required_if_no_default_specified(self):
from pydantic import ValidationError
mcp = FastMCP()
@mcp.tool
def analyze(x: int = Field()) -> None:
pass
with pytest.raises(ValidationError, match="missing"):
await mcp.call_tool("analyze", {})
async def test_literal_type_validation_error(self):
from pydantic import ValidationError
mcp = FastMCP()
@mcp.tool
def analyze(x: Literal["a", "b"]) -> None:
pass
with pytest.raises(
ValidationError,
match="Input should be 'a' or 'b'",
):
await mcp.call_tool("analyze", {"x": "c"})
async def test_literal_type_validation_success(self):
mcp = FastMCP()
@mcp.tool
def analyze(x: Literal["a", "b"]) -> str:
return x
result = await mcp.call_tool("analyze", {"x": "a"})
assert result.structured_content == {"result": "a"}
async def test_enum_type_validation_error(self):
from pydantic import ValidationError
mcp = FastMCP()
class MyEnum(Enum):
RED = "red"
GREEN = "green"
BLUE = "blue"
@mcp.tool
def analyze(x: MyEnum) -> str:
return x.value
with pytest.raises(
ValidationError,
match="Input should be 'red', 'green' or 'blue'",
):
await mcp.call_tool("analyze", {"x": "some-color"})
async def test_enum_type_validation_success(self):
mcp = FastMCP()
class MyEnum(Enum):
RED = "red"
GREEN = "green"
BLUE = "blue"
@mcp.tool
def analyze(x: MyEnum) -> str:
return x.value
result = await mcp.call_tool("analyze", {"x": "red"})
assert result.structured_content == {"result": "red"}
async def test_union_type_validation(self):
from pydantic import ValidationError
mcp = FastMCP()
@mcp.tool
def analyze(x: int | float) -> str:
return str(x)
result = await mcp.call_tool("analyze", {"x": 1})
assert result.structured_content == {"result": "1"}
result = await mcp.call_tool("analyze", {"x": 1.0})
assert result.structured_content == {"result": "1.0"}
with pytest.raises(
ValidationError,
match="Input should be a valid",
):
await mcp.call_tool("analyze", {"x": "not a number"})
async def test_path_type(self):
mcp = FastMCP()
@mcp.tool
def send_path(path: Path) -> str:
assert isinstance(path, Path)
return str(path)
test_path = Path("tmp") / "test.txt"
result = await mcp.call_tool("send_path", {"path": str(test_path)})
assert result.structured_content == {"result": str(test_path)}
async def test_path_type_error(self):
from pydantic import ValidationError
mcp = FastMCP()
@mcp.tool
def send_path(path: Path) -> str:
return str(path)
with pytest.raises(ValidationError, match="Input is not a valid path"):
await mcp.call_tool("send_path", {"path": 1})
async def test_uuid_type(self):
mcp = FastMCP()
@mcp.tool
def send_uuid(x: uuid.UUID) -> str:
assert isinstance(x, uuid.UUID)
return str(x)
test_uuid = uuid.uuid4()
result = await mcp.call_tool("send_uuid", {"x": test_uuid})
assert result.structured_content == {"result": str(test_uuid)}
async def test_uuid_type_error(self):
from pydantic import ValidationError
mcp = FastMCP()
@mcp.tool
def send_uuid(x: uuid.UUID) -> str:
return str(x)
with pytest.raises(ValidationError, match="Input should be a valid UUID"):
await mcp.call_tool("send_uuid", {"x": "not a uuid"})
async def test_datetime_type(self):
mcp = FastMCP()
@mcp.tool
def send_datetime(x: datetime.datetime) -> str:
return x.isoformat()
dt = datetime.datetime(2025, 4, 25, 1, 2, 3)
result = await mcp.call_tool("send_datetime", {"x": dt})
assert result.structured_content == {"result": dt.isoformat()}
async def test_datetime_type_parse_string(self):
mcp = FastMCP()
@mcp.tool
def send_datetime(x: datetime.datetime) -> str:
return x.isoformat()
result = await mcp.call_tool("send_datetime", {"x": "2021-01-01T00:00:00"})
assert result.structured_content == {"result": "2021-01-01T00:00:00"}
async def test_datetime_type_error(self):
from pydantic import ValidationError
mcp = FastMCP()
@mcp.tool
def send_datetime(x: datetime.datetime) -> str:
return x.isoformat()
with pytest.raises(ValidationError, match="Input should be a valid datetime"):
await mcp.call_tool("send_datetime", {"x": "not a datetime"})
async def test_date_type(self):
mcp = FastMCP()
@mcp.tool
def send_date(x: datetime.date) -> str:
return x.isoformat()
result = await mcp.call_tool("send_date", {"x": datetime.date.today()})
assert result.structured_content == {
"result": datetime.date.today().isoformat()
}
async def test_date_type_parse_string(self):
mcp = FastMCP()
@mcp.tool
def send_date(x: datetime.date) -> str:
return x.isoformat()
result = await mcp.call_tool("send_date", {"x": "2021-01-01"})
assert result.structured_content == {"result": "2021-01-01"}
async def test_timedelta_type(self):
mcp = FastMCP()
@mcp.tool
def send_timedelta(x: datetime.timedelta) -> str:
return str(x)
result = await mcp.call_tool(
"send_timedelta", {"x": datetime.timedelta(days=1)}
)
assert result.structured_content == {"result": "1 day, 0:00:00"}
async def test_timedelta_type_parse_int(self):
"""Test that int input is coerced to timedelta (seconds)."""
mcp = FastMCP()
@mcp.tool
def send_timedelta(x: datetime.timedelta) -> str:
return str(x)
result = await mcp.call_tool("send_timedelta", {"x": 1000})
assert result.structured_content is not None
result_str = result.structured_content["result"]
assert (
"0:16:40" in result_str or "16:40" in result_str
) # 1000 seconds = 16 minutes 40 seconds
async def test_annotated_string_description(self):
mcp = FastMCP()
@mcp.tool
def f(x: Annotated[int, "A number"]):
return x
tools = await mcp.list_tools()
assert len(tools) == 1
assert tools[0].parameters["properties"]["x"]["description"] == "A number"
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/providers/local_provider_tools/test_parameters.py",
"license": "Apache License 2.0",
"lines": 306,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/providers/local_provider_tools/test_tags.py | """Tests for tool tags."""
from dataclasses import dataclass
import pytest
from pydantic import BaseModel
from typing_extensions import TypedDict
from fastmcp import FastMCP
from fastmcp.exceptions import NotFoundError
def _normalize_anyof_order(schema):
"""Normalize the order of items in anyOf arrays for consistent comparison."""
if isinstance(schema, dict):
if "anyOf" in schema:
schema = schema.copy()
schema["anyOf"] = sorted(schema["anyOf"], key=str)
return {k: _normalize_anyof_order(v) for k, v in schema.items()}
elif isinstance(schema, list):
return [_normalize_anyof_order(item) for item in schema]
return schema
class PersonTypedDict(TypedDict):
name: str
age: int
class PersonModel(BaseModel):
name: str
age: int
@dataclass
class PersonDataclass:
name: str
age: int
class TestToolTags:
def create_server(self, include_tags=None, exclude_tags=None):
mcp = FastMCP()
@mcp.tool(tags={"a", "b"})
def tool_1() -> int:
return 1
@mcp.tool(tags={"b", "c"})
def tool_2() -> int:
return 2
if include_tags:
mcp.enable(tags=include_tags, only=True)
if exclude_tags:
mcp.disable(tags=exclude_tags)
return mcp
async def test_include_tags_all_tools(self):
mcp = self.create_server(include_tags={"a", "b"})
tools = await mcp.list_tools()
assert {t.name for t in tools} == {"tool_1", "tool_2"}
async def test_include_tags_some_tools(self):
mcp = self.create_server(include_tags={"a", "z"})
tools = await mcp.list_tools()
assert {t.name for t in tools} == {"tool_1"}
async def test_exclude_tags_all_tools(self):
mcp = self.create_server(exclude_tags={"a", "b"})
tools = await mcp.list_tools()
assert {t.name for t in tools} == set()
async def test_exclude_tags_some_tools(self):
mcp = self.create_server(exclude_tags={"a", "z"})
tools = await mcp.list_tools()
assert {t.name for t in tools} == {"tool_2"}
async def test_exclude_precedence(self):
mcp = self.create_server(exclude_tags={"a"}, include_tags={"b"})
tools = await mcp.list_tools()
assert {t.name for t in tools} == {"tool_2"}
async def test_call_included_tool(self):
mcp = self.create_server(include_tags={"a"})
result_1 = await mcp.call_tool("tool_1", {})
assert result_1.structured_content == {"result": 1}
with pytest.raises(NotFoundError, match="Unknown tool"):
await mcp.call_tool("tool_2", {})
async def test_call_excluded_tool(self):
mcp = self.create_server(exclude_tags={"a"})
with pytest.raises(NotFoundError, match="Unknown tool"):
await mcp.call_tool("tool_1", {})
result_2 = await mcp.call_tool("tool_2", {})
assert result_2.structured_content == {"result": 2}
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/providers/local_provider_tools/test_tags.py",
"license": "Apache License 2.0",
"lines": 73,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/versioning/test_calls.py | """Tests for versioned calls and client version selection."""
# ruff: noqa: F811 # Intentional function redefinition for version testing
from __future__ import annotations
from mcp.types import TextContent
from fastmcp import FastMCP
from fastmcp.utilities.versions import (
VersionSpec,
)
class TestVersionMixingValidation:
"""Tests for versioned/unversioned mixing prevention."""
async def test_resource_mixing_rejected(self):
"""Cannot mix versioned and unversioned resources with the same URI."""
import pytest
mcp = FastMCP()
@mcp.resource("file:///config", version="1.0")
def config_v1() -> str:
return "v1"
with pytest.raises(ValueError, match="unversioned.*versioned"):
@mcp.resource("file:///config")
def config_unversioned() -> str:
return "unversioned"
async def test_prompt_mixing_rejected(self):
"""Cannot mix versioned and unversioned prompts with the same name."""
import pytest
mcp = FastMCP()
@mcp.prompt
def greet(name: str) -> str:
return f"Hello, {name}!"
with pytest.raises(ValueError, match="versioned.*unversioned"):
@mcp.prompt(version="1.0")
def greet(name: str) -> str:
return f"Hi, {name}!"
async def test_multiple_versions_allowed(self):
"""Multiple versioned components with same name are allowed."""
mcp = FastMCP()
@mcp.tool(version="1.0")
def calc() -> int:
return 1
@mcp.tool(version="2.0")
def calc() -> int:
return 2
@mcp.tool(version="3.0")
def calc() -> int:
return 3
# All versioned - list_tools returns all
tools = await mcp.list_tools()
assert len(tools) == 3
versions = {t.version for t in tools}
assert versions == {"1.0", "2.0", "3.0"}
# get_tool returns highest
tool = await mcp.get_tool("calc")
assert tool is not None
assert tool.version == "3.0"
class TestVersionValidation:
"""Tests for version string validation."""
async def test_version_with_at_symbol_rejected(self):
"""Version strings containing '@' should be rejected."""
import pytest
from pydantic import ValidationError
mcp = FastMCP()
with pytest.raises(ValidationError, match="cannot contain '@'"):
@mcp.tool(version="1.0@beta")
def my_tool() -> str:
return "test"
class TestVersionMetadata:
"""Tests for version metadata exposure in list operations."""
async def test_tool_versions_in_meta(self):
"""Each version has its own version in metadata."""
mcp = FastMCP()
@mcp.tool(version="1.0")
def add(x: int, y: int) -> int: # noqa: F811
return x + y
@mcp.tool(version="2.0")
def add(x: int, y: int) -> int: # noqa: F811
return x + y
# list_tools returns all versions
tools = await mcp.list_tools()
assert len(tools) == 2
# Each version has its own version in metadata
by_version = {t.version: t for t in tools}
assert by_version["1.0"].get_meta()["fastmcp"]["version"] == "1.0"
assert by_version["2.0"].get_meta()["fastmcp"]["version"] == "2.0"
async def test_resource_versions_in_meta(self):
"""Each version has its own version in metadata."""
mcp = FastMCP()
@mcp.resource("data://config", version="1.0")
def config_v1() -> str: # noqa: F811
return "v1"
@mcp.resource("data://config", version="2.0")
def config_v2() -> str: # noqa: F811
return "v2"
# list_resources returns all versions
resources = await mcp.list_resources()
assert len(resources) == 2
# Each version has its own version in metadata
by_version = {r.version: r for r in resources}
assert by_version["1.0"].get_meta()["fastmcp"]["version"] == "1.0"
assert by_version["2.0"].get_meta()["fastmcp"]["version"] == "2.0"
async def test_prompt_versions_in_meta(self):
"""Each version has its own version in metadata."""
mcp = FastMCP()
@mcp.prompt(version="1.0")
def greet() -> str: # noqa: F811
return "Hello v1"
@mcp.prompt(version="2.0")
def greet() -> str: # noqa: F811
return "Hello v2"
# list_prompts returns all versions
prompts = await mcp.list_prompts()
assert len(prompts) == 2
# Each version has its own version in metadata
by_version = {p.version: p for p in prompts}
assert by_version["1.0"].get_meta()["fastmcp"]["version"] == "1.0"
assert by_version["2.0"].get_meta()["fastmcp"]["version"] == "2.0"
async def test_unversioned_no_versions_list(self):
"""Unversioned components should not have versions list in meta."""
mcp = FastMCP()
@mcp.tool
def simple() -> str:
return "simple"
tools = await mcp.list_tools()
assert len(tools) == 1
tool = tools[0]
meta = tool.get_meta()
assert "versions" not in meta.get("fastmcp", {})
class TestVersionedCalls:
"""Tests for calling specific component versions."""
async def test_call_tool_with_version(self):
"""call_tool should use specified version."""
mcp = FastMCP()
@mcp.tool(version="1.0")
def calculate(x: int, y: int) -> int: # noqa: F811
return x + y
@mcp.tool(version="2.0")
def calculate(x: int, y: int) -> int: # noqa: F811
return x * y
# Default: highest version (2.0, multiplication)
result = await mcp.call_tool("calculate", {"x": 3, "y": 4})
assert result.structured_content is not None
assert result.structured_content["result"] == 12
# Explicit v1.0 (addition)
result = await mcp.call_tool(
"calculate", {"x": 3, "y": 4}, version=VersionSpec(eq="1.0")
)
assert result.structured_content is not None
assert result.structured_content["result"] == 7
# Explicit v2.0 (multiplication)
result = await mcp.call_tool(
"calculate", {"x": 3, "y": 4}, version=VersionSpec(eq="2.0")
)
assert result.structured_content is not None
assert result.structured_content["result"] == 12
async def test_read_resource_with_version(self):
"""read_resource should use specified version."""
mcp = FastMCP()
@mcp.resource("data://config", version="1.0")
def config() -> str: # noqa: F811
return "config v1"
@mcp.resource("data://config", version="2.0")
def config() -> str: # noqa: F811
return "config v2"
# Default: highest version
result = await mcp.read_resource("data://config")
assert result.contents[0].content == "config v2"
# Explicit v1.0
result = await mcp.read_resource("data://config", version=VersionSpec(eq="1.0"))
assert result.contents[0].content == "config v1"
async def test_render_prompt_with_version(self):
"""render_prompt should use specified version."""
mcp = FastMCP()
@mcp.prompt(version="1.0")
def greet() -> str: # noqa: F811
return "Hello from v1"
@mcp.prompt(version="2.0")
def greet() -> str: # noqa: F811
return "Hello from v2"
# Default: highest version
result = await mcp.render_prompt("greet")
content = result.messages[0].content
assert isinstance(content, TextContent) and content.text == "Hello from v2"
# Explicit v1.0
result = await mcp.render_prompt("greet", version=VersionSpec(eq="1.0"))
content = result.messages[0].content
assert isinstance(content, TextContent) and content.text == "Hello from v1"
async def test_call_tool_invalid_version_not_found(self):
"""Calling with non-existent version should raise NotFoundError."""
import pytest
from fastmcp.exceptions import NotFoundError
mcp = FastMCP()
@mcp.tool(version="1.0")
def mytool() -> str:
return "v1"
with pytest.raises(NotFoundError):
await mcp.call_tool("mytool", {}, version=VersionSpec(eq="999.0"))
class TestClientVersionSelection:
"""Tests for client-side version selection via the version parameter.
Version selection flows through request-level _meta, not arguments.
"""
import pytest
@pytest.mark.parametrize(
"version,expected",
[
(None, 10), # Default: highest version (2.0) -> 5 * 2
("1.0", 6), # v1.0 -> 5 + 1
("2.0", 10), # v2.0 -> 5 * 2
],
)
async def test_call_tool_version_selection(
self, version: str | None, expected: int
):
"""Client.call_tool routes to correct version via request meta."""
from fastmcp import Client
mcp = FastMCP()
@mcp.tool(version="1.0")
def calc(x: int) -> int: # noqa: F811
return x + 1
@mcp.tool(version="2.0")
def calc(x: int) -> int: # noqa: F811
return x * 2
async with Client(mcp) as client:
result = await client.call_tool("calc", {"x": 5}, version=version)
assert result.data == expected
@pytest.mark.parametrize(
"version,expected",
[
(None, "Hello world from v2"), # Default: highest version
("1.0", "Hello world from v1"),
("2.0", "Hello world from v2"),
],
)
async def test_get_prompt_version_selection(
self, version: str | None, expected: str
):
"""Client.get_prompt routes to correct version via request meta."""
from fastmcp import Client
mcp = FastMCP()
@mcp.prompt(version="1.0")
def greet(name: str) -> str: # noqa: F811
return f"Hello {name} from v1"
@mcp.prompt(version="2.0")
def greet(name: str) -> str: # noqa: F811
return f"Hello {name} from v2"
async with Client(mcp) as client:
result = await client.get_prompt(
"greet", {"name": "world"}, version=version
)
content = result.messages[0].content
assert isinstance(content, TextContent) and content.text == expected
@pytest.mark.parametrize(
"version,expected",
[
(None, "v2 data"), # Default: highest version
("1.0", "v1 data"),
("2.0", "v2 data"),
],
)
async def test_read_resource_version_selection(
self, version: str | None, expected: str
):
"""Client.read_resource routes to correct version via request meta."""
from fastmcp import Client
mcp = FastMCP()
@mcp.resource("data://info", version="1.0")
def info_v1() -> str: # noqa: F811
return "v1 data"
@mcp.resource("data://info", version="2.0")
def info_v2() -> str: # noqa: F811
return "v2 data"
async with Client(mcp) as client:
result = await client.read_resource("data://info", version=version)
assert result[0].text == expected
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/versioning/test_calls.py",
"license": "Apache License 2.0",
"lines": 271,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/versioning/test_filtering.py | """Tests for version filtering functionality."""
# ruff: noqa: F811 # Intentional function redefinition for version testing
from __future__ import annotations
from fastmcp import FastMCP
from fastmcp.server.transforms import VersionFilter
from fastmcp.utilities.versions import (
VersionSpec,
)
class TestVersionFilter:
"""Tests for VersionFilter transform."""
async def test_version_lt_filters_high_versions(self):
"""VersionFilter(version_lt='3.0') hides v3+, shows v1 and v2."""
from fastmcp.server.transforms import VersionFilter
mcp = FastMCP()
@mcp.tool(version="1.0")
def calc() -> int:
return 1
@mcp.tool(version="2.0")
def calc() -> int:
return 2
@mcp.tool(version="3.0")
def calc() -> int:
return 3
# Without filter, list_tools returns all versions
tools = await mcp.list_tools()
versions = {t.version for t in tools}
assert versions == {"1.0", "2.0", "3.0"}
# With filter, only v1 and v2 are visible
mcp.add_transform(VersionFilter(version_lt="3.0"))
tools = await mcp.list_tools()
versions = {t.version for t in tools}
assert versions == {"1.0", "2.0"}
# get_tool returns highest matching version
tool = await mcp.get_tool("calc")
assert tool is not None
assert tool.version == "2.0"
async def test_version_gte_filters_low_versions(self):
"""VersionFilter(version_gte='2.0') hides v1, shows v2 and v3."""
from fastmcp.server.transforms import VersionFilter
mcp = FastMCP()
@mcp.tool(version="1.0")
def add(x: int) -> int:
return x + 1
@mcp.tool(version="2.0")
def add(x: int) -> int:
return x + 2
@mcp.tool(version="3.0")
def add(x: int) -> int:
return x + 3
mcp.add_transform(VersionFilter(version_gte="2.0"))
# list_tools shows all matching versions (v2 and v3)
tools = await mcp.list_tools()
versions = {t.version for t in tools}
assert versions == {"2.0", "3.0"}
# get_tool returns highest matching version
tool = await mcp.get_tool("add")
assert tool is not None
assert tool.version == "3.0"
# Can request specific versions in range
tool_v2 = await mcp.get_tool("add", VersionSpec(eq="2.0"))
assert tool_v2 is not None
assert tool_v2.version == "2.0"
# Cannot request version outside range - returns None
assert await mcp.get_tool("add", VersionSpec(eq="1.0")) is None
async def test_version_range(self):
"""VersionFilter(version_gte='2.0', version_lt='3.0') shows only v2.x."""
from fastmcp.server.transforms import VersionFilter
mcp = FastMCP()
@mcp.tool(version="1.0")
def calc() -> int:
return 1
@mcp.tool(version="2.0")
def calc() -> int:
return 2
@mcp.tool(version="2.5")
def calc() -> int:
return 25
@mcp.tool(version="3.0")
def calc() -> int:
return 3
mcp.add_transform(VersionFilter(version_gte="2.0", version_lt="3.0"))
# list_tools shows all versions in range
tools = await mcp.list_tools()
versions = {t.version for t in tools}
assert versions == {"2.0", "2.5"}
# get_tool returns highest in range
tool = await mcp.get_tool("calc")
assert tool is not None
assert tool.version == "2.5"
# Can request specific versions in range
tool_v2 = await mcp.get_tool("calc", VersionSpec(eq="2.0"))
assert tool_v2 is not None
assert tool_v2.version == "2.0"
# Versions outside range are not accessible - return None
assert await mcp.get_tool("calc", VersionSpec(eq="1.0")) is None
assert await mcp.get_tool("calc", VersionSpec(eq="3.0")) is None
async def test_unversioned_always_passes(self):
"""Unversioned components pass through any filter."""
from fastmcp.server.transforms import VersionFilter
mcp = FastMCP()
@mcp.tool
def unversioned_tool() -> str:
return "unversioned"
@mcp.tool(version="5.0")
def versioned_tool() -> str:
return "v5"
# Filter that would exclude v5.0
mcp.add_transform(VersionFilter(version_lt="3.0"))
tools = await mcp.list_tools()
names = [t.name for t in tools]
assert "unversioned_tool" in names
assert "versioned_tool" not in names
async def test_include_unversioned_false_excludes_unversioned_tools(self):
"""Setting include_unversioned=False hides unversioned tools."""
mcp = FastMCP()
@mcp.tool
def unversioned_tool() -> str:
return "unversioned"
@mcp.tool(version="2.0")
def included_versioned_tool() -> str:
return "v2"
@mcp.tool(version="5.0")
def excluded_versioned_tool() -> str:
return "v5"
mcp.add_transform(VersionFilter(version_lt="3.0", include_unversioned=False))
tools = await mcp.list_tools()
assert [tool.name for tool in tools] == ["included_versioned_tool"]
async def test_date_versions(self):
"""Works with date-based versions like '2025-01-15'."""
from fastmcp.server.transforms import VersionFilter
mcp = FastMCP()
@mcp.tool(version="2025-01-01")
def report() -> str:
return "jan"
@mcp.tool(version="2025-06-01")
def report() -> str:
return "jun"
@mcp.tool(version="2025-12-01")
def report() -> str:
return "dec"
# Q1 API: before April
mcp.add_transform(VersionFilter(version_lt="2025-04-01"))
tools = await mcp.list_tools()
assert len(tools) == 1
assert tools[0].version == "2025-01-01"
async def test_get_tool_respects_filter(self):
"""get_tool() returns None if highest version is filtered out."""
from fastmcp.server.transforms import VersionFilter
mcp = FastMCP()
@mcp.tool(version="5.0")
def only_v5() -> str:
return "v5"
mcp.add_transform(VersionFilter(version_lt="3.0"))
# Tool exists but is filtered out - returns None (use get_tool to apply transforms)
assert await mcp.get_tool("only_v5") is None
async def test_must_specify_at_least_one(self):
"""VersionFilter() with no args raises ValueError."""
import pytest
from fastmcp.server.transforms import VersionFilter
with pytest.raises(ValueError, match="At least one of"):
VersionFilter()
async def test_resources_filtered(self):
"""Resources are filtered by version."""
from fastmcp.server.transforms import VersionFilter
mcp = FastMCP()
@mcp.resource("file:///config", version="1.0")
def config_v1() -> str:
return "v1"
@mcp.resource("file:///config", version="2.0")
def config_v2() -> str:
return "v2"
mcp.add_transform(VersionFilter(version_lt="2.0"))
resources = await mcp.list_resources()
assert len(resources) == 1
assert resources[0].version == "1.0"
async def test_include_unversioned_false_excludes_unversioned_resources(self):
"""Setting include_unversioned=False hides unversioned resources."""
mcp = FastMCP()
@mcp.resource("file:///unversioned")
def unversioned_resource() -> str:
return "unversioned"
@mcp.resource("file:///included_versioned", version="1.0")
def included_versioned_resource() -> str:
return "v1"
@mcp.resource("file:///excluded_versioned", version="5.0")
def excluded_versioned_resource() -> str:
return "v5"
mcp.add_transform(VersionFilter(version_lt="2.0", include_unversioned=False))
resources = await mcp.list_resources()
assert [str(resource.uri) for resource in resources] == [
"file:///included_versioned"
]
async def test_include_unversioned_false_excludes_unversioned_resource_templates(
self,
):
"""Setting include_unversioned=False hides unversioned resource templates."""
mcp = FastMCP()
@mcp.resource("resource://unversioned/{name}")
def unversioned_template(name: str) -> str:
return f"unversioned:{name}"
@mcp.resource("resource://included_versioned/{name}", version="1.0")
def included_versioned_template(name: str) -> str:
return f"versioned:{name}"
@mcp.resource("resource://excluded_versioned/{name}", version="5.0")
def excluded_versioned_template(name: str) -> str:
return f"excluded:{name}"
mcp.add_transform(VersionFilter(version_lt="2.0", include_unversioned=False))
templates = await mcp.list_resource_templates()
assert [template.uri_template for template in templates] == [
"resource://included_versioned/{name}"
]
async def test_prompts_filtered(self):
"""Prompts are filtered by version."""
from fastmcp.server.transforms import VersionFilter
mcp = FastMCP()
@mcp.prompt(version="1.0")
def greet(name: str) -> str:
return f"Hi {name}"
@mcp.prompt(version="2.0")
def greet(name: str) -> str:
return f"Hello {name}"
mcp.add_transform(VersionFilter(version_lt="2.0"))
prompts = await mcp.list_prompts()
assert len(prompts) == 1
assert prompts[0].version == "1.0"
async def test_include_unversioned_false_excludes_unversioned_prompts(self):
"""Setting include_unversioned=False hides unversioned prompts."""
mcp = FastMCP()
@mcp.prompt
def unversioned_prompt(name: str) -> str:
return f"Unversioned: {name}"
@mcp.prompt(version="1.0")
def included_versioned_prompt(name: str) -> str:
return f"Versioned: {name}"
@mcp.prompt(version="5.0")
def excluded_versioned_prompt(name: str) -> str:
return f"Excluded: {name}"
mcp.add_transform(VersionFilter(version_lt="2.0", include_unversioned=False))
prompts = await mcp.list_prompts()
assert [prompt.name for prompt in prompts] == ["included_versioned_prompt"]
async def test_repr(self):
"""Test VersionFilter string representation."""
from fastmcp.server.transforms import VersionFilter
f1 = VersionFilter(version_lt="3.0")
assert repr(f1) == "VersionFilter(version_lt='3.0')"
f2 = VersionFilter(version_gte="2.0", version_lt="3.0")
assert repr(f2) == "VersionFilter(version_gte='2.0', version_lt='3.0')"
f3 = VersionFilter(version_gte="1.0")
assert repr(f3) == "VersionFilter(version_gte='1.0')"
f4 = VersionFilter(version_lt="3.0", include_unversioned=False)
assert repr(f4) == "VersionFilter(version_lt='3.0', include_unversioned=False)"
class TestMountedVersionFiltering:
"""Tests for version filtering with mounted servers (FastMCPProvider).
Note: For mounted servers, list_* methods show what the child exposes (already
deduplicated to highest version). get_* methods support range filtering via
VersionSpec propagation to FastMCPProvider.
"""
async def test_mounted_get_tool_with_range_filter(self):
"""FastMCPProvider.get_tool applies range filtering from VersionSpec."""
from fastmcp.server.providers.fastmcp_provider import FastMCPProvider
from fastmcp.utilities.versions import VersionSpec
child = FastMCP("Child")
@child.tool(version="2.0")
def calc() -> int:
return 2
provider = FastMCPProvider(child)
# Without range spec, should return the tool
tool = await provider.get_tool("calc")
assert tool is not None
assert tool.version == "2.0"
# With range spec that excludes v2.0, should return None
tool = await provider.get_tool("calc", version=VersionSpec(lt="2.0"))
assert tool is None
# With range spec that includes v2.0, should return the tool
tool = await provider.get_tool("calc", version=VersionSpec(gte="2.0"))
assert tool is not None
assert tool.version == "2.0"
async def test_mounted_get_resource_with_range_filter(self):
"""FastMCPProvider.get_resource applies range filtering from VersionSpec."""
from fastmcp.server.providers.fastmcp_provider import FastMCPProvider
from fastmcp.utilities.versions import VersionSpec
child = FastMCP("Child")
@child.resource("file://data/", version="2.0")
def data() -> str:
return "data"
provider = FastMCPProvider(child)
# Without range spec, should return the resource
resource = await provider.get_resource("file://data/")
assert resource is not None
assert resource.version == "2.0"
# With range spec that excludes v2.0, should return None
resource = await provider.get_resource(
"file://data/", version=VersionSpec(lt="2.0")
)
assert resource is None
async def test_mounted_get_prompt_with_range_filter(self):
"""FastMCPProvider.get_prompt applies range filtering from VersionSpec."""
from fastmcp.server.providers.fastmcp_provider import FastMCPProvider
from fastmcp.utilities.versions import VersionSpec
child = FastMCP("Child")
@child.prompt(version="2.0")
def greet(name: str) -> str:
return f"Hello {name}"
provider = FastMCPProvider(child)
# Without range spec, should return the prompt
prompt = await provider.get_prompt("greet")
assert prompt is not None
assert prompt.version == "2.0"
# With range spec that excludes v2.0, should return None
prompt = await provider.get_prompt("greet", version=VersionSpec(lt="2.0"))
assert prompt is None
async def test_mounted_unversioned_passes_version_filter(self):
"""Unversioned components in mounted servers pass through version filters."""
from fastmcp.server.transforms import VersionFilter
child = FastMCP("Child")
@child.tool
def unversioned_tool() -> str:
return "unversioned"
parent = FastMCP("Parent")
parent.mount(child, "child")
parent.add_transform(VersionFilter(version_lt="3.0"))
# Unversioned should pass through
tools = await parent.list_tools()
assert len(tools) == 1
assert tools[0].name == "child_unversioned_tool"
assert tools[0].version is None
async def test_mounted_include_unversioned_false_excludes_unversioned_tools(self):
"""Mounted unversioned tools can be excluded with include_unversioned=False."""
child = FastMCP("Child")
@child.tool
def unversioned_tool() -> str:
return "unversioned"
@child.tool(version="2.0")
def included_versioned_tool() -> str:
return "versioned"
@child.tool(version="0.5")
def excluded_versioned_tool() -> str:
return "excluded-versioned"
parent = FastMCP("Parent")
parent.mount(child, "child")
parent.add_transform(
VersionFilter(version_gte="1.0", include_unversioned=False)
)
tools = await parent.list_tools()
assert [tool.name for tool in tools] == ["child_included_versioned_tool"]
async def test_version_filter_filters_out_high_mounted_version(self):
"""VersionFilter hides mounted components outside the range."""
from fastmcp.server.transforms import VersionFilter
child = FastMCP("Child")
@child.tool(version="5.0")
def high_version_tool() -> int:
return 5
parent = FastMCP("Parent")
parent.mount(child, "child")
parent.add_transform(VersionFilter(version_lt="3.0"))
# v5.0 is outside the filter range, so it should be hidden
tools = await parent.list_tools()
assert len(tools) == 0
# get_tool should also return None (respects filter, applies transforms)
assert await parent.get_tool("child_high_version_tool") is None
class TestMountedRangeFiltering:
"""Tests for version range filtering with mounted servers."""
async def test_mounted_lower_version_selected_by_filter(self):
"""When parent has filter <2.0 and child has v1.0+v3.0, should get v1.0."""
from fastmcp.server.transforms import VersionFilter
child = FastMCP("Child")
@child.tool(version="1.0")
def calc() -> int:
return 1
@child.tool(version="3.0")
def calc() -> int:
return 3
parent = FastMCP("Parent")
parent.mount(child, "child")
parent.add_transform(VersionFilter(version_lt="2.0"))
# Should return v1.0 (the highest version that matches <2.0)
# Use get_tool to apply transforms
tool = await parent.get_tool("child_calc")
assert tool is not None
assert tool.version == "1.0"
async def test_explicit_version_honored_within_filter_range(self):
"""Explicit version="1.0" request should work within filter range."""
from fastmcp.server.transforms import VersionFilter
child = FastMCP("Child")
@child.tool(version="1.0")
def calc() -> int:
return 1
@child.tool(version="2.0")
def calc() -> int:
return 2
@child.tool(version="3.0")
def calc() -> int:
return 3
parent = FastMCP("Parent")
parent.mount(child, "child")
parent.add_transform(VersionFilter(version_gte="1.0", version_lt="3.0"))
# Request specific version within range (use get_tool to apply transforms)
tool = await parent.get_tool("child_calc", VersionSpec(eq="1.0"))
assert tool is not None
assert tool.version == "1.0"
# Request version outside range should return None
result = await parent.get_tool("child_calc", VersionSpec(eq="3.0"))
assert result is None
class TestUnversionedExemption:
"""Tests confirming unversioned components bypass version filters."""
async def test_unversioned_bypasses_version_filter(self):
"""Unversioned components pass through any VersionFilter - by design."""
from fastmcp.server.transforms import VersionFilter
mcp = FastMCP()
@mcp.tool
def unversioned_tool() -> str:
return "unversioned"
@mcp.tool(version="5.0")
def versioned_tool() -> str:
return "v5"
# Filter that would exclude v5.0
mcp.add_transform(VersionFilter(version_lt="3.0"))
tools = await mcp.list_tools()
names = [t.name for t in tools]
# Unversioned passes through (exempt from filtering)
assert "unversioned_tool" in names
# Versioned is filtered out
assert "versioned_tool" not in names
async def test_unversioned_returned_for_exact_version_request(self):
"""Requesting exact version of unversioned tool returns the tool."""
mcp = FastMCP()
@mcp.tool
def my_tool() -> str:
return "unversioned"
# Even with explicit version request, unversioned tool is returned
# (it's the only version that exists, and unversioned matches any spec)
tool = await mcp.get_tool("my_tool", VersionSpec(eq="1.0"))
assert tool is not None
assert tool.version is None
async def test_unversioned_matches_any_version_spec(self):
"""VersionSpec.matches(None) returns True for any spec."""
from fastmcp.utilities.versions import VersionSpec
# Unversioned matches exact version specs
assert VersionSpec(eq="1.0").matches(None) is True
# Unversioned matches range specs
assert VersionSpec(gte="1.0", lt="3.0").matches(None) is True
# Unversioned matches open specs
assert VersionSpec(lt="5.0").matches(None) is True
assert VersionSpec(gte="1.0").matches(None) is True
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/versioning/test_filtering.py",
"license": "Apache License 2.0",
"lines": 444,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/versioning/test_mounting.py | """Tests for versioning in mounted servers."""
# ruff: noqa: F811 # Intentional function redefinition for version testing
from __future__ import annotations
from mcp.types import TextContent
from fastmcp import FastMCP
from fastmcp.utilities.versions import (
VersionSpec,
)
class TestVersionSorting:
"""Tests for version sorting behavior."""
async def test_semantic_version_sorting(self):
"""Versions should sort semantically, not lexicographically."""
mcp = FastMCP()
# Add versions out of order
@mcp.tool(version="1")
def count() -> int:
return 1
@mcp.tool(version="10")
def count() -> int:
return 10
@mcp.tool(version="2")
def count() -> int:
return 2
# list_tools returns all versions
tools = await mcp.list_tools()
assert len(tools) == 3
versions = {t.version for t in tools}
assert versions == {"1", "2", "10"}
# get_tool returns highest (semantic: 10 > 2 > 1)
tool = await mcp.get_tool("count")
assert tool is not None
assert tool.version == "10"
# call_tool uses highest version
result = await mcp.call_tool("count", {})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "10"
async def test_semver_sorting(self):
"""Full semver versions should sort correctly."""
mcp = FastMCP()
@mcp.tool(version="1.2.3")
def info() -> str:
return "1.2.3"
@mcp.tool(version="1.2.10")
def info() -> str:
return "1.2.10"
@mcp.tool(version="1.10.1")
def info() -> str:
return "1.10.1"
# list_tools returns all versions
tools = await mcp.list_tools()
assert len(tools) == 3
versions = {t.version for t in tools}
assert versions == {"1.2.3", "1.2.10", "1.10.1"}
# get_tool returns highest: 1.10.1 > 1.2.10 > 1.2.3 (semantic)
tool = await mcp.get_tool("info")
assert tool is not None
assert tool.version == "1.10.1"
async def test_v_prefix_normalized(self):
"""Versions with 'v' prefix should compare correctly."""
mcp = FastMCP()
@mcp.tool(version="v1.0")
def calc() -> int:
return 1
@mcp.tool(version="v2.0")
def calc() -> int:
return 2
# list_tools returns all versions
tools = await mcp.list_tools()
assert len(tools) == 2
versions = {t.version for t in tools}
assert versions == {"v1.0", "v2.0"}
# get_tool returns highest
tool = await mcp.get_tool("calc")
assert tool is not None
assert tool.version == "v2.0"
class TestMountedServerVersioning:
"""Tests for versioning in mounted servers (FastMCPProvider)."""
async def test_mounted_tool_preserves_version(self):
"""Mounted tools should preserve their version info."""
child = FastMCP("Child")
@child.tool(version="2.0")
def add(x: int, y: int) -> int:
return x + y
parent = FastMCP("Parent")
parent.mount(child, "child")
tools = await parent.list_tools()
assert len(tools) == 1
assert tools[0].name == "child_add"
assert tools[0].version == "2.0"
async def test_mounted_resource_preserves_version(self):
"""Mounted resources should preserve their version info."""
child = FastMCP("Child")
@child.resource("file:///config", version="1.5")
def config() -> str:
return "config data"
parent = FastMCP("Parent")
parent.mount(child, "child")
resources = await parent.list_resources()
assert len(resources) == 1
assert resources[0].version == "1.5"
async def test_mounted_prompt_preserves_version(self):
"""Mounted prompts should preserve their version info."""
child = FastMCP("Child")
@child.prompt(version="3.0")
def greet(name: str) -> str:
return f"Hello, {name}!"
parent = FastMCP("Parent")
parent.mount(child, "child")
prompts = await parent.list_prompts()
assert len(prompts) == 1
assert prompts[0].name == "child_greet"
assert prompts[0].version == "3.0"
async def test_mounted_get_tool_with_version(self):
"""Should be able to get specific version from mounted server."""
child = FastMCP("Child")
@child.tool(version="1.0")
def calc() -> int:
return 1
@child.tool(version="2.0")
def calc() -> int:
return 2
parent = FastMCP("Parent")
parent.mount(child, "child")
# Get highest version (default)
tool = await parent.get_tool("child_calc")
assert tool is not None
assert tool.version == "2.0"
# Get specific version
tool_v1 = await parent.get_tool("child_calc", VersionSpec(eq="1.0"))
assert tool_v1 is not None
assert tool_v1.version == "1.0"
async def test_mounted_multiple_versions_all_returned(self):
"""Mounted server with multiple versions should show all versions."""
child = FastMCP("Child")
@child.tool(version="1.0")
def my_tool() -> str:
return "v1"
@child.tool(version="3.0")
def my_tool() -> str:
return "v3"
@child.tool(version="2.0")
def my_tool() -> str:
return "v2"
parent = FastMCP("Parent")
parent.mount(child, "child")
# list_tools returns all versions
tools = await parent.list_tools()
assert len(tools) == 3
versions = {t.version for t in tools}
assert versions == {"1.0", "2.0", "3.0"}
# get_tool returns highest
tool = await parent.get_tool("child_my_tool")
assert tool is not None
assert tool.version == "3.0"
async def test_mounted_call_tool_uses_highest_version(self):
"""Calling mounted tool should use highest version."""
child = FastMCP("Child")
@child.tool(version="1.0")
def double(x: int) -> int:
return x * 2
@child.tool(version="2.0")
def double(x: int) -> int:
return x * 2 + 100 # Different behavior
parent = FastMCP("Parent")
parent.mount(child, "child")
result = await parent.call_tool("child_double", {"x": 5})
# Should use v2.0 which adds 100
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "110"
async def test_mounted_tool_wrapper_executes_correct_version(self):
"""Calling a specific versioned tool wrapper should execute that version."""
child = FastMCP("Child")
@child.tool(version="1.0")
def calc(x: int) -> int:
return x * 10 # v1.0 multiplies by 10
@child.tool(version="2.0")
def calc(x: int) -> int:
return x * 100 # v2.0 multiplies by 100
parent = FastMCP("Parent")
parent.mount(child, "child")
# Get the v1.0 wrapper specifically
tools = await parent.list_tools()
v1_tool = next(
t for t in tools if t.name == "child_calc" and t.version == "1.0"
)
# Calling the v1.0 wrapper should execute v1.0's logic
result = await v1_tool.run({"x": 5})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "50" # 5 * 10, not 5 * 100
async def test_mounted_resource_wrapper_reads_correct_version(self):
"""Reading a specific versioned resource should read that version."""
from fastmcp.utilities.versions import VersionSpec
child = FastMCP("Child")
@child.resource("data:///config", version="1.0")
def config_v1() -> str:
return "config-v1-content"
@child.resource("data:///config", version="2.0")
def config_v2() -> str:
return "config-v2-content"
parent = FastMCP("Parent")
parent.mount(child, "child")
# Reading with version=1.0 should read v1.0's content
result = await parent.read_resource(
"data://child//config", version=VersionSpec(eq="1.0")
)
assert result.contents[0].content == "config-v1-content"
# Reading with version=2.0 should read v2.0's content
result = await parent.read_resource(
"data://child//config", version=VersionSpec(eq="2.0")
)
assert result.contents[0].content == "config-v2-content"
async def test_mounted_prompt_wrapper_renders_correct_version(self):
"""Rendering a specific versioned prompt should render that version."""
from fastmcp.utilities.versions import VersionSpec
child = FastMCP("Child")
@child.prompt(version="1.0")
def greeting(name: str) -> str:
return f"Hello, {name}!" # v1.0 says Hello
@child.prompt(version="2.0")
def greeting(name: str) -> str:
return f"Greetings, {name}!" # v2.0 says Greetings
parent = FastMCP("Parent")
parent.mount(child, "child")
# Rendering with version=1.0 should render v1.0's content
result = await parent.render_prompt(
"child_greeting", {"name": "World"}, version=VersionSpec(eq="1.0")
)
content = result.messages[0].content
assert isinstance(content, TextContent) and "Hello, World!" in content.text
# Rendering with version=2.0 should render v2.0's content
result = await parent.render_prompt(
"child_greeting", {"name": "World"}, version=VersionSpec(eq="2.0")
)
content = result.messages[0].content
assert isinstance(content, TextContent) and "Greetings, World!" in content.text
async def test_deeply_nested_version_forwarding(self):
"""Verify version is correctly forwarded through multiple mount levels."""
level3 = FastMCP("Level3")
@level3.tool(version="1.0")
def calc(x: int) -> int:
return x * 10 # v1.0 multiplies by 10
@level3.tool(version="2.0")
def calc(x: int) -> int:
return x * 100 # v2.0 multiplies by 100
level2 = FastMCP("Level2")
level2.mount(level3, "l3")
level1 = FastMCP("Level1")
level1.mount(level2, "l2")
# All versions should be visible through two levels of mounting
tools = await level1.list_tools()
calc_tools = [t for t in tools if "calc" in t.name]
assert len(calc_tools) == 2
versions = {t.version for t in calc_tools}
assert versions == {"1.0", "2.0"}
# Get v1.0 wrapper through two levels of mounting
v1_tool = next(t for t in tools if "calc" in t.name and t.version == "1.0")
# Should execute v1.0 logic, not v2.0
result = await v1_tool.run({"x": 5})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "50" # 5 * 10, not 5 * 100
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/versioning/test_mounting.py",
"license": "Apache License 2.0",
"lines": 260,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/versioning/test_versioning.py | """Core versioning functionality: VersionKey, utilities, and components."""
# ruff: noqa: F811 # Intentional function redefinition for version testing
from __future__ import annotations
from typing import cast
import pytest
from mcp.types import TextContent
from fastmcp import FastMCP
from fastmcp.tools import Tool
from fastmcp.utilities.versions import (
VersionKey,
compare_versions,
is_version_greater,
)
class TestVersionKey:
"""Tests for VersionKey comparison class."""
def test_none_sorts_lowest(self):
"""None (unversioned) should sort lower than any version."""
assert VersionKey(None) < VersionKey("1.0")
assert VersionKey(None) < VersionKey("0.1")
assert VersionKey(None) < VersionKey("anything")
def test_none_equals_none(self):
"""Two None versions should be equal."""
assert VersionKey(None) == VersionKey(None)
assert not (VersionKey(None) < VersionKey(None))
assert not (VersionKey(None) > VersionKey(None))
def test_pep440_versions_compared_semantically(self):
"""Valid PEP 440 versions should compare semantically."""
assert VersionKey("1.0") < VersionKey("2.0")
assert VersionKey("1.0") < VersionKey("1.1")
assert VersionKey("1.9") < VersionKey("1.10") # Semantic, not string
assert VersionKey("2") < VersionKey("10") # Semantic, not string
def test_v_prefix_stripped(self):
"""Versions with 'v' prefix should be handled correctly."""
assert VersionKey("v1.0") == VersionKey("1.0")
assert VersionKey("v2.0") > VersionKey("v1.0")
def test_string_fallback_for_invalid_versions(self):
"""Invalid PEP 440 versions should fall back to string comparison."""
# Dates are not valid PEP 440
assert VersionKey("2024-01-01") < VersionKey("2025-01-01")
# String comparison (lexicographic)
assert VersionKey("alpha") < VersionKey("beta")
def test_pep440_sorts_before_strings(self):
"""PEP 440 versions sort before invalid string versions."""
# "1.0" is valid PEP 440, "not-semver" is not
assert VersionKey("1.0") < VersionKey("not-semver")
assert VersionKey("999.0") < VersionKey("aaa") # PEP 440 < string
def test_repr(self):
"""Test string representation."""
assert repr(VersionKey("1.0")) == "VersionKey('1.0')"
assert repr(VersionKey(None)) == "VersionKey(None)"
class TestVersionFunctions:
"""Tests for version comparison functions."""
def test_compare_versions(self):
"""Test compare_versions function."""
assert compare_versions("1.0", "2.0") == -1
assert compare_versions("2.0", "1.0") == 1
assert compare_versions("1.0", "1.0") == 0
assert compare_versions(None, "1.0") == -1
assert compare_versions("1.0", None) == 1
assert compare_versions(None, None) == 0
def test_is_version_greater(self):
"""Test is_version_greater function."""
assert is_version_greater("2.0", "1.0")
assert not is_version_greater("1.0", "2.0")
assert not is_version_greater("1.0", "1.0")
assert is_version_greater("1.0", None)
assert not is_version_greater(None, "1.0")
class TestComponentVersioning:
"""Tests for versioning in FastMCP components."""
async def test_tool_with_version(self):
"""Tool version should be reflected in key."""
mcp = FastMCP()
@mcp.tool(version="2.0")
def my_tool(x: int) -> int:
return x * 2
tools = await mcp.list_tools()
assert len(tools) == 1
assert tools[0].name == "my_tool"
assert tools[0].version == "2.0"
assert tools[0].key == "tool:my_tool@2.0"
async def test_tool_without_version(self):
"""Tool without version should have @ sentinel in key but empty version."""
mcp = FastMCP()
@mcp.tool
def my_tool(x: int) -> int:
return x * 2
tools = await mcp.list_tools()
assert len(tools) == 1
assert tools[0].version is None
# Keys always have @ sentinel for unambiguous parsing
assert tools[0].key == "tool:my_tool@"
async def test_tool_version_as_int(self):
"""Tool version as int should be coerced to string."""
mcp = FastMCP()
@mcp.tool(version=2)
def my_tool(x: int) -> int:
return x * 2
tools = await mcp.list_tools()
assert len(tools) == 1
assert tools[0].version == "2"
assert tools[0].key == "tool:my_tool@2"
async def test_tool_version_zero_is_truthy(self):
"""Version 0 should become "0" (truthy string), not empty."""
mcp = FastMCP()
@mcp.tool(version=0)
def my_tool(x: int) -> int:
return x * 2
tools = await mcp.list_tools()
assert len(tools) == 1
assert tools[0].version == "0"
assert tools[0].key == "tool:my_tool@0" # Not "tool:my_tool@"
async def test_multiple_tool_versions_all_returned(self):
"""list_tools returns all versions; get_tool returns highest."""
mcp = FastMCP()
@mcp.tool(version="1.0")
def add(x: int, y: int) -> int:
return x + y
@mcp.tool(version="2.0")
def add(x: int, y: int, z: int = 0) -> int:
return x + y + z
# list_tools returns all versions
tools = await mcp.list_tools()
assert len(tools) == 2
versions = {t.version for t in tools}
assert versions == {"1.0", "2.0"}
# get_tool returns highest version
tool = await mcp.get_tool("add")
assert tool is not None
assert tool.version == "2.0"
async def test_call_tool_invokes_highest_version(self):
"""Calling a tool by name should invoke the highest version."""
mcp = FastMCP()
@mcp.tool(version="1.0")
def add(x: int, y: int) -> int:
return x + y
@mcp.tool(version="2.0")
def add(x: int, y: int) -> int:
return (x + y) * 10 # Different behavior to distinguish
result = await mcp.call_tool("add", {"x": 1, "y": 2})
# Should invoke v2.0 which multiplies by 10
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "30"
async def test_mixing_versioned_and_unversioned_rejected(self):
"""Cannot mix versioned and unversioned tools with the same name."""
import pytest
mcp = FastMCP()
@mcp.tool
def my_tool() -> str:
return "unversioned"
# Adding versioned tool when unversioned exists should fail
with pytest.raises(ValueError, match="versioned.*unversioned"):
@mcp.tool(version="1.0")
def my_tool() -> str:
return "v1.0"
async def test_mixing_unversioned_after_versioned_rejected(self):
"""Cannot add unversioned tool when versioned exists."""
import pytest
mcp = FastMCP()
@mcp.tool(version="1.0")
def my_tool() -> str:
return "v1.0"
# Adding unversioned tool when versioned exists should fail
with pytest.raises(ValueError, match="unversioned.*versioned"):
@mcp.tool
def my_tool() -> str:
return "unversioned"
async def test_resource_with_version(self):
"""Resource version should work like tool version."""
mcp = FastMCP()
@mcp.resource("file:///config", version="1.0")
def config_v1() -> str:
return "config v1"
@mcp.resource("file:///config", version="2.0")
def config_v2() -> str:
return "config v2"
# list_resources returns all versions
resources = await mcp.list_resources()
assert len(resources) == 2
versions = {r.version for r in resources}
assert versions == {"1.0", "2.0"}
# get_resource returns highest version
resource = await mcp.get_resource("file:///config")
assert resource is not None
assert resource.version == "2.0"
async def test_prompt_with_version(self):
"""Prompt version should work like tool version."""
mcp = FastMCP()
@mcp.prompt(version="1.0")
def greet(name: str) -> str:
return f"Hello, {name}!"
@mcp.prompt(version="2.0")
def greet(name: str) -> str:
return f"Greetings, {name}!"
# list_prompts returns all versions
prompts = await mcp.list_prompts()
assert len(prompts) == 2
versions = {p.version for p in prompts}
assert versions == {"1.0", "2.0"}
# get_prompt returns highest version
prompt = await mcp.get_prompt("greet")
assert prompt is not None
assert prompt.version == "2.0"
class TestVersionValidation:
"""Tests for version type validation in components and server."""
async def test_fastmcp_version_int_coerced(self):
"""FastMCP(version=42) should coerce to string '42'."""
mcp = FastMCP(version=42)
assert mcp._mcp_server.version == "42"
async def test_fastmcp_version_float_coerced(self):
"""FastMCP(version=1.5) should coerce to string."""
mcp = FastMCP(version=1.5)
assert mcp._mcp_server.version == "1.5"
async def test_tool_version_list_rejected(self):
"""Tool with version=[1, 2] should raise TypeError."""
with pytest.raises(TypeError, match="Version must be a string"):
Tool(
name="t",
version=cast(str, [1, 2]),
parameters={"type": "object"},
)
async def test_tool_version_dict_rejected(self):
"""Tool with version={'major': 1} should raise TypeError."""
with pytest.raises(TypeError, match="Version must be a string"):
Tool(
name="t",
version=cast(str, {"major": 1}),
parameters={"type": "object"},
)
async def test_fastmcp_version_list_rejected(self):
"""FastMCP(version=[1, 2]) should raise TypeError."""
with pytest.raises(TypeError, match="Version must be a string"):
FastMCP(version=cast(str, [1, 2]))
async def test_fastmcp_version_dict_rejected(self):
"""FastMCP(version={'v': 1}) should raise TypeError."""
with pytest.raises(TypeError, match="Version must be a string"):
FastMCP(version=cast(str, {"v": 1}))
async def test_fastmcp_version_true_rejected(self):
"""FastMCP(version=True) should raise TypeError, not coerce to 'True'."""
with pytest.raises(TypeError, match="got bool"):
FastMCP(version=cast(str, True))
async def test_fastmcp_version_false_rejected(self):
"""FastMCP(version=False) should raise TypeError, not coerce to 'False'."""
with pytest.raises(TypeError, match="got bool"):
FastMCP(version=cast(str, False))
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/versioning/test_versioning.py",
"license": "Apache License 2.0",
"lines": 244,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/tools/tool/test_callable.py | import asyncio
import threading
from mcp.types import TextContent
from fastmcp import Context, FastMCP
from fastmcp.tools.tool import Tool
class TestToolCallable:
"""Test tools with callable objects."""
async def test_callable_object_sync(self):
"""Test that callable objects with sync __call__ work."""
class MyTool:
def __init__(self, multiplier: int):
self.multiplier = multiplier
def __call__(self, x: int) -> int:
return x * self.multiplier
tool = Tool.from_function(MyTool(3))
result = await tool.run({"x": 5})
assert result.content == [TextContent(type="text", text="15")]
async def test_callable_object_async(self):
"""Test that callable objects with async __call__ work."""
class AsyncTool:
def __init__(self, multiplier: int):
self.multiplier = multiplier
async def __call__(self, x: int) -> int:
return x * self.multiplier
tool = Tool.from_function(AsyncTool(4))
result = await tool.run({"x": 5})
assert result.content == [TextContent(type="text", text="20")]
class TestSyncToolConcurrency:
"""Tests for concurrent execution of sync tools without blocking the event loop."""
async def test_sync_tools_run_concurrently(self):
"""Test that sync tools run in threadpool and don't block each other.
Uses a threading barrier to prove concurrent execution: all calls must
reach the barrier simultaneously for any to proceed. If they ran
sequentially, only one would reach the barrier and it would time out.
"""
num_calls = 3
# Barrier requires all threads to arrive before any proceed
# Short timeout since concurrent threads should arrive within milliseconds
barrier = threading.Barrier(num_calls, timeout=0.5)
def concurrent_tool(x: int) -> int:
"""Tool that proves concurrency via barrier synchronization."""
# If calls run sequentially, only 1 thread reaches barrier and times out
# If calls run concurrently, all 3 reach barrier and proceed
barrier.wait()
return x * 2
tool = Tool.from_function(concurrent_tool)
# Run concurrent calls - will raise BrokenBarrierError if not concurrent
results = await asyncio.gather(
tool.run({"x": 1}),
tool.run({"x": 2}),
tool.run({"x": 3}),
)
# Verify results
assert [r.content for r in results] == [
[TextContent(type="text", text="2")],
[TextContent(type="text", text="4")],
[TextContent(type="text", text="6")],
]
async def test_sync_tool_with_context_runs_concurrently(self):
"""Test that sync tools with Context dependency also run concurrently."""
num_calls = 3
barrier = threading.Barrier(num_calls, timeout=0.5)
mcp = FastMCP("test")
@mcp.tool
def ctx_tool(x: int, ctx: Context) -> str:
"""A sync tool with context that uses barrier to prove concurrency."""
barrier.wait()
return f"{ctx.fastmcp.name}:{x}"
# Run concurrent calls through the server interface (which sets up Context)
results = await asyncio.gather(
mcp.call_tool("ctx_tool", {"x": 1}),
mcp.call_tool("ctx_tool", {"x": 2}),
mcp.call_tool("ctx_tool", {"x": 3}),
)
# Verify results
for i, result in enumerate(results, 1):
assert result.content == [TextContent(type="text", text=f"test:{i}")]
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/tools/tool/test_callable.py",
"license": "Apache License 2.0",
"lines": 77,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/tools/tool/test_content.py | from dataclasses import dataclass
import pytest
from inline_snapshot import snapshot
from mcp.types import (
AudioContent,
BlobResourceContents,
EmbeddedResource,
ImageContent,
ResourceLink,
TextContent,
TextResourceContents,
)
from pydantic import AnyUrl, BaseModel
from fastmcp.tools.tool import Tool, _convert_to_content
from fastmcp.utilities.types import Audio, File, Image
class SampleModel(BaseModel):
x: int
y: str
class TestConvertResultToContent:
"""Tests for the _convert_to_content helper function."""
@pytest.mark.parametrize(
argnames=("result", "expected"),
argvalues=[
(True, "true"),
("hello", "hello"),
(123, "123"),
(123.45, "123.45"),
({"key": "value"}, '{"key":"value"}'),
(
SampleModel(x=1, y="hello"),
'{"x":1,"y":"hello"}',
),
],
ids=[
"boolean",
"string",
"integer",
"float",
"object",
"basemodel",
],
)
def test_convert_singular(self, result, expected):
"""Test that a single item is converted to a TextContent."""
converted = _convert_to_content(result)
assert converted == [TextContent(type="text", text=expected)]
@pytest.mark.parametrize(
argnames=("result", "expected_text"),
argvalues=[
([None], "[null]"),
([None, None], "[null,null]"),
([True], "[true]"),
([True, False], "[true,false]"),
(["hello"], '["hello"]'),
(["hello", "world"], '["hello","world"]'),
([123], "[123]"),
([123, 456], "[123,456]"),
([123.45], "[123.45]"),
([123.45, 456.78], "[123.45,456.78]"),
([{"key": "value"}], '[{"key":"value"}]'),
(
[{"key": "value"}, {"key2": "value2"}],
'[{"key":"value"},{"key2":"value2"}]',
),
([SampleModel(x=1, y="hello")], '[{"x":1,"y":"hello"}]'),
(
[SampleModel(x=1, y="hello"), SampleModel(x=2, y="world")],
'[{"x":1,"y":"hello"},{"x":2,"y":"world"}]',
),
([1, "two", None, {"c": 3}, False], '[1,"two",null,{"c":3},false]'),
],
ids=[
"none",
"none_many",
"boolean",
"boolean_many",
"string",
"string_many",
"integer",
"integer_many",
"float",
"float_many",
"object",
"object_many",
"basemodel",
"basemodel_many",
"mixed",
],
)
def test_convert_list(self, result, expected_text):
"""Test that a list is converted to a TextContent."""
converted = _convert_to_content(result)
assert converted == [TextContent(type="text", text=expected_text)]
@pytest.mark.parametrize(
argnames="content_block",
argvalues=[
(TextContent(type="text", text="hello")),
(ImageContent(type="image", data="fakeimagedata", mimeType="image/png")),
(AudioContent(type="audio", data="fakeaudiodata", mimeType="audio/mpeg")),
(
ResourceLink(
type="resource_link",
name="test resource",
uri=AnyUrl("resource://test"),
)
),
(
EmbeddedResource(
type="resource",
resource=TextResourceContents(
uri=AnyUrl("resource://test"),
mimeType="text/plain",
text="resource content",
),
)
),
],
ids=["text", "image", "audio", "resource link", "embedded resource"],
)
def test_convert_content_block(self, content_block):
converted = _convert_to_content(content_block)
assert converted == [content_block]
converted = _convert_to_content([content_block, content_block])
assert converted == [content_block, content_block]
@pytest.mark.parametrize(
argnames=("result", "expected"),
argvalues=[
(
Image(data=b"fakeimagedata"),
[
ImageContent(
type="image", data="ZmFrZWltYWdlZGF0YQ==", mimeType="image/png"
)
],
),
(
Audio(data=b"fakeaudiodata"),
[
AudioContent(
type="audio", data="ZmFrZWF1ZGlvZGF0YQ==", mimeType="audio/wav"
)
],
),
(
File(data=b"filedata", format="octet-stream"),
[
EmbeddedResource(
type="resource",
resource=BlobResourceContents(
uri=AnyUrl("file:///resource.octet-stream"),
blob="ZmlsZWRhdGE=",
mimeType="application/octet-stream",
),
)
],
),
],
ids=["image", "audio", "file"],
)
def test_convert_helpers(self, result, expected):
converted = _convert_to_content(result)
assert converted == expected
converted = _convert_to_content([result, result])
assert converted == expected * 2
def test_convert_mixed_content(self):
result = [
"hello",
123,
123.45,
{"key": "value"},
SampleModel(x=1, y="hello"),
Image(data=b"fakeimagedata"),
Audio(data=b"fakeaudiodata"),
ResourceLink(
type="resource_link",
name="test resource",
uri=AnyUrl("resource://test"),
),
EmbeddedResource(
type="resource",
resource=TextResourceContents(
uri=AnyUrl("resource://test"),
mimeType="text/plain",
text="resource content",
),
),
]
converted = _convert_to_content(result)
assert converted == snapshot(
[
TextContent(type="text", text="hello"),
TextContent(type="text", text="123"),
TextContent(type="text", text="123.45"),
TextContent(type="text", text='{"key":"value"}'),
TextContent(type="text", text='{"x":1,"y":"hello"}'),
ImageContent(
type="image", data="ZmFrZWltYWdlZGF0YQ==", mimeType="image/png"
),
AudioContent(
type="audio", data="ZmFrZWF1ZGlvZGF0YQ==", mimeType="audio/wav"
),
ResourceLink(
name="test resource",
uri=AnyUrl("resource://test"),
type="resource_link",
),
EmbeddedResource(
type="resource",
resource=TextResourceContents(
uri=AnyUrl("resource://test"),
mimeType="text/plain",
text="resource content",
),
),
]
)
def test_empty_list(self):
"""Test that an empty list results in an empty list."""
result = _convert_to_content([])
assert isinstance(result, list)
assert len(result) == 0
def test_empty_dict(self):
"""Test that an empty dictionary is converted to TextContent."""
result = _convert_to_content({})
assert isinstance(result, list)
assert len(result) == 1
assert isinstance(result[0], TextContent)
assert result[0].text == "{}"
class TestAutomaticStructuredContent:
"""Tests for automatic structured content generation based on return types."""
async def test_dict_return_creates_structured_content_without_schema(self):
"""Test that dict returns automatically create structured content even without output schema."""
def get_user_data(user_id: str) -> dict:
return {"name": "Alice", "age": 30, "active": True}
# No explicit output schema provided
tool = Tool.from_function(get_user_data)
result = await tool.run({"user_id": "123"})
# Should have both content and structured content
assert len(result.content) == 1
assert isinstance(result.content[0], TextContent)
assert result.structured_content == {"name": "Alice", "age": 30, "active": True}
async def test_dataclass_return_creates_structured_content_without_schema(self):
"""Test that dataclass returns automatically create structured content even without output schema."""
@dataclass
class UserProfile:
name: str
age: int
email: str
def get_profile(user_id: str) -> UserProfile:
return UserProfile(name="Bob", age=25, email="bob@example.com")
# No explicit output schema, but dataclass should still create structured content
tool = Tool.from_function(get_profile, output_schema=None)
result = await tool.run({"user_id": "456"})
# Should have both content and structured content
assert len(result.content) == 1
assert isinstance(result.content[0], TextContent)
# Dataclass should serialize to dict
assert result.structured_content == {
"name": "Bob",
"age": 25,
"email": "bob@example.com",
}
async def test_pydantic_model_return_creates_structured_content_without_schema(
self,
):
"""Test that Pydantic model returns automatically create structured content even without output schema."""
class UserData(BaseModel):
username: str
score: int
verified: bool
def get_user_stats(user_id: str) -> UserData:
return UserData(username="charlie", score=100, verified=True)
# Explicitly set output schema to None to test automatic structured content
tool = Tool.from_function(get_user_stats, output_schema=None)
result = await tool.run({"user_id": "789"})
# Should have both content and structured content
assert len(result.content) == 1
assert isinstance(result.content[0], TextContent)
# Pydantic model should serialize to dict
assert result.structured_content == {
"username": "charlie",
"score": 100,
"verified": True,
}
async def test_self_referencing_dataclass_not_wrapped(self):
"""Test that self-referencing dataclasses are not wrapped in result field."""
@dataclass
class ReturnThing:
value: int
stuff: list["ReturnThing"]
def return_things() -> ReturnThing:
return ReturnThing(value=123, stuff=[ReturnThing(value=456, stuff=[])])
tool = Tool.from_function(return_things)
result = await tool.run({})
# Should have structured content without wrapping
assert result.structured_content is not None
# Should NOT be wrapped in "result" field
assert "result" not in result.structured_content
# Should have the actual data directly
assert result.structured_content == {
"value": 123,
"stuff": [{"value": 456, "stuff": []}],
}
async def test_self_referencing_pydantic_model_has_type_object_at_root(self):
"""Test that self-referencing Pydantic models have type: object at root.
MCP spec requires outputSchema to have "type": "object" at the root level.
Pydantic generates schemas with $ref at root for self-referential models,
which violates this requirement. FastMCP should resolve the $ref.
Regression test for issue #2455.
"""
class Issue(BaseModel):
id: str
title: str
dependencies: list["Issue"] = []
dependents: list["Issue"] = []
def get_issue(issue_id: str) -> Issue:
return Issue(id=issue_id, title="Test")
tool = Tool.from_function(get_issue)
# The output schema should have "type": "object" at root, not $ref
assert tool.output_schema is not None
assert tool.output_schema.get("type") == "object"
assert "properties" in tool.output_schema
# Should still have $defs for nested references
assert "$defs" in tool.output_schema
# Should NOT have $ref at root level
assert "$ref" not in tool.output_schema
async def test_self_referencing_model_outputschema_mcp_compliant(self):
"""Test that self-referencing model schemas are MCP spec compliant.
The MCP spec requires:
- type: "object" at root level
- properties field
- required field (optional)
This ensures clients can properly validate the schema.
Regression test for issue #2455.
"""
class Node(BaseModel):
id: str
children: list["Node"] = []
def get_node() -> Node:
return Node(id="1")
tool = Tool.from_function(get_node)
# Schema should be MCP-compliant
assert tool.output_schema is not None
assert tool.output_schema.get("type") == "object", (
"MCP spec requires 'type': 'object' at root"
)
assert "properties" in tool.output_schema
assert "id" in tool.output_schema["properties"]
assert "children" in tool.output_schema["properties"]
# Required should include 'id'
assert "id" in tool.output_schema.get("required", [])
async def test_int_return_no_structured_content_without_schema(self):
"""Test that int returns don't create structured content without output schema."""
def calculate_sum(a: int, b: int):
"""No return annotation."""
return a + b
# No output schema
tool = Tool.from_function(calculate_sum)
result = await tool.run({"a": 5, "b": 3})
# Should only have content, no structured content
assert len(result.content) == 1
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "8"
assert result.structured_content is None
async def test_str_return_no_structured_content_without_schema(self):
"""Test that str returns don't create structured content without output schema."""
def get_greeting(name: str):
"""No return annotation."""
return f"Hello, {name}!"
# No output schema
tool = Tool.from_function(get_greeting)
result = await tool.run({"name": "World"})
# Should only have content, no structured content
assert len(result.content) == 1
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "Hello, World!"
assert result.structured_content is None
async def test_list_return_no_structured_content_without_schema(self):
"""Test that list returns don't create structured content without output schema."""
def get_numbers():
"""No return annotation."""
return [1, 2, 3, 4, 5]
# No output schema
tool = Tool.from_function(get_numbers)
result = await tool.run({})
assert result.structured_content is None
assert result.content == snapshot(
[TextContent(type="text", text="[1,2,3,4,5]")]
)
async def test_audio_return_creates_no_structured_content(self):
"""Test that audio returns don't create structured content."""
def get_audio() -> AudioContent:
"""No return annotation."""
return Audio(data=b"fakeaudiodata").to_audio_content()
# No output schema
tool = Tool.from_function(get_audio)
result = await tool.run({})
assert result.content == snapshot(
[
AudioContent(
type="audio", data="ZmFrZWF1ZGlvZGF0YQ==", mimeType="audio/wav"
)
]
)
assert result.structured_content is None
async def test_int_return_with_schema_creates_structured_content(self):
"""Test that int returns DO create structured content when there's an output schema."""
def calculate_sum(a: int, b: int) -> int:
"""With return annotation."""
return a + b
# Output schema should be auto-generated from annotation
tool = Tool.from_function(calculate_sum)
assert tool.output_schema is not None
result = await tool.run({"a": 5, "b": 3})
# Should have both content and structured content
assert len(result.content) == 1
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "8"
assert result.structured_content == {"result": 8}
async def test_client_automatic_deserialization_with_dict_result(self):
"""Test that clients automatically deserialize dict results from structured content."""
from fastmcp import FastMCP
from fastmcp.client import Client
mcp = FastMCP()
@mcp.tool
def get_user_info(user_id: str) -> dict:
return {"name": "Alice", "age": 30, "active": True}
async with Client(mcp) as client:
result = await client.call_tool("get_user_info", {"user_id": "123"})
# Client should provide the deserialized data
assert result.data == {"name": "Alice", "age": 30, "active": True}
assert result.structured_content == {
"name": "Alice",
"age": 30,
"active": True,
}
assert len(result.content) == 1
async def test_client_automatic_deserialization_with_dataclass_result(self):
"""Test that clients automatically deserialize dataclass results from structured content."""
from fastmcp import FastMCP
from fastmcp.client import Client
mcp = FastMCP()
@dataclass
class UserProfile:
name: str
age: int
verified: bool
@mcp.tool
def get_profile(user_id: str) -> UserProfile:
return UserProfile(name="Bob", age=25, verified=True)
async with Client(mcp) as client:
result = await client.call_tool("get_profile", {"user_id": "456"})
# Client should deserialize back to a dataclass (but type name is lost with title pruning)
assert result.data.__class__.__name__ == "Root"
assert result.data.name == "Bob"
assert result.data.age == 25
assert result.data.verified is True
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/tools/tool/test_content.py",
"license": "Apache License 2.0",
"lines": 457,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/tools/tool/test_output_schema.py | from dataclasses import dataclass
from typing import Annotated, Any
import pytest
from inline_snapshot import snapshot
from mcp.types import AudioContent, EmbeddedResource, ImageContent, TextContent
from pydantic import AnyUrl, BaseModel, Field, TypeAdapter
from typing_extensions import TypedDict
from fastmcp.tools.tool import Tool
from fastmcp.utilities.json_schema import compress_schema
from fastmcp.utilities.types import Audio, File, Image
class TestToolFromFunctionOutputSchema:
async def test_no_return_annotation(self):
def func():
pass
tool = Tool.from_function(func)
assert tool.output_schema is None
@pytest.mark.parametrize(
"annotation",
[
int,
float,
bool,
str,
int | float,
list,
list[int],
list[int | float],
dict,
dict[str, Any],
dict[str, int | None],
tuple[int, str],
set[int],
list[tuple[int, str]],
],
)
async def test_simple_return_annotation(self, annotation):
def func() -> annotation:
return 1
tool = Tool.from_function(func)
base_schema = TypeAdapter(annotation).json_schema()
# Non-object types get wrapped
schema_type = base_schema.get("type")
is_object_type = schema_type == "object"
if not is_object_type:
# Non-object types get wrapped
expected_schema = {
"type": "object",
"properties": {"result": base_schema},
"required": ["result"],
"x-fastmcp-wrap-result": True,
}
assert tool.output_schema == expected_schema
# # Note: Parameterized test - keeping original assertion for multiple parameter values
else:
# Object types remain unwrapped
assert tool.output_schema == base_schema
@pytest.mark.parametrize(
"annotation",
[
AnyUrl,
Annotated[int, Field(ge=1)],
Annotated[int, Field(ge=1)],
],
)
async def test_complex_return_annotation(self, annotation):
def func() -> annotation:
return 1
tool = Tool.from_function(func)
base_schema = TypeAdapter(annotation).json_schema()
expected_schema = {
"type": "object",
"properties": {"result": base_schema},
"required": ["result"],
"x-fastmcp-wrap-result": True,
}
assert tool.output_schema == expected_schema
async def test_none_return_annotation(self):
def func() -> None:
pass
tool = Tool.from_function(func)
assert tool.output_schema is None
async def test_any_return_annotation(self):
from typing import Any
def func() -> Any:
return 1
tool = Tool.from_function(func)
assert tool.output_schema is None
@pytest.mark.parametrize(
"annotation, expected",
[
(Image, ImageContent),
(Audio, AudioContent),
(File, EmbeddedResource),
(Image | int, ImageContent | int),
(Image | Audio, ImageContent | AudioContent),
(list[Image | Audio], list[ImageContent | AudioContent]),
],
)
async def test_converted_return_annotation(self, annotation, expected):
def func() -> annotation:
return 1
tool = Tool.from_function(func)
# Image, Audio, File types don't generate output schemas since they're converted to content directly
assert tool.output_schema is None
async def test_dataclass_return_annotation(self):
@dataclass
class Person:
name: str
age: int
def func() -> Person:
return Person(name="John", age=30)
tool = Tool.from_function(func)
expected_schema = compress_schema(
TypeAdapter(Person).json_schema(), prune_titles=True
)
assert tool.output_schema == expected_schema
async def test_base_model_return_annotation(self):
class Person(BaseModel):
name: str
age: int
def func() -> Person:
return Person(name="John", age=30)
tool = Tool.from_function(func)
assert tool.output_schema == snapshot(
{
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
},
"required": ["name", "age"],
"type": "object",
}
)
async def test_typeddict_return_annotation(self):
class Person(TypedDict):
name: str
age: int
def func() -> Person:
return Person(name="John", age=30)
tool = Tool.from_function(func)
assert tool.output_schema == snapshot(
{
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
},
"required": ["name", "age"],
"type": "object",
}
)
async def test_unserializable_return_annotation(self):
class Unserializable:
def __init__(self, data: Any):
self.data = data
def func() -> Unserializable:
return Unserializable(data="test")
tool = Tool.from_function(func)
assert tool.output_schema is None
async def test_mixed_unserializable_return_annotation(self):
class Unserializable:
def __init__(self, data: Any):
self.data = data
def func() -> Unserializable | int:
return Unserializable(data="test")
tool = Tool.from_function(func)
assert tool.output_schema is None
async def test_provided_output_schema_takes_precedence_over_json_compatible_annotation(
self,
):
"""Test that provided output_schema takes precedence over inferred schema from JSON-compatible annotation."""
def func() -> dict[str, int]:
return {"a": 1, "b": 2}
# Provide a custom output schema that differs from the inferred one
custom_schema = {"type": "object", "description": "Custom schema"}
tool = Tool.from_function(func, output_schema=custom_schema)
assert tool.output_schema == custom_schema
async def test_provided_output_schema_takes_precedence_over_complex_annotation(
self,
):
"""Test that provided output_schema takes precedence over inferred schema from complex annotation."""
def func() -> list[dict[str, int | float]]:
return [{"a": 1, "b": 2.5}]
# Provide a custom output schema that differs from the inferred one
custom_schema = {"type": "object", "properties": {"custom": {"type": "string"}}}
tool = Tool.from_function(func, output_schema=custom_schema)
assert tool.output_schema == custom_schema
async def test_provided_output_schema_takes_precedence_over_unserializable_annotation(
self,
):
"""Test that provided output_schema takes precedence over None schema from unserializable annotation."""
class Unserializable:
def __init__(self, data: Any):
self.data = data
def func() -> Unserializable:
return Unserializable(data="test")
# Provide a custom output schema even though the annotation is unserializable
custom_schema = {
"type": "object",
"properties": {"items": {"type": "array", "items": {"type": "string"}}},
}
tool = Tool.from_function(func, output_schema=custom_schema)
assert tool.output_schema == custom_schema
async def test_provided_output_schema_takes_precedence_over_no_annotation(self):
"""Test that provided output_schema takes precedence over None schema from no annotation."""
def func():
return "hello"
# Provide a custom output schema even though there's no return annotation
custom_schema = {
"type": "object",
"properties": {"value": {"type": "number", "minimum": 0}},
}
tool = Tool.from_function(func, output_schema=custom_schema)
assert tool.output_schema == custom_schema
async def test_provided_output_schema_takes_precedence_over_converted_annotation(
self,
):
"""Test that provided output_schema takes precedence over converted schema from Image/Audio/File annotations."""
def func() -> Image:
return Image(data=b"test")
# Provide a custom output schema that differs from the converted ImageContent schema
custom_schema = {
"type": "object",
"properties": {"custom_image": {"type": "string"}},
}
tool = Tool.from_function(func, output_schema=custom_schema)
assert tool.output_schema == custom_schema
async def test_provided_output_schema_takes_precedence_over_union_annotation(self):
"""Test that provided output_schema takes precedence over inferred schema from union annotation."""
def func() -> str | int | None:
return "hello"
# Provide a custom output schema that differs from the inferred union schema
custom_schema = {"type": "object", "properties": {"flag": {"type": "boolean"}}}
tool = Tool.from_function(func, output_schema=custom_schema)
assert tool.output_schema == custom_schema
async def test_provided_output_schema_takes_precedence_over_pydantic_annotation(
self,
):
"""Test that provided output_schema takes precedence over inferred schema from Pydantic model annotation."""
class Person(BaseModel):
name: str
age: int
def func() -> Person:
return Person(name="John", age=30)
# Provide a custom output schema that differs from the inferred Person schema
custom_schema = {
"type": "object",
"properties": {"numbers": {"type": "array", "items": {"type": "number"}}},
}
tool = Tool.from_function(func, output_schema=custom_schema)
assert tool.output_schema == custom_schema
async def test_output_schema_false_allows_automatic_structured_content(self):
"""Test that output_schema=False still allows automatic structured content for dict-like objects."""
def func() -> dict[str, str]:
return {"message": "Hello, world!"}
tool = Tool.from_function(func, output_schema=None)
assert tool.output_schema is None
result = await tool.run({})
# Dict objects automatically become structured content even without schema
assert result.structured_content == {"message": "Hello, world!"}
assert len(result.content) == 1
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == '{"message":"Hello, world!"}'
async def test_output_schema_none_disables_structured_content(self):
"""Test that output_schema=None explicitly disables structured content."""
def func() -> int:
return 42
tool = Tool.from_function(func, output_schema=None)
assert tool.output_schema is None
result = await tool.run({})
assert result.structured_content is None
assert len(result.content) == 1
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "42"
async def test_output_schema_inferred_when_not_specified(self):
"""Test that output schema is inferred when not explicitly specified."""
def func() -> int:
return 42
# Don't specify output_schema - should infer and wrap
tool = Tool.from_function(func)
assert tool.output_schema == snapshot(
{
"properties": {"result": {"type": "integer"}},
"required": ["result"],
"type": "object",
"x-fastmcp-wrap-result": True,
}
)
result = await tool.run({})
assert result.structured_content == {"result": 42}
async def test_explicit_object_schema_with_dict_return(self):
"""Test that explicit object schemas work when function returns a dict."""
def func() -> dict[str, int]:
return {"value": 42}
# Provide explicit object schema
explicit_schema = {
"type": "object",
"properties": {"value": {"type": "integer", "minimum": 0}},
}
tool = Tool.from_function(func, output_schema=explicit_schema)
assert tool.output_schema == explicit_schema # Schema not wrapped
assert tool.output_schema and "x-fastmcp-wrap-result" not in tool.output_schema
result = await tool.run({})
# Dict result with object schema is used directly
assert result.structured_content == {"value": 42}
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == '{"value":42}'
async def test_explicit_object_schema_with_non_dict_return_fails(self):
"""Test that explicit object schemas fail when function returns non-dict."""
def func() -> int:
return 42
# Provide explicit object schema but return non-dict
explicit_schema = {
"type": "object",
"properties": {"value": {"type": "integer"}},
}
tool = Tool.from_function(func, output_schema=explicit_schema)
# Should fail because int is not dict-compatible with object schema
with pytest.raises(ValueError, match="structured_content must be a dict"):
await tool.run({})
async def test_object_output_schema_not_wrapped(self):
"""Test that object-type output schemas are never wrapped."""
def func() -> dict[str, int]:
return {"value": 42}
# Object schemas should never be wrapped, even when inferred
tool = Tool.from_function(func)
expected_schema = TypeAdapter(dict[str, int]).json_schema()
assert tool.output_schema == expected_schema # Not wrapped
assert tool.output_schema and "x-fastmcp-wrap-result" not in tool.output_schema
result = await tool.run({})
assert result.structured_content == {"value": 42} # Direct value
async def test_structured_content_interaction_with_wrapping(self):
"""Test that structured content works correctly with schema wrapping."""
def func() -> str:
return "hello"
# Inferred schema should wrap string type
tool = Tool.from_function(func)
assert tool.output_schema == snapshot(
{
"properties": {"result": {"type": "string"}},
"required": ["result"],
"type": "object",
"x-fastmcp-wrap-result": True,
}
)
result = await tool.run({})
# Unstructured content
assert len(result.content) == 1
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "hello"
# Structured content should be wrapped
assert result.structured_content == {"result": "hello"}
async def test_structured_content_with_explicit_object_schema(self):
"""Test structured content with explicit object schema."""
def func() -> dict[str, str]:
return {"greeting": "hello"}
# Provide explicit object schema
explicit_schema = {
"type": "object",
"properties": {"greeting": {"type": "string"}},
"required": ["greeting"],
}
tool = Tool.from_function(func, output_schema=explicit_schema)
assert tool.output_schema == explicit_schema
result = await tool.run({})
# Should use direct value since explicit schema doesn't have wrap marker
assert result.structured_content == {"greeting": "hello"}
async def test_structured_content_with_custom_wrapper_schema(self):
"""Test structured content with custom schema that includes wrap marker."""
def func() -> str:
return "world"
# Custom schema with wrap marker
custom_schema = {
"type": "object",
"properties": {"message": {"type": "string"}},
"x-fastmcp-wrap-result": True,
}
tool = Tool.from_function(func, output_schema=custom_schema)
assert tool.output_schema == custom_schema
result = await tool.run({})
# Should wrap with "result" key due to wrap marker
assert result.structured_content == {"result": "world"}
async def test_none_vs_false_output_schema_behavior(self):
"""Test the difference between None and False for output_schema."""
def func() -> int:
return 123
# None should disable
tool_none = Tool.from_function(func, output_schema=None)
assert tool_none.output_schema is None
# Default (NotSet) should infer from return type
tool_default = Tool.from_function(func)
assert (
tool_default.output_schema is not None
) # Should infer schema from dict return type
# Different behavior: None vs inferred
result_none = await tool_none.run({})
result_default = await tool_default.run({})
# None should still try fallback generation but fail for non-dict
assert result_none.structured_content is None # Fallback fails for int
# Default should use proper schema and wrap the result
assert result_default.structured_content == {
"result": 123
} # Schema-based generation with wrapping
assert isinstance(result_none.content[0], TextContent)
assert isinstance(result_default.content[0], TextContent)
assert result_none.content[0].text == result_default.content[0].text == "123"
async def test_non_object_output_schema_raises_error(self):
"""Test that providing a non-object output schema raises a ValueError."""
def func() -> int:
return 42
# Test various non-object schemas that should raise errors
non_object_schemas = [
{"type": "string"},
{"type": "integer", "minimum": 0},
{"type": "number"},
{"type": "boolean"},
{"type": "array", "items": {"type": "string"}},
]
for schema in non_object_schemas:
with pytest.raises(
ValueError, match="Output schemas must represent object types"
):
Tool.from_function(func, output_schema=schema)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/tools/tool/test_output_schema.py",
"license": "Apache License 2.0",
"lines": 422,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/tools/tool/test_results.py | from dataclasses import dataclass
from typing import Any
import pytest
from fastmcp.tools.tool import Tool, ToolResult
class TestToolResultCasting:
@pytest.fixture
async def client(self):
from fastmcp import FastMCP
from fastmcp.client import Client
mcp = FastMCP()
@mcp.tool
def test_tool(
unstructured: str | None = None,
structured: dict[str, Any] | None = None,
meta: dict[str, Any] | None = None,
):
return ToolResult(
content=unstructured,
structured_content=structured,
meta=meta,
)
async with Client(mcp) as client:
yield client
async def test_only_unstructured_content(self, client):
result = await client.call_tool("test_tool", {"unstructured": "test data"})
assert result.content[0].type == "text"
assert result.content[0].text == "test data"
assert result.structured_content is None
assert result.meta is None
async def test_neither_unstructured_or_structured_content(self, client):
from fastmcp.exceptions import ToolError
with pytest.raises(ToolError):
await client.call_tool("test_tool", {})
async def test_structured_and_unstructured_content(self, client):
result = await client.call_tool(
"test_tool",
{"unstructured": "test data", "structured": {"data_type": "test"}},
)
assert result.content[0].type == "text"
assert result.content[0].text == "test data"
assert result.structured_content == {"data_type": "test"}
assert result.meta is None
async def test_structured_unstructured_and_meta_content(self, client):
result = await client.call_tool(
"test_tool",
{
"unstructured": "test data",
"structured": {"data_type": "test"},
"meta": {"some": "metadata"},
},
)
assert result.content[0].type == "text"
assert result.content[0].text == "test data"
assert result.structured_content == {"data_type": "test"}
assert result.meta == {"some": "metadata"}
class TestUnionReturnTypes:
"""Tests for tools with union return types."""
async def test_dataclass_union_string_works(self):
"""Test that union of dataclass and string works correctly."""
@dataclass
class Data:
value: int
def get_data(return_error: bool) -> Data | str:
if return_error:
return "error occurred"
return Data(value=42)
tool = Tool.from_function(get_data)
# Test returning dataclass
result1 = await tool.run({"return_error": False})
assert result1.structured_content == {"result": {"value": 42}}
# Test returning string
result2 = await tool.run({"return_error": True})
assert result2.structured_content == {"result": "error occurred"}
class TestSerializationAlias:
"""Tests for Pydantic field serialization alias support in tool output schemas."""
def test_output_schema_respects_serialization_alias(self):
"""Test that Tool.from_function generates output schema using serialization alias."""
from typing import Annotated
from pydantic import AliasChoices, BaseModel, Field
class Component(BaseModel):
"""Model with multiple validation aliases but specific serialization alias."""
component_id: str = Field(
validation_alias=AliasChoices("id", "componentId"),
serialization_alias="componentId",
description="The ID of the component",
)
async def get_component(
component_id: str,
) -> Annotated[Component, Field(description="The component.")]:
# API returns data with 'id' field
api_data = {"id": component_id}
return Component.model_validate(api_data)
tool = Tool.from_function(get_component, name="get-component")
# The output schema should use the serialization alias 'componentId'
# not the first validation alias 'id'
assert tool.output_schema is not None
# Object schemas have properties directly at root (MCP spec compliance)
# Root-level $refs are resolved to ensure type: object at root
assert "properties" in tool.output_schema
assert tool.output_schema.get("type") == "object"
# Should have 'componentId' not 'id' in properties
assert "componentId" in tool.output_schema["properties"]
assert "id" not in tool.output_schema["properties"]
# Should require 'componentId' not 'id'
assert "componentId" in tool.output_schema.get("required", [])
assert "id" not in tool.output_schema.get("required", [])
async def test_tool_execution_with_serialization_alias(self):
"""Test that tool execution works correctly with serialization aliases."""
from typing import Annotated
from pydantic import AliasChoices, BaseModel, Field
from fastmcp import Client, FastMCP
class Component(BaseModel):
"""Model with multiple validation aliases but specific serialization alias."""
component_id: str = Field(
validation_alias=AliasChoices("id", "componentId"),
serialization_alias="componentId",
description="The ID of the component",
)
mcp = FastMCP("TestServer")
@mcp.tool
async def get_component(
component_id: str,
) -> Annotated[Component, Field(description="The component.")]:
# API returns data with 'id' field
api_data = {"id": component_id}
return Component.model_validate(api_data)
async with Client(mcp) as client:
# Execute the tool - this should work without validation errors
result = await client.call_tool(
"get_component", {"component_id": "test123"}
)
# The result should contain the serialized form with 'componentId'
assert result.structured_content is not None
# Object types may be wrapped in "result" or not, depending on schema structure
if "result" in result.structured_content:
component_data = result.structured_content["result"]
else:
component_data = result.structured_content
assert component_data["componentId"] == "test123"
assert "id" not in component_data
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/tools/tool/test_results.py",
"license": "Apache License 2.0",
"lines": 140,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/tools/tool/test_title.py | from fastmcp.tools.tool import Tool
class TestToolTitle:
"""Tests for tool title functionality."""
def test_tool_with_title(self):
"""Test that tools can have titles and they appear in MCP conversion."""
def calculate(x: int, y: int) -> int:
"""Calculate the sum of two numbers."""
return x + y
tool = Tool.from_function(
calculate,
name="calc",
title="Advanced Calculator Tool",
description="Custom description",
)
assert tool.name == "calc"
assert tool.title == "Advanced Calculator Tool"
assert tool.description == "Custom description"
# Test MCP conversion includes title
mcp_tool = tool.to_mcp_tool()
assert mcp_tool.name == "calc"
assert (
hasattr(mcp_tool, "title") and mcp_tool.title == "Advanced Calculator Tool"
)
def test_tool_without_title(self):
"""Test that tools without titles use name as display name."""
def multiply(a: int, b: int) -> int:
return a * b
tool = Tool.from_function(multiply)
assert tool.name == "multiply"
assert tool.title is None
# Test MCP conversion doesn't include title when None
mcp_tool = tool.to_mcp_tool()
assert mcp_tool.name == "multiply"
assert not hasattr(mcp_tool, "title") or mcp_tool.title is None
def test_tool_title_priority(self):
"""Test that explicit title takes priority over annotations.title."""
from mcp.types import ToolAnnotations
def divide(x: int, y: int) -> float:
"""Divide two numbers."""
return x / y
# Test with both explicit title and annotations.title
annotations = ToolAnnotations(title="Annotation Title")
tool = Tool.from_function(
divide,
name="div",
title="Explicit Title",
annotations=annotations,
)
assert tool.title == "Explicit Title"
assert tool.annotations is not None
assert tool.annotations.title == "Annotation Title"
# Explicit title should take priority
mcp_tool = tool.to_mcp_tool()
assert mcp_tool.title == "Explicit Title"
def test_tool_annotations_title_fallback(self):
"""Test that annotations.title is used when no explicit title is provided."""
from mcp.types import ToolAnnotations
def modulo(x: int, y: int) -> int:
"""Get modulo of two numbers."""
return x % y
# Test with only annotations.title (no explicit title)
annotations = ToolAnnotations(title="Annotation Title")
tool = Tool.from_function(
modulo,
name="mod",
annotations=annotations,
)
assert tool.title is None
assert tool.annotations is not None
assert tool.annotations.title == "Annotation Title"
# Should fall back to annotations.title
mcp_tool = tool.to_mcp_tool()
assert mcp_tool.title == "Annotation Title"
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/tools/tool/test_title.py",
"license": "Apache License 2.0",
"lines": 73,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/tools/tool/test_tool.py | from datetime import timedelta
import pytest
from dirty_equals import HasName
from inline_snapshot import snapshot
from mcp.types import (
AudioContent,
ImageContent,
ToolExecution,
)
from pydantic import BaseModel
from fastmcp.tools.tool import Tool, ToolResult
from fastmcp.utilities.types import Audio, File, Image
class TestToolFromFunction:
def test_basic_function(self):
"""Test registering and running a basic function."""
def add(a: int, b: int) -> int:
"""Add two numbers."""
return a + b
tool = Tool.from_function(add)
assert tool.model_dump(exclude_none=True) == snapshot(
{
"name": "add",
"description": "Add two numbers.",
"tags": set(),
"parameters": {
"additionalProperties": False,
"properties": {
"a": {"type": "integer"},
"b": {"type": "integer"},
},
"required": ["a", "b"],
"type": "object",
},
"output_schema": {
"properties": {"result": {"type": "integer"}},
"required": ["result"],
"type": "object",
"x-fastmcp-wrap-result": True,
},
"fn": HasName("add"),
"task_config": {
"mode": "forbidden",
"poll_interval": timedelta(seconds=5),
},
}
)
def test_meta_parameter(self):
"""Test that meta parameter is properly handled."""
def multiply(a: int, b: int) -> int:
"""Multiply two numbers."""
return a * b
meta_data = {"version": "1.0", "author": "test"}
tool = Tool.from_function(multiply, meta=meta_data)
assert tool.meta == meta_data
mcp_tool = tool.to_mcp_tool()
# MCP tool includes fastmcp meta, so check that our meta is included
assert mcp_tool.meta is not None
assert meta_data.items() <= mcp_tool.meta.items()
async def test_async_function(self):
"""Test registering and running an async function."""
async def fetch_data(url: str) -> str:
"""Fetch data from URL."""
return f"Data from {url}"
tool = Tool.from_function(fetch_data)
assert tool.model_dump(exclude_none=True) == snapshot(
{
"name": "fetch_data",
"description": "Fetch data from URL.",
"tags": set(),
"parameters": {
"additionalProperties": False,
"properties": {"url": {"type": "string"}},
"required": ["url"],
"type": "object",
},
"output_schema": {
"properties": {"result": {"type": "string"}},
"required": ["result"],
"type": "object",
"x-fastmcp-wrap-result": True,
},
"fn": HasName("fetch_data"),
"task_config": {
"mode": "forbidden",
"poll_interval": timedelta(seconds=5),
},
}
)
def test_callable_object(self):
class Adder:
"""Adds two numbers."""
def __call__(self, x: int, y: int) -> int:
"""ignore this"""
return x + y
tool = Tool.from_function(Adder())
assert tool.model_dump(exclude_none=True, exclude={"fn"}) == snapshot(
{
"name": "Adder",
"description": "Adds two numbers.",
"tags": set(),
"parameters": {
"additionalProperties": False,
"properties": {
"x": {"type": "integer"},
"y": {"type": "integer"},
},
"required": ["x", "y"],
"type": "object",
},
"output_schema": {
"properties": {"result": {"type": "integer"}},
"required": ["result"],
"type": "object",
"x-fastmcp-wrap-result": True,
},
"task_config": {
"mode": "forbidden",
"poll_interval": timedelta(seconds=5),
},
}
)
def test_async_callable_object(self):
class Adder:
"""Adds two numbers."""
async def __call__(self, x: int, y: int) -> int:
"""ignore this"""
return x + y
tool = Tool.from_function(Adder())
assert tool.model_dump(exclude_none=True, exclude={"fn"}) == snapshot(
{
"name": "Adder",
"description": "Adds two numbers.",
"tags": set(),
"parameters": {
"additionalProperties": False,
"properties": {
"x": {"type": "integer"},
"y": {"type": "integer"},
},
"required": ["x", "y"],
"type": "object",
},
"output_schema": {
"properties": {"result": {"type": "integer"}},
"required": ["result"],
"type": "object",
"x-fastmcp-wrap-result": True,
},
"task_config": {
"mode": "forbidden",
"poll_interval": timedelta(seconds=5),
},
}
)
def test_pydantic_model_function(self):
"""Test registering a function that takes a Pydantic model."""
class UserInput(BaseModel):
name: str
age: int
def create_user(user: UserInput, flag: bool) -> dict:
"""Create a new user."""
return {"id": 1, **user.model_dump()}
tool = Tool.from_function(create_user)
assert tool.model_dump(exclude_none=True) == snapshot(
{
"name": "create_user",
"description": "Create a new user.",
"tags": set(),
"parameters": {
"$defs": {
"UserInput": {
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
},
"required": ["name", "age"],
"type": "object",
},
},
"additionalProperties": False,
"properties": {
"user": {"$ref": "#/$defs/UserInput"},
"flag": {"type": "boolean"},
},
"required": ["user", "flag"],
"type": "object",
},
"output_schema": {"additionalProperties": True, "type": "object"},
"fn": HasName("create_user"),
"task_config": {
"mode": "forbidden",
"poll_interval": timedelta(seconds=5),
},
}
)
async def test_tool_with_image_return(self):
def image_tool(data: bytes) -> Image:
return Image(data=data)
tool = Tool.from_function(image_tool)
assert tool.parameters["properties"]["data"]["type"] == "string"
assert tool.output_schema is None
result = await tool.run({"data": "test.png"})
assert isinstance(result.content[0], ImageContent)
async def test_tool_with_audio_return(self):
def audio_tool(data: bytes) -> Audio:
return Audio(data=data)
tool = Tool.from_function(audio_tool)
assert tool.parameters["properties"]["data"]["type"] == "string"
assert tool.output_schema is None
result = await tool.run({"data": "test.wav"})
assert isinstance(result.content[0], AudioContent)
async def test_tool_with_file_return(self):
from pydantic import AnyUrl
def file_tool(data: bytes) -> File:
return File(data=data, format="octet-stream")
tool = Tool.from_function(file_tool)
assert tool.parameters["properties"]["data"]["type"] == "string"
assert tool.output_schema is None
result: ToolResult = await tool.run({"data": "test.bin"})
assert result.content[0].model_dump(exclude_none=True) == snapshot(
{
"type": "resource",
"resource": {
"uri": AnyUrl("file:///resource.octet-stream"),
"mimeType": "application/octet-stream",
"blob": "dGVzdC5iaW4=",
},
}
)
def test_non_callable_fn(self):
with pytest.raises(TypeError, match="not a callable object"):
Tool.from_function(1) # type: ignore
def test_lambda(self):
tool = Tool.from_function(lambda x: x, name="my_tool")
assert tool.model_dump(exclude_none=True, exclude={"fn"}) == snapshot(
{
"name": "my_tool",
"tags": set(),
"parameters": {
"additionalProperties": False,
"properties": {"x": {"title": "X"}},
"required": ["x"],
"type": "object",
},
"task_config": {
"mode": "forbidden",
"poll_interval": timedelta(seconds=5),
},
}
)
def test_lambda_with_no_name(self):
with pytest.raises(
ValueError, match="You must provide a name for lambda functions"
):
Tool.from_function(lambda x: x)
def test_private_arguments(self):
def add(_a: int, _b: int) -> int:
"""Add two numbers."""
return _a + _b
tool = Tool.from_function(add)
assert tool.model_dump(
exclude_none=True, exclude={"output_schema", "fn"}
) == snapshot(
{
"name": "add",
"description": "Add two numbers.",
"tags": set(),
"parameters": {
"additionalProperties": False,
"properties": {
"_a": {"type": "integer"},
"_b": {"type": "integer"},
},
"required": ["_a", "_b"],
"type": "object",
},
"task_config": {
"mode": "forbidden",
"poll_interval": timedelta(seconds=5),
},
}
)
def test_tool_with_varargs_not_allowed(self):
def func(a: int, b: int, *args: int) -> int:
"""Add two numbers."""
return a + b
with pytest.raises(
ValueError, match=r"Functions with \*args are not supported as tools"
):
Tool.from_function(func)
def test_tool_with_varkwargs_not_allowed(self):
def func(a: int, b: int, **kwargs: int) -> int:
"""Add two numbers."""
return a + b
with pytest.raises(
ValueError, match=r"Functions with \*\*kwargs are not supported as tools"
):
Tool.from_function(func)
async def test_instance_method(self):
class MyClass:
def add(self, x: int, y: int) -> int:
"""Add two numbers."""
return x + y
obj = MyClass()
tool = Tool.from_function(obj.add)
assert "self" not in tool.parameters["properties"]
assert tool.model_dump(exclude_none=True, exclude={"fn"}) == snapshot(
{
"name": "add",
"description": "Add two numbers.",
"tags": set(),
"parameters": {
"additionalProperties": False,
"properties": {
"x": {"type": "integer"},
"y": {"type": "integer"},
},
"required": ["x", "y"],
"type": "object",
},
"output_schema": {
"properties": {"result": {"type": "integer"}},
"required": ["result"],
"type": "object",
"x-fastmcp-wrap-result": True,
},
"task_config": {
"mode": "forbidden",
"poll_interval": timedelta(seconds=5),
},
}
)
async def test_instance_method_with_varargs_not_allowed(self):
class MyClass:
def add(self, x: int, y: int, *args: int) -> int:
"""Add two numbers."""
return x + y
obj = MyClass()
with pytest.raises(
ValueError, match=r"Functions with \*args are not supported as tools"
):
Tool.from_function(obj.add)
async def test_instance_method_with_varkwargs_not_allowed(self):
class MyClass:
def add(self, x: int, y: int, **kwargs: int) -> int:
"""Add two numbers."""
return x + y
obj = MyClass()
with pytest.raises(
ValueError, match=r"Functions with \*\*kwargs are not supported as tools"
):
Tool.from_function(obj.add)
async def test_classmethod(self):
class MyClass:
x: int = 10
@classmethod
def call(cls, x: int, y: int) -> int:
"""Add two numbers."""
return x + y
tool = Tool.from_function(MyClass.call)
assert tool.name == "call"
assert tool.description == "Add two numbers."
assert "x" in tool.parameters["properties"]
assert "y" in tool.parameters["properties"]
class TestToolNameValidation:
"""Tests for tool name validation per MCP specification (SEP-986)."""
@pytest.fixture
def caplog_for_mcp_validation(self, caplog):
"""Capture logs from the MCP SDK's tool name validation logger."""
import logging
caplog.set_level(logging.WARNING)
logger = logging.getLogger("mcp.shared.tool_name_validation")
original_level = logger.level
logger.setLevel(logging.WARNING)
logger.addHandler(caplog.handler)
try:
yield caplog
finally:
logger.removeHandler(caplog.handler)
logger.setLevel(original_level)
@pytest.mark.parametrize(
"name",
[
"valid_tool",
"valid-tool",
"valid.tool",
"ValidTool",
"tool123",
"a",
"a" * 128,
],
)
def test_valid_tool_names_no_warnings(self, name, caplog_for_mcp_validation):
"""Valid tool names should not produce warnings."""
def fn() -> str:
return "test"
tool = Tool.from_function(fn, name=name)
assert tool.name == name
assert "Tool name validation warning" not in caplog_for_mcp_validation.text
def test_tool_name_with_spaces_warns(self, caplog_for_mcp_validation):
"""Tool names with spaces should produce a warning."""
def fn() -> str:
return "test"
tool = Tool.from_function(fn, name="my tool")
assert tool.name == "my tool"
assert "Tool name validation warning" in caplog_for_mcp_validation.text
assert "contains spaces" in caplog_for_mcp_validation.text
def test_tool_name_with_invalid_chars_warns(self, caplog_for_mcp_validation):
"""Tool names with invalid characters should produce a warning."""
def fn() -> str:
return "test"
tool = Tool.from_function(fn, name="tool@name!")
assert tool.name == "tool@name!"
assert "Tool name validation warning" in caplog_for_mcp_validation.text
assert "invalid characters" in caplog_for_mcp_validation.text
def test_tool_name_too_long_warns(self, caplog_for_mcp_validation):
"""Tool names exceeding 128 characters should produce a warning."""
def fn() -> str:
return "test"
long_name = "a" * 129
tool = Tool.from_function(fn, name=long_name)
assert tool.name == long_name
assert "Tool name validation warning" in caplog_for_mcp_validation.text
assert "exceeds maximum length" in caplog_for_mcp_validation.text
def test_tool_name_with_leading_dash_warns(self, caplog_for_mcp_validation):
"""Tool names starting with dash should produce a warning."""
def fn() -> str:
return "test"
tool = Tool.from_function(fn, name="-tool")
assert tool.name == "-tool"
assert "Tool name validation warning" in caplog_for_mcp_validation.text
assert "starts or ends with a dash" in caplog_for_mcp_validation.text
def test_tool_still_created_despite_warnings(self, caplog_for_mcp_validation):
"""Tools with invalid names should still be created (SHOULD not MUST)."""
def add(a: int, b: int) -> int:
return a + b
tool = Tool.from_function(add, name="invalid tool name!")
assert tool.name == "invalid tool name!"
assert tool.parameters is not None
assert "a" in tool.parameters["properties"]
assert "b" in tool.parameters["properties"]
class TestToolExecutionField:
"""Tests for the execution field on the base Tool class."""
def test_tool_with_execution_field(self):
"""Test that Tool can store and return execution metadata."""
tool = Tool(
name="my_tool",
description="A tool with execution",
parameters={"type": "object", "properties": {}},
execution=ToolExecution(taskSupport="optional"),
)
mcp_tool = tool.to_mcp_tool()
assert mcp_tool.execution is not None
assert mcp_tool.execution.taskSupport == "optional"
def test_tool_without_execution_field(self):
"""Test that Tool without execution returns None."""
tool = Tool(
name="my_tool",
description="A tool without execution",
parameters={"type": "object", "properties": {}},
)
mcp_tool = tool.to_mcp_tool()
assert mcp_tool.execution is None
def test_execution_override_takes_precedence(self):
"""Test that explicit override takes precedence over field value."""
tool = Tool(
name="my_tool",
description="A tool",
parameters={"type": "object", "properties": {}},
execution=ToolExecution(taskSupport="optional"),
)
override_execution = ToolExecution(taskSupport="required")
mcp_tool = tool.to_mcp_tool(execution=override_execution)
assert mcp_tool.execution is not None
assert mcp_tool.execution.taskSupport == "required"
async def test_function_tool_task_config_still_works(self):
"""FunctionTool should still derive execution from task_config."""
async def my_fn() -> str:
return "hello"
tool = Tool.from_function(my_fn, task=True)
mcp_tool = tool.to_mcp_tool()
# FunctionTool sets execution from task_config
assert mcp_tool.execution is not None
assert mcp_tool.execution.taskSupport == "optional"
def test_tool_execution_required_mode(self):
"""Test that Tool can store required execution mode."""
tool = Tool(
name="my_tool",
description="A tool with required execution",
parameters={"type": "object", "properties": {}},
execution=ToolExecution(taskSupport="required"),
)
mcp_tool = tool.to_mcp_tool()
assert mcp_tool.execution is not None
assert mcp_tool.execution.taskSupport == "required"
def test_tool_execution_forbidden_mode(self):
"""Test that Tool can store forbidden execution mode."""
tool = Tool(
name="my_tool",
description="A tool with forbidden execution",
parameters={"type": "object", "properties": {}},
execution=ToolExecution(taskSupport="forbidden"),
)
mcp_tool = tool.to_mcp_tool()
assert mcp_tool.execution is not None
assert mcp_tool.execution.taskSupport == "forbidden"
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/tools/tool/test_tool.py",
"license": "Apache License 2.0",
"lines": 506,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/tools/tool_transform/test_args.py | """Tests for argument transformation in tool transforms."""
from dataclasses import dataclass
from typing import Annotated, Any
import pytest
from mcp.types import TextContent
from pydantic import BaseModel, Field
from typing_extensions import TypedDict
from fastmcp import FastMCP
from fastmcp.client.client import Client
from fastmcp.exceptions import ToolError
from fastmcp.tools import Tool, forward, forward_raw
from fastmcp.tools.function_tool import FunctionTool
from fastmcp.tools.tool_transform import (
ArgTransform,
)
def get_property(tool: Tool, name: str) -> dict[str, Any]:
return tool.parameters["properties"][name]
@pytest.fixture
def add_tool() -> FunctionTool:
def add(
old_x: Annotated[int, Field(description="old_x description")], old_y: int = 10
) -> int:
print("running!")
return old_x + old_y
return Tool.from_function(add)
async def test_tool_transform_chaining(add_tool):
"""Test that transformed tools can be transformed again."""
# First transformation: a -> x
tool1 = Tool.from_tool(add_tool, transform_args={"old_x": ArgTransform(name="x")})
# Second transformation: x -> final_x, using tool1
tool2 = Tool.from_tool(tool1, transform_args={"x": ArgTransform(name="final_x")})
result = await tool2.run(arguments={"final_x": 5})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "15"
# Transform tool1 with custom function that handles all parameters
async def custom(final_x: int, **kwargs) -> str:
result = await forward(final_x=final_x, **kwargs)
assert isinstance(result.content[0], TextContent)
return f"custom {result.content[0].text}" # Extract text from content
tool3 = Tool.from_tool(
tool1, transform_fn=custom, transform_args={"x": ArgTransform(name="final_x")}
)
result = await tool3.run(arguments={"final_x": 3, "old_y": 5})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "custom 8"
class MyModel(BaseModel):
x: int
y: str
@dataclass
class MyDataclass:
x: int
y: str
class MyTypedDict(TypedDict):
x: int
y: str
@pytest.mark.parametrize(
"py_type, json_type",
[
(int, "integer"),
(str, "string"),
(float, "number"),
(bool, "boolean"),
(MyModel, "object"),
(MyDataclass, "object"),
(MyTypedDict, "object"),
],
)
def test_arg_transform_type_handling(add_tool, py_type, json_type):
new_tool = Tool.from_tool(
add_tool, transform_args={"old_x": ArgTransform(type=py_type)}
)
prop = get_property(new_tool, "old_x")
assert prop["type"] == json_type
def test_arg_transform_annotated_types(add_tool):
new_tool = Tool.from_tool(
add_tool,
transform_args={
"old_x": ArgTransform(
type=Annotated[int, Field(ge=0, le=100)], description="A number 0-100"
)
},
)
prop = get_property(new_tool, "old_x")
assert prop["type"] == "integer"
assert prop["description"] == "A number 0-100"
assert prop["minimum"] == 0
assert prop["maximum"] == 100
def test_arg_transform_precedence_over_function_without_kwargs():
def base(x: int) -> int:
return x
tool = Tool.from_function(base)
new_tool = Tool.from_tool(
tool, transform_args={"x": ArgTransform(type=str, description="String input")}
)
prop = get_property(new_tool, "x")
assert prop["type"] == "string"
assert prop["description"] == "String input"
async def test_arg_transform_precedence_over_function_with_kwargs():
"""Test that ArgTransform attributes take precedence over function signature (with **kwargs)."""
@Tool.from_function
def base(x: int, y: str = "base_default") -> str:
return f"{x}: {y}"
# Function signature has different types/defaults than ArgTransform
async def custom_fn(x: str = "function_default", **kwargs) -> str:
result = await forward(x=x, **kwargs)
assert isinstance(result.content[0], TextContent)
return f"custom: {result.content[0].text}"
tool = Tool.from_tool(
base,
transform_fn=custom_fn,
transform_args={
"x": ArgTransform(type=int, default=42), # Different type and default
"y": ArgTransform(description="ArgTransform description"),
},
)
# ArgTransform should take precedence
x_prop = get_property(tool, "x")
y_prop = get_property(tool, "y")
assert x_prop["type"] == "integer" # ArgTransform type wins over function's str
assert x_prop["default"] == 42 # ArgTransform default wins over function's default
assert (
y_prop["description"] == "ArgTransform description"
) # ArgTransform description
# x should not be required due to ArgTransform default
assert "x" not in tool.parameters["required"]
# Test it works at runtime
result = await tool.run(arguments={"y": "test"})
# Should use ArgTransform default of 42
assert isinstance(result.content[0], TextContent)
assert "42: test" in result.content[0].text
def test_arg_transform_combined_attributes(add_tool):
new_tool = Tool.from_tool(
add_tool,
transform_args={
"old_x": ArgTransform(
name="new_x",
description="New description",
type=str,
)
},
)
prop = get_property(new_tool, "new_x")
assert prop["type"] == "string"
assert prop["description"] == "New description"
assert "old_x" not in new_tool.parameters["properties"]
async def test_arg_transform_type_precedence_runtime():
"""Test that ArgTransform type changes work correctly at runtime."""
@Tool.from_function
def base(x: int, y: int = 10) -> int:
return x + y
# Transform x to string type but keep same logic
async def custom_fn(x: str, y: int = 10) -> str:
# Convert string back to int for the original function
result = await forward_raw(x=int(x), y=y)
# Extract the text from the result
assert isinstance(result.content[0], TextContent)
result_text = result.content[0].text
return f"String input '{x}' converted to result: {result_text}"
tool = Tool.from_tool(
base, transform_fn=custom_fn, transform_args={"x": ArgTransform(type=str)}
)
# Verify schema shows string type
assert get_property(tool, "x")["type"] == "string"
# Test it works with string input
result = await tool.run(arguments={"x": "5", "y": 3})
assert isinstance(result.content[0], TextContent)
assert "String input '5'" in result.content[0].text
assert "result: 8" in result.content[0].text
async def test_arg_transform_default_factory():
"""Test ArgTransform with default_factory for hidden parameters."""
import asyncio
import time
@Tool.from_function
def base_tool(x: int, timestamp: float) -> str:
return f"{x}_{timestamp}"
new_tool = Tool.from_tool(
base_tool,
transform_args={
"timestamp": ArgTransform(hide=True, default_factory=time.time)
},
)
result1 = await new_tool.run(arguments={"x": 1})
await asyncio.sleep(0.01)
result2 = await new_tool.run(arguments={"x": 2})
# Each call should get a different timestamp
assert isinstance(result1.content[0], TextContent)
assert isinstance(result2.content[0], TextContent)
assert result1.content[0].text != result2.content[0].text
assert "1_" in result1.content[0].text
assert "2_" in result2.content[0].text
async def test_arg_transform_default_factory_called_each_time():
"""Test that default_factory is called for each tool execution."""
call_count = {"count": 0}
def get_counter():
call_count["count"] += 1
return call_count["count"]
@Tool.from_function
def base_tool(x: int, counter: int) -> str:
return f"{x}_{counter}"
new_tool = Tool.from_tool(
base_tool,
transform_args={
"counter": ArgTransform(hide=True, default_factory=get_counter)
},
)
result1 = await new_tool.run(arguments={"x": 1})
result2 = await new_tool.run(arguments={"x": 2})
result3 = await new_tool.run(arguments={"x": 3})
# Each call should increment the counter
assert isinstance(result1.content[0], TextContent)
assert isinstance(result2.content[0], TextContent)
assert isinstance(result3.content[0], TextContent)
assert "1_1" in result1.content[0].text
assert "2_2" in result2.content[0].text
assert "3_3" in result3.content[0].text
async def test_arg_transform_hidden_with_default_factory():
"""Test that hidden parameters with default_factory work correctly."""
@Tool.from_function
def base_tool(x: int, session_id: str) -> str:
return f"{x}_{session_id}"
import uuid
new_tool = Tool.from_tool(
base_tool,
transform_args={
"session_id": ArgTransform(
hide=True, default_factory=lambda: str(uuid.uuid4())
)
},
)
result = await new_tool.run(arguments={"x": 1})
# Should have a UUID in the result
assert isinstance(result.content[0], TextContent)
assert "1_" in result.content[0].text
assert len(result.content[0].text.split("_")[1]) > 10
async def test_arg_transform_default_and_factory_raises_error():
"""Test that providing both default and default_factory raises an error."""
with pytest.raises(
ValueError, match="Cannot specify both 'default' and 'default_factory'"
):
ArgTransform(default=10, default_factory=lambda: 20)
async def test_arg_transform_default_factory_requires_hide():
"""Test that default_factory requires hide=True."""
with pytest.raises(
ValueError, match="default_factory can only be used with hide=True"
):
ArgTransform(default_factory=lambda: 10)
async def test_arg_transform_required_true(add_tool):
"""Test ArgTransform with required=True."""
new_tool = Tool.from_tool(
add_tool,
transform_args={"old_y": ArgTransform(required=True)},
)
# old_y should now be required (even though it had a default)
assert "old_y" in new_tool.parameters["required"]
async def test_arg_transform_required_false():
"""Test ArgTransform with required=False by setting a default."""
def func(x: int, y: int) -> int:
return x + y
tool = Tool.from_function(func)
# Setting a default makes it not required
new_tool = Tool.from_tool(tool, transform_args={"y": ArgTransform(default=0)})
# y should not be required since it has a default
assert "y" not in new_tool.parameters.get("required", [])
async def test_arg_transform_required_with_rename(add_tool):
"""Test ArgTransform with required and rename."""
new_tool = Tool.from_tool(
add_tool,
transform_args={"old_y": ArgTransform(name="new_y", required=True)},
)
# new_y should be required
assert "new_y" in new_tool.parameters["required"]
assert "old_y" not in new_tool.parameters["properties"]
async def test_arg_transform_required_true_with_default_raises_error():
"""Test that required=True with default raises an error."""
with pytest.raises(
ValueError, match="Cannot specify 'required=True' with 'default'"
):
ArgTransform(required=True, default=42)
async def test_arg_transform_required_true_with_factory_raises_error():
"""Test that required=True with default_factory raises an error."""
with pytest.raises(
ValueError, match="default_factory can only be used with hide=True"
):
ArgTransform(required=True, default_factory=lambda: 42)
async def test_arg_transform_required_no_change():
"""Test that not specifying required doesn't change existing required status."""
def func(x: int, y: int) -> int:
return x + y
tool = Tool.from_function(func)
# Both x and y are required in original
assert "x" in tool.parameters["required"]
assert "y" in tool.parameters["required"]
# Not specifying required should keep x required
new_tool = Tool.from_tool(
tool, transform_args={"x": ArgTransform(description="Updated x")}
)
# x should still be required, and y should still be
assert "x" in new_tool.parameters.get("required", [])
assert "y" in new_tool.parameters["required"]
async def test_arg_transform_hide_and_required_raises_error():
"""Test that hide=True and required=True together raises an error."""
with pytest.raises(
ValueError, match="Cannot specify both 'hide=True' and 'required=True'"
):
ArgTransform(hide=True, required=True)
class TestEnableDisable:
async def test_transform_disabled_tool(self):
"""
Tests that a transformed tool can run even if the parent tool is disabled via server.
"""
mcp = FastMCP()
@mcp.tool
def add(x: int, y: int = 10) -> int:
return x + y
# Get the registered Tool object from the server
add_tool = await mcp._local_provider.get_tool("add")
assert isinstance(add_tool, Tool)
new_add = Tool.from_tool(add_tool, name="new_add")
mcp.add_tool(new_add)
# Disable original tool, but new_add should still work
mcp.disable(names={"add"}, components={"tool"})
async with Client(mcp) as client:
tools = await client.list_tools()
assert {tool.name for tool in tools} == {"new_add"}
result = await client.call_tool("new_add", {"x": 1, "y": 2})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "3"
with pytest.raises(ToolError):
await client.call_tool("add", {"x": 1, "y": 2})
async def test_disable_transformed_tool(self):
mcp = FastMCP()
@mcp.tool
def add(x: int, y: int = 10) -> int:
return x + y
# Get the registered Tool object from the server
add_tool = await mcp._local_provider.get_tool("add")
assert isinstance(add_tool, Tool)
new_add = Tool.from_tool(add_tool, name="new_add")
mcp.add_tool(new_add)
# Disable both tools via server
mcp.disable(names={"add"}, components={"tool"}).disable(
names={"new_add"}, components={"tool"}
)
async with Client(mcp) as client:
tools = await client.list_tools()
assert len(tools) == 0
with pytest.raises(ToolError):
await client.call_tool("new_add", {"x": 1, "y": 2})
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/tools/tool_transform/test_args.py",
"license": "Apache License 2.0",
"lines": 348,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/tools/tool_transform/test_metadata.py | from typing import Annotated, Any
import pytest
from pydantic import Field
from fastmcp.tools import Tool
from fastmcp.tools.function_tool import FunctionTool
from fastmcp.tools.tool_transform import (
ToolTransformConfig,
)
def get_property(tool: Tool, name: str) -> dict[str, Any]:
return tool.parameters["properties"][name]
@pytest.fixture
def add_tool() -> FunctionTool:
def add(
old_x: Annotated[int, Field(description="old_x description")], old_y: int = 10
) -> int:
print("running!")
return old_x + old_y
return Tool.from_function(add)
@pytest.fixture
def sample_tool():
"""Sample tool for testing transformations."""
def sample_func(x: int) -> str:
return f"Result: {x}"
return Tool.from_function(
sample_func,
name="sample_tool",
title="Original Tool Title",
description="Original description",
)
@pytest.fixture
def sample_tool_no_title():
"""Sample tool without title for testing."""
def sample_func(x: int) -> str:
return f"Result: {x}"
return Tool.from_function(sample_func, name="no_title_tool")
def test_transform_inherits_title(sample_tool):
"""Test that transformed tools inherit title when none specified."""
transformed = Tool.from_tool(sample_tool)
assert transformed.title == "Original Tool Title"
def test_transform_overrides_title(sample_tool):
"""Test that transformed tools can override title."""
transformed = Tool.from_tool(sample_tool, title="New Tool Title")
assert transformed.title == "New Tool Title"
def test_transform_sets_title_to_none(sample_tool):
"""Test that transformed tools can explicitly set title to None."""
transformed = Tool.from_tool(sample_tool, title=None)
assert transformed.title is None
def test_transform_inherits_none_title(sample_tool_no_title):
"""Test that transformed tools inherit None title."""
transformed = Tool.from_tool(sample_tool_no_title)
assert transformed.title is None
def test_transform_adds_title_to_none(sample_tool_no_title):
"""Test that transformed tools can add title when parent has None."""
transformed = Tool.from_tool(sample_tool_no_title, title="Added Title")
assert transformed.title == "Added Title"
def test_transform_inherits_description(sample_tool):
"""Test that transformed tools inherit description when none specified."""
transformed = Tool.from_tool(sample_tool)
assert transformed.description == "Original description"
def test_transform_overrides_description(sample_tool):
"""Test that transformed tools can override description."""
transformed = Tool.from_tool(sample_tool, description="New description")
assert transformed.description == "New description"
def test_transform_sets_description_to_none(sample_tool):
"""Test that transformed tools can explicitly set description to None."""
transformed = Tool.from_tool(sample_tool, description=None)
assert transformed.description is None
def test_transform_inherits_none_description(sample_tool_no_title):
"""Test that transformed tools inherit None description."""
transformed = Tool.from_tool(sample_tool_no_title)
assert transformed.description is None
def test_transform_adds_description_to_none(sample_tool_no_title):
"""Test that transformed tools can add description when parent has None."""
transformed = Tool.from_tool(sample_tool_no_title, description="Added description")
assert transformed.description == "Added description"
# Meta transformation tests
def test_transform_inherits_meta(sample_tool):
"""Test that transformed tools inherit meta when none specified."""
sample_tool.meta = {"original": True, "version": "1.0"}
transformed = Tool.from_tool(sample_tool)
assert transformed.meta == {"original": True, "version": "1.0"}
def test_transform_overrides_meta(sample_tool):
"""Test that transformed tools can override meta."""
sample_tool.meta = {"original": True, "version": "1.0"}
transformed = Tool.from_tool(sample_tool, meta={"custom": True, "priority": "high"})
assert transformed.meta == {"custom": True, "priority": "high"}
def test_transform_sets_meta_to_none(sample_tool):
"""Test that transformed tools can explicitly set meta to None."""
sample_tool.meta = {"original": True, "version": "1.0"}
transformed = Tool.from_tool(sample_tool, meta=None)
assert transformed.meta is None
def test_transform_inherits_none_meta(sample_tool_no_title):
"""Test that transformed tools inherit None meta."""
sample_tool_no_title.meta = None
transformed = Tool.from_tool(sample_tool_no_title)
assert transformed.meta is None
def test_transform_adds_meta_to_none(sample_tool_no_title):
"""Test that transformed tools can add meta when parent has None."""
sample_tool_no_title.meta = None
transformed = Tool.from_tool(sample_tool_no_title, meta={"added": True})
assert transformed.meta == {"added": True}
def test_tool_transform_config_inherits_meta(sample_tool):
"""Test that ToolTransformConfig inherits meta when unset."""
sample_tool.meta = {"original": True, "version": "1.0"}
config = ToolTransformConfig(name="config_tool")
transformed = config.apply(sample_tool)
assert transformed.meta == {"original": True, "version": "1.0"}
def test_tool_transform_config_overrides_meta(sample_tool):
"""Test that ToolTransformConfig can override meta."""
sample_tool.meta = {"original": True, "version": "1.0"}
config = ToolTransformConfig(
name="config_tool", meta={"config": True, "priority": "high"}
)
transformed = config.apply(sample_tool)
assert transformed.meta == {"config": True, "priority": "high"}
def test_tool_transform_config_removes_meta(sample_tool):
"""Test that ToolTransformConfig can remove meta with None."""
sample_tool.meta = {"original": True, "version": "1.0"}
config = ToolTransformConfig(name="config_tool", meta=None)
transformed = config.apply(sample_tool)
assert transformed.meta is None
# Enabled field tests
def test_tool_transform_config_enabled_defaults_to_true(sample_tool):
"""Test that enabled defaults to True and no visibility metadata is set."""
config = ToolTransformConfig(name="enabled_tool")
transformed = config.apply(sample_tool)
# No visibility metadata should be set when enabled=True (default)
meta = transformed.meta or {}
internal = meta.get("fastmcp", {}).get("_internal", {})
assert "visibility" not in internal
def test_tool_transform_config_enabled_false_sets_visibility_metadata(sample_tool):
"""Test that enabled=False sets visibility metadata to hide the tool."""
from fastmcp.server.transforms.visibility import is_enabled
config = ToolTransformConfig(name="disabled_tool", enabled=False)
transformed = config.apply(sample_tool)
# The is_enabled helper should return False
assert is_enabled(transformed) is False
# Check the raw metadata structure
assert transformed.meta is not None
assert transformed.meta["fastmcp"]["_internal"]["visibility"] is False
def test_tool_transform_config_enabled_true_explicit_sets_visibility(sample_tool):
"""Test that enabled=True explicitly sets visibility metadata to allow overriding earlier disables."""
from fastmcp.server.transforms.visibility import is_enabled
config = ToolTransformConfig(name="explicit_enabled", enabled=True)
transformed = config.apply(sample_tool)
# Visibility metadata should be set to True when enabled=True is explicit
# This allows later transforms to override earlier disables
assert is_enabled(transformed) is True
assert transformed.meta is not None
assert transformed.meta["fastmcp"]["_internal"]["visibility"] is True
def test_tool_transform_config_enabled_false_preserves_existing_meta(sample_tool):
"""Test that enabled=False preserves existing meta while adding visibility."""
from fastmcp.server.transforms.visibility import is_enabled
sample_tool.meta = {"custom_key": "custom_value"}
config = ToolTransformConfig(enabled=False)
transformed = config.apply(sample_tool)
# Original meta should be preserved
assert transformed.meta is not None
assert transformed.meta["custom_key"] == "custom_value"
# Visibility should be set
assert is_enabled(transformed) is False
def test_tool_transform_config_enabled_false_merges_with_config_meta(sample_tool):
"""Test that enabled=False works with explicit meta override."""
from fastmcp.server.transforms.visibility import is_enabled
sample_tool.meta = {"original": True}
config = ToolTransformConfig(meta={"overridden": True}, enabled=False)
transformed = config.apply(sample_tool)
# Config meta should override original
assert transformed.meta is not None
assert "original" not in transformed.meta
assert transformed.meta["overridden"] is True
# But visibility should still be set
assert is_enabled(transformed) is False
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/tools/tool_transform/test_metadata.py",
"license": "Apache License 2.0",
"lines": 173,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/tools/tool_transform/test_schemas.py | from typing import Annotated, Any
import pytest
from dirty_equals import IsList
from inline_snapshot import snapshot
from mcp.types import TextContent
from pydantic import BaseModel, Field, TypeAdapter
from fastmcp.tools import Tool, forward
from fastmcp.tools.function_tool import FunctionTool
from fastmcp.tools.tool import ToolResult
from fastmcp.tools.tool_transform import (
ArgTransform,
TransformedTool,
)
def get_property(tool: Tool, name: str) -> dict[str, Any]:
return tool.parameters["properties"][name]
@pytest.fixture
def add_tool() -> FunctionTool:
def add(
old_x: Annotated[int, Field(description="old_x description")], old_y: int = 10
) -> int:
print("running!")
return old_x + old_y
return Tool.from_function(add)
class TestTransformToolOutputSchema:
"""Test output schema handling in transformed tools."""
@pytest.fixture
def base_string_tool(self) -> FunctionTool:
"""Tool that returns a string (gets wrapped)."""
def string_tool(x: int) -> str:
return f"Result: {x}"
return Tool.from_function(string_tool)
@pytest.fixture
def base_dict_tool(self) -> FunctionTool:
"""Tool that returns a dict (object type, not wrapped)."""
def dict_tool(x: int) -> dict[str, int]:
return {"value": x}
return Tool.from_function(dict_tool)
def test_transform_inherits_parent_output_schema(self, base_string_tool):
"""Test that transformed tool inherits parent's output schema by default."""
new_tool = Tool.from_tool(base_string_tool)
# Should inherit parent's wrapped string schema
expected_schema = {
"type": "object",
"properties": {"result": {"type": "string"}},
"required": ["result"],
"x-fastmcp-wrap-result": True,
}
assert new_tool.output_schema == expected_schema
assert new_tool.output_schema == base_string_tool.output_schema
def test_transform_with_explicit_output_schema_none(self, base_string_tool):
"""Test that output_schema=None sets output schema to None."""
new_tool = Tool.from_tool(base_string_tool, output_schema=None)
assert new_tool.output_schema is None
async def test_transform_output_schema_none_runtime(self, base_string_tool):
"""Test runtime behavior with output_schema=None."""
new_tool = Tool.from_tool(base_string_tool, output_schema=None)
# Debug: check that output_schema is actually None
assert new_tool.output_schema is None, (
f"Expected None, got {new_tool.output_schema}"
)
result = await new_tool.run({"x": 5})
# Even with output_schema=None, structured content should be generated via fallback logic
assert result.structured_content == {"result": "Result: 5"}
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "Result: 5"
def test_transform_with_explicit_output_schema_dict(self, base_string_tool):
"""Test that explicit output schema overrides parent."""
custom_schema = {
"type": "object",
"properties": {"message": {"type": "string"}},
}
new_tool = Tool.from_tool(base_string_tool, output_schema=custom_schema)
assert new_tool.output_schema == custom_schema
assert new_tool.output_schema != base_string_tool.output_schema
async def test_transform_explicit_schema_runtime(self, base_string_tool):
"""Test runtime behavior with explicit output schema."""
custom_schema = {"type": "string", "minLength": 1}
new_tool = Tool.from_tool(base_string_tool, output_schema=custom_schema)
result = await new_tool.run({"x": 10})
# Non-object explicit schemas disable structured content
assert result.structured_content is None
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "Result: 10"
def test_transform_with_custom_function_inferred_schema(self, base_dict_tool):
"""Test that custom function's output schema is inferred."""
async def custom_fn(x: int) -> str:
result = await forward(x=x)
assert isinstance(result.content[0], TextContent)
return f"Custom: {result.content[0].text}"
new_tool = Tool.from_tool(base_dict_tool, transform_fn=custom_fn)
# Should infer string schema from custom function and wrap it
expected_schema = {
"type": "object",
"properties": {"result": {"type": "string"}},
"required": ["result"],
"x-fastmcp-wrap-result": True,
}
assert new_tool.output_schema == expected_schema
async def test_transform_custom_function_runtime(self, base_dict_tool):
"""Test runtime behavior with custom function that has inferred schema."""
async def custom_fn(x: int) -> str:
result = await forward(x=x)
assert isinstance(result.content[0], TextContent)
return f"Custom: {result.content[0].text}"
new_tool = Tool.from_tool(base_dict_tool, transform_fn=custom_fn)
result = await new_tool.run({"x": 3})
# Should wrap string result
assert result.structured_content == {"result": 'Custom: {"value":3}'}
def test_transform_custom_function_fallback_to_parent(self, base_string_tool):
"""Test that custom function without output annotation falls back to parent."""
async def custom_fn(x: int):
# No return annotation - should fallback to parent schema
result = await forward(x=x)
return result
new_tool = Tool.from_tool(base_string_tool, transform_fn=custom_fn)
# Should use parent's schema since custom function has no annotation
assert new_tool.output_schema == base_string_tool.output_schema
def test_transform_custom_function_explicit_overrides(self, base_string_tool):
"""Test that explicit output_schema overrides both custom function and parent."""
async def custom_fn(x: int) -> dict[str, str]:
return {"custom": "value"}
explicit_schema = {"type": "array", "items": {"type": "number"}}
new_tool = Tool.from_tool(
base_string_tool, transform_fn=custom_fn, output_schema=explicit_schema
)
# Explicit schema should win
assert new_tool.output_schema == explicit_schema
async def test_transform_custom_function_object_return(self, base_string_tool):
"""Test custom function returning object type."""
async def custom_fn(x: int) -> dict[str, int]:
await forward(x=x)
return {"original": x, "transformed": x * 2}
new_tool = Tool.from_tool(base_string_tool, transform_fn=custom_fn)
# Object types should not be wrapped
expected_schema = TypeAdapter(dict[str, int]).json_schema()
assert new_tool.output_schema == expected_schema
assert isinstance(new_tool.output_schema, dict)
assert "x-fastmcp-wrap-result" not in new_tool.output_schema
result = await new_tool.run({"x": 4})
# Direct value, not wrapped
assert result.structured_content == {"original": 4, "transformed": 8}
async def test_transform_preserves_wrap_marker_behavior(self, base_string_tool):
"""Test that wrap marker behavior is preserved through transformation."""
new_tool = Tool.from_tool(base_string_tool)
result = await new_tool.run({"x": 7})
# Should wrap because parent schema has wrap marker
assert result.structured_content == {"result": "Result: 7"}
assert isinstance(new_tool.output_schema, dict)
assert "x-fastmcp-wrap-result" in new_tool.output_schema
def test_transform_chained_output_schema_inheritance(self, base_string_tool):
"""Test output schema inheritance through multiple transformations."""
# First transformation keeps parent schema
tool1 = Tool.from_tool(base_string_tool)
assert tool1.output_schema == base_string_tool.output_schema
# Second transformation also inherits
tool2 = Tool.from_tool(tool1)
assert (
tool2.output_schema == tool1.output_schema == base_string_tool.output_schema
)
# Third transformation with explicit override
custom_schema = {"type": "number"}
tool3 = Tool.from_tool(tool2, output_schema=custom_schema)
assert tool3.output_schema == custom_schema
assert tool3.output_schema != tool2.output_schema
async def test_transform_mixed_structured_unstructured_content(
self, base_string_tool
):
"""Test transformation handling of mixed content types."""
async def custom_fn(x: int):
# Return mixed content including ToolResult
if x == 1:
return ["text", {"data": x}]
else:
# Return ToolResult directly
return ToolResult(
content=[TextContent(type="text", text=f"Custom: {x}")],
structured_content={"custom_value": x},
)
new_tool = Tool.from_tool(base_string_tool, transform_fn=custom_fn)
# Test mixed content return
result1 = await new_tool.run({"x": 1})
assert result1.structured_content == {"result": ["text", {"data": 1}]}
# Test ToolResult return
result2 = await new_tool.run({"x": 2})
assert result2.structured_content == {"custom_value": 2}
assert isinstance(result2.content[0], TextContent)
assert result2.content[0].text == "Custom: 2"
def test_transform_output_schema_with_arg_transforms(self, base_string_tool):
"""Test that output schema works correctly with argument transformations."""
async def custom_fn(new_x: int) -> dict[str, str]:
result = await forward(new_x=new_x)
assert isinstance(result.content[0], TextContent)
return {"transformed": result.content[0].text}
new_tool = Tool.from_tool(
base_string_tool,
transform_fn=custom_fn,
transform_args={"x": ArgTransform(name="new_x")},
)
# Should infer object schema from custom function
expected_schema = TypeAdapter(dict[str, str]).json_schema()
assert new_tool.output_schema == expected_schema
async def test_transform_output_schema_default_vs_none(self, base_string_tool):
"""Test default (NotSet) vs explicit None behavior for output_schema in transforms."""
# Default (NotSet) should use smart fallback (inherit from parent)
tool_default = Tool.from_tool(base_string_tool) # default output_schema=NotSet
assert tool_default.output_schema == base_string_tool.output_schema # Inherits
# None should explicitly set output_schema to None but still generate structured content via fallback
tool_explicit_none = Tool.from_tool(base_string_tool, output_schema=None)
assert tool_explicit_none.output_schema is None
# Both should generate structured content now (via different paths)
result_default = await tool_default.run({"x": 5})
result_explicit_none = await tool_explicit_none.run({"x": 5})
assert result_default.structured_content == {
"result": "Result: 5"
} # Inherits wrapping
assert result_explicit_none.structured_content == {
"result": "Result: 5"
} # Generated via fallback logic
assert isinstance(result_default.content[0], TextContent)
assert isinstance(result_explicit_none.content[0], TextContent)
assert result_default.content[0].text == result_explicit_none.content[0].text
async def test_transform_output_schema_with_tool_result_return(
self, base_string_tool
):
"""Test transform when custom function returns ToolResult directly."""
async def custom_fn(x: int) -> ToolResult:
# Custom function returns ToolResult - should bypass schema handling
return ToolResult(
content=[TextContent(type="text", text=f"Direct: {x}")],
structured_content={"direct_value": x, "doubled": x * 2},
)
new_tool = Tool.from_tool(base_string_tool, transform_fn=custom_fn)
# ToolResult return type should result in None output schema
assert new_tool.output_schema is None
result = await new_tool.run({"x": 6})
# Should use ToolResult content directly
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "Direct: 6"
assert result.structured_content == {"direct_value": 6, "doubled": 12}
class TestInputSchema:
"""Test schema definition handling and reference finding."""
def test_arg_transform_examples_in_schema(self, add_tool: Tool):
# Simple example
new_tool = Tool.from_tool(
add_tool,
transform_args={
"old_x": ArgTransform(examples=[1, 2, 3]),
},
)
prop = get_property(new_tool, "old_x")
assert prop["examples"] == [1, 2, 3]
# Nested example (e.g., for array type)
new_tool2 = Tool.from_tool(
add_tool,
transform_args={
"old_x": ArgTransform(examples=[["a", "b"], ["c", "d"]]),
},
)
prop2 = get_property(new_tool2, "old_x")
assert prop2["examples"] == [["a", "b"], ["c", "d"]]
# If not set, should not be present
new_tool3 = Tool.from_tool(
add_tool,
transform_args={
"old_x": ArgTransform(),
},
)
prop3 = get_property(new_tool3, "old_x")
assert "examples" not in prop3
def test_merge_schema_with_defs_precedence(self):
"""Test _merge_schema_with_precedence merges $defs correctly.
Note: compress_schema no longer dereferences $ref by default.
Used definitions are kept in $defs; unused definitions are pruned.
"""
base_schema = {
"type": "object",
"properties": {"field1": {"$ref": "#/$defs/BaseType"}},
"$defs": {
"BaseType": {"type": "string", "description": "base"},
"SharedType": {"type": "integer", "minimum": 0},
},
}
override_schema = {
"type": "object",
"properties": {"field2": {"$ref": "#/$defs/OverrideType"}},
"$defs": {
"OverrideType": {"type": "boolean"},
"SharedType": {"type": "integer", "minimum": 10}, # Override
},
}
transformed_tool_schema = TransformedTool._merge_schema_with_precedence(
base_schema, override_schema
)
# SharedType should no longer be present on the schema (unused)
assert "SharedType" not in transformed_tool_schema.get("$defs", {})
# $ref and $defs are preserved for used definitions
assert transformed_tool_schema == snapshot(
{
"type": "object",
"properties": {
"field1": {"$ref": "#/$defs/BaseType"},
"field2": {"$ref": "#/$defs/OverrideType"},
},
"$defs": {
"BaseType": {"type": "string", "description": "base"},
"OverrideType": {"type": "boolean"},
},
"required": [],
"additionalProperties": False,
}
)
def test_transform_tool_with_complex_defs_pruning(self):
"""Test that tool transformation properly handles hidden params.
Unused type definitions are pruned from $defs when their
corresponding parameters are hidden. Used types remain as $ref.
"""
class UsedType(BaseModel):
value: str
class UnusedType(BaseModel):
other: int
@Tool.from_function
def complex_tool(
used_param: UsedType, unused_param: UnusedType | None = None
) -> str:
return used_param.value
# Transform to hide unused_param
transformed_tool: TransformedTool = Tool.from_tool(
complex_tool, transform_args={"unused_param": ArgTransform(hide=True)}
)
# UnusedType should be pruned from $defs, but UsedType remains
assert "UnusedType" not in transformed_tool.parameters.get("$defs", {})
assert transformed_tool.parameters == snapshot(
{
"type": "object",
"properties": {
"used_param": {"$ref": "#/$defs/UsedType"},
},
"$defs": {
"UsedType": {
"properties": {"value": {"type": "string"}},
"required": ["value"],
"type": "object",
},
},
"required": ["used_param"],
"additionalProperties": False,
}
)
def test_transform_with_custom_function_preserves_needed_types(self):
"""Test that custom transform functions preserve necessary type definitions."""
class InputType(BaseModel):
data: str
class OutputType(BaseModel):
result: str
@Tool.from_function
def base_tool(input_data: InputType) -> OutputType:
return OutputType(result=input_data.data.upper())
async def transform_function(renamed_input: InputType):
return await forward(renamed_input=renamed_input)
# Transform with custom function and argument rename
transformed = Tool.from_tool(
base_tool,
transform_fn=transform_function,
transform_args={"input_data": ArgTransform(name="renamed_input")},
)
# Used type definitions are preserved as $ref/$defs
assert transformed.parameters == snapshot(
{
"type": "object",
"properties": {
"renamed_input": {"$ref": "#/$defs/InputType"},
},
"$defs": {
"InputType": {
"properties": {"data": {"type": "string"}},
"required": ["data"],
"type": "object",
},
},
"required": ["renamed_input"],
"additionalProperties": False,
}
)
def test_chained_transforms_inline_types(self):
"""Test that chained transformations produce correct schemas with $ref/$defs."""
class TypeA(BaseModel):
a: str
class TypeB(BaseModel):
b: int
class TypeC(BaseModel):
c: bool
@Tool.from_function
def base_tool(param_a: TypeA, param_b: TypeB, param_c: TypeC) -> str:
return f"{param_a.a}-{param_b.b}-{param_c.c}"
# First transform: hide param_c
transform1 = Tool.from_tool(
base_tool,
transform_args={"param_c": ArgTransform(hide=True, default=TypeC(c=True))},
)
# TypeC should be pruned from $defs, TypeA and TypeB remain
assert "TypeC" not in transform1.parameters.get("$defs", {})
assert transform1.parameters == snapshot(
{
"type": "object",
"properties": {
"param_a": {"$ref": "#/$defs/TypeA"},
"param_b": {"$ref": "#/$defs/TypeB"},
},
"$defs": {
"TypeA": {
"properties": {"a": {"type": "string"}},
"required": ["a"],
"type": "object",
},
"TypeB": {
"properties": {"b": {"type": "integer"}},
"required": ["b"],
"type": "object",
},
},
"required": IsList("param_b", "param_a", check_order=False),
"additionalProperties": False,
}
)
# Second transform: hide param_b
transform2 = Tool.from_tool(
transform1,
transform_args={"param_b": ArgTransform(hide=True, default=TypeB(b=42))},
)
# TypeB should be pruned from $defs, only TypeA remains
assert "TypeB" not in transform2.parameters.get("$defs", {})
assert transform2.parameters == snapshot(
{
"type": "object",
"properties": {
"param_a": {"$ref": "#/$defs/TypeA"},
},
"$defs": {
"TypeA": {
"properties": {"a": {"type": "string"}},
"required": ["a"],
"type": "object",
},
},
"required": ["param_a"],
"additionalProperties": False,
}
)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/tools/tool_transform/test_schemas.py",
"license": "Apache License 2.0",
"lines": 448,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/tools/tool_transform/test_tool_transform.py | """Core tool transform functionality."""
import re
from typing import Annotated, Any
import pytest
from mcp.types import TextContent
from pydantic import BaseModel, Field
from fastmcp import FastMCP
from fastmcp.client.client import Client
from fastmcp.tools import Tool, forward, forward_raw, tool
from fastmcp.tools.function_tool import FunctionTool
from fastmcp.tools.tool import ToolResult
from fastmcp.tools.tool_transform import (
ArgTransform,
TransformedTool,
)
def get_property(tool: Tool, name: str) -> dict[str, Any]:
return tool.parameters["properties"][name]
@pytest.fixture
def add_tool() -> FunctionTool:
def add(
old_x: Annotated[int, Field(description="old_x description")], old_y: int = 10
) -> int:
print("running!")
return old_x + old_y
return Tool.from_function(add)
def test_tool_from_tool_no_change(add_tool):
new_tool = Tool.from_tool(add_tool)
assert isinstance(new_tool, TransformedTool)
assert new_tool.parameters == add_tool.parameters
assert new_tool.name == add_tool.name
assert new_tool.description == add_tool.description
def test_from_tool_accepts_decorated_function():
@tool
def search(q: str, limit: int = 10) -> list[str]:
"""Search for items."""
return [f"Result {i} for {q}" for i in range(limit)]
transformed = Tool.from_tool(
search,
name="find_items",
transform_args={"q": ArgTransform(name="query")},
)
assert isinstance(transformed, TransformedTool)
assert transformed.name == "find_items"
assert "query" in transformed.parameters["properties"]
assert "q" not in transformed.parameters["properties"]
def test_from_tool_accepts_plain_function():
def search(q: str, limit: int = 10) -> list[str]:
return [f"Result {i} for {q}" for i in range(limit)]
transformed = Tool.from_tool(
search,
name="find_items",
transform_args={"q": ArgTransform(name="query")},
)
assert isinstance(transformed, TransformedTool)
assert transformed.name == "find_items"
assert "query" in transformed.parameters["properties"]
def test_from_tool_decorated_function_preserves_metadata():
@tool(description="Custom description")
def search(q: str) -> list[str]:
"""Original description."""
return []
transformed = Tool.from_tool(search)
assert transformed.parent_tool.description == "Custom description"
async def test_from_tool_decorated_function_runs(add_tool):
@tool
def add(x: int, y: int = 10) -> int:
return x + y
transformed = Tool.from_tool(
add,
transform_args={"x": ArgTransform(name="a")},
)
result = await transformed.run(arguments={"a": 3, "y": 5})
assert result.structured_content == {"result": 8}
async def test_renamed_arg_description_is_maintained(add_tool):
new_tool = Tool.from_tool(
add_tool, transform_args={"old_x": ArgTransform(name="new_x")}
)
assert (
new_tool.parameters["properties"]["new_x"]["description"] == "old_x description"
)
async def test_tool_defaults_are_maintained_on_unmapped_args(add_tool):
new_tool = Tool.from_tool(
add_tool, transform_args={"old_x": ArgTransform(name="new_x")}
)
result = await new_tool.run(arguments={"new_x": 1})
# The parent tool returns int which gets wrapped as structured output
assert result.structured_content == {"result": 11}
async def test_tool_defaults_are_maintained_on_mapped_args(add_tool):
new_tool = Tool.from_tool(
add_tool, transform_args={"old_y": ArgTransform(name="new_y")}
)
result = await new_tool.run(arguments={"old_x": 1})
# The parent tool returns int which gets wrapped as structured output
assert result.structured_content == {"result": 11}
def test_tool_change_arg_name(add_tool):
new_tool = Tool.from_tool(
add_tool, transform_args={"old_x": ArgTransform(name="new_x")}
)
assert sorted(new_tool.parameters["properties"]) == ["new_x", "old_y"]
assert get_property(new_tool, "new_x") == get_property(add_tool, "old_x")
assert get_property(new_tool, "old_y") == get_property(add_tool, "old_y")
assert new_tool.parameters["required"] == ["new_x"]
def test_tool_change_arg_description(add_tool):
new_tool = Tool.from_tool(
add_tool, transform_args={"old_x": ArgTransform(description="new description")}
)
assert get_property(new_tool, "old_x")["description"] == "new description"
async def test_tool_drop_arg(add_tool):
new_tool = Tool.from_tool(
add_tool, transform_args={"old_y": ArgTransform(hide=True)}
)
assert sorted(new_tool.parameters["properties"]) == ["old_x"]
result = await new_tool.run(arguments={"old_x": 1})
assert result.structured_content == {"result": 11}
async def test_dropped_args_error_if_provided(add_tool):
new_tool = Tool.from_tool(
add_tool, transform_args={"old_y": ArgTransform(hide=True)}
)
with pytest.raises(
TypeError, match="Got unexpected keyword argument\\(s\\): old_y"
):
await new_tool.run(arguments={"old_x": 1, "old_y": 2})
async def test_hidden_arg_with_constant_default(add_tool):
new_tool = Tool.from_tool(
add_tool, transform_args={"old_y": ArgTransform(hide=True)}
)
result = await new_tool.run(arguments={"old_x": 1})
# old_y should use its default value of 10
assert result.structured_content == {"result": 11}
async def test_hidden_arg_without_default_uses_parent_default(add_tool):
"""Test that hidden argument without default uses parent's default."""
new_tool = Tool.from_tool(
add_tool, transform_args={"old_y": ArgTransform(hide=True)}
)
# Only old_x should be exposed
assert sorted(new_tool.parameters["properties"]) == ["old_x"]
# Should pass old_x=3 and let parent use its default old_y=10
result = await new_tool.run(arguments={"old_x": 3})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "13"
assert result.structured_content == {"result": 13}
async def test_mixed_hidden_args_with_custom_function(add_tool):
async def custom_fn(new_x: int, **kwargs) -> str:
result = await forward(new_x=new_x, **kwargs)
assert isinstance(result.content[0], TextContent)
return f"Custom: {result.content[0].text}"
new_tool = Tool.from_tool(
add_tool,
transform_fn=custom_fn,
transform_args={
"old_x": ArgTransform(name="new_x"),
"old_y": ArgTransform(hide=True),
},
)
result = await new_tool.run(arguments={"new_x": 5})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "Custom: 15"
async def test_hide_required_param_without_default_raises_error():
"""Test that hiding a required parameter without providing default raises error."""
@Tool.from_function
def tool_with_required_param(required_param: int, optional_param: int = 10) -> int:
return required_param + optional_param
# This should raise an error because required_param has no default and we're not providing one
with pytest.raises(
ValueError,
match=r"Hidden parameter 'required_param' has no default value in parent tool",
):
Tool.from_tool(
tool_with_required_param,
transform_args={"required_param": ArgTransform(hide=True)},
)
async def test_hide_required_param_with_user_default_works():
"""Test that hiding a required parameter works when user provides a default."""
@Tool.from_function
def tool_with_required_param(required_param: int, optional_param: int = 10) -> int:
return required_param + optional_param
# This should work because we're providing a default for the hidden required param
new_tool = Tool.from_tool(
tool_with_required_param,
transform_args={"required_param": ArgTransform(hide=True, default=5)},
)
# Only optional_param should be exposed
assert sorted(new_tool.parameters["properties"]) == ["optional_param"]
# Should pass required_param=5 and optional_param=20 to parent
result = await new_tool.run(arguments={"optional_param": 20})
assert result.structured_content == {"result": 25}
async def test_hidden_param_prunes_defs():
class VisibleType(BaseModel):
x: int
class HiddenType(BaseModel):
y: int
@Tool.from_function
def tool_with_refs(a: VisibleType, b: HiddenType | None = None) -> int:
return a.x + (b.y if b else 0)
# Hide parameter 'b'
new_tool = Tool.from_tool(
tool_with_refs, transform_args={"b": ArgTransform(hide=True)}
)
schema = new_tool.parameters
# Only 'a' should be visible
assert list(schema["properties"].keys()) == ["a"]
# HiddenType should be pruned from $defs
assert "HiddenType" not in schema.get("$defs", {})
# VisibleType should remain in $defs and be referenced via $ref
assert schema["properties"]["a"] == {"$ref": "#/$defs/VisibleType"}
assert schema["$defs"]["VisibleType"] == {
"properties": {"x": {"type": "integer"}},
"required": ["x"],
"type": "object",
}
async def test_forward_with_argument_mapping(add_tool):
async def custom_fn(new_x: int, **kwargs) -> str:
result = await forward(new_x=new_x, **kwargs)
assert isinstance(result.content[0], TextContent)
return f"Mapped: {result.content[0].text}"
new_tool = Tool.from_tool(
add_tool,
transform_fn=custom_fn,
transform_args={"old_x": ArgTransform(name="new_x")},
)
result = await new_tool.run(arguments={"new_x": 3, "old_y": 7})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "Mapped: 10"
async def test_forward_with_incorrect_args_raises_error(add_tool):
async def custom_fn(new_x: int, new_y: int = 5) -> ToolResult:
# the forward should use the new args, not the old ones
return await forward(old_x=new_x, old_y=new_y)
new_tool = Tool.from_tool(
add_tool,
transform_fn=custom_fn,
transform_args={
"old_x": ArgTransform(name="new_x"),
"old_y": ArgTransform(name="new_y"),
},
)
with pytest.raises(
TypeError, match=re.escape("Got unexpected keyword argument(s): old_x, old_y")
):
await new_tool.run(arguments={"new_x": 2, "new_y": 3})
async def test_forward_raw_without_argument_mapping(add_tool):
async def custom_fn(**kwargs) -> str:
# forward_raw passes through kwargs as-is
result = await forward_raw(**kwargs)
assert isinstance(result.content[0], TextContent)
return f"Raw: {result.content[0].text}"
new_tool = Tool.from_tool(add_tool, transform_fn=custom_fn)
result = await new_tool.run(arguments={"old_x": 2, "old_y": 8})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "Raw: 10"
async def test_custom_fn_with_kwargs_and_no_transform_args(add_tool):
async def custom_fn(**kwargs) -> str:
result = await forward(**kwargs)
assert isinstance(result.content[0], TextContent)
return f"Custom: {result.content[0].text}"
new_tool = Tool.from_tool(add_tool, transform_fn=custom_fn)
result = await new_tool.run(arguments={"old_x": 4, "old_y": 6})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "Custom: 10"
async def test_fn_with_kwargs_passes_through_original_args(add_tool):
async def custom_fn(**kwargs) -> str:
# Should receive original arg names
assert "old_x" in kwargs
assert "old_y" in kwargs
result = await forward(**kwargs)
assert isinstance(result.content[0], TextContent)
return result.content[0].text
new_tool = Tool.from_tool(add_tool, transform_fn=custom_fn)
result = await new_tool.run(arguments={"old_x": 1, "old_y": 2})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "3"
async def test_fn_with_kwargs_receives_transformed_arg_names(add_tool):
"""Test that **kwargs receives arguments with their transformed names from transform_args."""
async def custom_fn(new_x: int, **kwargs) -> ToolResult:
# kwargs should contain 'old_y': 3 (transformed name), not 'old_y': 3 (original name)
assert kwargs == {"old_y": 3}
result = await forward(new_x=new_x, **kwargs)
return result
new_tool = Tool.from_tool(
add_tool,
transform_fn=custom_fn,
transform_args={"old_x": ArgTransform(name="new_x")},
)
result = await new_tool.run(arguments={"new_x": 2, "old_y": 3})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "5"
assert result.structured_content == {"result": 5}
async def test_fn_with_kwargs_handles_partial_explicit_args(add_tool):
async def custom_fn(new_x: int, **kwargs) -> str:
result = await forward(new_x=new_x, **kwargs)
assert isinstance(result.content[0], TextContent)
return result.content[0].text
new_tool = Tool.from_tool(
add_tool,
transform_fn=custom_fn,
transform_args={"old_x": ArgTransform(name="new_x")},
)
# Only provide new_x, old_y should use default
result = await new_tool.run(arguments={"new_x": 7})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "17" # 7 + 10 (default)
async def test_fn_with_kwargs_mixed_mapped_and_unmapped_args(add_tool):
async def custom_fn(new_x: int, old_y: int, **kwargs) -> str:
result = await forward(new_x=new_x, old_y=old_y, **kwargs)
assert isinstance(result.content[0], TextContent)
return result.content[0].text
new_tool = Tool.from_tool(
add_tool,
transform_fn=custom_fn,
transform_args={"old_x": ArgTransform(name="new_x")},
)
result = await new_tool.run(arguments={"new_x": 2, "old_y": 8})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "10"
async def test_fn_with_kwargs_dropped_args_not_in_kwargs(add_tool):
async def custom_fn(new_x: int, **kwargs) -> str:
# old_y is dropped, so it shouldn't be in kwargs
assert "old_y" not in kwargs
result = await forward(new_x=new_x, **kwargs)
assert isinstance(result.content[0], TextContent)
return result.content[0].text
new_tool = Tool.from_tool(
add_tool,
transform_fn=custom_fn,
transform_args={
"old_x": ArgTransform(name="new_x"),
"old_y": ArgTransform(hide=True),
},
)
result = await new_tool.run(arguments={"new_x": 3})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "13" # 3 + 10 (default for hidden old_y)
async def test_forward_outside_context_raises_error():
"""Test that forward() raises error when called outside transform context."""
with pytest.raises(RuntimeError, match="forward\(\) can only be called"):
await forward(x=1)
async def test_forward_raw_outside_context_raises_error():
"""Test that forward_raw() raises error when called outside transform context."""
with pytest.raises(RuntimeError, match="forward_raw\(\) can only be called"):
await forward_raw(x=1)
def test_transform_args_with_parent_defaults():
"""Test that transform_args with parent defaults works."""
class CoolModel(BaseModel):
x: int = 10
def parent_tool(cool_model: CoolModel) -> int:
return cool_model.x
tool = Tool.from_function(parent_tool)
new_tool = Tool.from_tool(tool)
# Both tools should have the same schema (with $ref/$defs preserved)
assert new_tool.parameters == tool.parameters
def test_transform_args_validation_unknown_arg(add_tool):
"""Test that transform_args with unknown arguments raises ValueError."""
with pytest.raises(
ValueError, match="Unknown arguments in transform_args: unknown_param"
) as exc_info:
Tool.from_tool(
add_tool, transform_args={"unknown_param": ArgTransform(name="new_name")}
)
assert "`add`" in str(exc_info.value)
def test_transform_args_creates_duplicate_names(add_tool):
"""Test that transform_args creating duplicate parameter names raises ValueError."""
with pytest.raises(
ValueError,
match="Multiple arguments would be mapped to the same names: same_name",
):
Tool.from_tool(
add_tool,
transform_args={
"old_x": ArgTransform(name="same_name"),
"old_y": ArgTransform(name="same_name"),
},
)
def test_transform_args_collision_with_passthrough_name(add_tool):
"""Test that renaming to a passthrough parameter name raises ValueError."""
with pytest.raises(
ValueError,
match="Multiple arguments would be mapped to the same names: old_y",
):
Tool.from_tool(
add_tool,
transform_args={
"old_x": ArgTransform(name="old_y"),
},
)
def test_function_without_kwargs_missing_params(add_tool):
"""Test that function missing required transformed parameters raises ValueError."""
def invalid_fn(new_x: int, non_existent: str) -> str:
return f"{new_x}_{non_existent}"
with pytest.raises(
ValueError,
match="Function missing parameters required after transformation: new_y",
):
Tool.from_tool(
add_tool,
transform_fn=invalid_fn,
transform_args={
"old_x": ArgTransform(name="new_x"),
"old_y": ArgTransform(name="new_y"),
},
)
def test_function_without_kwargs_can_have_extra_params(add_tool):
"""Test that function can have extra parameters not in parent tool."""
def valid_fn(new_x: int, new_y: int, extra_param: str = "default") -> str:
return f"{new_x}_{new_y}_{extra_param}"
# Should work - extra_param is fine as long as it has a default
new_tool = Tool.from_tool(
add_tool,
transform_fn=valid_fn,
transform_args={
"old_x": ArgTransform(name="new_x"),
"old_y": ArgTransform(name="new_y"),
},
)
# The final schema should include all function parameters
assert "new_x" in new_tool.parameters["properties"]
assert "new_y" in new_tool.parameters["properties"]
assert "extra_param" in new_tool.parameters["properties"]
def test_function_with_kwargs_can_add_params(add_tool):
"""Test that function with **kwargs can add new parameters."""
async def valid_fn(extra_param: str, **kwargs) -> str:
result = await forward(**kwargs)
return f"{extra_param}: {result}"
# This should work fine - kwargs allows access to all transformed params
tool = Tool.from_tool(
add_tool,
transform_fn=valid_fn,
transform_args={
"old_x": ArgTransform(name="new_x"),
"old_y": ArgTransform(name="new_y"),
},
)
# extra_param is added, new_x and new_y are available
assert "extra_param" in tool.parameters["properties"]
assert "new_x" in tool.parameters["properties"]
async def test_from_tool_decorated_function_via_client():
@tool
def search(q: str, limit: int = 10) -> list[str]:
"""Search for items."""
return [f"Result {i} for {q}" for i in range(limit)]
better_search = Tool.from_tool(
search,
name="find_items",
transform_args={
"q": ArgTransform(name="query", description="The search terms"),
},
)
mcp = FastMCP("Server")
mcp.add_tool(better_search)
async with Client(mcp) as client:
result = await client.call_tool("find_items", {"query": "hello", "limit": 3})
assert isinstance(result.content[0], TextContent)
assert "Result 0 for hello" in result.content[0].text
class TestProxy:
@pytest.fixture
def mcp_server(self) -> FastMCP:
mcp = FastMCP()
@mcp.tool
def add(old_x: int, old_y: int = 10) -> int:
return old_x + old_y
return mcp
@pytest.fixture
def proxy_server(self, mcp_server: FastMCP) -> FastMCP:
from fastmcp.client.transports import FastMCPTransport
proxy = FastMCP.as_proxy(FastMCPTransport(mcp_server))
return proxy
async def test_transform_proxy(self, proxy_server: FastMCP):
# when adding transformed tools to proxy servers. Needs separate investigation.
add_tool = await proxy_server.get_tool("add")
assert add_tool is not None
new_add_tool = Tool.from_tool(
add_tool,
name="add_transformed",
transform_args={"old_x": ArgTransform(name="new_x")},
)
proxy_server.add_tool(new_add_tool)
async with Client(proxy_server) as client:
# The tool should be registered with its transformed name
result = await client.call_tool("add_transformed", {"new_x": 1, "old_y": 2})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "3"
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/tools/tool_transform/test_tool_transform.py",
"license": "Apache License 2.0",
"lines": 479,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/utilities/json_schema_type/test_constraints.py | """Tests for type constraints in JSON schema conversion."""
from dataclasses import Field
import pytest
from pydantic import TypeAdapter, ValidationError
from fastmcp.utilities.json_schema_type import (
json_schema_to_type,
)
def get_dataclass_field(type: type, field_name: str) -> Field:
return type.__dataclass_fields__[field_name] # ty: ignore[unresolved-attribute]
class TestStringConstraints:
"""Test suite for string constraint validation."""
@pytest.fixture
def min_length_string(self):
return json_schema_to_type({"type": "string", "minLength": 3})
@pytest.fixture
def max_length_string(self):
return json_schema_to_type({"type": "string", "maxLength": 5})
@pytest.fixture
def pattern_string(self):
return json_schema_to_type({"type": "string", "pattern": "^[A-Z][a-z]+$"})
@pytest.fixture
def email_string(self):
return json_schema_to_type({"type": "string", "format": "email"})
def test_min_length_accepts_valid(self, min_length_string):
validator = TypeAdapter(min_length_string)
assert validator.validate_python("test") == "test"
def test_min_length_rejects_short(self, min_length_string):
validator = TypeAdapter(min_length_string)
with pytest.raises(ValidationError):
validator.validate_python("ab")
def test_max_length_accepts_valid(self, max_length_string):
validator = TypeAdapter(max_length_string)
assert validator.validate_python("test") == "test"
def test_max_length_rejects_long(self, max_length_string):
validator = TypeAdapter(max_length_string)
with pytest.raises(ValidationError):
validator.validate_python("toolong")
def test_pattern_accepts_valid(self, pattern_string):
validator = TypeAdapter(pattern_string)
assert validator.validate_python("Hello") == "Hello"
def test_pattern_rejects_invalid(self, pattern_string):
validator = TypeAdapter(pattern_string)
with pytest.raises(ValidationError):
validator.validate_python("hello")
def test_email_accepts_valid(self, email_string):
validator = TypeAdapter(email_string)
result = validator.validate_python("test@example.com")
assert result == "test@example.com"
def test_email_rejects_invalid(self, email_string):
validator = TypeAdapter(email_string)
with pytest.raises(ValidationError):
validator.validate_python("not-an-email")
class TestNumberConstraints:
"""Test suite for numeric constraint validation."""
@pytest.fixture
def multiple_of_number(self):
return json_schema_to_type({"type": "number", "multipleOf": 0.5})
@pytest.fixture
def min_number(self):
return json_schema_to_type({"type": "number", "minimum": 0})
@pytest.fixture
def exclusive_min_number(self):
return json_schema_to_type({"type": "number", "exclusiveMinimum": 0})
@pytest.fixture
def max_number(self):
return json_schema_to_type({"type": "number", "maximum": 100})
@pytest.fixture
def exclusive_max_number(self):
return json_schema_to_type({"type": "number", "exclusiveMaximum": 100})
def test_multiple_of_accepts_valid(self, multiple_of_number):
validator = TypeAdapter(multiple_of_number)
assert validator.validate_python(2.5) == 2.5
def test_multiple_of_rejects_invalid(self, multiple_of_number):
validator = TypeAdapter(multiple_of_number)
with pytest.raises(ValidationError):
validator.validate_python(2.7)
def test_minimum_accepts_equal(self, min_number):
validator = TypeAdapter(min_number)
assert validator.validate_python(0) == 0
def test_minimum_rejects_less(self, min_number):
validator = TypeAdapter(min_number)
with pytest.raises(ValidationError):
validator.validate_python(-1)
def test_exclusive_minimum_rejects_equal(self, exclusive_min_number):
validator = TypeAdapter(exclusive_min_number)
with pytest.raises(ValidationError):
validator.validate_python(0)
def test_maximum_accepts_equal(self, max_number):
validator = TypeAdapter(max_number)
assert validator.validate_python(100) == 100
def test_maximum_rejects_greater(self, max_number):
validator = TypeAdapter(max_number)
with pytest.raises(ValidationError):
validator.validate_python(101)
def test_exclusive_maximum_rejects_equal(self, exclusive_max_number):
validator = TypeAdapter(exclusive_max_number)
with pytest.raises(ValidationError):
validator.validate_python(100)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/utilities/json_schema_type/test_constraints.py",
"license": "Apache License 2.0",
"lines": 98,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/utilities/json_schema_type/test_containers.py | """Tests for container types in JSON schema conversion."""
from dataclasses import Field, dataclass
from typing import Any
import pytest
from pydantic import TypeAdapter, ValidationError
from fastmcp.utilities.json_schema_type import (
json_schema_to_type,
)
def get_dataclass_field(type: type, field_name: str) -> Field:
return type.__dataclass_fields__[field_name] # ty: ignore[unresolved-attribute]
class TestArrayTypes:
"""Test suite for array validation."""
@pytest.fixture
def string_array(self):
return json_schema_to_type({"type": "array", "items": {"type": "string"}})
@pytest.fixture
def min_items_array(self):
return json_schema_to_type(
{"type": "array", "items": {"type": "string"}, "minItems": 2}
)
@pytest.fixture
def max_items_array(self):
return json_schema_to_type(
{"type": "array", "items": {"type": "string"}, "maxItems": 3}
)
@pytest.fixture
def unique_items_array(self):
return json_schema_to_type(
{"type": "array", "items": {"type": "string"}, "uniqueItems": True}
)
def test_array_accepts_valid_items(self, string_array):
validator = TypeAdapter(string_array)
assert validator.validate_python(["a", "b"]) == ["a", "b"]
def test_array_rejects_invalid_items(self, string_array):
validator = TypeAdapter(string_array)
with pytest.raises(ValidationError):
validator.validate_python([1, "b"])
def test_min_items_accepts_valid(self, min_items_array):
validator = TypeAdapter(min_items_array)
assert validator.validate_python(["a", "b"]) == ["a", "b"]
def test_min_items_rejects_too_few(self, min_items_array):
validator = TypeAdapter(min_items_array)
with pytest.raises(ValidationError):
validator.validate_python(["a"])
def test_max_items_accepts_valid(self, max_items_array):
validator = TypeAdapter(max_items_array)
assert validator.validate_python(["a", "b", "c"]) == ["a", "b", "c"]
def test_max_items_rejects_too_many(self, max_items_array):
validator = TypeAdapter(max_items_array)
with pytest.raises(ValidationError):
validator.validate_python(["a", "b", "c", "d"])
def test_unique_items_accepts_unique(self, unique_items_array):
validator = TypeAdapter(unique_items_array)
assert isinstance(validator.validate_python(["a", "b"]), set)
def test_unique_items_converts_duplicates(self, unique_items_array):
validator = TypeAdapter(unique_items_array)
result = validator.validate_python(["a", "a", "b"])
assert result == {"a", "b"}
class TestObjectTypes:
"""Test suite for object validation."""
@pytest.fixture
def simple_object(self):
return json_schema_to_type(
{
"type": "object",
"properties": {"name": {"type": "string"}, "age": {"type": "integer"}},
}
)
@pytest.fixture
def required_object(self):
return json_schema_to_type(
{
"type": "object",
"properties": {"name": {"type": "string"}, "age": {"type": "integer"}},
"required": ["name"],
}
)
@pytest.fixture
def nested_object(self):
return json_schema_to_type(
{
"type": "object",
"properties": {
"user": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
},
"required": ["name"],
}
},
}
)
@pytest.mark.parametrize(
"input_type, expected_type",
[
# Plain dict becomes dict[str, Any] (JSON Schema accurate)
(dict, dict[str, Any]),
# dict[str, Any] stays the same
(dict[str, Any], dict[str, Any]),
# Simple typed dicts work correctly
(dict[str, str], dict[str, str]),
(dict[str, int], dict[str, int]),
# Union value types work
(dict[str, str | int], dict[str, str | int]),
# Key types are constrained to str in JSON Schema
(dict[int, list[str]], dict[str, list[str]]),
# Union key types become str (JSON Schema limitation)
(dict[str | int, str | None], dict[str, str | None]),
],
)
def test_dict_types_are_generated_correctly(self, input_type, expected_type):
schema = TypeAdapter(input_type).json_schema()
generated_type = json_schema_to_type(schema)
assert generated_type == expected_type
def test_object_accepts_valid(self, simple_object):
validator = TypeAdapter(simple_object)
result = validator.validate_python({"name": "test", "age": 30})
assert result.name == "test"
assert result.age == 30
def test_object_accepts_extra_properties(self, simple_object):
validator = TypeAdapter(simple_object)
result = validator.validate_python(
{"name": "test", "age": 30, "extra": "field"}
)
assert result.name == "test"
assert result.age == 30
assert not hasattr(result, "extra")
def test_required_accepts_valid(self, required_object):
validator = TypeAdapter(required_object)
result = validator.validate_python({"name": "test"})
assert result.name == "test"
assert result.age is None
def test_required_rejects_missing(self, required_object):
validator = TypeAdapter(required_object)
with pytest.raises(ValidationError):
validator.validate_python({})
def test_nested_accepts_valid(self, nested_object):
validator = TypeAdapter(nested_object)
result = validator.validate_python({"user": {"name": "test", "age": 30}})
assert result.user.name == "test"
assert result.user.age == 30
def test_nested_rejects_invalid(self, nested_object):
validator = TypeAdapter(nested_object)
with pytest.raises(ValidationError):
validator.validate_python({"user": {"age": 30}})
def test_object_with_underscore_names(self):
@dataclass
class Data:
x: int
x_: int
_x: int
schema = TypeAdapter(Data).json_schema()
assert schema == {
"title": "Data",
"type": "object",
"properties": {
"x": {"type": "integer", "title": "X"},
"x_": {"type": "integer", "title": "X"},
"_x": {"type": "integer", "title": "X"},
},
"required": ["x", "x_", "_x"],
}
object = json_schema_to_type(schema)
object_schema = TypeAdapter(object).json_schema()
assert object_schema == schema
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/utilities/json_schema_type/test_containers.py",
"license": "Apache License 2.0",
"lines": 167,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/utilities/json_schema_type/test_formats.py | """Tests for format handling in JSON schema conversion."""
from dataclasses import Field
from datetime import datetime
import pytest
from pydantic import AnyUrl, TypeAdapter, ValidationError
from fastmcp.utilities.json_schema_type import (
json_schema_to_type,
)
def get_dataclass_field(type: type, field_name: str) -> Field:
return type.__dataclass_fields__[field_name] # ty: ignore[unresolved-attribute]
class TestFormatTypes:
"""Test suite for format type validation."""
@pytest.fixture
def datetime_format(self):
return json_schema_to_type({"type": "string", "format": "date-time"})
@pytest.fixture
def email_format(self):
return json_schema_to_type({"type": "string", "format": "email"})
@pytest.fixture
def uri_format(self):
return json_schema_to_type({"type": "string", "format": "uri"})
@pytest.fixture
def uri_reference_format(self):
return json_schema_to_type({"type": "string", "format": "uri-reference"})
@pytest.fixture
def json_format(self):
return json_schema_to_type({"type": "string", "format": "json"})
@pytest.fixture
def mixed_formats_object(self):
return json_schema_to_type(
{
"type": "object",
"properties": {
"full_uri": {"type": "string", "format": "uri"},
"ref_uri": {"type": "string", "format": "uri-reference"},
},
}
)
def test_datetime_valid(self, datetime_format):
validator = TypeAdapter(datetime_format)
result = validator.validate_python("2024-01-17T12:34:56Z")
assert isinstance(result, datetime)
def test_datetime_invalid(self, datetime_format):
validator = TypeAdapter(datetime_format)
with pytest.raises(ValidationError):
validator.validate_python("not-a-date")
def test_email_valid(self, email_format):
validator = TypeAdapter(email_format)
result = validator.validate_python("test@example.com")
assert isinstance(result, str)
def test_email_invalid(self, email_format):
validator = TypeAdapter(email_format)
with pytest.raises(ValidationError):
validator.validate_python("not-an-email")
def test_uri_valid(self, uri_format):
validator = TypeAdapter(uri_format)
result = validator.validate_python("https://example.com")
assert isinstance(result, AnyUrl)
def test_uri_invalid(self, uri_format):
validator = TypeAdapter(uri_format)
with pytest.raises(ValidationError):
validator.validate_python("not-a-uri")
def test_uri_reference_valid(self, uri_reference_format):
validator = TypeAdapter(uri_reference_format)
result = validator.validate_python("https://example.com")
assert isinstance(result, str)
def test_uri_reference_relative_valid(self, uri_reference_format):
validator = TypeAdapter(uri_reference_format)
result = validator.validate_python("/path/to/resource")
assert isinstance(result, str)
def test_uri_reference_invalid(self, uri_reference_format):
validator = TypeAdapter(uri_reference_format)
result = validator.validate_python("not a uri")
assert isinstance(result, str)
def test_json_valid(self, json_format):
validator = TypeAdapter(json_format)
result = validator.validate_python('{"key": "value"}')
assert isinstance(result, dict)
def test_json_invalid(self, json_format):
validator = TypeAdapter(json_format)
with pytest.raises(ValidationError):
validator.validate_python("{invalid json}")
def test_mixed_formats_object(self, mixed_formats_object):
validator = TypeAdapter(mixed_formats_object)
result = validator.validate_python(
{"full_uri": "https://example.com", "ref_uri": "/path/to/resource"}
)
assert isinstance(result.full_uri, AnyUrl)
assert isinstance(result.ref_uri, str)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/utilities/json_schema_type/test_formats.py",
"license": "Apache License 2.0",
"lines": 89,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/utilities/json_schema_type/test_json_schema_type.py | """Core JSON schema type conversion tests."""
from dataclasses import Field
from enum import Enum
from typing import Literal
import pytest
from pydantic import TypeAdapter, ValidationError
from fastmcp.utilities.json_schema_type import (
json_schema_to_type,
)
def get_dataclass_field(type: type, field_name: str) -> Field:
return type.__dataclass_fields__[field_name] # ty: ignore[unresolved-attribute]
class TestSimpleTypes:
"""Test suite for basic type validation."""
@pytest.fixture
def simple_string(self):
return json_schema_to_type({"type": "string"})
@pytest.fixture
def simple_number(self):
return json_schema_to_type({"type": "number"})
@pytest.fixture
def simple_integer(self):
return json_schema_to_type({"type": "integer"})
@pytest.fixture
def simple_boolean(self):
return json_schema_to_type({"type": "boolean"})
@pytest.fixture
def simple_null(self):
return json_schema_to_type({"type": "null"})
def test_string_accepts_string(self, simple_string):
validator = TypeAdapter(simple_string)
assert validator.validate_python("test") == "test"
def test_string_rejects_number(self, simple_string):
validator = TypeAdapter(simple_string)
with pytest.raises(ValidationError):
validator.validate_python(123)
def test_number_accepts_float(self, simple_number):
validator = TypeAdapter(simple_number)
assert validator.validate_python(123.45) == 123.45
def test_number_accepts_integer(self, simple_number):
validator = TypeAdapter(simple_number)
assert validator.validate_python(123) == 123
def test_number_accepts_numeric_string(self, simple_number):
validator = TypeAdapter(simple_number)
assert validator.validate_python("123.45") == 123.45
assert validator.validate_python("123") == 123
def test_number_rejects_invalid_string(self, simple_number):
validator = TypeAdapter(simple_number)
with pytest.raises(ValidationError):
validator.validate_python("not a number")
def test_integer_accepts_integer(self, simple_integer):
validator = TypeAdapter(simple_integer)
assert validator.validate_python(123) == 123
def test_integer_accepts_integer_string(self, simple_integer):
validator = TypeAdapter(simple_integer)
assert validator.validate_python("123") == 123
def test_integer_rejects_float(self, simple_integer):
validator = TypeAdapter(simple_integer)
with pytest.raises(ValidationError):
validator.validate_python(123.45)
def test_integer_rejects_float_string(self, simple_integer):
validator = TypeAdapter(simple_integer)
with pytest.raises(ValidationError):
validator.validate_python("123.45")
def test_boolean_accepts_boolean(self, simple_boolean):
validator = TypeAdapter(simple_boolean)
assert validator.validate_python(True) is True
assert validator.validate_python(False) is False
def test_boolean_accepts_boolean_strings(self, simple_boolean):
validator = TypeAdapter(simple_boolean)
assert validator.validate_python("true") is True
assert validator.validate_python("True") is True
assert validator.validate_python("false") is False
assert validator.validate_python("False") is False
def test_boolean_rejects_invalid_string(self, simple_boolean):
validator = TypeAdapter(simple_boolean)
with pytest.raises(ValidationError):
validator.validate_python("not a boolean")
def test_null_accepts_none(self, simple_null):
validator = TypeAdapter(simple_null)
assert validator.validate_python(None) is None
def test_null_rejects_false(self, simple_null):
validator = TypeAdapter(simple_null)
with pytest.raises(ValidationError):
validator.validate_python(False)
class TestConstrainedTypes:
def test_constant(self):
validator = TypeAdapter(Literal["x"])
schema = validator.json_schema()
type_ = json_schema_to_type(schema)
assert type_ == Literal["x"]
assert TypeAdapter(type_).validate_python("x") == "x"
with pytest.raises(ValidationError):
TypeAdapter(type_).validate_python("y")
def test_union_constants(self):
validator = TypeAdapter(Literal["x"] | Literal["y"])
schema = validator.json_schema()
type_ = json_schema_to_type(schema)
assert type_ == Literal["x"] | Literal["y"]
assert TypeAdapter(type_).validate_python("x") == "x"
assert TypeAdapter(type_).validate_python("y") == "y"
with pytest.raises(ValidationError):
TypeAdapter(type_).validate_python("z")
def test_enum_str(self):
class MyEnum(Enum):
X = "x"
Y = "y"
validator = TypeAdapter(MyEnum)
schema = validator.json_schema()
type_ = json_schema_to_type(schema)
assert type_ == Literal["x", "y"]
assert TypeAdapter(type_).validate_python("x") == "x"
assert TypeAdapter(type_).validate_python("y") == "y"
with pytest.raises(ValidationError):
TypeAdapter(type_).validate_python("z")
def test_enum_int(self):
class MyEnum(Enum):
X = 1
Y = 2
validator = TypeAdapter(MyEnum)
schema = validator.json_schema()
type_ = json_schema_to_type(schema)
assert type_ == Literal[1, 2]
assert TypeAdapter(type_).validate_python(1) == 1
assert TypeAdapter(type_).validate_python(2) == 2
with pytest.raises(ValidationError):
TypeAdapter(type_).validate_python(3)
def test_choice(self):
validator = TypeAdapter(Literal["x", "y"])
schema = validator.json_schema()
type_ = json_schema_to_type(schema)
assert type_ == Literal["x", "y"]
assert TypeAdapter(type_).validate_python("x") == "x"
assert TypeAdapter(type_).validate_python("y") == "y"
with pytest.raises(ValidationError):
TypeAdapter(type_).validate_python("z")
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/utilities/json_schema_type/test_json_schema_type.py",
"license": "Apache License 2.0",
"lines": 135,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/utilities/json_schema_type/test_unions.py | """Tests for union types in JSON schema conversion."""
from dataclasses import Field
import pytest
from pydantic import TypeAdapter, ValidationError
from fastmcp.utilities.json_schema_type import (
json_schema_to_type,
)
def get_dataclass_field(type: type, field_name: str) -> Field:
return type.__dataclass_fields__[field_name] # ty: ignore[unresolved-attribute]
class TestUnionTypes:
"""Test suite for testing union type behaviors."""
@pytest.fixture
def heterogeneous_union(self):
return json_schema_to_type({"type": ["string", "number", "boolean", "null"]})
@pytest.fixture
def union_with_constraints(self):
return json_schema_to_type(
{"type": ["string", "number"], "minLength": 3, "minimum": 0}
)
@pytest.fixture
def union_with_formats(self):
return json_schema_to_type({"type": ["string", "null"], "format": "email"})
@pytest.fixture
def nested_union_array(self):
return json_schema_to_type(
{"type": "array", "items": {"type": ["string", "number"]}}
)
@pytest.fixture
def nested_union_object(self):
return json_schema_to_type(
{
"type": "object",
"properties": {
"id": {"type": ["string", "integer"]},
"data": {
"type": ["object", "null"],
"properties": {"value": {"type": "string"}},
},
},
}
)
def test_heterogeneous_accepts_string(self, heterogeneous_union):
validator = TypeAdapter(heterogeneous_union)
assert validator.validate_python("test") == "test"
def test_heterogeneous_accepts_number(self, heterogeneous_union):
validator = TypeAdapter(heterogeneous_union)
assert validator.validate_python(123.45) == 123.45
def test_heterogeneous_accepts_boolean(self, heterogeneous_union):
validator = TypeAdapter(heterogeneous_union)
assert validator.validate_python(True) is True
def test_heterogeneous_accepts_null(self, heterogeneous_union):
validator = TypeAdapter(heterogeneous_union)
assert validator.validate_python(None) is None
def test_heterogeneous_rejects_array(self, heterogeneous_union):
validator = TypeAdapter(heterogeneous_union)
with pytest.raises(ValidationError):
validator.validate_python([])
def test_constrained_string_valid(self, union_with_constraints):
validator = TypeAdapter(union_with_constraints)
assert validator.validate_python("test") == "test"
def test_constrained_string_invalid(self, union_with_constraints):
validator = TypeAdapter(union_with_constraints)
with pytest.raises(ValidationError):
validator.validate_python("ab")
def test_constrained_number_valid(self, union_with_constraints):
validator = TypeAdapter(union_with_constraints)
assert validator.validate_python(10) == 10
def test_constrained_number_invalid(self, union_with_constraints):
validator = TypeAdapter(union_with_constraints)
with pytest.raises(ValidationError):
validator.validate_python(-1)
def test_format_valid_email(self, union_with_formats):
validator = TypeAdapter(union_with_formats)
result = validator.validate_python("test@example.com")
assert isinstance(result, str)
def test_format_valid_null(self, union_with_formats):
validator = TypeAdapter(union_with_formats)
assert validator.validate_python(None) is None
def test_format_invalid_email(self, union_with_formats):
validator = TypeAdapter(union_with_formats)
with pytest.raises(ValidationError):
validator.validate_python("not-an-email")
def test_nested_array_mixed_types(self, nested_union_array):
validator = TypeAdapter(nested_union_array)
result = validator.validate_python(["test", 123, "abc"])
assert result == ["test", 123, "abc"]
def test_nested_array_rejects_invalid(self, nested_union_array):
validator = TypeAdapter(nested_union_array)
with pytest.raises(ValidationError):
validator.validate_python(["test", ["not", "allowed"], "abc"])
def test_nested_object_string_id(self, nested_union_object):
validator = TypeAdapter(nested_union_object)
result = validator.validate_python({"id": "abc123", "data": {"value": "test"}})
assert result.id == "abc123"
assert result.data.value == "test"
def test_nested_object_integer_id(self, nested_union_object):
validator = TypeAdapter(nested_union_object)
result = validator.validate_python({"id": 123, "data": None})
assert result.id == 123
assert result.data is None
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/utilities/json_schema_type/test_unions.py",
"license": "Apache License 2.0",
"lines": 100,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:src/fastmcp/server/mixins/lifespan.py | """Lifespan and Docket task infrastructure for FastMCP Server."""
from __future__ import annotations
import asyncio
import weakref
from collections.abc import AsyncIterator
from contextlib import AsyncExitStack, asynccontextmanager, suppress
from typing import TYPE_CHECKING, Any
from uncalled_for import SharedContext
import fastmcp
from fastmcp.utilities.logging import get_logger
if TYPE_CHECKING:
from docket import Docket
from fastmcp.server.server import FastMCP
logger = get_logger(__name__)
class LifespanMixin:
"""Mixin providing lifespan and Docket task infrastructure for FastMCP."""
@property
def docket(self: FastMCP) -> Docket | None:
"""Get the Docket instance if Docket support is enabled.
Returns None if Docket is not enabled or server hasn't been started yet.
"""
return self._docket
@asynccontextmanager
async def _docket_lifespan(self: FastMCP) -> AsyncIterator[None]:
"""Manage Docket instance and Worker for background task execution.
Docket infrastructure is only initialized if:
1. pydocket is installed (fastmcp[tasks] extra)
2. There are task-enabled components (task_config.mode != 'forbidden')
This means users with pydocket installed but no task-enabled components
won't spin up Docket/Worker infrastructure.
"""
from fastmcp.server.dependencies import _current_server, is_docket_available
# Set FastMCP server in ContextVar so CurrentFastMCP can access it
# (use weakref to avoid reference cycles)
server_token = _current_server.set(weakref.ref(self))
try:
# If docket is not available, skip task infrastructure but still
# set up SharedContext so Shared() dependencies work.
if not is_docket_available():
async with SharedContext():
yield
return
# Collect task-enabled components at startup with all transforms applied.
# Components must be available now to be registered with Docket workers;
# dynamically added components after startup won't be registered.
try:
task_components = list(await self.get_tasks())
except Exception as e:
logger.warning(f"Failed to get tasks: {e}")
if fastmcp.settings.mounted_components_raise_on_load_error:
raise
task_components = []
# If no task-enabled components, skip Docket infrastructure but still
# set up SharedContext so Shared() dependencies work.
if not task_components:
async with SharedContext():
yield
return
# Docket is available AND there are task-enabled components
from docket import Docket, Worker
from fastmcp import settings
from fastmcp.server.dependencies import (
_current_docket,
_current_worker,
)
# Create Docket instance using configured name and URL
async with Docket(
name=settings.docket.name,
url=settings.docket.url,
) as docket:
# Store on server instance for cross-task access (FastMCPTransport)
self._docket = docket
# Register task-enabled components with Docket
for component in task_components:
component.register_with_docket(docket)
# Set Docket in ContextVar so CurrentDocket can access it
docket_token = _current_docket.set(docket)
try:
# Build worker kwargs from settings
worker_kwargs: dict[str, Any] = {
"concurrency": settings.docket.concurrency,
"redelivery_timeout": settings.docket.redelivery_timeout,
"reconnection_delay": settings.docket.reconnection_delay,
}
if settings.docket.worker_name:
worker_kwargs["name"] = settings.docket.worker_name
# Create and start Worker
async with Worker(docket, **worker_kwargs) as worker:
# Store on server instance for cross-context access
self._worker = worker
# Set Worker in ContextVar so CurrentWorker can access it
worker_token = _current_worker.set(worker)
try:
worker_task = asyncio.create_task(worker.run_forever())
try:
yield
finally:
worker_task.cancel()
with suppress(asyncio.CancelledError):
await worker_task
finally:
_current_worker.reset(worker_token)
self._worker = None
finally:
# Reset ContextVar
_current_docket.reset(docket_token)
# Clear instance attribute
self._docket = None
finally:
# Reset server ContextVar
_current_server.reset(server_token)
@asynccontextmanager
async def _lifespan_manager(self: FastMCP) -> AsyncIterator[None]:
async with self._lifespan_lock:
if self._lifespan_result_set:
self._lifespan_ref_count += 1
should_enter_lifespan = False
else:
self._lifespan_ref_count = 1
should_enter_lifespan = True
if not should_enter_lifespan:
try:
yield
finally:
async with self._lifespan_lock:
self._lifespan_ref_count -= 1
if self._lifespan_ref_count == 0:
self._lifespan_result_set = False
self._lifespan_result = None
return
try:
async with (
self._lifespan(self) as user_lifespan_result,
self._docket_lifespan(),
):
self._lifespan_result = user_lifespan_result
self._lifespan_result_set = True
async with AsyncExitStack[bool | None]() as stack:
# Start lifespans for all providers
for provider in self.providers:
await stack.enter_async_context(provider.lifespan())
self._started.set()
try:
yield
finally:
self._started.clear()
finally:
async with self._lifespan_lock:
self._lifespan_ref_count -= 1
if self._lifespan_ref_count == 0:
self._lifespan_result_set = False
self._lifespan_result = None
def _setup_task_protocol_handlers(self: FastMCP) -> None:
"""Register SEP-1686 task protocol handlers with SDK.
Only registers handlers if docket is installed. Without docket,
task protocol requests will return "method not found" errors.
"""
from fastmcp.server.dependencies import is_docket_available
if not is_docket_available():
return
from mcp.types import (
CancelTaskRequest,
GetTaskPayloadRequest,
GetTaskRequest,
ListTasksRequest,
ServerResult,
)
from fastmcp.server.tasks.requests import (
tasks_cancel_handler,
tasks_get_handler,
tasks_list_handler,
tasks_result_handler,
)
# Manually register handlers (SDK decorators fail with locally-defined functions)
# SDK expects handlers that receive Request objects and return ServerResult
async def handle_get_task(req: GetTaskRequest) -> ServerResult:
params = req.params.model_dump(by_alias=True, exclude_none=True)
result = await tasks_get_handler(self, params)
return ServerResult(result)
async def handle_get_task_result(req: GetTaskPayloadRequest) -> ServerResult:
params = req.params.model_dump(by_alias=True, exclude_none=True)
result = await tasks_result_handler(self, params)
return ServerResult(result)
async def handle_list_tasks(req: ListTasksRequest) -> ServerResult:
params = (
req.params.model_dump(by_alias=True, exclude_none=True)
if req.params
else {}
)
result = await tasks_list_handler(self, params)
return ServerResult(result)
async def handle_cancel_task(req: CancelTaskRequest) -> ServerResult:
params = req.params.model_dump(by_alias=True, exclude_none=True)
result = await tasks_cancel_handler(self, params)
return ServerResult(result)
# Register directly with SDK (same as what decorators do internally)
self._mcp_server.request_handlers[GetTaskRequest] = handle_get_task
self._mcp_server.request_handlers[GetTaskPayloadRequest] = (
handle_get_task_result
)
self._mcp_server.request_handlers[ListTasksRequest] = handle_list_tasks
self._mcp_server.request_handlers[CancelTaskRequest] = handle_cancel_task
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/server/mixins/lifespan.py",
"license": "Apache License 2.0",
"lines": 202,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/server/mixins/mcp_operations.py | """MCP protocol handler setup and wire-format handlers for FastMCP Server."""
from __future__ import annotations
from collections.abc import Awaitable, Callable, Sequence
from typing import TYPE_CHECKING, Any, TypeVar, cast
import mcp.types
from mcp.shared.exceptions import McpError
from mcp.types import ContentBlock
from pydantic import AnyUrl
from fastmcp.exceptions import DisabledError, NotFoundError
from fastmcp.server.tasks.config import TaskMeta
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.pagination import paginate_sequence
from fastmcp.utilities.versions import VersionSpec, dedupe_with_versions
if TYPE_CHECKING:
from fastmcp.server.server import FastMCP
logger = get_logger(__name__)
PaginateT = TypeVar("PaginateT")
def _apply_pagination(
items: Sequence[PaginateT],
cursor: str | None,
page_size: int | None,
) -> tuple[list[PaginateT], str | None]:
"""Apply pagination to items, raising McpError for invalid cursors.
If page_size is None, returns all items without pagination.
"""
if page_size is None:
return list(items), None
try:
return paginate_sequence(items, cursor, page_size)
except ValueError as e:
raise McpError(mcp.types.ErrorData(code=-32602, message=str(e))) from e
class MCPOperationsMixin:
"""Mixin providing MCP protocol handler setup and wire-format handlers.
Note: Methods registered with SDK decorators (e.g., _list_tools_mcp, _call_tool_mcp)
cannot use `self: FastMCP` type hints because the SDK's `get_type_hints()` fails
to resolve FastMCP at runtime (it's only available under TYPE_CHECKING). When
type hints fail to resolve, the SDK falls back to calling handlers with no arguments.
These methods use untyped `self` to avoid this issue.
"""
def _setup_handlers(self: FastMCP) -> None:
"""Set up core MCP protocol handlers.
List handlers use SDK decorators that pass the request object to our handler
(needed for pagination cursor). The SDK also populates caches like _tool_cache.
Exception: list_resource_templates SDK decorator doesn't pass the request,
so we register that handler directly.
The call_tool decorator is from the SDK (supports CreateTaskResult + validate_input).
The read_resource and get_prompt decorators are from LowLevelServer to add
CreateTaskResult support until the SDK provides it natively.
"""
self._mcp_server.list_tools()(self._list_tools_mcp)
self._mcp_server.list_resources()(self._list_resources_mcp)
self._mcp_server.list_prompts()(self._list_prompts_mcp)
# list_resource_templates SDK decorator doesn't pass the request to handlers,
# so we register directly to get cursor access for pagination
self._mcp_server.request_handlers[mcp.types.ListResourceTemplatesRequest] = (
self._wrap_list_handler(self._list_resource_templates_mcp)
)
self._mcp_server.call_tool(validate_input=self.strict_input_validation)(
self._call_tool_mcp
)
self._mcp_server.read_resource()(self._read_resource_mcp)
self._mcp_server.get_prompt()(self._get_prompt_mcp)
# Register SEP-1686 task protocol handlers
self._setup_task_protocol_handlers()
def _wrap_list_handler(
self: FastMCP, handler: Callable[..., Awaitable[Any]]
) -> Callable[..., Awaitable[mcp.types.ServerResult]]:
"""Wrap a list handler to pass the request and return ServerResult."""
async def wrapper(request: Any) -> mcp.types.ServerResult:
result = await handler(request)
return mcp.types.ServerResult(result)
return wrapper
async def _list_tools_mcp(
self, request: mcp.types.ListToolsRequest
) -> mcp.types.ListToolsResult:
"""
List all available tools, in the format expected by the low-level MCP
server. Supports pagination when list_page_size is configured.
"""
# Cast self to FastMCP for type checking (see class docstring for why
# we can't use `self: FastMCP` annotation on SDK-registered handlers)
server = cast("FastMCP", self)
logger.debug(f"[{server.name}] Handler called: list_tools")
tools = dedupe_with_versions(list(await server.list_tools()), lambda t: t.name)
sdk_tools = [tool.to_mcp_tool(name=tool.name) for tool in tools]
# SDK may pass None for internal cache refresh despite type hint
cursor = (
request.params.cursor if request is not None and request.params else None
)
page, next_cursor = _apply_pagination(sdk_tools, cursor, server._list_page_size)
return mcp.types.ListToolsResult(tools=page, nextCursor=next_cursor)
async def _list_resources_mcp(
self, request: mcp.types.ListResourcesRequest
) -> mcp.types.ListResourcesResult:
"""
List all available resources, in the format expected by the low-level MCP
server. Supports pagination when list_page_size is configured.
"""
server = cast("FastMCP", self)
logger.debug(f"[{server.name}] Handler called: list_resources")
resources = dedupe_with_versions(
list(await server.list_resources()), lambda r: str(r.uri)
)
sdk_resources = [
resource.to_mcp_resource(uri=str(resource.uri)) for resource in resources
]
cursor = request.params.cursor if request.params else None
page, next_cursor = _apply_pagination(
sdk_resources, cursor, server._list_page_size
)
return mcp.types.ListResourcesResult(resources=page, nextCursor=next_cursor)
async def _list_resource_templates_mcp(
self, request: mcp.types.ListResourceTemplatesRequest
) -> mcp.types.ListResourceTemplatesResult:
"""
List all available resource templates, in the format expected by the low-level MCP
server. Supports pagination when list_page_size is configured.
"""
server = cast("FastMCP", self)
logger.debug(f"[{server.name}] Handler called: list_resource_templates")
templates = dedupe_with_versions(
list(await server.list_resource_templates()), lambda t: t.uri_template
)
sdk_templates = [
template.to_mcp_template(uriTemplate=template.uri_template)
for template in templates
]
cursor = request.params.cursor if request.params else None
page, next_cursor = _apply_pagination(
sdk_templates, cursor, server._list_page_size
)
return mcp.types.ListResourceTemplatesResult(
resourceTemplates=page, nextCursor=next_cursor
)
async def _list_prompts_mcp(
self, request: mcp.types.ListPromptsRequest
) -> mcp.types.ListPromptsResult:
"""
List all available prompts, in the format expected by the low-level MCP
server. Supports pagination when list_page_size is configured.
"""
server = cast("FastMCP", self)
logger.debug(f"[{server.name}] Handler called: list_prompts")
prompts = dedupe_with_versions(
list(await server.list_prompts()), lambda p: p.name
)
sdk_prompts = [prompt.to_mcp_prompt(name=prompt.name) for prompt in prompts]
cursor = request.params.cursor if request.params else None
page, next_cursor = _apply_pagination(
sdk_prompts, cursor, server._list_page_size
)
return mcp.types.ListPromptsResult(prompts=page, nextCursor=next_cursor)
async def _call_tool_mcp(
self, key: str, arguments: dict[str, Any]
) -> (
list[ContentBlock]
| tuple[list[ContentBlock], dict[str, Any]]
| mcp.types.CallToolResult
| mcp.types.CreateTaskResult
):
"""
Handle MCP 'callTool' requests.
Extracts task metadata from MCP request context and passes it explicitly
to call_tool(). The tool's _run() method handles the backgrounding decision,
ensuring middleware runs before Docket.
Args:
key: The name of the tool to call
arguments: Arguments to pass to the tool
Returns:
Tool result or CreateTaskResult for background execution
"""
server = cast("FastMCP", self)
logger.debug(
f"[{server.name}] Handler called: call_tool %s with %s", key, arguments
)
try:
# Extract version and task metadata from request context.
# fn_key is set by call_tool() after finding the tool.
version_str: str | None = None
task_meta: TaskMeta | None = None
try:
ctx = server._mcp_server.request_context
# Extract version from request-level _meta.fastmcp.version
if ctx.meta:
meta_dict = ctx.meta.model_dump(exclude_none=True)
version_str = meta_dict.get("fastmcp", {}).get("version")
# Extract SEP-1686 task metadata
if ctx.experimental.is_task:
mcp_task_meta = ctx.experimental.task_metadata
task_meta_dict = mcp_task_meta.model_dump(exclude_none=True)
task_meta = TaskMeta(ttl=task_meta_dict.get("ttl"))
except (AttributeError, LookupError):
pass
version = VersionSpec(eq=version_str) if version_str else None
result = await server.call_tool(
key, arguments, version=version, task_meta=task_meta
)
if isinstance(result, mcp.types.CreateTaskResult):
return result
return result.to_mcp_result()
except DisabledError as e:
raise NotFoundError(f"Unknown tool: {key!r}") from e
except NotFoundError as e:
raise NotFoundError(f"Unknown tool: {key!r}") from e
async def _read_resource_mcp(
self, uri: AnyUrl | str
) -> mcp.types.ReadResourceResult | mcp.types.CreateTaskResult:
"""Handle MCP 'readResource' requests.
Extracts task metadata from MCP request context and passes it explicitly
to read_resource(). The resource's _read() method handles the backgrounding
decision, ensuring middleware runs before Docket.
Args:
uri: The resource URI
Returns:
ReadResourceResult or CreateTaskResult for background execution
"""
server = cast("FastMCP", self)
logger.debug(f"[{server.name}] Handler called: read_resource %s", uri)
try:
# Extract version and task metadata from request context.
version_str: str | None = None
task_meta: TaskMeta | None = None
try:
ctx = server._mcp_server.request_context
# Extract version from _meta.fastmcp.version if provided
if ctx.meta:
meta_dict = ctx.meta.model_dump(exclude_none=True)
fastmcp_meta = meta_dict.get("fastmcp") or {}
version_str = fastmcp_meta.get("version")
# Extract SEP-1686 task metadata
if ctx.experimental.is_task:
mcp_task_meta = ctx.experimental.task_metadata
task_meta_dict = mcp_task_meta.model_dump(exclude_none=True)
task_meta = TaskMeta(ttl=task_meta_dict.get("ttl"))
except (AttributeError, LookupError):
pass
version = VersionSpec(eq=version_str) if version_str else None
result = await server.read_resource(
str(uri), version=version, task_meta=task_meta
)
if isinstance(result, mcp.types.CreateTaskResult):
return result
return result.to_mcp_result(uri)
except DisabledError as e:
raise McpError(
mcp.types.ErrorData(
code=-32002, message=f"Resource not found: {str(uri)!r}"
)
) from e
except NotFoundError as e:
raise McpError(
mcp.types.ErrorData(code=-32002, message=f"Resource not found: {e}")
) from e
async def _get_prompt_mcp(
self, name: str, arguments: dict[str, Any] | None
) -> mcp.types.GetPromptResult | mcp.types.CreateTaskResult:
"""Handle MCP 'getPrompt' requests.
Extracts task metadata from MCP request context and passes it explicitly
to render_prompt(). The prompt's _render() method handles the backgrounding
decision, ensuring middleware runs before Docket.
Args:
name: The prompt name
arguments: Prompt arguments
Returns:
GetPromptResult or CreateTaskResult for background execution
"""
server = cast("FastMCP", self)
logger.debug(
f"[{server.name}] Handler called: get_prompt %s with %s", name, arguments
)
try:
# Extract version and task metadata from request context.
# fn_key is set by render_prompt() after finding the prompt.
version_str: str | None = None
task_meta: TaskMeta | None = None
try:
ctx = server._mcp_server.request_context
# Extract version from request-level _meta.fastmcp.version
if ctx.meta:
meta_dict = ctx.meta.model_dump(exclude_none=True)
version_str = meta_dict.get("fastmcp", {}).get("version")
# Extract SEP-1686 task metadata
if ctx.experimental.is_task:
mcp_task_meta = ctx.experimental.task_metadata
task_meta_dict = mcp_task_meta.model_dump(exclude_none=True)
task_meta = TaskMeta(ttl=task_meta_dict.get("ttl"))
except (AttributeError, LookupError):
pass
version = VersionSpec(eq=version_str) if version_str else None
result = await server.render_prompt(
name, arguments, version=version, task_meta=task_meta
)
if isinstance(result, mcp.types.CreateTaskResult):
return result
return result.to_mcp_prompt_result()
except DisabledError as e:
raise NotFoundError(f"Unknown prompt: {name!r}") from e
except NotFoundError:
raise
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/server/mixins/mcp_operations.py",
"license": "Apache License 2.0",
"lines": 299,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/server/mixins/transport.py | """Transport-related methods for FastMCP Server."""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from functools import partial
from typing import TYPE_CHECKING, Any, Literal
import anyio
import uvicorn
from mcp.server.lowlevel.server import NotificationOptions
from mcp.server.stdio import stdio_server
from starlette.middleware import Middleware as ASGIMiddleware
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import BaseRoute, Route
import fastmcp
from fastmcp.server.event_store import EventStore
from fastmcp.server.http import (
StarletteWithLifespan,
create_sse_app,
create_streamable_http_app,
)
from fastmcp.utilities.cli import log_server_banner
from fastmcp.utilities.logging import get_logger, temporary_log_level
if TYPE_CHECKING:
from fastmcp.server.server import FastMCP, Transport
logger = get_logger(__name__)
class TransportMixin:
"""Mixin providing transport-related methods for FastMCP.
Includes HTTP/stdio/SSE transport handling and custom HTTP routes.
"""
async def run_async(
self: FastMCP,
transport: Transport | None = None,
show_banner: bool | None = None,
**transport_kwargs: Any,
) -> None:
"""Run the FastMCP server asynchronously.
Args:
transport: Transport protocol to use ("stdio", "http", "sse", or "streamable-http")
show_banner: Whether to display the server banner. If None, uses the
FASTMCP_SHOW_SERVER_BANNER setting (default: True).
"""
if show_banner is None:
show_banner = fastmcp.settings.show_server_banner
if transport is None:
transport = fastmcp.settings.transport
if transport not in {"stdio", "http", "sse", "streamable-http"}:
raise ValueError(f"Unknown transport: {transport}")
if transport == "stdio":
await self.run_stdio_async(
show_banner=show_banner,
**transport_kwargs,
)
elif transport in {"http", "sse", "streamable-http"}:
await self.run_http_async(
transport=transport,
show_banner=show_banner,
**transport_kwargs,
)
else:
raise ValueError(f"Unknown transport: {transport}")
def run(
self: FastMCP,
transport: Transport | None = None,
show_banner: bool | None = None,
**transport_kwargs: Any,
) -> None:
"""Run the FastMCP server. Note this is a synchronous function.
Args:
transport: Transport protocol to use ("http", "stdio", "sse", or "streamable-http")
show_banner: Whether to display the server banner. If None, uses the
FASTMCP_SHOW_SERVER_BANNER setting (default: True).
"""
anyio.run(
partial(
self.run_async,
transport,
show_banner=show_banner,
**transport_kwargs,
)
)
def custom_route(
self: FastMCP,
path: str,
methods: list[str],
name: str | None = None,
include_in_schema: bool = True,
) -> Callable[
[Callable[[Request], Awaitable[Response]]],
Callable[[Request], Awaitable[Response]],
]:
"""
Decorator to register a custom HTTP route on the FastMCP server.
Allows adding arbitrary HTTP endpoints outside the standard MCP protocol,
which can be useful for OAuth callbacks, health checks, or admin APIs.
The handler function must be an async function that accepts a Starlette
Request and returns a Response.
Args:
path: URL path for the route (e.g., "/auth/callback")
methods: List of HTTP methods to support (e.g., ["GET", "POST"])
name: Optional name for the route (to reference this route with
Starlette's reverse URL lookup feature)
include_in_schema: Whether to include in OpenAPI schema, defaults to True
Example:
Register a custom HTTP route for a health check endpoint:
```python
@server.custom_route("/health", methods=["GET"])
async def health_check(request: Request) -> Response:
return JSONResponse({"status": "ok"})
```
"""
def decorator(
fn: Callable[[Request], Awaitable[Response]],
) -> Callable[[Request], Awaitable[Response]]:
self._additional_http_routes.append(
Route(
path,
endpoint=fn,
methods=methods,
name=name,
include_in_schema=include_in_schema,
)
)
return fn
return decorator
def _get_additional_http_routes(self: FastMCP) -> list[BaseRoute]:
"""Get all additional HTTP routes including from providers.
Returns a list of all custom HTTP routes from this server and
from all providers that have HTTP routes (e.g., FastMCPProvider).
Returns:
List of Starlette BaseRoute objects
"""
return list(self._additional_http_routes)
async def run_stdio_async(
self: FastMCP,
show_banner: bool = True,
log_level: str | None = None,
stateless: bool = False,
) -> None:
"""Run the server using stdio transport.
Args:
show_banner: Whether to display the server banner
log_level: Log level for the server
stateless: Whether to run in stateless mode (no session initialization)
"""
from fastmcp.server.context import reset_transport, set_transport
# Display server banner
if show_banner:
log_server_banner(server=self)
token = set_transport("stdio")
try:
with temporary_log_level(log_level):
async with self._lifespan_manager():
async with stdio_server() as (read_stream, write_stream):
mode = " (stateless)" if stateless else ""
logger.info(
f"Starting MCP server {self.name!r} with transport 'stdio'{mode}"
)
await self._mcp_server.run(
read_stream,
write_stream,
self._mcp_server.create_initialization_options(
notification_options=NotificationOptions(
tools_changed=True
),
),
stateless=stateless,
)
finally:
reset_transport(token)
async def run_http_async(
self: FastMCP,
show_banner: bool = True,
transport: Literal["http", "streamable-http", "sse"] = "http",
host: str | None = None,
port: int | None = None,
log_level: str | None = None,
path: str | None = None,
uvicorn_config: dict[str, Any] | None = None,
middleware: list[ASGIMiddleware] | None = None,
json_response: bool | None = None,
stateless_http: bool | None = None,
stateless: bool | None = None,
) -> None:
"""Run the server using HTTP transport.
Args:
transport: Transport protocol to use - "http" (default), "streamable-http", or "sse"
host: Host address to bind to (defaults to settings.host)
port: Port to bind to (defaults to settings.port)
log_level: Log level for the server (defaults to settings.log_level)
path: Path for the endpoint (defaults to settings.streamable_http_path or settings.sse_path)
uvicorn_config: Additional configuration for the Uvicorn server
middleware: A list of middleware to apply to the app
json_response: Whether to use JSON response format (defaults to settings.json_response)
stateless_http: Whether to use stateless HTTP (defaults to settings.stateless_http)
stateless: Alias for stateless_http for CLI consistency
"""
# Allow stateless as alias for stateless_http
if stateless is not None and stateless_http is None:
stateless_http = stateless
# Resolve from settings/env var if not explicitly set
if stateless_http is None:
stateless_http = fastmcp.settings.stateless_http
# SSE doesn't support stateless mode
if stateless_http and transport == "sse":
raise ValueError("SSE transport does not support stateless mode")
host = host or fastmcp.settings.host
port = port or fastmcp.settings.port
default_log_level_to_use = (log_level or fastmcp.settings.log_level).lower()
app = self.http_app(
path=path,
transport=transport,
middleware=middleware,
json_response=json_response,
stateless_http=stateless_http,
)
# Display server banner
if show_banner:
log_server_banner(server=self)
uvicorn_config_from_user = uvicorn_config or {}
config_kwargs: dict[str, Any] = {
"timeout_graceful_shutdown": 0,
"lifespan": "on",
"ws": "websockets-sansio",
}
config_kwargs.update(uvicorn_config_from_user)
if "log_config" not in config_kwargs and "log_level" not in config_kwargs:
config_kwargs["log_level"] = default_log_level_to_use
with temporary_log_level(log_level):
async with self._lifespan_manager():
config = uvicorn.Config(app, host=host, port=port, **config_kwargs)
server = uvicorn.Server(config)
path = getattr(app.state, "path", "").lstrip("/")
mode = " (stateless)" if stateless_http else ""
logger.info(
f"Starting MCP server {self.name!r} with transport {transport!r}{mode} on http://{host}:{port}/{path}"
)
await server.serve()
def http_app(
self: FastMCP,
path: str | None = None,
middleware: list[ASGIMiddleware] | None = None,
json_response: bool | None = None,
stateless_http: bool | None = None,
transport: Literal["http", "streamable-http", "sse"] = "http",
event_store: EventStore | None = None,
retry_interval: int | None = None,
) -> StarletteWithLifespan:
"""Create a Starlette app using the specified HTTP transport.
Args:
path: The path for the HTTP endpoint
middleware: A list of middleware to apply to the app
json_response: Whether to use JSON response format
stateless_http: Whether to use stateless mode (new transport per request)
transport: Transport protocol to use - "http", "streamable-http", or "sse"
event_store: Optional event store for SSE polling/resumability. When set,
enables clients to reconnect and resume receiving events after
server-initiated disconnections. Only used with streamable-http transport.
retry_interval: Optional retry interval in milliseconds for SSE polling.
Controls how quickly clients should reconnect after server-initiated
disconnections. Requires event_store to be set. Only used with
streamable-http transport.
Returns:
A Starlette application configured with the specified transport
"""
if transport in ("streamable-http", "http"):
return create_streamable_http_app(
server=self,
streamable_http_path=path or fastmcp.settings.streamable_http_path,
event_store=event_store,
retry_interval=retry_interval,
auth=self.auth,
json_response=(
json_response
if json_response is not None
else fastmcp.settings.json_response
),
stateless_http=(
stateless_http
if stateless_http is not None
else fastmcp.settings.stateless_http
),
debug=fastmcp.settings.debug,
middleware=middleware,
)
elif transport == "sse":
return create_sse_app(
server=self,
message_path=fastmcp.settings.message_path,
sse_path=path or fastmcp.settings.sse_path,
auth=self.auth,
debug=fastmcp.settings.debug,
middleware=middleware,
)
else:
raise ValueError(f"Unknown transport: {transport}")
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/server/mixins/transport.py",
"license": "Apache License 2.0",
"lines": 295,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/server/providers/local_provider/decorators/prompts.py | """Prompt decorator mixin for LocalProvider.
This module provides the PromptDecoratorMixin class that adds prompt
registration functionality to LocalProvider.
"""
from __future__ import annotations
import inspect
from collections.abc import Callable
from functools import partial
from typing import TYPE_CHECKING, Any, TypeVar, overload
import mcp.types
from mcp.types import AnyFunction
import fastmcp
from fastmcp.prompts.function_prompt import FunctionPrompt
from fastmcp.prompts.prompt import Prompt
from fastmcp.server.auth.authorization import AuthCheck
from fastmcp.server.tasks.config import TaskConfig
if TYPE_CHECKING:
from fastmcp.server.providers.local_provider import LocalProvider
F = TypeVar("F", bound=Callable[..., Any])
class PromptDecoratorMixin:
"""Mixin class providing prompt decorator functionality for LocalProvider.
This mixin contains all methods related to:
- Prompt registration via add_prompt()
- Prompt decorator (@provider.prompt)
"""
def add_prompt(self: LocalProvider, prompt: Prompt | Callable[..., Any]) -> Prompt:
"""Add a prompt to this provider's storage.
Accepts either a Prompt object or a decorated function with __fastmcp__ metadata.
"""
enabled = True
if not isinstance(prompt, Prompt):
from fastmcp.decorators import get_fastmcp_meta
from fastmcp.prompts.function_prompt import PromptMeta
meta = get_fastmcp_meta(prompt)
if meta is not None and isinstance(meta, PromptMeta):
resolved_task = meta.task if meta.task is not None else False
enabled = meta.enabled
prompt = Prompt.from_function(
prompt,
name=meta.name,
version=meta.version,
title=meta.title,
description=meta.description,
icons=meta.icons,
tags=meta.tags,
meta=meta.meta,
task=resolved_task,
auth=meta.auth,
)
else:
raise TypeError(
f"Expected Prompt or @prompt-decorated function, got {type(prompt).__name__}. "
"Use @prompt decorator or pass a Prompt instance."
)
self._add_component(prompt)
if not enabled:
self.disable(keys={prompt.key})
return prompt
@overload
def prompt(
self: LocalProvider,
name_or_fn: F,
*,
name: str | None = None,
version: str | int | None = None,
title: str | None = None,
description: str | None = None,
icons: list[mcp.types.Icon] | None = None,
tags: set[str] | None = None,
enabled: bool = True,
meta: dict[str, Any] | None = None,
task: bool | TaskConfig | None = None,
auth: AuthCheck | list[AuthCheck] | None = None,
) -> F: ...
@overload
def prompt(
self: LocalProvider,
name_or_fn: str | None = None,
*,
name: str | None = None,
version: str | int | None = None,
title: str | None = None,
description: str | None = None,
icons: list[mcp.types.Icon] | None = None,
tags: set[str] | None = None,
enabled: bool = True,
meta: dict[str, Any] | None = None,
task: bool | TaskConfig | None = None,
auth: AuthCheck | list[AuthCheck] | None = None,
) -> Callable[[F], F]: ...
def prompt(
self: LocalProvider,
name_or_fn: str | AnyFunction | None = None,
*,
name: str | None = None,
version: str | int | None = None,
title: str | None = None,
description: str | None = None,
icons: list[mcp.types.Icon] | None = None,
tags: set[str] | None = None,
enabled: bool = True,
meta: dict[str, Any] | None = None,
task: bool | TaskConfig | None = None,
auth: AuthCheck | list[AuthCheck] | None = None,
) -> (
Callable[[AnyFunction], FunctionPrompt]
| FunctionPrompt
| partial[Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt]
):
"""Decorator to register a prompt.
This decorator supports multiple calling patterns:
- @provider.prompt (without parentheses)
- @provider.prompt() (with empty parentheses)
- @provider.prompt("custom_name") (with name as first argument)
- @provider.prompt(name="custom_name") (with name as keyword argument)
- provider.prompt(function, name="custom_name") (direct function call)
Args:
name_or_fn: Either a function (when used as @prompt), a string name, or None
name: Optional name for the prompt (keyword-only, alternative to name_or_fn)
title: Optional title for the prompt
description: Optional description of what the prompt does
icons: Optional icons for the prompt
tags: Optional set of tags for categorizing the prompt
enabled: Whether the prompt is enabled (default True). If False, adds to blocklist.
meta: Optional meta information about the prompt
task: Optional task configuration for background execution
auth: Optional authorization checks for the prompt
Returns:
The registered FunctionPrompt or a decorator function.
Example:
```python
provider = LocalProvider()
@provider.prompt
def analyze(topic: str) -> list:
return [{"role": "user", "content": f"Analyze: {topic}"}]
@provider.prompt("custom_name")
def my_prompt(data: str) -> list:
return [{"role": "user", "content": data}]
```
"""
if isinstance(name_or_fn, classmethod):
raise TypeError(
"To decorate a classmethod, use @classmethod above @prompt. "
"See https://gofastmcp.com/servers/prompts#using-with-methods"
)
def decorate_and_register(
fn: AnyFunction, prompt_name: str | None
) -> FunctionPrompt | AnyFunction:
# Check for unbound method
try:
params = list(inspect.signature(fn).parameters.keys())
except (ValueError, TypeError):
params = []
if params and params[0] in ("self", "cls"):
fn_name = getattr(fn, "__name__", "function")
raise TypeError(
f"The function '{fn_name}' has '{params[0]}' as its first parameter. "
f"Use the standalone @prompt decorator and register the bound method:\n\n"
f" from fastmcp.prompts import prompt\n\n"
f" class MyClass:\n"
f" @prompt\n"
f" def {fn_name}(...):\n"
f" ...\n\n"
f" obj = MyClass()\n"
f" mcp.add_prompt(obj.{fn_name})\n\n"
f"See https://gofastmcp.com/servers/prompts#using-with-methods"
)
resolved_task: bool | TaskConfig = task if task is not None else False
if fastmcp.settings.decorator_mode == "object":
prompt_obj = Prompt.from_function(
fn,
name=prompt_name,
version=version,
title=title,
description=description,
icons=icons,
tags=tags,
meta=meta,
task=resolved_task,
auth=auth,
)
self._add_component(prompt_obj)
if not enabled:
self.disable(keys={prompt_obj.key})
return prompt_obj
else:
from fastmcp.prompts.function_prompt import PromptMeta
metadata = PromptMeta(
name=prompt_name,
version=version,
title=title,
description=description,
icons=icons,
tags=tags,
meta=meta,
task=task,
auth=auth,
enabled=enabled,
)
target = fn.__func__ if hasattr(fn, "__func__") else fn
target.__fastmcp__ = metadata # type: ignore[attr-defined]
self.add_prompt(fn)
return fn
if inspect.isroutine(name_or_fn):
return decorate_and_register(name_or_fn, name)
elif isinstance(name_or_fn, str):
if name is not None:
raise TypeError(
f"Cannot specify both a name as first argument and as keyword argument. "
f"Use either @prompt('{name_or_fn}') or @prompt(name='{name}'), not both."
)
prompt_name = name_or_fn
elif name_or_fn is None:
prompt_name = name
else:
raise TypeError(f"Invalid first argument: {type(name_or_fn)}")
return partial(
self.prompt,
name=prompt_name,
version=version,
title=title,
description=description,
icons=icons,
tags=tags,
meta=meta,
enabled=enabled,
task=task,
auth=auth,
)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/server/providers/local_provider/decorators/prompts.py",
"license": "Apache License 2.0",
"lines": 229,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/server/providers/local_provider/decorators/resources.py | """Resource decorator mixin for LocalProvider.
This module provides the ResourceDecoratorMixin class that adds resource
and template registration functionality to LocalProvider.
"""
from __future__ import annotations
import inspect
from collections.abc import Callable
from typing import TYPE_CHECKING, Any, TypeVar
import mcp.types
from mcp.types import Annotations, AnyFunction
import fastmcp
from fastmcp.resources.function_resource import resource as standalone_resource
from fastmcp.resources.resource import Resource
from fastmcp.resources.template import ResourceTemplate
from fastmcp.server.auth.authorization import AuthCheck
from fastmcp.server.tasks.config import TaskConfig
if TYPE_CHECKING:
from fastmcp.server.providers.local_provider import LocalProvider
F = TypeVar("F", bound=Callable[..., Any])
class ResourceDecoratorMixin:
"""Mixin class providing resource decorator functionality for LocalProvider.
This mixin contains all methods related to:
- Resource registration via add_resource()
- Resource template registration via add_template()
- Resource decorator (@provider.resource)
"""
def add_resource(
self: LocalProvider, resource: Resource | ResourceTemplate | Callable[..., Any]
) -> Resource | ResourceTemplate:
"""Add a resource to this provider's storage.
Accepts either a Resource/ResourceTemplate object or a decorated function with __fastmcp__ metadata.
"""
enabled = True
if not isinstance(resource, (Resource, ResourceTemplate)):
from fastmcp.decorators import get_fastmcp_meta
from fastmcp.resources.function_resource import ResourceMeta
from fastmcp.server.dependencies import without_injected_parameters
meta = get_fastmcp_meta(resource)
if meta is not None and isinstance(meta, ResourceMeta):
resolved_task = meta.task if meta.task is not None else False
enabled = meta.enabled
has_uri_params = "{" in meta.uri and "}" in meta.uri
wrapper_fn = without_injected_parameters(resource)
has_func_params = bool(inspect.signature(wrapper_fn).parameters)
if has_uri_params or has_func_params:
resource = ResourceTemplate.from_function(
fn=resource,
uri_template=meta.uri,
name=meta.name,
version=meta.version,
title=meta.title,
description=meta.description,
icons=meta.icons,
mime_type=meta.mime_type,
tags=meta.tags,
annotations=meta.annotations,
meta=meta.meta,
task=resolved_task,
auth=meta.auth,
)
else:
resource = Resource.from_function(
fn=resource,
uri=meta.uri,
name=meta.name,
version=meta.version,
title=meta.title,
description=meta.description,
icons=meta.icons,
mime_type=meta.mime_type,
tags=meta.tags,
annotations=meta.annotations,
meta=meta.meta,
task=resolved_task,
auth=meta.auth,
)
else:
raise TypeError(
f"Expected Resource, ResourceTemplate, or @resource-decorated function, got {type(resource).__name__}. "
"Use @resource('uri') decorator or pass a Resource/ResourceTemplate instance."
)
self._add_component(resource)
if not enabled:
self.disable(keys={resource.key})
return resource
def add_template(
self: LocalProvider, template: ResourceTemplate
) -> ResourceTemplate:
"""Add a resource template to this provider's storage."""
return self._add_component(template)
def resource(
self: LocalProvider,
uri: str,
*,
name: str | None = None,
version: str | int | None = None,
title: str | None = None,
description: str | None = None,
icons: list[mcp.types.Icon] | None = None,
mime_type: str | None = None,
tags: set[str] | None = None,
enabled: bool = True,
annotations: Annotations | dict[str, Any] | None = None,
meta: dict[str, Any] | None = None,
task: bool | TaskConfig | None = None,
auth: AuthCheck | list[AuthCheck] | None = None,
) -> Callable[[F], F]:
"""Decorator to register a function as a resource.
If the URI contains parameters (e.g. "resource://{param}") or the function
has parameters, it will be registered as a template resource.
Args:
uri: URI for the resource (e.g. "resource://my-resource" or "resource://{param}")
name: Optional name for the resource
title: Optional title for the resource
description: Optional description of the resource
icons: Optional icons for the resource
mime_type: Optional MIME type for the resource
tags: Optional set of tags for categorizing the resource
enabled: Whether the resource is enabled (default True). If False, adds to blocklist.
annotations: Optional annotations about the resource's behavior
meta: Optional meta information about the resource
task: Optional task configuration for background execution
auth: Optional authorization checks for the resource
Returns:
A decorator function.
Example:
```python
provider = LocalProvider()
@provider.resource("data://config")
def get_config() -> str:
return '{"setting": "value"}'
@provider.resource("data://{city}/weather")
def get_weather(city: str) -> str:
return f"Weather for {city}"
```
"""
if isinstance(annotations, dict):
annotations = Annotations(**annotations)
if inspect.isroutine(uri):
raise TypeError(
"The @resource decorator was used incorrectly. "
"It requires a URI as the first argument. "
"Use @resource('uri') instead of @resource"
)
resolved_task: bool | TaskConfig = task if task is not None else False
def decorator(fn: AnyFunction) -> Any:
# Check for unbound method
try:
params = list(inspect.signature(fn).parameters.keys())
except (ValueError, TypeError):
params = []
if params and params[0] in ("self", "cls"):
fn_name = getattr(fn, "__name__", "function")
raise TypeError(
f"The function '{fn_name}' has '{params[0]}' as its first parameter. "
f"Use the standalone @resource decorator and register the bound method:\n\n"
f" from fastmcp.resources import resource\n\n"
f" class MyClass:\n"
f" @resource('{uri}')\n"
f" def {fn_name}(...):\n"
f" ...\n\n"
f" obj = MyClass()\n"
f" mcp.add_resource(obj.{fn_name})\n\n"
f"See https://gofastmcp.com/servers/resources#using-with-methods"
)
if fastmcp.settings.decorator_mode == "object":
create_resource = standalone_resource(
uri,
name=name,
version=version,
title=title,
description=description,
icons=icons,
mime_type=mime_type,
tags=tags,
annotations=annotations,
meta=meta,
task=resolved_task,
auth=auth,
)
obj = create_resource(fn)
# In legacy mode, standalone_resource always returns a component
assert isinstance(obj, (Resource, ResourceTemplate))
if isinstance(obj, ResourceTemplate):
self.add_template(obj)
if not enabled:
self.disable(keys={obj.key})
else:
self.add_resource(obj)
if not enabled:
self.disable(keys={obj.key})
return obj
else:
from fastmcp.resources.function_resource import ResourceMeta
metadata = ResourceMeta(
uri=uri,
name=name,
version=version,
title=title,
description=description,
icons=icons,
tags=tags,
mime_type=mime_type,
annotations=annotations,
meta=meta,
task=task,
auth=auth,
enabled=enabled,
)
target = fn.__func__ if hasattr(fn, "__func__") else fn
target.__fastmcp__ = metadata # type: ignore[attr-defined]
self.add_resource(fn)
return fn
return decorator
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/server/providers/local_provider/decorators/resources.py",
"license": "Apache License 2.0",
"lines": 214,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/server/providers/local_provider/decorators/tools.py | """Tool decorator mixin for LocalProvider.
This module provides the ToolDecoratorMixin class that adds tool
registration functionality to LocalProvider.
"""
from __future__ import annotations
import inspect
import types
import warnings
from collections.abc import Callable
from functools import partial
from typing import (
TYPE_CHECKING,
Annotated,
Any,
Literal,
TypeVar,
Union,
get_args,
get_origin,
overload,
)
import mcp.types
from mcp.types import AnyFunction, ToolAnnotations
import fastmcp
from fastmcp.server.auth.authorization import AuthCheck
from fastmcp.server.tasks.config import TaskConfig
from fastmcp.tools.function_tool import FunctionTool
from fastmcp.tools.tool import Tool
from fastmcp.utilities.types import NotSet, NotSetT
try:
from prefab_ui.app import PrefabApp as _PrefabApp
from prefab_ui.components.base import Component as _PrefabComponent
_HAS_PREFAB = True
except ImportError:
_HAS_PREFAB = False
if TYPE_CHECKING:
from fastmcp.server.providers.local_provider import LocalProvider
from fastmcp.tools.tool import ToolResultSerializerType
F = TypeVar("F", bound=Callable[..., Any])
DuplicateBehavior = Literal["error", "warn", "replace", "ignore"]
PREFAB_RENDERER_URI = "ui://prefab/renderer.html"
def _is_prefab_type(tp: Any) -> bool:
"""Check if *tp* is or contains a prefab type, recursing through unions and Annotated."""
if isinstance(tp, type) and issubclass(tp, (_PrefabApp, _PrefabComponent)):
return True
origin = get_origin(tp)
if origin is Union or origin is types.UnionType or origin is Annotated:
return any(_is_prefab_type(a) for a in get_args(tp))
return False
def _has_prefab_return_type(tool: Tool) -> bool:
"""Check if a FunctionTool's return type annotation is a prefab type."""
if not _HAS_PREFAB or not isinstance(tool, FunctionTool):
return False
rt = tool.return_type
if rt is None or rt is inspect.Parameter.empty:
return False
return _is_prefab_type(rt)
def _ensure_prefab_renderer(provider: LocalProvider) -> None:
"""Lazily register the shared prefab renderer as a ui:// resource."""
from prefab_ui.renderer import get_renderer_csp, get_renderer_html
from fastmcp.resources.types import TextResource
from fastmcp.server.apps import (
UI_MIME_TYPE,
AppConfig,
ResourceCSP,
app_config_to_meta_dict,
)
renderer_key = f"resource:{PREFAB_RENDERER_URI}@"
if renderer_key in provider._components:
return
csp = get_renderer_csp()
resource_app = AppConfig(
csp=ResourceCSP(
resource_domains=csp.get("resource_domains"),
connect_domains=csp.get("connect_domains"),
)
)
resource = TextResource(
uri=PREFAB_RENDERER_URI, # type: ignore[arg-type] # AnyUrl accepts ui:// scheme at runtime
name="Prefab Renderer",
text=get_renderer_html(),
mime_type=UI_MIME_TYPE,
meta={"ui": app_config_to_meta_dict(resource_app)},
)
provider._add_component(resource)
def _expand_prefab_ui_meta(tool: Tool) -> None:
"""Expand meta["ui"] = True into the full AppConfig dict for a prefab tool."""
from prefab_ui.renderer import get_renderer_csp
from fastmcp.server.apps import AppConfig, ResourceCSP, app_config_to_meta_dict
csp = get_renderer_csp()
app_config = AppConfig(
resource_uri=PREFAB_RENDERER_URI,
csp=ResourceCSP(
resource_domains=csp.get("resource_domains"),
connect_domains=csp.get("connect_domains"),
),
)
meta = dict(tool.meta) if tool.meta else {}
meta["ui"] = app_config_to_meta_dict(app_config)
tool.meta = meta
def _maybe_apply_prefab_ui(provider: LocalProvider, tool: Tool) -> None:
"""Auto-wire prefab UI metadata and renderer resource if needed."""
if not _HAS_PREFAB:
return
meta = tool.meta or {}
ui = meta.get("ui")
if ui is True:
# Explicit app=True: expand to full AppConfig and register renderer
_ensure_prefab_renderer(provider)
_expand_prefab_ui_meta(tool)
elif ui is None and _has_prefab_return_type(tool):
# Inference: return type is a prefab type, auto-wire
_ensure_prefab_renderer(provider)
_expand_prefab_ui_meta(tool)
# If ui is a dict, it's already manually configured — leave it alone
class ToolDecoratorMixin:
"""Mixin class providing tool decorator functionality for LocalProvider.
This mixin contains all methods related to:
- Tool registration via add_tool()
- Tool decorator (@provider.tool)
"""
def add_tool(self: LocalProvider, tool: Tool | Callable[..., Any]) -> Tool:
"""Add a tool to this provider's storage.
Accepts either a Tool object or a decorated function with __fastmcp__ metadata.
"""
enabled = True
if not isinstance(tool, Tool):
from fastmcp.decorators import get_fastmcp_meta
from fastmcp.tools.function_tool import ToolMeta
fmeta = get_fastmcp_meta(tool)
if fmeta is not None and isinstance(fmeta, ToolMeta):
resolved_task = fmeta.task if fmeta.task is not None else False
enabled = fmeta.enabled
# Merge ToolMeta.app into the meta dict
tool_meta = fmeta.meta
if fmeta.app is not None:
from fastmcp.server.apps import app_config_to_meta_dict
tool_meta = dict(tool_meta) if tool_meta else {}
if fmeta.app is True:
tool_meta["ui"] = True
else:
tool_meta["ui"] = app_config_to_meta_dict(fmeta.app)
tool = Tool.from_function(
tool,
name=fmeta.name,
version=fmeta.version,
title=fmeta.title,
description=fmeta.description,
icons=fmeta.icons,
tags=fmeta.tags,
output_schema=fmeta.output_schema,
annotations=fmeta.annotations,
meta=tool_meta,
task=resolved_task,
exclude_args=fmeta.exclude_args,
serializer=fmeta.serializer,
timeout=fmeta.timeout,
auth=fmeta.auth,
)
else:
tool = Tool.from_function(tool)
self._add_component(tool)
if not enabled:
self.disable(keys={tool.key})
_maybe_apply_prefab_ui(self, tool)
return tool
@overload
def tool(
self: LocalProvider,
name_or_fn: F,
*,
name: str | None = None,
version: str | int | None = None,
title: str | None = None,
description: str | None = None,
icons: list[mcp.types.Icon] | None = None,
tags: set[str] | None = None,
output_schema: dict[str, Any] | NotSetT | None = NotSet,
annotations: ToolAnnotations | dict[str, Any] | None = None,
exclude_args: list[str] | None = None,
meta: dict[str, Any] | None = None,
enabled: bool = True,
task: bool | TaskConfig | None = None,
serializer: ToolResultSerializerType | None = None, # Deprecated
timeout: float | None = None,
auth: AuthCheck | list[AuthCheck] | None = None,
) -> F: ...
@overload
def tool(
self: LocalProvider,
name_or_fn: str | None = None,
*,
name: str | None = None,
version: str | int | None = None,
title: str | None = None,
description: str | None = None,
icons: list[mcp.types.Icon] | None = None,
tags: set[str] | None = None,
output_schema: dict[str, Any] | NotSetT | None = NotSet,
annotations: ToolAnnotations | dict[str, Any] | None = None,
exclude_args: list[str] | None = None,
meta: dict[str, Any] | None = None,
enabled: bool = True,
task: bool | TaskConfig | None = None,
serializer: ToolResultSerializerType | None = None, # Deprecated
timeout: float | None = None,
auth: AuthCheck | list[AuthCheck] | None = None,
) -> Callable[[F], F]: ...
# NOTE: This method mirrors fastmcp.tools.tool() but adds registration,
# the `enabled` param, and supports deprecated params (serializer, exclude_args).
# When deprecated params are removed, this should delegate to the standalone
# decorator to reduce duplication.
def tool(
self: LocalProvider,
name_or_fn: str | AnyFunction | None = None,
*,
name: str | None = None,
version: str | int | None = None,
title: str | None = None,
description: str | None = None,
icons: list[mcp.types.Icon] | None = None,
tags: set[str] | None = None,
output_schema: dict[str, Any] | NotSetT | None = NotSet,
annotations: ToolAnnotations | dict[str, Any] | None = None,
exclude_args: list[str] | None = None,
meta: dict[str, Any] | None = None,
enabled: bool = True,
task: bool | TaskConfig | None = None,
serializer: ToolResultSerializerType | None = None, # Deprecated
timeout: float | None = None,
auth: AuthCheck | list[AuthCheck] | None = None,
) -> (
Callable[[AnyFunction], FunctionTool]
| FunctionTool
| partial[Callable[[AnyFunction], FunctionTool] | FunctionTool]
):
"""Decorator to register a tool.
This decorator supports multiple calling patterns:
- @provider.tool (without parentheses)
- @provider.tool() (with empty parentheses)
- @provider.tool("custom_name") (with name as first argument)
- @provider.tool(name="custom_name") (with name as keyword argument)
- provider.tool(function, name="custom_name") (direct function call)
Args:
name_or_fn: Either a function (when used as @tool), a string name, or None
name: Optional name for the tool (keyword-only, alternative to name_or_fn)
title: Optional title for the tool
description: Optional description of what the tool does
icons: Optional icons for the tool
tags: Optional set of tags for categorizing the tool
output_schema: Optional JSON schema for the tool's output
annotations: Optional annotations about the tool's behavior
exclude_args: Optional list of argument names to exclude from the tool schema
meta: Optional meta information about the tool
enabled: Whether the tool is enabled (default True). If False, adds to blocklist.
task: Optional task configuration for background execution
serializer: Deprecated. Return ToolResult from your tools for full control over serialization.
Returns:
The registered FunctionTool or a decorator function.
Example:
```python
provider = LocalProvider()
@provider.tool
def greet(name: str) -> str:
return f"Hello, {name}!"
@provider.tool("custom_name")
def my_tool(x: int) -> str:
return str(x)
```
"""
if serializer is not None and fastmcp.settings.deprecation_warnings:
warnings.warn(
"The `serializer` parameter is deprecated. "
"Return ToolResult from your tools for full control over serialization. "
"See https://gofastmcp.com/servers/tools#custom-serialization for migration examples.",
DeprecationWarning,
stacklevel=2,
)
if isinstance(annotations, dict):
annotations = ToolAnnotations(**annotations)
if isinstance(name_or_fn, classmethod):
raise TypeError(
"To decorate a classmethod, use @classmethod above @tool. "
"See https://gofastmcp.com/servers/tools#using-with-methods"
)
def decorate_and_register(
fn: AnyFunction, tool_name: str | None
) -> FunctionTool | AnyFunction:
# Check for unbound method
try:
params = list(inspect.signature(fn).parameters.keys())
except (ValueError, TypeError):
params = []
if params and params[0] in ("self", "cls"):
fn_name = getattr(fn, "__name__", "function")
raise TypeError(
f"The function '{fn_name}' has '{params[0]}' as its first parameter. "
f"Use the standalone @tool decorator and register the bound method:\n\n"
f" from fastmcp.tools import tool\n\n"
f" class MyClass:\n"
f" @tool\n"
f" def {fn_name}(...):\n"
f" ...\n\n"
f" obj = MyClass()\n"
f" mcp.add_tool(obj.{fn_name})\n\n"
f"See https://gofastmcp.com/servers/tools#using-with-methods"
)
resolved_task: bool | TaskConfig = task if task is not None else False
if fastmcp.settings.decorator_mode == "object":
tool_obj = Tool.from_function(
fn,
name=tool_name,
version=version,
title=title,
description=description,
icons=icons,
tags=tags,
output_schema=output_schema,
annotations=annotations,
exclude_args=exclude_args,
meta=meta,
serializer=serializer,
task=resolved_task,
timeout=timeout,
auth=auth,
)
self._add_component(tool_obj)
if not enabled:
self.disable(keys={tool_obj.key})
_maybe_apply_prefab_ui(self, tool_obj)
return tool_obj
else:
from fastmcp.tools.function_tool import ToolMeta
metadata = ToolMeta(
name=tool_name,
version=version,
title=title,
description=description,
icons=icons,
tags=tags,
output_schema=output_schema,
annotations=annotations,
meta=meta,
task=task,
exclude_args=exclude_args,
serializer=serializer,
timeout=timeout,
auth=auth,
enabled=enabled,
)
target = fn.__func__ if hasattr(fn, "__func__") else fn
target.__fastmcp__ = metadata # type: ignore[attr-defined]
tool_obj = self.add_tool(fn)
return fn
if inspect.isroutine(name_or_fn):
return decorate_and_register(name_or_fn, name)
elif isinstance(name_or_fn, str):
# Case 3: @tool("custom_name") - name passed as first argument
if name is not None:
raise TypeError(
"Cannot specify both a name as first argument and as keyword argument. "
f"Use either @tool('{name_or_fn}') or @tool(name='{name}'), not both."
)
tool_name = name_or_fn
elif name_or_fn is None:
# Case 4: @tool() or @tool(name="something") - use keyword name
tool_name = name
else:
raise TypeError(
f"First argument to @tool must be a function, string, or None, got {type(name_or_fn)}"
)
# Return partial for cases where we need to wait for the function
return partial(
self.tool,
name=tool_name,
version=version,
title=title,
description=description,
icons=icons,
tags=tags,
output_schema=output_schema,
annotations=annotations,
exclude_args=exclude_args,
meta=meta,
enabled=enabled,
task=task,
serializer=serializer,
timeout=timeout,
auth=auth,
)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/server/providers/local_provider/decorators/tools.py",
"license": "Apache License 2.0",
"lines": 390,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/server/providers/local_provider/local_provider.py | """LocalProvider for locally-defined MCP components.
This module provides the `LocalProvider` class that manages tools, resources,
templates, and prompts registered via decorators or direct methods.
LocalProvider can be used standalone and attached to multiple servers:
```python
from fastmcp.server.providers import LocalProvider
# Create a reusable provider with tools
provider = LocalProvider()
@provider.tool
def greet(name: str) -> str:
return f"Hello, {name}!"
# Attach to any server
from fastmcp import FastMCP
server1 = FastMCP("Server1", providers=[provider])
server2 = FastMCP("Server2", providers=[provider])
```
"""
from __future__ import annotations
from collections.abc import Sequence
from typing import Literal, TypeVar
from fastmcp.prompts.prompt import Prompt
from fastmcp.resources.resource import Resource
from fastmcp.resources.template import ResourceTemplate
from fastmcp.server.providers.base import Provider
from fastmcp.server.providers.local_provider.decorators import (
PromptDecoratorMixin,
ResourceDecoratorMixin,
ToolDecoratorMixin,
)
from fastmcp.tools.tool import Tool
from fastmcp.utilities.components import FastMCPComponent
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.versions import VersionSpec, version_sort_key
logger = get_logger(__name__)
DuplicateBehavior = Literal["error", "warn", "replace", "ignore"]
_C = TypeVar("_C", bound=FastMCPComponent)
class LocalProvider(
Provider,
ToolDecoratorMixin,
ResourceDecoratorMixin,
PromptDecoratorMixin,
):
"""Provider for locally-defined components.
Supports decorator-based registration (`@provider.tool`, `@provider.resource`,
`@provider.prompt`) and direct object registration methods.
When used standalone, LocalProvider uses default settings. When attached
to a FastMCP server via the server's decorators, server-level settings
like `_tool_serializer` and `_support_tasks_by_default` are injected.
Example:
```python
from fastmcp.server.providers import LocalProvider
# Standalone usage
provider = LocalProvider()
@provider.tool
def greet(name: str) -> str:
return f"Hello, {name}!"
@provider.resource("data://config")
def get_config() -> str:
return '{"setting": "value"}'
@provider.prompt
def analyze(topic: str) -> list:
return [{"role": "user", "content": f"Analyze: {topic}"}]
# Attach to server(s)
from fastmcp import FastMCP
server = FastMCP("MyServer", providers=[provider])
```
"""
def __init__(
self,
on_duplicate: DuplicateBehavior = "error",
) -> None:
"""Initialize a LocalProvider with empty storage.
Args:
on_duplicate: Behavior when adding a component that already exists:
- "error": Raise ValueError
- "warn": Log warning and replace
- "replace": Silently replace
- "ignore": Keep existing, return it
"""
super().__init__()
self._on_duplicate = on_duplicate
# Unified component storage - keyed by prefixed key (e.g., "tool:name", "resource:uri")
self._components: dict[str, FastMCPComponent] = {}
# =========================================================================
# Storage methods
# =========================================================================
def _get_component_identity(self, component: FastMCPComponent) -> tuple[type, str]:
"""Get the identity (type, name/uri) for a component.
Returns:
A tuple of (component_type, logical_name) where logical_name is
the name for tools/prompts or URI for resources/templates.
"""
if isinstance(component, Tool):
return (Tool, component.name)
elif isinstance(component, ResourceTemplate):
return (ResourceTemplate, component.uri_template)
elif isinstance(component, Resource):
return (Resource, str(component.uri))
elif isinstance(component, Prompt):
return (Prompt, component.name)
else:
# Fall back to key without version suffix
key = component.key
base_key = key.rsplit("@", 1)[0] if "@" in key else key
return (type(component), base_key)
def _check_version_mixing(self, component: _C) -> None:
"""Check that versioned and unversioned components aren't mixed.
LocalProvider enforces a simple rule: for any given name/URI, all
registered components must either be versioned or unversioned, not both.
This prevents confusing situations where unversioned components can't
be filtered out by version filters.
Args:
component: The component being added.
Raises:
ValueError: If adding would mix versioned and unversioned components.
"""
comp_type, logical_name = self._get_component_identity(component)
is_versioned = component.version is not None
# Check all existing components of the same type and logical name
for existing in self._components.values():
if not isinstance(existing, comp_type):
continue
_, existing_name = self._get_component_identity(existing)
if existing_name != logical_name:
continue
existing_versioned = existing.version is not None
if is_versioned != existing_versioned:
type_name = comp_type.__name__.lower()
if is_versioned:
raise ValueError(
f"Cannot add versioned {type_name} {logical_name!r} "
f"(version={component.version!r}): an unversioned "
f"{type_name} with this name already exists. "
f"Either version all components or none."
)
else:
raise ValueError(
f"Cannot add unversioned {type_name} {logical_name!r}: "
f"versioned {type_name}s with this name already exist "
f"(e.g., version={existing.version!r}). "
f"Either version all components or none."
)
def _add_component(self, component: _C) -> _C:
"""Add a component to unified storage.
Args:
component: The component to add.
Returns:
The component that was added (or existing if on_duplicate="ignore").
"""
existing = self._components.get(component.key)
if existing:
if self._on_duplicate == "error":
raise ValueError(f"Component already exists: {component.key}")
elif self._on_duplicate == "warn":
logger.warning(f"Component already exists: {component.key}")
elif self._on_duplicate == "ignore":
return existing # type: ignore[return-value]
# "replace" and "warn" fall through to add
# Check for versioned/unversioned mixing before adding
self._check_version_mixing(component)
self._components[component.key] = component
return component
def _remove_component(self, key: str) -> None:
"""Remove a component from unified storage.
Args:
key: The prefixed key of the component.
Raises:
KeyError: If the component is not found.
"""
component = self._components.get(key)
if component is None:
raise KeyError(f"Component {key!r} not found")
del self._components[key]
def _get_component(self, key: str) -> FastMCPComponent | None:
"""Get a component by its prefixed key.
Args:
key: The prefixed key (e.g., "tool:name", "resource:uri").
Returns:
The component, or None if not found.
"""
return self._components.get(key)
def remove_tool(self, name: str, version: str | None = None) -> None:
"""Remove tool(s) from this provider's storage.
Args:
name: The tool name.
version: If None, removes ALL versions. If specified, removes only that version.
Raises:
KeyError: If no matching tool is found.
"""
if version is None:
# Remove all versions
keys_to_remove = [
k
for k, c in self._components.items()
if isinstance(c, Tool) and c.name == name
]
if not keys_to_remove:
raise KeyError(f"Tool {name!r} not found")
for key in keys_to_remove:
self._remove_component(key)
else:
# Remove specific version - key format is "tool:name@version"
key = f"{Tool.make_key(name)}@{version}"
if key not in self._components:
raise KeyError(f"Tool {name!r} version {version!r} not found")
self._remove_component(key)
def remove_resource(self, uri: str, version: str | None = None) -> None:
"""Remove resource(s) from this provider's storage.
Args:
uri: The resource URI.
version: If None, removes ALL versions. If specified, removes only that version.
Raises:
KeyError: If no matching resource is found.
"""
if version is None:
# Remove all versions
keys_to_remove = [
k
for k, c in self._components.items()
if isinstance(c, Resource) and str(c.uri) == uri
]
if not keys_to_remove:
raise KeyError(f"Resource {uri!r} not found")
for key in keys_to_remove:
self._remove_component(key)
else:
# Remove specific version
key = f"{Resource.make_key(uri)}@{version}"
if key not in self._components:
raise KeyError(f"Resource {uri!r} version {version!r} not found")
self._remove_component(key)
def remove_template(self, uri_template: str, version: str | None = None) -> None:
"""Remove resource template(s) from this provider's storage.
Args:
uri_template: The template URI pattern.
version: If None, removes ALL versions. If specified, removes only that version.
Raises:
KeyError: If no matching template is found.
"""
if version is None:
# Remove all versions
keys_to_remove = [
k
for k, c in self._components.items()
if isinstance(c, ResourceTemplate) and c.uri_template == uri_template
]
if not keys_to_remove:
raise KeyError(f"Template {uri_template!r} not found")
for key in keys_to_remove:
self._remove_component(key)
else:
# Remove specific version
key = f"{ResourceTemplate.make_key(uri_template)}@{version}"
if key not in self._components:
raise KeyError(
f"Template {uri_template!r} version {version!r} not found"
)
self._remove_component(key)
def remove_prompt(self, name: str, version: str | None = None) -> None:
"""Remove prompt(s) from this provider's storage.
Args:
name: The prompt name.
version: If None, removes ALL versions. If specified, removes only that version.
Raises:
KeyError: If no matching prompt is found.
"""
if version is None:
# Remove all versions
keys_to_remove = [
k
for k, c in self._components.items()
if isinstance(c, Prompt) and c.name == name
]
if not keys_to_remove:
raise KeyError(f"Prompt {name!r} not found")
for key in keys_to_remove:
self._remove_component(key)
else:
# Remove specific version
key = f"{Prompt.make_key(name)}@{version}"
if key not in self._components:
raise KeyError(f"Prompt {name!r} version {version!r} not found")
self._remove_component(key)
# =========================================================================
# Provider interface implementation
# =========================================================================
async def _list_tools(self) -> Sequence[Tool]:
"""Return all tools."""
return [v for v in self._components.values() if isinstance(v, Tool)]
async def _get_tool(
self, name: str, version: VersionSpec | None = None
) -> Tool | None:
"""Get a tool by name.
Args:
name: The tool name.
version: Optional version filter. If None, returns highest version.
"""
matching = [
v
for v in self._components.values()
if isinstance(v, Tool) and v.name == name
]
if version:
matching = [t for t in matching if version.matches(t.version)]
if not matching:
return None
return max(matching, key=version_sort_key) # type: ignore[type-var]
async def _list_resources(self) -> Sequence[Resource]:
"""Return all resources."""
return [v for v in self._components.values() if isinstance(v, Resource)]
async def _get_resource(
self, uri: str, version: VersionSpec | None = None
) -> Resource | None:
"""Get a resource by URI.
Args:
uri: The resource URI.
version: Optional version filter. If None, returns highest version.
"""
matching = [
v
for v in self._components.values()
if isinstance(v, Resource) and str(v.uri) == uri
]
if version:
matching = [r for r in matching if version.matches(r.version)]
if not matching:
return None
return max(matching, key=version_sort_key) # type: ignore[type-var]
async def _list_resource_templates(self) -> Sequence[ResourceTemplate]:
"""Return all resource templates."""
return [v for v in self._components.values() if isinstance(v, ResourceTemplate)]
async def _get_resource_template(
self, uri: str, version: VersionSpec | None = None
) -> ResourceTemplate | None:
"""Get a resource template that matches the given URI.
Args:
uri: The URI to match against templates.
version: Optional version filter. If None, returns highest version.
"""
# Find all templates that match the URI
matching = [
component
for component in self._components.values()
if isinstance(component, ResourceTemplate)
and component.matches(uri) is not None
]
if version:
matching = [t for t in matching if version.matches(t.version)]
if not matching:
return None
return max(matching, key=version_sort_key) # type: ignore[type-var]
async def _list_prompts(self) -> Sequence[Prompt]:
"""Return all prompts."""
return [v for v in self._components.values() if isinstance(v, Prompt)]
async def _get_prompt(
self, name: str, version: VersionSpec | None = None
) -> Prompt | None:
"""Get a prompt by name.
Args:
name: The prompt name.
version: Optional version filter. If None, returns highest version.
"""
matching = [
v
for v in self._components.values()
if isinstance(v, Prompt) and v.name == name
]
if version:
matching = [p for p in matching if version.matches(p.version)]
if not matching:
return None
return max(matching, key=version_sort_key) # type: ignore[type-var]
# =========================================================================
# Task registration
# =========================================================================
async def get_tasks(self) -> Sequence[FastMCPComponent]:
"""Return components eligible for background task execution.
Returns components that have task_config.mode != 'forbidden'.
This includes both FunctionTool/Resource/Prompt instances created via
decorators and custom Tool/Resource/Prompt subclasses.
"""
return [c for c in self._components.values() if c.task_config.supports_tasks()]
# =========================================================================
# Decorator methods
# =========================================================================
# Note: Decorator methods (tool, resource, prompt, add_tool, add_resource,
# add_template, add_prompt) are provided by mixin classes:
# - ToolDecoratorMixin
# - ResourceDecoratorMixin
# - PromptDecoratorMixin
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/server/providers/local_provider/local_provider.py",
"license": "Apache License 2.0",
"lines": 390,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/server/auth/oauth_proxy/consent.py | """OAuth Proxy Consent Management.
This module contains consent management functionality for the OAuth proxy.
The ConsentMixin class provides methods for handling user consent flows,
cookie management, and consent page rendering.
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import secrets
import time
from base64 import urlsafe_b64encode
from typing import TYPE_CHECKING, Any
from urllib.parse import urlencode, urlparse
from pydantic import AnyUrl
from starlette.requests import Request
from starlette.responses import HTMLResponse, RedirectResponse
from fastmcp.server.auth.oauth_proxy.models import ProxyDCRClient
from fastmcp.server.auth.oauth_proxy.ui import create_consent_html
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.ui import create_secure_html_response
if TYPE_CHECKING:
from fastmcp.server.auth.oauth_proxy.proxy import OAuthProxy
logger = get_logger(__name__)
class ConsentMixin:
"""Mixin class providing consent management functionality for OAuthProxy.
This mixin contains all methods related to:
- Cookie signing and verification
- Consent page rendering
- Consent approval/denial handling
- URI normalization for consent tracking
"""
def _normalize_uri(self, uri: str) -> str:
"""Normalize a URI to a canonical form for consent tracking."""
parsed = urlparse(uri)
path = parsed.path or ""
normalized = f"{parsed.scheme.lower()}://{parsed.netloc.lower()}{path}"
if normalized.endswith("/") and len(path) > 1:
normalized = normalized[:-1]
return normalized
def _make_client_key(self, client_id: str, redirect_uri: str | AnyUrl) -> str:
"""Create a stable key for consent tracking from client_id and redirect_uri."""
normalized = self._normalize_uri(str(redirect_uri))
return f"{client_id}:{normalized}"
def _cookie_name(self: OAuthProxy, base_name: str) -> str:
"""Return secure cookie name for HTTPS, fallback for HTTP development."""
if self._is_https:
return f"__Host-{base_name}"
return f"__{base_name}"
def _sign_cookie(self: OAuthProxy, payload: str) -> str:
"""Sign a cookie payload with HMAC-SHA256.
Returns: base64(payload).base64(signature)
"""
# Use upstream client secret as signing key
key = self._upstream_client_secret.get_secret_value().encode()
signature = hmac.new(key, payload.encode(), hashlib.sha256).digest()
signature_b64 = base64.b64encode(signature).decode()
return f"{payload}.{signature_b64}"
def _verify_cookie(self: OAuthProxy, signed_value: str) -> str | None:
"""Verify and extract payload from signed cookie.
Returns: payload if signature valid, None otherwise
"""
try:
if "." not in signed_value:
return None
payload, signature_b64 = signed_value.rsplit(".", 1)
# Verify signature
key = self._upstream_client_secret.get_secret_value().encode()
expected_sig = hmac.new(key, payload.encode(), hashlib.sha256).digest()
provided_sig = base64.b64decode(signature_b64.encode())
# Constant-time comparison
if not hmac.compare_digest(expected_sig, provided_sig):
return None
return payload
except Exception:
return None
def _decode_list_cookie(
self: OAuthProxy, request: Request, base_name: str
) -> list[str]:
"""Decode and verify a signed base64-encoded JSON list from cookie. Returns [] if missing/invalid."""
# Prefer secure name, but also check non-secure variant for dev
secure_name = self._cookie_name(base_name)
raw = request.cookies.get(secure_name) or request.cookies.get(f"__{base_name}")
if not raw:
return []
try:
# Verify signature
payload = self._verify_cookie(raw)
if not payload:
logger.debug("Cookie signature verification failed for %s", secure_name)
return []
# Decode payload
data = base64.b64decode(payload.encode())
value = json.loads(data.decode())
if isinstance(value, list):
return [str(x) for x in value]
except Exception:
logger.debug("Failed to decode cookie %s; treating as empty", secure_name)
return []
def _encode_list_cookie(self: OAuthProxy, values: list[str]) -> str:
"""Encode values to base64 and sign with HMAC.
Returns: signed cookie value (payload.signature)
"""
payload = json.dumps(values, separators=(",", ":")).encode()
payload_b64 = base64.b64encode(payload).decode()
return self._sign_cookie(payload_b64)
def _set_list_cookie(
self: OAuthProxy,
response: HTMLResponse | RedirectResponse,
base_name: str,
value_b64: str,
max_age: int,
) -> None:
name = self._cookie_name(base_name)
response.set_cookie(
name,
value_b64,
max_age=max_age,
secure=self._is_https,
httponly=True,
samesite="lax",
path="/",
)
def _read_consent_bindings(self: OAuthProxy, request: Request) -> dict[str, str]:
"""Read the consent binding map from the signed cookie.
Returns a dict of {txn_id: consent_token} for all pending flows.
"""
cookie_name = self._cookie_name("MCP_CONSENT_BINDING")
raw = request.cookies.get(cookie_name)
# Only fall back to the non-__Host- name over plain HTTP. On HTTPS,
# __Host- enforces host-only scope; accepting the weaker name would
# bypass that guarantee.
if not raw and not self._is_https:
raw = request.cookies.get("__MCP_CONSENT_BINDING")
if not raw:
return {}
payload = self._verify_cookie(raw)
if not payload:
return {}
try:
data = json.loads(base64.b64decode(payload.encode()).decode())
if isinstance(data, dict):
return {str(k): str(v) for k, v in data.items()}
except Exception:
logger.debug("Failed to decode consent binding cookie")
return {}
def _write_consent_bindings(
self: OAuthProxy,
response: HTMLResponse | RedirectResponse,
bindings: dict[str, str],
) -> None:
"""Write the consent binding map to a signed cookie."""
name = self._cookie_name("MCP_CONSENT_BINDING")
if not bindings:
response.set_cookie(
name,
"",
max_age=0,
secure=self._is_https,
httponly=True,
samesite="lax",
path="/",
)
return
payload_bytes = json.dumps(bindings, separators=(",", ":")).encode()
payload_b64 = base64.b64encode(payload_bytes).decode()
signed_value = self._sign_cookie(payload_b64)
response.set_cookie(
name,
signed_value,
max_age=15 * 60,
secure=self._is_https,
httponly=True,
samesite="lax",
path="/",
)
def _set_consent_binding_cookie(
self: OAuthProxy,
request: Request,
response: HTMLResponse | RedirectResponse,
txn_id: str,
consent_token: str,
) -> None:
"""Add a consent binding entry for a transaction.
This cookie binds the browser that approved consent to the IdP callback,
ensuring a different browser cannot complete the OAuth flow. Multiple
concurrent flows are supported by storing a map of txn_id → consent_token.
"""
bindings = self._read_consent_bindings(request)
bindings[txn_id] = consent_token
self._write_consent_bindings(response, bindings)
def _clear_consent_binding_cookie(
self: OAuthProxy,
request: Request,
response: HTMLResponse | RedirectResponse,
txn_id: str,
) -> None:
"""Remove a specific consent binding entry after successful callback."""
bindings = self._read_consent_bindings(request)
bindings.pop(txn_id, None)
self._write_consent_bindings(response, bindings)
def _verify_consent_binding_cookie(
self: OAuthProxy,
request: Request,
txn_id: str,
expected_token: str,
) -> bool:
"""Verify the consent binding for a specific transaction."""
bindings = self._read_consent_bindings(request)
actual = bindings.get(txn_id)
if not actual:
return False
return hmac.compare_digest(actual, expected_token)
def _build_upstream_authorize_url(
self: OAuthProxy, txn_id: str, transaction: dict[str, Any]
) -> str:
"""Construct the upstream IdP authorization URL using stored transaction data."""
query_params: dict[str, Any] = {
"response_type": "code",
"client_id": self._upstream_client_id,
"redirect_uri": f"{str(self.base_url).rstrip('/')}{self._redirect_path}",
"state": txn_id,
}
scopes_to_use = transaction.get("scopes") or self.required_scopes or []
if scopes_to_use:
query_params["scope"] = " ".join(scopes_to_use)
# If PKCE forwarding was enabled, include the proxy challenge
proxy_code_verifier = transaction.get("proxy_code_verifier")
if proxy_code_verifier:
challenge_bytes = hashlib.sha256(proxy_code_verifier.encode()).digest()
proxy_code_challenge = (
urlsafe_b64encode(challenge_bytes).decode().rstrip("=")
)
query_params["code_challenge"] = proxy_code_challenge
query_params["code_challenge_method"] = "S256"
# Forward resource indicator if present in transaction
if resource := transaction.get("resource"):
query_params["resource"] = resource
# Extra configured parameters
if self._extra_authorize_params:
query_params.update(self._extra_authorize_params)
separator = "&" if "?" in self._upstream_authorization_endpoint else "?"
return f"{self._upstream_authorization_endpoint}{separator}{urlencode(query_params)}"
async def _handle_consent(
self: OAuthProxy, request: Request
) -> HTMLResponse | RedirectResponse:
"""Handle consent page - dispatch to GET or POST handler based on method."""
if request.method == "POST":
return await self._submit_consent(request)
return await self._show_consent_page(request)
async def _show_consent_page(
self: OAuthProxy, request: Request
) -> HTMLResponse | RedirectResponse:
"""Display consent page or auto-approve/deny based on cookies."""
from fastmcp.server.server import FastMCP
txn_id = request.query_params.get("txn_id")
if not txn_id:
return create_secure_html_response(
"<h1>Error</h1><p>Invalid or expired transaction</p>", status_code=400
)
txn_model = await self._transaction_store.get(key=txn_id)
if not txn_model:
return create_secure_html_response(
"<h1>Error</h1><p>Invalid or expired transaction</p>", status_code=400
)
txn = txn_model.model_dump()
client_key = self._make_client_key(txn["client_id"], txn["client_redirect_uri"])
approved = set(self._decode_list_cookie(request, "MCP_APPROVED_CLIENTS"))
denied = set(self._decode_list_cookie(request, "MCP_DENIED_CLIENTS"))
if client_key in approved:
consent_token = secrets.token_urlsafe(32)
txn_model.consent_token = consent_token
await self._transaction_store.put(key=txn_id, value=txn_model, ttl=15 * 60)
upstream_url = self._build_upstream_authorize_url(txn_id, txn)
response = RedirectResponse(url=upstream_url, status_code=302)
self._set_consent_binding_cookie(request, response, txn_id, consent_token)
return response
if client_key in denied:
callback_params = {
"error": "access_denied",
"state": txn.get("client_state") or "",
}
sep = "&" if "?" in txn["client_redirect_uri"] else "?"
return RedirectResponse(
url=f"{txn['client_redirect_uri']}{sep}{urlencode(callback_params)}",
status_code=302,
)
# Need consent: issue CSRF token and show HTML
csrf_token = secrets.token_urlsafe(32)
csrf_expires_at = time.time() + 15 * 60
# Update transaction with CSRF token
txn_model.csrf_token = csrf_token
txn_model.csrf_expires_at = csrf_expires_at
await self._transaction_store.put(
key=txn_id, value=txn_model, ttl=15 * 60
) # Auto-expire after 15 minutes
# Update dict for use in HTML generation
txn["csrf_token"] = csrf_token
txn["csrf_expires_at"] = csrf_expires_at
# Load client to get client_name and CIMD info if available
client = await self.get_client(txn["client_id"])
client_name = getattr(client, "client_name", None) if client else None
# Detect CIMD clients for verified domain badge
is_cimd_client = False
cimd_domain: str | None = None
if isinstance(client, ProxyDCRClient) and client.cimd_document is not None:
is_cimd_client = True
cimd_domain = urlparse(txn["client_id"]).hostname
# Extract server metadata from app state
fastmcp = getattr(request.app.state, "fastmcp_server", None)
if isinstance(fastmcp, FastMCP):
server_name = fastmcp.name
icons = fastmcp.icons
server_icon_url = icons[0].src if icons else None
server_website_url = fastmcp.website_url
else:
server_name = None
server_icon_url = None
server_website_url = None
html = create_consent_html(
client_id=txn["client_id"],
redirect_uri=txn["client_redirect_uri"],
scopes=txn.get("scopes") or [],
txn_id=txn_id,
csrf_token=csrf_token,
client_name=client_name,
server_name=server_name,
server_icon_url=server_icon_url,
server_website_url=server_website_url,
csp_policy=self._consent_csp_policy,
is_cimd_client=is_cimd_client,
cimd_domain=cimd_domain,
)
response = create_secure_html_response(html)
# Store CSRF in cookie with short lifetime
self._set_list_cookie(
response,
"MCP_CONSENT_STATE",
self._encode_list_cookie([csrf_token]),
max_age=15 * 60,
)
return response
async def _submit_consent(
self: OAuthProxy, request: Request
) -> RedirectResponse | HTMLResponse:
"""Handle consent approval/denial, set cookies, and redirect appropriately."""
form = await request.form()
txn_id = str(form.get("txn_id", ""))
action = str(form.get("action", ""))
csrf_token = str(form.get("csrf_token", ""))
if not txn_id:
return create_secure_html_response(
"<h1>Error</h1><p>Invalid or expired transaction</p>", status_code=400
)
txn_model = await self._transaction_store.get(key=txn_id)
if not txn_model:
return create_secure_html_response(
"<h1>Error</h1><p>Invalid or expired transaction</p>", status_code=400
)
txn = txn_model.model_dump()
expected_csrf = txn.get("csrf_token")
expires_at = float(txn.get("csrf_expires_at") or 0)
if not expected_csrf or csrf_token != expected_csrf or time.time() > expires_at:
return create_secure_html_response(
"<h1>Error</h1><p>Invalid or expired consent token</p>", status_code=400
)
client_key = self._make_client_key(txn["client_id"], txn["client_redirect_uri"])
if action == "approve":
approved = set(self._decode_list_cookie(request, "MCP_APPROVED_CLIENTS"))
if client_key not in approved:
approved.add(client_key)
approved_b64 = self._encode_list_cookie(sorted(approved))
consent_token = secrets.token_urlsafe(32)
txn_model.consent_token = consent_token
await self._transaction_store.put(key=txn_id, value=txn_model, ttl=15 * 60)
upstream_url = self._build_upstream_authorize_url(txn_id, txn)
response = RedirectResponse(url=upstream_url, status_code=302)
self._set_list_cookie(
response, "MCP_APPROVED_CLIENTS", approved_b64, max_age=365 * 24 * 3600
)
# Clear CSRF cookie by setting empty short-lived value
self._set_list_cookie(
response, "MCP_CONSENT_STATE", self._encode_list_cookie([]), max_age=60
)
self._set_consent_binding_cookie(request, response, txn_id, consent_token)
return response
elif action == "deny":
denied = set(self._decode_list_cookie(request, "MCP_DENIED_CLIENTS"))
if client_key not in denied:
denied.add(client_key)
denied_b64 = self._encode_list_cookie(sorted(denied))
callback_params = {
"error": "access_denied",
"state": txn.get("client_state") or "",
}
sep = "&" if "?" in txn["client_redirect_uri"] else "?"
client_callback_url = (
f"{txn['client_redirect_uri']}{sep}{urlencode(callback_params)}"
)
response = RedirectResponse(url=client_callback_url, status_code=302)
self._set_list_cookie(
response, "MCP_DENIED_CLIENTS", denied_b64, max_age=365 * 24 * 3600
)
self._set_list_cookie(
response, "MCP_CONSENT_STATE", self._encode_list_cookie([]), max_age=60
)
return response
else:
return create_secure_html_response(
"<h1>Error</h1><p>Invalid action</p>", status_code=400
)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/server/auth/oauth_proxy/consent.py",
"license": "Apache License 2.0",
"lines": 412,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/server/auth/oauth_proxy/models.py | """OAuth Proxy Models and Constants.
This module contains all Pydantic models and constants used by the OAuth proxy.
"""
from __future__ import annotations
import hashlib
from typing import Any, Final
from mcp.shared.auth import InvalidRedirectUriError, OAuthClientInformationFull
from pydantic import AnyUrl, BaseModel, Field
from fastmcp.server.auth.cimd import CIMDDocument
from fastmcp.server.auth.redirect_validation import (
matches_allowed_pattern,
validate_redirect_uri,
)
# -------------------------------------------------------------------------
# Constants
# -------------------------------------------------------------------------
# Default token expiration times
DEFAULT_ACCESS_TOKEN_EXPIRY_SECONDS: Final[int] = 60 * 60 # 1 hour
DEFAULT_ACCESS_TOKEN_EXPIRY_NO_REFRESH_SECONDS: Final[int] = (
60 * 60 * 24 * 365
) # 1 year
DEFAULT_AUTH_CODE_EXPIRY_SECONDS: Final[int] = 5 * 60 # 5 minutes
# HTTP client timeout
HTTP_TIMEOUT_SECONDS: Final[int] = 30
# -------------------------------------------------------------------------
# Pydantic Models
# -------------------------------------------------------------------------
class OAuthTransaction(BaseModel):
"""OAuth transaction state for consent flow.
Stored server-side to track active authorization flows with client context.
Includes CSRF tokens for consent protection per MCP security best practices.
"""
txn_id: str
client_id: str
client_redirect_uri: str
client_state: str
code_challenge: str | None
code_challenge_method: str
scopes: list[str]
created_at: float
resource: str | None = None
proxy_code_verifier: str | None = None
csrf_token: str | None = None
csrf_expires_at: float | None = None
consent_token: str | None = None
class ClientCode(BaseModel):
"""Client authorization code with PKCE and upstream tokens.
Stored server-side after upstream IdP callback. Contains the upstream
tokens bound to the client's PKCE challenge for secure token exchange.
"""
code: str
client_id: str
redirect_uri: str
code_challenge: str | None
code_challenge_method: str
scopes: list[str]
idp_tokens: dict[str, Any]
expires_at: float
created_at: float
class UpstreamTokenSet(BaseModel):
"""Stored upstream OAuth tokens from identity provider.
These tokens are obtained from the upstream provider (Google, GitHub, etc.)
and stored in plaintext within this model. Encryption is handled transparently
at the storage layer via FernetEncryptionWrapper. Tokens are never exposed to MCP clients.
"""
upstream_token_id: str # Unique ID for this token set
access_token: str # Upstream access token
refresh_token: str | None # Upstream refresh token
refresh_token_expires_at: (
float | None
) # Unix timestamp when refresh token expires (if known)
expires_at: float # Unix timestamp when access token expires
token_type: str # Usually "Bearer"
scope: str # Space-separated scopes
client_id: str # MCP client this is bound to
created_at: float # Unix timestamp
raw_token_data: dict[str, Any] = Field(default_factory=dict) # Full token response
class JTIMapping(BaseModel):
"""Maps FastMCP token JTI to upstream token ID.
This allows stateless JWT validation while still being able to look up
the corresponding upstream token when tools need to access upstream APIs.
"""
jti: str # JWT ID from FastMCP-issued token
upstream_token_id: str # References UpstreamTokenSet
created_at: float # Unix timestamp
class RefreshTokenMetadata(BaseModel):
"""Metadata for a refresh token, stored keyed by token hash.
We store only metadata (not the token itself) for security - if storage
is compromised, attackers get hashes they can't reverse into usable tokens.
"""
client_id: str
scopes: list[str]
expires_at: int | None = None
created_at: float
def _hash_token(token: str) -> str:
"""Hash a token for secure storage lookup.
Uses SHA-256 to create a one-way hash. The original token cannot be
recovered from the hash, providing defense in depth if storage is compromised.
"""
return hashlib.sha256(token.encode()).hexdigest()
class ProxyDCRClient(OAuthClientInformationFull):
"""Client for DCR proxy with configurable redirect URI validation.
This special client class is critical for the OAuth proxy to work correctly
with Dynamic Client Registration (DCR). Here's why it exists:
Problem:
--------
When MCP clients use OAuth, they dynamically register with random localhost
ports (e.g., http://localhost:55454/callback). The OAuth proxy needs to:
1. Accept these dynamic redirect URIs from clients based on configured patterns
2. Use its own fixed redirect URI with the upstream provider (Google, GitHub, etc.)
3. Forward the authorization code back to the client's dynamic URI
Solution:
---------
This class validates redirect URIs against configurable patterns,
while the proxy internally uses its own fixed redirect URI with the upstream
provider. This allows the flow to work even when clients reconnect with
different ports or when tokens are cached.
Without proper validation, clients could get "Redirect URI not registered" errors
when trying to authenticate with cached tokens, or security vulnerabilities could
arise from accepting arbitrary redirect URIs.
"""
allowed_redirect_uri_patterns: list[str] | None = Field(default=None)
client_name: str | None = Field(default=None)
cimd_document: CIMDDocument | None = Field(default=None)
cimd_fetched_at: float | None = Field(default=None)
def validate_redirect_uri(self, redirect_uri: AnyUrl | None) -> AnyUrl:
"""Validate redirect URI against proxy patterns and optionally CIMD redirect_uris.
For CIMD clients: validates against BOTH the CIMD document's redirect_uris
AND the proxy's allowed patterns (if configured). Both must pass.
For DCR clients: validates against proxy patterns first, falling back to
base validation (registered redirect_uris) if patterns don't match.
"""
if redirect_uri is None and self.cimd_document is not None:
cimd_redirect_uris = self.cimd_document.redirect_uris
if len(cimd_redirect_uris) == 1:
candidate = cimd_redirect_uris[0]
if "*" in candidate:
raise InvalidRedirectUriError(
"redirect_uri must be specified when CIMD redirect_uris uses wildcards."
)
try:
resolved = AnyUrl(candidate)
except Exception as e:
raise InvalidRedirectUriError(
f"Invalid CIMD redirect_uri: {e}"
) from e
# Respect proxy-level redirect URI restrictions even when the
# client omits redirect_uri and we fall back to CIMD defaults.
if (
self.allowed_redirect_uri_patterns is not None
and not validate_redirect_uri(
redirect_uri=resolved,
allowed_patterns=self.allowed_redirect_uri_patterns,
)
):
raise InvalidRedirectUriError(
f"Redirect URI '{resolved}' does not match allowed patterns."
)
return resolved
raise InvalidRedirectUriError(
"redirect_uri must be specified when CIMD lists multiple redirect_uris."
)
if redirect_uri is not None:
cimd_redirect_uris = (
self.cimd_document.redirect_uris if self.cimd_document else None
)
if cimd_redirect_uris:
uri_str = str(redirect_uri)
cimd_match = any(
matches_allowed_pattern(uri_str, pattern)
for pattern in cimd_redirect_uris
)
if not cimd_match:
raise InvalidRedirectUriError(
f"Redirect URI '{redirect_uri}' does not match CIMD redirect_uris."
)
if self.allowed_redirect_uri_patterns is not None:
if not validate_redirect_uri(
redirect_uri=redirect_uri,
allowed_patterns=self.allowed_redirect_uri_patterns,
):
raise InvalidRedirectUriError(
f"Redirect URI '{redirect_uri}' does not match allowed patterns."
)
return redirect_uri
pattern_matches = validate_redirect_uri(
redirect_uri=redirect_uri,
allowed_patterns=self.allowed_redirect_uri_patterns,
)
if pattern_matches:
return redirect_uri
# Patterns configured but didn't match
if self.allowed_redirect_uri_patterns:
raise InvalidRedirectUriError(
f"Redirect URI '{redirect_uri}' does not match allowed patterns."
)
# No redirect_uri provided or no patterns configured — use base validation
return super().validate_redirect_uri(redirect_uri)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/server/auth/oauth_proxy/models.py",
"license": "Apache License 2.0",
"lines": 198,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/server/auth/oauth_proxy/ui.py | """OAuth Proxy UI Generation Functions.
This module contains HTML generation functions for consent and error pages.
"""
from __future__ import annotations
from fastmcp.utilities.ui import (
BUTTON_STYLES,
DETAIL_BOX_STYLES,
DETAILS_STYLES,
INFO_BOX_STYLES,
REDIRECT_SECTION_STYLES,
TOOLTIP_STYLES,
create_logo,
create_page,
)
def create_consent_html(
client_id: str,
redirect_uri: str,
scopes: list[str],
txn_id: str,
csrf_token: str,
client_name: str | None = None,
title: str = "Application Access Request",
server_name: str | None = None,
server_icon_url: str | None = None,
server_website_url: str | None = None,
client_website_url: str | None = None,
csp_policy: str | None = None,
is_cimd_client: bool = False,
cimd_domain: str | None = None,
) -> str:
"""Create a styled HTML consent page for OAuth authorization requests.
Args:
csp_policy: Content Security Policy override.
If None, uses the built-in CSP policy with appropriate directives.
If empty string "", disables CSP entirely (no meta tag is rendered).
If a non-empty string, uses that as the CSP policy value.
"""
import html as html_module
client_display = html_module.escape(client_name or client_id)
server_name_escaped = html_module.escape(server_name or "FastMCP")
# Make server name a hyperlink if website URL is available
if server_website_url:
website_url_escaped = html_module.escape(server_website_url)
server_display = f'<a href="{website_url_escaped}" target="_blank" rel="noopener noreferrer" class="server-name-link">{server_name_escaped}</a>'
else:
server_display = server_name_escaped
# Build intro box with call-to-action
intro_box = f"""
<div class="info-box">
<p>The application <strong>{client_display}</strong> wants to access the MCP server <strong>{server_display}</strong>. Please ensure you recognize the callback address below.</p>
</div>
"""
# Build CIMD verified domain badge if applicable
cimd_badge = ""
if is_cimd_client and cimd_domain:
cimd_domain_escaped = html_module.escape(cimd_domain)
cimd_badge = f"""
<div class="cimd-badge">
<span class="cimd-check">✓</span>
Verified domain: <strong>{cimd_domain_escaped}</strong>
</div>
"""
# Build redirect URI section (yellow box, centered)
redirect_uri_escaped = html_module.escape(redirect_uri)
redirect_section = f"""
<div class="redirect-section">
<span class="label">Credentials will be sent to:</span>
<div class="value">{redirect_uri_escaped}</div>
</div>
"""
# Build advanced details with collapsible section
detail_rows = [
("Application Name", html_module.escape(client_name or client_id)),
("Application Website", html_module.escape(client_website_url or "N/A")),
("Application ID", html_module.escape(client_id)),
("Redirect URI", redirect_uri_escaped),
(
"Requested Scopes",
", ".join(html_module.escape(s) for s in scopes) if scopes else "None",
),
]
detail_rows_html = "\n".join(
[
f"""
<div class="detail-row">
<div class="detail-label">{label}:</div>
<div class="detail-value">{value}</div>
</div>
"""
for label, value in detail_rows
]
)
advanced_details = f"""
<details>
<summary>Advanced Details</summary>
<div class="detail-box">
{detail_rows_html}
</div>
</details>
"""
# Build form with buttons
# Use empty action to submit to current URL (/consent or /mcp/consent)
# The POST handler is registered at the same path as GET
form = f"""
<form id="consentForm" method="POST" action="">
<input type="hidden" name="txn_id" value="{txn_id}" />
<input type="hidden" name="csrf_token" value="{csrf_token}" />
<input type="hidden" name="submit" value="true" />
<div class="button-group">
<button type="submit" name="action" value="approve" class="btn-approve">Allow Access</button>
<button type="submit" name="action" value="deny" class="btn-deny">Deny</button>
</div>
</form>
"""
# Build help link with tooltip (identical to current implementation)
help_link = """
<div class="help-link-container">
<span class="help-link">
Why am I seeing this?
<span class="tooltip">
This FastMCP server requires your consent to allow a new client
to connect. This protects you from <a
href="https://modelcontextprotocol.io/specification/2025-06-18/basic/security_best_practices#confused-deputy-problem"
target="_blank" class="tooltip-link">confused deputy
attacks</a>, where malicious clients could impersonate you
and steal access.<br><br>
<a
href="https://gofastmcp.com/servers/auth/oauth-proxy#confused-deputy-attacks"
target="_blank" class="tooltip-link">Learn more about
FastMCP security →</a>
</span>
</span>
</div>
"""
# Build the page content
content = f"""
<div class="container">
{create_logo(icon_url=server_icon_url, alt_text=server_name or "FastMCP")}
<h1>Application Access Request</h1>
{intro_box}
{cimd_badge}
{redirect_section}
{advanced_details}
{form}
</div>
{help_link}
"""
# Additional styles needed for this page
cimd_badge_styles = """
.cimd-badge {
background: #ecfdf5;
border: 1px solid #6ee7b7;
border-radius: 8px;
padding: 8px 16px;
margin-bottom: 16px;
font-size: 14px;
color: #065f46;
text-align: center;
}
.cimd-check {
color: #059669;
font-weight: bold;
margin-right: 4px;
}
"""
additional_styles = (
INFO_BOX_STYLES
+ REDIRECT_SECTION_STYLES
+ DETAILS_STYLES
+ DETAIL_BOX_STYLES
+ BUTTON_STYLES
+ TOOLTIP_STYLES
+ cimd_badge_styles
)
# Determine CSP policy to use
# If csp_policy is None, build the default CSP policy
# If csp_policy is empty string, CSP will be disabled entirely in create_page
# If csp_policy is a non-empty string, use it as-is
if csp_policy is None:
# The consent form posts to itself (action="") and all subsequent redirects
# are server-controlled. Chrome enforces form-action across the entire redirect
# chain (Chromium issue #40923007), which breaks flows where an HTTPS callback
# internally redirects to a custom scheme (e.g., claude:// or cursor://).
# Since the form target is same-origin and we control the redirect chain,
# omitting form-action is safe and avoids these browser-specific CSP issues.
csp_policy = "default-src 'none'; style-src 'unsafe-inline'; img-src https: data:; base-uri 'none'"
return create_page(
content=content,
title=title,
additional_styles=additional_styles,
csp_policy=csp_policy,
)
def create_error_html(
error_title: str,
error_message: str,
error_details: dict[str, str] | None = None,
server_name: str | None = None,
server_icon_url: str | None = None,
) -> str:
"""Create a styled HTML error page for OAuth errors.
Args:
error_title: The error title (e.g., "OAuth Error", "Authorization Failed")
error_message: The main error message to display
error_details: Optional dictionary of error details to show (e.g., `{"Error Code": "invalid_client"}`)
server_name: Optional server name to display
server_icon_url: Optional URL to server icon/logo
Returns:
Complete HTML page as a string
"""
import html as html_module
error_message_escaped = html_module.escape(error_message)
# Build error message box
error_box = f"""
<div class="info-box error">
<p>{error_message_escaped}</p>
</div>
"""
# Build error details section if provided
details_section = ""
if error_details:
detail_rows_html = "\n".join(
[
f"""
<div class="detail-row">
<div class="detail-label">{html_module.escape(label)}:</div>
<div class="detail-value">{html_module.escape(value)}</div>
</div>
"""
for label, value in error_details.items()
]
)
details_section = f"""
<details>
<summary>Error Details</summary>
<div class="detail-box">
{detail_rows_html}
</div>
</details>
"""
# Build the page content
content = f"""
<div class="container">
{create_logo(icon_url=server_icon_url, alt_text=server_name or "FastMCP")}
<h1>{html_module.escape(error_title)}</h1>
{error_box}
{details_section}
</div>
"""
# Additional styles needed for this page
# Override .info-box.error to use normal text color instead of red
additional_styles = (
INFO_BOX_STYLES
+ DETAILS_STYLES
+ DETAIL_BOX_STYLES
+ """
.info-box.error {
color: #111827;
}
"""
)
# Simple CSP policy for error pages (no forms needed)
csp_policy = "default-src 'none'; style-src 'unsafe-inline'; img-src https: data:; base-uri 'none'"
return create_page(
content=content,
title=error_title,
additional_styles=additional_styles,
csp_policy=csp_policy,
)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/server/auth/oauth_proxy/ui.py",
"license": "Apache License 2.0",
"lines": 268,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
PrefectHQ/fastmcp:src/fastmcp/client/transports/sse.py | """Server-Sent Events (SSE) transport for FastMCP Client."""
from __future__ import annotations
import contextlib
import datetime
from collections.abc import AsyncIterator
from typing import Any, Literal, cast
import httpx
from mcp import ClientSession
from mcp.client.sse import sse_client
from mcp.shared._httpx_utils import McpHttpClientFactory
from pydantic import AnyUrl
from typing_extensions import Unpack
from fastmcp.client.auth.bearer import BearerAuth
from fastmcp.client.auth.oauth import OAuth
from fastmcp.client.transports.base import ClientTransport, SessionKwargs
from fastmcp.server.dependencies import get_http_headers
from fastmcp.utilities.timeout import normalize_timeout_to_timedelta
class SSETransport(ClientTransport):
"""Transport implementation that connects to an MCP server via Server-Sent Events."""
def __init__(
self,
url: str | AnyUrl,
headers: dict[str, str] | None = None,
auth: httpx.Auth | Literal["oauth"] | str | None = None,
sse_read_timeout: datetime.timedelta | float | int | None = None,
httpx_client_factory: McpHttpClientFactory | None = None,
):
if isinstance(url, AnyUrl):
url = str(url)
if not isinstance(url, str) or not url.startswith("http"):
raise ValueError("Invalid HTTP/S URL provided for SSE.")
# Don't modify the URL path - respect the exact URL provided by the user
# Some servers are strict about trailing slashes (e.g., PayPal MCP)
self.url: str = url
self.headers = headers or {}
self.httpx_client_factory = httpx_client_factory
self._set_auth(auth)
self.sse_read_timeout = normalize_timeout_to_timedelta(sse_read_timeout)
def _set_auth(self, auth: httpx.Auth | Literal["oauth"] | str | None):
resolved: httpx.Auth | None
if auth == "oauth":
resolved = OAuth(self.url, httpx_client_factory=self.httpx_client_factory)
elif isinstance(auth, OAuth):
auth._bind(self.url)
resolved = auth
elif isinstance(auth, str):
resolved = BearerAuth(auth)
else:
resolved = auth
self.auth: httpx.Auth | None = resolved
@contextlib.asynccontextmanager
async def connect_session(
self, **session_kwargs: Unpack[SessionKwargs]
) -> AsyncIterator[ClientSession]:
client_kwargs: dict[str, Any] = {}
# load headers from an active HTTP request, if available. This will only be true
# if the client is used in a FastMCP Proxy, in which case the MCP client headers
# need to be forwarded to the remote server.
client_kwargs["headers"] = (
get_http_headers(include={"authorization"}) | self.headers
)
# sse_read_timeout has a default value set, so we can't pass None without overriding it
# instead we simply leave the kwarg out if it's not provided
if self.sse_read_timeout is not None:
client_kwargs["sse_read_timeout"] = self.sse_read_timeout.total_seconds()
if session_kwargs.get("read_timeout_seconds") is not None:
read_timeout_seconds = cast(
datetime.timedelta, session_kwargs.get("read_timeout_seconds")
)
client_kwargs["timeout"] = read_timeout_seconds.total_seconds()
if self.httpx_client_factory is not None:
client_kwargs["httpx_client_factory"] = self.httpx_client_factory
async with sse_client(self.url, auth=self.auth, **client_kwargs) as transport:
read_stream, write_stream = transport
async with ClientSession(
read_stream, write_stream, **session_kwargs
) as session:
yield session
def __repr__(self) -> str:
return f"<SSETransport(url='{self.url}')>"
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/client/transports/sse.py",
"license": "Apache License 2.0",
"lines": 80,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/utilities/timeout.py | """Timeout normalization utilities."""
from __future__ import annotations
import datetime
def normalize_timeout_to_timedelta(
value: int | float | datetime.timedelta | None,
) -> datetime.timedelta | None:
"""Normalize a timeout value to a timedelta.
Args:
value: Timeout value as int/float (seconds), timedelta, or None
Returns:
timedelta if value provided, None otherwise
"""
if value is None:
return None
if isinstance(value, datetime.timedelta):
return value
if isinstance(value, int | float):
return datetime.timedelta(seconds=float(value))
raise TypeError(f"Invalid timeout type: {type(value)}")
def normalize_timeout_to_seconds(
value: int | float | datetime.timedelta | None,
) -> float | None:
"""Normalize a timeout value to seconds (float).
Args:
value: Timeout value as int/float (seconds), timedelta, or None.
Zero values are treated as "disabled" and return None.
Returns:
float seconds if value provided and non-zero, None otherwise
"""
if value is None:
return None
if isinstance(value, datetime.timedelta):
seconds = value.total_seconds()
return None if seconds == 0 else seconds
if isinstance(value, int | float):
return None if value == 0 else float(value)
raise TypeError(f"Invalid timeout type: {type(value)}")
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/utilities/timeout.py",
"license": "Apache License 2.0",
"lines": 37,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
PrefectHQ/fastmcp:examples/namespace_activation/client.py | """
Namespace Activation Client
Demonstrates how session-specific visibility works from the client perspective.
"""
import asyncio
import sys
from pathlib import Path
from rich import print
from rich.panel import Panel
from fastmcp import Client
def load_server():
"""Load the example server."""
examples_dir = Path(__file__).parent
if str(examples_dir) not in sys.path:
sys.path.insert(0, str(examples_dir))
import server as server_module
return server_module.server
server = load_server()
def show_tools(tools: list, title: str) -> None:
"""Display available tools in a panel."""
tool_names = [f"[cyan]{t.name}[/]" for t in tools]
print(Panel(", ".join(tool_names) or "[dim]No tools[/]", title=title))
async def main():
print("\n[bold]Namespace Activation Demo[/]\n")
async with Client(server) as client:
# Initially only activation tools are visible
tools = await client.list_tools()
show_tools(tools, "Initial Tools")
# Activate finance namespace
print("\n[yellow]→ Calling activate_finance()[/]")
result = await client.call_tool("activate_finance", {})
print(f" [green]{result.data}[/]")
tools = await client.list_tools()
show_tools(tools, "After Activating Finance")
# Use a finance tool
print("\n[yellow]→ Calling get_market_data(symbol='AAPL')[/]")
result = await client.call_tool("get_market_data", {"symbol": "AAPL"})
print(f" [green]{result.data}[/]")
# Activate admin namespace too
print("\n[yellow]→ Calling activate_admin()[/]")
result = await client.call_tool("activate_admin", {})
print(f" [green]{result.data}[/]")
tools = await client.list_tools()
show_tools(tools, "After Activating Admin")
# Deactivate all - back to defaults
print("\n[yellow]→ Calling deactivate_all()[/]")
result = await client.call_tool("deactivate_all", {})
print(f" [green]{result.data}[/]")
tools = await client.list_tools()
show_tools(tools, "After Deactivating All")
if __name__ == "__main__":
asyncio.run(main())
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "examples/namespace_activation/client.py",
"license": "Apache License 2.0",
"lines": 52,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
PrefectHQ/fastmcp:examples/namespace_activation/server.py | """
Namespace Activation Server
Tools are organized into namespaces using tags, globally disabled by default,
and selectively enabled per-session via activation tools.
"""
from fastmcp import FastMCP
from fastmcp.server.context import Context
server = FastMCP("Multi-Domain Assistant")
# Finance namespace
@server.tool(tags={"namespace:finance"})
def analyze_portfolio(symbols: list[str]) -> str:
"""Analyze a portfolio of stock symbols."""
return f"Portfolio analysis for: {', '.join(symbols)}"
@server.tool(tags={"namespace:finance"})
def get_market_data(symbol: str) -> dict:
"""Get current market data for a symbol."""
return {"symbol": symbol, "price": 150.25, "change": "+2.5%"}
@server.tool(tags={"namespace:finance"})
def execute_trade(symbol: str, quantity: int, side: str) -> str:
"""Execute a trade (simulated)."""
return f"Executed {side} order: {quantity} shares of {symbol}"
# Admin namespace
@server.tool(tags={"namespace:admin"})
def list_users() -> list[str]:
"""List all system users."""
return ["alice", "bob", "charlie"]
@server.tool(tags={"namespace:admin"})
def reset_user_password(username: str) -> str:
"""Reset a user's password (simulated)."""
return f"Password reset for {username}"
# Activation tools - always visible
@server.tool
async def activate_finance(ctx: Context) -> str:
"""Activate finance tools for this session."""
await ctx.enable_components(tags={"namespace:finance"})
return "Finance tools activated"
@server.tool
async def activate_admin(ctx: Context) -> str:
"""Activate admin tools for this session."""
await ctx.enable_components(tags={"namespace:admin"})
return "Admin tools activated"
@server.tool
async def deactivate_all(ctx: Context) -> str:
"""Deactivate all namespaces, returning to defaults."""
await ctx.reset_visibility()
return "All namespaces deactivated"
# Globally disable namespace tools by default
server.disable(tags={"namespace:finance", "namespace:admin"})
if __name__ == "__main__":
server.run()
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "examples/namespace_activation/server.py",
"license": "Apache License 2.0",
"lines": 50,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
PrefectHQ/fastmcp:tests/server/test_session_visibility.py | """Tests for session-specific visibility control via Context."""
from dataclasses import dataclass, field
from datetime import datetime
import anyio
import mcp.types
from fastmcp.client.messages import MessageHandler
from fastmcp.server.context import Context
from fastmcp.server.server import FastMCP
@dataclass
class NotificationRecording:
"""Record of a notification that was received."""
method: str
notification: mcp.types.ServerNotification
timestamp: datetime = field(default_factory=datetime.now)
class RecordingMessageHandler(MessageHandler):
"""A message handler that records all notifications."""
def __init__(self):
super().__init__()
self.notifications: list[NotificationRecording] = []
async def on_notification(self, message: mcp.types.ServerNotification) -> None:
"""Record all notifications with timestamp."""
self.notifications.append(
NotificationRecording(method=message.root.method, notification=message)
)
def get_notifications(
self, method: str | None = None
) -> list[NotificationRecording]:
"""Get all recorded notifications, optionally filtered by method."""
if method is None:
return self.notifications
return [n for n in self.notifications if n.method == method]
def reset(self):
"""Clear all recorded notifications."""
self.notifications.clear()
class TestSessionVisibility:
"""Test session-specific visibility control via Context."""
async def test_enable_components_stores_rule_dict(self):
"""Test that enable_components stores a rule dict in session state."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.tool(tags={"finance"})
def finance_tool() -> str:
return "finance"
@mcp.tool
async def activate_finance(ctx: Context) -> str:
await ctx.enable_components(tags={"finance"})
# Check that the rule was stored
rules = await ctx._get_visibility_rules()
assert len(rules) == 1
assert rules[0]["enabled"] is True
assert rules[0]["tags"] == ["finance"]
return "activated"
async with Client(mcp) as client:
result = await client.call_tool("activate_finance", {})
assert result.data == "activated"
async def test_disable_components_stores_rule_dict(self):
"""Test that disable_components stores a rule dict in session state."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.tool(tags={"internal"})
def internal_tool() -> str:
return "internal"
@mcp.tool
async def deactivate_internal(ctx: Context) -> str:
await ctx.disable_components(tags={"internal"})
# Check that the rule was stored
rules = await ctx._get_visibility_rules()
assert len(rules) == 1
assert rules[0]["enabled"] is False
assert rules[0]["tags"] == ["internal"]
return "deactivated"
async with Client(mcp) as client:
result = await client.call_tool("deactivate_internal", {})
assert result.data == "deactivated"
async def test_session_rules_override_global_disables(self):
"""Test that session enable rules override global disable transforms."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.tool(tags={"finance"})
def finance_tool() -> str:
return "finance"
@mcp.tool
async def activate_finance(ctx: Context) -> str:
await ctx.enable_components(tags={"finance"})
return "activated"
# Globally disable finance tools
mcp.disable(tags={"finance"})
async with Client(mcp) as client:
# Before activation, finance tool should not be visible
tools_before = await client.list_tools()
assert not any(t.name == "finance_tool" for t in tools_before)
# Activate finance for this session
await client.call_tool("activate_finance", {})
# After activation, finance tool should be visible in this session
tools_after = await client.list_tools()
assert any(t.name == "finance_tool" for t in tools_after)
async def test_rules_persist_across_requests(self):
"""Test that session rules persist across multiple requests."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.tool(tags={"finance"})
def finance_tool() -> str:
return "finance"
@mcp.tool
async def activate_finance(ctx: Context) -> str:
await ctx.enable_components(tags={"finance"})
return "activated"
@mcp.tool
async def check_rules(ctx: Context) -> int:
rules = await ctx._get_visibility_rules()
return len(rules)
# Globally disable finance tools
mcp.disable(tags={"finance"})
async with Client(mcp) as client:
# Activate finance
await client.call_tool("activate_finance", {})
# In a subsequent request, rules should still be there
result = await client.call_tool("check_rules", {})
assert result.data == 1
# And finance tool should still be visible
tools = await client.list_tools()
assert any(t.name == "finance_tool" for t in tools)
async def test_rules_isolated_between_sessions(self):
"""Test that session rules are isolated between different sessions."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.tool(tags={"finance"})
def finance_tool() -> str:
return "finance"
@mcp.tool
async def activate_finance(ctx: Context) -> str:
await ctx.enable_components(tags={"finance"})
return "activated"
# Globally disable finance tools
mcp.disable(tags={"finance"})
# Session A activates finance
async with Client(mcp) as client_a:
await client_a.call_tool("activate_finance", {})
tools_a = await client_a.list_tools()
assert any(t.name == "finance_tool" for t in tools_a)
# Session B should not see finance tool (different session)
async with Client(mcp) as client_b:
tools_b = await client_b.list_tools()
assert not any(t.name == "finance_tool" for t in tools_b)
async def test_version_spec_serialization(self):
"""Test that VersionSpec is serialized/deserialized correctly."""
from fastmcp import Client
from fastmcp.utilities.versions import VersionSpec
mcp = FastMCP("test")
@mcp.tool(version="1.0.0")
def old_tool() -> str:
return "old"
@mcp.tool(version="2.0.0")
def new_tool() -> str:
return "new"
@mcp.tool
async def enable_v2_only(ctx: Context) -> str:
await ctx.enable_components(version=VersionSpec(gte="2.0.0"))
# Check serialization - version is stored as a dict
rules = await ctx._get_visibility_rules()
assert rules[0]["version"]["gte"] == "2.0.0"
assert rules[0]["version"]["lt"] is None
assert rules[0]["version"]["eq"] is None
return "enabled"
# Globally disable all versioned tools
mcp.disable(names={"old_tool", "new_tool"})
async with Client(mcp) as client:
# Enable v2 tools
await client.call_tool("enable_v2_only", {})
# Should see new_tool (v2.0.0) but not old_tool (v1.0.0)
tools = await client.list_tools()
assert any(t.name == "new_tool" for t in tools)
assert not any(t.name == "old_tool" for t in tools)
async def test_clear_visibility_rules(self):
"""Test that reset_visibility removes all session rules."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.tool(tags={"finance"})
def finance_tool() -> str:
return "finance"
@mcp.tool
async def activate_finance(ctx: Context) -> str:
await ctx.enable_components(tags={"finance"})
return "activated"
@mcp.tool
async def clear_rules(ctx: Context) -> str:
await ctx.reset_visibility()
rules = await ctx._get_visibility_rules()
assert len(rules) == 0
return "cleared"
# Globally disable finance tools
mcp.disable(tags={"finance"})
async with Client(mcp) as client:
# Activate finance
await client.call_tool("activate_finance", {})
tools_after_activate = await client.list_tools()
assert any(t.name == "finance_tool" for t in tools_after_activate)
# Clear rules
await client.call_tool("clear_rules", {})
# Finance tool should no longer be visible (back to global disable)
tools_after_clear = await client.list_tools()
assert not any(t.name == "finance_tool" for t in tools_after_clear)
async def test_multiple_rules_accumulate(self):
"""Test that multiple enable/disable calls accumulate rules."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.tool(tags={"finance"})
def finance_tool() -> str:
return "finance"
@mcp.tool(tags={"admin"})
def admin_tool() -> str:
return "admin"
@mcp.tool
async def activate_multiple(ctx: Context) -> str:
await ctx.enable_components(tags={"finance"})
await ctx.enable_components(tags={"admin"})
rules = await ctx._get_visibility_rules()
assert len(rules) == 2
return "activated"
# Globally disable finance and admin tools
mcp.disable(tags={"finance", "admin"})
async with Client(mcp) as client:
# Activate both
await client.call_tool("activate_multiple", {})
# Both should be visible
tools = await client.list_tools()
assert any(t.name == "finance_tool" for t in tools)
assert any(t.name == "admin_tool" for t in tools)
async def test_later_rules_override_earlier_rules(self):
"""Test that later session rules override earlier ones (mark semantics)."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.tool(tags={"test"})
def test_tool() -> str:
return "test"
@mcp.tool
async def toggle_test(ctx: Context) -> str:
# First enable, then disable
await ctx.enable_components(tags={"test"})
await ctx.disable_components(tags={"test"})
return "toggled"
async with Client(mcp) as client:
# Toggle (enable then disable)
await client.call_tool("toggle_test", {})
# The disable should win (later mark overrides earlier)
tools = await client.list_tools()
assert not any(t.name == "test_tool" for t in tools)
async def test_session_transforms_apply_to_resources(self):
"""Test that session transforms apply to resources too."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.resource("resource://finance", tags={"finance"})
def finance_resource() -> str:
return "finance data"
@mcp.tool
async def activate_finance(ctx: Context) -> str:
await ctx.enable_components(tags={"finance"})
return "activated"
# Globally disable finance resources
mcp.disable(tags={"finance"})
async with Client(mcp) as client:
# Before activation, finance resource should not be visible
resources_before = await client.list_resources()
assert not any(str(r.uri) == "resource://finance" for r in resources_before)
# Activate finance for this session
await client.call_tool("activate_finance", {})
# After activation, finance resource should be visible
resources_after = await client.list_resources()
assert any(str(r.uri) == "resource://finance" for r in resources_after)
async def test_session_transforms_apply_to_prompts(self):
"""Test that session transforms apply to prompts too."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.prompt(tags={"finance"})
def finance_prompt() -> str:
return "finance prompt"
@mcp.tool
async def activate_finance(ctx: Context) -> str:
await ctx.enable_components(tags={"finance"})
return "activated"
# Globally disable finance prompts
mcp.disable(tags={"finance"})
async with Client(mcp) as client:
# Before activation, finance prompt should not be visible
prompts_before = await client.list_prompts()
assert not any(p.name == "finance_prompt" for p in prompts_before)
# Activate finance for this session
await client.call_tool("activate_finance", {})
# After activation, finance prompt should be visible
prompts_after = await client.list_prompts()
assert any(p.name == "finance_prompt" for p in prompts_after)
class TestSessionVisibilityNotifications:
"""Test that notifications are sent when session visibility changes."""
async def test_enable_components_sends_notifications(self):
"""Test that enable_components sends all three notification types."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.tool
async def activate(ctx: Context) -> str:
await ctx.enable_components(tags={"finance"})
return "activated"
handler = RecordingMessageHandler()
async with Client(mcp, message_handler=handler) as client:
handler.reset()
await client.call_tool("activate", {})
# Should receive all three notifications
tool_notifications = handler.get_notifications(
"notifications/tools/list_changed"
)
resource_notifications = handler.get_notifications(
"notifications/resources/list_changed"
)
prompt_notifications = handler.get_notifications(
"notifications/prompts/list_changed"
)
assert len(tool_notifications) == 1
assert len(resource_notifications) == 1
assert len(prompt_notifications) == 1
async def test_disable_components_sends_notifications(self):
"""Test that disable_components sends all three notification types."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.tool
async def deactivate(ctx: Context) -> str:
await ctx.disable_components(tags={"finance"})
return "deactivated"
handler = RecordingMessageHandler()
async with Client(mcp, message_handler=handler) as client:
handler.reset()
await client.call_tool("deactivate", {})
# Should receive all three notifications
assert (
len(handler.get_notifications("notifications/tools/list_changed")) == 1
)
assert (
len(handler.get_notifications("notifications/resources/list_changed"))
== 1
)
assert (
len(handler.get_notifications("notifications/prompts/list_changed"))
== 1
)
async def test_clear_visibility_rules_sends_notifications(self):
"""Test that reset_visibility sends notifications."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.tool
async def clear(ctx: Context) -> str:
await ctx.reset_visibility()
return "cleared"
handler = RecordingMessageHandler()
async with Client(mcp, message_handler=handler) as client:
handler.reset()
await client.call_tool("clear", {})
# Should receive all three notifications
assert (
len(handler.get_notifications("notifications/tools/list_changed")) == 1
)
assert (
len(handler.get_notifications("notifications/resources/list_changed"))
== 1
)
assert (
len(handler.get_notifications("notifications/prompts/list_changed"))
== 1
)
async def test_components_hint_limits_notifications(self):
"""Test that the components hint limits which notifications are sent."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.tool
async def activate_tools_only(ctx: Context) -> str:
# Only specify tool components - should only send tool notification
await ctx.enable_components(tags={"finance"}, components={"tool"})
return "activated"
handler = RecordingMessageHandler()
async with Client(mcp, message_handler=handler) as client:
handler.reset()
await client.call_tool("activate_tools_only", {})
# Should only receive tool notification
assert (
len(handler.get_notifications("notifications/tools/list_changed")) == 1
)
assert (
len(handler.get_notifications("notifications/resources/list_changed"))
== 0
)
assert (
len(handler.get_notifications("notifications/prompts/list_changed"))
== 0
)
class TestConcurrentSessionIsolation:
"""Test that concurrent sessions don't leak visibility transforms."""
async def test_concurrent_sessions_isolated(self):
"""Test that two concurrent clients don't leak session transforms."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.tool(tags={"finance"})
def finance_tool() -> str:
return "finance"
@mcp.tool
async def activate_finance(ctx: Context) -> str:
await ctx.enable_components(tags={"finance"})
return "activated"
# Globally disable finance tools
mcp.disable(tags={"finance"})
# Track what each session sees
session_a_sees_finance = False
session_b_sees_finance = False
ready_event = anyio.Event()
async def session_a():
nonlocal session_a_sees_finance
async with Client(mcp) as client:
# Activate finance for this session
await client.call_tool("activate_finance", {})
# Signal that session A has activated
ready_event.set()
# Check that session A sees finance tool
tools = await client.list_tools()
session_a_sees_finance = any(t.name == "finance_tool" for t in tools)
# Keep session A alive while session B checks
await anyio.sleep(0.2)
async def session_b():
nonlocal session_b_sees_finance
# Wait for session A to activate
await ready_event.wait()
async with Client(mcp) as client:
# Session B should NOT see finance tool
tools = await client.list_tools()
session_b_sees_finance = any(t.name == "finance_tool" for t in tools)
async with anyio.create_task_group() as tg:
tg.start_soon(session_a)
tg.start_soon(session_b)
# Session A should see finance, session B should not
assert session_a_sees_finance is True, "Session A should see finance tool"
assert session_b_sees_finance is False, "Session B should NOT see finance tool"
async def test_many_concurrent_sessions_isolated(self):
"""Test that many concurrent sessions remain properly isolated."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.tool(tags={"premium"})
def premium_tool() -> str:
return "premium"
@mcp.tool
async def activate_premium(ctx: Context) -> str:
await ctx.enable_components(tags={"premium"})
return "activated"
# Globally disable premium tools
mcp.disable(tags={"premium"})
results: dict[str, bool] = {}
async def activated_session(session_id: str):
async with Client(mcp) as client:
await client.call_tool("activate_premium", {})
tools = await client.list_tools()
results[session_id] = any(t.name == "premium_tool" for t in tools)
async def non_activated_session(session_id: str):
async with Client(mcp) as client:
tools = await client.list_tools()
results[session_id] = any(t.name == "premium_tool" for t in tools)
async with anyio.create_task_group() as tg:
# Start 5 activated sessions
for i in range(5):
tg.start_soon(activated_session, f"activated_{i}")
# Start 5 non-activated sessions
for i in range(5):
tg.start_soon(non_activated_session, f"non_activated_{i}")
# All activated sessions should see premium tool
for i in range(5):
assert results[f"activated_{i}"] is True, (
f"Activated session {i} should see premium tool"
)
# All non-activated sessions should NOT see premium tool
for i in range(5):
assert results[f"non_activated_{i}"] is False, (
f"Non-activated session {i} should NOT see premium tool"
)
class TestSessionVisibilityResetBug:
"""Regression tests for #3034: visibility marks leak via shared component mutation."""
async def test_disable_then_reset_restores_tools(self):
"""After disable + reset within the same session, tools should reappear."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.tool(tags={"system"})
def my_tool() -> str:
return "hello"
@mcp.tool(tags={"env"})
async def enter_env(ctx: Context) -> str:
await ctx.disable_components(tags={"system"})
return "entered"
@mcp.tool(tags={"env"})
async def exit_env(ctx: Context) -> str:
await ctx.reset_visibility()
return "exited"
async with Client(mcp) as client:
# Tool visible initially
tools = await client.list_tools()
assert any(t.name == "my_tool" for t in tools)
# Disable it
await client.call_tool("enter_env", {})
tools = await client.list_tools()
assert not any(t.name == "my_tool" for t in tools)
# Reset — tool should come back
await client.call_tool("exit_env", {})
tools = await client.list_tools()
assert any(t.name == "my_tool" for t in tools), (
"Tool should be visible again after reset_visibility"
)
async def test_disable_reset_loop(self):
"""Repeated disable/reset cycles should work every time (the exact bug from #3034)."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.tool(tags={"system"})
def create_project() -> str:
return "created"
@mcp.tool(tags={"env"})
async def enter_env(ctx: Context) -> str:
await ctx.disable_components(tags={"system"})
return "entered"
@mcp.tool(tags={"env"})
async def exit_env(ctx: Context) -> str:
await ctx.reset_visibility()
return "exited"
async with Client(mcp) as client:
for i in range(3):
# create_project should be visible
tools = await client.list_tools()
assert any(t.name == "create_project" for t in tools), (
f"Iteration {i}: create_project should be visible before enter_env"
)
# Enter env — disables system tools
await client.call_tool("enter_env", {})
tools = await client.list_tools()
assert not any(t.name == "create_project" for t in tools), (
f"Iteration {i}: create_project should be hidden after enter_env"
)
# Exit env — reset
await client.call_tool("exit_env", {})
async def test_session_disable_does_not_leak_to_concurrent_session(self):
"""Disabling tools in one session must not affect a concurrent session."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.tool(tags={"system"})
def shared_tool() -> str:
return "shared"
@mcp.tool
async def disable_system(ctx: Context) -> str:
await ctx.disable_components(tags={"system"})
return "disabled"
session_b_sees_tool = False
ready = anyio.Event()
check_done = anyio.Event()
async def session_a():
async with Client(mcp) as client:
await client.call_tool("disable_system", {})
ready.set()
await check_done.wait()
async def session_b():
nonlocal session_b_sees_tool
await ready.wait()
async with Client(mcp) as client:
tools = await client.list_tools()
session_b_sees_tool = any(t.name == "shared_tool" for t in tools)
check_done.set()
async with anyio.create_task_group() as tg:
tg.start_soon(session_a)
tg.start_soon(session_b)
assert session_b_sees_tool is True, (
"Session B should still see shared_tool despite Session A disabling it"
)
async def test_session_disable_does_not_leak_to_sequential_session(self):
"""Disabling tools in one session must not affect a later session."""
from fastmcp import Client
mcp = FastMCP("test")
@mcp.tool(tags={"system"})
def shared_tool() -> str:
return "shared"
@mcp.tool
async def disable_system(ctx: Context) -> str:
await ctx.disable_components(tags={"system"})
return "disabled"
# Session A disables the tool (no reset)
async with Client(mcp) as client_a:
await client_a.call_tool("disable_system", {})
tools = await client_a.list_tools()
assert not any(t.name == "shared_tool" for t in tools)
# Session B should see it fresh
async with Client(mcp) as client_b:
tools = await client_b.list_tools()
assert any(t.name == "shared_tool" for t in tools), (
"New session should see shared_tool regardless of previous session"
)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/test_session_visibility.py",
"license": "Apache License 2.0",
"lines": 591,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:src/fastmcp/client/transports/base.py | import abc
import contextlib
import datetime
from collections.abc import AsyncIterator
from typing import Literal, TypeVar
import httpx
import mcp.types
from mcp import ClientSession
from mcp.client.session import (
ElicitationFnT,
ListRootsFnT,
LoggingFnT,
MessageHandlerFnT,
SamplingFnT,
)
from typing_extensions import TypedDict, Unpack
# TypeVar for preserving specific ClientTransport subclass types
ClientTransportT = TypeVar("ClientTransportT", bound="ClientTransport")
class SessionKwargs(TypedDict, total=False):
"""Keyword arguments for the MCP ClientSession constructor."""
read_timeout_seconds: datetime.timedelta | None
sampling_callback: SamplingFnT | None
sampling_capabilities: mcp.types.SamplingCapability | None
list_roots_callback: ListRootsFnT | None
logging_callback: LoggingFnT | None
elicitation_callback: ElicitationFnT | None
message_handler: MessageHandlerFnT | None
client_info: mcp.types.Implementation | None
class ClientTransport(abc.ABC):
"""
Abstract base class for different MCP client transport mechanisms.
A Transport is responsible for establishing and managing connections
to an MCP server, and providing a ClientSession within an async context.
"""
@abc.abstractmethod
@contextlib.asynccontextmanager
async def connect_session(
self, **session_kwargs: Unpack[SessionKwargs]
) -> AsyncIterator[ClientSession]:
"""
Establishes a connection and yields an active ClientSession.
The ClientSession is *not* expected to be initialized in this context manager.
The session is guaranteed to be valid only within the scope of the
async context manager. Connection setup and teardown are handled
within this context.
Args:
**session_kwargs: Keyword arguments to pass to the ClientSession
constructor (e.g., callbacks, timeouts).
Yields:
A mcp.ClientSession instance.
"""
raise NotImplementedError
yield
def __repr__(self) -> str:
# Basic representation for subclasses
return f"<{self.__class__.__name__}>"
async def close(self): # noqa: B027
"""Close the transport."""
def get_session_id(self) -> str | None:
"""Get the session ID for this transport, if available."""
return None
def _set_auth(self, auth: httpx.Auth | Literal["oauth"] | str | None):
if auth is not None:
raise ValueError("This transport does not support auth")
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/client/transports/base.py",
"license": "Apache License 2.0",
"lines": 64,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
PrefectHQ/fastmcp:src/fastmcp/client/transports/config.py | import contextlib
import datetime
from collections.abc import AsyncIterator
from typing import Any
from mcp import ClientSession
from typing_extensions import Unpack
from fastmcp.client.transports.base import ClientTransport, SessionKwargs
from fastmcp.client.transports.memory import FastMCPTransport
from fastmcp.mcp_config import (
MCPConfig,
MCPServerTypes,
RemoteMCPServer,
StdioMCPServer,
TransformingRemoteMCPServer,
TransformingStdioMCPServer,
)
from fastmcp.server.server import FastMCP, create_proxy
class MCPConfigTransport(ClientTransport):
"""Transport for connecting to one or more MCP servers defined in an MCPConfig.
This transport provides a unified interface to multiple MCP servers defined in an MCPConfig
object or dictionary matching the MCPConfig schema. It supports two key scenarios:
1. If the MCPConfig contains exactly one server, it creates a direct transport to that server.
2. If the MCPConfig contains multiple servers, it creates a composite client by mounting
all servers on a single FastMCP instance, with each server's name, by default, used as its mounting prefix.
In the multiserver case, tools are accessible with the prefix pattern `{server_name}_{tool_name}`
and resources with the pattern `protocol://{server_name}/path/to/resource`.
This is particularly useful for creating clients that need to interact with multiple specialized
MCP servers through a single interface, simplifying client code.
Examples:
```python
from fastmcp import Client
# Create a config with multiple servers
config = {
"mcpServers": {
"weather": {
"url": "https://weather-api.example.com/mcp",
"transport": "http"
},
"calendar": {
"url": "https://calendar-api.example.com/mcp",
"transport": "http"
}
}
}
# Create a client with the config
client = Client(config)
async with client:
# Access tools with prefixes
weather = await client.call_tool("weather_get_forecast", {"city": "London"})
events = await client.call_tool("calendar_list_events", {"date": "2023-06-01"})
# Access resources with prefixed URIs
icons = await client.read_resource("weather://weather/icons/sunny")
```
"""
def __init__(self, config: MCPConfig | dict, name_as_prefix: bool = True):
if isinstance(config, dict):
config = MCPConfig.from_dict(config)
self.config = config
self.name_as_prefix = name_as_prefix
self._transports: list[ClientTransport] = []
if not self.config.mcpServers:
raise ValueError("No MCP servers defined in the config")
# For single server, create transport eagerly so it can be inspected
if len(self.config.mcpServers) == 1:
self.transport = next(iter(self.config.mcpServers.values())).to_transport()
self._transports.append(self.transport)
@contextlib.asynccontextmanager
async def connect_session(
self, **session_kwargs: Unpack[SessionKwargs]
) -> AsyncIterator[ClientSession]:
# Single server - delegate directly to pre-created transport
if len(self.config.mcpServers) == 1:
async with self.transport.connect_session(**session_kwargs) as session:
yield session
return
# Multiple servers - create composite with mounted proxies, connecting
# each ProxyClient so its underlying transport session stays alive for
# the duration of this context (fixes session persistence for
# streamable-http backends — see #2790).
timeout = session_kwargs.get("read_timeout_seconds")
composite = FastMCP[Any](name="MCPRouter")
async with contextlib.AsyncExitStack() as stack:
# Close any previous transports from prior connections to avoid leaking
for t in self._transports:
await t.close()
self._transports = []
try:
for name, server_config in self.config.mcpServers.items():
transport, _client, proxy = await self._create_proxy(
name, server_config, timeout, stack
)
self._transports.append(transport)
composite.mount(
proxy, namespace=name if self.name_as_prefix else None
)
except Exception:
# Clean up any transports created before the failure
for t in self._transports:
await t.close()
self._transports = []
raise
async with FastMCPTransport(mcp=composite).connect_session(
**session_kwargs
) as session:
yield session
async def _create_proxy(
self,
name: str,
config: MCPServerTypes,
timeout: datetime.timedelta | None,
stack: contextlib.AsyncExitStack,
) -> tuple[ClientTransport, Any, FastMCP[Any]]:
"""Create underlying transport, proxy client, and proxy server for a single backend.
The ProxyClient is connected via the AsyncExitStack *before* being
passed to create_proxy so the factory sees it as connected and reuses
the same session for all tool calls (instead of creating fresh copies).
Returns a tuple of (transport, proxy_client, proxy_server).
"""
# Import here to avoid circular dependency
from fastmcp.server.providers.proxy import StatefulProxyClient
tool_transforms = None
include_tags = None
exclude_tags = None
# Handle transforming servers - call base class to_transport() for underlying transport
if isinstance(config, TransformingStdioMCPServer):
transport = StdioMCPServer.to_transport(config)
tool_transforms = config.tools
include_tags = config.include_tags
exclude_tags = config.exclude_tags
elif isinstance(config, TransformingRemoteMCPServer):
transport = RemoteMCPServer.to_transport(config)
tool_transforms = config.tools
include_tags = config.include_tags
exclude_tags = config.exclude_tags
else:
transport = config.to_transport()
client = StatefulProxyClient(transport=transport, timeout=timeout)
# Connect the client *before* create_proxy so _create_client_factory
# detects it as connected and reuses it for all tool calls, preserving
# the session ID across requests. StatefulProxyClient is used instead
# of ProxyClient because its context-restoring handler wrappers prevent
# stale ContextVars in the reused session's receive loop.
#
# StatefulProxyClient.__aexit__ is a no-op (by design, for the
# new_stateful() use case), so we cannot rely on enter_async_context
# alone to clean up. Instead we connect manually and push an
# explicit force-disconnect callback so the subprocess is terminated
# when the AsyncExitStack unwinds.
await client.__aenter__()
# Callbacks run LIFO: transport.close() must run *after*
# client._disconnect so push it first.
stack.push_async_callback(transport.close)
stack.push_async_callback(client._disconnect, force=True)
# Create proxy without include_tags/exclude_tags - we'll add them after tool transforms
proxy = create_proxy(
client,
name=f"Proxy-{name}",
)
# Add tool transforms FIRST - they may add/modify tags
if tool_transforms:
from fastmcp.server.transforms import ToolTransform
proxy.add_transform(ToolTransform(tool_transforms))
# Then add enabled filters - they filter based on tags
if include_tags:
proxy.enable(tags=set(include_tags), only=True)
if exclude_tags:
proxy.disable(tags=set(exclude_tags))
return transport, client, proxy
async def close(self):
for transport in self._transports:
await transport.close()
def __repr__(self) -> str:
return f"<MCPConfigTransport(config='{self.config}')>"
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/client/transports/config.py",
"license": "Apache License 2.0",
"lines": 173,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/client/transports/http.py | """Streamable HTTP transport for FastMCP Client."""
from __future__ import annotations
import contextlib
import datetime
from collections.abc import AsyncIterator, Callable
from typing import Literal, cast
import httpx
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client
from mcp.shared._httpx_utils import McpHttpClientFactory, create_mcp_http_client
from pydantic import AnyUrl
from typing_extensions import Unpack
import fastmcp
from fastmcp.client.auth.bearer import BearerAuth
from fastmcp.client.auth.oauth import OAuth
from fastmcp.client.transports.base import ClientTransport, SessionKwargs
from fastmcp.server.dependencies import get_http_headers
from fastmcp.utilities.timeout import normalize_timeout_to_timedelta
class StreamableHttpTransport(ClientTransport):
"""Transport implementation that connects to an MCP server via Streamable HTTP Requests."""
def __init__(
self,
url: str | AnyUrl,
headers: dict[str, str] | None = None,
auth: httpx.Auth | Literal["oauth"] | str | None = None,
sse_read_timeout: datetime.timedelta | float | int | None = None,
httpx_client_factory: McpHttpClientFactory | None = None,
):
"""Initialize a Streamable HTTP transport.
Args:
url: The MCP server endpoint URL.
headers: Optional headers to include in requests.
auth: Authentication method - httpx.Auth, "oauth" for OAuth flow,
or a bearer token string.
sse_read_timeout: Deprecated. Use read_timeout_seconds in session_kwargs.
httpx_client_factory: Optional factory for creating httpx.AsyncClient.
If provided, must accept keyword arguments: headers, auth,
follow_redirects, and optionally timeout. Using **kwargs is
recommended to ensure forward compatibility.
"""
if isinstance(url, AnyUrl):
url = str(url)
if not isinstance(url, str) or not url.startswith("http"):
raise ValueError("Invalid HTTP/S URL provided for Streamable HTTP.")
# Don't modify the URL path - respect the exact URL provided by the user
# Some servers are strict about trailing slashes (e.g., PayPal MCP)
self.url: str = url
self.headers = headers or {}
self.httpx_client_factory = httpx_client_factory
self._set_auth(auth)
if sse_read_timeout is not None:
if fastmcp.settings.deprecation_warnings:
import warnings
warnings.warn(
"The `sse_read_timeout` parameter is deprecated and no longer used. "
"The new streamable_http_client API does not support this parameter. "
"Use `read_timeout_seconds` in session_kwargs or configure timeout on "
"the httpx client via `httpx_client_factory` instead.",
DeprecationWarning,
stacklevel=2,
)
self.sse_read_timeout = normalize_timeout_to_timedelta(sse_read_timeout)
self._get_session_id_cb: Callable[[], str | None] | None = None
def _set_auth(self, auth: httpx.Auth | Literal["oauth"] | str | None):
resolved: httpx.Auth | None
if auth == "oauth":
resolved = OAuth(self.url, httpx_client_factory=self.httpx_client_factory)
elif isinstance(auth, OAuth):
auth._bind(self.url)
resolved = auth
elif isinstance(auth, str):
resolved = BearerAuth(auth)
else:
resolved = auth
self.auth: httpx.Auth | None = resolved
@contextlib.asynccontextmanager
async def connect_session(
self, **session_kwargs: Unpack[SessionKwargs]
) -> AsyncIterator[ClientSession]:
# Load headers from an active HTTP request, if available. This will only be true
# if the client is used in a FastMCP Proxy, in which case the MCP client headers
# need to be forwarded to the remote server.
headers = get_http_headers(include={"authorization"}) | self.headers
# Configure timeout if provided, preserving MCP's 30s connect default
timeout: httpx.Timeout | None = None
if session_kwargs.get("read_timeout_seconds") is not None:
read_timeout_seconds = cast(
datetime.timedelta, session_kwargs.get("read_timeout_seconds")
)
timeout = httpx.Timeout(30.0, read=read_timeout_seconds.total_seconds())
# Create httpx client from factory or use default with MCP-appropriate timeouts
# create_mcp_http_client uses 30s connect/5min read timeout by default,
# and always enables follow_redirects
if self.httpx_client_factory is not None:
# Factory clients get the full kwargs for backwards compatibility
http_client = self.httpx_client_factory(
headers=headers,
auth=self.auth,
follow_redirects=True, # type: ignore[call-arg]
**({"timeout": timeout} if timeout else {}),
)
else:
http_client = create_mcp_http_client(
headers=headers,
timeout=timeout,
auth=self.auth,
)
# Ensure httpx client is closed after use
async with (
http_client,
streamable_http_client(self.url, http_client=http_client) as transport,
):
read_stream, write_stream, get_session_id = transport
self._get_session_id_cb = get_session_id
async with ClientSession(
read_stream, write_stream, **session_kwargs
) as session:
yield session
def get_session_id(self) -> str | None:
if self._get_session_id_cb:
try:
return self._get_session_id_cb()
except Exception:
return None
return None
async def close(self):
# Reset the session id callback
self._get_session_id_cb = None
def __repr__(self) -> str:
return f"<StreamableHttpTransport(url='{self.url}')>"
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/client/transports/http.py",
"license": "Apache License 2.0",
"lines": 130,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/client/transports/inference.py | from pathlib import Path
from typing import TYPE_CHECKING, Any, cast, overload
from mcp.server.fastmcp import FastMCP as FastMCP1Server
from pydantic import AnyUrl
from fastmcp.client.transports.base import ClientTransport, ClientTransportT
from fastmcp.client.transports.config import MCPConfigTransport
from fastmcp.client.transports.http import StreamableHttpTransport
from fastmcp.client.transports.memory import FastMCPTransport
from fastmcp.client.transports.sse import SSETransport
from fastmcp.client.transports.stdio import NodeStdioTransport, PythonStdioTransport
from fastmcp.mcp_config import MCPConfig, infer_transport_type_from_url
from fastmcp.server.server import FastMCP
from fastmcp.utilities.logging import get_logger
if TYPE_CHECKING:
pass
logger = get_logger(__name__)
@overload
def infer_transport(transport: ClientTransportT) -> ClientTransportT: ...
@overload
def infer_transport(transport: FastMCP) -> FastMCPTransport: ...
@overload
def infer_transport(transport: FastMCP1Server) -> FastMCPTransport: ...
@overload
def infer_transport(transport: MCPConfig) -> MCPConfigTransport: ...
@overload
def infer_transport(transport: dict[str, Any]) -> MCPConfigTransport: ...
@overload
def infer_transport(
transport: AnyUrl,
) -> SSETransport | StreamableHttpTransport: ...
@overload
def infer_transport(
transport: str,
) -> (
PythonStdioTransport | NodeStdioTransport | SSETransport | StreamableHttpTransport
): ...
@overload
def infer_transport(transport: Path) -> PythonStdioTransport | NodeStdioTransport: ...
def infer_transport(
transport: ClientTransport
| FastMCP
| FastMCP1Server
| AnyUrl
| Path
| MCPConfig
| dict[str, Any]
| str,
) -> ClientTransport:
"""
Infer the appropriate transport type from the given transport argument.
This function attempts to infer the correct transport type from the provided
argument, handling various input types and converting them to the appropriate
ClientTransport subclass.
The function supports these input types:
- ClientTransport: Used directly without modification
- FastMCP or FastMCP1Server: Creates an in-memory FastMCPTransport
- Path or str (file path): Creates PythonStdioTransport (.py) or NodeStdioTransport (.js)
- AnyUrl or str (URL): Creates StreamableHttpTransport (default) or SSETransport (for /sse endpoints)
- MCPConfig or dict: Creates MCPConfigTransport, potentially connecting to multiple servers
For HTTP URLs, they are assumed to be Streamable HTTP URLs unless they end in `/sse`.
For MCPConfig with multiple servers, a composite client is created where each server
is mounted with its name as prefix. This allows accessing tools and resources from multiple
servers through a single unified client interface, using naming patterns like
`servername_toolname` for tools and `protocol://servername/path` for resources.
If the MCPConfig contains only one server, a direct connection is established without prefixing.
Examples:
```python
# Connect to a local Python script
transport = infer_transport("my_script.py")
# Connect to a remote server via HTTP
transport = infer_transport("http://example.com/mcp")
# Connect to multiple servers using MCPConfig
config = {
"mcpServers": {
"weather": {"url": "http://weather.example.com/mcp"},
"calendar": {"url": "http://calendar.example.com/mcp"}
}
}
transport = infer_transport(config)
```
"""
# the transport is already a ClientTransport
if isinstance(transport, ClientTransport):
return transport
# the transport is a FastMCP server (2.x or 1.0)
elif isinstance(transport, FastMCP | FastMCP1Server):
inferred_transport = FastMCPTransport(
mcp=cast(FastMCP[Any] | FastMCP1Server, transport)
)
# the transport is a path to a script
elif isinstance(transport, Path | str) and Path(transport).exists():
if str(transport).endswith(".py"):
inferred_transport = PythonStdioTransport(script_path=cast(Path, transport))
elif str(transport).endswith(".js"):
inferred_transport = NodeStdioTransport(script_path=cast(Path, transport))
else:
raise ValueError(f"Unsupported script type: {transport}")
# the transport is an http(s) URL
elif isinstance(transport, AnyUrl | str) and str(transport).startswith("http"):
inferred_transport_type = infer_transport_type_from_url(
cast(AnyUrl | str, transport)
)
if inferred_transport_type == "sse":
inferred_transport = SSETransport(url=cast(AnyUrl | str, transport))
else:
inferred_transport = StreamableHttpTransport(
url=cast(AnyUrl | str, transport)
)
# if the transport is a config dict or MCPConfig
elif isinstance(transport, dict | MCPConfig):
inferred_transport = MCPConfigTransport(
config=cast(dict | MCPConfig, transport)
)
# the transport is an unknown type
else:
raise ValueError(f"Could not infer a valid transport from: {transport}")
logger.debug(f"Inferred transport: {inferred_transport}")
return inferred_transport
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/client/transports/inference.py",
"license": "Apache License 2.0",
"lines": 118,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/client/transports/memory.py | import contextlib
from collections.abc import AsyncIterator
import anyio
from mcp import ClientSession
from mcp.server.fastmcp import FastMCP as FastMCP1Server
from mcp.shared.memory import create_client_server_memory_streams
from typing_extensions import Unpack
from fastmcp.client.transports.base import ClientTransport, SessionKwargs
from fastmcp.server.server import FastMCP
class FastMCPTransport(ClientTransport):
"""In-memory transport for FastMCP servers.
This transport connects directly to a FastMCP server instance in the same
Python process. It works with both FastMCP 2.x servers and FastMCP 1.0
servers from the low-level MCP SDK. This is particularly useful for unit
tests or scenarios where client and server run in the same runtime.
"""
def __init__(self, mcp: FastMCP | FastMCP1Server, raise_exceptions: bool = False):
"""Initialize a FastMCPTransport from a FastMCP server instance."""
# Accept both FastMCP 2.x and FastMCP 1.0 servers. Both expose a
# ``_mcp_server`` attribute pointing to the underlying MCP server
# implementation, so we can treat them identically.
self.server = mcp
self.raise_exceptions = raise_exceptions
@contextlib.asynccontextmanager
async def connect_session(
self, **session_kwargs: Unpack[SessionKwargs]
) -> AsyncIterator[ClientSession]:
async with create_client_server_memory_streams() as (
client_streams,
server_streams,
):
client_read, client_write = client_streams
server_read, server_write = server_streams
# Capture exceptions to re-raise after task group cleanup.
# anyio task groups can suppress exceptions when cancel_scope.cancel()
# is called during cleanup, so we capture and re-raise manually.
exception_to_raise: BaseException | None = None
async with (
anyio.create_task_group() as tg,
_enter_server_lifespan(server=self.server),
):
tg.start_soon(
lambda: self.server._mcp_server.run(
server_read,
server_write,
self.server._mcp_server.create_initialization_options(),
raise_exceptions=self.raise_exceptions,
)
)
try:
async with ClientSession(
read_stream=client_read,
write_stream=client_write,
**session_kwargs,
) as client_session:
yield client_session
except BaseException as e:
exception_to_raise = e
finally:
tg.cancel_scope.cancel()
# Re-raise after task group has exited cleanly
if exception_to_raise is not None:
raise exception_to_raise
def __repr__(self) -> str:
return f"<FastMCPTransport(server='{self.server.name}')>"
@contextlib.asynccontextmanager
async def _enter_server_lifespan(
server: FastMCP | FastMCP1Server,
) -> AsyncIterator[None]:
"""Enters the server's lifespan context for FastMCP servers and does nothing for FastMCP 1 servers."""
if isinstance(server, FastMCP):
async with server._lifespan_manager():
yield
else:
yield
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/client/transports/memory.py",
"license": "Apache License 2.0",
"lines": 75,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/client/transports/stdio.py | import asyncio
import contextlib
import os
import shutil
import sys
from collections.abc import AsyncIterator
from pathlib import Path
from typing import TextIO, cast
import anyio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from typing_extensions import Unpack
from fastmcp.client.transports.base import ClientTransport, SessionKwargs
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.mcp_server_config.v1.environments.uv import UVEnvironment
logger = get_logger(__name__)
class StdioTransport(ClientTransport):
"""
Base transport for connecting to an MCP server via subprocess with stdio.
This is a base class that can be subclassed for specific command-based
transports like Python, Node, Uvx, etc.
"""
def __init__(
self,
command: str,
args: list[str],
env: dict[str, str] | None = None,
cwd: str | None = None,
keep_alive: bool | None = None,
log_file: Path | TextIO | None = None,
):
"""
Initialize a Stdio transport.
Args:
command: The command to run (e.g., "python", "node", "uvx")
args: The arguments to pass to the command
env: Environment variables to set for the subprocess
cwd: Current working directory for the subprocess
keep_alive: Whether to keep the subprocess alive between connections.
Defaults to True. When True, the subprocess remains active
after the connection context exits, allowing reuse in
subsequent connections.
log_file: Optional path or file-like object where subprocess stderr will
be written. Can be a Path or TextIO object. Defaults to sys.stderr
if not provided. When a Path is provided, the file will be created
if it doesn't exist, or appended to if it does. When set, server
errors will be written to this file instead of appearing in the console.
"""
self.command = command
self.args = args
self.env = env
self.cwd = cwd
if keep_alive is None:
keep_alive = True
self.keep_alive = keep_alive
self.log_file = log_file
self._session: ClientSession | None = None
self._connect_task: asyncio.Task | None = None
self._ready_event = anyio.Event()
self._stop_event = anyio.Event()
@contextlib.asynccontextmanager
async def connect_session(
self, **session_kwargs: Unpack[SessionKwargs]
) -> AsyncIterator[ClientSession]:
try:
await self.connect(**session_kwargs)
yield cast(ClientSession, self._session)
finally:
if not self.keep_alive:
await self.disconnect()
else:
logger.debug("Stdio transport has keep_alive=True, not disconnecting")
async def connect(
self, **session_kwargs: Unpack[SessionKwargs]
) -> ClientSession | None:
if self._connect_task is not None:
return
session_future: asyncio.Future[ClientSession] = asyncio.Future()
# start the connection task
self._connect_task = asyncio.create_task(
_stdio_transport_connect_task(
command=self.command,
args=self.args,
env=self.env,
cwd=self.cwd,
log_file=self.log_file,
# TODO(ty): remove when ty supports Unpack[TypedDict] inference
session_kwargs=session_kwargs, # type: ignore[arg-type]
ready_event=self._ready_event,
stop_event=self._stop_event,
session_future=session_future,
)
)
# wait for the client to be ready before returning
await self._ready_event.wait()
# Check if connect task completed with an exception (early failure)
if self._connect_task.done():
exception = self._connect_task.exception()
if exception is not None:
raise exception
self._session = await session_future
return self._session
async def disconnect(self):
if self._connect_task is None:
return
# signal the connection task to stop
self._stop_event.set()
# wait for the connection task to finish cleanly
await self._connect_task
# reset variables and events for potential future reconnects
self._connect_task = None
self._stop_event = anyio.Event()
self._ready_event = anyio.Event()
async def close(self):
await self.disconnect()
def __del__(self):
"""Ensure that we send a disconnection signal to the transport task if we are being garbage collected."""
if not self._stop_event.is_set():
self._stop_event.set()
def __repr__(self) -> str:
return (
f"<{self.__class__.__name__}(command='{self.command}', args={self.args})>"
)
async def _stdio_transport_connect_task(
command: str,
args: list[str],
env: dict[str, str] | None,
cwd: str | None,
log_file: Path | TextIO | None,
session_kwargs: SessionKwargs,
ready_event: anyio.Event,
stop_event: anyio.Event,
session_future: asyncio.Future[ClientSession],
):
"""A standalone connection task for a stdio transport. It is not a part of the StdioTransport class
to ensure that the connection task does not hold a reference to the Transport object."""
try:
async with contextlib.AsyncExitStack() as stack:
try:
server_params = StdioServerParameters(
command=command,
args=args,
env=env,
cwd=cwd,
)
# Handle log_file: Path needs to be opened, TextIO used as-is
if log_file is None:
log_file_handle = sys.stderr
elif isinstance(log_file, Path):
log_file_handle = stack.enter_context(log_file.open("a"))
else:
# Must be TextIO - use it directly
log_file_handle = log_file
transport = await stack.enter_async_context(
stdio_client(server_params, errlog=log_file_handle)
)
read_stream, write_stream = transport
session_future.set_result(
await stack.enter_async_context(
ClientSession(read_stream, write_stream, **session_kwargs)
)
)
logger.debug("Stdio transport connected")
ready_event.set()
# Wait until disconnect is requested (stop_event is set)
await stop_event.wait()
finally:
# Clean up client on exit
logger.debug("Stdio transport disconnected")
except Exception:
# Ensure ready event is set even if connection fails
ready_event.set()
raise
class PythonStdioTransport(StdioTransport):
"""Transport for running Python scripts."""
def __init__(
self,
script_path: str | Path,
args: list[str] | None = None,
env: dict[str, str] | None = None,
cwd: str | None = None,
python_cmd: str = sys.executable,
keep_alive: bool | None = None,
log_file: Path | TextIO | None = None,
):
"""
Initialize a Python transport.
Args:
script_path: Path to the Python script to run
args: Additional arguments to pass to the script
env: Environment variables to set for the subprocess
cwd: Current working directory for the subprocess
python_cmd: Python command to use (default: "python")
keep_alive: Whether to keep the subprocess alive between connections.
Defaults to True. When True, the subprocess remains active
after the connection context exits, allowing reuse in
subsequent connections.
log_file: Optional path or file-like object where subprocess stderr will
be written. Can be a Path or TextIO object. Defaults to sys.stderr
if not provided. When a Path is provided, the file will be created
if it doesn't exist, or appended to if it does. When set, server
errors will be written to this file instead of appearing in the console.
"""
script_path = Path(script_path).resolve()
if not script_path.is_file():
raise FileNotFoundError(f"Script not found: {script_path}")
if not str(script_path).endswith(".py"):
raise ValueError(f"Not a Python script: {script_path}")
full_args = [str(script_path)]
if args:
full_args.extend(args)
super().__init__(
command=python_cmd,
args=full_args,
env=env,
cwd=cwd,
keep_alive=keep_alive,
log_file=log_file,
)
self.script_path = script_path
class FastMCPStdioTransport(StdioTransport):
"""Transport for running FastMCP servers using the FastMCP CLI."""
def __init__(
self,
script_path: str | Path,
args: list[str] | None = None,
env: dict[str, str] | None = None,
cwd: str | None = None,
keep_alive: bool | None = None,
log_file: Path | TextIO | None = None,
):
script_path = Path(script_path).resolve()
if not script_path.is_file():
raise FileNotFoundError(f"Script not found: {script_path}")
if not str(script_path).endswith(".py"):
raise ValueError(f"Not a Python script: {script_path}")
super().__init__(
command="fastmcp",
args=["run", str(script_path)],
env=env,
cwd=cwd,
keep_alive=keep_alive,
log_file=log_file,
)
self.script_path = script_path
class NodeStdioTransport(StdioTransport):
"""Transport for running Node.js scripts."""
def __init__(
self,
script_path: str | Path,
args: list[str] | None = None,
env: dict[str, str] | None = None,
cwd: str | None = None,
node_cmd: str = "node",
keep_alive: bool | None = None,
log_file: Path | TextIO | None = None,
):
"""
Initialize a Node transport.
Args:
script_path: Path to the Node.js script to run
args: Additional arguments to pass to the script
env: Environment variables to set for the subprocess
cwd: Current working directory for the subprocess
node_cmd: Node.js command to use (default: "node")
keep_alive: Whether to keep the subprocess alive between connections.
Defaults to True. When True, the subprocess remains active
after the connection context exits, allowing reuse in
subsequent connections.
log_file: Optional path or file-like object where subprocess stderr will
be written. Can be a Path or TextIO object. Defaults to sys.stderr
if not provided. When a Path is provided, the file will be created
if it doesn't exist, or appended to if it does. When set, server
errors will be written to this file instead of appearing in the console.
"""
script_path = Path(script_path).resolve()
if not script_path.is_file():
raise FileNotFoundError(f"Script not found: {script_path}")
if not str(script_path).endswith(".js"):
raise ValueError(f"Not a JavaScript script: {script_path}")
full_args = [str(script_path)]
if args:
full_args.extend(args)
super().__init__(
command=node_cmd,
args=full_args,
env=env,
cwd=cwd,
keep_alive=keep_alive,
log_file=log_file,
)
self.script_path = script_path
class UvStdioTransport(StdioTransport):
"""Transport for running commands via the uv tool."""
def __init__(
self,
command: str,
args: list[str] | None = None,
module: bool = False,
project_directory: Path | None = None,
python_version: str | None = None,
with_packages: list[str] | None = None,
with_requirements: Path | None = None,
env_vars: dict[str, str] | None = None,
keep_alive: bool | None = None,
):
# Basic validation
if project_directory and not project_directory.exists():
raise NotADirectoryError(
f"Project directory not found: {project_directory}"
)
# Create Environment from provided parameters (internal use)
env_config = UVEnvironment(
python=python_version,
dependencies=with_packages,
requirements=with_requirements,
project=project_directory,
editable=None, # Not exposed in this transport
)
# Build uv arguments using the config
uv_args: list[str] = []
# Check if we need any environment setup
if env_config._must_run_with_uv():
# Use the config to build args, but we need to handle the command differently
# since transport has specific needs
uv_args = ["run"]
if python_version:
uv_args.extend(["--python", python_version])
if project_directory:
uv_args.extend(["--directory", str(project_directory)])
# Note: Don't add fastmcp as dependency here, transport is for general use
for pkg in with_packages or []:
uv_args.extend(["--with", pkg])
if with_requirements:
uv_args.extend(["--with-requirements", str(with_requirements)])
else:
# No environment setup needed
uv_args = ["run"]
if module:
uv_args.append("--module")
if not args:
args = []
uv_args.extend([command, *args])
# Get environment with any additional variables
env: dict[str, str] | None = None
if env_vars or project_directory:
env = os.environ.copy()
if project_directory:
env["UV_PROJECT_DIR"] = str(project_directory)
if env_vars:
env.update(env_vars)
super().__init__(
command="uv",
args=uv_args,
env=env,
cwd=None, # Use --directory flag instead of cwd
keep_alive=keep_alive,
)
class UvxStdioTransport(StdioTransport):
"""Transport for running commands via the uvx tool."""
def __init__(
self,
tool_name: str,
tool_args: list[str] | None = None,
project_directory: str | None = None,
python_version: str | None = None,
with_packages: list[str] | None = None,
from_package: str | None = None,
env_vars: dict[str, str] | None = None,
keep_alive: bool | None = None,
):
"""
Initialize a Uvx transport.
Args:
tool_name: Name of the tool to run via uvx
tool_args: Arguments to pass to the tool
project_directory: Project directory (for package resolution)
python_version: Python version to use
with_packages: Additional packages to include
from_package: Package to install the tool from
env_vars: Additional environment variables
keep_alive: Whether to keep the subprocess alive between connections.
Defaults to True. When True, the subprocess remains active
after the connection context exits, allowing reuse in
subsequent connections.
"""
# Basic validation
if project_directory and not Path(project_directory).exists():
raise NotADirectoryError(
f"Project directory not found: {project_directory}"
)
# Build uvx arguments
uvx_args: list[str] = []
if python_version:
uvx_args.extend(["--python", python_version])
if from_package:
uvx_args.extend(["--from", from_package])
for pkg in with_packages or []:
uvx_args.extend(["--with", pkg])
# Add the tool name and tool args
uvx_args.append(tool_name)
if tool_args:
uvx_args.extend(tool_args)
env: dict[str, str] | None = None
if env_vars:
env = os.environ.copy()
env.update(env_vars)
super().__init__(
command="uvx",
args=uvx_args,
env=env,
cwd=project_directory,
keep_alive=keep_alive,
)
self.tool_name: str = tool_name
class NpxStdioTransport(StdioTransport):
"""Transport for running commands via the npx tool."""
def __init__(
self,
package: str,
args: list[str] | None = None,
project_directory: str | None = None,
env_vars: dict[str, str] | None = None,
use_package_lock: bool = True,
keep_alive: bool | None = None,
):
"""
Initialize an Npx transport.
Args:
package: Name of the npm package to run
args: Arguments to pass to the package command
project_directory: Project directory with package.json
env_vars: Additional environment variables
use_package_lock: Whether to use package-lock.json (--prefer-offline)
keep_alive: Whether to keep the subprocess alive between connections.
Defaults to True. When True, the subprocess remains active
after the connection context exits, allowing reuse in
subsequent connections.
"""
# verify npx is installed
if shutil.which("npx") is None:
raise ValueError("Command 'npx' not found")
# Basic validation
if project_directory and not Path(project_directory).exists():
raise NotADirectoryError(
f"Project directory not found: {project_directory}"
)
# Build npx arguments
npx_args = []
if use_package_lock:
npx_args.append("--prefer-offline")
# Add the package name and args
npx_args.append(package)
if args:
npx_args.extend(args)
# Get environment with any additional variables
env = None
if env_vars:
env = os.environ.copy()
env.update(env_vars)
super().__init__(
command="npx",
args=npx_args,
env=env,
cwd=project_directory,
keep_alive=keep_alive,
)
self.package = package
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/client/transports/stdio.py",
"license": "Apache License 2.0",
"lines": 468,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/server/providers/wrapped_provider.py | """WrappedProvider for immutable transform composition.
This module provides `_WrappedProvider`, an internal class that wraps a provider
with an additional transform. Created by `Provider.wrap_transform()`.
"""
from __future__ import annotations
from collections.abc import AsyncIterator, Sequence
from contextlib import asynccontextmanager
from typing import TYPE_CHECKING
from fastmcp.server.providers.base import Provider
from fastmcp.utilities.versions import VersionSpec
if TYPE_CHECKING:
from fastmcp.prompts.prompt import Prompt
from fastmcp.resources.resource import Resource
from fastmcp.resources.template import ResourceTemplate
from fastmcp.server.transforms import Transform
from fastmcp.tools.tool import Tool
from fastmcp.utilities.components import FastMCPComponent
class _WrappedProvider(Provider):
"""Internal provider that wraps another provider with a transform.
Created by Provider.wrap_transform(). Delegates all component sourcing
to the inner provider's public methods (which apply inner's transforms),
then applies the wrapper's transform on top.
This enables immutable transform composition - the inner provider is
unchanged, and the wrapper adds its transform layer.
"""
def __init__(self, inner: Provider, transform: Transform) -> None:
"""Initialize wrapped provider.
Args:
inner: The provider to wrap.
transform: The transform to apply on top of inner's results.
"""
super().__init__()
self._inner = inner
# Add the transform to this provider's transform list
# It will be applied via the normal transform chain
self._transforms.append(transform)
def __repr__(self) -> str:
return f"_WrappedProvider({self._inner!r}, transforms={self._transforms!r})"
# -------------------------------------------------------------------------
# Delegate to inner provider's public methods (which apply inner's transforms)
# -------------------------------------------------------------------------
async def _list_tools(self) -> Sequence[Tool]:
"""Delegate to inner's list_tools (includes inner's transforms)."""
return await self._inner.list_tools()
async def _get_tool(
self, name: str, version: VersionSpec | None = None
) -> Tool | None:
"""Delegate to inner's get_tool (includes inner's transforms)."""
return await self._inner.get_tool(name, version)
async def _list_resources(self) -> Sequence[Resource]:
"""Delegate to inner's list_resources (includes inner's transforms)."""
return await self._inner.list_resources()
async def _get_resource(
self, uri: str, version: VersionSpec | None = None
) -> Resource | None:
"""Delegate to inner's get_resource (includes inner's transforms)."""
return await self._inner.get_resource(uri, version)
async def _list_resource_templates(self) -> Sequence[ResourceTemplate]:
"""Delegate to inner's list_resource_templates (includes inner's transforms)."""
return await self._inner.list_resource_templates()
async def _get_resource_template(
self, uri: str, version: VersionSpec | None = None
) -> ResourceTemplate | None:
"""Delegate to inner's get_resource_template (includes inner's transforms)."""
return await self._inner.get_resource_template(uri, version)
async def _list_prompts(self) -> Sequence[Prompt]:
"""Delegate to inner's list_prompts (includes inner's transforms)."""
return await self._inner.list_prompts()
async def _get_prompt(
self, name: str, version: VersionSpec | None = None
) -> Prompt | None:
"""Delegate to inner's get_prompt (includes inner's transforms)."""
return await self._inner.get_prompt(name, version)
async def get_tasks(self) -> Sequence[FastMCPComponent]:
"""Delegate to inner's get_tasks and apply wrapper's transforms."""
# Import here to avoid circular imports
from fastmcp.prompts.prompt import Prompt
from fastmcp.resources.resource import Resource
from fastmcp.resources.template import ResourceTemplate
from fastmcp.tools.tool import Tool
# Get tasks from inner (already has inner's transforms)
components = list(await self._inner.get_tasks())
# Apply this wrapper's transforms to the components
# We need to apply transforms per component type
tools = [c for c in components if isinstance(c, Tool)]
resources = [c for c in components if isinstance(c, Resource)]
templates = [c for c in components if isinstance(c, ResourceTemplate)]
prompts = [c for c in components if isinstance(c, Prompt)]
# Apply this wrapper's transforms sequentially
for transform in self.transforms:
tools = await transform.list_tools(tools)
resources = await transform.list_resources(resources)
templates = await transform.list_resource_templates(templates)
prompts = await transform.list_prompts(prompts)
return [
c
for c in [
*tools,
*resources,
*templates,
*prompts,
]
if c.task_config.supports_tasks()
]
# -------------------------------------------------------------------------
# Lifecycle - combine with inner
# -------------------------------------------------------------------------
@asynccontextmanager
async def lifespan(self) -> AsyncIterator[None]:
"""Combine lifespan with inner provider."""
async with self._inner.lifespan():
yield
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/server/providers/wrapped_provider.py",
"license": "Apache License 2.0",
"lines": 112,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/utilities/pagination.py | """Pagination utilities for MCP list operations."""
from __future__ import annotations
import base64
import binascii
import json
from collections.abc import Sequence
from dataclasses import dataclass
from typing import TypeVar
T = TypeVar("T")
@dataclass
class CursorState:
"""Internal representation of pagination cursor state.
The cursor encodes the offset into the result set. This is opaque to clients
per the MCP spec - they should not parse or modify cursors.
"""
offset: int
def encode(self) -> str:
"""Encode cursor state to an opaque string."""
data = json.dumps({"o": self.offset})
return base64.urlsafe_b64encode(data.encode()).decode()
@classmethod
def decode(cls, cursor: str) -> CursorState:
"""Decode cursor from an opaque string.
Raises:
ValueError: If the cursor is invalid or malformed.
"""
try:
data = json.loads(base64.urlsafe_b64decode(cursor.encode()).decode())
return cls(offset=data["o"])
except (
json.JSONDecodeError,
KeyError,
ValueError,
TypeError,
binascii.Error,
) as e:
raise ValueError(f"Invalid cursor: {cursor}") from e
def paginate_sequence(
items: Sequence[T],
cursor: str | None,
page_size: int,
) -> tuple[list[T], str | None]:
"""Paginate a sequence of items.
Args:
items: The full sequence to paginate.
cursor: Optional cursor from a previous request. None for first page.
page_size: Maximum number of items per page.
Returns:
Tuple of (page_items, next_cursor). next_cursor is None if no more pages.
Raises:
ValueError: If the cursor is invalid.
"""
offset = 0
if cursor:
state = CursorState.decode(cursor)
offset = state.offset
end = offset + page_size
page = list(items[offset:end])
next_cursor = None
if end < len(items):
next_cursor = CursorState(offset=end).encode()
return page, next_cursor
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/utilities/pagination.py",
"license": "Apache License 2.0",
"lines": 62,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
PrefectHQ/fastmcp:tests/server/test_pagination.py | """Tests for MCP pagination support."""
from __future__ import annotations
from unittest.mock import patch
import mcp.types
import pytest
from mcp.shared.exceptions import McpError
from fastmcp import Client, FastMCP
from fastmcp.utilities.pagination import CursorState, paginate_sequence
class TestCursorEncoding:
"""Tests for cursor encoding/decoding."""
def test_encode_decode_roundtrip(self) -> None:
"""Cursor should survive encode/decode roundtrip."""
state = CursorState(offset=100)
encoded = state.encode()
decoded = CursorState.decode(encoded)
assert decoded.offset == 100
def test_encode_produces_string(self) -> None:
"""Encoded cursor should be a string."""
state = CursorState(offset=50)
encoded = state.encode()
assert isinstance(encoded, str)
assert len(encoded) > 0
def test_decode_invalid_base64_raises(self) -> None:
"""Invalid base64 should raise ValueError."""
with pytest.raises(ValueError, match="Invalid cursor"):
CursorState.decode("not-valid-base64!!!")
def test_decode_invalid_json_raises(self) -> None:
"""Valid base64 but invalid JSON should raise ValueError."""
import base64
invalid = base64.urlsafe_b64encode(b"not json").decode()
with pytest.raises(ValueError, match="Invalid cursor"):
CursorState.decode(invalid)
def test_decode_missing_offset_raises(self) -> None:
"""JSON missing the offset key should raise ValueError."""
import base64
import json
invalid = base64.urlsafe_b64encode(json.dumps({"x": 1}).encode()).decode()
with pytest.raises(ValueError, match="Invalid cursor"):
CursorState.decode(invalid)
class TestPaginateSequence:
"""Tests for the paginate_sequence helper."""
def test_first_page_no_cursor(self) -> None:
"""First page should start from beginning."""
items = list(range(25))
page, cursor = paginate_sequence(items, None, 10)
assert page == list(range(10))
assert cursor is not None
def test_second_page_with_cursor(self) -> None:
"""Second page should continue from cursor."""
items = list(range(25))
_, cursor = paginate_sequence(items, None, 10)
page, next_cursor = paginate_sequence(items, cursor, 10)
assert page == list(range(10, 20))
assert next_cursor is not None
def test_last_page_returns_none_cursor(self) -> None:
"""Last page should return None cursor."""
items = list(range(25))
_, c1 = paginate_sequence(items, None, 10)
_, c2 = paginate_sequence(items, c1, 10)
page, next_cursor = paginate_sequence(items, c2, 10)
assert page == list(range(20, 25))
assert next_cursor is None
def test_empty_list(self) -> None:
"""Empty list should return empty page and no cursor."""
page, cursor = paginate_sequence([], None, 10)
assert page == []
assert cursor is None
def test_exact_page_size(self) -> None:
"""List exactly matching page size should return no cursor."""
items = list(range(10))
page, cursor = paginate_sequence(items, None, 10)
assert page == items
assert cursor is None
def test_smaller_than_page_size(self) -> None:
"""List smaller than page size should return all items."""
items = list(range(5))
page, cursor = paginate_sequence(items, None, 10)
assert page == items
assert cursor is None
def test_invalid_cursor_raises(self) -> None:
"""Invalid cursor should raise ValueError."""
with pytest.raises(ValueError, match="Invalid cursor"):
paginate_sequence([1, 2, 3], "invalid!", 10)
class TestServerPagination:
"""Integration tests for server pagination."""
async def test_tools_pagination_returns_all_tools(self) -> None:
"""Client should receive all tools across paginated requests."""
server = FastMCP(list_page_size=10)
for i in range(25):
@server.tool(name=f"tool_{i}")
def make_tool() -> str:
return "ok"
async with Client(server) as client:
tools = await client.list_tools()
assert len(tools) == 25
tool_names = {t.name for t in tools}
assert tool_names == {f"tool_{i}" for i in range(25)}
async def test_resources_pagination_returns_all_resources(self) -> None:
"""Client should receive all resources across paginated requests."""
server = FastMCP(list_page_size=10)
for i in range(25):
@server.resource(f"test://resource_{i}")
def make_resource() -> str:
return "data"
async with Client(server) as client:
resources = await client.list_resources()
assert len(resources) == 25
async def test_prompts_pagination_returns_all_prompts(self) -> None:
"""Client should receive all prompts across paginated requests."""
server = FastMCP(list_page_size=10)
for i in range(25):
@server.prompt(name=f"prompt_{i}")
def make_prompt() -> str:
return "text"
async with Client(server) as client:
prompts = await client.list_prompts()
assert len(prompts) == 25
async def test_manual_pagination(self) -> None:
"""Client can manually paginate using cursor."""
server = FastMCP(list_page_size=10)
for i in range(25):
@server.tool(name=f"tool_{i}")
def make_tool() -> str:
return "ok"
async with Client(server) as client:
# First page
result = await client.list_tools_mcp()
assert len(result.tools) == 10
assert result.nextCursor is not None
# Second page
result2 = await client.list_tools_mcp(cursor=result.nextCursor)
assert len(result2.tools) == 10
assert result2.nextCursor is not None
# Third (last) page
result3 = await client.list_tools_mcp(cursor=result2.nextCursor)
assert len(result3.tools) == 5
assert result3.nextCursor is None
async def test_invalid_cursor_returns_error(self) -> None:
"""Server should return MCP error for invalid cursor."""
server = FastMCP(list_page_size=10)
@server.tool
def my_tool() -> str:
return "ok"
async with Client(server) as client:
with pytest.raises(McpError) as exc:
await client.list_tools_mcp(cursor="invalid!")
assert exc.value.error.code == -32602
async def test_no_pagination_when_disabled(self) -> None:
"""Without list_page_size, all items returned at once."""
server = FastMCP() # No pagination
for i in range(25):
@server.tool(name=f"tool_{i}")
def make_tool() -> str:
return "ok"
async with Client(server) as client:
result = await client.list_tools_mcp()
assert len(result.tools) == 25
assert result.nextCursor is None
async def test_pagination_exact_page_boundary(self) -> None:
"""Test pagination at exact page boundaries."""
server = FastMCP(list_page_size=10)
for i in range(20): # Exactly 2 pages
@server.tool(name=f"tool_{i}")
def make_tool() -> str:
return "ok"
async with Client(server) as client:
# First page
result = await client.list_tools_mcp()
assert len(result.tools) == 10
assert result.nextCursor is not None
# Second (last) page
result2 = await client.list_tools_mcp(cursor=result.nextCursor)
assert len(result2.tools) == 10
assert result2.nextCursor is None
class TestPageSizeValidation:
"""Tests for list_page_size validation."""
def test_zero_page_size_raises(self) -> None:
"""Zero page size should raise ValueError."""
with pytest.raises(
ValueError, match="list_page_size must be a positive integer"
):
FastMCP(list_page_size=0)
def test_negative_page_size_raises(self) -> None:
"""Negative page size should raise ValueError."""
with pytest.raises(
ValueError, match="list_page_size must be a positive integer"
):
FastMCP(list_page_size=-1)
class TestPaginationCycleDetection:
"""Tests that auto-pagination terminates when the server returns cycling cursors."""
async def test_tools_constant_cursor_terminates(self) -> None:
"""list_tools should stop if the server always returns the same cursor."""
server = FastMCP()
@server.tool
def my_tool() -> str:
return "ok"
async with Client(server) as client:
original = client.list_tools_mcp
async def returning_constant_cursor(
*,
cursor: str | None = None,
) -> mcp.types.ListToolsResult:
result = await original(cursor=cursor)
result.nextCursor = "stuck"
return result
with patch.object(
client, "list_tools_mcp", side_effect=returning_constant_cursor
):
tools = await client.list_tools()
# Should get tools from first page + one duplicate (the retry before
# detecting the cycle), then stop.
assert len(tools) == 2
assert all(t.name == "my_tool" for t in tools)
async def test_prompts_constant_cursor_terminates(self) -> None:
"""list_prompts should stop if the server always returns the same cursor."""
server = FastMCP()
@server.prompt
def my_prompt() -> str:
return "text"
async with Client(server) as client:
original = client.list_prompts_mcp
async def returning_constant_cursor(
*,
cursor: str | None = None,
) -> mcp.types.ListPromptsResult:
result = await original(cursor=cursor)
result.nextCursor = "stuck"
return result
with patch.object(
client, "list_prompts_mcp", side_effect=returning_constant_cursor
):
prompts = await client.list_prompts()
assert len(prompts) == 2
assert all(p.name == "my_prompt" for p in prompts)
async def test_resources_constant_cursor_terminates(self) -> None:
"""list_resources should stop if the server always returns the same cursor."""
server = FastMCP()
@server.resource("test://r")
def my_resource() -> str:
return "data"
async with Client(server) as client:
original = client.list_resources_mcp
async def returning_constant_cursor(
*,
cursor: str | None = None,
) -> mcp.types.ListResourcesResult:
result = await original(cursor=cursor)
result.nextCursor = "stuck"
return result
with patch.object(
client, "list_resources_mcp", side_effect=returning_constant_cursor
):
resources = await client.list_resources()
assert len(resources) == 2
assert all(r.name == "my_resource" for r in resources)
async def test_resource_templates_constant_cursor_terminates(self) -> None:
"""list_resource_templates should stop if the server always returns the same cursor."""
server = FastMCP()
@server.resource("test://items/{item_id}")
def my_template(item_id: str) -> str:
return item_id
async with Client(server) as client:
original = client.list_resource_templates_mcp
async def returning_constant_cursor(
*,
cursor: str | None = None,
) -> mcp.types.ListResourceTemplatesResult:
result = await original(cursor=cursor)
result.nextCursor = "stuck"
return result
with patch.object(
client,
"list_resource_templates_mcp",
side_effect=returning_constant_cursor,
):
templates = await client.list_resource_templates()
assert len(templates) == 2
async def test_cycling_cursors_terminates(self) -> None:
"""list_tools should stop if the server cycles through a set of cursors."""
server = FastMCP()
@server.tool
def my_tool() -> str:
return "ok"
async with Client(server) as client:
call_count = 0
original = client.list_tools_mcp
async def returning_cycling_cursor(
*,
cursor: str | None = None,
) -> mcp.types.ListToolsResult:
nonlocal call_count
result = await original(cursor=cursor)
# Cycle through A -> B -> C -> A
cursors = ["A", "B", "C"]
result.nextCursor = cursors[call_count % 3]
call_count += 1
return result
with patch.object(
client, "list_tools_mcp", side_effect=returning_cycling_cursor
):
tools = await client.list_tools()
# A, B, C seen, then A is a duplicate → 4 calls total
assert call_count == 4
assert len(tools) == 4
async def test_empty_string_cursor_terminates(self) -> None:
"""list_tools should stop if the server returns an empty string cursor."""
server = FastMCP()
@server.tool
def my_tool() -> str:
return "ok"
async with Client(server) as client:
original = client.list_tools_mcp
async def returning_empty_cursor(
*,
cursor: str | None = None,
) -> mcp.types.ListToolsResult:
result = await original(cursor=cursor)
result.nextCursor = ""
return result
with patch.object(
client, "list_tools_mcp", side_effect=returning_empty_cursor
):
tools = await client.list_tools()
assert len(tools) == 1
assert tools[0].name == "my_tool"
async def test_tools_raises_on_auto_pagination_limit(self) -> None:
"""list_tools should raise RuntimeError after exceeding max_pages."""
server = FastMCP()
@server.tool
def my_tool() -> str:
return "ok"
async with Client(server) as client:
original = client.list_tools_mcp
call_count = 0
async def returning_unique_cursor(
*,
cursor: str | None = None,
) -> mcp.types.ListToolsResult:
nonlocal call_count
result = await original(cursor=cursor)
call_count += 1
result.nextCursor = f"cursor-{call_count}"
return result
with (
patch.object(
client, "list_tools_mcp", side_effect=returning_unique_cursor
),
pytest.raises(RuntimeError, match="auto-pagination limit"),
):
await client.list_tools(max_pages=5)
async def test_resources_raises_on_auto_pagination_limit(self) -> None:
"""list_resources should raise RuntimeError after exceeding max_pages."""
server = FastMCP()
@server.resource("test://r")
def my_resource() -> str:
return "data"
async with Client(server) as client:
original = client.list_resources_mcp
call_count = 0
async def returning_unique_cursor(
*,
cursor: str | None = None,
) -> mcp.types.ListResourcesResult:
nonlocal call_count
result = await original(cursor=cursor)
call_count += 1
result.nextCursor = f"cursor-{call_count}"
return result
with (
patch.object(
client, "list_resources_mcp", side_effect=returning_unique_cursor
),
pytest.raises(RuntimeError, match="auto-pagination limit"),
):
await client.list_resources(max_pages=5)
async def test_prompts_raises_on_auto_pagination_limit(self) -> None:
"""list_prompts should raise RuntimeError after exceeding max_pages."""
server = FastMCP()
@server.prompt
def my_prompt() -> str:
return "text"
async with Client(server) as client:
original = client.list_prompts_mcp
call_count = 0
async def returning_unique_cursor(
*,
cursor: str | None = None,
) -> mcp.types.ListPromptsResult:
nonlocal call_count
result = await original(cursor=cursor)
call_count += 1
result.nextCursor = f"cursor-{call_count}"
return result
with (
patch.object(
client, "list_prompts_mcp", side_effect=returning_unique_cursor
),
pytest.raises(RuntimeError, match="auto-pagination limit"),
):
await client.list_prompts(max_pages=5)
async def test_normal_pagination_unaffected(self) -> None:
"""Cycle detection should not interfere with normal pagination."""
server = FastMCP(list_page_size=10)
for i in range(25):
@server.tool(name=f"tool_{i}")
def make_tool() -> str:
return "ok"
async with Client(server) as client:
tools = await client.list_tools()
assert len(tools) == 25
assert len({t.name for t in tools}) == 25
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/test_pagination.py",
"license": "Apache License 2.0",
"lines": 411,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:examples/versioning/client_version_selection.py | """
Client-Side Version Selection
Discover available versions via metadata and request specific versions
when calling tools, prompts, or resources.
Run: uv run python examples/versioning/client_version_selection.py
"""
import asyncio
from rich import print
from fastmcp import Client, FastMCP
from fastmcp.exceptions import ToolError
mcp = FastMCP("Payment API")
@mcp.tool(version="1.0")
def charge(amount: int, currency: str = "USD") -> dict:
"""Charge a payment (v1.0 - basic)."""
return {"status": "charged", "amount": amount, "currency": currency}
@mcp.tool(version="1.1")
def charge( # noqa: F811
amount: int, currency: str = "USD", idempotency_key: str | None = None
) -> dict:
"""Charge a payment (v1.1 - added idempotency)."""
return {"status": "charged", "amount": amount, "idempotency_key": idempotency_key}
@mcp.tool(version="2.0")
def charge( # noqa: F811
amount: int,
currency: str = "USD",
idempotency_key: str | None = None,
metadata: dict | None = None,
) -> dict:
"""Charge a payment (v2.0 - added metadata)."""
return {"status": "charged", "amount": amount, "metadata": metadata or {}}
async def main():
async with Client(mcp) as client:
# Discover versions via metadata
tools = await client.list_tools()
tool = tools[0]
meta = tool.meta.get("fastmcp", {})
print(f"[bold]{tool.name}[/]")
print(f" Current version: [green]{meta.get('version')}[/]")
print(f" All versions: {meta.get('versions')}")
# Call specific versions
print("\n[bold]Calling specific versions:[/]")
r1 = await client.call_tool("charge", {"amount": 100}, version="1.0")
print(f" v1.0: {r1.data}")
r1_1 = await client.call_tool(
"charge", {"amount": 100, "idempotency_key": "abc"}, version="1.1"
)
print(f" v1.1: {r1_1.data}")
r2 = await client.call_tool(
"charge", {"amount": 100, "metadata": {"order": "xyz"}}, version="2.0"
)
print(f" v2.0: {r2.data}")
# Handle missing versions
print("\n[bold]Missing version:[/]")
try:
await client.call_tool("charge", {"amount": 100}, version="99.0")
except ToolError as e:
print(f" [red]ToolError:[/] {e}")
if __name__ == "__main__":
asyncio.run(main())
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "examples/versioning/client_version_selection.py",
"license": "Apache License 2.0",
"lines": 59,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
PrefectHQ/fastmcp:examples/versioning/version_filters.py | """
Version Filters for API Surfaces
Use VersionFilter to create distinct API surfaces from shared components.
This lets you serve v1, v2, v3 APIs from a single codebase.
Run: uv run python examples/versioning/version_filters.py
"""
import asyncio
from rich import print
from rich.table import Table
from fastmcp import Client, FastMCP
from fastmcp.server.providers import LocalProvider
from fastmcp.server.transforms import VersionFilter
# Shared component pool with all versions
components = LocalProvider()
@components.tool(version="1.0")
def process(data: str) -> str:
"""Process data (v1 - uppercase only)."""
return data.upper()
@components.tool(version="2.0")
def process(data: str, mode: str = "upper") -> str: # noqa: F811
"""Process data (v2 - with mode selection)."""
return data.lower() if mode == "lower" else data.upper()
@components.tool(version="3.0")
def process(data: str, mode: str = "upper", repeat: int = 1) -> str: # noqa: F811
"""Process data (v3 - with repeat)."""
result = data.lower() if mode == "lower" else data.upper()
return result * repeat
# Unversioned components pass through all filters
@components.tool()
def health() -> str:
"""Health check (always available)."""
return "ok"
# Create filtered API surfaces
api_v1 = FastMCP("API v1", providers=[components])
api_v1.add_transform(VersionFilter(version_lt="2.0"))
api_v2 = FastMCP("API v2", providers=[components])
api_v2.add_transform(VersionFilter(version_gte="2.0", version_lt="3.0"))
api_v3 = FastMCP("API v3", providers=[components])
api_v3.add_transform(VersionFilter(version_gte="3.0"))
async def show_surface(name: str, server: FastMCP):
"""Show what's visible through a filtered server."""
async with Client(server) as client:
tools = await client.list_tools()
table = Table(title=name)
table.add_column("Tool")
table.add_column("Version", style="green")
for tool in tools:
meta = tool.meta.get("fastmcp", {}) if tool.meta else {}
table.add_row(tool.name, meta.get("version", "(unversioned)"))
print(table)
async def main():
# Show what each API surface exposes
await show_surface("API v1 (version_lt='2.0')", api_v1)
await show_surface("API v2 (version_gte='2.0', version_lt='3.0')", api_v2)
await show_surface("API v3 (version_gte='3.0')", api_v3)
# Same tool name, different behavior per API
print("\n[bold]Same call through different APIs:[/]")
for name, server in [("v1", api_v1), ("v2", api_v2), ("v3", api_v3)]:
async with Client(server) as client:
result = await client.call_tool("process", {"data": "Hello"})
print(f" API {name}: process('Hello') -> '{result.data}'")
if __name__ == "__main__":
asyncio.run(main())
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "examples/versioning/version_filters.py",
"license": "Apache License 2.0",
"lines": 63,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
PrefectHQ/fastmcp:examples/versioning/versioned_components.py | """
Creating Versioned Components
Register multiple versions of the same tool, resource, or prompt.
Clients see the highest version by default but can request specific versions.
Run: uv run python examples/versioning/versioned_components.py
"""
import asyncio
from rich import print
from rich.table import Table
from fastmcp import Client, FastMCP
mcp = FastMCP("Versioned API")
# --- Versioned Tools ---
# Same name, different versions with different signatures
@mcp.tool(version="1.0")
def calculate(x: int, y: int) -> int:
"""Add two numbers (v1.0)."""
return x + y
@mcp.tool(version="2.0")
def calculate(x: int, y: int, z: int = 0) -> int: # noqa: F811
"""Add two or three numbers (v2.0)."""
return x + y + z
# --- Versioned Resources ---
# Same URI, different content per version
@mcp.resource("config://app", version="1.0")
def config_v1() -> str:
return '{"format": "legacy"}'
@mcp.resource("config://app", version="2.0")
def config_v2() -> str:
return '{"format": "modern", "telemetry": true}'
# --- Versioned Prompts ---
# Same prompt, different templates per version
@mcp.prompt(version="1.0")
def summarize(text: str) -> str:
return f"Summarize: {text}"
@mcp.prompt(version="2.0")
def summarize(text: str, style: str = "concise") -> str: # noqa: F811
return f"Summarize in a {style} style: {text}"
async def main():
async with Client(mcp) as client:
# List components - clients see highest version + all available versions
tools = await client.list_tools()
table = Table(title="Components (as seen by clients)")
table.add_column("Type")
table.add_column("Name")
table.add_column("Version", style="green")
table.add_column("All Versions", style="dim")
for tool in tools:
meta = tool.meta.get("fastmcp", {}) if tool.meta else {}
table.add_row(
"Tool",
tool.name,
meta.get("version"),
", ".join(meta.get("versions", [])),
)
print(table)
# Call specific versions
print("\n[bold]Calling specific versions:[/]")
r_default = await client.call_tool("calculate", {"x": 5, "y": 3})
r_v1 = await client.call_tool("calculate", {"x": 5, "y": 3}, version="1.0")
r_v2 = await client.call_tool(
"calculate", {"x": 5, "y": 3, "z": 2}, version="2.0"
)
print(f" calculate(5, 3) -> {r_default.data} (default: highest)")
print(f" calculate(5, 3) v1.0 -> {r_v1.data}")
print(f" calculate(5, 3, 2) v2.0 -> {r_v2.data}")
if __name__ == "__main__":
asyncio.run(main())
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "examples/versioning/versioned_components.py",
"license": "Apache License 2.0",
"lines": 67,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
PrefectHQ/fastmcp:src/fastmcp/server/transforms/version_filter.py | """Version filter transform for filtering components by version range."""
from __future__ import annotations
from collections.abc import Sequence
from typing import TYPE_CHECKING
from fastmcp.server.transforms import (
GetPromptNext,
GetResourceNext,
GetResourceTemplateNext,
GetToolNext,
Transform,
)
from fastmcp.utilities.versions import VersionSpec
if TYPE_CHECKING:
from fastmcp.prompts.prompt import Prompt
from fastmcp.resources.resource import Resource
from fastmcp.resources.template import ResourceTemplate
from fastmcp.tools.tool import Tool
class VersionFilter(Transform):
"""Filters components by version range.
When applied to a provider or server, components within the version range
are visible, and unversioned components are included by default. Within
that filtered set, the highest version of each component is exposed to
clients (standard deduplication behavior). Set
``include_unversioned=False`` to exclude unversioned components.
Parameters mirror comparison operators for clarity:
# Versions < 3.0 (v1 and v2)
server.add_transform(VersionFilter(version_lt="3.0"))
# Versions >= 2.0 and < 3.0 (only v2.x)
server.add_transform(VersionFilter(version_gte="2.0", version_lt="3.0"))
Works with any version string - PEP 440 (1.0, 2.0) or dates (2025-01-01).
Args:
version_gte: Versions >= this value pass through.
version_lt: Versions < this value pass through.
include_unversioned: Whether unversioned components (``version=None``)
should pass through the filter. Defaults to True.
"""
def __init__(
self,
*,
version_gte: str | None = None,
version_lt: str | None = None,
include_unversioned: bool = True,
) -> None:
if version_gte is None and version_lt is None:
raise ValueError(
"At least one of version_gte or version_lt must be specified"
)
self.version_gte = version_gte
self.version_lt = version_lt
self.include_unversioned = include_unversioned
self._spec = VersionSpec(gte=version_gte, lt=version_lt)
def __repr__(self) -> str:
parts = []
if self.version_gte:
parts.append(f"version_gte={self.version_gte!r}")
if self.version_lt:
parts.append(f"version_lt={self.version_lt!r}")
if not self.include_unversioned:
parts.append("include_unversioned=False")
return f"VersionFilter({', '.join(parts)})"
# -------------------------------------------------------------------------
# Tools
# -------------------------------------------------------------------------
async def list_tools(self, tools: Sequence[Tool]) -> Sequence[Tool]:
return [
t
for t in tools
if self._spec.matches(t.version, match_none=self.include_unversioned)
]
async def get_tool(
self, name: str, call_next: GetToolNext, *, version: VersionSpec | None = None
) -> Tool | None:
return await call_next(name, version=self._spec.intersect(version))
# -------------------------------------------------------------------------
# Resources
# -------------------------------------------------------------------------
async def list_resources(self, resources: Sequence[Resource]) -> Sequence[Resource]:
return [
r
for r in resources
if self._spec.matches(r.version, match_none=self.include_unversioned)
]
async def get_resource(
self,
uri: str,
call_next: GetResourceNext,
*,
version: VersionSpec | None = None,
) -> Resource | None:
return await call_next(uri, version=self._spec.intersect(version))
# -------------------------------------------------------------------------
# Resource Templates
# -------------------------------------------------------------------------
async def list_resource_templates(
self, templates: Sequence[ResourceTemplate]
) -> Sequence[ResourceTemplate]:
return [
t
for t in templates
if self._spec.matches(t.version, match_none=self.include_unversioned)
]
async def get_resource_template(
self,
uri: str,
call_next: GetResourceTemplateNext,
*,
version: VersionSpec | None = None,
) -> ResourceTemplate | None:
return await call_next(uri, version=self._spec.intersect(version))
# -------------------------------------------------------------------------
# Prompts
# -------------------------------------------------------------------------
async def list_prompts(self, prompts: Sequence[Prompt]) -> Sequence[Prompt]:
return [
p
for p in prompts
if self._spec.matches(p.version, match_none=self.include_unversioned)
]
async def get_prompt(
self, name: str, call_next: GetPromptNext, *, version: VersionSpec | None = None
) -> Prompt | None:
return await call_next(name, version=self._spec.intersect(version))
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/server/transforms/version_filter.py",
"license": "Apache License 2.0",
"lines": 122,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/utilities/versions.py | """Version comparison utilities for component versioning.
This module provides utilities for comparing component versions. Versions are
strings that are first attempted to be parsed as PEP 440 versions (using the
`packaging` library), falling back to lexicographic string comparison.
Examples:
- "1", "2", "10" → parsed as PEP 440, compared semantically (1 < 2 < 10)
- "1.0", "2.0" → parsed as PEP 440
- "v1.0" → 'v' prefix stripped, parsed as "1.0"
- "2025-01-15" → not valid PEP 440, compared as strings
- None → sorts lowest (unversioned components)
"""
from __future__ import annotations
from collections.abc import Callable, Sequence
from dataclasses import dataclass
from functools import total_ordering
from typing import TYPE_CHECKING, Any, TypeVar, cast
from packaging.version import InvalidVersion, Version
if TYPE_CHECKING:
from fastmcp.utilities.components import FastMCPComponent
C = TypeVar("C", bound=Any)
@dataclass
class VersionSpec:
"""Specification for filtering components by version.
Used by transforms and providers to filter components to a specific
version or version range. Unversioned components (version=None) always
match any spec.
Args:
gte: If set, only versions >= this value match.
lt: If set, only versions < this value match.
eq: If set, only this exact version matches (gte/lt ignored).
"""
gte: str | None = None
lt: str | None = None
eq: str | None = None
def matches(self, version: str | None, *, match_none: bool = True) -> bool:
"""Check if a version matches this spec.
Args:
version: The version to check, or None for unversioned.
match_none: Whether unversioned (None) components match. Defaults to True
for backward compatibility with retrieval operations. Set to False
when filtering (e.g., enable/disable) to exclude unversioned components
from version-specific rules.
Returns:
True if the version matches the spec.
"""
if version is None:
return match_none
if self.eq is not None:
return version == self.eq
key = parse_version_key(version)
if self.gte is not None:
gte_key = parse_version_key(self.gte)
if key < gte_key:
return False
if self.lt is not None:
lt_key = parse_version_key(self.lt)
if not key < lt_key:
return False
return True
def intersect(self, other: VersionSpec | None) -> VersionSpec:
"""Return a spec that satisfies both this spec and other.
Used by transforms to combine caller constraints with filter constraints.
For example, if a VersionFilter has lt="3.0" and caller requests eq="1.0",
the intersection validates "1.0" is in range and returns the exact spec.
Args:
other: Another spec to intersect with, or None.
Returns:
A VersionSpec that matches only versions satisfying both specs.
"""
if other is None:
return self
if self.eq is not None:
# This spec wants exact - validate against other's range
if other.matches(self.eq):
return self
return VersionSpec(eq="__impossible__")
if other.eq is not None:
# Other wants exact - validate against our range
if self.matches(other.eq):
return other
return VersionSpec(eq="__impossible__")
# Both are ranges - take tighter bounds
return VersionSpec(
gte=max_version(self.gte, other.gte),
lt=min_version(self.lt, other.lt),
)
@total_ordering
class VersionKey:
"""A comparable version key that handles None, PEP 440 versions, and strings.
Comparison order:
1. None (unversioned) sorts lowest
2. PEP 440 versions sort by semantic version order
3. Invalid versions (strings) sort lexicographically
4. When comparing PEP 440 vs string, PEP 440 comes first
"""
__slots__ = ("_is_none", "_is_pep440", "_parsed", "_raw")
def __init__(self, version: str | None) -> None:
self._raw = version
self._is_none = version is None
self._is_pep440 = False
self._parsed: Version | str | None = None
if version is not None:
# Strip leading 'v' if present (common convention like "v1.0")
normalized = version.lstrip("v") if version.startswith("v") else version
try:
self._parsed = Version(normalized)
self._is_pep440 = True
except InvalidVersion:
# Fall back to string comparison for non-PEP 440 versions
self._parsed = version
def __eq__(self, other: object) -> bool:
if not isinstance(other, VersionKey):
return NotImplemented
if self._is_none and other._is_none:
return True
if self._is_none != other._is_none:
return False
# Both are not None
if self._is_pep440 and other._is_pep440:
return self._parsed == other._parsed
if not self._is_pep440 and not other._is_pep440:
return self._parsed == other._parsed
# One is PEP 440, other is string - never equal
return False
def __lt__(self, other: object) -> bool:
if not isinstance(other, VersionKey):
return NotImplemented
# None sorts lowest
if self._is_none and other._is_none:
return False # Equal
if self._is_none:
return True # None < anything
if other._is_none:
return False # anything > None
# Both are not None
if self._is_pep440 and other._is_pep440:
# Both PEP 440 - compare normally
assert isinstance(self._parsed, Version)
assert isinstance(other._parsed, Version)
return self._parsed < other._parsed
if not self._is_pep440 and not other._is_pep440:
# Both strings - lexicographic
assert isinstance(self._parsed, str)
assert isinstance(other._parsed, str)
return self._parsed < other._parsed
# Mixed: PEP 440 sorts before strings
# (arbitrary but consistent choice)
return self._is_pep440
def __repr__(self) -> str:
return f"VersionKey({self._raw!r})"
def parse_version_key(version: str | None) -> VersionKey:
"""Parse a version string into a sortable key.
Args:
version: The version string, or None for unversioned.
Returns:
A VersionKey suitable for sorting.
"""
return VersionKey(version)
def version_sort_key(component: FastMCPComponent) -> VersionKey:
"""Get a sort key for a component based on its version.
Use with sorted() or max() to order components by version.
Args:
component: The component to get a sort key for.
Returns:
A sortable VersionKey.
Example:
```python
tools = [tool_v1, tool_v2, tool_unversioned]
highest = max(tools, key=version_sort_key) # Returns tool_v2
```
"""
return parse_version_key(component.version)
def compare_versions(a: str | None, b: str | None) -> int:
"""Compare two version strings.
Args:
a: First version string (or None).
b: Second version string (or None).
Returns:
-1 if a < b, 0 if a == b, 1 if a > b.
Example:
```python
compare_versions("1.0", "2.0") # Returns -1
compare_versions("2.0", "1.0") # Returns 1
compare_versions(None, "1.0") # Returns -1 (None < any version)
```
"""
key_a = parse_version_key(a)
key_b = parse_version_key(b)
return (key_a > key_b) - (key_a < key_b)
def is_version_greater(a: str | None, b: str | None) -> bool:
"""Check if version a is greater than version b.
Args:
a: First version string (or None).
b: Second version string (or None).
Returns:
True if a > b, False otherwise.
"""
return compare_versions(a, b) > 0
def max_version(a: str | None, b: str | None) -> str | None:
"""Return the greater of two versions.
Args:
a: First version string (or None).
b: Second version string (or None).
Returns:
The greater version, or None if both are None.
"""
if a is None:
return b
if b is None:
return a
return a if compare_versions(a, b) >= 0 else b
def min_version(a: str | None, b: str | None) -> str | None:
"""Return the lesser of two versions.
Args:
a: First version string (or None).
b: Second version string (or None).
Returns:
The lesser version, or None if both are None.
"""
if a is None:
return b
if b is None:
return a
return a if compare_versions(a, b) <= 0 else b
def dedupe_with_versions(
components: Sequence[C],
key_fn: Callable[[C], str],
) -> list[C]:
"""Deduplicate components by key, keeping highest version.
Groups components by key, selects the highest version from each group,
and injects available versions into meta if any component is versioned.
Args:
components: Sequence of components to deduplicate.
key_fn: Function to extract the grouping key from a component.
Returns:
Deduplicated list with versions injected into meta.
"""
by_key: dict[str, list[C]] = {}
for c in components:
by_key.setdefault(key_fn(c), []).append(c)
result: list[C] = []
for versions in by_key.values():
highest: C = cast(C, max(versions, key=version_sort_key))
if any(c.version is not None for c in versions):
all_versions = sorted(
[c.version for c in versions if c.version is not None],
key=parse_version_key,
reverse=True,
)
meta = highest.meta or {}
highest = highest.model_copy(
update={
"meta": {
**meta,
"fastmcp": {
**meta.get("fastmcp", {}),
"versions": all_versions,
},
}
}
)
result.append(highest)
return result
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/utilities/versions.py",
"license": "Apache License 2.0",
"lines": 263,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
PrefectHQ/fastmcp:examples/persistent_state/client.py | """Client for testing persistent state.
Run the server first:
uv run python examples/persistent_state/server.py
Then run this client:
uv run python examples/persistent_state/client.py
"""
import asyncio
from rich.console import Console
from fastmcp import Client
from fastmcp.client.transports import StreamableHttpTransport
URL = "http://127.0.0.1:8000/mcp"
console = Console()
async def main() -> None:
console.print()
console.print("[dim italic]Each line below is a separate tool call[/dim italic]")
console.print()
# --- Alice's session ---
console.print("[dim]Alice connects[/dim]")
transport1 = StreamableHttpTransport(url=URL)
async with Client(transport=transport1) as alice:
result = await alice.call_tool("list_session_info", {})
console.print(f" session [cyan]{result.data['session_id'][:8]}[/cyan]")
await alice.call_tool("set_value", {"key": "user", "value": "Alice"})
console.print(" set [white]user[/white] = [green]Alice[/green]")
await alice.call_tool("set_value", {"key": "secret", "value": "alice-password"})
console.print(" set [white]secret[/white] = [green]alice-password[/green]")
result = await alice.call_tool("get_value", {"key": "user"})
console.print(" get [white]user[/white] → [green]Alice[/green]")
result = await alice.call_tool("get_value", {"key": "secret"})
console.print(" get [white]secret[/white] → [green]alice-password[/green]")
console.print()
# --- Bob's session ---
console.print("[dim]Bob connects (different session)[/dim]")
transport2 = StreamableHttpTransport(url=URL)
async with Client(transport=transport2) as bob:
result = await bob.call_tool("list_session_info", {})
console.print(f" session [cyan]{result.data['session_id'][:8]}[/cyan]")
await bob.call_tool("get_value", {"key": "user"})
console.print(" get [white]user[/white] → [dim]not found[/dim]")
await bob.call_tool("get_value", {"key": "secret"})
console.print(" get [white]secret[/white] → [dim]not found[/dim]")
await bob.call_tool("set_value", {"key": "user", "value": "Bob"})
console.print(" set [white]user[/white] = [green]Bob[/green]")
await bob.call_tool("get_value", {"key": "user"})
console.print(" get [white]user[/white] → [green]Bob[/green]")
console.print()
# --- Alice reconnects ---
console.print("[dim]Alice reconnects (new session)[/dim]")
transport3 = StreamableHttpTransport(url=URL)
async with Client(transport=transport3) as alice_again:
result = await alice_again.call_tool("list_session_info", {})
console.print(f" session [cyan]{result.data['session_id'][:8]}[/cyan]")
await alice_again.call_tool("get_value", {"key": "user"})
console.print(" get [white]user[/white] → [dim]not found[/dim]")
console.print()
if __name__ == "__main__":
asyncio.run(main())
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "examples/persistent_state/client.py",
"license": "Apache License 2.0",
"lines": 57,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
PrefectHQ/fastmcp:examples/persistent_state/client_stdio.py | """Client for testing persistent state over STDIO.
Run directly:
uv run python examples/persistent_state/client_stdio.py
"""
import asyncio
import sys
from pathlib import Path
from rich.console import Console
from fastmcp import Client, FastMCP
# Add parent directory to path for importing the server module
examples_dir: Path = Path(__file__).parent.parent.parent
if str(examples_dir) not in sys.path:
sys.path.insert(0, str(examples_dir))
import examples.persistent_state.server as server_module # noqa: E402
server: FastMCP = server_module.server
console: Console = Console()
async def main() -> None:
console.print()
console.print("[dim italic]Each line below is a separate tool call[/dim italic]")
console.print()
# --- Alice's session ---
console.print("[dim]Alice connects[/dim]")
async with Client(server) as alice:
result = await alice.call_tool("list_session_info", {})
console.print(f" session [cyan]{result.data['session_id'][:8]}[/cyan]")
await alice.call_tool("set_value", {"key": "user", "value": "Alice"})
console.print(" set [white]user[/white] = [green]Alice[/green]")
await alice.call_tool("set_value", {"key": "secret", "value": "alice-password"})
console.print(" set [white]secret[/white] = [green]alice-password[/green]")
await alice.call_tool("get_value", {"key": "user"})
console.print(" get [white]user[/white] → [green]Alice[/green]")
await alice.call_tool("get_value", {"key": "secret"})
console.print(" get [white]secret[/white] → [green]alice-password[/green]")
console.print()
# --- Bob's session ---
console.print("[dim]Bob connects (different session)[/dim]")
async with Client(server) as bob:
result = await bob.call_tool("list_session_info", {})
console.print(f" session [cyan]{result.data['session_id'][:8]}[/cyan]")
await bob.call_tool("get_value", {"key": "user"})
console.print(" get [white]user[/white] → [dim]not found[/dim]")
await bob.call_tool("get_value", {"key": "secret"})
console.print(" get [white]secret[/white] → [dim]not found[/dim]")
await bob.call_tool("set_value", {"key": "user", "value": "Bob"})
console.print(" set [white]user[/white] = [green]Bob[/green]")
await bob.call_tool("get_value", {"key": "user"})
console.print(" get [white]user[/white] → [green]Bob[/green]")
console.print()
# --- Alice reconnects ---
console.print("[dim]Alice reconnects (new session)[/dim]")
async with Client(server) as alice_again:
result = await alice_again.call_tool("list_session_info", {})
console.print(f" session [cyan]{result.data['session_id'][:8]}[/cyan]")
await alice_again.call_tool("get_value", {"key": "user"})
console.print(" get [white]user[/white] → [dim]not found[/dim]")
console.print()
if __name__ == "__main__":
asyncio.run(main())
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "examples/persistent_state/client_stdio.py",
"license": "Apache License 2.0",
"lines": 58,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
PrefectHQ/fastmcp:examples/persistent_state/server.py | """Example: Persistent session-scoped state.
This demonstrates using Context.get_state() and set_state() to store
data that persists across tool calls within the same MCP session.
Run with:
uv run python examples/persistent_state/server.py
"""
from fastmcp import FastMCP
from fastmcp.server.context import Context
server = FastMCP("StateExample")
@server.tool
async def set_value(key: str, value: str, ctx: Context) -> str:
"""Store a value in session state."""
await ctx.set_state(key, value)
return f"Stored '{key}' = '{value}'"
@server.tool
async def get_value(key: str, ctx: Context) -> str:
"""Retrieve a value from session state."""
value = await ctx.get_state(key)
if value is None:
return f"Key '{key}' not found"
return f"'{key}' = '{value}'"
@server.tool
async def list_session_info(ctx: Context) -> dict[str, str | None]:
"""Get information about the current session."""
return {
"session_id": ctx.session_id,
"transport": ctx.transport,
}
if __name__ == "__main__":
server.run(transport="streamable-http")
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "examples/persistent_state/server.py",
"license": "Apache License 2.0",
"lines": 30,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
PrefectHQ/fastmcp:examples/diagnostics/client_with_tracing.py | #!/usr/bin/env python
"""Client script to exercise all diagnostics server components with tracing.
Usage:
# First, start the diagnostics server with tracing in one terminal:
uv run examples/run_with_tracing.py examples/diagnostics/server.py --transport sse --port 8001
# Then run this client in another terminal:
uv run examples/diagnostics/client_with_tracing.py
# View traces in otel-desktop-viewer (http://localhost:8000):
otel-desktop-viewer
This script exercises all 8 components:
- 4 successful: ping, diag://status, diag://echo/{message}, greet prompt
- 4 error: fail_tool, diag://error, diag://error/{code}, fail prompt
"""
from __future__ import annotations
import asyncio
import os
# Configure OTEL SDK before importing fastmcp
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
def setup_tracing():
"""Set up OpenTelemetry tracing with OTLP export."""
endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4317")
service_name = os.environ.get("OTEL_SERVICE_NAME", "fastmcp-diagnostics-client")
resource = Resource.create({"service.name": service_name})
provider = TracerProvider(resource=resource)
exporter = OTLPSpanExporter(endpoint=endpoint, insecure=True)
provider.add_span_processor(BatchSpanProcessor(exporter))
trace.set_tracer_provider(provider)
print(f"Tracing enabled: OTLP {endpoint}")
print(f"Service: {service_name}")
print("View traces: otel-desktop-viewer (http://localhost:8000)\n")
async def main():
setup_tracing()
from fastmcp import Client
server_url = os.environ.get("DIAGNOSTICS_SERVER_URL", "http://localhost:8001/sse")
print(f"Connecting to: {server_url}\n")
async with Client(server_url) as client:
# List all available components
tools = await client.list_tools()
resources = await client.list_resources()
prompts = await client.list_prompts()
print(f"Found {len(tools)} tools: {[t.name for t in tools]}")
print(f"Found {len(resources)} resources: {[r.uri for r in resources]}")
print(f"Found {len(prompts)} prompts: {[p.name for p in prompts]}\n")
# === SUCCESSFUL OPERATIONS ===
print("=" * 60)
print("SUCCESSFUL OPERATIONS")
print("=" * 60)
# Local successful components
print("\n--- Local Tools ---")
result = await client.call_tool("ping", {})
print(f"ping: {result}")
print("\n--- Local Resources ---")
result = await client.read_resource("diag://status")
print(f"diag://status: {result}")
result = await client.read_resource("diag://echo/hello-world")
print(f"diag://echo/hello-world: {result}")
print("\n--- Local Prompts ---")
result = await client.get_prompt("greet", {"name": "Diagnostics"})
print(
f"greet: {result.messages[0].content.text if result.messages else result}"
)
# Proxied components from echo server
print("\n--- Proxied Tools ---")
try:
result = await client.call_tool(
"proxied_echo_tool", {"text": "proxied test"}
)
print(f"proxied_echo_tool: {result}")
except Exception as e:
print(f"proxied_echo_tool: ERROR - {e}")
print("\n--- Proxied Resources ---")
try:
# Resource: echo://static -> echo://proxied/static
result = await client.read_resource("echo://proxied/static")
print(f"echo://proxied/static: {result}")
except Exception as e:
print(f"echo://proxied/static: ERROR - {e}")
try:
# Template: echo://{text} -> echo://proxied/{text}
result = await client.read_resource("echo://proxied/test-message")
print(f"echo://proxied/test-message: {result}")
except Exception as e:
print(f"echo://proxied/test-message: ERROR - {e}")
print("\n--- Proxied Prompts ---")
try:
result = await client.get_prompt("proxied_echo", {"text": "proxied prompt"})
print(
f"proxied_echo: {result.messages[0].content.text if result.messages else result}"
)
except Exception as e:
print(f"proxied_echo: ERROR - {e}")
# === ERROR OPERATIONS ===
print("\n" + "=" * 60)
print("ERROR OPERATIONS (expected to fail)")
print("=" * 60)
print("\n--- Error Tools ---")
try:
await client.call_tool("fail_tool", {})
print("fail_tool: UNEXPECTED SUCCESS")
except Exception as e:
print(f"fail_tool: {type(e).__name__} - {e}")
print("\n--- Error Resources ---")
try:
await client.read_resource("diag://error")
print("diag://error: UNEXPECTED SUCCESS")
except Exception as e:
print(f"diag://error: {type(e).__name__} - {e}")
try:
await client.read_resource("diag://error/500")
print("diag://error/500: UNEXPECTED SUCCESS")
except Exception as e:
print(f"diag://error/500: {type(e).__name__} - {e}")
print("\n--- Error Prompts ---")
try:
await client.get_prompt("fail", {})
print("fail: UNEXPECTED SUCCESS")
except Exception as e:
print(f"fail: {type(e).__name__} - {e}")
print("\n" + "=" * 60)
print("DONE - Check otel-desktop-viewer for traces")
print("=" * 60)
if __name__ == "__main__":
asyncio.run(main())
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "examples/diagnostics/client_with_tracing.py",
"license": "Apache License 2.0",
"lines": 127,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:examples/diagnostics/server.py | """FastMCP Diagnostics Server - for testing tracing, errors, and observability."""
import asyncio
import os
import subprocess
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from pathlib import Path
import httpx
from fastmcp import FastMCP
from fastmcp.server import create_proxy
ECHO_SERVER_PORT = 8002
ECHO_SERVER_URL = f"http://localhost:{ECHO_SERVER_PORT}/sse"
@asynccontextmanager
async def lifespan(server: FastMCP) -> AsyncIterator[None]:
"""Start echo server subprocess and mount proxy to it."""
echo_path = Path(__file__).parent.parent / "echo.py"
# Pass OTEL config to subprocess with different service name
env = os.environ.copy()
env["OTEL_SERVICE_NAME"] = "fastmcp-echo-server"
# Start echo server as subprocess using run_with_tracing.py for OTEL export
run_with_tracing = Path(__file__).parent.parent / "run_with_tracing.py"
proc = subprocess.Popen(
[
"uv",
"run",
str(run_with_tracing),
str(echo_path),
"--transport",
"sse",
"--port",
str(ECHO_SERVER_PORT),
],
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
# Wait for server to be ready (async to avoid blocking event loop)
async with httpx.AsyncClient() as client:
for _ in range(50):
try:
await client.get(
f"http://localhost:{ECHO_SERVER_PORT}/sse", timeout=0.1
)
break
except Exception:
await asyncio.sleep(0.1)
# Mount proxy to the running echo server
echo_proxy = create_proxy(ECHO_SERVER_URL, name="Echo Proxy")
server.mount(echo_proxy, namespace="proxied")
try:
yield
finally:
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
mcp = FastMCP("Diagnostics Server", lifespan=lifespan)
# === SUCCESSFUL COMPONENTS ===
@mcp.tool
def ping() -> str:
"""Simple ping tool - always succeeds."""
return "pong"
@mcp.resource("diag://status")
def status_resource() -> str:
"""Status resource - always succeeds."""
return "OK"
@mcp.resource("diag://echo/{message}")
def echo_template(message: str) -> str:
"""Echo template - always succeeds."""
return f"Echo: {message}"
@mcp.prompt("greet")
def greet_prompt(name: str = "World") -> str:
"""Greeting prompt - always succeeds."""
return f"Hello, {name}!"
# === ERROR COMPONENTS ===
@mcp.tool
def fail_tool(message: str = "Intentional tool failure") -> str:
"""Tool that always raises ValueError - for error tracing."""
raise ValueError(message)
@mcp.resource("diag://error")
def error_resource() -> str:
"""Resource that always raises ValueError."""
raise ValueError("Intentional resource failure")
@mcp.resource("diag://error/{code}")
def error_template(code: str) -> str:
"""Template that always raises ValueError."""
raise ValueError(f"Intentional template failure: {code}")
@mcp.prompt("fail")
def fail_prompt() -> str:
"""Prompt that always raises ValueError."""
raise ValueError("Intentional prompt failure")
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "examples/diagnostics/server.py",
"license": "Apache License 2.0",
"lines": 93,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:examples/run_with_tracing.py | #!/usr/bin/env python
"""Run a FastMCP server with OpenTelemetry tracing enabled.
Usage:
uv run examples/run_with_tracing.py examples/echo.py --transport sse --port 8001
All arguments after the script name are passed to `fastmcp run`.
Traces are exported via OTLP to localhost:4317.
To view traces, run otel-desktop-viewer in another terminal:
otel-desktop-viewer
# Trace UI at http://localhost:8000, OTLP receiver on :4317
Install otel-desktop-viewer:
brew install nico-barbas/brew/otel-desktop-viewer
"""
import os
import sys
def main() -> None:
if len(sys.argv) < 2:
print(__doc__)
sys.exit(1)
# Configure OTEL SDK before importing fastmcp
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4317")
service_name = os.environ.get(
"OTEL_SERVICE_NAME",
f"fastmcp-{os.path.basename(sys.argv[1]).replace('.py', '')}",
)
# Set up tracer provider with OTLP exporter
resource = Resource.create({"service.name": service_name})
provider = TracerProvider(resource=resource)
exporter = OTLPSpanExporter(endpoint=endpoint, insecure=True)
provider.add_span_processor(BatchSpanProcessor(exporter))
trace.set_tracer_provider(provider)
print(f"Tracing enabled → OTLP {endpoint}", flush=True)
print(f"Service: {service_name}", flush=True)
print("View traces: otel-desktop-viewer (http://localhost:8000)\n", flush=True)
# Now run fastmcp CLI
from fastmcp.cli.cli import app
sys.argv = ["fastmcp", "run", *sys.argv[1:]]
app()
if __name__ == "__main__":
main()
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "examples/run_with_tracing.py",
"license": "Apache License 2.0",
"lines": 44,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
PrefectHQ/fastmcp:src/fastmcp/client/telemetry.py | """Client-side telemetry helpers."""
from collections.abc import Generator
from contextlib import contextmanager
from opentelemetry.trace import Span, SpanKind, Status, StatusCode
from fastmcp.telemetry import get_tracer
@contextmanager
def client_span(
name: str,
method: str,
component_key: str,
session_id: str | None = None,
resource_uri: str | None = None,
) -> Generator[Span, None, None]:
"""Create a CLIENT span with standard MCP attributes.
Automatically records any exception on the span and sets error status.
"""
tracer = get_tracer()
with tracer.start_as_current_span(name, kind=SpanKind.CLIENT) as span:
attrs: dict[str, str] = {
# RPC semantic conventions
"rpc.system": "mcp",
"rpc.method": method,
# MCP semantic conventions
"mcp.method.name": method,
# FastMCP-specific attributes
"fastmcp.component.key": component_key,
}
if session_id:
attrs["mcp.session.id"] = session_id
if resource_uri:
attrs["mcp.resource.uri"] = resource_uri
span.set_attributes(attrs)
try:
yield span
except Exception as e:
span.record_exception(e)
span.set_status(Status(StatusCode.ERROR))
raise
__all__ = ["client_span"]
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/client/telemetry.py",
"license": "Apache License 2.0",
"lines": 39,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
PrefectHQ/fastmcp:src/fastmcp/server/telemetry.py | """Server-side telemetry helpers."""
from collections.abc import Generator
from contextlib import contextmanager
from mcp.server.lowlevel.server import request_ctx
from opentelemetry.context import Context
from opentelemetry.trace import Span, SpanKind, Status, StatusCode
from fastmcp.telemetry import extract_trace_context, get_tracer
def get_auth_span_attributes() -> dict[str, str]:
"""Get auth attributes for the current request, if authenticated."""
from fastmcp.server.dependencies import get_access_token
attrs: dict[str, str] = {}
try:
token = get_access_token()
if token:
if token.client_id:
attrs["enduser.id"] = token.client_id
if token.scopes:
attrs["enduser.scope"] = " ".join(token.scopes)
except RuntimeError:
pass
return attrs
def get_session_span_attributes() -> dict[str, str]:
"""Get session attributes for the current request."""
from fastmcp.server.dependencies import get_context
attrs: dict[str, str] = {}
try:
ctx = get_context()
if ctx.request_context is not None and ctx.session_id is not None:
attrs["mcp.session.id"] = ctx.session_id
except RuntimeError:
pass
return attrs
def _get_parent_trace_context() -> Context | None:
"""Get parent trace context from request meta for distributed tracing."""
try:
req_ctx = request_ctx.get()
if req_ctx and hasattr(req_ctx, "meta") and req_ctx.meta:
return extract_trace_context(dict(req_ctx.meta))
except LookupError:
pass
return None
@contextmanager
def server_span(
name: str,
method: str,
server_name: str,
component_type: str,
component_key: str,
resource_uri: str | None = None,
) -> Generator[Span, None, None]:
"""Create a SERVER span with standard MCP attributes and auth context.
Automatically records any exception on the span and sets error status.
"""
tracer = get_tracer()
with tracer.start_as_current_span(
name,
context=_get_parent_trace_context(),
kind=SpanKind.SERVER,
) as span:
attrs: dict[str, str] = {
# RPC semantic conventions
"rpc.system": "mcp",
"rpc.service": server_name,
"rpc.method": method,
# MCP semantic conventions
"mcp.method.name": method,
# FastMCP-specific attributes
"fastmcp.server.name": server_name,
"fastmcp.component.type": component_type,
"fastmcp.component.key": component_key,
**get_auth_span_attributes(),
**get_session_span_attributes(),
}
if resource_uri is not None:
attrs["mcp.resource.uri"] = resource_uri
span.set_attributes(attrs)
try:
yield span
except Exception as e:
span.record_exception(e)
span.set_status(Status(StatusCode.ERROR))
raise
@contextmanager
def delegate_span(
name: str,
provider_type: str,
component_key: str,
) -> Generator[Span, None, None]:
"""Create an INTERNAL span for provider delegation.
Used by FastMCPProvider when delegating to mounted servers.
Automatically records any exception on the span and sets error status.
"""
tracer = get_tracer()
with tracer.start_as_current_span(f"delegate {name}") as span:
span.set_attributes(
{
"fastmcp.provider.type": provider_type,
"fastmcp.component.key": component_key,
}
)
try:
yield span
except Exception as e:
span.record_exception(e)
span.set_status(Status(StatusCode.ERROR))
raise
__all__ = [
"delegate_span",
"get_auth_span_attributes",
"get_session_span_attributes",
"server_span",
]
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/server/telemetry.py",
"license": "Apache License 2.0",
"lines": 112,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/telemetry.py | """OpenTelemetry instrumentation for FastMCP.
This module provides native OpenTelemetry integration for FastMCP servers and clients.
It uses only the opentelemetry-api package, so telemetry is a no-op unless the user
installs an OpenTelemetry SDK and configures exporters.
Example usage with SDK:
```python
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
# Configure the SDK (user responsibility)
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)
# Now FastMCP will emit traces
from fastmcp import FastMCP
mcp = FastMCP("my-server")
```
"""
from typing import Any
from opentelemetry import context as otel_context
from opentelemetry import propagate, trace
from opentelemetry.context import Context
from opentelemetry.trace import Span, Status, StatusCode, Tracer
from opentelemetry.trace import get_tracer as otel_get_tracer
INSTRUMENTATION_NAME = "fastmcp"
TRACE_PARENT_KEY = "traceparent"
TRACE_STATE_KEY = "tracestate"
def get_tracer(version: str | None = None) -> Tracer:
"""Get the FastMCP tracer for creating spans.
Args:
version: Optional version string for the instrumentation
Returns:
A tracer instance. Returns a no-op tracer if no SDK is configured.
"""
return otel_get_tracer(INSTRUMENTATION_NAME, version)
def inject_trace_context(
meta: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
"""Inject current trace context into a meta dict for MCP request propagation.
Args:
meta: Optional existing meta dict to merge with trace context
Returns:
A new dict containing the original meta (if any) plus trace context keys,
or None if no trace context to inject and meta was None
"""
carrier: dict[str, str] = {}
propagate.inject(carrier)
trace_meta: dict[str, Any] = {}
if "traceparent" in carrier:
trace_meta[TRACE_PARENT_KEY] = carrier["traceparent"]
if "tracestate" in carrier:
trace_meta[TRACE_STATE_KEY] = carrier["tracestate"]
if trace_meta:
return {**(meta or {}), **trace_meta}
return meta
def record_span_error(span: Span, exception: BaseException) -> None:
"""Record an exception on a span and set error status."""
span.record_exception(exception)
span.set_status(Status(StatusCode.ERROR))
def extract_trace_context(meta: dict[str, Any] | None) -> Context:
"""Extract trace context from an MCP request meta dict.
If already in a valid trace (e.g., from HTTP propagation), the existing
trace context is preserved and meta is not used.
Args:
meta: The meta dict from an MCP request (ctx.request_context.meta)
Returns:
An OpenTelemetry Context with the extracted trace context,
or the current context if no trace context found or already in a trace
"""
# Don't override existing trace context (e.g., from HTTP propagation)
current_span = trace.get_current_span()
if current_span.get_span_context().is_valid:
return otel_context.get_current()
if not meta:
return otel_context.get_current()
carrier: dict[str, str] = {}
if TRACE_PARENT_KEY in meta:
carrier["traceparent"] = str(meta[TRACE_PARENT_KEY])
if TRACE_STATE_KEY in meta:
carrier["tracestate"] = str(meta[TRACE_STATE_KEY])
if carrier:
return propagate.extract(carrier)
return otel_context.get_current()
__all__ = [
"INSTRUMENTATION_NAME",
"TRACE_PARENT_KEY",
"TRACE_STATE_KEY",
"extract_trace_context",
"get_tracer",
"inject_trace_context",
"record_span_error",
]
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/telemetry.py",
"license": "Apache License 2.0",
"lines": 92,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
PrefectHQ/fastmcp:tests/client/telemetry/test_client_tracing.py | """Tests for client OpenTelemetry tracing."""
from __future__ import annotations
from collections.abc import AsyncGenerator
import pytest
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.trace import SpanKind, StatusCode
from fastmcp import Client, FastMCP
from fastmcp.exceptions import ToolError
class TestClientToolTracing:
"""Tests for client tool call tracing."""
async def test_call_tool_creates_span(self, trace_exporter: InMemorySpanExporter):
server = FastMCP("test-server")
@server.tool()
def greet(name: str) -> str:
return f"Hello, {name}!"
client = Client(server)
async with client:
result = await client.call_tool("greet", {"name": "World"})
assert "Hello, World!" in str(result)
spans = trace_exporter.get_finished_spans()
span_names = [s.name for s in spans]
# Client should create "tools/call greet" span
assert "tools/call greet" in span_names
async def test_call_tool_span_attributes(
self, trace_exporter: InMemorySpanExporter
):
server = FastMCP("test-server")
@server.tool()
def add(a: int, b: int) -> int:
return a + b
client = Client(server)
async with client:
await client.call_tool("add", {"a": 1, "b": 2})
spans = trace_exporter.get_finished_spans()
# Find client-side span (doesn't have fastmcp.server.name)
client_span = next(
(
s
for s in spans
if s.name == "tools/call add"
and s.attributes is not None
and "fastmcp.server.name" not in s.attributes
),
None,
)
assert client_span is not None
assert client_span.attributes is not None
# Standard MCP semantic conventions
assert client_span.attributes["mcp.method.name"] == "tools/call"
# Standard RPC semantic conventions
assert client_span.attributes["rpc.system"] == "mcp"
assert client_span.attributes["rpc.method"] == "tools/call"
# FastMCP-specific attributes
assert client_span.attributes["fastmcp.component.key"] == "add"
class TestClientResourceTracing:
"""Tests for client resource read tracing."""
async def test_read_resource_creates_span(
self, trace_exporter: InMemorySpanExporter
):
server = FastMCP("test-server")
@server.resource("data://config")
def get_config() -> str:
return "config data"
client = Client(server)
async with client:
result = await client.read_resource("data://config")
assert "config data" in str(result)
spans = trace_exporter.get_finished_spans()
span_names = [s.name for s in spans]
# Client should create "resources/read data://config" span
assert "resources/read data://config" in span_names
async def test_read_resource_span_attributes(
self, trace_exporter: InMemorySpanExporter
):
server = FastMCP("test-server")
@server.resource("data://config")
def get_config() -> str:
return "config value"
client = Client(server)
async with client:
await client.read_resource("data://config")
spans = trace_exporter.get_finished_spans()
# Find client-side resource span (doesn't have fastmcp.server.name)
client_span = next(
(
s
for s in spans
if s.name.startswith("resources/read data://")
and s.attributes is not None
and "fastmcp.server.name" not in s.attributes
),
None,
)
assert client_span is not None
assert client_span.attributes is not None
# Standard MCP semantic conventions
assert client_span.attributes["mcp.method.name"] == "resources/read"
assert "data://" in str(client_span.attributes["mcp.resource.uri"])
# Standard RPC semantic conventions
assert client_span.attributes["rpc.system"] == "mcp"
assert client_span.attributes["rpc.method"] == "resources/read"
# FastMCP-specific attributes
# The URI may be normalized with trailing slash
assert "data://" in str(client_span.attributes["fastmcp.component.key"])
class TestClientPromptTracing:
"""Tests for client prompt get tracing."""
async def test_get_prompt_creates_span(self, trace_exporter: InMemorySpanExporter):
server = FastMCP("test-server")
@server.prompt()
def greeting() -> str:
return "Hello from prompt!"
client = Client(server)
async with client:
result = await client.get_prompt("greeting")
assert "Hello from prompt!" in str(result)
spans = trace_exporter.get_finished_spans()
span_names = [s.name for s in spans]
# Client should create "prompts/get greeting" span
assert "prompts/get greeting" in span_names
async def test_get_prompt_span_attributes(
self, trace_exporter: InMemorySpanExporter
):
server = FastMCP("test-server")
@server.prompt()
def welcome(name: str) -> str:
return f"Welcome, {name}!"
client = Client(server)
async with client:
await client.get_prompt("welcome", {"name": "Test"})
spans = trace_exporter.get_finished_spans()
# Find client-side prompt span (doesn't have fastmcp.server.name)
client_span = next(
(
s
for s in spans
if s.name == "prompts/get welcome"
and s.attributes is not None
and "fastmcp.server.name" not in s.attributes
),
None,
)
assert client_span is not None
assert client_span.attributes is not None
# Standard MCP semantic conventions
assert client_span.attributes["mcp.method.name"] == "prompts/get"
# Standard RPC semantic conventions
assert client_span.attributes["rpc.system"] == "mcp"
assert client_span.attributes["rpc.method"] == "prompts/get"
# FastMCP-specific attributes
assert client_span.attributes["fastmcp.component.key"] == "welcome"
class TestClientServerSpanHierarchy:
"""Tests for span relationships between client and server."""
async def test_client_and_server_spans_created(
self, trace_exporter: InMemorySpanExporter
):
"""Both client and server should create spans for the same operation."""
server = FastMCP("test-server")
@server.tool()
def echo(message: str) -> str:
return message
client = Client(server)
async with client:
await client.call_tool("echo", {"message": "test"})
spans = trace_exporter.get_finished_spans()
# Find client span (no fastmcp.server.name) and server span (has fastmcp.server.name)
client_span = next(
(
s
for s in spans
if s.name == "tools/call echo"
and s.attributes is not None
and "fastmcp.server.name" not in s.attributes
),
None,
)
server_span = next(
(
s
for s in spans
if s.name == "tools/call echo"
and s.attributes is not None
and "fastmcp.server.name" in s.attributes
),
None,
)
# Both spans should exist
assert client_span is not None, "Client should create a span"
assert client_span.attributes is not None
assert server_span is not None, "Server should create a span"
assert server_span.attributes is not None
# Verify span kinds are correct
assert client_span.kind == SpanKind.CLIENT, "Client span should be CLIENT kind"
assert server_span.kind == SpanKind.SERVER, "Server span should be SERVER kind"
# Verify the spans have different characteristics
assert client_span.attributes["rpc.method"] == "tools/call"
assert server_span.attributes["fastmcp.server.name"] == "test-server"
async def test_trace_context_propagation(
self, trace_exporter: InMemorySpanExporter
):
"""Server span should be a child of client span via trace context propagation."""
server = FastMCP("test-server")
@server.tool()
def add(a: int, b: int) -> int:
return a + b
client = Client(server)
async with client:
await client.call_tool("add", {"a": 1, "b": 2})
spans = trace_exporter.get_finished_spans()
# Find client span and server span
client_span = next(
(
s
for s in spans
if s.name == "tools/call add"
and s.attributes is not None
and "fastmcp.server.name" not in s.attributes
),
None,
)
server_span = next(
(
s
for s in spans
if s.name == "tools/call add"
and s.attributes is not None
and "fastmcp.server.name" in s.attributes
),
None,
)
assert client_span is not None, "Client span should exist"
assert server_span is not None, "Server span should exist"
# Verify trace context propagation: server span should be child of client span
# Both should share the same trace_id
assert server_span.context.trace_id == client_span.context.trace_id, (
"Server and client spans should share the same trace_id"
)
# Server span's parent should be the client span
assert server_span.parent is not None, "Server span should have a parent"
assert server_span.parent.span_id == client_span.context.span_id, (
"Server span's parent should be the client span"
)
class TestClientErrorTracing:
"""Tests for client span creation during errors.
Note: MCP protocol errors are returned as successful responses with error content,
so client spans may not have ERROR status even when the operation fails. This is
different from server-side where exceptions happen inside the span.
The server-side span WILL have ERROR status because the exception occurs within
the server's span context. The client span represents the successful MCP protocol
round-trip, while application-level errors are communicated via the response.
"""
async def test_call_tool_error_creates_spans(
self, trace_exporter: InMemorySpanExporter
):
"""Both client and server spans should be created when tool fails."""
server = FastMCP("test-server")
@server.tool()
def failing_tool() -> str:
raise ValueError("Something went wrong")
client = Client(server)
async with client:
with pytest.raises(ToolError):
await client.call_tool("failing_tool", {})
spans = trace_exporter.get_finished_spans()
# Find client-side span
client_span = next(
(
s
for s in spans
if s.name == "tools/call failing_tool"
and s.attributes is not None
and "fastmcp.server.name" not in s.attributes
),
None,
)
# Find server-side span
server_span = next(
(
s
for s in spans
if s.name == "tools/call failing_tool"
and s.attributes is not None
and "fastmcp.server.name" in s.attributes
),
None,
)
# Both spans should exist
assert client_span is not None, "Client should create a span"
assert server_span is not None, "Server should create a span"
# Server span should have ERROR status (exception inside span)
assert server_span.status.status_code == StatusCode.ERROR
async def test_read_resource_error_creates_spans(
self, trace_exporter: InMemorySpanExporter
):
"""Both client and server spans should be created when resource read fails."""
server = FastMCP("test-server")
@server.resource("data://fail")
def failing_resource() -> str:
raise ValueError("Resource error")
client = Client(server)
async with client:
with pytest.raises(Exception):
await client.read_resource("data://fail")
spans = trace_exporter.get_finished_spans()
# Find client-side span
client_span = next(
(
s
for s in spans
if s.name.startswith("resources/read data://fail")
and s.attributes is not None
and "fastmcp.server.name" not in s.attributes
),
None,
)
# Find server-side span
server_span = next(
(
s
for s in spans
if s.name.startswith("resources/read data://fail")
and s.attributes is not None
and "fastmcp.server.name" in s.attributes
),
None,
)
# Both spans should exist
assert client_span is not None, "Client should create a span"
assert server_span is not None, "Server should create a span"
# Server span should have ERROR status
assert server_span.status.status_code == StatusCode.ERROR
async def test_get_prompt_error_creates_spans(
self, trace_exporter: InMemorySpanExporter
):
"""Both client and server spans should be created when prompt get fails."""
server = FastMCP("test-server")
@server.prompt()
def failing_prompt() -> str:
raise ValueError("Prompt error")
client = Client(server)
async with client:
with pytest.raises(Exception):
await client.get_prompt("failing_prompt", {})
spans = trace_exporter.get_finished_spans()
# Find client-side span
client_span = next(
(
s
for s in spans
if s.name == "prompts/get failing_prompt"
and s.attributes is not None
and "fastmcp.server.name" not in s.attributes
),
None,
)
# Find server-side span
server_span = next(
(
s
for s in spans
if s.name == "prompts/get failing_prompt"
and s.attributes is not None
and "fastmcp.server.name" in s.attributes
),
None,
)
# Both spans should exist
assert client_span is not None, "Client should create a span"
assert server_span is not None, "Server should create a span"
# Server span should have ERROR status
assert server_span.status.status_code == StatusCode.ERROR
async def test_call_nonexistent_tool_creates_spans(
self, trace_exporter: InMemorySpanExporter
):
"""Both client and server spans should be created for nonexistent tool."""
server = FastMCP("test-server")
client = Client(server)
async with client:
with pytest.raises(Exception):
await client.call_tool("nonexistent", {})
spans = trace_exporter.get_finished_spans()
# Find client-side span
client_span = next(
(
s
for s in spans
if s.name == "tools/call nonexistent"
and s.attributes is not None
and "fastmcp.server.name" not in s.attributes
),
None,
)
# Find server-side span
server_span = next(
(
s
for s in spans
if s.name == "tools/call nonexistent"
and s.attributes is not None
and "fastmcp.server.name" in s.attributes
),
None,
)
# Both spans should exist
assert client_span is not None, "Client should create a span"
assert server_span is not None, "Server should create a span"
# Server span should have ERROR status
assert server_span.status.status_code == StatusCode.ERROR
class TestSessionIdOnSpans:
"""Tests for session ID capture on client and server spans.
Session IDs are only available with HTTP transport (StreamableHttp).
"""
@pytest.fixture
async def http_server_url(self) -> AsyncGenerator[str, None]:
"""Start an HTTP server and return its URL."""
from fastmcp.utilities.tests import run_server_async
server = FastMCP("session-test-server")
@server.tool()
def echo(message: str) -> str:
return message
async with run_server_async(server) as url:
yield url
async def test_client_span_includes_session_id(
self,
trace_exporter: InMemorySpanExporter,
http_server_url: str,
):
"""Client span should include session ID when using HTTP transport."""
from fastmcp.client.transports import StreamableHttpTransport
transport = StreamableHttpTransport(http_server_url)
client = Client(transport=transport)
async with client:
await client.call_tool("echo", {"message": "test"})
spans = trace_exporter.get_finished_spans()
# Find client-side span
client_span = next(
(
s
for s in spans
if s.name == "tools/call echo"
and s.attributes is not None
and "fastmcp.server.name" not in s.attributes
),
None,
)
assert client_span is not None, "Client should create a span"
assert client_span.attributes is not None
assert "mcp.session.id" in client_span.attributes
assert client_span.attributes["mcp.session.id"] is not None
async def test_server_span_includes_session_id(
self,
trace_exporter: InMemorySpanExporter,
http_server_url: str,
):
"""Server span should include session ID when called via HTTP."""
from fastmcp.client.transports import StreamableHttpTransport
transport = StreamableHttpTransport(http_server_url)
client = Client(transport=transport)
async with client:
await client.call_tool("echo", {"message": "test"})
spans = trace_exporter.get_finished_spans()
# Find server-side span
server_span = next(
(
s
for s in spans
if s.name == "tools/call echo"
and s.attributes is not None
and "fastmcp.server.name" in s.attributes
),
None,
)
assert server_span is not None, "Server should create a span"
assert server_span.attributes is not None
assert "mcp.session.id" in server_span.attributes
assert server_span.attributes["mcp.session.id"] is not None
async def test_client_and_server_share_same_session_id(
self,
trace_exporter: InMemorySpanExporter,
http_server_url: str,
):
"""Client and server spans should have the same session ID."""
from fastmcp.client.transports import StreamableHttpTransport
transport = StreamableHttpTransport(http_server_url)
client = Client(transport=transport)
async with client:
await client.call_tool("echo", {"message": "test"})
spans = trace_exporter.get_finished_spans()
# Find both spans
client_span = next(
(
s
for s in spans
if s.name == "tools/call echo"
and s.attributes is not None
and "fastmcp.server.name" not in s.attributes
),
None,
)
server_span = next(
(
s
for s in spans
if s.name == "tools/call echo"
and s.attributes is not None
and "fastmcp.server.name" in s.attributes
),
None,
)
assert client_span is not None
assert client_span.attributes is not None
assert server_span is not None
assert server_span.attributes is not None
# Both should have session IDs and they should match
client_session = client_span.attributes.get("mcp.session.id")
server_session = server_span.attributes.get("mcp.session.id")
assert client_session is not None, "Client span should have session ID"
assert server_session is not None, "Server span should have session ID"
assert client_session == server_session, (
"Client and server should share the same session ID"
)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/client/telemetry/test_client_tracing.py",
"license": "Apache License 2.0",
"lines": 520,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/telemetry/test_provider_tracing.py | """Tests for provider-level OpenTelemetry tracing."""
from __future__ import annotations
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from fastmcp import FastMCP
class TestFastMCPProviderTracing:
"""Tests for FastMCPProvider delegation tracing."""
async def test_mounted_tool_creates_delegate_span(
self, trace_exporter: InMemorySpanExporter
):
# Create a child server with a tool
child = FastMCP("child-server")
@child.tool()
def child_tool() -> str:
return "child result"
# Create parent server and mount child with namespace
parent = FastMCP("parent-server")
parent.mount(child, namespace="child")
# Call the tool through the parent (namespace uses underscore, not slash)
result = await parent.call_tool("child_child_tool", {})
assert "child result" in str(result)
# Check spans: should have parent tool span, delegate span, and child tool span
spans = trace_exporter.get_finished_spans()
span_names = [s.name for s in spans]
# Parent server creates "tools/call child_child_tool"
assert "tools/call child_child_tool" in span_names
# FastMCPProvider creates "delegate child_tool"
assert "delegate child_tool" in span_names
# Child server creates "tools/call child_tool"
assert "tools/call child_tool" in span_names
# Verify delegate span has correct attributes
delegate_span = next(s for s in spans if s.name == "delegate child_tool")
assert delegate_span.attributes is not None
assert delegate_span.attributes["fastmcp.provider.type"] == "FastMCPProvider"
assert delegate_span.attributes["fastmcp.component.key"] == "child_tool"
async def test_mounted_resource_creates_delegate_span(
self, trace_exporter: InMemorySpanExporter
):
# Create a child server with a resource
child = FastMCP("child-server")
@child.resource("data://config")
def child_config() -> str:
return "config data"
# Create parent server and mount child with namespace
parent = FastMCP("parent-server")
parent.mount(child, namespace="child")
# Read the resource through the parent (namespace is in the URI path)
result = await parent.read_resource("data://child/config")
assert "config data" in str(result)
spans = trace_exporter.get_finished_spans()
span_names = [s.name for s in spans]
# Should have delegate span for resource
assert any(
"delegate" in name and "data://config" in name for name in span_names
)
async def test_mounted_prompt_creates_delegate_span(
self, trace_exporter: InMemorySpanExporter
):
# Create a child server with a prompt
child = FastMCP("child-server")
@child.prompt()
def child_prompt() -> str:
return "Hello from child!"
# Create parent server and mount child with namespace
parent = FastMCP("parent-server")
parent.mount(child, namespace="child")
# Render the prompt through the parent (namespace uses underscore)
result = await parent.render_prompt("child_child_prompt", {})
assert "Hello from child!" in str(result)
spans = trace_exporter.get_finished_spans()
span_names = [s.name for s in spans]
# Should have delegate span for prompt
assert "delegate child_prompt" in span_names
# Verify delegate span has correct attributes
delegate_span = next(s for s in spans if s.name == "delegate child_prompt")
assert delegate_span.attributes is not None
assert delegate_span.attributes["fastmcp.provider.type"] == "FastMCPProvider"
class TestProviderSpanHierarchy:
"""Tests for span parent-child relationships in mounted servers."""
async def test_delegate_span_is_child_of_server_span(
self, trace_exporter: InMemorySpanExporter
):
# Create nested server structure
child = FastMCP("child")
@child.tool()
def greet() -> str:
return "Hello"
parent = FastMCP("parent")
parent.mount(child, namespace="ns")
await parent.call_tool("ns_greet", {})
spans = trace_exporter.get_finished_spans()
# Find the spans
parent_span = next(s for s in spans if s.name == "tools/call ns_greet")
delegate_span = next(s for s in spans if s.name == "delegate greet")
child_span = next(s for s in spans if s.name == "tools/call greet")
# Verify parent-child relationships
assert delegate_span.parent is not None
assert child_span.parent is not None
assert delegate_span.parent.span_id == parent_span.context.span_id
assert child_span.parent.span_id == delegate_span.context.span_id
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/telemetry/test_provider_tracing.py",
"license": "Apache License 2.0",
"lines": 99,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/server/telemetry/test_server_tracing.py | """Tests for server-level OpenTelemetry tracing."""
from __future__ import annotations
from unittest.mock import patch
import pytest
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.trace import SpanKind, StatusCode
from fastmcp import FastMCP
from fastmcp.exceptions import NotFoundError, ToolError
from fastmcp.server.auth import AccessToken
class TestToolTracing:
async def test_call_tool_creates_span(self, trace_exporter: InMemorySpanExporter):
mcp = FastMCP("test-server")
@mcp.tool()
def greet(name: str) -> str:
return f"Hello, {name}!"
result = await mcp.call_tool("greet", {"name": "World"})
assert "Hello, World!" in str(result)
spans = trace_exporter.get_finished_spans()
assert len(spans) == 1
span = spans[0]
assert span.name == "tools/call greet"
assert span.kind == SpanKind.SERVER
assert span.attributes is not None
# Standard MCP semantic conventions
assert span.attributes["mcp.method.name"] == "tools/call"
# Standard RPC semantic conventions
assert span.attributes["rpc.system"] == "mcp"
assert span.attributes["rpc.service"] == "test-server"
assert span.attributes["rpc.method"] == "tools/call"
# FastMCP-specific attributes
assert span.attributes["fastmcp.server.name"] == "test-server"
assert span.attributes["fastmcp.component.type"] == "tool"
assert span.attributes["fastmcp.component.key"] == "tool:greet@"
async def test_call_tool_with_error_sets_status(
self, trace_exporter: InMemorySpanExporter
):
mcp = FastMCP("test-server")
@mcp.tool()
def failing_tool() -> str:
raise ValueError("Something went wrong")
with pytest.raises(ToolError):
await mcp.call_tool("failing_tool", {})
spans = trace_exporter.get_finished_spans()
assert len(spans) == 1
span = spans[0]
assert span.name == "tools/call failing_tool"
assert span.status.status_code == StatusCode.ERROR
assert len(span.events) > 0 # Exception recorded
async def test_call_nonexistent_tool_sets_error(
self, trace_exporter: InMemorySpanExporter
):
mcp = FastMCP("test-server")
with pytest.raises(NotFoundError):
await mcp.call_tool("nonexistent", {})
spans = trace_exporter.get_finished_spans()
assert len(spans) == 1
span = spans[0]
assert span.name == "tools/call nonexistent"
assert span.status.status_code == StatusCode.ERROR
class TestResourceTracing:
async def test_read_resource_creates_span(
self, trace_exporter: InMemorySpanExporter
):
mcp = FastMCP("test-server")
@mcp.resource("config://app")
def get_config() -> str:
return "app_config_data"
result = await mcp.read_resource("config://app")
assert "app_config_data" in str(result)
spans = trace_exporter.get_finished_spans()
assert len(spans) == 1
span = spans[0]
assert span.name == "resources/read config://app"
assert span.kind == SpanKind.SERVER
assert span.attributes is not None
# Standard MCP semantic conventions
assert span.attributes["mcp.method.name"] == "resources/read"
assert span.attributes["mcp.resource.uri"] == "config://app"
# Standard RPC semantic conventions
assert span.attributes["rpc.system"] == "mcp"
assert span.attributes["rpc.service"] == "test-server"
assert span.attributes["rpc.method"] == "resources/read"
# FastMCP-specific attributes
assert span.attributes["fastmcp.server.name"] == "test-server"
assert span.attributes["fastmcp.component.type"] == "resource"
assert span.attributes["fastmcp.component.key"] == "resource:config://app@"
async def test_read_resource_template_creates_span(
self, trace_exporter: InMemorySpanExporter
):
mcp = FastMCP("test-server")
@mcp.resource("users://{user_id}/profile")
def get_user_profile(user_id: str) -> str:
return f"profile for {user_id}"
result = await mcp.read_resource("users://123/profile")
assert "profile for 123" in str(result)
spans = trace_exporter.get_finished_spans()
assert len(spans) == 1
span = spans[0]
assert span.name == "resources/read users://123/profile"
assert span.kind == SpanKind.SERVER
assert span.attributes is not None
# Standard MCP semantic conventions
assert span.attributes["mcp.method.name"] == "resources/read"
assert span.attributes["mcp.resource.uri"] == "users://123/profile"
# Standard RPC semantic conventions
assert span.attributes["rpc.method"] == "resources/read"
# Template component type is set by get_span_attributes
assert span.attributes["fastmcp.component.type"] == "resource_template"
assert (
span.attributes["fastmcp.component.key"]
== "template:users://{user_id}/profile@"
)
async def test_read_nonexistent_resource_sets_error(
self, trace_exporter: InMemorySpanExporter
):
mcp = FastMCP("test-server")
with pytest.raises(NotFoundError):
await mcp.read_resource("nonexistent://resource")
spans = trace_exporter.get_finished_spans()
assert len(spans) == 1
span = spans[0]
assert span.name == "resources/read nonexistent://resource"
assert span.status.status_code == StatusCode.ERROR
class TestPromptTracing:
async def test_render_prompt_creates_span(
self, trace_exporter: InMemorySpanExporter
):
mcp = FastMCP("test-server")
@mcp.prompt()
def greeting(name: str) -> str:
return f"Hello, {name}!"
result = await mcp.render_prompt("greeting", {"name": "World"})
assert "Hello, World!" in str(result)
spans = trace_exporter.get_finished_spans()
assert len(spans) == 1
span = spans[0]
assert span.name == "prompts/get greeting"
assert span.kind == SpanKind.SERVER
assert span.attributes is not None
# Standard MCP semantic conventions
assert span.attributes["mcp.method.name"] == "prompts/get"
# Standard RPC semantic conventions
assert span.attributes["rpc.system"] == "mcp"
assert span.attributes["rpc.service"] == "test-server"
assert span.attributes["rpc.method"] == "prompts/get"
# FastMCP-specific attributes
assert span.attributes["fastmcp.server.name"] == "test-server"
assert span.attributes["fastmcp.component.type"] == "prompt"
assert span.attributes["fastmcp.component.key"] == "prompt:greeting@"
async def test_render_nonexistent_prompt_sets_error(
self, trace_exporter: InMemorySpanExporter
):
mcp = FastMCP("test-server")
with pytest.raises(NotFoundError):
await mcp.render_prompt("nonexistent", {})
spans = trace_exporter.get_finished_spans()
assert len(spans) == 1
span = spans[0]
assert span.name == "prompts/get nonexistent"
assert span.status.status_code == StatusCode.ERROR
class TestAuthAttributesOnSpans:
async def test_tool_span_includes_auth_attributes_when_authenticated(
self, trace_exporter: InMemorySpanExporter
):
mcp = FastMCP("test-server")
@mcp.tool()
def greet(name: str) -> str:
return f"Hello, {name}!"
test_token = AccessToken(
token="test-token",
client_id="test-client-123",
scopes=["read", "write"],
)
with patch(
"fastmcp.server.dependencies.get_access_token", return_value=test_token
):
await mcp.call_tool("greet", {"name": "World"})
spans = trace_exporter.get_finished_spans()
assert len(spans) == 1
span = spans[0]
assert span.attributes is not None
assert span.attributes["enduser.id"] == "test-client-123"
assert span.attributes["enduser.scope"] == "read write"
async def test_resource_span_includes_auth_attributes_when_authenticated(
self, trace_exporter: InMemorySpanExporter
):
mcp = FastMCP("test-server")
@mcp.resource("config://app")
def get_config() -> str:
return "config_data"
test_token = AccessToken(
token="test-token",
client_id="user-456",
scopes=["config:read"],
)
with patch(
"fastmcp.server.dependencies.get_access_token", return_value=test_token
):
await mcp.read_resource("config://app")
spans = trace_exporter.get_finished_spans()
assert len(spans) == 1
span = spans[0]
assert span.attributes is not None
assert span.attributes["enduser.id"] == "user-456"
assert span.attributes["enduser.scope"] == "config:read"
async def test_prompt_span_includes_auth_attributes_when_authenticated(
self, trace_exporter: InMemorySpanExporter
):
mcp = FastMCP("test-server")
@mcp.prompt()
def greeting(name: str) -> str:
return f"Hello, {name}!"
test_token = AccessToken(
token="test-token",
client_id="prompt-user",
scopes=["prompts"],
)
with patch(
"fastmcp.server.dependencies.get_access_token", return_value=test_token
):
await mcp.render_prompt("greeting", {"name": "World"})
spans = trace_exporter.get_finished_spans()
assert len(spans) == 1
span = spans[0]
assert span.attributes is not None
assert span.attributes["enduser.id"] == "prompt-user"
assert span.attributes["enduser.scope"] == "prompts"
async def test_span_omits_auth_attributes_when_not_authenticated(
self, trace_exporter: InMemorySpanExporter
):
mcp = FastMCP("test-server")
@mcp.tool()
def greet(name: str) -> str:
return f"Hello, {name}!"
# No mock - get_access_token returns None by default (no auth context)
await mcp.call_tool("greet", {"name": "World"})
spans = trace_exporter.get_finished_spans()
assert len(spans) == 1
span = spans[0]
assert span.attributes is not None
# Auth attributes should not be present
assert "enduser.id" not in span.attributes
assert "enduser.scope" not in span.attributes
async def test_span_omits_scope_when_no_scopes(
self, trace_exporter: InMemorySpanExporter
):
mcp = FastMCP("test-server")
@mcp.tool()
def greet(name: str) -> str:
return f"Hello, {name}!"
test_token = AccessToken(
token="test-token",
client_id="client-no-scopes",
scopes=[], # Empty scopes
)
with patch(
"fastmcp.server.dependencies.get_access_token", return_value=test_token
):
await mcp.call_tool("greet", {"name": "World"})
spans = trace_exporter.get_finished_spans()
assert len(spans) == 1
span = spans[0]
assert span.attributes is not None
assert span.attributes["enduser.id"] == "client-no-scopes"
# Scope attribute should not be present when scopes list is empty
assert "enduser.scope" not in span.attributes
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/server/telemetry/test_server_tracing.py",
"license": "Apache License 2.0",
"lines": 266,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/telemetry/test_module.py | """Tests for the core telemetry module."""
from __future__ import annotations
from opentelemetry import trace
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from fastmcp.server.telemetry import get_auth_span_attributes
from fastmcp.telemetry import (
INSTRUMENTATION_NAME,
TRACE_PARENT_KEY,
extract_trace_context,
get_tracer,
inject_trace_context,
)
class TestGetTracer:
def test_tracer_uses_instrumentation_name(
self, trace_exporter: InMemorySpanExporter
):
tracer = get_tracer()
with tracer.start_as_current_span("test-span"):
pass
spans = trace_exporter.get_finished_spans()
assert len(spans) == 1
scope = spans[0].instrumentation_scope
assert scope is not None
assert scope.name == INSTRUMENTATION_NAME
class TestGetAuthSpanAttributes:
def test_returns_empty_dict_when_no_context(self):
attrs = get_auth_span_attributes()
assert attrs == {}
VALID_TRACEPARENT = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"
VALID_TRACESTATE = "congo=t61rcWkgMzE"
class TestInjectTraceContext:
def test_injects_bare_keys(self, trace_exporter: InMemorySpanExporter):
tracer = get_tracer()
with tracer.start_as_current_span("test"):
meta = inject_trace_context()
assert meta is not None
assert TRACE_PARENT_KEY in meta
assert meta[TRACE_PARENT_KEY].startswith("00-")
class TestExtractTraceContext:
def test_bare_traceparent(self, trace_exporter: InMemorySpanExporter):
ctx = extract_trace_context({"traceparent": VALID_TRACEPARENT})
span_ctx = trace.get_current_span(ctx).get_span_context()
assert span_ctx.is_valid
assert format(span_ctx.trace_id, "032x") == "0af7651916cd43dd8448eb211c80319c"
def test_bare_tracestate(self, trace_exporter: InMemorySpanExporter):
ctx = extract_trace_context(
{
"traceparent": VALID_TRACEPARENT,
"tracestate": VALID_TRACESTATE,
}
)
span_ctx = trace.get_current_span(ctx).get_span_context()
assert span_ctx.is_valid
assert span_ctx.trace_state.get("congo") == "t61rcWkgMzE"
def test_none_meta_returns_current_context(
self, trace_exporter: InMemorySpanExporter
):
ctx = extract_trace_context(None)
assert ctx is not None
def test_empty_meta_returns_current_context(
self, trace_exporter: InMemorySpanExporter
):
ctx = extract_trace_context({})
span_ctx = trace.get_current_span(ctx).get_span_context()
assert not span_ctx.is_valid
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/telemetry/test_module.py",
"license": "Apache License 2.0",
"lines": 65,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:tests/tools/test_tool_timeout.py | """Tests for tool timeout functionality."""
import time
import anyio
import pytest
from mcp.shared.exceptions import McpError
from mcp.types import TextContent
from fastmcp import FastMCP
from fastmcp.exceptions import ToolError
class TestToolTimeout:
"""Test tool timeout behavior."""
async def test_no_timeout_completes_normally_async(self):
"""Tool without timeout completes normally (async)."""
mcp = FastMCP()
@mcp.tool
async def quick_async_tool() -> str:
await anyio.sleep(0.01)
return "completed"
result = await mcp.call_tool("quick_async_tool")
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "completed"
async def test_no_timeout_completes_normally_sync(self):
"""Tool without timeout completes normally (sync)."""
mcp = FastMCP()
@mcp.tool
def quick_sync_tool() -> str:
time.sleep(0.01)
return "completed"
result = await mcp.call_tool("quick_sync_tool")
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "completed"
async def test_timeout_not_reached_async(self):
"""Async tool with timeout completes before timeout."""
mcp = FastMCP()
@mcp.tool(timeout=5.0)
async def fast_async_tool() -> str:
await anyio.sleep(0.1)
return "completed"
result = await mcp.call_tool("fast_async_tool")
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "completed"
async def test_timeout_not_reached_sync(self):
"""Sync tool with timeout completes before timeout."""
mcp = FastMCP()
@mcp.tool(timeout=5.0)
def fast_sync_tool() -> str:
time.sleep(0.1)
return "completed"
result = await mcp.call_tool("fast_sync_tool")
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "completed"
async def test_async_timeout_exceeded(self):
"""Async tool exceeds timeout and raises TimeoutError."""
mcp = FastMCP()
@mcp.tool(timeout=0.2)
async def slow_async_tool() -> str:
await anyio.sleep(2.0)
return "should not reach"
# TimeoutError is caught and converted to ToolError by FastMCP
with pytest.raises(ToolError) as exc_info:
await mcp.call_tool("slow_async_tool")
# Verify the tool raised an error (error message may be masked)
assert exc_info.value is not None
async def test_sync_timeout_exceeded(self):
"""Sync tool timeout works with CPU-bound operations."""
pytest.skip(
"Sync timeouts require thread pool execution (coming in future commit)"
)
# Note: time.sleep() blocks the event loop and cannot be interrupted
# by anyio.fail_after(). This will work once sync functions run in
# thread pools (commit 8c471a49).
async def test_timeout_error_raises_tool_error(self):
"""Timeout error is converted to ToolError and logs warning."""
mcp = FastMCP()
@mcp.tool(timeout=0.1)
async def slow_tool() -> str:
await anyio.sleep(1.0)
return "never"
# Verify that ToolError is raised (timeout warning is logged to stderr)
with pytest.raises(ToolError):
await mcp.call_tool("slow_tool")
async def test_timeout_from_tool_from_function(self):
"""Timeout works when using Tool.from_function()."""
from fastmcp.tools import Tool
async def my_slow_tool() -> str:
await anyio.sleep(1.0)
return "never"
tool = Tool.from_function(my_slow_tool, timeout=0.1)
mcp = FastMCP()
mcp.add_tool(tool)
with pytest.raises(ToolError):
await mcp.call_tool("my_slow_tool")
async def test_timeout_zero_times_out_immediately(self):
"""Timeout of 0 times out immediately."""
mcp = FastMCP()
@mcp.tool(timeout=0.0)
async def instant_timeout() -> str:
await anyio.sleep(0) # Give the event loop a chance to check timeout
return "never"
with pytest.raises(ToolError):
await mcp.call_tool("instant_timeout")
async def test_timeout_with_task_mode(self):
"""Tool with timeout and task mode can be configured together."""
mcp = FastMCP(tasks=True)
@mcp.tool(task=True, timeout=1.0)
async def task_with_timeout() -> str:
await anyio.sleep(0.1)
return "completed"
# Tool should be registered successfully
tools = await mcp.list_tools()
tool = next((t for t in tools if t.name == "task_with_timeout"), None)
assert tool is not None
assert tool.timeout == 1.0
assert tool.task_config.supports_tasks()
async def test_multiple_tools_with_different_timeouts(self):
"""Multiple tools can have different timeout values."""
mcp = FastMCP()
@mcp.tool(timeout=1.0)
async def short_timeout() -> str:
await anyio.sleep(0.1)
return "short"
@mcp.tool(timeout=5.0)
async def long_timeout() -> str:
await anyio.sleep(0.1)
return "long"
@mcp.tool
async def no_timeout() -> str:
await anyio.sleep(0.1)
return "none"
# All should complete successfully
result1 = await mcp.call_tool("short_timeout")
result2 = await mcp.call_tool("long_timeout")
result3 = await mcp.call_tool("no_timeout")
assert isinstance(result1.content[0], TextContent)
assert isinstance(result2.content[0], TextContent)
assert isinstance(result3.content[0], TextContent)
assert result1.content[0].text == "short"
assert result2.content[0].text == "long"
assert result3.content[0].text == "none"
async def test_timeout_error_converted_to_tool_error(self):
"""Timeout errors are converted to ToolError by FastMCP."""
mcp = FastMCP()
@mcp.tool(timeout=0.1)
async def times_out() -> str:
await anyio.sleep(1.0)
return "never"
# TimeoutError should be caught and converted to ToolError
with pytest.raises((ToolError, McpError)):
await mcp.call_tool("times_out")
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/tools/test_tool_timeout.py",
"license": "Apache License 2.0",
"lines": 148,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:src/fastmcp/tools/function_parsing.py | """Function introspection and schema generation for FastMCP tools."""
from __future__ import annotations
import functools
import inspect
import types
from collections.abc import Callable
from dataclasses import dataclass
from typing import Annotated, Any, Generic, Union, get_args, get_origin, get_type_hints
import mcp.types
from pydantic import PydanticSchemaGenerationError
from typing_extensions import TypeVar as TypeVarExt
from fastmcp.server.dependencies import (
transform_context_annotations,
without_injected_parameters,
)
from fastmcp.tools.tool import ToolResult
from fastmcp.utilities.json_schema import compress_schema
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import (
Audio,
File,
Image,
create_function_without_params,
get_cached_typeadapter,
replace_type,
)
try:
from prefab_ui.app import PrefabApp as _PrefabApp
from prefab_ui.components.base import Component as _PrefabComponent
_PREFAB_TYPES: tuple[type, ...] = (_PrefabApp, _PrefabComponent)
except ImportError:
_PREFAB_TYPES = ()
def _contains_prefab_type(tp: Any) -> bool:
"""Check if *tp* is or contains a prefab type, recursing through unions and Annotated."""
if isinstance(tp, type) and issubclass(tp, _PREFAB_TYPES):
return True
origin = get_origin(tp)
if origin is Union or origin is types.UnionType or origin is Annotated:
return any(_contains_prefab_type(a) for a in get_args(tp))
return False
T = TypeVarExt("T", default=Any)
logger = get_logger(__name__)
@dataclass
class _WrappedResult(Generic[T]):
"""Generic wrapper for non-object return types."""
result: T
class _UnserializableType:
pass
def _is_object_schema(
schema: dict[str, Any],
*,
_root_schema: dict[str, Any] | None = None,
_seen_refs: set[str] | None = None,
) -> bool:
"""Check if a JSON schema represents an object type."""
root_schema = _root_schema or schema
seen_refs = _seen_refs or set()
# Direct object type
if schema.get("type") == "object":
return True
# Schema with properties but no explicit type is treated as object
if "properties" in schema:
return True
# Resolve local $ref definitions and recurse into the target schema.
ref = schema.get("$ref")
if not isinstance(ref, str) or not ref.startswith("#/"):
return False
if ref in seen_refs:
return False
# Walk the JSON Pointer path from the root schema, unescaping each
# token per RFC 6901 (~1 → /, ~0 → ~).
pointer = ref.removeprefix("#/")
segments = pointer.split("/")
target: Any = root_schema
for segment in segments:
unescaped = segment.replace("~1", "/").replace("~0", "~")
if not isinstance(target, dict) or unescaped not in target:
return False
target = target[unescaped]
target_schema = target
if not isinstance(target_schema, dict):
return False
return _is_object_schema(
target_schema,
_root_schema=root_schema,
_seen_refs=seen_refs | {ref},
)
@dataclass
class ParsedFunction:
fn: Callable[..., Any]
name: str
description: str | None
input_schema: dict[str, Any]
output_schema: dict[str, Any] | None
return_type: Any = None
@classmethod
def from_function(
cls,
fn: Callable[..., Any],
exclude_args: list[str] | None = None,
validate: bool = True,
wrap_non_object_output_schema: bool = True,
) -> ParsedFunction:
if validate:
sig = inspect.signature(fn)
# Reject functions with *args or **kwargs
for param in sig.parameters.values():
if param.kind == inspect.Parameter.VAR_POSITIONAL:
raise ValueError("Functions with *args are not supported as tools")
if param.kind == inspect.Parameter.VAR_KEYWORD:
raise ValueError(
"Functions with **kwargs are not supported as tools"
)
# Reject exclude_args that don't exist in the function or don't have a default value
if exclude_args:
for arg_name in exclude_args:
if arg_name not in sig.parameters:
raise ValueError(
f"Parameter '{arg_name}' in exclude_args does not exist in function."
)
param = sig.parameters[arg_name]
if param.default == inspect.Parameter.empty:
raise ValueError(
f"Parameter '{arg_name}' in exclude_args must have a default value."
)
# collect name and doc before we potentially modify the function
fn_name = getattr(fn, "__name__", None) or fn.__class__.__name__
fn_doc = inspect.getdoc(fn)
# if the fn is a callable class, we need to get the __call__ method from here out
if not inspect.isroutine(fn) and not isinstance(fn, functools.partial):
fn = fn.__call__
# if the fn is a staticmethod, we need to work with the underlying function
if isinstance(fn, staticmethod):
fn = fn.__func__
# Transform Context type annotations to Depends() for unified DI
fn = transform_context_annotations(fn)
# Handle injected parameters (Context, Docket dependencies)
wrapper_fn = without_injected_parameters(fn)
# Also handle exclude_args with non-serializable types (issue #2431)
# This must happen before Pydantic tries to serialize the parameters
if exclude_args:
wrapper_fn = create_function_without_params(wrapper_fn, list(exclude_args))
input_type_adapter = get_cached_typeadapter(wrapper_fn)
input_schema = input_type_adapter.json_schema()
# Compress and handle exclude_args
prune_params = list(exclude_args) if exclude_args else None
input_schema = compress_schema(
input_schema, prune_params=prune_params, prune_titles=True
)
output_schema = None
# Get the return annotation from the signature
sig = inspect.signature(fn)
output_type = sig.return_annotation
# If the annotation is a string (from __future__ annotations), resolve it
if isinstance(output_type, str):
try:
# Use get_type_hints to resolve the return type
# include_extras=True preserves Annotated metadata
type_hints = get_type_hints(fn, include_extras=True)
output_type = type_hints.get("return", output_type)
except Exception as e:
# If resolution fails, keep the string annotation
logger.debug("Failed to resolve type hint for return annotation: %s", e)
# Save original for return_type before any schema-related replacement
original_output_type = output_type
if output_type not in (inspect._empty, None, Any, ...):
# Prefab component subclasses (Column, Card, etc.) shouldn't
# produce output schemas — replace_type only does exact matching,
# so we handle subclass matching explicitly here. We also need
# to handle composite types like ``Column | None`` and
# ``Annotated[PrefabApp, ...]`` by recursing into their args.
if _PREFAB_TYPES and _contains_prefab_type(output_type):
output_type = _UnserializableType
# there are a variety of types that we don't want to attempt to
# serialize because they are either used by FastMCP internally,
# or are MCP content types that explicitly don't form structured
# content. By replacing them with an explicitly unserializable type,
# we ensure that no output schema is automatically generated.
clean_output_type = replace_type(
output_type,
dict.fromkeys(
(
Image,
Audio,
File,
ToolResult,
mcp.types.TextContent,
mcp.types.ImageContent,
mcp.types.AudioContent,
mcp.types.ResourceLink,
mcp.types.EmbeddedResource,
*_PREFAB_TYPES,
),
_UnserializableType,
),
)
try:
type_adapter = get_cached_typeadapter(clean_output_type)
base_schema = type_adapter.json_schema(mode="serialization")
# Generate schema for wrapped type if it's non-object
# because MCP requires that output schemas are objects
# Check if schema is an object type, resolving $ref references
# (self-referencing types use $ref at root level)
if wrap_non_object_output_schema and not _is_object_schema(base_schema):
# Use the wrapped result schema directly
wrapped_type = _WrappedResult[clean_output_type]
wrapped_adapter = get_cached_typeadapter(wrapped_type)
output_schema = wrapped_adapter.json_schema(mode="serialization")
output_schema["x-fastmcp-wrap-result"] = True
else:
output_schema = base_schema
output_schema = compress_schema(output_schema, prune_titles=True)
except PydanticSchemaGenerationError as e:
if "_UnserializableType" not in str(e):
logger.debug(f"Unable to generate schema for type {output_type!r}")
return cls(
fn=fn,
name=fn_name,
description=fn_doc,
input_schema=input_schema,
output_schema=output_schema or None,
return_type=original_output_type,
)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/tools/function_parsing.py",
"license": "Apache License 2.0",
"lines": 223,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/server/providers/aggregate.py | """AggregateProvider for combining multiple providers into one.
This module provides `AggregateProvider`, a utility class that presents
multiple providers as a single unified provider. Useful when you want to
combine custom providers without creating a full FastMCP server.
Example:
```python
from fastmcp.server.providers import AggregateProvider
# Combine multiple providers into one
combined = AggregateProvider()
combined.add_provider(provider1)
combined.add_provider(provider2, namespace="api") # Tools become "api_foo"
# Use like any other provider
tools = await combined.list_tools()
```
"""
from __future__ import annotations
import logging
from collections.abc import AsyncIterator, Sequence
from contextlib import AsyncExitStack, asynccontextmanager
from typing import TYPE_CHECKING, TypeVar
from fastmcp.exceptions import NotFoundError
from fastmcp.server.providers.base import Provider
from fastmcp.server.transforms import Namespace
from fastmcp.utilities.async_utils import gather
from fastmcp.utilities.components import FastMCPComponent
from fastmcp.utilities.versions import VersionSpec, version_sort_key
if TYPE_CHECKING:
from fastmcp.prompts.prompt import Prompt
from fastmcp.resources.resource import Resource
from fastmcp.resources.template import ResourceTemplate
from fastmcp.tools.tool import Tool
logger = logging.getLogger(__name__)
T = TypeVar("T")
class AggregateProvider(Provider):
"""Utility provider that combines multiple providers into one.
Components are aggregated from all providers. For get_* operations,
providers are queried in parallel and the highest version is returned.
When adding providers with a namespace, wrap_transform() is used to apply
the Namespace transform. This means namespace transformation is handled
by the wrapped provider, not by AggregateProvider.
Errors from individual providers are logged and skipped (graceful degradation).
Example:
```python
combined = AggregateProvider()
combined.add_provider(db_provider)
combined.add_provider(api_provider, namespace="api")
# db_provider's tools keep original names
# api_provider's tools become "api_foo", "api_bar", etc.
```
"""
def __init__(self, providers: Sequence[Provider] | None = None) -> None:
"""Initialize with an optional sequence of providers.
Args:
providers: Optional initial providers (without namespacing).
For namespaced providers, use add_provider() instead.
"""
super().__init__()
self.providers: list[Provider] = list(providers or [])
def add_provider(self, provider: Provider, *, namespace: str = "") -> None:
"""Add a provider with optional namespace.
If the provider is a FastMCP server, it's automatically wrapped in
FastMCPProvider to ensure middleware is invoked correctly.
Args:
provider: The provider to add.
namespace: Optional namespace prefix. When set:
- Tools become "namespace_toolname"
- Resources become "protocol://namespace/path"
- Prompts become "namespace_promptname"
"""
# Import here to avoid circular imports
from fastmcp.server.server import FastMCP
# Auto-wrap FastMCP servers to ensure middleware is invoked
if isinstance(provider, FastMCP):
from fastmcp.server.providers.fastmcp_provider import FastMCPProvider
provider = FastMCPProvider(provider)
# Apply namespace via wrap_transform if specified
if namespace:
provider = provider.wrap_transform(Namespace(namespace))
self.providers.append(provider)
def _collect_list_results(
self, results: list[Sequence[T] | BaseException], operation: str
) -> list[T]:
"""Collect successful list results, logging any exceptions."""
collected: list[T] = []
for i, result in enumerate(results):
if isinstance(result, BaseException):
logger.debug(
f"Error during {operation} from provider "
f"{self.providers[i]}: {result}"
)
continue
collected.extend(result)
return collected
def _get_highest_version_result(
self,
results: list[FastMCPComponent | None | BaseException],
operation: str,
) -> FastMCPComponent | None:
"""Get the highest version from successful non-None results.
Used for versioned components where we want the highest version
across all providers rather than the first match.
"""
valid: list[FastMCPComponent] = []
for i, result in enumerate(results):
if isinstance(result, BaseException):
if not isinstance(result, NotFoundError):
logger.debug(
f"Error during {operation} from provider "
f"{self.providers[i]}: {result}"
)
continue
if result is not None:
valid.append(result)
if not valid:
return None
return max(valid, key=version_sort_key)
def __repr__(self) -> str:
return f"AggregateProvider(providers={self.providers!r})"
# -------------------------------------------------------------------------
# Tools
# -------------------------------------------------------------------------
async def _list_tools(self) -> Sequence[Tool]:
"""List all tools from all providers."""
results = await gather(
*[p.list_tools() for p in self.providers],
return_exceptions=True,
)
return self._collect_list_results(results, "list_tools")
async def _get_tool(
self, name: str, version: VersionSpec | None = None
) -> Tool | None:
"""Get tool by name from providers."""
results = await gather(
*[p.get_tool(name, version) for p in self.providers],
return_exceptions=True,
)
return self._get_highest_version_result(results, f"get_tool({name!r})") # type: ignore[return-value]
# -------------------------------------------------------------------------
# Resources
# -------------------------------------------------------------------------
async def _list_resources(self) -> Sequence[Resource]:
"""List all resources from all providers."""
results = await gather(
*[p.list_resources() for p in self.providers],
return_exceptions=True,
)
return self._collect_list_results(results, "list_resources")
async def _get_resource(
self, uri: str, version: VersionSpec | None = None
) -> Resource | None:
"""Get resource by URI from providers."""
results = await gather(
*[p.get_resource(uri, version) for p in self.providers],
return_exceptions=True,
)
return self._get_highest_version_result(results, f"get_resource({uri!r})") # type: ignore[return-value]
# -------------------------------------------------------------------------
# Resource Templates
# -------------------------------------------------------------------------
async def _list_resource_templates(self) -> Sequence[ResourceTemplate]:
"""List all resource templates from all providers."""
results = await gather(
*[p.list_resource_templates() for p in self.providers],
return_exceptions=True,
)
return self._collect_list_results(results, "list_resource_templates")
async def _get_resource_template(
self, uri: str, version: VersionSpec | None = None
) -> ResourceTemplate | None:
"""Get resource template by URI from providers."""
results = await gather(
*[p.get_resource_template(uri, version) for p in self.providers],
return_exceptions=True,
)
return self._get_highest_version_result(
results, f"get_resource_template({uri!r})"
) # type: ignore[return-value]
# -------------------------------------------------------------------------
# Prompts
# -------------------------------------------------------------------------
async def _list_prompts(self) -> Sequence[Prompt]:
"""List all prompts from all providers."""
results = await gather(
*[p.list_prompts() for p in self.providers],
return_exceptions=True,
)
return self._collect_list_results(results, "list_prompts")
async def _get_prompt(
self, name: str, version: VersionSpec | None = None
) -> Prompt | None:
"""Get prompt by name from providers."""
results = await gather(
*[p.get_prompt(name, version) for p in self.providers],
return_exceptions=True,
)
return self._get_highest_version_result(results, f"get_prompt({name!r})") # type: ignore[return-value]
# -------------------------------------------------------------------------
# Tasks
# -------------------------------------------------------------------------
async def get_tasks(self) -> Sequence[FastMCPComponent]:
"""Get all task-eligible components from all providers."""
results = await gather(
*[p.get_tasks() for p in self.providers],
return_exceptions=True,
)
return self._collect_list_results(results, "get_tasks")
# -------------------------------------------------------------------------
# Lifecycle
# -------------------------------------------------------------------------
@asynccontextmanager
async def lifespan(self) -> AsyncIterator[None]:
"""Combine lifespans of all providers."""
async with AsyncExitStack() as stack:
for p in self.providers:
await stack.enter_async_context(p.lifespan())
yield
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/server/providers/aggregate.py",
"license": "Apache License 2.0",
"lines": 216,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/server/transforms/namespace.py | """Namespace transform for prefixing component names."""
from __future__ import annotations
import re
from collections.abc import Sequence
from typing import TYPE_CHECKING
from fastmcp.server.transforms import (
GetPromptNext,
GetResourceNext,
GetResourceTemplateNext,
GetToolNext,
Transform,
)
from fastmcp.utilities.versions import VersionSpec
if TYPE_CHECKING:
from fastmcp.prompts.prompt import Prompt
from fastmcp.resources.resource import Resource
from fastmcp.resources.template import ResourceTemplate
from fastmcp.tools.tool import Tool
# Pattern for matching URIs: protocol://path
_URI_PATTERN = re.compile(r"^([^:]+://)(.*?)$")
class Namespace(Transform):
"""Prefixes component names with a namespace.
- Tools: name → namespace_name
- Prompts: name → namespace_name
- Resources: protocol://path → protocol://namespace/path
- Resource Templates: same as resources
Example:
```python
transform = Namespace("math")
# Tool "add" becomes "math_add"
# Resource "file://data.txt" becomes "file://math/data.txt"
```
"""
def __init__(self, prefix: str) -> None:
"""Initialize Namespace transform.
Args:
prefix: The namespace prefix to apply.
"""
self._prefix = prefix
self._name_prefix = f"{prefix}_"
def __repr__(self) -> str:
return f"Namespace({self._prefix!r})"
# -------------------------------------------------------------------------
# Name transformation helpers
# -------------------------------------------------------------------------
def _transform_name(self, name: str) -> str:
"""Apply namespace prefix to a name."""
return f"{self._name_prefix}{name}"
def _reverse_name(self, name: str) -> str | None:
"""Remove namespace prefix from a name, or None if no match."""
if name.startswith(self._name_prefix):
return name[len(self._name_prefix) :]
return None
# -------------------------------------------------------------------------
# URI transformation helpers
# -------------------------------------------------------------------------
def _transform_uri(self, uri: str) -> str:
"""Apply namespace to a URI: protocol://path → protocol://namespace/path."""
match = _URI_PATTERN.match(uri)
if match:
protocol, path = match.groups()
return f"{protocol}{self._prefix}/{path}"
return uri
def _reverse_uri(self, uri: str) -> str | None:
"""Remove namespace from a URI, or None if no match."""
match = _URI_PATTERN.match(uri)
if match:
protocol, path = match.groups()
prefix = f"{self._prefix}/"
if path.startswith(prefix):
return f"{protocol}{path[len(prefix) :]}"
return None
return None
# -------------------------------------------------------------------------
# Tools
# -------------------------------------------------------------------------
async def list_tools(self, tools: Sequence[Tool]) -> Sequence[Tool]:
"""Prefix tool names with namespace."""
return [
t.model_copy(update={"name": self._transform_name(t.name)}) for t in tools
]
async def get_tool(
self, name: str, call_next: GetToolNext, *, version: VersionSpec | None = None
) -> Tool | None:
"""Get tool by namespaced name."""
original = self._reverse_name(name)
if original is None:
return None
tool = await call_next(original, version=version)
if tool:
return tool.model_copy(update={"name": name})
return None
# -------------------------------------------------------------------------
# Resources
# -------------------------------------------------------------------------
async def list_resources(self, resources: Sequence[Resource]) -> Sequence[Resource]:
"""Add namespace path segment to resource URIs."""
return [
r.model_copy(update={"uri": self._transform_uri(str(r.uri))})
for r in resources
]
async def get_resource(
self,
uri: str,
call_next: GetResourceNext,
*,
version: VersionSpec | None = None,
) -> Resource | None:
"""Get resource by namespaced URI."""
original = self._reverse_uri(uri)
if original is None:
return None
resource = await call_next(original, version=version)
if resource:
return resource.model_copy(update={"uri": uri})
return None
# -------------------------------------------------------------------------
# Resource Templates
# -------------------------------------------------------------------------
async def list_resource_templates(
self, templates: Sequence[ResourceTemplate]
) -> Sequence[ResourceTemplate]:
"""Add namespace path segment to template URIs."""
return [
t.model_copy(update={"uri_template": self._transform_uri(t.uri_template)})
for t in templates
]
async def get_resource_template(
self,
uri: str,
call_next: GetResourceTemplateNext,
*,
version: VersionSpec | None = None,
) -> ResourceTemplate | None:
"""Get resource template by namespaced URI."""
original = self._reverse_uri(uri)
if original is None:
return None
template = await call_next(original, version=version)
if template:
return template.model_copy(
update={"uri_template": self._transform_uri(template.uri_template)}
)
return None
# -------------------------------------------------------------------------
# Prompts
# -------------------------------------------------------------------------
async def list_prompts(self, prompts: Sequence[Prompt]) -> Sequence[Prompt]:
"""Prefix prompt names with namespace."""
return [
p.model_copy(update={"name": self._transform_name(p.name)}) for p in prompts
]
async def get_prompt(
self, name: str, call_next: GetPromptNext, *, version: VersionSpec | None = None
) -> Prompt | None:
"""Get prompt by namespaced name."""
original = self._reverse_name(name)
if original is None:
return None
prompt = await call_next(original, version=version)
if prompt:
return prompt.model_copy(update={"name": name})
return None
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/server/transforms/namespace.py",
"license": "Apache License 2.0",
"lines": 163,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/server/transforms/tool_transform.py | """Transform for applying tool transformations."""
from __future__ import annotations
from collections.abc import Sequence
from typing import TYPE_CHECKING
from fastmcp.server.transforms import GetToolNext, Transform
from fastmcp.tools.tool_transform import ToolTransformConfig
from fastmcp.utilities.versions import VersionSpec
if TYPE_CHECKING:
from fastmcp.tools.tool import Tool
class ToolTransform(Transform):
"""Applies tool transformations to modify tool schemas.
Wraps ToolTransformConfig to apply argument renames, schema changes,
hidden arguments, and other transformations at the transform level.
Example:
```python
transform = ToolTransform({
"my_tool": ToolTransformConfig(
name="renamed_tool",
arguments={"old_arg": ArgTransformConfig(name="new_arg")}
)
})
```
"""
def __init__(self, transforms: dict[str, ToolTransformConfig]) -> None:
"""Initialize ToolTransform.
Args:
transforms: Map of original tool name → transform config.
"""
self._transforms = transforms
# Build reverse mapping: final_name → original_name
self._name_reverse: dict[str, str] = {}
for original_name, config in transforms.items():
final_name = config.name if config.name else original_name
self._name_reverse[final_name] = original_name
# Validate no duplicate target names
seen_targets: dict[str, str] = {}
for original_name, config in transforms.items():
target = config.name if config.name else original_name
if target in seen_targets:
raise ValueError(
f"ToolTransform has duplicate target name {target!r}: "
f"both {seen_targets[target]!r} and {original_name!r} map to it"
)
seen_targets[target] = original_name
def __repr__(self) -> str:
names = list(self._transforms.keys())
if len(names) <= 3:
return f"ToolTransform({names!r})"
return f"ToolTransform({names[:3]!r}... +{len(names) - 3} more)"
async def list_tools(self, tools: Sequence[Tool]) -> Sequence[Tool]:
"""Apply transforms to matching tools."""
result: list[Tool] = []
for tool in tools:
if tool.name in self._transforms:
transformed = self._transforms[tool.name].apply(tool)
result.append(transformed)
else:
result.append(tool)
return result
async def get_tool(
self, name: str, call_next: GetToolNext, *, version: VersionSpec | None = None
) -> Tool | None:
"""Get tool by transformed name."""
# Check if this name is a transformed name
original_name = self._name_reverse.get(name, name)
# Get the original tool
tool = await call_next(original_name, version=version)
if tool is None:
return None
# Apply transform if applicable
if original_name in self._transforms:
transformed = self._transforms[original_name].apply(tool)
# Only return if requested name matches transformed name
if transformed.name == name:
return transformed
return None
# No transform, return as-is only if name matches
return tool if tool.name == name else None
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/server/transforms/tool_transform.py",
"license": "Apache License 2.0",
"lines": 78,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:tests/deprecated/test_add_tool_transformation.py | """Tests for deprecated add_tool_transformation API."""
import warnings
from fastmcp import FastMCP
from fastmcp.client import Client
from fastmcp.tools.tool_transform import ToolTransformConfig
class TestAddToolTransformationDeprecated:
"""Test that add_tool_transformation still works but emits deprecation warning."""
async def test_add_tool_transformation_emits_warning(self):
"""add_tool_transformation should emit deprecation warning."""
mcp = FastMCP("test")
@mcp.tool
def my_tool() -> str:
return "hello"
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
mcp.add_tool_transformation(
"my_tool", ToolTransformConfig(name="renamed_tool")
)
assert len(w) == 1
assert issubclass(w[0].category, DeprecationWarning)
assert "add_tool_transformation is deprecated" in str(w[0].message)
async def test_add_tool_transformation_still_works(self):
"""add_tool_transformation should still apply the transformation."""
mcp = FastMCP("test")
@mcp.tool
def verbose_tool_name() -> str:
return "result"
# Suppress warning for this test - we just want to verify it works
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
mcp.add_tool_transformation(
"verbose_tool_name", ToolTransformConfig(name="short")
)
async with Client(mcp) as client:
tools = await client.list_tools()
tool_names = [t.name for t in tools]
# Original name should be gone, renamed version should exist
assert "verbose_tool_name" not in tool_names
assert "short" in tool_names
# Should be callable by new name
result = await client.call_tool("short", {})
assert result.content[0].text == "result"
async def test_remove_tool_transformation_emits_warning(self):
"""remove_tool_transformation should emit deprecation warning."""
mcp = FastMCP("test")
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
mcp.remove_tool_transformation("any_tool")
assert len(w) == 1
assert issubclass(w[0].category, DeprecationWarning)
assert "remove_tool_transformation is deprecated" in str(w[0].message)
assert "no effect" in str(w[0].message)
async def test_tool_transformations_constructor_raises_type_error(self):
"""tool_transformations constructor param should raise TypeError."""
import pytest
with pytest.raises(TypeError, match="no longer accepts `tool_transformations`"):
FastMCP(
"test",
tool_transformations={"my_tool": ToolTransformConfig(name="renamed")},
)
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/deprecated/test_add_tool_transformation.py",
"license": "Apache License 2.0",
"lines": 60,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
PrefectHQ/fastmcp:src/fastmcp/decorators.py | """Shared decorator utilities for FastMCP."""
from __future__ import annotations
import inspect
from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
if TYPE_CHECKING:
from fastmcp.prompts.function_prompt import PromptMeta
from fastmcp.resources.function_resource import ResourceMeta
from fastmcp.server.tasks.config import TaskConfig
from fastmcp.tools.function_tool import ToolMeta
FastMCPMeta = ToolMeta | ResourceMeta | PromptMeta
def resolve_task_config(task: bool | TaskConfig | None) -> bool | TaskConfig:
"""Resolve task config, defaulting None to False."""
return task if task is not None else False
@runtime_checkable
class HasFastMCPMeta(Protocol):
"""Protocol for callables decorated with FastMCP metadata."""
__fastmcp__: Any
def get_fastmcp_meta(fn: Any) -> Any | None:
"""Extract FastMCP metadata from a function, handling bound methods and wrappers."""
if hasattr(fn, "__fastmcp__"):
return fn.__fastmcp__
if hasattr(fn, "__func__") and hasattr(fn.__func__, "__fastmcp__"):
return fn.__func__.__fastmcp__
try:
unwrapped = inspect.unwrap(fn)
if unwrapped is not fn and hasattr(unwrapped, "__fastmcp__"):
return unwrapped.__fastmcp__
except ValueError:
pass
return None
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/decorators.py",
"license": "Apache License 2.0",
"lines": 30,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
PrefectHQ/fastmcp:src/fastmcp/prompts/function_prompt.py | """Standalone @prompt decorator for FastMCP."""
from __future__ import annotations
import functools
import inspect
import json
import warnings
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import (
TYPE_CHECKING,
Any,
Literal,
Protocol,
TypeVar,
overload,
runtime_checkable,
)
import pydantic_core
from mcp.types import Icon
from pydantic.json_schema import SkipJsonSchema
import fastmcp
from fastmcp.decorators import resolve_task_config
from fastmcp.exceptions import PromptError
from fastmcp.prompts.prompt import Prompt, PromptArgument, PromptResult
from fastmcp.server.auth.authorization import AuthCheck
from fastmcp.server.dependencies import (
transform_context_annotations,
without_injected_parameters,
)
from fastmcp.server.tasks.config import TaskConfig
from fastmcp.utilities.async_utils import (
call_sync_fn_in_threadpool,
is_coroutine_function,
)
from fastmcp.utilities.json_schema import compress_schema
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import get_cached_typeadapter
if TYPE_CHECKING:
from docket import Docket
from docket.execution import Execution
F = TypeVar("F", bound=Callable[..., Any])
logger = get_logger(__name__)
@runtime_checkable
class DecoratedPrompt(Protocol):
"""Protocol for functions decorated with @prompt."""
__fastmcp__: PromptMeta
def __call__(self, *args: Any, **kwargs: Any) -> Any: ...
@dataclass(frozen=True, kw_only=True)
class PromptMeta:
"""Metadata attached to functions by the @prompt decorator."""
type: Literal["prompt"] = field(default="prompt", init=False)
name: str | None = None
version: str | int | None = None
title: str | None = None
description: str | None = None
icons: list[Icon] | None = None
tags: set[str] | None = None
meta: dict[str, Any] | None = None
task: bool | TaskConfig | None = None
auth: AuthCheck | list[AuthCheck] | None = None
enabled: bool = True
class FunctionPrompt(Prompt):
"""A prompt that is a function."""
fn: SkipJsonSchema[Callable[..., Any]]
@classmethod
def from_function(
cls,
fn: Callable[..., Any],
*,
metadata: PromptMeta | None = None,
# Keep individual params for backwards compat
name: str | None = None,
version: str | int | None = None,
title: str | None = None,
description: str | None = None,
icons: list[Icon] | None = None,
tags: set[str] | None = None,
meta: dict[str, Any] | None = None,
task: bool | TaskConfig | None = None,
auth: AuthCheck | list[AuthCheck] | None = None,
) -> FunctionPrompt:
"""Create a Prompt from a function.
Args:
fn: The function to wrap
metadata: PromptMeta object with all configuration. If provided,
individual parameters must not be passed.
name, title, etc.: Individual parameters for backwards compatibility.
Cannot be used together with metadata parameter.
The function can return:
- str: wrapped as single user Message
- list[Message | str]: converted to list[Message]
- PromptResult: used directly
"""
# Check mutual exclusion
individual_params_provided = any(
x is not None
for x in [name, version, title, description, icons, tags, meta, task, auth]
)
if metadata is not None and individual_params_provided:
raise TypeError(
"Cannot pass both 'metadata' and individual parameters to from_function(). "
"Use metadata alone or individual parameters alone."
)
# Build metadata from kwargs if not provided
if metadata is None:
metadata = PromptMeta(
name=name,
version=version,
title=title,
description=description,
icons=icons,
tags=tags,
meta=meta,
task=task,
auth=auth,
)
func_name = (
metadata.name or getattr(fn, "__name__", None) or fn.__class__.__name__
)
if func_name == "<lambda>":
raise ValueError("You must provide a name for lambda functions")
# Reject functions with *args or **kwargs
sig = inspect.signature(fn)
for param in sig.parameters.values():
if param.kind == inspect.Parameter.VAR_POSITIONAL:
raise ValueError("Functions with *args are not supported as prompts")
if param.kind == inspect.Parameter.VAR_KEYWORD:
raise ValueError("Functions with **kwargs are not supported as prompts")
description = metadata.description or inspect.getdoc(fn)
# Normalize task to TaskConfig and validate
task_value = metadata.task
if task_value is None:
task_config = TaskConfig(mode="forbidden")
elif isinstance(task_value, bool):
task_config = TaskConfig.from_bool(task_value)
else:
task_config = task_value
task_config.validate_function(fn, func_name)
# if the fn is a callable class, we need to get the __call__ method from here out
if not inspect.isroutine(fn) and not isinstance(fn, functools.partial):
fn = fn.__call__
# if the fn is a staticmethod, we need to work with the underlying function
if isinstance(fn, staticmethod):
fn = fn.__func__
# Transform Context type annotations to Depends() for unified DI
fn = transform_context_annotations(fn)
# Wrap fn to handle dependency resolution internally
wrapped_fn = without_injected_parameters(fn)
type_adapter = get_cached_typeadapter(wrapped_fn)
parameters = type_adapter.json_schema()
parameters = compress_schema(parameters, prune_titles=True)
# Convert parameters to PromptArguments
arguments: list[PromptArgument] = []
if "properties" in parameters:
for param_name, param in parameters["properties"].items():
arg_description = param.get("description")
# For non-string parameters, append JSON schema info to help users
# understand the expected format when passing as strings (MCP requirement)
if param_name in sig.parameters:
sig_param = sig.parameters[param_name]
if (
sig_param.annotation != inspect.Parameter.empty
and sig_param.annotation is not str
):
# Get the JSON schema for this specific parameter type
try:
param_adapter = get_cached_typeadapter(sig_param.annotation)
param_schema = param_adapter.json_schema()
# Create compact schema representation
schema_str = json.dumps(param_schema, separators=(",", ":"))
# Append schema info to description
schema_note = f"Provide as a JSON string matching the following schema: {schema_str}"
if arg_description:
arg_description = f"{arg_description}\n\n{schema_note}"
else:
arg_description = schema_note
except Exception as e:
# If schema generation fails, skip enhancement
logger.debug(
"Failed to generate schema for prompt argument %s: %s",
param_name,
e,
)
arguments.append(
PromptArgument(
name=param_name,
description=arg_description,
required=param_name in parameters.get("required", []),
)
)
return cls(
name=func_name,
version=str(metadata.version) if metadata.version is not None else None,
title=metadata.title,
description=description,
icons=metadata.icons,
arguments=arguments,
tags=metadata.tags or set(),
fn=wrapped_fn,
meta=metadata.meta,
task_config=task_config,
auth=metadata.auth,
)
def _convert_string_arguments(self, kwargs: dict[str, Any]) -> dict[str, Any]:
"""Convert string arguments to expected types based on function signature."""
from fastmcp.server.dependencies import without_injected_parameters
wrapper_fn = without_injected_parameters(self.fn)
sig = inspect.signature(wrapper_fn)
converted_kwargs = {}
for param_name, param_value in kwargs.items():
if param_name in sig.parameters:
param = sig.parameters[param_name]
# If parameter has no annotation or annotation is str, pass as-is
if (
param.annotation == inspect.Parameter.empty
or param.annotation is str
) or not isinstance(param_value, str):
converted_kwargs[param_name] = param_value
else:
# Try to convert string argument using type adapter
try:
adapter = get_cached_typeadapter(param.annotation)
# Try JSON parsing first for complex types
try:
converted_kwargs[param_name] = adapter.validate_json(
param_value
)
except (ValueError, TypeError, pydantic_core.ValidationError):
# Fallback to direct validation
converted_kwargs[param_name] = adapter.validate_python(
param_value
)
except (ValueError, TypeError, pydantic_core.ValidationError) as e:
# If conversion fails, provide informative error
raise PromptError(
f"Could not convert argument '{param_name}' with value '{param_value}' "
f"to expected type {param.annotation}. Error: {e}"
) from e
else:
# Parameter not in function signature, pass as-is
converted_kwargs[param_name] = param_value
return converted_kwargs
async def render(
self,
arguments: dict[str, Any] | None = None,
) -> PromptResult:
"""Render the prompt with arguments."""
# Validate required arguments
if self.arguments:
required = {arg.name for arg in self.arguments if arg.required}
provided = set(arguments or {})
missing = required - provided
if missing:
raise ValueError(f"Missing required arguments: {missing}")
try:
# Prepare arguments
kwargs = arguments.copy() if arguments else {}
# Convert string arguments to expected types BEFORE validation
kwargs = self._convert_string_arguments(kwargs)
# Filter out arguments that aren't in the function signature
# This is important for security: dependencies should not be overridable
# from external callers. self.fn is wrapped by without_injected_parameters,
# so we only accept arguments that are in the wrapped function's signature.
sig = inspect.signature(self.fn)
valid_params = set(sig.parameters.keys())
kwargs = {k: v for k, v in kwargs.items() if k in valid_params}
# Use type adapter to validate arguments and handle Field() defaults
# This matches the behavior of tools in function_tool
type_adapter = get_cached_typeadapter(self.fn)
# self.fn is wrapped by without_injected_parameters which handles
# dependency resolution internally
if is_coroutine_function(self.fn):
result = await type_adapter.validate_python(kwargs)
else:
# Run sync functions in threadpool to avoid blocking the event loop
result = await call_sync_fn_in_threadpool(
type_adapter.validate_python, kwargs
)
# Handle sync wrappers that return awaitables (e.g., partial(async_fn))
if inspect.isawaitable(result):
result = await result
return self.convert_result(result)
except Exception as e:
logger.exception(f"Error rendering prompt {self.name}")
raise PromptError(f"Error rendering prompt {self.name}.") from e
def register_with_docket(self, docket: Docket) -> None:
"""Register this prompt with docket for background execution.
FunctionPrompt registers the underlying function, which has the user's
Depends parameters for docket to resolve.
"""
if not self.task_config.supports_tasks():
return
docket.register(self.fn, names=[self.key])
async def add_to_docket(
self,
docket: Docket,
arguments: dict[str, Any] | None,
*,
fn_key: str | None = None,
task_key: str | None = None,
**kwargs: Any,
) -> Execution:
"""Schedule this prompt for background execution via docket.
FunctionPrompt splats the arguments dict since .fn expects **kwargs.
Args:
docket: The Docket instance
arguments: Prompt arguments
fn_key: Function lookup key in Docket registry (defaults to self.key)
task_key: Redis storage key for the result
**kwargs: Additional kwargs passed to docket.add()
"""
lookup_key = fn_key or self.key
if task_key:
kwargs["key"] = task_key
return await docket.add(lookup_key, **kwargs)(**(arguments or {}))
@overload
def prompt(fn: F) -> F: ...
@overload
def prompt(
name_or_fn: str,
*,
version: str | int | None = None,
title: str | None = None,
description: str | None = None,
icons: list[Icon] | None = None,
tags: set[str] | None = None,
meta: dict[str, Any] | None = None,
task: bool | TaskConfig | None = None,
auth: AuthCheck | list[AuthCheck] | None = None,
) -> Callable[[F], F]: ...
@overload
def prompt(
name_or_fn: None = None,
*,
name: str | None = None,
version: str | int | None = None,
title: str | None = None,
description: str | None = None,
icons: list[Icon] | None = None,
tags: set[str] | None = None,
meta: dict[str, Any] | None = None,
task: bool | TaskConfig | None = None,
auth: AuthCheck | list[AuthCheck] | None = None,
) -> Callable[[F], F]: ...
def prompt(
name_or_fn: str | Callable[..., Any] | None = None,
*,
name: str | None = None,
version: str | int | None = None,
title: str | None = None,
description: str | None = None,
icons: list[Icon] | None = None,
tags: set[str] | None = None,
meta: dict[str, Any] | None = None,
task: bool | TaskConfig | None = None,
auth: AuthCheck | list[AuthCheck] | None = None,
) -> Any:
"""Standalone decorator to mark a function as an MCP prompt.
Returns the original function with metadata attached. Register with a server
using mcp.add_prompt().
"""
if isinstance(name_or_fn, classmethod):
raise TypeError(
"To decorate a classmethod, use @classmethod above @prompt. "
"See https://gofastmcp.com/servers/prompts#using-with-methods"
)
def create_prompt(
fn: Callable[..., Any], prompt_name: str | None
) -> FunctionPrompt:
# Create metadata first, then pass it
prompt_meta = PromptMeta(
name=prompt_name,
version=version,
title=title,
description=description,
icons=icons,
tags=tags,
meta=meta,
task=resolve_task_config(task),
auth=auth,
)
return FunctionPrompt.from_function(fn, metadata=prompt_meta)
def attach_metadata(fn: F, prompt_name: str | None) -> F:
metadata = PromptMeta(
name=prompt_name,
version=version,
title=title,
description=description,
icons=icons,
tags=tags,
meta=meta,
task=task,
auth=auth,
)
target = fn.__func__ if hasattr(fn, "__func__") else fn
target.__fastmcp__ = metadata
return fn
def decorator(fn: F, prompt_name: str | None) -> F:
if fastmcp.settings.decorator_mode == "object":
warnings.warn(
"decorator_mode='object' is deprecated and will be removed in a future version. "
"Decorators now return the original function with metadata attached.",
DeprecationWarning,
stacklevel=4,
)
return create_prompt(fn, prompt_name) # type: ignore[return-value]
return attach_metadata(fn, prompt_name)
if inspect.isroutine(name_or_fn):
return decorator(name_or_fn, name)
elif isinstance(name_or_fn, str):
if name is not None:
raise TypeError("Cannot specify name both as first argument and keyword")
prompt_name = name_or_fn
elif name_or_fn is None:
prompt_name = name
else:
raise TypeError(f"Invalid first argument: {type(name_or_fn)}")
def wrapper(fn: F) -> F:
return decorator(fn, prompt_name)
return wrapper
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/prompts/function_prompt.py",
"license": "Apache License 2.0",
"lines": 420,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/resources/function_resource.py | """Standalone @resource decorator for FastMCP."""
from __future__ import annotations
import functools
import inspect
import warnings
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Literal, Protocol, TypeVar, runtime_checkable
from mcp.types import Annotations, Icon
from pydantic import AnyUrl
from pydantic.json_schema import SkipJsonSchema
import fastmcp
from fastmcp.decorators import resolve_task_config
from fastmcp.resources.resource import Resource, ResourceResult
from fastmcp.server.apps import resolve_ui_mime_type
from fastmcp.server.auth.authorization import AuthCheck
from fastmcp.server.dependencies import (
transform_context_annotations,
without_injected_parameters,
)
from fastmcp.server.tasks.config import TaskConfig
from fastmcp.utilities.async_utils import (
call_sync_fn_in_threadpool,
is_coroutine_function,
)
if TYPE_CHECKING:
from docket import Docket
from fastmcp.resources.template import ResourceTemplate
F = TypeVar("F", bound=Callable[..., Any])
@runtime_checkable
class DecoratedResource(Protocol):
"""Protocol for functions decorated with @resource."""
__fastmcp__: ResourceMeta
def __call__(self, *args: Any, **kwargs: Any) -> Any: ...
@dataclass(frozen=True, kw_only=True)
class ResourceMeta:
"""Metadata attached to functions by the @resource decorator."""
type: Literal["resource"] = field(default="resource", init=False)
uri: str
name: str | None = None
version: str | int | None = None
title: str | None = None
description: str | None = None
icons: list[Icon] | None = None
tags: set[str] | None = None
mime_type: str | None = None
annotations: Annotations | None = None
meta: dict[str, Any] | None = None
task: bool | TaskConfig | None = None
auth: AuthCheck | list[AuthCheck] | None = None
enabled: bool = True
class FunctionResource(Resource):
"""A resource that defers data loading by wrapping a function.
The function is only called when the resource is read, allowing for lazy loading
of potentially expensive data. This is particularly useful when listing resources,
as the function won't be called until the resource is actually accessed.
The function can return:
- str for text content (default)
- bytes for binary content
- other types will be converted to JSON
"""
fn: SkipJsonSchema[Callable[..., Any]]
@classmethod
def from_function(
cls,
fn: Callable[..., Any],
uri: str | AnyUrl | None = None,
*,
metadata: ResourceMeta | None = None,
# Keep individual params for backwards compat
name: str | None = None,
version: str | int | None = None,
title: str | None = None,
description: str | None = None,
icons: list[Icon] | None = None,
mime_type: str | None = None,
tags: set[str] | None = None,
annotations: Annotations | None = None,
meta: dict[str, Any] | None = None,
task: bool | TaskConfig | None = None,
auth: AuthCheck | list[AuthCheck] | None = None,
) -> FunctionResource:
"""Create a FunctionResource from a function.
Args:
fn: The function to wrap
uri: The URI for the resource (required if metadata not provided)
metadata: ResourceMeta object with all configuration. If provided,
individual parameters must not be passed.
name, title, etc.: Individual parameters for backwards compatibility.
Cannot be used together with metadata parameter.
"""
# Check mutual exclusion
individual_params_provided = (
any(
x is not None
for x in [
name,
version,
title,
description,
icons,
mime_type,
tags,
annotations,
meta,
task,
auth,
]
)
or uri is not None
)
if metadata is not None and individual_params_provided:
raise TypeError(
"Cannot pass both 'metadata' and individual parameters to from_function(). "
"Use metadata alone or individual parameters alone."
)
# Build metadata from kwargs if not provided
if metadata is None:
if uri is None:
raise TypeError("uri is required when metadata is not provided")
metadata = ResourceMeta(
uri=str(uri),
name=name,
version=version,
title=title,
description=description,
icons=icons,
tags=tags,
mime_type=mime_type,
annotations=annotations,
meta=meta,
task=task,
auth=auth,
)
uri_obj = AnyUrl(metadata.uri)
# Get function name - use class name for callable objects
func_name = (
metadata.name or getattr(fn, "__name__", None) or fn.__class__.__name__
)
# Normalize task to TaskConfig and validate
task_value = metadata.task
if task_value is None:
task_config = TaskConfig(mode="forbidden")
elif isinstance(task_value, bool):
task_config = TaskConfig.from_bool(task_value)
else:
task_config = task_value
task_config.validate_function(fn, func_name)
# if the fn is a callable class, we need to get the __call__ method from here out
if not inspect.isroutine(fn) and not isinstance(fn, functools.partial):
fn = fn.__call__
# if the fn is a staticmethod, we need to work with the underlying function
if isinstance(fn, staticmethod):
fn = fn.__func__
# Transform Context type annotations to Depends() for unified DI
fn = transform_context_annotations(fn)
# Wrap fn to handle dependency resolution internally
wrapped_fn = without_injected_parameters(fn)
# Apply ui:// MIME default, then fall back to text/plain
resolved_mime = resolve_ui_mime_type(metadata.uri, metadata.mime_type)
return cls(
fn=wrapped_fn,
uri=uri_obj,
name=func_name,
version=str(metadata.version) if metadata.version is not None else None,
title=metadata.title,
description=metadata.description or inspect.getdoc(fn),
icons=metadata.icons,
mime_type=resolved_mime or "text/plain",
tags=metadata.tags or set(),
annotations=metadata.annotations,
meta=metadata.meta,
task_config=task_config,
auth=metadata.auth,
)
async def read(
self,
) -> str | bytes | ResourceResult:
"""Read the resource by calling the wrapped function."""
# self.fn is wrapped by without_injected_parameters which handles
# dependency resolution internally
if is_coroutine_function(self.fn):
result = await self.fn()
else:
# Run sync functions in threadpool to avoid blocking the event loop
result = await call_sync_fn_in_threadpool(self.fn)
# Handle sync wrappers that return awaitables (e.g., partial(async_fn))
if inspect.isawaitable(result):
result = await result
# If user returned another Resource, read it recursively
if isinstance(result, Resource):
return await result.read()
return result
def register_with_docket(self, docket: Docket) -> None:
"""Register this resource with docket for background execution.
FunctionResource registers the underlying function, which has the user's
Depends parameters for docket to resolve.
"""
if not self.task_config.supports_tasks():
return
docket.register(self.fn, names=[self.key])
def resource(
uri: str,
*,
name: str | None = None,
version: str | int | None = None,
title: str | None = None,
description: str | None = None,
icons: list[Icon] | None = None,
mime_type: str | None = None,
tags: set[str] | None = None,
annotations: Annotations | dict[str, Any] | None = None,
meta: dict[str, Any] | None = None,
task: bool | TaskConfig | None = None,
auth: AuthCheck | list[AuthCheck] | None = None,
) -> Callable[[F], F]:
"""Standalone decorator to mark a function as an MCP resource.
Returns the original function with metadata attached. Register with a server
using mcp.add_resource().
"""
if isinstance(annotations, dict):
annotations = Annotations(**annotations)
if inspect.isroutine(uri):
raise TypeError(
"The @resource decorator requires a URI. "
"Use @resource('uri') instead of @resource"
)
def create_resource(fn: Callable[..., Any]) -> FunctionResource | ResourceTemplate:
from fastmcp.resources.template import ResourceTemplate
from fastmcp.server.dependencies import without_injected_parameters
resolved = resolve_task_config(task)
has_uri_params = "{" in uri and "}" in uri
wrapper_fn = without_injected_parameters(fn)
has_func_params = bool(inspect.signature(wrapper_fn).parameters)
# Create metadata first
resource_meta = ResourceMeta(
uri=uri,
name=name,
version=version,
title=title,
description=description,
icons=icons,
tags=tags,
mime_type=mime_type,
annotations=annotations,
meta=meta,
task=resolved,
auth=auth,
)
if has_uri_params or has_func_params:
# ResourceTemplate doesn't have metadata support yet, so pass individual params
return ResourceTemplate.from_function(
fn=fn,
uri_template=uri,
name=name,
version=version,
title=title,
description=description,
icons=icons,
mime_type=mime_type,
tags=tags,
annotations=annotations,
meta=meta,
task=resolved,
auth=auth,
)
else:
return FunctionResource.from_function(fn, metadata=resource_meta)
def attach_metadata(fn: F) -> F:
metadata = ResourceMeta(
uri=uri,
name=name,
version=version,
title=title,
description=description,
icons=icons,
tags=tags,
mime_type=mime_type,
annotations=annotations,
meta=meta,
task=task,
auth=auth,
)
target = fn.__func__ if hasattr(fn, "__func__") else fn
target.__fastmcp__ = metadata
return fn
def decorator(fn: F) -> F:
if fastmcp.settings.decorator_mode == "object":
warnings.warn(
"decorator_mode='object' is deprecated and will be removed in a future version. "
"Decorators now return the original function with metadata attached.",
DeprecationWarning,
stacklevel=3,
)
return create_resource(fn) # type: ignore[return-value]
return attach_metadata(fn)
return decorator
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/resources/function_resource.py",
"license": "Apache License 2.0",
"lines": 297,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:src/fastmcp/tools/function_tool.py | """Standalone @tool decorator for FastMCP."""
from __future__ import annotations
import inspect
import warnings
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import (
TYPE_CHECKING,
Annotated,
Any,
Literal,
Protocol,
TypeVar,
overload,
runtime_checkable,
)
import anyio
import mcp.types
from mcp.shared.exceptions import McpError
from mcp.types import ErrorData, Icon, ToolAnnotations, ToolExecution
from pydantic import Field
from pydantic.json_schema import SkipJsonSchema
import fastmcp
from fastmcp.decorators import resolve_task_config
from fastmcp.server.auth.authorization import AuthCheck
from fastmcp.server.dependencies import without_injected_parameters
from fastmcp.server.tasks.config import TaskConfig
from fastmcp.tools.function_parsing import ParsedFunction, _is_object_schema
from fastmcp.tools.tool import (
Tool,
ToolResult,
ToolResultSerializerType,
)
from fastmcp.utilities.async_utils import (
call_sync_fn_in_threadpool,
is_coroutine_function,
)
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import (
NotSet,
NotSetT,
get_cached_typeadapter,
)
logger = get_logger(__name__)
if TYPE_CHECKING:
from docket import Docket
from docket.execution import Execution
F = TypeVar("F", bound=Callable[..., Any])
@runtime_checkable
class DecoratedTool(Protocol):
"""Protocol for functions decorated with @tool."""
__fastmcp__: ToolMeta
def __call__(self, *args: Any, **kwargs: Any) -> Any: ...
@dataclass(frozen=True, kw_only=True)
class ToolMeta:
"""Metadata attached to functions by the @tool decorator."""
type: Literal["tool"] = field(default="tool", init=False)
name: str | None = None
version: str | int | None = None
title: str | None = None
description: str | None = None
icons: list[Icon] | None = None
tags: set[str] | None = None
output_schema: dict[str, Any] | NotSetT | None = NotSet
annotations: ToolAnnotations | None = None
meta: dict[str, Any] | None = None
app: Any = None
task: bool | TaskConfig | None = None
exclude_args: list[str] | None = None
serializer: Any | None = None
timeout: float | None = None
auth: AuthCheck | list[AuthCheck] | None = None
enabled: bool = True
class FunctionTool(Tool):
fn: SkipJsonSchema[Callable[..., Any]]
return_type: Annotated[SkipJsonSchema[Any], Field(exclude=True)] = None
def to_mcp_tool(
self,
**overrides: Any,
) -> mcp.types.Tool:
"""Convert the FastMCP tool to an MCP tool.
Extends the base implementation to add task execution mode if enabled.
"""
# Get base MCP tool from parent
mcp_tool = super().to_mcp_tool(**overrides)
# Add task execution mode per SEP-1686
# Only set execution if not overridden and task execution is supported
if self.task_config.supports_tasks() and "execution" not in overrides:
mcp_tool.execution = ToolExecution(taskSupport=self.task_config.mode)
return mcp_tool
@classmethod
def from_function(
cls,
fn: Callable[..., Any],
*,
metadata: ToolMeta | None = None,
# Keep individual params for backwards compat
name: str | None = None,
version: str | int | None = None,
title: str | None = None,
description: str | None = None,
icons: list[Icon] | None = None,
tags: set[str] | None = None,
annotations: ToolAnnotations | None = None,
exclude_args: list[str] | None = None,
output_schema: dict[str, Any] | NotSetT | None = NotSet,
serializer: ToolResultSerializerType | None = None,
meta: dict[str, Any] | None = None,
task: bool | TaskConfig | None = None,
timeout: float | None = None,
auth: AuthCheck | list[AuthCheck] | None = None,
) -> FunctionTool:
"""Create a FunctionTool from a function.
Args:
fn: The function to wrap
metadata: ToolMeta object with all configuration. If provided,
individual parameters must not be passed.
name, title, etc.: Individual parameters for backwards compatibility.
Cannot be used together with metadata parameter.
"""
# Check mutual exclusion
individual_params_provided = (
any(
x is not None and x is not NotSet
for x in [
name,
version,
title,
description,
icons,
tags,
annotations,
meta,
task,
serializer,
timeout,
auth,
]
)
or output_schema is not NotSet
or exclude_args is not None
)
if metadata is not None and individual_params_provided:
raise TypeError(
"Cannot pass both 'metadata' and individual parameters to from_function(). "
"Use metadata alone or individual parameters alone."
)
# Build metadata from kwargs if not provided
if metadata is None:
metadata = ToolMeta(
name=name,
version=version,
title=title,
description=description,
icons=icons,
tags=tags,
output_schema=output_schema,
annotations=annotations,
meta=meta,
task=task,
exclude_args=exclude_args,
serializer=serializer,
timeout=timeout,
auth=auth,
)
if metadata.serializer is not None and fastmcp.settings.deprecation_warnings:
warnings.warn(
"The `serializer` parameter is deprecated. "
"Return ToolResult from your tools for full control over serialization. "
"See https://gofastmcp.com/servers/tools#custom-serialization for migration examples.",
DeprecationWarning,
stacklevel=2,
)
if metadata.exclude_args and fastmcp.settings.deprecation_warnings:
warnings.warn(
"The `exclude_args` parameter is deprecated as of FastMCP 2.14. "
"Use dependency injection with `Depends()` instead for better lifecycle management. "
"See https://gofastmcp.com/servers/dependency-injection#using-depends for examples.",
DeprecationWarning,
stacklevel=2,
)
parsed_fn = ParsedFunction.from_function(fn, exclude_args=metadata.exclude_args)
func_name = metadata.name or parsed_fn.name
if func_name == "<lambda>":
raise ValueError("You must provide a name for lambda functions")
# Normalize task to TaskConfig
task_value = metadata.task
if task_value is None:
task_config = TaskConfig(mode="forbidden")
elif isinstance(task_value, bool):
task_config = TaskConfig.from_bool(task_value)
else:
task_config = task_value
task_config.validate_function(fn, func_name)
# Handle output_schema
if isinstance(metadata.output_schema, NotSetT):
final_output_schema = parsed_fn.output_schema
else:
final_output_schema = metadata.output_schema
if final_output_schema is not None and isinstance(final_output_schema, dict):
if not _is_object_schema(final_output_schema):
raise ValueError(
f"Output schemas must represent object types due to MCP spec limitations. "
f"Received: {final_output_schema!r}"
)
return cls(
fn=parsed_fn.fn,
return_type=parsed_fn.return_type,
name=metadata.name or parsed_fn.name,
version=str(metadata.version) if metadata.version is not None else None,
title=metadata.title,
description=metadata.description or parsed_fn.description,
icons=metadata.icons,
parameters=parsed_fn.input_schema,
output_schema=final_output_schema,
annotations=metadata.annotations,
tags=metadata.tags or set(),
serializer=metadata.serializer,
meta=metadata.meta,
task_config=task_config,
timeout=metadata.timeout,
auth=metadata.auth,
)
async def run(self, arguments: dict[str, Any]) -> ToolResult:
"""Run the tool with arguments."""
wrapper_fn = without_injected_parameters(self.fn)
type_adapter = get_cached_typeadapter(wrapper_fn)
# Apply timeout if configured
if self.timeout is not None:
try:
with anyio.fail_after(self.timeout):
# Thread pool execution for sync functions, direct await for async
if is_coroutine_function(wrapper_fn):
result = await type_adapter.validate_python(arguments)
else:
# Sync function: run in threadpool to avoid blocking
result = await call_sync_fn_in_threadpool(
type_adapter.validate_python, arguments
)
# Handle sync wrappers that return awaitables
if inspect.isawaitable(result):
result = await result
except TimeoutError:
logger.warning(
f"Tool '{self.name}' timed out after {self.timeout}s. "
f"Consider using task=True for long-running operations. "
f"See https://gofastmcp.com/servers/tasks"
)
raise McpError(
ErrorData(
code=-32000,
message=f"Tool '{self.name}' execution timed out after {self.timeout}s",
)
) from None
else:
# No timeout: use existing execution path
if is_coroutine_function(wrapper_fn):
result = await type_adapter.validate_python(arguments)
else:
result = await call_sync_fn_in_threadpool(
type_adapter.validate_python, arguments
)
if inspect.isawaitable(result):
result = await result
return self.convert_result(result)
def register_with_docket(self, docket: Docket) -> None:
"""Register this tool with docket for background execution.
FunctionTool registers the underlying function, which has the user's
Depends parameters for docket to resolve.
"""
if not self.task_config.supports_tasks():
return
docket.register(self.fn, names=[self.key])
async def add_to_docket(
self,
docket: Docket,
arguments: dict[str, Any],
*,
fn_key: str | None = None,
task_key: str | None = None,
**kwargs: Any,
) -> Execution:
"""Schedule this tool for background execution via docket.
FunctionTool splats the arguments dict since .fn expects **kwargs.
Args:
docket: The Docket instance
arguments: Tool arguments
fn_key: Function lookup key in Docket registry (defaults to self.key)
task_key: Redis storage key for the result
**kwargs: Additional kwargs passed to docket.add()
"""
lookup_key = fn_key or self.key
if task_key:
kwargs["key"] = task_key
return await docket.add(lookup_key, **kwargs)(**arguments)
@overload
def tool(fn: F) -> F: ...
@overload
def tool(
name_or_fn: str,
*,
version: str | int | None = None,
title: str | None = None,
description: str | None = None,
icons: list[Icon] | None = None,
tags: set[str] | None = None,
output_schema: dict[str, Any] | NotSetT | None = NotSet,
annotations: ToolAnnotations | dict[str, Any] | None = None,
meta: dict[str, Any] | None = None,
task: bool | TaskConfig | None = None,
exclude_args: list[str] | None = None,
serializer: Any | None = None,
timeout: float | None = None,
auth: AuthCheck | list[AuthCheck] | None = None,
) -> Callable[[F], F]: ...
@overload
def tool(
name_or_fn: None = None,
*,
name: str | None = None,
version: str | int | None = None,
title: str | None = None,
description: str | None = None,
icons: list[Icon] | None = None,
tags: set[str] | None = None,
output_schema: dict[str, Any] | NotSetT | None = NotSet,
annotations: ToolAnnotations | dict[str, Any] | None = None,
meta: dict[str, Any] | None = None,
task: bool | TaskConfig | None = None,
exclude_args: list[str] | None = None,
serializer: Any | None = None,
timeout: float | None = None,
auth: AuthCheck | list[AuthCheck] | None = None,
) -> Callable[[F], F]: ...
def tool(
name_or_fn: str | Callable[..., Any] | None = None,
*,
name: str | None = None,
version: str | int | None = None,
title: str | None = None,
description: str | None = None,
icons: list[Icon] | None = None,
tags: set[str] | None = None,
output_schema: dict[str, Any] | NotSetT | None = NotSet,
annotations: ToolAnnotations | dict[str, Any] | None = None,
meta: dict[str, Any] | None = None,
task: bool | TaskConfig | None = None,
exclude_args: list[str] | None = None,
serializer: Any | None = None,
timeout: float | None = None,
auth: AuthCheck | list[AuthCheck] | None = None,
) -> Any:
"""Standalone decorator to mark a function as an MCP tool.
Returns the original function with metadata attached. Register with a server
using mcp.add_tool().
"""
if isinstance(annotations, dict):
annotations = ToolAnnotations(**annotations)
if isinstance(name_or_fn, classmethod):
raise TypeError(
"To decorate a classmethod, use @classmethod above @tool. "
"See https://gofastmcp.com/servers/tools#using-with-methods"
)
def create_tool(fn: Callable[..., Any], tool_name: str | None) -> FunctionTool:
# Create metadata first, then pass it
tool_meta = ToolMeta(
name=tool_name,
version=version,
title=title,
description=description,
icons=icons,
tags=tags,
output_schema=output_schema,
annotations=annotations,
meta=meta,
task=resolve_task_config(task),
exclude_args=exclude_args,
serializer=serializer,
timeout=timeout,
auth=auth,
)
return FunctionTool.from_function(fn, metadata=tool_meta)
def attach_metadata(fn: F, tool_name: str | None) -> F:
metadata = ToolMeta(
name=tool_name,
version=version,
title=title,
description=description,
icons=icons,
tags=tags,
output_schema=output_schema,
annotations=annotations,
meta=meta,
task=task,
exclude_args=exclude_args,
serializer=serializer,
timeout=timeout,
auth=auth,
)
target = fn.__func__ if hasattr(fn, "__func__") else fn
target.__fastmcp__ = metadata
return fn
def decorator(fn: F, tool_name: str | None) -> F:
if fastmcp.settings.decorator_mode == "object":
warnings.warn(
"decorator_mode='object' is deprecated and will be removed in a future version. "
"Decorators now return the original function with metadata attached.",
DeprecationWarning,
stacklevel=4,
)
return create_tool(fn, tool_name) # type: ignore[return-value]
return attach_metadata(fn, tool_name)
if inspect.isroutine(name_or_fn):
return decorator(name_or_fn, name)
elif isinstance(name_or_fn, str):
if name is not None:
raise TypeError("Cannot specify name both as first argument and keyword")
tool_name = name_or_fn
elif name_or_fn is None:
tool_name = name
else:
raise TypeError(f"Invalid first argument: {type(name_or_fn)}")
def wrapper(fn: F) -> F:
return decorator(fn, tool_name)
return wrapper
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "src/fastmcp/tools/function_tool.py",
"license": "Apache License 2.0",
"lines": 425,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
PrefectHQ/fastmcp:tests/deprecated/test_function_component_imports.py | """Test that deprecated import paths for function components still work."""
import warnings
import pytest
from fastmcp.utilities.tests import temporary_settings
class TestDeprecatedFunctionToolImports:
def test_function_tool_from_tool_module(self):
with temporary_settings(deprecation_warnings=True):
with pytest.warns(
DeprecationWarning, match="Import from fastmcp.tools.function_tool"
):
from fastmcp.tools.tool import FunctionTool
# Verify it's the real class
from fastmcp.tools.function_tool import (
FunctionTool as CanonicalFunctionTool,
)
assert FunctionTool is CanonicalFunctionTool
def test_parsed_function_from_tool_module(self):
with temporary_settings(deprecation_warnings=True):
with pytest.warns(
DeprecationWarning, match="Import from fastmcp.tools.function_tool"
):
from fastmcp.tools.tool import ParsedFunction
from fastmcp.tools.function_tool import (
ParsedFunction as CanonicalParsedFunction,
)
assert ParsedFunction is CanonicalParsedFunction
def test_tool_decorator_from_tool_module(self):
with temporary_settings(deprecation_warnings=True):
with pytest.warns(
DeprecationWarning, match="Import from fastmcp.tools.function_tool"
):
from fastmcp.tools.tool import tool
from fastmcp.tools.function_tool import tool as canonical_tool
assert tool is canonical_tool
def test_no_warning_when_disabled(self):
with temporary_settings(deprecation_warnings=False):
with warnings.catch_warnings():
warnings.simplefilter("error")
from fastmcp.tools.tool import FunctionTool # noqa: F401
class TestDeprecatedFunctionResourceImports:
def test_function_resource_from_resource_module(self):
with temporary_settings(deprecation_warnings=True):
with pytest.warns(
DeprecationWarning,
match="Import from fastmcp.resources.function_resource",
):
from fastmcp.resources.resource import FunctionResource
from fastmcp.resources.function_resource import (
FunctionResource as CanonicalFunctionResource,
)
assert FunctionResource is CanonicalFunctionResource
def test_resource_decorator_from_resource_module(self):
with temporary_settings(deprecation_warnings=True):
with pytest.warns(
DeprecationWarning,
match="Import from fastmcp.resources.function_resource",
):
from fastmcp.resources.resource import resource
from fastmcp.resources.function_resource import (
resource as canonical_resource,
)
assert resource is canonical_resource
def test_no_warning_when_disabled(self):
with temporary_settings(deprecation_warnings=False):
with warnings.catch_warnings():
warnings.simplefilter("error")
from fastmcp.resources.resource import FunctionResource # noqa: F401
class TestDeprecatedFunctionPromptImports:
def test_function_prompt_from_prompt_module(self):
with temporary_settings(deprecation_warnings=True):
with pytest.warns(
DeprecationWarning, match="Import from fastmcp.prompts.function_prompt"
):
from fastmcp.prompts.prompt import FunctionPrompt
from fastmcp.prompts.function_prompt import (
FunctionPrompt as CanonicalFunctionPrompt,
)
assert FunctionPrompt is CanonicalFunctionPrompt
def test_prompt_decorator_from_prompt_module(self):
with temporary_settings(deprecation_warnings=True):
with pytest.warns(
DeprecationWarning, match="Import from fastmcp.prompts.function_prompt"
):
from fastmcp.prompts.prompt import prompt
from fastmcp.prompts.function_prompt import prompt as canonical_prompt
assert prompt is canonical_prompt
def test_no_warning_when_disabled(self):
with temporary_settings(deprecation_warnings=False):
with warnings.catch_warnings():
warnings.simplefilter("error")
from fastmcp.prompts.prompt import FunctionPrompt # noqa: F401
| {
"repo_id": "PrefectHQ/fastmcp",
"file_path": "tests/deprecated/test_function_component_imports.py",
"license": "Apache License 2.0",
"lines": 91,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.