-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Fix(mcp): Unreachable structured content branch in invoke_mcp_tool #1250
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
Kunmeer-SyedMohamedHyder
wants to merge
3
commits into
openai:main
Choose a base branch
from
SyedMohamedHyder:fix/issue-1236
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
Fix(mcp): Unreachable structured content branch in invoke_mcp_tool #1250
Kunmeer-SyedMohamedHyder
wants to merge
3
commits into
openai:main
from
SyedMohamedHyder:fix/issue-1236
Conversation
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
Could you resolve the lint and typecheck errors? |
Hey @seratch. Fixed them! ![]() ![]() ![]() |
seratch
approved these changes
Jul 28, 2025
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.
Looks good to me; @rm-openai can you do final check before merging it?
![]() Following is the code I ran! #!/usr/bin/env python3
import asyncio
import json
from typing import Any
from mcp.types import CallToolResult, TextContent, Tool as MCPTool
from agents.run_context import RunContextWrapper
from agents.mcp import MCPServer, MCPUtil
class TestMCPServer(MCPServer):
def __init__(self, use_structured_content: bool = False):
super().__init__(use_structured_content=use_structured_content)
self._server_name = "test_server"
async def cleanup(self) -> None:
pass
async def connect(self) -> None:
pass
async def get_prompt(self, name: str, arguments: dict[str, Any] | None = None):
raise NotImplementedError()
async def list_prompts(self, run_context: RunContextWrapper[Any], agent):
return []
@property
def name(self) -> str:
return self._server_name
async def list_tools(self, run_context: RunContextWrapper[Any], agent) -> list:
return [MCPTool(name="search_users", description="test", inputSchema={"type": "object"})]
async def call_tool(self, tool_name: str, arguments: dict[str, Any] | None) -> CallToolResult:
return CallToolResult(
content=[TextContent(text="Found 2 users", type="text")],
structuredContent={
"users": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}],
"total": 2
}
)
async def test_structured_content_fix():
print("Testing MCP Structured Content Fix (Issue #1236)")
run_context = RunContextWrapper(context=None)
tool = MCPTool(name="search_users", description="test", inputSchema={"type": "object"})
# Test 1: use_structured_content=False (returns text content)
print("\nTest 1: use_structured_content=False")
server_text = TestMCPServer(use_structured_content=False)
result = await MCPUtil.invoke_mcp_tool(server_text, tool, run_context, "{}")
parsed = json.loads(result)
print(f"Result: {result}")
print(f"PASS: Returns text content" if "text" in parsed else "FAIL: Expected text content")
# Test 2: use_structured_content=True (THE FIX - returns structured content)
print("\nTest 2: use_structured_content=True (THE FIX)")
print("Before fix: Would return text content (unreachable path)")
print("After fix: Returns structured content exclusively")
server_structured = TestMCPServer(use_structured_content=True)
result_structured = await MCPUtil.invoke_mcp_tool(server_structured, tool, run_context, "{}")
parsed_structured = json.loads(result_structured)
print(f"Result: {result_structured}")
if "users" in parsed_structured and "text" not in parsed_structured:
print(f"PASS: Returns structured content exclusively")
print(f"Found {len(parsed_structured['users'])} users")
print("FIX CONFIRMED: Previously unreachable code now works!")
else:
print("FAIL: Expected structured content or found text mixing")
# Test 3: Fallback when no structured content
print("\nTest 3: Fallback when no structured content")
class FallbackServer(TestMCPServer):
async def call_tool(self, tool_name: str, arguments: dict[str, Any] | None):
return CallToolResult(
content=[TextContent(text="No structured data", type="text")],
structuredContent=None
)
server_fallback = FallbackServer(use_structured_content=True)
result_fallback = await MCPUtil.invoke_mcp_tool(server_fallback, tool, run_context, "{}")
parsed_fallback = json.loads(result_fallback)
print(f"Result: {result_fallback}")
print("PASS: Fallback to text content works" if parsed_fallback.get("text") == "No structured data" else "FAIL: Fallback behavior not working")
if __name__ == "__main__":
asyncio.run(test_structured_content_fix()) Did a quick test @seratch!! BTW thanks to GPT! 😄 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
This PR handles the MCP tool output where structured content could never be returned exclusively when
use_structured_content=True
. The conditional logic checked for content length first, making the structured content branch unreachable when both content types were present.Before (broken logic):
After (fixed logic):
Example usage:
Test plan
I've added thorough test coverage to make sure this fix works properly:
Issue number
Fixes #1236
Checks
make lint
andmake format
- Code follows project formatting standards