77
88import pytest
99from openai .types .responses import ResponseReasoningItem
10+ from openai .types .responses .response_output_item import McpApprovalRequest
1011
11- from agents import Agent , ModelSettings , RunConfig , Runner , RunState , handoff
12+ from agents import Agent , HostedMCPTool , ModelSettings , RunConfig , Runner , RunState , handoff
1213from agents .handoffs import HandoffInputData
1314from agents .items import TResponseInputItem
1415from agents .memory import OpenAIResponsesCompactionSession , Session , SQLiteSession
1516from agents .memory .session import SessionABC
1617from agents .result import RunResult , RunResultStreaming
1718from agents .run_config import CallModelData , ModelInputData
1819from agents .testing import ScriptedModel
20+ from tests .model_test_helpers import get_exact_output_stream_step
1921from tests .test_responses import (
2022 get_function_tool ,
2123 get_function_tool_call ,
@@ -324,15 +326,12 @@ async def test_resumed_tool_output_stays_local_when_filtered(streamed: bool) ->
324326 tool .needs_approval = True
325327 model = ScriptedModel (steps = [[get_function_tool_call ("lookup" )], [get_text_message ("ok" )]])
326328 agent = Agent (name = "worker" , model = model , tools = [tool ], tool_use_behavior = "stop_on_first_tool" )
327- # Avoid compacting the interruption's still-pending tool call.
328- session .should_trigger_compaction = lambda _ : False
329329 interrupted = await run (agent , "first" , session , streamed )
330330 state = interrupted .to_state ()
331331 state .approve (interrupted .interruptions [0 ])
332332 serialized = state .to_json ()
333333 assert "_session_compaction_model_exchange" not in str (serialized )
334334 restored = await RunState .from_json (agent , serialized )
335- session .should_trigger_compaction = lambda _ : True
336335 resumed = await run (agent , restored , session , streamed )
337336 assert resumed .final_output == LOCAL_OUTPUT
338337 await run (agent , "second" , session , streamed , RunConfig (call_model_input_filter = filter_tools ))
@@ -341,6 +340,152 @@ async def test_resumed_tool_output_stays_local_when_filtered(streamed: bool) ->
341340 assert LOCAL_OUTPUT in str (await session .get_items ())
342341
343342
343+ @pytest .mark .parametrize ("streamed" , [False , True ])
344+ @pytest .mark .parametrize ("approve" , [False , True ])
345+ @pytest .mark .parametrize ("atomic_backend" , [False , True ])
346+ async def test_pending_approval_defers_automatic_compaction (
347+ streamed : bool , approve : bool , atomic_backend : bool
348+ ) -> None :
349+ client = MagicMock ()
350+ summary = {"type" : "compaction" , "id" : "cmp-test" , "encrypted_content" : "synthetic-summary" }
351+ client .responses .compact = AsyncMock (return_value = SimpleNamespace (output = [summary ]))
352+ backend = SQLiteSession ("approval" ) if atomic_backend else SimpleListSession ()
353+ session = OpenAIResponsesCompactionSession (
354+ "approval" ,
355+ backend ,
356+ client = client ,
357+ compaction_mode = "input" ,
358+ should_trigger_compaction = lambda _ : True ,
359+ )
360+ tool = get_function_tool (name = "lookup" , return_value = LOCAL_OUTPUT )
361+ tool .needs_approval = True
362+ call = get_function_tool_call ("lookup" )
363+ model = ScriptedModel (
364+ steps = [
365+ [call ],
366+ [get_text_message ("resolved" )],
367+ [get_text_message ("next" )],
368+ [get_text_message ("done" )],
369+ ]
370+ )
371+ agent = Agent (name = "worker" , model = model , tools = [tool ])
372+ try :
373+ interrupted = await run (agent , "first" , session , streamed )
374+ assert len (interrupted .interruptions ) == 1
375+ client .responses .compact .assert_not_awaited ()
376+ assert any (item .get ("call_id" ) == call .call_id for item in await session .get_items ())
377+
378+ state = await RunState .from_json (agent , interrupted .to_state ().to_json ())
379+ if approve :
380+ state .approve (interrupted .interruptions [0 ])
381+ else :
382+ state .reject (interrupted .interruptions [0 ])
383+ await run (agent , state , session , streamed )
384+
385+ for items in (model .calls [1 ].input , await session .get_items ()):
386+ assert [item ["type" ] for item in items if item .get ("call_id" ) == call .call_id ] == [
387+ "function_call" ,
388+ "function_call_output" ,
389+ ]
390+
391+ await run (agent , "second" , session , streamed )
392+ client .responses .compact .assert_awaited_once ()
393+ assert [
394+ item ["type" ]
395+ for item in client .responses .compact .call_args .kwargs ["input" ]
396+ if item .get ("call_id" ) == call .call_id
397+ ] == ["function_call" , "function_call_output" ]
398+ assert await session .get_items () == [summary ]
399+
400+ await run (agent , "third" , session , streamed )
401+ assert model .calls [3 ].input == [summary , {"role" : "user" , "content" : "third" }]
402+ finally :
403+ if isinstance (backend , SQLiteSession ):
404+ backend .close ()
405+
406+
407+ @pytest .mark .parametrize ("streamed" , [False , True ])
408+ @pytest .mark .parametrize ("approve" , [False , True ])
409+ async def test_pending_hosted_mcp_approval_defers_automatic_compaction (
410+ streamed : bool , approve : bool
411+ ) -> None :
412+ client = MagicMock ()
413+ summary = {"type" : "compaction" , "id" : "cmp-mcp" , "encrypted_content" : "synthetic-summary" }
414+ client .responses .compact = AsyncMock (return_value = SimpleNamespace (output = [summary ]))
415+ backend = SQLiteSession ("mcp-approval" )
416+ session = OpenAIResponsesCompactionSession (
417+ "mcp-approval" ,
418+ backend ,
419+ client = client ,
420+ compaction_mode = "input" ,
421+ should_trigger_compaction = lambda _ : True ,
422+ )
423+ request = McpApprovalRequest (
424+ id = "approval-1" ,
425+ type = "mcp_approval_request" ,
426+ arguments = "{}" ,
427+ name = "lookup" ,
428+ server_label = "synthetic" ,
429+ )
430+ model = ScriptedModel (
431+ steps = [
432+ get_exact_output_stream_step ([request ]) if streamed else [request ],
433+ [get_text_message ("resolved" )],
434+ [get_text_message ("next" )],
435+ [get_text_message ("done" )],
436+ ]
437+ )
438+ agent = Agent (
439+ name = "worker" ,
440+ model = model ,
441+ tools = [
442+ HostedMCPTool (
443+ tool_config = {
444+ "type" : "mcp" ,
445+ "server_label" : "synthetic" ,
446+ "server_url" : "https://synthetic.example/mcp" ,
447+ "require_approval" : "always" ,
448+ }
449+ )
450+ ],
451+ )
452+ try :
453+ interrupted = await run (agent , "first" , session , streamed )
454+ assert len (interrupted .interruptions ) == 1
455+ client .responses .compact .assert_not_awaited ()
456+ assert request .model_dump (exclude_unset = True ) in await session .get_items ()
457+
458+ state = await RunState .from_json (agent , interrupted .to_state ().to_json ())
459+ if approve :
460+ state .approve (interrupted .interruptions [0 ])
461+ else :
462+ state .reject (interrupted .interruptions [0 ])
463+ await run (agent , state , session , streamed )
464+ for items in (model .calls [1 ].input , await session .get_items ()):
465+ assert request .model_dump (exclude_unset = True ) in items
466+ responses = [item for item in items if item .get ("type" ) == "mcp_approval_response" ]
467+ assert len (responses ) == 1
468+ assert responses [0 ]["approval_request_id" ] == request .id
469+ assert responses [0 ]["approve" ] is approve
470+
471+ await run (agent , "second" , session , streamed )
472+ client .responses .compact .assert_awaited_once ()
473+ compact_input = client .responses .compact .call_args .kwargs ["input" ]
474+ assert request .model_dump (exclude_unset = True ) in compact_input
475+ assert any (
476+ item .get ("type" ) == "mcp_approval_response"
477+ and item .get ("approval_request_id" ) == request .id
478+ and item .get ("approve" ) is approve
479+ for item in compact_input
480+ )
481+ assert await session .get_items () == [summary ]
482+
483+ await run (agent , "third" , session , streamed )
484+ assert model .calls [3 ].input == [summary , {"role" : "user" , "content" : "third" }]
485+ finally :
486+ backend .close ()
487+
488+
344489@pytest .mark .parametrize ("streamed" , [False , True ])
345490@pytest .mark .parametrize ("encrypted" , [False , True ])
346491async def test_backend_read_limit_cannot_hide_retained_history_from_compaction (
0 commit comments