|
| 1 | +import argparse |
| 2 | +import asyncio |
| 3 | + |
| 4 | +from agents import ( |
| 5 | + Agent, |
| 6 | + HostedMCPTool, |
| 7 | + MCPToolApprovalFunctionResult, |
| 8 | + MCPToolApprovalRequest, |
| 9 | + Runner, |
| 10 | +) |
| 11 | + |
| 12 | +"""This example demonstrates how to use the hosted MCP support in the OpenAI Responses API, with |
| 13 | +approval callbacks.""" |
| 14 | + |
| 15 | + |
| 16 | +def approval_callback(request: MCPToolApprovalRequest) -> MCPToolApprovalFunctionResult: |
| 17 | + answer = input(f"Approve running the tool `{request.data.name}`? (y/n) ") |
| 18 | + result: MCPToolApprovalFunctionResult = {"approve": answer == "y"} |
| 19 | + if not result["approve"]: |
| 20 | + result["reason"] = "User denied" |
| 21 | + return result |
| 22 | + |
| 23 | + |
| 24 | +async def main(verbose: bool, stream: bool): |
| 25 | + agent = Agent( |
| 26 | + name="Assistant", |
| 27 | + tools=[ |
| 28 | + HostedMCPTool( |
| 29 | + tool_config={ |
| 30 | + "type": "mcp", |
| 31 | + "server_label": "gitmcp", |
| 32 | + "server_url": "https://gitmcp.io/openai/codex", |
| 33 | + "require_approval": "always", |
| 34 | + }, |
| 35 | + on_approval_request=approval_callback, |
| 36 | + ) |
| 37 | + ], |
| 38 | + ) |
| 39 | + |
| 40 | + if stream: |
| 41 | + result = Runner.run_streamed(agent, "Which language is this repo written in?") |
| 42 | + async for event in result.stream_events(): |
| 43 | + if event.type == "run_item_stream_event": |
| 44 | + print(f"Got event of type {event.item.__class__.__name__}") |
| 45 | + print(f"Done streaming; final result: {result.final_output}") |
| 46 | + else: |
| 47 | + res = await Runner.run(agent, "Which language is this repo written in?") |
| 48 | + print(res.final_output) |
| 49 | + |
| 50 | + if verbose: |
| 51 | + for item in result.new_items: |
| 52 | + print(item) |
| 53 | + |
| 54 | + |
| 55 | +if __name__ == "__main__": |
| 56 | + parser = argparse.ArgumentParser() |
| 57 | + parser.add_argument("--verbose", action="store_true", default=False) |
| 58 | + parser.add_argument("--stream", action="store_true", default=False) |
| 59 | + args = parser.parse_args() |
| 60 | + |
| 61 | + asyncio.run(main(args.verbose, args.stream)) |
0 commit comments