-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Python: Allow @tool functions to return rich content (images, audio) #4331
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
giles17
wants to merge
3
commits into
microsoft:main
Choose a base branch
from
giles17:giles/tool-rich-content-results
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
3 commits
Select commit
Hold shift + click to select a range
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
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 |
|---|---|---|
|
|
@@ -142,38 +142,44 @@ def _parse_message_from_mcp( | |
|
|
||
| def _parse_tool_result_from_mcp( | ||
| mcp_type: types.CallToolResult, | ||
| ) -> str: | ||
| """Parse an MCP CallToolResult directly into a string representation. | ||
| ) -> str | list[Content]: | ||
| """Parse an MCP CallToolResult into a string or rich content list. | ||
|
|
||
| Converts each content item in the MCP result to its string form and combines them. | ||
| This skips the intermediate Content object step for tool results. | ||
| Converts each content item in the MCP result to its appropriate form. | ||
| Text-only results are returned as strings. When the result contains | ||
| image or audio content, returns a list of Content objects so the | ||
| framework can forward the rich media to the model. | ||
|
|
||
| Args: | ||
| mcp_type: The MCP CallToolResult object to convert. | ||
|
|
||
| Returns: | ||
| A string representation of the tool result — either plain text or serialized JSON. | ||
| A string for text-only results, or a list of Content for rich media results. | ||
| """ | ||
| import json | ||
|
|
||
| parts: list[str] = [] | ||
| text_parts: list[str] = [] | ||
| rich_items: list[Content] = [] | ||
| for item in mcp_type.content: | ||
| match item: | ||
| case types.TextContent(): | ||
| parts.append(item.text) | ||
| case types.ImageContent() | types.AudioContent(): | ||
| parts.append( | ||
| json.dumps( | ||
| { | ||
| "type": "image" if isinstance(item, types.ImageContent) else "audio", | ||
| "data": item.data, | ||
| "mimeType": item.mimeType, | ||
| }, | ||
| default=str, | ||
| text_parts.append(item.text) | ||
| case types.ImageContent(): | ||
| rich_items.append( | ||
| Content.from_uri( | ||
| uri=f"data:{item.mimeType};base64,{item.data}", | ||
| media_type=item.mimeType, | ||
| ) | ||
| ) | ||
| case types.AudioContent(): | ||
| rich_items.append( | ||
| Content.from_uri( | ||
| uri=f"data:{item.mimeType};base64,{item.data}", | ||
| media_type=item.mimeType, | ||
| ) | ||
| ) | ||
| case types.ResourceLink(): | ||
| parts.append( | ||
| text_parts.append( | ||
| json.dumps( | ||
| { | ||
| "type": "resource_link", | ||
|
|
@@ -186,9 +192,9 @@ def _parse_tool_result_from_mcp( | |
| case types.EmbeddedResource(): | ||
| match item.resource: | ||
| case types.TextResourceContents(): | ||
| parts.append(item.resource.text) | ||
| text_parts.append(item.resource.text) | ||
| case types.BlobResourceContents(): | ||
| parts.append( | ||
| text_parts.append( | ||
| json.dumps( | ||
| { | ||
| "type": "blob", | ||
|
|
@@ -199,12 +205,21 @@ def _parse_tool_result_from_mcp( | |
| ) | ||
| ) | ||
| case _: | ||
| parts.append(str(item)) | ||
| if not parts: | ||
| text_parts.append(str(item)) | ||
|
|
||
| if rich_items: | ||
| # Return rich content list with text items included | ||
| result: list[Content] = [] | ||
| for text in text_parts: | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This will change the order of the content since we don't know what came first, not sure if that's an issue but might be good to doublecheck |
||
| result.append(Content.from_text(text)) | ||
| result.extend(rich_items) | ||
| return result | ||
|
|
||
| if not text_parts: | ||
| return "" | ||
| if len(parts) == 1: | ||
| return parts[0] | ||
| return json.dumps(parts, default=str) | ||
| if len(text_parts) == 1: | ||
| return text_parts[0] | ||
| return json.dumps(text_parts, default=str) | ||
|
|
||
|
|
||
| def _parse_content_from_mcp( | ||
|
|
@@ -425,7 +440,7 @@ def __init__( | |
| approval_mode: (Literal["always_require", "never_require"] | MCPSpecificApproval | None) = None, | ||
| allowed_tools: Collection[str] | None = None, | ||
| load_tools: bool = True, | ||
| parse_tool_results: Callable[[types.CallToolResult], str] | None = None, | ||
| parse_tool_results: Callable[[types.CallToolResult], str | list[Content]] | None = None, | ||
| load_prompts: bool = True, | ||
| parse_prompt_results: Callable[[types.GetPromptResult], str] | None = None, | ||
| session: ClientSession | None = None, | ||
|
|
@@ -850,7 +865,7 @@ async def _ensure_connected(self) -> None: | |
| inner_exception=ex, | ||
| ) from ex | ||
|
|
||
| async def call_tool(self, tool_name: str, **kwargs: Any) -> str: | ||
| async def call_tool(self, tool_name: str, **kwargs: Any) -> str | list[Content]: | ||
| """Call a tool with the given arguments. | ||
|
|
||
| Args: | ||
|
|
@@ -860,7 +875,7 @@ async def call_tool(self, tool_name: str, **kwargs: Any) -> str: | |
| kwargs: Arguments to pass to the tool. | ||
|
|
||
| Returns: | ||
| A string representation of the tool result — either plain text or serialized JSON. | ||
| A string for text-only results, or a list of Content for rich media results. | ||
|
|
||
| Raises: | ||
| ToolExecutionException: If the MCP server is not connected, tools are not loaded, | ||
|
|
@@ -1053,7 +1068,7 @@ def __init__( | |
| command: str, | ||
| *, | ||
| load_tools: bool = True, | ||
| parse_tool_results: Callable[[types.CallToolResult], str] | None = None, | ||
| parse_tool_results: Callable[[types.CallToolResult], str | list[Content]] | None = None, | ||
| load_prompts: bool = True, | ||
| parse_prompt_results: Callable[[types.GetPromptResult], str] | None = None, | ||
| request_timeout: int | None = None, | ||
|
|
@@ -1178,7 +1193,7 @@ def __init__( | |
| url: str, | ||
| *, | ||
| load_tools: bool = True, | ||
| parse_tool_results: Callable[[types.CallToolResult], str] | None = None, | ||
| parse_tool_results: Callable[[types.CallToolResult], str | list[Content]] | None = None, | ||
| load_prompts: bool = True, | ||
| parse_prompt_results: Callable[[types.GetPromptResult], str] | None = None, | ||
| request_timeout: int | None = None, | ||
|
|
@@ -1297,7 +1312,7 @@ def __init__( | |
| url: str, | ||
| *, | ||
| load_tools: bool = True, | ||
| parse_tool_results: Callable[[types.CallToolResult], str] | None = None, | ||
| parse_tool_results: Callable[[types.CallToolResult], str | list[Content]] | None = None, | ||
| load_prompts: bool = True, | ||
| parse_prompt_results: Callable[[types.GetPromptResult], str] | None = None, | ||
| request_timeout: int | None = 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.
Uh oh!
There was an error while loading. Please reload this page.