openai-agents-python/examples/hosted_mcp/approvals.py
Kazuhiro Sera 3e7b2863e9
Fix #777 by handling MCPCall events in RunImpl (#799)
This pull request resolves #777; If you think we should introduce a new
item type for MCP call output, please let me know. As other hosted tools
use this event, I believe using the same should be good to go tho.
2025-06-02 11:10:07 -04:00

61 lines
1.9 KiB
Python

import argparse
import asyncio
from agents import (
Agent,
HostedMCPTool,
MCPToolApprovalFunctionResult,
MCPToolApprovalRequest,
Runner,
)
"""This example demonstrates how to use the hosted MCP support in the OpenAI Responses API, with
approval callbacks."""
def approval_callback(request: MCPToolApprovalRequest) -> MCPToolApprovalFunctionResult:
answer = input(f"Approve running the tool `{request.data.name}`? (y/n) ")
result: MCPToolApprovalFunctionResult = {"approve": answer == "y"}
if not result["approve"]:
result["reason"] = "User denied"
return result
async def main(verbose: bool, stream: bool):
agent = Agent(
name="Assistant",
tools=[
HostedMCPTool(
tool_config={
"type": "mcp",
"server_label": "gitmcp",
"server_url": "https://gitmcp.io/openai/codex",
"require_approval": "always",
},
on_approval_request=approval_callback,
)
],
)
if stream:
result = Runner.run_streamed(agent, "Which language is this repo written in?")
async for event in result.stream_events():
if event.type == "run_item_stream_event":
print(f"Got event of type {event.item.__class__.__name__}")
print(f"Done streaming; final result: {result.final_output}")
else:
res = await Runner.run(agent, "Which language is this repo written in?")
print(res.final_output)
if verbose:
for item in res.new_items:
print(item)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", action="store_true", default=False)
parser.add_argument("--stream", action="store_true", default=False)
args = parser.parse_args()
asyncio.run(main(args.verbose, args.stream))