sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
PaddlePaddle/PaddleOCR:tests/testing_utils.py
from pathlib import Path TEST_DATA_DIR = Path(__file__).parent / "test_files" def check_simple_inference_result(result, *, expected_length=1): assert result is not None assert isinstance(result, list) assert len(result) == expected_length for res in result: assert isinstance(res, dict) def check_wrapper_simple_inference_param_forwarding( monkeypatch, wrapper, wrapped_obj_attr_name, input, params, ): def _dummy_predict(input, **params): yield params monkeypatch.setattr( getattr(wrapper, wrapped_obj_attr_name), "predict", _dummy_predict ) result = getattr(wrapper, "predict")( input, **params, ) assert isinstance(result, list) assert len(result) == 1 for k, v in params.items(): assert result[0][k] == v
{ "repo_id": "PaddlePaddle/PaddleOCR", "file_path": "tests/testing_utils.py", "license": "Apache License 2.0", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/deprecated/test_tool_injection_middleware.py
"""Tests for deprecated PromptToolMiddleware and ResourceToolMiddleware.""" import pytest from inline_snapshot import snapshot from mcp.types import TextContent from mcp.types import Tool as SDKTool from fastmcp import FastMCP from fastmcp.client import Client from fastmcp.client.client import CallToolResult from fastmcp.client.transports import FastMCPTransport from fastmcp.server.middleware.tool_injection import ( PromptToolMiddleware, ResourceToolMiddleware, ) class TestPromptToolMiddleware: """Tests for PromptToolMiddleware.""" @pytest.fixture def server_with_prompts(self): """Create a FastMCP server with prompts.""" mcp = FastMCP("PromptServer") @mcp.tool def add(a: int, b: int) -> int: """Add two numbers.""" return a + b @mcp.prompt def greeting(name: str) -> str: """Generate a greeting message.""" return f"Hello, {name}!" @mcp.prompt def farewell(name: str) -> str: """Generate a farewell message.""" return f"Goodbye, {name}!" return mcp async def test_prompt_tools_added_to_list(self, server_with_prompts: FastMCP): """Test that prompt tools are added to the tool list.""" middleware = PromptToolMiddleware() server_with_prompts.add_middleware(middleware) async with Client[FastMCPTransport](server_with_prompts) as client: tools: list[SDKTool] = await client.list_tools() tool_names: list[str] = [tool.name for tool in tools] # Should have: add, list_prompts, get_prompt assert len(tools) == 3 assert "add" in tool_names assert "list_prompts" in tool_names assert "get_prompt" in tool_names async def test_list_prompts_tool_works(self, server_with_prompts: FastMCP): """Test that the list_prompts tool can be called.""" middleware = PromptToolMiddleware() server_with_prompts.add_middleware(middleware) async with Client[FastMCPTransport](server_with_prompts) as client: result: CallToolResult = await client.call_tool( name="list_prompts", arguments={} ) assert result.content == snapshot( [ TextContent( type="text", text='[{"name":"greeting","title":null,"description":"Generate a greeting message.","arguments":[{"name":"name","description":null,"required":true}],"icons":null,"_meta":{"fastmcp":{"tags":[]}}},{"name":"farewell","title":null,"description":"Generate a farewell message.","arguments":[{"name":"name","description":null,"required":true}],"icons":null,"_meta":{"fastmcp":{"tags":[]}}}]', ) ] ) assert result.structured_content is not None assert result.structured_content["result"] == snapshot( [ { "name": "greeting", "title": None, "description": "Generate a greeting message.", "arguments": [ {"name": "name", "description": None, "required": True} ], "icons": None, "_meta": {"fastmcp": {"tags": []}}, }, { "name": "farewell", "title": None, "description": "Generate a farewell message.", "arguments": [ {"name": "name", "description": None, "required": True} ], "icons": None, "_meta": {"fastmcp": {"tags": []}}, }, ] ) async def test_get_prompt_tool_works(self, server_with_prompts: FastMCP): """Test that the get_prompt tool can be called.""" middleware = PromptToolMiddleware() server_with_prompts.add_middleware(middleware) async with Client[FastMCPTransport](server_with_prompts) as client: result: CallToolResult = await client.call_tool( name="get_prompt", arguments={"name": "greeting", "arguments": {"name": "World"}}, ) # The tool returns the prompt result with structured_content assert result.content == snapshot( [ TextContent( type="text", text='{"_meta":null,"description":"Generate a greeting message.","messages":[{"role":"user","content":{"type":"text","text":"Hello, World!","annotations":null,"_meta":null}}]}', ) ] ) assert result.structured_content is not None assert result.structured_content == snapshot( { "_meta": None, "description": "Generate a greeting message.", "messages": [ { "role": "user", "content": { "type": "text", "text": "Hello, World!", "annotations": None, "_meta": None, }, } ], } ) class TestResourceToolMiddleware: """Tests for ResourceToolMiddleware.""" @pytest.fixture def server_with_resources(self): """Create a FastMCP server with resources.""" mcp = FastMCP("ResourceServer") @mcp.tool def add(a: int, b: int) -> int: """Add two numbers.""" return a + b @mcp.resource("file://config.txt") def config_resource() -> str: """Get configuration.""" return "debug=true" @mcp.resource("file://data.json") def data_resource() -> str: """Get data.""" return '{"count": 42}' return mcp async def test_resource_tools_added_to_list(self, server_with_resources: FastMCP): """Test that resource tools are added to the tool list.""" middleware = ResourceToolMiddleware() server_with_resources.add_middleware(middleware) async with Client[FastMCPTransport](server_with_resources) as client: tools: list[SDKTool] = await client.list_tools() tool_names: list[str] = [tool.name for tool in tools] # Should have: add, list_resources, read_resource assert len(tools) == 3 assert "add" in tool_names assert "list_resources" in tool_names assert "read_resource" in tool_names async def test_list_resources_tool_works(self, server_with_resources: FastMCP): """Test that the list_resources tool can be called.""" middleware = ResourceToolMiddleware() server_with_resources.add_middleware(middleware) async with Client[FastMCPTransport](server_with_resources) as client: result: CallToolResult = await client.call_tool( name="list_resources", arguments={} ) assert result.structured_content is not None assert result.structured_content["result"] == snapshot( [ { "name": "config_resource", "title": None, "uri": "file://config.txt/", "description": "Get configuration.", "mimeType": "text/plain", "size": None, "icons": None, "annotations": None, "_meta": {"fastmcp": {"tags": []}}, }, { "name": "data_resource", "title": None, "uri": "file://data.json/", "description": "Get data.", "mimeType": "text/plain", "size": None, "icons": None, "annotations": None, "_meta": {"fastmcp": {"tags": []}}, }, ] ) async def test_read_resource_tool_works(self, server_with_resources: FastMCP): """Test that the read_resource tool can be called.""" middleware = ResourceToolMiddleware() server_with_resources.add_middleware(middleware) async with Client[FastMCPTransport](server_with_resources) as client: result: CallToolResult = await client.call_tool( name="read_resource", arguments={"uri": "file://config.txt"} ) assert result.content == snapshot( [ TextContent( type="text", text='{"contents":[{"content":"debug=true","mime_type":"text/plain","meta":null}],"meta":null}', ) ] ) assert result.structured_content == snapshot( { "contents": [ {"content": "debug=true", "mime_type": "text/plain", "meta": None} ], "meta": None, } )
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/deprecated/test_tool_injection_middleware.py", "license": "Apache License 2.0", "lines": 211, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/experimental/transforms/test_code_mode_discovery.py
import json from typing import Any from mcp.types import TextContent from fastmcp import FastMCP from fastmcp.experimental.transforms.code_mode import ( CodeMode, GetTags, ListTools, Search, _ensure_async, ) from fastmcp.tools.tool import ToolResult def _unwrap_result(result: ToolResult) -> Any: """Extract the logical return value from a ToolResult.""" if result.structured_content is not None: return result.structured_content text_blocks = [ content.text for content in result.content if isinstance(content, TextContent) ] if not text_blocks: return None if len(text_blocks) == 1: try: return json.loads(text_blocks[0]) except json.JSONDecodeError: return text_blocks[0] values: list[Any] = [] for text in text_blocks: try: values.append(json.loads(text)) except json.JSONDecodeError: values.append(text) return values def _unwrap_string_result(result: ToolResult) -> str: """Extract a string result from a ToolResult.""" data = _unwrap_result(result) if isinstance(data, dict) and "result" in data: return data["result"] assert isinstance(data, str) return data class _UnsafeTestSandboxProvider: """UNSAFE: Uses exec() for testing only. Never use in production.""" async def run( self, code: str, *, inputs: dict[str, Any] | None = None, external_functions: dict[str, Any] | None = None, ) -> Any: namespace: dict[str, Any] = {} if inputs: namespace.update(inputs) if external_functions: namespace.update( {key: _ensure_async(value) for key, value in external_functions.items()} ) wrapped = "async def __test_main__():\n" for line in code.splitlines(): wrapped += f" {line}\n" if not code.strip(): wrapped += " return None\n" exec(wrapped, namespace, namespace) return await namespace["__test_main__"]() async def _run_tool( server: FastMCP, name: str, arguments: dict[str, Any] ) -> ToolResult: return await server.call_tool(name, arguments) # --------------------------------------------------------------------------- # Tags discovery tool # --------------------------------------------------------------------------- async def test_categories_brief_shows_tag_counts() -> None: mcp = FastMCP("Tags Brief") @mcp.tool(tags={"math"}) def add(x: int, y: int) -> int: return x + y @mcp.tool(tags={"math"}) def multiply(x: int, y: int) -> int: return x * y @mcp.tool(tags={"text"}) def greet(name: str) -> str: return f"Hello, {name}!" mcp.add_transform( CodeMode( discovery_tools=[GetTags()], sandbox_provider=_UnsafeTestSandboxProvider(), ) ) result = await _run_tool(mcp, "tags", {}) text = _unwrap_string_result(result) assert "math (2 tools)" in text assert "text (1 tool)" in text async def test_categories_full_lists_tools_per_tag() -> None: mcp = FastMCP("Tags Full") @mcp.tool(tags={"math"}) def add(x: int, y: int) -> int: """Add two numbers.""" return x + y @mcp.tool(tags={"text"}) def greet(name: str) -> str: """Say hello.""" return f"Hello, {name}!" mcp.add_transform( CodeMode( discovery_tools=[GetTags(default_detail="full")], sandbox_provider=_UnsafeTestSandboxProvider(), ) ) result = await _run_tool(mcp, "tags", {}) text = _unwrap_string_result(result) assert "### math" in text assert "- add: Add two numbers." in text assert "### text" in text assert "- greet: Say hello." in text async def test_categories_includes_untagged() -> None: mcp = FastMCP("Tags Untagged") @mcp.tool(tags={"math"}) def add(x: int, y: int) -> int: return x + y @mcp.tool def ping() -> str: return "pong" mcp.add_transform( CodeMode( discovery_tools=[GetTags()], sandbox_provider=_UnsafeTestSandboxProvider(), ) ) result = await _run_tool(mcp, "tags", {}) text = _unwrap_string_result(result) assert "math" in text assert "untagged (1 tool)" in text async def test_categories_tool_in_multiple_tags() -> None: mcp = FastMCP("Tags Multi-tag") @mcp.tool(tags={"math", "core"}) def add(x: int, y: int) -> int: return x + y mcp.add_transform( CodeMode( discovery_tools=[GetTags(default_detail="full")], sandbox_provider=_UnsafeTestSandboxProvider(), ) ) result = await _run_tool(mcp, "tags", {}) text = _unwrap_string_result(result) assert "### core" in text assert "### math" in text # Tool appears under both tags assert text.count("- add") == 2 async def test_categories_detail_override_per_call() -> None: """LLM can override default_detail on a per-call basis.""" mcp = FastMCP("Tags Override") @mcp.tool(tags={"math"}) def add(x: int, y: int) -> int: """Add numbers.""" return x + y mcp.add_transform( CodeMode( discovery_tools=[GetTags()], # default_detail="brief" sandbox_provider=_UnsafeTestSandboxProvider(), ) ) # Override to full result = await _run_tool(mcp, "tags", {"detail": "full"}) text = _unwrap_string_result(result) assert "### math" in text assert "- add: Add numbers." in text async def test_get_tags_empty_catalog() -> None: """GetTags with no tools returns 'No tools available.'.""" mcp = FastMCP("CodeMode Empty Tags") mcp.disable(names={"ping"}, components={"tool"}) mcp.add_transform( CodeMode( discovery_tools=[GetTags()], sandbox_provider=_UnsafeTestSandboxProvider(), ) ) result = await _run_tool(mcp, "tags", {}) text = _unwrap_string_result(result) assert "No tools available" in text # --------------------------------------------------------------------------- # Search with tags filtering # --------------------------------------------------------------------------- async def test_search_with_tags_filter() -> None: mcp = FastMCP("Search Tags") @mcp.tool(tags={"math"}) def add(x: int, y: int) -> int: """Add two numbers.""" return x + y @mcp.tool(tags={"text"}) def greet(name: str) -> str: """Say hello.""" return f"Hello, {name}!" mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool(mcp, "search", {"query": "add hello", "tags": ["math"]}) text = _unwrap_string_result(result) assert "add" in text assert "greet" not in text async def test_search_with_tags_filter_no_matches() -> None: mcp = FastMCP("Search Tags Empty") @mcp.tool(tags={"math"}) def add(x: int, y: int) -> int: """Add two numbers.""" return x + y mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool(mcp, "search", {"query": "add", "tags": ["nonexistent"]}) text = _unwrap_string_result(result) assert "add" not in text or "No tools" in text async def test_search_without_tags_returns_all() -> None: """Search without tags parameter searches the full catalog.""" mcp = FastMCP("Search No Tags") @mcp.tool(tags={"math"}) def add(x: int, y: int) -> int: """Add two numbers.""" return x + y @mcp.tool(tags={"text"}) def greet(name: str) -> str: """Say hello.""" return f"Hello, {name}!" mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool(mcp, "search", {"query": "add hello"}) text = _unwrap_string_result(result) assert "add" in text assert "greet" in text async def test_search_with_untagged_filter() -> None: """Search with tags=["untagged"] matches tools that have no tags.""" mcp = FastMCP("Search Untagged") @mcp.tool(tags={"math"}) def add(x: int, y: int) -> int: """Add two numbers.""" return x + y @mcp.tool def ping() -> str: """Ping.""" return "pong" mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool(mcp, "search", {"query": "ping add", "tags": ["untagged"]}) text = _unwrap_string_result(result) assert "ping" in text assert "add" not in text async def test_search_default_detail_detailed_skips_get_schema() -> None: """Two-stage pattern: Search(default_detail='detailed') returns schemas inline.""" mcp = FastMCP("CodeMode Two-Stage") @mcp.tool def square(x: int) -> int: """Compute the square.""" return x * x mcp.add_transform( CodeMode( discovery_tools=[Search(default_detail="detailed")], sandbox_provider=_UnsafeTestSandboxProvider(), ) ) result = await _run_tool(mcp, "search", {"query": "square"}) text = _unwrap_string_result(result) assert "### square" in text assert "**Parameters**" in text assert "`x` (integer, required)" in text async def test_search_full_detail_empty_results_returns_json() -> None: """Search with detail=full and no matches returns valid JSON, not plain text.""" mcp = FastMCP("CodeMode Empty Full") @mcp.tool(tags={"math"}) def add(x: int, y: int) -> int: return x + y mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool( mcp, "search", {"query": "nonexistent", "tags": ["nonexistent"], "detail": "full"}, ) text = _unwrap_string_result(result) parsed = json.loads(text) assert parsed == [] async def test_get_schema_empty_tools_list() -> None: """get_schema with an empty tools list returns no-match message.""" mcp = FastMCP("CodeMode Empty Schema") @mcp.tool def ping() -> str: return "pong" mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool(mcp, "get_schema", {"tools": []}) text = _unwrap_string_result(result) assert "No tools matched" in text async def test_get_schema_full_partial_match_returns_valid_json() -> None: """get_schema with detail=full and missing tools returns valid JSON.""" mcp = FastMCP("Schema Full Partial") @mcp.tool def square(x: int) -> int: """Compute the square.""" return x * x mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool( mcp, "get_schema", {"tools": ["square", "nonexistent"], "detail": "full"} ) text = _unwrap_string_result(result) parsed = json.loads(text) assert isinstance(parsed, list) assert parsed[0]["name"] == "square" assert parsed[-1] == {"not_found": ["nonexistent"]} # --------------------------------------------------------------------------- # Search catalog size annotation # --------------------------------------------------------------------------- async def test_search_shows_catalog_size_when_results_are_subset() -> None: """Search annotates results with 'N of M tools' when not all tools match.""" mcp = FastMCP("Search Annotation") @mcp.tool def add(x: int, y: int) -> int: """Add two numbers.""" return x + y @mcp.tool def multiply(x: int, y: int) -> int: """Multiply two numbers.""" return x * y @mcp.tool def greet(name: str) -> str: """Say hello.""" return f"Hello, {name}!" mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool(mcp, "search", {"query": "add numbers"}) text = _unwrap_string_result(result) # Should show partial result count out of total catalog assert "of 3 tools:" in text async def test_search_omits_annotation_when_all_tools_returned() -> None: """Search does not annotate when results include every tool.""" mcp = FastMCP("Search All Match") @mcp.tool def add(x: int, y: int) -> int: """Add two numbers.""" return x + y mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool(mcp, "search", {"query": "add numbers"}) text = _unwrap_string_result(result) assert "of" not in text or "tools:" not in text # --------------------------------------------------------------------------- # Search limit # --------------------------------------------------------------------------- async def test_search_limit_caps_results() -> None: """Search with limit returns at most that many results.""" mcp = FastMCP("Search Limit") @mcp.tool def add(x: int, y: int) -> int: """Add numbers.""" return x + y @mcp.tool def subtract(x: int, y: int) -> int: """Subtract numbers.""" return x - y @mcp.tool def multiply(x: int, y: int) -> int: """Multiply numbers.""" return x * y mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool(mcp, "search", {"query": "numbers", "limit": 1}) text = _unwrap_string_result(result) assert "1 of 3 tools:" in text # Only one tool line (starts with "- ") tool_lines = [line for line in text.splitlines() if line.startswith("- ")] assert len(tool_lines) == 1 async def test_search_default_limit_from_constructor() -> None: """Search(default_limit=N) caps results by default.""" mcp = FastMCP("Search Default Limit") @mcp.tool def a() -> str: """Tool A.""" return "a" @mcp.tool def b() -> str: """Tool B.""" return "b" @mcp.tool def c() -> str: """Tool C.""" return "c" mcp.add_transform( CodeMode( discovery_tools=[Search(default_limit=2)], sandbox_provider=_UnsafeTestSandboxProvider(), ) ) result = await _run_tool(mcp, "search", {"query": "tool"}) text = _unwrap_string_result(result) assert "2 of 3 tools:" in text # --------------------------------------------------------------------------- # ListTools discovery tool # --------------------------------------------------------------------------- async def test_list_tools_brief() -> None: """ListTools at brief detail lists all tool names and descriptions.""" mcp = FastMCP("ListTools Brief") @mcp.tool def add(x: int, y: int) -> int: """Add two numbers.""" return x + y @mcp.tool def multiply(x: int, y: int) -> int: """Multiply two numbers.""" return x * y mcp.add_transform( CodeMode( discovery_tools=[ListTools()], sandbox_provider=_UnsafeTestSandboxProvider(), ) ) result = await _run_tool(mcp, "list_tools", {}) text = _unwrap_string_result(result) assert "add" in text assert "multiply" in text assert "Add two numbers" in text # brief should not include parameter details assert "**Parameters**" not in text async def test_list_tools_detailed() -> None: """ListTools at detailed shows parameter schemas.""" mcp = FastMCP("ListTools Detailed") @mcp.tool def square(x: int) -> int: """Compute the square.""" return x * x mcp.add_transform( CodeMode( discovery_tools=[ListTools(default_detail="detailed")], sandbox_provider=_UnsafeTestSandboxProvider(), ) ) result = await _run_tool(mcp, "list_tools", {}) text = _unwrap_string_result(result) assert "### square" in text assert "**Parameters**" in text assert "`x` (integer, required)" in text async def test_list_tools_full_returns_json() -> None: """ListTools at full returns valid JSON with schemas.""" mcp = FastMCP("ListTools Full") @mcp.tool def ping() -> str: """Ping.""" return "pong" mcp.add_transform( CodeMode( discovery_tools=[ListTools()], sandbox_provider=_UnsafeTestSandboxProvider(), ) ) result = await _run_tool(mcp, "list_tools", {"detail": "full"}) text = _unwrap_string_result(result) parsed = json.loads(text) assert isinstance(parsed, list) assert parsed[0]["name"] == "ping" async def test_list_tools_empty_catalog() -> None: """ListTools with no tools returns no-match message.""" mcp = FastMCP("ListTools Empty") mcp.add_transform( CodeMode( discovery_tools=[ListTools()], sandbox_provider=_UnsafeTestSandboxProvider(), ) ) result = await _run_tool(mcp, "list_tools", {}) text = _unwrap_string_result(result) assert "No tools matched" in text
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/experimental/transforms/test_code_mode_discovery.py", "license": "Apache License 2.0", "lines": 456, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:src/fastmcp/client/sampling/handlers/google_genai.py
"""Google GenAI sampling handler with tool support for FastMCP 3.0.""" from collections.abc import Sequence from uuid import uuid4 try: from google.genai import Client as GoogleGenaiClient from google.genai.types import ( Candidate, Content, FunctionCall, FunctionCallingConfig, FunctionCallingConfigMode, FunctionDeclaration, FunctionResponse, GenerateContentConfig, GenerateContentResponse, ModelContent, Part, ThinkingConfig, ToolConfig, UserContent, ) from google.genai.types import Tool as GoogleTool except ImportError as e: raise ImportError( "The `google-genai` package is not installed. " "Install it with `pip install fastmcp[gemini]` or add `google-genai` " "to your dependencies." ) from e from mcp import ClientSession, ServerSession from mcp.shared.context import LifespanContextT, RequestContext from mcp.types import ( AudioContent, CreateMessageResult, CreateMessageResultWithTools, ImageContent, ModelPreferences, SamplingMessage, SamplingMessageContentBlock, StopReason, TextContent, ToolChoice, ToolResultContent, ToolUseContent, ) from mcp.types import CreateMessageRequestParams as SamplingParams from mcp.types import Tool as MCPTool __all__ = ["GoogleGenaiSamplingHandler"] class GoogleGenaiSamplingHandler: """Sampling handler that uses the Google GenAI API with tool support. Example: ```python from google.genai import Client from fastmcp import FastMCP from fastmcp.client.sampling.handlers.google_genai import ( GoogleGenaiSamplingHandler, ) handler = GoogleGenaiSamplingHandler( default_model="gemini-2.0-flash", client=Client(), ) server = FastMCP(sampling_handler=handler) ``` """ def __init__( self, default_model: str, client: GoogleGenaiClient | None = None, thinking_budget: int | None = None, ) -> None: self.client: GoogleGenaiClient = client or GoogleGenaiClient() self.default_model: str = default_model self.thinking_budget: int | None = thinking_budget async def __call__( self, messages: list[SamplingMessage], params: SamplingParams, context: RequestContext[ServerSession, LifespanContextT] | RequestContext[ClientSession, LifespanContextT], ) -> CreateMessageResult | CreateMessageResultWithTools: contents: list[Content] = _convert_messages_to_google_genai_content(messages) # Convert MCP tools to Google GenAI format google_tools: list[GoogleTool] | None = None tool_config: ToolConfig | None = None if params.tools: google_tools = [ _convert_tool_to_google_genai(tool) for tool in params.tools ] tool_config = _convert_tool_choice_to_google_genai(params.toolChoice) # Select the model based on preferences selected_model = self._get_model(model_preferences=params.modelPreferences) # Configure thinking if a budget is specified thinking_config = ( ThinkingConfig(thinking_budget=self.thinking_budget) if self.thinking_budget is not None else None ) response: GenerateContentResponse = ( await self.client.aio.models.generate_content( model=selected_model, contents=contents, config=GenerateContentConfig( system_instruction=params.systemPrompt, temperature=params.temperature, max_output_tokens=params.maxTokens, stop_sequences=params.stopSequences, thinking_config=thinking_config, tools=google_tools, # ty: ignore[invalid-argument-type] tool_config=tool_config, ), ) ) # Return appropriate result type based on whether tools were provided if params.tools: return _response_to_result_with_tools(response, selected_model) return _response_to_create_message_result(response, selected_model) def _get_model(self, model_preferences: ModelPreferences | None) -> str: if model_preferences and model_preferences.hints: for hint in model_preferences.hints: if hint.name and hint.name.startswith("gemini"): return hint.name return self.default_model def _convert_tool_to_google_genai(tool: MCPTool) -> GoogleTool: """Convert an MCP Tool to Google GenAI format. Google's parameters_json_schema accepts standard JSON Schema format, so we pass tool.inputSchema directly without conversion. """ return GoogleTool( function_declarations=[ FunctionDeclaration( name=tool.name, description=tool.description or "", parameters_json_schema=tool.inputSchema, ) ] ) def _convert_tool_choice_to_google_genai(tool_choice: ToolChoice | None) -> ToolConfig: """Convert MCP ToolChoice to Google GenAI ToolConfig.""" if tool_choice is None: return ToolConfig( function_calling_config=FunctionCallingConfig( mode=FunctionCallingConfigMode.AUTO ) ) if tool_choice.mode == "required": return ToolConfig( function_calling_config=FunctionCallingConfig( mode=FunctionCallingConfigMode.ANY ) ) if tool_choice.mode == "none": return ToolConfig( function_calling_config=FunctionCallingConfig( mode=FunctionCallingConfigMode.NONE ) ) # Default to AUTO for "auto" or any other value return ToolConfig( function_calling_config=FunctionCallingConfig( mode=FunctionCallingConfigMode.AUTO ) ) def _sampling_content_to_google_genai_part( content: TextContent | ImageContent | AudioContent | ToolUseContent | ToolResultContent, ) -> Part: """Convert MCP content to Google GenAI Part.""" if isinstance(content, TextContent): return Part(text=content.text) if isinstance(content, ToolUseContent): # Note: thought_signature bypass is required for manually constructed tool calls. # Google's Gemini 3+ models enforce thought signature validation for function calls. # Since we're constructing these Parts from MCP protocol data (not from model responses), # they lack legitimate signatures. The bypass value allows validation to pass. # See: https://ai.google.dev/gemini-api/docs/thought-signatures return Part( function_call=FunctionCall( name=content.name, args=content.input, ), thought_signature=b"skip_thought_signature_validator", ) if isinstance(content, ToolResultContent): # Extract text from tool result content result_parts: list[str] = [] if content.content: for item in content.content: if isinstance(item, TextContent): result_parts.append(item.text) else: msg = f"Unsupported tool result content type: {type(item).__name__}" raise ValueError(msg) result_text = "".join(result_parts) # Extract function name from toolUseId # Our IDs are formatted as "{function_name}_{uuid8}", so extract the name. # Note: This is a limitation of MCP's ToolResultContent which only carries # toolUseId, while Google's FunctionResponse requires the function name. tool_use_id = content.toolUseId if "_" in tool_use_id: # Split and rejoin all but the last part (the UUID suffix) parts = tool_use_id.rsplit("_", 1) function_name = parts[0] else: # Fallback: use the full ID as the name function_name = tool_use_id return Part( function_response=FunctionResponse( name=function_name, response={"result": result_text}, ) ) msg = f"Unsupported content type: {type(content)}" raise ValueError(msg) def _convert_messages_to_google_genai_content( messages: Sequence[SamplingMessage], ) -> list[Content]: """Convert MCP messages to Google GenAI content.""" google_messages: list[Content] = [] for message in messages: content = message.content # Handle list content (tool calls + results) if isinstance(content, list): parts: list[Part] = [] for item in content: parts.append(_sampling_content_to_google_genai_part(item)) if message.role == "user": google_messages.append(UserContent(parts=parts)) elif message.role == "assistant": google_messages.append(ModelContent(parts=parts)) else: msg = f"Invalid message role: {message.role}" raise ValueError(msg) continue # Handle single content item part = _sampling_content_to_google_genai_part(content) if message.role == "user": google_messages.append(UserContent(parts=[part])) elif message.role == "assistant": google_messages.append(ModelContent(parts=[part])) else: msg = f"Invalid message role: {message.role}" raise ValueError(msg) return google_messages def _get_candidate_from_response(response: GenerateContentResponse) -> Candidate: """Extract the first candidate from a response.""" if response.candidates and response.candidates[0]: return response.candidates[0] msg = "No candidate in response from completion." raise ValueError(msg) def _response_to_create_message_result( response: GenerateContentResponse, model: str, ) -> CreateMessageResult: """Convert Google GenAI response to CreateMessageResult (no tools).""" if not (text := response.text): candidate = _get_candidate_from_response(response) msg = f"No content in response: {candidate.finish_reason}" raise ValueError(msg) return CreateMessageResult( content=TextContent(type="text", text=text), role="assistant", model=model, ) def _response_to_result_with_tools( response: GenerateContentResponse, model: str, ) -> CreateMessageResultWithTools: """Convert Google GenAI response to CreateMessageResultWithTools.""" candidate = _get_candidate_from_response(response) # Determine stop reason and check for function calls stop_reason: StopReason finish_reason = candidate.finish_reason has_function_calls = False if candidate.content and candidate.content.parts: for part in candidate.content.parts: if part.function_call is not None: has_function_calls = True break if has_function_calls: stop_reason = "toolUse" elif finish_reason == "STOP": stop_reason = "endTurn" elif finish_reason == "MAX_TOKENS": stop_reason = "maxTokens" else: stop_reason = "endTurn" # Build content list content: list[SamplingMessageContentBlock] = [] if candidate.content and candidate.content.parts: for part in candidate.content.parts: # Note: Skip thought parts from thinking_config - not relevant for MCP responses if part.text: content.append(TextContent(type="text", text=part.text)) elif part.function_call is not None: fc = part.function_call fc_name: str = fc.name or "unknown" content.append( ToolUseContent( type="tool_use", id=f"{fc_name}_{uuid4().hex[:8]}", # Generate unique ID name=fc_name, input=dict(fc.args) if fc.args else {}, ) ) if not content: raise ValueError("No content in response from completion") return CreateMessageResultWithTools( content=content, role="assistant", model=model, stopReason=stop_reason, )
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/client/sampling/handlers/google_genai.py", "license": "Apache License 2.0", "lines": 314, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:tests/client/sampling/handlers/test_google_genai_handler.py
from unittest.mock import MagicMock import pytest try: from google.genai import Client as GoogleGenaiClient from google.genai.types import ( Candidate, FunctionCall, FunctionCallingConfigMode, GenerateContentResponse, ModelContent, Part, UserContent, ) from mcp.types import ( CreateMessageResult, ModelHint, ModelPreferences, TextContent, ToolChoice, ToolResultContent, ToolUseContent, ) from fastmcp.client.sampling.handlers.google_genai import ( GoogleGenaiSamplingHandler, _convert_messages_to_google_genai_content, _convert_tool_choice_to_google_genai, _response_to_create_message_result, _response_to_result_with_tools, _sampling_content_to_google_genai_part, ) GOOGLE_GENAI_AVAILABLE = True except ImportError: GOOGLE_GENAI_AVAILABLE = False pytestmark = pytest.mark.skipif( not GOOGLE_GENAI_AVAILABLE, reason="google-genai not installed" ) def test_convert_sampling_messages_to_google_genai_content(): from mcp.types import SamplingMessage, TextContent msgs = _convert_messages_to_google_genai_content( messages=[ SamplingMessage( role="user", content=TextContent(type="text", text="hello") ), SamplingMessage( role="assistant", content=TextContent(type="text", text="ok") ), ], ) assert len(msgs) == 2 assert isinstance(msgs[0], UserContent) assert isinstance(msgs[1], ModelContent) assert msgs[0].parts[0].text == "hello" assert msgs[1].parts[0].text == "ok" def test_convert_to_google_genai_messages_raises_on_non_text(): from mcp.types import SamplingMessage from fastmcp.utilities.types import Image with pytest.raises(ValueError): _convert_messages_to_google_genai_content( messages=[ SamplingMessage( role="user", content=Image(data=b"abc").to_image_content(), ) ], ) def test_get_model(): mock_client = MagicMock(spec=GoogleGenaiClient) handler = GoogleGenaiSamplingHandler( default_model="fallback-model", client=mock_client ) # Test with Gemini model hint prefs = ModelPreferences(hints=[ModelHint(name="gemini-2.0-flash-exp")]) assert handler._get_model(prefs) == "gemini-2.0-flash-exp" # Test with None assert handler._get_model(None) == "fallback-model" # Test with empty hints prefs_empty = ModelPreferences(hints=[]) assert handler._get_model(prefs_empty) == "fallback-model" # Test with non-Gemini hint falls back to default prefs_other = ModelPreferences(hints=[ModelHint(name="gpt-4o")]) assert handler._get_model(prefs_other) == "fallback-model" # Test with mixed hints selects first Gemini model prefs_mixed = ModelPreferences( hints=[ModelHint(name="claude-3.5-sonnet"), ModelHint(name="gemini-2.0-flash")] ) assert handler._get_model(prefs_mixed) == "gemini-2.0-flash" async def test_response_to_create_message_result(): # Create a mock response mock_response = MagicMock(spec=GenerateContentResponse) mock_response.text = "HELPFUL CONTENT FROM GEMINI" result: CreateMessageResult = _response_to_create_message_result( response=mock_response, model="gemini-2.0-flash-exp" ) assert result == CreateMessageResult( content=TextContent(type="text", text="HELPFUL CONTENT FROM GEMINI"), role="assistant", model="gemini-2.0-flash-exp", ) def test_convert_tool_choice_to_google_genai(): # Test auto mode result = _convert_tool_choice_to_google_genai(ToolChoice(mode="auto")) assert result.function_calling_config is not None assert result.function_calling_config.mode == FunctionCallingConfigMode.AUTO # Test required mode result = _convert_tool_choice_to_google_genai(ToolChoice(mode="required")) assert result.function_calling_config is not None assert result.function_calling_config.mode == FunctionCallingConfigMode.ANY # Test none mode result = _convert_tool_choice_to_google_genai(ToolChoice(mode="none")) assert result.function_calling_config is not None assert result.function_calling_config.mode == FunctionCallingConfigMode.NONE # Test None (defaults to auto) result = _convert_tool_choice_to_google_genai(None) assert result.function_calling_config is not None assert result.function_calling_config.mode == FunctionCallingConfigMode.AUTO def test_sampling_content_to_google_genai_part_tool_use(): """Test converting ToolUseContent to Google GenAI Part with FunctionCall.""" content = ToolUseContent( type="tool_use", id="get_weather_abc123", name="get_weather", input={"city": "London"}, ) part = _sampling_content_to_google_genai_part(content) assert part.function_call is not None assert part.function_call.name == "get_weather" assert part.function_call.args == {"city": "London"} def test_sampling_content_to_google_genai_part_tool_result(): """Test converting ToolResultContent to Google GenAI Part with FunctionResponse.""" content = ToolResultContent( type="tool_result", toolUseId="get_weather_abc123", content=[TextContent(type="text", text="Weather is sunny")], ) part = _sampling_content_to_google_genai_part(content) assert part.function_response is not None # Function name is extracted from toolUseId by removing the UUID suffix assert part.function_response.name == "get_weather" assert part.function_response.response == {"result": "Weather is sunny"} def test_sampling_content_to_google_genai_part_tool_result_empty(): """Test converting empty ToolResultContent to Google GenAI Part.""" content = ToolResultContent( type="tool_result", toolUseId="my_tool_xyz789", content=[], ) part = _sampling_content_to_google_genai_part(content) assert part.function_response is not None assert part.function_response.name == "my_tool" assert part.function_response.response == {"result": ""} def test_sampling_content_to_google_genai_part_tool_result_no_underscore(): """Test ToolResultContent when toolUseId has no underscore (fallback).""" content = ToolResultContent( type="tool_result", toolUseId="simplefunction", content=[TextContent(type="text", text="Result")], ) part = _sampling_content_to_google_genai_part(content) # When no underscore, the full ID is used as the name assert part.function_response is not None assert part.function_response.name == "simplefunction" def test_convert_messages_with_tool_use(): """Test converting messages containing ToolUseContent.""" from mcp.types import SamplingMessage msgs = _convert_messages_to_google_genai_content( messages=[ SamplingMessage( role="user", content=TextContent(type="text", text="What's the weather?"), ), SamplingMessage( role="assistant", content=ToolUseContent( type="tool_use", id="get_weather_123", name="get_weather", input={"city": "NYC"}, ), ), ], ) assert len(msgs) == 2 assert isinstance(msgs[0], UserContent) assert isinstance(msgs[1], ModelContent) assert msgs[1].parts[0].function_call is not None assert msgs[1].parts[0].function_call.name == "get_weather" def test_convert_messages_with_tool_result(): """Test converting messages containing ToolResultContent.""" from mcp.types import SamplingMessage msgs = _convert_messages_to_google_genai_content( messages=[ SamplingMessage( role="user", content=ToolResultContent( type="tool_result", toolUseId="get_weather_123", content=[TextContent(type="text", text="Sunny, 72°F")], ), ), ], ) assert len(msgs) == 1 assert isinstance(msgs[0], UserContent) assert msgs[0].parts[0].function_response is not None assert msgs[0].parts[0].function_response.name == "get_weather" def test_convert_messages_with_multiple_content_blocks(): """Test converting messages with multiple content blocks (list content).""" from mcp.types import SamplingMessage msgs = _convert_messages_to_google_genai_content( messages=[ SamplingMessage( role="user", content=[ TextContent(type="text", text="I need weather info."), ToolResultContent( type="tool_result", toolUseId="get_weather_xyz", content=[TextContent(type="text", text="Cloudy")], ), ], ), ], ) assert len(msgs) == 1 assert isinstance(msgs[0], UserContent) assert len(msgs[0].parts) == 2 assert msgs[0].parts[0].text == "I need weather info." assert msgs[0].parts[1].function_response is not None def test_response_to_result_with_tools_text_only(): """Test _response_to_result_with_tools with a text-only response.""" mock_candidate = MagicMock(spec=Candidate) mock_candidate.content = MagicMock() mock_candidate.content.parts = [Part(text="Here's the answer")] mock_candidate.finish_reason = "STOP" mock_response = MagicMock(spec=GenerateContentResponse) mock_response.candidates = [mock_candidate] result = _response_to_result_with_tools(mock_response, model="gemini-2.0-flash") assert result.role == "assistant" assert result.model == "gemini-2.0-flash" assert result.stopReason == "endTurn" assert isinstance(result.content, list) assert len(result.content) == 1 assert result.content[0].type == "text" assert isinstance(result.content[0], TextContent) assert result.content[0].text == "Here's the answer" def test_response_to_result_with_tools_function_call(): """Test _response_to_result_with_tools with a function call response.""" mock_candidate = MagicMock(spec=Candidate) mock_candidate.content = MagicMock() mock_candidate.content.parts = [ Part(function_call=FunctionCall(name="get_weather", args={"city": "Paris"})) ] mock_candidate.finish_reason = "STOP" mock_response = MagicMock(spec=GenerateContentResponse) mock_response.candidates = [mock_candidate] result = _response_to_result_with_tools(mock_response, model="gemini-2.0-flash") assert result.stopReason == "toolUse" assert isinstance(result.content, list) assert len(result.content) == 1 tool_use = result.content[0] assert isinstance(tool_use, ToolUseContent) assert tool_use.type == "tool_use" assert tool_use.name == "get_weather" assert tool_use.input == {"city": "Paris"} # ID should be in format "get_weather_{uuid}" assert tool_use.id.startswith("get_weather_") def test_response_to_result_with_tools_mixed_content(): """Test _response_to_result_with_tools with text and function call.""" mock_candidate = MagicMock(spec=Candidate) mock_candidate.content = MagicMock() mock_candidate.content.parts = [ Part(text="Let me check that for you."), Part(function_call=FunctionCall(name="search", args={"query": "test"})), ] mock_candidate.finish_reason = "STOP" mock_response = MagicMock(spec=GenerateContentResponse) mock_response.candidates = [mock_candidate] result = _response_to_result_with_tools(mock_response, model="gemini-2.0-flash") assert result.stopReason == "toolUse" assert isinstance(result.content, list) assert len(result.content) == 2 text_content = result.content[0] assert isinstance(text_content, TextContent) assert text_content.type == "text" assert text_content.text == "Let me check that for you." tool_use = result.content[1] assert isinstance(tool_use, ToolUseContent) assert tool_use.type == "tool_use" assert tool_use.name == "search"
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/client/sampling/handlers/test_google_genai_handler.py", "license": "Apache License 2.0", "lines": 289, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/experimental/transforms/test_code_mode_serialization.py
from typing import Any import pytest from fastmcp import FastMCP from fastmcp.server.transforms.search.base import ( _schema_section, _schema_type, serialize_tools_for_output_markdown, ) # --------------------------------------------------------------------------- # _schema_type unit tests # --------------------------------------------------------------------------- @pytest.mark.parametrize( "schema,expected", [ ({"type": "string"}, "string"), ({"type": "integer"}, "integer"), ({"type": "boolean"}, "boolean"), ({"type": "null"}, "null"), ({"type": "array", "items": {"type": "string"}}, "string[]"), ({"type": "array", "items": {"type": "integer"}}, "integer[]"), ({"type": "array"}, "any[]"), ({"$ref": "#/$defs/Foo"}, "object"), ({"properties": {"x": {"type": "int"}}}, "object"), ({}, "any"), (None, "any"), ("not a dict", "any"), ], ) def test_schema_type_basic(schema: Any, expected: str) -> None: assert _schema_type(schema) == expected @pytest.mark.parametrize( "schema,expected", [ ({"anyOf": [{"type": "string"}, {"type": "null"}]}, "string?"), ({"anyOf": [{"type": "string"}, {"type": "integer"}]}, "string | integer"), ( {"anyOf": [{"type": "string"}, {"type": "integer"}, {"type": "null"}]}, "string | integer?", ), ({"anyOf": [{"type": "null"}]}, "null"), ({"anyOf": []}, "any"), ({"oneOf": [{"type": "string"}, {"type": "null"}]}, "string?"), ({"oneOf": [{"type": "string"}, {"type": "integer"}]}, "string | integer"), ({"allOf": [{"type": "object"}]}, "object"), ({"allOf": [{"$ref": "#/$defs/Foo"}, {"$ref": "#/$defs/Bar"}]}, "object"), ], ) def test_schema_type_unions(schema: Any, expected: str) -> None: assert _schema_type(schema) == expected # --------------------------------------------------------------------------- # _schema_section unit tests # --------------------------------------------------------------------------- @pytest.mark.parametrize( "schema,expected_lines", [ (None, ["**Parameters**", "- `value` (any)"]), ("string", ["**Parameters**", "- `value` (any)"]), ({"type": "string"}, ["**Parameters**", "- `value` (string)"]), ( {"type": "object", "properties": {}}, ["**Parameters**", "*(no parameters)*"], ), ], ) def test_schema_section_fallbacks(schema: Any, expected_lines: list[str]) -> None: assert _schema_section(schema, "Parameters") == expected_lines def test_schema_section_lists_fields_with_required_marker() -> None: schema = { "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer"}, }, "required": ["name"], } lines = _schema_section(schema, "Parameters") assert lines[0] == "**Parameters**" assert "- `name` (string, required)" in lines assert "- `age` (integer)" in lines # --------------------------------------------------------------------------- # serialize_tools_for_output_markdown unit tests # --------------------------------------------------------------------------- def test_serialize_tools_for_output_markdown_empty_list() -> None: assert serialize_tools_for_output_markdown([]) == "No tools matched the query." async def test_serialize_tools_for_output_markdown_basic_tool() -> None: mcp = FastMCP("MD Basic") @mcp.tool def square(x: int) -> int: """Compute the square of a number.""" return x * x tools = await mcp.list_tools() result = serialize_tools_for_output_markdown(tools) assert "### square" in result assert "Compute the square of a number." in result assert "**Parameters**" in result assert "`x` (integer, required)" in result async def test_serialize_tools_for_output_markdown_omits_output_section_when_no_schema() -> ( None ): mcp = FastMCP("MD No Output") @mcp.tool def ping() -> None: pass tools = await mcp.list_tools() result = serialize_tools_for_output_markdown(tools) assert "**Returns**" not in result async def test_serialize_tools_for_output_markdown_includes_output_section_when_schema_present() -> ( None ): mcp = FastMCP("MD With Output") @mcp.tool def double(x: int) -> int: return x * 2 tools = await mcp.list_tools() result = serialize_tools_for_output_markdown(tools) assert "**Returns**" in result async def test_serialize_tools_for_output_markdown_omits_description_when_absent() -> ( None ): mcp = FastMCP("MD No Desc") @mcp.tool def ping() -> None: pass tools = await mcp.list_tools() result = serialize_tools_for_output_markdown(tools) assert "### ping" in result async def test_serialize_tools_for_output_markdown_optional_field_uses_question_mark() -> ( None ): mcp = FastMCP("MD Optional") @mcp.tool def greet(name: str, greeting: str | None = None) -> str: return f"{greeting or 'Hello'}, {name}!" tools = await mcp.list_tools() result = serialize_tools_for_output_markdown(tools) assert "`greeting` (string?)" in result async def test_serialize_tools_for_output_markdown_multiple_tools_separated() -> None: mcp = FastMCP("MD Multi") @mcp.tool def add(a: int, b: int) -> int: return a + b @mcp.tool def subtract(a: int, b: int) -> int: return a - b tools = await mcp.list_tools() result = serialize_tools_for_output_markdown(tools) assert "### add" in result assert "### subtract" in result assert "\n\n" in result
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/experimental/transforms/test_code_mode_serialization.py", "license": "Apache License 2.0", "lines": 149, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:examples/auth/propelauth_oauth/client.py
"""OAuth client example for connecting to PropelAuth-protected FastMCP servers. This example demonstrates how to connect to a PropelAuth OAuth-protected FastMCP server. To run: python client.py """ import asyncio from fastmcp.client import Client SERVER_URL = "http://127.0.0.1:8000/mcp" async def main(): try: async with Client(SERVER_URL, auth="oauth") as client: assert await client.ping() print("✅ Successfully authenticated with PropelAuth!") tools = await client.list_tools() print(f"🔧 Available tools ({len(tools)}):") for tool in tools: print(f" - {tool.name}: {tool.description}") # Test calling a tool result = await client.call_tool( "echo", {"message": "Hello from PropelAuth!"} ) print(f"🎯 Echo result: {result}") # Test calling whoami tool whoami = await client.call_tool("whoami", {}) print(f"👤 Who am I: {whoami}") except Exception as e: print(f"❌ Authentication failed: {e}") raise if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/auth/propelauth_oauth/client.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/auth/propelauth_oauth/server.py
"""PropelAuth OAuth server example for FastMCP. This example demonstrates how to protect a FastMCP server with PropelAuth OAuth. Required environment variables: - PROPELAUTH_AUTH_URL: Your PropelAuth Auth URL (from Backend Integration page) - PROPELAUTH_INTROSPECTION_CLIENT_ID: Introspection Client ID (from MCP > Request Validation) - PROPELAUTH_INTROSPECTION_CLIENT_SECRET: Introspection Client Secret (from MCP > Request Validation) Optional: - PROPELAUTH_REQUIRED_SCOPES: Comma-separated scopes tokens must include - BASE_URL: Public URL where the FastMCP server is exposed (defaults to `http://localhost:8000/`) To run: python server.py """ import os from dotenv import load_dotenv from fastmcp import FastMCP from fastmcp.server.auth.providers.propelauth import PropelAuthProvider from fastmcp.server.dependencies import get_access_token load_dotenv() auth = PropelAuthProvider( auth_url=os.environ["PROPELAUTH_AUTH_URL"], introspection_client_id=os.environ["PROPELAUTH_INTROSPECTION_CLIENT_ID"], introspection_client_secret=os.environ["PROPELAUTH_INTROSPECTION_CLIENT_SECRET"], base_url=os.getenv("BASE_URL", "http://localhost:8000/"), ) mcp = FastMCP("PropelAuth OAuth Example Server", auth=auth) @mcp.tool def echo(message: str) -> str: """Echo the provided message.""" return message @mcp.tool def whoami() -> dict: """Return the authenticated user's ID.""" token = get_access_token() if token is None: return {"error": "Not authenticated"} return {"user_id": token.claims.get("sub")} if __name__ == "__main__": mcp.run(transport="http", port=8000)
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/auth/propelauth_oauth/server.py", "license": "Apache License 2.0", "lines": 38, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
PrefectHQ/fastmcp:src/fastmcp/server/auth/providers/propelauth.py
"""PropelAuth authentication provider for FastMCP. Example: ```python from fastmcp import FastMCP from fastmcp.server.auth.providers.propelauth import PropelAuthProvider auth = PropelAuthProvider( auth_url="https://auth.yourdomain.com", introspection_client_id="your-client-id", introspection_client_secret="your-client-secret", base_url="https://your-fastmcp-server.com", required_scopes=["read:user_data"], ) mcp = FastMCP("My App", auth=auth) ``` """ from __future__ import annotations from typing import TypedDict import httpx from pydantic import AnyHttpUrl, SecretStr from starlette.responses import JSONResponse from starlette.routing import Route from fastmcp.server.auth import AccessToken, RemoteAuthProvider from fastmcp.server.auth.providers.introspection import IntrospectionTokenVerifier from fastmcp.utilities.logging import get_logger logger = get_logger(__name__) class PropelAuthTokenIntrospectionOverrides(TypedDict, total=False): timeout_seconds: int cache_ttl_seconds: int | None max_cache_size: int | None http_client: httpx.AsyncClient | None class PropelAuthProvider(RemoteAuthProvider): """PropelAuth resource server provider using OAuth 2.1 token introspection. This provider validates access tokens via PropelAuth's introspection endpoint and forwards authorization server metadata for OAuth discovery. Setup: 1. Enable MCP authentication in the PropelAuth Dashboard 2. Configure scopes on the MCP page 3. Select which redirect URIs to enable by picking which clients you support 4. Generate introspection credentials (Client ID + Client Secret) For detailed setup instructions, see: https://docs.propelauth.com/mcp-authentication/overview Example: ```python from fastmcp import FastMCP from fastmcp.server.auth.providers.propelauth import PropelAuthProvider auth = PropelAuthProvider( auth_url="https://auth.yourdomain.com", introspection_client_id="your-client-id", introspection_client_secret="your-client-secret", base_url="https://your-fastmcp-server.com", required_scopes=["read:user_data"], ) mcp = FastMCP("My App", auth=auth) ``` """ def __init__( self, *, auth_url: AnyHttpUrl | str, introspection_client_id: str, introspection_client_secret: str | SecretStr, base_url: AnyHttpUrl | str, required_scopes: list[str] | None = None, scopes_supported: list[str] | None = None, resource_name: str | None = None, resource_documentation: AnyHttpUrl | None = None, resource: AnyHttpUrl | str | None = None, token_introspection_overrides: ( PropelAuthTokenIntrospectionOverrides | None ) = None, ): """Initialize PropelAuth provider. Args: auth_url: Your PropelAuth Auth URL (from the Backend Integration page) introspection_client_id: Introspection Client ID from the PropelAuth Dashboard introspection_client_secret: Introspection Client Secret from the PropelAuth Dashboard base_url: Public URL of this FastMCP server required_scopes: Optional list of scopes that must be present in tokens scopes_supported: Optional list of scopes to advertise in OAuth metadata. If None, uses required_scopes. Use this when the scopes clients should request differ from the scopes enforced on tokens. resource_name: Optional name for the protected resource metadata. resource_documentation: Optional documentation URL for the protected resource. resource: Optional resource URI (RFC 8707) identifying this MCP server. Use this when multiple MCP servers share the same PropelAuth authorization server (e.g. ``resource="https://api.example.com/mcp"``), so only tokens intended for this MCP server are accepted. token_introspection_overrides: Optional overrides for the underlying IntrospectionTokenVerifier (timeout, caching, http_client) """ normalized_auth_url = str(auth_url).rstrip("/") introspection_url = f"{normalized_auth_url}/oauth/2.1/introspect" authorization_server_url = AnyHttpUrl(f"{normalized_auth_url}/oauth/2.1") if resource is None: self._resource = None logger.debug( "PropelAuthProvider: no resource configured, audience checking disabled" ) else: self._resource = str(resource) token_verifier = self._create_token_verifier( introspection_url=introspection_url, client_id=introspection_client_id, client_secret=introspection_client_secret, required_scopes=required_scopes, introspection_overrides=token_introspection_overrides, ) self._normalized_auth_url = normalized_auth_url super().__init__( token_verifier=token_verifier, authorization_servers=[authorization_server_url], base_url=base_url, scopes_supported=scopes_supported, resource_name=resource_name, resource_documentation=resource_documentation, ) def get_routes( self, mcp_path: str | None = None, ) -> list[Route]: """Get routes for this provider. Includes the standard routes from the RemoteAuthProvider (protected resource metadata routes (RFC 9728)), and creates an authorization server metadata route that forwards to PropelAuth's route Args: mcp_path: The path where the MCP endpoint is mounted (e.g., "/mcp") This is used to advertise the resource URL in metadata. """ routes = super().get_routes(mcp_path) async def oauth_authorization_server_metadata(request): """Forward PropelAuth OAuth authorization server metadata""" try: async with httpx.AsyncClient() as client: response = await client.get( f"{self._normalized_auth_url}/.well-known/oauth-authorization-server/oauth/2.1" ) response.raise_for_status() metadata = response.json() return JSONResponse(metadata) except Exception as e: return JSONResponse( { "error": "server_error", "error_description": f"Failed to fetch PropelAuth metadata: {e}", }, status_code=500, ) routes.append( Route( "/.well-known/oauth-authorization-server", endpoint=oauth_authorization_server_metadata, methods=["GET"], ) ) return routes async def verify_token(self, token: str) -> AccessToken | None: """Verify token and check the ``aud`` claim against the configured resource.""" result = await super().verify_token(token) if result is None or self._resource is None: return result aud = result.claims.get("aud") if aud != self._resource: logger.debug( "PropelAuthProvider: token audience %r does not match resource %s", aud, self._resource, ) return None return result def _create_token_verifier( self, introspection_url: str, client_id: str, client_secret: str | SecretStr, required_scopes: list[str] | None, introspection_overrides: PropelAuthTokenIntrospectionOverrides | None, ) -> IntrospectionTokenVerifier: # Being defensive here, check for only the fields we are expecting safe_overrides: PropelAuthTokenIntrospectionOverrides = {} if introspection_overrides is not None: if "timeout_seconds" in introspection_overrides: safe_overrides["timeout_seconds"] = introspection_overrides[ "timeout_seconds" ] if "cache_ttl_seconds" in introspection_overrides: safe_overrides["cache_ttl_seconds"] = introspection_overrides[ "cache_ttl_seconds" ] if "max_cache_size" in introspection_overrides: safe_overrides["max_cache_size"] = introspection_overrides[ "max_cache_size" ] if "http_client" in introspection_overrides: safe_overrides["http_client"] = introspection_overrides["http_client"] return IntrospectionTokenVerifier( introspection_url=introspection_url, client_id=client_id, client_secret=client_secret, required_scopes=required_scopes, **safe_overrides, )
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/server/auth/providers/propelauth.py", "license": "Apache License 2.0", "lines": 200, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:tests/server/auth/providers/test_propelauth.py
"""Tests for PropelAuthProvider.""" from typing import cast from unittest.mock import AsyncMock import httpx import pytest from pydantic import SecretStr from fastmcp import Client, FastMCP from fastmcp.server.auth import AccessToken from fastmcp.server.auth.providers.introspection import IntrospectionTokenVerifier from fastmcp.server.auth.providers.propelauth import ( PropelAuthProvider, PropelAuthTokenIntrospectionOverrides, ) from fastmcp.utilities.tests import run_server_async class TestPropelAuthProvider: """Test PropelAuth's auth provider.""" def test_init_with_only_required_params(self): """Test PropelAuthProvider initialization with only required params.""" provider = PropelAuthProvider( auth_url="https://auth.example.com", introspection_client_id="client_id_123", introspection_client_secret="client_secret_123", base_url="https://example.com", ) # Verify the provider is configured correctly assert len(provider.authorization_servers) == 1 assert ( str(provider.authorization_servers[0]) == "https://auth.example.com/oauth/2.1" ) assert str(provider.base_url) == "https://example.com/" # Verify token verifier is configured correctly assert isinstance(provider.token_verifier, IntrospectionTokenVerifier) assert ( provider.token_verifier.introspection_url == "https://auth.example.com/oauth/2.1/introspect" ) assert provider.token_verifier.client_id == "client_id_123" assert provider.token_verifier.client_secret == "client_secret_123" def test_auth_url_trailing_slash_normalization(self): """Test that trailing slash on auth_url is stripped before building URLs.""" provider = PropelAuthProvider( auth_url="https://auth.example.com/", introspection_client_id="client_id_123", introspection_client_secret="client_secret_123", base_url="https://example.com", ) assert isinstance(provider.token_verifier, IntrospectionTokenVerifier) assert len(provider.authorization_servers) == 1 assert ( str(provider.authorization_servers[0]) == "https://auth.example.com/oauth/2.1" ) assert ( provider.token_verifier.introspection_url == "https://auth.example.com/oauth/2.1/introspect" ) def test_required_scopes_passed_to_verifier(self): """Test that required_scopes are passed through to the token verifier.""" provider = PropelAuthProvider( auth_url="https://auth.example.com", introspection_client_id="client_id_123", introspection_client_secret="client_secret_123", base_url="https://example.com", required_scopes=["read", "write"], ) assert isinstance(provider.token_verifier, IntrospectionTokenVerifier) assert provider.token_verifier.required_scopes == ["read", "write"] def test_introspection_client_secret_as_secret_str(self): """Test that SecretStr client_secret is unwrapped correctly.""" provider = PropelAuthProvider( auth_url="https://auth.example.com", introspection_client_id="client_id_123", introspection_client_secret=SecretStr("my_secret"), base_url="https://example.com", ) assert isinstance(provider.token_verifier, IntrospectionTokenVerifier) assert provider.token_verifier.client_secret == "my_secret" def test_authorization_servers_configuration(self): """Test that authorization_servers contains the correct PropelAuth URL.""" provider = PropelAuthProvider( auth_url="https://auth.propelauth.com", introspection_client_id="client_id_123", introspection_client_secret="client_secret_123", base_url="https://example.com", ) assert len(provider.authorization_servers) == 1 assert ( str(provider.authorization_servers[0]) == "https://auth.propelauth.com/oauth/2.1" ) def test_token_introspection_overrides_timeout(self): """Test that timeout_seconds override is passed to the verifier.""" provider = PropelAuthProvider( auth_url="https://auth.example.com", introspection_client_id="client_id_123", introspection_client_secret="client_secret_123", base_url="https://example.com", token_introspection_overrides={"timeout_seconds": 30}, ) assert isinstance(provider.token_verifier, IntrospectionTokenVerifier) assert provider.token_verifier.timeout_seconds == 30 def test_token_introspection_overrides_cache(self): """Test that cache overrides are passed to the verifier.""" provider = PropelAuthProvider( auth_url="https://auth.example.com", introspection_client_id="client_id_123", introspection_client_secret="client_secret_123", base_url="https://example.com", token_introspection_overrides={ "cache_ttl_seconds": 300, "max_cache_size": 500, }, ) assert isinstance(provider.token_verifier, IntrospectionTokenVerifier) assert provider.token_verifier._cache_ttl == 300 assert provider.token_verifier._max_cache_size == 500 def test_token_introspection_overrides_http_client(self): """Test that http_client override is passed to the verifier.""" client = httpx.AsyncClient() provider = PropelAuthProvider( auth_url="https://auth.example.com", introspection_client_id="client_id_123", introspection_client_secret="client_secret_123", base_url="https://example.com", token_introspection_overrides={"http_client": client}, ) assert isinstance(provider.token_verifier, IntrospectionTokenVerifier) assert provider.token_verifier._http_client is client def test_token_introspection_overrides_ignores_unknown_keys(self): """Test that unknown override keys are silently ignored.""" provider = PropelAuthProvider( auth_url="https://auth.example.com", introspection_client_id="client_id_123", introspection_client_secret="client_secret_123", base_url="https://example.com", # This won't typecheck without casting, since it shouldn't be allowed token_introspection_overrides=cast( PropelAuthTokenIntrospectionOverrides, {"unknown_key": "value"} ), ) assert isinstance(provider.token_verifier, IntrospectionTokenVerifier) assert provider.token_verifier.timeout_seconds == 10 def test_token_introspection_overrides_ignores_disallowed_known_keys(self): """Test that known IntrospectionTokenVerifier keys not in the allow list are ignored.""" provider = PropelAuthProvider( auth_url="https://auth.example.com", introspection_client_id="client_id_123", introspection_client_secret="client_secret_123", base_url="https://example.com", # This won't typecheck without casting, since it shouldn't be allowed token_introspection_overrides=cast( PropelAuthTokenIntrospectionOverrides, {"client_id": "sneaky_override"} ), ) assert isinstance(provider.token_verifier, IntrospectionTokenVerifier) assert provider.token_verifier.client_id == "client_id_123" class TestPropelAuthResourceChecking: """Test audience (aud) checking when resource is configured.""" def _make_provider(self, resource: str | None = None) -> PropelAuthProvider: return PropelAuthProvider( auth_url="https://auth.example.com", introspection_client_id="client_id_123", introspection_client_secret="client_secret_123", base_url="https://example.com", resource=resource, ) def _make_access_token(self, aud: str) -> AccessToken: return AccessToken( token="test-token", client_id="client_id_123", scopes=[], claims={"active": True, "sub": "user-1", "aud": aud}, ) async def test_no_resource_skips_aud_check(self, monkeypatch: pytest.MonkeyPatch): """When resource is not configured, tokens are accepted without aud checking.""" provider = self._make_provider(resource=None) token = self._make_access_token(aud="https://anything.example.com") monkeypatch.setattr( provider.token_verifier, "verify_token", AsyncMock(return_value=token) ) result = await provider.verify_token("test-token") assert result is token async def test_aud_matches_resource(self, monkeypatch: pytest.MonkeyPatch): """Token is accepted when aud matches the configured resource.""" provider = self._make_provider(resource="https://api.example.com/mcp") token = self._make_access_token(aud="https://api.example.com/mcp") monkeypatch.setattr( provider.token_verifier, "verify_token", AsyncMock(return_value=token) ) result = await provider.verify_token("test-token") assert result is token async def test_aud_does_not_match_resource(self, monkeypatch: pytest.MonkeyPatch): """Token is rejected when aud doesn't match the configured resource.""" provider = self._make_provider(resource="https://api.example.com/mcp") token = self._make_access_token(aud="https://other-server.example.com/mcp") monkeypatch.setattr( provider.token_verifier, "verify_token", AsyncMock(return_value=token) ) result = await provider.verify_token("test-token") assert result is None async def test_inner_verifier_returns_none(self, monkeypatch: pytest.MonkeyPatch): """When the inner verifier rejects the token, None is returned without aud checking.""" provider = self._make_provider(resource="https://api.example.com/mcp") monkeypatch.setattr( provider.token_verifier, "verify_token", AsyncMock(return_value=None) ) result = await provider.verify_token("test-token") assert result is None @pytest.fixture async def mcp_server_url(): """Start MCP server with PropelAuth authentication.""" mcp = FastMCP( auth=PropelAuthProvider( auth_url="https://auth.example.com", introspection_client_id="client_id_123", introspection_client_secret="client_secret_123", base_url="http://localhost:4321", ) ) @mcp.tool def add(a: int, b: int) -> int: return a + b async with run_server_async(mcp, transport="http") as url: yield url class TestPropelAuthProviderIntegration: async def test_unauthorized_access(self, mcp_server_url: str): with pytest.raises(httpx.HTTPStatusError) as exc_info: async with Client(mcp_server_url) as client: tools = await client.list_tools() # noqa: F841 assert isinstance(exc_info.value, httpx.HTTPStatusError) assert exc_info.value.response.status_code == 401 assert "tools" not in locals() async def test_metadata_route_forwards_propelauth_response( self, monkeypatch: pytest.MonkeyPatch, mcp_server_url: str, ) -> None: """Ensure PropelAuth metadata route proxies upstream JSON.""" metadata_payload = { "issuer": "https://auth.example.com", "token_endpoint": "https://auth.example.com/oauth/2.1/token", "authorization_endpoint": "https://auth.example.com/oauth/2.1/authorize", } class DummyResponse: status_code = 200 def __init__(self, data: dict[str, str]): self._data = data def json(self): return self._data def raise_for_status(self): return None class DummyAsyncClient: last_url: str | None = None async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): return False async def get(self, url: str): DummyAsyncClient.last_url = url return DummyResponse(metadata_payload) real_httpx_client = httpx.AsyncClient monkeypatch.setattr( "fastmcp.server.auth.providers.propelauth.httpx.AsyncClient", DummyAsyncClient, ) base_url = mcp_server_url.rsplit("/mcp", 1)[0] async with real_httpx_client() as client: response = await client.get( f"{base_url}/.well-known/oauth-authorization-server" ) assert response.status_code == 200 assert response.json() == metadata_payload assert ( DummyAsyncClient.last_url == "https://auth.example.com/.well-known/oauth-authorization-server/oauth/2.1" )
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/auth/providers/test_propelauth.py", "license": "Apache License 2.0", "lines": 277, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/server/auth/test_multi_auth.py
import httpx import pytest from pydantic import AnyHttpUrl from fastmcp import FastMCP from fastmcp.server.auth import MultiAuth, RemoteAuthProvider, TokenVerifier from fastmcp.server.auth.auth import AccessToken from fastmcp.server.auth.providers.jwt import StaticTokenVerifier class RaisingVerifier(TokenVerifier): """A verifier that always raises, for testing exception resilience.""" async def verify_token(self, token: str) -> AccessToken | None: raise RuntimeError("simulated failure") class TestMultiAuthInit: """Test MultiAuth initialization and validation.""" def test_requires_server_or_verifiers(self): """MultiAuth with neither server nor verifiers raises ValueError.""" with pytest.raises(ValueError, match="at least a server or one verifier"): MultiAuth() def test_server_only(self): verifier = StaticTokenVerifier(tokens={"t": {"client_id": "c", "scopes": []}}) provider = RemoteAuthProvider( token_verifier=verifier, authorization_servers=[AnyHttpUrl("https://auth.example.com")], base_url="https://api.example.com", ) auth = MultiAuth(server=provider) assert auth.server is provider assert auth.verifiers == [] def test_verifiers_only(self): v = StaticTokenVerifier(tokens={"t": {"client_id": "c", "scopes": []}}) auth = MultiAuth(verifiers=[v]) assert auth.server is None assert auth.verifiers == [v] def test_single_verifier_not_in_list(self): """A single TokenVerifier (not in a list) is accepted.""" v = StaticTokenVerifier(tokens={"t": {"client_id": "c", "scopes": []}}) auth = MultiAuth(verifiers=v) assert auth.verifiers == [v] def test_base_url_from_server(self): verifier = StaticTokenVerifier(tokens={"t": {"client_id": "c", "scopes": []}}) provider = RemoteAuthProvider( token_verifier=verifier, authorization_servers=[AnyHttpUrl("https://auth.example.com")], base_url="https://api.example.com", ) auth = MultiAuth(server=provider) assert auth.base_url == AnyHttpUrl("https://api.example.com/") def test_base_url_override(self): verifier = StaticTokenVerifier(tokens={"t": {"client_id": "c", "scopes": []}}) provider = RemoteAuthProvider( token_verifier=verifier, authorization_servers=[AnyHttpUrl("https://auth.example.com")], base_url="https://api.example.com", ) auth = MultiAuth(server=provider, base_url="https://override.example.com") assert auth.base_url == AnyHttpUrl("https://override.example.com/") def test_required_scopes_from_server(self): verifier = StaticTokenVerifier( tokens={"t": {"client_id": "c", "scopes": ["read"]}}, required_scopes=["read"], ) provider = RemoteAuthProvider( token_verifier=verifier, authorization_servers=[AnyHttpUrl("https://auth.example.com")], base_url="https://api.example.com", ) auth = MultiAuth(server=provider) assert auth.required_scopes == ["read"] class TestMultiAuthVerifyToken: """Test MultiAuth token verification chain.""" async def test_server_verified_first(self): """Server's verify_token is tried before verifiers.""" server_verifier = StaticTokenVerifier( tokens={"server_token": {"client_id": "server-client", "scopes": []}} ) server = RemoteAuthProvider( token_verifier=server_verifier, authorization_servers=[AnyHttpUrl("https://auth.example.com")], base_url="https://api.example.com", ) extra = StaticTokenVerifier( tokens={"extra_token": {"client_id": "extra-client", "scopes": []}} ) auth = MultiAuth(server=server, verifiers=[extra]) result = await auth.verify_token("server_token") assert result is not None assert result.client_id == "server-client" async def test_falls_back_to_verifiers(self): """When server rejects a token, verifiers are tried.""" server_verifier = StaticTokenVerifier( tokens={"server_token": {"client_id": "server-client", "scopes": []}} ) server = RemoteAuthProvider( token_verifier=server_verifier, authorization_servers=[AnyHttpUrl("https://auth.example.com")], base_url="https://api.example.com", ) extra = StaticTokenVerifier( tokens={"m2m_token": {"client_id": "m2m-service", "scopes": []}} ) auth = MultiAuth(server=server, verifiers=[extra]) result = await auth.verify_token("m2m_token") assert result is not None assert result.client_id == "m2m-service" async def test_verifier_order_matters(self): """Verifiers are tried in order; first match wins.""" v1 = StaticTokenVerifier( tokens={"shared_token": {"client_id": "first", "scopes": []}} ) v2 = StaticTokenVerifier( tokens={"shared_token": {"client_id": "second", "scopes": []}} ) auth = MultiAuth(verifiers=[v1, v2]) result = await auth.verify_token("shared_token") assert result is not None assert result.client_id == "first" async def test_no_match_returns_none(self): """When no server or verifier accepts the token, returns None.""" v = StaticTokenVerifier(tokens={"known": {"client_id": "c", "scopes": []}}) auth = MultiAuth(verifiers=[v]) result = await auth.verify_token("unknown") assert result is None async def test_verifiers_only_no_server(self): """MultiAuth with only verifiers (no server) works.""" v1 = StaticTokenVerifier(tokens={"token_a": {"client_id": "a", "scopes": []}}) v2 = StaticTokenVerifier(tokens={"token_b": {"client_id": "b", "scopes": []}}) auth = MultiAuth(verifiers=[v1, v2]) result_a = await auth.verify_token("token_a") assert result_a is not None assert result_a.client_id == "a" result_b = await auth.verify_token("token_b") assert result_b is not None assert result_b.client_id == "b" async def test_raising_verifier_does_not_break_chain(self): """If a verifier raises, the chain continues to the next source.""" good = StaticTokenVerifier( tokens={"valid": {"client_id": "good-client", "scopes": []}} ) auth = MultiAuth(verifiers=[RaisingVerifier(), good]) result = await auth.verify_token("valid") assert result is not None assert result.client_id == "good-client" async def test_raising_server_does_not_break_chain(self): """If the server raises, verifiers are still tried.""" good = StaticTokenVerifier( tokens={"valid": {"client_id": "fallback", "scopes": []}} ) auth = MultiAuth(server=RaisingVerifier(), verifiers=[good]) result = await auth.verify_token("valid") assert result is not None assert result.client_id == "fallback" async def test_all_raising_returns_none(self): """If every source raises, verify_token returns None.""" auth = MultiAuth(verifiers=[RaisingVerifier(), RaisingVerifier()]) result = await auth.verify_token("anything") assert result is None async def test_server_match_short_circuits(self): """When the server matches, verifiers are not consulted.""" # Both server and verifier know the same token with different client_ids server_verifier = StaticTokenVerifier( tokens={"token": {"client_id": "from-server", "scopes": []}} ) server = RemoteAuthProvider( token_verifier=server_verifier, authorization_servers=[AnyHttpUrl("https://auth.example.com")], base_url="https://api.example.com", ) extra = StaticTokenVerifier( tokens={"token": {"client_id": "from-verifier", "scopes": []}} ) auth = MultiAuth(server=server, verifiers=[extra]) result = await auth.verify_token("token") assert result is not None assert result.client_id == "from-server" class TestMultiAuthRoutes: """Test that routes delegate to the server.""" def test_routes_from_server(self): verifier = StaticTokenVerifier(tokens={"t": {"client_id": "c", "scopes": []}}) server = RemoteAuthProvider( token_verifier=verifier, authorization_servers=[AnyHttpUrl("https://auth.example.com")], base_url="https://api.example.com", ) auth = MultiAuth(server=server) routes = auth.get_routes(mcp_path="/mcp") # RemoteAuthProvider creates a protected resource metadata route assert len(routes) >= 1 def test_no_routes_without_server(self): v = StaticTokenVerifier(tokens={"t": {"client_id": "c", "scopes": []}}) auth = MultiAuth(verifiers=[v]) assert auth.get_routes() == [] def test_well_known_routes_delegate_to_server(self): """get_well_known_routes delegates to the server's implementation.""" verifier = StaticTokenVerifier(tokens={"t": {"client_id": "c", "scopes": []}}) server = RemoteAuthProvider( token_verifier=verifier, authorization_servers=[AnyHttpUrl("https://auth.example.com")], base_url="https://api.example.com", ) auth = MultiAuth(server=server) well_known = auth.get_well_known_routes(mcp_path="/mcp") server_well_known = server.get_well_known_routes(mcp_path="/mcp") # MultiAuth should produce the same well-known routes as the server assert len(well_known) == len(server_well_known) assert [r.path for r in well_known] == [r.path for r in server_well_known] def test_well_known_routes_empty_without_server(self): v = StaticTokenVerifier(tokens={"t": {"client_id": "c", "scopes": []}}) auth = MultiAuth(verifiers=[v]) assert auth.get_well_known_routes() == [] def test_required_scopes_explicit_empty_list(self): """Passing required_scopes=[] explicitly clears inherited scopes.""" verifier = StaticTokenVerifier( tokens={"t": {"client_id": "c", "scopes": ["read"]}}, required_scopes=["read"], ) server = RemoteAuthProvider( token_verifier=verifier, authorization_servers=[AnyHttpUrl("https://auth.example.com")], base_url="https://api.example.com", ) # Server has required_scopes=["read"], but we explicitly clear them auth = MultiAuth(server=server, required_scopes=[]) assert auth.required_scopes == [] class TestMultiAuthIntegration: """Integration tests: MultiAuth with a real FastMCP HTTP app.""" async def test_multi_auth_rejects_bad_tokens(self): """End-to-end: MultiAuth rejects unknown tokens at the HTTP layer.""" oauth_tokens = StaticTokenVerifier( tokens={ "oauth_token": { "client_id": "interactive-client", "scopes": ["read"], } } ) m2m_tokens = StaticTokenVerifier( tokens={ "m2m_token": { "client_id": "backend-service", "scopes": ["read"], } } ) auth = MultiAuth(verifiers=[oauth_tokens, m2m_tokens]) mcp = FastMCP("test", auth=auth) app = mcp.http_app(path="/mcp") async with httpx.AsyncClient( transport=httpx.ASGITransport(app=app), base_url="http://localhost", ) as client: # No token → 401 response = await client.get("/mcp") assert response.status_code == 401 # Bad token → 401 response = await client.get( "/mcp", headers={"Authorization": "Bearer bad_token"} ) assert response.status_code == 401 async def test_multi_auth_with_server_provides_routes(self): """MultiAuth with a server exposes the server's metadata routes.""" verifier = StaticTokenVerifier(tokens={"t": {"client_id": "c", "scopes": []}}) server = RemoteAuthProvider( token_verifier=verifier, authorization_servers=[AnyHttpUrl("https://auth.example.com")], base_url="https://api.example.com", ) extra = StaticTokenVerifier(tokens={"m2m": {"client_id": "svc", "scopes": []}}) auth = MultiAuth(server=server, verifiers=[extra]) mcp = FastMCP("test", auth=auth) app = mcp.http_app(path="/mcp") async with httpx.AsyncClient( transport=httpx.ASGITransport(app=app), base_url="https://api.example.com", ) as client: # Protected resource metadata should be available response = await client.get("/.well-known/oauth-protected-resource/mcp") assert response.status_code == 200 data = response.json() assert data["resource"] == "https://api.example.com/mcp" async def test_multi_auth_accepts_valid_verifier_token(self): """MultiAuth accepts tokens from verifiers (not just the server). Verifies that both server and verifier tokens pass the HTTP auth middleware. We use GET /mcp to check: 401 means auth rejected, any other status means auth accepted and the request reached the MCP session layer. """ interactive_tokens = StaticTokenVerifier( tokens={ "interactive_token": { "client_id": "interactive-client", "scopes": [], } } ) m2m_tokens = StaticTokenVerifier( tokens={ "m2m_token": { "client_id": "backend-service", "scopes": [], } } ) auth = MultiAuth(verifiers=[interactive_tokens, m2m_tokens]) mcp = FastMCP("test", auth=auth) app = mcp.http_app(path="/mcp") async with httpx.AsyncClient( transport=httpx.ASGITransport(app=app, raise_app_exceptions=False), base_url="http://localhost", ) as client: # No token → 401 response = await client.get("/mcp") assert response.status_code == 401 # Interactive token passes auth (non-401 means auth accepted) response = await client.get( "/mcp", headers={"Authorization": "Bearer interactive_token"} ) assert response.status_code != 401 # M2M token also passes auth response = await client.get( "/mcp", headers={"Authorization": "Bearer m2m_token"} ) assert response.status_code != 401 # Bad token → 401 response = await client.get( "/mcp", headers={"Authorization": "Bearer bad_token"} ) assert response.status_code == 401 class TestMultiAuthSetMcpPath: """Test that set_mcp_path propagates to server and verifiers.""" def test_propagates_to_server(self): verifier = StaticTokenVerifier(tokens={"t": {"client_id": "c", "scopes": []}}) server = RemoteAuthProvider( token_verifier=verifier, authorization_servers=[AnyHttpUrl("https://auth.example.com")], base_url="https://api.example.com", ) auth = MultiAuth(server=server) auth.set_mcp_path("/mcp") assert server._mcp_path == "/mcp" def test_propagates_to_verifiers(self): v1 = StaticTokenVerifier(tokens={"t": {"client_id": "c", "scopes": []}}) v2 = StaticTokenVerifier(tokens={"t2": {"client_id": "c2", "scopes": []}}) auth = MultiAuth(verifiers=[v1, v2]) auth.set_mcp_path("/mcp") assert v1._mcp_path == "/mcp" assert v2._mcp_path == "/mcp"
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/auth/test_multi_auth.py", "license": "Apache License 2.0", "lines": 345, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/client/test_elicitation_enums.py
"""Tests for enum-based elicitation, multi-select, and default values.""" from dataclasses import dataclass from enum import Enum import pytest from pydantic import BaseModel, Field from fastmcp import Context, FastMCP from fastmcp.client.client import Client from fastmcp.client.elicitation import ElicitResult from fastmcp.exceptions import ToolError from fastmcp.server.elicitation import ( AcceptedElicitation, get_elicitation_schema, validate_elicitation_json_schema, ) @pytest.fixture def fastmcp_server(): mcp = FastMCP("TestServer") @dataclass class Person: name: str @mcp.tool async def ask_for_name(context: Context) -> str: result = await context.elicit( message="What is your name?", response_type=Person, ) if result.action == "accept": assert isinstance(result, AcceptedElicitation) assert isinstance(result.data, Person) return f"Hello, {result.data.name}!" else: return "No name provided." @mcp.tool def simple_test() -> str: return "Hello!" return mcp async def test_elicitation_implicit_acceptance(fastmcp_server): """Test that elicitation handler can return data directly without ElicitResult wrapper.""" async def elicitation_handler(message, response_type, params, ctx): # Return data directly without wrapping in ElicitResult # This should be treated as implicit acceptance return response_type(name="Bob") async with Client( fastmcp_server, elicitation_handler=elicitation_handler ) as client: result = await client.call_tool("ask_for_name") assert result.data == "Hello, Bob!" async def test_elicitation_implicit_acceptance_must_be_dict(fastmcp_server): """Test that elicitation handler can return data directly without ElicitResult wrapper.""" async def elicitation_handler(message, response_type, params, ctx): # Return data directly without wrapping in ElicitResult # This should be treated as implicit acceptance return "Bob" async with Client( fastmcp_server, elicitation_handler=elicitation_handler ) as client: with pytest.raises( ToolError, match="Elicitation responses must be serializable as a JSON object", ): await client.call_tool("ask_for_name") def test_enum_elicitation_schema_inline(): """Test that enum schemas are generated inline without $ref/$defs for MCP compatibility.""" class Priority(Enum): LOW = "low" MEDIUM = "medium" HIGH = "high" @dataclass class TaskRequest: title: str priority: Priority # Generate elicitation schema schema = get_elicitation_schema(TaskRequest) # Verify no $defs section exists (enums should be inlined) assert "$defs" not in schema, ( "Schema should not contain $defs - enums must be inline" ) # Verify no $ref in properties for prop_name, prop_schema in schema.get("properties", {}).items(): assert "$ref" not in prop_schema, ( f"Property {prop_name} contains $ref - should be inline" ) # Verify the priority field has inline enum values priority_schema = schema["properties"]["priority"] assert "enum" in priority_schema, "Priority should have enum values inline" assert priority_schema["enum"] == ["low", "medium", "high"] assert priority_schema.get("type") == "string" # Verify title field is a simple string assert schema["properties"]["title"]["type"] == "string" def test_enum_elicitation_schema_inline_untitled(): """Test that enum schemas generate simple enum pattern (no automatic titles).""" class TaskStatus(Enum): NOT_STARTED = "not_started" IN_PROGRESS = "in_progress" COMPLETED = "completed" ON_HOLD = "on_hold" @dataclass class TaskUpdate: task_id: str status: TaskStatus # Generate elicitation schema schema = get_elicitation_schema(TaskUpdate) # Verify enum is inline assert "$defs" not in schema assert "$ref" not in str(schema) status_schema = schema["properties"]["status"] # Should generate simple enum pattern (no automatic title generation) assert "enum" in status_schema assert "oneOf" not in status_schema assert "enumNames" not in status_schema assert status_schema["enum"] == [ "not_started", "in_progress", "completed", "on_hold", ] async def test_dict_based_titled_single_select(): """Test dict-based titled single-select enum.""" mcp = FastMCP("TestServer") @mcp.tool async def my_tool(ctx: Context) -> str: result = await ctx.elicit( "Choose priority", response_type={ "low": {"title": "Low Priority"}, "high": {"title": "High Priority"}, }, ) if result.action == "accept": assert isinstance(result, AcceptedElicitation) assert isinstance(result.data, str) return result.data return "declined" async def elicitation_handler(message, response_type, params, ctx): # Verify schema follows SEP-1330 pattern with type: "string" schema = params.requestedSchema assert schema["type"] == "object" assert "value" in schema["properties"] value_schema = schema["properties"]["value"] assert value_schema["type"] == "string" assert "oneOf" in value_schema one_of = value_schema["oneOf"] assert {"const": "low", "title": "Low Priority"} in one_of assert {"const": "high", "title": "High Priority"} in one_of return ElicitResult(action="accept", content={"value": "low"}) async with Client(mcp, elicitation_handler=elicitation_handler) as client: result = await client.call_tool("my_tool", {}) assert result.data == "low" async def test_list_list_multi_select_untitled(): """Test list[list[str]] for multi-select untitled shorthand.""" mcp = FastMCP("TestServer") @mcp.tool async def my_tool(ctx: Context) -> str: result = await ctx.elicit( "Choose tags", response_type=[["bug", "feature", "documentation"]], ) if result.action == "accept": assert isinstance(result, AcceptedElicitation) assert isinstance(result.data, list) return ",".join(result.data) # type: ignore[no-matching-overload] return "declined" async def elicitation_handler(message, response_type, params, ctx): # Verify schema has array with enum pattern schema = params.requestedSchema assert schema["type"] == "object" assert "value" in schema["properties"] value_schema = schema["properties"]["value"] assert value_schema["type"] == "array" assert "enum" in value_schema["items"] assert value_schema["items"]["enum"] == ["bug", "feature", "documentation"] return ElicitResult(action="accept", content={"value": ["bug", "feature"]}) async with Client(mcp, elicitation_handler=elicitation_handler) as client: result = await client.call_tool("my_tool", {}) assert result.data == "bug,feature" async def test_list_dict_multi_select_titled(): """Test list[dict] for multi-select titled.""" mcp = FastMCP("TestServer") @mcp.tool async def my_tool(ctx: Context) -> str: result = await ctx.elicit( "Choose priorities", response_type=[ { "low": {"title": "Low Priority"}, "high": {"title": "High Priority"}, } ], ) if result.action == "accept": assert isinstance(result, AcceptedElicitation) assert isinstance(result.data, list) return ",".join(result.data) # type: ignore[no-matching-overload] return "declined" async def elicitation_handler(message, response_type, params, ctx): # Verify schema has array with SEP-1330 compliant items (anyOf pattern) schema = params.requestedSchema assert schema["type"] == "object" assert "value" in schema["properties"] value_schema = schema["properties"]["value"] assert value_schema["type"] == "array" items_schema = value_schema["items"] assert "anyOf" in items_schema any_of = items_schema["anyOf"] assert {"const": "low", "title": "Low Priority"} in any_of assert {"const": "high", "title": "High Priority"} in any_of return ElicitResult(action="accept", content={"value": ["low", "high"]}) async with Client(mcp, elicitation_handler=elicitation_handler) as client: result = await client.call_tool("my_tool", {}) assert result.data == "low,high" async def test_list_enum_multi_select(): """Test list[Enum] for multi-select with enum in dataclass field.""" class Priority(Enum): LOW = "low" MEDIUM = "medium" HIGH = "high" @dataclass class TaskRequest: priorities: list[Priority] schema = get_elicitation_schema(TaskRequest) priorities_schema = schema["properties"]["priorities"] assert priorities_schema["type"] == "array" assert "items" in priorities_schema items_schema = priorities_schema["items"] # Should have enum pattern for untitled enums assert "enum" in items_schema assert items_schema["enum"] == ["low", "medium", "high"] async def test_list_enum_multi_select_direct(): """Test list[Enum] type annotation passed directly to ctx.elicit().""" mcp = FastMCP("TestServer") class Priority(Enum): LOW = "low" MEDIUM = "medium" HIGH = "high" @mcp.tool async def my_tool(ctx: Context) -> str: result = await ctx.elicit( "Choose priorities", response_type=list[Priority], # Type annotation for multi-select ) if result.action == "accept": assert isinstance(result, AcceptedElicitation) assert isinstance(result.data, list) priorities = result.data return ",".join( [p.value if isinstance(p, Priority) else str(p) for p in priorities] ) return "declined" async def elicitation_handler(message, response_type, params, ctx): # Verify schema has array with enum pattern schema = params.requestedSchema assert schema["type"] == "object" assert "value" in schema["properties"] value_schema = schema["properties"]["value"] assert value_schema["type"] == "array" assert "enum" in value_schema["items"] assert value_schema["items"]["enum"] == ["low", "medium", "high"] return ElicitResult(action="accept", content={"value": ["low", "high"]}) async with Client(mcp, elicitation_handler=elicitation_handler) as client: result = await client.call_tool("my_tool", {}) assert result.data == "low,high" async def test_validation_allows_enum_arrays(): """Test validation accepts arrays with enum items.""" schema = { "type": "object", "properties": { "priorities": { "type": "array", "items": {"enum": ["low", "medium", "high"]}, } }, } validate_elicitation_json_schema(schema) # Should not raise async def test_validation_allows_enum_arrays_with_anyof(): """Test validation accepts arrays with anyOf enum pattern (SEP-1330 compliant).""" schema = { "type": "object", "properties": { "priorities": { "type": "array", "items": { "anyOf": [ {"const": "low", "title": "Low Priority"}, {"const": "high", "title": "High Priority"}, ] }, } }, } validate_elicitation_json_schema(schema) # Should not raise async def test_validation_rejects_non_enum_arrays(): """Test validation still rejects arrays of objects.""" schema = { "type": "object", "properties": { "users": { "type": "array", "items": {"type": "object", "properties": {"name": {"type": "string"}}}, } }, } with pytest.raises(TypeError, match="array of objects"): validate_elicitation_json_schema(schema) async def test_validation_rejects_primitive_arrays(): """Test validation rejects arrays of primitives without enum pattern.""" schema = { "type": "object", "properties": { "names": {"type": "array", "items": {"type": "string"}}, }, } with pytest.raises(TypeError, match="arrays are only allowed"): validate_elicitation_json_schema(schema) class TestElicitationDefaults: """Test suite for default values in elicitation schemas.""" def test_string_default_preserved(self): """Test that string defaults are preserved in the schema.""" class Model(BaseModel): email: str = Field(default="[email protected]") schema = get_elicitation_schema(Model) props = schema.get("properties", {}) assert "email" in props assert "default" in props["email"] assert props["email"]["default"] == "[email protected]" assert props["email"]["type"] == "string" def test_integer_default_preserved(self): """Test that integer defaults are preserved in the schema.""" class Model(BaseModel): count: int = Field(default=50) schema = get_elicitation_schema(Model) props = schema.get("properties", {}) assert "count" in props assert "default" in props["count"] assert props["count"]["default"] == 50 assert props["count"]["type"] == "integer" def test_number_default_preserved(self): """Test that number defaults are preserved in the schema.""" class Model(BaseModel): price: float = Field(default=3.14) schema = get_elicitation_schema(Model) props = schema.get("properties", {}) assert "price" in props assert "default" in props["price"] assert props["price"]["default"] == 3.14 assert props["price"]["type"] == "number" def test_boolean_default_preserved(self): """Test that boolean defaults are preserved in the schema.""" class Model(BaseModel): enabled: bool = Field(default=False) schema = get_elicitation_schema(Model) props = schema.get("properties", {}) assert "enabled" in props assert "default" in props["enabled"] assert props["enabled"]["default"] is False assert props["enabled"]["type"] == "boolean" def test_enum_default_preserved(self): """Test that enum defaults are preserved in the schema.""" class Priority(Enum): LOW = "low" MEDIUM = "medium" HIGH = "high" class Model(BaseModel): choice: Priority = Field(default=Priority.MEDIUM) schema = get_elicitation_schema(Model) props = schema.get("properties", {}) assert "choice" in props assert "default" in props["choice"] assert props["choice"]["default"] == "medium" assert "enum" in props["choice"] assert props["choice"]["type"] == "string" def test_all_defaults_preserved_together(self): """Test that all default types are preserved when used together.""" class Priority(Enum): A = "A" B = "B" class Model(BaseModel): string_field: str = Field(default="[email protected]") integer_field: int = Field(default=50) number_field: float = Field(default=3.14) boolean_field: bool = Field(default=False) enum_field: Priority = Field(default=Priority.A) schema = get_elicitation_schema(Model) props = schema.get("properties", {}) assert props["string_field"]["default"] == "[email protected]" assert props["integer_field"]["default"] == 50 assert props["number_field"]["default"] == 3.14 assert props["boolean_field"]["default"] is False assert props["enum_field"]["default"] == "A" def test_mixed_defaults_and_required(self): """Test that fields with defaults are not in required list.""" class Model(BaseModel): required_field: str = Field(description="Required field") optional_with_default: int = Field(default=42) schema = get_elicitation_schema(Model) props = schema.get("properties", {}) required = schema.get("required", []) assert "required_field" in required assert "optional_with_default" not in required assert props["optional_with_default"]["default"] == 42 def test_compress_schema_preserves_defaults(self): """Test that compress_schema() doesn't strip default values.""" class Model(BaseModel): string_field: str = Field(default="test") integer_field: int = Field(default=42) schema = get_elicitation_schema(Model) props = schema.get("properties", {}) assert "default" in props["string_field"] assert "default" in props["integer_field"]
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/client/test_elicitation_enums.py", "license": "Apache License 2.0", "lines": 408, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/client/test_sampling_result_types.py
from mcp.types import TextContent from fastmcp import Client, Context, FastMCP from fastmcp.client.sampling import RequestContext, SamplingMessage, SamplingParams class TestSamplingResultType: """Tests for result_type parameter (structured output).""" async def test_result_type_creates_final_response_tool(self): """Test that result_type creates a synthetic final_response tool.""" from mcp.types import CreateMessageResultWithTools, ToolUseContent from pydantic import BaseModel class MathResult(BaseModel): answer: int explanation: str received_tools: list = [] def sampling_handler( messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext ) -> CreateMessageResultWithTools: received_tools.extend(params.tools or []) # Return the final_response tool call return CreateMessageResultWithTools( role="assistant", content=[ ToolUseContent( type="tool_use", id="call_1", name="final_response", input={"answer": 42, "explanation": "The meaning of life"}, ) ], model="test-model", stopReason="toolUse", ) mcp = FastMCP(sampling_handler=sampling_handler) @mcp.tool async def math_tool(context: Context) -> str: result = await context.sample( messages="What is 6 * 7?", result_type=MathResult, ) # result.result should be a MathResult object assert isinstance(result.result, MathResult) return f"{result.result.answer}: {result.result.explanation}" async with Client(mcp) as client: result = await client.call_tool("math_tool", {}) # Check that final_response tool was added tool_names = [t.name for t in received_tools] assert "final_response" in tool_names # Check the result assert result.data == "42: The meaning of life" async def test_result_type_with_user_tools(self): """Test result_type works alongside user-provided tools.""" from mcp.types import CreateMessageResultWithTools, ToolUseContent from pydantic import BaseModel class SearchResult(BaseModel): summary: str sources: list[str] def search(query: str) -> str: """Search for information.""" return f"Found info about: {query}" call_count = 0 tool_was_called = False def sampling_handler( messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext ) -> CreateMessageResultWithTools: nonlocal call_count, tool_was_called call_count += 1 if call_count == 1: # First call: use the search tool return CreateMessageResultWithTools( role="assistant", content=[ ToolUseContent( type="tool_use", id="call_1", name="search", input={"query": "Python tutorials"}, ) ], model="test-model", stopReason="toolUse", ) else: # Second call: call final_response tool_was_called = True return CreateMessageResultWithTools( role="assistant", content=[ ToolUseContent( type="tool_use", id="call_2", name="final_response", input={ "summary": "Python is great", "sources": ["python.org", "docs.python.org"], }, ) ], model="test-model", stopReason="toolUse", ) mcp = FastMCP(sampling_handler=sampling_handler) @mcp.tool async def research(context: Context) -> str: result = await context.sample( messages="Research Python", tools=[search], result_type=SearchResult, ) assert isinstance(result.result, SearchResult) return f"{result.result.summary} - {len(result.result.sources)} sources" async with Client(mcp) as client: result = await client.call_tool("research", {}) assert tool_was_called assert result.data == "Python is great - 2 sources" async def test_result_type_validation_error_retries(self): """Test that validation errors are sent back to LLM for retry.""" from mcp.types import ( CreateMessageResultWithTools, ToolResultContent, ToolUseContent, ) from pydantic import BaseModel class StrictResult(BaseModel): value: int # Must be an int messages_received: list[list[SamplingMessage]] = [] def sampling_handler( messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext ) -> CreateMessageResultWithTools: messages_received.append(list(messages)) if len(messages_received) == 1: # First call: invalid type return CreateMessageResultWithTools( role="assistant", content=[ ToolUseContent( type="tool_use", id="call_1", name="final_response", input={"value": "not_an_int"}, # Wrong type ) ], model="test-model", stopReason="toolUse", ) else: # Second call: valid type after seeing error return CreateMessageResultWithTools( role="assistant", content=[ ToolUseContent( type="tool_use", id="call_2", name="final_response", input={"value": 42}, # Correct type ) ], model="test-model", stopReason="toolUse", ) mcp = FastMCP(sampling_handler=sampling_handler) @mcp.tool async def validate_tool(context: Context) -> str: result = await context.sample( messages="Give me a number", result_type=StrictResult, ) assert isinstance(result.result, StrictResult) return str(result.result.value) async with Client(mcp) as client: result = await client.call_tool("validate_tool", {}) # Should have retried after validation error assert len(messages_received) == 2 # Check that error was passed back last_messages = messages_received[1] # Find the tool result in list content tool_result = None for msg in last_messages: # Tool results are now in a list if isinstance(msg.content, list): for item in msg.content: if isinstance(item, ToolResultContent): tool_result = item break elif isinstance(msg.content, ToolResultContent): tool_result = msg.content break assert tool_result is not None assert tool_result.isError is True assert isinstance(tool_result.content[0], TextContent) error_text = tool_result.content[0].text assert "Validation error" in error_text # Final result should be correct assert result.data == "42" async def test_sampling_result_has_text_and_history(self): """Test that SamplingResult has text, result, and history attributes.""" from mcp.types import CreateMessageResultWithTools def sampling_handler( messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext ) -> CreateMessageResultWithTools: return CreateMessageResultWithTools( role="assistant", content=[TextContent(type="text", text="Hello world")], model="test-model", stopReason="endTurn", ) mcp = FastMCP(sampling_handler=sampling_handler) @mcp.tool async def check_result(context: Context) -> str: result = await context.sample(messages="Say hello") # Check all attributes exist assert result.text == "Hello world" assert result.result == "Hello world" assert len(result.history) >= 1 return "ok" async with Client(mcp) as client: result = await client.call_tool("check_result", {}) assert result.data == "ok" class TestSampleStep: """Tests for ctx.sample_step() - single LLM call with manual control.""" async def test_sample_step_basic(self): """Test basic sample_step returns text response.""" from mcp.types import CreateMessageResultWithTools def sampling_handler( messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext ) -> CreateMessageResultWithTools: return CreateMessageResultWithTools( role="assistant", content=[TextContent(type="text", text="Hello from step")], model="test-model", stopReason="endTurn", ) mcp = FastMCP(sampling_handler=sampling_handler) @mcp.tool async def test_step(context: Context) -> str: step = await context.sample_step(messages="Hi") assert not step.is_tool_use assert step.text == "Hello from step" return step.text or "" async with Client(mcp) as client: result = await client.call_tool("test_step", {}) assert result.data == "Hello from step" async def test_sample_step_with_tool_execution(self): """Test sample_step executes tools by default.""" from mcp.types import CreateMessageResultWithTools, ToolUseContent call_count = 0 def my_tool(x: int) -> str: """A test tool.""" return f"result:{x}" def sampling_handler( messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext ) -> CreateMessageResultWithTools: nonlocal call_count call_count += 1 if call_count == 1: return CreateMessageResultWithTools( role="assistant", content=[ ToolUseContent( type="tool_use", id="call_1", name="my_tool", input={"x": 42}, ) ], model="test-model", stopReason="toolUse", ) else: return CreateMessageResultWithTools( role="assistant", content=[TextContent(type="text", text="Done")], model="test-model", stopReason="endTurn", ) mcp = FastMCP(sampling_handler=sampling_handler) @mcp.tool async def test_step(context: Context) -> str: messages: str | list[SamplingMessage] = "Run tool" while True: step = await context.sample_step(messages=messages, tools=[my_tool]) if not step.is_tool_use: return step.text or "" # History should include tool results when execute_tools=True messages = step.history async with Client(mcp) as client: result = await client.call_tool("test_step", {}) assert result.data == "Done" assert call_count == 2 async def test_sample_step_execute_tools_false(self): """Test sample_step with execute_tools=False doesn't execute tools.""" from mcp.types import CreateMessageResultWithTools, ToolUseContent tool_executed = False def my_tool() -> str: """A test tool.""" nonlocal tool_executed tool_executed = True return "executed" def sampling_handler( messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext ) -> CreateMessageResultWithTools: return CreateMessageResultWithTools( role="assistant", content=[ ToolUseContent( type="tool_use", id="call_1", name="my_tool", input={}, ) ], model="test-model", stopReason="toolUse", ) mcp = FastMCP(sampling_handler=sampling_handler) @mcp.tool async def test_step(context: Context) -> str: step = await context.sample_step( messages="Run tool", tools=[my_tool], execute_tools=False, ) assert step.is_tool_use assert len(step.tool_calls) == 1 assert step.tool_calls[0].name == "my_tool" # History should include assistant message but no tool results assert len(step.history) == 2 # user + assistant return "ok" async with Client(mcp) as client: result = await client.call_tool("test_step", {}) assert result.data == "ok" assert not tool_executed # Tool should not have been executed async def test_sample_step_history_includes_assistant_message(self): """Test that history includes assistant message when execute_tools=False.""" from mcp.types import CreateMessageResultWithTools, ToolUseContent def sampling_handler( messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext ) -> CreateMessageResultWithTools: return CreateMessageResultWithTools( role="assistant", content=[ ToolUseContent( type="tool_use", id="call_1", name="my_tool", input={"query": "test"}, ) ], model="test-model", stopReason="toolUse", ) mcp = FastMCP(sampling_handler=sampling_handler) def my_tool(query: str) -> str: return f"result for {query}" @mcp.tool async def test_step(context: Context) -> str: step = await context.sample_step( messages="Search", tools=[my_tool], execute_tools=False, ) # History should have: user message + assistant message assert len(step.history) == 2 assert step.history[0].role == "user" assert step.history[1].role == "assistant" return "ok" async with Client(mcp) as client: result = await client.call_tool("test_step", {}) assert result.data == "ok"
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/client/test_sampling_result_types.py", "license": "Apache License 2.0", "lines": 367, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/client/test_sampling_tool_loop.py
from typing import cast from mcp.types import TextContent from fastmcp import Client, Context, FastMCP from fastmcp.client.sampling import RequestContext, SamplingMessage, SamplingParams from fastmcp.server.sampling import SamplingTool class TestAutomaticToolLoop: """Tests for automatic tool execution loop in ctx.sample().""" async def test_automatic_tool_loop_executes_tools(self): """Test that ctx.sample() automatically executes tool calls.""" from mcp.types import CreateMessageResultWithTools, ToolUseContent call_count = 0 tool_was_called = False def get_weather(city: str) -> str: """Get weather for a city.""" nonlocal tool_was_called tool_was_called = True return f"Weather in {city}: sunny, 72°F" def sampling_handler( messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext ) -> CreateMessageResultWithTools: nonlocal call_count call_count += 1 if call_count == 1: # First call: return tool use return CreateMessageResultWithTools( role="assistant", content=[ ToolUseContent( type="tool_use", id="call_1", name="get_weather", input={"city": "Seattle"}, ) ], model="test-model", stopReason="toolUse", ) else: # Second call: return final response return CreateMessageResultWithTools( role="assistant", content=[TextContent(type="text", text="The weather is sunny!")], model="test-model", stopReason="endTurn", ) mcp = FastMCP(sampling_handler=sampling_handler) @mcp.tool async def weather_assistant(question: str, context: Context) -> str: result = await context.sample( messages=question, tools=[get_weather], ) # Get text from SamplingResult return result.text or "" async with Client(mcp) as client: result = await client.call_tool( "weather_assistant", {"question": "What's the weather?"} ) assert tool_was_called assert call_count == 2 assert result.data == "The weather is sunny!" async def test_automatic_tool_loop_multiple_tools(self): """Test that multiple tool calls in one response are all executed.""" from mcp.types import CreateMessageResultWithTools, ToolUseContent executed_tools: list[str] = [] def tool_a(x: int) -> int: """Tool A.""" executed_tools.append(f"tool_a({x})") return x * 2 def tool_b(y: int) -> int: """Tool B.""" executed_tools.append(f"tool_b({y})") return y + 10 call_count = 0 def sampling_handler( messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext ) -> CreateMessageResultWithTools: nonlocal call_count call_count += 1 if call_count == 1: # Return multiple tool calls return CreateMessageResultWithTools( role="assistant", content=[ ToolUseContent( type="tool_use", id="call_a", name="tool_a", input={"x": 5} ), ToolUseContent( type="tool_use", id="call_b", name="tool_b", input={"y": 3} ), ], model="test-model", stopReason="toolUse", ) else: return CreateMessageResultWithTools( role="assistant", content=[TextContent(type="text", text="Done!")], model="test-model", stopReason="endTurn", ) mcp = FastMCP(sampling_handler=sampling_handler) @mcp.tool async def multi_tool(context: Context) -> str: result = await context.sample(messages="Run tools", tools=[tool_a, tool_b]) return result.text or "" async with Client(mcp) as client: result = await client.call_tool("multi_tool", {}) assert executed_tools == ["tool_a(5)", "tool_b(3)"] assert result.data == "Done!" async def test_automatic_tool_loop_handles_unknown_tool(self): """Test that unknown tool names result in error being passed to LLM.""" from mcp.types import ( CreateMessageResultWithTools, ToolResultContent, ToolUseContent, ) def known_tool() -> str: """A known tool.""" return "known result" messages_received: list[list[SamplingMessage]] = [] def sampling_handler( messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext ) -> CreateMessageResultWithTools: messages_received.append(list(messages)) if len(messages_received) == 1: # Request unknown tool return CreateMessageResultWithTools( role="assistant", content=[ ToolUseContent( type="tool_use", id="call_1", name="unknown_tool", input={}, ) ], model="test-model", stopReason="toolUse", ) else: return CreateMessageResultWithTools( role="assistant", content=[TextContent(type="text", text="Handled error")], model="test-model", stopReason="endTurn", ) mcp = FastMCP(sampling_handler=sampling_handler) @mcp.tool async def test_unknown(context: Context) -> str: result = await context.sample(messages="Test", tools=[known_tool]) return result.text or "" async with Client(mcp) as client: result = await client.call_tool("test_unknown", {}) # Check that error was passed back in messages assert len(messages_received) == 2 last_messages = messages_received[1] # Find the tool result in list content tool_result = None for msg in last_messages: # Tool results are now in a list if isinstance(msg.content, list): for item in msg.content: if isinstance(item, ToolResultContent): tool_result = item break elif isinstance(msg.content, ToolResultContent): tool_result = msg.content break assert tool_result is not None assert tool_result.isError is True # Content is list of TextContent objects assert isinstance(tool_result.content[0], TextContent) error_text = tool_result.content[0].text assert "Unknown tool" in error_text assert result.data == "Handled error" async def test_automatic_tool_loop_handles_tool_exception(self): """Test that tool exceptions are caught and passed to LLM as errors.""" from mcp.types import ( CreateMessageResultWithTools, ToolResultContent, ToolUseContent, ) def failing_tool() -> str: """A tool that raises an exception.""" raise ValueError("Tool failed intentionally") messages_received: list[list[SamplingMessage]] = [] def sampling_handler( messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext ) -> CreateMessageResultWithTools: messages_received.append(list(messages)) if len(messages_received) == 1: return CreateMessageResultWithTools( role="assistant", content=[ ToolUseContent( type="tool_use", id="call_1", name="failing_tool", input={}, ) ], model="test-model", stopReason="toolUse", ) else: return CreateMessageResultWithTools( role="assistant", content=[TextContent(type="text", text="Handled error")], model="test-model", stopReason="endTurn", ) mcp = FastMCP(sampling_handler=sampling_handler) @mcp.tool async def test_exception(context: Context) -> str: result = await context.sample(messages="Test", tools=[failing_tool]) return result.text or "" async with Client(mcp) as client: result = await client.call_tool("test_exception", {}) # Check that error was passed back assert len(messages_received) == 2 last_messages = messages_received[1] # Find the tool result in list content tool_result = None for msg in last_messages: # Tool results are now in a list if isinstance(msg.content, list): for item in msg.content: if isinstance(item, ToolResultContent): tool_result = item break elif isinstance(msg.content, ToolResultContent): tool_result = msg.content break assert tool_result is not None assert tool_result.isError is True # Content is list of TextContent objects assert isinstance(tool_result.content[0], TextContent) error_text = tool_result.content[0].text assert "Tool failed intentionally" in error_text assert result.data == "Handled error" async def test_concurrent_tool_execution_default_sequential(self): """Test that tools execute sequentially by default.""" import asyncio import time from mcp.types import CreateMessageResultWithTools, ToolUseContent execution_order: list[tuple[str, float]] = [] async def slow_tool_a(x: int) -> int: """Slow tool A.""" start = time.time() execution_order.append(("tool_a_start", start)) await asyncio.sleep(0.1) execution_order.append(("tool_a_end", time.time())) return x * 2 async def slow_tool_b(y: int) -> int: """Slow tool B.""" start = time.time() execution_order.append(("tool_b_start", start)) await asyncio.sleep(0.1) execution_order.append(("tool_b_end", time.time())) return y + 10 call_count = 0 def sampling_handler( messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext ) -> CreateMessageResultWithTools: nonlocal call_count call_count += 1 if call_count == 1: return CreateMessageResultWithTools( role="assistant", content=[ ToolUseContent( type="tool_use", id="call_a", name="slow_tool_a", input={"x": 5}, ), ToolUseContent( type="tool_use", id="call_b", name="slow_tool_b", input={"y": 3}, ), ], model="test-model", stopReason="toolUse", ) else: return CreateMessageResultWithTools( role="assistant", content=[TextContent(type="text", text="Done!")], model="test-model", stopReason="endTurn", ) mcp = FastMCP(sampling_handler=sampling_handler) @mcp.tool async def test_tool(context: Context) -> str: result = await context.sample( messages="Run tools", tools=[slow_tool_a, slow_tool_b], # Default: tool_concurrency=None (sequential) ) return result.text or "" async with Client(mcp) as client: result = await client.call_tool("test_tool", {}) assert result.data == "Done!" # Verify sequential execution: tool_a must complete before tool_b starts events = [e[0] for e in execution_order] assert events == ["tool_a_start", "tool_a_end", "tool_b_start", "tool_b_end"] async def test_concurrent_tool_execution_unlimited(self): """Test unlimited parallel tool execution with tool_concurrency=0.""" import asyncio import time from mcp.types import CreateMessageResultWithTools, ToolUseContent execution_times: dict[str, dict[str, float]] = {} async def slow_tool_a(x: int) -> int: """Slow tool A.""" execution_times["tool_a"] = {"start": time.time()} await asyncio.sleep(0.1) execution_times["tool_a"]["end"] = time.time() return x * 2 async def slow_tool_b(y: int) -> int: """Slow tool B.""" execution_times["tool_b"] = {"start": time.time()} await asyncio.sleep(0.1) execution_times["tool_b"]["end"] = time.time() return y + 10 call_count = 0 def sampling_handler( messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext ) -> CreateMessageResultWithTools: nonlocal call_count call_count += 1 if call_count == 1: return CreateMessageResultWithTools( role="assistant", content=[ ToolUseContent( type="tool_use", id="call_a", name="slow_tool_a", input={"x": 5}, ), ToolUseContent( type="tool_use", id="call_b", name="slow_tool_b", input={"y": 3}, ), ], model="test-model", stopReason="toolUse", ) else: return CreateMessageResultWithTools( role="assistant", content=[TextContent(type="text", text="Done!")], model="test-model", stopReason="endTurn", ) mcp = FastMCP(sampling_handler=sampling_handler) @mcp.tool async def test_tool(context: Context) -> str: result = await context.sample( messages="Run tools", tools=[slow_tool_a, slow_tool_b], tool_concurrency=0, # Unlimited parallel ) return result.text or "" async with Client(mcp) as client: result = await client.call_tool("test_tool", {}) assert result.data == "Done!" # Verify parallel execution: both tools should overlap in time assert "tool_a" in execution_times assert "tool_b" in execution_times # tool_b should start before tool_a finishes (overlap) assert execution_times["tool_b"]["start"] < execution_times["tool_a"]["end"] async def test_concurrent_tool_execution_bounded(self): """Test bounded parallel execution with tool_concurrency=2.""" import asyncio import time from mcp.types import CreateMessageResultWithTools, ToolUseContent execution_order: list[tuple[str, float]] = [] async def slow_tool(name: str, duration: float = 0.1) -> str: """Generic slow tool.""" execution_order.append((f"{name}_start", time.time())) await asyncio.sleep(duration) execution_order.append((f"{name}_end", time.time())) return f"{name} done" call_count = 0 def sampling_handler( messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext ) -> CreateMessageResultWithTools: nonlocal call_count call_count += 1 if call_count == 1: # Request 3 tools (with concurrency=2, first 2 run parallel, then 3rd) return CreateMessageResultWithTools( role="assistant", content=[ ToolUseContent( type="tool_use", id="call_1", name="slow_tool", input={"name": "tool_1", "duration": 0.1}, ), ToolUseContent( type="tool_use", id="call_2", name="slow_tool", input={"name": "tool_2", "duration": 0.1}, ), ToolUseContent( type="tool_use", id="call_3", name="slow_tool", input={"name": "tool_3", "duration": 0.05}, ), ], model="test-model", stopReason="toolUse", ) else: return CreateMessageResultWithTools( role="assistant", content=[TextContent(type="text", text="Done!")], model="test-model", stopReason="endTurn", ) mcp = FastMCP(sampling_handler=sampling_handler) @mcp.tool async def test_tool(context: Context) -> str: result = await context.sample( messages="Run tools", tools=[slow_tool], tool_concurrency=2, # Max 2 concurrent ) return result.text or "" async with Client(mcp) as client: result = await client.call_tool("test_tool", {}) assert result.data == "Done!" # Verify that at most 2 tools run concurrently events = [e[0] for e in execution_order] # First 2 tools should start before either ends assert events[0] in ["tool_1_start", "tool_2_start"] assert events[1] in ["tool_1_start", "tool_2_start"] # Third tool should start after at least one of the first two finishes tool_3_start_idx = events.index("tool_3_start") assert ( "tool_1_end" in events[:tool_3_start_idx] or "tool_2_end" in events[:tool_3_start_idx] ) async def test_sequential_tool_forces_sequential_execution(self): """Test that sequential=True forces all tools to execute sequentially.""" import asyncio import time from mcp.types import CreateMessageResultWithTools, ToolUseContent execution_order: list[tuple[str, float]] = [] async def normal_tool(x: int) -> int: """Normal tool.""" execution_order.append(("normal_start", time.time())) await asyncio.sleep(0.05) execution_order.append(("normal_end", time.time())) return x * 2 async def sequential_tool(y: int) -> int: """Sequential tool.""" execution_order.append(("sequential_start", time.time())) await asyncio.sleep(0.05) execution_order.append(("sequential_end", time.time())) return y + 10 call_count = 0 def sampling_handler( messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext ) -> CreateMessageResultWithTools: nonlocal call_count call_count += 1 if call_count == 1: return CreateMessageResultWithTools( role="assistant", content=[ ToolUseContent( type="tool_use", id="call_1", name="normal_tool", input={"x": 5}, ), ToolUseContent( type="tool_use", id="call_2", name="sequential_tool", input={"y": 3}, ), ], model="test-model", stopReason="toolUse", ) else: return CreateMessageResultWithTools( role="assistant", content=[TextContent(type="text", text="Done!")], model="test-model", stopReason="endTurn", ) mcp = FastMCP(sampling_handler=sampling_handler) @mcp.tool async def test_tool(context: Context) -> str: # Create tools with sequential=True for one of them normal = SamplingTool.from_function(normal_tool, sequential=False) sequential = SamplingTool.from_function(sequential_tool, sequential=True) result = await context.sample( messages="Run tools", tools=[normal, sequential], tool_concurrency=0, # Request unlimited, but sequential tool forces sequential ) return result.text or "" async with Client(mcp) as client: result = await client.call_tool("test_tool", {}) assert result.data == "Done!" # Verify sequential execution: first tool must complete before second starts events = [e[0] for e in execution_order] assert events[0] in ["normal_start", "sequential_start"] assert events[1] in ["normal_end", "sequential_end"] # Ensure the second tool starts after the first ends if events[0] == "normal_start": assert events[1] == "normal_end" assert events[2] == "sequential_start" else: assert events[1] == "sequential_end" assert events[2] == "normal_start" async def test_concurrent_tool_execution_error_handling(self): """Test that errors are captured per-tool in parallel execution.""" from mcp.types import ( CreateMessageResultWithTools, ToolResultContent, ToolUseContent, ) def good_tool() -> str: return "success" def bad_tool() -> str: raise ValueError("Tool error") messages_received: list[list[SamplingMessage]] = [] def sampling_handler( messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext ) -> CreateMessageResultWithTools: messages_received.append(list(messages)) if len(messages_received) == 1: return CreateMessageResultWithTools( role="assistant", content=[ ToolUseContent( type="tool_use", id="call_1", name="good_tool", input={} ), ToolUseContent( type="tool_use", id="call_2", name="bad_tool", input={} ), ], model="test-model", stopReason="toolUse", ) else: return CreateMessageResultWithTools( role="assistant", content=[TextContent(type="text", text="Handled errors")], model="test-model", stopReason="endTurn", ) mcp = FastMCP(sampling_handler=sampling_handler) @mcp.tool async def test_tool(context: Context) -> str: result = await context.sample( messages="Run tools", tools=[good_tool, bad_tool], tool_concurrency=0, # Parallel execution ) return result.text or "" async with Client(mcp) as client: result = await client.call_tool("test_tool", {}) assert result.data == "Handled errors" # Check that tool results include both success and error tool_result_message = messages_received[1][-1] assert tool_result_message.role == "user" tool_results = cast(list[ToolResultContent], tool_result_message.content) assert len(tool_results) == 2 # One should be success, one should be error assert any(not r.isError for r in tool_results) assert any(r.isError for r in tool_results) async def test_concurrent_tool_result_order_preserved(self): """Test that tool results maintain the same order as tool calls.""" import asyncio from mcp.types import ( CreateMessageResultWithTools, ToolResultContent, ToolUseContent, ) async def tool_with_delay(value: int, delay: float) -> int: """Tool that takes variable time.""" await asyncio.sleep(delay) return value messages_received: list[list[SamplingMessage]] = [] def sampling_handler( messages: list[SamplingMessage], params: SamplingParams, ctx: RequestContext ) -> CreateMessageResultWithTools: messages_received.append(list(messages)) if len(messages_received) == 1: # Tools with different delays - later tools finish first return CreateMessageResultWithTools( role="assistant", content=[ ToolUseContent( type="tool_use", id="call_1", name="tool_with_delay", input={"value": 1, "delay": 0.15}, ), ToolUseContent( type="tool_use", id="call_2", name="tool_with_delay", input={"value": 2, "delay": 0.05}, ), ToolUseContent( type="tool_use", id="call_3", name="tool_with_delay", input={"value": 3, "delay": 0.1}, ), ], model="test-model", stopReason="toolUse", ) else: return CreateMessageResultWithTools( role="assistant", content=[TextContent(type="text", text="Done!")], model="test-model", stopReason="endTurn", ) mcp = FastMCP(sampling_handler=sampling_handler) @mcp.tool async def test_tool(context: Context) -> str: result = await context.sample( messages="Run tools", tools=[tool_with_delay], tool_concurrency=0, # Parallel execution ) return result.text or "" async with Client(mcp) as client: result = await client.call_tool("test_tool", {}) assert result.data == "Done!" # Check that results are in the correct order (1, 2, 3) despite finishing order (2, 3, 1) tool_result_message = messages_received[1][-1] tool_results = cast(list[ToolResultContent], tool_result_message.content) assert len(tool_results) == 3 assert tool_results[0].toolUseId == "call_1" assert tool_results[1].toolUseId == "call_2" assert tool_results[2].toolUseId == "call_3" # Check values are correct result_texts = [cast(TextContent, r.content[0]).text for r in tool_results] assert result_texts == ["1", "2", "3"]
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/client/test_sampling_tool_loop.py", "license": "Apache License 2.0", "lines": 659, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/resources/test_resource_template_query_params.py
import pytest from fastmcp.resources import ResourceTemplate class TestQueryParameterExtraction: """Test basic query parameter extraction from URIs.""" async def test_single_query_param(self): """Test resource template with single query parameter.""" def get_data(id: str, format: str = "json") -> str: return f"Data {id} in {format}" template = ResourceTemplate.from_function( fn=get_data, uri_template="data://{id}{?format}", name="test", ) # Match without query param (uses default) params = template.matches("data://123") assert params == {"id": "123"} # Match with query param params = template.matches("data://123?format=xml") assert params == {"id": "123", "format": "xml"} async def test_multiple_query_params(self): """Test resource template with multiple query parameters.""" def get_items(category: str, page: int = 1, limit: int = 10) -> str: return f"Category {category}, page {page}, limit {limit}" template = ResourceTemplate.from_function( fn=get_items, uri_template="items://{category}{?page,limit}", name="test", ) # No query params params = template.matches("items://books") assert params == {"category": "books"} # One query param params = template.matches("items://books?page=2") assert params == {"category": "books", "page": "2"} # Both query params params = template.matches("items://books?page=2&limit=20") assert params == {"category": "books", "page": "2", "limit": "20"} class TestQueryParameterTypeCoercion: """Test type coercion for query parameters.""" async def test_int_coercion(self): """Test integer type coercion for query parameters.""" def get_page(resource: str, page: int = 1) -> dict: return {"resource": resource, "page": page, "type": type(page).__name__} template = ResourceTemplate.from_function( fn=get_page, uri_template="resource://{resource}{?page}", name="test", ) # Create resource with string query param resource = await template.create_resource( "resource://docs?page=5", {"resource": "docs", "page": "5"}, ) # read() returns raw dict result = await resource.read() assert isinstance(result, dict) assert result["page"] == 5 assert result["type"] == "int" async def test_bool_coercion(self): """Test boolean type coercion for query parameters.""" def get_config(name: str, enabled: bool = False) -> dict: return {"name": name, "enabled": enabled, "type": type(enabled).__name__} template = ResourceTemplate.from_function( fn=get_config, uri_template="config://{name}{?enabled}", name="test", ) # Test true value resource = await template.create_resource( "config://feature?enabled=true", {"name": "feature", "enabled": "true"}, ) # read() returns raw dict result = await resource.read() assert isinstance(result, dict) assert result["enabled"] is True # Test false value resource = await template.create_resource( "config://feature?enabled=false", {"name": "feature", "enabled": "false"}, ) result = await resource.read() assert isinstance(result, dict) assert result["enabled"] is False async def test_float_coercion(self): """Test float type coercion for query parameters.""" def get_metrics(service: str, threshold: float = 0.5) -> dict: return { "service": service, "threshold": threshold, "type": type(threshold).__name__, } template = ResourceTemplate.from_function( fn=get_metrics, uri_template="metrics://{service}{?threshold}", name="test", ) resource = await template.create_resource( "metrics://api?threshold=0.95", {"service": "api", "threshold": "0.95"}, ) # read() returns raw dict result = await resource.read() assert isinstance(result, dict) assert result["threshold"] == 0.95 assert result["type"] == "float" class TestQueryParameterValidation: """Test validation rules for query parameters.""" def test_query_params_must_be_optional(self): """Test that query parameters must have default values.""" def invalid_func(id: str, format: str) -> str: return f"Data {id} in {format}" with pytest.raises( ValueError, match="Query parameters .* must be optional function parameters with default values", ): ResourceTemplate.from_function( fn=invalid_func, uri_template="data://{id}{?format}", name="test", ) def test_required_params_in_path(self): """Test that required parameters must be in path.""" def valid_func(id: str, format: str = "json") -> str: return f"Data {id} in {format}" # This should work - required param in path, optional in query template = ResourceTemplate.from_function( fn=valid_func, uri_template="data://{id}{?format}", name="test", ) assert template.uri_template == "data://{id}{?format}" class TestQueryParameterWithDefaults: """Test that missing query parameters use default values.""" async def test_missing_query_param_uses_default(self): """Test that missing query parameters fall back to defaults.""" def get_data(id: str, format: str = "json", verbose: bool = False) -> dict: return {"id": id, "format": format, "verbose": verbose} template = ResourceTemplate.from_function( fn=get_data, uri_template="data://{id}{?format,verbose}", name="test", ) # No query params - should use defaults resource = await template.create_resource( "data://123", {"id": "123"}, ) # read() returns raw dict result = await resource.read() assert isinstance(result, dict) assert result["format"] == "json" assert result["verbose"] is False async def test_partial_query_params(self): """Test providing only some query parameters.""" def get_data( id: str, format: str = "json", limit: int = 10, offset: int = 0 ) -> dict: return {"id": id, "format": format, "limit": limit, "offset": offset} template = ResourceTemplate.from_function( fn=get_data, uri_template="data://{id}{?format,limit,offset}", name="test", ) # Provide only some query params resource = await template.create_resource( "data://123?limit=20", {"id": "123", "limit": "20"}, ) # read() returns raw dict result = await resource.read() assert isinstance(result, dict) assert result["format"] == "json" # default assert result["limit"] == 20 # provided assert result["offset"] == 0 # default class TestQueryParameterWithWildcards: """Test query parameters combined with wildcard path parameters.""" async def test_wildcard_with_query_params(self): """Test combining wildcard path params with query params.""" def get_file(path: str, encoding: str = "utf-8", lines: int = 100) -> dict: return {"path": path, "encoding": encoding, "lines": lines} template = ResourceTemplate.from_function( fn=get_file, uri_template="files://{path*}{?encoding,lines}", name="test", ) # Match path with query params params = template.matches("files://src/test/data.txt?encoding=ascii&lines=50") assert params == { "path": "src/test/data.txt", "encoding": "ascii", "lines": "50", } # Create resource resource = await template.create_resource( "files://src/test/data.txt?lines=50", {"path": "src/test/data.txt", "lines": "50"}, ) # read() returns raw dict result = await resource.read() assert isinstance(result, dict) assert result["path"] == "src/test/data.txt" assert result["encoding"] == "utf-8" # default assert result["lines"] == 50 # provided class TestBooleanQueryParameterValidation: """Test that invalid boolean query parameter values raise errors.""" async def _make_template(self): def get_config(name: str, enabled: bool = False) -> dict: return {"name": name, "enabled": enabled} return ResourceTemplate.from_function( fn=get_config, uri_template="config://{name}{?enabled}", name="test", ) async def test_invalid_boolean_value_raises_error(self): """Test that nonsense boolean values like 'banana' raise ValueError.""" template = await self._make_template() with pytest.raises(ValueError, match="Invalid boolean value for enabled"): resource = await template.create_resource( "config://feature?enabled=banana", {"name": "feature", "enabled": "banana"}, ) await resource.read() @pytest.mark.parametrize( "value", ["true", "True", "TRUE", "1", "yes", "Yes", "YES"] ) async def test_valid_true_values(self, value: str): """Test that all accepted truthy string values coerce to True.""" template = await self._make_template() resource = await template.create_resource( f"config://feature?enabled={value}", {"name": "feature", "enabled": value}, ) result = await resource.read() assert isinstance(result, dict) assert result["enabled"] is True @pytest.mark.parametrize( "value", ["false", "False", "FALSE", "0", "no", "No", "NO"] ) async def test_valid_false_values(self, value: str): """Test that all accepted falsy string values coerce to False.""" template = await self._make_template() resource = await template.create_resource( f"config://feature?enabled={value}", {"name": "feature", "enabled": value}, ) result = await resource.read() assert isinstance(result, dict) assert result["enabled"] is False @pytest.mark.parametrize("value", ["banana", "nope", "2", "truee", ""]) async def test_various_invalid_boolean_values(self, value: str): """Test that various invalid boolean strings raise ValueError.""" template = await self._make_template() with pytest.raises(ValueError, match="Invalid boolean value for enabled"): resource = await template.create_resource( f"config://feature?enabled={value}", {"name": "feature", "enabled": value}, ) await resource.read() class TestResourceTemplateFieldDefaults: """Test resource templates with Field() defaults.""" async def test_field_with_default(self): """Test that Field(default=...) correctly provides default values in resource templates.""" from pydantic import Field def get_data( id: str = Field(description="Resource ID"), format: str = Field(default="json", description="Output format"), ) -> str: return f"id={id}, format={format}" template = ResourceTemplate.from_function( fn=get_data, uri_template="data://{id}{?format}", name="test", ) # Test with only required parameter resource = await template.create_resource("data://123", {"id": "123"}) result = await resource.read() assert result == "id=123, format=json" # Test with override resource = await template.create_resource( "data://123?format=xml", {"id": "123", "format": "xml"} ) result = await resource.read() assert result == "id=123, format=xml" async def test_multiple_field_defaults(self): """Test multiple query parameters with Field() defaults.""" from typing import Any from pydantic import Field def fetch_data( resource_id: str = Field(description="Resource ID"), limit: int = Field(default=10, description="Result limit"), offset: int = Field(default=0, description="Result offset"), format: str = Field(default="json", description="Output format"), ) -> dict[str, Any]: return { "resource_id": resource_id, "limit": limit, "offset": offset, "format": format, } template = ResourceTemplate.from_function( fn=fetch_data, uri_template="api://{resource_id}{?limit,offset,format}", name="test", ) # Test with only required parameter - all defaults should apply resource1 = await template.create_resource( "api://user123", {"resource_id": "user123"} ) result1 = await resource1.read() assert isinstance(result1, dict) assert result1["resource_id"] == "user123" assert result1["limit"] == 10 assert result1["offset"] == 0 assert result1["format"] == "json" # Test with some overrides resource2 = await template.create_resource( "api://user123?limit=50&format=xml", {"resource_id": "user123", "limit": "50", "format": "xml"}, ) result2 = await resource2.read() assert isinstance(result2, dict) assert result2["resource_id"] == "user123" assert result2["limit"] == 50 # overridden assert result2["offset"] == 0 # default assert result2["format"] == "xml" # overridden
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/resources/test_resource_template_query_params.py", "license": "Apache License 2.0", "lines": 326, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/server/auth/providers/test_azure_scopes.py
"""Tests for Azure provider scope handling, JWT verifier, and OBO integration.""" import pytest from key_value.aio.stores.memory import MemoryStore from fastmcp.server.auth.providers.azure import ( OIDC_SCOPES, AzureJWTVerifier, AzureProvider, ) from fastmcp.server.auth.providers.jwt import RSAKeyPair @pytest.fixture def memory_storage() -> MemoryStore: """Provide a MemoryStore for tests to avoid SQLite initialization on Windows.""" return MemoryStore() class TestOIDCScopeHandling: """Tests for OIDC scope handling in Azure provider. Azure access tokens do NOT include OIDC scopes (openid, profile, email, offline_access) in the `scp` claim - they're only used during authorization. These tests verify that: 1. OIDC scopes are never prefixed with identifier_uri 2. OIDC scopes are filtered from token validation 3. OIDC scopes are still advertised to clients via valid_scopes """ def test_oidc_scopes_constant(self, memory_storage: MemoryStore): """Verify OIDC_SCOPES contains the standard OIDC scopes.""" assert OIDC_SCOPES == {"openid", "profile", "email", "offline_access"} def test_prefix_scopes_does_not_prefix_oidc_scopes( self, memory_storage: MemoryStore ): """Test that _prefix_scopes_for_azure never prefixes OIDC scopes.""" provider = AzureProvider( client_id="test_client", client_secret="test_secret", tenant_id="test-tenant", base_url="https://myserver.com", identifier_uri="api://my-api", required_scopes=["read"], jwt_signing_key="test-secret", client_storage=memory_storage, ) # All OIDC scopes should pass through unchanged result = provider._prefix_scopes_for_azure( ["openid", "profile", "email", "offline_access"] ) assert result == ["openid", "profile", "email", "offline_access"] def test_prefix_scopes_mixed_oidc_and_custom(self, memory_storage: MemoryStore): """Test prefixing with a mix of OIDC and custom scopes.""" provider = AzureProvider( client_id="test_client", client_secret="test_secret", tenant_id="test-tenant", base_url="https://myserver.com", identifier_uri="api://my-api", required_scopes=["read"], jwt_signing_key="test-secret", client_storage=memory_storage, ) result = provider._prefix_scopes_for_azure( ["read", "openid", "write", "profile"] ) # Custom scopes should be prefixed, OIDC scopes should not assert "api://my-api/read" in result assert "api://my-api/write" in result assert "openid" in result assert "profile" in result # Verify OIDC scopes are NOT prefixed assert "api://my-api/openid" not in result assert "api://my-api/profile" not in result def test_prefix_scopes_dot_notation_gets_prefixed( self, memory_storage: MemoryStore ): """Test that dot-notation scopes get prefixed (use additional_authorize_scopes for Graph).""" provider = AzureProvider( client_id="test_client", client_secret="test_secret", tenant_id="test-tenant", base_url="https://myserver.com", identifier_uri="api://my-api", required_scopes=["read"], jwt_signing_key="test-secret", client_storage=memory_storage, ) # Dot-notation scopes ARE prefixed - use additional_authorize_scopes for Graph # or fully-qualified format like https://graph.microsoft.com/User.Read result = provider._prefix_scopes_for_azure(["my.scope", "admin.read"]) assert result == ["api://my-api/my.scope", "api://my-api/admin.read"] def test_prefix_scopes_fully_qualified_graph_not_prefixed( self, memory_storage: MemoryStore ): """Test that fully-qualified Graph scopes are not prefixed.""" provider = AzureProvider( client_id="test_client", client_secret="test_secret", tenant_id="test-tenant", base_url="https://myserver.com", identifier_uri="api://my-api", required_scopes=["read"], jwt_signing_key="test-secret", client_storage=memory_storage, ) result = provider._prefix_scopes_for_azure( [ "https://graph.microsoft.com/User.Read", "https://graph.microsoft.com/Mail.Send", ] ) # Fully-qualified URIs pass through unchanged assert result == [ "https://graph.microsoft.com/User.Read", "https://graph.microsoft.com/Mail.Send", ] def test_required_scopes_with_oidc_filters_validation( self, memory_storage: MemoryStore ): """Test that OIDC scopes in required_scopes are filtered from token validation.""" provider = AzureProvider( client_id="test_client", client_secret="test_secret", tenant_id="test-tenant", base_url="https://myserver.com", identifier_uri="api://my-api", required_scopes=["read", "openid", "profile"], jwt_signing_key="test-secret", client_storage=memory_storage, ) # Token validator should only require non-OIDC scopes assert provider._token_validator.required_scopes == ["read"] def test_required_scopes_all_oidc_results_in_no_validation( self, memory_storage: MemoryStore ): """Test that if all required_scopes are OIDC, no scope validation occurs.""" provider = AzureProvider( client_id="test_client", client_secret="test_secret", tenant_id="test-tenant", base_url="https://myserver.com", identifier_uri="api://my-api", required_scopes=["openid", "profile"], jwt_signing_key="test-secret", client_storage=memory_storage, ) # Token validator should have empty required scopes (all were OIDC) assert provider._token_validator.required_scopes == [] def test_valid_scopes_includes_oidc_scopes(self, memory_storage: MemoryStore): """Test that valid_scopes advertises OIDC scopes to clients.""" provider = AzureProvider( client_id="test_client", client_secret="test_secret", tenant_id="test-tenant", base_url="https://myserver.com", identifier_uri="api://my-api", required_scopes=["read", "openid", "profile"], jwt_signing_key="test-secret", client_storage=memory_storage, ) # required_scopes (used for validation) excludes OIDC scopes assert provider.required_scopes == ["read"] # But valid_scopes (advertised to clients) includes all scopes assert provider.client_registration_options is not None assert provider.client_registration_options.valid_scopes == [ "read", "openid", "profile", ] def test_prepare_scopes_for_refresh_handles_oidc_scopes( self, memory_storage: MemoryStore ): """Test that token refresh correctly handles OIDC scopes.""" provider = AzureProvider( client_id="test_client", client_secret="test_secret", tenant_id="test-tenant", base_url="https://myserver.com", identifier_uri="api://my-api", required_scopes=["read"], jwt_signing_key="test-secret", client_storage=memory_storage, ) # Simulate stored scopes that include OIDC scopes result = provider._prepare_scopes_for_upstream_refresh( ["read", "openid", "profile"] ) # Custom scope should be prefixed, OIDC scopes should not assert "api://my-api/read" in result assert "openid" in result assert "profile" in result assert "api://my-api/openid" not in result assert "api://my-api/profile" not in result class TestAzureTokenExchangeScopes: """Tests for Azure provider's token exchange scope handling. Azure requires scopes to be sent during the authorization code exchange. The provider overrides _prepare_scopes_for_token_exchange to return properly prefixed scopes. """ def test_prepare_scopes_returns_prefixed_scopes(self, memory_storage: MemoryStore): """Test that _prepare_scopes_for_token_exchange returns prefixed scopes.""" provider = AzureProvider( client_id="test_client", client_secret="test_secret", tenant_id="test-tenant", base_url="https://myserver.com", identifier_uri="api://my-api", required_scopes=["read", "write"], jwt_signing_key="test-secret", client_storage=memory_storage, ) scopes = provider._prepare_scopes_for_token_exchange(["read", "write"]) assert len(scopes) > 0 assert "api://my-api/read" in scopes assert "api://my-api/write" in scopes def test_prepare_scopes_includes_additional_oidc_scopes( self, memory_storage: MemoryStore ): """Test that _prepare_scopes_for_token_exchange includes OIDC scopes.""" provider = AzureProvider( client_id="test_client", client_secret="test_secret", tenant_id="test-tenant", base_url="https://myserver.com", identifier_uri="api://my-api", required_scopes=["read"], additional_authorize_scopes=["openid", "profile", "offline_access"], jwt_signing_key="test-secret", client_storage=memory_storage, ) scopes = provider._prepare_scopes_for_token_exchange(["read"]) assert len(scopes) > 0 assert "api://my-api/read" in scopes assert "openid" in scopes assert "profile" in scopes assert "offline_access" in scopes def test_prepare_scopes_excludes_other_api_scopes( self, memory_storage: MemoryStore ): """Test token exchange excludes other API scopes (Azure AADSTS28000). Azure only allows ONE resource per token exchange. Other API scopes are requested during authorization but excluded from token exchange. """ provider = AzureProvider( client_id="00000000-1111-2222-3333-444444444444", client_secret="test_secret", tenant_id="test-tenant", base_url="https://myserver.com", required_scopes=["user_impersonation"], additional_authorize_scopes=[ "openid", "profile", "offline_access", "api://aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/user_impersonation", "api://11111111-2222-3333-4444-555555555555/user_impersonation", ], jwt_signing_key="test-secret", client_storage=memory_storage, ) scopes = provider._prepare_scopes_for_token_exchange(["user_impersonation"]) assert len(scopes) > 0 # Primary API scope should be prefixed with the provider's identifier_uri assert "api://00000000-1111-2222-3333-444444444444/user_impersonation" in scopes # OIDC scopes should be included assert "openid" in scopes assert "profile" in scopes assert "offline_access" in scopes # Other API scopes should NOT be included (Azure multi-resource limitation) assert not any("api://aaaaaaaa" in s for s in scopes) assert not any("api://11111111" in s for s in scopes) def test_prepare_scopes_deduplicates_scopes(self, memory_storage: MemoryStore): """Test that duplicate scopes are deduplicated.""" provider = AzureProvider( client_id="test_client", client_secret="test_secret", tenant_id="test-tenant", base_url="https://myserver.com", identifier_uri="api://my-api", required_scopes=["read"], additional_authorize_scopes=["api://my-api/read", "openid"], jwt_signing_key="test-secret", client_storage=memory_storage, ) # Pass a scope that will be prefixed to match one in additional_authorize_scopes scopes = provider._prepare_scopes_for_token_exchange(["read"]) assert len(scopes) > 0 # Should be deduplicated - api://my-api/read appears only once assert scopes.count("api://my-api/read") == 1 assert "openid" in scopes def test_extra_token_params_does_not_contain_scope( self, memory_storage: MemoryStore ): """Test that extra_token_params doesn't contain scope to avoid TypeError. Previously, Azure provider set extra_token_params={"scope": ...} during init. This caused a TypeError in exchange_refresh_token because it passes both scope=... AND **self._extra_token_params, resulting in: "got multiple values for keyword argument 'scope'" The fix uses the _prepare_scopes_for_token_exchange hook instead. """ provider = AzureProvider( client_id="test_client", client_secret="test_secret", tenant_id="test-tenant", base_url="https://myserver.com", identifier_uri="api://my-api", required_scopes=["read", "write"], additional_authorize_scopes=["openid", "profile", "offline_access"], jwt_signing_key="test-secret", client_storage=memory_storage, ) # extra_token_params should NOT contain "scope" to avoid TypeError during refresh assert "scope" not in provider._extra_token_params # Instead, scopes should be provided via the hook methods exchange_scopes = provider._prepare_scopes_for_token_exchange(["read", "write"]) assert len(exchange_scopes) > 0 refresh_scopes = provider._prepare_scopes_for_upstream_refresh( ["read", "write"] ) assert len(refresh_scopes) > 0 class TestAzureJWTVerifier: """Tests for AzureJWTVerifier pre-configured JWT verifier.""" def test_auto_configures_from_client_and_tenant(self): verifier = AzureJWTVerifier( client_id="my-client-id", tenant_id="my-tenant-id", required_scopes=["access_as_user"], ) assert ( verifier.jwks_uri == "https://login.microsoftonline.com/my-tenant-id/discovery/v2.0/keys" ) assert verifier.issuer == "https://login.microsoftonline.com/my-tenant-id/v2.0" assert verifier.audience == "my-client-id" assert verifier.algorithm == "RS256" assert verifier.required_scopes == ["access_as_user"] async def test_validates_short_form_scopes(self): key_pair = RSAKeyPair.generate() verifier = AzureJWTVerifier( client_id="my-client-id", tenant_id="my-tenant-id", required_scopes=["access_as_user"], ) # Override to use our test key instead of JWKS verifier.public_key = key_pair.public_key verifier.jwks_uri = None token = key_pair.create_token( subject="test-user", issuer="https://login.microsoftonline.com/my-tenant-id/v2.0", audience="my-client-id", additional_claims={"scp": "access_as_user"}, ) result = await verifier.load_access_token(token) assert result is not None assert "access_as_user" in result.scopes def test_scopes_supported_returns_prefixed_form(self): verifier = AzureJWTVerifier( client_id="my-client-id", tenant_id="my-tenant-id", required_scopes=["read", "write"], ) assert verifier.scopes_supported == [ "api://my-client-id/read", "api://my-client-id/write", ] def test_already_prefixed_scopes_pass_through(self): verifier = AzureJWTVerifier( client_id="my-client-id", tenant_id="my-tenant-id", required_scopes=["api://my-client-id/read"], ) assert verifier.scopes_supported == ["api://my-client-id/read"] def test_oidc_scopes_not_prefixed(self): verifier = AzureJWTVerifier( client_id="my-client-id", tenant_id="my-tenant-id", required_scopes=["openid", "read"], ) assert verifier.scopes_supported == ["openid", "api://my-client-id/read"] def test_custom_identifier_uri(self): verifier = AzureJWTVerifier( client_id="my-client-id", tenant_id="my-tenant-id", required_scopes=["read"], identifier_uri="api://custom-uri", ) assert verifier.scopes_supported == ["api://custom-uri/read"] def test_custom_base_authority_for_gov_cloud(self): verifier = AzureJWTVerifier( client_id="my-client-id", tenant_id="my-tenant-id", required_scopes=["read"], base_authority="login.microsoftonline.us", ) assert ( verifier.jwks_uri == "https://login.microsoftonline.us/my-tenant-id/discovery/v2.0/keys" ) assert verifier.issuer == "https://login.microsoftonline.us/my-tenant-id/v2.0" def test_scopes_supported_empty_when_no_required_scopes(self): verifier = AzureJWTVerifier( client_id="my-client-id", tenant_id="my-tenant-id", ) assert verifier.scopes_supported == [] def test_default_identifier_uri_uses_client_id(self): verifier = AzureJWTVerifier( client_id="abc-123", tenant_id="my-tenant-id", required_scopes=["read"], ) assert verifier.scopes_supported == ["api://abc-123/read"] def test_multi_tenant_organizations_skips_issuer(self): verifier = AzureJWTVerifier( client_id="my-client-id", tenant_id="organizations", ) assert verifier.issuer is None def test_multi_tenant_consumers_skips_issuer(self): verifier = AzureJWTVerifier( client_id="my-client-id", tenant_id="consumers", ) assert verifier.issuer is None def test_multi_tenant_common_skips_issuer(self): verifier = AzureJWTVerifier( client_id="my-client-id", tenant_id="common", ) assert verifier.issuer is None def test_specific_tenant_sets_issuer(self): verifier = AzureJWTVerifier( client_id="my-client-id", tenant_id="12345678-1234-1234-1234-123456789012", ) assert ( verifier.issuer == "https://login.microsoftonline.com/12345678-1234-1234-1234-123456789012/v2.0" ) class TestAzureOBOIntegration: """Tests for azure.identity OBO integration (get_obo_credential, EntraOBOToken).""" async def test_get_obo_credential_returns_configured_credential(self): """Test that get_obo_credential returns a properly configured credential.""" from unittest.mock import MagicMock, patch provider = AzureProvider( client_id="test-client-id", client_secret="test-client-secret", tenant_id="test-tenant-id", base_url="https://myserver.com", required_scopes=["read"], jwt_signing_key="test-secret", ) mock_credential = MagicMock() with patch( "azure.identity.aio.OnBehalfOfCredential", return_value=mock_credential ) as mock_class: credential = await provider.get_obo_credential( user_assertion="user-token-123" ) mock_class.assert_called_once_with( tenant_id="test-tenant-id", client_id="test-client-id", client_secret="test-client-secret", user_assertion="user-token-123", authority="https://login.microsoftonline.com", ) assert credential is mock_credential async def test_get_obo_credential_caches_by_assertion(self): """Test that the same assertion returns the cached credential.""" from unittest.mock import MagicMock, patch provider = AzureProvider( client_id="test-client-id", client_secret="test-client-secret", tenant_id="test-tenant-id", base_url="https://myserver.com", required_scopes=["read"], jwt_signing_key="test-secret", ) mock_credential = MagicMock() with patch( "azure.identity.aio.OnBehalfOfCredential", return_value=mock_credential ) as mock_class: first = await provider.get_obo_credential(user_assertion="same-token") second = await provider.get_obo_credential(user_assertion="same-token") assert first is second mock_class.assert_called_once() async def test_get_obo_credential_different_assertions_get_different_credentials( self, ): """Test that different assertions produce different credentials.""" from unittest.mock import MagicMock, patch provider = AzureProvider( client_id="test-client-id", client_secret="test-client-secret", tenant_id="test-tenant-id", base_url="https://myserver.com", required_scopes=["read"], jwt_signing_key="test-secret", ) creds = [MagicMock(), MagicMock()] with patch("azure.identity.aio.OnBehalfOfCredential", side_effect=creds): first = await provider.get_obo_credential(user_assertion="token-a") second = await provider.get_obo_credential(user_assertion="token-b") assert first is not second assert first is creds[0] assert second is creds[1] async def test_get_obo_credential_evicts_oldest_when_over_capacity(self): """Test that credentials are evicted LRU-style when cache is full.""" from unittest.mock import AsyncMock, MagicMock, patch provider = AzureProvider( client_id="test-client-id", client_secret="test-client-secret", tenant_id="test-tenant-id", base_url="https://myserver.com", required_scopes=["read"], jwt_signing_key="test-secret", ) provider._obo_max_credentials = 2 creds = [MagicMock(close=AsyncMock()) for _ in range(3)] with patch("azure.identity.aio.OnBehalfOfCredential", side_effect=creds): await provider.get_obo_credential(user_assertion="token-1") await provider.get_obo_credential(user_assertion="token-2") await provider.get_obo_credential(user_assertion="token-3") assert len(provider._obo_credentials) == 2 creds[0].close.assert_awaited_once() # token-1's credential was evicted assert ( await provider.get_obo_credential(user_assertion="token-2") is creds[1] ) assert ( await provider.get_obo_credential(user_assertion="token-3") is creds[2] ) async def test_close_obo_credentials(self): """Test that close_obo_credentials closes all cached credentials.""" from unittest.mock import AsyncMock, MagicMock, patch provider = AzureProvider( client_id="test-client-id", client_secret="test-client-secret", tenant_id="test-tenant-id", base_url="https://myserver.com", required_scopes=["read"], jwt_signing_key="test-secret", ) creds = [MagicMock(close=AsyncMock()) for _ in range(2)] with patch("azure.identity.aio.OnBehalfOfCredential", side_effect=creds): await provider.get_obo_credential(user_assertion="token-a") await provider.get_obo_credential(user_assertion="token-b") await provider.close_obo_credentials() assert len(provider._obo_credentials) == 0 for cred in creds: cred.close.assert_awaited_once() async def test_get_obo_credential_with_custom_authority(self): """Test that get_obo_credential uses custom base_authority.""" from unittest.mock import MagicMock, patch provider = AzureProvider( client_id="test-client-id", client_secret="test-client-secret", tenant_id="gov-tenant-id", base_url="https://myserver.com", required_scopes=["read"], base_authority="login.microsoftonline.us", jwt_signing_key="test-secret", ) mock_credential = MagicMock() with patch( "azure.identity.aio.OnBehalfOfCredential", return_value=mock_credential ) as mock_class: await provider.get_obo_credential(user_assertion="user-token") call_kwargs = mock_class.call_args[1] assert call_kwargs["authority"] == "https://login.microsoftonline.us" def test_tenant_and_authority_stored_as_attributes(self): """Test that tenant_id and base_authority are stored for OBO credential creation.""" provider = AzureProvider( client_id="test-client-id", client_secret="test-client-secret", tenant_id="my-tenant", base_url="https://myserver.com", required_scopes=["read"], base_authority="login.microsoftonline.us", jwt_signing_key="test-secret", ) assert provider._tenant_id == "my-tenant" assert provider._base_authority == "login.microsoftonline.us" def test_entra_obo_token_is_importable(self): """Test that EntraOBOToken can be imported.""" from fastmcp.server.auth.providers.azure import EntraOBOToken assert EntraOBOToken is not None def test_entra_obo_token_creates_dependency(self): """Test that EntraOBOToken creates a dependency with scopes.""" from fastmcp.server.auth.providers.azure import EntraOBOToken, _EntraOBOToken dep = EntraOBOToken(["https://graph.microsoft.com/User.Read"]) assert isinstance(dep, _EntraOBOToken) assert dep.scopes == ["https://graph.microsoft.com/User.Read"] def test_entra_obo_token_is_dependency_instance(self): """Test that EntraOBOToken is a Dependency instance.""" from fastmcp.dependencies import Dependency from fastmcp.server.auth.providers.azure import _EntraOBOToken dep = _EntraOBOToken(["scope"]) assert isinstance(dep, Dependency)
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/auth/providers/test_azure_scopes.py", "license": "Apache License 2.0", "lines": 592, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/server/auth/test_cimd_validators.py
"""Unit tests for CIMD assertion validators, client manager, and redirect URI enforcement.""" from __future__ import annotations from unittest.mock import AsyncMock, patch import pytest from pydantic import AnyHttpUrl from fastmcp.server.auth.cimd import ( CIMDAssertionValidator, CIMDClientManager, CIMDDocument, ) from fastmcp.server.auth.oauth_proxy.models import ProxyDCRClient # Standard public IP used for DNS mocking in tests TEST_PUBLIC_IP = "93.184.216.34" class TestCIMDAssertionValidator: """Tests for CIMDAssertionValidator (private_key_jwt support).""" @pytest.fixture def validator(self): """Create a CIMDAssertionValidator for testing.""" return CIMDAssertionValidator() @pytest.fixture def key_pair(self): """Generate RSA key pair for testing.""" from fastmcp.server.auth.providers.jwt import RSAKeyPair return RSAKeyPair.generate() @pytest.fixture def jwks(self, key_pair): """Create JWKS from key pair.""" import base64 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization # Load public key public_key = serialization.load_pem_public_key( key_pair.public_key.encode(), backend=default_backend() ) # Get RSA public numbers from cryptography.hazmat.primitives.asymmetric import rsa if isinstance(public_key, rsa.RSAPublicKey): numbers = public_key.public_numbers() # Convert to JWK format return { "keys": [ { "kty": "RSA", "kid": "test-key-1", "use": "sig", "alg": "RS256", "n": base64.urlsafe_b64encode( numbers.n.to_bytes((numbers.n.bit_length() + 7) // 8, "big") ) .rstrip(b"=") .decode(), "e": base64.urlsafe_b64encode( numbers.e.to_bytes((numbers.e.bit_length() + 7) // 8, "big") ) .rstrip(b"=") .decode(), } ] } @pytest.fixture def cimd_doc_with_jwks_uri(self): """Create CIMD document with jwks_uri.""" return CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), redirect_uris=["http://localhost:3000/callback"], token_endpoint_auth_method="private_key_jwt", jwks_uri=AnyHttpUrl("https://example.com/.well-known/jwks.json"), ) @pytest.fixture def cimd_doc_with_inline_jwks(self, jwks): """Create CIMD document with inline JWKS.""" return CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), redirect_uris=["http://localhost:3000/callback"], token_endpoint_auth_method="private_key_jwt", jwks=jwks, ) async def test_valid_assertion_with_jwks_uri( self, validator, key_pair, cimd_doc_with_jwks_uri, httpx_mock ): """Test that valid JWT assertion passes validation (jwks_uri).""" client_id = "https://example.com/client.json" token_endpoint = "https://oauth.example.com/token" # Mock JWKS endpoint import base64 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization public_key = serialization.load_pem_public_key( key_pair.public_key.encode(), backend=default_backend() ) from cryptography.hazmat.primitives.asymmetric import rsa assert isinstance(public_key, rsa.RSAPublicKey) numbers = public_key.public_numbers() jwks = { "keys": [ { "kty": "RSA", "kid": "test-key-1", "use": "sig", "alg": "RS256", "n": base64.urlsafe_b64encode( numbers.n.to_bytes((numbers.n.bit_length() + 7) // 8, "big") ) .rstrip(b"=") .decode(), "e": base64.urlsafe_b64encode( numbers.e.to_bytes((numbers.e.bit_length() + 7) // 8, "big") ) .rstrip(b"=") .decode(), } ] } # Mock DNS resolution for SSRF-safe fetch with patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=[TEST_PUBLIC_IP], ): httpx_mock.add_response(json=jwks) # Create valid assertion (use short lifetime for security compliance) assertion = key_pair.create_token( subject=client_id, issuer=client_id, audience=token_endpoint, additional_claims={"jti": "unique-jti-123"}, expires_in_seconds=60, # 1 minute (max allowed is 300s) kid="test-key-1", ) # Should validate successfully assert await validator.validate_assertion( assertion, client_id, token_endpoint, cimd_doc_with_jwks_uri ) async def test_valid_assertion_with_inline_jwks( self, validator, key_pair, cimd_doc_with_inline_jwks ): """Test that valid JWT assertion passes validation (inline JWKS).""" client_id = "https://example.com/client.json" token_endpoint = "https://oauth.example.com/token" # Create valid assertion (use short lifetime for security compliance) assertion = key_pair.create_token( subject=client_id, issuer=client_id, audience=token_endpoint, additional_claims={"jti": "unique-jti-456"}, expires_in_seconds=60, # 1 minute (max allowed is 300s) kid="test-key-1", ) # Should validate successfully assert await validator.validate_assertion( assertion, client_id, token_endpoint, cimd_doc_with_inline_jwks ) async def test_rejects_wrong_issuer( self, validator, key_pair, cimd_doc_with_inline_jwks ): """Test that wrong issuer is rejected.""" client_id = "https://example.com/client.json" token_endpoint = "https://oauth.example.com/token" # Create assertion with wrong issuer assertion = key_pair.create_token( subject=client_id, issuer="https://attacker.com", # Wrong! audience=token_endpoint, additional_claims={"jti": "unique-jti-789"}, expires_in_seconds=60, kid="test-key-1", ) with pytest.raises(ValueError) as exc_info: await validator.validate_assertion( assertion, client_id, token_endpoint, cimd_doc_with_inline_jwks ) assert "Invalid JWT assertion" in str(exc_info.value) async def test_rejects_wrong_audience( self, validator, key_pair, cimd_doc_with_inline_jwks ): """Test that wrong audience is rejected.""" client_id = "https://example.com/client.json" token_endpoint = "https://oauth.example.com/token" # Create assertion with wrong audience assertion = key_pair.create_token( subject=client_id, issuer=client_id, audience="https://wrong-endpoint.com/token", # Wrong! additional_claims={"jti": "unique-jti-abc"}, expires_in_seconds=60, kid="test-key-1", ) with pytest.raises(ValueError) as exc_info: await validator.validate_assertion( assertion, client_id, token_endpoint, cimd_doc_with_inline_jwks ) assert "Invalid JWT assertion" in str(exc_info.value) async def test_rejects_wrong_subject( self, validator, key_pair, cimd_doc_with_inline_jwks ): """Test that wrong subject claim is rejected.""" client_id = "https://example.com/client.json" token_endpoint = "https://oauth.example.com/token" # Create assertion with wrong subject assertion = key_pair.create_token( subject="https://different-client.com", # Wrong! issuer=client_id, audience=token_endpoint, additional_claims={"jti": "unique-jti-def"}, expires_in_seconds=60, kid="test-key-1", ) with pytest.raises(ValueError) as exc_info: await validator.validate_assertion( assertion, client_id, token_endpoint, cimd_doc_with_inline_jwks ) assert "sub claim must be" in str(exc_info.value) async def test_rejects_missing_jti( self, validator, key_pair, cimd_doc_with_inline_jwks ): """Test that missing jti claim is rejected.""" client_id = "https://example.com/client.json" token_endpoint = "https://oauth.example.com/token" # Create assertion without jti assertion = key_pair.create_token( subject=client_id, issuer=client_id, audience=token_endpoint, # No jti! expires_in_seconds=60, kid="test-key-1", ) with pytest.raises(ValueError) as exc_info: await validator.validate_assertion( assertion, client_id, token_endpoint, cimd_doc_with_inline_jwks ) assert "jti claim" in str(exc_info.value) async def test_rejects_replayed_jti( self, validator, key_pair, cimd_doc_with_inline_jwks ): """Test that replayed JTI is detected and rejected.""" client_id = "https://example.com/client.json" token_endpoint = "https://oauth.example.com/token" # Create assertion assertion = key_pair.create_token( subject=client_id, issuer=client_id, audience=token_endpoint, additional_claims={"jti": "replayed-jti"}, expires_in_seconds=60, kid="test-key-1", ) # First use should succeed assert await validator.validate_assertion( assertion, client_id, token_endpoint, cimd_doc_with_inline_jwks ) # Second use with same jti should fail (replay attack) with pytest.raises(ValueError) as exc_info: await validator.validate_assertion( assertion, client_id, token_endpoint, cimd_doc_with_inline_jwks ) assert "replay" in str(exc_info.value).lower() async def test_rejects_expired_token( self, validator, key_pair, cimd_doc_with_inline_jwks ): """Test that expired tokens are rejected.""" client_id = "https://example.com/client.json" token_endpoint = "https://oauth.example.com/token" # Create expired assertion (expired 1 hour ago) assertion = key_pair.create_token( subject=client_id, issuer=client_id, audience=token_endpoint, additional_claims={"jti": "expired-jti"}, expires_in_seconds=-3600, # Negative = expired kid="test-key-1", ) with pytest.raises(ValueError) as exc_info: await validator.validate_assertion( assertion, client_id, token_endpoint, cimd_doc_with_inline_jwks ) assert "Invalid JWT assertion" in str(exc_info.value) class TestCIMDClientManager: """Tests for CIMDClientManager.""" @pytest.fixture def manager(self): """Create a CIMDClientManager for testing.""" return CIMDClientManager(enable_cimd=True) @pytest.fixture def disabled_manager(self): """Create a disabled CIMDClientManager for testing.""" return CIMDClientManager(enable_cimd=False) @pytest.fixture def mock_dns(self): """Mock DNS resolution to return test public IP.""" with patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=[TEST_PUBLIC_IP], ): yield def test_is_cimd_client_id_enabled(self, manager): """Test CIMD URL detection when enabled.""" assert manager.is_cimd_client_id("https://example.com/client.json") assert not manager.is_cimd_client_id("regular-client-id") def test_is_cimd_client_id_disabled(self, disabled_manager): """Test CIMD URL detection when disabled.""" assert not disabled_manager.is_cimd_client_id("https://example.com/client.json") assert not disabled_manager.is_cimd_client_id("regular-client-id") async def test_get_client_success(self, manager, httpx_mock, mock_dns): """Test successful CIMD client creation.""" url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "Test App", "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "none", } httpx_mock.add_response( json=doc_data, headers={"content-length": "200"}, ) client = await manager.get_client(url) assert client is not None assert client.client_id == url assert client.client_name == "Test App" # Verify it uses proxy's patterns (None by default), not document's redirect_uris assert client.allowed_redirect_uri_patterns is None async def test_get_client_disabled(self, disabled_manager): """Test that get_client returns None when disabled.""" client = await disabled_manager.get_client("https://example.com/client.json") assert client is None async def test_get_client_fetch_failure(self, manager, httpx_mock, mock_dns): """Test that get_client returns None on fetch failure.""" url = "https://example.com/client.json" httpx_mock.add_response(status_code=404) client = await manager.get_client(url) assert client is None # Trust policy and consent bypass tests removed - functionality removed from CIMD class TestCIMDClientManagerGetClientOptions: """Tests for CIMDClientManager.get_client with default_scope and allowed patterns.""" @pytest.fixture def mock_dns(self): """Mock DNS resolution to return test public IP.""" with patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=[TEST_PUBLIC_IP], ): yield async def test_default_scope_applied_when_doc_has_no_scope( self, httpx_mock, mock_dns ): """When the CIMD document omits scope, the manager's default_scope is used.""" url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "Test App", "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "none", # No scope field } httpx_mock.add_response( json=doc_data, headers={"content-length": "200"}, ) manager = CIMDClientManager( enable_cimd=True, default_scope="read write admin", ) client = await manager.get_client(url) assert client is not None assert client.scope == "read write admin" async def test_doc_scope_takes_precedence_over_default(self, httpx_mock, mock_dns): """When the CIMD document specifies scope, it wins over the default.""" url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "Test App", "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "none", "scope": "custom-scope", } httpx_mock.add_response( json=doc_data, headers={"content-length": "200"}, ) manager = CIMDClientManager( enable_cimd=True, default_scope="default-scope", ) client = await manager.get_client(url) assert client is not None assert client.scope == "custom-scope" async def test_allowed_redirect_uri_patterns_stored_on_client( self, httpx_mock, mock_dns ): """Proxy's allowed_redirect_uri_patterns are forwarded to the created client.""" url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "Test App", "redirect_uris": ["http://localhost:*/callback"], "token_endpoint_auth_method": "none", } httpx_mock.add_response( json=doc_data, headers={"content-length": "200"}, ) patterns = ["http://localhost:*", "https://app.example.com/*"] manager = CIMDClientManager( enable_cimd=True, allowed_redirect_uri_patterns=patterns, ) client = await manager.get_client(url) assert client is not None assert client.allowed_redirect_uri_patterns == patterns async def test_cimd_document_attached_to_client(self, httpx_mock, mock_dns): """The fetched CIMDDocument is attached to the created client.""" url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "Attached Doc App", "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "none", } httpx_mock.add_response( json=doc_data, headers={"content-length": "200"}, ) manager = CIMDClientManager(enable_cimd=True) client = await manager.get_client(url) assert client is not None assert client.cimd_document is not None assert client.cimd_document.client_name == "Attached Doc App" assert str(client.cimd_document.client_id) == url class TestCIMDClientManagerValidatePrivateKeyJwt: """Tests for CIMDClientManager.validate_private_key_jwt wrapper.""" @pytest.fixture def manager(self): return CIMDClientManager(enable_cimd=True) async def test_missing_cimd_document_raises(self, manager): """validate_private_key_jwt raises ValueError if client has no cimd_document.""" client = ProxyDCRClient( client_id="https://example.com/client.json", client_secret=None, redirect_uris=None, cimd_document=None, ) with pytest.raises(ValueError, match="must have CIMD document"): await manager.validate_private_key_jwt( "fake.jwt.token", client, "https://oauth.example.com/token", ) async def test_wrong_auth_method_raises(self, manager): """validate_private_key_jwt raises ValueError if auth method is not private_key_jwt.""" cimd_doc = CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), redirect_uris=["http://localhost:3000/callback"], token_endpoint_auth_method="none", # Not private_key_jwt ) client = ProxyDCRClient( client_id="https://example.com/client.json", client_secret=None, redirect_uris=None, cimd_document=cimd_doc, ) with pytest.raises(ValueError, match="private_key_jwt"): await manager.validate_private_key_jwt( "fake.jwt.token", client, "https://oauth.example.com/token", ) async def test_success_delegates_to_assertion_validator(self, manager): """On success, validate_private_key_jwt delegates to the assertion validator.""" cimd_doc = CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), redirect_uris=["http://localhost:3000/callback"], token_endpoint_auth_method="private_key_jwt", jwks_uri=AnyHttpUrl("https://example.com/.well-known/jwks.json"), ) client = ProxyDCRClient( client_id="https://example.com/client.json", client_secret=None, redirect_uris=None, cimd_document=cimd_doc, ) manager._assertion_validator.validate_assertion = AsyncMock(return_value=True) result = await manager.validate_private_key_jwt( "test.jwt.assertion", client, "https://oauth.example.com/token", ) assert result is True manager._assertion_validator.validate_assertion.assert_awaited_once_with( "test.jwt.assertion", "https://example.com/client.json", "https://oauth.example.com/token", cimd_doc, ) class TestCIMDRedirectUriEnforcement: """Tests for CIMD redirect_uri validation security. Verifies that CIMD clients enforce BOTH: 1. CIMD document's redirect_uris 2. Proxy's allowed_redirect_uri_patterns """ @pytest.fixture def mock_dns(self): """Mock DNS resolution to return test public IP.""" with patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=[TEST_PUBLIC_IP], ): yield async def test_cimd_redirect_uris_enforced(self, httpx_mock, mock_dns): """Test that CIMD document redirect_uris are enforced. Even if proxy patterns allow http://localhost:*, a CIMD client should only accept URIs declared in its document. """ from mcp.shared.auth import InvalidRedirectUriError from pydantic import AnyUrl url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "Test App", # CIMD only declares port 3000 "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "none", } httpx_mock.add_response( json=doc_data, headers={"content-length": "200"}, ) # Proxy allows any localhost port manager = CIMDClientManager( enable_cimd=True, allowed_redirect_uri_patterns=["http://localhost:*"], ) client = await manager.get_client(url) assert client is not None # Declared URI should work validated = client.validate_redirect_uri( AnyUrl("http://localhost:3000/callback") ) assert str(validated) == "http://localhost:3000/callback" # Different port should fail (not in CIMD redirect_uris) with pytest.raises(InvalidRedirectUriError): client.validate_redirect_uri(AnyUrl("http://localhost:4000/callback")) async def test_proxy_patterns_also_checked(self, httpx_mock, mock_dns): """Test that proxy patterns are checked even for CIMD clients. A CIMD client should not be able to use a redirect_uri that's in its document but not allowed by proxy patterns. """ from mcp.shared.auth import InvalidRedirectUriError from pydantic import AnyUrl url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "Test App", # CIMD declares both localhost and external URI "redirect_uris": [ "http://localhost:3000/callback", "https://evil.com/callback", ], "token_endpoint_auth_method": "none", } httpx_mock.add_response( json=doc_data, headers={"content-length": "200"}, ) # Proxy only allows localhost manager = CIMDClientManager( enable_cimd=True, allowed_redirect_uri_patterns=["http://localhost:*"], ) client = await manager.get_client(url) assert client is not None # Localhost should work (in CIMD and matches pattern) validated = client.validate_redirect_uri( AnyUrl("http://localhost:3000/callback") ) assert str(validated) == "http://localhost:3000/callback" # Evil.com should fail (in CIMD but doesn't match proxy patterns) with pytest.raises(InvalidRedirectUriError): client.validate_redirect_uri(AnyUrl("https://evil.com/callback"))
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/auth/test_cimd_validators.py", "license": "Apache License 2.0", "lines": 578, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/server/auth/test_jwt_provider_bearer.py
from collections.abc import AsyncGenerator from typing import Any import httpx import pytest from fastmcp import Client, FastMCP from fastmcp.client.auth.bearer import BearerAuth from fastmcp.server.auth.providers.jwt import JWTVerifier, RSAKeyPair from fastmcp.utilities.tests import run_server_async # Standard public IP used for DNS mocking in tests TEST_PUBLIC_IP = "93.184.216.34" @pytest.fixture(scope="module") def rsa_key_pair() -> RSAKeyPair: return RSAKeyPair.generate() @pytest.fixture(scope="module") def bearer_token(rsa_key_pair: RSAKeyPair) -> str: return rsa_key_pair.create_token( subject="test-user", issuer="https://test.example.com", audience="https://api.example.com", ) @pytest.fixture def bearer_provider(rsa_key_pair: RSAKeyPair) -> JWTVerifier: return JWTVerifier( public_key=rsa_key_pair.public_key, issuer="https://test.example.com", audience="https://api.example.com", ) def create_mcp_server( public_key: str, auth_kwargs: dict[str, Any] | None = None, ) -> FastMCP: mcp = FastMCP( auth=JWTVerifier( public_key=public_key, **auth_kwargs or {}, ) ) @mcp.tool def add(a: int, b: int) -> int: return a + b return mcp @pytest.fixture async def mcp_server_url(rsa_key_pair: RSAKeyPair) -> AsyncGenerator[str, None]: server = create_mcp_server( public_key=rsa_key_pair.public_key, auth_kwargs=dict( issuer="https://test.example.com", audience="https://api.example.com", ), ) async with run_server_async(server, transport="http") as url: yield url class TestBearerToken: def test_initialization_with_public_key(self, rsa_key_pair: RSAKeyPair): """Test provider initialization with public key.""" provider = JWTVerifier( public_key=rsa_key_pair.public_key, issuer="https://test.example.com" ) assert provider.issuer == "https://test.example.com" assert provider.public_key is not None assert provider.jwks_uri is None def test_initialization_with_jwks_uri(self): """Test provider initialization with JWKS URI.""" provider = JWTVerifier( jwks_uri="https://test.example.com/.well-known/jwks.json", issuer="https://test.example.com", ) assert provider.issuer == "https://test.example.com" assert provider.jwks_uri == "https://test.example.com/.well-known/jwks.json" assert provider.public_key is None def test_initialization_requires_key_or_uri(self): """Test that either public_key or jwks_uri is required.""" with pytest.raises( ValueError, match="Either public_key or jwks_uri must be provided" ): JWTVerifier(issuer="https://test.example.com") def test_initialization_rejects_both_key_and_uri(self, rsa_key_pair: RSAKeyPair): """Test that both public_key and jwks_uri cannot be provided.""" with pytest.raises( ValueError, match="Provide either public_key or jwks_uri, not both" ): JWTVerifier( public_key=rsa_key_pair.public_key, jwks_uri="https://test.example.com/.well-known/jwks.json", issuer="https://test.example.com", ) async def test_valid_token_validation( self, rsa_key_pair: RSAKeyPair, bearer_provider: JWTVerifier ): """Test validation of a valid token.""" token = rsa_key_pair.create_token( subject="test-user", issuer="https://test.example.com", audience="https://api.example.com", scopes=["read", "write"], ) access_token = await bearer_provider.load_access_token(token) assert access_token is not None assert access_token.client_id == "test-user" assert "read" in access_token.scopes assert "write" in access_token.scopes assert access_token.expires_at is not None async def test_expired_token_rejection( self, rsa_key_pair: RSAKeyPair, bearer_provider: JWTVerifier ): """Test rejection of expired tokens.""" token = rsa_key_pair.create_token( subject="test-user", issuer="https://test.example.com", audience="https://api.example.com", expires_in_seconds=-3600, # Expired 1 hour ago ) access_token = await bearer_provider.load_access_token(token) assert access_token is None async def test_invalid_issuer_rejection( self, rsa_key_pair: RSAKeyPair, bearer_provider: JWTVerifier ): """Test rejection of tokens with invalid issuer.""" token = rsa_key_pair.create_token( subject="test-user", issuer="https://evil.example.com", # Wrong issuer audience="https://api.example.com", ) access_token = await bearer_provider.load_access_token(token) assert access_token is None async def test_invalid_audience_rejection( self, rsa_key_pair: RSAKeyPair, bearer_provider: JWTVerifier ): """Test rejection of tokens with invalid audience.""" token = rsa_key_pair.create_token( subject="test-user", issuer="https://test.example.com", audience="https://wrong-api.example.com", # Wrong audience ) access_token = await bearer_provider.load_access_token(token) assert access_token is None async def test_no_issuer_validation_when_none(self, rsa_key_pair: RSAKeyPair): """Test that issuer validation is skipped when provider has no issuer configured.""" provider = JWTVerifier( public_key=rsa_key_pair.public_key, issuer=None, # No issuer validation ) token = rsa_key_pair.create_token( subject="test-user", issuer="https://any.example.com" ) access_token = await provider.load_access_token(token) assert access_token is not None async def test_no_audience_validation_when_none(self, rsa_key_pair: RSAKeyPair): """Test that audience validation is skipped when provider has no audience configured.""" provider = JWTVerifier( public_key=rsa_key_pair.public_key, issuer="https://test.example.com", audience=None, # No audience validation ) token = rsa_key_pair.create_token( subject="test-user", issuer="https://test.example.com", audience="https://any-api.example.com", ) access_token = await provider.load_access_token(token) assert access_token is not None async def test_multiple_audiences_validation(self, rsa_key_pair: RSAKeyPair): """Test validation with multiple audiences in token.""" provider = JWTVerifier( public_key=rsa_key_pair.public_key, issuer="https://test.example.com", audience="https://api.example.com", ) token = rsa_key_pair.create_token( subject="test-user", issuer="https://test.example.com", additional_claims={ "aud": ["https://api.example.com", "https://other-api.example.com"] }, ) access_token = await provider.load_access_token(token) assert access_token is not None async def test_provider_with_multiple_expected_audiences( self, rsa_key_pair: RSAKeyPair ): """Test provider configured with multiple expected audiences.""" provider = JWTVerifier( public_key=rsa_key_pair.public_key, issuer="https://test.example.com", audience=["https://api.example.com", "https://other-api.example.com"], ) # Token with single audience that matches one of the expected token1 = rsa_key_pair.create_token( subject="test-user", issuer="https://test.example.com", audience="https://api.example.com", ) access_token1 = await provider.load_access_token(token1) assert access_token1 is not None # Token with multiple audiences, one of which matches token2 = rsa_key_pair.create_token( subject="test-user", issuer="https://test.example.com", additional_claims={ "aud": ["https://api.example.com", "https://third-party.example.com"] }, ) access_token2 = await provider.load_access_token(token2) assert access_token2 is not None # Token with audience that doesn't match any expected token3 = rsa_key_pair.create_token( subject="test-user", issuer="https://test.example.com", audience="https://wrong-api.example.com", ) access_token3 = await provider.load_access_token(token3) assert access_token3 is None @pytest.mark.parametrize( ("iss", "expected"), [ ("https://test.example.com", True), ("https://other-issuer.example.com", True), ("https://wrong-issuer.example.com", False), ], ) async def test_provider_with_multiple_expected_issuers( self, rsa_key_pair: RSAKeyPair, iss: str, expected: bool ): """Provider accepts any issuer from the configured list.""" provider = JWTVerifier( public_key=rsa_key_pair.public_key, issuer=["https://test.example.com", "https://other-issuer.example.com"], audience="https://api.example.com", ) token = rsa_key_pair.create_token( subject="test-user", issuer=iss, audience="https://api.example.com" ) access_token = await provider.load_access_token(token) assert (access_token is not None) is expected async def test_scope_extraction_string( self, rsa_key_pair: RSAKeyPair, bearer_provider: JWTVerifier ): """Test scope extraction from space-separated string.""" token = rsa_key_pair.create_token( subject="test-user", issuer="https://test.example.com", audience="https://api.example.com", scopes=["read", "write", "admin"], ) access_token = await bearer_provider.load_access_token(token) assert access_token is not None assert set(access_token.scopes) == {"read", "write", "admin"} async def test_scope_extraction_list( self, rsa_key_pair: RSAKeyPair, bearer_provider: JWTVerifier ): """Test scope extraction from list format.""" token = rsa_key_pair.create_token( subject="test-user", issuer="https://test.example.com", audience="https://api.example.com", additional_claims={"scope": ["read", "write"]}, # List format ) access_token = await bearer_provider.load_access_token(token) assert access_token is not None assert set(access_token.scopes) == {"read", "write"} async def test_no_scopes( self, rsa_key_pair: RSAKeyPair, bearer_provider: JWTVerifier ): """Test token with no scopes.""" token = rsa_key_pair.create_token( subject="test-user", issuer="https://test.example.com", audience="https://api.example.com", # No scopes ) access_token = await bearer_provider.load_access_token(token) assert access_token is not None assert access_token.scopes == [] async def test_scp_claim_extraction_string( self, rsa_key_pair: RSAKeyPair, bearer_provider: JWTVerifier ): """Test scope extraction from 'scp' claim with space-separated string.""" token = rsa_key_pair.create_token( subject="test-user", issuer="https://test.example.com", audience="https://api.example.com", additional_claims={"scp": "read write admin"}, # 'scp' claim as string ) access_token = await bearer_provider.load_access_token(token) assert access_token is not None assert set(access_token.scopes) == {"read", "write", "admin"} async def test_scp_claim_extraction_list( self, rsa_key_pair: RSAKeyPair, bearer_provider: JWTVerifier ): """Test scope extraction from 'scp' claim with list format.""" token = rsa_key_pair.create_token( subject="test-user", issuer="https://test.example.com", audience="https://api.example.com", additional_claims={ "scp": ["read", "write", "admin"] }, # 'scp' claim as list ) access_token = await bearer_provider.load_access_token(token) assert access_token is not None assert set(access_token.scopes) == {"read", "write", "admin"} async def test_scope_precedence_over_scp( self, rsa_key_pair: RSAKeyPair, bearer_provider: JWTVerifier ): """Test that 'scope' claim takes precedence over 'scp' claim when both are present.""" token = rsa_key_pair.create_token( subject="test-user", issuer="https://test.example.com", audience="https://api.example.com", additional_claims={ "scope": "read write", # Standard OAuth2 claim "scp": "admin delete", # Should be ignored when 'scope' is present }, ) access_token = await bearer_provider.load_access_token(token) assert access_token is not None assert set(access_token.scopes) == {"read", "write"} # Only 'scope' claim used async def test_malformed_token_rejection(self, bearer_provider: JWTVerifier): """Test rejection of malformed tokens.""" malformed_tokens = [ "not.a.jwt", "too.many.parts.here.invalid", "invalid-token", "", "header.body", # Missing signature ] for token in malformed_tokens: access_token = await bearer_provider.load_access_token(token) assert access_token is None async def test_invalid_signature_rejection( self, rsa_key_pair: RSAKeyPair, bearer_provider: JWTVerifier ): """Test rejection of tokens with invalid signatures.""" # Create a token with a different key pair other_key_pair = RSAKeyPair.generate() token = other_key_pair.create_token( subject="test-user", issuer="https://test.example.com", audience="https://api.example.com", ) access_token = await bearer_provider.load_access_token(token) assert access_token is None async def test_client_id_fallback( self, rsa_key_pair: RSAKeyPair, bearer_provider: JWTVerifier ): """Test client_id extraction with fallback logic.""" # Test with explicit client_id claim token = rsa_key_pair.create_token( subject="user123", issuer="https://test.example.com", audience="https://api.example.com", additional_claims={"client_id": "app456"}, ) access_token = await bearer_provider.load_access_token(token) assert access_token is not None assert access_token.client_id == "app456" # Should prefer client_id over sub async def test_string_issuer_validation(self, rsa_key_pair: RSAKeyPair): """Test that string (non-URL) issuers are supported per RFC 7519.""" # Create provider with string issuer provider = JWTVerifier( public_key=rsa_key_pair.public_key, issuer="my-service", # String issuer, not a URL ) # Create token with matching string issuer token = rsa_key_pair.create_token( subject="test-user", issuer="my-service", # Same string issuer ) access_token = await provider.load_access_token(token) assert access_token is not None assert access_token.client_id == "test-user" async def test_string_issuer_mismatch_rejection(self, rsa_key_pair: RSAKeyPair): """Test that mismatched string issuers are rejected.""" # Create provider with one string issuer provider = JWTVerifier( public_key=rsa_key_pair.public_key, issuer="my-service", ) # Create token with different string issuer token = rsa_key_pair.create_token( subject="test-user", issuer="other-service", # Different string issuer ) access_token = await provider.load_access_token(token) assert access_token is None async def test_url_issuer_still_works(self, rsa_key_pair: RSAKeyPair): """Test that URL issuers still work after the fix.""" # Create provider with URL issuer provider = JWTVerifier( public_key=rsa_key_pair.public_key, issuer="https://my-auth-server.com", # URL issuer ) # Create token with matching URL issuer token = rsa_key_pair.create_token( subject="test-user", issuer="https://my-auth-server.com", # Same URL issuer ) access_token = await provider.load_access_token(token) assert access_token is not None assert access_token.client_id == "test-user" class TestFastMCPBearerAuth: def test_bearer_auth(self): mcp = FastMCP( auth=JWTVerifier(issuer="https://test.example.com", public_key="abc") ) assert isinstance(mcp.auth, JWTVerifier) async def test_unauthorized_access(self, mcp_server_url: str): with pytest.raises(httpx.HTTPStatusError) as exc_info: async with Client(mcp_server_url) as client: tools = await client.list_tools() # noqa: F841 assert isinstance(exc_info.value, httpx.HTTPStatusError) assert exc_info.value.response.status_code == 401 assert "tools" not in locals() async def test_authorized_access(self, mcp_server_url: str, bearer_token): async with Client(mcp_server_url, auth=BearerAuth(bearer_token)) as client: tools = await client.list_tools() # noqa: F841 assert tools async def test_invalid_token_raises_401(self, mcp_server_url: str): with pytest.raises(httpx.HTTPStatusError) as exc_info: async with Client(mcp_server_url, auth=BearerAuth("invalid")) as client: tools = await client.list_tools() # noqa: F841 assert isinstance(exc_info.value, httpx.HTTPStatusError) assert exc_info.value.response.status_code == 401 assert "tools" not in locals() async def test_expired_token(self, mcp_server_url: str, rsa_key_pair: RSAKeyPair): token = rsa_key_pair.create_token( subject="test-user", issuer="https://test.example.com", audience="https://api.example.com", expires_in_seconds=-3600, ) with pytest.raises(httpx.HTTPStatusError) as exc_info: async with Client(mcp_server_url, auth=BearerAuth(token)) as client: tools = await client.list_tools() # noqa: F841 assert isinstance(exc_info.value, httpx.HTTPStatusError) assert exc_info.value.response.status_code == 401 assert "tools" not in locals() async def test_token_with_bad_signature(self, mcp_server_url: str): rsa_key_pair = RSAKeyPair.generate() token = rsa_key_pair.create_token() with pytest.raises(httpx.HTTPStatusError) as exc_info: async with Client(mcp_server_url, auth=BearerAuth(token)) as client: tools = await client.list_tools() # noqa: F841 assert isinstance(exc_info.value, httpx.HTTPStatusError) assert exc_info.value.response.status_code == 401 assert "tools" not in locals() async def test_token_with_insufficient_scopes(self, rsa_key_pair: RSAKeyPair): token = rsa_key_pair.create_token( subject="test-user", issuer="https://test.example.com", audience="https://api.example.com", scopes=["read"], ) server = create_mcp_server( public_key=rsa_key_pair.public_key, auth_kwargs=dict(required_scopes=["read", "write"]), ) async with run_server_async(server, transport="http") as mcp_server_url: with pytest.raises(httpx.HTTPStatusError) as exc_info: async with Client(mcp_server_url, auth=BearerAuth(token)) as client: tools = await client.list_tools() # noqa: F841 # JWTVerifier returns 401 when verify_token returns None (invalid token) # This is correct behavior - when TokenVerifier.verify_token returns None, # it indicates the token is invalid (not just insufficient permissions) assert isinstance(exc_info.value, httpx.HTTPStatusError) assert exc_info.value.response.status_code == 401 assert "tools" not in locals() async def test_token_with_sufficient_scopes(self, rsa_key_pair: RSAKeyPair): token = rsa_key_pair.create_token( subject="test-user", issuer="https://test.example.com", audience="https://api.example.com", scopes=["read", "write"], ) server = create_mcp_server( public_key=rsa_key_pair.public_key, auth_kwargs=dict(required_scopes=["read", "write"]), ) async with run_server_async(server, transport="http") as mcp_server_url: async with Client(mcp_server_url, auth=BearerAuth(token)) as client: tools = await client.list_tools() assert tools class TestJWTVerifierImport: """Test JWT token verifier can be imported and created.""" def test_jwt_verifier_requires_pyjwt(self): """Test that JWTVerifier raises helpful error without PyJWT.""" # Since PyJWT is likely installed in test environment, we'll just test construction from fastmcp.server.auth.providers.jwt import JWTVerifier # This should work if PyJWT is available try: verifier = JWTVerifier(public_key="dummy-key") assert verifier.public_key == "dummy-key" assert verifier.algorithm == "RS256" except ImportError as e: # If PyJWT not available, should get helpful error assert "PyJWT is required" in str(e) class TestScopesSupported: """Tests for the scopes_supported property on TokenVerifier.""" def test_defaults_to_required_scopes(self, rsa_key_pair: RSAKeyPair): provider = JWTVerifier( public_key=rsa_key_pair.public_key, required_scopes=["read", "write"], ) assert provider.scopes_supported == ["read", "write"] def test_empty_when_no_required_scopes(self, rsa_key_pair: RSAKeyPair): provider = JWTVerifier( public_key=rsa_key_pair.public_key, ) assert provider.scopes_supported == []
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/auth/test_jwt_provider_bearer.py", "license": "Apache License 2.0", "lines": 509, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/server/auth/test_oauth_consent_page.py
"""Tests for OAuth Proxy consent page display, CSP policy, and consent binding cookie.""" import re import secrets import time from unittest.mock import Mock 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 mcp.types import Icon from pydantic import AnyUrl from starlette.applications import Starlette from starlette.testclient import TestClient from fastmcp import FastMCP from fastmcp.server.auth.auth import AccessToken, TokenVerifier from fastmcp.server.auth.oauth_proxy import OAuthProxy from fastmcp.server.auth.oauth_proxy.models import OAuthTransaction class _Verifier(TokenVerifier): """Minimal token verifier for security tests.""" def __init__(self): self.required_scopes = ["read"] async def verify_token(self, token: str): return AccessToken( token=token, client_id="c", scopes=self.required_scopes, expires_at=None ) @pytest.fixture def oauth_proxy_https(): """OAuthProxy configured with HTTPS base_url for __Host- cookies.""" return OAuthProxy( upstream_authorization_endpoint="https://github.com/login/oauth/authorize", upstream_token_endpoint="https://github.com/login/oauth/access_token", upstream_client_id="client-id", upstream_client_secret="client-secret", token_verifier=_Verifier(), base_url="https://myserver.example", client_storage=MemoryStore(), jwt_signing_key="test-secret", ) async def _start_flow( proxy: OAuthProxy, client_id: str, redirect: str ) -> tuple[str, str]: """Register client and start auth; returns (txn_id, consent_url).""" await proxy.register_client( OAuthClientInformationFull( client_id=client_id, client_secret="s", redirect_uris=[AnyUrl(redirect)], ) ) params = AuthorizationParams( redirect_uri=AnyUrl(redirect), redirect_uri_provided_explicitly=True, state="client-state-xyz", code_challenge="challenge", scopes=["read"], ) consent_url = await proxy.authorize( OAuthClientInformationFull( client_id=client_id, client_secret="s", redirect_uris=[AnyUrl(redirect)], ), params, ) qs = parse_qs(urlparse(consent_url).query) return qs["txn_id"][0], consent_url def _extract_csrf(html: str) -> str | None: """Extract CSRF token from HTML form.""" m = re.search(r"name=\"csrf_token\"\s+value=\"([^\"]+)\"", html) return m.group(1) if m else None class TestConsentPageServerIcon: """Tests for server icon display in OAuth consent screen.""" async def test_consent_screen_displays_server_icon(self): """Test that consent screen shows server's custom icon when available.""" # Create mock JWT verifier verifier = Mock(spec=TokenVerifier) verifier.required_scopes = ["read"] verifier.verify_token = Mock(return_value=None) # Create OAuthProxy 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=verifier, base_url="https://proxy.example.com", client_storage=MemoryStore(), jwt_signing_key="test-secret", ) # Create FastMCP server with custom icon server = FastMCP( name="My Custom Server", auth=proxy, icons=[Icon(src="https://example.com/custom-icon.png")], website_url="https://example.com", ) # Create HTTP app app = server.http_app() # Register a test client with the proxy client_info = OAuthClientInformationFull( client_id="test-client", client_secret="test-secret", redirect_uris=[AnyUrl("http://localhost:12345/callback")], ) await proxy.register_client(client_info) # Create a transaction manually txn_id = "test-txn-id" transaction = OAuthTransaction( txn_id=txn_id, client_id="test-client", client_redirect_uri="http://localhost:12345/callback", client_state="client-state", code_challenge="challenge", code_challenge_method="S256", scopes=["read"], created_at=time.time(), ) await proxy._transaction_store.put(key=txn_id, value=transaction) # Make request to consent page with TestClient(app) as client: response = client.get(f"/consent?txn_id={txn_id}") # Check that response is successful assert response.status_code == 200 # Check that HTML contains custom icon assert "https://example.com/custom-icon.png" in response.text # Check that server name is used as alt text assert 'alt="My Custom Server"' in response.text async def test_consent_screen_falls_back_to_fastmcp_logo(self): """Test that consent screen shows FastMCP logo when no server icon provided.""" # Create mock JWT verifier verifier = Mock(spec=TokenVerifier) verifier.required_scopes = ["read"] verifier.verify_token = Mock(return_value=None) # Create OAuthProxy 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=verifier, base_url="https://proxy.example.com", client_storage=MemoryStore(), jwt_signing_key="test-secret", ) # Create FastMCP server without icon server = FastMCP(name="Server Without Icon", auth=proxy) # Create HTTP app app = server.http_app() # Register a test client client_info = OAuthClientInformationFull( client_id="test-client", client_secret="test-secret", redirect_uris=[AnyUrl("http://localhost:12345/callback")], ) await proxy.register_client(client_info) # Create a transaction txn_id = "test-txn-id" transaction = OAuthTransaction( txn_id=txn_id, client_id="test-client", client_redirect_uri="http://localhost:12345/callback", client_state="client-state", code_challenge="challenge", code_challenge_method="S256", scopes=["read"], created_at=time.time(), ) await proxy._transaction_store.put(key=txn_id, value=transaction) # Make request to consent page with TestClient(app) as client: response = client.get(f"/consent?txn_id={txn_id}") # Check that response is successful assert response.status_code == 200 # Check that HTML contains FastMCP logo assert "gofastmcp.com/assets/brand/blue-logo.png" in response.text # Check that alt text is still the server name assert 'alt="Server Without Icon"' in response.text async def test_consent_screen_escapes_server_name(self): """Test that server name is properly HTML-escaped.""" # Create mock JWT verifier verifier = Mock(spec=TokenVerifier) verifier.required_scopes = ["read"] verifier.verify_token = Mock(return_value=None) # Create OAuthProxy 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=verifier, base_url="https://proxy.example.com", client_storage=MemoryStore(), jwt_signing_key="test-secret", ) # Create FastMCP server with special characters in name server = FastMCP( name='<script>alert("xss")</script>Server', auth=proxy, icons=[Icon(src="https://example.com/icon.png")], ) # Create HTTP app app = server.http_app() # Register a test client client_info = OAuthClientInformationFull( client_id="test-client", client_secret="test-secret", redirect_uris=[AnyUrl("http://localhost:12345/callback")], ) await proxy.register_client(client_info) # Create a transaction txn_id = "test-txn-id" transaction = OAuthTransaction( txn_id=txn_id, client_id="test-client", client_redirect_uri="http://localhost:12345/callback", client_state="client-state", code_challenge="challenge", code_challenge_method="S256", scopes=["read"], created_at=time.time(), ) await proxy._transaction_store.put(key=txn_id, value=transaction) # Make request to consent page with TestClient(app) as client: response = client.get(f"/consent?txn_id={txn_id}") # Check that response is successful assert response.status_code == 200 # Check that script tag is escaped assert "<script>" not in response.text assert "&lt;script&gt;" in response.text assert ( 'alt="&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;Server"' in response.text ) class TestConsentCSPPolicy: """Tests for Content Security Policy customization on consent page.""" async def test_default_csp_omits_form_action(self): """Test that default CSP omits form-action to avoid Chrome redirect chain issues.""" verifier = Mock(spec=TokenVerifier) verifier.required_scopes = ["read"] verifier.verify_token = Mock(return_value=None) # Create OAuthProxy with default CSP (no custom CSP) 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=verifier, base_url="https://proxy.example.com", client_storage=MemoryStore(), jwt_signing_key="test-secret", ) server = FastMCP(name="Test Server", auth=proxy) app = server.http_app() client_info = OAuthClientInformationFull( client_id="test-client", client_secret="test-secret", redirect_uris=[AnyUrl("http://localhost:12345/callback")], ) await proxy.register_client(client_info) txn_id = "test-txn-id" transaction = OAuthTransaction( txn_id=txn_id, client_id="test-client", client_redirect_uri="http://localhost:12345/callback", client_state="client-state", code_challenge="challenge", code_challenge_method="S256", scopes=["read"], created_at=time.time(), ) await proxy._transaction_store.put(key=txn_id, value=transaction) with TestClient(app) as client: response = client.get(f"/consent?txn_id={txn_id}") assert response.status_code == 200 # Default CSP should be present but WITHOUT form-action assert 'http-equiv="Content-Security-Policy"' in response.text assert "form-action" not in response.text async def test_empty_csp_disables_csp_meta_tag(self): """Test that empty string CSP disables CSP meta tag entirely.""" verifier = Mock(spec=TokenVerifier) verifier.required_scopes = ["read"] verifier.verify_token = Mock(return_value=None) # Create OAuthProxy with empty CSP to disable it 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=verifier, base_url="https://proxy.example.com", client_storage=MemoryStore(), jwt_signing_key="test-secret", consent_csp_policy="", # Empty string disables CSP ) server = FastMCP(name="Test Server", auth=proxy) app = server.http_app() client_info = OAuthClientInformationFull( client_id="test-client", client_secret="test-secret", redirect_uris=[AnyUrl("http://localhost:12345/callback")], ) await proxy.register_client(client_info) txn_id = "test-txn-id" transaction = OAuthTransaction( txn_id=txn_id, client_id="test-client", client_redirect_uri="http://localhost:12345/callback", client_state="client-state", code_challenge="challenge", code_challenge_method="S256", scopes=["read"], created_at=time.time(), ) await proxy._transaction_store.put(key=txn_id, value=transaction) with TestClient(app) as client: response = client.get(f"/consent?txn_id={txn_id}") assert response.status_code == 200 # CSP meta tag should NOT be present assert 'http-equiv="Content-Security-Policy"' not in response.text async def test_custom_csp_policy_is_used(self): """Test that custom CSP policy is applied to consent page.""" verifier = Mock(spec=TokenVerifier) verifier.required_scopes = ["read"] verifier.verify_token = Mock(return_value=None) # Create OAuthProxy with custom CSP policy custom_csp = "default-src 'self'; script-src 'none'" 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=verifier, base_url="https://proxy.example.com", client_storage=MemoryStore(), jwt_signing_key="test-secret", consent_csp_policy=custom_csp, ) server = FastMCP(name="Test Server", auth=proxy) app = server.http_app() client_info = OAuthClientInformationFull( client_id="test-client", client_secret="test-secret", redirect_uris=[AnyUrl("http://localhost:12345/callback")], ) await proxy.register_client(client_info) txn_id = "test-txn-id" transaction = OAuthTransaction( txn_id=txn_id, client_id="test-client", client_redirect_uri="http://localhost:12345/callback", client_state="client-state", code_challenge="challenge", code_challenge_method="S256", scopes=["read"], created_at=time.time(), ) await proxy._transaction_store.put(key=txn_id, value=transaction) with TestClient(app) as client: response = client.get(f"/consent?txn_id={txn_id}") assert response.status_code == 200 # Custom CSP should be present (HTML-escaped) assert 'http-equiv="Content-Security-Policy"' in response.text # Check for the HTML-escaped version (single quotes become &#x27;) import html assert html.escape(custom_csp, quote=True) in response.text # Default form-action should NOT be present (we're using custom) assert "form-action" not in response.text class TestConsentBindingCookie: """Tests for consent binding cookie that prevents confused deputy attacks. GHSA-rww4-4w9c-7733: Without browser-binding between consent approval and the IdP callback, an attacker can intercept the upstream authorization URL and send it to a victim whose browser completes the flow. """ async def test_approve_sets_consent_binding_cookie(self, oauth_proxy_https): """Approving consent must set a signed consent binding cookie.""" txn_id, _ = await _start_flow( oauth_proxy_https, "client-binding", "http://localhost:6001/callback" ) app = Starlette(routes=oauth_proxy_https.get_routes()) with TestClient(app) as c: consent = c.get(f"/consent?txn_id={txn_id}") csrf = _extract_csrf(consent.text) assert csrf for k, v in consent.cookies.items(): c.cookies.set(k, v) r = c.post( "/consent", data={"action": "approve", "txn_id": txn_id, "csrf_token": csrf}, follow_redirects=False, ) assert r.status_code in (302, 303) set_cookie_header = r.headers.get("set-cookie", "") assert "__Host-MCP_CONSENT_BINDING" in set_cookie_header async def test_auto_approve_sets_consent_binding_cookie(self, oauth_proxy_https): """Auto-approve path (previously approved client) must also set the binding cookie.""" client_id = "client-autobinding" redirect = "http://localhost:6002/callback" txn_id, _ = await _start_flow(oauth_proxy_https, client_id, redirect) app = Starlette(routes=oauth_proxy_https.get_routes()) with TestClient(app) as c: # First: approve manually to get the approved cookie consent = c.get(f"/consent?txn_id={txn_id}") csrf = _extract_csrf(consent.text) assert csrf for k, v in consent.cookies.items(): c.cookies.set(k, v) r = c.post( "/consent", data={"action": "approve", "txn_id": txn_id, "csrf_token": csrf}, follow_redirects=False, ) # Extract approved cookie m = re.search( r"__Host-MCP_APPROVED_CLIENTS=([^;]+)", r.headers.get("set-cookie", ""), ) assert m approved_cookie = m.group(1) # Second: start new flow, auto-approve should set binding cookie new_txn, _ = await _start_flow(oauth_proxy_https, client_id, redirect) c.cookies.set("__Host-MCP_APPROVED_CLIENTS", approved_cookie) r2 = c.get(f"/consent?txn_id={new_txn}", follow_redirects=False) assert r2.status_code in (302, 303) set_cookie_header = r2.headers.get("set-cookie", "") assert "__Host-MCP_CONSENT_BINDING" in set_cookie_header async def test_parallel_flows_do_not_interfere(self, oauth_proxy_https): """Multiple concurrent consent flows in the same browser must not clobber each other. Uses two different clients so the second flow also shows a consent form (auto-approve only kicks in for the same client+redirect pair). """ txn1, _ = await _start_flow( oauth_proxy_https, "client-par-a", "http://localhost:6010/callback" ) txn2, _ = await _start_flow( oauth_proxy_https, "client-par-b", "http://localhost:6011/callback" ) app = Starlette(routes=oauth_proxy_https.get_routes()) with TestClient(app) as c: # Approve first flow consent1 = c.get(f"/consent?txn_id={txn1}") csrf1 = _extract_csrf(consent1.text) assert csrf1 for k, v in consent1.cookies.items(): c.cookies.set(k, v) r1 = c.post( "/consent", data={"action": "approve", "txn_id": txn1, "csrf_token": csrf1}, follow_redirects=False, ) assert r1.status_code in (302, 303) for k, v in r1.cookies.items(): c.cookies.set(k, v) # Approve second flow (different client, so consent form is shown) consent2 = c.get(f"/consent?txn_id={txn2}") csrf2 = _extract_csrf(consent2.text) assert csrf2 for k, v in consent2.cookies.items(): c.cookies.set(k, v) r2 = c.post( "/consent", data={"action": "approve", "txn_id": txn2, "csrf_token": csrf2}, follow_redirects=False, ) assert r2.status_code in (302, 303) for k, v in r2.cookies.items(): c.cookies.set(k, v) # Both transactions should have consent tokens txn1_model = await oauth_proxy_https._transaction_store.get(key=txn1) txn2_model = await oauth_proxy_https._transaction_store.get(key=txn2) assert txn1_model is not None and txn1_model.consent_token assert txn2_model is not None and txn2_model.consent_token # First flow's callback should still work (cookie has both bindings) r_cb1 = c.get( f"/auth/callback?code=fake&state={txn1}", follow_redirects=False ) # Should NOT be 403 — the binding for txn1 should still be in the cookie. # It will fail at token exchange (500) but not at consent verification. assert r_cb1.status_code != 403 async def test_idp_callback_rejects_missing_consent_cookie(self, oauth_proxy_https): """IdP callback must reject requests without the consent binding cookie. This is the core confused deputy scenario: a different browser (the victim) hits the callback without the cookie that was set on the attacker's browser. """ txn_id, _ = await _start_flow( oauth_proxy_https, "client-nocd", "http://localhost:6003/callback" ) # Manually set consent_token on transaction (simulating consent approval) txn_model = await oauth_proxy_https._transaction_store.get(key=txn_id) assert txn_model is not None txn_model.consent_token = secrets.token_urlsafe(32) await oauth_proxy_https._transaction_store.put( key=txn_id, value=txn_model, ttl=15 * 60 ) app = Starlette(routes=oauth_proxy_https.get_routes()) with TestClient(app) as c: # Hit callback WITHOUT the consent binding cookie r = c.get( f"/auth/callback?code=fake-code&state={txn_id}", follow_redirects=False, ) assert r.status_code == 403 assert ( "session mismatch" in r.text.lower() or "Authorization Error" in r.text ) async def test_idp_callback_rejects_wrong_consent_cookie(self, oauth_proxy_https): """IdP callback must reject requests with a tampered consent binding cookie.""" txn_id, _ = await _start_flow( oauth_proxy_https, "client-wrongcd", "http://localhost:6004/callback" ) txn_model = await oauth_proxy_https._transaction_store.get(key=txn_id) assert txn_model is not None txn_model.consent_token = secrets.token_urlsafe(32) await oauth_proxy_https._transaction_store.put( key=txn_id, value=txn_model, ttl=15 * 60 ) app = Starlette(routes=oauth_proxy_https.get_routes()) with TestClient(app) as c: # Set a wrong/tampered consent binding cookie c.cookies.set("__Host-MCP_CONSENT_BINDING", "wrong-token.invalidsig") r = c.get( f"/auth/callback?code=fake-code&state={txn_id}", follow_redirects=False, ) assert r.status_code == 403 async def test_idp_callback_rejects_missing_consent_token_on_transaction( self, oauth_proxy_https ): """IdP callback must reject when transaction has no consent_token set.""" txn_id, _ = await _start_flow( oauth_proxy_https, "client-notxntoken", "http://localhost:6005/callback" ) # Transaction exists but consent_token is None (consent was never completed) app = Starlette(routes=oauth_proxy_https.get_routes()) with TestClient(app) as c: r = c.get( f"/auth/callback?code=fake-code&state={txn_id}", follow_redirects=False, ) assert r.status_code == 403 async def test_consent_disabled_skips_binding_check(self): """When require_authorization_consent=False, the binding check is skipped.""" proxy = OAuthProxy( upstream_authorization_endpoint="https://github.com/login/oauth/authorize", upstream_token_endpoint="https://github.com/login/oauth/access_token", upstream_client_id="client-id", upstream_client_secret="client-secret", token_verifier=_Verifier(), base_url="https://myserver.example", client_storage=MemoryStore(), jwt_signing_key="test-secret", require_authorization_consent=False, ) client_id = "client-noconsent" redirect = "http://localhost:6006/callback" await proxy.register_client( OAuthClientInformationFull( client_id=client_id, client_secret="s", redirect_uris=[AnyUrl(redirect)], ) ) params = AuthorizationParams( redirect_uri=AnyUrl(redirect), redirect_uri_provided_explicitly=True, state="st", code_challenge="ch", scopes=["read"], ) upstream_url = await proxy.authorize( OAuthClientInformationFull( client_id=client_id, client_secret="s", redirect_uris=[AnyUrl(redirect)], ), params, ) # With consent disabled, authorize returns upstream URL directly assert upstream_url.startswith("https://github.com/login/oauth/authorize") qs = parse_qs(urlparse(upstream_url).query) txn_id = qs["state"][0] # The transaction should have no consent_token txn_model = await proxy._transaction_store.get(key=txn_id) assert txn_model is not None assert txn_model.consent_token is None # IdP callback should NOT reject due to missing consent cookie # (it will fail at token exchange, but not at the consent check) app = Starlette(routes=proxy.get_routes()) with TestClient(app) as c: r = c.get( f"/auth/callback?code=fake-code&state={txn_id}", follow_redirects=False, ) # Should NOT be 403 (consent binding rejection) # It will be 500 because the fake code can't be exchanged with GitHub, # but that's fine — we're verifying the consent check was skipped. assert r.status_code != 403
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/auth/test_oauth_consent_page.py", "license": "Apache License 2.0", "lines": 598, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/server/auth/test_oidc_proxy_token.py
"""Tests for OIDC Proxy verify_id_token functionality.""" from unittest.mock import patch import pytest from pydantic import AnyHttpUrl from fastmcp.server.auth.oauth_proxy.models import UpstreamTokenSet from fastmcp.server.auth.oidc_proxy import OIDCConfiguration, OIDCProxy from fastmcp.server.auth.providers.introspection import IntrospectionTokenVerifier from fastmcp.server.auth.providers.jwt import JWTVerifier TEST_ISSUER = "https://example.com" TEST_AUTHORIZATION_ENDPOINT = "https://example.com/authorize" TEST_TOKEN_ENDPOINT = "https://example.com/oauth/token" TEST_CONFIG_URL = AnyHttpUrl("https://example.com/.well-known/openid-configuration") TEST_CLIENT_ID = "test-client-id" TEST_CLIENT_SECRET = "test-client-secret" TEST_BASE_URL = AnyHttpUrl("https://example.com:8000/") # ============================================================================= # Shared Fixtures # ============================================================================= @pytest.fixture def valid_oidc_configuration_dict(): """Create a valid OIDC configuration dict for testing.""" return { "issuer": TEST_ISSUER, "authorization_endpoint": TEST_AUTHORIZATION_ENDPOINT, "token_endpoint": TEST_TOKEN_ENDPOINT, "jwks_uri": "https://example.com/.well-known/jwks.json", "response_types_supported": ["code"], "subject_types_supported": ["public"], "id_token_signing_alg_values_supported": ["RS256"], } # ============================================================================= # Test Helpers # ============================================================================= def _make_upstream_token_set(*, id_token: str | None = None) -> UpstreamTokenSet: """Create an UpstreamTokenSet with optional id_token.""" raw_token_data: dict[str, str] = {"access_token": "opaque-access-token"} if id_token is not None: raw_token_data["id_token"] = id_token return UpstreamTokenSet( upstream_token_id="test-id", access_token="opaque-access-token", refresh_token=None, refresh_token_expires_at=None, expires_at=9999999999.0, token_type="Bearer", scope="openid", client_id="test-client", created_at=1000000000.0, raw_token_data=raw_token_data, ) # ============================================================================= # Test Classes # ============================================================================= class TestVerifyIdToken: """Tests for verify_id_token functionality.""" def test_verify_id_token_disabled_by_default(self, valid_oidc_configuration_dict): """Default behavior: verify the access_token.""" with patch( "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration" ) as mock_get: oidc_config = OIDCConfiguration.model_validate( valid_oidc_configuration_dict ) mock_get.return_value = oidc_config proxy = OIDCProxy( config_url=TEST_CONFIG_URL, client_id=TEST_CLIENT_ID, client_secret=TEST_CLIENT_SECRET, base_url=TEST_BASE_URL, jwt_signing_key="test-secret", ) token_set = _make_upstream_token_set(id_token="jwt-id-token") assert proxy._get_verification_token(token_set) == "opaque-access-token" def test_verify_id_token_returns_id_token(self, valid_oidc_configuration_dict): """When enabled, verify the id_token instead of access_token.""" with patch( "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration" ) as mock_get: oidc_config = OIDCConfiguration.model_validate( valid_oidc_configuration_dict ) mock_get.return_value = oidc_config proxy = OIDCProxy( config_url=TEST_CONFIG_URL, client_id=TEST_CLIENT_ID, client_secret=TEST_CLIENT_SECRET, base_url=TEST_BASE_URL, jwt_signing_key="test-secret", verify_id_token=True, ) token_set = _make_upstream_token_set(id_token="jwt-id-token") assert proxy._get_verification_token(token_set) == "jwt-id-token" def test_verify_id_token_returns_none_when_missing( self, valid_oidc_configuration_dict ): """When enabled but id_token is absent, return None.""" with patch( "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration" ) as mock_get: oidc_config = OIDCConfiguration.model_validate( valid_oidc_configuration_dict ) mock_get.return_value = oidc_config proxy = OIDCProxy( config_url=TEST_CONFIG_URL, client_id=TEST_CLIENT_ID, client_secret=TEST_CLIENT_SECRET, base_url=TEST_BASE_URL, jwt_signing_key="test-secret", verify_id_token=True, ) token_set = _make_upstream_token_set(id_token=None) assert proxy._get_verification_token(token_set) is None def test_verify_id_token_works_with_custom_verifier( self, valid_oidc_configuration_dict ): """verify_id_token can be combined with a custom token_verifier.""" with patch( "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration" ) as mock_get: oidc_config = OIDCConfiguration.model_validate( valid_oidc_configuration_dict ) mock_get.return_value = oidc_config custom_verifier = IntrospectionTokenVerifier( introspection_url="https://example.com/oauth/introspect", client_id="introspection-client", client_secret="introspection-secret", ) proxy = OIDCProxy( config_url=TEST_CONFIG_URL, client_id=TEST_CLIENT_ID, client_secret=TEST_CLIENT_SECRET, base_url=TEST_BASE_URL, jwt_signing_key="test-secret", verify_id_token=True, token_verifier=custom_verifier, ) token_set = _make_upstream_token_set(id_token="jwt-id-token") assert proxy._get_verification_token(token_set) == "jwt-id-token" assert proxy._token_validator is custom_verifier def test_verify_id_token_survives_refresh_without_id_token( self, valid_oidc_configuration_dict ): """id_token from original auth is preserved when refresh omits it.""" with patch( "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration" ) as mock_get: oidc_config = OIDCConfiguration.model_validate( valid_oidc_configuration_dict ) mock_get.return_value = oidc_config proxy = OIDCProxy( config_url=TEST_CONFIG_URL, client_id=TEST_CLIENT_ID, client_secret=TEST_CLIENT_SECRET, base_url=TEST_BASE_URL, jwt_signing_key="test-secret", verify_id_token=True, ) token_set = _make_upstream_token_set(id_token="original-id-token") # Simulate a refresh response that omits id_token — # the merge in exchange_refresh_token should preserve it refresh_response = { "access_token": "new-access-token", "token_type": "Bearer", } token_set.raw_token_data = {**token_set.raw_token_data, **refresh_response} token_set.access_token = "new-access-token" assert proxy._get_verification_token(token_set) == "original-id-token" def test_verify_id_token_updated_when_refresh_includes_it( self, valid_oidc_configuration_dict ): """id_token is updated when refresh response includes a new one.""" with patch( "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration" ) as mock_get: oidc_config = OIDCConfiguration.model_validate( valid_oidc_configuration_dict ) mock_get.return_value = oidc_config proxy = OIDCProxy( config_url=TEST_CONFIG_URL, client_id=TEST_CLIENT_ID, client_secret=TEST_CLIENT_SECRET, base_url=TEST_BASE_URL, jwt_signing_key="test-secret", verify_id_token=True, ) token_set = _make_upstream_token_set(id_token="original-id-token") # Simulate a refresh response that includes a new id_token refresh_response = { "access_token": "new-access-token", "id_token": "refreshed-id-token", } token_set.raw_token_data = {**token_set.raw_token_data, **refresh_response} token_set.access_token = "new-access-token" assert proxy._get_verification_token(token_set) == "refreshed-id-token" def test_verify_id_token_uses_client_id_as_verifier_audience( self, valid_oidc_configuration_dict ): """When verify_id_token is enabled, the verifier audience should be client_id (matching id_token.aud), not the API audience parameter.""" with patch( "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration" ) as mock_get: oidc_config = OIDCConfiguration.model_validate( valid_oidc_configuration_dict ) mock_get.return_value = oidc_config proxy = OIDCProxy( config_url=TEST_CONFIG_URL, client_id=TEST_CLIENT_ID, client_secret=TEST_CLIENT_SECRET, base_url=TEST_BASE_URL, jwt_signing_key="test-secret", audience="https://api.example.com", verify_id_token=True, ) assert isinstance(proxy._token_validator, JWTVerifier) assert proxy._token_validator.audience == TEST_CLIENT_ID # The API audience should still be sent upstream assert ( proxy._extra_authorize_params["audience"] == "https://api.example.com" ) assert proxy._extra_token_params["audience"] == "https://api.example.com" def test_verify_id_token_without_audience_uses_client_id( self, valid_oidc_configuration_dict ): """When verify_id_token is enabled without an audience param, the verifier audience should still be client_id.""" with patch( "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration" ) as mock_get: oidc_config = OIDCConfiguration.model_validate( valid_oidc_configuration_dict ) mock_get.return_value = oidc_config proxy = OIDCProxy( config_url=TEST_CONFIG_URL, client_id=TEST_CLIENT_ID, client_secret=TEST_CLIENT_SECRET, base_url=TEST_BASE_URL, jwt_signing_key="test-secret", verify_id_token=True, ) assert isinstance(proxy._token_validator, JWTVerifier) assert proxy._token_validator.audience == TEST_CLIENT_ID def test_verify_id_token_does_not_enforce_scopes_on_verifier( self, valid_oidc_configuration_dict ): """When verify_id_token is enabled, required_scopes should not be passed to the JWTVerifier since id_tokens don't carry scope claims.""" with patch( "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration" ) as mock_get: oidc_config = OIDCConfiguration.model_validate( valid_oidc_configuration_dict ) mock_get.return_value = oidc_config proxy = OIDCProxy( config_url=TEST_CONFIG_URL, client_id=TEST_CLIENT_ID, client_secret=TEST_CLIENT_SECRET, base_url=TEST_BASE_URL, jwt_signing_key="test-secret", required_scopes=["read", "write"], verify_id_token=True, ) assert isinstance(proxy._token_validator, JWTVerifier) assert proxy._token_validator.required_scopes == [] # Scopes should still be advertised via the proxy's required_scopes assert proxy.required_scopes == ["read", "write"] # Derived scope state should also be recomputed assert proxy._default_scope_str == "read write" assert proxy.client_registration_options is not None assert proxy.client_registration_options.valid_scopes == [ "read", "write", ]
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/auth/test_oidc_proxy_token.py", "license": "Apache License 2.0", "lines": 280, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/server/middleware/test_middleware_nested.py
from collections.abc import Callable from dataclasses import dataclass from typing import Any import mcp.types import pytest from fastmcp import Client, FastMCP from fastmcp.exceptions import ToolError from fastmcp.server.context import Context from fastmcp.server.middleware import CallNext, Middleware, MiddlewareContext from fastmcp.tools.tool import ToolResult @dataclass class Recording: # the hook is the name of the hook that was called, e.g. "on_list_tools" hook: str context: MiddlewareContext result: mcp.types.ServerResult | None class RecordingMiddleware(Middleware): """A middleware that automatically records all method calls.""" def __init__(self, name: str | None = None): super().__init__() self.calls: list[Recording] = [] self.name = name def __getattribute__(self, name: str) -> Callable: """Dynamically create recording methods for any on_* method.""" if name.startswith("on_"): async def record_and_call( context: MiddlewareContext, call_next: Callable ) -> Any: result = await call_next(context) self.calls.append(Recording(hook=name, context=context, result=result)) return result return record_and_call return super().__getattribute__(name) def get_calls( self, method: str | None = None, hook: str | None = None ) -> list[Recording]: """ Get all recorded calls for a specific method or hook. Args: method: The method to filter by (e.g. "tools/list") hook: The hook to filter by (e.g. "on_list_tools") Returns: A list of recorded calls. """ calls = [] for recording in self.calls: if method and hook: if recording.context.method == method and recording.hook == hook: calls.append(recording) elif method: if recording.context.method == method: calls.append(recording) elif hook: if recording.hook == hook: calls.append(recording) else: calls.append(recording) return calls def assert_called( self, hook: str | None = None, method: str | None = None, times: int | None = None, at_least: int | None = None, ) -> bool: """Assert that a hook was called a specific number of times.""" if times is not None and at_least is not None: raise ValueError("Cannot specify both times and at_least") elif times is None and at_least is None: times = 1 calls = self.get_calls(hook=hook, method=method) actual_times = len(calls) identifier = dict(hook=hook, method=method) if times is not None: assert actual_times == times, ( f"Expected {times} calls for {identifier}, " f"but was called {actual_times} times" ) elif at_least is not None: assert actual_times >= at_least, ( f"Expected at least {at_least} calls for {identifier}, " f"but was called {actual_times} times" ) return True def assert_not_called(self, hook: str | None = None, method: str | None = None): """Assert that a hook was not called.""" calls = self.get_calls(hook=hook, method=method) assert len(calls) == 0, f"Expected {hook!r} to not be called" return True def reset(self): """Clear all recorded calls.""" self.calls.clear() @pytest.fixture def recording_middleware(): """Fixture that provides a recording middleware instance.""" middleware = RecordingMiddleware(name="recording_middleware") yield middleware @pytest.fixture def mcp_server(recording_middleware): mcp = FastMCP() @mcp.tool(tags={"add-tool"}) def add(a: int, b: int) -> int: return a + b @mcp.resource("resource://test") def test_resource() -> str: return "test resource" @mcp.resource("resource://test-template/{x}") def test_resource_with_path(x: int) -> str: return f"test resource with {x}" @mcp.prompt def test_prompt(x: str) -> str: return f"test prompt with {x}" @mcp.tool async def progress_tool(context: Context) -> None: await context.report_progress(progress=1, total=10, message="test") @mcp.tool async def log_tool(context: Context) -> None: await context.info(message="test log") @mcp.tool async def sample_tool(context: Context) -> None: await context.sample("hello") mcp.add_middleware(recording_middleware) # Register progress handler @mcp._mcp_server.progress_notification() async def handle_progress( progress_token: str | int, progress: float, total: float | None, message: str | None, ): print("HI") return mcp class TestNestedMiddlewareHooks: @pytest.fixture @staticmethod def nested_middleware(): return RecordingMiddleware(name="nested_middleware") @pytest.fixture def nested_mcp_server(self, nested_middleware: RecordingMiddleware): mcp = FastMCP(name="Nested MCP") @mcp.tool def add(a: int, b: int) -> int: return a + b @mcp.resource("resource://test") def test_resource() -> str: return "test resource" @mcp.resource("resource://test-template/{x}") def test_resource_with_path(x: int) -> str: return f"test resource with {x}" @mcp.prompt def test_prompt(x: str) -> str: return f"test prompt with {x}" @mcp.tool async def progress_tool(context: Context) -> None: await context.report_progress(progress=1, total=10, message="test") @mcp.tool async def log_tool(context: Context) -> None: await context.info(message="test log") @mcp.tool async def sample_tool(context: Context) -> None: await context.sample("hello") mcp.add_middleware(nested_middleware) return mcp async def test_call_tool_on_parent_server( self, mcp_server: FastMCP, nested_mcp_server: FastMCP, recording_middleware: RecordingMiddleware, nested_middleware: RecordingMiddleware, ): mcp_server.mount(nested_mcp_server, namespace="nested") async with Client(mcp_server) as client: await client.call_tool("add", {"a": 1, "b": 2}) assert recording_middleware.assert_called(at_least=3) assert recording_middleware.assert_called(method="tools/call", at_least=3) assert recording_middleware.assert_called(hook="on_message", at_least=1) assert recording_middleware.assert_called(hook="on_request", at_least=1) assert recording_middleware.assert_called(hook="on_call_tool", at_least=1) assert nested_middleware.assert_called(method="tools/call", times=0) async def test_call_tool_on_nested_server( self, mcp_server: FastMCP, nested_mcp_server: FastMCP, recording_middleware: RecordingMiddleware, nested_middleware: RecordingMiddleware, ): mcp_server.mount(nested_mcp_server, namespace="nested") async with Client(mcp_server) as client: await client.call_tool("nested_add", {"a": 1, "b": 2}) assert recording_middleware.assert_called(at_least=3) assert recording_middleware.assert_called(method="tools/call", at_least=3) assert recording_middleware.assert_called(hook="on_message", at_least=1) assert recording_middleware.assert_called(hook="on_request", at_least=1) assert recording_middleware.assert_called(hook="on_call_tool", at_least=1) assert nested_middleware.assert_called(at_least=3) assert nested_middleware.assert_called(method="tools/call", at_least=3) assert nested_middleware.assert_called(hook="on_message", at_least=1) assert nested_middleware.assert_called(hook="on_request", at_least=1) assert nested_middleware.assert_called(hook="on_call_tool", at_least=1) async def test_read_resource_on_parent_server( self, mcp_server: FastMCP, nested_mcp_server: FastMCP, recording_middleware: RecordingMiddleware, nested_middleware: RecordingMiddleware, ): mcp_server.mount(nested_mcp_server, namespace="nested") async with Client(mcp_server) as client: await client.read_resource("resource://test") assert recording_middleware.assert_called(at_least=3) assert recording_middleware.assert_called(method="resources/read", at_least=3) assert recording_middleware.assert_called(hook="on_message", at_least=1) assert recording_middleware.assert_called(hook="on_request", at_least=1) assert recording_middleware.assert_called(hook="on_read_resource", at_least=1) assert nested_middleware.assert_called(times=0) async def test_read_resource_on_nested_server( self, mcp_server: FastMCP, nested_mcp_server: FastMCP, recording_middleware: RecordingMiddleware, nested_middleware: RecordingMiddleware, ): mcp_server.mount(nested_mcp_server, namespace="nested") async with Client(mcp_server) as client: await client.read_resource("resource://nested/test") assert recording_middleware.assert_called(at_least=3) assert recording_middleware.assert_called(method="resources/read", at_least=3) assert recording_middleware.assert_called(hook="on_message", at_least=1) assert recording_middleware.assert_called(hook="on_request", at_least=1) assert recording_middleware.assert_called(hook="on_read_resource", at_least=1) assert nested_middleware.assert_called(at_least=3) assert nested_middleware.assert_called(method="resources/read", at_least=3) assert nested_middleware.assert_called(hook="on_message", at_least=1) assert nested_middleware.assert_called(hook="on_request", at_least=1) assert nested_middleware.assert_called(hook="on_read_resource", at_least=1) async def test_read_resource_template_on_parent_server( self, mcp_server: FastMCP, nested_mcp_server: FastMCP, recording_middleware: RecordingMiddleware, nested_middleware: RecordingMiddleware, ): mcp_server.mount(nested_mcp_server, namespace="nested") async with Client(mcp_server) as client: await client.read_resource("resource://test-template/1") assert recording_middleware.assert_called(at_least=3) assert recording_middleware.assert_called(method="resources/read", at_least=3) assert recording_middleware.assert_called(hook="on_message", at_least=1) assert recording_middleware.assert_called(hook="on_request", at_least=1) assert recording_middleware.assert_called(hook="on_read_resource", at_least=1) assert nested_middleware.assert_called(times=0) async def test_read_resource_template_on_nested_server( self, mcp_server: FastMCP, nested_mcp_server: FastMCP, recording_middleware: RecordingMiddleware, nested_middleware: RecordingMiddleware, ): mcp_server.mount(nested_mcp_server, namespace="nested") async with Client(mcp_server) as client: await client.read_resource("resource://nested/test-template/1") assert recording_middleware.assert_called(at_least=3) assert recording_middleware.assert_called(method="resources/read", at_least=3) assert recording_middleware.assert_called(hook="on_message", at_least=1) assert recording_middleware.assert_called(hook="on_request", at_least=1) assert recording_middleware.assert_called(hook="on_read_resource", at_least=1) assert nested_middleware.assert_called(at_least=3) assert nested_middleware.assert_called(method="resources/read", at_least=3) assert nested_middleware.assert_called(hook="on_message", at_least=1) assert nested_middleware.assert_called(hook="on_request", at_least=1) assert nested_middleware.assert_called(hook="on_read_resource", at_least=1) async def test_get_prompt_on_parent_server( self, mcp_server: FastMCP, nested_mcp_server: FastMCP, recording_middleware: RecordingMiddleware, nested_middleware: RecordingMiddleware, ): mcp_server.mount(nested_mcp_server, namespace="nested") async with Client(mcp_server) as client: await client.get_prompt("test_prompt", {"x": "test"}) assert recording_middleware.assert_called(at_least=3) assert recording_middleware.assert_called(method="prompts/get", at_least=3) assert recording_middleware.assert_called(hook="on_message", at_least=1) assert recording_middleware.assert_called(hook="on_request", at_least=1) assert recording_middleware.assert_called(hook="on_get_prompt", at_least=1) assert nested_middleware.assert_called(times=0) async def test_get_prompt_on_nested_server( self, mcp_server: FastMCP, nested_mcp_server: FastMCP, recording_middleware: RecordingMiddleware, nested_middleware: RecordingMiddleware, ): mcp_server.mount(nested_mcp_server, namespace="nested") async with Client(mcp_server) as client: await client.get_prompt("nested_test_prompt", {"x": "test"}) assert recording_middleware.assert_called(at_least=3) assert recording_middleware.assert_called(method="prompts/get", at_least=3) assert recording_middleware.assert_called(hook="on_message", at_least=1) assert recording_middleware.assert_called(hook="on_request", at_least=1) assert recording_middleware.assert_called(hook="on_get_prompt", at_least=1) assert nested_middleware.assert_called(at_least=3) assert nested_middleware.assert_called(method="prompts/get", at_least=3) assert nested_middleware.assert_called(hook="on_message", at_least=1) assert nested_middleware.assert_called(hook="on_request", at_least=1) assert nested_middleware.assert_called(hook="on_get_prompt", at_least=1) async def test_list_tools_on_nested_server( self, mcp_server: FastMCP, nested_mcp_server: FastMCP, recording_middleware: RecordingMiddleware, nested_middleware: RecordingMiddleware, ): mcp_server.mount(nested_mcp_server, namespace="nested") async with Client(mcp_server) as client: await client.list_tools() assert recording_middleware.assert_called(at_least=3) assert recording_middleware.assert_called(method="tools/list", at_least=3) assert recording_middleware.assert_called(hook="on_message", at_least=1) assert recording_middleware.assert_called(hook="on_request", at_least=1) assert recording_middleware.assert_called(hook="on_list_tools", at_least=1) assert nested_middleware.assert_called(at_least=3) assert nested_middleware.assert_called(method="tools/list", at_least=3) assert nested_middleware.assert_called(hook="on_message", at_least=1) assert nested_middleware.assert_called(hook="on_request", at_least=1) assert nested_middleware.assert_called(hook="on_list_tools", at_least=1) async def test_list_resources_on_nested_server( self, mcp_server: FastMCP, nested_mcp_server: FastMCP, recording_middleware: RecordingMiddleware, nested_middleware: RecordingMiddleware, ): mcp_server.mount(nested_mcp_server, namespace="nested") async with Client(mcp_server) as client: await client.list_resources() assert recording_middleware.assert_called(at_least=3) assert recording_middleware.assert_called(method="resources/list", at_least=3) assert recording_middleware.assert_called(hook="on_message", at_least=1) assert recording_middleware.assert_called(hook="on_request", at_least=1) assert recording_middleware.assert_called(hook="on_list_resources", at_least=1) assert nested_middleware.assert_called(at_least=3) assert nested_middleware.assert_called(method="resources/list", at_least=3) assert nested_middleware.assert_called(hook="on_message", at_least=1) assert nested_middleware.assert_called(hook="on_request", at_least=1) assert nested_middleware.assert_called(hook="on_list_resources", at_least=1) async def test_list_resource_templates_on_nested_server( self, mcp_server: FastMCP, nested_mcp_server: FastMCP, recording_middleware: RecordingMiddleware, nested_middleware: RecordingMiddleware, ): mcp_server.mount(nested_mcp_server, namespace="nested") async with Client(mcp_server) as client: await client.list_resource_templates() assert recording_middleware.assert_called(at_least=3) assert recording_middleware.assert_called( method="resources/templates/list", at_least=3 ) assert recording_middleware.assert_called(hook="on_message", at_least=1) assert recording_middleware.assert_called(hook="on_request", at_least=1) assert recording_middleware.assert_called( hook="on_list_resource_templates", at_least=1 ) assert nested_middleware.assert_called(at_least=3) assert nested_middleware.assert_called( method="resources/templates/list", at_least=3 ) assert nested_middleware.assert_called(hook="on_message", at_least=1) assert nested_middleware.assert_called(hook="on_request", at_least=1) assert nested_middleware.assert_called( hook="on_list_resource_templates", at_least=1 ) class TestProxyServer: async def test_call_tool( self, mcp_server: FastMCP, recording_middleware: RecordingMiddleware ): # proxy server will have its tools listed as well as called in order to # apply transforms and filters prior to the call. proxy_server = FastMCP.as_proxy(mcp_server, name="Proxy Server") async with Client(proxy_server) as client: await client.call_tool("add", {"a": 1, "b": 2}) assert recording_middleware.assert_called(at_least=6) assert recording_middleware.assert_called(method="tools/call", at_least=3) assert recording_middleware.assert_called(method="tools/list", at_least=3) assert recording_middleware.assert_called(hook="on_message", at_least=2) assert recording_middleware.assert_called(hook="on_request", at_least=2) assert recording_middleware.assert_called(hook="on_call_tool", at_least=1) assert recording_middleware.assert_called(hook="on_list_tools", at_least=1) async def test_proxied_tags_are_visible_to_middleware( self, mcp_server: FastMCP, recording_middleware: RecordingMiddleware ): """Tests that tags on remote FastMCP servers are visible to middleware via proxy. See https://github.com/PrefectHQ/fastmcp/issues/1300""" proxy_server = FastMCP.as_proxy(mcp_server, name="Proxy Server") TAGS = [] class TagMiddleware(Middleware): async def on_list_tools(self, context: MiddlewareContext, call_next): nonlocal TAGS result = await call_next(context) for tool in result: TAGS.append(tool.tags) return result proxy_server.add_middleware(TagMiddleware()) async with Client(proxy_server) as client: await client.list_tools() assert TAGS == [{"add-tool"}, set(), set(), set()] class TestToolCallDenial: """Test denying tool calls in middleware using ToolError.""" async def test_deny_tool_call_with_tool_error(self): """Test that middleware can deny tool calls by raising ToolError.""" class AuthMiddleware(Middleware): async def on_call_tool( self, context: MiddlewareContext[mcp.types.CallToolRequestParams], call_next: CallNext[mcp.types.CallToolRequestParams, ToolResult], ) -> ToolResult: tool_name = context.message.name if tool_name.lower() == "restricted_tool": raise ToolError("Access denied: tool is disabled") return await call_next(context) server = FastMCP("TestServer") @server.tool def allowed_tool(x: int) -> int: """This tool is allowed.""" return x * 2 @server.tool def restricted_tool(x: int) -> int: """This tool should be denied by middleware.""" return x * 3 server.add_middleware(AuthMiddleware()) async with Client(server) as client: # Allowed tool should work normally result = await client.call_tool("allowed_tool", {"x": 5}) assert result.structured_content is not None assert result.structured_content["result"] == 10 # Restricted tool should raise ToolError with pytest.raises(ToolError) as exc_info: await client.call_tool("restricted_tool", {"x": 5}) # Verify the error message is preserved assert "Access denied: tool is disabled" in str(exc_info.value) async def test_middleware_can_selectively_deny_tools(self): """Test that middleware can deny specific tools while allowing others.""" denied_tools = set() class SelectiveAuthMiddleware(Middleware): async def on_call_tool( self, context: MiddlewareContext[mcp.types.CallToolRequestParams], call_next: CallNext[mcp.types.CallToolRequestParams, ToolResult], ) -> ToolResult: tool_name = context.message.name # Deny tools that start with "admin_" if tool_name.startswith("admin_"): denied_tools.add(tool_name) raise ToolError( f"Access denied: {tool_name} requires admin privileges" ) return await call_next(context) server = FastMCP("TestServer") @server.tool def public_tool(x: int) -> int: """Public tool available to all.""" return x + 1 @server.tool def admin_delete(item_id: str) -> str: """Admin tool that should be denied.""" return f"Deleted {item_id}" @server.tool def admin_config(setting: str, value: str) -> str: """Another admin tool that should be denied.""" return f"Set {setting} to {value}" server.add_middleware(SelectiveAuthMiddleware()) async with Client(server) as client: # Public tool should work result = await client.call_tool("public_tool", {"x": 10}) assert result.structured_content is not None assert result.structured_content["result"] == 11 # Admin tools should be denied with pytest.raises(ToolError) as exc_info: await client.call_tool("admin_delete", {"item_id": "test123"}) assert "requires admin privileges" in str(exc_info.value) with pytest.raises(ToolError) as exc_info: await client.call_tool( "admin_config", {"setting": "debug", "value": "true"} ) assert "requires admin privileges" in str(exc_info.value) # Verify both admin tools were denied assert denied_tools == {"admin_delete", "admin_config"} class TestMiddlewareRequestState: """Non-serializable state set in middleware must be visible to tools/resources. Regression test for https://github.com/PrefectHQ/fastmcp/issues/3228. """ async def test_non_serializable_state_from_middleware_visible_in_tool(self): server = FastMCP("test") sentinel = object() class StateMiddleware(Middleware): async def on_call_tool( self, context: MiddlewareContext, call_next: CallNext ) -> Any: assert context.fastmcp_context is not None await context.fastmcp_context.set_state( "obj", sentinel, serializable=False ) return await call_next(context) server.add_middleware(StateMiddleware()) @server.tool() async def read_it(ctx: Context) -> str: val = await ctx.get_state("obj") return "found" if val is sentinel else "missing" async with Client(server) as client: result = await client.call_tool("read_it") assert result.content[0].text == "found" async def test_non_serializable_state_from_middleware_visible_in_resource(self): server = FastMCP("test") sentinel = object() class StateMiddleware(Middleware): async def on_read_resource( self, context: MiddlewareContext, call_next: CallNext ) -> Any: assert context.fastmcp_context is not None await context.fastmcp_context.set_state( "obj", sentinel, serializable=False ) return await call_next(context) server.add_middleware(StateMiddleware()) @server.resource("test://data") async def read_it(ctx: Context) -> str: val = await ctx.get_state("obj") return "found" if val is sentinel else "missing" async with Client(server) as client: result = await client.read_resource("test://data") assert result[0].text == "found"
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/middleware/test_middleware_nested.py", "license": "Apache License 2.0", "lines": 534, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/server/test_auth_integration_errors.py
import base64 import hashlib import secrets import time from urllib.parse import parse_qs, urlparse import httpx import pytest from mcp.server.auth.provider import ( AccessToken, AuthorizationCode, AuthorizationParams, OAuthAuthorizationServerProvider, RefreshToken, construct_redirect_uri, ) from mcp.server.auth.routes import ( create_auth_routes, ) from mcp.server.auth.settings import ( ClientRegistrationOptions, RevocationOptions, ) from mcp.shared.auth import ( OAuthClientInformationFull, OAuthToken, ) from pydantic import AnyHttpUrl from starlette.applications import Starlette # Mock OAuth provider for testing class MockOAuthProvider(OAuthAuthorizationServerProvider): def __init__(self): self.clients = {} self.auth_codes = {} # code -> {client_id, code_challenge, redirect_uri} self.tokens = {} # token -> {client_id, scopes, expires_at} self.refresh_tokens = {} # refresh_token -> access_token async def get_client(self, client_id: str) -> OAuthClientInformationFull | None: return self.clients.get(client_id) async def register_client(self, client_info: OAuthClientInformationFull): self.clients[client_info.client_id] = client_info async def authorize( self, client: OAuthClientInformationFull, params: AuthorizationParams ) -> str: # toy authorize implementation which just immediately generates an authorization # code and completes the redirect if client.client_id is None: raise ValueError("client_id is required") code = AuthorizationCode( code=f"code_{int(time.time())}", client_id=client.client_id, code_challenge=params.code_challenge, redirect_uri=params.redirect_uri, redirect_uri_provided_explicitly=params.redirect_uri_provided_explicitly, expires_at=time.time() + 300, scopes=params.scopes or ["read", "write"], ) self.auth_codes[code.code] = code return construct_redirect_uri( str(params.redirect_uri), code=code.code, state=params.state ) async def load_authorization_code( self, client: OAuthClientInformationFull, authorization_code: str ) -> AuthorizationCode | None: return self.auth_codes.get(authorization_code) async def exchange_authorization_code( self, client: OAuthClientInformationFull, authorization_code: AuthorizationCode ) -> OAuthToken: assert authorization_code.code in self.auth_codes # Generate an access token and refresh token access_token = f"access_{secrets.token_hex(32)}" refresh_token = f"refresh_{secrets.token_hex(32)}" # Store the tokens if client.client_id is None: raise ValueError("client_id is required") self.tokens[access_token] = AccessToken( token=access_token, client_id=client.client_id, scopes=authorization_code.scopes, expires_at=int(time.time()) + 3600, ) self.refresh_tokens[refresh_token] = access_token # Remove the used code del self.auth_codes[authorization_code.code] return OAuthToken( access_token=access_token, token_type="Bearer", expires_in=3600, scope="read write", refresh_token=refresh_token, ) async def load_refresh_token( self, client: OAuthClientInformationFull, refresh_token: str ) -> RefreshToken | None: old_access_token = self.refresh_tokens.get(refresh_token) if old_access_token is None: return None token_info = self.tokens.get(old_access_token) if token_info is None: return None # Create a RefreshToken object that matches what is expected in later code refresh_obj = RefreshToken( token=refresh_token, client_id=token_info.client_id, scopes=token_info.scopes, expires_at=token_info.expires_at, ) return refresh_obj async def exchange_refresh_token( self, client: OAuthClientInformationFull, refresh_token: RefreshToken, scopes: list[str], ) -> OAuthToken: # Check if refresh token exists assert refresh_token.token in self.refresh_tokens old_access_token = self.refresh_tokens[refresh_token.token] # Check if the access token exists assert old_access_token in self.tokens # Check if the token was issued to this client token_info = self.tokens[old_access_token] assert token_info.client_id == client.client_id # Generate a new access token and refresh token new_access_token = f"access_{secrets.token_hex(32)}" new_refresh_token = f"refresh_{secrets.token_hex(32)}" # Store the new tokens if client.client_id is None: raise ValueError("client_id is required") self.tokens[new_access_token] = AccessToken( token=new_access_token, client_id=client.client_id, scopes=scopes or token_info.scopes, expires_at=int(time.time()) + 3600, ) self.refresh_tokens[new_refresh_token] = new_access_token # Remove the old tokens del self.refresh_tokens[refresh_token.token] del self.tokens[old_access_token] return OAuthToken( access_token=new_access_token, token_type="Bearer", expires_in=3600, scope=" ".join(scopes) if scopes else " ".join(token_info.scopes), refresh_token=new_refresh_token, ) async def load_access_token(self, token: str) -> AccessToken | None: token_info = self.tokens.get(token) return token_info and AccessToken( token=token, client_id=token_info.client_id, scopes=token_info.scopes, expires_at=token_info.expires_at, ) async def revoke_token(self, token: AccessToken | RefreshToken) -> None: match token: case RefreshToken(): # Remove the refresh token del self.refresh_tokens[token.token] case AccessToken(): # Remove the access token del self.tokens[token.token] # Also remove any refresh tokens that point to this access token for refresh_token, access_token in list(self.refresh_tokens.items()): if access_token == token.token: del self.refresh_tokens[refresh_token] @pytest.fixture def mock_oauth_provider(): return MockOAuthProvider() @pytest.fixture def auth_app(mock_oauth_provider): # Create auth router auth_routes = create_auth_routes( mock_oauth_provider, AnyHttpUrl("https://auth.example.com"), AnyHttpUrl("https://docs.example.com"), client_registration_options=ClientRegistrationOptions( enabled=True, valid_scopes=["read", "write", "profile"], default_scopes=["read", "write"], ), revocation_options=RevocationOptions(enabled=True), ) # Create Starlette app app = Starlette(routes=auth_routes) return app @pytest.fixture async def test_client(auth_app): async with httpx.AsyncClient( transport=httpx.ASGITransport(app=auth_app), base_url="https://mcptest.com" ) as client: yield client @pytest.fixture async def registered_client(test_client: httpx.AsyncClient, request): """Create and register a test client. Parameters can be customized via indirect parameterization: @pytest.mark.parametrize("registered_client", [{"grant_types": ["authorization_code"]}], indirect=True) """ # Default client metadata client_metadata = { "redirect_uris": ["https://client.example.com/callback"], "client_name": "Test Client", "grant_types": ["authorization_code", "refresh_token"], } # Override with any parameters from the test if hasattr(request, "param") and request.param: client_metadata.update(request.param) response = await test_client.post("/register", json=client_metadata) assert response.status_code == 201, f"Failed to register client: {response.content}" client_info = response.json() return client_info @pytest.fixture def pkce_challenge(): """Create a PKCE challenge with code_verifier and code_challenge.""" code_verifier = "some_random_verifier_string" code_challenge = ( base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode()).digest()) .decode() .rstrip("=") ) return {"code_verifier": code_verifier, "code_challenge": code_challenge} class TestAuthorizeEndpointErrors: """Test error handling in the OAuth authorization endpoint.""" async def test_authorize_missing_client_id( self, test_client: httpx.AsyncClient, pkce_challenge ): """Test authorization endpoint with missing client_id. According to the OAuth2.0 spec, if client_id is missing, the server should inform the resource owner and NOT redirect. """ response = await test_client.get( "/authorize", params={ "response_type": "code", # Missing client_id "redirect_uri": "https://client.example.com/callback", "state": "test_state", "code_challenge": pkce_challenge["code_challenge"], "code_challenge_method": "S256", }, ) # Should NOT redirect, should show an error page assert response.status_code == 400 # The response should include an error message about missing client_id assert "client_id" in response.text.lower() async def test_authorize_invalid_client_id( self, test_client: httpx.AsyncClient, pkce_challenge ): """Test authorization endpoint with invalid client_id. According to the OAuth2.0 spec, if client_id is invalid, the server should inform the resource owner and NOT redirect. """ response = await test_client.get( "/authorize", params={ "response_type": "code", "client_id": "invalid_client_id_that_does_not_exist", "redirect_uri": "https://client.example.com/callback", "state": "test_state", "code_challenge": pkce_challenge["code_challenge"], "code_challenge_method": "S256", }, ) # Should NOT redirect, should show an error page assert response.status_code == 400 # The response should include an error message about invalid client_id assert "client" in response.text.lower() async def test_authorize_missing_redirect_uri( self, test_client: httpx.AsyncClient, registered_client, pkce_challenge ): """Test authorization endpoint with missing redirect_uri. If client has only one registered redirect_uri, it can be omitted. """ response = await test_client.get( "/authorize", params={ "response_type": "code", "client_id": registered_client["client_id"], # Missing redirect_uri "code_challenge": pkce_challenge["code_challenge"], "code_challenge_method": "S256", "state": "test_state", }, ) # Should redirect to the registered redirect_uri assert response.status_code == 302, response.content redirect_url = response.headers["location"] assert redirect_url.startswith("https://client.example.com/callback") async def test_authorize_invalid_redirect_uri( self, test_client: httpx.AsyncClient, registered_client, pkce_challenge ): """Test authorization endpoint with invalid redirect_uri. According to the OAuth2.0 spec, if redirect_uri is invalid or doesn't match, the server should inform the resource owner and NOT redirect. """ response = await test_client.get( "/authorize", params={ "response_type": "code", "client_id": registered_client["client_id"], # Non-matching URI "redirect_uri": "https://attacker.example.com/callback", "code_challenge": pkce_challenge["code_challenge"], "code_challenge_method": "S256", "state": "test_state", }, ) # Should NOT redirect, should show an error page assert response.status_code == 400, response.content # The response should include an error message about redirect_uri mismatch assert "redirect" in response.text.lower() @pytest.mark.parametrize( "registered_client", [ { "redirect_uris": [ "https://client.example.com/callback", "https://client.example.com/other-callback", ] } ], indirect=True, ) async def test_authorize_missing_redirect_uri_multiple_registered( self, test_client: httpx.AsyncClient, registered_client, pkce_challenge ): """Test endpoint with missing redirect_uri with multiple registered URIs. If client has multiple registered redirect_uris, redirect_uri must be provided. """ response = await test_client.get( "/authorize", params={ "response_type": "code", "client_id": registered_client["client_id"], # Missing redirect_uri "code_challenge": pkce_challenge["code_challenge"], "code_challenge_method": "S256", "state": "test_state", }, ) # Should NOT redirect, should return a 400 error assert response.status_code == 400 # The response should include an error message about missing redirect_uri assert "redirect_uri" in response.text.lower() async def test_authorize_unsupported_response_type( self, test_client: httpx.AsyncClient, registered_client, pkce_challenge ): """Test authorization endpoint with unsupported response_type. According to the OAuth2.0 spec, for other errors like unsupported_response_type, the server should redirect with error parameters. """ response = await test_client.get( "/authorize", params={ "response_type": "token", # Unsupported (we only support "code") "client_id": registered_client["client_id"], "redirect_uri": "https://client.example.com/callback", "code_challenge": pkce_challenge["code_challenge"], "code_challenge_method": "S256", "state": "test_state", }, ) # Should redirect with error parameters assert response.status_code == 302 redirect_url = response.headers["location"] parsed_url = urlparse(redirect_url) query_params = parse_qs(parsed_url.query) assert "error" in query_params assert query_params["error"][0] == "unsupported_response_type" # State should be preserved assert "state" in query_params assert query_params["state"][0] == "test_state" async def test_authorize_missing_response_type( self, test_client: httpx.AsyncClient, registered_client, pkce_challenge ): """Test authorization endpoint with missing response_type. Missing required parameter should result in invalid_request error. """ response = await test_client.get( "/authorize", params={ # Missing response_type "client_id": registered_client["client_id"], "redirect_uri": "https://client.example.com/callback", "code_challenge": pkce_challenge["code_challenge"], "code_challenge_method": "S256", "state": "test_state", }, ) # Should redirect with error parameters assert response.status_code == 302 redirect_url = response.headers["location"] parsed_url = urlparse(redirect_url) query_params = parse_qs(parsed_url.query) assert "error" in query_params assert query_params["error"][0] == "invalid_request" # State should be preserved assert "state" in query_params assert query_params["state"][0] == "test_state" async def test_authorize_missing_pkce_challenge( self, test_client: httpx.AsyncClient, registered_client ): """Test authorization endpoint with missing PKCE code_challenge. Missing PKCE parameters should result in invalid_request error. """ response = await test_client.get( "/authorize", params={ "response_type": "code", "client_id": registered_client["client_id"], # Missing code_challenge "state": "test_state", # using default URL }, ) # Should redirect with error parameters assert response.status_code == 302 redirect_url = response.headers["location"] parsed_url = urlparse(redirect_url) query_params = parse_qs(parsed_url.query) assert "error" in query_params assert query_params["error"][0] == "invalid_request" # State should be preserved assert "state" in query_params assert query_params["state"][0] == "test_state" async def test_authorize_invalid_scope( self, test_client: httpx.AsyncClient, registered_client, pkce_challenge ): """Test authorization endpoint with invalid scope. Invalid scope should redirect with invalid_scope error. """ response = await test_client.get( "/authorize", params={ "response_type": "code", "client_id": registered_client["client_id"], "redirect_uri": "https://client.example.com/callback", "code_challenge": pkce_challenge["code_challenge"], "code_challenge_method": "S256", "scope": "invalid_scope_that_does_not_exist", "state": "test_state", }, ) # Should redirect with error parameters assert response.status_code == 302 redirect_url = response.headers["location"] parsed_url = urlparse(redirect_url) query_params = parse_qs(parsed_url.query) assert "error" in query_params assert query_params["error"][0] == "invalid_scope" # State should be preserved assert "state" in query_params assert query_params["state"][0] == "test_state"
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/test_auth_integration_errors.py", "license": "Apache License 2.0", "lines": 452, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/server/test_dependencies_advanced.py
"""Advanced tests for dependency injection in FastMCP: context annotations, vendored DI, and auth dependencies.""" import inspect import mcp.types as mcp_types import pytest from fastmcp import FastMCP from fastmcp.client import Client from fastmcp.dependencies import CurrentContext from fastmcp.server.context import Context class Connection: """Test connection that tracks whether it's currently open.""" def __init__(self): self.is_open = False async def __aenter__(self): self.is_open = True return self async def __aexit__(self, exc_type, exc_val, exc_tb): self.is_open = False @pytest.fixture def mcp(): """Create a FastMCP server for testing.""" return FastMCP("test-server") class TestTransformContextAnnotations: """Tests for the transform_context_annotations function.""" async def test_optional_context_degrades_to_none_without_active_context(self): """Optional Context should resolve to None when no context is active.""" from fastmcp.server.dependencies import transform_context_annotations async def fn_with_optional_ctx(name: str, ctx: Context | None = None) -> str: return name transform_context_annotations(fn_with_optional_ctx) sig = inspect.signature(fn_with_optional_ctx) ctx_dependency = sig.parameters["ctx"].default resolved_ctx = await ctx_dependency.__aenter__() try: assert resolved_ctx is None finally: await ctx_dependency.__aexit__(None, None, None) async def test_optional_context_still_injected_in_foreground_requests( self, mcp: FastMCP ): """Optional Context should still be injected for normal MCP requests.""" @mcp.tool() async def tool_with_optional_context( name: str, ctx: Context | None = None ) -> str: if ctx is None: return f"missing:{name}" return f"present:{ctx.session_id}:{name}" async with Client(mcp) as client: result = await client.call_tool("tool_with_optional_context", {"name": "x"}) assert result.content[0].text.startswith("present:") async def test_basic_context_transformation(self, mcp: FastMCP): """Test basic Context type annotation is transformed.""" @mcp.tool() async def tool_with_context(name: str, ctx: Context) -> str: return f"session={ctx.session_id}, name={name}" async with Client(mcp) as client: result = await client.call_tool("tool_with_context", {"name": "test"}) assert "session=" in result.content[0].text assert "name=test" in result.content[0].text async def test_transform_with_var_params(self): """Test transform_context_annotations handles *args and **kwargs correctly.""" from fastmcp.server.dependencies import transform_context_annotations # This function can't be a tool (FastMCP doesn't support *args/**kwargs), # but transform should handle it gracefully for signature inspection async def fn_with_var_params( first: str, ctx: Context, *args: str, **kwargs: str ) -> str: return f"first={first}" transform_context_annotations(fn_with_var_params) sig = inspect.signature(fn_with_var_params) # Verify structure is preserved param_kinds = {p.name: p.kind for p in sig.parameters.values()} assert param_kinds["first"] == inspect.Parameter.POSITIONAL_OR_KEYWORD assert param_kinds["ctx"] == inspect.Parameter.POSITIONAL_OR_KEYWORD assert param_kinds["args"] == inspect.Parameter.VAR_POSITIONAL assert param_kinds["kwargs"] == inspect.Parameter.VAR_KEYWORD # ctx should now have a default assert sig.parameters["ctx"].default is not inspect.Parameter.empty async def test_context_keyword_only(self, mcp: FastMCP): """Test Context transformation preserves keyword-only parameter semantics.""" from fastmcp.server.dependencies import transform_context_annotations # Define function with keyword-only Context param async def fn_with_kw_only(a: str, *, ctx: Context, b: str = "default") -> str: return f"a={a}, b={b}" # Transform and check signature structure transform_context_annotations(fn_with_kw_only) sig = inspect.signature(fn_with_kw_only) params = list(sig.parameters.values()) # 'a' should be POSITIONAL_OR_KEYWORD assert params[0].name == "a" assert params[0].kind == inspect.Parameter.POSITIONAL_OR_KEYWORD # 'ctx' should still be KEYWORD_ONLY (after transformation) ctx_param = sig.parameters["ctx"] assert ctx_param.kind == inspect.Parameter.KEYWORD_ONLY # 'b' should still be KEYWORD_ONLY b_param = sig.parameters["b"] assert b_param.kind == inspect.Parameter.KEYWORD_ONLY async def test_context_with_annotated(self, mcp: FastMCP): """Test Context with Annotated type is transformed.""" from typing import Annotated @mcp.tool() async def tool_with_annotated_ctx( name: str, ctx: Annotated[Context, "custom annotation"] ) -> str: return f"session={ctx.session_id}" async with Client(mcp) as client: result = await client.call_tool("tool_with_annotated_ctx", {"name": "test"}) assert "session=" in result.content[0].text async def test_context_already_has_dependency_default(self, mcp: FastMCP): """Test that Context with existing Depends default is not re-transformed.""" @mcp.tool() async def tool_with_explicit_context( name: str, ctx: Context = CurrentContext() ) -> str: return f"session={ctx.session_id}" async with Client(mcp) as client: result = await client.call_tool( "tool_with_explicit_context", {"name": "test"} ) assert "session=" in result.content[0].text async def test_multiple_context_params(self, mcp: FastMCP): """Test multiple Context-typed parameters are all transformed.""" @mcp.tool() async def tool_with_multiple_ctx( name: str, ctx1: Context, ctx2: Context ) -> str: # Both should refer to same context assert ctx1.session_id == ctx2.session_id return f"same={ctx1 is ctx2}" # Both ctx params should be excluded from schema result = await mcp._list_tools_mcp(mcp_types.ListToolsRequest()) tool = next(t for t in result.tools if t.name == "tool_with_multiple_ctx") assert "name" in tool.inputSchema["properties"] assert "ctx1" not in tool.inputSchema["properties"] assert "ctx2" not in tool.inputSchema["properties"] async def test_context_in_class_method(self, mcp: FastMCP): """Test Context transformation works with bound methods.""" class MyTools: def __init__(self, prefix: str): self.prefix = prefix async def greet(self, name: str, ctx: Context) -> str: return f"{self.prefix} {name}, session={ctx.session_id}" tools = MyTools("Hello") mcp.tool()(tools.greet) async with Client(mcp) as client: result = await client.call_tool("greet", {"name": "World"}) assert "Hello World" in result.content[0].text assert "session=" in result.content[0].text async def test_context_in_static_method(self, mcp: FastMCP): """Test Context transformation works with static methods.""" class MyTools: @staticmethod async def static_tool(name: str, ctx: Context) -> str: return f"name={name}, session={ctx.session_id}" mcp.tool()(MyTools.static_tool) async with Client(mcp) as client: result = await client.call_tool("static_tool", {"name": "test"}) assert "name=test" in result.content[0].text assert "session=" in result.content[0].text async def test_context_in_callable_class(self, mcp: FastMCP): """Test Context transformation works with callable class instances.""" from fastmcp.tools import Tool class CallableTool: def __init__(self, multiplier: int): self.multiplier = multiplier async def __call__(self, x: int, ctx: Context) -> str: return f"result={x * self.multiplier}, session={ctx.session_id}" # Use Tool.from_function directly (mcp.tool() decorator doesn't support callable instances) tool = Tool.from_function(CallableTool(3)) mcp.add_tool(tool) async with Client(mcp) as client: result = await client.call_tool("CallableTool", {"x": 5}) assert "result=15" in result.content[0].text assert "session=" in result.content[0].text async def test_context_param_reordering(self, mcp: FastMCP): """Test that Context params are reordered correctly to maintain valid signature.""" from fastmcp.server.dependencies import transform_context_annotations # Context in middle without default - should be moved after non-default params async def fn_with_middle_ctx(a: str, ctx: Context, b: str) -> str: return f"{a},{b}" transform_context_annotations(fn_with_middle_ctx) sig = inspect.signature(fn_with_middle_ctx) params = list(sig.parameters.values()) # After transform: a, b should come before ctx (which now has default) param_names = [p.name for p in params] assert param_names == ["a", "b", "ctx"] # ctx should have a default now assert sig.parameters["ctx"].default is not inspect.Parameter.empty async def test_context_resource(self, mcp: FastMCP): """Test Context transformation works with resources.""" @mcp.resource("data://test") async def resource_with_ctx(ctx: Context) -> str: return f"session={ctx.session_id}" async with Client(mcp) as client: result = await client.read_resource("data://test") assert len(result) == 1 assert "session=" in result[0].text async def test_context_resource_template(self, mcp: FastMCP): """Test Context transformation works with resource templates.""" @mcp.resource("item://{item_id}") async def template_with_ctx(item_id: str, ctx: Context) -> str: return f"item={item_id}, session={ctx.session_id}" async with Client(mcp) as client: result = await client.read_resource("item://123") assert len(result) == 1 assert "item=123" in result[0].text assert "session=" in result[0].text async def test_context_prompt(self, mcp: FastMCP): """Test Context transformation works with prompts.""" @mcp.prompt() async def prompt_with_ctx(topic: str, ctx: Context) -> str: return f"Write about {topic} (session: {ctx.session_id})" async with Client(mcp) as client: result = await client.get_prompt("prompt_with_ctx", {"topic": "AI"}) assert "Write about AI" in result.messages[0].content.text assert "session:" in result.messages[0].content.text
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/test_dependencies_advanced.py", "license": "Apache License 2.0", "lines": 216, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/utilities/openapi/test_circular_references.py
"""Tests for circular and self-referential schema serialization (Issues #1016, #1206, #3242).""" import httpx from fastmcp import FastMCP from fastmcp.utilities.openapi.models import ( ResponseInfo, ) from fastmcp.utilities.openapi.schemas import ( _replace_ref_with_defs, extract_output_schema_from_responses, ) class TestCircularReferencesSerialization: """Tests for circular/self-referential schemas surviving MCP serialization. Issues: #1016, #1206, #3242 The crash occurs when Pydantic's model_dump() encounters the same Python dict object at multiple positions in the serialization tree. This happens because _replace_ref_with_defs mutates shared list objects (anyOf/allOf/oneOf) in place via shallow copy, causing different tools to share internal dict references. """ def test_replace_ref_with_defs_does_not_mutate_input(self): """_replace_ref_with_defs must not mutate its input dict's lists.""" schema = { "oneOf": [ {"$ref": "#/components/schemas/Cat"}, {"$ref": "#/components/schemas/Dog"}, ] } original_list = schema["oneOf"] original_items = list(original_list) # snapshot _replace_ref_with_defs(schema) # The original list object must not have been mutated assert original_list is schema["oneOf"] assert original_list == original_items def test_replace_ref_with_defs_produces_independent_results(self): """Calling _replace_ref_with_defs twice on the same input must produce independent dict trees with no shared mutable objects.""" schema = { "type": "object", "properties": { "pet": { "oneOf": [ {"$ref": "#/components/schemas/Cat"}, {"$ref": "#/components/schemas/Dog"}, ] } }, } result1 = _replace_ref_with_defs(schema) result2 = _replace_ref_with_defs(schema) # The oneOf lists should be different objects list1 = result1["properties"]["pet"]["oneOf"] list2 = result2["properties"]["pet"]["oneOf"] assert list1 is not list2 # Items within the lists should also be independent assert list1[0] is not list2[0] def test_circular_output_schema_serialization(self): """Output schemas with self-referential types must survive model_dump(). This is the exact crash from issue #3242: Pydantic raises ValueError('Circular reference detected (id repeated)') when serializing MCP Tool objects whose schemas share Python dict references. """ responses = { "200": ResponseInfo( description="A tree node", content_schema={ "application/json": {"$ref": "#/components/schemas/Node"} }, ) } schema_definitions = { "Node": { "type": "object", "properties": { "value": {"type": "string"}, "children": { "type": "array", "items": {"$ref": "#/components/schemas/Node"}, }, }, }, } output_schema = extract_output_schema_from_responses( responses, schema_definitions=schema_definitions, openapi_version="3.0.0" ) assert output_schema is not None # Build an MCP Tool with this schema and try to serialize it — # this is the exact path that crashes in the reported issue. from mcp.types import Tool as MCPTool tool = MCPTool( name="get_node", description="Get a node", inputSchema={"type": "object", "properties": {}}, outputSchema=output_schema, ) # This must not raise ValueError: Circular reference detected tool.model_dump(by_alias=True, mode="json", exclude_none=True) def test_mutual_circular_references_serialization(self): """Mutually circular schemas (A→B→A) must survive serialization.""" responses = { "200": ResponseInfo( description="A pull request", content_schema={ "application/json": {"$ref": "#/components/schemas/PullRequest"} }, ) } schema_definitions = { "PullRequest": { "type": "object", "properties": { "title": {"type": "string"}, "author": {"$ref": "#/components/schemas/User"}, }, }, "User": { "type": "object", "properties": { "name": {"type": "string"}, "pull_requests": { "type": "array", "items": {"$ref": "#/components/schemas/PullRequest"}, }, }, }, } output_schema = extract_output_schema_from_responses( responses, schema_definitions=schema_definitions, openapi_version="3.0.0" ) assert output_schema is not None from mcp.types import Tool as MCPTool tool = MCPTool( name="get_pr", description="Get a pull request", inputSchema={"type": "object", "properties": {}}, outputSchema=output_schema, ) tool.model_dump(by_alias=True, mode="json", exclude_none=True) async def test_multiple_tools_sharing_circular_schemas(self): """Multiple tools from the same spec must not share Python dict objects in their schemas, which would cause Pydantic to raise circular reference errors when serializing the list_tools response.""" spec = { "openapi": "3.0.0", "info": {"title": "Test API", "version": "1.0.0"}, "paths": { "/nodes": { "get": { "operationId": "list_nodes", "responses": { "200": { "description": "List of nodes", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Node" }, } } }, } }, }, "post": { "operationId": "create_node", "requestBody": { "required": True, "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Node"} } }, }, "responses": { "201": { "description": "Created node", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Node"} } }, } }, }, }, "/nodes/{id}": { "get": { "operationId": "get_node", "parameters": [ { "name": "id", "in": "path", "required": True, "schema": {"type": "string"}, } ], "responses": { "200": { "description": "A node", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Node"} } }, } }, }, }, }, "components": { "schemas": { "Node": { "type": "object", "properties": { "value": {"type": "string"}, "children": { "type": "array", "items": {"$ref": "#/components/schemas/Node"}, }, }, } } }, } server = FastMCP.from_openapi(spec, httpx.AsyncClient()) tools = await server.list_tools() assert len(tools) >= 3 # Simulate what the MCP SDK does: serialize all tools together. # This is the exact crash path — model_dump on a list of tools # whose schemas share Python dict objects. mcp_tools = [tool.to_mcp_tool(name=tool.name) for tool in tools] for mcp_tool in mcp_tools: mcp_tool.model_dump(by_alias=True, mode="json", exclude_none=True)
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/utilities/openapi/test_circular_references.py", "license": "Apache License 2.0", "lines": 234, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/utilities/test_inspect_icons.py
"""Tests for icon extraction and formatting functions in inspect.py.""" import importlib.metadata from mcp.server.fastmcp import FastMCP as FastMCP1x import fastmcp from fastmcp import FastMCP from fastmcp.utilities.inspect import ( InspectFormat, format_fastmcp_info, format_info, format_mcp_info, inspect_fastmcp, inspect_fastmcp_v1, ) class TestIconExtraction: """Tests for icon extraction in inspect.""" async def test_server_icons_and_website(self): """Test that server-level icons and website_url are extracted.""" from mcp.types import Icon mcp = FastMCP( "IconServer", website_url="https://example.com", icons=[ Icon( src="https://example.com/icon.png", mimeType="image/png", sizes=["48x48"], ) ], ) info = await inspect_fastmcp(mcp) assert info.website_url == "https://example.com" assert info.icons is not None assert len(info.icons) == 1 assert info.icons[0]["src"] == "https://example.com/icon.png" assert info.icons[0]["mimeType"] == "image/png" assert info.icons[0]["sizes"] == ["48x48"] async def test_server_without_icons(self): """Test that servers without icons have None for icons and website_url.""" mcp = FastMCP("NoIconServer") info = await inspect_fastmcp(mcp) assert info.website_url is None assert info.icons is None async def test_tool_icons(self): """Test that tool icons are extracted.""" from mcp.types import Icon mcp = FastMCP("ToolIconServer") @mcp.tool( icons=[ Icon( src="https://example.com/calculator.png", mimeType="image/png", ) ] ) def calculate(x: int) -> int: """Calculate something.""" return x * 2 @mcp.tool def no_icon_tool() -> str: """Tool without icon.""" return "no icon" info = await inspect_fastmcp(mcp) assert len(info.tools) == 2 # Find the calculate tool calculate_tool = next(t for t in info.tools if t.name == "calculate") assert calculate_tool.icons is not None assert len(calculate_tool.icons) == 1 assert calculate_tool.icons[0]["src"] == "https://example.com/calculator.png" # Find the no_icon tool no_icon = next(t for t in info.tools if t.name == "no_icon_tool") assert no_icon.icons is None async def test_resource_icons(self): """Test that resource icons are extracted.""" from mcp.types import Icon mcp = FastMCP("ResourceIconServer") @mcp.resource( "resource://data", icons=[Icon(src="https://example.com/data.png", mimeType="image/png")], ) def get_data() -> str: """Get data.""" return "data" @mcp.resource("resource://no-icon") def get_no_icon() -> str: """Get data without icon.""" return "no icon" info = await inspect_fastmcp(mcp) assert len(info.resources) == 2 # Find the data resource data_resource = next(r for r in info.resources if r.uri == "resource://data") assert data_resource.icons is not None assert len(data_resource.icons) == 1 assert data_resource.icons[0]["src"] == "https://example.com/data.png" # Find the no-icon resource no_icon = next(r for r in info.resources if r.uri == "resource://no-icon") assert no_icon.icons is None async def test_template_icons(self): """Test that resource template icons are extracted.""" from mcp.types import Icon mcp = FastMCP("TemplateIconServer") @mcp.resource( "resource://user/{id}", icons=[Icon(src="https://example.com/user.png", mimeType="image/png")], ) def get_user(id: str) -> str: """Get user by ID.""" return f"user {id}" @mcp.resource("resource://item/{id}") def get_item(id: str) -> str: """Get item without icon.""" return f"item {id}" info = await inspect_fastmcp(mcp) assert len(info.templates) == 2 # Find the user template user_template = next( t for t in info.templates if t.uri_template == "resource://user/{id}" ) assert user_template.icons is not None assert len(user_template.icons) == 1 assert user_template.icons[0]["src"] == "https://example.com/user.png" # Find the no-icon template no_icon = next( t for t in info.templates if t.uri_template == "resource://item/{id}" ) assert no_icon.icons is None async def test_prompt_icons(self): """Test that prompt icons are extracted.""" from mcp.types import Icon mcp = FastMCP("PromptIconServer") @mcp.prompt( icons=[Icon(src="https://example.com/analyze.png", mimeType="image/png")] ) def analyze(data: str) -> list: """Analyze data.""" return [{"role": "user", "content": f"Analyze: {data}"}] @mcp.prompt def no_icon_prompt(text: str) -> list: """Prompt without icon.""" return [{"role": "user", "content": text}] info = await inspect_fastmcp(mcp) assert len(info.prompts) == 2 # Find the analyze prompt analyze_prompt = next(p for p in info.prompts if p.name == "analyze") assert analyze_prompt.icons is not None assert len(analyze_prompt.icons) == 1 assert analyze_prompt.icons[0]["src"] == "https://example.com/analyze.png" # Find the no-icon prompt no_icon = next(p for p in info.prompts if p.name == "no_icon_prompt") assert no_icon.icons is None async def test_multiple_icons(self): """Test that components with multiple icons extract all of them.""" from mcp.types import Icon mcp = FastMCP( "MultiIconServer", icons=[ Icon( src="https://example.com/icon-48.png", mimeType="image/png", sizes=["48x48"], ), Icon( src="https://example.com/icon-96.png", mimeType="image/png", sizes=["96x96"], ), ], ) @mcp.tool( icons=[ Icon(src="https://example.com/tool-small.png", sizes=["24x24"]), Icon(src="https://example.com/tool-large.png", sizes=["48x48"]), ] ) def multi_icon_tool() -> str: """Tool with multiple icons.""" return "multi" info = await inspect_fastmcp(mcp) # Check server icons assert info.icons is not None assert len(info.icons) == 2 assert info.icons[0]["sizes"] == ["48x48"] assert info.icons[1]["sizes"] == ["96x96"] # Check tool icons assert len(info.tools) == 1 assert info.tools[0].icons is not None assert len(info.tools[0].icons) == 2 assert info.tools[0].icons[0]["sizes"] == ["24x24"] assert info.tools[0].icons[1]["sizes"] == ["48x48"] async def test_data_uri_icons(self): """Test that data URI icons are extracted correctly.""" from mcp.types import Icon data_uri = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==" mcp = FastMCP("DataURIServer") @mcp.tool(icons=[Icon(src=data_uri, mimeType="image/png")]) def data_uri_tool() -> str: """Tool with data URI icon.""" return "data" info = await inspect_fastmcp(mcp) assert len(info.tools) == 1 assert info.tools[0].icons is not None assert info.tools[0].icons[0]["src"] == data_uri assert info.tools[0].icons[0]["mimeType"] == "image/png" async def test_icons_in_fastmcp_v1(self): """Test that icons are extracted from FastMCP 1.x servers.""" from mcp.types import Icon mcp = FastMCP1x("Icon1xServer") @mcp.tool( icons=[Icon(src="https://example.com/v1-tool.png", mimeType="image/png")] ) def v1_tool() -> str: """Tool in v1 server.""" return "v1" info = await inspect_fastmcp_v1(mcp) assert len(info.tools) == 1 # v1 servers should also extract icons if present if info.tools[0].icons is not None: assert info.tools[0].icons[0]["src"] == "https://example.com/v1-tool.png" async def test_icons_in_formatted_output(self): """Test that icons appear in formatted JSON output.""" from mcp.types import Icon mcp = FastMCP( "FormattedIconServer", website_url="https://example.com", icons=[Icon(src="https://example.com/server.png", mimeType="image/png")], ) @mcp.tool( icons=[Icon(src="https://example.com/tool.png", mimeType="image/png")] ) def icon_tool() -> str: """Tool with icon.""" return "icon" info = await inspect_fastmcp(mcp) json_bytes = format_fastmcp_info(info) import json data = json.loads(json_bytes) # Check server icons in formatted output assert data["server"]["website_url"] == "https://example.com" assert data["server"]["icons"] is not None assert len(data["server"]["icons"]) == 1 assert data["server"]["icons"][0]["src"] == "https://example.com/server.png" # Check tool icons in formatted output assert len(data["tools"]) == 1 assert data["tools"][0]["icons"] is not None assert len(data["tools"][0]["icons"]) == 1 assert data["tools"][0]["icons"][0]["src"] == "https://example.com/tool.png" async def test_icons_always_present_in_json(self): """Test that icons and website_url fields are always present in JSON, even when None.""" mcp = FastMCP("AlwaysPresentServer") @mcp.tool def no_icon() -> str: """Tool without icon.""" return "none" info = await inspect_fastmcp(mcp) json_bytes = format_fastmcp_info(info) import json data = json.loads(json_bytes) # Fields should always be present, even when None assert "website_url" in data["server"] assert "icons" in data["server"] assert data["server"]["website_url"] is None assert data["server"]["icons"] is None assert len(data["tools"]) == 1 assert "icons" in data["tools"][0] assert data["tools"][0]["icons"] is None class TestFormatFunctions: """Tests for the formatting functions.""" async def test_format_fastmcp_info(self): """Test formatting as FastMCP-specific JSON.""" mcp = FastMCP("TestServer", instructions="Test instructions", version="1.2.3") @mcp.tool def test_tool(x: int) -> dict: """A test tool.""" return {"result": x * 2} info = await inspect_fastmcp(mcp) json_bytes = format_fastmcp_info(info) # Verify it's valid JSON import json data = json.loads(json_bytes) # Check FastMCP-specific fields are present assert "server" in data assert data["server"]["name"] == "TestServer" assert data["server"]["instructions"] == "Test instructions" assert data["server"]["generation"] == 2 # v2 server assert data["server"]["version"] == "1.2.3" assert "capabilities" in data["server"] # Check environment information assert "environment" in data assert data["environment"]["fastmcp"] == fastmcp.__version__ assert data["environment"]["mcp"] == importlib.metadata.version("mcp") # Check tools assert len(data["tools"]) == 1 assert data["tools"][0]["name"] == "test_tool" assert "tags" in data["tools"][0] async def test_format_mcp_info(self): """Test formatting as MCP protocol JSON.""" mcp = FastMCP("TestServer", instructions="Test instructions", version="2.0.0") @mcp.tool def add(a: int, b: int) -> int: """Add two numbers.""" return a + b @mcp.prompt def test_prompt(name: str) -> list: """Test prompt.""" return [{"role": "user", "content": f"Hello {name}"}] json_bytes = await format_mcp_info(mcp) # Verify it's valid JSON import json data = json.loads(json_bytes) # Check MCP protocol structure with camelCase assert "serverInfo" in data assert data["serverInfo"]["name"] == "TestServer" # Check server version in MCP format assert data["serverInfo"]["version"] == "2.0.0" # MCP format SHOULD have environment fields assert "environment" in data assert data["environment"]["fastmcp"] == fastmcp.__version__ assert data["environment"]["mcp"] == importlib.metadata.version("mcp") assert "capabilities" in data assert "tools" in data assert "prompts" in data assert "resources" in data assert "resourceTemplates" in data # Check tools have MCP format (camelCase fields) assert len(data["tools"]) == 1 assert data["tools"][0]["name"] == "add" assert "inputSchema" in data["tools"][0] # FastMCP-specific fields should not be present assert "tags" not in data["tools"][0] assert "enabled" not in data["tools"][0] async def test_format_info_with_fastmcp_format(self): """Test format_info with fastmcp format.""" mcp = FastMCP("TestServer") @mcp.tool def test() -> str: return "test" # Test with string format json_bytes = await format_info(mcp, "fastmcp") import json data = json.loads(json_bytes) assert data["server"]["name"] == "TestServer" assert "tags" in data["tools"][0] # FastMCP-specific field # Test with enum format json_bytes = await format_info(mcp, InspectFormat.FASTMCP) data = json.loads(json_bytes) assert data["server"]["name"] == "TestServer" async def test_format_info_with_mcp_format(self): """Test format_info with mcp format.""" mcp = FastMCP("TestServer") @mcp.tool def test() -> str: return "test" json_bytes = await format_info(mcp, "mcp") import json data = json.loads(json_bytes) assert "serverInfo" in data assert "tools" in data assert "inputSchema" in data["tools"][0] # MCP uses camelCase async def test_format_info_requires_format(self): """Test that format_info requires a format parameter.""" mcp = FastMCP("TestServer") @mcp.tool def test() -> str: return "test" # Should work with valid formats json_bytes = await format_info(mcp, "fastmcp") assert json_bytes json_bytes = await format_info(mcp, "mcp") assert json_bytes # Should fail with invalid format import pytest with pytest.raises(ValueError, match="not a valid InspectFormat"): await format_info(mcp, "invalid") # type: ignore async def test_tool_with_output_schema(self): """Test that output_schema is properly extracted and included.""" mcp = FastMCP("TestServer") @mcp.tool( output_schema={ "type": "object", "properties": { "result": {"type": "number"}, "message": {"type": "string"}, }, } ) def compute(x: int) -> dict: """Compute something.""" return {"result": x * 2, "message": f"Doubled {x}"} info = await inspect_fastmcp(mcp) # Check output_schema is captured assert len(info.tools) == 1 assert info.tools[0].output_schema is not None assert info.tools[0].output_schema["type"] == "object" assert "result" in info.tools[0].output_schema["properties"] # Verify it's included in FastMCP format json_bytes = format_fastmcp_info(info) import json data = json.loads(json_bytes) # Tools are at the top level, not nested assert data["tools"][0]["output_schema"]["type"] == "object"
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/utilities/test_inspect_icons.py", "license": "Apache License 2.0", "lines": 399, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:examples/apps/chart_server.py
"""Chart MCP App — interactive data visualizations with Prefab. Demonstrates `fastmcp[apps]` with Prefab chart components: - `BarChart` and `LineChart` for categorical and trend data - Multiple series, stacking, and curve styles - Layout composition with `Column`, `Heading`, and `Muted` - Custom text fallback via `ToolResult` Usage: uv run python chart_server.py # HTTP (port 8000) uv run python chart_server.py --stdio # stdio for MCP clients """ from __future__ import annotations from prefab_ui.app import PrefabApp from prefab_ui.components import ( BarChart, ChartSeries, Column, Heading, LineChart, Muted, ) from fastmcp import FastMCP mcp = FastMCP("Sales Dashboard") MONTHLY_SALES = [ {"month": "Jan", "online": 4200, "retail": 2400}, {"month": "Feb", "online": 3800, "retail": 2100}, {"month": "Mar", "online": 5100, "retail": 2800}, {"month": "Apr", "online": 4600, "retail": 3200}, {"month": "May", "online": 5800, "retail": 3100}, {"month": "Jun", "online": 6200, "retail": 3500}, ] @mcp.tool(app=True) def sales_overview(stacked: bool = False) -> PrefabApp: """View monthly sales broken down by channel. Args: stacked: Stack bars to show total revenue per month. """ total = sum(row["online"] + row["retail"] for row in MONTHLY_SALES) with Column(gap=6, css_class="p-6") as view: with Column(gap=1): Heading("Monthly Sales") Muted(f"${total:,} total revenue") BarChart( data=MONTHLY_SALES, series=[ ChartSeries(data_key="online", label="Online"), ChartSeries(data_key="retail", label="Retail"), ], x_axis="month", stacked=stacked, show_legend=True, ) return PrefabApp( title="Sales Dashboard", view=view, ) @mcp.tool(app=True) def sales_trend(curve: str = "linear") -> PrefabApp: """View sales trends over time as a line chart. Args: curve: Line style — "linear", "smooth", or "step". """ with Column(gap=6, css_class="p-6") as view: with Column(gap=1): Heading("Sales Trend") Muted("Online vs. retail over 6 months") LineChart( data=MONTHLY_SALES, series=[ ChartSeries(data_key="online", label="Online"), ChartSeries(data_key="retail", label="Retail"), ], x_axis="month", curve=curve, show_dots=True, show_legend=True, ) return PrefabApp( title="Sales Trend", view=view, ) if __name__ == "__main__": mcp.run()
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/apps/chart_server.py", "license": "Apache License 2.0", "lines": 82, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
PrefectHQ/fastmcp:examples/apps/datatable_server.py
"""DataTable MCP App — interactive, sortable data views with Prefab. Demonstrates `fastmcp[apps]` with Prefab UI components: - `app=True` for automatic renderer wiring - `PrefabApp` with `DataTable` for rich tabular views - Searchable, sortable, paginated tables - Layout composition with `Column`, `Heading`, `Text`, and `Badge` Usage: uv run python datatable_server.py # HTTP (port 8000) uv run python datatable_server.py --stdio # stdio for MCP clients """ from __future__ import annotations from prefab_ui.app import PrefabApp from prefab_ui.components import ( Badge, Column, DataTable, DataTableColumn, Heading, Muted, Row, ) from fastmcp import FastMCP mcp = FastMCP("Team Directory") EMPLOYEES = [ { "name": "Alice Chen", "role": "Engineering", "level": "Senior", "location": "San Francisco", "status": "active", }, { "name": "Bob Martinez", "role": "Design", "level": "Lead", "location": "New York", "status": "active", }, { "name": "Carol Johnson", "role": "Engineering", "level": "Staff", "location": "London", "status": "active", }, { "name": "David Kim", "role": "Product", "level": "Senior", "location": "San Francisco", "status": "away", }, { "name": "Eva Müller", "role": "Engineering", "level": "Mid", "location": "Berlin", "status": "active", }, { "name": "Frank Okafor", "role": "Data Science", "level": "Senior", "location": "Lagos", "status": "active", }, { "name": "Grace Liu", "role": "Engineering", "level": "Junior", "location": "Singapore", "status": "active", }, { "name": "Hassan Ali", "role": "Design", "level": "Senior", "location": "Dubai", "status": "away", }, { "name": "Iris Tanaka", "role": "Product", "level": "Lead", "location": "Tokyo", "status": "active", }, { "name": "James Wright", "role": "Engineering", "level": "Senior", "location": "London", "status": "inactive", }, { "name": "Karen Petrov", "role": "Data Science", "level": "Lead", "location": "Berlin", "status": "active", }, { "name": "Liam O'Brien", "role": "Engineering", "level": "Mid", "location": "Dublin", "status": "active", }, ] @mcp.tool(app=True) def list_team(department: str | None = None) -> PrefabApp: """Browse the team directory with sorting and search. Args: department: Filter by department (e.g. "Engineering", "Design"). Leave empty to show everyone. """ if department: rows = [e for e in EMPLOYEES if e["role"].lower() == department.lower()] else: rows = EMPLOYEES active = sum(1 for e in rows if e["status"] == "active") with Column(gap=6, css_class="p-6") as view: with Column(gap=1): Heading("Team Directory") with Row(gap=2): Muted(f"{len(rows)} members") Muted(f"{active} active", css_class="text-success") if department: Badge(department, variant="outline") DataTable( columns=[ DataTableColumn(key="name", header="Name", sortable=True), DataTableColumn(key="role", header="Department", sortable=True), DataTableColumn(key="level", header="Level", sortable=True), DataTableColumn(key="location", header="Location", sortable=True), DataTableColumn(key="status", header="Status", sortable=True), ], rows=rows, searchable=True, paginated=True, page_size=10, ) return PrefabApp( title="Team Directory", view=view, state={"total": len(rows), "active": active}, ) if __name__ == "__main__": mcp.run()
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/apps/datatable_server.py", "license": "Apache License 2.0", "lines": 149, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:examples/apps/patterns_server.py
"""Patterns showcase — every Prefab pattern from the docs in one server. A runnable collection of the patterns from https://gofastmcp.com/apps/patterns. Each tool demonstrates a different Prefab UI pattern: charts, tables, forms, status displays, conditional content, tabs, and accordions. Usage: uv run python patterns_server.py # HTTP (port 8000) uv run python patterns_server.py --stdio # stdio for MCP clients """ from __future__ import annotations from prefab_ui.actions import ShowToast from prefab_ui.actions.mcp import CallTool from prefab_ui.app import PrefabApp from prefab_ui.components import ( Accordion, AccordionItem, Alert, AreaChart, Badge, BarChart, Button, Card, CardContent, ChartSeries, Column, DataTable, DataTableColumn, ForEach, Form, Grid, Heading, If, Input, Muted, PieChart, Progress, Row, Select, Separator, Switch, Tab, Tabs, Text, Textarea, ) from fastmcp import FastMCP mcp = FastMCP("Patterns Showcase") # --------------------------------------------------------------------------- # Data # --------------------------------------------------------------------------- QUARTERLY_DATA = [ {"quarter": "Q1", "revenue": 42000, "costs": 28000}, {"quarter": "Q2", "revenue": 51000, "costs": 31000}, {"quarter": "Q3", "revenue": 47000, "costs": 29000}, {"quarter": "Q4", "revenue": 63000, "costs": 35000}, ] DAILY_USAGE = [ {"date": f"Feb {d}", "requests": v} for d, v in zip( range(1, 11), [1200, 1350, 980, 1500, 1420, 1680, 1550, 1700, 1450, 1600], ) ] TICKETS = [ {"category": "Bug", "count": 23}, {"category": "Feature", "count": 15}, {"category": "Docs", "count": 8}, {"category": "Infra", "count": 12}, ] EMPLOYEES = [ { "name": "Alice Chen", "department": "Engineering", "role": "Staff Engineer", "location": "San Francisco", }, { "name": "Bob Martinez", "department": "Design", "role": "Lead Designer", "location": "New York", }, { "name": "Carol Johnson", "department": "Engineering", "role": "Senior Engineer", "location": "London", }, { "name": "David Kim", "department": "Product", "role": "Product Manager", "location": "San Francisco", }, { "name": "Eva Müller", "department": "Engineering", "role": "Engineer", "location": "Berlin", }, { "name": "Frank Okafor", "department": "Data Science", "role": "Senior Analyst", "location": "Lagos", }, { "name": "Grace Liu", "department": "Engineering", "role": "Junior Engineer", "location": "Singapore", }, { "name": "Hassan Ali", "department": "Design", "role": "Senior Designer", "location": "Dubai", }, ] SERVICES = [ { "name": "API Gateway", "status": "healthy", "ok": True, "latency_ms": 12, "uptime_pct": 99.9, }, { "name": "Database", "status": "healthy", "ok": True, "latency_ms": 3, "uptime_pct": 99.99, }, { "name": "Cache", "status": "degraded", "ok": False, "latency_ms": 45, "uptime_pct": 98.2, }, { "name": "Queue", "status": "healthy", "ok": True, "latency_ms": 8, "uptime_pct": 99.8, }, ] ENDPOINTS = [ { "path": "/api/users", "status": 200, "healthy": True, "avg_ms": 45, "p99_ms": 120, "uptime_pct": 99.9, }, { "path": "/api/orders", "status": 200, "healthy": True, "avg_ms": 82, "p99_ms": 250, "uptime_pct": 99.7, }, { "path": "/api/search", "status": 200, "healthy": True, "avg_ms": 150, "p99_ms": 500, "uptime_pct": 99.5, }, { "path": "/api/webhooks", "status": 503, "healthy": False, "avg_ms": 2000, "p99_ms": 5000, "uptime_pct": 95.1, }, ] PROJECT = { "name": "FastMCP v3", "description": "Next generation MCP framework with Apps support.", "status": "Active", "created_at": "2025-01-15", "members": [ {"name": "Alice Chen", "role": "Lead"}, {"name": "Bob Martinez", "role": "Design"}, {"name": "Carol Johnson", "role": "Backend"}, ], "activity": [ { "timestamp": "2 hours ago", "message": "Merged PR #342: Add Prefab UI integration", }, { "timestamp": "5 hours ago", "message": "Opened issue #345: CORS convenience API", }, {"timestamp": "1 day ago", "message": "Released v3.0.1"}, ], } # In-memory contact store for the form demo _contacts: list[dict] = [ {"name": "Zaphod Beeblebrox", "email": "zaphod@galaxy.gov", "category": "Partner"}, ] # --------------------------------------------------------------------------- # Charts # --------------------------------------------------------------------------- @mcp.tool(app=True) def quarterly_revenue(year: int = 2025) -> PrefabApp: """Show quarterly revenue as a bar chart.""" with Column(gap=4, css_class="p-6") as view: Heading(f"{year} Revenue vs Costs") BarChart( data=QUARTERLY_DATA, series=[ ChartSeries(data_key="revenue", label="Revenue"), ChartSeries(data_key="costs", label="Costs"), ], x_axis="quarter", show_legend=True, ) return PrefabApp(view=view) @mcp.tool(app=True) def usage_trend() -> PrefabApp: """Show API usage over time as an area chart.""" with Column(gap=4, css_class="p-6") as view: Heading("API Usage (10 Days)") AreaChart( data=DAILY_USAGE, series=[ChartSeries(data_key="requests", label="Requests")], x_axis="date", curve="smooth", height=250, ) return PrefabApp(view=view) @mcp.tool(app=True) def ticket_breakdown() -> PrefabApp: """Show open tickets by category as a donut chart.""" with Column(gap=4, css_class="p-6") as view: Heading("Open Tickets") PieChart( data=TICKETS, data_key="count", name_key="category", show_legend=True, inner_radius=60, ) return PrefabApp(view=view) # --------------------------------------------------------------------------- # Data Tables # --------------------------------------------------------------------------- @mcp.tool(app=True) def employee_directory() -> PrefabApp: """Show a searchable, sortable employee directory.""" with Column(gap=4, css_class="p-6") as view: Heading("Employee Directory") DataTable( columns=[ DataTableColumn(key="name", header="Name", sortable=True), DataTableColumn(key="department", header="Department", sortable=True), DataTableColumn(key="role", header="Role"), DataTableColumn(key="location", header="Office", sortable=True), ], rows=EMPLOYEES, searchable=True, paginated=True, page_size=15, ) return PrefabApp(view=view) # --------------------------------------------------------------------------- # Forms # --------------------------------------------------------------------------- @mcp.tool(app=True) def contact_form() -> PrefabApp: """Show a form to create a new contact, with a live contact list below.""" with Column(gap=6, css_class="p-6") as view: Heading("Contacts") with ForEach("contacts"): with Row(gap=2, align="center"): Text("{{ name }}", css_class="font-medium") Muted("{{ email }}") Badge("{{ category }}") Separator() Heading("Add Contact", level=3) with Form( on_submit=CallTool( "save_contact", result_key="contacts", on_success=ShowToast("Contact saved!", variant="success"), on_error=ShowToast("{{ $error }}", variant="error"), ) ): Input(name="name", label="Full Name", required=True) Input(name="email", label="Email", input_type="email", required=True) Select( name="category", label="Category", options=["Customer", "Vendor", "Partner", "Other"], ) Textarea(name="notes", label="Notes", placeholder="Optional notes...") Button("Save Contact") return PrefabApp(view=view, state={"contacts": list(_contacts)}) @mcp.tool def save_contact( name: str, email: str, category: str = "Other", notes: str = "", ) -> list[dict]: """Save a new contact and return the updated list.""" contact = {"name": name, "email": email, "category": category, "notes": notes} _contacts.append(contact) return list(_contacts) # --------------------------------------------------------------------------- # Status Displays # --------------------------------------------------------------------------- @mcp.tool(app=True) def system_status() -> PrefabApp: """Show current system health.""" all_ok = all(s["ok"] for s in SERVICES) with Column(gap=4, css_class="p-6") as view: with Row(gap=2, align="center"): Heading("System Status") Badge( "All Healthy" if all_ok else "Degraded", variant="success" if all_ok else "destructive", ) Separator() with Grid(columns=2, gap=4): for svc in SERVICES: with Card(): with CardContent(): with Row(gap=2, align="center"): Text(svc["name"], css_class="font-medium") Badge( svc["status"], variant="success" if svc["ok"] else "destructive", ) Muted(f"Response: {svc['latency_ms']}ms") Progress(value=svc["uptime_pct"]) return PrefabApp(view=view) # --------------------------------------------------------------------------- # Conditional Content # --------------------------------------------------------------------------- @mcp.tool(app=True) def feature_flags() -> PrefabApp: """Toggle feature flags with live preview.""" with Column(gap=4, css_class="p-6") as view: Heading("Feature Flags") Switch(name="dark_mode", label="Dark Mode") Switch(name="beta_features", label="Beta Features") Separator() with If("{{ dark_mode }}"): Alert(title="Dark mode enabled", description="UI will use dark theme.") with If("{{ beta_features }}"): Alert( title="Beta features active", description="Experimental features are now visible.", variant="warning", ) return PrefabApp(view=view, state={"dark_mode": False, "beta_features": False}) # --------------------------------------------------------------------------- # Tabs # --------------------------------------------------------------------------- @mcp.tool(app=True) def project_overview() -> PrefabApp: """Show project details organized in tabs.""" with Column(gap=4, css_class="p-6") as view: Heading(PROJECT["name"]) with Tabs(): with Tab("Overview"): Text(PROJECT["description"]) with Row(gap=4): Badge(PROJECT["status"]) Muted(f"Created: {PROJECT['created_at']}") with Tab("Members"): DataTable( columns=[ DataTableColumn(key="name", header="Name", sortable=True), DataTableColumn(key="role", header="Role"), ], rows=PROJECT["members"], ) with Tab("Activity"): with ForEach("activity"): with Row(gap=2): Muted("{{ timestamp }}") Text("{{ message }}") return PrefabApp(view=view, state={"activity": PROJECT["activity"]}) # --------------------------------------------------------------------------- # Accordion # --------------------------------------------------------------------------- @mcp.tool(app=True) def api_health() -> PrefabApp: """Show health details for each API endpoint.""" with Column(gap=4, css_class="p-6") as view: Heading("API Health") with Accordion(multiple=True): for ep in ENDPOINTS: with AccordionItem(ep["path"]): with Row(gap=4): Badge( f"{ep['status']}", variant="success" if ep["healthy"] else "destructive", ) Text(f"Avg: {ep['avg_ms']}ms") Text(f"P99: {ep['p99_ms']}ms") Progress(value=ep["uptime_pct"]) return PrefabApp(view=view) if __name__ == "__main__": mcp.run()
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/apps/patterns_server.py", "license": "Apache License 2.0", "lines": 415, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:tests/test_apps_prefab.py
"""Tests for MCP Apps Phase 2 — Prefab integration. Covers ``convert_result`` for PrefabApp/Component, ``app=True`` auto-wiring, return-type inference, output-schema suppression, and end-to-end round trips. """ from __future__ import annotations from typing import Annotated from mcp.types import TextContent from prefab_ui.app import PrefabApp from prefab_ui.components import Column, Heading, Text from prefab_ui.components.base import Component from fastmcp import Client, FastMCP from fastmcp.resources.types import TextResource from fastmcp.server.apps import UI_MIME_TYPE, AppConfig from fastmcp.server.providers.local_provider.decorators.tools import ( PREFAB_RENDERER_URI, ) from fastmcp.tools.tool import Tool, ToolResult # --------------------------------------------------------------------------- # convert_result # --------------------------------------------------------------------------- class TestConvertResult: def test_prefab_app(self): with Column() as view: Heading("Hello") app = PrefabApp(view=view, state={"name": "Alice"}) tool = Tool(name="t", parameters={}) result = tool.convert_result(app) assert isinstance(result, ToolResult) assert isinstance(result.content[0], TextContent) assert result.content[0].text == "[Rendered Prefab UI]" assert result.structured_content is not None assert result.structured_content["version"] == "0.2" assert result.structured_content["state"] == {"name": "Alice"} assert result.structured_content["view"]["type"] == "Column" def test_bare_component(self): heading = Heading("World") tool = Tool(name="t", parameters={}) result = tool.convert_result(heading) assert isinstance(result, ToolResult) assert result.structured_content is not None assert result.structured_content["version"] == "0.2" assert result.structured_content["view"]["type"] == "Heading" def test_tool_result_with_prefab_structured_content(self): """ToolResult with PrefabApp as structured_content preserves custom text.""" app = PrefabApp(view=Heading("Hello"), state={"x": 1}) tool = Tool(name="t", parameters={}) result = tool.convert_result( ToolResult(content="Custom fallback text", structured_content=app) ) assert isinstance(result.content[0], TextContent) assert result.content[0].text == "Custom fallback text" assert result.structured_content is not None assert result.structured_content["version"] == "0.2" assert result.structured_content["view"]["type"] == "Heading" def test_tool_result_with_component_structured_content(self): """ToolResult with bare Component as structured_content.""" tool = Tool(name="t", parameters={}) result = tool.convert_result( ToolResult(content="My text", structured_content=Heading("Hi")) ) assert isinstance(result.content[0], TextContent) assert result.content[0].text == "My text" assert result.structured_content is not None assert result.structured_content["version"] == "0.2" assert result.structured_content["view"]["type"] == "Heading" def test_tool_result_passthrough(self): """ToolResult without prefab structured_content passes through unchanged.""" original = ToolResult(content="hello") tool = Tool(name="t", parameters={}) assert tool.convert_result(original) is original # --------------------------------------------------------------------------- # app=True auto-wiring # --------------------------------------------------------------------------- class TestAppTrue: def test_app_true_sets_meta(self): mcp = FastMCP("test") @mcp.tool(app=True) def my_tool() -> str: return "hello" tools = mcp._local_provider._components tool = next( v for v in tools.values() if hasattr(v, "parameters") and v.name == "my_tool" ) assert tool.meta is not None assert "ui" in tool.meta assert tool.meta["ui"]["resourceUri"] == PREFAB_RENDERER_URI def test_app_true_registers_renderer_resource(self): mcp = FastMCP("test") @mcp.tool(app=True) def my_tool() -> str: return "hello" renderer_key = f"resource:{PREFAB_RENDERER_URI}@" assert renderer_key in mcp._local_provider._components def test_renderer_resource_has_correct_mime_type(self): mcp = FastMCP("test") @mcp.tool(app=True) def my_tool() -> str: return "hello" renderer_key = f"resource:{PREFAB_RENDERER_URI}@" resource = mcp._local_provider._components[renderer_key] assert isinstance(resource, TextResource) assert resource.mime_type == UI_MIME_TYPE def test_renderer_resource_has_csp(self): mcp = FastMCP("test") @mcp.tool(app=True) def my_tool() -> str: return "hello" renderer_key = f"resource:{PREFAB_RENDERER_URI}@" resource = mcp._local_provider._components[renderer_key] assert resource.meta is not None assert "ui" in resource.meta assert "csp" in resource.meta["ui"] def test_multiple_tools_share_renderer(self): mcp = FastMCP("test") @mcp.tool(app=True) def tool_a() -> str: return "a" @mcp.tool(app=True) def tool_b() -> str: return "b" renderer_keys = [ k for k in mcp._local_provider._components if k.startswith("resource:ui://") ] assert len(renderer_keys) == 1 def test_explicit_app_config_not_overridden(self): mcp = FastMCP("test") @mcp.tool(app=AppConfig(resource_uri="ui://custom/app.html")) def my_tool() -> PrefabApp: return PrefabApp(view=Heading("hi")) tools = mcp._local_provider._components tool = next( v for v in tools.values() if hasattr(v, "parameters") and v.name == "my_tool" ) assert tool.meta is not None assert tool.meta["ui"]["resourceUri"] == "ui://custom/app.html" # --------------------------------------------------------------------------- # Return type inference # --------------------------------------------------------------------------- class TestInference: def test_prefab_app_annotation_inferred(self): mcp = FastMCP("test") @mcp.tool def my_tool() -> PrefabApp: return PrefabApp(view=Heading("hi")) tools = mcp._local_provider._components tool = next( v for v in tools.values() if hasattr(v, "parameters") and v.name == "my_tool" ) assert tool.meta is not None assert tool.meta["ui"]["resourceUri"] == PREFAB_RENDERER_URI def test_component_annotation_inferred(self): mcp = FastMCP("test") @mcp.tool def my_tool() -> Component: return Heading("hi") tools = mcp._local_provider._components tool = next( v for v in tools.values() if hasattr(v, "parameters") and v.name == "my_tool" ) assert tool.meta is not None assert tool.meta["ui"]["resourceUri"] == PREFAB_RENDERER_URI def test_no_annotation_no_inference(self): mcp = FastMCP("test") @mcp.tool def my_tool(): return "hello" tools = mcp._local_provider._components tool = next( v for v in tools.values() if hasattr(v, "parameters") and v.name == "my_tool" ) assert tool.meta is None or "ui" not in (tool.meta or {}) def test_non_prefab_annotation_no_inference(self): mcp = FastMCP("test") @mcp.tool def my_tool() -> str: return "hello" tools = mcp._local_provider._components tool = next( v for v in tools.values() if hasattr(v, "parameters") and v.name == "my_tool" ) assert tool.meta is None or "ui" not in (tool.meta or {}) def test_optional_prefab_app_inferred(self): mcp = FastMCP("test") @mcp.tool def my_tool() -> PrefabApp | None: return None tools = mcp._local_provider._components tool = next( v for v in tools.values() if hasattr(v, "parameters") and v.name == "my_tool" ) assert tool.meta is not None assert tool.meta["ui"]["resourceUri"] == PREFAB_RENDERER_URI def test_annotated_prefab_app_inferred(self): mcp = FastMCP("test") @mcp.tool def my_tool() -> Annotated[PrefabApp | None, "some metadata"]: return None tools = mcp._local_provider._components tool = next( v for v in tools.values() if hasattr(v, "parameters") and v.name == "my_tool" ) assert tool.meta is not None assert tool.meta["ui"]["resourceUri"] == PREFAB_RENDERER_URI def test_component_subclass_union_inferred(self): mcp = FastMCP("test") @mcp.tool def my_tool() -> Column | None: return None tools = mcp._local_provider._components tool = next( v for v in tools.values() if hasattr(v, "parameters") and v.name == "my_tool" ) assert tool.meta is not None assert tool.meta["ui"]["resourceUri"] == PREFAB_RENDERER_URI # --------------------------------------------------------------------------- # Output schema suppression # --------------------------------------------------------------------------- class TestOutputSchema: def test_prefab_app_return_no_output_schema(self): mcp = FastMCP("test") @mcp.tool def my_tool() -> PrefabApp: return PrefabApp(view=Heading("hi")) tools = mcp._local_provider._components tool: Tool = next( v for v in tools.values() if isinstance(v, Tool) and v.name == "my_tool" ) assert tool.output_schema is None def test_component_return_no_output_schema(self): mcp = FastMCP("test") @mcp.tool def my_tool() -> Column: with Column() as view: Heading("hi") return view tools = mcp._local_provider._components tool: Tool = next( v for v in tools.values() if isinstance(v, Tool) and v.name == "my_tool" ) assert tool.output_schema is None def test_optional_component_no_output_schema(self): mcp = FastMCP("test") @mcp.tool def my_tool() -> Column | None: return None tools = mcp._local_provider._components tool: Tool = next( v for v in tools.values() if isinstance(v, Tool) and v.name == "my_tool" ) assert tool.output_schema is None def test_annotated_prefab_app_no_output_schema(self): mcp = FastMCP("test") @mcp.tool def my_tool() -> Annotated[PrefabApp | None, "metadata"]: return None tools = mcp._local_provider._components tool: Tool = next( v for v in tools.values() if isinstance(v, Tool) and v.name == "my_tool" ) assert tool.output_schema is None # --------------------------------------------------------------------------- # Integration — client-server round trip # --------------------------------------------------------------------------- class TestIntegration: async def test_tool_call_returns_prefab_structured_content(self): mcp = FastMCP("test") @mcp.tool(app=True) def greet(name: str) -> PrefabApp: with Column() as view: Heading("Hello") Text(f"Welcome, {name}!") return PrefabApp(view=view, state={"name": name}) async with Client(mcp) as client: result = await client.call_tool("greet", {"name": "Alice"}) assert result.structured_content is not None assert result.structured_content["version"] == "0.2" assert result.structured_content["state"] == {"name": "Alice"} async def test_tool_call_with_custom_text(self): mcp = FastMCP("test") @mcp.tool(app=True) def greet(name: str) -> ToolResult: app = PrefabApp(view=Heading(f"Hello {name}")) return ToolResult( content=f"Greeting for {name}", structured_content=app, ) async with Client(mcp) as client: result = await client.call_tool("greet", {"name": "Alice"}) assert any( "Greeting for Alice" in c.text for c in result.content if hasattr(c, "text") ) assert result.structured_content is not None assert result.structured_content["version"] == "0.2" async def test_tools_list_includes_app_meta(self): mcp = FastMCP("test") @mcp.tool(app=True) def my_tool() -> PrefabApp: return PrefabApp(view=Heading("hi")) async with Client(mcp) as client: tools = await client.list_tools() tool = next(t for t in tools if t.name == "my_tool") meta = tool.meta or {} assert "ui" in meta assert meta["ui"]["resourceUri"] == PREFAB_RENDERER_URI async def test_renderer_resource_readable(self): mcp = FastMCP("test") @mcp.tool(app=True) def my_tool() -> str: return "hello" async with Client(mcp) as client: contents = await client.read_resource(PREFAB_RENDERER_URI) assert len(contents) > 0 text = contents[0].text if hasattr(contents[0], "text") else "" assert "<html" in text.lower() or "<!doctype" in text.lower()
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/test_apps_prefab.py", "license": "Apache License 2.0", "lines": 332, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:examples/code_mode/client.py
"""Example: Client using CodeMode to discover and chain tools. CodeMode exposes just two tools: `search` (keyword query) and `execute` (run Python code with `call_tool` available). This client demonstrates both: searching for tools, then chaining multiple calls in a single execute block — one round-trip instead of many. Run with: uv run python examples/code_mode/client.py """ import asyncio import json from typing import Any from rich.console import Console from rich.panel import Panel from rich.syntax import Syntax from rich.table import Table from fastmcp.client import Client console = Console() def _get_result(result) -> Any: """Extract the value from a CallToolResult (structured or text).""" if result.structured_content is not None: data = result.structured_content if isinstance(data, dict) and set(data) == {"result"}: return data["result"] return data return result.content[0].text def _format_params(tool: dict) -> str: """Format inputSchema properties as a compact signature.""" schema = tool.get("inputSchema", {}) props = schema.get("properties", {}) if not props: return "()" parts = [] for name, info in props.items(): typ = info.get("type", "") parts.append(f"{name}: {typ}" if typ else name) return f"({', '.join(parts)})" def _tool_table( tools: list[dict], *, ranked: bool = False, show_params: bool = False ) -> Table: table = Table(show_header=True, show_edge=False, pad_edge=False, expand=True) if ranked: table.add_column("#", style="dim", width=3, justify="right") table.add_column("Tool", style="cyan", no_wrap=True) if show_params: table.add_column("Parameters", style="dim", no_wrap=True) table.add_column("Description", style="dim") for i, tool in enumerate(tools, 1): row = [tool["name"]] if show_params: row.append(_format_params(tool)) row.append(tool.get("description", "")) if ranked: row.insert(0, str(i)) table.add_row(*row) return table async def main(): async with Client("examples/code_mode/server.py") as client: console.print() console.rule("[bold]CodeMode[/bold]") console.print() # Step 1: list_tools only returns two synthetic meta-tools console.print( "The server has 8 tools. CodeMode replaces them with " "two synthetic tools — [bold]search[/bold] and [bold]execute[/bold]:" ) console.print() tools = await client.list_tools() visible = [{"name": t.name, "description": t.description} for t in tools] console.print( Panel( _tool_table(visible), title="[bold]list_tools()[/bold]", title_align="left", border_style="blue", ) ) console.print() # Step 2: search discovers available tools console.print("The LLM calls [bold]search[/bold] to discover available tools:") console.print() result = await client.call_tool("search", {"query": "add multiply numbers"}) found = _get_result(result) if isinstance(found, str): found = json.loads(found) console.print( Panel( _tool_table(found, ranked=True, show_params=True), title='[bold]search[/bold] [dim]query="add multiply numbers"[/dim]', title_align="left", border_style="green", ) ) console.print() # Step 3: execute chains tool calls in one round-trip console.print( "Now the LLM writes a Python script that chains " "the tools it found. All of it runs server-side in a " "sandbox — [bold]one round-trip[/bold], intermediate " "data never hits the context window:" ) console.print() code = """\ a = await call_tool("add", {"a": 3, "b": 4}) b = await call_tool("multiply", {"x": a["result"], "y": 2}) fib = await call_tool("fibonacci", {"n": b["result"]}) return {"sum": a["result"], "product": b["result"], "fibonacci": fib["result"]} """ result = await client.call_tool("execute", {"code": code}) console.print( Panel( Syntax(code.strip(), "python", theme="monokai"), title="[bold]execute[/bold]", title_align="left", border_style="yellow", ) ) console.print() # Final result console.print(f" Result: [bold green]{_get_result(result)}[/bold green]") console.print() if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/code_mode/client.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:examples/code_mode/server.py
"""Example: CodeMode transform — search and execute tools via code. CodeMode replaces the entire tool catalog with two meta-tools: `search` (keyword-based tool discovery) and `execute` (run Python code that chains tool calls in a sandbox). This dramatically reduces round-trips and context window usage when an LLM needs to orchestrate many tools. Requires pydantic-monty for the sandbox: pip install "fastmcp[code-mode]" Run with: uv run python examples/code_mode/server.py """ from fastmcp import FastMCP from fastmcp.experimental.transforms.code_mode import CodeMode mcp = FastMCP("CodeMode Demo") @mcp.tool def add(a: int, b: int) -> int: """Add two numbers together.""" return a + b @mcp.tool def multiply(x: float, y: float) -> float: """Multiply two numbers.""" return x * y @mcp.tool def fibonacci(n: int) -> list[int]: """Generate the first n Fibonacci numbers.""" if n <= 0: return [] seq = [0, 1] while len(seq) < n: seq.append(seq[-1] + seq[-2]) return seq[:n] @mcp.tool def reverse_string(text: str) -> str: """Reverse a string.""" return text[::-1] @mcp.tool def word_count(text: str) -> int: """Count the number of words in a text.""" return len(text.split()) @mcp.tool def to_uppercase(text: str) -> str: """Convert text to uppercase.""" return text.upper() @mcp.tool def list_files(directory: str) -> list[str]: """List files in a directory.""" import os return os.listdir(directory) @mcp.tool def read_file(path: str) -> str: """Read the contents of a file.""" with open(path) as f: return f.read() # CodeMode collapses all 8 tools into just `search` + `execute`. # The LLM discovers tools via keyword search, then writes Python # scripts that chain multiple tool calls in a single round-trip. mcp.add_transform(CodeMode()) if __name__ == "__main__": mcp.run()
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/code_mode/server.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:src/fastmcp/experimental/transforms/code_mode.py
import importlib import json from collections.abc import Awaitable, Callable, Sequence from typing import Annotated, Any, Literal, Protocol from mcp.types import TextContent from pydantic import Field from fastmcp.exceptions import NotFoundError from fastmcp.server.context import Context from fastmcp.server.transforms import GetToolNext from fastmcp.server.transforms.catalog import CatalogTransform from fastmcp.server.transforms.search.base import ( serialize_tools_for_output_json, serialize_tools_for_output_markdown, ) from fastmcp.tools.tool import Tool, ToolResult from fastmcp.utilities.async_utils import is_coroutine_function from fastmcp.utilities.versions import VersionSpec # --------------------------------------------------------------------------- # Type aliases # --------------------------------------------------------------------------- GetToolCatalog = Callable[[Context], Awaitable[Sequence[Tool]]] """Async callable that returns the auth-filtered tool catalog.""" SearchFn = Callable[[Sequence[Tool], str], Awaitable[Sequence[Tool]]] """Async callable that searches a tool sequence by query string.""" DiscoveryToolFactory = Callable[[GetToolCatalog], Tool] """Factory that receives catalog access and returns a synthetic Tool.""" # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def _ensure_async(fn: Callable[..., Any]) -> Callable[..., Any]: if is_coroutine_function(fn): return fn async def wrapper(*args: Any, **kwargs: Any) -> Any: return fn(*args, **kwargs) return wrapper def _unwrap_tool_result(result: ToolResult) -> dict[str, Any] | str: """Convert a ToolResult for use in the sandbox. - Output schema present → structured_content dict (matches the schema) - Otherwise → concatenated text content as a string """ if result.structured_content is not None: return result.structured_content parts: list[str] = [] for content in result.content: if isinstance(content, TextContent): parts.append(content.text) else: parts.append(str(content)) return "\n".join(parts) # --------------------------------------------------------------------------- # Sandbox providers # --------------------------------------------------------------------------- class SandboxProvider(Protocol): """Interface for executing LLM-generated Python code in a sandbox. WARNING: The ``code`` parameter passed to ``run`` contains untrusted, LLM-generated Python. Implementations MUST execute it in an isolated sandbox — never with plain ``exec()``. Use ``MontySandboxProvider`` (backed by ``pydantic-monty``) for production workloads. """ async def run( self, code: str, *, inputs: dict[str, Any] | None = None, external_functions: dict[str, Callable[..., Any]] | None = None, ) -> Any: ... class MontySandboxProvider: """Sandbox provider backed by `pydantic-monty`. Args: limits: Resource limits for sandbox execution. Supported keys: ``max_duration_secs`` (float), ``max_allocations`` (int), ``max_memory`` (int), ``max_recursion_depth`` (int), ``gc_interval`` (int). All are optional; omit a key to leave that limit uncapped. """ def __init__( self, *, limits: dict[str, Any] | None = None, ) -> None: self.limits = limits async def run( self, code: str, *, inputs: dict[str, Any] | None = None, external_functions: dict[str, Callable[..., Any]] | None = None, ) -> Any: try: pydantic_monty = importlib.import_module("pydantic_monty") except ModuleNotFoundError as exc: raise ImportError( "CodeMode requires pydantic-monty for the Monty sandbox provider. " "Install it with `fastmcp[code-mode]` or pass a custom SandboxProvider." ) from exc inputs = inputs or {} async_functions = { key: _ensure_async(value) for key, value in (external_functions or {}).items() } monty = pydantic_monty.Monty( code, inputs=list(inputs.keys()), external_functions=list(async_functions.keys()), ) run_kwargs: dict[str, Any] = {"external_functions": async_functions} if inputs: run_kwargs["inputs"] = inputs if self.limits is not None: run_kwargs["limits"] = self.limits return await pydantic_monty.run_monty_async(monty, **run_kwargs) # --------------------------------------------------------------------------- # Built-in discovery tools # --------------------------------------------------------------------------- ToolDetailLevel = Literal["brief", "detailed", "full"] """Detail level for discovery tool output. - ``"brief"``: tool names and one-line descriptions - ``"detailed"``: compact markdown with parameter names, types, and required markers - ``"full"``: complete JSON schema """ def _render_tools(tools: Sequence[Tool], detail: ToolDetailLevel) -> str: """Render tools at the requested detail level. The same detail value produces the same output format regardless of which discovery tool calls this, so ``detail="detailed"`` on Search gives identical formatting to ``detail="detailed"`` on GetSchemas. """ if not tools: if detail == "full": return json.dumps([], indent=2) return "No tools matched the query." if detail == "full": return json.dumps(serialize_tools_for_output_json(tools), indent=2) if detail == "detailed": return serialize_tools_for_output_markdown(tools) # brief lines: list[str] = [] for tool in tools: desc = f": {tool.description}" if tool.description else "" lines.append(f"- {tool.name}{desc}") return "\n".join(lines) class Search: """Discovery tool factory that searches the catalog by query. Args: search_fn: Async callable ``(tools, query) -> matching_tools``. Defaults to BM25 ranking. name: Name of the synthetic tool exposed to the LLM. default_detail: Default detail level for search results. ``"brief"`` returns tool names and descriptions only. ``"detailed"`` returns compact markdown with parameter schemas. ``"full"`` returns complete JSON tool definitions. default_limit: Maximum number of results to return. The LLM can override this per call. ``None`` means no limit. """ def __init__( self, *, search_fn: SearchFn | None = None, name: str = "search", default_detail: ToolDetailLevel | None = None, default_limit: int | None = None, ) -> None: if search_fn is None: from fastmcp.server.transforms.search.bm25 import BM25SearchTransform _bm25 = BM25SearchTransform(max_results=default_limit or 50) search_fn = _bm25._search self._search_fn = search_fn self._name = name self._default_detail: ToolDetailLevel = default_detail or "brief" self._default_limit = default_limit def __call__(self, get_catalog: GetToolCatalog) -> Tool: search_fn = self._search_fn default_detail = self._default_detail default_limit = self._default_limit async def search( query: Annotated[str, "Search query to find available tools"], tags: Annotated[ list[str] | None, "Filter to tools with any of these tags before searching", ] = None, detail: Annotated[ ToolDetailLevel, "'brief' for names and descriptions, 'detailed' for parameter schemas as markdown, 'full' for complete JSON schemas", ] = default_detail, limit: Annotated[ int | None, "Maximum number of results to return", ] = default_limit, ctx: Context = None, # type: ignore[assignment] ) -> str: """Search for available tools by query. Returns matching tools ranked by relevance. """ catalog = await get_catalog(ctx) catalog_size = len(catalog) tools: Sequence[Tool] = catalog if tags: tag_set = set(tags) has_untagged = "untagged" in tag_set real_tags = tag_set - {"untagged"} tools = [ t for t in tools if (t.tags & real_tags) or (has_untagged and not t.tags) ] results = await search_fn(tools, query) if limit is not None: results = results[:limit] rendered = _render_tools(results, detail) if len(results) < catalog_size and detail != "full": n = len(results) rendered = f"{n} of {catalog_size} tools:\n\n{rendered}" return rendered return Tool.from_function(fn=search, name=self._name) class GetSchemas: """Discovery tool factory that returns schemas for tools by name. Args: name: Name of the synthetic tool exposed to the LLM. default_detail: Default detail level for schema results. ``"brief"`` returns tool names and descriptions only. ``"detailed"`` renders compact markdown with parameter names, types, and required markers. ``"full"`` returns the complete JSON schema. """ def __init__( self, *, name: str = "get_schema", default_detail: ToolDetailLevel | None = None, ) -> None: self._name = name self._default_detail: ToolDetailLevel = default_detail or "detailed" def __call__(self, get_catalog: GetToolCatalog) -> Tool: default_detail = self._default_detail async def get_schema( tools: Annotated[ list[str], "List of tool names to get schemas for", ], detail: Annotated[ ToolDetailLevel, "'brief' for names and descriptions, 'detailed' for parameter schemas as markdown, 'full' for complete JSON schemas", ] = default_detail, ctx: Context = None, # type: ignore[assignment] ) -> str: """Get parameter schemas for specific tools. Use after searching to get the detail needed to call a tool. """ catalog = await get_catalog(ctx) catalog_by_name = {t.name: t for t in catalog} matched = [catalog_by_name[n] for n in tools if n in catalog_by_name] not_found = [n for n in tools if n not in catalog_by_name] if not matched and not_found: return f"Tools not found: {', '.join(not_found)}" if detail == "full": data = serialize_tools_for_output_json(matched) if not_found: data.append({"not_found": not_found}) return json.dumps(data, indent=2) result = _render_tools(matched, detail) if not_found: result += f"\n\nTools not found: {', '.join(not_found)}" return result return Tool.from_function(fn=get_schema, name=self._name) class GetTags: """Discovery tool factory that lists tool tags from the catalog. Reads ``tool.tags`` from the catalog and groups tools by tag. Tools without tags appear under ``"untagged"``. Args: name: Name of the synthetic tool exposed to the LLM. default_detail: Default detail level. ``"brief"`` returns tag names with tool counts. ``"full"`` lists all tools under each tag. """ def __init__( self, *, name: str = "tags", default_detail: Literal["brief", "full"] | None = None, ) -> None: self._name = name self._default_detail: Literal["brief", "full"] = default_detail or "brief" def __call__(self, get_catalog: GetToolCatalog) -> Tool: default_detail = self._default_detail async def tags( detail: Annotated[ Literal["brief", "full"], "Level of detail: 'brief' for tag names and counts, 'full' for tools listed under each tag", ] = default_detail, ctx: Context = None, # type: ignore[assignment] ) -> str: """List available tool tags. Use to browse available tools by tag before searching. """ catalog = await get_catalog(ctx) by_tag: dict[str, list[Tool]] = {} for tool in catalog: if tool.tags: for tag in tool.tags: by_tag.setdefault(tag, []).append(tool) else: by_tag.setdefault("untagged", []).append(tool) if not by_tag: return "No tools available." if detail == "brief": lines = [ f"- {tag} ({len(tools)} tool{'s' if len(tools) != 1 else ''})" for tag, tools in sorted(by_tag.items()) ] return "\n".join(lines) blocks: list[str] = [] for tag, tools in sorted(by_tag.items()): lines = [f"### {tag}"] for tool in tools: desc = f": {tool.description}" if tool.description else "" lines.append(f"- {tool.name}{desc}") blocks.append("\n".join(lines)) return "\n\n".join(blocks) return Tool.from_function(fn=tags, name=self._name) class ListTools: """Discovery tool factory that lists all tools in the catalog. Args: name: Name of the synthetic tool exposed to the LLM. default_detail: Default detail level. ``"brief"`` returns tool names and one-line descriptions. ``"detailed"`` returns compact markdown with parameter schemas. ``"full"`` returns the complete JSON schema. """ def __init__( self, *, name: str = "list_tools", default_detail: ToolDetailLevel | None = None, ) -> None: self._name = name self._default_detail: ToolDetailLevel = default_detail or "brief" def __call__(self, get_catalog: GetToolCatalog) -> Tool: default_detail = self._default_detail async def list_tools( detail: Annotated[ ToolDetailLevel, "'brief' for names and descriptions, 'detailed' for parameter schemas as markdown, 'full' for complete JSON schemas", ] = default_detail, ctx: Context = None, # type: ignore[assignment] ) -> str: """List all available tools. Use to see the full catalog before searching or calling tools. """ catalog = await get_catalog(ctx) return _render_tools(catalog, detail) return Tool.from_function(fn=list_tools, name=self._name) # --------------------------------------------------------------------------- # CodeMode # --------------------------------------------------------------------------- def _default_discovery_tools() -> list[DiscoveryToolFactory]: return [Search(), GetSchemas()] class CodeMode(CatalogTransform): """Transform that collapses all tools into discovery + execute meta-tools. Discovery tools are composable via the ``discovery_tools`` parameter. Each is a callable that receives catalog access and returns a ``Tool``. By default, ``Search`` and ``GetSchemas`` are included for progressive disclosure: search finds candidates, get_schema retrieves parameter details, and execute runs code. The ``execute`` tool is always present and provides a sandboxed Python environment with ``call_tool(name, params)`` in scope. """ def __init__( self, *, sandbox_provider: SandboxProvider | None = None, discovery_tools: list[DiscoveryToolFactory] | None = None, execute_tool_name: str = "execute", execute_description: str | None = None, ) -> None: super().__init__() self.execute_tool_name = execute_tool_name self.execute_description = execute_description self.sandbox_provider = sandbox_provider or MontySandboxProvider() self._discovery_factories = ( discovery_tools if discovery_tools is not None else _default_discovery_tools() ) self._built_discovery_tools: list[Tool] | None = None self._cached_execute_tool: Tool | None = None def _build_discovery_tools(self) -> list[Tool]: if self._built_discovery_tools is None: tools = [ factory(self.get_tool_catalog) for factory in self._discovery_factories ] names = {t.name for t in tools} if self.execute_tool_name in names: raise ValueError( f"Discovery tool name '{self.execute_tool_name}' " f"collides with execute_tool_name." ) if len(names) != len(tools): raise ValueError("Discovery tools must have unique names.") self._built_discovery_tools = tools return self._built_discovery_tools async def transform_tools(self, tools: Sequence[Tool]) -> Sequence[Tool]: return [*self._build_discovery_tools(), self._get_execute_tool()] async def get_tool( self, name: str, call_next: GetToolNext, *, version: VersionSpec | None = None, ) -> Tool | None: for tool in self._build_discovery_tools(): if tool.name == name: return tool if name == self.execute_tool_name: return self._get_execute_tool() return await call_next(name, version=version) def _build_execute_description(self) -> str: if self.execute_description is not None: return self.execute_description return ( "Chain `await call_tool(...)` calls in one Python block; prefer returning the final answer from a single block.\n" "Use `return` to produce output.\n" "Only `call_tool(tool_name: str, params: dict) -> Any` is available in scope." ) @staticmethod def _find_tool(name: str, tools: Sequence[Tool]) -> Tool | None: """Find a tool by name from a pre-fetched list.""" for tool in tools: if tool.name == name: return tool return None def _get_execute_tool(self) -> Tool: if self._cached_execute_tool is None: self._cached_execute_tool = self._make_execute_tool() return self._cached_execute_tool def _make_execute_tool(self) -> Tool: transform = self async def execute( code: Annotated[ str, Field( description=( "Python async code to execute tool calls via call_tool(name, arguments)" ) ), ], ctx: Context = None, # type: ignore[assignment] ) -> Any: """Execute tool calls using Python code.""" async def call_tool(tool_name: str, params: dict[str, Any]) -> Any: backend_tools = await transform.get_tool_catalog(ctx) tool = transform._find_tool(tool_name, backend_tools) if tool is None: raise NotFoundError(f"Unknown tool: {tool_name}") result = await ctx.fastmcp.call_tool(tool.name, params) return _unwrap_tool_result(result) return await transform.sandbox_provider.run( code, external_functions={"call_tool": call_tool}, ) return Tool.from_function( fn=execute, name=self.execute_tool_name, description=self._build_execute_description(), ) __all__ = [ "CodeMode", "GetSchemas", "GetTags", "GetToolCatalog", "ListTools", "MontySandboxProvider", "SandboxProvider", "Search", ]
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/experimental/transforms/code_mode.py", "license": "Apache License 2.0", "lines": 473, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:tests/experimental/transforms/test_code_mode.py
import importlib import json from typing import Any import pytest from mcp.types import ImageContent, TextContent from fastmcp import Client, FastMCP from fastmcp.exceptions import ToolError from fastmcp.experimental.transforms.code_mode import ( CodeMode, GetSchemas, GetToolCatalog, MontySandboxProvider, Search, _ensure_async, ) from fastmcp.server.context import Context from fastmcp.tools.tool import Tool, ToolResult def _unwrap_result(result: ToolResult) -> Any: """Extract the logical return value from a ToolResult.""" if result.structured_content is not None: return result.structured_content text_blocks = [ content.text for content in result.content if isinstance(content, TextContent) ] if not text_blocks: return None if len(text_blocks) == 1: try: return json.loads(text_blocks[0]) except json.JSONDecodeError: return text_blocks[0] values: list[Any] = [] for text in text_blocks: try: values.append(json.loads(text)) except json.JSONDecodeError: values.append(text) return values def _unwrap_string_result(result: ToolResult) -> str: """Extract a string result from a ToolResult. String results are wrapped in ``{"result": "..."}`` by the structured-output convention. """ data = _unwrap_result(result) if isinstance(data, dict) and "result" in data: return data["result"] assert isinstance(data, str) return data class _UnsafeTestSandboxProvider: """UNSAFE: Uses exec() for testing only. Never use in production.""" async def run( self, code: str, *, inputs: dict[str, Any] | None = None, external_functions: dict[str, Any] | None = None, ) -> Any: namespace: dict[str, Any] = {} if inputs: namespace.update(inputs) if external_functions: namespace.update( {key: _ensure_async(value) for key, value in external_functions.items()} ) wrapped = "async def __test_main__():\n" for line in code.splitlines(): wrapped += f" {line}\n" if not code.strip(): wrapped += " return None\n" exec(wrapped, namespace, namespace) return await namespace["__test_main__"]() async def _run_tool( server: FastMCP, name: str, arguments: dict[str, Any] ) -> ToolResult: return await server.call_tool(name, arguments) # --------------------------------------------------------------------------- # CodeMode core tests # --------------------------------------------------------------------------- async def test_code_mode_default_tools() -> None: """Default CodeMode exposes search, get_schema, and execute.""" mcp = FastMCP("CodeMode Default") @mcp.tool def ping() -> str: return "pong" mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) listed_tools = await mcp.list_tools(run_middleware=False) assert {tool.name for tool in listed_tools} == {"search", "get_schema", "execute"} async def test_code_mode_search_returns_lightweight_results() -> None: """Default search returns tool names and descriptions, not full schemas.""" mcp = FastMCP("CodeMode Search") @mcp.tool def square(x: int) -> int: """Compute the square of a number.""" return x * x @mcp.tool def greet(name: str) -> str: """Say hello to someone.""" return f"Hello, {name}!" mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool(mcp, "search", {"query": "square number"}) text = _unwrap_string_result(result) assert "square" in text assert "Compute the square" in text # Should NOT contain full schema details assert "inputSchema" not in text async def test_code_mode_get_schema_brief() -> None: """get_schema with detail=brief returns names and descriptions only.""" mcp = FastMCP("CodeMode Schema Brief") @mcp.tool def square(x: int) -> int: """Compute the square of a number.""" return x * x mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool( mcp, "get_schema", {"tools": ["square"], "detail": "brief"} ) text = _unwrap_string_result(result) assert "square" in text assert "Compute the square" in text # brief should NOT include parameter details assert "**Parameters**" not in text async def test_code_mode_get_schema_detailed() -> None: """get_schema with detail=detailed returns markdown with parameter info.""" mcp = FastMCP("CodeMode Schema Detailed") @mcp.tool def square(x: int) -> int: """Compute the square of a number.""" return x * x mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool( mcp, "get_schema", {"tools": ["square"], "detail": "detailed"} ) text = _unwrap_string_result(result) assert "### square" in text assert "Compute the square" in text assert "**Parameters**" in text assert "`x` (integer, required)" in text async def test_code_mode_get_schema_full() -> None: """get_schema with detail=full returns JSON schema.""" mcp = FastMCP("CodeMode Schema Full") @mcp.tool def square(x: int) -> int: """Compute the square of a number.""" return x * x mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool(mcp, "get_schema", {"tools": ["square"], "detail": "full"}) text = _unwrap_string_result(result) parsed = json.loads(text) assert isinstance(parsed, list) assert parsed[0]["name"] == "square" assert "inputSchema" in parsed[0] async def test_code_mode_get_schema_default_is_detailed() -> None: """get_schema defaults to detailed (markdown with parameters).""" mcp = FastMCP("CodeMode Schema Default") @mcp.tool def square(x: int) -> int: """Compute the square of a number.""" return x * x mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool(mcp, "get_schema", {"tools": ["square"]}) text = _unwrap_string_result(result) assert "### square" in text assert "**Parameters**" in text async def test_code_mode_get_schema_not_found() -> None: """get_schema reports tools that don't exist in the catalog.""" mcp = FastMCP("CodeMode Schema NotFound") @mcp.tool def ping() -> str: return "pong" mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool(mcp, "get_schema", {"tools": ["nonexistent"]}) text = _unwrap_string_result(result) assert "not found" in text.lower() assert "nonexistent" in text async def test_code_mode_get_schema_partial_match() -> None: """get_schema returns schemas for found tools and reports missing ones.""" mcp = FastMCP("CodeMode Schema Partial") @mcp.tool def square(x: int) -> int: """Compute the square.""" return x * x mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool(mcp, "get_schema", {"tools": ["square", "nonexistent"]}) text = _unwrap_string_result(result) assert "### square" in text assert "nonexistent" in text async def test_code_mode_execute_works() -> None: """Execute tool can call backend tools through the sandbox.""" mcp = FastMCP("CodeMode Execute") @mcp.tool def add(x: int, y: int) -> int: return x + y mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool( mcp, "execute", {"code": "return await call_tool('add', {'x': 2, 'y': 3})"} ) assert _unwrap_result(result) == {"result": 5} # --------------------------------------------------------------------------- # Tool naming and configuration # --------------------------------------------------------------------------- async def test_code_mode_custom_execute_name() -> None: mcp = FastMCP("CodeMode Custom Execute") @mcp.tool def ping() -> str: return "pong" mcp.add_transform( CodeMode( sandbox_provider=_UnsafeTestSandboxProvider(), execute_tool_name="run_code", ) ) listed = await mcp.list_tools(run_middleware=False) names = {t.name for t in listed} assert "run_code" in names assert "execute" not in names async def test_code_mode_custom_execute_description() -> None: mcp = FastMCP("CodeMode Custom Desc") @mcp.tool def ping() -> str: return "pong" mcp.add_transform( CodeMode( sandbox_provider=_UnsafeTestSandboxProvider(), execute_description="Custom execute description", ) ) listed = await mcp.list_tools(run_middleware=False) by_name = {t.name: t for t in listed} assert by_name["execute"].description == "Custom execute description" async def test_code_mode_default_execute_description() -> None: mcp = FastMCP("CodeMode Defaults") @mcp.tool def ping() -> str: return "pong" mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) listed = await mcp.list_tools(run_middleware=False) by_name = {t.name: t for t in listed} desc = by_name["execute"].description or "" assert "single block" in desc assert "Use `return` to produce output." in desc assert ( "Only `call_tool(tool_name: str, params: dict) -> Any` is available in scope." in desc ) # --------------------------------------------------------------------------- # Discovery tool customization # --------------------------------------------------------------------------- async def test_code_mode_no_discovery_tools() -> None: """CodeMode with empty discovery_tools exposes only execute.""" mcp = FastMCP("CodeMode No Discovery") @mcp.tool def ping() -> str: return "pong" mcp.add_transform( CodeMode( discovery_tools=[], sandbox_provider=_UnsafeTestSandboxProvider(), ) ) listed = await mcp.list_tools(run_middleware=False) assert {t.name for t in listed} == {"execute"} async def test_code_mode_custom_discovery_tool_function() -> None: """A plain function can serve as a discovery tool factory.""" mcp = FastMCP("CodeMode Custom Discovery") @mcp.tool def square(x: int) -> int: """Compute the square.""" return x * x def list_all(get_catalog: GetToolCatalog) -> Tool: async def list_tools( ctx: Context = None, # type: ignore[assignment] ) -> str: """List all available tools.""" tools = await get_catalog(ctx) return ", ".join(t.name for t in tools) return Tool.from_function(fn=list_tools, name="list_all") mcp.add_transform( CodeMode( discovery_tools=[list_all], sandbox_provider=_UnsafeTestSandboxProvider(), ) ) listed = await mcp.list_tools(run_middleware=False) assert {t.name for t in listed} == {"list_all", "execute"} result = await _run_tool(mcp, "list_all", {}) text = _unwrap_string_result(result) assert "square" in text async def test_code_mode_search_detailed() -> None: """Search with detail='detailed' returns markdown with parameter info.""" mcp = FastMCP("CodeMode Search Detailed") @mcp.tool def square(x: int) -> int: """Compute the square.""" return x * x mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool(mcp, "search", {"query": "square", "detail": "detailed"}) text = _unwrap_string_result(result) assert "### square" in text assert "Compute the square" in text assert "**Parameters**" in text assert "`x` (integer, required)" in text async def test_code_mode_search_tool_full_detail() -> None: """Search with detail='full' includes JSON schemas.""" mcp = FastMCP("CodeMode Search Full") @mcp.tool def square(x: int) -> int: """Compute the square.""" return x * x mcp.add_transform( CodeMode( discovery_tools=[Search(default_detail="full")], sandbox_provider=_UnsafeTestSandboxProvider(), ) ) result = await _run_tool(mcp, "search", {"query": "square"}) text = _unwrap_string_result(result) parsed = json.loads(text) assert isinstance(parsed, list) assert parsed[0]["name"] == "square" assert "inputSchema" in parsed[0] async def test_code_mode_custom_search_tool_name() -> None: """Search and GetSchemas support custom names.""" mcp = FastMCP("CodeMode Custom Names") @mcp.tool def ping() -> str: return "pong" mcp.add_transform( CodeMode( discovery_tools=[ Search(name="find"), GetSchemas(name="describe"), ], sandbox_provider=_UnsafeTestSandboxProvider(), ) ) listed = await mcp.list_tools(run_middleware=False) assert {t.name for t in listed} == {"find", "describe", "execute"} def test_code_mode_rejects_discovery_execute_name_collision() -> None: """CodeMode raises ValueError when a discovery tool collides with execute.""" cm = CodeMode( discovery_tools=[Search(name="execute")], sandbox_provider=_UnsafeTestSandboxProvider(), ) with pytest.raises(ValueError, match="collides"): cm._build_discovery_tools() def test_code_mode_rejects_duplicate_discovery_names() -> None: """CodeMode raises ValueError when discovery tools have duplicate names.""" cm = CodeMode( discovery_tools=[Search(name="search"), Search(name="search")], sandbox_provider=_UnsafeTestSandboxProvider(), ) with pytest.raises(ValueError, match="unique"): cm._build_discovery_tools() # --------------------------------------------------------------------------- # Visibility and auth # --------------------------------------------------------------------------- async def test_code_mode_execute_respects_disabled_tool_visibility() -> None: mcp = FastMCP("CodeMode Disabled") @mcp.tool def secret() -> str: return "nope" mcp.disable(names={"secret"}, components={"tool"}) mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) with pytest.raises(ToolError, match=r"Unknown tool"): await _run_tool( mcp, "execute", {"code": "return await call_tool('secret', {})"} ) async def test_code_mode_search_respects_disabled_tool_visibility() -> None: mcp = FastMCP("CodeMode Disabled Search") @mcp.tool def secret() -> str: """A secret tool.""" return "nope" mcp.disable(names={"secret"}, components={"tool"}) mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool(mcp, "search", {"query": "secret"}) text = _unwrap_string_result(result) assert "secret" not in text or "No tools" in text async def test_code_mode_execute_sees_mid_run_visibility_changes() -> None: """Unlocking a tool mid-execution makes it callable in the same run.""" mcp = FastMCP("CodeMode Unlock") @mcp.tool async def unlock(ctx: Context) -> str: await ctx.enable_components(names={"secret"}, components={"tool"}) return "unlocked" @mcp.tool async def secret() -> str: return "secret-ok" mcp.disable(names={"secret"}, components={"tool"}) mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) async with Client(mcp) as client: result = await client.call_tool( "execute", { "code": "await call_tool('unlock', {})\nreturn await call_tool('secret', {})" }, ) assert result.data == {"result": "secret-ok"} async def test_code_mode_execute_respects_tool_auth() -> None: mcp = FastMCP("CodeMode Auth") @mcp.tool(auth=lambda _ctx: False) def protected() -> str: return "nope" mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) with pytest.raises(ToolError, match=r"Unknown tool"): await _run_tool( mcp, "execute", {"code": "return await call_tool('protected', {})"} ) async def test_code_mode_search_respects_tool_auth() -> None: mcp = FastMCP("CodeMode Auth Search") @mcp.tool(auth=lambda _ctx: False) def protected() -> str: """A protected tool.""" return "nope" mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool(mcp, "search", {"query": "protected"}) text = _unwrap_string_result(result) assert "protected" not in text or "No tools" in text async def test_code_mode_shadows_colliding_tool_names() -> None: """Backend tools with the same name as meta-tools are shadowed.""" mcp = FastMCP("CodeMode Collision") @mcp.tool def search() -> str: return "real search" @mcp.tool def ping() -> str: return "pong" mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) tools = await mcp.list_tools(run_middleware=False) tool_names = {t.name for t in tools} assert "execute" in tool_names result = await _run_tool( mcp, "execute", {"code": 'return await call_tool("ping", {})'} ) assert _unwrap_result(result) == {"result": "pong"} # --------------------------------------------------------------------------- # get_tool pass-through # --------------------------------------------------------------------------- async def test_code_mode_get_tool_returns_meta_tools_and_passes_through() -> None: """get_tool returns meta-tools by name and passes through backend tools.""" mcp = FastMCP("CodeMode GetTool") @mcp.tool def ping() -> str: return "pong" mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) search_tool = await mcp.get_tool("search") assert search_tool is not None assert search_tool.name == "search" schema_tool = await mcp.get_tool("get_schema") assert schema_tool is not None assert schema_tool.name == "get_schema" execute_tool = await mcp.get_tool("execute") assert execute_tool is not None assert execute_tool.name == "execute" ping_tool = await mcp.get_tool("ping") assert ping_tool is not None assert ping_tool.name == "ping" # --------------------------------------------------------------------------- # Execute edge cases # --------------------------------------------------------------------------- async def test_code_mode_execute_non_text_content_stringified() -> None: mcp = FastMCP("CodeMode NonText") @mcp.tool def image_tool() -> ImageContent: return ImageContent(type="image", data="base64data", mimeType="image/png") mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool( mcp, "execute", {"code": "return await call_tool('image_tool', {})"} ) unwrapped = _unwrap_result(result) assert isinstance(unwrapped, str) assert "base64data" in unwrapped async def test_code_mode_execute_multi_tool_chaining() -> None: """Execute block can chain multiple call_tool() calls.""" mcp = FastMCP("CodeMode Chaining") @mcp.tool def double(x: int) -> int: return x * 2 @mcp.tool def add_one(x: int) -> int: return x + 1 mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) result = await _run_tool( mcp, "execute", { "code": ( "a = await call_tool('double', {'x': 3})\n" "b = await call_tool('add_one', {'x': a['result']})\n" "return b" ) }, ) assert _unwrap_result(result) == {"result": 7} async def test_code_mode_sandbox_error_surfaces_as_tool_error() -> None: mcp = FastMCP("CodeMode Errors") @mcp.tool def ping() -> str: return "pong" mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider())) with pytest.raises(ToolError): await _run_tool(mcp, "execute", {"code": "raise ValueError('boom')"}) # --------------------------------------------------------------------------- # Sandbox provider tests # --------------------------------------------------------------------------- async def test_monty_provider_raises_informative_error_when_missing( monkeypatch: pytest.MonkeyPatch, ) -> None: provider = MontySandboxProvider() real_import_module = importlib.import_module def _fake_import_module(name: str, package: str | None = None): if name == "pydantic_monty": raise ModuleNotFoundError("No module named 'pydantic_monty'") return real_import_module(name, package) monkeypatch.setattr(importlib, "import_module", _fake_import_module) with pytest.raises(ImportError, match=r"fastmcp\[code-mode\]"): await provider.run("return 1") async def test_monty_provider_forwards_limits() -> None: provider = MontySandboxProvider(limits={"max_duration_secs": 0.1}) with pytest.raises(Exception, match="time limit exceeded"): await provider.run("x = 0\nfor _ in range(10**9):\n x += 1") async def test_monty_provider_no_limits_by_default() -> None: provider = MontySandboxProvider() result = await provider.run("return 1 + 2") assert result == 3
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/experimental/transforms/test_code_mode.py", "license": "Apache License 2.0", "lines": 525, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:examples/search/client_bm25.py
"""Example: Client using BM25 search to discover and call tools. BM25 search accepts natural language queries instead of regex patterns. This client shows how relevance ranking surfaces the best matches. Run with: uv run python examples/search/client_bm25.py """ import asyncio import json from typing import Any from rich.console import Console from rich.panel import Panel from rich.table import Table from fastmcp.client import Client console = Console() def _get_result(result) -> Any: """Extract the value from a CallToolResult (structured or text).""" if result.structured_content is not None: data = result.structured_content if isinstance(data, dict) and set(data) == {"result"}: return data["result"] return data return result.content[0].text def _format_params(tool: dict) -> str: """Format inputSchema properties as a compact signature.""" schema = tool.get("inputSchema", {}) props = schema.get("properties", {}) if not props: return "()" parts = [] for name, info in props.items(): typ = info.get("type", "") parts.append(f"{name}: {typ}" if typ else name) return f"({', '.join(parts)})" def _tool_table( tools: list[dict], *, ranked: bool = False, show_params: bool = False ) -> Table: table = Table(show_header=True, show_edge=False, pad_edge=False, expand=True) if ranked: table.add_column("#", style="dim", width=3, justify="right") table.add_column("Tool", style="cyan", no_wrap=True) if show_params: table.add_column("Parameters", style="dim", no_wrap=True) table.add_column("Description", style="dim") for i, tool in enumerate(tools, 1): row = [tool["name"]] if show_params: row.append(_format_params(tool)) row.append(tool.get("description", "")) if ranked: row.insert(0, str(i)) table.add_row(*row) return table async def main(): async with Client("examples/search/server_bm25.py") as client: console.print() console.rule("[bold]BM25 Search Transform[/bold]") console.print() # Step 1: list_tools shows only synthetic tools + pinned tools console.print( "The server has 8 tools. BM25SearchTransform replaces them with " "just [bold]search_tools[/bold] and [bold]call_tool[/bold]. " "[bold]list_files[/bold] stays visible via [dim]always_visible[/dim]:" ) console.print() tools = await client.list_tools() visible = [{"name": t.name, "description": t.description} for t in tools] console.print( Panel( _tool_table(visible), title="[bold]list_tools()[/bold]", title_align="left", border_style="blue", ) ) console.print() # Step 2: natural language search discovers tools by relevance console.print( "The LLM uses [bold]search_tools[/bold] with natural language " "to discover tools ranked by relevance:" ) console.print() result = await client.call_tool("search_tools", {"query": "work with numbers"}) found = _get_result(result) if isinstance(found, str): found = json.loads(found) console.print( Panel( _tool_table(found, ranked=True, show_params=True), title='[bold]search_tools[/bold] [dim]query="work with numbers"[/dim]', title_align="left", border_style="green", ) ) console.print() result = await client.call_tool( "search_tools", {"query": "manipulate text strings"} ) found = _get_result(result) if isinstance(found, str): found = json.loads(found) console.print( Panel( _tool_table(found, ranked=True, show_params=True), title='[bold]search_tools[/bold] [dim]query="manipulate text strings"[/dim]', title_align="left", border_style="green", ) ) console.print() # Step 3: call a discovered tool console.print( "Then the LLM calls a discovered tool through [bold]call_tool[/bold]:" ) console.print() result = await client.call_tool( "call_tool", { "name": "word_count", "arguments": {"text": "BM25 search makes tool discovery easy"}, }, ) console.print( Panel( f'call_tool(name="word_count", arguments={{"text": "BM25 search makes tool discovery easy"}})\n→ [bold green]{_get_result(result)}[/bold green]', title="[bold]call_tool()[/bold]", title_align="left", border_style="magenta", ) ) console.print() if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/search/client_bm25.py", "license": "Apache License 2.0", "lines": 132, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:examples/search/client_regex.py
"""Example: Client using regex search to discover and call tools. Regex search lets clients find tools by matching patterns against tool names and descriptions. Precise when you know what you're looking for. Run with: uv run python examples/search/client_regex.py """ import asyncio import json from typing import Any from rich.console import Console from rich.panel import Panel from rich.table import Table from fastmcp.client import Client console = Console() def _get_result(result) -> Any: """Extract the value from a CallToolResult (structured or text).""" if result.structured_content is not None: data = result.structured_content if isinstance(data, dict) and set(data) == {"result"}: return data["result"] return data return result.content[0].text def _format_params(tool: dict) -> str: """Format inputSchema properties as a compact signature.""" schema = tool.get("inputSchema", {}) props = schema.get("properties", {}) if not props: return "()" parts = [] for name, info in props.items(): typ = info.get("type", "") parts.append(f"{name}: {typ}" if typ else name) return f"({', '.join(parts)})" def _tool_table( tools: list[dict], *, ranked: bool = False, show_params: bool = False ) -> Table: table = Table(show_header=True, show_edge=False, pad_edge=False, expand=True) if ranked: table.add_column("#", style="dim", width=3, justify="right") table.add_column("Tool", style="cyan", no_wrap=True) if show_params: table.add_column("Parameters", style="dim", no_wrap=True) table.add_column("Description", style="dim") for i, tool in enumerate(tools, 1): row = [tool["name"]] if show_params: row.append(_format_params(tool)) row.append(tool.get("description", "")) if ranked: row.insert(0, str(i)) table.add_row(*row) return table async def main(): async with Client("examples/search/server_regex.py") as client: console.print() console.rule("[bold]Regex Search Transform[/bold]") console.print() # Step 1: list_tools shows only synthetic tools console.print( "The server has 6 tools. RegexSearchTransform replaces them with " "just [bold]search_tools[/bold] and [bold]call_tool[/bold]:" ) console.print() tools = await client.list_tools() visible = [{"name": t.name, "description": t.description} for t in tools] console.print( Panel( _tool_table(visible), title="[bold]list_tools()[/bold]", title_align="left", border_style="blue", ) ) console.print() # Step 2: regex patterns discover tools console.print( "The LLM uses [bold]search_tools[/bold] with regex patterns " "to find tools by name:" ) console.print() result = await client.call_tool( "search_tools", {"pattern": "add|multiply|fibonacci"} ) found = _get_result(result) if isinstance(found, str): found = json.loads(found) console.print( Panel( _tool_table(found, show_params=True), title='[bold]search_tools[/bold] [dim]pattern="add|multiply|fibonacci"[/dim]', title_align="left", border_style="green", ) ) console.print() result = await client.call_tool("search_tools", {"pattern": "text|string|word"}) found = _get_result(result) if isinstance(found, str): found = json.loads(found) console.print( Panel( _tool_table(found, show_params=True), title='[bold]search_tools[/bold] [dim]pattern="text|string|word"[/dim]', title_align="left", border_style="green", ) ) console.print() # Step 3: call discovered tools console.print( "Then the LLM calls discovered tools through [bold]call_tool[/bold]:" ) console.print() result = await client.call_tool( "call_tool", {"name": "add", "arguments": {"a": 17, "b": 25}} ) console.print( Panel( f'call_tool(name="add", arguments={{"a": 17, "b": 25}})\n→ [bold green]{_get_result(result)}[/bold green]', title="[bold]call_tool()[/bold]", title_align="left", border_style="magenta", ) ) console.print() result = await client.call_tool( "call_tool", {"name": "reverse_string", "arguments": {"text": "hello world"}}, ) console.print( Panel( f'call_tool(name="reverse_string", arguments={{"text": "hello world"}})\n→ [bold green]{_get_result(result)}[/bold green]', title="[bold]call_tool()[/bold]", title_align="left", border_style="magenta", ) ) console.print() if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/search/client_regex.py", "license": "Apache License 2.0", "lines": 140, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:examples/search/server_bm25.py
"""Example: Search transforms with BM25 relevance ranking. BM25SearchTransform uses term-frequency/inverse-document-frequency scoring to rank tools by relevance to a natural language query. Unlike regex search (which requires the user to construct a pattern), BM25 handles queries like "work with text" or "do math" and returns the most relevant matches. The index is built lazily and rebuilt automatically when the tool catalog changes (e.g. tools added or removed between requests). Run with: uv run python examples/search/server_bm25.py """ import os from fastmcp import FastMCP from fastmcp.server.transforms.search import BM25SearchTransform mcp = FastMCP("BM25 Search Demo") @mcp.tool def add(a: int, b: int) -> int: """Add two numbers together.""" return a + b @mcp.tool def multiply(x: float, y: float) -> float: """Multiply two numbers.""" return x * y @mcp.tool def fibonacci(n: int) -> list[int]: """Generate the first n Fibonacci numbers.""" if n <= 0: return [] seq = [0, 1] while len(seq) < n: seq.append(seq[-1] + seq[-2]) return seq[:n] @mcp.tool def reverse_string(text: str) -> str: """Reverse a string.""" return text[::-1] @mcp.tool def word_count(text: str) -> int: """Count the number of words in a text.""" return len(text.split()) @mcp.tool def to_uppercase(text: str) -> str: """Convert text to uppercase.""" return text.upper() @mcp.tool def list_files(directory: str) -> list[str]: """List files in a directory.""" return os.listdir(directory) @mcp.tool def read_file(path: str) -> str: """Read the contents of a file.""" with open(path) as f: return f.read() # BM25 search with a higher result limit for this larger catalog. # The `always_visible` option keeps specific tools in list_tools output # alongside the search/call tools — useful for tools the LLM should # always know about. mcp.add_transform(BM25SearchTransform(max_results=5, always_visible=["list_files"])) if __name__ == "__main__": mcp.run()
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/search/server_bm25.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/search/server_regex.py
"""Example: Search transforms with regex pattern matching. When a server has many tools, listing them all at once can overwhelm an LLM's context window. Search transforms collapse the full tool catalog behind a search interface — clients see only `search_tools` and `call_tool`, and discover the real tools on demand. This example registers a handful of tools and applies RegexSearchTransform. Clients use `search_tools` with a regex pattern to find relevant tools, then `call_tool` to execute them by name. Run with: uv run python examples/search/server_regex.py """ from fastmcp import FastMCP from fastmcp.server.transforms.search import RegexSearchTransform mcp = FastMCP("Regex Search Demo") # Register a variety of tools across different domains. # With the search transform active, none of these appear in list_tools — # they're only discoverable via search. @mcp.tool def add(a: int, b: int) -> int: """Add two numbers together.""" return a + b @mcp.tool def multiply(x: float, y: float) -> float: """Multiply two numbers.""" return x * y @mcp.tool def fibonacci(n: int) -> list[int]: """Generate the first n Fibonacci numbers.""" if n <= 0: return [] seq = [0, 1] while len(seq) < n: seq.append(seq[-1] + seq[-2]) return seq[:n] @mcp.tool def reverse_string(text: str) -> str: """Reverse a string.""" return text[::-1] @mcp.tool def word_count(text: str) -> int: """Count the number of words in a text.""" return len(text.split()) @mcp.tool def to_uppercase(text: str) -> str: """Convert text to uppercase.""" return text.upper() # Apply the regex search transform. # max_results limits how many tools a single search returns. mcp.add_transform(RegexSearchTransform(max_results=3)) if __name__ == "__main__": mcp.run()
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/search/server_regex.py", "license": "Apache License 2.0", "lines": 51, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
PrefectHQ/fastmcp:src/fastmcp/server/transforms/catalog.py
"""Base class for transforms that need to read the real component catalog. Some transforms replace ``list_tools()`` output with synthetic components (e.g. a search interface) while still needing access to the *real* (auth-filtered) catalog at call time. ``CatalogTransform`` provides the bypass machinery so subclasses can call ``get_tool_catalog()`` without triggering their own replacement logic. Re-entrancy problem ------------------- When a synthetic tool handler calls ``get_tool_catalog()``, that calls ``ctx.fastmcp.list_tools()`` which re-enters the transform pipeline — including *this* transform's ``list_tools()``. If the subclass overrides ``list_tools()`` directly, the re-entrant call would hit the subclass's replacement logic again (returning synthetic tools instead of the real catalog). A ``super()`` call can't prevent this because Python can't short-circuit a method after ``super()`` returns. Solution: ``CatalogTransform`` owns ``list_tools()`` and uses a per-instance ``ContextVar`` to detect re-entrant calls. During bypass, it passes through to the base ``Transform.list_tools()`` (a no-op). Otherwise, it delegates to ``transform_tools()`` — the subclass hook where replacement logic lives. Same pattern for resources, prompts, and resource templates. This is *not* the same as the ``Provider._list_tools()`` convention (which produces raw components with no arguments). ``transform_tools()`` receives the current catalog and returns a transformed version. The distinct name avoids confusion between the two patterns. Usage:: class MyTransform(CatalogTransform): async def transform_tools(self, tools): return [self._make_search_tool()] def _make_search_tool(self): async def search(ctx: Context = None): real_tools = await self.get_tool_catalog(ctx) ... return Tool.from_function(fn=search, name="search") """ from __future__ import annotations import itertools from collections.abc import Sequence from contextvars import ContextVar from typing import TYPE_CHECKING from fastmcp.server.transforms import Transform from fastmcp.utilities.versions import dedupe_with_versions if TYPE_CHECKING: from fastmcp.prompts.prompt import Prompt from fastmcp.resources.resource import Resource from fastmcp.resources.template import ResourceTemplate from fastmcp.server.context import Context from fastmcp.tools.tool import Tool _instance_counter = itertools.count() class CatalogTransform(Transform): """Transform that needs access to the real component catalog. Subclasses override ``transform_tools()`` / ``transform_resources()`` / ``transform_prompts()`` / ``transform_resource_templates()`` instead of the ``list_*()`` methods. The base class owns ``list_*()`` and handles re-entrant bypass automatically — subclasses never see re-entrant calls from ``get_*_catalog()``. The ``get_*_catalog()`` methods fetch the real (auth-filtered) catalog by temporarily setting a bypass flag so that this transform's ``list_*()`` passes through without calling the subclass hook. """ def __init__(self) -> None: self._instance_id: int = next(_instance_counter) self._bypass: ContextVar[bool] = ContextVar( f"_catalog_bypass_{self._instance_id}", default=False ) # ------------------------------------------------------------------ # list_* (bypass-aware — subclasses override transform_* instead) # ------------------------------------------------------------------ async def list_tools(self, tools: Sequence[Tool]) -> Sequence[Tool]: if self._bypass.get(): return await super().list_tools(tools) return await self.transform_tools(tools) async def list_resources(self, resources: Sequence[Resource]) -> Sequence[Resource]: if self._bypass.get(): return await super().list_resources(resources) return await self.transform_resources(resources) async def list_resource_templates( self, templates: Sequence[ResourceTemplate] ) -> Sequence[ResourceTemplate]: if self._bypass.get(): return await super().list_resource_templates(templates) return await self.transform_resource_templates(templates) async def list_prompts(self, prompts: Sequence[Prompt]) -> Sequence[Prompt]: if self._bypass.get(): return await super().list_prompts(prompts) return await self.transform_prompts(prompts) # ------------------------------------------------------------------ # Subclass hooks (override these, not list_*) # ------------------------------------------------------------------ async def transform_tools(self, tools: Sequence[Tool]) -> Sequence[Tool]: """Transform the tool catalog. Override this method to replace, filter, or augment the tool listing. The default implementation passes through unchanged. Do NOT override ``list_tools()`` directly — the base class uses it to handle re-entrant bypass when ``get_tool_catalog()`` reads the real catalog. """ return tools async def transform_resources( self, resources: Sequence[Resource] ) -> Sequence[Resource]: """Transform the resource catalog. Override this method to replace, filter, or augment the resource listing. The default implementation passes through unchanged. Do NOT override ``list_resources()`` directly — the base class uses it to handle re-entrant bypass when ``get_resource_catalog()`` reads the real catalog. """ return resources async def transform_resource_templates( self, templates: Sequence[ResourceTemplate] ) -> Sequence[ResourceTemplate]: """Transform the resource template catalog. Override this method to replace, filter, or augment the template listing. The default implementation passes through unchanged. Do NOT override ``list_resource_templates()`` directly — the base class uses it to handle re-entrant bypass when ``get_resource_template_catalog()`` reads the real catalog. """ return templates async def transform_prompts(self, prompts: Sequence[Prompt]) -> Sequence[Prompt]: """Transform the prompt catalog. Override this method to replace, filter, or augment the prompt listing. The default implementation passes through unchanged. Do NOT override ``list_prompts()`` directly — the base class uses it to handle re-entrant bypass when ``get_prompt_catalog()`` reads the real catalog. """ return prompts # ------------------------------------------------------------------ # Catalog accessors # ------------------------------------------------------------------ async def get_tool_catalog( self, ctx: Context, *, run_middleware: bool = True ) -> Sequence[Tool]: """Fetch the real tool catalog, bypassing this transform. The result is deduplicated by name so that only the highest version of each tool is returned — matching what protocol handlers expose on the wire. Args: ctx: The current request context. run_middleware: Whether to run middleware on the inner call. Defaults to True because this is typically called from a tool handler where list_tools middleware has not yet run. """ token = self._bypass.set(True) try: tools = await ctx.fastmcp.list_tools(run_middleware=run_middleware) finally: self._bypass.reset(token) return dedupe_with_versions(tools, lambda t: t.name) async def get_resource_catalog( self, ctx: Context, *, run_middleware: bool = True ) -> Sequence[Resource]: """Fetch the real resource catalog, bypassing this transform. Args: ctx: The current request context. run_middleware: Whether to run middleware on the inner call. Defaults to True because this is typically called from a tool handler where list_resources middleware has not yet run. """ token = self._bypass.set(True) try: return await ctx.fastmcp.list_resources(run_middleware=run_middleware) finally: self._bypass.reset(token) async def get_prompt_catalog( self, ctx: Context, *, run_middleware: bool = True ) -> Sequence[Prompt]: """Fetch the real prompt catalog, bypassing this transform. Args: ctx: The current request context. run_middleware: Whether to run middleware on the inner call. Defaults to True because this is typically called from a tool handler where list_prompts middleware has not yet run. """ token = self._bypass.set(True) try: return await ctx.fastmcp.list_prompts(run_middleware=run_middleware) finally: self._bypass.reset(token) async def get_resource_template_catalog( self, ctx: Context, *, run_middleware: bool = True ) -> Sequence[ResourceTemplate]: """Fetch the real resource template catalog, bypassing this transform. Args: ctx: The current request context. run_middleware: Whether to run middleware on the inner call. Defaults to True because this is typically called from a tool handler where list_resource_templates middleware has not yet run. """ token = self._bypass.set(True) try: return await ctx.fastmcp.list_resource_templates( run_middleware=run_middleware ) finally: self._bypass.reset(token)
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/server/transforms/catalog.py", "license": "Apache License 2.0", "lines": 199, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
PrefectHQ/fastmcp:src/fastmcp/server/transforms/search/base.py
"""Base class for search transforms. Search transforms replace ``list_tools()`` output with a small set of synthetic tools — a search tool and a call-tool proxy — so LLMs can discover tools on demand instead of receiving the full catalog. All concrete search transforms (``RegexSearchTransform``, ``BM25SearchTransform``, etc.) inherit from ``BaseSearchTransform`` and implement ``_make_search_tool()`` and ``_search()`` to provide their specific search strategy. Example:: from fastmcp import FastMCP from fastmcp.server.transforms.search import RegexSearchTransform mcp = FastMCP("Server") @mcp.tool def add(a: int, b: int) -> int: ... @mcp.tool def multiply(x: float, y: float) -> float: ... # Clients now see only ``search_tools`` and ``call_tool``. # The original tools are discoverable via search. mcp.add_transform(RegexSearchTransform()) """ from abc import abstractmethod from collections.abc import Awaitable, Callable, Sequence from typing import Annotated, Any from fastmcp.server.context import Context from fastmcp.server.transforms import GetToolNext from fastmcp.server.transforms.catalog import CatalogTransform from fastmcp.tools.tool import Tool, ToolResult from fastmcp.utilities.versions import VersionSpec def _extract_searchable_text(tool: Tool) -> str: """Combine tool name, description, and parameter info into searchable text.""" parts = [tool.name] if tool.description: parts.append(tool.description) schema = tool.parameters if schema: properties = schema.get("properties", {}) for param_name, param_info in properties.items(): parts.append(param_name) if isinstance(param_info, dict): desc = param_info.get("description", "") if desc: parts.append(desc) return " ".join(parts) def serialize_tools_for_output_json(tools: Sequence[Tool]) -> list[dict[str, Any]]: """Serialize tools to the same dict format as ``list_tools`` output.""" return [ tool.to_mcp_tool().model_dump(mode="json", exclude_none=True) for tool in tools ] SearchResultSerializer = Callable[[Sequence[Tool]], Any | Awaitable[Any]] async def _invoke_serializer( serializer: SearchResultSerializer, tools: Sequence[Tool] ) -> Any: """Call a serializer and await the result if it returns a coroutine.""" result = serializer(tools) if isinstance(result, Awaitable): return await result return result def _union_type(branches: list[Any]) -> str: branch_types = list(dict.fromkeys(_schema_type(b) for b in branches)) if "null" not in branch_types: return " | ".join(branch_types) if branch_types else "any" non_null = [b for b in branch_types if b != "null"] if not non_null: return "null" return f"{' | '.join(non_null)}?" def _schema_type(schema: Any) -> str: # Intentionally heuristic: the goal is a concise readable label, not a # complete type system. Malformed schemas (e.g. {"type": ""}) → "any". if not isinstance(schema, dict): return "any" t = schema.get("type") if isinstance(t, str) and t: if t == "array": return f"{_schema_type(schema.get('items'))}[]" if t == "null": return "null" return t if "$ref" in schema: return "object" if "anyOf" in schema: return _union_type(schema["anyOf"]) if "oneOf" in schema: return _union_type(schema["oneOf"]) if "allOf" in schema: # allOf = intersection / Pydantic composed model → always an object return "object" return "object" if "properties" in schema else "any" def _schema_section(schema: dict[str, Any] | None, title: str) -> list[str]: lines = [f"**{title}**"] if not isinstance(schema, dict): lines.append("- `value` (any)") return lines props = schema.get("properties") raw_required = schema.get("required") req = set(raw_required) if isinstance(raw_required, list) else set() if props is None: # Not a properties-based schema — treat as a single unnamed value. lines.append(f"- `value` ({_schema_type(schema)})") return lines if not props: # Object schema with no properties — zero-argument tool. lines.append("*(no parameters)*") return lines for name, field in props.items(): required = ", required" if name in req else "" lines.append(f"- `{name}` ({_schema_type(field)}{required})") return lines def serialize_tools_for_output_markdown(tools: Sequence[Tool]) -> str: """Serialize tools to compact markdown, using ~65-70% fewer tokens than JSON.""" if not tools: return "No tools matched the query." blocks: list[str] = [] for tool in tools: lines = [f"### {tool.name}"] if tool.description: lines.extend(["", tool.description.strip()]) lines.extend(["", *_schema_section(tool.parameters, "Parameters")]) if tool.output_schema is not None: lines.extend(["", *_schema_section(tool.output_schema, "Returns")]) blocks.append("\n".join(lines)) return "\n\n".join(blocks) class BaseSearchTransform(CatalogTransform): """Replace the tool listing with a search interface. When this transform is active, ``list_tools()`` returns only: * Any tools listed in ``always_visible`` (pinned). * A **search tool** that finds tools matching a query. * A **call_tool** proxy that executes tools discovered via search. Hidden tools remain callable — ``get_tool()`` delegates unknown names downstream, so direct calls and the call-tool proxy both work. Search results respect the full auth pipeline: middleware, visibility transforms, and component-level auth checks all apply. Args: max_results: Maximum number of tools returned per search. always_visible: Tool names that stay in the ``list_tools`` output alongside the synthetic search/call tools. search_tool_name: Name of the generated search tool. call_tool_name: Name of the generated call-tool proxy. """ def __init__( self, *, max_results: int = 5, always_visible: list[str] | None = None, search_tool_name: str = "search_tools", call_tool_name: str = "call_tool", search_result_serializer: SearchResultSerializer | None = None, ) -> None: super().__init__() self._max_results = max_results self._always_visible = set(always_visible or []) self._search_tool_name = search_tool_name self._call_tool_name = call_tool_name self._search_result_serializer: SearchResultSerializer = ( search_result_serializer or serialize_tools_for_output_json ) # ------------------------------------------------------------------ # Transform interface # ------------------------------------------------------------------ async def transform_tools(self, tools: Sequence[Tool]) -> Sequence[Tool]: """Replace the catalog with pinned + synthetic search/call tools.""" pinned = [t for t in tools if t.name in self._always_visible] return [*pinned, self._make_search_tool(), self._make_call_tool()] async def get_tool( self, name: str, call_next: GetToolNext, *, version: VersionSpec | None = None ) -> Tool | None: """Intercept synthetic tool names; delegate everything else.""" if name == self._search_tool_name: return self._make_search_tool() if name == self._call_tool_name: return self._make_call_tool() return await call_next(name, version=version) # ------------------------------------------------------------------ # Synthetic tools # ------------------------------------------------------------------ @abstractmethod def _make_search_tool(self) -> Tool: """Create the search tool. Subclasses define the parameter schema.""" ... def _make_call_tool(self) -> Tool: """Create the call_tool proxy that executes discovered tools.""" transform = self async def call_tool( name: Annotated[str, "The name of the tool to call"], arguments: Annotated[ dict[str, Any] | None, "Arguments to pass to the tool" ] = None, ctx: Context = None, # type: ignore[assignment] ) -> ToolResult: """Call a tool by name with the given arguments. Use this to execute tools discovered via search_tools. """ if name in {transform._call_tool_name, transform._search_tool_name}: raise ValueError( f"'{name}' is a synthetic search tool and cannot be called via the call_tool proxy" ) return await ctx.fastmcp.call_tool(name, arguments) return Tool.from_function(fn=call_tool, name=self._call_tool_name) # ------------------------------------------------------------------ # Serialization # ------------------------------------------------------------------ async def _render_results(self, tools: Sequence[Tool]) -> Any: return await _invoke_serializer(self._search_result_serializer, tools) # ------------------------------------------------------------------ # Catalog access # ------------------------------------------------------------------ async def _get_visible_tools(self, ctx: Context) -> Sequence[Tool]: """Get the auth-filtered tool catalog, excluding pinned tools.""" tools = await self.get_tool_catalog(ctx) return [t for t in tools if t.name not in self._always_visible] # ------------------------------------------------------------------ # Abstract search # ------------------------------------------------------------------ @abstractmethod async def _search(self, tools: Sequence[Tool], query: str) -> Sequence[Tool]: """Search the given tools and return matches.""" ...
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/server/transforms/search/base.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/search/bm25.py
"""BM25-based search transform.""" import hashlib import math import re from collections.abc import Sequence from typing import Annotated, Any from fastmcp.server.context import Context from fastmcp.server.transforms.search.base import ( BaseSearchTransform, SearchResultSerializer, _extract_searchable_text, ) from fastmcp.tools.tool import Tool def _tokenize(text: str) -> list[str]: """Lowercase, split on non-alphanumeric, filter short tokens.""" return [t for t in re.split(r"[^a-z0-9]+", text.lower()) if len(t) > 1] class _BM25Index: """Self-contained BM25 Okapi index.""" def __init__(self, k1: float = 1.5, b: float = 0.75) -> None: self.k1 = k1 self.b = b self._doc_tokens: list[list[str]] = [] self._doc_lengths: list[int] = [] self._avg_dl: float = 0.0 self._df: dict[str, int] = {} self._tf: list[dict[str, int]] = [] self._n: int = 0 def build(self, documents: list[str]) -> None: self._doc_tokens = [_tokenize(doc) for doc in documents] self._doc_lengths = [len(tokens) for tokens in self._doc_tokens] self._n = len(documents) self._avg_dl = sum(self._doc_lengths) / self._n if self._n else 0.0 self._df = {} self._tf = [] for tokens in self._doc_tokens: tf: dict[str, int] = {} seen: set[str] = set() for token in tokens: tf[token] = tf.get(token, 0) + 1 if token not in seen: self._df[token] = self._df.get(token, 0) + 1 seen.add(token) self._tf.append(tf) def query(self, text: str, top_k: int) -> list[int]: """Return indices of top_k documents sorted by BM25 score.""" query_tokens = _tokenize(text) if not query_tokens or not self._n: return [] scores: list[float] = [0.0] * self._n for token in query_tokens: if token not in self._df: continue idf = math.log( (self._n - self._df[token] + 0.5) / (self._df[token] + 0.5) + 1.0 ) for i in range(self._n): tf = self._tf[i].get(token, 0) if tf == 0: continue dl = self._doc_lengths[i] numerator = tf * (self.k1 + 1) denominator = tf + self.k1 * (1 - self.b + self.b * dl / self._avg_dl) scores[i] += idf * numerator / denominator ranked = sorted(range(self._n), key=lambda i: scores[i], reverse=True) return [i for i in ranked[:top_k] if scores[i] > 0] def _catalog_hash(tools: Sequence[Tool]) -> str: """SHA256 hash of sorted tool searchable text for staleness detection.""" key = "|".join(sorted(_extract_searchable_text(t) for t in tools)) return hashlib.sha256(key.encode()).hexdigest() class BM25SearchTransform(BaseSearchTransform): """Search transform using BM25 Okapi relevance ranking. Maintains an in-memory index that is lazily rebuilt when the tool catalog changes (detected via a hash of tool names). """ def __init__( self, *, max_results: int = 5, always_visible: list[str] | None = None, search_tool_name: str = "search_tools", call_tool_name: str = "call_tool", search_result_serializer: SearchResultSerializer | None = None, ) -> None: super().__init__( max_results=max_results, always_visible=always_visible, search_tool_name=search_tool_name, call_tool_name=call_tool_name, search_result_serializer=search_result_serializer, ) self._index = _BM25Index() self._indexed_tools: Sequence[Tool] = () self._last_hash: str = "" def _make_search_tool(self) -> Tool: transform = self async def search_tools( query: Annotated[str, "Natural language query to search for tools"], ctx: Context = None, # type: ignore[assignment] ) -> str | list[dict[str, Any]]: """Search for tools using natural language. Returns matching tool definitions ranked by relevance, in the same format as list_tools. """ hidden = await transform._get_visible_tools(ctx) results = await transform._search(hidden, query) return await transform._render_results(results) return Tool.from_function(fn=search_tools, name=self._search_tool_name) async def _search(self, tools: Sequence[Tool], query: str) -> Sequence[Tool]: current_hash = _catalog_hash(tools) if current_hash != self._last_hash: documents = [_extract_searchable_text(t) for t in tools] new_index = _BM25Index(self._index.k1, self._index.b) new_index.build(documents) self._index, self._indexed_tools, self._last_hash = ( new_index, tools, current_hash, ) indices = self._index.query(query, self._max_results) return [self._indexed_tools[i] for i in indices]
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/server/transforms/search/bm25.py", "license": "Apache License 2.0", "lines": 120, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:src/fastmcp/server/transforms/search/regex.py
"""Regex-based search transform.""" import re from collections.abc import Sequence from typing import Annotated, Any from fastmcp.server.context import Context from fastmcp.server.transforms.search.base import ( BaseSearchTransform, _extract_searchable_text, ) from fastmcp.tools.tool import Tool class RegexSearchTransform(BaseSearchTransform): """Search transform using regex pattern matching. Tools are matched against their name, description, and parameter information using ``re.search`` with ``re.IGNORECASE``. """ def _make_search_tool(self) -> Tool: transform = self async def search_tools( pattern: Annotated[ str, "Regex pattern to match against tool names, descriptions, and parameters", ], ctx: Context = None, # type: ignore[assignment] ) -> str | list[dict[str, Any]]: """Search for tools matching a regex pattern. Returns matching tool definitions in the same format as list_tools. """ hidden = await transform._get_visible_tools(ctx) results = await transform._search(hidden, pattern) return await transform._render_results(results) return Tool.from_function(fn=search_tools, name=self._search_tool_name) async def _search(self, tools: Sequence[Tool], query: str) -> Sequence[Tool]: try: compiled = re.compile(query, re.IGNORECASE) except re.error: return [] matches: list[Tool] = [] for tool in tools: text = _extract_searchable_text(tool) if compiled.search(text): matches.append(tool) if len(matches) >= self._max_results: break return matches
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/server/transforms/search/regex.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:tests/server/transforms/test_catalog.py
"""Tests for CatalogTransform base class.""" from __future__ import annotations import ast from collections.abc import Sequence from mcp.types import TextContent from fastmcp import FastMCP from fastmcp.server.context import Context from fastmcp.server.transforms import GetToolNext from fastmcp.server.transforms.catalog import CatalogTransform from fastmcp.server.transforms.version_filter import VersionFilter from fastmcp.tools.tool import Tool from fastmcp.utilities.versions import VersionSpec # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def _make_versioned_tool(name: str, version: str) -> Tool: """Create a tool with a specific version for testing.""" async def _fn() -> str: return f"{name}@{version}" return Tool.from_function(fn=_fn, name=name, version=version) class CatalogReader(CatalogTransform): """Minimal CatalogTransform that exposes get_tool_catalog via a tool. After calling the ``read_catalog`` tool, the full catalog is available on ``self.last_catalog`` for assertions beyond tool names. """ def __init__(self) -> None: super().__init__() self.last_catalog: Sequence[Tool] = [] async def transform_tools(self, tools: Sequence[Tool]) -> Sequence[Tool]: return [self._make_reader_tool()] async def get_tool( self, name: str, call_next: GetToolNext, *, version: VersionSpec | None = None ) -> Tool | None: if name == "read_catalog": return self._make_reader_tool() return await call_next(name, version=version) def _make_reader_tool(self) -> Tool: transform = self async def read_catalog(ctx: Context = None) -> list[str]: # type: ignore[assignment] """Return names of tools visible in the catalog.""" transform.last_catalog = await transform.get_tool_catalog(ctx) return [t.name for t in transform.last_catalog] return Tool.from_function(fn=read_catalog, name="read_catalog") class ReplacingTransform(CatalogTransform): """Minimal subclass that replaces tools with a synthetic tool. Uses ``get_tool_catalog()`` to read the real catalog inside the synthetic tool's handler, verifying that the bypass mechanism works. """ async def transform_tools(self, tools: Sequence[Tool]) -> Sequence[Tool]: return [self._make_synthetic_tool()] async def get_tool( self, name: str, call_next: GetToolNext, *, version: VersionSpec | None = None ) -> Tool | None: if name == "count_tools": return self._make_synthetic_tool() return await call_next(name, version=version) def _make_synthetic_tool(self) -> Tool: transform = self async def count_tools(ctx: Context = None) -> int: # type: ignore[assignment] """Return the number of real tools in the catalog.""" catalog = await transform.get_tool_catalog(ctx) return len(catalog) return Tool.from_function(fn=count_tools, name="count_tools") class TestCatalogTransformBypass: async def test_list_tools_replaced_by_subclass(self): mcp = FastMCP("test") @mcp.tool def add(a: int, b: int) -> int: return a + b @mcp.tool def multiply(x: float, y: float) -> float: return x * y mcp.add_transform(ReplacingTransform()) tools = await mcp.list_tools() names = {t.name for t in tools} assert names == {"count_tools"} async def test_get_tool_catalog_returns_real_tools(self): mcp = FastMCP("test") @mcp.tool def add(a: int, b: int) -> int: return a + b @mcp.tool def multiply(x: float, y: float) -> float: return x * y mcp.add_transform(ReplacingTransform()) result = await mcp.call_tool("count_tools", {}) assert any("2" in c.text for c in result.content if isinstance(c, TextContent)) async def test_multiple_instances_have_independent_bypass(self): """Each CatalogTransform instance has its own bypass ContextVar.""" t1 = ReplacingTransform() t2 = ReplacingTransform() assert t1._instance_id != t2._instance_id assert t1._bypass is not t2._bypass class TestCatalogDeduplication: """get_tool_catalog() deduplicates versioned tools, keeping only the highest.""" async def test_returns_highest_version_only(self): mcp = FastMCP("test") mcp.add_tool(_make_versioned_tool("greet", "1")) mcp.add_tool(_make_versioned_tool("greet", "2")) mcp.add_tool(_make_versioned_tool("greet", "3")) reader = CatalogReader() mcp.add_transform(reader) result = await mcp.call_tool("read_catalog", {}) names = _extract_result(result) assert names == ["greet"] async def test_version_metadata_injected(self): """Highest-version tool has meta.fastmcp.versions listing all available.""" mcp = FastMCP("test") mcp.add_tool(_make_versioned_tool("greet", "1")) mcp.add_tool(_make_versioned_tool("greet", "3")) reader = CatalogReader() mcp.add_transform(reader) await mcp.call_tool("read_catalog", {}) assert len(reader.last_catalog) == 1 tool = reader.last_catalog[0] assert tool.name == "greet" assert tool.version == "3" assert tool.meta is not None versions = tool.meta["fastmcp"]["versions"] assert versions == ["3", "1"] async def test_mixed_versioned_and_unversioned(self): mcp = FastMCP("test") @mcp.tool def standalone() -> str: return "hi" mcp.add_tool(_make_versioned_tool("greet", "1")) mcp.add_tool(_make_versioned_tool("greet", "2")) reader = CatalogReader() mcp.add_transform(reader) result = await mcp.call_tool("read_catalog", {}) names = sorted(_extract_result(result)) assert names == ["greet", "standalone"] async def test_version_filter_applied_before_catalog(self): """A VersionFilter added before the CatalogTransform restricts what the catalog sees.""" mcp = FastMCP("test") mcp.add_tool(_make_versioned_tool("greet", "1")) mcp.add_tool(_make_versioned_tool("greet", "2")) mcp.add_tool(_make_versioned_tool("greet", "3")) # Filter keeps only versions < 3 — so v1 and v2 survive, v3 is excluded. mcp.add_transform(VersionFilter(version_lt="3")) reader = CatalogReader() mcp.add_transform(reader) await mcp.call_tool("read_catalog", {}) assert len(reader.last_catalog) == 1 tool = reader.last_catalog[0] assert tool.name == "greet" assert tool.version == "2" class TestCatalogVisibility: """get_tool_catalog() respects visibility (disabled tools are excluded).""" async def test_disabled_tool_excluded(self): mcp = FastMCP("test") @mcp.tool def public() -> str: return "visible" @mcp.tool def secret() -> str: return "hidden" mcp.disable(names={"secret"}, components={"tool"}) reader = CatalogReader() mcp.add_transform(reader) result = await mcp.call_tool("read_catalog", {}) names = _extract_result(result) assert names == ["public"] class TestCatalogAuth: """get_tool_catalog() respects tool-level auth filtering.""" async def test_auth_rejected_tool_excluded(self): mcp = FastMCP("test") @mcp.tool def public() -> str: return "visible" @mcp.tool(auth=lambda _ctx: False) def protected() -> str: return "hidden" reader = CatalogReader() mcp.add_transform(reader) result = await mcp.call_tool("read_catalog", {}) names = _extract_result(result) assert names == ["public"] # --------------------------------------------------------------------------- # Test helpers # --------------------------------------------------------------------------- def _extract_result(result: object) -> list[str]: """Extract the list of names from a call_tool ToolResult.""" for c in result.content: # type: ignore[union-attr] if isinstance(c, TextContent): return ast.literal_eval(c.text) raise AssertionError("No text content found")
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/transforms/test_catalog.py", "license": "Apache License 2.0", "lines": 187, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/server/transforms/test_search.py
"""Tests for search transforms.""" from __future__ import annotations from collections.abc import Sequence from typing import Any from unittest.mock import MagicMock import mcp.types as mcp_types import pytest from mcp.types import TextContent from fastmcp import Client, FastMCP from fastmcp.server.context import Context from fastmcp.server.middleware.middleware import CallNext, Middleware, MiddlewareContext from fastmcp.server.transforms import Visibility from fastmcp.server.transforms.search.bm25 import ( BM25SearchTransform, _BM25Index, _catalog_hash, ) from fastmcp.server.transforms.search.regex import RegexSearchTransform from fastmcp.tools.tool import Tool, ToolResult # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def _parse_tool_result(result: ToolResult) -> list[dict[str, Any]]: """Extract tool list from a ToolResult's structured content.""" assert result.structured_content is not None return result.structured_content["result"] def _make_server_with_tools() -> FastMCP: mcp = FastMCP("test") @mcp.tool def add(a: int, b: int) -> int: """Add two numbers together.""" return a + b @mcp.tool def multiply(x: float, y: float) -> float: """Multiply two numbers.""" return x * y @mcp.tool def search_database(query: str, limit: int = 10) -> str: """Search the database for records matching the query.""" return f"results for {query}" @mcp.tool def delete_record(record_id: str) -> str: """Delete a record from the database by its ID.""" return f"deleted {record_id}" @mcp.tool def send_email(to: str, subject: str, body: str) -> str: """Send an email to the given recipient.""" return "sent" return mcp # --------------------------------------------------------------------------- # Shared behavior tests (parameterized across both transforms) # --------------------------------------------------------------------------- class TestBaseTransformBehavior: """Tests for behavior shared by all search transforms.""" async def test_list_tools_hides_tools_regex(self): mcp = _make_server_with_tools() mcp.add_transform(RegexSearchTransform()) tools = await mcp.list_tools() names = {t.name for t in tools} assert names == {"search_tools", "call_tool"} async def test_list_tools_hides_tools_bm25(self): mcp = _make_server_with_tools() mcp.add_transform(BM25SearchTransform()) tools = await mcp.list_tools() names = {t.name for t in tools} assert names == {"search_tools", "call_tool"} async def test_always_visible_pins_tools(self): mcp = _make_server_with_tools() mcp.add_transform(RegexSearchTransform(always_visible=["add"])) tools = await mcp.list_tools() names = {t.name for t in tools} assert "add" in names assert "search_tools" in names assert "call_tool" in names assert "multiply" not in names async def test_get_tool_returns_synthetic(self): mcp = _make_server_with_tools() mcp.add_transform(RegexSearchTransform()) search = await mcp.get_tool("search_tools") assert search is not None assert search.name == "search_tools" call = await mcp.get_tool("call_tool") assert call is not None assert call.name == "call_tool" async def test_get_tool_passes_through_hidden(self): mcp = _make_server_with_tools() mcp.add_transform(RegexSearchTransform()) tool = await mcp.get_tool("add") assert tool is not None assert tool.name == "add" async def test_call_tool_proxy_executes(self): mcp = _make_server_with_tools() mcp.add_transform(RegexSearchTransform()) # Need to call list_tools to populate catalog await mcp.list_tools() result = await mcp.call_tool( "call_tool", {"name": "add", "arguments": {"a": 2, "b": 3}} ) assert any("5" in c.text for c in result.content if isinstance(c, TextContent)) async def test_custom_tool_names(self): mcp = _make_server_with_tools() mcp.add_transform( RegexSearchTransform( search_tool_name="find_tools", call_tool_name="run_tool", ) ) tools = await mcp.list_tools() names = {t.name for t in tools} assert names == {"find_tools", "run_tool"} assert await mcp.get_tool("find_tools") is not None assert await mcp.get_tool("run_tool") is not None async def test_search_respects_visibility_filtering(self): """Tools disabled via Visibility transform should not appear in search.""" mcp = _make_server_with_tools() mcp.add_transform(Visibility(False, names={"delete_record"})) mcp.add_transform(RegexSearchTransform()) tools = await mcp.list_tools() names = {t.name for t in tools} assert "delete_record" not in names result = await mcp.call_tool("search_tools", {"pattern": "delete"}) found = _parse_tool_result(result) assert not any(t["name"] == "delete_record" for t in found) async def test_search_respects_auth_middleware(self): """Tools filtered by auth middleware should not appear in search.""" class BlockAdminTools(Middleware): async def on_list_tools( self, context: MiddlewareContext[mcp_types.ListToolsRequest], call_next: CallNext[mcp_types.ListToolsRequest, Sequence[Tool]], ) -> Sequence[Tool]: tools = await call_next(context) return [t for t in tools if t.name != "delete_record"] mcp = _make_server_with_tools() mcp.add_middleware(BlockAdminTools()) mcp.add_transform(RegexSearchTransform()) async with Client(mcp) as client: tools = await client.list_tools() names = {t.name for t in tools} assert "delete_record" not in names assert "search_tools" in names result = await client.call_tool("search_tools", {"pattern": "delete"}) found = _parse_tool_result(result) assert not any(t["name"] == "delete_record" for t in found) async def test_search_respects_session_visibility(self): """Tools disabled via session visibility should not appear in search.""" mcp = _make_server_with_tools() mcp.add_transform(RegexSearchTransform()) @mcp.tool async def disable_delete(ctx: Context) -> str: """Helper tool to disable delete_record for this session.""" await ctx.disable_components(names={"delete_record"}) return "disabled" async with Client(mcp) as client: # Before disabling, search should find delete_record result = await client.call_tool("search_tools", {"pattern": "delete"}) found = _parse_tool_result(result) assert any(t["name"] == "delete_record" for t in found) # Disable via session visibility await client.call_tool("disable_delete", {}) # After disabling, search should NOT find it result = await client.call_tool("search_tools", {"pattern": "delete"}) found = _parse_tool_result(result) assert not any(t["name"] == "delete_record" for t in found) # --------------------------------------------------------------------------- # Regex-specific tests # --------------------------------------------------------------------------- class TestRegexSearch: async def test_search_by_name(self): mcp = _make_server_with_tools() mcp.add_transform(RegexSearchTransform()) await mcp.list_tools() result = await mcp.call_tool("search_tools", {"pattern": "add"}) tools = _parse_tool_result(result) assert any(t["name"] == "add" for t in tools) async def test_search_by_description(self): mcp = _make_server_with_tools() mcp.add_transform(RegexSearchTransform()) await mcp.list_tools() result = await mcp.call_tool("search_tools", {"pattern": "email"}) tools = _parse_tool_result(result) assert any(t["name"] == "send_email" for t in tools) async def test_search_by_param_name(self): mcp = _make_server_with_tools() mcp.add_transform(RegexSearchTransform()) await mcp.list_tools() result = await mcp.call_tool("search_tools", {"pattern": "record_id"}) tools = _parse_tool_result(result) assert any(t["name"] == "delete_record" for t in tools) async def test_search_by_param_description(self): mcp = _make_server_with_tools() mcp.add_transform(RegexSearchTransform()) await mcp.list_tools() result = await mcp.call_tool("search_tools", {"pattern": "recipient"}) tools = _parse_tool_result(result) assert any(t["name"] == "send_email" for t in tools) async def test_search_or_pattern(self): mcp = _make_server_with_tools() mcp.add_transform(RegexSearchTransform(max_results=10)) await mcp.list_tools() result = await mcp.call_tool("search_tools", {"pattern": "add|multiply"}) tools = _parse_tool_result(result) names = {t["name"] for t in tools} assert "add" in names assert "multiply" in names async def test_search_case_insensitive(self): mcp = _make_server_with_tools() mcp.add_transform(RegexSearchTransform()) await mcp.list_tools() result = await mcp.call_tool("search_tools", {"pattern": "ADD"}) tools = _parse_tool_result(result) assert any(t["name"] == "add" for t in tools) async def test_search_invalid_pattern(self): mcp = _make_server_with_tools() mcp.add_transform(RegexSearchTransform()) await mcp.list_tools() result = await mcp.call_tool("search_tools", {"pattern": "[invalid"}) tools = _parse_tool_result(result) assert tools == [] async def test_search_max_results(self): mcp = _make_server_with_tools() mcp.add_transform(RegexSearchTransform(max_results=2)) await mcp.list_tools() # Match everything result = await mcp.call_tool("search_tools", {"pattern": ".*"}) tools = _parse_tool_result(result) assert len(tools) == 2 async def test_search_no_matches(self): mcp = _make_server_with_tools() mcp.add_transform(RegexSearchTransform()) await mcp.list_tools() result = await mcp.call_tool("search_tools", {"pattern": "zzz_nonexistent"}) tools = _parse_tool_result(result) assert tools == [] async def test_search_returns_full_schema(self): mcp = _make_server_with_tools() mcp.add_transform(RegexSearchTransform()) await mcp.list_tools() result = await mcp.call_tool("search_tools", {"pattern": "add"}) tools = _parse_tool_result(result) add_tool = next(t for t in tools if t["name"] == "add") assert "inputSchema" in add_tool assert "properties" in add_tool["inputSchema"] # --------------------------------------------------------------------------- # BM25-specific tests # --------------------------------------------------------------------------- class TestBM25Search: async def test_search_relevance(self): mcp = _make_server_with_tools() mcp.add_transform(BM25SearchTransform()) await mcp.list_tools() result = await mcp.call_tool("search_tools", {"query": "database"}) tools = _parse_tool_result(result) # Database tools should rank highest assert len(tools) > 0 names = {t["name"] for t in tools} assert "search_database" in names async def test_search_database_tools(self): mcp = _make_server_with_tools() mcp.add_transform(BM25SearchTransform()) await mcp.list_tools() result = await mcp.call_tool( "search_tools", {"query": "delete records from database"} ) tools = _parse_tool_result(result) assert len(tools) > 0 # delete_record should be highly relevant assert tools[0]["name"] == "delete_record" async def test_search_max_results(self): mcp = _make_server_with_tools() mcp.add_transform(BM25SearchTransform(max_results=2)) await mcp.list_tools() result = await mcp.call_tool("search_tools", {"query": "number"}) tools = _parse_tool_result(result) assert len(tools) <= 2 async def test_search_no_matches(self): mcp = _make_server_with_tools() mcp.add_transform(BM25SearchTransform()) await mcp.list_tools() result = await mcp.call_tool("search_tools", {"query": "zzz_nonexistent_xyz"}) tools = _parse_tool_result(result) assert tools == [] async def test_index_rebuilds_on_catalog_change(self): """When a new tool is added, the next list_tools + search sees it.""" mcp = _make_server_with_tools() mcp.add_transform(BM25SearchTransform()) await mcp.list_tools() # Search before adding tool result = await mcp.call_tool("search_tools", {"query": "weather forecast"}) tools = _parse_tool_result(result) assert not any(t["name"] == "get_weather" for t in tools) # Add a new tool @mcp.tool def get_weather(city: str) -> str: """Get the weather forecast for a city.""" return f"sunny in {city}" # Must call list_tools to refresh the catalog cache await mcp.list_tools() result = await mcp.call_tool("search_tools", {"query": "weather forecast"}) tools = _parse_tool_result(result) assert any(t["name"] == "get_weather" for t in tools) async def test_search_empty_query(self): mcp = _make_server_with_tools() mcp.add_transform(BM25SearchTransform()) await mcp.list_tools() result = await mcp.call_tool("search_tools", {"query": ""}) tools = _parse_tool_result(result) assert tools == [] async def test_search_returns_full_schema(self): mcp = _make_server_with_tools() mcp.add_transform(BM25SearchTransform()) await mcp.list_tools() result = await mcp.call_tool("search_tools", {"query": "add numbers"}) tools = _parse_tool_result(result) add_tool = next(t for t in tools if t["name"] == "add") assert "inputSchema" in add_tool assert "properties" in add_tool["inputSchema"] # --------------------------------------------------------------------------- # BM25 index unit tests # --------------------------------------------------------------------------- class TestBM25Index: def test_basic_ranking(self): index = _BM25Index() index.build( [ "search database query records", "add two numbers together", "send email recipient subject", ] ) results = index.query("database records", 3) assert results[0] == 0 # Database doc should rank first def test_empty_corpus(self): index = _BM25Index() index.build([]) assert index.query("anything", 5) == [] def test_no_matching_tokens(self): index = _BM25Index() index.build(["alpha beta gamma"]) assert index.query("zzz", 5) == [] # --------------------------------------------------------------------------- # call_tool self-reference guard # --------------------------------------------------------------------------- class TestCallToolGuard: async def test_call_tool_proxy_rejects_itself(self): """Calling call_tool(name='call_tool') must not recurse infinitely.""" mcp = _make_server_with_tools() mcp.add_transform(RegexSearchTransform()) async with Client(mcp) as client: with pytest.raises(Exception): await client.call_tool( "call_tool", {"name": "call_tool", "arguments": {}} ) async def test_call_tool_proxy_rejects_search_tool(self): """Calling call_tool(name='search_tools') must be rejected.""" mcp = _make_server_with_tools() mcp.add_transform(RegexSearchTransform()) async with Client(mcp) as client: with pytest.raises(Exception): await client.call_tool( "call_tool", {"name": "search_tools", "arguments": {"pattern": "add"}}, ) async def test_call_tool_proxy_rejects_custom_names(self): """Guard works when synthetic tools have custom names.""" mcp = _make_server_with_tools() mcp.add_transform( RegexSearchTransform( search_tool_name="find_tools", call_tool_name="run_tool" ) ) async with Client(mcp) as client: with pytest.raises(Exception): await client.call_tool( "run_tool", {"name": "run_tool", "arguments": {}} ) with pytest.raises(Exception): await client.call_tool( "run_tool", {"name": "find_tools", "arguments": {"pattern": "add"}} ) # --------------------------------------------------------------------------- # catalog hash staleness # --------------------------------------------------------------------------- class TestCatalogHash: def test_hash_differs_for_same_name_different_description(self): """Hash must change when a tool's description changes, not just its name.""" tool_a = MagicMock() tool_a.name = "search" tool_a.description = "find records in the database" tool_a.parameters = {} tool_b = MagicMock() tool_b.name = "search" tool_b.description = "send an email to a recipient" tool_b.parameters = {} assert _catalog_hash([tool_a]) != _catalog_hash([tool_b])
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/transforms/test_search.py", "license": "Apache License 2.0", "lines": 395, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/utilities/openapi/test_propertynames_ref_rewrite.py
from fastmcp.utilities.openapi.schemas import _replace_ref_with_defs def test_replace_ref_with_defs_rewrites_propertyNames_ref(): """ Regression test for issue #3303. When using dict[StrEnum, Model], Pydantic generates: { "type": "object", "propertyNames": {"$ref": "#/components/schemas/Category"}, "additionalProperties": {"$ref": "#/components/schemas/ItemInfo"} } _replace_ref_with_defs should rewrite BOTH refs to #/$defs/. """ schema = { "type": "object", "propertyNames": {"$ref": "#/components/schemas/Category"}, "additionalProperties": {"$ref": "#/components/schemas/ItemInfo"}, } result = _replace_ref_with_defs(schema) # additionalProperties ref is rewritten assert result["additionalProperties"]["$ref"] == "#/$defs/ItemInfo" # propertyNames ref must also be rewritten (this was the bug) assert result["propertyNames"]["$ref"] == "#/$defs/Category" # Ensure no dangling OpenAPI refs remain assert "#/components/schemas/" not in str(result)
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/utilities/openapi/test_propertynames_ref_rewrite.py", "license": "Apache License 2.0", "lines": 24, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/server/auth/providers/test_http_client.py
"""Tests for http_client parameter on token verifiers. Verifies that all token verifiers accept an optional httpx.AsyncClient for connection pooling (issues #3287 and #3293). """ import time import httpx import pytest from pytest_httpx import HTTPXMock from fastmcp.server.auth.providers.introspection import IntrospectionTokenVerifier from fastmcp.server.auth.providers.jwt import JWTVerifier, RSAKeyPair class TestIntrospectionHttpClient: """Test http_client parameter on IntrospectionTokenVerifier.""" @pytest.fixture def shared_client(self) -> httpx.AsyncClient: return httpx.AsyncClient(timeout=30) def test_stores_http_client(self, shared_client: httpx.AsyncClient): verifier = IntrospectionTokenVerifier( introspection_url="https://auth.example.com/introspect", client_id="test", client_secret="secret", http_client=shared_client, ) assert verifier._http_client is shared_client def test_default_http_client_is_none(self): verifier = IntrospectionTokenVerifier( introspection_url="https://auth.example.com/introspect", client_id="test", client_secret="secret", ) assert verifier._http_client is None async def test_uses_provided_client( self, shared_client: httpx.AsyncClient, httpx_mock: HTTPXMock ): """When http_client is provided, it should be used for requests.""" httpx_mock.add_response( url="https://auth.example.com/introspect", method="POST", json={ "active": True, "client_id": "user-1", "scope": "read", "exp": int(time.time()) + 3600, }, ) verifier = IntrospectionTokenVerifier( introspection_url="https://auth.example.com/introspect", client_id="test", client_secret="secret", http_client=shared_client, ) result = await verifier.verify_token("tok") assert result is not None assert result.client_id == "user-1" async def test_client_not_closed_after_call( self, shared_client: httpx.AsyncClient, httpx_mock: HTTPXMock ): """User-provided client must not be closed by the verifier.""" httpx_mock.add_response( url="https://auth.example.com/introspect", method="POST", json={ "active": True, "client_id": "user-1", "scope": "read", "exp": int(time.time()) + 3600, }, ) verifier = IntrospectionTokenVerifier( introspection_url="https://auth.example.com/introspect", client_id="test", client_secret="secret", http_client=shared_client, ) await verifier.verify_token("tok") # Client should still be open — not closed by the verifier assert not shared_client.is_closed async def test_reuses_client_across_calls( self, shared_client: httpx.AsyncClient, httpx_mock: HTTPXMock ): """Same client instance should be reused across multiple verify_token calls.""" for _ in range(3): httpx_mock.add_response( url="https://auth.example.com/introspect", method="POST", json={ "active": True, "client_id": "user-1", "scope": "read", "exp": int(time.time()) + 3600, }, ) verifier = IntrospectionTokenVerifier( introspection_url="https://auth.example.com/introspect", client_id="test", client_secret="secret", http_client=shared_client, ) for _ in range(3): result = await verifier.verify_token("tok") assert result is not None assert not shared_client.is_closed class TestJWTVerifierHttpClient: """Test http_client parameter on JWTVerifier.""" @pytest.fixture(scope="class") def rsa_key_pair(self) -> RSAKeyPair: return RSAKeyPair.generate() @pytest.fixture def shared_client(self) -> httpx.AsyncClient: return httpx.AsyncClient(timeout=30) def test_stores_http_client(self, shared_client: httpx.AsyncClient): verifier = JWTVerifier( jwks_uri="https://auth.example.com/.well-known/jwks.json", http_client=shared_client, ) assert verifier._http_client is shared_client def test_default_http_client_is_none(self): verifier = JWTVerifier( jwks_uri="https://auth.example.com/.well-known/jwks.json", ) assert verifier._http_client is None async def test_jwks_fetch_uses_provided_client( self, rsa_key_pair: RSAKeyPair, shared_client: httpx.AsyncClient, httpx_mock: HTTPXMock, ): """When http_client is provided, JWKS fetches should use it.""" from authlib.jose import JsonWebKey # Build a JWKS response from the RSA key pair public_key_obj = JsonWebKey.import_key(rsa_key_pair.public_key) jwk_dict = dict(public_key_obj.as_dict()) jwk_dict["kid"] = "test-key-1" jwk_dict["use"] = "sig" jwk_dict["alg"] = "RS256" httpx_mock.add_response( url="https://auth.example.com/.well-known/jwks.json", json={"keys": [jwk_dict]}, ) verifier = JWTVerifier( jwks_uri="https://auth.example.com/.well-known/jwks.json", issuer="https://auth.example.com", http_client=shared_client, ) token = rsa_key_pair.create_token( issuer="https://auth.example.com", kid="test-key-1", ) result = await verifier.verify_token(token) assert result is not None assert not shared_client.is_closed def test_ssrf_safe_rejects_http_client_with_jwks( self, shared_client: httpx.AsyncClient, ): """ssrf_safe=True and http_client cannot be used together with JWKS.""" with pytest.raises(ValueError, match="cannot be used with ssrf_safe=True"): JWTVerifier( jwks_uri="https://auth.example.com/.well-known/jwks.json", ssrf_safe=True, http_client=shared_client, ) def test_ssrf_safe_allows_http_client_with_static_key( self, rsa_key_pair: RSAKeyPair, shared_client: httpx.AsyncClient, ): """ssrf_safe with http_client is allowed when using static public_key (no HTTP).""" # This should NOT raise — static key means no JWKS fetching verifier = JWTVerifier( public_key=rsa_key_pair.public_key, ssrf_safe=True, http_client=shared_client, ) assert verifier._http_client is shared_client assert verifier.ssrf_safe is True class TestGitHubHttpClient: """Test http_client parameter on GitHubTokenVerifier.""" def test_stores_http_client(self): from fastmcp.server.auth.providers.github import GitHubTokenVerifier client = httpx.AsyncClient() verifier = GitHubTokenVerifier(http_client=client) assert verifier._http_client is client async def test_uses_provided_client(self, httpx_mock: HTTPXMock): from fastmcp.server.auth.providers.github import GitHubTokenVerifier client = httpx.AsyncClient() httpx_mock.add_response( url="https://api.github.com/user", json={"id": 123, "login": "testuser"}, ) httpx_mock.add_response( url="https://api.github.com/user/repos", headers={"x-oauth-scopes": "user,repo"}, json=[], ) verifier = GitHubTokenVerifier(http_client=client) result = await verifier.verify_token("ghp_test") assert result is not None assert not client.is_closed class TestDiscordHttpClient: """Test http_client parameter on DiscordTokenVerifier.""" def test_stores_http_client(self): from fastmcp.server.auth.providers.discord import DiscordTokenVerifier client = httpx.AsyncClient() verifier = DiscordTokenVerifier( expected_client_id="test-client-id", http_client=client, ) assert verifier._http_client is client class TestGoogleHttpClient: """Test http_client parameter on GoogleTokenVerifier.""" def test_stores_http_client(self): from fastmcp.server.auth.providers.google import GoogleTokenVerifier client = httpx.AsyncClient() verifier = GoogleTokenVerifier(http_client=client) assert verifier._http_client is client class TestWorkOSHttpClient: """Test http_client parameter on WorkOSTokenVerifier.""" def test_stores_http_client(self): from fastmcp.server.auth.providers.workos import WorkOSTokenVerifier client = httpx.AsyncClient() verifier = WorkOSTokenVerifier( authkit_domain="https://test.authkit.app", http_client=client, ) assert verifier._http_client is client class TestProviderHttpClientPassthrough: """Test that convenience providers pass http_client to their verifiers.""" def test_github_provider_threads_http_client(self): from fastmcp.server.auth.providers.github import ( GitHubProvider, GitHubTokenVerifier, ) client = httpx.AsyncClient() provider = GitHubProvider( client_id="test", client_secret="secret", base_url="https://example.com", http_client=client, ) # OAuthProxy stores token verifier as _token_validator verifier = provider._token_validator assert isinstance(verifier, GitHubTokenVerifier) assert verifier._http_client is client def test_discord_provider_threads_http_client(self): from fastmcp.server.auth.providers.discord import ( DiscordProvider, DiscordTokenVerifier, ) client = httpx.AsyncClient() provider = DiscordProvider( client_id="test", client_secret="secret", base_url="https://example.com", http_client=client, ) verifier = provider._token_validator assert isinstance(verifier, DiscordTokenVerifier) assert verifier._http_client is client def test_google_provider_threads_http_client(self): from fastmcp.server.auth.providers.google import ( GoogleProvider, GoogleTokenVerifier, ) client = httpx.AsyncClient() provider = GoogleProvider( client_id="test", client_secret="secret", base_url="https://example.com", http_client=client, ) verifier = provider._token_validator assert isinstance(verifier, GoogleTokenVerifier) assert verifier._http_client is client def test_workos_provider_threads_http_client(self): from fastmcp.server.auth.providers.workos import ( WorkOSProvider, WorkOSTokenVerifier, ) client = httpx.AsyncClient() provider = WorkOSProvider( client_id="test", client_secret="secret", authkit_domain="https://test.authkit.app", base_url="https://example.com", http_client=client, ) verifier = provider._token_validator assert isinstance(verifier, WorkOSTokenVerifier) assert verifier._http_client is client def test_azure_provider_threads_http_client(self): from fastmcp.server.auth.providers.azure import AzureProvider from fastmcp.server.auth.providers.jwt import JWTVerifier client = httpx.AsyncClient() provider = AzureProvider( client_id="test-client-id", client_secret="secret", tenant_id="test-tenant-id", required_scopes=["read"], base_url="https://example.com", http_client=client, ) verifier = provider._token_validator assert isinstance(verifier, JWTVerifier) assert verifier._http_client is client
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/auth/providers/test_http_client.py", "license": "Apache License 2.0", "lines": 304, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:scripts/benchmark_imports.py
#!/usr/bin/env python """Benchmark import times for fastmcp and its dependency chain. Each measurement runs in a fresh subprocess so there's no shared module cache. Incremental costs are measured by pre-importing dependencies, so we can see what each module truly adds. Usage: uv run python scripts/benchmark_imports.py uv run python scripts/benchmark_imports.py --runs 10 uv run python scripts/benchmark_imports.py --json """ from __future__ import annotations import argparse import json import subprocess import sys from dataclasses import dataclass @dataclass class BenchmarkCase: label: str stmt: str prereqs: str = "" group: str = "" CASES = [ # --- Floor --- BenchmarkCase("pydantic", "import pydantic", group="floor"), BenchmarkCase("mcp", "import mcp", group="floor"), BenchmarkCase( "mcp (server only)", "import mcp.server.lowlevel.server", group="floor" ), # --- Auth stack (incremental over mcp) --- BenchmarkCase( "authlib.jose", "import authlib.jose", prereqs="import mcp", group="auth" ), BenchmarkCase( "cryptography.fernet", "from cryptography.fernet import Fernet", prereqs="import mcp", group="auth", ), BenchmarkCase( "authlib.integrations.httpx_client", "from authlib.integrations.httpx_client import AsyncOAuth2Client", prereqs="import mcp", group="auth", ), BenchmarkCase( "key_value.aio", "import key_value.aio", prereqs="import mcp", group="auth" ), BenchmarkCase( "key_value.aio.stores.filetree", "from key_value.aio.stores.filetree import FileTreeStore", prereqs="import mcp", group="auth", ), BenchmarkCase("beartype", "import beartype", prereqs="import mcp", group="auth"), # --- Docket stack (incremental over mcp) --- BenchmarkCase("redis", "import redis", prereqs="import mcp", group="docket"), BenchmarkCase( "opentelemetry.sdk.metrics", "import opentelemetry.sdk.metrics", prereqs="import mcp", group="docket", ), BenchmarkCase("docket", "import docket", prereqs="import mcp", group="docket"), BenchmarkCase("croniter", "import croniter", prereqs="import mcp", group="docket"), # --- Other deps (incremental over mcp) --- BenchmarkCase("httpx", "import httpx", prereqs="import mcp", group="other"), BenchmarkCase( "starlette", "from starlette.applications import Starlette", prereqs="import mcp", group="other", ), BenchmarkCase( "pydantic_settings", "import pydantic_settings", prereqs="import mcp", group="other", ), BenchmarkCase( "rich.console", "import rich.console", prereqs="import mcp", group="other" ), BenchmarkCase("jsonref", "import jsonref", prereqs="import mcp", group="other"), BenchmarkCase("requests", "import requests", prereqs="import mcp", group="other"), # --- FastMCP (total and incremental) --- BenchmarkCase("fastmcp (total)", "from fastmcp import FastMCP", group="fastmcp"), BenchmarkCase( "fastmcp (over mcp)", "from fastmcp import FastMCP", prereqs="import mcp", group="fastmcp", ), BenchmarkCase( "fastmcp (over mcp+docket)", "from fastmcp import FastMCP", prereqs="import mcp; import docket", group="fastmcp", ), BenchmarkCase( "fastmcp (over mcp+docket+auth deps)", "from fastmcp import FastMCP", prereqs=( "import mcp; import docket; import authlib.jose;" " from cryptography.fernet import Fernet;" " import key_value.aio" ), group="fastmcp", ), ] def measure_once(stmt: str, prereqs: str) -> float | None: pre = prereqs + "; " if prereqs else "" code = ( f"{pre}" "import time as _t; _s=_t.perf_counter(); " f"{stmt}; " "print(f'{(_t.perf_counter()-_s)*1000:.2f}')" ) r = subprocess.run( [sys.executable, "-c", code], capture_output=True, text=True, timeout=30, ) if r.returncode == 0 and r.stdout.strip(): return float(r.stdout.strip()) return None def measure(case: BenchmarkCase, runs: int) -> dict[str, float | str | None]: times: list[float] = [] for _ in range(runs): t = measure_once(case.stmt, case.prereqs) if t is not None: times.append(t) if not times: return {"label": case.label, "group": case.group, "median_ms": None} times.sort() median = times[len(times) // 2] return { "label": case.label, "group": case.group, "median_ms": round(median, 1), "min_ms": round(times[0], 1), "max_ms": round(times[-1], 1), "runs": len(times), } def print_table(results: list[dict[str, float | str | None]]) -> None: current_group = None print(f"\n{'Module':<45} {'Median':>8} {'Min':>8} {'Max':>8}") print("-" * 71) for r in results: if r["group"] != current_group: current_group = r["group"] group_labels = { "floor": "--- Unavoidable floor ---", "auth": "--- Auth stack (incremental over mcp) ---", "docket": "--- Docket stack (incremental over mcp) ---", "other": "--- Other deps (incremental over mcp) ---", "fastmcp": "--- FastMCP totals ---", } print(f"\n{group_labels.get(current_group, current_group)}") if r["median_ms"] is not None: print( f" {r['label']:<43} {r['median_ms']:>7.1f}ms" f" {r['min_ms']:>7.1f}ms {r['max_ms']:>7.1f}ms" ) else: print(f" {r['label']:<43} error") def main() -> None: parser = argparse.ArgumentParser(description="Benchmark fastmcp import times") parser.add_argument( "--runs", type=int, default=5, help="Number of runs per measurement (default 5)" ) parser.add_argument("--json", action="store_true", help="Output results as JSON") args = parser.parse_args() print(f"Benchmarking import times ({args.runs} runs each)...") print(f"Python: {sys.version.split()[0]}") print(f"Executable: {sys.executable}") results = [] for case in CASES: r = measure(case, args.runs) results.append(r) if not args.json: ms = f"{r['median_ms']:.1f}ms" if r["median_ms"] is not None else "error" print(f" {case.label}: {ms}") if args.json: print(json.dumps(results, indent=2)) else: print_table(results) if __name__ == "__main__": main()
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "scripts/benchmark_imports.py", "license": "Apache License 2.0", "lines": 189, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:tests/server/sampling/test_prepare_tools.py
"""Tests for prepare_tools helper function.""" import pytest from fastmcp.server.sampling.run import prepare_tools from fastmcp.server.sampling.sampling_tool import SamplingTool from fastmcp.tools.function_tool import FunctionTool from fastmcp.tools.tool_transform import ArgTransform, TransformedTool class TestPrepareTools: """Tests for prepare_tools().""" def test_prepare_tools_with_none(self): """Test that None returns None.""" result = prepare_tools(None) assert result is None def test_prepare_tools_with_sampling_tool(self): """Test that SamplingTool instances pass through.""" def search(query: str) -> str: return f"Results: {query}" sampling_tool = SamplingTool.from_function(search) result = prepare_tools([sampling_tool]) assert result is not None assert len(result) == 1 assert result[0] is sampling_tool def test_prepare_tools_with_function(self): """Test that plain functions are converted.""" def search(query: str) -> str: """Search function.""" return f"Results: {query}" result = prepare_tools([search]) assert result is not None assert len(result) == 1 assert isinstance(result[0], SamplingTool) assert result[0].name == "search" def test_prepare_tools_with_function_tool(self): """Test that FunctionTool instances are converted.""" def search(query: str) -> str: """Search the web.""" return f"Results: {query}" function_tool = FunctionTool.from_function(search) result = prepare_tools([function_tool]) assert result is not None assert len(result) == 1 assert isinstance(result[0], SamplingTool) assert result[0].name == "search" assert result[0].description == "Search the web." def test_prepare_tools_with_transformed_tool(self): """Test that TransformedTool instances are converted.""" def original(query: str) -> str: """Original tool.""" return f"Results: {query}" function_tool = FunctionTool.from_function(original) transformed_tool = TransformedTool.from_tool( function_tool, name="search_v2", transform_args={"query": ArgTransform(name="q")}, ) result = prepare_tools([transformed_tool]) assert result is not None assert len(result) == 1 assert isinstance(result[0], SamplingTool) assert result[0].name == "search_v2" assert "q" in result[0].parameters.get("properties", {}) def test_prepare_tools_with_mixed_types(self): """Test that mixed tool types are all converted.""" def plain_fn(x: int) -> int: return x * 2 def fn_for_tool(y: int) -> int: return y * 3 function_tool = FunctionTool.from_function(fn_for_tool) sampling_tool = SamplingTool.from_function(lambda z: z * 4, name="lambda_tool") result = prepare_tools([plain_fn, function_tool, sampling_tool]) assert result is not None assert len(result) == 3 assert all(isinstance(t, SamplingTool) for t in result) def test_prepare_tools_with_invalid_type(self): """Test that invalid types raise TypeError.""" with pytest.raises(TypeError, match="Expected SamplingTool, FunctionTool"): prepare_tools(["not a tool"]) # type: ignore[arg-type] def test_prepare_tools_empty_list(self): """Test that empty list returns None.""" result = prepare_tools([]) assert result is None
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/sampling/test_prepare_tools.py", "license": "Apache License 2.0", "lines": 80, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:examples/elicitation.py
""" FastMCP Elicitation Example Demonstrates tools that ask users for input during execution. Try it with the CLI: fastmcp list examples/elicitation.py fastmcp call examples/elicitation.py greet fastmcp call examples/elicitation.py survey """ from dataclasses import dataclass from fastmcp import Context, FastMCP mcp = FastMCP("Elicitation Demo") @mcp.tool async def greet(ctx: Context) -> str: """Greet the user by name (asks for their name).""" result = await ctx.elicit("What is your name?", response_type=str) if result.action == "accept": return f"Hello, {result.data}!" return "Maybe next time!" @mcp.tool async def survey(ctx: Context) -> str: """Run a short survey collecting structured info.""" @dataclass class SurveyResponse: favorite_color: str lucky_number: int result = await ctx.elicit( "Quick survey — tell us about yourself:", response_type=SurveyResponse, ) if result.action == "accept": resp = result.data return f"Got it — you like {resp.favorite_color} and your lucky number is {resp.lucky_number}." return "Survey skipped."
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/elicitation.py", "license": "Apache License 2.0", "lines": 33, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
PrefectHQ/fastmcp:examples/task_elicitation.py
""" Background task elicitation demo. A background task (Docket) that pauses mid-execution to ask the user a question, waits for the answer, then resumes and finishes. Works with both in-memory and Redis backends: # In-memory (single process, no Redis needed) FASTMCP_DOCKET_URL=memory:// uv run python examples/task_elicitation.py # Redis (distributed, needs a worker running separately) # Terminal 1: docker compose -f examples/tasks/docker-compose.yml up -d # Terminal 2: FASTMCP_DOCKET_URL=redis://localhost:24242/0 \ # uv run fastmcp tasks worker examples/task_elicitation.py # Terminal 3: FASTMCP_DOCKET_URL=redis://localhost:24242/0 \ # uv run python examples/task_elicitation.py Requires the `docket` extra (included in dev dependencies). """ import asyncio from dataclasses import dataclass from mcp.types import TextContent from fastmcp import Context, FastMCP from fastmcp.client import Client from fastmcp.server.elicitation import AcceptedElicitation mcp = FastMCP("Task Elicitation Demo") @dataclass class DinnerPrefs: cuisine: str vegetarian: bool @mcp.tool(task=True) async def plan_dinner(ctx: Context) -> str: """Plan a dinner menu, asking the user what they're in the mood for.""" await ctx.report_progress(0, 2, "Asking what you'd like...") result = await ctx.elicit( "What kind of dinner are you in the mood for?", response_type=DinnerPrefs, ) if not isinstance(result, AcceptedElicitation): return "Dinner cancelled!" prefs = result.data await ctx.report_progress(1, 2, "Planning your menu...") await asyncio.sleep(1) await ctx.report_progress(2, 2, "Done!") veg = "vegetarian " if prefs.vegetarian else "" return f"Tonight's menu: a lovely {veg}{prefs.cuisine} dinner!" async def handle_elicitation(message, response_type, params, context): """Handle elicitation requests from background tasks.""" print(f" Server asks: {message}") print(" Responding with: cuisine=Thai, vegetarian=True") return DinnerPrefs(cuisine="Thai", vegetarian=True) async def main(): async with Client(mcp, elicitation_handler=handle_elicitation) as client: print("Starting background task...") task = await client.call_tool("plan_dinner", {}, task=True) print(f" task_id = {task.task_id}\n") result = await task.result() assert isinstance(result.content[0], TextContent) print(f"\nResult: {result.content[0].text}") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/task_elicitation.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:src/fastmcp/cli/auth.py
"""Authentication-related CLI commands.""" import cyclopts from fastmcp.cli.cimd import cimd_app auth_app = cyclopts.App( name="auth", help="Authentication-related utilities and configuration.", ) # Nest CIMD commands under auth auth_app.command(cimd_app)
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/cli/auth.py", "license": "Apache License 2.0", "lines": 9, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
PrefectHQ/fastmcp:src/fastmcp/cli/cimd.py
"""CIMD (Client ID Metadata Document) CLI commands.""" from __future__ import annotations import asyncio import json import sys from pathlib import Path from typing import Annotated import cyclopts from rich.console import Console from fastmcp.server.auth.cimd import ( CIMDFetcher, CIMDFetchError, CIMDValidationError, ) from fastmcp.utilities.logging import get_logger logger = get_logger("cli.cimd") console = Console() cimd_app = cyclopts.App( name="cimd", help="CIMD (Client ID Metadata Document) utilities for OAuth authentication.", ) @cimd_app.command(name="create") def create_command( *, name: Annotated[ str, cyclopts.Parameter(help="Human-readable name of the client application"), ], redirect_uri: Annotated[ list[str], cyclopts.Parameter( name=["--redirect-uri", "-r"], help="Allowed redirect URIs (can specify multiple)", ), ], client_id: Annotated[ str | None, cyclopts.Parameter( name="--client-id", help="The URL where this document will be hosted (sets client_id directly)", ), ] = None, client_uri: Annotated[ str | None, cyclopts.Parameter( name="--client-uri", help="URL of the client's home page", ), ] = None, logo_uri: Annotated[ str | None, cyclopts.Parameter( name="--logo-uri", help="URL of the client's logo image", ), ] = None, scope: Annotated[ str | None, cyclopts.Parameter( name="--scope", help="Space-separated list of scopes the client may request", ), ] = None, output: Annotated[ str | None, cyclopts.Parameter( name=["--output", "-o"], help="Output file path (default: stdout)", ), ] = None, pretty: Annotated[ bool, cyclopts.Parameter( help="Pretty-print JSON output", ), ] = True, ) -> None: """Generate a CIMD document for hosting. Create a Client ID Metadata Document that you can host at an HTTPS URL. The URL where you host this document becomes your client_id. Example: fastmcp cimd create --name "My App" -r "http://localhost:*/callback" After creating the document, host it at an HTTPS URL with a non-root path, for example: https://myapp.example.com/oauth/client.json """ # Build the document doc = { "client_id": client_id or "https://YOUR-DOMAIN.com/path/to/client.json", "client_name": name, "redirect_uris": redirect_uri, "token_endpoint_auth_method": "none", "grant_types": ["authorization_code"], "response_types": ["code"], } # Add optional fields if client_uri: doc["client_uri"] = client_uri if logo_uri: doc["logo_uri"] = logo_uri if scope: doc["scope"] = scope # Format output json_output = json.dumps(doc, indent=2) if pretty else json.dumps(doc) # Write output if output: output_path = Path(output).expanduser().resolve() output_path.parent.mkdir(parents=True, exist_ok=True) with open(output_path, "w") as f: f.write(json_output) f.write("\n") console.print(f"[green]✓[/green] CIMD document written to {output}") if not client_id: console.print( "\n[yellow]Important:[/yellow] client_id is a placeholder. Update it to the URL where you will host this document, or re-run with --client-id." ) else: print(json_output) if not client_id: # Print instructions to stderr so they don't interfere with piping stderr_console = Console(stderr=True) stderr_console.print( "\n[yellow]Important:[/yellow] client_id is a placeholder." " Update it to the URL where you will host this document," " or re-run with --client-id." ) @cimd_app.command(name="validate") def validate_command( url: Annotated[ str, cyclopts.Parameter(help="URL of the CIMD document to validate"), ], *, timeout: Annotated[ float, cyclopts.Parameter( name=["--timeout", "-t"], help="HTTP request timeout in seconds", ), ] = 10.0, ) -> None: """Validate a hosted CIMD document. Fetches the document from the given URL and validates: - URL is valid CIMD URL (HTTPS, non-root path) - Document is valid JSON - Document conforms to CIMD schema - client_id in document matches the URL Example: fastmcp cimd validate https://myapp.example.com/oauth/client.json """ async def _validate() -> bool: fetcher = CIMDFetcher(timeout=timeout) # Check URL format first if not fetcher.is_cimd_client_id(url): console.print(f"[red]✗[/red] Invalid CIMD URL: {url}") console.print() console.print("CIMD URLs must:") console.print(" • Use HTTPS (not HTTP)") console.print(" • Have a non-root path (e.g., /client.json, not just /)") return False console.print(f"[blue]→[/blue] Fetching {url}...") try: doc = await fetcher.fetch(url) except CIMDFetchError as e: console.print(f"[red]✗[/red] Failed to fetch document: {e}") return False except CIMDValidationError as e: console.print(f"[red]✗[/red] Validation error: {e}") return False # Success - show document details console.print("[green]✓[/green] Valid CIMD document") console.print() console.print("[bold]Document details:[/bold]") console.print(f" client_id: {doc.client_id}") console.print(f" client_name: {doc.client_name or '(not set)'}") console.print(f" token_endpoint_auth_method: {doc.token_endpoint_auth_method}") if doc.redirect_uris: console.print(" redirect_uris:") for uri in doc.redirect_uris: console.print(f" • {uri}") else: console.print(" redirect_uris: (none)") if doc.scope: console.print(f" scope: {doc.scope}") if doc.client_uri: console.print(f" client_uri: {doc.client_uri}") return True success = asyncio.run(_validate()) if not success: sys.exit(1)
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/cli/cimd.py", "license": "Apache License 2.0", "lines": 189, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:src/fastmcp/cli/client.py
"""Client-side CLI commands for querying and invoking MCP servers.""" import difflib import json import shlex import sys from pathlib import Path from typing import Annotated, Any, Literal import cyclopts import mcp.types from rich.console import Console from rich.markup import escape as escape_rich_markup from fastmcp.cli.discovery import DiscoveredServer, discover_servers, resolve_name from fastmcp.client.client import CallToolResult, Client from fastmcp.client.elicitation import ElicitResult from fastmcp.client.transports.base import ClientTransport from fastmcp.client.transports.http import StreamableHttpTransport from fastmcp.client.transports.sse import SSETransport from fastmcp.client.transports.stdio import StdioTransport from fastmcp.utilities.logging import get_logger logger = get_logger("cli.client") console = Console() # --------------------------------------------------------------------------- # Server spec resolution # --------------------------------------------------------------------------- _JSON_SCHEMA_TYPE_MAP: dict[str, str] = { "string": "str", "integer": "int", "number": "float", "boolean": "bool", "array": "list", "object": "dict", "null": "None", } def resolve_server_spec( server_spec: str | None, *, command: str | None = None, transport: str | None = None, ) -> str | dict[str, Any] | ClientTransport: """Turn CLI inputs into something ``Client()`` accepts. Exactly one of ``server_spec`` or ``command`` should be provided. Resolution order for ``server_spec``: 1. URLs (``http://``, ``https://``) — passed through as-is. If ``--transport`` is ``sse``, the URL is rewritten to end with ``/sse`` so ``infer_transport`` picks the right transport. 2. Existing file paths, or strings ending in ``.py``/``.js``/``.json``. 3. Anything else — name-based resolution via ``resolve_name``. When ``command`` is provided, the string is shell-split into a ``StdioTransport(command, args)``. """ if command is not None and server_spec is not None: console.print( "[bold red]Error:[/bold red] Cannot use both a server spec and --command" ) sys.exit(1) if command is not None: return _build_stdio_from_command(command) if server_spec is None: console.print( "[bold red]Error:[/bold red] Provide a server spec or use --command" ) sys.exit(1) assert isinstance(server_spec, str) spec: str = server_spec # 1. URL if spec.startswith(("http://", "https://")): if transport == "sse" and not spec.rstrip("/").endswith("/sse"): spec = spec.rstrip("/") + "/sse" return spec # 2. File path (must be a file, not a directory) path = Path(spec) is_file = path.is_file() or ( not path.is_dir() and spec.endswith((".py", ".js", ".json")) ) if is_file: if spec.endswith(".json"): return _resolve_json_spec(path) if spec.endswith(".py"): # Run via `fastmcp run` so scripts don't need mcp.run() resolved_path = path.resolve() return StdioTransport( command="fastmcp", args=["run", str(resolved_path), "--no-banner"], ) # .js — pass through for Client's infer_transport return spec # 3. Name-based resolution (bare name or source:name) try: return resolve_name(spec) except ValueError as exc: console.print(f"[bold red]Error:[/bold red] {exc}") sys.exit(1) def _build_stdio_from_command(command_str: str) -> StdioTransport: """Shell-split a command string into a ``StdioTransport``.""" try: parts = shlex.split(command_str) except ValueError as exc: console.print(f"[bold red]Error:[/bold red] Invalid command: {exc}") sys.exit(1) if not parts: console.print("[bold red]Error:[/bold red] Empty --command") sys.exit(1) return StdioTransport(command=parts[0], args=parts[1:]) def _resolve_json_spec(path: Path) -> str | dict[str, Any]: """Disambiguate a ``.json`` server spec.""" if not path.exists(): console.print( f"[bold red]Error:[/bold red] File not found: [cyan]{path}[/cyan]" ) sys.exit(1) try: data = json.loads(path.read_text()) except json.JSONDecodeError as exc: console.print(f"[bold red]Error:[/bold red] Invalid JSON in {path}: {exc}") sys.exit(1) if isinstance(data, dict) and "mcpServers" in data: return data # Likely a fastmcp.json (MCPServerConfig) — not directly usable as a client target. console.print( f"[bold red]Error:[/bold red] [cyan]{path}[/cyan] is a FastMCP server config, not an MCPConfig.\n" f"Start the server first, then query it:\n\n" f" fastmcp run {path}\n" f" fastmcp list http://localhost:8000/mcp\n" ) sys.exit(1) def _is_http_target(resolved: str | dict[str, Any] | ClientTransport) -> bool: """Return True if the resolved target will use an HTTP-based transport. MCPConfig dicts are excluded because ``MCPConfigTransport`` manages individual server transports internally and does not support top-level auth. """ if isinstance(resolved, str): return resolved.startswith(("http://", "https://")) return isinstance(resolved, (StreamableHttpTransport, SSETransport)) async def _terminal_elicitation_handler( message: str, response_type: type[Any] | None, params: Any, context: Any, ) -> ElicitResult[dict[str, Any]]: """Prompt the user on the terminal for elicitation responses. Prints the server's message and prompts for each field in the schema. The user can type 'decline' or 'cancel' instead of a value to abort. """ from mcp.types import ElicitRequestFormParams console.print(f"\n[bold yellow]Server asks:[/bold yellow] {message}") if not isinstance(params, ElicitRequestFormParams): answer = console.input( "[dim](press Enter to accept, or type 'decline'):[/dim] " ) if answer.strip().lower() == "decline": return ElicitResult(action="decline") if answer.strip().lower() == "cancel": return ElicitResult(action="cancel") return ElicitResult(action="accept", content={}) schema = params.requestedSchema properties = schema.get("properties", {}) required = set(schema.get("required", [])) if not properties: answer = console.input( "[dim](press Enter to accept, or type 'decline'):[/dim] " ) if answer.strip().lower() == "decline": return ElicitResult(action="decline") if answer.strip().lower() == "cancel": return ElicitResult(action="cancel") return ElicitResult(action="accept", content={}) result: dict[str, Any] = {} for field_name, field_schema in properties.items(): type_hint = field_schema.get("type", "string") req_marker = " [red]*[/red]" if field_name in required else "" prompt_text = f" [cyan]{field_name}[/cyan] ({type_hint}){req_marker}: " raw = console.input(prompt_text) if raw.strip().lower() == "decline": return ElicitResult(action="decline") if raw.strip().lower() == "cancel": return ElicitResult(action="cancel") if raw == "" and field_name not in required: continue result[field_name] = coerce_value(raw, field_schema) return ElicitResult(action="accept", content=result) def _build_client( resolved: str | dict[str, Any] | ClientTransport, *, timeout: float | None = None, auth: str | None = None, ) -> Client: """Build a ``Client`` from a resolved server spec. Applies ``auth='oauth'`` automatically for HTTP-based targets unless the caller explicitly passes ``--auth none`` to disable it. ``auth=None`` means "not specified" (use default), ``auth="none"`` means "explicitly disabled". """ if auth == "none": effective_auth: str | None = None elif auth is not None: effective_auth = auth elif _is_http_target(resolved): effective_auth = "oauth" else: effective_auth = None return Client( resolved, timeout=timeout, auth=effective_auth, elicitation_handler=_terminal_elicitation_handler, ) # --------------------------------------------------------------------------- # Argument coercion # --------------------------------------------------------------------------- def coerce_value(raw: str, schema: dict[str, Any]) -> Any: """Coerce a string CLI value according to a JSON-Schema type hint.""" schema_type = schema.get("type", "string") if schema_type == "integer": try: return int(raw) except ValueError: raise ValueError(f"Expected integer, got {raw!r}") from None if schema_type == "number": try: return float(raw) except ValueError: raise ValueError(f"Expected number, got {raw!r}") from None if schema_type == "boolean": if raw.lower() in ("true", "1", "yes"): return True if raw.lower() in ("false", "0", "no"): return False raise ValueError(f"Expected boolean, got {raw!r}") if schema_type in ("array", "object"): try: return json.loads(raw) except json.JSONDecodeError: raise ValueError(f"Expected JSON {schema_type}, got {raw!r}") from None # Default: treat as string return raw def parse_tool_arguments( raw_args: tuple[str, ...], input_json: str | None, input_schema: dict[str, Any], ) -> dict[str, Any]: """Build a tool-call argument dict from CLI inputs. A single JSON object argument is treated as the full argument dict. ``--input-json`` provides the base dict; ``key=value`` pairs override. Values are coerced using the tool's ``inputSchema``. """ # A single positional arg that looks like JSON → treat as input-json if len(raw_args) == 1 and raw_args[0].startswith("{") and input_json is None: input_json = raw_args[0] raw_args = () result: dict[str, Any] = {} if input_json is not None: try: parsed = json.loads(input_json) except json.JSONDecodeError as exc: console.print(f"[bold red]Error:[/bold red] Invalid --input-json: {exc}") sys.exit(1) if not isinstance(parsed, dict): console.print( "[bold red]Error:[/bold red] --input-json must be a JSON object" ) sys.exit(1) result.update(parsed) properties = input_schema.get("properties", {}) for arg in raw_args: if "=" not in arg: console.print( f"[bold red]Error:[/bold red] Invalid argument [cyan]{arg}[/cyan] — expected key=value" ) sys.exit(1) key, value = arg.split("=", 1) prop_schema = properties.get(key, {}) try: result[key] = coerce_value(value, prop_schema) except ValueError as exc: console.print( f"[bold red]Error:[/bold red] Argument [cyan]{key}[/cyan]: {exc}" ) sys.exit(1) return result # --------------------------------------------------------------------------- # Tool signature formatting # --------------------------------------------------------------------------- def _json_schema_type_to_str(schema: dict[str, Any]) -> str: """Produce a short Python-style type string from a JSON-Schema fragment.""" if "anyOf" in schema: parts = [_json_schema_type_to_str(s) for s in schema["anyOf"]] return " | ".join(parts) schema_type = schema.get("type", "any") if isinstance(schema_type, list): return " | ".join(_JSON_SCHEMA_TYPE_MAP.get(t, t) for t in schema_type) return _JSON_SCHEMA_TYPE_MAP.get(schema_type, schema_type) def format_tool_signature(tool: mcp.types.Tool) -> str: """Build ``name(param: type, ...) -> return_type`` from a tool's JSON schemas.""" params: list[str] = [] schema = tool.inputSchema properties = schema.get("properties", {}) required = set(schema.get("required", [])) for prop_name, prop_schema in properties.items(): type_str = _json_schema_type_to_str(prop_schema) if prop_name in required: params.append(f"{prop_name}: {type_str}") else: default = prop_schema.get("default") default_repr = repr(default) if default is not None else "..." params.append(f"{prop_name}: {type_str} = {default_repr}") sig = f"{tool.name}({', '.join(params)})" if tool.outputSchema: ret = _json_schema_type_to_str(tool.outputSchema) sig += f" -> {ret}" return sig # --------------------------------------------------------------------------- # Output formatting # --------------------------------------------------------------------------- def _print_schema(label: str, schema: dict[str, Any]) -> None: """Print a JSON schema with a label.""" properties = schema.get("properties", {}) if not properties: return console.print(f" [dim]{label}: {json.dumps(schema)}[/dim]") def _sanitize_untrusted_text(value: str) -> str: """Escape rich markup and encode control chars for terminal-safe output.""" sanitized = escape_rich_markup(value) return "".join( ch if ch in {"\n", "\t"} or (0x20 <= ord(ch) < 0x7F) or ord(ch) > 0x9F else f"\\x{ord(ch):02x}" for ch in sanitized ) def _format_call_result_text(result: CallToolResult) -> None: """Pretty-print a tool call result to the console.""" if result.is_error: for block in result.content: if isinstance(block, mcp.types.TextContent): console.print( f"[bold red]Error:[/bold red] {_sanitize_untrusted_text(block.text)}" ) else: console.print( f"[bold red]Error:[/bold red] {_sanitize_untrusted_text(str(block))}" ) return if result.structured_content is not None: console.print_json(json.dumps(result.structured_content)) return for block in result.content: if isinstance(block, mcp.types.TextContent): console.print(_sanitize_untrusted_text(block.text)) elif isinstance(block, mcp.types.ImageContent): size = len(block.data) * 3 // 4 # rough decoded size console.print(f"[dim][Image: {block.mimeType}, ~{size} bytes][/dim]") elif isinstance(block, mcp.types.AudioContent): size = len(block.data) * 3 // 4 console.print(f"[dim][Audio: {block.mimeType}, ~{size} bytes][/dim]") else: console.print(_sanitize_untrusted_text(str(block))) def _content_block_to_dict(block: mcp.types.ContentBlock) -> dict[str, Any]: """Serialize a single content block to a JSON-safe dict.""" if isinstance(block, mcp.types.TextContent): return {"type": "text", "text": block.text} if isinstance(block, mcp.types.ImageContent): return {"type": "image", "mimeType": block.mimeType, "data": block.data} if isinstance(block, mcp.types.AudioContent): return {"type": "audio", "mimeType": block.mimeType, "data": block.data} return {"type": "unknown", "value": str(block)} def _call_result_to_dict(result: CallToolResult) -> dict[str, Any]: """Serialize a ``CallToolResult`` to a JSON-safe dict.""" content_list = [_content_block_to_dict(block) for block in result.content] out: dict[str, Any] = {"content": content_list, "is_error": result.is_error} if result.structured_content is not None: out["structured_content"] = result.structured_content return out def _tools_to_json(tools: list[mcp.types.Tool]) -> list[dict[str, Any]]: """Serialize a list of tools to JSON-safe dicts.""" return [ { "name": t.name, "description": t.description, "inputSchema": t.inputSchema, **({"outputSchema": t.outputSchema} if t.outputSchema else {}), } for t in tools ] # --------------------------------------------------------------------------- # Call handlers (tool, resource, prompt) # --------------------------------------------------------------------------- async def _handle_tool_call( client: Client, tool_name: str, arguments: tuple[str, ...], input_json: str | None, json_output: bool, ) -> None: """Handle a tool call within an open client session.""" tools = await client.list_tools() tool_map = {t.name: t for t in tools} if tool_name not in tool_map: close_matches = difflib.get_close_matches( tool_name, tool_map.keys(), n=3, cutoff=0.5 ) msg = f"Tool [cyan]{tool_name}[/cyan] not found." if close_matches: suggestions = ", ".join(f"[cyan]{m}[/cyan]" for m in close_matches) msg += f" Did you mean: {suggestions}?" console.print(f"[bold red]Error:[/bold red] {msg}") sys.exit(1) tool = tool_map[tool_name] parsed_args = parse_tool_arguments(arguments, input_json, tool.inputSchema) required = set(tool.inputSchema.get("required", [])) provided = set(parsed_args.keys()) missing = required - provided if missing: missing_str = ", ".join(f"[cyan]{m}[/cyan]" for m in sorted(missing)) console.print( f"[bold red]Error:[/bold red] Missing required arguments: {missing_str}" ) console.print() sig = format_tool_signature(tool) console.print(f" [dim]{sig}[/dim]") sys.exit(1) result = await client.call_tool(tool_name, parsed_args, raise_on_error=False) if json_output: console.print_json(json.dumps(_call_result_to_dict(result))) else: _format_call_result_text(result) if result.is_error: sys.exit(1) async def _handle_resource( client: Client, uri: str, json_output: bool, ) -> None: """Handle a resource read within an open client session.""" contents = await client.read_resource(uri) if json_output: data = [] for block in contents: if isinstance(block, mcp.types.TextResourceContents): data.append( { "uri": str(block.uri), "mimeType": block.mimeType, "text": block.text, } ) elif isinstance(block, mcp.types.BlobResourceContents): data.append( { "uri": str(block.uri), "mimeType": block.mimeType, "blob": block.blob, } ) console.print_json(json.dumps(data)) return for block in contents: if isinstance(block, mcp.types.TextResourceContents): console.print(_sanitize_untrusted_text(block.text)) elif isinstance(block, mcp.types.BlobResourceContents): size = len(block.blob) * 3 // 4 console.print(f"[dim][Blob: {block.mimeType}, ~{size} bytes][/dim]") async def _handle_prompt( client: Client, prompt_name: str, arguments: tuple[str, ...], input_json: str | None, json_output: bool, ) -> None: """Handle a prompt get within an open client session.""" # Prompt arguments are always string->string, but we reuse # parse_tool_arguments for the key=value / --input-json parsing. # Pass an empty schema so values stay as strings. parsed_args = parse_tool_arguments(arguments, input_json, {"type": "object"}) prompts = await client.list_prompts() prompt_map = {p.name: p for p in prompts} if prompt_name not in prompt_map: close_matches = difflib.get_close_matches( prompt_name, prompt_map.keys(), n=3, cutoff=0.5 ) msg = f"Prompt [cyan]{prompt_name}[/cyan] not found." if close_matches: suggestions = ", ".join(f"[cyan]{m}[/cyan]" for m in close_matches) msg += f" Did you mean: {suggestions}?" console.print(f"[bold red]Error:[/bold red] {msg}") sys.exit(1) result = await client.get_prompt(prompt_name, parsed_args or None) if json_output: data: dict[str, Any] = {} if result.description: data["description"] = result.description data["messages"] = [ { "role": msg.role, "content": _content_block_to_dict(msg.content), } for msg in result.messages ] console.print_json(json.dumps(data)) return for msg in result.messages: console.print(f"[bold]{_sanitize_untrusted_text(msg.role)}:[/bold]") if isinstance(msg.content, mcp.types.TextContent): console.print(f" {_sanitize_untrusted_text(msg.content.text)}") elif isinstance(msg.content, mcp.types.ImageContent): size = len(msg.content.data) * 3 // 4 console.print( f" [dim][Image: {msg.content.mimeType}, ~{size} bytes][/dim]" ) else: console.print(f" {_sanitize_untrusted_text(str(msg.content))}") console.print() # --------------------------------------------------------------------------- # Commands # --------------------------------------------------------------------------- async def list_command( server_spec: Annotated[ str | None, cyclopts.Parameter( help="Server URL, Python file, MCPConfig JSON, or .js file", ), ] = None, *, command: Annotated[ str | None, cyclopts.Parameter( "--command", help="Stdio command to connect to (e.g. 'npx -y @mcp/server')", ), ] = None, transport: Annotated[ Literal["http", "sse"] | None, cyclopts.Parameter( name=["--transport", "-t"], help="Force transport type for URL targets (http or sse)", ), ] = None, resources: Annotated[ bool, cyclopts.Parameter("--resources", help="Also list resources"), ] = False, prompts: Annotated[ bool, cyclopts.Parameter("--prompts", help="Also list prompts"), ] = False, input_schema: Annotated[ bool, cyclopts.Parameter("--input-schema", help="Show full input schemas"), ] = False, output_schema: Annotated[ bool, cyclopts.Parameter("--output-schema", help="Show full output schemas"), ] = False, json_output: Annotated[ bool, cyclopts.Parameter("--json", help="Output as JSON"), ] = False, timeout: Annotated[ float | None, cyclopts.Parameter("--timeout", help="Connection timeout in seconds"), ] = None, auth: Annotated[ str | None, cyclopts.Parameter( "--auth", help="Auth method: 'oauth', a bearer token string, or 'none' to disable", ), ] = None, ) -> None: """List tools available on an MCP server. Examples: fastmcp list http://localhost:8000/mcp fastmcp list server.py fastmcp list mcp.json --json fastmcp list --command 'npx -y @mcp/server' --resources fastmcp list http://server/mcp --transport sse """ resolved = resolve_server_spec(server_spec, command=command, transport=transport) client = _build_client(resolved, timeout=timeout, auth=auth) try: async with client: tools = await client.list_tools() if json_output: data: dict[str, Any] = {"tools": _tools_to_json(tools)} if resources: res = await client.list_resources() data["resources"] = [ { "uri": str(r.uri), "name": r.name, "description": r.description, "mimeType": r.mimeType, } for r in res ] if prompts: prm = await client.list_prompts() data["prompts"] = [ { "name": p.name, "description": p.description, "arguments": [a.model_dump() for a in (p.arguments or [])], } for p in prm ] console.print_json(json.dumps(data)) return # Text output if not tools: console.print("[dim]No tools found.[/dim]") else: console.print(f"[bold]Tools ({len(tools)})[/bold]") console.print() for tool in tools: sig = format_tool_signature(tool) console.print(f" [cyan]{_sanitize_untrusted_text(sig)}[/cyan]") if tool.description: console.print( f" {_sanitize_untrusted_text(tool.description)}" ) if input_schema: _print_schema("Input", tool.inputSchema) if output_schema and tool.outputSchema: _print_schema("Output", tool.outputSchema) console.print() if resources: res = await client.list_resources() console.print(f"[bold]Resources ({len(res)})[/bold]") console.print() if not res: console.print(" [dim]No resources found.[/dim]") for r in res: console.print( f" [cyan]{_sanitize_untrusted_text(str(r.uri))}[/cyan]" ) desc_parts = [r.name or "", r.description or ""] desc = " — ".join(p for p in desc_parts if p) if desc: console.print(f" {_sanitize_untrusted_text(desc)}") console.print() if prompts: prm = await client.list_prompts() console.print(f"[bold]Prompts ({len(prm)})[/bold]") console.print() if not prm: console.print(" [dim]No prompts found.[/dim]") for p in prm: args_str = "" if p.arguments: parts = [a.name for a in p.arguments] args_str = f"({', '.join(parts)})" console.print( f" [cyan]{_sanitize_untrusted_text(p.name + args_str)}[/cyan]" ) if p.description: console.print(f" {_sanitize_untrusted_text(p.description)}") console.print() except Exception as exc: console.print(f"[bold red]Error:[/bold red] {exc}") sys.exit(1) async def call_command( server_spec: Annotated[ str | None, cyclopts.Parameter( help="Server URL, Python file, MCPConfig JSON, or .js file", ), ] = None, target: Annotated[ str, cyclopts.Parameter( help="Tool name, resource URI, or prompt name (with --prompt)", ), ] = "", *arguments: str, command: Annotated[ str | None, cyclopts.Parameter( "--command", help="Stdio command to connect to (e.g. 'npx -y @mcp/server')", ), ] = None, transport: Annotated[ Literal["http", "sse"] | None, cyclopts.Parameter( name=["--transport", "-t"], help="Force transport type for URL targets (http or sse)", ), ] = None, prompt: Annotated[ bool, cyclopts.Parameter("--prompt", help="Treat target as a prompt name"), ] = False, input_json: Annotated[ str | None, cyclopts.Parameter( "--input-json", help="JSON string of arguments (merged with key=value args)", ), ] = None, json_output: Annotated[ bool, cyclopts.Parameter("--json", help="Output raw JSON result"), ] = False, timeout: Annotated[ float | None, cyclopts.Parameter("--timeout", help="Connection timeout in seconds"), ] = None, auth: Annotated[ str | None, cyclopts.Parameter( "--auth", help="Auth method: 'oauth', a bearer token string, or 'none' to disable", ), ] = None, ) -> None: """Call a tool, read a resource, or get a prompt on an MCP server. By default the target is treated as a tool name. If the target contains ``://`` it is treated as a resource URI. Pass ``--prompt`` to treat it as a prompt name. Arguments are passed as key=value pairs. Use --input-json for complex or nested arguments. Examples: ``` fastmcp call server.py greet name=World fastmcp call server.py resource://docs/readme fastmcp call server.py analyze --prompt data='[1,2,3]' fastmcp call http://server/mcp create --input-json '{"tags": ["a","b"]}' ``` """ if not target: console.print( "[bold red]Error:[/bold red] Missing target.\n\n" "Usage: fastmcp call <server> <target> [key=value ...]\n\n" " target can be a tool name, a resource URI, or a prompt name (with --prompt).\n\n" "Use [cyan]fastmcp list <server>[/cyan] to see available tools." ) sys.exit(1) resolved = resolve_server_spec(server_spec, command=command, transport=transport) client = _build_client(resolved, timeout=timeout, auth=auth) try: async with client: if prompt: await _handle_prompt(client, target, arguments, input_json, json_output) elif "://" in target: await _handle_resource(client, target, json_output) else: await _handle_tool_call( client, target, arguments, input_json, json_output ) except Exception as exc: console.print(f"[bold red]Error:[/bold red] {exc}") sys.exit(1) async def discover_command( *, source: Annotated[ list[str] | None, cyclopts.Parameter( "--source", help="Only show servers from these sources (e.g. claude-code, cursor, gemini)", ), ] = None, json_output: Annotated[ bool, cyclopts.Parameter("--json", help="Output as JSON"), ] = False, ) -> None: """Discover MCP servers configured in editor and project configs. Scans Claude Desktop, Claude Code, Cursor, Gemini CLI, Goose, and project-level mcp.json files for MCP server definitions. Discovered server names can be used directly with ``fastmcp list`` and ``fastmcp call`` instead of specifying a URL or file path. Examples: fastmcp discover fastmcp discover --source claude-code fastmcp discover --source cursor --source gemini --json fastmcp list weather fastmcp call cursor:weather get_forecast city=London """ servers = discover_servers() if source: servers = [s for s in servers if s.source in source] if json_output: data: list[dict[str, Any]] = [ { "name": s.name, "source": s.source, "qualified_name": s.qualified_name, "transport_summary": s.transport_summary, "config_path": str(s.config_path), } for s in servers ] console.print_json(json.dumps(data)) return if not servers: console.print("[dim]No MCP servers found.[/dim]") console.print() console.print("Searched:") console.print(" • Claude Desktop config") console.print(" • ~/.claude.json (Claude Code)") console.print(" • .cursor/mcp.json (walked up from cwd)") console.print(" • ~/.gemini/settings.json (Gemini CLI)") console.print(" • ~/.config/goose/config.yaml (Goose)") console.print(" • ./mcp.json") return from rich.table import Table # Group by source by_source: dict[str, list[DiscoveredServer]] = {} for s in servers: by_source.setdefault(s.source, []).append(s) for source_name, group in by_source.items(): console.print() console.print(f"[bold]Source:[/bold] {source_name}") console.print(f"[bold]Config:[/bold] [dim]{group[0].config_path}[/dim]") console.print() table = Table( show_header=True, header_style="bold", show_edge=False, pad_edge=False, box=None, padding=(0, 2), ) table.add_column("Server", style="cyan") table.add_column("Transport", style="dim") for s in group: table.add_row(s.name, s.transport_summary) console.print(table) console.print()
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/cli/client.py", "license": "Apache License 2.0", "lines": 827, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:src/fastmcp/cli/discovery.py
"""Discover MCP servers configured in editor config files. Scans filesystem-readable config files from editors like Claude Desktop, Claude Code, Cursor, Gemini CLI, and Goose, as well as project-level ``mcp.json`` files. Each discovered server can be resolved by name (or ``source:name``) so the CLI can connect without requiring a URL or file path. """ import json import os import sys from dataclasses import dataclass from pathlib import Path from typing import Any import yaml from fastmcp.client.transports.base import ClientTransport from fastmcp.mcp_config import ( MCPConfig, MCPServerTypes, RemoteMCPServer, StdioMCPServer, ) from fastmcp.utilities.logging import get_logger logger = get_logger("cli.discovery") # --------------------------------------------------------------------------- # Data model # --------------------------------------------------------------------------- @dataclass(frozen=True) class DiscoveredServer: """A single MCP server found in an editor or project config.""" name: str source: str config: MCPServerTypes config_path: Path @property def qualified_name(self) -> str: """Fully qualified ``source:name`` identifier.""" return f"{self.source}:{self.name}" @property def transport_summary(self) -> str: """Human-readable one-liner describing the transport.""" cfg = self.config if isinstance(cfg, StdioMCPServer): parts = [cfg.command, *cfg.args] return f"stdio: {' '.join(parts)}" if isinstance(cfg, RemoteMCPServer): transport = cfg.transport or "http" return f"{transport}: {cfg.url}" return str(type(cfg).__name__) # --------------------------------------------------------------------------- # Scanners — one per config source # --------------------------------------------------------------------------- def _normalize_server_entry(entry: dict[str, Any]) -> dict[str, Any]: """Normalize editor-specific server config fields to MCPConfig format. Handles two known differences: - Claude Code uses ``type`` where MCPConfig uses ``transport`` for remote servers. - Gemini CLI uses ``httpUrl`` where MCPConfig uses ``url``. """ # Gemini: httpUrl → url if "httpUrl" in entry and "url" not in entry: entry = {**entry, "url": entry["httpUrl"]} del entry["httpUrl"] # Claude Code / others: type → transport (for url-based entries only) if "url" in entry and "type" in entry and "transport" not in entry: transport = entry["type"] entry = {k: v for k, v in entry.items() if k != "type"} entry["transport"] = transport return entry def _parse_mcp_servers( servers_dict: dict[str, Any], *, source: str, config_path: Path, ) -> list[DiscoveredServer]: """Parse an ``mcpServers``-style dict into discovered servers.""" if not servers_dict: return [] normalized = { name: _normalize_server_entry(entry) for name, entry in servers_dict.items() if isinstance(entry, dict) } try: config = MCPConfig.from_dict({"mcpServers": normalized}) except Exception as exc: logger.warning("Could not parse MCP servers from %s: %s", config_path, exc) return [] return [ DiscoveredServer( name=name, source=source, config=server, config_path=config_path ) for name, server in config.mcpServers.items() ] def _parse_mcp_config(path: Path, source: str) -> list[DiscoveredServer]: """Parse an mcpServers-style JSON file into discovered servers.""" try: text = path.read_text() except OSError as exc: logger.debug("Could not read %s: %s", path, exc) return [] try: data: dict[str, Any] = json.loads(text) except json.JSONDecodeError as exc: logger.warning("Invalid JSON in %s: %s", path, exc) return [] if not isinstance(data, dict) or "mcpServers" not in data: return [] return _parse_mcp_servers(data["mcpServers"], source=source, config_path=path) def _scan_claude_desktop() -> list[DiscoveredServer]: """Scan the Claude Desktop config file.""" if sys.platform == "win32": config_dir = Path(Path.home(), "AppData", "Roaming", "Claude") elif sys.platform == "darwin": config_dir = Path(Path.home(), "Library", "Application Support", "Claude") elif sys.platform.startswith("linux"): config_dir = Path( os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"), "Claude" ) else: return [] path = config_dir / "claude_desktop_config.json" return _parse_mcp_config(path, "claude-desktop") def _scan_claude_code(start_dir: Path) -> list[DiscoveredServer]: """Scan ``~/.claude.json`` for global and project-scoped MCP servers.""" path = Path.home() / ".claude.json" try: text = path.read_text() except OSError: return [] try: data: dict[str, Any] = json.loads(text) except json.JSONDecodeError as exc: logger.warning("Invalid JSON in %s: %s", path, exc) return [] if not isinstance(data, dict): return [] results: list[DiscoveredServer] = [] # Global servers if global_servers := data.get("mcpServers"): if isinstance(global_servers, dict): results.extend( _parse_mcp_servers( global_servers, source="claude-code", config_path=path ) ) # Project-scoped servers matching start_dir resolved_dir = str(start_dir.resolve()) projects = data.get("projects", {}) if isinstance(projects, dict): project_data = projects.get(resolved_dir, {}) if isinstance(project_data, dict): if project_servers := project_data.get("mcpServers"): if isinstance(project_servers, dict): results.extend( _parse_mcp_servers( project_servers, source="claude-code", config_path=path, ) ) return results def _scan_cursor_workspace(start_dir: Path) -> list[DiscoveredServer]: """Walk up from *start_dir* looking for ``.cursor/mcp.json``.""" current = start_dir.resolve() home = Path.home().resolve() while True: candidate = current / ".cursor" / "mcp.json" if candidate.is_file(): return _parse_mcp_config(candidate, "cursor") parent = current.parent # Stop at filesystem root or home directory if parent == current or current == home: break current = parent return [] def _scan_project_mcp_json(start_dir: Path) -> list[DiscoveredServer]: """Check for ``mcp.json`` in *start_dir*.""" candidate = start_dir.resolve() / "mcp.json" if candidate.is_file(): return _parse_mcp_config(candidate, "project") return [] def _scan_gemini(start_dir: Path) -> list[DiscoveredServer]: """Scan Gemini CLI settings for MCP servers. Checks both user-level ``~/.gemini/settings.json`` and project-level ``.gemini/settings.json``. """ results: list[DiscoveredServer] = [] # User-level user_path = Path.home() / ".gemini" / "settings.json" results.extend(_parse_mcp_config(user_path, "gemini")) # Project-level project_path = start_dir.resolve() / ".gemini" / "settings.json" if project_path != user_path: results.extend(_parse_mcp_config(project_path, "gemini")) return results def _scan_goose() -> list[DiscoveredServer]: """Scan Goose config for MCP server extensions. Goose uses YAML (``~/.config/goose/config.yaml``) with a different schema — MCP servers are defined as ``extensions`` with ``type: stdio``. """ if sys.platform == "win32": config_dir = Path( os.environ.get("APPDATA", Path.home() / "AppData" / "Roaming"), "Block", "goose", "config", ) else: config_dir = Path( os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"), "goose", ) path = config_dir / "config.yaml" try: text = path.read_text() except OSError: return [] try: data = yaml.safe_load(text) except yaml.YAMLError as exc: logger.warning("Invalid YAML in %s: %s", path, exc) return [] if not isinstance(data, dict): return [] extensions = data.get("extensions", {}) if not isinstance(extensions, dict): return [] # Convert Goose extensions to mcpServers format servers: dict[str, Any] = {} for name, ext in extensions.items(): if not isinstance(ext, dict): continue if not ext.get("enabled", True): continue ext_type = ext.get("type", "") if ext_type == "stdio" and "cmd" in ext: servers[name] = { "command": ext["cmd"], "args": ext.get("args", []), "env": ext.get("envs", {}), } elif ext_type == "sse" and "uri" in ext: servers[name] = {"url": ext["uri"], "transport": "sse"} return _parse_mcp_servers(servers, source="goose", config_path=path) # --------------------------------------------------------------------------- # Public API # --------------------------------------------------------------------------- def discover_servers(start_dir: Path | None = None) -> list[DiscoveredServer]: """Run all scanners and return the combined results. Duplicate names across sources are preserved — callers can use :pyattr:`DiscoveredServer.qualified_name` to disambiguate. """ cwd = start_dir or Path.cwd() results: list[DiscoveredServer] = [] results.extend(_scan_claude_desktop()) results.extend(_scan_claude_code(cwd)) results.extend(_scan_cursor_workspace(cwd)) results.extend(_scan_gemini(cwd)) results.extend(_scan_goose()) results.extend(_scan_project_mcp_json(cwd)) return results def resolve_name(name: str, start_dir: Path | None = None) -> ClientTransport: """Resolve a server name (or ``source:name``) to a transport. Raises :class:`ValueError` when the name is not found or is ambiguous. """ servers = discover_servers(start_dir) # Qualified form: "cursor:weather" if ":" in name: source, server_name = name.split(":", 1) matches = [s for s in servers if s.source == source and s.name == server_name] if not matches: raise ValueError( f"No server named '{server_name}' found in source '{source}'." ) return matches[0].config.to_transport() # Bare name: "weather" matches = [s for s in servers if s.name == name] if not matches: if servers: available = ", ".join(sorted({s.name for s in servers})) raise ValueError(f"No server named '{name}' found. Available: {available}") locations = [ "Claude Desktop config", "~/.claude.json (Claude Code)", ".cursor/mcp.json (walked up from cwd)", "~/.gemini/settings.json (Gemini CLI)", "~/.config/goose/config.yaml (Goose)", "./mcp.json", ] raise ValueError( f"No server named '{name}' found. Searched: {', '.join(locations)}" ) if len(matches) == 1: return matches[0].config.to_transport() # Ambiguous — list qualified alternatives alternatives = ", ".join(f"'{m.qualified_name}'" for m in matches) raise ValueError( f"Ambiguous server name '{name}' — found in multiple sources. " f"Use a qualified name: {alternatives}" )
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/cli/discovery.py", "license": "Apache License 2.0", "lines": 300, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:src/fastmcp/cli/generate.py
"""Generate a standalone CLI script and agent skill from an MCP server.""" import keyword import re import sys import textwrap from pathlib import Path from typing import Annotated, Any from urllib.parse import urlparse import cyclopts import mcp.types import pydantic_core from mcp import McpError from rich.console import Console from fastmcp.cli.client import _build_client, resolve_server_spec from fastmcp.client.transports.base import ClientTransport from fastmcp.client.transports.stdio import StdioTransport from fastmcp.utilities.logging import get_logger logger = get_logger("cli.generate") console = Console() # --------------------------------------------------------------------------- # JSON Schema type → Python type string # --------------------------------------------------------------------------- _SIMPLE_TYPES = {"string", "integer", "number", "boolean", "null"} def _is_simple_type(schema: dict[str, Any]) -> bool: """Check if a schema represents a simple (non-complex) type.""" schema_type = schema.get("type") if isinstance(schema_type, list): # Union of types - simple only if all are simple return all(t in _SIMPLE_TYPES for t in schema_type) return schema_type in _SIMPLE_TYPES def _is_simple_array(schema: dict[str, Any]) -> tuple[bool, str | None]: """Check if schema is an array of simple types. Returns (is_simple_array, item_type_str). """ if schema.get("type") != "array": return False, None items = schema.get("items", {}) if not _is_simple_type(items): return False, None # Map JSON Schema type to Python type item_type = items.get("type", "string") if isinstance(item_type, list): return False, None type_map = { "string": "str", "integer": "int", "number": "float", "boolean": "bool", } py_type = type_map.get(item_type) if py_type is None: return False, None return True, py_type def _schema_to_python_type(schema: dict[str, Any]) -> tuple[str, bool]: """Convert a JSON Schema to a Python type annotation. Returns (type_annotation, needs_json_parsing). """ # Check for simple array first is_simple_arr, item_type = _is_simple_array(schema) if is_simple_arr: return f"list[{item_type}]", False # Check for simple type if _is_simple_type(schema): schema_type = schema.get("type", "string") if isinstance(schema_type, list): # Union of simple types type_map = { "string": "str", "integer": "int", "number": "float", "boolean": "bool", "null": "None", } parts = [type_map.get(t, "str") for t in schema_type] return " | ".join(parts), False type_map = { "string": "str", "integer": "int", "number": "float", "boolean": "bool", "null": "None", } return type_map.get(schema_type, "str"), False # Complex type - needs JSON parsing return "str", True def _format_schema_for_help(schema: dict[str, Any]) -> str: """Format a JSON schema for display in help text.""" # Pretty print the schema, indented for help text schema_str = pydantic_core.to_json(schema, indent=2).decode() # Indent each line for help text alignment lines = schema_str.split("\n") indented = "\n ".join(lines) return f"JSON Schema: {indented}" # --------------------------------------------------------------------------- # Transport serialization # --------------------------------------------------------------------------- def serialize_transport( resolved: str | dict[str, Any] | ClientTransport, ) -> tuple[str, set[str]]: """Serialize a resolved transport to a Python expression string. Returns ``(expression, extra_imports)`` where *extra_imports* is a set of import lines needed by the expression. """ if isinstance(resolved, str): return repr(resolved), set() if isinstance(resolved, StdioTransport): parts = [f"command={resolved.command!r}", f"args={resolved.args!r}"] if resolved.env: parts.append(f"env={resolved.env!r}") if resolved.cwd: parts.append(f"cwd={resolved.cwd!r}") expr = f"StdioTransport({', '.join(parts)})" imports = {"from fastmcp.client.transports import StdioTransport"} return expr, imports if isinstance(resolved, dict): return repr(resolved), set() # Fallback: try repr return repr(resolved), set() # --------------------------------------------------------------------------- # Per-tool code generation # --------------------------------------------------------------------------- def _to_python_identifier(name: str) -> str: """Sanitize a string into a valid Python identifier.""" safe = re.sub(r"[^a-zA-Z0-9_]", "_", name) if safe and safe[0].isdigit(): safe = f"_{safe}" safe = safe or "_unnamed" if keyword.iskeyword(safe): safe = f"{safe}_" return safe def _tool_function_source(tool: mcp.types.Tool) -> str: """Generate the source for a single ``@call_tool_app.command`` function.""" schema = tool.inputSchema properties: dict[str, Any] = schema.get("properties", {}) required = set(schema.get("required", [])) # Build parameter lines and track which need JSON parsing param_lines: list[str] = [] call_args: list[str] = [] json_params: list[tuple[str, str]] = [] # (prop_name, safe_name) seen_names: dict[str, str] = {} # safe_name -> original prop_name for prop_name, prop_schema in properties.items(): py_type, needs_json = _schema_to_python_type(prop_schema) help_text = prop_schema.get("description", "") is_required = prop_name in required safe_name = _to_python_identifier(prop_name) # Check for name collisions after sanitization if safe_name in seen_names: raise ValueError( f"Parameter name collision: '{prop_name}' and '{seen_names[safe_name]}' " f"both sanitize to '{safe_name}'" ) seen_names[safe_name] = prop_name # For complex types, add schema to help text if needs_json: schema_help = _format_schema_for_help(prop_schema) help_text = f"{help_text}\\n{schema_help}" if help_text else schema_help json_params.append((prop_name, safe_name)) # Escape special characters in help text help_escaped = ( help_text.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") ) # Build parameter annotation if is_required: annotation = ( f'Annotated[{py_type}, cyclopts.Parameter(help="{help_escaped}")]' ) param_lines.append(f" {safe_name}: {annotation},") else: default = prop_schema.get("default") if default is not None: # For complex types with defaults, serialize to JSON string if needs_json: default_str = pydantic_core.to_json(default, fallback=str).decode() annotation = f'Annotated[{py_type}, cyclopts.Parameter(help="{help_escaped}")]' param_lines.append( f" {safe_name}: {annotation} = {default_str!r}," ) else: annotation = f'Annotated[{py_type}, cyclopts.Parameter(help="{help_escaped}")]' param_lines.append(f" {safe_name}: {annotation} = {default!r},") else: # For list types, default to empty list; others default to None if py_type.startswith("list["): annotation = f'Annotated[{py_type}, cyclopts.Parameter(help="{help_escaped}")]' param_lines.append(f" {safe_name}: {annotation} = [],") else: annotation = f'Annotated[{py_type} | None, cyclopts.Parameter(help="{help_escaped}")]' param_lines.append(f" {safe_name}: {annotation} = None,") call_args.append(f"{prop_name!r}: {safe_name}") # Function name: sanitize to valid Python identifier fn_name = _to_python_identifier(tool.name) # Docstring - use single-quoted docstrings to avoid triple-quote escaping issues description = (tool.description or "").replace("\\", "\\\\").replace("'", "\\'") lines = [] lines.append("") # Always pass name= to preserve the original tool name (cyclopts # would otherwise convert underscores to hyphens). lines.append(f"@call_tool_app.command(name={tool.name!r})") lines.append(f"async def {fn_name}(") if param_lines: lines.append(" *,") lines.extend(param_lines) lines.append(") -> None:") lines.append(f" '''{description}'''") # Add JSON parsing for complex parameters if json_params: lines.append(" # Parse JSON parameters") for _prop_name, safe_name in json_params: lines.append( f" {safe_name}_parsed = json.loads({safe_name}) if isinstance({safe_name}, str) else {safe_name}" ) lines.append("") # Build call arguments, using parsed versions for JSON params call_arg_parts = [] for prop_name, _ in properties.items(): safe_name = _to_python_identifier(prop_name) if any(pn == prop_name for pn, _ in json_params): call_arg_parts.append(f"{prop_name!r}: {safe_name}_parsed") else: call_arg_parts.append(f"{prop_name!r}: {safe_name}") dict_items = ", ".join(call_arg_parts) lines.append(f" await _call_tool({tool.name!r}, {{{dict_items}}})") lines.append("") return "\n".join(lines) # --------------------------------------------------------------------------- # Full script generation # --------------------------------------------------------------------------- def generate_cli_script( server_name: str, server_spec: str, transport_code: str, extra_imports: set[str], tools: list[mcp.types.Tool], ) -> str: """Generate the full CLI script source code.""" # Determine app name from server_name - sanitize for use in string literal app_name = ( server_name.replace(" ", "-").lower().replace("\\", "\\\\").replace('"', '\\"') ) # --- Header --- lines: list[str] = [] lines.append("#!/usr/bin/env python3") lines.append(f'"""CLI for {server_name} MCP server.') lines.append("") lines.append(f"Generated by: fastmcp generate-cli {server_spec}") lines.append('"""') lines.append("") # --- Imports --- lines.append("import json") lines.append("import sys") lines.append("from typing import Annotated") lines.append("") lines.append("import cyclopts") lines.append("import mcp.types") lines.append("from rich.console import Console") lines.append("") lines.append("from fastmcp import Client") for imp in sorted(extra_imports): lines.append(imp) lines.append("") # --- Transport config --- lines.append("# Modify this to change how the CLI connects to the MCP server.") lines.append(f"CLIENT_SPEC = {transport_code}") lines.append("") # --- App setup --- server_name_escaped = server_name.replace("\\", "\\\\").replace('"', '\\"') lines.append( f'app = cyclopts.App(name="{app_name}", help="CLI for {server_name_escaped} MCP server")' ) lines.append( 'call_tool_app = cyclopts.App(name="call-tool", help="Call a tool on the server")' ) lines.append("app.command(call_tool_app)") lines.append("") lines.append("console = Console()") lines.append("") lines.append("") # --- Shared helpers --- lines.append( textwrap.dedent("""\ # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def _print_tool_result(result): if result.is_error: for block in result.content: if isinstance(block, mcp.types.TextContent): console.print(f"[bold red]Error:[/bold red] {block.text}") else: console.print(f"[bold red]Error:[/bold red] {block}") sys.exit(1) if result.structured_content is not None: console.print_json(json.dumps(result.structured_content)) return for block in result.content: if isinstance(block, mcp.types.TextContent): console.print(block.text) elif isinstance(block, mcp.types.ImageContent): size = len(block.data) * 3 // 4 console.print(f"[dim][Image: {block.mimeType}, ~{size} bytes][/dim]") elif isinstance(block, mcp.types.AudioContent): size = len(block.data) * 3 // 4 console.print(f"[dim][Audio: {block.mimeType}, ~{size} bytes][/dim]") async def _call_tool(tool_name: str, arguments: dict) -> None: # Filter out None values and empty lists (defaults for optional array params) filtered = { k: v for k, v in arguments.items() if v is not None and (not isinstance(v, list) or len(v) > 0) } async with Client(CLIENT_SPEC) as client: result = await client.call_tool(tool_name, filtered, raise_on_error=False) _print_tool_result(result) if result.is_error: sys.exit(1)""") ) lines.append("") lines.append("") # --- Generic commands --- lines.append( textwrap.dedent("""\ # --------------------------------------------------------------------------- # List / read commands # --------------------------------------------------------------------------- @app.command async def list_tools() -> None: \"\"\"List available tools.\"\"\" async with Client(CLIENT_SPEC) as client: tools = await client.list_tools() if not tools: console.print("[dim]No tools found.[/dim]") return for tool in tools: sig_parts = [] props = tool.inputSchema.get("properties", {}) required = set(tool.inputSchema.get("required", [])) for pname, pschema in props.items(): ptype = pschema.get("type", "string") if pname in required: sig_parts.append(f"{pname}: {ptype}") else: sig_parts.append(f"{pname}: {ptype} = ...") sig = f"{tool.name}({', '.join(sig_parts)})" console.print(f" [cyan]{sig}[/cyan]") if tool.description: console.print(f" {tool.description}") console.print() @app.command async def list_resources() -> None: \"\"\"List available resources.\"\"\" async with Client(CLIENT_SPEC) as client: resources = await client.list_resources() if not resources: console.print("[dim]No resources found.[/dim]") return for r in resources: console.print(f" [cyan]{r.uri}[/cyan]") desc_parts = [r.name or "", r.description or ""] desc = " — ".join(p for p in desc_parts if p) if desc: console.print(f" {desc}") console.print() @app.command async def read_resource(uri: Annotated[str, cyclopts.Parameter(help="Resource URI")]) -> None: \"\"\"Read a resource by URI.\"\"\" async with Client(CLIENT_SPEC) as client: contents = await client.read_resource(uri) for block in contents: if isinstance(block, mcp.types.TextResourceContents): console.print(block.text) elif isinstance(block, mcp.types.BlobResourceContents): size = len(block.blob) * 3 // 4 console.print(f"[dim][Blob: {block.mimeType}, ~{size} bytes][/dim]") @app.command async def list_prompts() -> None: \"\"\"List available prompts.\"\"\" async with Client(CLIENT_SPEC) as client: prompts = await client.list_prompts() if not prompts: console.print("[dim]No prompts found.[/dim]") return for p in prompts: args_str = "" if p.arguments: parts = [a.name for a in p.arguments] args_str = f"({', '.join(parts)})" console.print(f" [cyan]{p.name}{args_str}[/cyan]") if p.description: console.print(f" {p.description}") console.print() @app.command async def get_prompt( name: Annotated[str, cyclopts.Parameter(help="Prompt name")], *arguments: str, ) -> None: \"\"\"Get a prompt by name. Pass arguments as key=value pairs.\"\"\" parsed: dict[str, str] = {} for arg in arguments: if "=" not in arg: console.print(f"[bold red]Error:[/bold red] Invalid argument {arg!r} — expected key=value") sys.exit(1) key, value = arg.split("=", 1) parsed[key] = value async with Client(CLIENT_SPEC) as client: result = await client.get_prompt(name, parsed or None) for msg in result.messages: console.print(f"[bold]{msg.role}:[/bold]") if isinstance(msg.content, mcp.types.TextContent): console.print(f" {msg.content.text}") elif isinstance(msg.content, mcp.types.ImageContent): size = len(msg.content.data) * 3 // 4 console.print(f" [dim][Image: {msg.content.mimeType}, ~{size} bytes][/dim]") else: console.print(f" {msg.content}") console.print()""") ) lines.append("") lines.append("") # --- Generated tool commands --- if tools: lines.append( "# ---------------------------------------------------------------------------" ) lines.append("# Tool commands (generated from server schema)") lines.append( "# ---------------------------------------------------------------------------" ) for tool in tools: lines.append(_tool_function_source(tool)) # --- Entry point --- lines.append("") lines.append('if __name__ == "__main__":') lines.append(" app()") lines.append("") return "\n".join(lines) # --------------------------------------------------------------------------- # Skill (SKILL.md) generation # --------------------------------------------------------------------------- _JSON_SCHEMA_TYPE_LABELS: dict[str, str] = { "string": "string", "integer": "integer", "number": "number", "boolean": "boolean", "null": "null", "array": "array", "object": "object", } def _param_to_cli_flag(prop_name: str) -> str: """Convert a JSON Schema property name to its CLI flag form. Replicates cyclopts' default_name_transform: camelCase → snake_case, lowercase, underscores → hyphens, strip leading/trailing hyphens. """ safe = _to_python_identifier(prop_name) # camelCase / PascalCase → snake_case safe = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", safe) safe = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", safe) safe = safe.lower().replace("_", "-").strip("-") return f"--{safe}" if safe else "--arg" def _schema_type_label(prop_schema: dict[str, Any]) -> str: """Return a human-readable type label for a property schema.""" schema_type = prop_schema.get("type", "string") if isinstance(schema_type, list): labels = [_JSON_SCHEMA_TYPE_LABELS.get(t, t) for t in schema_type] return " | ".join(labels) label = _JSON_SCHEMA_TYPE_LABELS.get(schema_type, schema_type) # For arrays, include item type if simple if schema_type == "array": items = prop_schema.get("items", {}) item_type = items.get("type", "") if isinstance(item_type, str) and item_type in _JSON_SCHEMA_TYPE_LABELS: return f"array[{item_type}]" return label def _tool_skill_section(tool: mcp.types.Tool, cli_filename: str) -> str: """Generate a SKILL.md section for a single tool.""" schema = tool.inputSchema properties: dict[str, Any] = schema.get("properties", {}) required = set(schema.get("required", [])) # Build example invocation flags flag_parts_list: list[str] = [] for p, p_schema in properties.items(): flag = _param_to_cli_flag(p) schema_type = p_schema.get("type") is_bool = schema_type == "boolean" or ( isinstance(schema_type, list) and "boolean" in schema_type ) if is_bool: flag_parts_list.append(flag) else: flag_parts_list.append(f"{flag} <value>") flag_parts = " ".join(flag_parts_list) invocation = f"uv run --with fastmcp python {cli_filename} call-tool {tool.name}" if flag_parts: invocation += f" {flag_parts}" # Build parameter table rows rows: list[str] = [] for prop_name, prop_schema in properties.items(): flag = f"`{_param_to_cli_flag(prop_name)}`" type_label = _schema_type_label(prop_schema).replace("|", "\\|") is_required = "yes" if prop_name in required else "no" description = prop_schema.get("description", "") _, needs_json = _schema_to_python_type(prop_schema) if needs_json: description = ( f"{description} (JSON string)" if description else "JSON string" ) description = description.replace("\n", " ").replace("|", "\\|") rows.append(f"| {flag} | {type_label} | {is_required} | {description} |") param_table = "" if rows: header = "| Flag | Type | Required | Description |\n|------|------|----------|-------------|" param_table = f"\n{header}\n" + "\n".join(rows) + "\n" lines: list[str] = [f"### {tool.name}"] if tool.description: lines.extend(["", tool.description]) lines.extend(["", "```bash", invocation, "```"]) if param_table: lines.extend(["", param_table.strip("\n")]) return "\n".join(lines) def generate_skill_content( server_name: str, cli_filename: str, tools: list[mcp.types.Tool], ) -> str: """Generate a SKILL.md file for a generated CLI script.""" skill_name = ( server_name.replace(" ", "-").lower().replace("\\", "").replace('"', "") ) safe_name = server_name.replace("\\", "").replace('"', "") description = f"CLI for the {safe_name} MCP server. Call tools, list resources, and get prompts." lines = [ "---", f'name: "{skill_name}-cli"', f'description: "{description}"', "---", "", f"# {server_name} CLI", "", ] if tools: tool_bodies = "\n\n".join( _tool_skill_section(tool, cli_filename) for tool in tools ) lines.extend(["## Tool Commands", "", tool_bodies, ""]) lines.extend( [ "## Utility Commands", "", "```bash", f"uv run --with fastmcp python {cli_filename} list-tools", f"uv run --with fastmcp python {cli_filename} list-resources", f"uv run --with fastmcp python {cli_filename} read-resource <uri>", f"uv run --with fastmcp python {cli_filename} list-prompts", f"uv run --with fastmcp python {cli_filename} get-prompt <name> [key=value ...]", "```", "", ] ) return "\n".join(lines) # --------------------------------------------------------------------------- # CLI command # --------------------------------------------------------------------------- async def generate_cli_command( server_spec: Annotated[ str, cyclopts.Parameter( help="Server URL, Python file, MCPConfig JSON, discovered name, or .js file", ), ], output: Annotated[ str, cyclopts.Parameter( help="Output file path (default: cli.py)", ), ] = "cli.py", *, force: Annotated[ bool, cyclopts.Parameter( name=["-f", "--force"], help="Overwrite output file if it exists", ), ] = False, timeout: Annotated[ float | None, cyclopts.Parameter("--timeout", help="Connection timeout in seconds"), ] = None, auth: Annotated[ str | None, cyclopts.Parameter( "--auth", help="Auth method: 'oauth', a bearer token string, or 'none' to disable", ), ] = None, no_skill: Annotated[ bool, cyclopts.Parameter( "--no-skill", help="Skip generating a SKILL.md agent skill alongside the CLI", ), ] = False, ) -> None: """Generate a standalone CLI script from an MCP server. Connects to the server, reads its tools/resources/prompts, and writes a Python script that can invoke them directly. Also generates a SKILL.md agent skill file unless --no-skill is passed. Examples: fastmcp generate-cli weather fastmcp generate-cli weather my_cli.py fastmcp generate-cli http://localhost:8000/mcp fastmcp generate-cli server.py output.py -f fastmcp generate-cli weather --no-skill """ output_path = Path(output) skill_path = output_path.parent / "SKILL.md" # Check both files up front before doing any work existing: list[Path] = [] if output_path.exists() and not force: existing.append(output_path) if not no_skill and skill_path.exists() and not force: existing.append(skill_path) if existing: names = ", ".join(f"[cyan]{p}[/cyan]" for p in existing) console.print( f"[bold red]Error:[/bold red] {names} already exist(s). " f"Use [cyan]-f[/cyan] to overwrite." ) sys.exit(1) # Resolve the server spec to a transport resolved = resolve_server_spec(server_spec) transport_code, extra_imports = serialize_transport(resolved) # Derive a human-friendly server name from the spec server_name = _derive_server_name(server_spec) # Connect and discover capabilities client = _build_client(resolved, timeout=timeout, auth=auth) try: async with client: tools = await client.list_tools() console.print( f"[dim]Discovered {len(tools)} tool(s) from {server_spec}[/dim]" ) except (RuntimeError, TimeoutError, McpError, OSError) as exc: console.print(f"[bold red]Error:[/bold red] Could not connect: {exc}") sys.exit(1) # Generate and write the script script = generate_cli_script( server_name=server_name, server_spec=server_spec, transport_code=transport_code, extra_imports=extra_imports, tools=tools, ) output_path.write_text(script) output_path.chmod(output_path.stat().st_mode | 0o111) # make executable console.print( f"[green]✓[/green] Wrote [cyan]{output_path}[/cyan] " f"with {len(tools)} tool command(s)" ) if not no_skill: skill_content = generate_skill_content( server_name=server_name, cli_filename=output_path.name, tools=tools, ) skill_path.write_text(skill_content) console.print(f"[green]✓[/green] Wrote [cyan]{skill_path}[/cyan]") console.print(f"[dim]Run: python {output_path} --help[/dim]") def _derive_server_name(server_spec: str) -> str: """Derive a human-friendly name from a server spec.""" # URL — use hostname if server_spec.startswith(("http://", "https://")): parsed = urlparse(server_spec) return parsed.hostname or "server" # File path — use stem if server_spec.endswith((".py", ".js", ".json")): return Path(server_spec).stem # Bare name or qualified name if ":" in server_spec: name = server_spec.split(":", 1)[1] return name or server_spec.split(":", 1)[0] return server_spec
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/cli/generate.py", "license": "Apache License 2.0", "lines": 680, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:src/fastmcp/server/auth/cimd.py
"""CIMD (Client ID Metadata Document) support for FastMCP. .. warning:: **Beta Feature**: CIMD support is currently in beta. The API may change in future releases. Please report any issues you encounter. CIMD is a simpler alternative to Dynamic Client Registration where clients host a static JSON document at an HTTPS URL, and that URL becomes their client_id. See the IETF draft: draft-parecki-oauth-client-id-metadata-document This module provides: - CIMDDocument: Pydantic model for CIMD document validation - CIMDFetcher: Fetch and validate CIMD documents with SSRF protection - CIMDClientManager: Manages CIMD client operations """ from __future__ import annotations import fnmatch import json import time from collections.abc import Mapping from dataclasses import dataclass from datetime import timezone from email.utils import parsedate_to_datetime from typing import TYPE_CHECKING, Any, Literal from urllib.parse import urlparse from pydantic import AnyHttpUrl, BaseModel, Field, field_validator from fastmcp.server.auth.ssrf import ( SSRFError, SSRFFetchError, ssrf_safe_fetch_response, validate_url, ) from fastmcp.utilities.logging import get_logger if TYPE_CHECKING: from fastmcp.server.auth.providers.jwt import JWTVerifier logger = get_logger(__name__) class CIMDDocument(BaseModel): """CIMD document per draft-parecki-oauth-client-id-metadata-document. The client metadata document is a JSON document containing OAuth client metadata. The client_id property MUST match the URL where this document is hosted. Key constraint: token_endpoint_auth_method MUST NOT use shared secrets (client_secret_post, client_secret_basic, client_secret_jwt). redirect_uris is required and must contain at least one entry. """ client_id: AnyHttpUrl = Field( ..., description="Must match the URL where this document is hosted", ) client_name: str | None = Field( default=None, description="Human-readable name of the client", ) client_uri: AnyHttpUrl | None = Field( default=None, description="URL of the client's home page", ) logo_uri: AnyHttpUrl | None = Field( default=None, description="URL of the client's logo image", ) redirect_uris: list[str] = Field( ..., description="Array of allowed redirect URIs (may include wildcards like http://localhost:*/callback)", ) token_endpoint_auth_method: Literal["none", "private_key_jwt"] = Field( default="none", description="Authentication method for token endpoint (no shared secrets allowed)", ) grant_types: list[str] = Field( default_factory=lambda: ["authorization_code"], description="OAuth grant types the client will use", ) response_types: list[str] = Field( default_factory=lambda: ["code"], description="OAuth response types the client will use", ) scope: str | None = Field( default=None, description="Space-separated list of scopes the client may request", ) contacts: list[str] | None = Field( default=None, description="Contact information for the client developer", ) tos_uri: AnyHttpUrl | None = Field( default=None, description="URL of the client's terms of service", ) policy_uri: AnyHttpUrl | None = Field( default=None, description="URL of the client's privacy policy", ) jwks_uri: AnyHttpUrl | None = Field( default=None, description="URL of the client's JSON Web Key Set (for private_key_jwt)", ) jwks: dict[str, Any] | None = Field( default=None, description="Client's JSON Web Key Set (for private_key_jwt)", ) software_id: str | None = Field( default=None, description="Unique identifier for the client software", ) software_version: str | None = Field( default=None, description="Version of the client software", ) @field_validator("token_endpoint_auth_method") @classmethod def validate_auth_method(cls, v: str) -> str: """Ensure no shared-secret auth methods are used.""" forbidden = {"client_secret_post", "client_secret_basic", "client_secret_jwt"} if v in forbidden: raise ValueError( f"CIMD documents cannot use shared-secret auth methods: {v}. " "Use 'none' or 'private_key_jwt' instead." ) return v @field_validator("redirect_uris") @classmethod def validate_redirect_uris(cls, v: list[str]) -> list[str]: """Ensure redirect_uris is non-empty and each entry is a valid URI.""" if not v: raise ValueError("CIMD documents must include at least one redirect_uri") for uri in v: if not uri or not uri.strip(): raise ValueError("CIMD redirect_uris must be non-empty strings") parsed = urlparse(uri) if not parsed.scheme: raise ValueError( f"CIMD redirect_uri must have a scheme (e.g. http:// or https://): {uri!r}" ) if not parsed.netloc and not uri.startswith("urn:"): raise ValueError(f"CIMD redirect_uri must have a host: {uri!r}") return v class CIMDValidationError(Exception): """Raised when CIMD document validation fails.""" class CIMDFetchError(Exception): """Raised when CIMD document fetching fails.""" @dataclass class _CIMDCacheEntry: """Cached CIMD document and associated HTTP cache metadata.""" doc: CIMDDocument etag: str | None last_modified: str | None expires_at: float freshness_lifetime: float must_revalidate: bool @dataclass class _CIMDCachePolicy: """Normalized cache directives parsed from HTTP response headers.""" etag: str | None last_modified: str | None expires_at: float freshness_lifetime: float no_store: bool must_revalidate: bool class CIMDFetcher: """Fetch and validate CIMD documents with SSRF protection. Delegates HTTP fetching to ssrf_safe_fetch_response, which provides DNS pinning, IP validation, size limits, and timeout enforcement. Documents are cached using HTTP caching semantics (Cache-Control/ETag/Last-Modified), with a TTL fallback when response headers do not define caching behavior. """ # Maximum response size (bytes) MAX_RESPONSE_SIZE = 5120 # 5KB # Default cache TTL (seconds) DEFAULT_CACHE_TTL_SECONDS = 3600 def __init__( self, timeout: float = 10.0, ): """Initialize the CIMD fetcher. Args: timeout: HTTP request timeout in seconds (default 10.0) """ self.timeout = timeout self._cache: dict[str, _CIMDCacheEntry] = {} def _parse_cache_policy( self, headers: Mapping[str, str], now: float ) -> _CIMDCachePolicy: """Parse HTTP cache headers and derive cache behavior.""" normalized = {k.lower(): v for k, v in headers.items()} cache_control = normalized.get("cache-control", "") directives = { part.strip().lower() for part in cache_control.split(",") if part.strip() } no_store = "no-store" in directives must_revalidate = "no-cache" in directives max_age: int | None = None for directive in directives: if directive.startswith("max-age="): value = directive.removeprefix("max-age=").strip() try: max_age = max(0, int(value)) except ValueError: logger.debug( "Ignoring invalid Cache-Control max-age value: %s", value ) break expires_at: float | None = None if max_age is not None: expires_at = now + max_age elif "expires" in normalized: try: dt = parsedate_to_datetime(normalized["expires"]) if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc) expires_at = dt.timestamp() except (TypeError, ValueError): logger.debug( "Ignoring invalid Expires header on CIMD response: %s", normalized["expires"], ) if expires_at is None: expires_at = now + self.DEFAULT_CACHE_TTL_SECONDS freshness_lifetime = max(0.0, expires_at - now) return _CIMDCachePolicy( etag=normalized.get("etag"), last_modified=normalized.get("last-modified"), expires_at=expires_at, freshness_lifetime=freshness_lifetime, no_store=no_store, must_revalidate=must_revalidate, ) def _has_freshness_headers(self, headers: Mapping[str, str]) -> bool: """Return True when response includes cache freshness directives.""" normalized = {k.lower() for k in headers} return "cache-control" in normalized or "expires" in normalized def is_cimd_client_id(self, client_id: str) -> bool: """Check if a client_id looks like a CIMD URL. CIMD URLs must be HTTPS with a host and non-root path. """ if not client_id: return False try: parsed = urlparse(client_id) return ( parsed.scheme == "https" and bool(parsed.netloc) and parsed.path not in ("", "/") ) except (ValueError, AttributeError): return False async def fetch(self, client_id_url: str) -> CIMDDocument: """Fetch and validate a CIMD document with SSRF protection. Uses ssrf_safe_fetch_response for the HTTP layer, which provides: - HTTPS only, DNS resolution with IP validation - DNS pinning (connects to validated IP directly) - Blocks private/loopback/link-local/multicast IPs - Response size limit and timeout enforcement - Redirects disabled Args: client_id_url: The URL to fetch (also the expected client_id) Returns: Validated CIMDDocument Raises: CIMDValidationError: If document is invalid or URL blocked CIMDFetchError: If document cannot be fetched """ cached = self._cache.get(client_id_url) now = time.time() request_headers: dict[str, str] | None = None allowed_status_codes = {200} if cached is not None: if not cached.must_revalidate and now < cached.expires_at: return cached.doc request_headers = {} if cached.etag: request_headers["If-None-Match"] = cached.etag if cached.last_modified: request_headers["If-Modified-Since"] = cached.last_modified if request_headers: allowed_status_codes = {200, 304} try: response = await ssrf_safe_fetch_response( client_id_url, require_path=True, max_size=self.MAX_RESPONSE_SIZE, timeout=self.timeout, overall_timeout=30.0, request_headers=request_headers, allowed_status_codes=allowed_status_codes, ) except SSRFError as e: raise CIMDValidationError(str(e)) from e except SSRFFetchError as e: raise CIMDFetchError(str(e)) from e if response.status_code == 304: if cached is None: raise CIMDFetchError( "CIMD server returned 304 Not Modified without cached document" ) now = time.time() if self._has_freshness_headers(response.headers): policy = self._parse_cache_policy(response.headers, now) else: # RFC allows 304 to omit unchanged headers. Preserve existing # cache policy rather than resetting to fallback defaults. policy = _CIMDCachePolicy( etag=None, last_modified=None, expires_at=now + cached.freshness_lifetime, freshness_lifetime=cached.freshness_lifetime, no_store=False, must_revalidate=cached.must_revalidate, ) if not policy.no_store: self._cache[client_id_url] = _CIMDCacheEntry( doc=cached.doc, etag=policy.etag or cached.etag, last_modified=policy.last_modified or cached.last_modified, expires_at=policy.expires_at, freshness_lifetime=policy.freshness_lifetime, must_revalidate=policy.must_revalidate, ) else: self._cache.pop(client_id_url, None) return cached.doc now = time.time() policy = self._parse_cache_policy(response.headers, now) try: data = json.loads(response.content) except json.JSONDecodeError as e: raise CIMDValidationError(f"CIMD document is not valid JSON: {e}") from e try: doc = CIMDDocument.model_validate(data) except Exception as e: raise CIMDValidationError(f"Invalid CIMD document: {e}") from e if str(doc.client_id).rstrip("/") != client_id_url.rstrip("/"): raise CIMDValidationError( f"CIMD client_id mismatch: document says '{doc.client_id}' " f"but was fetched from '{client_id_url}'" ) # Validate jwks_uri if present (SSRF check for JWKS endpoint) if doc.jwks_uri: jwks_uri_str = str(doc.jwks_uri) try: await validate_url(jwks_uri_str) except SSRFError as e: raise CIMDValidationError( f"CIMD jwks_uri failed SSRF validation: {e}" ) from e logger.info( "CIMD document fetched and validated: %s (client_name=%s)", client_id_url, doc.client_name, ) if not policy.no_store: self._cache[client_id_url] = _CIMDCacheEntry( doc=doc, etag=policy.etag, last_modified=policy.last_modified, expires_at=policy.expires_at, freshness_lifetime=policy.freshness_lifetime, must_revalidate=policy.must_revalidate, ) else: self._cache.pop(client_id_url, None) return doc def validate_redirect_uri(self, doc: CIMDDocument, redirect_uri: str) -> bool: """Validate that a redirect_uri is allowed by the CIMD document. Args: doc: The CIMD document redirect_uri: The redirect URI to validate Returns: True if valid, False otherwise """ if not doc.redirect_uris: # No redirect_uris specified - reject all return False # Normalize for comparison redirect_uri = redirect_uri.rstrip("/") for allowed in doc.redirect_uris: allowed_str = allowed.rstrip("/") if redirect_uri == allowed_str: return True # Check for wildcard port matching (http://localhost:*/callback) if "*" in allowed_str: if fnmatch.fnmatch(redirect_uri, allowed_str): return True return False class CIMDAssertionValidator: """Validates JWT assertions for private_key_jwt CIMD clients. Implements RFC 7523 (JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants) for CIMD client authentication. JTI replay protection uses TTL-based caching to ensure proper security: - JTIs are cached with expiration matching the JWT's exp claim - Expired JTIs are automatically cleaned up - Maximum assertion lifetime is enforced (5 minutes) """ # Maximum allowed assertion lifetime in seconds (RFC 7523 recommends short-lived) MAX_ASSERTION_LIFETIME = 300 # 5 minutes def __init__(self): # JTI cache: maps jti -> expiration timestamp self._jti_cache: dict[str, float] = {} self._jti_cache_max_size = 10000 self._last_cleanup = time.monotonic() self._cleanup_interval = 60 # Cleanup every 60 seconds # Cache JWTVerifier per jwks_uri so JWKS keys are not re-fetched # on every token exchange self._verifier_cache: dict[str, JWTVerifier] = {} self._verifier_cache_max_size = 100 self.logger = get_logger(__name__) def _cleanup_expired_jtis(self) -> None: """Remove expired JTIs from cache.""" now = time.time() expired = [jti for jti, exp in self._jti_cache.items() if exp < now] for jti in expired: del self._jti_cache[jti] if expired: self.logger.debug("Cleaned up %d expired JTIs from cache", len(expired)) def _maybe_cleanup(self) -> None: """Periodically cleanup expired JTIs to prevent unbounded growth.""" now = time.monotonic() if now - self._last_cleanup > self._cleanup_interval: self._cleanup_expired_jtis() self._last_cleanup = now async def validate_assertion( self, assertion: str, client_id: str, token_endpoint: str, cimd_doc: CIMDDocument, ) -> bool: """Validate JWT assertion from client. Args: assertion: The JWT assertion string client_id: Expected client_id (must match iss and sub claims) token_endpoint: Token endpoint URL (must match aud claim) cimd_doc: CIMD document containing JWKS for key verification Returns: True if valid Raises: ValueError: If validation fails """ from fastmcp.server.auth.providers.jwt import JWTVerifier as _JWTVerifier # Periodic cleanup of expired JTIs self._maybe_cleanup() # 1. Validate CIMD document has key material and get/create verifier if cimd_doc.jwks_uri: jwks_uri_str = str(cimd_doc.jwks_uri) cache_key = f"{jwks_uri_str}|{client_id}|{token_endpoint}" verifier = self._verifier_cache.get(cache_key) if verifier is None: verifier = _JWTVerifier( jwks_uri=jwks_uri_str, issuer=client_id, audience=token_endpoint, ssrf_safe=True, ) if len(self._verifier_cache) >= self._verifier_cache_max_size: oldest_key = next(iter(self._verifier_cache)) del self._verifier_cache[oldest_key] self._verifier_cache[cache_key] = verifier elif cimd_doc.jwks: # Inline JWKS — no caching since the key is embedded public_key = self._extract_public_key_from_jwks(assertion, cimd_doc.jwks) verifier = _JWTVerifier( public_key=public_key, issuer=client_id, audience=token_endpoint, ) else: raise ValueError( "CIMD document must have jwks_uri or jwks for private_key_jwt" ) # 2. Verify JWT using JWTVerifier (handles signature, exp, iss, aud) access_token = await verifier.load_access_token(assertion) if not access_token: raise ValueError("Invalid JWT assertion") claims = access_token.claims # 3. Validate assertion lifetime (exp and iat) now = time.time() exp = claims.get("exp") iat = claims.get("iat") if not exp: raise ValueError("Assertion must include exp claim") # Validate exp is in the future (with small clock skew tolerance) if exp < now - 30: # 30 second clock skew tolerance raise ValueError("Assertion has expired") # If iat is present, validate it and check assertion lifetime if iat: if iat > now + 30: # 30 second clock skew tolerance raise ValueError("Assertion iat is in the future") if exp - iat > self.MAX_ASSERTION_LIFETIME: raise ValueError( f"Assertion lifetime too long: {exp - iat}s (max {self.MAX_ASSERTION_LIFETIME}s)" ) else: # No iat, enforce max lifetime from now if exp > now + self.MAX_ASSERTION_LIFETIME: raise ValueError( f"Assertion exp too far in future (max {self.MAX_ASSERTION_LIFETIME}s)" ) # 4. Additional RFC 7523 validation: sub claim must equal client_id if claims.get("sub") != client_id: raise ValueError(f"Assertion sub claim must be {client_id}") # 5. Check jti for replay attacks (RFC 7523 requirement) jti = claims.get("jti") if not jti: raise ValueError("Assertion must include jti claim") # Check if JTI was already used (and hasn't expired from cache) if jti in self._jti_cache: cached_exp = self._jti_cache[jti] if cached_exp > now: # Still valid in cache raise ValueError(f"Assertion replay detected: jti {jti} already used") # Expired in cache, can be reused (clean it up) del self._jti_cache[jti] # Add to cache with expiration time # Use the assertion's exp claim so it stays cached until it would expire anyway self._jti_cache[jti] = exp # Emergency size limit (shouldn't hit with proper TTL cleanup) if len(self._jti_cache) > self._jti_cache_max_size: self._cleanup_expired_jtis() # If still over limit after cleanup, reject to prevent DoS if len(self._jti_cache) > self._jti_cache_max_size: self.logger.warning( "JTI cache at max capacity (%d), possible attack", self._jti_cache_max_size, ) raise ValueError("Server overloaded, please retry") self.logger.debug( "JWT assertion validated successfully for client %s", client_id ) return True def _extract_public_key_from_jwks(self, token: str, jwks: dict) -> str: """Extract public key from inline JWKS. Args: token: JWT token to extract kid from jwks: JWKS document containing keys Returns: PEM-encoded public key Raises: ValueError: If key cannot be found or extracted """ import base64 import json from authlib.jose import JsonWebKey # Extract kid from token header try: header_b64 = token.split(".")[0] header_b64 += "=" * (4 - len(header_b64) % 4) # Add padding header = json.loads(base64.urlsafe_b64decode(header_b64)) kid = header.get("kid") except Exception as e: raise ValueError(f"Failed to extract key ID from token: {e}") from e # Find matching key in JWKS keys = jwks.get("keys", []) if not keys: raise ValueError("JWKS document contains no keys") matching_key = None for key in keys: if kid and key.get("kid") == kid: matching_key = key break if not matching_key: # If no kid match, try first key as fallback if len(keys) == 1: matching_key = keys[0] self.logger.warning( "No matching kid in JWKS, using single available key" ) else: raise ValueError(f"No matching key found for kid={kid} in JWKS") # Convert JWK to PEM try: jwk = JsonWebKey.import_key(matching_key) return jwk.as_pem().decode("utf-8") except Exception as e: raise ValueError(f"Failed to convert JWK to PEM: {e}") from e class CIMDClientManager: """Manages all CIMD client operations for OAuth proxy. This class encapsulates: - CIMD client detection - Document fetching and validation - Synthetic OAuth client creation - Private key JWT assertion validation This allows the OAuth proxy to delegate all CIMD-specific logic to a single, focused manager class. """ def __init__( self, enable_cimd: bool = True, default_scope: str = "", allowed_redirect_uri_patterns: list[str] | None = None, ): """Initialize CIMD client manager. Args: enable_cimd: Whether CIMD support is enabled default_scope: Default scope for CIMD clients if not specified in document allowed_redirect_uri_patterns: Allowed redirect URI patterns (proxy's config) """ self.enabled = enable_cimd self.default_scope = default_scope self.allowed_redirect_uri_patterns = allowed_redirect_uri_patterns self._fetcher = CIMDFetcher() self._assertion_validator = CIMDAssertionValidator() self.logger = get_logger(__name__) def is_cimd_client_id(self, client_id: str) -> bool: """Check if client_id is a CIMD URL. Args: client_id: Client ID to check Returns: True if client_id is an HTTPS URL (CIMD format) """ return self.enabled and self._fetcher.is_cimd_client_id(client_id) async def get_client(self, client_id_url: str): """Fetch CIMD document and create synthetic OAuth client. Args: client_id_url: HTTPS URL pointing to CIMD document Returns: OAuthProxyClient with CIMD document attached, or None if fetch fails Note: Return type is left untyped to avoid circular import with oauth_proxy. Returns OAuthProxyClient instance or None. """ if not self.enabled: return None try: cimd_doc = await self._fetcher.fetch(client_id_url) except (CIMDFetchError, CIMDValidationError) as e: self.logger.warning("CIMD fetch failed for %s: %s", client_id_url, e) return None # Import here to avoid circular dependency from fastmcp.server.auth.oauth_proxy.models import ProxyDCRClient # Create synthetic client from CIMD document. # Keep CIMD redirect_uris as strings on the document itself so wildcard # patterns like http://localhost:*/callback remain valid. redirect_uris = None client = ProxyDCRClient( client_id=client_id_url, client_secret=None, redirect_uris=redirect_uris, grant_types=cimd_doc.grant_types, scope=cimd_doc.scope or self.default_scope, token_endpoint_auth_method=cimd_doc.token_endpoint_auth_method, allowed_redirect_uri_patterns=self.allowed_redirect_uri_patterns, client_name=cimd_doc.client_name, cimd_document=cimd_doc, cimd_fetched_at=time.time(), ) self.logger.debug( "CIMD client resolved: %s (name=%s)", client_id_url, cimd_doc.client_name, ) return client async def validate_private_key_jwt( self, assertion: str, client, # OAuthProxyClient, untyped to avoid circular import token_endpoint: str, ) -> bool: """Validate JWT assertion for private_key_jwt auth. Args: assertion: JWT assertion string from client client: OAuth proxy client (must have cimd_document) token_endpoint: Token endpoint URL for aud validation Returns: True if assertion is valid Raises: ValueError: If client doesn't have CIMD document or validation fails """ if not hasattr(client, "cimd_document") or not client.cimd_document: raise ValueError("Client must have CIMD document for private_key_jwt") cimd_doc = client.cimd_document if cimd_doc.token_endpoint_auth_method != "private_key_jwt": raise ValueError("CIMD document must specify private_key_jwt auth method") return await self._assertion_validator.validate_assertion( assertion, client.client_id, token_endpoint, cimd_doc )
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/server/auth/cimd.py", "license": "Apache License 2.0", "lines": 671, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:src/fastmcp/server/auth/ssrf.py
"""SSRF-safe HTTP utilities for FastMCP. This module provides SSRF-protected HTTP fetching with: - DNS resolution and IP validation before requests - DNS pinning to prevent rebinding TOCTOU attacks - Support for both CIMD and JWKS fetches """ from __future__ import annotations import asyncio import ipaddress import socket import time from collections.abc import Mapping from dataclasses import dataclass from urllib.parse import urlparse import httpx from fastmcp.utilities.logging import get_logger logger = get_logger(__name__) def format_ip_for_url(ip_str: str) -> str: """Format IP address for use in URL (bracket IPv6 addresses). IPv6 addresses must be bracketed in URLs to distinguish the address from the port separator. For example: https://[2001:db8::1]:443/path Args: ip_str: IP address string Returns: IP string suitable for URL (IPv6 addresses are bracketed) """ try: ip = ipaddress.ip_address(ip_str) if isinstance(ip, ipaddress.IPv6Address): return f"[{ip_str}]" return ip_str except ValueError: return ip_str class SSRFError(Exception): """Raised when an SSRF protection check fails.""" class SSRFFetchError(Exception): """Raised when SSRF-safe fetch fails.""" def is_ip_allowed(ip_str: str) -> bool: """Check if an IP address is allowed (must be globally routable unicast). Uses ip.is_global which catches: - Private (10.x, 172.16-31.x, 192.168.x) - Loopback (127.x, ::1) - Link-local (169.254.x, fe80::) - includes AWS metadata! - Reserved, unspecified - RFC6598 Carrier-Grade NAT (100.64.0.0/10) - can point to internal networks Additionally blocks multicast addresses (not caught by is_global). Args: ip_str: IP address string to check Returns: True if the IP is allowed (public unicast internet), False if blocked """ try: ip = ipaddress.ip_address(ip_str) except ValueError: return False if not ip.is_global: return False # Block multicast (not caught by is_global for some ranges) if ip.is_multicast: return False # IPv6-specific checks for embedded IPv4 addresses if isinstance(ip, ipaddress.IPv6Address): if ip.ipv4_mapped: return is_ip_allowed(str(ip.ipv4_mapped)) if ip.sixtofour: return is_ip_allowed(str(ip.sixtofour)) if ip.teredo: server, client = ip.teredo return is_ip_allowed(str(server)) and is_ip_allowed(str(client)) return True async def resolve_hostname(hostname: str, port: int = 443) -> list[str]: """Resolve hostname to IP addresses using DNS. Args: hostname: Hostname to resolve port: Port number (used for getaddrinfo) Returns: List of resolved IP addresses Raises: SSRFError: If resolution fails """ loop = asyncio.get_running_loop() try: infos = await loop.run_in_executor( None, lambda: socket.getaddrinfo( hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM ), ) ips = list({info[4][0] for info in infos}) if not ips: raise SSRFError(f"DNS resolution returned no addresses for {hostname}") return ips except socket.gaierror as e: raise SSRFError(f"DNS resolution failed for {hostname}: {e}") from e @dataclass class ValidatedURL: """A URL that has been validated for SSRF with resolved IPs.""" original_url: str hostname: str port: int path: str resolved_ips: list[str] @dataclass class SSRFFetchResponse: """Response payload from an SSRF-safe fetch.""" content: bytes status_code: int headers: dict[str, str] async def validate_url(url: str, require_path: bool = False) -> ValidatedURL: """Validate URL for SSRF and resolve to IPs. Args: url: URL to validate require_path: If True, require non-root path (for CIMD) Returns: ValidatedURL with resolved IPs Raises: SSRFError: If URL is invalid or resolves to blocked IPs """ try: parsed = urlparse(url) except (ValueError, AttributeError) as e: raise SSRFError(f"Invalid URL: {e}") from e if parsed.scheme != "https": raise SSRFError(f"URL must use HTTPS, got: {parsed.scheme}") if not parsed.netloc: raise SSRFError("URL must have a host") if require_path and parsed.path in ("", "/"): raise SSRFError("URL must have a non-root path") hostname = parsed.hostname or parsed.netloc port = parsed.port or 443 # Resolve and validate IPs resolved_ips = await resolve_hostname(hostname, port) blocked = [ip for ip in resolved_ips if not is_ip_allowed(ip)] if blocked: raise SSRFError( f"URL resolves to blocked IP address(es): {blocked}. " f"Private, loopback, link-local, and reserved IPs are not allowed." ) return ValidatedURL( original_url=url, hostname=hostname, port=port, path=parsed.path + ("?" + parsed.query if parsed.query else ""), resolved_ips=resolved_ips, ) async def ssrf_safe_fetch( url: str, *, require_path: bool = False, max_size: int = 5120, timeout: float = 10.0, overall_timeout: float = 30.0, ) -> bytes: """Fetch URL with comprehensive SSRF protection and DNS pinning. Security measures: 1. HTTPS only 2. DNS resolution with IP validation 3. Connects to validated IP directly (DNS pinning prevents rebinding) 4. Response size limit 5. Redirects disabled 6. Overall timeout Args: url: URL to fetch require_path: If True, require non-root path max_size: Maximum response size in bytes (default 5KB) timeout: Per-operation timeout in seconds overall_timeout: Overall timeout for entire operation Returns: Response body as bytes Raises: SSRFError: If SSRF validation fails SSRFFetchError: If fetch fails """ response = await ssrf_safe_fetch_response( url, require_path=require_path, max_size=max_size, timeout=timeout, overall_timeout=overall_timeout, allowed_status_codes={200}, ) return response.content async def ssrf_safe_fetch_response( url: str, *, require_path: bool = False, max_size: int = 5120, timeout: float = 10.0, overall_timeout: float = 30.0, request_headers: Mapping[str, str] | None = None, allowed_status_codes: set[int] | None = None, ) -> SSRFFetchResponse: """Fetch URL with SSRF protection and return response metadata. This is equivalent to :func:`ssrf_safe_fetch` but returns response headers and status code, and supports conditional request headers. """ start_time = time.monotonic() # Validate URL and resolve DNS validated = await validate_url(url, require_path=require_path) last_error: Exception | None = None expected_statuses = allowed_status_codes or {200} for pinned_ip in validated.resolved_ips: elapsed = time.monotonic() - start_time if elapsed > overall_timeout: raise SSRFFetchError(f"Overall timeout exceeded: {url}") remaining = max(1.0, overall_timeout - elapsed) pinned_url = ( f"https://{format_ip_for_url(pinned_ip)}:{validated.port}{validated.path}" ) logger.debug( "SSRF-safe fetch: %s -> %s (pinned to %s)", url, pinned_url, pinned_ip, ) headers = {"Host": validated.hostname} if request_headers: for key, value in request_headers.items(): # Host must remain pinned to the validated hostname. if key.lower() == "host": continue headers[key] = value try: # Use httpx with streaming to enforce size limit during download async with ( httpx.AsyncClient( timeout=httpx.Timeout( connect=min(timeout, remaining), read=min(timeout, remaining), write=min(timeout, remaining), pool=min(timeout, remaining), ), follow_redirects=False, verify=True, ) as client, client.stream( "GET", pinned_url, headers=headers, extensions={"sni_hostname": validated.hostname}, ) as response, ): if time.monotonic() - start_time > overall_timeout: raise SSRFFetchError(f"Overall timeout exceeded: {url}") if response.status_code not in expected_statuses: raise SSRFFetchError(f"HTTP {response.status_code} fetching {url}") # Check Content-Length header first if available content_length = response.headers.get("content-length") if content_length: try: size = int(content_length) if size > max_size: raise SSRFFetchError( f"Response too large: {size} bytes (max {max_size})" ) except ValueError: pass # Stream the response and enforce size limit during download chunks = [] total = 0 async for chunk in response.aiter_bytes(): if time.monotonic() - start_time > overall_timeout: raise SSRFFetchError(f"Overall timeout exceeded: {url}") total += len(chunk) if total > max_size: raise SSRFFetchError( f"Response too large: exceeded {max_size} bytes" ) chunks.append(chunk) return SSRFFetchResponse( content=b"".join(chunks), status_code=response.status_code, headers=dict(response.headers), ) except httpx.TimeoutException as e: last_error = e continue except httpx.RequestError as e: last_error = e continue if last_error is not None: if isinstance(last_error, httpx.TimeoutException): raise SSRFFetchError(f"Timeout fetching {url}") from last_error raise SSRFFetchError(f"Error fetching {url}: {last_error}") from last_error raise SSRFFetchError(f"Error fetching {url}: no resolved IPs succeeded")
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/server/auth/ssrf.py", "license": "Apache License 2.0", "lines": 285, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:src/fastmcp/server/middleware/dereference.py
"""Middleware that dereferences $ref in JSON schemas before sending to clients.""" from collections.abc import Sequence from typing import Any import mcp.types as mt from typing_extensions import override from fastmcp.resources.template import ResourceTemplate from fastmcp.server.middleware.middleware import CallNext, Middleware, MiddlewareContext from fastmcp.tools.tool import Tool from fastmcp.utilities.json_schema import dereference_refs class DereferenceRefsMiddleware(Middleware): """Dereferences $ref in component schemas before sending to clients. Some MCP clients (e.g., VS Code Copilot) don't handle JSON Schema $ref properly. This middleware inlines all $ref definitions so schemas are self-contained. Enabled by default via ``FastMCP(dereference_schemas=True)``. """ @override async def on_list_tools( self, context: MiddlewareContext[mt.ListToolsRequest], call_next: CallNext[mt.ListToolsRequest, Sequence[Tool]], ) -> Sequence[Tool]: tools = await call_next(context) return [_dereference_tool(tool) for tool in tools] @override async def on_list_resource_templates( self, context: MiddlewareContext[mt.ListResourceTemplatesRequest], call_next: CallNext[ mt.ListResourceTemplatesRequest, Sequence[ResourceTemplate] ], ) -> Sequence[ResourceTemplate]: templates = await call_next(context) return [_dereference_resource_template(t) for t in templates] def _dereference_tool(tool: Tool) -> Tool: """Return a copy of the tool with dereferenced schemas.""" updates: dict[str, object] = {} if "$defs" in tool.parameters or _has_ref(tool.parameters): updates["parameters"] = dereference_refs(tool.parameters) if tool.output_schema is not None and ( "$defs" in tool.output_schema or _has_ref(tool.output_schema) ): updates["output_schema"] = dereference_refs(tool.output_schema) if updates: return tool.model_copy(update=updates) return tool def _dereference_resource_template(template: ResourceTemplate) -> ResourceTemplate: """Return a copy of the template with dereferenced schemas.""" if "$defs" in template.parameters or _has_ref(template.parameters): return template.model_copy( update={"parameters": dereference_refs(template.parameters)} ) return template def _has_ref(schema: dict[str, Any]) -> bool: """Check if a schema contains any $ref.""" if "$ref" in schema: return True for value in schema.values(): if isinstance(value, dict) and _has_ref(value): return True if isinstance(value, list): for item in value: if isinstance(item, dict) and _has_ref(item): return True return False
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/server/middleware/dereference.py", "license": "Apache License 2.0", "lines": 64, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:src/fastmcp/server/middleware/response_limiting.py
"""Response limiting middleware for controlling tool response sizes.""" from __future__ import annotations import logging import mcp.types as mt import pydantic_core from mcp.types import TextContent from fastmcp.tools.tool import ToolResult from .middleware import CallNext, Middleware, MiddlewareContext __all__ = ["ResponseLimitingMiddleware"] logger = logging.getLogger(__name__) class ResponseLimitingMiddleware(Middleware): """Middleware that limits the response size of tool calls. Intercepts tool call responses and enforces size limits. If a response exceeds the limit, it extracts text content, truncates it, and returns a single TextContent block. Example: ```python from fastmcp import FastMCP from fastmcp.server.middleware.response_limiting import ( ResponseLimitingMiddleware, ) mcp = FastMCP("MyServer") # Limit all tool responses to 500KB mcp.add_middleware(ResponseLimitingMiddleware(max_size=500_000)) # Limit only specific tools mcp.add_middleware( ResponseLimitingMiddleware( max_size=100_000, tools=["search", "fetch_data"], ) ) ``` """ def __init__( self, *, max_size: int = 1_000_000, truncation_suffix: str = "\n\n[Response truncated due to size limit]", tools: list[str] | None = None, ) -> None: """Initialize response limiting middleware. Args: max_size: Maximum response size in bytes. Defaults to 1MB (1,000,000). truncation_suffix: Suffix to append when truncating responses. Defaults to "\\n\\n[Response truncated due to size limit]". tools: List of tool names to apply limiting to. If None, applies to all. """ if max_size <= 0: raise ValueError(f"max_size must be positive, got {max_size}") self.max_size = max_size self.truncation_suffix = truncation_suffix self.tools = set(tools) if tools is not None else None def _truncate_to_result(self, text: str) -> ToolResult: """Truncate text to fit within max_size and wrap in ToolResult.""" suffix_bytes = len(self.truncation_suffix.encode("utf-8")) # Account for JSON wrapper overhead: {"content":[{"type":"text","text":"..."}]} overhead = 50 target_size = self.max_size - suffix_bytes - overhead if target_size <= 0: # Edge case: max_size too small for even the suffix truncated = self.truncation_suffix else: # Truncate to target size, preserving UTF-8 boundaries encoded = text.encode("utf-8") if len(encoded) <= target_size: truncated = text + self.truncation_suffix else: truncated = ( encoded[:target_size].decode("utf-8", errors="ignore") + self.truncation_suffix ) return ToolResult(content=[TextContent(type="text", text=truncated)]) async def on_call_tool( self, context: MiddlewareContext[mt.CallToolRequestParams], call_next: CallNext[mt.CallToolRequestParams, ToolResult], ) -> ToolResult: """Intercept tool calls and limit response size.""" result = await call_next(context) # Check if we should limit this tool if self.tools is not None and context.message.name not in self.tools: return result # Measure serialized size serialized = pydantic_core.to_json(result, fallback=str) if len(serialized) <= self.max_size: return result # Over limit: extract text, truncate, return single TextContent logger.warning( "Tool %r response exceeds size limit: %d bytes > %d bytes, truncating", context.message.name, len(serialized), self.max_size, ) texts = [b.text for b in result.content if isinstance(b, TextContent)] text = ( "\n\n".join(texts) if texts else serialized.decode("utf-8", errors="replace") ) return self._truncate_to_result(text)
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/server/middleware/response_limiting.py", "license": "Apache License 2.0", "lines": 100, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:src/fastmcp/server/tasks/elicitation.py
"""Background task elicitation support (SEP-1686). This module provides elicitation capabilities for background tasks running in Docket workers. Unlike regular MCP requests, background tasks don't have an active request context, so elicitation requires special handling: 1. Set task status to "input_required" via Redis 2. Send notifications/tasks/status with elicitation metadata 3. Wait for client to send input via tasks/sendInput 4. Resume task execution with the provided input This uses the public MCP SDK APIs where possible, with minimal use of internal APIs for background task coordination. """ from __future__ import annotations import json import logging import uuid from datetime import datetime, timezone from typing import TYPE_CHECKING, Any, cast import mcp.types from mcp import ServerSession logger = logging.getLogger(__name__) if TYPE_CHECKING: from fastmcp.server.server import FastMCP # Redis key patterns for task elicitation state ELICIT_REQUEST_KEY = "fastmcp:task:{session_id}:{task_id}:elicit:request" ELICIT_RESPONSE_KEY = "fastmcp:task:{session_id}:{task_id}:elicit:response" ELICIT_STATUS_KEY = "fastmcp:task:{session_id}:{task_id}:elicit:status" # TTL for elicitation state (1 hour) ELICIT_TTL_SECONDS = 3600 async def elicit_for_task( task_id: str, session: ServerSession | None, message: str, schema: dict[str, Any], fastmcp: FastMCP, ) -> mcp.types.ElicitResult: """Send an elicitation request from a background task. This function handles the complexity of eliciting user input when running in a Docket worker context where there's no active MCP request. Args: task_id: The background task ID session: The MCP ServerSession for this task message: The message to display to the user schema: The JSON schema for the expected response fastmcp: The FastMCP server instance Returns: ElicitResult containing the user's response Raises: RuntimeError: If Docket is not available McpError: If the elicitation request fails """ docket = fastmcp._docket if docket is None: raise RuntimeError( "Background task elicitation requires Docket. " "Ensure 'fastmcp[tasks]' is installed and the server has task-enabled components." ) # Generate a unique request ID for this elicitation request_id = str(uuid.uuid4()) # Get session ID from task context (authoritative source for background tasks) # This is extracted from the Docket execution key: {session_id}:{task_id}:... from fastmcp.server.dependencies import get_task_context task_context = get_task_context() if task_context is not None: session_id = task_context.session_id else: # Fallback: try to get from session attribute (shouldn't happen in background) session_id = getattr(session, "_fastmcp_state_prefix", None) if session_id is None: raise RuntimeError( "Cannot determine session_id for elicitation. " "This typically means elicit_for_task() was called outside a Docket worker context." ) # Store elicitation request in Redis request_key = ELICIT_REQUEST_KEY.format(session_id=session_id, task_id=task_id) response_key = ELICIT_RESPONSE_KEY.format(session_id=session_id, task_id=task_id) status_key = ELICIT_STATUS_KEY.format(session_id=session_id, task_id=task_id) elicit_request = { "request_id": request_id, "message": message, "schema": schema, } async with docket.redis() as redis: # Store the elicitation request await redis.set( docket.key(request_key), json.dumps(elicit_request), ex=ELICIT_TTL_SECONDS, ) # Set status to "waiting" await redis.set( docket.key(status_key), "waiting", ex=ELICIT_TTL_SECONDS, ) # Send task status update notification with input_required status. # Use notifications/tasks/status so typed MCP clients can consume it. # # NOTE: We use the distributed notification queue instead of session.send_notification() # This enables notifications to work when workers run in separate processes # (Azure Web PubSub / Service Bus inspired pattern) timestamp = datetime.now(timezone.utc).isoformat() notification_dict = { "method": "notifications/tasks/status", "params": { "taskId": task_id, "status": "input_required", "statusMessage": message, "createdAt": timestamp, "lastUpdatedAt": timestamp, "ttl": ELICIT_TTL_SECONDS * 1000, }, "_meta": { "io.modelcontextprotocol/related-task": { "taskId": task_id, "status": "input_required", "statusMessage": message, "elicitation": { "requestId": request_id, "message": message, "requestedSchema": schema, }, } }, } # Push notification to Redis queue (works from any process) # Server's subscriber loop will forward to client from fastmcp.server.tasks.notifications import push_notification try: await push_notification(session_id, notification_dict, docket) except Exception as e: # Fail fast: if notification can't be queued, client won't know to respond # Return cancel immediately rather than waiting for 1-hour timeout logger.warning( "Failed to queue input_required notification for task %s, cancelling elicitation: %s", task_id, e, ) # Best-effort cleanup try: async with docket.redis() as redis: await redis.delete( docket.key(request_key), docket.key(status_key), ) except Exception: pass # Keys will expire via TTL return mcp.types.ElicitResult(action="cancel", content=None) # Wait for response using BLPOP (blocking pop) # This is much more efficient than polling - single Redis round-trip # that blocks until a response is pushed, vs 7,200 round-trips/hour with polling max_wait_seconds = ELICIT_TTL_SECONDS try: async with docket.redis() as redis: # BLPOP blocks until an item is pushed to the list or timeout # Returns tuple of (key, value) or None on timeout result = await cast( Any, redis.blpop( [docket.key(response_key)], timeout=max_wait_seconds, ), ) if result: # result is (key, value) tuple _key, response_data = result response = json.loads(response_data) # Clean up Redis keys await redis.delete( docket.key(request_key), docket.key(status_key), ) # Convert to ElicitResult return mcp.types.ElicitResult( action=response.get("action", "accept"), content=response.get("content"), ) except Exception as e: logger.warning( "BLPOP failed for task %s elicitation, falling back to cancel: %s", task_id, e, ) # Timeout or error - treat as cancellation # Best-effort cleanup - if Redis is unavailable, keys will expire via TTL try: async with docket.redis() as redis: await redis.delete( docket.key(request_key), docket.key(response_key), docket.key(status_key), ) except Exception as cleanup_error: logger.debug( "Failed to clean up elicitation keys for task %s (will expire via TTL): %s", task_id, cleanup_error, ) return mcp.types.ElicitResult(action="cancel", content=None) async def relay_elicitation( session: ServerSession, session_id: str, task_id: str, elicitation: dict[str, Any], fastmcp: FastMCP, ) -> None: """Relay elicitation from a background task worker to the client. Called by the notification subscriber when it detects an input_required notification with elicitation metadata. Sends a standard elicitation/create request to the client session, then uses handle_task_input() to push the response to Redis so the blocked worker can resume. Args: session: MCP ServerSession session_id: Session identifier task_id: Background task ID elicitation: Elicitation metadata (message, requestedSchema) fastmcp: FastMCP server instance """ try: result = await session.elicit( message=elicitation["message"], requestedSchema=elicitation["requestedSchema"], ) await handle_task_input( task_id=task_id, session_id=session_id, action=result.action, content=result.content, fastmcp=fastmcp, ) logger.debug( "Relayed elicitation response for task %s (action=%s)", task_id, result.action, ) except Exception as e: logger.warning("Failed to relay elicitation for task %s: %s", task_id, e) # Push a cancel response so the worker's BLPOP doesn't block forever success = await handle_task_input( task_id=task_id, session_id=session_id, action="cancel", content=None, fastmcp=fastmcp, ) if not success: logger.warning( "Failed to push cancel response for task %s " "(worker may block until TTL)", task_id, ) async def handle_task_input( task_id: str, session_id: str, action: str, content: dict[str, Any] | None, fastmcp: FastMCP, ) -> bool: """Handle input sent to a background task via tasks/sendInput. This is called when a client sends input in response to an elicitation request from a background task. Args: task_id: The background task ID session_id: The MCP session ID action: The elicitation action ("accept", "decline", "cancel") content: The response content (for "accept" action) fastmcp: The FastMCP server instance Returns: True if the input was successfully stored, False otherwise """ docket = fastmcp._docket if docket is None: return False response_key = ELICIT_RESPONSE_KEY.format(session_id=session_id, task_id=task_id) status_key = ELICIT_STATUS_KEY.format(session_id=session_id, task_id=task_id) response = { "action": action, "content": content, } async with docket.redis() as redis: # Check if there's a pending elicitation status = await redis.get(docket.key(status_key)) if status is None or status.decode("utf-8") != "waiting": return False # Push response to list - this wakes up the BLPOP in elicit_for_task # Using LPUSH instead of SET enables the efficient blocking wait pattern await redis.lpush( # type: ignore[invalid-await] # redis-py union type (sync/async) docket.key(response_key), json.dumps(response), ) # Set TTL on the response list (in case BLPOP doesn't consume it) await redis.expire(docket.key(response_key), ELICIT_TTL_SECONDS) # Update status to "responded" await redis.set( docket.key(status_key), "responded", ex=ELICIT_TTL_SECONDS, ) return True
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/server/tasks/elicitation.py", "license": "Apache License 2.0", "lines": 298, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:src/fastmcp/server/tasks/notifications.py
"""Distributed notification queue for background task events (SEP-1686). Enables distributed Docket workers to send MCP notifications to clients without holding session references. Workers push to a Redis queue, the MCP server process subscribes and forwards to the client's session. Pattern: Fire-and-forward with retry - One queue per session_id - LPUSH/BRPOP for reliable ordered delivery - Retry up to 3 times on delivery failure, then discard - TTL-based expiration for stale messages Note: Docket's execution.subscribe() handles task state/progress events via Redis Pub/Sub. This module handles elicitation-specific notifications that require reliable delivery (input_required prompts, cancel signals). """ from __future__ import annotations import asyncio import json import logging import weakref from contextlib import suppress from datetime import datetime, timezone from typing import TYPE_CHECKING, Any, cast import mcp.types if TYPE_CHECKING: from docket import Docket from mcp.server.session import ServerSession from fastmcp.server.server import FastMCP logger = logging.getLogger(__name__) # Redis key patterns NOTIFICATION_QUEUE_KEY = "fastmcp:notifications:{session_id}" NOTIFICATION_ACTIVE_KEY = "fastmcp:notifications:{session_id}:active" # Configuration NOTIFICATION_TTL_SECONDS = 300 # 5 minute message TTL (elicitation response window) MAX_DELIVERY_ATTEMPTS = 3 # Retry failed deliveries before discarding SUBSCRIBER_TIMEOUT_SECONDS = 30 # BRPOP timeout (also heartbeat interval) async def push_notification( session_id: str, notification: dict[str, Any], docket: Docket, ) -> None: """Push notification to session's queue (called from Docket worker). Used for elicitation-specific notifications (input_required, cancel) that need reliable delivery across distributed processes. Args: session_id: Target session's identifier notification: MCP notification dict (method, params, _meta) docket: Docket instance for Redis access """ key = docket.key(NOTIFICATION_QUEUE_KEY.format(session_id=session_id)) message = json.dumps( { "notification": notification, "attempt": 0, "enqueued_at": datetime.now(timezone.utc).isoformat(), } ) async with docket.redis() as redis: await redis.lpush(key, message) # type: ignore[invalid-await] # redis-py union type (sync/async) await redis.expire(key, NOTIFICATION_TTL_SECONDS) async def notification_subscriber_loop( session_id: str, session: ServerSession, docket: Docket, fastmcp: FastMCP, ) -> None: """Subscribe to notification queue and forward to session. Runs in the MCP server process. Bridges distributed workers to clients. This loop: 1. Maintains a heartbeat (active subscriber marker for debugging) 2. Blocks on BRPOP waiting for notifications 3. Forwards notifications to the client's session 4. Retries failed deliveries, then discards (no dead-letter queue) Args: session_id: Session identifier to subscribe to session: MCP ServerSession for sending notifications docket: Docket instance for Redis access fastmcp: FastMCP server instance (for elicitation relay) """ queue_key = docket.key(NOTIFICATION_QUEUE_KEY.format(session_id=session_id)) active_key = docket.key(NOTIFICATION_ACTIVE_KEY.format(session_id=session_id)) logger.debug("Starting notification subscriber for session %s", session_id) while True: try: async with docket.redis() as redis: # Heartbeat: mark subscriber as active (for distributed debugging) await redis.set(active_key, "1", ex=SUBSCRIBER_TIMEOUT_SECONDS * 2) # Blocking wait for notification (timeout refreshes heartbeat) # Using BRPOP (right pop) for FIFO order with LPUSH (left push) result = await cast( Any, redis.brpop([queue_key], timeout=SUBSCRIBER_TIMEOUT_SECONDS) ) if not result: continue # Timeout - refresh heartbeat and retry _, message_bytes = result message = json.loads(message_bytes) notification_dict = message["notification"] attempt = message.get("attempt", 0) try: # Reconstruct and send MCP notification await _send_mcp_notification( session, notification_dict, session_id, docket, fastmcp ) logger.debug( "Delivered notification to session %s (attempt %d)", session_id, attempt + 1, ) except Exception as send_error: # Delivery failed - retry or discard if attempt < MAX_DELIVERY_ATTEMPTS - 1: # Re-queue with incremented attempt (back of queue) message["attempt"] = attempt + 1 message["last_error"] = str(send_error) await redis.lpush(queue_key, json.dumps(message)) # type: ignore[invalid-await] logger.debug( "Requeued notification for session %s (attempt %d): %s", session_id, attempt + 2, send_error, ) else: # Discard after max attempts (session likely disconnected) logger.warning( "Discarding notification for session %s after %d attempts: %s", session_id, MAX_DELIVERY_ATTEMPTS, send_error, ) except asyncio.CancelledError: # Graceful shutdown - leave pending messages in queue for reconnect logger.debug("Notification subscriber cancelled for session %s", session_id) break except Exception as e: logger.debug( "Notification subscriber error for session %s: %s", session_id, e ) await asyncio.sleep(1) # Backoff on error async def _send_mcp_notification( session: ServerSession, notification_dict: dict[str, Any], session_id: str, docket: Docket, fastmcp: FastMCP, ) -> None: """Reconstruct MCP notification from dict and send to session. For input_required notifications with elicitation metadata, also sends a standard elicitation/create request to the client and relays the response back to the worker via Redis. Args: session: MCP ServerSession notification_dict: Notification as dict (method, params, _meta) session_id: Session identifier (for elicitation relay) docket: Docket instance (for notification delivery) fastmcp: FastMCP server instance (for elicitation relay) """ method = notification_dict.get("method", "notifications/tasks/status") if method != "notifications/tasks/status": raise ValueError(f"Unsupported notification method for subscriber: {method}") notification = mcp.types.TaskStatusNotification.model_validate( { "method": "notifications/tasks/status", "params": notification_dict.get("params", {}), "_meta": notification_dict.get("_meta"), } ) server_notification = mcp.types.ServerNotification(notification) await session.send_notification(server_notification) # If this is an input_required notification with elicitation metadata, # relay the elicitation to the client via standard elicitation/create params = notification_dict.get("params", {}) if params.get("status") == "input_required": meta = notification_dict.get("_meta", {}) related_task = meta.get("io.modelcontextprotocol/related-task", {}) elicitation = related_task.get("elicitation") if elicitation: task_id = params.get("taskId") if not task_id: logger.warning( "input_required notification missing taskId, skipping relay" ) return from fastmcp.server.tasks.elicitation import relay_elicitation task = asyncio.create_task( relay_elicitation(session, session_id, task_id, elicitation, fastmcp), name=f"elicitation-relay-{task_id[:8]}", ) _background_tasks.add(task) task.add_done_callback(_background_tasks.discard) # ============================================================================= # Subscriber Management # ============================================================================= # Strong references to fire-and-forget relay tasks (prevent GC mid-flight) _background_tasks: set[asyncio.Task[None]] = set() # Registry of active subscribers per session (prevents duplicates) # Uses weakref to session to detect disconnects _active_subscribers: dict[ str, tuple[asyncio.Task[None], weakref.ref[ServerSession]] ] = {} async def ensure_subscriber_running( session_id: str, session: ServerSession, docket: Docket, fastmcp: FastMCP, ) -> None: """Start notification subscriber if not already running (idempotent). Subscriber is created on first task submission and cleaned up on disconnect. Safe to call multiple times for the same session. Args: session_id: Session identifier session: MCP ServerSession docket: Docket instance fastmcp: FastMCP server instance (for elicitation relay) """ # Check if subscriber already running for this session if session_id in _active_subscribers: task, session_ref = _active_subscribers[session_id] # Check if task is still running AND session is still alive if not task.done() and session_ref() is not None: return # Already running # Task finished or session dead - clean up if not task.done(): task.cancel() with suppress(asyncio.CancelledError): await task del _active_subscribers[session_id] # Start new subscriber task task = asyncio.create_task( notification_subscriber_loop(session_id, session, docket, fastmcp), name=f"notification-subscriber-{session_id[:8]}", ) _active_subscribers[session_id] = (task, weakref.ref(session)) logger.debug("Started notification subscriber for session %s", session_id) async def stop_subscriber(session_id: str) -> None: """Stop notification subscriber for a session. Called when session disconnects. Pending messages remain in queue for delivery if client reconnects (with TTL expiration). Args: session_id: Session identifier """ if session_id not in _active_subscribers: return task, _ = _active_subscribers.pop(session_id) if not task.done(): task.cancel() with suppress(asyncio.CancelledError): await task logger.debug("Stopped notification subscriber for session %s", session_id) def get_subscriber_count() -> int: """Get number of active subscribers (for monitoring).""" return len(_active_subscribers)
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/server/tasks/notifications.py", "license": "Apache License 2.0", "lines": 249, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:tests/cli/test_cimd_cli.py
"""Tests for the CIMD CLI commands (create and validate).""" from __future__ import annotations import json from unittest.mock import AsyncMock, patch import pytest from pydantic import AnyHttpUrl from fastmcp.cli.cimd import create_command, validate_command from fastmcp.server.auth.cimd import CIMDDocument, CIMDFetchError, CIMDValidationError class TestCIMDCreateCommand: """Tests for `fastmcp auth cimd create`.""" def test_minimal_output(self, capsys: pytest.CaptureFixture[str]): create_command( name="Test App", redirect_uri=["http://localhost:*/callback"], ) doc = json.loads(capsys.readouterr().out) assert doc["client_name"] == "Test App" assert doc["redirect_uris"] == ["http://localhost:*/callback"] assert doc["token_endpoint_auth_method"] == "none" assert doc["grant_types"] == ["authorization_code"] assert doc["response_types"] == ["code"] # Placeholder client_id assert "YOUR-DOMAIN" in doc["client_id"] def test_with_client_id(self, capsys: pytest.CaptureFixture[str]): create_command( name="Test App", redirect_uri=["http://localhost:*/callback"], client_id="https://myapp.example.com/client.json", ) doc = json.loads(capsys.readouterr().out) assert doc["client_id"] == "https://myapp.example.com/client.json" def test_with_output_file(self, tmp_path): output_file = tmp_path / "client.json" create_command( name="Test App", redirect_uri=["http://localhost:*/callback"], client_id="https://example.com/client.json", output=str(output_file), ) doc = json.loads(output_file.read_text()) assert doc["client_id"] == "https://example.com/client.json" assert doc["client_name"] == "Test App" def test_relative_path_resolved(self, tmp_path, monkeypatch): """Relative paths should be resolved against cwd.""" monkeypatch.chdir(tmp_path) create_command( name="Test App", redirect_uri=["http://localhost:*/callback"], output="./subdir/client.json", ) resolved = tmp_path / "subdir" / "client.json" assert resolved.exists() doc = json.loads(resolved.read_text()) assert doc["client_name"] == "Test App" def test_with_scope(self, capsys: pytest.CaptureFixture[str]): create_command( name="Test App", redirect_uri=["http://localhost:*/callback"], scope="read write", ) doc = json.loads(capsys.readouterr().out) assert doc["scope"] == "read write" def test_with_client_uri(self, capsys: pytest.CaptureFixture[str]): create_command( name="Test App", redirect_uri=["http://localhost:*/callback"], client_uri="https://example.com", ) doc = json.loads(capsys.readouterr().out) assert doc["client_uri"] == "https://example.com" def test_with_logo_uri(self, capsys: pytest.CaptureFixture[str]): create_command( name="Test App", redirect_uri=["http://localhost:*/callback"], logo_uri="https://example.com/logo.png", ) doc = json.loads(capsys.readouterr().out) assert doc["logo_uri"] == "https://example.com/logo.png" def test_multiple_redirect_uris(self, capsys: pytest.CaptureFixture[str]): create_command( name="Test App", redirect_uri=[ "http://localhost:*/callback", "https://myapp.example.com/callback", ], ) doc = json.loads(capsys.readouterr().out) assert len(doc["redirect_uris"]) == 2 def test_no_pretty(self, capsys: pytest.CaptureFixture[str]): create_command( name="Test App", redirect_uri=["http://localhost:*/callback"], pretty=False, ) output = capsys.readouterr().out.strip() # Compact JSON has no newlines within the object assert "\n" not in output doc = json.loads(output) assert doc["client_name"] == "Test App" def test_placeholder_warning_on_stderr(self, capsys: pytest.CaptureFixture[str]): """When outputting to stdout with no --client-id, warning goes to stderr.""" create_command( name="Test App", redirect_uri=["http://localhost:*/callback"], ) captured = capsys.readouterr() # stdout has valid JSON json.loads(captured.out) # stderr has the warning (Rich Console writes to stderr) assert "placeholder" in captured.err def test_no_warning_with_client_id(self, capsys: pytest.CaptureFixture[str]): """No placeholder warning when --client-id is provided.""" create_command( name="Test App", redirect_uri=["http://localhost:*/callback"], client_id="https://example.com/client.json", ) captured = capsys.readouterr() assert "placeholder" not in captured.err def test_optional_fields_omitted_when_none( self, capsys: pytest.CaptureFixture[str] ): """Optional fields like scope, client_uri, logo_uri are omitted if not given.""" create_command( name="Test App", redirect_uri=["http://localhost:*/callback"], ) doc = json.loads(capsys.readouterr().out) assert "scope" not in doc assert "client_uri" not in doc assert "logo_uri" not in doc class TestCIMDValidateCommand: """Tests for `fastmcp auth cimd validate`.""" def test_invalid_url_format(self, capsys: pytest.CaptureFixture[str]): with pytest.raises(SystemExit, match="1"): validate_command("http://insecure.com/client.json") captured = capsys.readouterr() assert "Invalid CIMD URL" in captured.out def test_root_path_rejected(self, capsys: pytest.CaptureFixture[str]): with pytest.raises(SystemExit, match="1"): validate_command("https://example.com/") captured = capsys.readouterr() assert "Invalid CIMD URL" in captured.out def test_success(self, capsys: pytest.CaptureFixture[str]): mock_doc = CIMDDocument( client_id=AnyHttpUrl("https://myapp.example.com/client.json"), client_name="Test App", redirect_uris=["http://localhost:*/callback"], token_endpoint_auth_method="none", grant_types=["authorization_code"], response_types=["code"], ) with patch.object(CIMDDocument, "__init__", return_value=None): pass mock_fetch = AsyncMock(return_value=mock_doc) with patch( "fastmcp.cli.cimd.CIMDFetcher.fetch", mock_fetch, ): validate_command("https://myapp.example.com/client.json") captured = capsys.readouterr() assert "Valid CIMD document" in captured.out assert "Test App" in captured.out def test_fetch_error(self, capsys: pytest.CaptureFixture[str]): mock_fetch = AsyncMock(side_effect=CIMDFetchError("Connection refused")) with patch( "fastmcp.cli.cimd.CIMDFetcher.fetch", mock_fetch, ): with pytest.raises(SystemExit, match="1"): validate_command("https://myapp.example.com/client.json") captured = capsys.readouterr() assert "Failed to fetch" in captured.out def test_validation_error(self, capsys: pytest.CaptureFixture[str]): mock_fetch = AsyncMock(side_effect=CIMDValidationError("client_id mismatch")) with patch( "fastmcp.cli.cimd.CIMDFetcher.fetch", mock_fetch, ): with pytest.raises(SystemExit, match="1"): validate_command("https://myapp.example.com/client.json") captured = capsys.readouterr() assert "Validation error" in captured.out
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/cli/test_cimd_cli.py", "license": "Apache License 2.0", "lines": 183, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/cli/test_client_commands.py
"""Tests for fastmcp list and fastmcp call CLI commands.""" import json from pathlib import Path from typing import Any from unittest.mock import patch import mcp.types import pytest from fastmcp import FastMCP from fastmcp.cli import client as client_module from fastmcp.cli.client import ( Client, _build_client, _build_stdio_from_command, _format_call_result_text, _is_http_target, _sanitize_untrusted_text, call_command, coerce_value, format_tool_signature, list_command, parse_tool_arguments, resolve_server_spec, ) from fastmcp.client.client import CallToolResult from fastmcp.client.transports.stdio import StdioTransport # --------------------------------------------------------------------------- # coerce_value # --------------------------------------------------------------------------- class TestCoerceValue: def test_integer(self): assert coerce_value("42", {"type": "integer"}) == 42 def test_integer_negative(self): assert coerce_value("-7", {"type": "integer"}) == -7 def test_integer_invalid(self): with pytest.raises(ValueError, match="Expected integer"): coerce_value("abc", {"type": "integer"}) def test_number(self): assert coerce_value("3.14", {"type": "number"}) == 3.14 def test_number_integer_value(self): assert coerce_value("5", {"type": "number"}) == 5.0 def test_number_invalid(self): with pytest.raises(ValueError, match="Expected number"): coerce_value("xyz", {"type": "number"}) def test_boolean_true_variants(self): for val in ("true", "True", "TRUE", "1", "yes"): assert coerce_value(val, {"type": "boolean"}) is True def test_boolean_false_variants(self): for val in ("false", "False", "FALSE", "0", "no"): assert coerce_value(val, {"type": "boolean"}) is False def test_boolean_invalid(self): with pytest.raises(ValueError, match="Expected boolean"): coerce_value("maybe", {"type": "boolean"}) def test_array(self): assert coerce_value("[1, 2, 3]", {"type": "array"}) == [1, 2, 3] def test_array_invalid(self): with pytest.raises(ValueError, match="Expected JSON array"): coerce_value("not-json", {"type": "array"}) def test_object(self): assert coerce_value('{"a": 1}', {"type": "object"}) == {"a": 1} def test_string(self): assert coerce_value("hello", {"type": "string"}) == "hello" def test_string_default(self): """Unknown or missing type treats value as string.""" assert coerce_value("hello", {}) == "hello" def test_string_preserves_numeric_looking_values(self): assert coerce_value("42", {"type": "string"}) == "42" # --------------------------------------------------------------------------- # parse_tool_arguments # --------------------------------------------------------------------------- class TestParseToolArguments: SCHEMA: dict[str, Any] = { "type": "object", "properties": { "query": {"type": "string"}, "limit": {"type": "integer"}, "verbose": {"type": "boolean"}, }, "required": ["query"], } def test_basic_key_value(self): result = parse_tool_arguments(("query=hello", "limit=10"), None, self.SCHEMA) assert result == {"query": "hello", "limit": 10} def test_input_json_only(self): result = parse_tool_arguments((), '{"query": "hello", "limit": 5}', self.SCHEMA) assert result == {"query": "hello", "limit": 5} def test_key_value_overrides_input_json(self): result = parse_tool_arguments( ("limit=20",), '{"query": "hello", "limit": 5}', self.SCHEMA ) assert result == {"query": "hello", "limit": 20} def test_value_containing_equals(self): result = parse_tool_arguments(("query=a=b=c",), None, self.SCHEMA) assert result == {"query": "a=b=c"} def test_invalid_arg_format_exits(self): with pytest.raises(SystemExit): parse_tool_arguments(("noequalssign",), None, self.SCHEMA) def test_invalid_input_json_exits(self): with pytest.raises(SystemExit): parse_tool_arguments((), "not-valid-json", self.SCHEMA) def test_input_json_non_object_exits(self): with pytest.raises(SystemExit): parse_tool_arguments((), "[1,2,3]", self.SCHEMA) def test_single_json_object_as_positional(self): result = parse_tool_arguments( ('{"query": "hello", "limit": 5}',), None, self.SCHEMA ) assert result == {"query": "hello", "limit": 5} def test_json_positional_ignored_when_input_json_set(self): """When --input-json is already provided, a JSON positional arg is not special.""" with pytest.raises(SystemExit): parse_tool_arguments(('{"limit": 99}',), '{"query": "hello"}', self.SCHEMA) def test_coercion_error_exits(self): with pytest.raises(SystemExit): parse_tool_arguments(("limit=abc",), None, self.SCHEMA) # --------------------------------------------------------------------------- # format_tool_signature # --------------------------------------------------------------------------- class TestFormatToolSignature: def _make_tool( self, name: str = "my_tool", properties: dict[str, Any] | None = None, required: list[str] | None = None, output_schema: dict[str, Any] | None = None, description: str | None = None, ) -> mcp.types.Tool: input_schema: dict[str, Any] = {"type": "object"} if properties is not None: input_schema["properties"] = properties if required is not None: input_schema["required"] = required return mcp.types.Tool( name=name, description=description, inputSchema=input_schema, outputSchema=output_schema, ) def test_no_params(self): tool = self._make_tool() assert format_tool_signature(tool) == "my_tool()" def test_required_param(self): tool = self._make_tool( properties={"query": {"type": "string"}}, required=["query"], ) assert format_tool_signature(tool) == "my_tool(query: str)" def test_optional_param_with_default(self): tool = self._make_tool( properties={"limit": {"type": "integer", "default": 10}}, ) assert format_tool_signature(tool) == "my_tool(limit: int = 10)" def test_optional_param_without_default(self): tool = self._make_tool( properties={"limit": {"type": "integer"}}, ) assert format_tool_signature(tool) == "my_tool(limit: int = ...)" def test_mixed_required_and_optional(self): tool = self._make_tool( properties={ "query": {"type": "string"}, "limit": {"type": "integer", "default": 10}, }, required=["query"], ) sig = format_tool_signature(tool) assert sig == "my_tool(query: str, limit: int = 10)" def test_with_output_schema(self): tool = self._make_tool( properties={"q": {"type": "string"}}, required=["q"], output_schema={"type": "object"}, ) assert format_tool_signature(tool) == "my_tool(q: str) -> dict" def test_anyof_type(self): tool = self._make_tool( properties={"value": {"anyOf": [{"type": "string"}, {"type": "integer"}]}}, required=["value"], ) assert format_tool_signature(tool) == "my_tool(value: str | int)" # --------------------------------------------------------------------------- # resolve_server_spec # --------------------------------------------------------------------------- class TestResolveServerSpec: def test_http_url(self): assert ( resolve_server_spec("http://localhost:8000/mcp") == "http://localhost:8000/mcp" ) def test_https_url(self): assert ( resolve_server_spec("https://example.com/mcp") == "https://example.com/mcp" ) def test_python_file_existing(self, tmp_path: Path): py_file = tmp_path / "server.py" py_file.write_text("# empty") result = resolve_server_spec(str(py_file)) assert isinstance(result, StdioTransport) assert result.command == "fastmcp" assert result.args == ["run", str(py_file.resolve()), "--no-banner"] def test_json_mcp_config(self, tmp_path: Path): config_file = tmp_path / "mcp.json" config = {"mcpServers": {"test": {"url": "http://localhost:8000"}}} config_file.write_text(json.dumps(config)) result = resolve_server_spec(str(config_file)) assert isinstance(result, dict) assert "mcpServers" in result def test_json_fastmcp_config_exits(self, tmp_path: Path): config_file = tmp_path / "fastmcp.json" config_file.write_text(json.dumps({"source": {"type": "file"}})) with pytest.raises(SystemExit): resolve_server_spec(str(config_file)) def test_json_not_found_exits(self, tmp_path: Path): with pytest.raises(SystemExit): resolve_server_spec(str(tmp_path / "nonexistent.json")) def test_directory_exits(self, tmp_path: Path): """Directories should not be treated as file paths.""" with pytest.raises(SystemExit): resolve_server_spec(str(tmp_path)) def test_unrecognised_exits(self): with pytest.raises(SystemExit): resolve_server_spec("some_random_thing") def test_command_returns_stdio_transport(self): result = resolve_server_spec(None, command="npx -y @mcp/server") assert isinstance(result, StdioTransport) assert result.command == "npx" assert result.args == ["-y", "@mcp/server"] def test_command_single_word(self): result = resolve_server_spec(None, command="myserver") assert isinstance(result, StdioTransport) assert result.command == "myserver" assert result.args == [] def test_server_spec_and_command_exits(self): with pytest.raises(SystemExit): resolve_server_spec("http://localhost:8000", command="npx server") def test_neither_server_spec_nor_command_exits(self): with pytest.raises(SystemExit): resolve_server_spec(None) def test_transport_sse_rewrites_url(self): result = resolve_server_spec("http://localhost:8000/mcp", transport="sse") assert result == "http://localhost:8000/mcp/sse" def test_transport_sse_no_duplicate_suffix(self): result = resolve_server_spec("http://localhost:8000/sse", transport="sse") assert result == "http://localhost:8000/sse" def test_transport_sse_trailing_slash(self): result = resolve_server_spec("http://localhost:8000/mcp/", transport="sse") assert result == "http://localhost:8000/mcp/sse" def test_transport_http_leaves_url_unchanged(self): result = resolve_server_spec("http://localhost:8000/mcp", transport="http") assert result == "http://localhost:8000/mcp" # --------------------------------------------------------------------------- # _build_stdio_from_command # --------------------------------------------------------------------------- class TestBuildStdioFromCommand: def test_simple_command(self): transport = _build_stdio_from_command("uvx my-server") assert transport.command == "uvx" assert transport.args == ["my-server"] def test_quoted_args(self): transport = _build_stdio_from_command("npx -y '@scope/server'") assert transport.command == "npx" assert transport.args == ["-y", "@scope/server"] def test_empty_command_exits(self): with pytest.raises(SystemExit): _build_stdio_from_command("") def test_invalid_shell_syntax_exits(self): with pytest.raises(SystemExit): _build_stdio_from_command("npx 'unterminated") # --------------------------------------------------------------------------- # _is_http_target # --------------------------------------------------------------------------- class TestIsHttpTarget: def test_http_url(self): assert _is_http_target("http://localhost:8000") is True def test_https_url(self): assert _is_http_target("https://example.com/mcp") is True def test_file_path(self): assert _is_http_target("/path/to/server.py") is False def test_stdio_transport(self): assert _is_http_target(StdioTransport(command="npx", args=[])) is False def test_mcp_config_dict(self): """MCPConfig dicts are not HTTP targets — auth is per-server internally.""" assert _is_http_target({"mcpServers": {}}) is False # --------------------------------------------------------------------------- # _build_client # --------------------------------------------------------------------------- class TestBuildClient: def test_http_target_gets_oauth_by_default(self): client = _build_client("http://localhost:8000/mcp") # OAuth is applied during Client init via _set_auth assert client.transport.auth is not None def test_stdio_target_no_auth(self): transport = StdioTransport(command="npx", args=["-y", "@mcp/server"]) client = _build_client(transport) # Stdio transports don't support auth — no auth should be set assert not hasattr(client.transport, "auth") or client.transport.auth is None def test_explicit_auth_none_disables_oauth(self): client = _build_client("http://localhost:8000/mcp", auth="none") # "none" explicitly disables auth, even for HTTP targets assert client.transport.auth is None def test_mcp_config_no_auth(self): """MCPConfig dicts handle auth per-server; no top-level auth applied.""" client = _build_client({"mcpServers": {"test": {"url": "http://localhost"}}}) # MCPConfigTransport doesn't support _set_auth — no crash means success assert client.transport is not None # --------------------------------------------------------------------------- # Integration tests — invoke actual CLI commands via monkeypatched _build_client # --------------------------------------------------------------------------- def _build_test_server() -> FastMCP: """Create a minimal FastMCP server for integration tests.""" server = FastMCP("TestServer") @server.tool def greet(name: str) -> str: """Say hello to someone.""" return f"Hello, {name}!" @server.tool def add(a: int, b: int) -> int: """Add two numbers.""" return a + b @server.resource("test://greeting") def greeting_resource() -> str: """A static greeting resource.""" return "Hello from resource!" @server.prompt def ask(topic: str) -> str: """Ask about a topic.""" return f"Tell me about {topic}" return server @pytest.fixture() def _patch_client(): """Patch resolve_server_spec and _build_client so CLI commands use the in-process test server without needing a real transport.""" server = _build_test_server() def fake_resolve(server_spec: Any, **kwargs: Any) -> str: return "fake" def fake_build_client(resolved: Any, **kwargs: Any) -> Client: return Client(server) with ( patch.object(client_module, "resolve_server_spec", side_effect=fake_resolve), patch.object(client_module, "_build_client", side_effect=fake_build_client), ): yield class TestListCommandCLI: @pytest.mark.usefixtures("_patch_client") async def test_list_tools(self, capsys: pytest.CaptureFixture[str]): await list_command("fake://server") captured = capsys.readouterr() assert "greet" in captured.out assert "add" in captured.out @pytest.mark.usefixtures("_patch_client") async def test_list_json(self, capsys: pytest.CaptureFixture[str]): await list_command("fake://server", json_output=True) captured = capsys.readouterr() data = json.loads(captured.out) names = {t["name"] for t in data["tools"]} assert "greet" in names assert "add" in names @pytest.mark.usefixtures("_patch_client") async def test_list_resources(self, capsys: pytest.CaptureFixture[str]): await list_command("fake://server", resources=True) captured = capsys.readouterr() assert "test://greeting" in captured.out @pytest.mark.usefixtures("_patch_client") async def test_list_prompts(self, capsys: pytest.CaptureFixture[str]): await list_command("fake://server", prompts=True) captured = capsys.readouterr() assert "ask" in captured.out class TestCallCommandCLI: @pytest.mark.usefixtures("_patch_client") async def test_call_tool(self, capsys: pytest.CaptureFixture[str]): await call_command("fake://server", "greet", "name=World") captured = capsys.readouterr() assert "Hello, World!" in captured.out @pytest.mark.usefixtures("_patch_client") async def test_call_tool_json(self, capsys: pytest.CaptureFixture[str]): await call_command("fake://server", "greet", "name=World", json_output=True) captured = capsys.readouterr() data = json.loads(captured.out) assert data["is_error"] is False @pytest.mark.usefixtures("_patch_client") async def test_call_tool_not_found(self): with pytest.raises(SystemExit): await call_command("fake://server", "nonexistent") @pytest.mark.usefixtures("_patch_client") async def test_call_tool_missing_args(self): with pytest.raises(SystemExit): await call_command("fake://server", "greet") @pytest.mark.usefixtures("_patch_client") async def test_call_resource_by_uri(self, capsys: pytest.CaptureFixture[str]): await call_command("fake://server", "test://greeting") captured = capsys.readouterr() assert "Hello from resource!" in captured.out @pytest.mark.usefixtures("_patch_client") async def test_call_resource_json(self, capsys: pytest.CaptureFixture[str]): await call_command("fake://server", "test://greeting", json_output=True) captured = capsys.readouterr() data = json.loads(captured.out) assert isinstance(data, list) assert data[0]["text"] == "Hello from resource!" @pytest.mark.usefixtures("_patch_client") async def test_call_prompt(self, capsys: pytest.CaptureFixture[str]): await call_command("fake://server", "ask", "topic=Python", prompt=True) captured = capsys.readouterr() assert "Python" in captured.out @pytest.mark.usefixtures("_patch_client") async def test_call_prompt_json(self, capsys: pytest.CaptureFixture[str]): await call_command( "fake://server", "ask", "topic=Python", prompt=True, json_output=True ) captured = capsys.readouterr() data = json.loads(captured.out) assert "messages" in data @pytest.mark.usefixtures("_patch_client") async def test_call_prompt_not_found(self): with pytest.raises(SystemExit): await call_command("fake://server", "nonexistent", prompt=True) async def test_call_missing_target(self): with pytest.raises(SystemExit): await call_command("fake://server", "") # --------------------------------------------------------------------------- # Structured content serialization # --------------------------------------------------------------------------- class TestFormatCallResult: def test_structured_content_uses_dict_not_data( self, capsys: pytest.CaptureFixture[str] ): """structured_content (raw dict) is used for display, not data (which may be a non-serializable dataclass).""" result = CallToolResult( content=[mcp.types.TextContent(type="text", text="ok")], structured_content={"key": "value"}, meta=None, data=object(), # non-serializable on purpose is_error=False, ) # Should not raise — uses structured_content, not data _format_call_result_text(result) captured = capsys.readouterr() assert "value" in captured.out def test_escapes_rich_markup_and_control_chars( self, capsys: pytest.CaptureFixture[str] ): result = CallToolResult( content=[mcp.types.TextContent(type="text", text="[red]x[/red]\x1b[2J")], structured_content=None, meta=None, data=None, is_error=False, ) _format_call_result_text(result) captured = capsys.readouterr() assert "[red]x[/red]" in captured.out assert "\\x1b" in captured.out assert "\x1b" not in captured.out class TestSanitizeUntrustedText: def test_sanitize_untrusted_text(self): value = "[bold]hello[/bold]\x07" sanitized = _sanitize_untrusted_text(value) assert sanitized == "\\[bold]hello\\[/bold]\\x07"
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/cli/test_client_commands.py", "license": "Apache License 2.0", "lines": 458, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/cli/test_discovery.py
"""Tests for MCP server discovery and name-based resolution.""" import json from pathlib import Path from typing import Any import pytest import yaml from fastmcp.cli.client import _is_http_target, resolve_server_spec from fastmcp.cli.discovery import ( DiscoveredServer, _normalize_server_entry, _parse_mcp_config, _scan_claude_code, _scan_claude_desktop, _scan_cursor_workspace, _scan_gemini, _scan_goose, _scan_project_mcp_json, discover_servers, resolve_name, ) from fastmcp.client.transports.http import StreamableHttpTransport from fastmcp.client.transports.sse import SSETransport from fastmcp.client.transports.stdio import StdioTransport from fastmcp.mcp_config import RemoteMCPServer, StdioMCPServer # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- _STDIO_CONFIG: dict[str, Any] = { "mcpServers": { "weather": { "command": "npx", "args": ["-y", "@mcp/weather"], }, "github": { "command": "npx", "args": ["-y", "@mcp/github"], "env": {"GITHUB_TOKEN": "xxx"}, }, } } _REMOTE_CONFIG: dict[str, Any] = { "mcpServers": { "api": { "url": "http://localhost:8000/mcp", }, } } def _write_config(path: Path, data: dict[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(data)) # --------------------------------------------------------------------------- # DiscoveredServer properties # --------------------------------------------------------------------------- class TestDiscoveredServer: def test_qualified_name(self): server = DiscoveredServer( name="weather", source="claude-desktop", config=StdioMCPServer(command="npx", args=["-y", "@mcp/weather"]), config_path=Path("/fake/config.json"), ) assert server.qualified_name == "claude-desktop:weather" def test_transport_summary_stdio(self): server = DiscoveredServer( name="weather", source="cursor", config=StdioMCPServer(command="npx", args=["-y", "@mcp/weather"]), config_path=Path("/fake/config.json"), ) assert server.transport_summary == "stdio: npx -y @mcp/weather" def test_transport_summary_remote(self): server = DiscoveredServer( name="api", source="project", config=RemoteMCPServer(url="http://localhost:8000/mcp"), config_path=Path("/fake/config.json"), ) assert server.transport_summary == "http: http://localhost:8000/mcp" def test_transport_summary_remote_sse(self): server = DiscoveredServer( name="api", source="project", config=RemoteMCPServer(url="http://localhost:8000/sse", transport="sse"), config_path=Path("/fake/config.json"), ) assert server.transport_summary == "sse: http://localhost:8000/sse" # --------------------------------------------------------------------------- # _parse_mcp_config # --------------------------------------------------------------------------- class TestParseMcpConfig: def test_valid_config(self, tmp_path: Path): path = tmp_path / "config.json" _write_config(path, _STDIO_CONFIG) servers = _parse_mcp_config(path, "test-source") assert len(servers) == 2 names = {s.name for s in servers} assert names == {"weather", "github"} assert all(s.source == "test-source" for s in servers) assert all(s.config_path == path for s in servers) def test_missing_file(self, tmp_path: Path): path = tmp_path / "nonexistent.json" servers = _parse_mcp_config(path, "test") assert servers == [] def test_invalid_json(self, tmp_path: Path): path = tmp_path / "bad.json" path.write_text("{not json") servers = _parse_mcp_config(path, "test") assert servers == [] def test_no_mcp_servers_key(self, tmp_path: Path): path = tmp_path / "config.json" _write_config(path, {"something": "else"}) servers = _parse_mcp_config(path, "test") assert servers == [] def test_empty_mcp_servers(self, tmp_path: Path): path = tmp_path / "config.json" _write_config(path, {"mcpServers": {}}) servers = _parse_mcp_config(path, "test") assert servers == [] def test_remote_server(self, tmp_path: Path): path = tmp_path / "config.json" _write_config(path, _REMOTE_CONFIG) servers = _parse_mcp_config(path, "test") assert len(servers) == 1 assert isinstance(servers[0].config, RemoteMCPServer) assert servers[0].config.url == "http://localhost:8000/mcp" # --------------------------------------------------------------------------- # Scanner: Claude Desktop # --------------------------------------------------------------------------- class TestScanClaudeDesktop: def test_finds_config(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): config_dir = tmp_path / "Claude" config_path = config_dir / "claude_desktop_config.json" _write_config(config_path, _STDIO_CONFIG) monkeypatch.setattr("fastmcp.cli.discovery.Path.home", lambda: tmp_path) # Force darwin for deterministic path monkeypatch.setattr("fastmcp.cli.discovery.sys.platform", "darwin") # We need to override the path construction. On macOS it's # ~/Library/Application Support/Claude — create that. mac_dir = tmp_path / "Library" / "Application Support" / "Claude" mac_path = mac_dir / "claude_desktop_config.json" _write_config(mac_path, _STDIO_CONFIG) servers = _scan_claude_desktop() assert len(servers) == 2 assert all(s.source == "claude-desktop" for s in servers) def test_missing_config(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr("fastmcp.cli.discovery.Path.home", lambda: tmp_path) monkeypatch.setattr("fastmcp.cli.discovery.sys.platform", "darwin") servers = _scan_claude_desktop() assert servers == [] # --------------------------------------------------------------------------- # Normalize server entry # --------------------------------------------------------------------------- class TestNormalizeServerEntry: def test_remote_type_becomes_transport(self): entry = {"url": "http://localhost:8000/sse", "type": "sse"} result = _normalize_server_entry(entry) assert result["transport"] == "sse" assert "type" not in result def test_remote_with_transport_unchanged(self): entry = {"url": "http://localhost:8000/mcp", "transport": "http"} result = _normalize_server_entry(entry) assert result["transport"] == "http" def test_stdio_type_unchanged(self): """Stdio entries have ``type`` as a proper field — leave it alone.""" entry = {"command": "npx", "args": [], "type": "stdio"} result = _normalize_server_entry(entry) assert result["type"] == "stdio" def test_gemini_http_url_becomes_url(self): entry = {"httpUrl": "https://api.example.com/mcp/"} result = _normalize_server_entry(entry) assert result["url"] == "https://api.example.com/mcp/" assert "httpUrl" not in result def test_gemini_http_url_does_not_override_url(self): entry = {"url": "http://real.com", "httpUrl": "http://other.com"} result = _normalize_server_entry(entry) assert result["url"] == "http://real.com" # --------------------------------------------------------------------------- # Scanner: Claude Code # --------------------------------------------------------------------------- def _claude_code_config( *, global_servers: dict[str, Any] | None = None, project_path: str | None = None, project_servers: dict[str, Any] | None = None, ) -> dict[str, Any]: """Build a minimal ~/.claude.json structure.""" data: dict[str, Any] = {} if global_servers is not None: data["mcpServers"] = global_servers if project_path and project_servers is not None: data["projects"] = {project_path: {"mcpServers": project_servers}} return data class TestScanClaudeCode: def test_global_servers(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr("fastmcp.cli.discovery.Path.home", lambda: tmp_path) config_path = tmp_path / ".claude.json" _write_config( config_path, _claude_code_config(global_servers=_STDIO_CONFIG["mcpServers"]), ) servers = _scan_claude_code(tmp_path) assert len(servers) == 2 assert all(s.source == "claude-code" for s in servers) def test_project_servers(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr("fastmcp.cli.discovery.Path.home", lambda: tmp_path) project_dir = tmp_path / "my-project" project_dir.mkdir() config_path = tmp_path / ".claude.json" _write_config( config_path, _claude_code_config( project_path=str(project_dir), project_servers={"api": {"url": "http://localhost:8000/mcp"}}, ), ) servers = _scan_claude_code(project_dir) assert len(servers) == 1 assert servers[0].name == "api" def test_global_and_project_combined( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ): monkeypatch.setattr("fastmcp.cli.discovery.Path.home", lambda: tmp_path) project_dir = tmp_path / "proj" project_dir.mkdir() config_path = tmp_path / ".claude.json" _write_config( config_path, _claude_code_config( global_servers={"global-tool": {"command": "echo", "args": ["hi"]}}, project_path=str(project_dir), project_servers={"local-tool": {"command": "cat", "args": []}}, ), ) servers = _scan_claude_code(project_dir) names = {s.name for s in servers} assert names == {"global-tool", "local-tool"} def test_type_normalized_to_transport( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ): """Claude Code uses ``type: sse`` — verify it becomes ``transport``.""" monkeypatch.setattr("fastmcp.cli.discovery.Path.home", lambda: tmp_path) config_path = tmp_path / ".claude.json" _write_config( config_path, _claude_code_config( global_servers={ "sse-server": { "type": "sse", "url": "http://localhost:8000/sse", } } ), ) servers = _scan_claude_code(tmp_path) assert len(servers) == 1 assert isinstance(servers[0].config, RemoteMCPServer) assert servers[0].config.transport == "sse" def test_missing_file(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr("fastmcp.cli.discovery.Path.home", lambda: tmp_path) servers = _scan_claude_code(tmp_path) assert servers == [] def test_no_matching_project(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr("fastmcp.cli.discovery.Path.home", lambda: tmp_path) config_path = tmp_path / ".claude.json" _write_config( config_path, _claude_code_config( project_path="/some/other/project", project_servers={"tool": {"command": "echo", "args": []}}, ), ) servers = _scan_claude_code(tmp_path) assert servers == [] # --------------------------------------------------------------------------- # Scanner: Cursor workspace # --------------------------------------------------------------------------- class TestScanCursorWorkspace: def test_finds_config_in_cwd(self, tmp_path: Path): cursor_path = tmp_path / ".cursor" / "mcp.json" _write_config(cursor_path, _STDIO_CONFIG) servers = _scan_cursor_workspace(tmp_path) assert len(servers) == 2 assert all(s.source == "cursor" for s in servers) def test_finds_config_in_parent(self, tmp_path: Path): cursor_path = tmp_path / ".cursor" / "mcp.json" _write_config(cursor_path, _STDIO_CONFIG) child = tmp_path / "src" / "deep" child.mkdir(parents=True) servers = _scan_cursor_workspace(child) assert len(servers) == 2 def test_stops_at_home(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): # Place config above home — should not be found monkeypatch.setattr("fastmcp.cli.discovery.Path.home", lambda: tmp_path) above_home = tmp_path.parent / ".cursor" / "mcp.json" _write_config(above_home, _STDIO_CONFIG) child = tmp_path / "project" child.mkdir() servers = _scan_cursor_workspace(child) assert servers == [] def test_no_config(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): # Confine walk to tmp_path so it doesn't find sibling test dirs monkeypatch.setattr("fastmcp.cli.discovery.Path.home", lambda: tmp_path) servers = _scan_cursor_workspace(tmp_path) assert servers == [] # --------------------------------------------------------------------------- # Scanner: project mcp.json # --------------------------------------------------------------------------- class TestScanProjectMcpJson: def test_finds_config(self, tmp_path: Path): config_path = tmp_path / "mcp.json" _write_config(config_path, _STDIO_CONFIG) servers = _scan_project_mcp_json(tmp_path) assert len(servers) == 2 assert all(s.source == "project" for s in servers) def test_no_config(self, tmp_path: Path): servers = _scan_project_mcp_json(tmp_path) assert servers == [] # --------------------------------------------------------------------------- # Scanner: Gemini CLI # --------------------------------------------------------------------------- class TestScanGemini: def test_user_level_config(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr("fastmcp.cli.discovery.Path.home", lambda: tmp_path) config_path = tmp_path / ".gemini" / "settings.json" _write_config(config_path, _STDIO_CONFIG) servers = _scan_gemini(tmp_path) assert len(servers) == 2 assert all(s.source == "gemini" for s in servers) def test_project_level_config( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ): monkeypatch.setattr("fastmcp.cli.discovery.Path.home", lambda: tmp_path) project_dir = tmp_path / "my-project" project_dir.mkdir() config_path = project_dir / ".gemini" / "settings.json" _write_config(config_path, _STDIO_CONFIG) servers = _scan_gemini(project_dir) assert len(servers) == 2 def test_http_url_normalized(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): """Gemini uses ``httpUrl`` — verify it becomes ``url``.""" monkeypatch.setattr("fastmcp.cli.discovery.Path.home", lambda: tmp_path) config_path = tmp_path / ".gemini" / "settings.json" _write_config( config_path, { "mcpServers": { "api": {"httpUrl": "https://api.example.com/mcp/"}, } }, ) servers = _scan_gemini(tmp_path) assert len(servers) == 1 assert isinstance(servers[0].config, RemoteMCPServer) assert servers[0].config.url == "https://api.example.com/mcp/" def test_missing_config(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr("fastmcp.cli.discovery.Path.home", lambda: tmp_path) servers = _scan_gemini(tmp_path) assert servers == [] # --------------------------------------------------------------------------- # Scanner: Goose # --------------------------------------------------------------------------- _GOOSE_CONFIG = { "extensions": { "developer": { "enabled": True, "name": "developer", "type": "builtin", }, "tavily": { "cmd": "npx", "args": ["-y", "mcp-tavily-search"], "enabled": True, "envs": {"TAVILY_API_KEY": "xxx"}, "type": "stdio", }, "disabled-tool": { "cmd": "echo", "args": ["hi"], "enabled": False, "type": "stdio", }, } } class TestScanGoose: def test_finds_stdio_extensions( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ): monkeypatch.setattr("fastmcp.cli.discovery.Path.home", lambda: tmp_path) monkeypatch.delenv("XDG_CONFIG_HOME", raising=False) config_dir = tmp_path / ".config" / "goose" config_path = config_dir / "config.yaml" config_path.parent.mkdir(parents=True) config_path.write_text(yaml.dump(_GOOSE_CONFIG)) # Force non-windows platform for path logic monkeypatch.setattr("fastmcp.cli.discovery.sys.platform", "linux") servers = _scan_goose() assert len(servers) == 1 assert servers[0].name == "tavily" assert servers[0].source == "goose" assert isinstance(servers[0].config, StdioMCPServer) assert servers[0].config.command == "npx" def test_skips_builtin_and_disabled( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ): monkeypatch.setattr("fastmcp.cli.discovery.Path.home", lambda: tmp_path) monkeypatch.delenv("XDG_CONFIG_HOME", raising=False) config_dir = tmp_path / ".config" / "goose" config_path = config_dir / "config.yaml" config_path.parent.mkdir(parents=True) config_path.write_text(yaml.dump(_GOOSE_CONFIG)) monkeypatch.setattr("fastmcp.cli.discovery.sys.platform", "linux") servers = _scan_goose() names = {s.name for s in servers} assert "developer" not in names assert "disabled-tool" not in names def test_missing_config(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr("fastmcp.cli.discovery.Path.home", lambda: tmp_path) monkeypatch.setattr("fastmcp.cli.discovery.sys.platform", "linux") servers = _scan_goose() assert servers == [] # --------------------------------------------------------------------------- # discover_servers # --------------------------------------------------------------------------- def _suppress_user_scanners(monkeypatch: pytest.MonkeyPatch) -> None: """Suppress all scanners that read real user config files.""" monkeypatch.setattr("fastmcp.cli.discovery._scan_claude_desktop", lambda: []) monkeypatch.setattr("fastmcp.cli.discovery._scan_claude_code", lambda start_dir: []) monkeypatch.setattr("fastmcp.cli.discovery._scan_gemini", lambda start_dir: []) monkeypatch.setattr("fastmcp.cli.discovery._scan_goose", lambda: []) class TestDiscoverServers: def test_combines_sources(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): # Set up project mcp.json project_config = tmp_path / "mcp.json" _write_config(project_config, _STDIO_CONFIG) # Set up cursor config cursor_config = tmp_path / ".cursor" / "mcp.json" _write_config(cursor_config, _REMOTE_CONFIG) _suppress_user_scanners(monkeypatch) servers = discover_servers(start_dir=tmp_path) sources = {s.source for s in servers} assert "project" in sources assert "cursor" in sources assert len(servers) == 3 # 2 from project + 1 from cursor def test_preserves_duplicates( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ): """Same server name in multiple sources should appear multiple times.""" project_config = tmp_path / "mcp.json" _write_config(project_config, _STDIO_CONFIG) cursor_config = tmp_path / ".cursor" / "mcp.json" _write_config(cursor_config, _STDIO_CONFIG) _suppress_user_scanners(monkeypatch) servers = discover_servers(start_dir=tmp_path) weather_servers = [s for s in servers if s.name == "weather"] assert len(weather_servers) == 2 assert {s.source for s in weather_servers} == {"cursor", "project"} # --------------------------------------------------------------------------- # resolve_name # --------------------------------------------------------------------------- class TestResolveName: @pytest.fixture(autouse=True) def _isolate_scanners(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): """Suppress scanners that read real user configs and confine walks to tmp_path.""" _suppress_user_scanners(monkeypatch) monkeypatch.setattr("fastmcp.cli.discovery.Path.home", lambda: tmp_path) def test_unique_match(self, tmp_path: Path): config_path = tmp_path / "mcp.json" _write_config(config_path, _STDIO_CONFIG) transport = resolve_name("weather", start_dir=tmp_path) assert isinstance(transport, StdioTransport) def test_qualified_match(self, tmp_path: Path): config_path = tmp_path / "mcp.json" _write_config(config_path, _STDIO_CONFIG) transport = resolve_name("project:weather", start_dir=tmp_path) assert isinstance(transport, StdioTransport) def test_not_found_with_servers(self, tmp_path: Path): config_path = tmp_path / "mcp.json" _write_config(config_path, _STDIO_CONFIG) with pytest.raises(ValueError, match="No server named 'nope'.*Available"): resolve_name("nope", start_dir=tmp_path) def test_not_found_no_servers(self, tmp_path: Path): with pytest.raises(ValueError, match="No server named 'nope'.*Searched"): resolve_name("nope", start_dir=tmp_path) def test_ambiguous_name(self, tmp_path: Path): project_config = tmp_path / "mcp.json" _write_config(project_config, _STDIO_CONFIG) cursor_config = tmp_path / ".cursor" / "mcp.json" _write_config(cursor_config, _STDIO_CONFIG) with pytest.raises(ValueError, match="Ambiguous server name 'weather'"): resolve_name("weather", start_dir=tmp_path) def test_ambiguous_resolved_by_qualified(self, tmp_path: Path): project_config = tmp_path / "mcp.json" _write_config(project_config, _STDIO_CONFIG) cursor_config = tmp_path / ".cursor" / "mcp.json" _write_config(cursor_config, _STDIO_CONFIG) transport = resolve_name("cursor:weather", start_dir=tmp_path) assert isinstance(transport, StdioTransport) def test_qualified_not_found(self, tmp_path: Path): config_path = tmp_path / "mcp.json" _write_config(config_path, _STDIO_CONFIG) with pytest.raises( ValueError, match="No server named 'nope' found in source 'project'" ): resolve_name("project:nope", start_dir=tmp_path) def test_remote_server_resolves_to_http_transport(self, tmp_path: Path): config_path = tmp_path / "mcp.json" _write_config(config_path, _REMOTE_CONFIG) transport = resolve_name("api", start_dir=tmp_path) assert isinstance(transport, StreamableHttpTransport) # --------------------------------------------------------------------------- # Integration: resolve_server_spec falls through to name resolution # --------------------------------------------------------------------------- class TestResolveServerSpecNameFallback: def test_bare_name_resolves(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): config_path = tmp_path / "mcp.json" _write_config(config_path, _STDIO_CONFIG) _suppress_user_scanners(monkeypatch) monkeypatch.setattr("fastmcp.cli.discovery.Path.home", lambda: tmp_path) # Monkeypatch resolve_name in client module to use our tmp_path original_resolve = resolve_name def patched_resolve(name: str, start_dir: Path | None = None) -> Any: return original_resolve(name, start_dir=tmp_path) monkeypatch.setattr("fastmcp.cli.client.resolve_name", patched_resolve) result = resolve_server_spec("weather") assert isinstance(result, StdioTransport) def test_url_takes_priority_over_name(self): """URLs should be resolved before name lookup.""" result = resolve_server_spec("http://localhost:8000/mcp") assert result == "http://localhost:8000/mcp" # --------------------------------------------------------------------------- # Integration: _is_http_target detects transport objects # --------------------------------------------------------------------------- class TestIsHttpTargetTransports: def test_streamable_http_transport(self): transport = StreamableHttpTransport("http://localhost:8000/mcp") assert _is_http_target(transport) is True def test_sse_transport(self): transport = SSETransport("http://localhost:8000/sse") assert _is_http_target(transport) is True def test_stdio_transport(self): transport = StdioTransport(command="echo", args=["hello"]) assert _is_http_target(transport) is False def test_string_url(self): assert _is_http_target("http://localhost:8000") is True def test_string_non_url(self): assert _is_http_target("server.py") is False def test_dict_config(self): assert _is_http_target({"mcpServers": {}}) is False
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/cli/test_discovery.py", "license": "Apache License 2.0", "lines": 548, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/cli/test_generate_cli.py
"""Tests for fastmcp generate-cli command.""" import sys from pathlib import Path from typing import Any from unittest.mock import patch import mcp.types import pytest from fastmcp import FastMCP from fastmcp.cli import generate as generate_module from fastmcp.cli.client import Client from fastmcp.cli.generate import ( _derive_server_name, _param_to_cli_flag, _schema_to_python_type, _schema_type_label, _to_python_identifier, _tool_function_source, generate_cli_command, generate_cli_script, generate_skill_content, serialize_transport, ) from fastmcp.client.transports.stdio import StdioTransport # --------------------------------------------------------------------------- # _schema_to_python_type # --------------------------------------------------------------------------- class TestSchemaToPythonType: def test_simple_string(self): py_type, needs_json = _schema_to_python_type({"type": "string"}) assert py_type == "str" assert needs_json is False def test_simple_integer(self): py_type, needs_json = _schema_to_python_type({"type": "integer"}) assert py_type == "int" assert needs_json is False def test_simple_number(self): py_type, needs_json = _schema_to_python_type({"type": "number"}) assert py_type == "float" assert needs_json is False def test_simple_boolean(self): py_type, needs_json = _schema_to_python_type({"type": "boolean"}) assert py_type == "bool" assert needs_json is False def test_array_of_strings(self): py_type, needs_json = _schema_to_python_type( {"type": "array", "items": {"type": "string"}} ) assert py_type == "list[str]" assert needs_json is False def test_array_of_integers(self): py_type, needs_json = _schema_to_python_type( {"type": "array", "items": {"type": "integer"}} ) assert py_type == "list[int]" assert needs_json is False def test_complex_object(self): py_type, needs_json = _schema_to_python_type({"type": "object"}) assert py_type == "str" assert needs_json is True def test_complex_nested_array(self): py_type, needs_json = _schema_to_python_type( {"type": "array", "items": {"type": "object"}} ) assert py_type == "str" assert needs_json is True def test_union_of_simple_types(self): py_type, needs_json = _schema_to_python_type({"type": ["string", "null"]}) assert py_type == "str | None" assert needs_json is False # --------------------------------------------------------------------------- # _to_python_identifier # --------------------------------------------------------------------------- class TestToPythonIdentifier: def test_plain_name(self): assert _to_python_identifier("hello") == "hello" def test_hyphens(self): assert _to_python_identifier("get-forecast") == "get_forecast" def test_dots_and_slashes(self): assert _to_python_identifier("a.b/c") == "a_b_c" def test_leading_digit(self): assert _to_python_identifier("3d_render") == "_3d_render" def test_spaces(self): assert _to_python_identifier("my tool") == "my_tool" def test_empty_string(self): assert _to_python_identifier("") == "_unnamed" # --------------------------------------------------------------------------- # serialize_transport # --------------------------------------------------------------------------- class TestSerializeTransport: def test_url_string(self): code, imports = serialize_transport("http://localhost:8000/mcp") assert code == "'http://localhost:8000/mcp'" assert imports == set() def test_stdio_transport_basic(self): transport = StdioTransport(command="fastmcp", args=["run", "server.py"]) code, imports = serialize_transport(transport) assert "StdioTransport" in code assert "command='fastmcp'" in code assert "args=['run', 'server.py']" in code assert "from fastmcp.client.transports import StdioTransport" in imports def test_stdio_transport_with_env(self): transport = StdioTransport( command="python", args=["-m", "myserver"], env={"KEY": "val"} ) code, imports = serialize_transport(transport) assert "env={'KEY': 'val'}" in code def test_dict_passthrough(self): d: dict[str, Any] = {"mcpServers": {"test": {"url": "http://localhost"}}} code, imports = serialize_transport(d) assert "mcpServers" in code assert imports == set() # --------------------------------------------------------------------------- # _tool_function_source # --------------------------------------------------------------------------- class TestToolFunctionSource: def test_required_param(self): tool = mcp.types.Tool( name="greet", inputSchema={ "properties": {"name": {"type": "string", "description": "Who"}}, "required": ["name"], }, ) source = _tool_function_source(tool) assert "async def greet(" in source assert "name: Annotated[str" in source assert "= None" not in source assert "_call_tool('greet', {'name': name})" in source def test_optional_param(self): tool = mcp.types.Tool( name="search", inputSchema={ "properties": { "query": {"type": "string", "description": "Search query"}, "limit": {"type": "integer", "description": "Max results"}, }, "required": ["query"], }, ) source = _tool_function_source(tool) assert "query: Annotated[str" in source assert "limit: Annotated[int | None" in source assert "= None" in source def test_param_with_default(self): tool = mcp.types.Tool( name="fetch", inputSchema={ "properties": { "url": {"type": "string", "description": "URL"}, "timeout": { "type": "integer", "description": "Timeout", "default": 30, }, }, "required": ["url"], }, ) source = _tool_function_source(tool) assert "timeout: Annotated[int" in source assert "= 30" in source def test_no_params(self): tool = mcp.types.Tool( name="ping", inputSchema={"properties": {}}, ) source = _tool_function_source(tool) assert "async def ping(" in source assert "_call_tool('ping', {})" in source def test_preserves_underscores(self): tool = mcp.types.Tool( name="get_forecast", inputSchema={ "properties": {"city": {"type": "string"}}, "required": ["city"], }, ) source = _tool_function_source(tool) assert "async def get_forecast(" in source def test_sanitizes_tool_name(self): tool = mcp.types.Tool( name="my.tool/v2", inputSchema={"properties": {}}, ) source = _tool_function_source(tool) assert "async def my_tool_v2(" in source assert "name='my.tool/v2'" in source def test_sanitizes_param_name(self): tool = mcp.types.Tool( name="fetch", inputSchema={ "properties": {"content-type": {"type": "string", "description": "CT"}}, "required": ["content-type"], }, ) source = _tool_function_source(tool) assert "content_type: Annotated[str" in source assert "'content-type': content_type" in source def test_description_in_docstring(self): tool = mcp.types.Tool( name="greet", description="Say hello to someone.", inputSchema={ "properties": {"name": {"type": "string"}}, "required": ["name"], }, ) source = _tool_function_source(tool) assert "'''Say hello to someone.'''" in source def test_description_with_quotes(self): tool = mcp.types.Tool( name="fetch", description="Fetch data from 'source' API.", inputSchema={ "properties": {"url": {"type": "string"}}, "required": ["url"], }, ) source = _tool_function_source(tool) # Should escape single quotes in the description assert r"Fetch data from \'source\' API." in source # Generated code should compile compile(source, "<test>", "exec") def test_array_of_strings_parameter(self): tool = mcp.types.Tool( name="tag_items", description="Tag multiple items.", inputSchema={ "properties": { "item_id": {"type": "string"}, "tags": {"type": "array", "items": {"type": "string"}}, }, "required": ["item_id"], }, ) source = _tool_function_source(tool) # Should use list[str] type with help metadata assert "tags: Annotated[list[str]" in source assert "= []" in source # Should not have JSON parsing for simple arrays assert "json.loads" not in source compile(source, "<test>", "exec") def test_complex_object_parameter(self): tool = mcp.types.Tool( name="create_user", description="Create a user.", inputSchema={ "properties": { "name": {"type": "string"}, "metadata": { "type": "object", "properties": { "role": {"type": "string"}, "dept": {"type": "string"}, }, }, }, "required": ["name"], }, ) source = _tool_function_source(tool) # Should use str type for complex object assert "metadata: Annotated[str | None" in source # Should include JSON schema in help (with escaped quotes) assert "JSON Schema:" in source assert '\\"type\\": \\"object\\"' in source # Should have JSON parsing with isinstance check assert ( "metadata_parsed = json.loads(metadata) if isinstance(metadata, str) else metadata" in source ) # Should use parsed version in call assert "'metadata': metadata_parsed" in source compile(source, "<test>", "exec") def test_nested_array_parameter(self): tool = mcp.types.Tool( name="batch_process", description="Process batches.", inputSchema={ "properties": { "batches": { "type": "array", "items": { "type": "object", "properties": {"id": {"type": "string"}}, }, }, }, "required": ["batches"], }, ) source = _tool_function_source(tool) # Nested arrays need JSON parsing assert "batches: Annotated[str" in source assert "JSON Schema:" in source assert ( "batches_parsed = json.loads(batches) if isinstance(batches, str) else batches" in source ) compile(source, "<test>", "exec") def test_complex_type_with_default(self): """Test that complex types with defaults are JSON-serialized.""" tool = mcp.types.Tool( name="configure", inputSchema={ "properties": { "options": { "type": "object", "default": {"timeout": 30, "retry": True}, }, }, }, ) source = _tool_function_source(tool) # Default should be JSON string, not Python dict # pydantic_core.to_json produces compact JSON assert '= \'{"timeout":30,"retry":true}\'' in source # Should parse safely even with default assert "isinstance(options, str)" in source compile(source, "<test>", "exec") def test_name_collision_detection(self): """Test that parameter name collisions are detected.""" tool = mcp.types.Tool( name="test", inputSchema={ "properties": { "content-type": {"type": "string"}, "content_type": {"type": "string"}, }, }, ) # Should raise ValueError for collision with pytest.raises(ValueError, match="both sanitize to 'content_type'"): _tool_function_source(tool) # --------------------------------------------------------------------------- # _derive_server_name # --------------------------------------------------------------------------- class TestDeriveServerName: def test_bare_name(self): assert _derive_server_name("weather") == "weather" def test_qualified_name(self): assert _derive_server_name("cursor:weather") == "weather" def test_python_file(self): assert _derive_server_name("server.py") == "server" def test_url(self): assert _derive_server_name("http://localhost:8000/mcp") == "localhost" def test_trailing_colon(self): assert _derive_server_name("source:") == "source" # --------------------------------------------------------------------------- # generate_cli_script — produces compilable Python # --------------------------------------------------------------------------- class TestGenerateCliScript: def _make_tools(self) -> list[mcp.types.Tool]: return [ mcp.types.Tool( name="greet", description="Say hello", inputSchema={ "properties": { "name": {"type": "string", "description": "Who to greet"}, }, "required": ["name"], }, ), mcp.types.Tool( name="add_numbers", description="Add two numbers", inputSchema={ "properties": { "a": {"type": "integer", "description": "First number"}, "b": {"type": "integer", "description": "Second number"}, }, "required": ["a", "b"], }, ), ] def test_compiles(self): script = generate_cli_script( server_name="test", server_spec="test", transport_code='"http://localhost:8000/mcp"', extra_imports=set(), tools=self._make_tools(), ) compile(script, "<generated>", "exec") def test_contains_tool_functions(self): script = generate_cli_script( server_name="test", server_spec="test", transport_code='"http://localhost:8000/mcp"', extra_imports=set(), tools=self._make_tools(), ) assert "async def greet(" in script assert "async def add_numbers(" in script def test_contains_generic_commands(self): script = generate_cli_script( server_name="test", server_spec="test", transport_code='"http://localhost:8000/mcp"', extra_imports=set(), tools=[], ) assert "async def list_tools(" in script assert "async def list_resources(" in script assert "async def list_prompts(" in script assert "async def read_resource(" in script assert "async def get_prompt(" in script def test_embeds_transport(self): script = generate_cli_script( server_name="test", server_spec="test", transport_code="StdioTransport(command='fastmcp', args=['run', 'x.py'])", extra_imports={"from fastmcp.client.transports import StdioTransport"}, tools=[], ) assert "StdioTransport(command='fastmcp'" in script assert "from fastmcp.client.transports import StdioTransport" in script def test_no_tools_still_valid(self): script = generate_cli_script( server_name="empty", server_spec="empty", transport_code='"http://localhost"', extra_imports=set(), tools=[], ) compile(script, "<generated>", "exec") assert "call_tool_app" in script def test_server_name_with_quotes(self): """Test that server names with quotes are properly escaped.""" script = generate_cli_script( server_name='Test "Server" Name', server_spec="test", transport_code='"http://localhost"', extra_imports=set(), tools=[], ) # Should compile without syntax errors compile(script, "<generated>", "exec") # App name should have escaped quotes assert r'app = cyclopts.App(name="test-\"server\"-name"' in script def test_compiles_with_unusual_names(self): tools = [ mcp.types.Tool( name="my.tool/v2", description="A tool with dots and slashes", inputSchema={ "properties": { "content-type": {"type": "string", "description": "CT"}, }, "required": ["content-type"], }, ), ] script = generate_cli_script( server_name="test", server_spec="test", transport_code='"http://localhost:8000/mcp"', extra_imports=set(), tools=tools, ) compile(script, "<generated>", "exec") def test_compiles_with_stdio_transport(self): transport = StdioTransport(command="fastmcp", args=["run", "server.py"]) transport_code, extra_imports = serialize_transport(transport) script = generate_cli_script( server_name="test", server_spec="server.py", transport_code=transport_code, extra_imports=extra_imports, tools=self._make_tools(), ) compile(script, "<generated>", "exec") # --------------------------------------------------------------------------- # generate_cli_command — integration tests # --------------------------------------------------------------------------- def _build_test_server() -> FastMCP: """Create a minimal FastMCP server for integration tests.""" server = FastMCP("TestServer") @server.tool def greet(name: str) -> str: """Say hello to someone.""" return f"Hello, {name}!" @server.tool def add(a: int, b: int) -> int: """Add two numbers.""" return a + b @server.resource("test://greeting") def greeting_resource() -> str: """A static greeting resource.""" return "Hello from resource!" @server.prompt def ask(topic: str) -> str: """Ask about a topic.""" return f"Tell me about {topic}" return server @pytest.fixture() def _patch_client(): """Patch resolve_server_spec and _build_client to use an in-process server.""" server = _build_test_server() def fake_resolve(server_spec: Any, **kwargs: Any) -> str: return "fake://server" def fake_build_client(resolved: Any, **kwargs: Any) -> Client: return Client(server) with ( patch.object(generate_module, "resolve_server_spec", side_effect=fake_resolve), patch.object(generate_module, "_build_client", side_effect=fake_build_client), ): yield class TestGenerateCliCommand: @pytest.mark.usefixtures("_patch_client") async def test_writes_file(self, tmp_path: Path): output = tmp_path / "cli.py" await generate_cli_command("test-server", str(output)) assert output.exists() content = output.read_text() compile(content, str(output), "exec") @pytest.mark.usefixtures("_patch_client") async def test_contains_tools(self, tmp_path: Path): output = tmp_path / "cli.py" await generate_cli_command("test-server", str(output)) content = output.read_text() assert "async def greet(" in content assert "async def add(" in content @pytest.mark.usefixtures("_patch_client") async def test_default_output_path( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ): monkeypatch.chdir(tmp_path) await generate_cli_command("test-server") assert (tmp_path / "cli.py").exists() @pytest.mark.usefixtures("_patch_client") async def test_error_if_exists(self, tmp_path: Path): output = tmp_path / "cli.py" output.write_text("existing") with pytest.raises(SystemExit): await generate_cli_command("test-server", str(output)) @pytest.mark.usefixtures("_patch_client") async def test_force_overwrites(self, tmp_path: Path): output = tmp_path / "cli.py" output.write_text("existing") await generate_cli_command("test-server", str(output), force=True) content = output.read_text() assert content != "existing" assert "async def greet(" in content @pytest.mark.skipif( sys.platform == "win32", reason="Unix executable bits N/A on Windows" ) @pytest.mark.usefixtures("_patch_client") async def test_file_is_executable(self, tmp_path: Path): output = tmp_path / "cli.py" await generate_cli_command("test-server", str(output)) assert output.stat().st_mode & 0o111 @pytest.mark.usefixtures("_patch_client") async def test_writes_skill_file(self, tmp_path: Path): output = tmp_path / "cli.py" await generate_cli_command("test-server", str(output)) skill_path = tmp_path / "SKILL.md" assert skill_path.exists() content = skill_path.read_text() assert "---" in content assert "name:" in content @pytest.mark.usefixtures("_patch_client") async def test_skill_contains_tools(self, tmp_path: Path): output = tmp_path / "cli.py" await generate_cli_command("test-server", str(output)) content = (tmp_path / "SKILL.md").read_text() assert "### greet" in content assert "### add" in content assert "--name" in content assert "call-tool greet" in content @pytest.mark.usefixtures("_patch_client") async def test_no_skill_flag(self, tmp_path: Path): output = tmp_path / "cli.py" await generate_cli_command("test-server", str(output), no_skill=True) assert not (tmp_path / "SKILL.md").exists() @pytest.mark.usefixtures("_patch_client") async def test_error_if_skill_exists(self, tmp_path: Path): output = tmp_path / "cli.py" (tmp_path / "SKILL.md").write_text("existing") with pytest.raises(SystemExit): await generate_cli_command("test-server", str(output)) @pytest.mark.usefixtures("_patch_client") async def test_force_overwrites_skill(self, tmp_path: Path): output = tmp_path / "cli.py" (tmp_path / "SKILL.md").write_text("existing") await generate_cli_command("test-server", str(output), force=True) content = (tmp_path / "SKILL.md").read_text() assert content != "existing" assert "### greet" in content @pytest.mark.usefixtures("_patch_client") async def test_skill_references_cli_filename(self, tmp_path: Path): output = tmp_path / "my_weather.py" await generate_cli_command("test-server", str(output)) content = (tmp_path / "SKILL.md").read_text() assert "uv run --with fastmcp python my_weather.py" in content # --------------------------------------------------------------------------- # _param_to_cli_flag # --------------------------------------------------------------------------- class TestParamToCliFlag: def test_simple_name(self): assert _param_to_cli_flag("city") == "--city" def test_underscore_name(self): assert _param_to_cli_flag("max_days") == "--max-days" def test_hyphenated_name(self): # content-type → _to_python_identifier → content_type → --content-type assert _param_to_cli_flag("content-type") == "--content-type" def test_digit_prefix(self): # 3d_mode → _3d_mode → --3d-mode (leading underscore stripped) assert _param_to_cli_flag("3d_mode") == "--3d-mode" def test_trailing_underscore(self): # from → from_ after identifier sanitization; Cyclopts strips trailing "-" assert _param_to_cli_flag("from") == "--from" def test_camel_case(self): # camelCase → camel-case (cyclopts default_name_transform) assert _param_to_cli_flag("myParam") == "--my-param" def test_pascal_case(self): assert _param_to_cli_flag("MyParam") == "--my-param" # --------------------------------------------------------------------------- # _schema_type_label # --------------------------------------------------------------------------- class TestSchemaTypeLabel: def test_simple_string(self): assert _schema_type_label({"type": "string"}) == "string" def test_integer(self): assert _schema_type_label({"type": "integer"}) == "integer" def test_array_of_strings(self): assert ( _schema_type_label({"type": "array", "items": {"type": "string"}}) == "array[string]" ) def test_union_types(self): result = _schema_type_label({"type": ["string", "null"]}) assert "string" in result assert "null" in result def test_object(self): assert _schema_type_label({"type": "object"}) == "object" def test_missing_type(self): assert _schema_type_label({}) == "string" # --------------------------------------------------------------------------- # generate_skill_content # --------------------------------------------------------------------------- class TestGenerateSkillContent: def test_frontmatter(self): content = generate_skill_content("weather", "cli.py", []) assert content.startswith("---\n") assert 'name: "weather-cli"' in content assert "description:" in content def test_no_tools(self): content = generate_skill_content("weather", "cli.py", []) assert "## Utility Commands" in content assert "## Tool Commands" not in content def test_tool_sections(self): tools = [ mcp.types.Tool( name="greet", description="Say hello", inputSchema={ "type": "object", "properties": { "name": {"type": "string", "description": "Who to greet"} }, "required": ["name"], }, ), ] content = generate_skill_content("test", "cli.py", tools) assert "## Tool Commands" in content assert "### greet" in content assert "Say hello" in content assert "call-tool greet" in content assert "`--name`" in content assert "| string |" in content assert "| yes |" in content def test_frontmatter_with_tools_starts_at_column_zero(self): tools = [ mcp.types.Tool( name="greet", inputSchema={"type": "object", "properties": {}}, ), ] content = generate_skill_content("weather", "cli.py", tools) assert content.splitlines()[0] == "---" def test_optional_param(self): tools = [ mcp.types.Tool( name="search", description="Search things", inputSchema={ "type": "object", "properties": { "query": {"type": "string"}, "limit": {"type": "integer"}, }, "required": ["query"], }, ), ] content = generate_skill_content("test", "cli.py", tools) # query is required, limit is not assert "| `--query` | string | yes |" in content assert "| `--limit` | integer | no |" in content def test_complex_json_param(self): tools = [ mcp.types.Tool( name="create", description="Create item", inputSchema={ "type": "object", "properties": { "data": { "type": "object", "properties": {"x": {"type": "integer"}}, }, }, "required": ["data"], }, ), ] content = generate_skill_content("test", "cli.py", tools) assert "JSON string" in content def test_no_params_tool(self): tools = [ mcp.types.Tool( name="ping", description="Ping the server", inputSchema={"type": "object", "properties": {}}, ), ] content = generate_skill_content("test", "cli.py", tools) assert "### ping" in content assert "call-tool ping" in content # No parameter table assert "| Flag |" not in content def test_cli_filename_in_utility_commands(self): content = generate_skill_content("test", "my_cli.py", []) assert "uv run --with fastmcp python my_cli.py list-tools" in content assert "uv run --with fastmcp python my_cli.py list-resources" in content def test_pipe_in_description_escaped(self): tools = [ mcp.types.Tool( name="test", description="Test", inputSchema={ "type": "object", "properties": { "mode": {"type": "string", "description": "a|b|c"}, }, }, ), ] content = generate_skill_content("test", "cli.py", tools) assert "a\\|b\\|c" in content def test_union_type_pipes_escaped(self): tools = [ mcp.types.Tool( name="test", description="Test", inputSchema={ "type": "object", "properties": { "val": {"type": ["string", "null"]}, }, }, ), ] content = generate_skill_content("test", "cli.py", tools) # Pipes in type label must be escaped so markdown table renders correctly assert "string \\| null" in content def test_boolean_param_no_value_placeholder(self): tools = [ mcp.types.Tool( name="run", description="Run something", inputSchema={ "type": "object", "properties": { "verbose": {"type": "boolean", "description": "Verbose output"}, "name": {"type": "string"}, }, }, ), ] content = generate_skill_content("test", "cli.py", tools) assert "--verbose <value>" not in content assert "--name <value>" in content def test_server_name_in_header(self): content = generate_skill_content("My Weather API", "cli.py", []) assert "# My Weather API CLI" in content assert 'name: "my-weather-api-cli"' in content
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/cli/test_generate_cli.py", "license": "Apache License 2.0", "lines": 790, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/client/auth/test_oauth_cimd.py
"""Tests for CIMD (Client ID Metadata Document) support in the OAuth client.""" from __future__ import annotations import warnings import httpx import pytest from fastmcp.client.auth import OAuth from fastmcp.client.transports import StreamableHttpTransport from fastmcp.client.transports.sse import SSETransport VALID_CIMD_URL = "https://myapp.example.com/oauth/client.json" MCP_SERVER_URL = "https://mcp-server.example.com/mcp" class TestOAuthClientMetadataURL: """Tests for the client_metadata_url parameter on OAuth.""" def test_stored_on_instance(self): oauth = OAuth(client_metadata_url=VALID_CIMD_URL) assert oauth._client_metadata_url == VALID_CIMD_URL def test_none_by_default(self): oauth = OAuth() assert oauth._client_metadata_url is None def test_passed_to_parent_on_bind(self): with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) oauth = OAuth(client_metadata_url=VALID_CIMD_URL) oauth._bind(MCP_SERVER_URL) assert oauth.context.client_metadata_url == VALID_CIMD_URL def test_none_metadata_url_on_parent(self): with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) oauth = OAuth(mcp_url=MCP_SERVER_URL) assert oauth.context.client_metadata_url is None def test_unbound_when_no_mcp_url(self): oauth = OAuth(client_metadata_url=VALID_CIMD_URL) assert oauth._bound is False def test_bound_when_mcp_url_provided(self): with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) oauth = OAuth( mcp_url=MCP_SERVER_URL, client_metadata_url=VALID_CIMD_URL, ) assert oauth._bound is True def test_invalid_cimd_url_rejected(self): """CIMD URLs must be HTTPS with a non-root path.""" with pytest.raises(ValueError, match="valid HTTPS URL"): OAuth( mcp_url=MCP_SERVER_URL, client_metadata_url="http://insecure.com/client.json", ) def test_root_path_cimd_url_rejected(self): with pytest.raises(ValueError, match="valid HTTPS URL"): OAuth( mcp_url=MCP_SERVER_URL, client_metadata_url="https://example.com/", ) class TestOAuthBind: """Tests for the _bind() deferred initialization.""" def test_bind_sets_bound_true(self): oauth = OAuth(client_metadata_url=VALID_CIMD_URL) assert oauth._bound is False with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) oauth._bind(MCP_SERVER_URL) assert oauth._bound is True def test_bind_idempotent(self): """Second call to _bind is a no-op.""" oauth = OAuth(client_metadata_url=VALID_CIMD_URL) with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) oauth._bind(MCP_SERVER_URL) oauth._bind("https://other-server.example.com/mcp") # First binding wins assert oauth.mcp_url == MCP_SERVER_URL def test_bind_sets_mcp_url(self): oauth = OAuth(client_metadata_url=VALID_CIMD_URL) with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) oauth._bind(MCP_SERVER_URL + "/") # Trailing slash stripped assert oauth.mcp_url == MCP_SERVER_URL def test_bind_creates_token_storage(self): oauth = OAuth(client_metadata_url=VALID_CIMD_URL) assert not hasattr(oauth, "token_storage_adapter") with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) oauth._bind(MCP_SERVER_URL) assert hasattr(oauth, "token_storage_adapter") async def test_unbound_raises_runtime_error(self): """async_auth_flow should fail clearly when OAuth is not bound.""" oauth = OAuth(client_metadata_url=VALID_CIMD_URL) request = httpx.Request("GET", MCP_SERVER_URL) with pytest.raises(RuntimeError, match="no server URL"): async for _ in oauth.async_auth_flow(request): pass def test_scopes_forwarded_as_list(self): with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) oauth = OAuth( client_metadata_url=VALID_CIMD_URL, scopes=["read", "write"], ) oauth._bind(MCP_SERVER_URL) assert oauth.context.client_metadata.scope == "read write" def test_scopes_forwarded_as_string(self): with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) oauth = OAuth( client_metadata_url=VALID_CIMD_URL, scopes="read write", ) oauth._bind(MCP_SERVER_URL) assert oauth.context.client_metadata.scope == "read write" class TestOAuthBindFromTransport: """Tests that transports call _bind() on OAuth instances.""" def test_http_transport_binds_oauth(self): oauth = OAuth(client_metadata_url=VALID_CIMD_URL) assert oauth._bound is False with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) StreamableHttpTransport(MCP_SERVER_URL, auth=oauth) assert oauth._bound is True assert oauth.mcp_url == MCP_SERVER_URL def test_sse_transport_binds_oauth(self): oauth = OAuth(client_metadata_url=VALID_CIMD_URL) assert oauth._bound is False with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) SSETransport(MCP_SERVER_URL, auth=oauth) assert oauth._bound is True assert oauth.mcp_url == MCP_SERVER_URL def test_http_transport_oauth_string_still_works(self): """auth="oauth" should still create a new OAuth instance.""" with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) transport = StreamableHttpTransport(MCP_SERVER_URL, auth="oauth") assert isinstance(transport.auth, OAuth) assert transport.auth._bound is True
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/client/auth/test_oauth_cimd.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/client/auth/test_oauth_static_client.py
"""Tests for OAuth static client registration (pre-registered client_id/client_secret).""" from unittest.mock import patch import httpx import pytest from mcp.shared.auth import OAuthClientInformationFull from pydantic import AnyUrl from fastmcp.client import Client from fastmcp.client.auth import OAuth from fastmcp.client.auth.oauth import ClientNotFoundError from fastmcp.client.transports import StreamableHttpTransport from fastmcp.server.auth.auth import ClientRegistrationOptions from fastmcp.server.auth.providers.in_memory import InMemoryOAuthProvider from fastmcp.server.server import FastMCP from fastmcp.utilities.http import find_available_port from fastmcp.utilities.tests import HeadlessOAuth, run_server_async class TestStaticClientInfoConstruction: """Static client info should include full metadata from client_metadata.""" def test_static_client_info_includes_metadata(self): """Static client info should include redirect_uris, grant_types, etc.""" oauth = OAuth( mcp_url="https://example.com/mcp", client_id="my-client-id", client_secret="my-secret", scopes=["read", "write"], ) info = oauth._static_client_info assert info is not None assert info.client_id == "my-client-id" assert info.client_secret == "my-secret" # Metadata fields should be populated from client_metadata assert info.redirect_uris is not None assert len(info.redirect_uris) == 1 assert info.grant_types is not None assert "authorization_code" in info.grant_types assert "refresh_token" in info.grant_types assert info.response_types is not None assert "code" in info.response_types assert info.scope == "read write" assert info.token_endpoint_auth_method == "client_secret_post" def test_static_client_info_without_secret(self): """Public clients can provide client_id without client_secret.""" oauth = OAuth( mcp_url="https://example.com/mcp", client_id="public-client", ) info = oauth._static_client_info assert info is not None assert info.client_id == "public-client" assert info.client_secret is None assert info.token_endpoint_auth_method == "none" # Metadata should still be present assert info.redirect_uris is not None assert info.grant_types is not None def test_no_static_client_info_without_client_id(self): """When no client_id is provided, _static_client_info should be None.""" oauth = OAuth(mcp_url="https://example.com/mcp") assert oauth._static_client_info is None def test_static_client_info_includes_additional_metadata(self): """Additional client metadata should be included in static client info.""" oauth = OAuth( mcp_url="https://example.com/mcp", client_id="my-client", additional_client_metadata={ "token_endpoint_auth_method": "client_secret_post" }, ) info = oauth._static_client_info assert info is not None assert info.token_endpoint_auth_method == "client_secret_post" class TestStaticClientInitialize: """_initialize should set context.client_info and persist to storage.""" async def test_initialize_sets_context_client_info(self): """_initialize should inject static client info into the auth context.""" oauth = OAuth( mcp_url="https://example.com/mcp", client_id="my-client", client_secret="my-secret", ) # Mock the parent _initialize since it needs a real server with patch.object(OAuth.__bases__[0], "_initialize", return_value=None): await oauth._initialize() assert oauth.context.client_info is not None assert oauth.context.client_info.client_id == "my-client" assert oauth.context.client_info.client_secret == "my-secret" async def test_initialize_persists_static_client_to_storage(self): """Static client info should be persisted to token storage.""" oauth = OAuth( mcp_url="https://example.com/mcp", client_id="my-client", client_secret="my-secret", ) with patch.object(OAuth.__bases__[0], "_initialize", return_value=None): await oauth._initialize() # Verify it was persisted to storage stored = await oauth.token_storage_adapter.get_client_info() assert stored is not None assert stored.client_id == "my-client" async def test_initialize_without_static_creds_works(self): """_initialize should not error when no static credentials are provided.""" oauth = OAuth(mcp_url="https://example.com/mcp") with patch.object(OAuth.__bases__[0], "_initialize", return_value=None): # This should not raise AttributeError await oauth._initialize() # context.client_info should be whatever the parent set (None by default) class TestStaticClientRetryBehavior: """Retry-on-stale-credentials should short-circuit for static creds.""" async def test_retry_skipped_with_static_creds(self): """When static creds are rejected, should raise immediately, not retry.""" oauth = OAuth( mcp_url="https://example.com/mcp", client_id="bad-client-id", client_secret="bad-secret", ) # Make the parent auth flow raise ClientNotFoundError async def failing_auth_flow(request): raise ClientNotFoundError("client not found") yield # make it a generator # noqa: E275 with patch.object( OAuth.__bases__[0], "async_auth_flow", side_effect=failing_auth_flow ): flow = oauth.async_auth_flow(httpx.Request("GET", "https://example.com")) with pytest.raises(ClientNotFoundError, match="static client credentials"): await flow.__anext__() async def test_retry_still_works_without_static_creds(self): """Without static creds, the retry behavior should be preserved.""" oauth = OAuth(mcp_url="https://example.com/mcp") call_count = 0 async def auth_flow_with_retry(request): nonlocal call_count call_count += 1 if call_count == 1: raise ClientNotFoundError("client not found") # Second attempt succeeds yield httpx.Request("GET", "https://example.com") with patch.object( OAuth.__bases__[0], "async_auth_flow", side_effect=auth_flow_with_retry ): flow = oauth.async_auth_flow(httpx.Request("GET", "https://example.com")) request = await flow.__anext__() assert request is not None assert call_count == 2 class TestStaticClientE2E: """End-to-end tests with a real OAuth server using pre-registered clients.""" async def test_static_client_with_dcr_disabled(self): """Static client_id should work when the server has DCR disabled.""" port = find_available_port() callback_port = find_available_port() issuer_url = f"http://127.0.0.1:{port}" provider = InMemoryOAuthProvider( base_url=issuer_url, client_registration_options=ClientRegistrationOptions( enabled=False, # DCR disabled valid_scopes=["read", "write"], ), ) server = FastMCP("TestServer", auth=provider) @server.tool def greet(name: str) -> str: return f"Hello, {name}!" # Pre-register a client directly in the provider. # The redirect_uri must match what the OAuth client will use. pre_registered = OAuthClientInformationFull( client_id="pre-registered-client", client_secret="pre-registered-secret", redirect_uris=[AnyUrl(f"http://localhost:{callback_port}/callback")], grant_types=["authorization_code", "refresh_token"], response_types=["code"], token_endpoint_auth_method="client_secret_post", scope="read write", ) await provider.register_client(pre_registered) async with run_server_async(server, port=port, transport="http") as url: oauth = HeadlessOAuth( mcp_url=url, client_id="pre-registered-client", client_secret="pre-registered-secret", scopes=["read", "write"], callback_port=callback_port, ) async with Client( transport=StreamableHttpTransport(url), auth=oauth, ) as client: assert await client.ping() tools = await client.list_tools() assert any(t.name == "greet" for t in tools) async def test_static_client_with_dcr_enabled(self): """Static client_id should also work when DCR is enabled (skips DCR).""" port = find_available_port() callback_port = find_available_port() issuer_url = f"http://127.0.0.1:{port}" provider = InMemoryOAuthProvider( base_url=issuer_url, client_registration_options=ClientRegistrationOptions( enabled=True, valid_scopes=["read"], ), ) server = FastMCP("TestServer", auth=provider) @server.tool def add(a: int, b: int) -> int: return a + b pre_registered = OAuthClientInformationFull( client_id="my-app", client_secret="my-secret", redirect_uris=[AnyUrl(f"http://localhost:{callback_port}/callback")], grant_types=["authorization_code", "refresh_token"], response_types=["code"], token_endpoint_auth_method="client_secret_post", scope="read", ) await provider.register_client(pre_registered) async with run_server_async(server, port=port, transport="http") as url: oauth = HeadlessOAuth( mcp_url=url, client_id="my-app", client_secret="my-secret", scopes=["read"], callback_port=callback_port, ) async with Client( transport=StreamableHttpTransport(url), auth=oauth, ) as client: result = await client.call_tool("add", {"a": 3, "b": 4}) assert result.data == 7
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/client/auth/test_oauth_static_client.py", "license": "Apache License 2.0", "lines": 226, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/server/auth/test_cimd.py
"""Unit tests for CIMD (Client ID Metadata Document) functionality.""" from __future__ import annotations import time from unittest.mock import patch import pytest from pydantic import AnyHttpUrl, ValidationError from fastmcp.server.auth.cimd import ( CIMDDocument, CIMDFetcher, CIMDFetchError, CIMDValidationError, ) # Standard public IP used for DNS mocking in tests TEST_PUBLIC_IP = "93.184.216.34" class TestCIMDDocument: """Tests for CIMDDocument model validation.""" def test_valid_minimal_document(self): """Test that minimal valid document passes validation.""" doc = CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), redirect_uris=["http://localhost:3000/callback"], ) assert str(doc.client_id) == "https://example.com/client.json" assert doc.token_endpoint_auth_method == "none" assert doc.grant_types == ["authorization_code"] assert doc.response_types == ["code"] def test_valid_full_document(self): """Test that full document passes validation.""" doc = CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), client_name="My App", client_uri=AnyHttpUrl("https://example.com"), logo_uri=AnyHttpUrl("https://example.com/logo.png"), redirect_uris=["http://localhost:3000/callback"], token_endpoint_auth_method="none", grant_types=["authorization_code", "refresh_token"], response_types=["code"], scope="read write", ) assert doc.client_name == "My App" assert doc.scope == "read write" def test_private_key_jwt_auth_method_allowed(self): """Test that private_key_jwt is allowed for CIMD.""" doc = CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), redirect_uris=["http://localhost:3000/callback"], token_endpoint_auth_method="private_key_jwt", jwks_uri=AnyHttpUrl("https://example.com/.well-known/jwks.json"), ) assert doc.token_endpoint_auth_method == "private_key_jwt" def test_client_secret_basic_rejected(self): """Test that client_secret_basic is rejected for CIMD.""" with pytest.raises(ValidationError) as exc_info: CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), redirect_uris=["http://localhost:3000/callback"], token_endpoint_auth_method="client_secret_basic", # type: ignore[arg-type] - testing invalid value ) # Literal type rejects invalid values before custom validator assert "token_endpoint_auth_method" in str(exc_info.value) def test_client_secret_post_rejected(self): """Test that client_secret_post is rejected for CIMD.""" with pytest.raises(ValidationError) as exc_info: CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), redirect_uris=["http://localhost:3000/callback"], token_endpoint_auth_method="client_secret_post", # type: ignore[arg-type] - testing invalid value ) assert "token_endpoint_auth_method" in str(exc_info.value) def test_client_secret_jwt_rejected(self): """Test that client_secret_jwt is rejected for CIMD.""" with pytest.raises(ValidationError) as exc_info: CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), redirect_uris=["http://localhost:3000/callback"], token_endpoint_auth_method="client_secret_jwt", # type: ignore[arg-type] - testing invalid value ) assert "token_endpoint_auth_method" in str(exc_info.value) def test_missing_redirect_uris_rejected(self): """Test that redirect_uris is required for CIMD.""" with pytest.raises(ValidationError) as exc_info: CIMDDocument(client_id=AnyHttpUrl("https://example.com/client.json")) assert "redirect_uris" in str(exc_info.value) def test_empty_redirect_uris_rejected(self): """Test that empty redirect_uris is rejected.""" with pytest.raises(ValidationError) as exc_info: CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), redirect_uris=[], ) assert "redirect_uris" in str(exc_info.value) def test_redirect_uri_without_scheme_rejected(self): """Test that redirect_uris without a scheme are rejected.""" with pytest.raises(ValidationError, match="must have a scheme"): CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), redirect_uris=["/just/a/path"], ) def test_redirect_uri_without_host_rejected(self): """Test that redirect_uris without a host are rejected.""" with pytest.raises(ValidationError, match="must have a host"): CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), redirect_uris=["http://"], ) def test_redirect_uri_whitespace_only_rejected(self): """Test that whitespace-only redirect_uris are rejected.""" with pytest.raises(ValidationError, match="non-empty"): CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), redirect_uris=[" "], ) class TestCIMDFetcher: """Tests for CIMDFetcher.""" @pytest.fixture def fetcher(self): """Create a CIMDFetcher for testing.""" return CIMDFetcher() def test_is_cimd_client_id_valid_urls(self, fetcher: CIMDFetcher): """Test is_cimd_client_id accepts valid CIMD URLs.""" assert fetcher.is_cimd_client_id("https://example.com/client.json") assert fetcher.is_cimd_client_id("https://example.com/path/to/client") assert fetcher.is_cimd_client_id("https://sub.example.com/cimd.json") def test_is_cimd_client_id_rejects_http(self, fetcher: CIMDFetcher): """Test is_cimd_client_id rejects HTTP URLs.""" assert not fetcher.is_cimd_client_id("http://example.com/client.json") def test_is_cimd_client_id_rejects_root_path(self, fetcher: CIMDFetcher): """Test is_cimd_client_id rejects URLs with no path.""" assert not fetcher.is_cimd_client_id("https://example.com/") assert not fetcher.is_cimd_client_id("https://example.com") def test_is_cimd_client_id_rejects_non_url(self, fetcher: CIMDFetcher): """Test is_cimd_client_id rejects non-URL strings.""" assert not fetcher.is_cimd_client_id("client-123") assert not fetcher.is_cimd_client_id("my-client") assert not fetcher.is_cimd_client_id("") assert not fetcher.is_cimd_client_id("not a url") def test_validate_redirect_uri_exact_match(self, fetcher: CIMDFetcher): """Test redirect_uri validation with exact match.""" doc = CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), redirect_uris=["http://localhost:3000/callback"], ) assert fetcher.validate_redirect_uri(doc, "http://localhost:3000/callback") assert not fetcher.validate_redirect_uri(doc, "http://localhost:4000/callback") def test_validate_redirect_uri_wildcard_match(self, fetcher: CIMDFetcher): """Test redirect_uri validation with wildcard port.""" doc = CIMDDocument( client_id=AnyHttpUrl("https://example.com/client.json"), redirect_uris=["http://localhost:*/callback"], ) assert fetcher.validate_redirect_uri(doc, "http://localhost:3000/callback") assert fetcher.validate_redirect_uri(doc, "http://localhost:8080/callback") assert not fetcher.validate_redirect_uri(doc, "http://localhost:3000/other") class TestCIMDFetcherHTTP: """Tests for CIMDFetcher HTTP fetching (using httpx mock). Note: With SSRF protection and DNS pinning, HTTP requests go to the resolved IP instead of the hostname. These tests mock DNS resolution to return a public IP and configure httpx_mock to expect the IP-based URL. """ @pytest.fixture def fetcher(self): """Create a CIMDFetcher for testing.""" return CIMDFetcher() @pytest.fixture def mock_dns(self): """Mock DNS resolution to return test public IP.""" with patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=[TEST_PUBLIC_IP], ): yield async def test_fetch_success(self, fetcher: CIMDFetcher, httpx_mock, mock_dns): """Test successful CIMD document fetch.""" url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "Test App", "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "none", } # With DNS pinning, request goes to IP. Match any URL. httpx_mock.add_response( json=doc_data, headers={ "content-type": "application/json", "content-length": "200", }, ) doc = await fetcher.fetch(url) assert str(doc.client_id) == url assert doc.client_name == "Test App" async def test_fetch_ttl_cache(self, fetcher: CIMDFetcher, httpx_mock, mock_dns): """Test that fetched documents are cached and served from cache within TTL.""" url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "Test App", "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "none", } httpx_mock.add_response( json=doc_data, headers={"content-length": "200"}, ) first = await fetcher.fetch(url) second = await fetcher.fetch(url) assert first.client_id == second.client_id assert len(httpx_mock.get_requests()) == 1 async def test_fetch_cache_control_max_age( self, fetcher: CIMDFetcher, httpx_mock, mock_dns ): """Cache-Control max-age should prevent refetch before expiry.""" url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "Max-Age App", "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "none", } httpx_mock.add_response( json=doc_data, headers={"cache-control": "max-age=60", "content-length": "200"}, ) first = await fetcher.fetch(url) second = await fetcher.fetch(url) assert first.client_name == second.client_name assert len(httpx_mock.get_requests()) == 1 async def test_fetch_etag_revalidation_304( self, fetcher: CIMDFetcher, httpx_mock, mock_dns ): """Expired cache should revalidate with ETag and accept 304.""" url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "ETag App", "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "none", } httpx_mock.add_response( json=doc_data, headers={ "cache-control": "max-age=0", "etag": '"v1"', "content-length": "200", }, ) httpx_mock.add_response( status_code=304, headers={ "cache-control": "max-age=120", "etag": '"v1"', "content-length": "0", }, ) first = await fetcher.fetch(url) second = await fetcher.fetch(url) requests = httpx_mock.get_requests() assert first.client_name == "ETag App" assert second.client_name == "ETag App" assert len(requests) == 2 assert requests[1].headers.get("if-none-match") == '"v1"' async def test_fetch_last_modified_revalidation_304( self, fetcher: CIMDFetcher, httpx_mock, mock_dns ): """Expired cache should revalidate with Last-Modified and accept 304.""" url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "Last-Modified App", "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "none", } last_modified = "Wed, 21 Oct 2015 07:28:00 GMT" httpx_mock.add_response( json=doc_data, headers={ "cache-control": "max-age=0", "last-modified": last_modified, "content-length": "200", }, ) httpx_mock.add_response( status_code=304, headers={"cache-control": "max-age=120", "content-length": "0"}, ) first = await fetcher.fetch(url) second = await fetcher.fetch(url) requests = httpx_mock.get_requests() assert first.client_name == "Last-Modified App" assert second.client_name == "Last-Modified App" assert len(requests) == 2 assert requests[1].headers.get("if-modified-since") == last_modified async def test_fetch_cache_control_no_store( self, fetcher: CIMDFetcher, httpx_mock, mock_dns ): """Cache-Control no-store should prevent storing CIMD documents.""" url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "No-Store App", "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "none", } httpx_mock.add_response( json=doc_data, headers={"cache-control": "no-store", "content-length": "200"}, ) httpx_mock.add_response( json=doc_data, headers={"cache-control": "no-store", "content-length": "200"}, ) first = await fetcher.fetch(url) second = await fetcher.fetch(url) assert first.client_name == second.client_name assert len(httpx_mock.get_requests()) == 2 async def test_fetch_cache_control_no_cache( self, fetcher: CIMDFetcher, httpx_mock, mock_dns ): """Cache-Control no-cache should force revalidation on each fetch.""" url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "No-Cache App", "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "none", } httpx_mock.add_response( json=doc_data, headers={ "cache-control": "no-cache", "etag": '"v2"', "content-length": "200", }, ) httpx_mock.add_response( status_code=304, headers={ "cache-control": "no-cache", "etag": '"v2"', "content-length": "0", }, ) first = await fetcher.fetch(url) second = await fetcher.fetch(url) requests = httpx_mock.get_requests() assert first.client_name == "No-Cache App" assert second.client_name == "No-Cache App" assert len(requests) == 2 assert requests[1].headers.get("if-none-match") == '"v2"' async def test_fetch_304_without_cache_headers_preserves_policy( self, fetcher: CIMDFetcher, httpx_mock, mock_dns ): """304 responses without cache headers should not reset cached policy.""" url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "No-Header-304 App", "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "none", } httpx_mock.add_response( json=doc_data, headers={ "cache-control": "no-cache", "etag": '"v3"', "content-length": "200", }, ) # Intentionally omit cache-control/expires on 304. httpx_mock.add_response( status_code=304, headers={"content-length": "0"}, ) httpx_mock.add_response( status_code=304, headers={"content-length": "0"}, ) first = await fetcher.fetch(url) second = await fetcher.fetch(url) third = await fetcher.fetch(url) requests = httpx_mock.get_requests() assert first.client_name == "No-Header-304 App" assert second.client_name == "No-Header-304 App" assert third.client_name == "No-Header-304 App" assert len(requests) == 3 assert requests[1].headers.get("if-none-match") == '"v3"' assert requests[2].headers.get("if-none-match") == '"v3"' async def test_fetch_304_without_cache_headers_refreshes_cached_freshness( self, fetcher: CIMDFetcher, httpx_mock, mock_dns ): """A header-less 304 should renew freshness using cached lifetime.""" url = "https://example.com/client.json" doc_data = { "client_id": url, "client_name": "Headerless 304 Freshness App", "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "none", } httpx_mock.add_response( json=doc_data, headers={ "cache-control": "max-age=60", "etag": '"v4"', "content-length": "200", }, ) httpx_mock.add_response( status_code=304, headers={"content-length": "0"}, ) first = await fetcher.fetch(url) # Simulate cache expiry so the next request triggers revalidation. cached_entry = fetcher._cache[url] cached_entry.expires_at = time.time() - 1 second = await fetcher.fetch(url) third = await fetcher.fetch(url) requests = httpx_mock.get_requests() assert first.client_name == "Headerless 304 Freshness App" assert second.client_name == "Headerless 304 Freshness App" assert third.client_name == "Headerless 304 Freshness App" assert len(requests) == 2 assert requests[1].headers.get("if-none-match") == '"v4"' async def test_fetch_client_id_mismatch( self, fetcher: CIMDFetcher, httpx_mock, mock_dns ): """Test that client_id mismatch is rejected.""" url = "https://example.com/client.json" doc_data = { "client_id": "https://other.com/client.json", # Different URL "client_name": "Test App", "redirect_uris": ["http://localhost:3000/callback"], } httpx_mock.add_response( json=doc_data, headers={"content-length": "100"}, ) with pytest.raises(CIMDValidationError) as exc_info: await fetcher.fetch(url) assert "mismatch" in str(exc_info.value).lower() async def test_fetch_http_error(self, fetcher: CIMDFetcher, httpx_mock, mock_dns): """Test handling of HTTP errors.""" url = "https://example.com/client.json" httpx_mock.add_response(status_code=404) with pytest.raises(CIMDFetchError) as exc_info: await fetcher.fetch(url) assert "404" in str(exc_info.value) async def test_fetch_invalid_json(self, fetcher: CIMDFetcher, httpx_mock, mock_dns): """Test handling of invalid JSON response.""" url = "https://example.com/client.json" httpx_mock.add_response( content=b"not json", headers={"content-length": "10"}, ) with pytest.raises(CIMDValidationError) as exc_info: await fetcher.fetch(url) assert "JSON" in str(exc_info.value) async def test_fetch_invalid_document( self, fetcher: CIMDFetcher, httpx_mock, mock_dns ): """Test handling of invalid CIMD document.""" url = "https://example.com/client.json" doc_data = { "client_id": url, "redirect_uris": ["http://localhost:3000/callback"], "token_endpoint_auth_method": "client_secret_basic", # Not allowed } httpx_mock.add_response( json=doc_data, headers={"content-length": "100"}, ) with pytest.raises(CIMDValidationError) as exc_info: await fetcher.fetch(url) assert "Invalid CIMD document" in str(exc_info.value)
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/auth/test_cimd.py", "license": "Apache License 2.0", "lines": 473, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/server/auth/test_ssrf_protection.py
"""Tests for SSRF-safe HTTP utilities. This module tests the ssrf.py module which provides SSRF-protected HTTP fetching. """ from unittest.mock import AsyncMock, MagicMock, patch import httpx import pytest from fastmcp.server.auth.ssrf import ( SSRFError, SSRFFetchError, is_ip_allowed, ssrf_safe_fetch, validate_url, ) class TestIsIPAllowed: """Tests for is_ip_allowed function.""" def test_public_ipv4_allowed(self): """Public IPv4 addresses should be allowed.""" assert is_ip_allowed("8.8.8.8") is True assert is_ip_allowed("1.1.1.1") is True assert is_ip_allowed("93.184.216.34") is True def test_private_ipv4_blocked(self): """Private IPv4 addresses should be blocked.""" assert is_ip_allowed("192.168.1.1") is False assert is_ip_allowed("10.0.0.1") is False assert is_ip_allowed("172.16.0.1") is False def test_loopback_blocked(self): """Loopback addresses should be blocked.""" assert is_ip_allowed("127.0.0.1") is False assert is_ip_allowed("::1") is False def test_link_local_blocked(self): """Link-local addresses (AWS metadata) should be blocked.""" assert is_ip_allowed("169.254.169.254") is False def test_rfc6598_cgnat_blocked(self): """RFC6598 Carrier-Grade NAT addresses should be blocked.""" assert is_ip_allowed("100.64.0.1") is False assert is_ip_allowed("100.100.100.100") is False def test_ipv4_mapped_ipv6_blocked_if_private(self): """IPv4-mapped IPv6 addresses should check the embedded IPv4.""" assert is_ip_allowed("::ffff:127.0.0.1") is False assert is_ip_allowed("::ffff:192.168.1.1") is False class TestValidateURL: """Tests for validate_url function.""" async def test_http_rejected(self): """HTTP URLs should be rejected (HTTPS required).""" with pytest.raises(SSRFError, match="must use HTTPS"): await validate_url("http://example.com/path") async def test_missing_host_rejected(self): """URLs without host should be rejected.""" with pytest.raises(SSRFError, match="must have a host"): await validate_url("https:///path") async def test_root_path_rejected_when_required(self): """Root paths should be rejected when require_path=True.""" with patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=["93.184.216.34"], ): with pytest.raises(SSRFError, match="non-root path"): await validate_url("https://example.com/", require_path=True) async def test_private_ip_rejected(self): """URLs resolving to private IPs should be rejected.""" with patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=["192.168.1.1"], ): with pytest.raises(SSRFError, match="blocked IP"): await validate_url("https://example.com/path") class TestSSRFSafeFetch: """Tests for ssrf_safe_fetch function.""" async def test_private_ip_blocked(self): """Fetch to private IP should be blocked.""" with patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=["192.168.1.1"], ): with pytest.raises(SSRFError, match="blocked IP"): await ssrf_safe_fetch("https://internal.example.com/api") async def test_cgnat_blocked(self): """Fetch to RFC6598 CGNAT IP should be blocked.""" with patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=["100.64.0.1"], ): with pytest.raises(SSRFError, match="blocked IP"): await ssrf_safe_fetch("https://cgnat.example.com/api") async def test_connects_to_pinned_ip(self): """Verify connection uses pinned IP, not re-resolved DNS.""" resolved_ip = "93.184.216.34" with ( patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=[resolved_ip], ), patch("httpx.AsyncClient") as mock_client_class, ): mock_stream = MagicMock() mock_stream.status_code = 200 mock_stream.headers = {"content-length": "15"} mock_stream.__aenter__ = AsyncMock(return_value=mock_stream) mock_stream.__aexit__ = AsyncMock(return_value=None) async def aiter_bytes(): yield b'{"data": "test"}' mock_stream.aiter_bytes = aiter_bytes mock_client = AsyncMock() mock_client.stream = MagicMock(return_value=mock_stream) mock_client.__aenter__.return_value = mock_client mock_client.__aexit__ = AsyncMock(return_value=None) mock_client_class.return_value = mock_client await ssrf_safe_fetch("https://example.com/api") # Verify URL contains pinned IP call_args = mock_client.stream.call_args url_called = call_args[0][1] assert resolved_ip in url_called async def test_fallback_to_second_ip(self): """If the first IP fails, the next resolved IP should be tried.""" resolved_ips = ["2001:4860:4860::8888", "93.184.216.34"] with ( patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=resolved_ips, ), patch("httpx.AsyncClient") as mock_client_class, ): request = httpx.Request("GET", "https://example.com/api") first_client = AsyncMock() first_client.stream = MagicMock( side_effect=httpx.RequestError("boom", request=request) ) first_client.__aenter__.return_value = first_client first_client.__aexit__ = AsyncMock(return_value=None) mock_stream = MagicMock() mock_stream.status_code = 200 mock_stream.headers = {"content-length": "2"} mock_stream.__aenter__ = AsyncMock(return_value=mock_stream) mock_stream.__aexit__ = AsyncMock(return_value=None) async def aiter_bytes(): yield b"ok" mock_stream.aiter_bytes = aiter_bytes second_client = AsyncMock() second_client.stream = MagicMock(return_value=mock_stream) second_client.__aenter__.return_value = second_client second_client.__aexit__ = AsyncMock(return_value=None) mock_client_class.side_effect = [first_client, second_client] content = await ssrf_safe_fetch("https://example.com/api") assert content == b"ok" call_args = second_client.stream.call_args url_called = call_args[0][1] assert resolved_ips[1] in url_called async def test_host_header_set(self): """Verify Host header is set to original hostname.""" resolved_ip = "93.184.216.34" original_host = "example.com" with ( patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=[resolved_ip], ), patch("httpx.AsyncClient") as mock_client_class, ): mock_stream = MagicMock() mock_stream.status_code = 200 mock_stream.headers = {"content-length": "15"} mock_stream.__aenter__ = AsyncMock(return_value=mock_stream) mock_stream.__aexit__ = AsyncMock(return_value=None) async def aiter_bytes(): yield b'{"data": "test"}' mock_stream.aiter_bytes = aiter_bytes mock_client = AsyncMock() mock_client.stream = MagicMock(return_value=mock_stream) mock_client.__aenter__.return_value = mock_client mock_client.__aexit__ = AsyncMock(return_value=None) mock_client_class.return_value = mock_client await ssrf_safe_fetch(f"https://{original_host}/api") # Verify Host header call_kwargs = mock_client.stream.call_args[1] assert call_kwargs["headers"]["Host"] == original_host async def test_response_size_limit(self): """Verify response size limit is enforced via streaming.""" with ( patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=["93.184.216.34"], ), patch("httpx.AsyncClient") as mock_client_class, ): # Response larger than default 5KB (no Content-Length, so streaming enforces) mock_stream = MagicMock() mock_stream.status_code = 200 mock_stream.headers = {} # No Content-Length to force streaming check mock_stream.__aenter__ = AsyncMock(return_value=mock_stream) mock_stream.__aexit__ = AsyncMock(return_value=None) async def aiter_bytes(): # Yield 10KB total for _ in range(10): yield b"x" * 1024 mock_stream.aiter_bytes = aiter_bytes mock_client = AsyncMock() mock_client.stream = MagicMock(return_value=mock_stream) mock_client.__aenter__.return_value = mock_client mock_client.__aexit__ = AsyncMock(return_value=None) mock_client_class.return_value = mock_client with pytest.raises(SSRFFetchError, match="too large"): await ssrf_safe_fetch("https://example.com/api") class TestJWKSSSRFProtection: """Tests for SSRF protection in JWTVerifier JWKS fetching.""" async def test_jwks_private_ip_blocked(self): """JWKS fetch to private IP should be blocked.""" from fastmcp.server.auth.providers.jwt import JWTVerifier verifier = JWTVerifier( jwks_uri="https://internal.example.com/.well-known/jwks.json", issuer="https://issuer.example.com", ssrf_safe=True, ) with patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=["192.168.1.1"], ): with pytest.raises(ValueError, match="Failed to fetch JWKS"): # Create a dummy token to trigger JWKS fetch await verifier._get_jwks_key("test-kid") async def test_jwks_cgnat_blocked(self): """JWKS fetch to RFC6598 CGNAT IP should be blocked.""" from fastmcp.server.auth.providers.jwt import JWTVerifier verifier = JWTVerifier( jwks_uri="https://cgnat.example.com/.well-known/jwks.json", issuer="https://issuer.example.com", ssrf_safe=True, ) with patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=["100.64.0.1"], ): with pytest.raises(ValueError, match="Failed to fetch JWKS"): await verifier._get_jwks_key("test-kid") async def test_jwks_loopback_blocked(self): """JWKS fetch to loopback should be blocked.""" from fastmcp.server.auth.providers.jwt import JWTVerifier verifier = JWTVerifier( jwks_uri="https://localhost/.well-known/jwks.json", issuer="https://issuer.example.com", ssrf_safe=True, ) with patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=["127.0.0.1"], ): with pytest.raises(ValueError, match="Failed to fetch JWKS"): await verifier._get_jwks_key("test-kid") class TestIPv6URLFormatting: """Tests for proper IPv6 address bracketing in URLs.""" def test_format_ip_for_url_ipv4(self): """IPv4 addresses should not be bracketed.""" from fastmcp.server.auth.ssrf import format_ip_for_url assert format_ip_for_url("8.8.8.8") == "8.8.8.8" assert format_ip_for_url("192.168.1.1") == "192.168.1.1" def test_format_ip_for_url_ipv6(self): """IPv6 addresses should be bracketed for URL use.""" from fastmcp.server.auth.ssrf import format_ip_for_url assert format_ip_for_url("2001:db8::1") == "[2001:db8::1]" assert format_ip_for_url("::1") == "[::1]" assert format_ip_for_url("fe80::1") == "[fe80::1]" def test_format_ip_for_url_invalid(self): """Invalid IP strings should be returned unchanged.""" from fastmcp.server.auth.ssrf import format_ip_for_url assert format_ip_for_url("not-an-ip") == "not-an-ip" assert format_ip_for_url("") == "" async def test_ipv6_pinned_url_is_valid(self): """Verify IPv6 addresses are properly bracketed in pinned URLs.""" resolved_ipv6 = "2001:4860:4860::8888" with ( patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=[resolved_ipv6], ), patch("httpx.AsyncClient") as mock_client_class, ): mock_stream = MagicMock() mock_stream.status_code = 200 mock_stream.headers = {"content-length": "10"} mock_stream.__aenter__ = AsyncMock(return_value=mock_stream) mock_stream.__aexit__ = AsyncMock(return_value=None) async def aiter_bytes(): yield b'{"key": 1}' mock_stream.aiter_bytes = aiter_bytes mock_client = AsyncMock() mock_client.stream = MagicMock(return_value=mock_stream) mock_client.__aenter__.return_value = mock_client mock_client.__aexit__ = AsyncMock(return_value=None) mock_client_class.return_value = mock_client await ssrf_safe_fetch("https://example.com/api") # Verify the URL contains bracketed IPv6 address call_args = mock_client.stream.call_args url_called = call_args[0][1] # IPv6 should be bracketed: https://[2001:4860:4860::8888]:443/path assert f"[{resolved_ipv6}]" in url_called, ( f"Expected bracketed IPv6 [{resolved_ipv6}] in URL, got {url_called}" ) class TestStreamingResponseSizeLimit: """Tests for streaming-based response size enforcement.""" async def test_size_limit_enforced_during_streaming(self): """Verify that size limit is enforced as chunks are received, not after.""" with ( patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=["93.184.216.34"], ), patch("httpx.AsyncClient") as mock_client_class, ): chunks_yielded = [] async def aiter_bytes(): # Yield chunks that exceed the limit for i in range(10): chunk = b"x" * 1024 # 1KB per chunk chunks_yielded.append(chunk) yield chunk mock_stream = MagicMock() mock_stream.status_code = 200 mock_stream.headers = {} # No content-length to force streaming check mock_stream.__aenter__ = AsyncMock(return_value=mock_stream) mock_stream.__aexit__ = AsyncMock(return_value=None) mock_stream.aiter_bytes = aiter_bytes mock_client = AsyncMock() mock_client.stream = MagicMock(return_value=mock_stream) mock_client.__aenter__.return_value = mock_client mock_client.__aexit__ = AsyncMock(return_value=None) mock_client_class.return_value = mock_client with pytest.raises(SSRFFetchError, match="too large"): await ssrf_safe_fetch("https://example.com/api", max_size=5120) # Verify we stopped after exceeding the limit (should be ~6 chunks for 5KB limit) # This confirms we're enforcing during streaming, not after downloading all assert len(chunks_yielded) <= 7, ( f"Downloaded {len(chunks_yielded)} chunks (expected <=7 for streaming enforcement)" ) async def test_content_length_header_checked_first(self): """Verify Content-Length header is checked before streaming.""" with ( patch( "fastmcp.server.auth.ssrf.resolve_hostname", return_value=["93.184.216.34"], ), patch("httpx.AsyncClient") as mock_client_class, ): mock_stream = MagicMock() mock_stream.status_code = 200 mock_stream.headers = {"content-length": "10240"} # 10KB mock_stream.__aenter__ = AsyncMock(return_value=mock_stream) mock_stream.__aexit__ = AsyncMock(return_value=None) # aiter_bytes should never be called if Content-Length is checked mock_stream.aiter_bytes = MagicMock( side_effect=AssertionError("Should not stream") ) mock_client = AsyncMock() mock_client.stream = MagicMock(return_value=mock_stream) mock_client.__aenter__.return_value = mock_client mock_client.__aexit__ = AsyncMock(return_value=None) mock_client_class.return_value = mock_client with pytest.raises(SSRFFetchError, match="too large"): await ssrf_safe_fetch("https://example.com/api", max_size=5120)
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/auth/test_ssrf_protection.py", "license": "Apache License 2.0", "lines": 357, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/server/middleware/test_dereference.py
"""Tests for DereferenceRefsMiddleware.""" from enum import Enum import pydantic from fastmcp import Client, FastMCP class Color(Enum): RED = "red" GREEN = "green" BLUE = "blue" class PaintRequest(pydantic.BaseModel): color: Color opacity: float = 1.0 class TestDereferenceRefsMiddleware: """End-to-end tests for the dereference_schemas server kwarg.""" async def test_dereference_schemas_true_inlines_refs(self): """With dereference_schemas=True (default), tool schemas have $ref inlined.""" mcp = FastMCP("test", dereference_schemas=True) @mcp.tool def paint(request: PaintRequest) -> str: return "ok" async with Client(mcp) as client: tools = await client.list_tools() schema = tools[0].inputSchema # $defs should be removed — everything inlined assert "$defs" not in schema # The Color enum should be inlined into the request property assert "$ref" not in str(schema) async def test_dereference_schemas_false_preserves_refs(self): """With dereference_schemas=False, $ref and $defs are preserved.""" mcp = FastMCP("test", dereference_schemas=False) @mcp.tool def paint(request: PaintRequest) -> str: return "ok" async with Client(mcp) as client: tools = await client.list_tools() schema = tools[0].inputSchema # $defs should still be present assert "$defs" in schema async def test_default_is_true(self): """Default behavior dereferences $ref.""" mcp = FastMCP("test") @mcp.tool def paint(request: PaintRequest) -> str: return "ok" async with Client(mcp) as client: tools = await client.list_tools() schema = tools[0].inputSchema assert "$defs" not in schema async def test_does_not_mutate_original_tool(self): """Middleware should not mutate the shared Tool object.""" mcp = FastMCP("test", dereference_schemas=True) @mcp.tool def paint(request: PaintRequest) -> str: return "ok" # Get the original tool's parameters before middleware runs original_tools = await mcp._local_provider._list_tools() assert "$defs" in original_tools[0].parameters # List tools through the client (triggers middleware) async with Client(mcp) as client: await client.list_tools() # The original tool stored in the server should still have $defs tools_after = await mcp._local_provider._list_tools() assert "$defs" in tools_after[0].parameters async def test_output_schema_dereferenced(self): """Middleware also dereferences output_schema when present.""" mcp = FastMCP("test", dereference_schemas=True) @mcp.tool def paint(request: PaintRequest) -> PaintRequest: return request async with Client(mcp) as client: tools = await client.list_tools() tool = tools[0] # Both input and output schemas should be dereferenced assert "$defs" not in tool.inputSchema if tool.outputSchema is not None: assert "$defs" not in tool.outputSchema async def test_resource_templates_dereferenced(self): """Middleware dereferences resource template schemas.""" mcp = FastMCP("test", dereference_schemas=True) @mcp.resource("paint://{color}") def get_paint(color: Color) -> str: return f"paint: {color}" async with Client(mcp) as client: templates = await client.list_resource_templates() # Resource templates also get their schemas dereferenced # (only if the template parameters have $ref) assert len(templates) == 1 async def test_no_ref_schemas_unchanged(self): """Tools without $ref should pass through unmodified.""" mcp = FastMCP("test", dereference_schemas=True) @mcp.tool def add(a: int, b: int) -> int: return a + b async with Client(mcp) as client: tools = await client.list_tools() schema = tools[0].inputSchema # Simple schema should not have $defs regardless assert "$defs" not in schema assert schema["properties"]["a"]["type"] == "integer"
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/middleware/test_dereference.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/server/middleware/test_response_limiting.py
"""Tests for ResponseLimitingMiddleware.""" import pytest from mcp.types import ImageContent, TextContent from fastmcp import Client, FastMCP from fastmcp.server.middleware.response_limiting import ResponseLimitingMiddleware from fastmcp.tools.tool import ToolResult class TestResponseLimitingMiddleware: """Tests for ResponseLimitingMiddleware.""" @pytest.fixture def mcp_server(self) -> FastMCP: """Create a basic MCP server for testing.""" return FastMCP("test-server") async def test_response_under_limit_passes_unchanged(self, mcp_server: FastMCP): """Test that responses under the limit pass through unchanged.""" mcp_server.add_middleware(ResponseLimitingMiddleware(max_size=1_000_000)) @mcp_server.tool() def small_tool() -> ToolResult: return ToolResult(content=[TextContent(type="text", text="hello world")]) async with Client(mcp_server) as client: result = await client.call_tool("small_tool", {}) assert len(result.content) == 1 assert result.content[0].text == "hello world" async def test_response_over_limit_is_truncated(self, mcp_server: FastMCP): """Test that responses over the limit are truncated.""" mcp_server.add_middleware(ResponseLimitingMiddleware(max_size=500)) @mcp_server.tool() def large_tool() -> ToolResult: return ToolResult(content=[TextContent(type="text", text="x" * 10_000)]) async with Client(mcp_server) as client: result = await client.call_tool("large_tool", {}) assert len(result.content) == 1 assert "[Response truncated due to size limit]" in result.content[0].text # Verify truncated result fits within limit assert len(result.content[0].text.encode("utf-8")) < 500 async def test_tool_filtering(self, mcp_server: FastMCP): """Test that tool filtering only applies to specified tools.""" mcp_server.add_middleware( ResponseLimitingMiddleware(max_size=100, tools=["limited_tool"]) ) @mcp_server.tool() def limited_tool() -> ToolResult: return ToolResult(content=[TextContent(type="text", text="x" * 10_000)]) @mcp_server.tool() def unlimited_tool() -> ToolResult: return ToolResult(content=[TextContent(type="text", text="y" * 10_000)]) async with Client(mcp_server) as client: # Limited tool should be truncated result = await client.call_tool("limited_tool", {}) assert "[Response truncated" in result.content[0].text # Unlimited tool should pass through result = await client.call_tool("unlimited_tool", {}) assert "y" * 100 in result.content[0].text async def test_empty_tools_list_limits_nothing(self, mcp_server: FastMCP): """Test that empty tools list means no tools are limited.""" mcp_server.add_middleware(ResponseLimitingMiddleware(max_size=100, tools=[])) @mcp_server.tool() def any_tool() -> ToolResult: return ToolResult(content=[TextContent(type="text", text="x" * 10_000)]) async with Client(mcp_server) as client: result = await client.call_tool("any_tool", {}) # Should NOT be truncated assert "[Response truncated" not in result.content[0].text async def test_custom_truncation_suffix(self, mcp_server: FastMCP): """Test that custom truncation suffix is applied.""" mcp_server.add_middleware( ResponseLimitingMiddleware(max_size=200, truncation_suffix="\n[CUT]") ) @mcp_server.tool() def large_tool() -> ToolResult: return ToolResult(content=[TextContent(type="text", text="x" * 10_000)]) async with Client(mcp_server) as client: result = await client.call_tool("large_tool", {}) assert "[CUT]" in result.content[0].text async def test_multiple_text_blocks_combined(self, mcp_server: FastMCP): """Test that multiple text blocks are combined when truncating.""" mcp_server.add_middleware(ResponseLimitingMiddleware(max_size=300)) @mcp_server.tool() def multi_block() -> ToolResult: return ToolResult( content=[ TextContent(type="text", text="First: " + "a" * 500), TextContent(type="text", text="Second: " + "b" * 500), ] ) async with Client(mcp_server) as client: result = await client.call_tool("multi_block", {}) # Both blocks should be joined and truncated assert len(result.content) == 1 assert "[Response truncated" in result.content[0].text async def test_binary_only_content_serialized(self, mcp_server: FastMCP): """Test that binary-only responses fall back to serialized content.""" mcp_server.add_middleware(ResponseLimitingMiddleware(max_size=200)) @mcp_server.tool() def binary_tool() -> ToolResult: return ToolResult( content=[ ImageContent(type="image", data="x" * 10_000, mimeType="image/png") ] ) async with Client(mcp_server) as client: result = await client.call_tool("binary_tool", {}) # Should be truncated (using serialized fallback) assert len(result.content) == 1 assert "[Response truncated" in result.content[0].text async def test_default_max_size_is_1mb(self): """Test that the default max size is 1MB.""" middleware = ResponseLimitingMiddleware() assert middleware.max_size == 1_000_000 def test_invalid_max_size_raises(self): """Test that zero or negative max_size raises ValueError.""" with pytest.raises(ValueError, match="max_size must be positive"): ResponseLimitingMiddleware(max_size=0) with pytest.raises(ValueError, match="max_size must be positive"): ResponseLimitingMiddleware(max_size=-100) def test_utf8_truncation_preserves_characters(self): """Test that UTF-8 truncation doesn't break multi-byte characters.""" middleware = ResponseLimitingMiddleware(max_size=100) # Text with multi-byte characters (emoji) text = "Hello 🌍 World 🎉 Test " * 100 result = middleware._truncate_to_result(text) # Should not raise and should be valid UTF-8 content = result.content[0] assert isinstance(content, TextContent) content.text.encode("utf-8")
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/middleware/test_response_limiting.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/server/tasks/test_context_background_task.py
"""Tests for Context background task support (SEP-1686). Tests Context API surface (unit) and background task elicitation (integration). Integration tests use Client(mcp) with the real memory:// Docket backend — no mocking of Redis, Docket, or session internals. """ import asyncio from typing import cast import pytest from mcp import ServerSession from fastmcp import FastMCP from fastmcp.client import Client from fastmcp.client.elicitation import ElicitResult from fastmcp.dependencies import CurrentDocket from fastmcp.server.auth import AccessToken from fastmcp.server.context import Context from fastmcp.server.dependencies import get_access_token from fastmcp.server.elicitation import AcceptedElicitation, DeclinedElicitation from fastmcp.server.tasks.elicitation import handle_task_input # ============================================================================= # Unit tests: Context API surface (no Redis/Docket needed) # ============================================================================= class TestContextBackgroundTaskSupport: """Tests for Context.is_background_task and related functionality.""" def test_context_not_background_task_by_default(self): """Context should not be a background task by default.""" mcp = FastMCP("test") ctx = Context(mcp) assert ctx.is_background_task is False assert ctx.task_id is None def test_context_is_background_task_when_task_id_provided(self): """Context should be a background task when task_id is provided.""" mcp = FastMCP("test") ctx = Context(mcp, task_id="test-task-123") assert ctx.is_background_task is True assert ctx.task_id == "test-task-123" def test_context_task_id_is_readonly(self): """task_id should be a read-only property.""" mcp = FastMCP("test") ctx = Context(mcp, task_id="test-task-123") with pytest.raises(AttributeError): setattr(ctx, "task_id", "new-id") class TestContextSessionProperty: """Tests for Context.session property in different modes.""" def test_session_raises_when_no_session_available(self): """session should raise RuntimeError when no session is available.""" mcp = FastMCP("test") ctx = Context(mcp) # No session, not a background task with pytest.raises(RuntimeError, match="session is not available"): _ = ctx.session def test_session_uses_stored_session_in_background_task(self): """session should use _session in background task mode.""" mcp = FastMCP("test") class MockSession: _fastmcp_state_prefix = "test-session" mock_session = MockSession() ctx = Context( mcp, session=cast(ServerSession, mock_session), task_id="test-task-123" ) assert ctx.session is mock_session def test_session_uses_stored_session_during_on_initialize(self): """session should use _session during on_initialize (no request context).""" mcp = FastMCP("test") class MockSession: _fastmcp_state_prefix = "test-session" mock_session = MockSession() ctx = Context(mcp, session=cast(ServerSession, mock_session)) assert ctx.session is mock_session class TestContextElicitBackgroundTask: """Tests for Context.elicit() in background task mode.""" async def test_elicit_raises_when_background_task_but_no_docket(self): """elicit() should raise when in background task mode but Docket unavailable.""" mcp = FastMCP("test") ctx = Context(mcp, task_id="test-task-123") class MockSession: _fastmcp_state_prefix = "test-session" ctx._session = cast(ServerSession, MockSession()) with pytest.raises(RuntimeError, match="Docket"): await ctx.elicit("Need input", str) class TestElicitFailFast: """Tests for elicit_for_task fail-fast on notification push failure.""" async def test_elicit_returns_cancel_when_notification_push_fails(self): """elicit_for_task should return cancel immediately when push_notification fails. If the client can't receive the input_required notification, waiting for a response that will never come would block for up to 1 hour. Instead, we return cancel immediately (fail-fast). This test patches ONLY push_notification — all other components (Docket, Redis, session) are real via the memory:// backend. """ from unittest.mock import patch from fastmcp.server.elicitation import CancelledElicitation mcp = FastMCP("failfast-test") elicit_started = asyncio.Event() captured: dict[str, object] = {} @mcp.tool(task=True) async def failfast_tool(ctx: Context) -> str: elicit_started.set() result = await ctx.elicit("This notification will fail", str) captured["result_type"] = type(result).__name__ captured["is_cancelled"] = isinstance(result, CancelledElicitation) return "done" # Patch push_notification BEFORE starting client so it's active # when the tool runs in the Docket worker with patch( "fastmcp.server.tasks.notifications.push_notification", side_effect=ConnectionError("Redis queue unavailable"), ): async with Client(mcp) as client: task = await client.call_tool("failfast_tool", {}, task=True) await asyncio.wait_for(elicit_started.wait(), timeout=5.0) await task.wait(timeout=10.0) result = await task.result() assert result.data == "done" # The tool should have received CancelledElicitation (fail-fast) assert captured["is_cancelled"] is True assert captured["result_type"] == "CancelledElicitation" class TestContextDocumentation: """Tests to verify Context documentation and API surface.""" def test_is_background_task_has_docstring(self): """is_background_task property should have documentation.""" assert Context.is_background_task.__doc__ is not None assert "background task" in Context.is_background_task.__doc__.lower() def test_task_id_has_docstring(self): """task_id property should have documentation.""" assert Context.task_id.fget.__doc__ is not None assert "task ID" in Context.task_id.fget.__doc__ def test_session_has_docstring(self): """session property should document background task support.""" assert Context.session.fget.__doc__ is not None assert "background task" in Context.session.fget.__doc__.lower() # ============================================================================= # Integration tests: Client(mcp) + memory:// Docket backend # ============================================================================= class TestBackgroundTaskIntegration: """Integration tests for background task context using real Docket memory backend. These tests use Client(mcp) with the memory:// broker — no mocking. The memory:// backend provides a fully functional in-memory Redis store that Docket uses automatically when running tests. """ async def test_report_progress_in_background_task(self): """report_progress() should complete without error in a background task.""" mcp = FastMCP("progress-test") progress_reported = asyncio.Event() @mcp.tool(task=True) async def progress_tool(ctx: Context) -> str: await ctx.report_progress(0, 100, "Starting...") await ctx.report_progress(50, 100, "Half done") await ctx.report_progress(100, 100, "Complete") progress_reported.set() return "done" async with Client(mcp) as client: task = await client.call_tool("progress_tool", {}, task=True) await asyncio.wait_for(progress_reported.wait(), timeout=5.0) await task.wait(timeout=5.0) result = await task.result() assert result.data == "done" async def test_context_wiring_in_background_task(self): """Context should be properly wired with task_id and session_id.""" mcp = FastMCP("wiring-test") task_completed = asyncio.Event() captured: dict[str, object] = {} @mcp.tool(task=True) async def verify_wiring(ctx: Context) -> str: captured["task_id"] = ctx.task_id captured["session_id"] = ctx.session_id captured["is_background"] = ctx.is_background_task task_completed.set() return "ok" async with Client(mcp) as client: task = await client.call_tool("verify_wiring", {}, task=True) await asyncio.wait_for(task_completed.wait(), timeout=5.0) await task.wait(timeout=5.0) result = await task.result() assert result.data == "ok" assert captured["task_id"] is not None assert captured["session_id"] is not None assert captured["is_background"] is True async def test_origin_request_id_round_trips_through_background_task(self): """E2E: origin_request_id captured at submit time is restored in worker. We validate this by comparing ctx.origin_request_id with the value stored in Docket's Redis for this task. """ mcp = FastMCP("origin-request-id-roundtrip") @mcp.tool(task=True) async def check_origin_request_id(ctx: Context, docket=CurrentDocket()) -> str: assert ctx.is_background_task is True assert ctx.request_context is None assert ctx.task_id is not None origin = ctx.origin_request_id assert origin is not None assert isinstance(origin, str) assert origin != "" key = docket.key( f"fastmcp:task:{ctx.session_id}:{ctx.task_id}:origin_request_id" ) async with docket.redis() as redis: raw = await redis.get(key) assert raw is not None if isinstance(raw, bytes): raw = raw.decode() assert str(raw) == origin return "ok" async with Client(mcp) as client: task = await client.call_tool("check_origin_request_id", {}, task=True) result = await task.result() assert result.data == "ok" async def test_elicit_accept_flow(self): """E2E: tool elicits input, client accepts via elicitation_handler.""" mcp = FastMCP("elicit-accept-test") @mcp.tool(task=True) async def ask_name(ctx: Context) -> str: result = await ctx.elicit("What is your name?", str) if isinstance(result, AcceptedElicitation): return f"Hello, {result.data}!" return "No name provided" async def handler(message, response_type, params, ctx): return ElicitResult(action="accept", content={"value": "Bob"}) async with Client(mcp, elicitation_handler=handler) as client: task = await client.call_tool("ask_name", {}, task=True) await task.wait(timeout=10.0) result = await task.result() assert result.data == "Hello, Bob!" async def test_elicit_decline_flow(self): """E2E: tool elicits input, client declines via elicitation_handler.""" mcp = FastMCP("elicit-decline-test") @mcp.tool(task=True) async def optional_input(ctx: Context) -> str: result = await ctx.elicit("Want to provide a name?", str) if isinstance(result, DeclinedElicitation): return "User declined" if isinstance(result, AcceptedElicitation): return f"Got: {result.data}" return "Cancelled" async def handler(message, response_type, params, ctx): return ElicitResult(action="decline") async with Client(mcp, elicitation_handler=handler) as client: task = await client.call_tool("optional_input", {}, task=True) await task.wait(timeout=10.0) result = await task.result() assert result.data == "User declined" async def test_elicit_with_pydantic_model(self): """E2E: tool elicits structured Pydantic input via elicitation_handler.""" from pydantic import BaseModel class UserInfo(BaseModel): name: str age: int mcp = FastMCP("elicit-pydantic-test") @mcp.tool(task=True) async def get_user_info(ctx: Context) -> str: result = await ctx.elicit("Provide user info", UserInfo) if isinstance(result, AcceptedElicitation): assert isinstance(result.data, UserInfo) return f"{result.data.name} is {result.data.age}" return "No info" async def handler(message, response_type, params, ctx): return ElicitResult(action="accept", content={"name": "Alice", "age": 30}) async with Client(mcp, elicitation_handler=handler) as client: task = await client.call_tool("get_user_info", {}, task=True) await task.wait(timeout=10.0) result = await task.result() assert result.data == "Alice is 30" async def test_handle_task_input_rejects_when_not_waiting(self): """handle_task_input returns False when no task is waiting for input.""" mcp = FastMCP("reject-test") @mcp.tool(task=True) async def simple_tool() -> str: return "done" async with Client(mcp) as client: task = await client.call_tool("simple_tool", {}, task=True) await task.wait(timeout=5.0) # Task already completed — no elicitation waiting success = await handle_task_input( task_id=task.task_id, session_id="nonexistent-session", action="accept", content={"value": "too late"}, fastmcp=mcp, ) assert success is False class TestAccessTokenInBackgroundTasks: """Tests for access token availability in background tasks (#3095). Integration tests use Client(mcp) with the real memory:// Docket backend. The token snapshot/restore round-trip flows through actual Redis (fakeredis). Note: async tests run in isolated asyncio tasks, so ContextVar changes are automatically scoped — no cleanup required. """ async def test_token_round_trips_through_background_task(self): """E2E: token set at submit time is available inside the worker.""" from mcp.server.auth.middleware.auth_context import auth_context_var from mcp.server.auth.middleware.bearer_auth import AuthenticatedUser mcp = FastMCP("token-roundtrip") @mcp.tool(task=True) async def check_token(ctx: Context) -> str: token = get_access_token() if token is None: return "no-token" return f"{token.token}|{token.client_id}" test_token = AccessToken( token="roundtrip-jwt", client_id="test-client", scopes=["read"], claims={"sub": "user-1"}, ) auth_context_var.set(AuthenticatedUser(test_token)) async with Client(mcp) as client: task = await client.call_tool("check_token", {}, task=True) result = await task.result() assert result.data == "roundtrip-jwt|test-client" async def test_no_token_when_unauthenticated(self): """E2E: background task gets no token when nothing was set.""" mcp = FastMCP("no-auth") @mcp.tool(task=True) async def check_token(ctx: Context) -> str: token = get_access_token() return "no-token" if token is None else token.token async with Client(mcp) as client: task = await client.call_tool("check_token", {}, task=True) result = await task.result() assert result.data == "no-token" async def test_expired_token_returns_none(self): """get_access_token() returns None when task token has expired.""" from datetime import datetime, timezone from fastmcp.server.dependencies import _task_access_token expired = AccessToken( token="expired-jwt", client_id="test-client", scopes=["read"], expires_at=int(datetime.now(timezone.utc).timestamp()) - 3600, ) _task_access_token.set(expired) assert get_access_token() is None async def test_valid_token_with_future_expiry(self): """get_access_token() returns token when expiry is in the future.""" from datetime import datetime, timezone from fastmcp.server.dependencies import _task_access_token valid = AccessToken( token="valid-jwt", client_id="test-client", scopes=["read"], expires_at=int(datetime.now(timezone.utc).timestamp()) + 3600, ) _task_access_token.set(valid) result = get_access_token() assert result is not None assert result.token == "valid-jwt" async def test_token_without_expiry_always_valid(self): """get_access_token() returns token when no expires_at is set.""" from fastmcp.server.dependencies import _task_access_token no_expiry = AccessToken( token="eternal-jwt", client_id="test-client", scopes=["read"], ) _task_access_token.set(no_expiry) result = get_access_token() assert result is not None assert result.token == "eternal-jwt" class TestLifespanContextInBackgroundTasks: """Tests for lifespan_context availability in background tasks (#3095).""" def test_lifespan_context_falls_back_to_server_result(self): """lifespan_context reads from server when request_context is None.""" mcp = FastMCP("test") mcp._lifespan_result = {"db": "mock-db-connection", "cache": "mock-cache"} ctx = Context(mcp, task_id="test-task") assert ctx.request_context is None assert ctx.lifespan_context == { "db": "mock-db-connection", "cache": "mock-cache", } def test_lifespan_context_returns_empty_dict_when_no_lifespan(self): """lifespan_context returns {} when no lifespan is configured.""" mcp = FastMCP("test") ctx = Context(mcp, task_id="test-task") assert ctx.request_context is None assert ctx.lifespan_context == {}
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/tasks/test_context_background_task.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/tasks/test_notifications.py
"""Tests for distributed notification queue (SEP-1686). Integration tests verify that the notification queue works end-to-end using Client(mcp) with the real memory:// Docket backend. No mocking of Redis, sessions, or Docket internals. """ import asyncio import mcp.types as mcp_types from fastmcp import FastMCP from fastmcp.client import Client from fastmcp.client.elicitation import ElicitResult from fastmcp.client.messages import MessageHandler from fastmcp.server.context import Context from fastmcp.server.elicitation import AcceptedElicitation from fastmcp.server.tasks.notifications import ( get_subscriber_count, ) class NotificationCaptureHandler(MessageHandler): """Capture server notifications for test assertions.""" def __init__(self) -> None: super().__init__() self.notifications: list[mcp_types.ServerNotification] = [] async def on_notification(self, message: mcp_types.ServerNotification) -> None: self.notifications.append(message) def for_method(self, method: str) -> list[mcp_types.ServerNotification]: return [ notification for notification in self.notifications if notification.root.method == method ] class TestNotificationIntegration: """Integration tests for the notification queue using real Docket memory backend. The elicitation flow validates the full notification pipeline: 1. Tool calls ctx.elicit() -> stores request in Redis -> pushes notification 2. Subscriber picks up notification -> sends MCP notification to client 3. Subscriber relays elicitation/create to client -> handler responds 4. Relay pushes response to Redis -> BLPOP wakes tool """ async def test_notification_delivered_during_elicitation(self): """Full E2E: notification queue delivers input_required metadata to client. The elicitation relay handles the response via the client's elicitation_handler. We verify both the notification metadata structure and the end-to-end elicitation flow. """ mcp = FastMCP("notification-test") notification_handler = NotificationCaptureHandler() @mcp.tool(task=True) async def elicit_tool(ctx: Context) -> str: result = await ctx.elicit("Enter value", str) if isinstance(result, AcceptedElicitation): return f"got: {result.data}" return "no value" async def elicitation_handler(message, response_type, params, ctx): return ElicitResult(action="accept", content={"value": "hello"}) async with Client( mcp, message_handler=notification_handler, elicitation_handler=elicitation_handler, ) as client: task = await client.call_tool("elicit_tool", {}, task=True) await task.wait(timeout=10.0) result = await task.result() assert result.data == "got: hello" # Verify the input_required notification was delivered with metadata notification: mcp_types.ServerNotification | None = None candidates = notification_handler.for_method("notifications/tasks/status") for candidate in reversed(candidates): candidate_meta = getattr(candidate.root, "_meta", None) related_task = ( candidate_meta.get("io.modelcontextprotocol/related-task") if isinstance(candidate_meta, dict) else None ) if ( isinstance(related_task, dict) and related_task.get("status") == "input_required" ): notification = candidate break assert notification is not None, "expected notifications/tasks/status" task_meta = getattr(notification.root, "_meta", None) assert isinstance(task_meta, dict) related_task = task_meta.get("io.modelcontextprotocol/related-task") assert isinstance(related_task, dict) assert related_task.get("taskId") == task.task_id assert related_task.get("status") == "input_required" elicitation = related_task.get("elicitation") assert isinstance(elicitation, dict) assert elicitation.get("message") == "Enter value" assert isinstance(elicitation.get("requestId"), str) assert isinstance(elicitation.get("requestedSchema"), dict) async def test_subscriber_started_and_cleaned_up(self): """Subscriber starts during background task and stops when client disconnects.""" mcp = FastMCP("subscriber-test") tool_started = asyncio.Event() tool_continue = asyncio.Event() @mcp.tool(task=True) async def lifecycle_tool(ctx: Context) -> str: tool_started.set() await asyncio.wait_for(tool_continue.wait(), timeout=10.0) return "done" count_before = get_subscriber_count() async with Client(mcp) as client: task = await client.call_tool("lifecycle_tool", {}, task=True) await asyncio.wait_for(tool_started.wait(), timeout=5.0) # While a background task is running, subscriber should be active count_during = get_subscriber_count() assert count_during > count_before # Let the tool complete tool_continue.set() await task.wait(timeout=5.0) result = await task.result() assert result.data == "done" # After client disconnects, subscriber should be cleaned up # Allow brief time for async cleanup for _ in range(20): if get_subscriber_count() == count_before: break await asyncio.sleep(0.05) assert get_subscriber_count() == count_before
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/tasks/test_notifications.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/tasks/test_task_elicitation_relay.py
"""Tests for background task elicitation relay (notifications.py). The relay bridges distributed background tasks to clients via the standard MCP elicitation/create protocol. When a worker calls ctx.elicit(), the notification subscriber detects the input_required notification and sends an elicitation/create request to the client session. The client's elicitation_handler fires, and the relay pushes the response to Redis for the blocked worker. These tests use Client(mcp) with the real memory:// Docket backend. """ import asyncio from dataclasses import dataclass from pydantic import BaseModel from fastmcp import FastMCP from fastmcp.client import Client from fastmcp.client.elicitation import ElicitResult from fastmcp.server.context import Context from fastmcp.server.elicitation import ( AcceptedElicitation, CancelledElicitation, DeclinedElicitation, ) class TestElicitationRelay: """E2E tests for elicitation flowing through the standard MCP protocol.""" async def test_accept_via_elicitation_handler(self): """Tool elicits, client handler accepts, tool gets the value.""" mcp = FastMCP("relay-accept") @mcp.tool(task=True) async def ask_name(ctx: Context) -> str: result = await ctx.elicit("What is your name?", str) if isinstance(result, AcceptedElicitation): return f"Hello, {result.data}!" return "No name" async def handler(message, response_type, params, ctx): assert message == "What is your name?" return ElicitResult(action="accept", content={"value": "Alice"}) async with Client(mcp, elicitation_handler=handler) as client: task = await client.call_tool("ask_name", {}, task=True) result = await task.result() assert result.data == "Hello, Alice!" async def test_decline_via_elicitation_handler(self): """Tool elicits, client handler declines, tool gets DeclinedElicitation.""" mcp = FastMCP("relay-decline") @mcp.tool(task=True) async def optional_input(ctx: Context) -> str: result = await ctx.elicit("Provide a name?", str) if isinstance(result, DeclinedElicitation): return "User declined" if isinstance(result, AcceptedElicitation): return f"Got: {result.data}" return "Cancelled" async def handler(message, response_type, params, ctx): return ElicitResult(action="decline") async with Client(mcp, elicitation_handler=handler) as client: task = await client.call_tool("optional_input", {}, task=True) result = await task.result() assert result.data == "User declined" async def test_cancel_via_elicitation_handler(self): """Tool elicits, client handler cancels, tool gets CancelledElicitation.""" mcp = FastMCP("relay-cancel") @mcp.tool(task=True) async def cancellable(ctx: Context) -> str: result = await ctx.elicit("Input?", str) if isinstance(result, CancelledElicitation): return "Cancelled" return "Not cancelled" async def handler(message, response_type, params, ctx): return ElicitResult(action="cancel") async with Client(mcp, elicitation_handler=handler) as client: task = await client.call_tool("cancellable", {}, task=True) result = await task.result() assert result.data == "Cancelled" async def test_dataclass_round_trips_through_relay(self): """Structured dataclass type round-trips through the relay.""" mcp = FastMCP("relay-dataclass") @dataclass class UserInfo: name: str age: int @mcp.tool(task=True) async def get_user(ctx: Context) -> str: result = await ctx.elicit("Provide user info", UserInfo) if isinstance(result, AcceptedElicitation): assert isinstance(result.data, UserInfo) return f"{result.data.name} is {result.data.age}" return "No info" async def handler(message, response_type, params, ctx): return ElicitResult(action="accept", content={"name": "Bob", "age": 30}) async with Client(mcp, elicitation_handler=handler) as client: task = await client.call_tool("get_user", {}, task=True) result = await task.result() assert result.data == "Bob is 30" async def test_pydantic_model_round_trips_through_relay(self): """Structured Pydantic model round-trips through the relay.""" mcp = FastMCP("relay-pydantic") class Config(BaseModel): host: str port: int @mcp.tool(task=True) async def get_config(ctx: Context) -> str: result = await ctx.elicit("Server config?", Config) if isinstance(result, AcceptedElicitation): assert isinstance(result.data, Config) return f"{result.data.host}:{result.data.port}" return "No config" async def handler(message, response_type, params, ctx): return ElicitResult( action="accept", content={"host": "localhost", "port": 8080} ) async with Client(mcp, elicitation_handler=handler) as client: task = await client.call_tool("get_config", {}, task=True) result = await task.result() assert result.data == "localhost:8080" async def test_multiple_sequential_elicitations(self): """Tool calls ctx.elicit() twice, both go through the relay.""" mcp = FastMCP("relay-multi") @mcp.tool(task=True) async def two_questions(ctx: Context) -> str: r1 = await ctx.elicit("First name?", str) r2 = await ctx.elicit("Last name?", str) if isinstance(r1, AcceptedElicitation) and isinstance( r2, AcceptedElicitation ): return f"{r1.data} {r2.data}" return "Incomplete" call_count = 0 async def handler(message, response_type, params, ctx): nonlocal call_count call_count += 1 if call_count == 1: assert message == "First name?" return ElicitResult(action="accept", content={"value": "Jane"}) else: assert message == "Last name?" return ElicitResult(action="accept", content={"value": "Doe"}) async with Client(mcp, elicitation_handler=handler) as client: task = await client.call_tool("two_questions", {}, task=True) result = await task.result() assert result.data == "Jane Doe" assert call_count == 2 async def test_no_elicitation_handler_returns_cancel(self): """Without an elicitation_handler, the relay fails and task gets cancel.""" mcp = FastMCP("relay-no-handler") @mcp.tool(task=True) async def needs_input(ctx: Context) -> str: result = await ctx.elicit("Input?", str) if isinstance(result, CancelledElicitation): return "Cancelled as expected" if isinstance(result, AcceptedElicitation): return f"Got: {result.data}" return "Other" async with Client(mcp) as client: task = await client.call_tool("needs_input", {}, task=True) result = await asyncio.wait_for(task.result(), timeout=15.0) assert result.data == "Cancelled as expected"
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/tasks/test_task_elicitation_relay.py", "license": "Apache License 2.0", "lines": 154, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/test_json_schema_generation.py
"""Tests for JSON schema generation from FastMCP BaseModel classes. Validates that callable fields are properly excluded from generated schemas using SkipJsonSchema annotations. """ from fastmcp.prompts.function_prompt import FunctionPrompt from fastmcp.resources.function_resource import FunctionResource from fastmcp.resources.template import FunctionResourceTemplate from fastmcp.tools.function_tool import FunctionTool from fastmcp.tools.tool import Tool from fastmcp.tools.tool_transform import TransformedTool class TestToolJsonSchema: """Test JSON schema generation for Tool classes.""" def test_tool_json_schema_generation(self): """Verify Tool.model_json_schema() works without errors.""" # This should not raise an error schema = Tool.model_json_schema() # Verify schema is valid assert schema["type"] == "object" assert "properties" in schema # Verify callable fields are excluded from schema assert "serializer" not in schema["properties"] # auth already uses exclude=True, so it shouldn't be in schema assert "auth" not in schema["properties"] def test_function_tool_json_schema_generation(self): """Verify FunctionTool.model_json_schema() works without errors.""" def sample_tool(x: int, y: int) -> int: """Add two numbers.""" return x + y tool = FunctionTool.from_function(sample_tool) # This should not raise an error schema = tool.model_json_schema() # Verify schema is valid assert schema["type"] == "object" assert "properties" in schema # Verify callable field 'fn' is excluded from schema assert "fn" not in schema["properties"] def test_transformed_tool_json_schema_generation(self): """Verify TransformedTool.model_json_schema() works without errors.""" def parent_fn(x: int) -> int: return x * 2 parent_tool = FunctionTool.from_function(parent_fn) transformed_tool = TransformedTool.from_tool(parent_tool, name="doubled") # This should not raise an error schema = transformed_tool.model_json_schema() # Verify schema is valid assert schema["type"] == "object" assert "properties" in schema # Verify callable fields are excluded from schema assert "fn" not in schema["properties"] assert "forwarding_fn" not in schema["properties"] assert "parent_tool" not in schema["properties"] class TestResourceJsonSchema: """Test JSON schema generation for Resource classes.""" def test_function_resource_json_schema_generation(self): """Verify FunctionResource.model_json_schema() works without errors.""" def sample_resource() -> str: """Return sample data.""" return "Hello, world!" resource = FunctionResource.from_function( sample_resource, uri="test://resource" ) # This should not raise an error schema = resource.model_json_schema() # Verify schema is valid assert schema["type"] == "object" assert "properties" in schema # Verify callable field 'fn' is excluded from schema assert "fn" not in schema["properties"] # auth already uses exclude=True assert "auth" not in schema["properties"] def test_function_resource_template_json_schema_generation(self): """Verify FunctionResourceTemplate.model_json_schema() works without errors.""" def sample_template(name: str) -> str: """Return greeting for name.""" return f"Hello, {name}!" template = FunctionResourceTemplate.from_function( sample_template, uri_template="greeting://{name}" ) # This should not raise an error schema = template.model_json_schema() # Verify schema is valid assert schema["type"] == "object" assert "properties" in schema # Verify callable field 'fn' is excluded from schema assert "fn" not in schema["properties"] class TestPromptJsonSchema: """Test JSON schema generation for Prompt classes.""" def test_function_prompt_json_schema_generation(self): """Verify FunctionPrompt.model_json_schema() works without errors.""" def sample_prompt(topic: str) -> str: """Generate prompt about topic.""" return f"Tell me about {topic}" prompt = FunctionPrompt.from_function(sample_prompt) # This should not raise an error schema = prompt.model_json_schema() # Verify schema is valid assert schema["type"] == "object" assert "properties" in schema # Verify callable field 'fn' is excluded from schema assert "fn" not in schema["properties"] # auth already uses exclude=True assert "auth" not in schema["properties"] class TestJsonSchemaIntegration: """Integration tests for JSON schema generation across all classes.""" def test_all_classes_generate_valid_schemas(self): """Verify all affected classes can generate valid JSON schemas.""" # Create instances of all affected classes def tool_fn(x: int) -> int: return x def resource_fn() -> str: return "data" def template_fn(id: str) -> str: return f"data-{id}" def prompt_fn(input: str) -> str: return f"Prompt: {input}" tool = FunctionTool.from_function(tool_fn) transformed_tool = TransformedTool.from_tool(tool) resource = FunctionResource.from_function(resource_fn, uri="test://resource") template = FunctionResourceTemplate.from_function( template_fn, uri_template="test://{id}" ) prompt = FunctionPrompt.from_function(prompt_fn) # All of these should succeed without errors schemas = [ Tool.model_json_schema(), tool.model_json_schema(), transformed_tool.model_json_schema(), resource.model_json_schema(), template.model_json_schema(), prompt.model_json_schema(), ] # Verify all schemas are valid for schema in schemas: assert isinstance(schema, dict) assert schema["type"] == "object" assert "properties" in schema def test_callable_fields_not_in_any_schema(self): """Verify no callable fields appear in any generated schema.""" # Define test functions def tool_fn(x: int) -> int: return x def resource_fn() -> str: return "data" def template_fn(id: str) -> str: return f"data-{id}" def prompt_fn(input: str) -> str: return f"Prompt: {input}" # Create instances tool = FunctionTool.from_function(tool_fn) transformed_tool = TransformedTool.from_tool(tool) resource = FunctionResource.from_function(resource_fn, uri="test://resource") template = FunctionResourceTemplate.from_function( template_fn, uri_template="test://{id}" ) prompt = FunctionPrompt.from_function(prompt_fn) # List of (instance, callable_field_names) tuples test_cases = [ (tool, ["fn", "serializer"]), (transformed_tool, ["fn", "forwarding_fn", "parent_tool", "serializer"]), (resource, ["fn"]), (template, ["fn"]), (prompt, ["fn"]), ] for instance, callable_fields in test_cases: schema = instance.model_json_schema() properties = schema.get("properties", {}) # Verify none of the callable fields are in the schema for field in callable_fields: assert field not in properties, ( f"Callable field '{field}' found in schema for {type(instance).__name__}" )
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/test_json_schema_generation.py", "license": "Apache License 2.0", "lines": 171, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:examples/apps/qr_server/qr_server.py
"""QR Code MCP App Server — generates QR codes with an interactive view UI. Demonstrates MCP Apps with FastMCP: - Tool linked to a ui:// resource via AppConfig - HTML resource with CSP metadata for CDN-loaded dependencies - Embedded HTML using the @modelcontextprotocol/ext-apps JS SDK - ImageContent return type for binary data - Both stdio and HTTP transport modes Based on https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/qr-server Setup (from examples/apps/): uv sync Usage: uv run python qr_server.py # HTTP mode (port 3001) uv run python qr_server.py --stdio # stdio mode for MCP clients """ from __future__ import annotations import base64 import io import qrcode # type: ignore[import-untyped] from mcp import types from fastmcp import FastMCP from fastmcp.server.apps import AppConfig, ResourceCSP from fastmcp.tools import ToolResult VIEW_URI: str = "ui://qr-server/view.html" mcp: FastMCP = FastMCP("QR Code Server") EMBEDDED_VIEW_HTML: str = """\ <!DOCTYPE html> <html> <head> <meta name="color-scheme" content="light dark"> <style> html, body { margin: 0; padding: 0; overflow: hidden; background: transparent; } body { display: flex; justify-content: center; align-items: center; height: 340px; width: 340px; } img { width: 300px; height: 300px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); } </style> </head> <body> <div id="qr"></div> <script type="module"> import { App } from "https://unpkg.com/@modelcontextprotocol/ext-apps@0.4.0/app-with-deps"; const app = new App({ name: "QR View", version: "1.0.0" }); app.ontoolresult = ({ content }) => { const img = content?.find(c => c.type === 'image'); if (img) { const qrDiv = document.getElementById('qr'); qrDiv.innerHTML = ''; const allowedTypes = ['image/png', 'image/jpeg', 'image/gif']; const mimeType = allowedTypes.includes(img.mimeType) ? img.mimeType : 'image/png'; const image = document.createElement('img'); image.src = `data:${mimeType};base64,${img.data}`; image.alt = "QR Code"; qrDiv.appendChild(image); } }; function handleHostContextChanged(ctx) { if (ctx.safeAreaInsets) { document.body.style.paddingTop = `${ctx.safeAreaInsets.top}px`; document.body.style.paddingRight = `${ctx.safeAreaInsets.right}px`; document.body.style.paddingBottom = `${ctx.safeAreaInsets.bottom}px`; document.body.style.paddingLeft = `${ctx.safeAreaInsets.left}px`; } } app.onhostcontextchanged = handleHostContextChanged; await app.connect(); const ctx = app.getHostContext(); if (ctx) { handleHostContextChanged(ctx); } </script> </body> </html>""" @mcp.tool(app=AppConfig(resource_uri=VIEW_URI)) def generate_qr( text: str = "https://gofastmcp.com", box_size: int = 10, border: int = 4, error_correction: str = "M", fill_color: str = "black", back_color: str = "white", ) -> ToolResult: """Generate a QR code from text. Args: text: The text/URL to encode box_size: Size of each box in pixels (default: 10) border: Border size in boxes (default: 4) error_correction: Error correction level - L(7%), M(15%), Q(25%), H(30%) fill_color: Foreground color (hex like #FF0000 or name like red) back_color: Background color (hex like #FFFFFF or name like white) """ error_levels = { "L": qrcode.constants.ERROR_CORRECT_L, "M": qrcode.constants.ERROR_CORRECT_M, "Q": qrcode.constants.ERROR_CORRECT_Q, "H": qrcode.constants.ERROR_CORRECT_H, } if box_size <= 0: raise ValueError("box_size must be > 0") if border < 0: raise ValueError("border must be >= 0") error_key = error_correction.upper() if error_key not in error_levels: raise ValueError(f"error_correction must be one of: {', '.join(error_levels)}") qr = qrcode.QRCode( version=1, error_correction=error_levels[error_key], box_size=box_size, border=border, ) qr.add_data(text) qr.make(fit=True) img = qr.make_image(fill_color=fill_color, back_color=back_color) buffer = io.BytesIO() img.save(buffer, format="PNG") b64 = base64.b64encode(buffer.getvalue()).decode() return ToolResult( content=[types.ImageContent(type="image", data=b64, mimeType="image/png")] ) @mcp.resource( VIEW_URI, app=AppConfig(csp=ResourceCSP(resource_domains=["https://unpkg.com"])), ) def view() -> str: """Interactive QR code viewer — renders tool results as images.""" return EMBEDDED_VIEW_HTML if __name__ == "__main__": mcp.run()
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/apps/qr_server/qr_server.py", "license": "Apache License 2.0", "lines": 141, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
PrefectHQ/fastmcp:src/fastmcp/cli/install/goose.py
"""Goose integration for FastMCP install using Cyclopts.""" import re import sys from pathlib import Path from typing import Annotated from urllib.parse import quote import cyclopts from rich import print from fastmcp.utilities.logging import get_logger from .shared import open_deeplink, process_common_args logger = get_logger(__name__) def _slugify(name: str) -> str: """Convert a display name to a URL-safe identifier. Lowercases, replaces non-alphanumeric runs with hyphens, and strips leading/trailing hyphens. """ slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-") return slug or "fastmcp-server" def generate_goose_deeplink( name: str, command: str, args: list[str], *, description: str = "MCP server installed via FastMCP", ) -> str: """Generate a Goose deeplink for installing an MCP extension. Args: name: Human-readable display name for the extension. command: The executable command (e.g. "uv"). args: Arguments to the command. description: Short description shown in Goose. Returns: A goose://extension?... deeplink URL. """ extension_id = _slugify(name) params: list[str] = [f"cmd={quote(command, safe='')}"] for arg in args: params.append(f"arg={quote(arg, safe='')}") params.append(f"id={quote(extension_id, safe='')}") params.append(f"name={quote(name, safe='')}") params.append(f"description={quote(description, safe='')}") return f"goose://extension?{'&'.join(params)}" def _build_uvx_command( server_spec: str, *, python_version: str | None = None, with_packages: list[str] | None = None, ) -> list[str]: """Build a uvx command for running a FastMCP server. Goose requires uvx (not uv run) as the command. The uvx format is: uvx [--with pkg] [--python X] fastmcp run <spec> uvx automatically infers that the `fastmcp` command comes from the `fastmcp` package, so --from is not needed. """ args: list[str] = ["uvx"] if python_version: args.extend(["--python", python_version]) for pkg in sorted(set(with_packages or [])): if pkg != "fastmcp": args.extend(["--with", pkg]) args.extend(["fastmcp", "run", server_spec]) return args def install_goose( file: Path, server_object: str | None, name: str, *, with_packages: list[str] | None = None, python_version: str | None = None, ) -> bool: """Install FastMCP server in Goose via deeplink. Args: file: Path to the server file. server_object: Optional server object name (for :object suffix). name: Name for the extension in Goose. with_packages: Optional list of additional packages to install. python_version: Optional Python version to use. Returns: True if installation was successful, False otherwise. """ if server_object: server_spec = f"{file.resolve()}:{server_object}" else: server_spec = str(file.resolve()) full_command = _build_uvx_command( server_spec, python_version=python_version, with_packages=with_packages, ) deeplink = generate_goose_deeplink( name=name, command=full_command[0], args=full_command[1:], ) print(f"[blue]Opening Goose to install '{name}'[/blue]") if open_deeplink(deeplink, expected_scheme="goose"): print("[green]Goose should now open with the installation dialog[/green]") return True else: print( "[red]Could not open Goose automatically.[/red]\n" f"[blue]Please copy this link and open it in Goose: {deeplink}[/blue]" ) return False async def goose_command( server_spec: str, *, server_name: Annotated[ str | None, cyclopts.Parameter( name=["--name", "-n"], help="Custom name for the extension in Goose", ), ] = None, with_packages: Annotated[ list[str] | None, cyclopts.Parameter( "--with", help="Additional packages to install (can be used multiple times)", ), ] = None, env_vars: Annotated[ list[str] | None, cyclopts.Parameter( "--env", help="Environment variables in KEY=VALUE format (can be used multiple times)", ), ] = None, env_file: Annotated[ Path | None, cyclopts.Parameter( "--env-file", help="Load environment variables from .env file", ), ] = None, python: Annotated[ str | None, cyclopts.Parameter( "--python", help="Python version to use (e.g., 3.10, 3.11)", ), ] = None, ) -> None: """Install an MCP server in Goose. Uses uvx to run the server. Environment variables are not included in the deeplink; use `fastmcp install mcp-json` to generate a full config for manual installation. Args: server_spec: Python file to install, optionally with :object suffix """ with_packages = with_packages or [] env_vars = env_vars or [] if env_vars or env_file: print( "[red]Goose deeplinks cannot include environment variables.[/red]\n" "[yellow]Use `fastmcp install mcp-json` to generate a config, then add it " "to your Goose config file with env vars: " "https://block.github.io/goose/docs/getting-started/using-extensions/#config-entry[/yellow]" ) sys.exit(1) file, server_object, name, with_packages, _env_dict = await process_common_args( server_spec, server_name, with_packages, env_vars, env_file ) success = install_goose( file=file, server_object=server_object, name=name, with_packages=with_packages, python_version=python, ) if not success: sys.exit(1)
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/cli/install/goose.py", "license": "Apache License 2.0", "lines": 172, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:src/fastmcp/cli/install/stdio.py
"""Stdio command generation for FastMCP install using Cyclopts.""" import builtins import shlex import sys from pathlib import Path from typing import Annotated import cyclopts import pyperclip from rich import print as rich_print from fastmcp.utilities.logging import get_logger from fastmcp.utilities.mcp_server_config.v1.environments.uv import UVEnvironment from .shared import process_common_args logger = get_logger(__name__) def install_stdio( file: Path, server_object: str | None, *, with_editable: list[Path] | None = None, with_packages: list[str] | None = None, copy: bool = False, python_version: str | None = None, with_requirements: Path | None = None, project: Path | None = None, ) -> bool: """Generate the stdio command for running a FastMCP server. Args: file: Path to the server file server_object: Optional server object name (for :object suffix) with_editable: Optional list of directories to install in editable mode with_packages: Optional list of additional packages to install copy: If True, copy to clipboard instead of printing to stdout python_version: Optional Python version to use with_requirements: Optional requirements file to install from project: Optional project directory to run within Returns: True if generation was successful, False otherwise """ try: env_config = UVEnvironment( python=python_version, dependencies=(with_packages or []) + ["fastmcp"], requirements=with_requirements, project=project, editable=with_editable, ) # Build server spec from parsed components if server_object: server_spec = f"{file.resolve()}:{server_object}" else: server_spec = str(file.resolve()) # Build the full command full_command = env_config.build_command(["fastmcp", "run", server_spec]) command_str = shlex.join(full_command) if copy: pyperclip.copy(command_str) rich_print("[green]✓ Command copied to clipboard[/green]") else: builtins.print(command_str) return True except (OSError, ValueError, pyperclip.PyperclipException) as e: rich_print(f"[red]Failed to generate stdio command: {e}[/red]") return False async def stdio_command( server_spec: str, *, server_name: Annotated[ str | None, cyclopts.Parameter( name=["--name", "-n"], help="Custom name for the server (used for dependency resolution)", ), ] = None, with_editable: Annotated[ list[Path] | None, cyclopts.Parameter( "--with-editable", help="Directory with pyproject.toml to install in editable mode (can be used multiple times)", ), ] = None, with_packages: Annotated[ list[str] | None, cyclopts.Parameter( "--with", help="Additional packages to install (can be used multiple times)" ), ] = None, copy: Annotated[ bool, cyclopts.Parameter( "--copy", help="Copy command to clipboard instead of printing to stdout", ), ] = False, python: Annotated[ str | None, cyclopts.Parameter( "--python", help="Python version to use (e.g., 3.10, 3.11)", ), ] = None, with_requirements: Annotated[ Path | None, cyclopts.Parameter( "--with-requirements", help="Requirements file to install dependencies from", ), ] = None, project: Annotated[ Path | None, cyclopts.Parameter( "--project", help="Run the command within the given project directory", ), ] = None, ) -> None: """Generate the stdio command for running a FastMCP server. Outputs the shell command that an MCP host would use to start this server over stdio transport. Useful for manual configuration or debugging. Args: server_spec: Python file to run, optionally with :object suffix """ with_editable = with_editable or [] with_packages = with_packages or [] file, server_object, _name, packages, _env_dict = await process_common_args( server_spec, server_name, with_packages, [], None ) success = install_stdio( file=file, server_object=server_object, with_editable=with_editable, with_packages=packages, copy=copy, python_version=python, with_requirements=with_requirements, project=project, ) if not success: sys.exit(1)
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/cli/install/stdio.py", "license": "Apache License 2.0", "lines": 137, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:src/fastmcp/server/apps.py
"""MCP Apps support — extension negotiation and typed UI metadata models. Provides constants and Pydantic models for the MCP Apps extension (io.modelcontextprotocol/ui), enabling tools and resources to carry UI metadata for clients that support interactive app rendering. """ from __future__ import annotations from typing import Any, Literal from pydantic import BaseModel, Field UI_EXTENSION_ID = "io.modelcontextprotocol/ui" UI_MIME_TYPE = "text/html;profile=mcp-app" class ResourceCSP(BaseModel): """Content Security Policy for MCP App resources. Declares which external origins the app is allowed to connect to or load resources from. Hosts use these declarations to build the ``Content-Security-Policy`` header for the sandboxed iframe. """ connect_domains: list[str] | None = Field( default=None, alias="connectDomains", description="Origins allowed for fetch/XHR/WebSocket (connect-src)", ) resource_domains: list[str] | None = Field( default=None, alias="resourceDomains", description="Origins allowed for scripts, images, styles, fonts (script-src etc.)", ) frame_domains: list[str] | None = Field( default=None, alias="frameDomains", description="Origins allowed for nested iframes (frame-src)", ) base_uri_domains: list[str] | None = Field( default=None, alias="baseUriDomains", description="Allowed base URIs for the document (base-uri)", ) model_config = {"populate_by_name": True, "extra": "allow"} class ResourcePermissions(BaseModel): """Iframe sandbox permissions for MCP App resources. Each field, when set (typically to ``{}``), requests that the host grant the corresponding Permission Policy feature to the sandboxed iframe. Hosts MAY honour these; apps should use JS feature detection as a fallback. """ camera: dict[str, Any] | None = Field( default=None, description="Request camera access" ) microphone: dict[str, Any] | None = Field( default=None, description="Request microphone access" ) geolocation: dict[str, Any] | None = Field( default=None, description="Request geolocation access" ) clipboard_write: dict[str, Any] | None = Field( default=None, alias="clipboardWrite", description="Request clipboard-write access", ) model_config = {"populate_by_name": True, "extra": "allow"} class AppConfig(BaseModel): """Configuration for MCP App tools and resources. Controls how a tool or resource participates in the MCP Apps extension. On tools, ``resource_uri`` and ``visibility`` specify which UI resource to render and where the tool appears. On resources, those fields must be left unset (the resource itself is the UI). All fields use ``exclude_none`` serialization so only explicitly-set values appear on the wire. Aliases match the MCP Apps wire format (camelCase). """ resource_uri: str | None = Field( default=None, alias="resourceUri", description="URI of the UI resource (typically ui:// scheme). Tools only.", ) visibility: list[Literal["app", "model"]] | None = Field( default=None, description="Where this tool is visible: 'app', 'model', or both. Tools only.", ) csp: ResourceCSP | None = Field( default=None, description="Content Security Policy for the app iframe" ) permissions: ResourcePermissions | None = Field( default=None, description="Iframe sandbox permissions" ) domain: str | None = Field(default=None, description="Domain for the iframe") prefers_border: bool | None = Field( default=None, alias="prefersBorder", description="Whether the UI prefers a visible border", ) model_config = {"populate_by_name": True, "extra": "allow"} def app_config_to_meta_dict(app: AppConfig | dict[str, Any]) -> dict[str, Any]: """Convert an AppConfig or dict to the wire-format dict for ``meta["ui"]``.""" if isinstance(app, AppConfig): return app.model_dump(by_alias=True, exclude_none=True) return app def resolve_ui_mime_type(uri: str, explicit_mime_type: str | None) -> str | None: """Return the appropriate MIME type for a resource URI. For ``ui://`` scheme resources, defaults to ``UI_MIME_TYPE`` when no explicit MIME type is provided. This ensures UI resources are correctly identified regardless of how they're registered (via FastMCP.resource, the standalone @resource decorator, or resource templates). Args: uri: The resource URI string explicit_mime_type: The MIME type explicitly provided by the user Returns: The resolved MIME type (explicit value, UI default, or None) """ if explicit_mime_type is not None: return explicit_mime_type # Case-insensitive scheme check per RFC 3986 if uri.lower().startswith("ui://"): return UI_MIME_TYPE return None
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/server/apps.py", "license": "Apache License 2.0", "lines": 114, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:tests/cli/test_goose.py
from pathlib import Path from unittest.mock import patch from urllib.parse import parse_qs, unquote, urlparse import pytest from fastmcp.cli.install.goose import ( _build_uvx_command, _slugify, generate_goose_deeplink, goose_command, install_goose, ) class TestSlugify: def test_simple_name(self): assert _slugify("My Server") == "my-server" def test_special_characters(self): assert _slugify("my_server (v2.0)") == "my-server-v2-0" def test_already_slugified(self): assert _slugify("my-server") == "my-server" def test_empty_string(self): assert _slugify("") == "fastmcp-server" def test_only_special_chars(self): assert _slugify("!!!") == "fastmcp-server" def test_consecutive_hyphens_collapsed(self): assert _slugify("a---b") == "a-b" def test_leading_trailing_stripped(self): assert _slugify("--hello--") == "hello" class TestBuildUvxCommand: def test_basic(self): cmd = _build_uvx_command("server.py") assert cmd == ["uvx", "fastmcp", "run", "server.py"] def test_with_python_version(self): cmd = _build_uvx_command("server.py", python_version="3.11") assert cmd == [ "uvx", "--python", "3.11", "fastmcp", "run", "server.py", ] def test_with_packages(self): cmd = _build_uvx_command("server.py", with_packages=["numpy", "pandas"]) assert "--with" in cmd assert "numpy" in cmd assert "pandas" in cmd def test_fastmcp_not_in_with(self): cmd = _build_uvx_command("server.py", with_packages=["fastmcp", "numpy"]) # fastmcp is the command itself, so it shouldn't appear in --with with_indices = [i for i, v in enumerate(cmd) if v == "--with"] with_values = [cmd[i + 1] for i in with_indices] assert "fastmcp" not in with_values def test_packages_sorted_and_deduplicated(self): cmd = _build_uvx_command( "server.py", with_packages=["pandas", "numpy", "pandas"] ) with_indices = [i for i, v in enumerate(cmd) if v == "--with"] with_values = [cmd[i + 1] for i in with_indices] assert with_values == ["numpy", "pandas"] def test_server_spec_with_object(self): cmd = _build_uvx_command("server.py:app") assert cmd[-1] == "server.py:app" class TestGooseDeeplinkGeneration: def test_basic_deeplink(self): deeplink = generate_goose_deeplink( name="test-server", command="uvx", args=["fastmcp", "run", "server.py"], ) assert deeplink.startswith("goose://extension?") parsed = urlparse(deeplink) params = parse_qs(parsed.query) assert params["cmd"] == ["uvx"] assert params["name"] == ["test-server"] assert params["id"] == ["test-server"] def test_special_characters_in_name(self): deeplink = generate_goose_deeplink( name="my server (test)", command="uvx", args=["fastmcp", "run", "server.py"], ) assert "name=my%20server%20%28test%29" in deeplink parsed = urlparse(deeplink) params = parse_qs(parsed.query) assert params["id"] == ["my-server-test"] def test_url_injection_protection(self): deeplink = generate_goose_deeplink( name="test&evil=true", command="uvx", args=["fastmcp", "run", "server.py"], ) assert "name=test%26evil%3Dtrue" in deeplink parsed = urlparse(deeplink) params = parse_qs(parsed.query) assert params["name"] == ["test&evil=true"] def test_dangerous_characters_encoded(self): dangerous_names = [ ("test|calc", "test%7Ccalc"), ("test;calc", "test%3Bcalc"), ("test<calc", "test%3Ccalc"), ("test>calc", "test%3Ecalc"), ("test`calc", "test%60calc"), ("test$calc", "test%24calc"), ("test'calc", "test%27calc"), ('test"calc', "test%22calc"), ("test calc", "test%20calc"), ("test#anchor", "test%23anchor"), ("test?query=val", "test%3Fquery%3Dval"), ] for dangerous_name, expected_encoded in dangerous_names: deeplink = generate_goose_deeplink( name=dangerous_name, command="uvx", args=["fastmcp", "run", "server.py"] ) assert f"name={expected_encoded}" in deeplink, ( f"Failed to encode {dangerous_name}" ) def test_custom_description(self): deeplink = generate_goose_deeplink( name="my-server", command="uvx", args=["fastmcp", "run", "server.py"], description="My custom MCP server", ) parsed = urlparse(deeplink) params = parse_qs(parsed.query) assert params["description"] == ["My custom MCP server"] def test_args_with_special_characters(self): deeplink = generate_goose_deeplink( name="test", command="uvx", args=[ "--with", "numpy>=1.20", "fastmcp", "run", "server.py:MyApp", ], ) parsed = urlparse(deeplink) params = parse_qs(parsed.query) assert "numpy>=1.20" in params["arg"] assert "server.py:MyApp" in params["arg"] def test_empty_args(self): deeplink = generate_goose_deeplink(name="simple", command="python", args=[]) parsed = urlparse(deeplink) params = parse_qs(parsed.query) assert "arg" not in params assert params["cmd"] == ["python"] def test_command_with_path(self): deeplink = generate_goose_deeplink( name="test", command="/usr/local/bin/uvx", args=["fastmcp", "run", "server.py"], ) parsed = urlparse(deeplink) params = parse_qs(parsed.query) assert params["cmd"] == ["/usr/local/bin/uvx"] class TestInstallGoose: @patch("fastmcp.cli.install.goose.open_deeplink") @patch("fastmcp.cli.install.goose.print") def test_success(self, mock_print, mock_open): mock_open.return_value = True result = install_goose( file=Path("/path/to/server.py"), server_object=None, name="test-server", ) assert result is True mock_open.assert_called_once() call_url = mock_open.call_args[0][0] assert call_url.startswith("goose://extension?") assert mock_open.call_args[1] == {"expected_scheme": "goose"} @patch("fastmcp.cli.install.goose.open_deeplink") @patch("fastmcp.cli.install.goose.print") def test_success_uses_uvx(self, mock_print, mock_open): mock_open.return_value = True install_goose( file=Path("/path/to/server.py"), server_object=None, name="test-server", ) call_url = mock_open.call_args[0][0] parsed = urlparse(call_url) params = parse_qs(parsed.query) assert params["cmd"] == ["uvx"] assert "fastmcp" in params["arg"] @patch("fastmcp.cli.install.goose.open_deeplink") @patch("fastmcp.cli.install.goose.print") def test_failure(self, mock_print, mock_open): mock_open.return_value = False result = install_goose( file=Path("/path/to/server.py"), server_object=None, name="test-server", ) assert result is False @patch("fastmcp.cli.install.goose.open_deeplink") @patch("fastmcp.cli.install.goose.print") def test_with_server_object(self, mock_print, mock_open): mock_open.return_value = True install_goose( file=Path("/path/to/server.py"), server_object="app", name="test-server", ) call_url = mock_open.call_args[0][0] parsed = urlparse(call_url) params = parse_qs(parsed.query) args = params["arg"] assert any("server.py:app" in unquote(a) for a in args) @patch("fastmcp.cli.install.goose.open_deeplink") @patch("fastmcp.cli.install.goose.print") def test_with_packages(self, mock_print, mock_open): mock_open.return_value = True install_goose( file=Path("/path/to/server.py"), server_object=None, name="test-server", with_packages=["numpy", "pandas"], ) call_url = mock_open.call_args[0][0] parsed = urlparse(call_url) params = parse_qs(parsed.query) args = params["arg"] assert "numpy" in args assert "pandas" in args @patch("fastmcp.cli.install.goose.open_deeplink") @patch("fastmcp.cli.install.goose.print") def test_fallback_message_on_failure(self, mock_print, mock_open): mock_open.return_value = False install_goose( file=Path("/path/to/server.py"), server_object=None, name="test-server", ) fallback_calls = [ call for call in mock_print.call_args_list if "copy this link" in str(call).lower() or "goose://" in str(call) ] assert len(fallback_calls) > 0 class TestGooseCommand: @patch("fastmcp.cli.install.goose.install_goose") @patch("fastmcp.cli.install.goose.process_common_args") async def test_basic(self, mock_process, mock_install): mock_process.return_value = (Path("server.py"), None, "test-server", [], {}) mock_install.return_value = True await goose_command("server.py") mock_install.assert_called_once_with( file=Path("server.py"), server_object=None, name="test-server", with_packages=[], python_version=None, ) @patch("fastmcp.cli.install.goose.install_goose") @patch("fastmcp.cli.install.goose.process_common_args") async def test_failure_exits(self, mock_process, mock_install): mock_process.return_value = (Path("server.py"), None, "test-server", [], {}) mock_install.return_value = False with pytest.raises(SystemExit) as exc_info: await goose_command("server.py") assert exc_info.value.code == 1
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/cli/test_goose.py", "license": "Apache License 2.0", "lines": 262, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/test_apps.py
"""Tests for MCP Apps Phase 1 — SDK compatibility. Covers app config models, tool/resource registration with ``app=``, extension negotiation, and the ``Context.client_supports_extension`` method. """ from __future__ import annotations from typing import Any import pytest from fastmcp import Client, FastMCP from fastmcp.server.apps import ( UI_EXTENSION_ID, UI_MIME_TYPE, AppConfig, ResourceCSP, ResourcePermissions, app_config_to_meta_dict, ) from fastmcp.server.context import Context # --------------------------------------------------------------------------- # Model serialization # --------------------------------------------------------------------------- class TestAppConfig: def test_serializes_with_aliases(self): cfg = AppConfig(resource_uri="ui://my-app/view.html", visibility=["app"]) d = cfg.model_dump(by_alias=True, exclude_none=True) assert d == {"resourceUri": "ui://my-app/view.html", "visibility": ["app"]} def test_excludes_none_fields(self): cfg = AppConfig(resource_uri="ui://foo") d = cfg.model_dump(by_alias=True, exclude_none=True) assert d == {"resourceUri": "ui://foo"} def test_all_fields(self): cfg = AppConfig( resource_uri="ui://app", visibility=["app", "model"], csp=ResourceCSP(resource_domains=["https://cdn.example.com"]), permissions=ResourcePermissions(camera={}, clipboard_write={}), domain="example.com", prefers_border=True, ) d = cfg.model_dump(by_alias=True, exclude_none=True) assert d == { "resourceUri": "ui://app", "visibility": ["app", "model"], "csp": {"resourceDomains": ["https://cdn.example.com"]}, "permissions": {"camera": {}, "clipboardWrite": {}}, "domain": "example.com", "prefersBorder": True, } def test_populate_by_name(self): cfg = AppConfig(resource_uri="ui://app") assert cfg.resource_uri == "ui://app" class TestResourceCSP: def test_serializes_with_aliases(self): csp = ResourceCSP( connect_domains=["https://api.example.com"], resource_domains=["https://cdn.example.com"], ) d = csp.model_dump(by_alias=True, exclude_none=True) assert d == { "connectDomains": ["https://api.example.com"], "resourceDomains": ["https://cdn.example.com"], } def test_excludes_none_fields(self): csp = ResourceCSP(resource_domains=["https://unpkg.com"]) d = csp.model_dump(by_alias=True, exclude_none=True) assert d == {"resourceDomains": ["https://unpkg.com"]} def test_all_fields(self): csp = ResourceCSP( connect_domains=["https://api.example.com"], resource_domains=["https://cdn.example.com"], frame_domains=["https://embed.example.com"], base_uri_domains=["https://base.example.com"], ) d = csp.model_dump(by_alias=True, exclude_none=True) assert d == { "connectDomains": ["https://api.example.com"], "resourceDomains": ["https://cdn.example.com"], "frameDomains": ["https://embed.example.com"], "baseUriDomains": ["https://base.example.com"], } def test_populate_by_name(self): csp = ResourceCSP(connect_domains=["https://api.example.com"]) assert csp.connect_domains == ["https://api.example.com"] def test_empty(self): csp = ResourceCSP() d = csp.model_dump(by_alias=True, exclude_none=True) assert d == {} def test_extra_fields_preserved(self): """Unknown CSP directives from future spec versions pass through.""" csp = ResourceCSP( resource_domains=["https://cdn.example.com"], **{"workerDomains": ["https://worker.example.com"]}, ) d = csp.model_dump(by_alias=True, exclude_none=True) assert d["resourceDomains"] == ["https://cdn.example.com"] assert d["workerDomains"] == ["https://worker.example.com"] class TestResourcePermissions: def test_serializes_with_aliases(self): perms = ResourcePermissions(microphone={}, clipboard_write={}) d = perms.model_dump(by_alias=True, exclude_none=True) assert d == {"microphone": {}, "clipboardWrite": {}} def test_excludes_none_fields(self): perms = ResourcePermissions(camera={}) d = perms.model_dump(by_alias=True, exclude_none=True) assert d == {"camera": {}} def test_all_fields(self): perms = ResourcePermissions( camera={}, microphone={}, geolocation={}, clipboard_write={} ) d = perms.model_dump(by_alias=True, exclude_none=True) assert d == { "camera": {}, "microphone": {}, "geolocation": {}, "clipboardWrite": {}, } def test_populate_by_name(self): perms = ResourcePermissions(clipboard_write={}) assert perms.clipboard_write == {} def test_extra_fields_preserved(self): """Unknown permissions from future spec versions pass through.""" perms = ResourcePermissions(camera={}, **{"midi": {}}) d = perms.model_dump(by_alias=True, exclude_none=True) assert d["camera"] == {} assert d["midi"] == {} def test_empty(self): perms = ResourcePermissions() d = perms.model_dump(by_alias=True, exclude_none=True) assert d == {} class TestAppConfigForResources: """AppConfig without resource_uri/visibility — for use on resources.""" def test_serializes_with_aliases(self): cfg = AppConfig( prefers_border=True, csp=ResourceCSP(resource_domains=["https://cdn.example.com"]), ) d = cfg.model_dump(by_alias=True, exclude_none=True) assert d == { "prefersBorder": True, "csp": {"resourceDomains": ["https://cdn.example.com"]}, } def test_excludes_none_fields(self): cfg = AppConfig() d = cfg.model_dump(by_alias=True, exclude_none=True) assert d == {} def test_with_permissions(self): cfg = AppConfig( permissions=ResourcePermissions(microphone={}, clipboard_write={}), ) d = cfg.model_dump(by_alias=True, exclude_none=True) assert d == { "permissions": {"microphone": {}, "clipboardWrite": {}}, } class TestAppConfigToMetaDict: def test_from_app_config_with_tool_fields(self): cfg = AppConfig(resource_uri="ui://app", visibility=["app"]) result = app_config_to_meta_dict(cfg) assert result["resourceUri"] == "ui://app" assert result["visibility"] == ["app"] def test_from_app_config_resource_fields_only(self): cfg = AppConfig(prefers_border=False) result = app_config_to_meta_dict(cfg) assert result == {"prefersBorder": False} def test_passthrough_for_dict(self): raw: dict[str, Any] = {"resourceUri": "ui://app", "custom": "value"} result = app_config_to_meta_dict(raw) assert result is raw # --------------------------------------------------------------------------- # Tool registration with app= # --------------------------------------------------------------------------- class TestToolRegistrationWithApp: async def test_app_config_model(self): server = FastMCP("test") @server.tool(app=AppConfig(resource_uri="ui://my-app/view.html")) def my_tool() -> str: return "hello" tools = list(await server.list_tools()) assert len(tools) == 1 assert tools[0].meta is not None assert tools[0].meta["ui"]["resourceUri"] == "ui://my-app/view.html" async def test_app_dict(self): server = FastMCP("test") @server.tool(app={"resourceUri": "ui://foo", "visibility": ["app"]}) def my_tool() -> str: return "hello" tools = list(await server.list_tools()) assert tools[0].meta is not None assert tools[0].meta["ui"]["resourceUri"] == "ui://foo" assert tools[0].meta["ui"]["visibility"] == ["app"] async def test_app_merges_with_existing_meta(self): server = FastMCP("test") @server.tool(meta={"custom": "data"}, app=AppConfig(resource_uri="ui://app")) def my_tool() -> str: return "hello" tools = list(await server.list_tools()) meta = tools[0].meta assert meta is not None assert meta["custom"] == "data" assert meta["ui"]["resourceUri"] == "ui://app" async def test_app_in_mcp_wire_format(self): server = FastMCP("test") @server.tool(app=AppConfig(resource_uri="ui://app", visibility=["app"])) def my_tool() -> str: return "hello" tools = list(await server.list_tools()) mcp_tool = tools[0].to_mcp_tool() assert mcp_tool.meta is not None assert mcp_tool.meta["ui"]["resourceUri"] == "ui://app" assert mcp_tool.meta["ui"]["visibility"] == ["app"] async def test_tool_without_app_has_no_ui_meta(self): server = FastMCP("test") @server.tool def my_tool() -> str: return "hello" tools = list(await server.list_tools()) meta = tools[0].meta assert meta is None or "ui" not in meta # --------------------------------------------------------------------------- # Resource registration with ui:// and app= # --------------------------------------------------------------------------- class TestResourceWithApp: async def test_ui_scheme_defaults_mime_type(self): server = FastMCP("test") @server.resource("ui://my-app/view.html") def app_html() -> str: return "<html>hello</html>" resources = list(await server.list_resources()) assert len(resources) == 1 assert resources[0].mime_type == UI_MIME_TYPE async def test_explicit_mime_type_overrides_ui_default(self): server = FastMCP("test") @server.resource("ui://my-app/view.html", mime_type="text/html") def app_html() -> str: return "<html>hello</html>" resources = list(await server.list_resources()) assert resources[0].mime_type == "text/html" async def test_resource_app_metadata(self): server = FastMCP("test") @server.resource( "ui://my-app/view.html", app=AppConfig(prefers_border=True), ) def app_html() -> str: return "<html>hello</html>" resources = list(await server.list_resources()) assert resources[0].meta is not None assert resources[0].meta["ui"]["prefersBorder"] is True async def test_non_ui_scheme_no_mime_default(self): server = FastMCP("test") @server.resource("resource://data") def data() -> str: return "data" resources = list(await server.list_resources()) assert resources[0].mime_type != UI_MIME_TYPE async def test_standalone_decorator_ui_scheme_defaults_mime_type(self): """The standalone @resource decorator also applies ui:// MIME default.""" from fastmcp.resources import resource @resource("ui://standalone-app/view.html") def standalone_app() -> str: return "<html>standalone</html>" server = FastMCP("test") server.add_resource(standalone_app) resources = list(await server.list_resources()) assert len(resources) == 1 assert resources[0].mime_type == UI_MIME_TYPE async def test_resource_template_ui_scheme_defaults_mime_type(self): """Resource templates also apply ui:// MIME default.""" server = FastMCP("test") @server.resource("ui://template-app/{view}") def template_app(view: str) -> str: return f"<html>{view}</html>" templates = list(await server.list_resource_templates()) assert len(templates) == 1 assert templates[0].mime_type == UI_MIME_TYPE async def test_resource_rejects_resource_uri(self): """AppConfig with resource_uri raises ValueError on resources.""" server = FastMCP("test") with pytest.raises(ValueError, match="resource_uri cannot be set on resources"): @server.resource( "ui://my-app/view.html", app=AppConfig(resource_uri="ui://other"), ) def app_html() -> str: return "<html>hello</html>" async def test_resource_rejects_visibility(self): """AppConfig with visibility raises ValueError on resources.""" server = FastMCP("test") with pytest.raises(ValueError, match="visibility cannot be set on resources"): @server.resource( "ui://my-app/view.html", app=AppConfig(visibility=["app"]), ) def app_html() -> str: return "<html>hello</html>" # --------------------------------------------------------------------------- # Extension advertisement # --------------------------------------------------------------------------- class TestExtensionAdvertisement: async def test_capabilities_include_ui_extension(self): server = FastMCP("test") @server.tool def my_tool() -> str: return "hello" async with Client(server) as client: init_result = client.initialize_result extras = init_result.capabilities.model_extra or {} extensions = extras.get("extensions", {}) assert UI_EXTENSION_ID in extensions # --------------------------------------------------------------------------- # Context.client_supports_extension # --------------------------------------------------------------------------- class TestContextClientSupportsExtension: async def test_returns_false_when_no_session(self): server = FastMCP("test") async with Context(fastmcp=server) as ctx: assert ctx.client_supports_extension(UI_EXTENSION_ID) is False # --------------------------------------------------------------------------- # Integration — full client↔server round-trip # --------------------------------------------------------------------------- class TestIntegration: async def test_tool_with_app_roundtrip(self): """App metadata flows through to clients — no server-side stripping.""" server = FastMCP("test") @server.tool( app=AppConfig(resource_uri="ui://app/view.html", visibility=["app"]) ) async def my_tool() -> dict[str, str]: return {"result": "ok"} async with Client(server) as client: tools = await client.list_tools() assert len(tools) == 1 # _meta.ui is preserved — the host decides what to do with it meta = tools[0].meta assert meta is not None assert meta["ui"]["resourceUri"] == "ui://app/view.html" assert meta["ui"]["visibility"] == ["app"] async def test_resource_with_ui_scheme_roundtrip(self): server = FastMCP("test") @server.resource("ui://my-app/view.html") def app_html() -> str: return "<html><body>Hello</body></html>" async with Client(server) as client: resources = await client.list_resources() assert len(resources) == 1 assert str(resources[0].uri) == "ui://my-app/view.html" assert resources[0].mimeType == UI_MIME_TYPE async def test_ui_resource_read_preserves_mime_type(self): """Reading a ui:// resource returns content with the correct MIME type.""" server = FastMCP("test") @server.resource("ui://my-app/view.html") def app_html() -> str: return "<html><body>Hello</body></html>" async with Client(server) as client: result = await client.read_resource_mcp("ui://my-app/view.html") assert len(result.contents) == 1 assert result.contents[0].mimeType == UI_MIME_TYPE async def test_app_tool_callable(self): """A tool registered with app= is still callable normally.""" server = FastMCP("test") @server.tool(app=AppConfig(resource_uri="ui://app")) async def greet(name: str) -> str: return f"Hello, {name}!" async with Client(server) as client: result = await client.call_tool("greet", {"name": "Alice"}) assert any("Hello, Alice!" in str(c) for c in result.content) async def test_extension_and_tool_together(self): """Server advertises extension AND tool has app meta.""" server = FastMCP("test") @server.tool(app=AppConfig(resource_uri="ui://dashboard", visibility=["app"])) def dashboard() -> str: return "data" tools = list(await server.list_tools()) assert tools[0].meta is not None assert tools[0].meta["ui"]["resourceUri"] == "ui://dashboard" async with Client(server) as client: extras = client.initialize_result.capabilities.model_extra or {} assert UI_EXTENSION_ID in extras.get("extensions", {}) async def test_csp_and_permissions_roundtrip(self): """CSP and permissions metadata flows through to clients correctly.""" server = FastMCP("test") @server.resource( "ui://secure-app/view.html", app=AppConfig( csp=ResourceCSP( resource_domains=["https://unpkg.com"], connect_domains=["https://api.example.com"], ), permissions=ResourcePermissions(microphone={}, clipboard_write={}), ), ) def secure_app() -> str: return "<html>secure</html>" @server.tool( app=AppConfig( resource_uri="ui://secure-app/view.html", csp=ResourceCSP(resource_domains=["https://cdn.example.com"]), permissions=ResourcePermissions(camera={}), ) ) def secure_tool() -> str: return "result" async with Client(server) as client: # Verify resource metadata resources = await client.list_resources() assert len(resources) == 1 meta = resources[0].meta assert meta is not None assert meta["ui"]["csp"]["resourceDomains"] == ["https://unpkg.com"] assert meta["ui"]["csp"]["connectDomains"] == ["https://api.example.com"] assert meta["ui"]["permissions"]["microphone"] == {} assert meta["ui"]["permissions"]["clipboardWrite"] == {} # Verify tool metadata tools = await client.list_tools() assert len(tools) == 1 tool_meta = tools[0].meta assert tool_meta is not None assert tool_meta["ui"]["csp"]["resourceDomains"] == [ "https://cdn.example.com" ] assert tool_meta["ui"]["permissions"]["camera"] == {} async def test_resource_read_propagates_meta_to_content_items(self): """resources/read must include _meta on content items so hosts can read CSP.""" server = FastMCP("test") @server.resource( "ui://csp-app/view.html", app=AppConfig( csp=ResourceCSP(resource_domains=["https://unpkg.com"]), ), ) def app_view() -> str: return "<html>app</html>" async with Client(server) as client: read_result = await client.read_resource_mcp("ui://csp-app/view.html") content_item = read_result.contents[0] assert content_item.meta is not None assert content_item.meta["ui"]["csp"]["resourceDomains"] == [ "https://unpkg.com" ]
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/test_apps.py", "license": "Apache License 2.0", "lines": 437, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/utilities/test_auth.py
"""Tests for authentication utility helpers.""" import base64 import json import pytest from fastmcp.utilities.auth import ( decode_jwt_header, decode_jwt_payload, parse_scopes, ) def create_jwt(header: dict, payload: dict, signature: bytes = b"fake-sig") -> str: """Create a test JWT token.""" header_b64 = base64.urlsafe_b64encode(json.dumps(header).encode()).rstrip(b"=") payload_b64 = base64.urlsafe_b64encode(json.dumps(payload).encode()).rstrip(b"=") sig_b64 = base64.urlsafe_b64encode(signature).rstrip(b"=") return f"{header_b64.decode()}.{payload_b64.decode()}.{sig_b64.decode()}" class TestDecodeJwtHeader: """Tests for decode_jwt_header utility.""" def test_decode_basic_header(self): """Test decoding a basic JWT header.""" header = {"alg": "RS256", "typ": "JWT"} payload = {"sub": "user-123"} token = create_jwt(header, payload) result = decode_jwt_header(token) assert result == header assert result["alg"] == "RS256" assert result["typ"] == "JWT" def test_decode_header_with_kid(self): """Test decoding header with key ID for JWKS lookup.""" header = {"alg": "RS256", "typ": "JWT", "kid": "key-id-123"} payload = {"sub": "user-123"} token = create_jwt(header, payload) result = decode_jwt_header(token) assert result["kid"] == "key-id-123" def test_invalid_jwt_format_two_parts(self): """Test that two-part token raises ValueError.""" with pytest.raises(ValueError, match="Invalid JWT format"): decode_jwt_header("header.payload") def test_invalid_jwt_format_one_part(self): """Test that single-part token raises ValueError.""" with pytest.raises(ValueError, match="Invalid JWT format"): decode_jwt_header("not-a-jwt") def test_invalid_jwt_format_four_parts(self): """Test that four-part token raises ValueError.""" with pytest.raises(ValueError, match="Invalid JWT format"): decode_jwt_header("a.b.c.d") def test_decode_header_length_divisible_by_4(self): """Test decoding when base64 length is divisible by 4 (no padding needed). This tests the edge case where len(part) % 4 == 0. The padding calculation (-len % 4) correctly yields 0 in this case. """ # Create a header that encodes to exactly 12 chars (divisible by 4) header = {"x": ""} # eyJ4IjogIiJ9 = 12 chars payload = {"sub": "user"} token = create_jwt(header, payload) result = decode_jwt_header(token) assert result == header class TestDecodeJwtPayload: """Tests for decode_jwt_payload utility.""" def test_decode_basic_payload(self): """Test decoding a basic JWT payload.""" header = {"alg": "RS256", "typ": "JWT"} payload = {"sub": "user-123", "name": "Test User"} token = create_jwt(header, payload) result = decode_jwt_payload(token) assert result == payload assert result["sub"] == "user-123" assert result["name"] == "Test User" def test_decode_payload_with_claims(self): """Test decoding payload with various claims.""" header = {"alg": "RS256"} payload = { "sub": "user-123", "oid": "object-456", "name": "Test User", "email": "test@example.com", "roles": ["admin", "user"], "exp": 1234567890, } token = create_jwt(header, payload) result = decode_jwt_payload(token) assert result["sub"] == "user-123" assert result["oid"] == "object-456" assert result["name"] == "Test User" assert result["email"] == "test@example.com" assert result["roles"] == ["admin", "user"] assert result["exp"] == 1234567890 def test_invalid_jwt_format(self): """Test that invalid format raises ValueError.""" with pytest.raises(ValueError, match="Invalid JWT format"): decode_jwt_payload("not-a-jwt") def test_decode_payload_with_padding_edge_cases(self): """Test that base64 padding is handled correctly.""" # Create payloads of different sizes to test padding for payload_size in [1, 2, 3, 4, 5, 10, 100]: payload = {"data": "x" * payload_size} token = create_jwt({"alg": "RS256"}, payload) result = decode_jwt_payload(token) assert result == payload def test_decode_payload_length_divisible_by_4(self): """Test decoding when base64 length is divisible by 4 (no padding needed). This tests the edge case where len(part) % 4 == 0. The padding calculation (-len % 4) correctly yields 0 in this case. """ # Create a payload that encodes to exactly 12 chars (divisible by 4) header = {"alg": "RS256"} payload = {"x": ""} # eyJ4IjogIiJ9 = 12 chars token = create_jwt(header, payload) result = decode_jwt_payload(token) assert result == payload class TestParseScopes: """Tests for parse_scopes utility.""" def test_parse_none(self): """Test that None returns None.""" assert parse_scopes(None) is None def test_parse_empty_string(self): """Test that empty string returns empty list.""" assert parse_scopes("") == [] def test_parse_space_separated(self): """Test parsing space-separated scopes.""" assert parse_scopes("read write delete") == ["read", "write", "delete"] def test_parse_comma_separated(self): """Test parsing comma-separated scopes.""" assert parse_scopes("read,write,delete") == ["read", "write", "delete"] def test_parse_json_array(self): """Test parsing JSON array string.""" assert parse_scopes('["read", "write", "delete"]') == [ "read", "write", "delete", ] def test_parse_list(self): """Test that list is returned as-is.""" assert parse_scopes(["read", "write"]) == ["read", "write"] def test_parse_strips_whitespace(self): """Test that whitespace is stripped.""" assert parse_scopes(" read , write ") == ["read", "write"]
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/utilities/test_auth.py", "license": "Apache License 2.0", "lines": 136, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:examples/skills/download_skills.py
"""Example: Downloading skills from an MCP server. This example shows how to use the skills client utilities to discover and download skills from any MCP server that exposes them via SkillsProvider. Run this script: uv run python examples/skills/download_skills.py This example creates an in-memory server with sample skills. In practice, you would connect to a remote server URL instead. """ import asyncio import tempfile from pathlib import Path from rich.console import Console from rich.panel import Panel from rich.table import Table from rich.tree import Tree from fastmcp import Client, FastMCP from fastmcp.server.providers.skills import SkillsDirectoryProvider from fastmcp.utilities.skills import list_skills, sync_skills console = Console() async def main(): # For this example, we'll create an in-memory server with skills. # In practice, you'd connect to a remote server URL. skills_dir = Path(__file__).parent / "sample_skills" mcp = FastMCP("Skills Server") mcp.add_provider(SkillsDirectoryProvider(roots=skills_dir)) async with Client(mcp) as client: # 1. Discover what skills are available on the server console.print() console.print( Panel.fit( "[bold]Discovering skills on MCP server...[/bold]", border_style="blue", ) ) skills = await list_skills(client) table = Table(title="Skills Available on Server", show_header=True) table.add_column("Skill", style="cyan") table.add_column("Description") for skill in sorted(skills, key=lambda s: s.name): table.add_row(skill.name, skill.description) console.print(table) # 2. Download all skills to a local directory console.print() console.print( Panel.fit( "[bold]Downloading all skills to local directory...[/bold]", border_style="green", ) ) with tempfile.TemporaryDirectory() as tmp: paths = await sync_skills(client, tmp) tree = Tree(f"[bold]{tmp}[/bold]") for skill_path in sorted(paths, key=lambda p: p.name): skill_branch = tree.add(f"[cyan]{skill_path.name}/[/cyan]") for f in sorted(skill_path.rglob("*")): if f.is_file(): rel = f.relative_to(skill_path) skill_branch.add(str(rel)) console.print(tree) console.print( f"\n[green]✓[/green] Downloaded {len(paths)} skills to local directory" ) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/skills/download_skills.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/utilities/skills.py
"""Client utilities for discovering and downloading skills from MCP servers.""" from __future__ import annotations import base64 import json from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING import mcp.types if TYPE_CHECKING: from fastmcp.client import Client @dataclass class SkillSummary: """Summary information about a skill available on a server.""" name: str description: str uri: str @dataclass class SkillFile: """Information about a file within a skill.""" path: str size: int hash: str @dataclass class SkillManifest: """Full manifest of a skill including all files.""" name: str files: list[SkillFile] async def list_skills(client: Client) -> list[SkillSummary]: """List all available skills from an MCP server. Discovers skills by finding resources with URIs matching the `skill://{name}/SKILL.md` pattern. Args: client: Connected FastMCP client Returns: List of SkillSummary objects with name, description, and URI Example: ```python from fastmcp import Client from fastmcp.utilities.skills import list_skills async with Client("http://skills-server/mcp") as client: skills = await list_skills(client) for skill in skills: print(f"{skill.name}: {skill.description}") ``` """ resources = await client.list_resources() skills = [] for resource in resources: uri = str(resource.uri) # Match skill://{name}/SKILL.md pattern if uri.startswith("skill://") and uri.endswith("/SKILL.md"): # Extract skill name from URI path_part = uri[len("skill://") :] name = path_part.rsplit("/", 1)[0] skills.append( SkillSummary( name=name, description=resource.description or "", uri=uri, ) ) return skills async def get_skill_manifest(client: Client, skill_name: str) -> SkillManifest: """Get the manifest for a specific skill. Args: client: Connected FastMCP client skill_name: Name of the skill Returns: SkillManifest with file listing Raises: ValueError: If manifest cannot be read or parsed """ manifest_uri = f"skill://{skill_name}/_manifest" result = await client.read_resource(manifest_uri) if not result: raise ValueError(f"Could not read manifest for skill: {skill_name}") content = result[0] if isinstance(content, mcp.types.TextResourceContents): try: manifest_data = json.loads(content.text) except json.JSONDecodeError as e: raise ValueError(f"Invalid manifest JSON for skill: {skill_name}") from e else: raise ValueError(f"Unexpected manifest format for skill: {skill_name}") try: return SkillManifest( name=manifest_data["skill"], files=[ SkillFile(path=f["path"], size=f["size"], hash=f["hash"]) for f in manifest_data["files"] ], ) except (KeyError, TypeError) as e: raise ValueError(f"Invalid manifest format for skill: {skill_name}") from e async def download_skill( client: Client, skill_name: str, target_dir: str | Path, *, overwrite: bool = False, ) -> Path: """Download a skill and all its files to a local directory. Creates a subdirectory named after the skill containing all files. Args: client: Connected FastMCP client skill_name: Name of the skill to download target_dir: Directory where skill folder will be created overwrite: If True, overwrite existing skill directory. If False (default), raise FileExistsError if directory exists. Returns: Path to the downloaded skill directory Raises: ValueError: If skill cannot be found or downloaded FileExistsError: If skill directory exists and overwrite=False Example: ```python from fastmcp import Client from fastmcp.utilities.skills import download_skill async with Client("http://skills-server/mcp") as client: skill_path = await download_skill( client, "pdf-processing", "~/.claude/skills" ) print(f"Downloaded to: {skill_path}") ``` """ target_dir = Path(target_dir).expanduser().resolve() skill_dir = target_dir / skill_name # Check if directory exists if skill_dir.exists() and not overwrite: raise FileExistsError( f"Skill directory already exists: {skill_dir}. " "Use overwrite=True to replace." ) # Get manifest to know what files to download manifest = await get_skill_manifest(client, skill_name) # Create skill directory skill_dir.mkdir(parents=True, exist_ok=True) # Download each file for file_info in manifest.files: # Security: reject absolute paths and paths that escape skill_dir if Path(file_info.path).is_absolute(): continue file_path = (skill_dir / file_info.path).resolve() if not file_path.is_relative_to(skill_dir): continue file_uri = f"skill://{skill_name}/{file_info.path}" result = await client.read_resource(file_uri) if not result: continue content = result[0] # Create parent directories if needed file_path.parent.mkdir(parents=True, exist_ok=True) # Write content if isinstance(content, mcp.types.TextResourceContents): file_path.write_text(content.text) elif isinstance(content, mcp.types.BlobResourceContents): file_path.write_bytes(base64.b64decode(content.blob)) else: # Skip unknown content types continue return skill_dir async def sync_skills( client: Client, target_dir: str | Path, *, overwrite: bool = False, ) -> list[Path]: """Download all available skills from a server. Args: client: Connected FastMCP client target_dir: Directory where skill folders will be created overwrite: If True, overwrite existing files Returns: List of paths to downloaded skill directories Example: ```python from fastmcp import Client from fastmcp.utilities.skills import sync_skills async with Client("http://skills-server/mcp") as client: paths = await sync_skills(client, "~/.claude/skills") print(f"Downloaded {len(paths)} skills") ``` """ skills = await list_skills(client) downloaded = [] for skill in skills: try: path = await download_skill( client, skill.name, target_dir, overwrite=overwrite ) downloaded.append(path) except FileExistsError: # Skip existing skills when not overwriting continue return downloaded
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/utilities/skills.py", "license": "Apache License 2.0", "lines": 197, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:tests/utilities/test_skills.py
"""Tests for skills client utilities.""" from __future__ import annotations from pathlib import Path import pytest from fastmcp import Client, FastMCP from fastmcp.server.providers.skills import SkillsDirectoryProvider from fastmcp.utilities.skills import ( SkillFile, SkillManifest, SkillSummary, download_skill, get_skill_manifest, list_skills, sync_skills, ) @pytest.fixture def skills_dir(tmp_path: Path) -> Path: """Create a temporary skills directory with sample skills.""" skills = tmp_path / "skills" skills.mkdir() # Create pdf-processing skill pdf_skill = skills / "pdf-processing" pdf_skill.mkdir() (pdf_skill / "SKILL.md").write_text( """--- description: Process PDF documents --- # PDF Processing Instructions for PDF handling. """ ) (pdf_skill / "reference.md").write_text("# Reference\n\nSome reference docs.") # Create code-review skill code_skill = skills / "code-review" code_skill.mkdir() (code_skill / "SKILL.md").write_text( """--- description: Review code for quality --- # Code Review Instructions for reviewing code. """ ) # Create skill with nested files nested_skill = skills / "nested-skill" nested_skill.mkdir() (nested_skill / "SKILL.md").write_text("# Nested\n\nHas nested files.") scripts = nested_skill / "scripts" scripts.mkdir() (scripts / "helper.py").write_text("# Helper script\nprint('hello')") return skills @pytest.fixture def skills_server(skills_dir: Path) -> FastMCP: """Create a FastMCP server with skills provider.""" mcp = FastMCP("Skills Server") mcp.add_provider(SkillsDirectoryProvider(roots=skills_dir)) return mcp class TestListSkills: async def test_lists_available_skills(self, skills_server: FastMCP): async with Client(skills_server) as client: skills = await list_skills(client) assert len(skills) == 3 names = {s.name for s in skills} assert names == {"pdf-processing", "code-review", "nested-skill"} async def test_returns_skill_summary_objects(self, skills_server: FastMCP): async with Client(skills_server) as client: skills = await list_skills(client) for skill in skills: assert isinstance(skill, SkillSummary) assert skill.name assert skill.uri.startswith("skill://") assert skill.uri.endswith("/SKILL.md") async def test_includes_descriptions(self, skills_server: FastMCP): async with Client(skills_server) as client: skills = await list_skills(client) by_name = {s.name: s for s in skills} assert by_name["pdf-processing"].description == "Process PDF documents" assert by_name["code-review"].description == "Review code for quality" async def test_empty_server_returns_empty_list(self): mcp = FastMCP("Empty") async with Client(mcp) as client: skills = await list_skills(client) assert skills == [] class TestGetSkillManifest: async def test_returns_manifest_with_files(self, skills_server: FastMCP): async with Client(skills_server) as client: manifest = await get_skill_manifest(client, "pdf-processing") assert isinstance(manifest, SkillManifest) assert manifest.name == "pdf-processing" assert len(manifest.files) == 2 paths = {f.path for f in manifest.files} assert paths == {"SKILL.md", "reference.md"} async def test_files_have_size_and_hash(self, skills_server: FastMCP): async with Client(skills_server) as client: manifest = await get_skill_manifest(client, "pdf-processing") for file in manifest.files: assert isinstance(file, SkillFile) assert file.size > 0 assert file.hash.startswith("sha256:") async def test_nested_files_use_posix_paths(self, skills_server: FastMCP): async with Client(skills_server) as client: manifest = await get_skill_manifest(client, "nested-skill") paths = {f.path for f in manifest.files} assert "scripts/helper.py" in paths async def test_nonexistent_skill_raises(self, skills_server: FastMCP): async with Client(skills_server) as client: with pytest.raises(Exception): await get_skill_manifest(client, "nonexistent") class TestDownloadSkill: async def test_downloads_skill_to_directory( self, skills_server: FastMCP, tmp_path: Path ): target = tmp_path / "downloaded" target.mkdir() async with Client(skills_server) as client: result = await download_skill(client, "pdf-processing", target) assert result == target / "pdf-processing" assert result.exists() assert (result / "SKILL.md").exists() assert (result / "reference.md").exists() async def test_creates_nested_directories( self, skills_server: FastMCP, tmp_path: Path ): target = tmp_path / "downloaded" target.mkdir() async with Client(skills_server) as client: result = await download_skill(client, "nested-skill", target) assert (result / "scripts" / "helper.py").exists() content = (result / "scripts" / "helper.py").read_text() assert "print('hello')" in content async def test_preserves_file_content( self, skills_server: FastMCP, tmp_path: Path, skills_dir: Path ): target = tmp_path / "downloaded" target.mkdir() async with Client(skills_server) as client: result = await download_skill(client, "pdf-processing", target) original = (skills_dir / "pdf-processing" / "SKILL.md").read_text() downloaded = (result / "SKILL.md").read_text() assert downloaded == original async def test_raises_if_exists_without_overwrite( self, skills_server: FastMCP, tmp_path: Path ): target = tmp_path / "downloaded" target.mkdir() (target / "pdf-processing").mkdir() async with Client(skills_server) as client: with pytest.raises(FileExistsError): await download_skill(client, "pdf-processing", target) async def test_overwrites_with_flag(self, skills_server: FastMCP, tmp_path: Path): target = tmp_path / "downloaded" target.mkdir() existing = target / "pdf-processing" existing.mkdir() (existing / "old-file.txt").write_text("old content") async with Client(skills_server) as client: result = await download_skill( client, "pdf-processing", target, overwrite=True ) assert (result / "SKILL.md").exists() async def test_expands_user_path(self, skills_server: FastMCP, tmp_path: Path): # This tests that ~ expansion works (though we can't actually test ~) async with Client(skills_server) as client: result = await download_skill(client, "code-review", tmp_path) assert result.exists() class TestSyncSkills: async def test_downloads_all_skills(self, skills_server: FastMCP, tmp_path: Path): target = tmp_path / "synced" target.mkdir() async with Client(skills_server) as client: results = await sync_skills(client, target) assert len(results) == 3 assert (target / "pdf-processing").exists() assert (target / "code-review").exists() assert (target / "nested-skill").exists() async def test_skips_existing_without_overwrite( self, skills_server: FastMCP, tmp_path: Path ): target = tmp_path / "synced" target.mkdir() (target / "pdf-processing").mkdir() async with Client(skills_server) as client: results = await sync_skills(client, target) # Should skip pdf-processing, download the other two assert len(results) == 2 names = {r.name for r in results} assert "pdf-processing" not in names async def test_overwrites_with_flag(self, skills_server: FastMCP, tmp_path: Path): target = tmp_path / "synced" target.mkdir() (target / "pdf-processing").mkdir() async with Client(skills_server) as client: results = await sync_skills(client, target, overwrite=True) assert len(results) == 3 async def test_returns_paths_to_downloaded_skills( self, skills_server: FastMCP, tmp_path: Path ): target = tmp_path / "synced" target.mkdir() async with Client(skills_server) as client: results = await sync_skills(client, target) for path in results: assert isinstance(path, Path) assert path.exists() assert (path / "SKILL.md").exists()
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/utilities/test_skills.py", "license": "Apache License 2.0", "lines": 205, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:examples/skills/client.py
"""Example: Skills Client This example shows how to discover and download skills from a skills server. Run this client (it starts its own server internally): uv run python examples/skills/client.py """ import asyncio import json from pathlib import Path from fastmcp import Client from fastmcp.server.providers.skills import SkillsDirectoryProvider async def main(): # Create a skills provider pointing at our sample skills skills_dir = Path(__file__).parent / "sample_skills" provider = SkillsDirectoryProvider(roots=skills_dir) # Connect to a FastMCP server with this provider from fastmcp import FastMCP mcp = FastMCP("Skills Server") mcp.add_provider(provider) async with Client(mcp) as client: print("Connected to skills server\n") # List available resources print("=== Available Resources ===") resources = await client.list_resources() for r in resources: print(f" {r.uri}") if r.description: print(f" Description: {r.description}") print() # List resource templates print("=== Resource Templates ===") templates = await client.list_resource_templates() for t in templates: print(f" {t.uriTemplate}") print() # Read a skill's main file print("=== Reading pdf-processing/SKILL.md ===") result = await client.read_resource("skill://pdf-processing/SKILL.md") print(result[0].text[:500] + "...\n") # Read the manifest to see all files print("=== Reading pdf-processing/_manifest ===") result = await client.read_resource("skill://pdf-processing/_manifest") manifest = json.loads(result[0].text) print(json.dumps(manifest, indent=2)) print() # Read a supporting file via template print("=== Reading pdf-processing/reference.md ===") result = await client.read_resource("skill://pdf-processing/reference.md") print(result[0].text[:500] + "...\n") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/skills/client.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:examples/skills/server.py
"""Example: Skills Provider Server This example shows how to expose agent skills as MCP resources. Skills can be discovered, browsed, and downloaded by any MCP client. Run this server: uv run python examples/skills/server.py Then use the client example to interact with it: uv run python examples/skills/client.py """ from pathlib import Path from fastmcp import FastMCP from fastmcp.server.providers.skills import ( SkillsDirectoryProvider, ) # Create server mcp = FastMCP("Skills Server") # Option 1: Load a single skill # mcp.add_provider(SkillProvider(Path.home() / ".claude/skills/pdf-processing")) # Option 2: Load all skills from a custom directory skills_dir = Path(__file__).parent / "sample_skills" mcp.add_provider(SkillsDirectoryProvider(roots=skills_dir, reload=True)) # Option 3: Load skills from a platform's default location # mcp.add_provider(ClaudeSkillsProvider()) # ~/.claude/skills/ # Option 4: Load from multiple directories (in precedence order) # mcp.add_provider(SkillsDirectoryProvider(roots=[ # Path.cwd() / ".claude/skills", # Project-level first # Path.home() / ".claude/skills", # User-level fallback # ])) # Other vendor providers available: # - CursorSkillsProvider() → ~/.cursor/skills/ # - VSCodeSkillsProvider() → ~/.copilot/skills/ # - CodexSkillsProvider() → ~/.codex/skills/ # - GeminiSkillsProvider() → ~/.gemini/skills/ # - GooseSkillsProvider() → ~/.config/agents/skills/ # - CopilotSkillsProvider() → ~/.copilot/skills/ # - OpenCodeSkillsProvider() → ~/.config/opencode/skills/ if __name__ == "__main__": mcp.run()
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/skills/server.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:src/fastmcp/server/providers/skills/_common.py
"""Shared utilities and data structures for skills providers.""" from __future__ import annotations import hashlib import re from dataclasses import dataclass, field from pathlib import Path from typing import Any @dataclass class SkillFileInfo: """Information about a file within a skill.""" path: str # Relative path within skill directory size: int hash: str # sha256 hash @dataclass class SkillInfo: """Parsed information about a skill.""" name: str # Directory name (canonical identifier) description: str # From frontmatter or first line path: Path # Absolute path to skill directory main_file: str # Name of main file (e.g., "SKILL.md") files: list[SkillFileInfo] = field(default_factory=list) frontmatter: dict[str, Any] = field(default_factory=dict) def parse_frontmatter(content: str) -> tuple[dict[str, Any], str]: """Parse YAML frontmatter from markdown content. Args: content: Markdown content potentially starting with --- Returns: Tuple of (frontmatter dict, remaining content) """ if not content.startswith("---"): return {}, content # Find the closing --- end_match = re.search(r"\n---\s*\n", content[3:]) if not end_match: return {}, content frontmatter_text = content[3 : 3 + end_match.start()] remaining = content[3 + end_match.end() :] # Parse YAML (simple key: value parsing, no complex types) frontmatter: dict[str, Any] = {} for line in frontmatter_text.strip().split("\n"): if ":" in line: key, _, value = line.partition(":") key = key.strip() value = value.strip() # Handle quoted strings if (value.startswith('"') and value.endswith('"')) or ( value.startswith("'") and value.endswith("'") ): value = value[1:-1] # Handle lists [a, b, c] if value.startswith("[") and value.endswith("]"): items = value[1:-1].split(",") value = [item.strip().strip("\"'") for item in items if item.strip()] frontmatter[key] = value return frontmatter, remaining def compute_file_hash(path: Path) -> str: """Compute SHA256 hash of a file.""" sha256 = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(8192), b""): sha256.update(chunk) return f"sha256:{sha256.hexdigest()}" def scan_skill_files(skill_dir: Path) -> list[SkillFileInfo]: """Scan a skill directory for all files.""" files = [] resolved_skill_dir = skill_dir.resolve() # Sort for deterministic ordering across platforms for file_path in sorted(skill_dir.rglob("*")): if file_path.is_file(): resolved_file_path = file_path.resolve() if not resolved_file_path.is_relative_to(resolved_skill_dir): continue rel_path = file_path.relative_to(skill_dir) files.append( SkillFileInfo( # Use POSIX paths for cross-platform URI consistency path=rel_path.as_posix(), size=resolved_file_path.stat().st_size, hash=compute_file_hash(resolved_file_path), ) ) return files
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/server/providers/skills/_common.py", "license": "Apache License 2.0", "lines": 82, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:src/fastmcp/server/providers/skills/claude_provider.py
"""Claude-specific skills provider for Claude Code skills.""" from __future__ import annotations from pathlib import Path from typing import Literal from fastmcp.server.providers.skills.directory_provider import SkillsDirectoryProvider class ClaudeSkillsProvider(SkillsDirectoryProvider): """Provider for Claude Code skills from ~/.claude/skills/. A convenience subclass that sets the default root to Claude's skills location. Args: reload: If True, re-scan on every request. Defaults to False. supporting_files: How supporting files are exposed: - "template": Accessed via ResourceTemplate, hidden from list_resources(). - "resources": Each file exposed as individual Resource in list_resources(). Example: ```python from fastmcp import FastMCP from fastmcp.server.providers.skills import ClaudeSkillsProvider mcp = FastMCP("Claude Skills") mcp.add_provider(ClaudeSkillsProvider()) # Uses default location ``` """ def __init__( self, reload: bool = False, supporting_files: Literal["template", "resources"] = "template", ) -> None: root = Path.home() / ".claude" / "skills" super().__init__( roots=[root], reload=reload, main_file_name="SKILL.md", supporting_files=supporting_files, )
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/server/providers/skills/claude_provider.py", "license": "Apache License 2.0", "lines": 33, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
PrefectHQ/fastmcp:src/fastmcp/server/providers/skills/directory_provider.py
"""Directory scanning provider for discovering multiple skills.""" from __future__ import annotations from collections.abc import Sequence from pathlib import Path from typing import Literal from fastmcp.resources.resource import Resource from fastmcp.resources.template import ResourceTemplate from fastmcp.server.providers.aggregate import AggregateProvider from fastmcp.server.providers.skills.skill_provider import SkillProvider from fastmcp.utilities.logging import get_logger from fastmcp.utilities.versions import VersionSpec logger = get_logger(__name__) class SkillsDirectoryProvider(AggregateProvider): """Provider that scans directories and creates a SkillProvider per skill folder. This extends AggregateProvider to combine multiple SkillProviders into one. Each subdirectory containing a main file (default: SKILL.md) becomes a skill. Can scan multiple root directories - if a skill name appears in multiple roots, the first one found wins. Args: roots: Root directory(ies) containing skill folders. Can be a single path or a sequence of paths. reload: If True, re-discover skills on each request. Defaults to False. main_file_name: Name of the main skill file. Defaults to "SKILL.md". supporting_files: How supporting files are exposed in child SkillProviders: - "template": Accessed via ResourceTemplate, hidden from list_resources(). - "resources": Each file exposed as individual Resource in list_resources(). Example: ```python from pathlib import Path from fastmcp import FastMCP from fastmcp.server.providers.skills import SkillsDirectoryProvider mcp = FastMCP("Skills") # Single directory mcp.add_provider(SkillsDirectoryProvider( roots=Path.home() / ".claude" / "skills", reload=True, # Re-scan on each request )) # Multiple directories mcp.add_provider(SkillsDirectoryProvider( roots=[Path("/etc/skills"), Path.home() / ".local" / "skills"], )) ``` """ def __init__( self, roots: str | Path | Sequence[str | Path], reload: bool = False, main_file_name: str = "SKILL.md", supporting_files: Literal["template", "resources"] = "template", ) -> None: super().__init__() # Normalize to sequence: single path becomes list if isinstance(roots, (str, Path)): roots = [roots] self._roots = [Path(r).resolve() for r in roots] self._reload = reload self._main_file_name = main_file_name self._supporting_files = supporting_files self._discovered = False # Discover skills at init self._discover_skills() def _discover_skills(self) -> None: """Scan root directories and create SkillProvider per valid skill folder.""" # Clear existing providers if reloading self.providers.clear() seen_skill_names: set[str] = set() for root in self._roots: if not root.exists(): logger.debug(f"Skills root does not exist: {root}") continue for skill_dir in root.iterdir(): if not skill_dir.is_dir(): continue main_file = skill_dir / self._main_file_name if not main_file.exists(): continue skill_name = skill_dir.name # Skip if we've already seen this skill name (first wins) if skill_name in seen_skill_names: logger.debug( f"Skipping duplicate skill '{skill_name}' from {root} " f"(already found in earlier root)" ) continue try: provider = SkillProvider( skill_path=skill_dir, main_file_name=self._main_file_name, supporting_files=self._supporting_files, ) self.providers.append(provider) seen_skill_names.add(skill_name) except (FileNotFoundError, PermissionError, OSError): logger.exception(f"Failed to load skill: {skill_dir.name}") self._discovered = True logger.debug( f"SkillsDirectoryProvider loaded {len(self.providers)} skills " f"from {len(self._roots)} root(s)" ) async def _ensure_discovered(self) -> None: """Ensure skills are discovered, rediscovering if reload is enabled.""" if self._reload or not self._discovered: self._discover_skills() # Override list methods to support reload async def _list_resources(self) -> Sequence[Resource]: await self._ensure_discovered() return await super()._list_resources() async def _list_resource_templates(self) -> Sequence[ResourceTemplate]: await self._ensure_discovered() return await super()._list_resource_templates() async def _get_resource( self, uri: str, version: VersionSpec | None = None ) -> Resource | None: await self._ensure_discovered() return await super()._get_resource(uri, version) async def _get_resource_template( self, uri: str, version: VersionSpec | None = None ) -> ResourceTemplate | None: await self._ensure_discovered() return await super()._get_resource_template(uri, version) def __repr__(self) -> str: roots_repr = self._roots[0] if len(self._roots) == 1 else self._roots return ( f"SkillsDirectoryProvider(roots={roots_repr!r}, " f"reload={self._reload}, skills={len(self.providers)})" )
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/server/providers/skills/directory_provider.py", "license": "Apache License 2.0", "lines": 126, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:src/fastmcp/server/providers/skills/skill_provider.py
"""Basic skill provider for handling a single skill folder.""" from __future__ import annotations import json import mimetypes from collections.abc import Sequence from pathlib import Path from typing import Any, Literal, cast from pydantic import AnyUrl from fastmcp.resources.resource import Resource, ResourceResult from fastmcp.resources.template import ResourceTemplate from fastmcp.server.providers.base import Provider from fastmcp.server.providers.skills._common import ( SkillInfo, parse_frontmatter, scan_skill_files, ) from fastmcp.utilities.logging import get_logger from fastmcp.utilities.versions import VersionSpec logger = get_logger(__name__) # Ensure .md is recognized as text/markdown on all platforms (Windows may not have this) mimetypes.add_type("text/markdown", ".md") # ----------------------------------------------------------------------------- # Skill-specific Resource and ResourceTemplate subclasses # ----------------------------------------------------------------------------- class SkillResource(Resource): """A resource representing a skill's main file or manifest.""" skill_info: SkillInfo is_manifest: bool = False def get_meta(self) -> dict[str, Any]: meta = super().get_meta() fastmcp = cast(dict[str, Any], meta["fastmcp"]) fastmcp["skill"] = { "name": self.skill_info.name, "is_manifest": self.is_manifest, } return meta async def read(self) -> str | bytes | ResourceResult: """Read the resource content.""" if self.is_manifest: return self._generate_manifest() else: main_file_path = self.skill_info.path / self.skill_info.main_file return main_file_path.read_text() def _generate_manifest(self) -> str: """Generate JSON manifest for the skill.""" manifest = { "skill": self.skill_info.name, "files": [ {"path": f.path, "size": f.size, "hash": f.hash} for f in self.skill_info.files ], } return json.dumps(manifest, indent=2) class SkillFileTemplate(ResourceTemplate): """A template for accessing files within a skill.""" skill_info: SkillInfo async def read(self, arguments: dict[str, Any]) -> str | bytes | ResourceResult: """Read a file from the skill directory.""" file_path = arguments.get("path", "") full_path = self.skill_info.path / file_path # Security: ensure path doesn't escape skill directory try: full_path = full_path.resolve() if not full_path.is_relative_to(self.skill_info.path): raise ValueError(f"Path {file_path} escapes skill directory") except ValueError as e: raise ValueError(f"Invalid path: {e}") from e if not full_path.exists(): raise FileNotFoundError(f"File not found: {file_path}") if not full_path.is_file(): raise ValueError(f"Not a file: {file_path}") # Determine if binary or text based on mime type mime_type, _ = mimetypes.guess_type(str(full_path)) if mime_type and mime_type.startswith("text/"): return full_path.read_text() else: return full_path.read_bytes() async def _read( # type: ignore[override] self, uri: str, params: dict[str, Any], task_meta: Any = None, ) -> ResourceResult: """Server entry point - read file directly without creating ephemeral resource. Note: task_meta is ignored - this template doesn't support background tasks. """ # Call read() directly and convert to ResourceResult result = await self.read(arguments=params) return self.convert_result(result) async def create_resource(self, uri: str, params: dict[str, Any]) -> Resource: """Create a resource for the given URI and parameters. Note: This is not typically used since _read() handles file reading directly. Provided for compatibility with the ResourceTemplate interface. """ file_path = params.get("path", "") full_path = (self.skill_info.path / file_path).resolve() # Security: ensure path doesn't escape skill directory if not full_path.is_relative_to(self.skill_info.path): raise ValueError(f"Path {file_path} escapes skill directory") mime_type, _ = mimetypes.guess_type(str(full_path)) # Create a SkillFileResource that can read the file return SkillFileResource( uri=AnyUrl(uri), name=f"{self.skill_info.name}/{file_path}", description=f"File from {self.skill_info.name} skill", mime_type=mime_type or "application/octet-stream", skill_info=self.skill_info, file_path=file_path, ) class SkillFileResource(Resource): """A resource representing a specific file within a skill.""" skill_info: SkillInfo file_path: str def get_meta(self) -> dict[str, Any]: meta = super().get_meta() fastmcp = cast(dict[str, Any], meta["fastmcp"]) fastmcp["skill"] = { "name": self.skill_info.name, } return meta async def read(self) -> str | bytes | ResourceResult: """Read the file content.""" full_path = self.skill_info.path / self.file_path # Security check full_path = full_path.resolve() if not full_path.is_relative_to(self.skill_info.path): raise ValueError(f"Path {self.file_path} escapes skill directory") if not full_path.exists(): raise FileNotFoundError(f"File not found: {self.file_path}") mime_type, _ = mimetypes.guess_type(str(full_path)) if mime_type and mime_type.startswith("text/"): return full_path.read_text() else: return full_path.read_bytes() # ----------------------------------------------------------------------------- # SkillProvider - handles a SINGLE skill folder # ----------------------------------------------------------------------------- class SkillProvider(Provider): """Provider that exposes a single skill folder as MCP resources. Each skill folder must contain a main file (default: SKILL.md) and may contain additional supporting files. Exposes: - A Resource for the main file (skill://{name}/SKILL.md) - A Resource for the synthetic manifest (skill://{name}/_manifest) - Supporting files via ResourceTemplate or Resources (configurable) Args: skill_path: Path to the skill directory. main_file_name: Name of the main skill file. Defaults to "SKILL.md". supporting_files: How supporting files (everything except main file and manifest) are exposed to clients: - "template": Accessed via ResourceTemplate, hidden from list_resources(). Clients discover files by reading the manifest first. - "resources": Each file exposed as individual Resource in list_resources(). Full enumeration upfront. Example: ```python from pathlib import Path from fastmcp import FastMCP from fastmcp.server.providers.skills import SkillProvider mcp = FastMCP("My Skill") mcp.add_provider(SkillProvider( Path.home() / ".claude/skills/pdf-processing" )) ``` """ def __init__( self, skill_path: str | Path, main_file_name: str = "SKILL.md", supporting_files: Literal["template", "resources"] = "template", ) -> None: super().__init__() self._skill_path = Path(skill_path).resolve() self._main_file_name = main_file_name self._supporting_files = supporting_files self._skill_info: SkillInfo | None = None # Load at init to catch errors early self._load_skill() def _load_skill(self) -> None: """Load and parse the skill directory.""" main_file = self._skill_path / self._main_file_name if not self._skill_path.exists(): raise FileNotFoundError(f"Skill directory not found: {self._skill_path}") if not main_file.exists(): raise FileNotFoundError( f"Main skill file not found: {main_file}. " f"Expected {self._main_file_name} in {self._skill_path}" ) content = main_file.read_text() frontmatter, body = parse_frontmatter(content) # Get description from frontmatter or first non-empty line description = frontmatter.get("description", "") if not description: for line in body.strip().split("\n"): line = line.strip() if line and not line.startswith("#"): description = line[:200] break elif line.startswith("#"): description = line.lstrip("#").strip()[:200] break # Scan all files in the skill directory files = scan_skill_files(self._skill_path) self._skill_info = SkillInfo( name=self._skill_path.name, description=description or f"Skill: {self._skill_path.name}", path=self._skill_path, main_file=self._main_file_name, files=files, frontmatter=frontmatter, ) logger.debug(f"SkillProvider loaded skill: {self._skill_info.name}") @property def skill_info(self) -> SkillInfo: """Get the loaded skill info.""" if self._skill_info is None: raise RuntimeError("Skill not loaded") return self._skill_info # ------------------------------------------------------------------------- # Provider interface implementation # ------------------------------------------------------------------------- async def _list_resources(self) -> Sequence[Resource]: """List skill resources.""" skill = self.skill_info resources: list[Resource] = [] # Main skill file resources.append( SkillResource( uri=AnyUrl(f"skill://{skill.name}/{self._main_file_name}"), name=f"{skill.name}/{self._main_file_name}", description=skill.description, mime_type="text/markdown", skill_info=skill, is_manifest=False, ) ) # Synthetic manifest resources.append( SkillResource( uri=AnyUrl(f"skill://{skill.name}/_manifest"), name=f"{skill.name}/_manifest", description=f"File listing for {skill.name}", mime_type="application/json", skill_info=skill, is_manifest=True, ) ) # If supporting_files="resources", add all supporting files as resources if self._supporting_files == "resources": for file_info in skill.files: # Skip main file and manifest (already added) if file_info.path == self._main_file_name: continue mime_type, _ = mimetypes.guess_type(file_info.path) resources.append( SkillFileResource( uri=AnyUrl(f"skill://{skill.name}/{file_info.path}"), name=f"{skill.name}/{file_info.path}", description=f"File from {skill.name} skill", mime_type=mime_type or "application/octet-stream", skill_info=skill, file_path=file_info.path, ) ) return resources async def _get_resource( self, uri: str, version: VersionSpec | None = None ) -> Resource | None: """Get a resource by URI.""" skill = self.skill_info # Parse URI: skill://{skill_name}/{file_path} if not uri.startswith("skill://"): return None path_part = uri[len("skill://") :] parts = path_part.split("/", 1) if len(parts) != 2: return None skill_name, file_path = parts if skill_name != skill.name: return None if file_path == "_manifest": return SkillResource( uri=AnyUrl(uri), name=f"{skill_name}/_manifest", description=f"File listing for {skill_name}", mime_type="application/json", skill_info=skill, is_manifest=True, ) elif file_path == self._main_file_name: return SkillResource( uri=AnyUrl(uri), name=f"{skill_name}/{self._main_file_name}", description=skill.description, mime_type="text/markdown", skill_info=skill, is_manifest=False, ) elif self._supporting_files == "resources": # Check if it's a known supporting file for file_info in skill.files: if file_info.path == file_path: mime_type, _ = mimetypes.guess_type(file_path) return SkillFileResource( uri=AnyUrl(uri), name=f"{skill_name}/{file_path}", description=f"File from {skill_name} skill", mime_type=mime_type or "application/octet-stream", skill_info=skill, file_path=file_path, ) return None async def _list_resource_templates(self) -> Sequence[ResourceTemplate]: """List resource templates for accessing files within the skill.""" # Only expose template if supporting_files="template" if self._supporting_files != "template": return [] skill = self.skill_info return [ SkillFileTemplate( uri_template=f"skill://{skill.name}/{{path*}}", name=f"{skill.name}_files", description=f"Access files within {skill.name}", mime_type="application/octet-stream", parameters={ "type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"], }, skill_info=skill, ) ] async def _get_resource_template( self, uri: str, version: VersionSpec | None = None ) -> ResourceTemplate | None: """Get a resource template that matches the given URI.""" # Only match if supporting_files="template" if self._supporting_files != "template": return None skill = self.skill_info if not uri.startswith("skill://"): return None path_part = uri[len("skill://") :] parts = path_part.split("/", 1) if len(parts) != 2: return None skill_name, file_path = parts if skill_name != skill.name: return None # Don't match known resources (main file, manifest) if file_path == "_manifest" or file_path == self._main_file_name: return None return SkillFileTemplate( uri_template=f"skill://{skill.name}/{{path*}}", name=f"{skill.name}_files", description=f"Access files within {skill.name}", mime_type="application/octet-stream", parameters={ "type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"], }, skill_info=skill, ) def __repr__(self) -> str: return ( f"SkillProvider(skill_path={self._skill_path!r}, " f"supporting_files={self._supporting_files!r})" )
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/server/providers/skills/skill_provider.py", "license": "Apache License 2.0", "lines": 369, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:src/fastmcp/server/providers/skills/vendor_providers.py
"""Vendor-specific skills providers for various AI coding platforms.""" from __future__ import annotations from pathlib import Path from typing import Literal from fastmcp.server.providers.skills.directory_provider import SkillsDirectoryProvider class CursorSkillsProvider(SkillsDirectoryProvider): """Cursor skills from ~/.cursor/skills/.""" def __init__( self, reload: bool = False, supporting_files: Literal["template", "resources"] = "template", ) -> None: root = Path.home() / ".cursor" / "skills" super().__init__( roots=[root], reload=reload, main_file_name="SKILL.md", supporting_files=supporting_files, ) class VSCodeSkillsProvider(SkillsDirectoryProvider): """VS Code skills from ~/.copilot/skills/.""" def __init__( self, reload: bool = False, supporting_files: Literal["template", "resources"] = "template", ) -> None: root = Path.home() / ".copilot" / "skills" super().__init__( roots=[root], reload=reload, main_file_name="SKILL.md", supporting_files=supporting_files, ) class CodexSkillsProvider(SkillsDirectoryProvider): """Codex skills from /etc/codex/skills/ and ~/.codex/skills/. Scans both system-level and user-level directories. System skills take precedence if duplicates exist. """ def __init__( self, reload: bool = False, supporting_files: Literal["template", "resources"] = "template", ) -> None: system_root = Path("/etc/codex/skills") user_root = Path.home() / ".codex" / "skills" # Include both paths (system first, then user) roots = [system_root, user_root] super().__init__( roots=roots, reload=reload, main_file_name="SKILL.md", supporting_files=supporting_files, ) class GeminiSkillsProvider(SkillsDirectoryProvider): """Gemini skills from ~/.gemini/skills/.""" def __init__( self, reload: bool = False, supporting_files: Literal["template", "resources"] = "template", ) -> None: root = Path.home() / ".gemini" / "skills" super().__init__( roots=[root], reload=reload, main_file_name="SKILL.md", supporting_files=supporting_files, ) class GooseSkillsProvider(SkillsDirectoryProvider): """Goose skills from ~/.config/agents/skills/.""" def __init__( self, reload: bool = False, supporting_files: Literal["template", "resources"] = "template", ) -> None: root = Path.home() / ".config" / "agents" / "skills" super().__init__( roots=[root], reload=reload, main_file_name="SKILL.md", supporting_files=supporting_files, ) class CopilotSkillsProvider(SkillsDirectoryProvider): """GitHub Copilot skills from ~/.copilot/skills/.""" def __init__( self, reload: bool = False, supporting_files: Literal["template", "resources"] = "template", ) -> None: root = Path.home() / ".copilot" / "skills" super().__init__( roots=[root], reload=reload, main_file_name="SKILL.md", supporting_files=supporting_files, ) class OpenCodeSkillsProvider(SkillsDirectoryProvider): """OpenCode skills from ~/.config/opencode/skills/.""" def __init__( self, reload: bool = False, supporting_files: Literal["template", "resources"] = "template", ) -> None: root = Path.home() / ".config" / "opencode" / "skills" super().__init__( roots=[root], reload=reload, main_file_name="SKILL.md", supporting_files=supporting_files, )
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/server/providers/skills/vendor_providers.py", "license": "Apache License 2.0", "lines": 109, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
PrefectHQ/fastmcp:tests/server/providers/test_skills_provider.py
"""Tests for SkillProvider, SkillsDirectoryProvider, and ClaudeSkillsProvider.""" import json from pathlib import Path import pytest from mcp.types import TextResourceContents from pydantic import AnyUrl from fastmcp import Client, FastMCP from fastmcp.server.providers.skills import ( ClaudeSkillsProvider, SkillProvider, SkillsDirectoryProvider, SkillsProvider, ) from fastmcp.server.providers.skills._common import parse_frontmatter class TestParseFrontmatter: def test_no_frontmatter(self): content = "# Just markdown\n\nSome content." frontmatter, body = parse_frontmatter(content) assert frontmatter == {} assert body == content def test_basic_frontmatter(self): content = """--- description: A test skill version: "1.0.0" --- # Skill Content """ frontmatter, body = parse_frontmatter(content) assert frontmatter["description"] == "A test skill" assert frontmatter["version"] == "1.0.0" assert body.strip().startswith("# Skill Content") def test_frontmatter_with_tags_list(self): content = """--- description: Test tags: [tag1, tag2, tag3] --- Content """ frontmatter, body = parse_frontmatter(content) assert frontmatter["tags"] == ["tag1", "tag2", "tag3"] def test_frontmatter_with_quoted_strings(self): content = """--- description: "A skill with quotes" version: '2.0.0' --- Content """ frontmatter, body = parse_frontmatter(content) assert frontmatter["description"] == "A skill with quotes" assert frontmatter["version"] == "2.0.0" class TestSkillProvider: """Tests for SkillProvider - single skill folder.""" @pytest.fixture def single_skill_dir(self, tmp_path: Path) -> Path: """Create a single skill directory with files.""" skill_dir = tmp_path / "my-skill" skill_dir.mkdir() (skill_dir / "SKILL.md").write_text( """--- description: A test skill version: "1.0.0" --- # My Skill This is my skill content. """ ) (skill_dir / "reference.md").write_text("# Reference\n\nExtra docs.") (skill_dir / "scripts").mkdir() (skill_dir / "scripts" / "helper.py").write_text('print("helper")') return skill_dir def test_loads_skill_at_init(self, single_skill_dir: Path): provider = SkillProvider(skill_path=single_skill_dir) assert provider.skill_info.name == "my-skill" assert provider.skill_info.description == "A test skill" assert len(provider.skill_info.files) == 3 def test_raises_if_directory_missing(self, tmp_path: Path): with pytest.raises(FileNotFoundError, match="Skill directory not found"): SkillProvider(skill_path=tmp_path / "nonexistent") def test_raises_if_main_file_missing(self, tmp_path: Path): skill_dir = tmp_path / "no-main" skill_dir.mkdir() with pytest.raises(FileNotFoundError, match="Main skill file not found"): SkillProvider(skill_path=skill_dir) async def test_list_resources_default_template_mode(self, single_skill_dir: Path): """In template mode (default), only main file and manifest are resources.""" provider = SkillProvider(skill_path=single_skill_dir) resources = await provider.list_resources() assert len(resources) == 2 names = {r.name for r in resources} assert "my-skill/SKILL.md" in names assert "my-skill/_manifest" in names async def test_list_resources_supporting_files_as_resources( self, single_skill_dir: Path ): """In resources mode, supporting files are also exposed as resources.""" provider = SkillProvider( skill_path=single_skill_dir, supporting_files="resources" ) resources = await provider.list_resources() # 2 standard + 2 supporting files assert len(resources) == 4 names = {r.name for r in resources} assert "my-skill/SKILL.md" in names assert "my-skill/_manifest" in names assert "my-skill/reference.md" in names assert "my-skill/scripts/helper.py" in names async def test_list_templates_default_mode(self, single_skill_dir: Path): """In template mode (default), one template is exposed.""" provider = SkillProvider(skill_path=single_skill_dir) templates = await provider.list_resource_templates() assert len(templates) == 1 assert templates[0].name == "my-skill_files" async def test_list_templates_resources_mode(self, single_skill_dir: Path): """In resources mode, no templates are exposed.""" provider = SkillProvider( skill_path=single_skill_dir, supporting_files="resources" ) templates = await provider.list_resource_templates() assert templates == [] async def test_read_main_file(self, single_skill_dir: Path): mcp = FastMCP("Test") mcp.add_provider(SkillProvider(skill_path=single_skill_dir)) async with Client(mcp) as client: result = await client.read_resource(AnyUrl("skill://my-skill/SKILL.md")) assert len(result) == 1 assert isinstance(result[0], TextResourceContents) assert "# My Skill" in result[0].text async def test_read_manifest(self, single_skill_dir: Path): mcp = FastMCP("Test") mcp.add_provider(SkillProvider(skill_path=single_skill_dir)) async with Client(mcp) as client: result = await client.read_resource(AnyUrl("skill://my-skill/_manifest")) manifest = json.loads(result[0].text) assert manifest["skill"] == "my-skill" assert len(manifest["files"]) == 3 paths = {f["path"] for f in manifest["files"]} assert "SKILL.md" in paths assert "reference.md" in paths assert "scripts/helper.py" in paths async def test_manifest_ignores_symlink_target_outside_skill(self, tmp_path: Path): skill_dir = tmp_path / "symlinked-skill" skill_dir.mkdir() (skill_dir / "SKILL.md").write_text("# Skill\n") outside_file = tmp_path / "outside.txt" outside_file.write_text("secret") (skill_dir / "leak.txt").symlink_to(outside_file) mcp = FastMCP("Test") mcp.add_provider(SkillProvider(skill_path=skill_dir)) async with Client(mcp) as client: result = await client.read_resource( AnyUrl("skill://symlinked-skill/_manifest") ) manifest = json.loads(result[0].text) paths = {f["path"] for f in manifest["files"]} assert "SKILL.md" in paths assert "leak.txt" not in paths async def test_read_supporting_file_via_template(self, single_skill_dir: Path): mcp = FastMCP("Test") mcp.add_provider(SkillProvider(skill_path=single_skill_dir)) async with Client(mcp) as client: result = await client.read_resource(AnyUrl("skill://my-skill/reference.md")) assert "# Reference" in result[0].text async def test_read_supporting_file_via_resource_mode(self, single_skill_dir: Path): mcp = FastMCP("Test") mcp.add_provider( SkillProvider(skill_path=single_skill_dir, supporting_files="resources") ) async with Client(mcp) as client: result = await client.read_resource(AnyUrl("skill://my-skill/reference.md")) assert "# Reference" in result[0].text async def test_skill_resource_meta(self, single_skill_dir: Path): """SkillResource populates meta with skill name and is_manifest.""" provider = SkillProvider(skill_path=single_skill_dir) resources = await provider.list_resources() by_name = {r.name: r for r in resources} main_meta = by_name["my-skill/SKILL.md"].get_meta() assert main_meta["fastmcp"]["skill"] == { "name": "my-skill", "is_manifest": False, } manifest_meta = by_name["my-skill/_manifest"].get_meta() assert manifest_meta["fastmcp"]["skill"] == { "name": "my-skill", "is_manifest": True, } async def test_skill_file_resource_meta(self, single_skill_dir: Path): """SkillFileResource populates meta with skill name.""" provider = SkillProvider( skill_path=single_skill_dir, supporting_files="resources" ) resources = await provider.list_resources() by_name = {r.name: r for r in resources} file_meta = by_name["my-skill/reference.md"].get_meta() assert file_meta["fastmcp"]["skill"] == {"name": "my-skill"} async def test_skill_meta_survives_mounting(self, single_skill_dir: Path): """Skill metadata in _meta is preserved when accessed through a mounted server.""" child = FastMCP("child") child.add_provider(SkillProvider(skill_path=single_skill_dir)) parent = FastMCP("parent") parent.mount(child, "skills") resources = await parent.list_resources() by_name = {r.name: r for r in resources} main_meta = by_name["my-skill/SKILL.md"].get_meta() assert main_meta["fastmcp"]["skill"] == { "name": "my-skill", "is_manifest": False, } manifest_meta = by_name["my-skill/_manifest"].get_meta() assert manifest_meta["fastmcp"]["skill"] == { "name": "my-skill", "is_manifest": True, } class TestSkillsDirectoryProvider: """Tests for SkillsDirectoryProvider - scans directory for skill folders.""" @pytest.fixture def skills_dir(self, tmp_path: Path) -> Path: """Create a test skills directory with sample skills.""" skills_root = tmp_path / "skills" skills_root.mkdir() # Create a simple skill simple_skill = skills_root / "simple-skill" simple_skill.mkdir() (simple_skill / "SKILL.md").write_text( """--- description: A simple test skill version: "1.0.0" --- # Simple Skill This is a simple skill for testing. """ ) # Create a skill with supporting files complex_skill = skills_root / "complex-skill" complex_skill.mkdir() (complex_skill / "SKILL.md").write_text( """--- description: A complex skill with supporting files --- # Complex Skill See [reference](reference.md) for more details. """ ) (complex_skill / "reference.md").write_text( """# Reference Additional documentation. """ ) (complex_skill / "scripts").mkdir() (complex_skill / "scripts" / "helper.py").write_text( 'print("Hello from helper")' ) return skills_root async def test_list_resources_discovers_skills(self, skills_dir: Path): provider = SkillsDirectoryProvider(roots=skills_dir) resources = await provider.list_resources() # Should have 2 resources per skill (main file + manifest) assert len(resources) == 4 # Check resource names resource_names = {r.name for r in resources} assert "simple-skill/SKILL.md" in resource_names assert "simple-skill/_manifest" in resource_names assert "complex-skill/SKILL.md" in resource_names assert "complex-skill/_manifest" in resource_names async def test_list_resources_includes_descriptions(self, skills_dir: Path): provider = SkillsDirectoryProvider(roots=skills_dir) resources = await provider.list_resources() # Find the simple-skill main resource simple_skill = next(r for r in resources if r.name == "simple-skill/SKILL.md") assert simple_skill.description == "A simple test skill" async def test_read_main_skill_file(self, skills_dir: Path): mcp = FastMCP("Test") mcp.add_provider(SkillsDirectoryProvider(roots=skills_dir)) async with Client(mcp) as client: result = await client.read_resource(AnyUrl("skill://simple-skill/SKILL.md")) assert len(result) == 1 assert isinstance(result[0], TextResourceContents) assert "# Simple Skill" in result[0].text async def test_read_manifest(self, skills_dir: Path): mcp = FastMCP("Test") mcp.add_provider(SkillsDirectoryProvider(roots=skills_dir)) async with Client(mcp) as client: result = await client.read_resource( AnyUrl("skill://complex-skill/_manifest") ) assert len(result) == 1 assert isinstance(result[0], TextResourceContents) manifest = json.loads(result[0].text) assert manifest["skill"] == "complex-skill" assert len(manifest["files"]) == 3 # SKILL.md, reference.md, helper.py # Check file paths paths = {f["path"] for f in manifest["files"]} assert "SKILL.md" in paths assert "reference.md" in paths assert "scripts/helper.py" in paths # Check hashes are present for file_info in manifest["files"]: assert file_info["hash"].startswith("sha256:") assert file_info["size"] > 0 async def test_list_resource_templates(self, skills_dir: Path): provider = SkillsDirectoryProvider(roots=skills_dir) templates = await provider.list_resource_templates() # One template per skill assert len(templates) == 2 template_names = {t.name for t in templates} assert "simple-skill_files" in template_names assert "complex-skill_files" in template_names async def test_read_supporting_file_via_template(self, skills_dir: Path): mcp = FastMCP("Test") mcp.add_provider(SkillsDirectoryProvider(roots=skills_dir)) async with Client(mcp) as client: result = await client.read_resource( AnyUrl("skill://complex-skill/reference.md") ) assert len(result) == 1 assert isinstance(result[0], TextResourceContents) assert "# Reference" in result[0].text async def test_read_nested_file_via_template(self, skills_dir: Path): mcp = FastMCP("Test") mcp.add_provider(SkillsDirectoryProvider(roots=skills_dir)) async with Client(mcp) as client: result = await client.read_resource( AnyUrl("skill://complex-skill/scripts/helper.py") ) assert len(result) == 1 assert isinstance(result[0], TextResourceContents) assert "Hello from helper" in result[0].text async def test_empty_skills_directory(self, tmp_path: Path): empty_dir = tmp_path / "empty" empty_dir.mkdir() provider = SkillsDirectoryProvider(roots=empty_dir) resources = await provider.list_resources() assert resources == [] templates = await provider.list_resource_templates() assert templates == [] async def test_nonexistent_skills_directory(self, tmp_path: Path): nonexistent = tmp_path / "does-not-exist" provider = SkillsDirectoryProvider(roots=nonexistent) resources = await provider.list_resources() assert resources == [] async def test_reload_mode(self, skills_dir: Path): provider = SkillsDirectoryProvider(roots=skills_dir, reload=True) # Initial load resources = await provider.list_resources() assert len(resources) == 4 # Add a new skill new_skill = skills_dir / "new-skill" new_skill.mkdir() (new_skill / "SKILL.md").write_text( """--- description: A new skill --- # New Skill """ ) # Reload should pick up the new skill resources = await provider.list_resources() assert len(resources) == 6 async def test_skill_without_frontmatter_uses_header_as_description( self, tmp_path: Path ): skills_dir = tmp_path / "skills" skills_dir.mkdir() skill = skills_dir / "no-frontmatter" skill.mkdir() (skill / "SKILL.md").write_text("# My Skill Title\n\nSome content.") provider = SkillsDirectoryProvider(roots=skills_dir) resources = await provider.list_resources() main_resource = next( r for r in resources if r.name == "no-frontmatter/SKILL.md" ) assert main_resource.description == "My Skill Title" async def test_supporting_files_as_resources(self, skills_dir: Path): """Test that supporting_files='resources' shows all files.""" provider = SkillsDirectoryProvider( roots=skills_dir, supporting_files="resources" ) resources = await provider.list_resources() # 2 skills * 2 standard resources + complex skill has 2 supporting files # simple-skill: SKILL.md, _manifest (2) # complex-skill: SKILL.md, _manifest, reference.md, scripts/helper.py (4) assert len(resources) == 6 names = {r.name for r in resources} assert "complex-skill/reference.md" in names assert "complex-skill/scripts/helper.py" in names async def test_supporting_files_as_resources_no_templates(self, skills_dir: Path): """In resources mode, no templates should be exposed.""" provider = SkillsDirectoryProvider( roots=skills_dir, supporting_files="resources" ) templates = await provider.list_resource_templates() assert templates == [] class TestMultiDirectoryProvider: """Tests for multi-directory support in SkillsDirectoryProvider.""" @pytest.fixture def multi_skills_dirs(self, tmp_path: Path) -> tuple[Path, Path]: """Create two separate skills directories.""" root1 = tmp_path / "skills1" root1.mkdir() skill1 = root1 / "skill-a" skill1.mkdir() (skill1 / "SKILL.md").write_text( """--- description: Skill A from root 1 --- # Skill A """ ) root2 = tmp_path / "skills2" root2.mkdir() skill2 = root2 / "skill-b" skill2.mkdir() (skill2 / "SKILL.md").write_text( """--- description: Skill B from root 2 --- # Skill B """ ) return root1, root2 async def test_multiple_roots_discover_all_skills(self, multi_skills_dirs): """Test that skills from multiple roots are all discovered.""" root1, root2 = multi_skills_dirs provider = SkillsDirectoryProvider(roots=[root1, root2]) resources = await provider.list_resources() # 2 skills * 2 resources each = 4 total assert len(resources) == 4 resource_names = {r.name for r in resources} assert "skill-a/SKILL.md" in resource_names assert "skill-a/_manifest" in resource_names assert "skill-b/SKILL.md" in resource_names assert "skill-b/_manifest" in resource_names async def test_duplicate_skill_names_first_wins(self, tmp_path: Path): """Test that if a skill appears in multiple roots, first one wins.""" root1 = tmp_path / "root1" root1.mkdir() skill1 = root1 / "duplicate-skill" skill1.mkdir() (skill1 / "SKILL.md").write_text( """--- description: First occurrence --- # First """ ) root2 = tmp_path / "root2" root2.mkdir() skill2 = root2 / "duplicate-skill" skill2.mkdir() (skill2 / "SKILL.md").write_text( """--- description: Second occurrence --- # Second """ ) provider = SkillsDirectoryProvider(roots=[root1, root2]) resources = await provider.list_resources() # Should only have one skill (first one) assert len(resources) == 2 # SKILL.md + _manifest # Should be the first one main_resource = next( r for r in resources if r.name == "duplicate-skill/SKILL.md" ) assert main_resource.description == "First occurrence" async def test_single_path_as_list(self, multi_skills_dirs): """Test that single path can be passed as a list.""" root1, _ = multi_skills_dirs provider = SkillsDirectoryProvider(roots=[root1]) resources = await provider.list_resources() assert len(resources) == 2 # skill-a has 2 resources async def test_single_path_as_string(self, multi_skills_dirs): """Test that single path can be passed as string.""" root1, _ = multi_skills_dirs provider = SkillsDirectoryProvider(roots=str(root1)) resources = await provider.list_resources() assert len(resources) == 2 async def test_nonexistent_roots_handled_gracefully(self, tmp_path: Path): """Test that non-existent roots don't cause errors.""" existent = tmp_path / "exists" existent.mkdir() skill = existent / "test-skill" skill.mkdir() (skill / "SKILL.md").write_text("# Test\n\nContent") nonexistent = tmp_path / "does-not-exist" provider = SkillsDirectoryProvider(roots=[existent, nonexistent]) resources = await provider.list_resources() # Should still find skills from existing root assert len(resources) == 2 async def test_empty_roots_list(self, tmp_path: Path): """Test that empty roots list results in no skills.""" provider = SkillsDirectoryProvider(roots=[]) resources = await provider.list_resources() assert resources == [] class TestSkillsProviderAlias: """Test that SkillsProvider is a backwards-compatible alias.""" def test_skills_provider_is_alias(self): assert SkillsProvider is SkillsDirectoryProvider class TestClaudeSkillsProvider: def test_default_root_is_claude_skills_dir(self, tmp_path: Path, monkeypatch): # Mock Path.home() to return a temp path (use tmp_path for cross-platform compatibility) monkeypatch.setattr(Path, "home", lambda: tmp_path) provider = ClaudeSkillsProvider() assert provider._roots == [tmp_path / ".claude" / "skills"] def test_main_file_name_is_skill_md(self): provider = ClaudeSkillsProvider() assert provider._main_file_name == "SKILL.md" def test_supporting_files_parameter(self): provider = ClaudeSkillsProvider(supporting_files="resources") assert provider._supporting_files == "resources" class TestPathTraversalPrevention: async def test_path_traversal_blocked(self, tmp_path: Path): skills_dir = tmp_path / "skills" skills_dir.mkdir() skill = skills_dir / "test-skill" skill.mkdir() (skill / "SKILL.md").write_text("# Test\n\nContent") # Create a file outside the skill directory secret_file = tmp_path / "secret.txt" secret_file.write_text("SECRET DATA") mcp = FastMCP("Test") mcp.add_provider(SkillsDirectoryProvider(roots=skills_dir)) async with Client(mcp) as client: # Path traversal attempts should fail (either normalized away or blocked) # The important thing is that SECRET DATA is never returned with pytest.raises(Exception): result = await client.read_resource( AnyUrl("skill://test-skill/../../../secret.txt") ) # If we somehow got here, ensure we didn't get the secret if result: for content in result: if hasattr(content, "text"): assert "SECRET DATA" not in content.text
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/providers/test_skills_provider.py", "license": "Apache License 2.0", "lines": 533, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:tests/server/providers/test_skills_vendor_providers.py
"""Tests for vendor-specific skills providers.""" from __future__ import annotations from pathlib import Path from fastmcp.server.providers.skills import ( ClaudeSkillsProvider, CodexSkillsProvider, CopilotSkillsProvider, CursorSkillsProvider, GeminiSkillsProvider, GooseSkillsProvider, OpenCodeSkillsProvider, VSCodeSkillsProvider, ) class TestVendorProviders: """Tests for vendor-specific skills providers.""" def test_cursor_skills_provider_path(self, tmp_path: Path, monkeypatch): """Test CursorSkillsProvider uses correct path.""" monkeypatch.setattr(Path, "home", lambda: tmp_path) provider = CursorSkillsProvider() assert provider._roots == [tmp_path / ".cursor" / "skills"] def test_vscode_skills_provider_path(self, tmp_path: Path, monkeypatch): """Test VSCodeSkillsProvider uses correct path.""" monkeypatch.setattr(Path, "home", lambda: tmp_path) provider = VSCodeSkillsProvider() assert provider._roots == [tmp_path / ".copilot" / "skills"] def test_codex_skills_provider_paths(self, tmp_path: Path, monkeypatch): """Test CodexSkillsProvider uses both system and user paths.""" monkeypatch.setattr(Path, "home", lambda: tmp_path) provider = CodexSkillsProvider() # Path.resolve() may add /private on macOS, so compare resolved paths expected_roots = [ Path("/etc/codex/skills").resolve(), (tmp_path / ".codex" / "skills").resolve(), ] assert provider._roots == expected_roots def test_gemini_skills_provider_path(self, tmp_path: Path, monkeypatch): """Test GeminiSkillsProvider uses correct path.""" monkeypatch.setattr(Path, "home", lambda: tmp_path) provider = GeminiSkillsProvider() assert provider._roots == [tmp_path / ".gemini" / "skills"] def test_goose_skills_provider_path(self, tmp_path: Path, monkeypatch): """Test GooseSkillsProvider uses correct path.""" monkeypatch.setattr(Path, "home", lambda: tmp_path) provider = GooseSkillsProvider() assert provider._roots == [tmp_path / ".config" / "agents" / "skills"] def test_copilot_skills_provider_path(self, tmp_path: Path, monkeypatch): """Test CopilotSkillsProvider uses correct path.""" monkeypatch.setattr(Path, "home", lambda: tmp_path) provider = CopilotSkillsProvider() assert provider._roots == [tmp_path / ".copilot" / "skills"] def test_opencode_skills_provider_path(self, tmp_path: Path, monkeypatch): """Test OpenCodeSkillsProvider uses correct path.""" monkeypatch.setattr(Path, "home", lambda: tmp_path) provider = OpenCodeSkillsProvider() assert provider._roots == [tmp_path / ".config" / "opencode" / "skills"] def test_claude_skills_provider_path(self, tmp_path: Path, monkeypatch): """Test ClaudeSkillsProvider uses correct path.""" monkeypatch.setattr(Path, "home", lambda: tmp_path) provider = ClaudeSkillsProvider() assert provider._roots == [tmp_path / ".claude" / "skills"] def test_all_providers_instantiable(self): """Test that all vendor providers can be instantiated.""" providers = [ ClaudeSkillsProvider(), CursorSkillsProvider(), VSCodeSkillsProvider(), CodexSkillsProvider(), GeminiSkillsProvider(), GooseSkillsProvider(), CopilotSkillsProvider(), OpenCodeSkillsProvider(), ] for provider in providers: assert provider is not None assert provider._main_file_name == "SKILL.md" def test_all_providers_support_reload(self): """Test that all providers support reload parameter.""" providers = [ ClaudeSkillsProvider(reload=True), CursorSkillsProvider(reload=True), VSCodeSkillsProvider(reload=True), CodexSkillsProvider(reload=True), GeminiSkillsProvider(reload=True), GooseSkillsProvider(reload=True), CopilotSkillsProvider(reload=True), OpenCodeSkillsProvider(reload=True), ] for provider in providers: assert provider._reload is True def test_all_providers_support_supporting_files(self): """Test that all providers support supporting_files parameter.""" providers = [ ClaudeSkillsProvider(supporting_files="resources"), CursorSkillsProvider(supporting_files="resources"), VSCodeSkillsProvider(supporting_files="resources"), CodexSkillsProvider(supporting_files="resources"), GeminiSkillsProvider(supporting_files="resources"), GooseSkillsProvider(supporting_files="resources"), CopilotSkillsProvider(supporting_files="resources"), OpenCodeSkillsProvider(supporting_files="resources"), ] for provider in providers: assert provider._supporting_files == "resources" async def test_codex_scans_both_paths(self, tmp_path: Path, monkeypatch): """Test that CodexSkillsProvider scans both system and user paths.""" # Mock system path system_skills = tmp_path / "etc" / "codex" / "skills" system_skills.mkdir(parents=True) system_skill = system_skills / "system-skill" system_skill.mkdir() (system_skill / "SKILL.md").write_text( """--- description: System skill --- # System """ ) # Mock user path fake_home = tmp_path / "home" / "user" fake_home.mkdir(parents=True) monkeypatch.setattr(Path, "home", lambda: fake_home) user_skills = fake_home / ".codex" / "skills" user_skills.mkdir(parents=True) user_skill = user_skills / "user-skill" user_skill.mkdir() (user_skill / "SKILL.md").write_text( """--- description: User skill --- # User """ ) # Create provider with mocked paths # Override roots before discovery provider = CodexSkillsProvider() provider._roots = [system_skills, user_skills] # Trigger re-discovery with new roots provider._discover_skills() resources = await provider.list_resources() # Should find both skills assert len(resources) == 4 # 2 skills * 2 resources each resource_names = {r.name for r in resources} assert "system-skill/SKILL.md" in resource_names assert "user-skill/SKILL.md" in resource_names async def test_nonexistent_paths_handled_gracefully( self, tmp_path: Path, monkeypatch ): """Test that non-existent paths don't cause errors.""" # Use a path that definitely doesn't exist nonexistent_home = tmp_path / "nonexistent" / "home" monkeypatch.setattr(Path, "home", lambda: nonexistent_home) # All providers should handle non-existent paths gracefully providers = [ ClaudeSkillsProvider(), CursorSkillsProvider(), VSCodeSkillsProvider(), GeminiSkillsProvider(), GooseSkillsProvider(), CopilotSkillsProvider(), OpenCodeSkillsProvider(), ] for provider in providers: resources = await provider.list_resources() # Should return empty list, not raise exception assert isinstance(resources, list)
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/providers/test_skills_vendor_providers.py", "license": "Apache License 2.0", "lines": 165, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:examples/prompts_as_tools/client.py
"""Example: Client using prompts-as-tools. This client demonstrates calling the list_prompts and get_prompt tools generated by the PromptsAsTools transform. Run with: uv run python examples/prompts_as_tools/client.py """ import asyncio import json from fastmcp.client import Client async def main(): # Connect to the server async with Client("examples/prompts_as_tools/server.py") as client: # List all available tools print("=== Available Tools ===") tools = await client.list_tools() for tool in tools: print(f" - {tool.name}: {tool.description}") print() # Use list_prompts tool to see what's available print("=== Listing Prompts ===") result = await client.call_tool("list_prompts", {}) prompts = json.loads(result.data) for prompt in prompts: print(f" {prompt['name']}") print(f" Description: {prompt.get('description', 'N/A')}") if prompt["arguments"]: print(" Arguments:") for arg in prompt["arguments"]: required = "required" if arg["required"] else "optional" print( f" - {arg['name']} ({required}): {arg.get('description', 'N/A')}" ) print() # Get a prompt without optional arguments print("=== Getting Simple Prompt ===") result = await client.call_tool( "get_prompt", {"name": "explain_concept", "arguments": {"concept": "recursion"}}, ) response = json.loads(result.data) print("Messages:") for msg in response["messages"]: print(f" Role: {msg['role']}") print(f" Content: {msg['content'][:100]}...") print() # Get a prompt with optional arguments print("=== Getting Prompt with Optional Arguments ===") result = await client.call_tool( "get_prompt", { "name": "analyze_code", "arguments": { "code": "def factorial(n):\n return n * factorial(n-1)", "language": "python", "focus": "bugs", }, }, ) response = json.loads(result.data) print("Messages:") for msg in response["messages"]: print(f" Role: {msg['role']}") print(f" Content: {msg['content'][:150]}...") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/prompts_as_tools/client.py", "license": "Apache License 2.0", "lines": 65, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
PrefectHQ/fastmcp:examples/prompts_as_tools/server.py
"""Example: Expose prompts as tools using PromptsAsTools transform. This example shows how to use PromptsAsTools to make prompts accessible to clients that only support tools (not the prompts protocol). Run with: uv run python examples/prompts_as_tools/server.py """ from fastmcp import FastMCP from fastmcp.server.transforms import PromptsAsTools mcp = FastMCP("Prompt Tools Demo") # Simple prompt without arguments @mcp.prompt def explain_concept(concept: str) -> str: """Explain a programming concept.""" return f"""Please explain the following programming concept in simple terms: {concept} Include: - A clear definition - Common use cases - A simple example """ # Prompt with multiple arguments @mcp.prompt def analyze_code(code: str, language: str = "python", focus: str = "all") -> str: """Analyze code for potential issues.""" return f"""Analyze this {language} code: ```{language} {code} ``` Focus on: {focus} Please identify: - Potential bugs or errors - Performance issues - Code style improvements - Security concerns """ # Prompt with required and optional arguments @mcp.prompt def review_pull_request( title: str, description: str, diff: str, guidelines: str = "" ) -> str: """Review a pull request.""" guidelines_section = ( f"\n\nGuidelines to follow:\n{guidelines}" if guidelines else "" ) return f"""Review this pull request: **Title:** {title} **Description:** {description} **Diff:** ``` {diff} ```{guidelines_section} Please provide: - Summary of changes - Potential issues or concerns - Suggestions for improvement - Overall recommendation (approve/request changes) """ # Add the transform - this creates list_prompts and get_prompt tools mcp.add_transform(PromptsAsTools(mcp)) if __name__ == "__main__": mcp.run()
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/prompts_as_tools/server.py", "license": "Apache License 2.0", "lines": 62, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
PrefectHQ/fastmcp:src/fastmcp/server/transforms/prompts_as_tools.py
"""Transform that exposes prompts as tools. This transform generates tools for listing and getting prompts, enabling clients that only support tools to access prompt functionality. Example: ```python from fastmcp import FastMCP from fastmcp.server.transforms import PromptsAsTools mcp = FastMCP("Server") mcp.add_transform(PromptsAsTools(mcp)) # Now has list_prompts and get_prompt tools ``` """ from __future__ import annotations import json from collections.abc import Sequence from typing import TYPE_CHECKING, Annotated, Any from mcp.types import TextContent from fastmcp.server.transforms import GetToolNext, Transform from fastmcp.tools.tool import Tool from fastmcp.utilities.versions import VersionSpec if TYPE_CHECKING: from fastmcp.server.providers.base import Provider # Note: FastMCP imported inside tools to avoid circular import class PromptsAsTools(Transform): """Transform that adds tools for listing and getting prompts. Generates two tools: - `list_prompts`: Lists all prompts from the provider - `get_prompt`: Gets a specific prompt with optional arguments The transform captures a provider reference at construction and queries it for prompts when the generated tools are called. When used with FastMCP, the provider's auth and visibility filtering is automatically applied. Example: ```python mcp = FastMCP("Server") mcp.add_transform(PromptsAsTools(mcp)) # Now has list_prompts and get_prompt tools ``` """ def __init__(self, provider: Provider) -> None: """Initialize the transform with a provider reference. Args: provider: The provider to query for prompts. Typically this is the same FastMCP server the transform is added to. """ self._provider = provider def __repr__(self) -> str: return f"PromptsAsTools({self._provider!r})" async def list_tools(self, tools: Sequence[Tool]) -> Sequence[Tool]: """Add prompt tools to the tool list.""" return [ *tools, self._make_list_prompts_tool(), self._make_get_prompt_tool(), ] async def get_tool( self, name: str, call_next: GetToolNext, *, version: VersionSpec | None = None ) -> Tool | None: """Get a tool by name, including generated prompt tools.""" # Check if it's one of our generated tools if name == "list_prompts": return self._make_list_prompts_tool() if name == "get_prompt": return self._make_get_prompt_tool() # Otherwise delegate to downstream return await call_next(name, version=version) def _make_list_prompts_tool(self) -> Tool: """Create the list_prompts tool.""" provider = self._provider async def list_prompts() -> str: """List all available prompts. Returns JSON with prompt metadata including name, description, and optional arguments. """ prompts = await provider.list_prompts() result: list[dict[str, Any]] = [] for p in prompts: result.append( { "name": p.name, "description": p.description, "arguments": [ { "name": arg.name, "description": arg.description, "required": arg.required, } for arg in (p.arguments or []) ], } ) return json.dumps(result, indent=2) return Tool.from_function(fn=list_prompts) def _make_get_prompt_tool(self) -> Tool: """Create the get_prompt tool.""" provider = self._provider async def get_prompt( name: Annotated[str, "The name of the prompt to get"], arguments: Annotated[ dict[str, Any] | None, "Optional arguments for the prompt", ] = None, ) -> str: """Get a prompt by name with optional arguments. Returns the rendered prompt as JSON with a messages array. Arguments should be provided as a dict mapping argument names to values. """ from fastmcp.server.server import FastMCP # Use FastMCP.render_prompt() if available - runs middleware chain if isinstance(provider, FastMCP): result = await provider.render_prompt(name, arguments=arguments or {}) return _format_prompt_result(result) # Fallback for plain providers - no middleware prompt = await provider.get_prompt(name) if prompt is None: raise ValueError(f"Prompt not found: {name}") result = await prompt._render(arguments or {}) return _format_prompt_result(result) return Tool.from_function(fn=get_prompt) def _format_prompt_result(result: Any) -> str: """Format PromptResult for tool output. Returns JSON with the messages array. Preserves embedded resources as structured JSON objects. """ messages = [] for msg in result.messages: if isinstance(msg.content, TextContent): content = msg.content.text else: # Preserve structured content (e.g., EmbeddedResource) as dict content = msg.content.model_dump(mode="json", exclude_none=True) messages.append( { "role": msg.role, "content": content, } ) return json.dumps({"messages": messages}, indent=2)
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/server/transforms/prompts_as_tools.py", "license": "Apache License 2.0", "lines": 137, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
PrefectHQ/fastmcp:tests/server/transforms/test_prompts_as_tools.py
"""Tests for PromptsAsTools transform.""" import json import pytest from fastmcp import FastMCP from fastmcp.client import Client from fastmcp.server.transforms import PromptsAsTools class TestPromptsAsToolsBasic: """Test basic PromptsAsTools functionality.""" async def test_adds_list_prompts_tool(self): """Transform adds list_prompts tool.""" mcp = FastMCP("Test") mcp.add_transform(PromptsAsTools(mcp)) async with Client(mcp) as client: tools = await client.list_tools() tool_names = {t.name for t in tools} assert "list_prompts" in tool_names async def test_adds_get_prompt_tool(self): """Transform adds get_prompt tool.""" mcp = FastMCP("Test") mcp.add_transform(PromptsAsTools(mcp)) async with Client(mcp) as client: tools = await client.list_tools() tool_names = {t.name for t in tools} assert "get_prompt" 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(PromptsAsTools(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_prompts" in tool_names assert "get_prompt" in tool_names class TestListPromptsTool: """Test the list_prompts tool.""" async def test_lists_prompts(self): """list_prompts returns prompt metadata.""" mcp = FastMCP("Test") @mcp.prompt def analyze_code() -> str: """Analyze code for issues.""" return "Analyze this code" mcp.add_transform(PromptsAsTools(mcp)) async with Client(mcp) as client: result = await client.call_tool("list_prompts", {}) prompts = json.loads(result.data) assert len(prompts) == 1 assert prompts[0]["name"] == "analyze_code" assert prompts[0]["description"] == "Analyze code for issues." async def test_lists_prompt_with_arguments(self): """list_prompts includes argument metadata.""" mcp = FastMCP("Test") @mcp.prompt def analyze_code(code: str, language: str = "python") -> str: """Analyze code for issues.""" return f"Analyze this {language} code:\n{code}" mcp.add_transform(PromptsAsTools(mcp)) async with Client(mcp) as client: result = await client.call_tool("list_prompts", {}) prompts = json.loads(result.data) assert len(prompts) == 1 args = prompts[0]["arguments"] assert len(args) == 2 # Check required arg code_arg = next(a for a in args if a["name"] == "code") assert code_arg["required"] is True # Check optional arg lang_arg = next(a for a in args if a["name"] == "language") assert lang_arg["required"] is False async def test_empty_when_no_prompts(self): """list_prompts returns empty list when no prompts exist.""" mcp = FastMCP("Test") mcp.add_transform(PromptsAsTools(mcp)) async with Client(mcp) as client: result = await client.call_tool("list_prompts", {}) assert json.loads(result.data) == [] class TestGetPromptTool: """Test the get_prompt tool.""" async def test_gets_prompt_without_arguments(self): """get_prompt gets a prompt with no arguments.""" mcp = FastMCP("Test") @mcp.prompt def simple_prompt() -> str: """A simple prompt.""" return "Hello, world!" mcp.add_transform(PromptsAsTools(mcp)) async with Client(mcp) as client: result = await client.call_tool("get_prompt", {"name": "simple_prompt"}) response = json.loads(result.data) assert "messages" in response assert len(response["messages"]) == 1 assert response["messages"][0]["role"] == "user" assert "Hello, world!" in response["messages"][0]["content"] async def test_gets_prompt_with_arguments(self): """get_prompt gets a prompt with arguments.""" mcp = FastMCP("Test") @mcp.prompt def analyze_code(code: str, language: str = "python") -> str: """Analyze code.""" return f"Analyze this {language} code:\n{code}" mcp.add_transform(PromptsAsTools(mcp)) async with Client(mcp) as client: result = await client.call_tool( "get_prompt", { "name": "analyze_code", "arguments": {"code": "x = 1", "language": "python"}, }, ) response = json.loads(result.data) assert "messages" in response content = response["messages"][0]["content"] assert "python" in content assert "x = 1" in content async def test_error_on_unknown_prompt(self): """get_prompt raises error for unknown prompt name.""" from fastmcp.exceptions import ToolError mcp = FastMCP("Test") mcp.add_transform(PromptsAsTools(mcp)) async with Client(mcp) as client: with pytest.raises(ToolError, match="Unknown prompt"): await client.call_tool("get_prompt", {"name": "unknown_prompt"}) class TestPromptsAsToolsWithNamespace: """Test PromptsAsTools combined with other transforms.""" async def test_works_with_namespace_on_provider(self): """PromptsAsTools works when provider has Namespace transform.""" from fastmcp.server.providers import FastMCPProvider from fastmcp.server.transforms import Namespace sub = FastMCP("Sub") @sub.prompt def my_prompt() -> str: """A prompt.""" return "Hello" main = FastMCP("Main") provider = FastMCPProvider(sub) provider.add_transform(Namespace("sub")) main.add_provider(provider) main.add_transform(PromptsAsTools(main)) async with Client(main) as client: result = await client.call_tool("list_prompts", {}) prompts = json.loads(result.data) # Prompt should have namespaced name assert len(prompts) == 1 assert prompts[0]["name"] == "sub_my_prompt" class TestPromptsAsToolsRepr: """Test PromptsAsTools repr.""" def test_repr(self): """Transform has useful repr.""" mcp = FastMCP("Test") transform = PromptsAsTools(mcp) assert "PromptsAsTools" in repr(transform)
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "tests/server/transforms/test_prompts_as_tools.py", "license": "Apache License 2.0", "lines": 155, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
PrefectHQ/fastmcp:examples/resources_as_tools/client.py
"""Example: Client using resources-as-tools. This client demonstrates calling the list_resources and read_resource tools generated by the ResourcesAsTools transform. Run with: uv run python examples/resources_as_tools/client.py """ import asyncio import json from fastmcp.client import Client async def main(): # Connect to the server async with Client("examples/resources_as_tools/server.py") as client: # List all available tools print("=== Available Tools ===") tools = await client.list_tools() for tool in tools: print(f" - {tool.name}: {tool.description}") print() # Use list_resources tool to see what's available print("=== Listing Resources ===") result = await client.call_tool("list_resources", {}) resources = json.loads(result.data) for resource in resources: if "uri" in resource: print(f" Static: {resource['uri']}") else: print(f" Template: {resource['uri_template']}") print(f" Name: {resource['name']}") print(f" Description: {resource.get('description', 'N/A')}") print() # Read a static resource print("=== Reading Static Resource ===") result = await client.call_tool("read_resource", {"uri": "config://app"}) print(f"config://app content:\n{result.data}") print() # Read a templated resource print("=== Reading Templated Resource ===") result = await client.call_tool("read_resource", {"uri": "user://42/profile"}) print(f"user://42/profile content:\n{result.data}") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/resources_as_tools/client.py", "license": "Apache License 2.0", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
PrefectHQ/fastmcp:examples/resources_as_tools/server.py
"""Example: Expose resources as tools using ResourcesAsTools transform. This example shows how to use ResourcesAsTools to make resources accessible to clients that only support tools (not the resources protocol). Run with: uv run python examples/resources_as_tools/server.py """ from fastmcp import FastMCP from fastmcp.server.transforms import ResourcesAsTools mcp = FastMCP("Resource Tools Demo") # Static resource - has a fixed URI @mcp.resource("config://app") def app_config() -> str: """Application configuration.""" return """ { "app_name": "My App", "version": "1.0.0", "debug": false } """ # Another static resource @mcp.resource("readme://main") def readme() -> str: """Project README.""" return """ # My Project This is an example project demonstrating ResourcesAsTools. """ # Resource template - URI has placeholders @mcp.resource("user://{user_id}/profile") def user_profile(user_id: str) -> str: """Get a user's profile by ID.""" return f""" {{ "user_id": "{user_id}", "name": "User {user_id}", "email": "user{user_id}@example.com" }} """ # Another template with multiple parameters @mcp.resource("file://{directory}/{filename}") def read_file(directory: str, filename: str) -> str: """Read a file from a directory.""" return f"Contents of {directory}/{filename}" # Add the transform - this creates list_resources and read_resource tools mcp.add_transform(ResourcesAsTools(mcp)) if __name__ == "__main__": mcp.run()
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "examples/resources_as_tools/server.py", "license": "Apache License 2.0", "lines": 48, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
PrefectHQ/fastmcp:src/fastmcp/server/transforms/resources_as_tools.py
"""Transform that exposes resources as tools. This transform generates tools for listing and reading resources, enabling clients that only support tools to access resource functionality. Example: ```python from fastmcp import FastMCP from fastmcp.server.transforms import ResourcesAsTools mcp = FastMCP("Server") mcp.add_transform(ResourcesAsTools(mcp)) # Now has list_resources and read_resource tools ``` """ from __future__ import annotations import base64 import json from collections.abc import Sequence from typing import TYPE_CHECKING, Annotated, Any from fastmcp.server.transforms import GetToolNext, Transform from fastmcp.tools.tool import Tool from fastmcp.utilities.versions import VersionSpec if TYPE_CHECKING: from fastmcp.server.providers.base import Provider class ResourcesAsTools(Transform): """Transform that adds tools for listing and reading resources. Generates two tools: - `list_resources`: Lists all resources and templates from the provider - `read_resource`: Reads a resource by URI The transform captures a provider reference at construction and queries it for resources when the generated tools are called. When used with FastMCP, the provider's auth and visibility filtering is automatically applied. Example: ```python mcp = FastMCP("Server") mcp.add_transform(ResourcesAsTools(mcp)) # Now has list_resources and read_resource tools ``` """ def __init__(self, provider: Provider) -> None: """Initialize the transform with a provider reference. Args: provider: The provider to query for resources. Typically this is the same FastMCP server the transform is added to. """ self._provider = provider def __repr__(self) -> str: return f"ResourcesAsTools({self._provider!r})" async def list_tools(self, tools: Sequence[Tool]) -> Sequence[Tool]: """Add resource tools to the tool list.""" return [ *tools, self._make_list_resources_tool(), self._make_read_resource_tool(), ] async def get_tool( self, name: str, call_next: GetToolNext, *, version: VersionSpec | None = None ) -> Tool | None: """Get a tool by name, including generated resource tools.""" # Check if it's one of our generated tools if name == "list_resources": return self._make_list_resources_tool() if name == "read_resource": return self._make_read_resource_tool() # Otherwise delegate to downstream return await call_next(name, version=version) def _make_list_resources_tool(self) -> Tool: """Create the list_resources tool.""" provider = self._provider async def list_resources() -> str: """List all available resources and resource templates. Returns JSON with resource metadata. Static resources have a 'uri' field, while templates have a 'uri_template' field with placeholders like {name}. """ resources = await provider.list_resources() templates = await provider.list_resource_templates() result: list[dict[str, Any]] = [] # Static resources for r in resources: result.append( { "uri": str(r.uri), "name": r.name, "description": r.description, "mime_type": r.mime_type, } ) # Resource templates (URI contains placeholders like {name}) for t in templates: result.append( { "uri_template": t.uri_template, "name": t.name, "description": t.description, } ) return json.dumps(result, indent=2) return Tool.from_function(fn=list_resources) def _make_read_resource_tool(self) -> Tool: """Create the read_resource tool.""" provider = self._provider async def read_resource( uri: Annotated[str, "The URI of the resource to read"], ) -> str: """Read a resource by its URI. For static resources, provide the exact URI. For templated resources, provide the URI with template parameters filled in. Returns the resource content as a string. Binary content is base64-encoded. """ from fastmcp import FastMCP # Use FastMCP.read_resource() if available - runs middleware chain if isinstance(provider, FastMCP): result = await provider.read_resource(uri) return _format_result(result) # Fallback for plain providers - no middleware resource = await provider.get_resource(uri) if resource is not None: result = await resource._read() return _format_result(result) template = await provider.get_resource_template(uri) if template is not None: params = template.matches(uri) if params is not None: result = await template._read(uri, params) return _format_result(result) raise ValueError(f"Resource not found: {uri}") return Tool.from_function(fn=read_resource) def _format_result(result: Any) -> str: """Format ResourceResult for tool output. Single text content is returned as-is. Single binary content is base64-encoded. Multiple contents are JSON-encoded with each item containing content and mime_type. """ # result is a ResourceResult with .contents list if len(result.contents) == 1: content = result.contents[0].content if isinstance(content, bytes): return base64.b64encode(content).decode() return content # Multiple contents - JSON encode return json.dumps( [ { "content": ( c.content if isinstance(c.content, str) else base64.b64encode(c.content).decode() ), "mime_type": c.mime_type, } for c in result.contents ] )
{ "repo_id": "PrefectHQ/fastmcp", "file_path": "src/fastmcp/server/transforms/resources_as_tools.py", "license": "Apache License 2.0", "lines": 151, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex