π The fast, Pythonic way to build MCP servers and clients.
Split large test files to comply with loq line limit (#3328)
Jeremiah Lowin610551c7b610
diff --git a/loq.toml b/loq.tomlindex f11d21871..0fffe3d5c 100644--- a/loq.toml+++ b/loq.toml@@ -10,90 +10,22 @@ exclude = ["**/uv.lock", ".git/**", "docs/**"]path = "tests/**"max_lines = 1000-[[rules]]-path = "tests/server/providers/test_local_provider_tools.py"-max_lines = 1554--[[rules]]-path = "tests/client/test_client.py"-max_lines = 1438--[[rules]]-path = "tests/server/test_auth_integration.py"-max_lines = 1242--[[rules]]-path = "tests/server/auth/test_oauth_proxy.py"-max_lines = 1899--[[rules]]-path = "tests/server/middleware/test_middleware.py"-max_lines = 1070-[[rules]]path = "src/fastmcp/server/context.py"max_lines = 1272-[[rules]]-path = "tests/tools/test_tool_transform.py"-max_lines = 1748--[[rules]]-path = "tests/server/test_mount.py"-max_lines = 1545--[[rules]]-path = "tests/utilities/test_inspect.py"-max_lines = 1111--[[rules]]-path = "tests/resources/test_resource_template.py"-max_lines = 1009--[[rules]]-path = "tests/server/auth/test_oauth_consent_flow.py"-max_lines = 1274-[[rules]]path = "src/fastmcp/server/server.py"max_lines = 3250-[[rules]]-path = "tests/tools/test_tool.py"-max_lines = 2026--[[rules]]-path = "tests/client/test_elicitation.py"-max_lines = 1132-[[rules]]path = "src/fastmcp/client/client.py"max_lines = 1885-[[rules]]-path = "tests/utilities/test_json_schema_type.py"-max_lines = 1584-[[rules]]path = "src/fastmcp/server/auth/oauth_proxy/proxy.py"max_lines = 1796-[[rules]]-path = "tests/server/test_dependencies.py"-max_lines = 1046--[[rules]]-path = "tests/client/test_sampling.py"-max_lines = 1002--[[rules]]-path = "tests/server/auth/test_jwt_provider.py"-max_lines = 1101-[[rules]]path = "src/fastmcp/server/providers/local_provider.py"max_lines = 1187--[[rules]]-path = "tests/server/test_versioning.py"-max_lines = 1235diff --git a/tests/client/test_elicitation.py b/tests/client/test_elicitation.pyindex 2316f6dae..ff00def14 100644--- a/tests/client/test_elicitation.py+++ b/tests/client/test_elicitation.py@@ -4,7 +4,7 @@ from typing import Any, Literal, castimport pytestfrom mcp.types import ElicitRequestFormParams, ElicitRequestParams-from pydantic import BaseModel, Field+from pydantic import BaseModelfrom typing_extensions import TypedDictfrom fastmcp import Context, FastMCP@@ -15,7 +15,6 @@ from fastmcp.server.elicitation import (AcceptedElicitation,CancelledElicitation,DeclinedElicitation,- get_elicitation_schema,validate_elicitation_json_schema,)from fastmcp.utilities.types import TypeAdapter@@ -659,474 +658,3 @@ class TestPatternMatching:async with Client(mcp, elicitation_handler=elicitation_handler) as client:result = await client.call_tool("pattern_match_tool", {})assert result.data == "Cancelled"---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"]diff --git a/tests/client/test_elicitation_enums.py b/tests/client/test_elicitation_enums.pynew file mode 100644index 000000000..d67e2b4f1--- /dev/null+++ b/tests/client/test_elicitation_enums.py@@ -0,0 +1,516 @@+"""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,+)+++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"]diff --git a/tests/client/test_sampling.py b/tests/client/test_sampling.pyindex 9df997124..b23276778 100644--- a/tests/client/test_sampling.py+++ b/tests/client/test_sampling.py@@ -344,1203 +344,3 @@ class TestSamplingWithTools:assert "auto" in choicesassert "required" in choicesassert "none" in choices---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"]---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"diff --git a/tests/client/test_sampling_result_types.py b/tests/client/test_sampling_result_types.pynew file mode 100644index 000000000..73d6fbddc--- /dev/null+++ b/tests/client/test_sampling_result_types.py@@ -0,0 +1,442 @@+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"diff --git a/tests/client/test_sampling_tool_loop.py b/tests/client/test_sampling_tool_loop.pynew file mode 100644index 000000000..7b3c2e9ad--- /dev/null+++ b/tests/client/test_sampling_tool_loop.py@@ -0,0 +1,769 @@+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"]diff --git a/tests/resources/test_resource_template.py b/tests/resources/test_resource_template.pyindex ed0b37376..1f43ce1d5 100644--- a/tests/resources/test_resource_template.py+++ b/tests/resources/test_resource_template.py@@ -747,343 +747,3 @@ class TestContextHandling:# read() returns the raw valueresult = await resource.read()assert result == "item: 42"---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 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" # overriddendiff --git a/tests/resources/test_resource_template_query_params.py b/tests/resources/test_resource_template_query_params.pynew file mode 100644index 000000000..d68025f66--- /dev/null+++ b/tests/resources/test_resource_template_query_params.py@@ -0,0 +1,343 @@+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 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" # overriddendiff --git a/tests/server/auth/providers/test_azure.py b/tests/server/auth/providers/test_azure.pyindex c64902aab..3d01c926d 100644--- a/tests/server/auth/providers/test_azure.py+++ b/tests/server/auth/providers/test_azure.py@@ -8,12 +8,8 @@ from mcp.server.auth.provider import AuthorizationParamsfrom mcp.shared.auth import OAuthClientInformationFullfrom pydantic import AnyUrl-from fastmcp.server.auth.providers.azure import (- OIDC_SCOPES,- AzureJWTVerifier,- AzureProvider,-)-from fastmcp.server.auth.providers.jwt import JWTVerifier, RSAKeyPair+from fastmcp.server.auth.providers.azure import AzureProvider+from fastmcp.server.auth.providers.jwt import JWTVerifier@pytest.fixture@@ -738,680 +734,3 @@ class TestAzureProvider:# Should have 3 items (read deduplicated, plus offline_access)assert len(result) == 3assert result.count("api://my-api/read") == 1---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."""- try:- from docket.dependencies import Dependency- except ImportError:- from fastmcp._vendor.docket_di import Dependency-- from fastmcp.server.auth.providers.azure import _EntraOBOToken-- dep = _EntraOBOToken(["scope"])- assert isinstance(dep, Dependency)diff --git a/tests/server/auth/providers/test_azure_scopes.py b/tests/server/auth/providers/test_azure_scopes.pynew file mode 100644index 000000000..92a4178c8--- /dev/null+++ b/tests/server/auth/providers/test_azure_scopes.py@@ -0,0 +1,694 @@+"""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+++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."""+ try:+ from docket.dependencies import Dependency+ except ImportError:+ from fastmcp._vendor.docket_di import Dependency++ from fastmcp.server.auth.providers.azure import _EntraOBOToken++ dep = _EntraOBOToken(["scope"])+ assert isinstance(dep, Dependency)diff --git a/tests/server/auth/test_cimd.py b/tests/server/auth/test_cimd.pyindex 111d863c7..3ed99857a 100644--- a/tests/server/auth/test_cimd.py+++ b/tests/server/auth/test_cimd.py@@ -3,20 +3,17 @@from __future__ import annotationsimport time-from unittest.mock import AsyncMock, patch+from unittest.mock import patchimport pytestfrom pydantic import AnyHttpUrl, ValidationErrorfrom fastmcp.server.auth.cimd import (- CIMDAssertionValidator,- CIMDClientManager,CIMDDocument,CIMDFetcher,CIMDFetchError,CIMDValidationError,)-from fastmcp.server.auth.oauth_proxy.models import ProxyDCRClient# Standard public IP used for DNS mocking in testsTEST_PUBLIC_IP = "93.184.216.34"@@ -543,667 +540,3 @@ class TestCIMDFetcherHTTP:with pytest.raises(CIMDValidationError) as exc_info:await fetcher.fetch(url)assert "Invalid CIMD document" in str(exc_info.value)---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"))diff --git a/tests/server/auth/test_cimd_validators.py b/tests/server/auth/test_cimd_validators.pynew file mode 100644index 000000000..995854ba2--- /dev/null+++ b/tests/server/auth/test_cimd_validators.py@@ -0,0 +1,682 @@+"""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"))diff --git a/tests/server/auth/test_jwt_provider.py b/tests/server/auth/test_jwt_provider.pyindex bced42a1f..19b0f9370 100644--- a/tests/server/auth/test_jwt_provider.py+++ b/tests/server/auth/test_jwt_provider.py@@ -2,12 +2,10 @@ from collections.abc import AsyncGeneratorfrom typing import Anyfrom unittest.mock import patch-import httpximport pytestfrom pytest_httpx import HTTPXMock-from fastmcp import Client, FastMCP-from fastmcp.client.auth.bearer import BearerAuth+from fastmcp import FastMCPfrom fastmcp.server.auth.providers.jwt import JWKData, JWKSData, JWTVerifier, RSAKeyPairfrom fastmcp.utilities.tests import run_server_async@@ -576,546 +574,3 @@ class TestBearerTokenJWKS:access_token = await jwks_provider.load_access_token(token)assert access_token is None---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 == []diff --git a/tests/server/auth/test_jwt_provider_bearer.py b/tests/server/auth/test_jwt_provider_bearer.pynew file mode 100644index 000000000..c88665c87--- /dev/null+++ b/tests/server/auth/test_jwt_provider_bearer.py@@ -0,0 +1,610 @@+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"++[email protected](scope="module")+def rsa_key_pair() -> RSAKeyPair:+ return RSAKeyPair.generate()++[email protected](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",+ )+++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+++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 == []diff --git a/tests/server/auth/test_oauth_consent_flow.py b/tests/server/auth/test_oauth_consent_flow.pyindex 25f53fe21..7a65df297 100644--- a/tests/server/auth/test_oauth_consent_flow.py+++ b/tests/server/auth/test_oauth_consent_flow.py@@ -15,19 +15,16 @@ This test suite verifies:import reimport secretsimport time-from unittest.mock import Mockfrom urllib.parse import parse_qs, urlparseimport pytestfrom key_value.aio.stores.memory import MemoryStorefrom mcp.server.auth.provider import AuthorizationParamsfrom mcp.shared.auth import OAuthClientInformationFull-from mcp.types import Iconfrom pydantic import AnyUrlfrom starlette.applications import Starlettefrom starlette.testclient import TestClient-from fastmcp import FastMCPfrom fastmcp.server.auth.auth import AccessToken, TokenVerifierfrom fastmcp.server.auth.oauth_proxy import OAuthProxyfrom fastmcp.server.auth.oauth_proxy.models import OAuthTransaction@@ -660,615 +657,3 @@ class TestConsentSecurity:assert r2.headers.get("location", "").startswith("https://github.com/login/oauth/authorize")---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 "<script>" in response.text- assert (- 'alt="<script>alert("xss")</script>Server"'- in response.text- )---class TestConsentCSPPolicy:- """Tests for Content Security Policy customization on consent page."""-- async def test_default_csp_includes_form_action(self):- """Test that default CSP includes form-action directive."""-- 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 with form-action- assert 'http-equiv="Content-Security-Policy"' in response.text- assert "form-action" 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 ')- 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 != 403diff --git a/tests/server/auth/test_oauth_consent_page.py b/tests/server/auth/test_oauth_consent_page.pynew file mode 100644index 000000000..5e2d51737--- /dev/null+++ b/tests/server/auth/test_oauth_consent_page.py@@ -0,0 +1,696 @@+"""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+ )+++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 "<script>" in response.text+ assert (+ 'alt="<script>alert("xss")</script>Server"'+ in response.text+ )+++class TestConsentCSPPolicy:+ """Tests for Content Security Policy customization on consent page."""++ async def test_default_csp_includes_form_action(self):+ """Test that default CSP includes form-action directive."""++ 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 with form-action+ assert 'http-equiv="Content-Security-Policy"' in response.text+ assert "form-action" 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 ')+ 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 != 403diff --git a/tests/server/auth/test_oidc_proxy.py b/tests/server/auth/test_oidc_proxy.pyindex b4fbd32a5..e3dd95e1c 100644--- a/tests/server/auth/test_oidc_proxy.py+++ b/tests/server/auth/test_oidc_proxy.py@@ -7,7 +7,6 @@ import pytestfrom httpx import Responsefrom pydantic import AnyHttpUrl-from fastmcp.server.auth.oauth_proxy.models import UpstreamTokenSetfrom fastmcp.server.auth.oidc_proxy import OIDCConfiguration, OIDCProxyfrom fastmcp.server.auth.providers.introspection import IntrospectionTokenVerifierfrom fastmcp.server.auth.providers.jwt import JWTVerifier@@ -877,285 +876,3 @@ class TestOIDCProxyInitialization:"audience": "original-audience","custom": "value",}---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,- )---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",- ]diff --git a/tests/server/auth/test_oidc_proxy_token.py b/tests/server/auth/test_oidc_proxy_token.pynew file mode 100644index 000000000..57083d50d--- /dev/null+++ b/tests/server/auth/test_oidc_proxy_token.py@@ -0,0 +1,331 @@+"""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+# =============================================================================+++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",+ ]diff --git a/tests/server/middleware/test_middleware.py b/tests/server/middleware/test_middleware.pyindex 3bee43b19..6b822e228 100644--- a/tests/server/middleware/test_middleware.py+++ b/tests/server/middleware/test_middleware.py@@ -6,7 +6,6 @@ import mcp.typesimport pytestfrom fastmcp import Client, FastMCP-from fastmcp.exceptions import ToolErrorfrom fastmcp.server.context import Contextfrom fastmcp.server.middleware import CallNext, Middleware, MiddlewareContextfrom fastmcp.tools.tool import ToolResult@@ -620,510 +619,3 @@ class TestApplyMiddlewareParameter:"add", {"a": 5, "b": 3}, run_middleware=False)assert result_without.structured_content["result"] == 8 # type: ignore[union-attr,index]---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"diff --git a/tests/server/middleware/test_middleware_nested.py b/tests/server/middleware/test_middleware_nested.pynew file mode 100644index 000000000..e57b9a311--- /dev/null+++ b/tests/server/middleware/test_middleware_nested.py@@ -0,0 +1,673 @@+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()+++def recording_middleware():+ """Fixture that provides a recording middleware instance."""+ middleware = RecordingMiddleware(name="recording_middleware")+ yield middleware+++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"diff --git a/tests/server/test_auth_integration.py b/tests/server/test_auth_integration.pyindex d005fe3d5..102e3e7c3 100644--- a/tests/server/test_auth_integration.py+++ b/tests/server/test_auth_integration.py@@ -969,274 +969,3 @@ class TestAuthEndpoints:error_data["error_description"]== "grant_types must be authorization_code and refresh_token")---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"diff --git a/tests/server/test_auth_integration_errors.py b/tests/server/test_auth_integration_errors.pynew file mode 100644index 000000000..196701119--- /dev/null+++ b/tests/server/test_auth_integration_errors.py@@ -0,0 +1,539 @@+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]+++def mock_oauth_provider():+ return MockOAuthProvider()+++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+++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+++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+++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"diff --git a/tests/server/test_dependencies.py b/tests/server/test_dependencies.pyindex b5134522c..8062a3b02 100644--- a/tests/server/test_dependencies.py+++ b/tests/server/test_dependencies.py@@ -746,450 +746,3 @@ async def test_validation_error_propagates_from_dependency(mcp: FastMCP):assert result.is_errorassert isinstance(result.content[0], TextContent)assert result.content[0].text == "Invalid input format"---# --- Tests for transform_context_annotations ------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."""- import inspect-- 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."""- import inspect-- 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."""- import inspect-- 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."""- import inspect-- 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---class TestVendoredDI:- """Tests for vendored DI when docket is not installed."""-- def test_is_docket_available(self):- """Test is_docket_available returns True when docket is installed."""- from fastmcp.server.dependencies import is_docket_available-- # In dev environment, docket should be available- assert is_docket_available() is True-- def test_require_docket_passes_when_installed(self):- """Test require_docket doesn't raise when docket is installed."""- from fastmcp.server.dependencies import require_docket-- # Should not raise- require_docket("test feature")-- def test_vendored_dependency_class_exists(self):- """Test vendored Dependency class is importable."""- from fastmcp._vendor.docket_di import Dependency, Depends-- assert Dependency is not None- assert Depends is not None-- def test_vendored_depends_works(self):- """Test vendored Depends() creates proper dependency wrapper."""- from fastmcp._vendor.docket_di import Depends, _Depends-- def get_value() -> str:- return "test_value"-- dep = Depends(get_value)- assert isinstance(dep, _Depends)- assert dep.dependency is get_value-- async def test_depends_import_fallback(self):- """Test that Depends can be imported from fastmcp.dependencies."""- # This tests the import path, not the actual fallback behavior- # since docket is always installed in dev- from fastmcp.dependencies import Depends-- def get_config() -> dict:- return {"key": "value"}-- dep = Depends(get_config)- # Should work regardless of whether docket or vendored is used- assert dep is not None-- def test_vendored_get_dependency_parameters(self):- """Test vendored get_dependency_parameters finds dependency defaults."""- from fastmcp._vendor.docket_di import (- Depends,- _Depends,- get_dependency_parameters,- )-- def get_db() -> str:- return "database"-- def my_func(name: str, db: str = Depends(get_db)) -> str:- return f"{name}: {db}"-- deps = get_dependency_parameters(my_func)- assert "db" in deps- db_dep = deps["db"]- assert isinstance(db_dep, _Depends)- assert db_dep.dependency is get_db---class TestAuthDependencies:- """Tests for authentication dependencies (CurrentAccessToken, TokenClaim)."""-- def test_current_access_token_is_importable(self):- """Test that CurrentAccessToken can be imported."""- from fastmcp.server.dependencies import CurrentAccessToken-- assert CurrentAccessToken is not None-- def test_token_claim_is_importable(self):- """Test that TokenClaim can be imported."""- from fastmcp.server.dependencies import TokenClaim-- assert TokenClaim is not None-- def test_current_access_token_is_dependency(self):- """Test that CurrentAccessToken is a Dependency instance."""- # Import the Dependency class the same way the code does- # (docket if available, vendored otherwise)- try:- from docket.dependencies import Dependency- except ImportError:- from fastmcp._vendor.docket_di import Dependency-- from fastmcp.server.dependencies import _CurrentAccessToken-- dep = _CurrentAccessToken()- assert isinstance(dep, Dependency)-- def test_token_claim_creates_dependency(self):- """Test that TokenClaim creates a Dependency instance."""- # Import the Dependency class the same way the code does- try:- from docket.dependencies import Dependency- except ImportError:- from fastmcp._vendor.docket_di import Dependency-- from fastmcp.server.dependencies import TokenClaim, _TokenClaim-- dep = TokenClaim("oid")- assert isinstance(dep, _TokenClaim)- assert isinstance(dep, Dependency)- assert dep.claim_name == "oid"-- async def test_current_access_token_raises_without_token(self):- """Test that CurrentAccessToken raises when no token is available."""- from fastmcp.server.dependencies import _CurrentAccessToken-- dep = _CurrentAccessToken()- with pytest.raises(RuntimeError, match="No access token found"):- await dep.__aenter__()-- async def test_token_claim_raises_without_token(self):- """Test that TokenClaim raises when no token is available."""- from fastmcp.server.dependencies import _TokenClaim-- dep = _TokenClaim("oid")- with pytest.raises(RuntimeError, match="No access token available"):- await dep.__aenter__()-- async def test_current_access_token_excluded_from_tool_schema(self, mcp: FastMCP):- """Test that CurrentAccessToken dependency is excluded from tool schema."""- import mcp.types as mcp_types-- from fastmcp.server.auth import AccessToken- from fastmcp.server.dependencies import CurrentAccessToken-- @mcp.tool()- async def tool_with_token(- name: str,- token: AccessToken = CurrentAccessToken(),- ) -> str:- return name-- result = await mcp._list_tools_mcp(mcp_types.ListToolsRequest())- tool = next(t for t in result.tools if t.name == "tool_with_token")-- assert "name" in tool.inputSchema["properties"]- assert "token" not in tool.inputSchema["properties"]-- async def test_token_claim_excluded_from_tool_schema(self, mcp: FastMCP):- """Test that TokenClaim dependency is excluded from tool schema."""- import mcp.types as mcp_types-- from fastmcp.server.dependencies import TokenClaim-- @mcp.tool()- async def tool_with_claim(- name: str,- user_id: str = TokenClaim("oid"),- ) -> str:- return name-- result = await mcp._list_tools_mcp(mcp_types.ListToolsRequest())- tool = next(t for t in result.tools if t.name == "tool_with_claim")-- assert "name" in tool.inputSchema["properties"]- assert "user_id" not in tool.inputSchema["properties"]-- def test_current_access_token_exported_from_all(self):- """Test that CurrentAccessToken is exported from __all__."""- from fastmcp.server import dependencies-- assert "CurrentAccessToken" in dependencies.__all__-- def test_token_claim_exported_from_all(self):- """Test that TokenClaim is exported from __all__."""- from fastmcp.server import dependencies-- assert "TokenClaim" in dependencies.__all__diff --git a/tests/server/test_dependencies_advanced.py b/tests/server/test_dependencies_advanced.pynew file mode 100644index 000000000..57fca6de0--- /dev/null+++ b/tests/server/test_dependencies_advanced.py@@ -0,0 +1,462 @@+"""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, Depends+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+++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+++class TestVendoredDI:+ """Tests for vendored DI when docket is not installed."""++ def test_is_docket_available(self):+ """Test is_docket_available returns True when docket is installed."""+ from fastmcp.server.dependencies import is_docket_available++ # In dev environment, docket should be available+ assert is_docket_available() is True++ def test_require_docket_passes_when_installed(self):+ """Test require_docket doesn't raise when docket is installed."""+ from fastmcp.server.dependencies import require_docket++ # Should not raise+ require_docket("test feature")++ def test_vendored_dependency_class_exists(self):+ """Test vendored Dependency class is importable."""+ from fastmcp._vendor.docket_di import Dependency, Depends++ assert Dependency is not None+ assert Depends is not None++ def test_vendored_depends_works(self):+ """Test vendored Depends() creates proper dependency wrapper."""+ from fastmcp._vendor.docket_di import Depends, _Depends++ def get_value() -> str:+ return "test_value"++ dep = Depends(get_value)+ assert isinstance(dep, _Depends)+ assert dep.dependency is get_value++ async def test_depends_import_fallback(self):+ """Test that Depends can be imported from fastmcp.dependencies."""+ # This tests the import path, not the actual fallback behavior+ # since docket is always installed in dev++ def get_config() -> dict:+ return {"key": "value"}++ dep = Depends(get_config)+ # Should work regardless of whether docket or vendored is used+ assert dep is not None++ def test_vendored_get_dependency_parameters(self):+ """Test vendored get_dependency_parameters finds dependency defaults."""+ from fastmcp._vendor.docket_di import (+ Depends,+ _Depends,+ get_dependency_parameters,+ )++ def get_db() -> str:+ return "database"++ def my_func(name: str, db: str = Depends(get_db)) -> str:+ return f"{name}: {db}"++ deps = get_dependency_parameters(my_func)+ assert "db" in deps+ db_dep = deps["db"]+ assert isinstance(db_dep, _Depends)+ assert db_dep.dependency is get_db+++class TestAuthDependencies:+ """Tests for authentication dependencies (CurrentAccessToken, TokenClaim)."""++ def test_current_access_token_is_importable(self):+ """Test that CurrentAccessToken can be imported."""+ from fastmcp.server.dependencies import CurrentAccessToken++ assert CurrentAccessToken is not None++ def test_token_claim_is_importable(self):+ """Test that TokenClaim can be imported."""+ from fastmcp.server.dependencies import TokenClaim++ assert TokenClaim is not None++ def test_current_access_token_is_dependency(self):+ """Test that CurrentAccessToken is a Dependency instance."""+ # Import the Dependency class the same way the code does+ # (docket if available, vendored otherwise)+ try:+ from docket.dependencies import Dependency+ except ImportError:+ from fastmcp._vendor.docket_di import Dependency++ from fastmcp.server.dependencies import _CurrentAccessToken++ dep = _CurrentAccessToken()+ assert isinstance(dep, Dependency)++ def test_token_claim_creates_dependency(self):+ """Test that TokenClaim creates a Dependency instance."""+ # Import the Dependency class the same way the code does+ try:+ from docket.dependencies import Dependency+ except ImportError:+ from fastmcp._vendor.docket_di import Dependency++ from fastmcp.server.dependencies import TokenClaim, _TokenClaim++ dep = TokenClaim("oid")+ assert isinstance(dep, _TokenClaim)+ assert isinstance(dep, Dependency)+ assert dep.claim_name == "oid"++ async def test_current_access_token_raises_without_token(self):+ """Test that CurrentAccessToken raises when no token is available."""+ from fastmcp.server.dependencies import _CurrentAccessToken++ dep = _CurrentAccessToken()+ with pytest.raises(RuntimeError, match="No access token found"):+ await dep.__aenter__()++ async def test_token_claim_raises_without_token(self):+ """Test that TokenClaim raises when no token is available."""+ from fastmcp.server.dependencies import _TokenClaim++ dep = _TokenClaim("oid")+ with pytest.raises(RuntimeError, match="No access token available"):+ await dep.__aenter__()++ async def test_current_access_token_excluded_from_tool_schema(self, mcp: FastMCP):+ """Test that CurrentAccessToken dependency is excluded from tool schema."""+ from fastmcp.server.auth import AccessToken+ from fastmcp.server.dependencies import CurrentAccessToken++ @mcp.tool()+ async def tool_with_token(+ name: str,+ token: AccessToken = CurrentAccessToken(),+ ) -> str:+ return name++ result = await mcp._list_tools_mcp(mcp_types.ListToolsRequest())+ tool = next(t for t in result.tools if t.name == "tool_with_token")++ assert "name" in tool.inputSchema["properties"]+ assert "token" not in tool.inputSchema["properties"]++ async def test_token_claim_excluded_from_tool_schema(self, mcp: FastMCP):+ """Test that TokenClaim dependency is excluded from tool schema."""+ from fastmcp.server.dependencies import TokenClaim++ @mcp.tool()+ async def tool_with_claim(+ name: str,+ user_id: str = TokenClaim("oid"),+ ) -> str:+ return name++ result = await mcp._list_tools_mcp(mcp_types.ListToolsRequest())+ tool = next(t for t in result.tools if t.name == "tool_with_claim")++ assert "name" in tool.inputSchema["properties"]+ assert "user_id" not in tool.inputSchema["properties"]++ def test_current_access_token_exported_from_all(self):+ """Test that CurrentAccessToken is exported from __all__."""+ from fastmcp.server import dependencies++ assert "CurrentAccessToken" in dependencies.__all__++ def test_token_claim_exported_from_all(self):+ """Test that TokenClaim is exported from __all__."""+ from fastmcp.server import dependencies++ assert "TokenClaim" in dependencies.__all__diff --git a/tests/utilities/openapi/test_circular_references.py b/tests/utilities/openapi/test_circular_references.pynew file mode 100644index 000000000..3c5a98c79--- /dev/null+++ b/tests/utilities/openapi/test_circular_references.py@@ -0,0 +1,260 @@+"""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)diff --git a/tests/utilities/openapi/test_transitive_references.py b/tests/utilities/openapi/test_transitive_references.pyindex 01cf189eb..fbb15f597 100644--- a/tests/utilities/openapi/test_transitive_references.py+++ b/tests/utilities/openapi/test_transitive_references.py@@ -1,8 +1,5 @@"""Comprehensive tests for transitive and nested reference handling (Issue #1372)."""-import httpx--from fastmcp import FastMCPfrom fastmcp.utilities.openapi.models import (HTTPRoute,ParameterInfo,@@ -12,7 +9,6 @@ from fastmcp.utilities.openapi.models import (from fastmcp.utilities.openapi.parser import parse_openapi_to_http_routesfrom fastmcp.utilities.openapi.schemas import (_combine_schemas_and_map_params,- _replace_ref_with_defs,extract_output_schema_from_responses,)@@ -844,251 +840,3 @@ class TestTransitiveAndNestedReferences:assert "Person" in route.response_schemasassert "Name" in route.response_schemasassert "Job" in route.response_schemas---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)diff --git a/tests/utilities/test_inspect.py b/tests/utilities/test_inspect.pyindex 448e1eb03..d846c844a 100644--- a/tests/utilities/test_inspect.py+++ b/tests/utilities/test_inspect.py@@ -8,11 +8,7 @@ import fastmcpfrom fastmcp import Client, FastMCPfrom fastmcp.utilities.inspect import (FastMCPInfo,- InspectFormat,ToolInfo,- format_fastmcp_info,- format_info,- format_mcp_info,inspect_fastmcp,inspect_fastmcp_v1,)@@ -606,506 +602,3 @@ class TestFastMCP1xCompatibility:# No templates added in these testsassert len(info1x.templates) == 0assert len(info2x.templates) == 0---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"diff --git a/tests/utilities/test_inspect_icons.py b/tests/utilities/test_inspect_icons.pynew file mode 100644index 000000000..bba995545--- /dev/null+++ b/tests/utilities/test_inspect_icons.py@@ -0,0 +1,519 @@+"""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"