🚀 The fast, Pythonic way to build MCP servers and clients.
Deprecate PromptToolMiddleware and ResourceToolMiddleware (#3389)
Jeremiah Lowine3b6b0c4705b
diff --git a/docs/servers/middleware.mdx b/docs/servers/middleware.mdxindex 40449ae10..424f5afa7 100644--- a/docs/servers/middleware.mdx+++ b/docs/servers/middleware.mdx@@ -535,30 +535,6 @@ mcp.add_middleware(PingMiddleware(interval_ms=5000))The ping task starts on the first message and stops automatically when the session ends. Most useful for stateful HTTP connections; has no effect on stateless connections.-### Tool Injection--```python-from fastmcp.server.middleware.tool_injection import (- ToolInjectionMiddleware,- PromptToolMiddleware,- ResourceToolMiddleware-)-```--`ToolInjectionMiddleware` dynamically injects tools during request processing. `PromptToolMiddleware` and `ResourceToolMiddleware` provide compatibility layers for clients that cannot list or access prompts and resources directly—they expose those capabilities as tools.--```python-from fastmcp import FastMCP-from fastmcp.tools import Tool-from fastmcp.server.middleware.tool_injection import ToolInjectionMiddleware--def my_tool_fn(a: int, b: int) -> int:- return a + b--my_tool = Tool.from_function(fn=my_tool_fn, name="my_tool")-mcp.add_middleware(ToolInjectionMiddleware(tools=[my_tool]))-```-### Response Limiting<VersionBadge version="3.0.0" />diff --git a/src/fastmcp/server/middleware/tool_injection.py b/src/fastmcp/server/middleware/tool_injection.pyindex 8f3ef0b43..e824eb8dc 100644--- a/src/fastmcp/server/middleware/tool_injection.py+++ b/src/fastmcp/server/middleware/tool_injection.py@@ -1,5 +1,6 @@"""A middleware for injecting tools into the MCP server context."""+import warningsfrom collections.abc import Sequencefrom logging import Loggerfrom typing import Annotated, Any@@ -9,6 +10,7 @@ from mcp.types import Promptfrom pydantic import AnyUrlfrom typing_extensions import override+import fastmcpfrom fastmcp.resources.resource import ResourceResultfrom fastmcp.server.context import Contextfrom fastmcp.server.middleware.middleware import CallNext, Middleware, MiddlewareContext@@ -78,9 +80,20 @@ get_prompt_tool = Tool.from_function(class PromptToolMiddleware(ToolInjectionMiddleware):- """A middleware for injecting prompts as tools into the context."""+ """A middleware for injecting prompts as tools into the context.++ .. deprecated::+ Use ``fastmcp.server.transforms.PromptsAsTools`` instead.+ """def __init__(self) -> None:+ if fastmcp.settings.deprecation_warnings:+ warnings.warn(+ "PromptToolMiddleware is deprecated. Use the PromptsAsTools transform instead: "+ "from fastmcp.server.transforms import PromptsAsTools",+ DeprecationWarning,+ stacklevel=2,+ )tools: list[Tool] = [list_prompts_tool, get_prompt_tool]super().__init__(tools=tools)@@ -109,8 +122,19 @@ read_resource_tool = Tool.from_function(class ResourceToolMiddleware(ToolInjectionMiddleware):- """A middleware for injecting resources as tools into the context."""+ """A middleware for injecting resources as tools into the context.++ .. deprecated::+ Use ``fastmcp.server.transforms.ResourcesAsTools`` instead.+ """def __init__(self) -> None:+ if fastmcp.settings.deprecation_warnings:+ warnings.warn(+ "ResourceToolMiddleware is deprecated. Use the ResourcesAsTools transform instead: "+ "from fastmcp.server.transforms import ResourcesAsTools",+ DeprecationWarning,+ stacklevel=2,+ )tools: list[Tool] = [list_resources_tool, read_resource_tool]super().__init__(tools=tools)diff --git a/tests/deprecated/test_tool_injection_middleware.py b/tests/deprecated/test_tool_injection_middleware.pynew file mode 100644index 000000000..af4f5df1c--- /dev/null+++ b/tests/deprecated/test_tool_injection_middleware.py@@ -0,0 +1,245 @@+"""Tests for deprecated PromptToolMiddleware and ResourceToolMiddleware."""++import pytest+from inline_snapshot import snapshot+from mcp.types import TextContent+from mcp.types import Tool as SDKTool++from fastmcp import FastMCP+from fastmcp.client import Client+from fastmcp.client.client import CallToolResult+from fastmcp.client.transports import FastMCPTransport+from fastmcp.server.middleware.tool_injection import (+ PromptToolMiddleware,+ ResourceToolMiddleware,+)+++class TestPromptToolMiddleware:+ """Tests for PromptToolMiddleware."""++ @pytest.fixture+ def server_with_prompts(self):+ """Create a FastMCP server with prompts."""+ mcp = FastMCP("PromptServer")++ @mcp.tool+ def add(a: int, b: int) -> int:+ """Add two numbers."""+ return a + b++ @mcp.prompt+ def greeting(name: str) -> str:+ """Generate a greeting message."""+ return f"Hello, {name}!"++ @mcp.prompt+ def farewell(name: str) -> str:+ """Generate a farewell message."""+ return f"Goodbye, {name}!"++ return mcp++ async def test_prompt_tools_added_to_list(self, server_with_prompts: FastMCP):+ """Test that prompt tools are added to the tool list."""+ middleware = PromptToolMiddleware()+ server_with_prompts.add_middleware(middleware)++ async with Client[FastMCPTransport](server_with_prompts) as client:+ tools: list[SDKTool] = await client.list_tools()++ tool_names: list[str] = [tool.name for tool in tools]+ # Should have: add, list_prompts, get_prompt+ assert len(tools) == 3+ assert "add" in tool_names+ assert "list_prompts" in tool_names+ assert "get_prompt" in tool_names++ async def test_list_prompts_tool_works(self, server_with_prompts: FastMCP):+ """Test that the list_prompts tool can be called."""+ middleware = PromptToolMiddleware()+ server_with_prompts.add_middleware(middleware)++ async with Client[FastMCPTransport](server_with_prompts) as client:+ result: CallToolResult = await client.call_tool(+ name="list_prompts", arguments={}+ )++ assert result.content == snapshot(+ [+ TextContent(+ type="text",+ text='[{"name":"greeting","title":null,"description":"Generate a greeting message.","arguments":[{"name":"name","description":null,"required":true}],"icons":null,"_meta":{"fastmcp":{"tags":[]}}},{"name":"farewell","title":null,"description":"Generate a farewell message.","arguments":[{"name":"name","description":null,"required":true}],"icons":null,"_meta":{"fastmcp":{"tags":[]}}}]',+ )+ ]+ )+ assert result.structured_content is not None+ assert result.structured_content["result"] == snapshot(+ [+ {+ "name": "greeting",+ "title": None,+ "description": "Generate a greeting message.",+ "arguments": [+ {"name": "name", "description": None, "required": True}+ ],+ "icons": None,+ "_meta": {"fastmcp": {"tags": []}},+ },+ {+ "name": "farewell",+ "title": None,+ "description": "Generate a farewell message.",+ "arguments": [+ {"name": "name", "description": None, "required": True}+ ],+ "icons": None,+ "_meta": {"fastmcp": {"tags": []}},+ },+ ]+ )++ async def test_get_prompt_tool_works(self, server_with_prompts: FastMCP):+ """Test that the get_prompt tool can be called."""+ middleware = PromptToolMiddleware()+ server_with_prompts.add_middleware(middleware)++ async with Client[FastMCPTransport](server_with_prompts) as client:+ result: CallToolResult = await client.call_tool(+ name="get_prompt",+ arguments={"name": "greeting", "arguments": {"name": "World"}},+ )++ # The tool returns the prompt result with structured_content+ assert result.content == snapshot(+ [+ TextContent(+ type="text",+ text='{"_meta":null,"description":"Generate a greeting message.","messages":[{"role":"user","content":{"type":"text","text":"Hello, World!","annotations":null,"_meta":null}}]}',+ )+ ]+ )+ assert result.structured_content is not None+ assert result.structured_content == snapshot(+ {+ "_meta": None,+ "description": "Generate a greeting message.",+ "messages": [+ {+ "role": "user",+ "content": {+ "type": "text",+ "text": "Hello, World!",+ "annotations": None,+ "_meta": None,+ },+ }+ ],+ }+ )+++class TestResourceToolMiddleware:+ """Tests for ResourceToolMiddleware."""++ @pytest.fixture+ def server_with_resources(self):+ """Create a FastMCP server with resources."""+ mcp = FastMCP("ResourceServer")++ @mcp.tool+ def add(a: int, b: int) -> int:+ """Add two numbers."""+ return a + b++ @mcp.resource("file://config.txt")+ def config_resource() -> str:+ """Get configuration."""+ return "debug=true"++ @mcp.resource("file://data.json")+ def data_resource() -> str:+ """Get data."""+ return '{"count": 42}'++ return mcp++ async def test_resource_tools_added_to_list(self, server_with_resources: FastMCP):+ """Test that resource tools are added to the tool list."""+ middleware = ResourceToolMiddleware()+ server_with_resources.add_middleware(middleware)++ async with Client[FastMCPTransport](server_with_resources) as client:+ tools: list[SDKTool] = await client.list_tools()++ tool_names: list[str] = [tool.name for tool in tools]+ # Should have: add, list_resources, read_resource+ assert len(tools) == 3+ assert "add" in tool_names+ assert "list_resources" in tool_names+ assert "read_resource" in tool_names++ async def test_list_resources_tool_works(self, server_with_resources: FastMCP):+ """Test that the list_resources tool can be called."""+ middleware = ResourceToolMiddleware()+ server_with_resources.add_middleware(middleware)++ async with Client[FastMCPTransport](server_with_resources) as client:+ result: CallToolResult = await client.call_tool(+ name="list_resources", arguments={}+ )++ assert result.structured_content is not None+ assert result.structured_content["result"] == snapshot(+ [+ {+ "name": "config_resource",+ "title": None,+ "uri": "file://config.txt/",+ "description": "Get configuration.",+ "mimeType": "text/plain",+ "size": None,+ "icons": None,+ "annotations": None,+ "_meta": {"fastmcp": {"tags": []}},+ },+ {+ "name": "data_resource",+ "title": None,+ "uri": "file://data.json/",+ "description": "Get data.",+ "mimeType": "text/plain",+ "size": None,+ "icons": None,+ "annotations": None,+ "_meta": {"fastmcp": {"tags": []}},+ },+ ]+ )++ async def test_read_resource_tool_works(self, server_with_resources: FastMCP):+ """Test that the read_resource tool can be called."""+ middleware = ResourceToolMiddleware()+ server_with_resources.add_middleware(middleware)++ async with Client[FastMCPTransport](server_with_resources) as client:+ result: CallToolResult = await client.call_tool(+ name="read_resource", arguments={"uri": "file://config.txt"}+ )++ assert result.content == snapshot(+ [+ TextContent(+ type="text",+ text='{"contents":[{"content":"debug=true","mime_type":"text/plain","meta":null}],"meta":null}',+ )+ ]+ )+ assert result.structured_content == snapshot(+ {+ "contents": [+ {"content": "debug=true", "mime_type": "text/plain", "meta": None}+ ],+ "meta": None,+ }+ )diff --git a/tests/server/middleware/test_tool_injection.py b/tests/server/middleware/test_tool_injection.pyindex 5a583f543..f16c132e6 100644--- a/tests/server/middleware/test_tool_injection.py+++ b/tests/server/middleware/test_tool_injection.py@@ -4,7 +4,6 @@ import mathimport pytestfrom inline_snapshot import snapshot-from mcp.types import TextContentfrom mcp.types import Tool as SDKToolfrom fastmcp import FastMCP@@ -12,8 +11,6 @@ from fastmcp.client import Clientfrom fastmcp.client.client import CallToolResultfrom fastmcp.client.transports import FastMCPTransportfrom fastmcp.server.middleware.tool_injection import (- PromptToolMiddleware,- ResourceToolMiddleware,ToolInjectionMiddleware,)from fastmcp.tools.function_tool import FunctionTool@@ -277,233 +274,3 @@ class TestToolInjectionMiddleware:assert result.structured_content is not Noneassert isinstance(result.structured_content, dict)assert result.structured_content["result"] == 7---class TestPromptToolMiddleware:- """Tests for PromptToolMiddleware."""-- @pytest.fixture- def server_with_prompts(self):- """Create a FastMCP server with prompts."""- mcp = FastMCP("PromptServer")-- @mcp.tool- def add(a: int, b: int) -> int:- """Add two numbers."""- return a + b-- @mcp.prompt- def greeting(name: str) -> str:- """Generate a greeting message."""- return f"Hello, {name}!"-- @mcp.prompt- def farewell(name: str) -> str:- """Generate a farewell message."""- return f"Goodbye, {name}!"-- return mcp-- async def test_prompt_tools_added_to_list(self, server_with_prompts: FastMCP):- """Test that prompt tools are added to the tool list."""- middleware = PromptToolMiddleware()- server_with_prompts.add_middleware(middleware)-- async with Client[FastMCPTransport](server_with_prompts) as client:- tools: list[SDKTool] = await client.list_tools()-- tool_names: list[str] = [tool.name for tool in tools]- # Should have: add, list_prompts, get_prompt- assert len(tools) == 3- assert "add" in tool_names- assert "list_prompts" in tool_names- assert "get_prompt" in tool_names-- async def test_list_prompts_tool_works(self, server_with_prompts: FastMCP):- """Test that the list_prompts tool can be called."""- middleware = PromptToolMiddleware()- server_with_prompts.add_middleware(middleware)-- async with Client[FastMCPTransport](server_with_prompts) as client:- result: CallToolResult = await client.call_tool(- name="list_prompts", arguments={}- )-- assert result.content == snapshot(- [- TextContent(- type="text",- text='[{"name":"greeting","title":null,"description":"Generate a greeting message.","arguments":[{"name":"name","description":null,"required":true}],"icons":null,"_meta":{"fastmcp":{"tags":[]}}},{"name":"farewell","title":null,"description":"Generate a farewell message.","arguments":[{"name":"name","description":null,"required":true}],"icons":null,"_meta":{"fastmcp":{"tags":[]}}}]',- )- ]- )- assert result.structured_content is not None- assert result.structured_content["result"] == snapshot(- [- {- "name": "greeting",- "title": None,- "description": "Generate a greeting message.",- "arguments": [- {"name": "name", "description": None, "required": True}- ],- "icons": None,- "_meta": {"fastmcp": {"tags": []}},- },- {- "name": "farewell",- "title": None,- "description": "Generate a farewell message.",- "arguments": [- {"name": "name", "description": None, "required": True}- ],- "icons": None,- "_meta": {"fastmcp": {"tags": []}},- },- ]- )-- async def test_get_prompt_tool_works(self, server_with_prompts: FastMCP):- """Test that the get_prompt tool can be called."""- middleware = PromptToolMiddleware()- server_with_prompts.add_middleware(middleware)-- async with Client[FastMCPTransport](server_with_prompts) as client:- result: CallToolResult = await client.call_tool(- name="get_prompt",- arguments={"name": "greeting", "arguments": {"name": "World"}},- )-- # The tool returns the prompt result with structured_content- assert result.content == snapshot(- [- TextContent(- type="text",- text='{"_meta":null,"description":"Generate a greeting message.","messages":[{"role":"user","content":{"type":"text","text":"Hello, World!","annotations":null,"_meta":null}}]}',- )- ]- )- assert result.structured_content is not None- assert result.structured_content == snapshot(- {- "_meta": None,- "description": "Generate a greeting message.",- "messages": [- {- "role": "user",- "content": {- "type": "text",- "text": "Hello, World!",- "annotations": None,- "_meta": None,- },- }- ],- }- )---class TestResourceToolMiddleware:- """Tests for ResourceToolMiddleware."""-- @pytest.fixture- def server_with_resources(self):- """Create a FastMCP server with resources."""- mcp = FastMCP("ResourceServer")-- @mcp.tool- def add(a: int, b: int) -> int:- """Add two numbers."""- return a + b-- @mcp.resource("file://config.txt")- def config_resource() -> str:- """Get configuration."""- return "debug=true"-- @mcp.resource("file://data.json")- def data_resource() -> str:- """Get data."""- return '{"count": 42}'-- return mcp-- async def test_resource_tools_added_to_list(self, server_with_resources: FastMCP):- """Test that resource tools are added to the tool list."""- middleware = ResourceToolMiddleware()- server_with_resources.add_middleware(middleware)-- async with Client[FastMCPTransport](server_with_resources) as client:- tools: list[SDKTool] = await client.list_tools()-- tool_names: list[str] = [tool.name for tool in tools]- # Should have: add, list_resources, read_resource- assert len(tools) == 3- assert "add" in tool_names- assert "list_resources" in tool_names- assert "read_resource" in tool_names-- async def test_list_resources_tool_works(self, server_with_resources: FastMCP):- """Test that the list_resources tool can be called."""- middleware = ResourceToolMiddleware()- server_with_resources.add_middleware(middleware)-- async with Client[FastMCPTransport](server_with_resources) as client:- result: CallToolResult = await client.call_tool(- name="list_resources", arguments={}- )-- assert result.structured_content is not None- assert result.structured_content["result"] == snapshot(- [- {- "name": "config_resource",- "title": None,- "uri": "file://config.txt/",- "description": "Get configuration.",- "mimeType": "text/plain",- "size": None,- "icons": None,- "annotations": None,- "_meta": {"fastmcp": {"tags": []}},- },- {- "name": "data_resource",- "title": None,- "uri": "file://data.json/",- "description": "Get data.",- "mimeType": "text/plain",- "size": None,- "icons": None,- "annotations": None,- "_meta": {"fastmcp": {"tags": []}},- },- ]- )-- async def test_read_resource_tool_works(self, server_with_resources: FastMCP):- """Test that the read_resource tool can be called."""- middleware = ResourceToolMiddleware()- server_with_resources.add_middleware(middleware)-- async with Client[FastMCPTransport](server_with_resources) as client:- result: CallToolResult = await client.call_tool(- name="read_resource", arguments={"uri": "file://config.txt"}- )-- assert result.content == snapshot(- [- TextContent(- type="text",- text='{"contents":[{"content":"debug=true","mime_type":"text/plain","meta":null}],"meta":null}',- )- ]- )- assert result.structured_content == snapshot(- {- "contents": [- {"content": "debug=true", "mime_type": "text/plain", "meta": None}- ],- "meta": None,- }- )