diff --git a/examples/basic/typed_answer_repair.md b/examples/basic/typed_answer_repair.md new file mode 100644 index 0000000000..4f7959d635 --- /dev/null +++ b/examples/basic/typed_answer_repair.md @@ -0,0 +1,9 @@ +# Repair typed answers within a fixed budget + +Run `uv run python examples/basic/typed_answer_repair.py` and `uv run python examples/mcp/bounded_tool_output/main.py` from this checkout with development dependencies. Neither needs model credentials. + +The semantic repair example parses a Pydantic Verdict and checks its evidence count in the existing final-output policy. Dynamic instructions read fixed feedback from application-owned context. A second invalid candidate raises a fixed RepairLimitError. Provisional candidates may remain in private model history; approve only the validated final answer for display. By default, Runner closes the provider it creates. If you pass a `run_config`, you must close its provider, such as `CodexProvider`, after its last use. The helper disables tracing for its own run and leaves your configuration unchanged. Offline checks do not prove live/native behavior. + +Malformed JSON or incompatible types fail during SDK parsing before final_output_policy. The separate tool-free `repair_schema` helper demonstrates two fresh synthetic attempts, with no session and no rejected text in the next request. It catches the SDK parser error without displaying its text, then fails with a fixed message when exhausted. Do not generalize new-run retries to providers that may perform native side effects. + +The bounded-output recipe reuses PR #6120 at `482dac681ab40a5d9f037f11b7bfa90f482862b7`. Originals stay in a per-owner ephemeral store; authorized reads retrieve them privately and close revokes every reference. The integration converts local source-read exceptions into a fixed unavailable result before SDK tracing/history. It preserves the recipe's limits for small results, remote MCP errors, images, metadata, unselected results and native/hosted execution. A configured summary must itself be safe to disclose. diff --git a/examples/basic/typed_answer_repair.py b/examples/basic/typed_answer_repair.py new file mode 100644 index 0000000000..4105d26a21 --- /dev/null +++ b/examples/basic/typed_answer_repair.py @@ -0,0 +1,141 @@ +"""Bounded semantic repair through the existing final-output policy, offline.""" + +import asyncio +from dataclasses import dataclass, replace +from typing import Literal + +from pydantic import BaseModel + +from agents import ( + Agent, + AgentHooks, + ModelBehaviorError, + ProposedFinalOutput, + RunConfig, + RunContextWrapper, + Runner, + RunResultStreaming, +) +from agents.models.interface import Model +from agents.testing import ScriptedModel, assistant_message + + +class Verdict(BaseModel): + decision: Literal["approve", "reject"] + evidence_count: int + + +class RepairLimitError(RuntimeError): + """The application declined to accept a candidate within its fixed budget.""" + + +@dataclass +class Review: + attempts: int = 0 + feedback: str = "Return a verdict supported by at least one evidence item." + + +def validate_candidate( + context: RunContextWrapper[Review], proposal: ProposedFinalOutput[Review] +) -> Literal["finish", "continue"]: + context.context.attempts += 1 + candidate = proposal.output + if isinstance(candidate, Verdict) and candidate.evidence_count > 0: + return "finish" + if context.context.attempts >= 2: + raise RepairLimitError("No acceptable verdict within two candidates") + # Dynamic instructions give fixed feedback without copying the rejected text. + context.context.feedback = "Repair the verdict: include a positive evidence_count." + return "continue" + + +async def _drain_stream(run: RunResultStreaming) -> None: + """Discard raw events and join provider cleanup before returning.""" + + async def drain() -> None: + async for _ in run.stream_events(): + pass + + # Cancelling the reader itself can let it return before cleanup finishes. + reader = asyncio.create_task(drain()) + try: + await asyncio.shield(reader) + except asyncio.CancelledError: + run.cancel() + while not reader.done(): + try: + await asyncio.wait((reader,)) + except asyncio.CancelledError: + pass + if not reader.cancelled(): + reader.exception() # A secondary error must not replace caller cancellation. + raise + + +async def repair( + model: Model | str | None, *, streamed: bool = False, run_config: RunConfig | None = None +) -> tuple[Verdict, Review]: + context = Review() + agent = Agent[Review]( + name="reviewer", + model=model, + output_type=Verdict, + instructions=lambda ctx, agent: ctx.context.feedback, + hooks=AgentHooks(final_output_policy=validate_candidate), + ) + config = ( + {"tracing_disabled": True} + if run_config is None + else replace(run_config, tracing_disabled=True) + ) + if streamed: + result = Runner.run_streamed( + agent, "Review the synthetic evidence.", context=context, run_config=config, max_turns=2 + ) + # Discard raw events privately, even if the producer has already started. + await _drain_stream(result) + else: + result = await Runner.run( + agent, "Review the synthetic evidence.", context=context, run_config=config, max_turns=2 + ) + return result.final_output_as(Verdict), context + + +async def repair_schema(model: ScriptedModel) -> tuple[Verdict, int]: + """Retry malformed synthetic answers at most twice without replaying bad text. + + This separate offline recipe uses a tool-free scripted model. Do not apply + automatic new-run retries to a provider that may perform native side effects. + Each attempt has no session, so a malformed candidate enters no next request. + """ + for attempt in range(1, 3): + try: + result = await Runner.run( + Agent(name="schema reviewer", model=model, output_type=Verdict), + "Return JSON with decision approve/reject and positive evidence_count.", + run_config={"tracing_disabled": True}, + max_turns=1, + ) + except ModelBehaviorError: + # Parsing precedes final_output_policy. Never feed the error or raw + # rejected text back into the next request or display it to a user. + continue + answer = result.final_output_as(Verdict) + if answer.evidence_count > 0: + return answer, attempt + raise RepairLimitError("No acceptable typed verdict within two attempts") + + +async def main() -> None: + model = ScriptedModel( + [ + [assistant_message('{"decision":"approve","evidence_count":0}')], + [assistant_message('{"decision":"reject","evidence_count":1}')], + ] + ) + answer, review = await repair(model) + print(answer.model_dump_json(), f"Candidates: {review.attempts}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/mcp/README.md b/examples/mcp/README.md index f5c65f1dd4..cf8675aa05 100644 --- a/examples/mcp/README.md +++ b/examples/mcp/README.md @@ -8,6 +8,7 @@ These examples connect agents to Model Context Protocol servers. Follow the [exa | Inspect a Git repository | [Git](git_example/README.md) | `uvx`, Git, and a repository path. | | Prefetch tools | [Get all tools](get_all_mcp_tools_example/README.md) | `npx`. | | Restrict available tools | [Tool filtering](tool_filter_example/README.md) | `npx`. | +| Retrieve large reports privately | [Bounded tool output](bounded_tool_output/README.md) | Runs offline with a local server and no API key. | | Start or configure an SSE server | [SSE](sse_example/README.md) and [remote SSE](sse_remote_example/README.md) | Local development environment or configured endpoint. | | Use Streamable HTTP | [Local server](streamablehttp_example/README.md), [remote server](streamable_http_remote_example/README.md), and [custom client](streamablehttp_custom_client_example/README.md) | See each README for dependencies and endpoints. | | Load MCP prompts | [Prompt server](prompt_server/README.md) | Local development environment. | diff --git a/examples/mcp/bounded_tool_output/README.md b/examples/mcp/bounded_tool_output/README.md new file mode 100644 index 0000000000..d223635338 --- /dev/null +++ b/examples/mcp/bounded_tool_output/README.md @@ -0,0 +1,48 @@ +# Keep large tool results out of the conversation + +Run the example from this source checkout. It uses a scripted model and a local MCP server over stdio. No API key is needed. + +```sh +uv run python examples/mcp/bounded_tool_output/main.py +``` + +Both inspection reports exceed the example's 128-byte text budget. The next model request, SDK history and caller receive warning counts of 20 and 8 with random references. The example prints each saved summary and checks the first page privately. + +## Choose what to share + +[main.py](main.py) uses two routes. + +- `reports.site_tool()` binds `inspect_site` to the private store. The function checks access before reading the report, applies the budget and checks access again before returning. Any output editor receives the result after those checks. +- For SDK-discovered MCP tools, each `ReportServer` applies the policy to `read.report` by raw tool name, regardless of the server's display name. Its `call_tool` method checks `isError` and sees every block. It replaces large successful reports before SDK conversion, custom data extraction and function span output capture. Other tools and ordinary `MCPServerStdio` instances keep their usual behavior. + +For a nonempty structured object, the wrapper uses its JSON in place of the fallback text. It resolves the sample `{"ticket": "site"}` by awaiting a local report. Runner calls `authorize_call` with the run context before sending the request. Direct calls to `server.call_tool()` skip this access check. Never let a server pick another user's record or an arbitrary file or URL. + +At the tool boundary, the budget covers the sum of UTF-8 text bytes per result, including the reference. Smaller reports pass through in full. For large reports, the summary shares only the count of literal `WARN:` markers. Choose facts safe to disclose for your data. The first text slot holds the replacement and the other text slots stay empty. A structured result without a text slot gets one. + +## Retrieve privately + +Create one `Reports` instance per run. Load the owner's nonblank string ID from a trusted application record. The store compares IDs exactly. Pass only the authenticated requester as the run context. Never accept either identity from tool arguments or a reference. The reader uses only summaries and references issued by this store. It ignores tool output, including short reports, errors and text that looks like a reference. Without an authorized saved report, it prints a fixed message. + +After the run, inside the `closing` block, application code can read the first page of each saved text part. Keep these pages out of tool results and model input. + +```python +for reference, summary, part_count in reports.saved(requester): + for part in range(part_count): + first_page = reports.fetch(requester, reference, part=part) +``` + +`saved()` returns an empty tuple for an empty or closed store or a different requester. Images do not count as text parts. A structured report has one JSON part. Each `fetch()` checks access again and returns up to 64 characters. To read the next page, advance `offset` by the page length. + +The originals stay in process memory outside SDK context. Leaving the `closing` block revokes every reference, including on failure or cancellation. Saved conversations cannot restore the originals. This example has no storage quota or durable store. + +## Limits + +- Selected successes support text and images. Images retain their contents and positions. Other media stop the run. The budget excludes images, block metadata and serialization overhead. Use this policy only for tools that accept a text replacement without a required output schema. +- Unselected results and MCP errors pass through, even when large. The local function converts source-read exceptions into a fixed unavailable status before SDK publication; it preserves cancellation. Other selected-operation exceptions and invalid summaries stop the run. Cancelling the run during preparation withholds the pending output. It cannot undo a remote action or stop counting already underway in a worker thread. +- This example disables tracing. Keep tool-data logging disabled and check logs, exceptions and other observers separately. Small reports, images and errors can still contain sensitive data. +- The recipe covers SDK-executed tools. It excludes native tools and provider-hosted MCP. Editing later requests cannot retract data already received by a provider. + + +## Source attribution + +This recipe has been reusing PR #6120 at `4c0fcf035faa12d34480329af49c6f634ddcc276`. The integration has been adding fixed local source-error handling and tests without changing the original ownership and media limits. diff --git a/examples/mcp/bounded_tool_output/main.py b/examples/mcp/bounded_tool_output/main.py new file mode 100644 index 0000000000..705ff8788b --- /dev/null +++ b/examples/mcp/bounded_tool_output/main.py @@ -0,0 +1,210 @@ +"""Keep large reports out of model input and SDK history. + +Run offline from the checkout with `uv run python examples/mcp/bounded_tool_output/main.py`. +""" + +import asyncio +import json +import secrets +import sys +from contextlib import closing +from pathlib import Path +from typing import Any + +from mcp.types import CallToolResult, ImageContent, TextContent + +from agents import Agent, FunctionTool, RunConfig, RunContextWrapper, Runner, UserError +from agents.decorators import tool +from agents.mcp import MCPServerStdio, MCPToolMetaContext +from agents.testing import ScriptedModel, assistant_message, function_call + +MAX_TEXT_BYTES = 128 +SERVER = "Inspection reports" + + +async def site_report() -> str: + """Read the local inspection report.""" + return "WARN: synthetic site detail\n" * 20 + + +async def summarize(texts: tuple[str, ...]) -> str: + """Share only the number of warning markers in these synthetic reports.""" + count = await asyncio.to_thread(lambda: sum(text.count("WARN:") for text in texts)) + return f"Inspection report with {count} warning markers." + + +class Reports: + """Private storage for one owner and one run. Never put this object in SDK context.""" + + def __init__(self, owner: str): + if not isinstance(owner, str) or not owner.strip(): + raise ValueError("Report owner must be a nonblank string") + self._owner = owner + self._reports: dict[str, tuple[str, tuple[str, ...]]] | None = {} + + def close(self) -> None: + self._reports = None + + def fetch(self, requester: str, reference: str, *, part: int = 0, offset: int = 0) -> str: + self.authorize(requester) + if self._reports is None or reference not in self._reports: + raise PermissionError("Report unavailable") + if part < 0 or offset < 0: + raise ValueError("Use a nonnegative part and offset") + _, texts = self._reports[reference] + return texts[part][offset : offset + 64] + + def saved(self, requester: str) -> tuple[tuple[str, str, int], ...]: + """List the owner's references, display summaries and text part counts.""" + if requester != self._owner or not self._reports: + return () + return tuple( + (reference, summary, len(texts)) + for reference, (summary, texts) in self._reports.items() + ) + + def show(self, requester: str) -> None: + """Display only summaries issued by this store to its owner.""" + saved = self.saved(requester) + if not saved: + print("No saved reports available.") + return + for reference, summary, _ in saved: + page = self.fetch(requester, reference) + print(summary) + print("Retrieved the first page privately." if page else "The first page is empty.") + + def ensure_open(self) -> None: + if self._reports is None: + raise PermissionError("Report unavailable") + + def authorize(self, requester: str) -> None: + self.ensure_open() + if requester != self._owner: + raise PermissionError("Report unavailable") + + def site_tool(self) -> FunctionTool: + @tool(failure_error_function=None) + async def inspect_site(ctx: RunContextWrapper[str]) -> str: + """Read the local inspection report.""" + self.authorize(ctx.context) + try: + text = await site_report() + except Exception: + # Source errors may contain private data. Return only a fixed status. + return "Inspection report unavailable." + if not isinstance(text, str): + raise UserError("Expected a report string") + replacement = await self.bound((text,)) + self.authorize(ctx.context) + return replacement or text + + return inspect_site + + async def bound(self, texts: tuple[str, ...]) -> str | None: + if sum(len(text.encode()) for text in texts) <= MAX_TEXT_BYTES: + return None + + summary = await summarize(texts) + if not isinstance(summary, str) or not summary.strip(): + raise UserError("Expected a nonempty report summary") + reference = secrets.token_urlsafe(24) + replacement = f"{summary} Reference: {reference}" + if len(replacement.encode()) > MAX_TEXT_BYTES: + raise UserError("Report summary exceeds the text budget") + if self._reports is None: + raise RuntimeError("Report storage closed") + self._reports[reference] = replacement, texts + return replacement + + +class ReportServer(MCPServerStdio): + """Shape the peer result before the SDK converts, logs or traces it.""" + + def __init__(self, reports: Reports, name: str = SERVER): + self.reports = reports + super().__init__( + name=name, + params={ + "command": sys.executable, + "args": [str(Path(__file__).with_name("server.py"))], + }, + tool_meta_resolver=self.authorize_call, + failure_error_function=None, + ) + + def authorize_call(self, call: MCPToolMetaContext) -> None: + if call.tool_name == "read.report": + self.reports.authorize(call.run_context.context) + + async def call_tool( + self, tool_name: str, arguments: dict[str, Any] | None, meta: dict[str, Any] | None = None + ) -> CallToolResult: + result = await super().call_tool(tool_name, arguments, meta=meta) + if tool_name != "read.report": + return result + # Wire aliases are the same in both supported MCP client versions. + fields = result.model_dump(by_alias=True, exclude={"content", "meta"}) + if fields.get("isError"): + return result + self.reports.ensure_open() + if any(not isinstance(block, (TextContent, ImageContent)) for block in result.content): + raise UserError("Unsupported report media") + + structured = fields.get("structuredContent") + if structured: + if structured == {"ticket": "site"}: + structured = {"report": await site_report()} + text = json.dumps(structured) + replacement: str | None = await self.reports.bound((text,)) or text + else: + texts = tuple(part.text for part in result.content if isinstance(part, TextContent)) + replacement = await self.reports.bound(texts) + + self.reports.ensure_open() + if replacement is None: + return result + + # Start a new result so neither structuredContent nor _meta carries the original. + parts = list(result.content) + slots = [i for i, part in enumerate(parts) if isinstance(part, TextContent)] + if not slots: + parts.append(TextContent(type="text", text=replacement)) + for i in slots: + parts[i] = TextContent(type="text", text=replacement if i == slots[0] else "") + return CallToolResult(content=parts) + + +async def main() -> None: + requester = "sample-user" # Use the authenticated principal from your application. + model = ScriptedModel( + [ + [ + function_call("inspect_site", {}, call_id="local"), + function_call( + "mcp_Inspection_reports__read_report", {"kind": "structured"}, call_id="remote" + ), + ], + [assistant_message("Reports ready.")], + ] + ) + with closing(Reports(owner="sample-user")) as reports: + async with ReportServer(reports) as server: + agent = Agent( + name="Inspector", + model=model, + tools=[reports.site_tool()], + mcp_servers=[server], + mcp_config={"include_server_in_tool_names": True}, + ) + await Runner.run( + agent, + "Inspect both sites.", + context=requester, + run_config=RunConfig(tracing_disabled=True), + ) + reports.show(requester) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/mcp/bounded_tool_output/server.py b/examples/mcp/bounded_tool_output/server.py new file mode 100644 index 0000000000..2918c4b9c8 --- /dev/null +++ b/examples/mcp/bounded_tool_output/server.py @@ -0,0 +1,66 @@ +"""Synthetic reports for the local stdio example.""" + +from mcp.types import CallToolResult + +try: + from mcp.server.mcpserver import MCPServer +except ImportError: + from mcp.server.fastmcp import FastMCP as MCPServer + +server = MCPServer("Reports") + + +@server.tool(name="read.report") +async def read_report(kind: str) -> CallToolResult: + """Read a sample inspection report.""" + detail = "WARN: synthetic detail " * 4 + if kind == "audio": + return CallToolResult.model_validate( + {"content": [{"type": "audio", "mimeType": "audio/wav", "data": "QUJD"}]} + ) + if kind == "ticket": + return CallToolResult.model_validate( + {"content": [], "structuredContent": {"ticket": "site"}} + ) + if kind in ("text", "brief"): + return CallToolResult.model_validate( + { + "content": [ + {"type": "text", "text": "Sample reading. " * (12 if kind == "text" else 1)} + ] + } + ) + if kind in ("illustrated", "combined"): + return CallToolResult.model_validate( + { + "structuredContent": {"report": detail * 3} if kind == "combined" else None, + "content": [ + {"type": "text", "text": detail}, + { + "type": "image", + "mimeType": "image/gif", + "data": "R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==", + }, + {"type": "text", "text": detail}, + ], + } + ) + return CallToolResult.model_validate( + { + "content": [ + { + "type": "text", + "text": "Fallback report" + if kind == "structured" + else "Report unavailable. " * 10, + } + ], + "structuredContent": {"report": detail * 2}, + "_meta": {"private": detail}, + "isError": kind != "structured", + } + ) + + +if __name__ == "__main__": + server.run() diff --git a/tests/mcp/test_bounded_tool_output_example.py b/tests/mcp/test_bounded_tool_output_example.py new file mode 100644 index 0000000000..a8dc8afac8 --- /dev/null +++ b/tests/mcp/test_bounded_tool_output_example.py @@ -0,0 +1,401 @@ +import asyncio +import json +from contextlib import closing +from typing import Any + +import pytest + +from agents import ( + Agent, + AgentsException, + RunConfig, + Runner, + SQLiteSession, + ToolExecutionConfig, + UserError, +) +from agents.mcp import MCPServerStdio, MCPToolCustomDataContext +from agents.testing import ScriptedModel, assistant_message, function_call +from agents.tool_context import ToolContext +from examples.mcp.bounded_tool_output import main as recipe +from tests.testing_processor import fetch_ordered_spans + +OWNER = "sample-user" + + +@pytest.mark.asyncio +async def test_sdk_discovery_and_function_results_before_publication(): + observed = {} + + def observe(result: MCPToolCustomDataContext) -> None: + assert isinstance(result.run_context, ToolContext) + observed[result.run_context.tool_call_id] = ( + result.run_context.context, + result.server_name, + result.tool_name, + result.tool_output, + result.structured_content, + result.result_meta, + result.is_error, + ) + + name = "mcp_Reports__read_report" + model = ScriptedModel( + [ + [ + function_call("inspect_site", {}, call_id="site"), + function_call(name, {"kind": "structured"}, call_id="json"), + function_call(name, {"kind": "illustrated"}, call_id="mixed"), + function_call(name, {"kind": "combined"}, call_id="combined"), + function_call(name, {"kind": "ticket"}, call_id="ticket"), + function_call(name, {"kind": "missing"}, call_id="error"), + function_call(name, {"kind": "text"}, call_id="text"), + function_call(name, {"kind": "brief"}, call_id="brief"), + function_call("mcp_Other__read_report", {"kind": "text"}, call_id="other"), + ], + [assistant_message("Done")], + ] + ) + with closing(recipe.Reports(OWNER)) as reports, closing(SQLiteSession("reports")) as session: + async with ( + recipe.ReportServer(reports, name="Reports") as selected, + MCPServerStdio( + name="Other", + params={"command": selected.params.command, "args": selected.params.args}, + ) as other, + ): + selected.custom_data_extractor = observe + agent = Agent( + name="Inspector", + model=model, + tools=[reports.site_tool()], + mcp_servers=[selected, other], + mcp_config={"include_server_in_tool_names": True}, + ) + result = Runner.run_streamed( + agent, + "Inspect", + context=OWNER, + run_config=RunConfig(trace_include_sensitive_data=True), + session=session, + ) + events = [event async for event in result.stream_events()] + + detail = "WARN: synthetic detail " * 4 + structured = json.dumps({"report": detail * 2}) + image = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==" + assert observed["json"][:3] == (OWNER, "Reports", "read.report") + assert observed["json"][4:6] == (None, None) + assert observed["error"][-1] is True + assert observed["mixed"][3][1] == {"type": "image", "image_url": image} + spans = [span.export() for span in fetch_ordered_spans()] + assert "Inspection report with 8 warning markers" in repr(spans) + + history = result.to_input_list() + request = model.calls[1].input + for surface in ( + events, + spans, + observed["json"], + result.new_items, + history, + request, + result.context_wrapper, + result.to_state().to_json(), + await session.get_items(), + ): + assert "synthetic detail" not in repr(surface) + assert "synthetic site detail" not in repr(surface) + assert "Fallback report" not in repr(surface) + + outputs = { + i["call_id"]: i["output"] for i in request if i.get("type") == "function_call_output" + } + assert outputs["error"] == [{"type": "input_text", "text": "Report unavailable. " * 10}] + assert outputs["brief"] == [{"type": "input_text", "text": "Sample reading. "}] + assert outputs["other"] == [{"type": "input_text", "text": "Sample reading. " * 12}] + assert ( + outputs["combined"][1:] + == outputs["mixed"][1:] + == [ + {"type": "input_image", "image_url": image}, + {"type": "input_text", "text": ""}, + ] + ) + saved = reports.saved(OWNER) + assert isinstance(saved, tuple) and len(saved) == 6 + by_summary = {summary: (ref, parts) for ref, summary, parts in saved} + for summary, count, original in [ + (outputs["site"], 20, ("WARN: synthetic site detail\n" * 20,)), + (outputs["json"][0]["text"], 8, (structured,)), + (outputs["combined"][0]["text"], 12, (json.dumps({"report": detail * 3}),)), + ( + outputs["ticket"][0]["text"], + 20, + (json.dumps({"report": "WARN: synthetic site detail\n" * 20}),), + ), + (outputs["mixed"][0]["text"], 8, (detail, detail)), + (outputs["text"][0]["text"], 0, ("Sample reading. " * 12,)), + ]: + assert len(summary.encode()) <= 128 + ref, parts = by_summary.pop(summary) + assert summary == f"Inspection report with {count} warning markers. Reference: {ref}" + assert parts == len(original) + assert ref in repr(events) and ref in repr(history) and ref in repr(result.new_items) + for part, expected in enumerate(original): + for offset in range(0, len(expected), 64): + assert ( + reports.fetch(OWNER, ref, part=part, offset=offset) + == expected[offset : offset + 64] + ) + with pytest.raises(PermissionError): + reports.fetch("other-user", ref) + + with closing(recipe.Reports(OWNER)) as other_session, pytest.raises(PermissionError): + other_session.fetch(OWNER, ref) + with pytest.raises(PermissionError): + reports.fetch(OWNER, ref) + + +@pytest.mark.asyncio +async def test_renamed_report_server_denies_other_users(): + model = ScriptedModel([[function_call("read.report", {"kind": "text"}, call_id="report")]]) + with closing(recipe.Reports(OWNER)) as reports: + async with recipe.ReportServer(reports, name="Reports") as server: + agent = Agent(name="Inspector", model=model, mcp_servers=[server]) + with pytest.raises(AgentsException, match="Report unavailable"): + await Runner.run(agent, "Inspect", context="other-user") + assert not reports.saved(OWNER) + assert len(model.calls) == 1 + + +@pytest.mark.asyncio +async def test_local_tool_denies_access_before_reading(monkeypatch): + async def forbidden(): + pytest.fail("Unauthorized caller reached the report reader") + + monkeypatch.setattr(recipe, "site_report", forbidden) + model = ScriptedModel([[function_call("inspect_site", {}, call_id="site")]]) + with closing(recipe.Reports(OWNER)) as reports: + agent = Agent(name="Inspector", model=model, tools=[reports.site_tool()]) + with pytest.raises(UserError, match="Report unavailable"): + await Runner.run(agent, "Inspect", context="other-user") + assert len(model.calls) == 1 + + +@pytest.mark.asyncio +async def test_local_tool_rechecks_access_before_returning_a_small_report(monkeypatch): + model = ScriptedModel([[function_call("inspect_site", {}, call_id="site")]]) + with closing(recipe.Reports(OWNER)) as reports: + + async def revoke(): + reports.close() + return "Private reading" + + monkeypatch.setattr(recipe, "site_report", revoke) + agent = Agent(name="Inspector", model=model, tools=[reports.site_tool()]) + with pytest.raises(UserError, match="Report unavailable"): + await Runner.run(agent, "Inspect", context=OWNER) + assert len(model.calls) == 1 + + +@pytest.mark.asyncio +async def test_local_output_is_bounded_before_an_independent_editor(): + seen = [] + + async def replace(call, output): + seen.append(output) + return "Reviewed" + + model = ScriptedModel( + [[function_call("inspect_site", {}, call_id="site")], [assistant_message("Done")]] + ) + with closing(recipe.Reports(OWNER)) as reports: + agent = Agent(name="Inspector", model=model, tools=[reports.site_tool()]) + config = RunConfig(tool_execution=ToolExecutionConfig(prepare_tool_output=replace)) + await Runner.run(agent, "Inspect", context=OWNER, run_config=config) + (summary,) = seen + assert len(summary.encode()) <= 128 + ((ref, saved_summary, parts),) = reports.saved(OWNER) + assert parts == 1 + assert ( + saved_summary + == summary + == f"Inspection report with 20 warning markers. Reference: {ref}" + ) + assert reports.fetch(OWNER, ref) == (await recipe.site_report())[:64] + assert "Reviewed" in repr(model.calls[1].input) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "invalid", [None, {"text": "private"}, "é" * 64], ids=["missing", "object", "oversized"] +) +async def test_invalid_summary_never_reaches_model_or_events(monkeypatch, invalid): + async def bad_summary(texts: tuple[str, ...]) -> Any: + return invalid + + monkeypatch.setattr(recipe, "summarize", bad_summary) + model = ScriptedModel([[function_call("inspect_site", {}, call_id="site")]]) + with closing(recipe.Reports(OWNER)) as reports: + agent = Agent(name="Inspector", model=model, tools=[reports.site_tool()]) + result = Runner.run_streamed(agent, "Inspect", context=OWNER) + with pytest.raises(UserError, match="summary"): + async for event in result.stream_events(): + assert getattr(event, "name", None) != "tool_output" + assert len(model.calls) == 1 + assert all(item.type != "tool_call_output_item" for item in result.new_items) + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("kind", "reason"), [("structured", "summary"), ("audio", "media")]) +async def test_rejected_mcp_output_withholds_raw_report_from_tracing(monkeypatch, kind, reason): + async def invalid(texts: tuple[str, ...]) -> str: + assert texts == (json.dumps({"report": "WARN: synthetic detail " * 8}),) + return "" + + monkeypatch.setattr(recipe, "summarize", invalid) + model = ScriptedModel([[function_call("read.report", {"kind": kind}, call_id="report")]]) + with closing(recipe.Reports(OWNER)) as reports: + async with recipe.ReportServer(reports) as server: + agent = Agent(name="Inspector", model=model, mcp_servers=[server]) + with pytest.raises(UserError, match=reason): + await Runner.run( + agent, + "Inspect", + context=OWNER, + run_config=RunConfig(trace_include_sensitive_data=True), + ) + spans = [span.export() for span in fetch_ordered_spans()] + assert reason in repr(spans) + assert "QUJD" not in repr(spans) + assert "synthetic detail" not in repr(spans) + assert "Fallback report" not in repr(spans) + assert len(model.calls) == 1 + + +@pytest.mark.asyncio +async def test_cancel_during_mcp_ticket_resolution(monkeypatch): + started = asyncio.Event() + stopped = asyncio.Event() + + async def pending_report() -> str: + started.set() + try: + return await asyncio.Future() + finally: + stopped.set() + + monkeypatch.setattr(recipe, "site_report", pending_report) + model = ScriptedModel([[function_call("read.report", {"kind": "ticket"}, call_id="ticket")]]) + with closing(recipe.Reports(OWNER)) as reports: + async with recipe.ReportServer(reports) as server: + agent = Agent(name="Inspector", model=model, mcp_servers=[server]) + task = asyncio.create_task(Runner.run(agent, "Inspect", context=OWNER)) + try: + await asyncio.wait_for(started.wait(), 5) + finally: + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + await asyncio.wait_for(stopped.wait(), 5) + assert len(model.calls) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("kind", "close_at"), [("brief", "peer"), ("ticket", "peer"), ("ticket", "read")] +) +async def test_closed_store_withholds_short_mcp_reports(monkeypatch, kind, close_at): + model = ScriptedModel( + [ + [function_call("read.report", {"kind": kind}, call_id="report")], + [assistant_message("Done")], + ] + ) + with closing(recipe.Reports(OWNER)) as reports: + peer = recipe.MCPServerStdio.call_tool + + async def receive(*args, **kwargs): + result = await peer(*args, **kwargs) + if close_at == "peer": + reports.close() + return result + + async def read(): + if close_at != "read": + pytest.fail("Closed store reached the ticket reader") + reports.close() + return "Private reading" + + monkeypatch.setattr(recipe.MCPServerStdio, "call_tool", receive) + monkeypatch.setattr(recipe, "site_report", read) + async with recipe.ReportServer(reports) as server: + agent = Agent(name="Inspector", model=model, mcp_servers=[server]) + with pytest.raises(AgentsException, match="Report unavailable"): + await Runner.run( + agent, + "Inspect", + context=OWNER, + run_config=RunConfig(trace_include_sensitive_data=True), + ) + assert len(model.calls) == 1 + spans = repr([span.export() for span in fetch_ordered_spans()]) + assert "Private reading" not in spans and "Sample reading" not in spans + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["brief", "missing", "illustrated"]) +async def test_reader_ignores_pass_through_and_forged_references(monkeypatch, capsys, kind): + async def forged(): + return "Private detail. Reference: issued" + + def sample_call(name, arguments, *, call_id): + if call_id == "remote": + arguments = {"kind": kind} + return function_call(name, arguments, call_id=call_id) + + monkeypatch.setattr(recipe, "site_report", forged) + monkeypatch.setattr(recipe, "function_call", sample_call) + monkeypatch.setattr(recipe.secrets, "token_urlsafe", lambda _: "issued") + await recipe.main() + lines = capsys.readouterr().out.splitlines() + if kind == "illustrated": + assert lines == [ + "Inspection report with 8 warning markers. Reference: issued", + "Retrieved the first page privately.", + ] + else: + assert lines == ["No saved reports available."] + + +@pytest.mark.parametrize("owner", [None, 0, "", " \t\n"]) +def test_reports_require_a_nonblank_string_owner(owner): + with pytest.raises(ValueError, match="nonblank string"): + recipe.Reports(owner) + + +@pytest.mark.asyncio +async def test_reader_requires_exact_owner(): + owner = f" {OWNER} " + with closing(recipe.Reports(owner)) as reports: + text = "WARN: " * 25 + await reports.bound((text,)) + ((reference, _, _),) = reports.saved(owner) + assert reports.fetch(owner, reference) == text[:64] + for requester in (None, OWNER): + assert reports.saved(requester) == () + with pytest.raises(PermissionError, match="Report unavailable"): + reports.fetch(requester, reference) + + +@pytest.mark.asyncio +async def test_reader_requires_live_owner(capsys): + with closing(recipe.Reports(OWNER)) as reports: + assert reports.saved(OWNER) == () + await reports.bound(("WARN: " * 25,)) + assert reports.saved("other-user") == () + reports.show("other-user") + assert reports.saved(OWNER) == () + reports.show(OWNER) + assert capsys.readouterr().out.splitlines() == ["No saved reports available."] * 2 diff --git a/tests/test_typed_and_private_result_examples.py b/tests/test_typed_and_private_result_examples.py new file mode 100644 index 0000000000..de64030f38 --- /dev/null +++ b/tests/test_typed_and_private_result_examples.py @@ -0,0 +1,218 @@ +import asyncio +from contextlib import closing + +import pytest + +from agents import Agent, RunConfig, Runner, SQLiteSession +from agents.models.multi_provider import MultiProvider +from agents.testing import ModelStep, ScriptedModel, assistant_message, function_call +from examples.basic.typed_answer_repair import RepairLimitError, Verdict, repair +from examples.mcp.bounded_tool_output import main as reports_recipe + + +@pytest.mark.asyncio +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_typed_semantic_repair_and_bounded_failure(streamed): + invalid = assistant_message('{"decision":"approve","evidence_count":0}') + valid = assistant_message('{"decision":"reject","evidence_count":2}') + model = ScriptedModel([[invalid], [valid]]) + result, review = await repair(model, streamed=streamed) + assert result == Verdict(decision="reject", evidence_count=2) + assert review.attempts == len(model.calls) == 2 + assert model.calls[1].system_instructions is not None + assert "positive evidence_count" in model.calls[1].system_instructions + failed = ScriptedModel([[invalid], [invalid]]) + with pytest.raises(RepairLimitError, match="two candidates"): + await repair(failed, streamed=streamed) + assert len(failed.calls) == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("supplied", [False, True], ids=["default-provider", "caller-provider"]) +@pytest.mark.parametrize("outcome", ["success", "failure", "cancellation"]) +async def test_repair_provider_ownership(monkeypatch, streamed, supplied, outcome): + closed = [] + close = MultiProvider.aclose + + async def record_close(provider): + await close(provider) + closed.append(provider) + + monkeypatch.setattr(MultiProvider, "aclose", record_close) + config = RunConfig(tracing_disabled=False) if supplied else None + entered = asyncio.Event() + release = asyncio.Event() + + async def respond(call): + assert call.tracing.is_disabled() + if outcome == "failure": + raise RuntimeError("model failed") + if outcome == "cancellation": + entered.set() + await release.wait() + return [assistant_message('{"decision":"approve","evidence_count":1}')] + + model = ScriptedModel([ModelStep.respond(respond)]) + task = asyncio.create_task(repair(model, streamed=streamed, run_config=config)) + try: + if outcome == "cancellation": + await asyncio.wait_for(entered.wait(), timeout=5) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + elif outcome == "failure": + with pytest.raises(RuntimeError, match="model failed"): + await task + else: + answer, _ = await task + assert answer == Verdict(decision="approve", evidence_count=1) + if config is None: + assert len(closed) == 1 + else: + assert closed == [] + assert not config.tracing_disabled + finally: + release.set() + task.cancel() + await asyncio.gather(task, return_exceptions=True) + if config is not None: + await config.model_provider.aclose() + + +@pytest.mark.asyncio +async def test_large_private_source_and_sensitive_error_never_enter_history(monkeypatch): + secret = "credential-secret " * 100 + + async def source(): + return secret + + monkeypatch.setattr(reports_recipe, "site_report", source) + with ( + closing(reports_recipe.Reports("owner")) as reports, + closing(SQLiteSession("private")) as session, + ): + model = ScriptedModel( + [ + [function_call("inspect_site", {}, call_id="one")], + [assistant_message("Public summary")], + ] + ) + result = await Runner.run( + Agent(name="demo", tools=[reports.site_tool()], model=model), + "Synthetic prompt", + context="owner", + session=session, + run_config=RunConfig(tracing_disabled=True), + ) + assert "credential-secret" not in str(await session.get_items()) + assert "credential-secret" not in str(model.calls[1].input) + assert "credential-secret" not in str(result.final_output) + reference, _, _ = reports.saved("owner")[0] + assert reports.fetch("owner", reference).startswith("credential-secret") + with pytest.raises(PermissionError): + reports.fetch("other", reference) + with pytest.raises(PermissionError): + reports.fetch("owner", reference) + + async def failure(): + raise RuntimeError("credential-secret") + + monkeypatch.setattr(reports_recipe, "site_report", failure) + with closing(reports_recipe.Reports("owner")) as reports: + model = ScriptedModel( + [ + [function_call("inspect_site", {}, call_id="one")], + [assistant_message("Public error summary")], + ] + ) + result = await Runner.run( + Agent(name="demo", tools=[reports.site_tool()], model=model), + "Synthetic prompt", + context="owner", + run_config=RunConfig(tracing_disabled=True), + ) + assert "credential-secret" not in str(result.new_items) + assert "Inspection report unavailable" in str(model.calls[1].input) + assert reports.saved("owner") == () + + +@pytest.mark.asyncio +async def test_schema_invalid_repair_never_replays_sensitive_candidate(): + from examples.basic.typed_answer_repair import repair_schema + + model = ScriptedModel( + [ + [assistant_message('{"decision":"credential-secret","evidence_count":"bad"}')], + [assistant_message('{"decision":"reject","evidence_count":1}')], + ] + ) + answer, attempts = await repair_schema(model) + assert answer == Verdict(decision="reject", evidence_count=1) and attempts == 2 + assert "credential-secret" not in str(model.calls[1].input) + failed = ScriptedModel([[assistant_message("credential-secret")]] * 2) + with pytest.raises(RepairLimitError, match="two attempts") as error: + await repair_schema(failed) + assert "credential-secret" not in str(error.value) and len(failed.calls) == 2 + + +@pytest.mark.asyncio +@pytest.mark.skipif(not hasattr(asyncio, "eager_task_factory"), reason="Requires Python 3.12+") +@pytest.mark.parametrize("cancel_during_run", [False, True]) +async def test_streamed_repair_joins_eager_run(monkeypatch, cancel_during_run): + entered, release, settled = asyncio.Event(), asyncio.Event(), asyncio.Event() + closing, allow_close, closed = asyncio.Event(), asyncio.Event(), asyncio.Event() + close = MultiProvider.aclose + + async def slow_close(provider): + closing.set() + await allow_close.wait() + await close(provider) + closed.set() + + monkeypatch.setattr(MultiProvider, "aclose", slow_close) + + async def respond(call): + entered.set() + try: + await release.wait() + return [assistant_message('{"decision":"approve","evidence_count":1}')] + finally: + settled.set() + + loop = asyncio.get_running_loop() + previous = loop.get_task_factory() + loop.set_task_factory(asyncio.eager_task_factory) + try: + task = asyncio.create_task( + repair(ScriptedModel([ModelStep.respond(respond)]), streamed=True) + ) + finally: + loop.set_task_factory(previous) + try: + await asyncio.wait_for(entered.wait(), timeout=5) + assert not task.done() + if cancel_during_run: + task.cancel("first") + else: + release.set() + await asyncio.wait_for(closing.wait(), timeout=5) + assert settled.is_set() + if cancel_during_run: + task.cancel("second") + await asyncio.sleep(0) + assert not task.done() + allow_close.set() + if cancel_during_run: + with pytest.raises(asyncio.CancelledError, match="first"): + await task + else: + answer, review = await task + assert answer == Verdict(decision="approve", evidence_count=1) + assert review.attempts == 1 + assert closed.is_set() + finally: + release.set() + allow_close.set() + await asyncio.gather(task, return_exceptions=True)