-
Notifications
You must be signed in to change notification settings - Fork 2k
Make $ref dereferencing optional via FastMCP(dereference_refs=...) #3151
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
4941719
Make $ref dereferencing in schemas optional via server kwarg
jlowin 3337f19
Fix tests: compress_schema preserves $ref, prunes unused $defs
jlowin e61bacf
chore: Update SDK documentation
marvin-context-protocol[bot] 0755b5e
fix: test_combined_operations expects $defs pruned when unreferenced
jlowin 5f1cc32
docs: document dereference_refs opt-out on tools page
jlowin 614bdb4
rename dereference_refs kwarg to dereference_schemas
jlowin 4965c96
chore: Update SDK documentation
marvin-context-protocol[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| --- | ||
| title: dereference | ||
| sidebarTitle: dereference | ||
| --- | ||
|
|
||
| # `fastmcp.server.middleware.dereference` | ||
|
|
||
|
|
||
| Middleware that dereferences $ref in JSON schemas before sending to clients. | ||
|
|
||
| ## Classes | ||
|
|
||
| ### `DereferenceRefsMiddleware` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/middleware/dereference.py#L15" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup> | ||
|
|
||
|
|
||
| Dereferences $ref in component schemas before sending to clients. | ||
|
|
||
| Some MCP clients (e.g., VS Code Copilot) don't handle JSON Schema $ref | ||
| properly. This middleware inlines all $ref definitions so schemas are | ||
| self-contained. Enabled by default via ``FastMCP(dereference_schemas=True)``. | ||
|
|
||
|
|
||
| **Methods:** | ||
|
|
||
| #### `on_list_tools` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/middleware/dereference.py#L24" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup> | ||
|
|
||
| ```python | ||
| on_list_tools(self, context: MiddlewareContext[mt.ListToolsRequest], call_next: CallNext[mt.ListToolsRequest, Sequence[Tool]]) -> Sequence[Tool] | ||
| ``` | ||
|
|
||
| #### `on_list_resource_templates` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/middleware/dereference.py#L33" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup> | ||
|
|
||
| ```python | ||
| on_list_resource_templates(self, context: MiddlewareContext[mt.ListResourceTemplatesRequest], call_next: CallNext[mt.ListResourceTemplatesRequest, Sequence[ResourceTemplate]]) -> Sequence[ResourceTemplate] | ||
| ``` |
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| """Middleware that dereferences $ref in JSON schemas before sending to clients.""" | ||
|
|
||
| from collections.abc import Sequence | ||
| from typing import Any | ||
|
|
||
| import mcp.types as mt | ||
| from typing_extensions import override | ||
|
|
||
| from fastmcp.resources.template import ResourceTemplate | ||
| from fastmcp.server.middleware.middleware import CallNext, Middleware, MiddlewareContext | ||
| from fastmcp.tools.tool import Tool | ||
| from fastmcp.utilities.json_schema import dereference_refs | ||
|
|
||
|
|
||
| class DereferenceRefsMiddleware(Middleware): | ||
| """Dereferences $ref in component schemas before sending to clients. | ||
|
|
||
| Some MCP clients (e.g., VS Code Copilot) don't handle JSON Schema $ref | ||
| properly. This middleware inlines all $ref definitions so schemas are | ||
| self-contained. Enabled by default via ``FastMCP(dereference_schemas=True)``. | ||
| """ | ||
|
|
||
| @override | ||
| async def on_list_tools( | ||
| self, | ||
| context: MiddlewareContext[mt.ListToolsRequest], | ||
| call_next: CallNext[mt.ListToolsRequest, Sequence[Tool]], | ||
| ) -> Sequence[Tool]: | ||
| tools = await call_next(context) | ||
| return [_dereference_tool(tool) for tool in tools] | ||
|
|
||
| @override | ||
| async def on_list_resource_templates( | ||
| self, | ||
| context: MiddlewareContext[mt.ListResourceTemplatesRequest], | ||
| call_next: CallNext[ | ||
| mt.ListResourceTemplatesRequest, Sequence[ResourceTemplate] | ||
| ], | ||
| ) -> Sequence[ResourceTemplate]: | ||
| templates = await call_next(context) | ||
| return [_dereference_resource_template(t) for t in templates] | ||
|
|
||
|
|
||
| def _dereference_tool(tool: Tool) -> Tool: | ||
| """Return a copy of the tool with dereferenced schemas.""" | ||
| updates: dict[str, object] = {} | ||
| if "$defs" in tool.parameters or _has_ref(tool.parameters): | ||
| updates["parameters"] = dereference_refs(tool.parameters) | ||
| if tool.output_schema is not None and ( | ||
| "$defs" in tool.output_schema or _has_ref(tool.output_schema) | ||
| ): | ||
| updates["output_schema"] = dereference_refs(tool.output_schema) | ||
| if updates: | ||
| return tool.model_copy(update=updates) | ||
| return tool | ||
|
|
||
|
|
||
| def _dereference_resource_template(template: ResourceTemplate) -> ResourceTemplate: | ||
| """Return a copy of the template with dereferenced schemas.""" | ||
| if "$defs" in template.parameters or _has_ref(template.parameters): | ||
| return template.model_copy( | ||
| update={"parameters": dereference_refs(template.parameters)} | ||
| ) | ||
| return template | ||
|
|
||
|
|
||
| def _has_ref(schema: dict[str, Any]) -> bool: | ||
| """Check if a schema contains any $ref.""" | ||
| if "$ref" in schema: | ||
| return True | ||
| for value in schema.values(): | ||
| if isinstance(value, dict) and _has_ref(value): | ||
| return True | ||
| if isinstance(value, list): | ||
| for item in value: | ||
| if isinstance(item, dict) and _has_ref(item): | ||
| return True | ||
| return False |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| """Tests for DereferenceRefsMiddleware.""" | ||
|
|
||
| from enum import Enum | ||
|
|
||
| import pydantic | ||
|
|
||
| from fastmcp import Client, FastMCP | ||
|
|
||
|
|
||
| class Color(Enum): | ||
| RED = "red" | ||
| GREEN = "green" | ||
| BLUE = "blue" | ||
|
|
||
|
|
||
| class PaintRequest(pydantic.BaseModel): | ||
| color: Color | ||
| opacity: float = 1.0 | ||
|
|
||
|
|
||
| class TestDereferenceRefsMiddleware: | ||
| """End-to-end tests for the dereference_schemas server kwarg.""" | ||
|
|
||
| async def test_dereference_schemas_true_inlines_refs(self): | ||
| """With dereference_schemas=True (default), tool schemas have $ref inlined.""" | ||
| mcp = FastMCP("test", dereference_schemas=True) | ||
|
|
||
| @mcp.tool | ||
| def paint(request: PaintRequest) -> str: | ||
| return "ok" | ||
|
|
||
| async with Client(mcp) as client: | ||
| tools = await client.list_tools() | ||
|
|
||
| schema = tools[0].inputSchema | ||
| # $defs should be removed — everything inlined | ||
| assert "$defs" not in schema | ||
| # The Color enum should be inlined into the request property | ||
| assert "$ref" not in str(schema) | ||
|
|
||
| async def test_dereference_schemas_false_preserves_refs(self): | ||
| """With dereference_schemas=False, $ref and $defs are preserved.""" | ||
| mcp = FastMCP("test", dereference_schemas=False) | ||
|
|
||
| @mcp.tool | ||
| def paint(request: PaintRequest) -> str: | ||
| return "ok" | ||
|
|
||
| async with Client(mcp) as client: | ||
| tools = await client.list_tools() | ||
|
|
||
| schema = tools[0].inputSchema | ||
| # $defs should still be present | ||
| assert "$defs" in schema | ||
|
|
||
| async def test_default_is_true(self): | ||
| """Default behavior dereferences $ref.""" | ||
| mcp = FastMCP("test") | ||
|
|
||
| @mcp.tool | ||
| def paint(request: PaintRequest) -> str: | ||
| return "ok" | ||
|
|
||
| async with Client(mcp) as client: | ||
| tools = await client.list_tools() | ||
|
|
||
| schema = tools[0].inputSchema | ||
| assert "$defs" not in schema | ||
|
|
||
| async def test_does_not_mutate_original_tool(self): | ||
| """Middleware should not mutate the shared Tool object.""" | ||
| mcp = FastMCP("test", dereference_schemas=True) | ||
|
|
||
| @mcp.tool | ||
| def paint(request: PaintRequest) -> str: | ||
| return "ok" | ||
|
|
||
| # Get the original tool's parameters before middleware runs | ||
| original_tools = await mcp._local_provider._list_tools() | ||
| assert "$defs" in original_tools[0].parameters | ||
|
|
||
| # List tools through the client (triggers middleware) | ||
| async with Client(mcp) as client: | ||
| await client.list_tools() | ||
|
|
||
| # The original tool stored in the server should still have $defs | ||
| tools_after = await mcp._local_provider._list_tools() | ||
| assert "$defs" in tools_after[0].parameters | ||
|
|
||
| async def test_output_schema_dereferenced(self): | ||
| """Middleware also dereferences output_schema when present.""" | ||
| mcp = FastMCP("test", dereference_schemas=True) | ||
|
|
||
| @mcp.tool | ||
| def paint(request: PaintRequest) -> PaintRequest: | ||
| return request | ||
|
|
||
| async with Client(mcp) as client: | ||
| tools = await client.list_tools() | ||
|
|
||
| tool = tools[0] | ||
| # Both input and output schemas should be dereferenced | ||
| assert "$defs" not in tool.inputSchema | ||
| if tool.outputSchema is not None: | ||
| assert "$defs" not in tool.outputSchema | ||
|
|
||
| async def test_resource_templates_dereferenced(self): | ||
| """Middleware dereferences resource template schemas.""" | ||
| mcp = FastMCP("test", dereference_schemas=True) | ||
|
|
||
| @mcp.resource("paint://{color}") | ||
| def get_paint(color: Color) -> str: | ||
| return f"paint: {color}" | ||
|
|
||
| async with Client(mcp) as client: | ||
| templates = await client.list_resource_templates() | ||
|
|
||
| # Resource templates also get their schemas dereferenced | ||
| # (only if the template parameters have $ref) | ||
| assert len(templates) == 1 | ||
|
|
||
| async def test_no_ref_schemas_unchanged(self): | ||
| """Tools without $ref should pass through unmodified.""" | ||
| mcp = FastMCP("test", dereference_schemas=True) | ||
|
|
||
| @mcp.tool | ||
| def add(a: int, b: int) -> int: | ||
| return a + b | ||
|
|
||
| async with Client(mcp) as client: | ||
| tools = await client.list_tools() | ||
|
|
||
| schema = tools[0].inputSchema | ||
| # Simple schema should not have $defs regardless | ||
| assert "$defs" not in schema | ||
| assert schema["properties"]["a"]["type"] == "integer" |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Guarding
dereference_refs()behindif dereference:removes theresolve_root_ref()fallback for schemas with a root-level$ref, so callers that now pass throughcompress_schema(..., dereference=False)can emit output schemas without a roottype: object; this is a regression for recursive/self-referential return models when users setFastMCP(dereference_refs=False), becauselist_toolscan return MCP-incompatibleoutputSchemapayloads in that mode.Useful? React with 👍 / 👎.