-
Notifications
You must be signed in to change notification settings - Fork 1.5k
[Draft] Convert BulkToolCaller to middleware #2267
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
Open
strawgate
wants to merge
4
commits into
main
Choose a base branch
from
claude/issue-2262-20251026-1426
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
e606d36
feat: convert BulkToolCaller to middleware
github-actions[bot] 009772a
Merge branch 'main' into claude/issue-2262-20251026-1426
strawgate 916c8e6
Merge branch 'main' into claude/issue-2262-20251026-1426
strawgate a11e3ab
Address PR feedback: preserve fields and improve type hints
github-actions[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
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
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,192 @@ | ||
| """Middleware for bulk tool calling functionality.""" | ||
|
|
||
| from typing import Annotated | ||
|
|
||
| from mcp.types import TextContent | ||
|
|
||
| from fastmcp.server.context import Context | ||
| from fastmcp.server.middleware.bulk_tool_caller_types import ( | ||
| CallToolRequest, | ||
| CallToolRequestResult, | ||
| ) | ||
| from fastmcp.server.middleware.tool_injection import ToolInjectionMiddleware | ||
| from fastmcp.tools.tool import Tool | ||
|
|
||
|
|
||
| async def call_tools_bulk( | ||
| context: Context, | ||
| tool_calls: Annotated[ | ||
| list[CallToolRequest], | ||
| "List of tool calls to execute. Each call can be for a different tool with different arguments.", | ||
| ], | ||
| continue_on_error: Annotated[ | ||
| bool, | ||
| "If True, continue executing remaining tools even if one fails. If False, stop on first error.", | ||
| ] = True, | ||
| ) -> list[CallToolRequestResult]: | ||
| """Call multiple tools registered on this MCP server in a single request. | ||
|
|
||
| Each call can be for a different tool and can include different arguments. | ||
| Useful for speeding up what would otherwise take several individual tool calls. | ||
|
|
||
| Args: | ||
| context: The request context providing access to the server | ||
| tool_calls: List of tool calls to execute | ||
| continue_on_error: Whether to continue on errors (default: True) | ||
|
|
||
| Returns: | ||
| List of results, one per tool call | ||
| """ | ||
| results = [] | ||
|
|
||
| for tool_call in tool_calls: | ||
| try: | ||
| # Call the tool directly through the tool manager | ||
| tool_result = await context.fastmcp._tool_manager.call_tool( | ||
| key=tool_call.tool, arguments=tool_call.arguments | ||
| ) | ||
|
|
||
| # Convert ToolResult to CallToolRequestResult, preserving all fields | ||
| # Note: ToolResult doesn't have isError - it's only on CallToolResult | ||
| # For successful calls, we don't set isError (defaults to None) | ||
| results.append( | ||
| CallToolRequestResult( | ||
| tool=tool_call.tool, | ||
| arguments=tool_call.arguments, | ||
| content=tool_result.content, | ||
| structuredContent=tool_result.structured_content, | ||
| ) | ||
| ) | ||
| except Exception as e: | ||
| # Create error result | ||
| error_message = f"Error calling tool '{tool_call.tool}': {e}" | ||
| results.append( | ||
| CallToolRequestResult( | ||
| tool=tool_call.tool, | ||
| arguments=tool_call.arguments, | ||
| isError=True, | ||
| content=[TextContent(text=error_message, type="text")], | ||
| ) | ||
| ) | ||
|
|
||
| if not continue_on_error: | ||
| break | ||
|
|
||
| return results | ||
|
|
||
|
|
||
| async def call_tool_bulk( | ||
| context: Context, | ||
| tool: Annotated[str, "The name of the tool to call multiple times."], | ||
| tool_arguments: Annotated[ | ||
| list[dict[str, str | int | float | bool | None]], | ||
| "List of argument dictionaries. Each dictionary contains the arguments for one tool invocation.", | ||
| ], | ||
| continue_on_error: Annotated[ | ||
| bool, | ||
| "If True, continue executing remaining calls even if one fails. If False, stop on first error.", | ||
| ] = True, | ||
| ) -> list[CallToolRequestResult]: | ||
| """Call a single tool registered on this MCP server multiple times with a single request. | ||
|
|
||
| Each call can include different arguments. Useful for speeding up what would | ||
| otherwise take several individual tool calls. | ||
|
|
||
| Args: | ||
| context: The request context providing access to the server | ||
| tool: The name of the tool to call | ||
| tool_arguments: List of argument dictionaries for each invocation | ||
| continue_on_error: Whether to continue on errors (default: True) | ||
|
|
||
| Returns: | ||
| List of results, one per invocation | ||
| """ | ||
| results = [] | ||
|
|
||
| for args in tool_arguments: | ||
| try: | ||
| # Call the tool directly through the tool manager | ||
| tool_result = await context.fastmcp._tool_manager.call_tool( | ||
| key=tool, arguments=args | ||
| ) | ||
|
|
||
| # Convert ToolResult to CallToolRequestResult, preserving all fields | ||
| # Note: ToolResult doesn't have isError - it's only on CallToolResult | ||
| # For successful calls, we don't set isError (defaults to None) | ||
| results.append( | ||
| CallToolRequestResult( | ||
| tool=tool, | ||
| arguments=args, | ||
| content=tool_result.content, | ||
| structuredContent=tool_result.structured_content, | ||
| ) | ||
| ) | ||
| except Exception as e: | ||
| # Create error result | ||
| error_message = f"Error calling tool '{tool}': {e}" | ||
| results.append( | ||
| CallToolRequestResult( | ||
| tool=tool, | ||
| arguments=args, | ||
| isError=True, | ||
| content=[TextContent(text=error_message, type="text")], | ||
| ) | ||
| ) | ||
|
|
||
| if not continue_on_error: | ||
| break | ||
|
|
||
| return results | ||
|
|
||
|
|
||
| class BulkToolCallerMiddleware(ToolInjectionMiddleware): | ||
| """Middleware for injecting bulk tool calling capabilities into the server. | ||
|
|
||
| This middleware adds two tools to the server: | ||
| - call_tools_bulk: Call multiple different tools in a single request | ||
| - call_tool_bulk: Call a single tool multiple times with different arguments | ||
|
|
||
| Example: | ||
| ```python | ||
| from fastmcp import FastMCP | ||
| from fastmcp.server.middleware import BulkToolCallerMiddleware | ||
|
|
||
| mcp = FastMCP("MyServer", middleware=[BulkToolCallerMiddleware()]) | ||
|
|
||
| @mcp.tool | ||
| def greet(name: str) -> str: | ||
| return f"Hello, {name}!" | ||
|
|
||
| @mcp.tool | ||
| def add(a: int, b: int) -> int: | ||
| return a + b | ||
| ``` | ||
|
|
||
| Now clients can use bulk calling: | ||
| ```python | ||
| # Call multiple different tools | ||
| result = await client.call_tool("call_tools_bulk", { | ||
| "tool_calls": [ | ||
| {"tool": "greet", "arguments": {"name": "Alice"}}, | ||
| {"tool": "add", "arguments": {"a": 1, "b": 2}} | ||
| ] | ||
| }) | ||
|
|
||
| # Call same tool multiple times | ||
| result = await client.call_tool("call_tool_bulk", { | ||
| "tool": "greet", | ||
| "tool_arguments": [ | ||
| {"name": "Alice"}, | ||
| {"name": "Bob"} | ||
| ] | ||
| }) | ||
| ``` | ||
| """ | ||
|
|
||
| def __init__(self) -> None: | ||
| """Initialize the bulk tool caller middleware.""" | ||
| tools: list[Tool] = [ | ||
| Tool.from_function(call_tools_bulk), | ||
| Tool.from_function(call_tool_bulk), | ||
| ] | ||
| super().__init__(tools=tools) |
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,41 @@ | ||
| """Types for bulk tool caller.""" | ||
|
|
||
| from typing import Any | ||
|
|
||
| from mcp.types import CallToolResult | ||
| from pydantic import BaseModel, Field | ||
|
|
||
|
|
||
| class CallToolRequest(BaseModel): | ||
| """A class to represent a request to call a tool with specific arguments.""" | ||
|
|
||
| tool: str = Field(description="The name of the tool to call.") | ||
| arguments: dict[str, Any] = Field( | ||
| description="A dictionary containing the arguments for the tool call." | ||
| ) | ||
|
|
||
|
|
||
| class CallToolRequestResult(CallToolResult): | ||
| """A class to represent the result of a bulk tool call. | ||
|
|
||
| It extends CallToolResult to include information about the requested tool call. | ||
| """ | ||
|
|
||
| tool: str = Field(description="The name of the tool that was called.") | ||
| arguments: dict[str, Any] = Field( | ||
| description="The arguments used for the tool call." | ||
| ) | ||
|
|
||
| @classmethod | ||
| def from_call_tool_result( | ||
| cls, result: CallToolResult, tool: str, arguments: dict[str, Any] | ||
| ) -> "CallToolRequestResult": | ||
| """Create a CallToolRequestResult from a CallToolResult.""" | ||
| return cls( | ||
| tool=tool, | ||
| arguments=arguments, | ||
| isError=result.isError, | ||
| content=result.content, | ||
| _meta=getattr(result, "_meta", None), | ||
| structuredContent=getattr(result, "structuredContent", None), | ||
| ) | ||
Oops, something went wrong.
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.
The
from_call_tool_resultmethod doesn't copy the_metaorstructuredContentfields from the sourceCallToolResult. If these fields contain values, they will be lost in the conversion. Consider including these fields:_meta=result._meta, structuredContent=result.structuredContent