33import pytest
44
55from mcp .server .fastmcp import FastMCP
6+ from mcp .server .fastmcp .server import Context
67from mcp .server .fastmcp .tools .base import Tool
78from mcp .shared .memory import create_connected_server_and_client_session
89from mcp .types import TextContent
1213async def test_runtime_tools ():
1314 """Test that runtime tools work correctly."""
1415
15- async def runtime_mcp_tools_generator () -> list [Tool ]:
16+ async def runtime_mcp_tools_generator (ctx : Context ) -> list [Tool ]:
1617 """Generate runtime tools."""
1718
1819 def runtime_tool_1 (message : str ):
@@ -21,7 +22,17 @@ def runtime_tool_1(message: str):
2122 def runtime_tool_2 (message : str ):
2223 return message
2324
24- return [Tool .from_function (runtime_tool_1 ), Tool .from_function (runtime_tool_2 )]
25+ def runtime_tool_3 (message : str ):
26+ return message
27+
28+ tools = [Tool .from_function (runtime_tool_1 ), Tool .from_function (runtime_tool_2 )]
29+
30+ # Tool added only after authorization
31+ request = ctx .request_context .request
32+ if request and request .header .get ("Authorization" ) == "Bearer test_auth" :
33+ tools .append (Tool .from_function (runtime_tool_3 ))
34+
35+ return tools
2536
2637 # Create server with various tool configurations, both static and runtime
2738 mcp = FastMCP (name = "RuntimeToolsTestServer" , runtime_mcp_tools_generator = runtime_mcp_tools_generator )
@@ -31,7 +42,7 @@ def runtime_tool_2(message: str):
3142 def static_tool (message : str ) -> str :
3243 return message
3344
34- # Start server and connect client
45+ # Start server and connect client without authorization
3546 async with create_connected_server_and_client_session (mcp ._mcp_server ) as client :
3647 await client .initialize ()
3748
@@ -71,3 +82,10 @@ def static_tool(message: str) -> str:
7182 content = result .content [0 ]
7283 assert isinstance (content , TextContent )
7384 assert content .text == "Unknown tool: non_existing_tool"
85+
86+ # Check not authorized tool
87+ result = await client .call_tool ("runtime_tool_3" , {"message" : "This is a test" })
88+ assert len (result .content ) == 1
89+ content = result .content [0 ]
90+ assert isinstance (content , TextContent )
91+ assert content .text == "Unknown tool: runtime_tool_3"
0 commit comments