forked from openai/openai-agents-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_mcp_util.py
More file actions
1509 lines (1173 loc) · 51.5 KB
/
test_mcp_util.py
File metadata and controls
1509 lines (1173 loc) · 51.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import dataclasses
import json
import logging
from typing import Any
import pytest
from inline_snapshot import snapshot
from mcp.types import CallToolResult, ImageContent, TextContent, Tool as MCPTool
from pydantic import BaseModel, TypeAdapter
from agents import Agent, FunctionTool, RunContextWrapper, default_tool_error_function
from agents.exceptions import AgentsException, MCPToolCancellationError, ModelBehaviorError
from agents.mcp import MCPServer, MCPUtil
from agents.tool_context import ToolContext
from .helpers import FakeMCPServer
class Foo(BaseModel):
bar: str
baz: int
class Bar(BaseModel):
qux: dict[str, str]
Baz = TypeAdapter(dict[str, str])
def _convertible_schema() -> dict[str, Any]:
schema = Foo.model_json_schema()
schema["additionalProperties"] = False
return schema
@pytest.mark.asyncio
async def test_get_all_function_tools():
"""Test that the get_all_function_tools function returns all function tools from a list of MCP
servers.
"""
names = ["test_tool_1", "test_tool_2", "test_tool_3", "test_tool_4", "test_tool_5"]
schemas = [
{},
{},
{},
Foo.model_json_schema(),
Bar.model_json_schema(),
]
server1 = FakeMCPServer()
server1.add_tool(names[0], schemas[0])
server1.add_tool(names[1], schemas[1])
server2 = FakeMCPServer()
server2.add_tool(names[2], schemas[2])
server2.add_tool(names[3], schemas[3])
server3 = FakeMCPServer()
server3.add_tool(names[4], schemas[4])
servers: list[MCPServer] = [server1, server2, server3]
run_context = RunContextWrapper(context=None)
agent = Agent(name="test_agent", instructions="Test agent")
tools = await MCPUtil.get_all_function_tools(servers, False, run_context, agent)
assert len(tools) == 5
assert all(tool.name in names for tool in tools)
for idx, tool in enumerate(tools):
assert isinstance(tool, FunctionTool)
if schemas[idx] == {}:
assert tool.params_json_schema == snapshot({"properties": {}})
else:
assert tool.params_json_schema == schemas[idx]
assert tool.name == names[idx]
# Also make sure it works with strict schemas
tools = await MCPUtil.get_all_function_tools(servers, True, run_context, agent)
assert len(tools) == 5
assert all(tool.name in names for tool in tools)
@pytest.mark.asyncio
async def test_invoke_mcp_tool():
"""Test that the invoke_mcp_tool function invokes an MCP tool and returns the result."""
server = FakeMCPServer()
server.add_tool("test_tool_1", {})
ctx = RunContextWrapper(context=None)
tool = MCPTool(name="test_tool_1", inputSchema={})
await MCPUtil.invoke_mcp_tool(server, tool, ctx, "")
# Just making sure it doesn't crash
@pytest.mark.asyncio
async def test_mcp_meta_resolver_merges_and_passes():
captured: dict[str, Any] = {}
def resolve_meta(context):
captured["run_context"] = context.run_context
captured["server_name"] = context.server_name
captured["tool_name"] = context.tool_name
captured["arguments"] = context.arguments
return {"request_id": "req-123", "locale": "ja"}
server = FakeMCPServer(tool_meta_resolver=resolve_meta)
server.add_tool("test_tool_1", {})
ctx = RunContextWrapper(context={"request_id": "req-123"})
tool = MCPTool(name="test_tool_1", inputSchema={})
await MCPUtil.invoke_mcp_tool(
server,
tool,
ctx,
"{}",
meta={"locale": "en", "extra": "value"},
)
assert server.tool_metas[-1] == {"request_id": "req-123", "locale": "en", "extra": "value"}
assert captured["run_context"] is ctx
assert captured["server_name"] == server.name
assert captured["tool_name"] == "test_tool_1"
assert captured["arguments"] == {}
@pytest.mark.asyncio
async def test_mcp_meta_resolver_does_not_mutate_arguments():
def resolve_meta(context):
if context.arguments is not None:
context.arguments["mutated"] = "yes"
return {"meta": "ok"}
server = FakeMCPServer(tool_meta_resolver=resolve_meta)
server.add_tool("test_tool_1", {})
ctx = RunContextWrapper(context=None)
tool = MCPTool(name="test_tool_1", inputSchema={})
await MCPUtil.invoke_mcp_tool(server, tool, ctx, '{"foo": "bar"}')
result = server.tool_results[-1]
prefix = f"result_{tool.name}_"
assert result.startswith(prefix)
args = json.loads(result[len(prefix) :])
assert args == {"foo": "bar"}
@pytest.mark.asyncio
async def test_to_function_tool_passes_static_mcp_meta():
server = FakeMCPServer()
tool = MCPTool(
name="test_tool_1",
inputSchema={},
_meta={"locale": "en", "extra": "value"},
)
function_tool = MCPUtil.to_function_tool(tool, server, convert_schemas_to_strict=False)
tool_context = ToolContext(
context=None,
tool_name="test_tool_1",
tool_call_id="test_call_static_meta",
tool_arguments="{}",
)
await function_tool.on_invoke_tool(tool_context, "{}")
assert server.tool_metas[-1] == {"locale": "en", "extra": "value"}
@pytest.mark.asyncio
async def test_to_function_tool_merges_static_mcp_meta_with_resolver():
captured: dict[str, Any] = {}
def resolve_meta(context):
captured["run_context"] = context.run_context
captured["server_name"] = context.server_name
captured["tool_name"] = context.tool_name
captured["arguments"] = context.arguments
return {"request_id": "req-123", "locale": "ja"}
server = FakeMCPServer(tool_meta_resolver=resolve_meta)
tool = MCPTool(
name="test_tool_1",
inputSchema={},
_meta={"locale": "en", "extra": "value"},
)
function_tool = MCPUtil.to_function_tool(tool, server, convert_schemas_to_strict=False)
tool_context = ToolContext(
context={"request_id": "req-123"},
tool_name="test_tool_1",
tool_call_id="test_call_static_meta_with_resolver",
tool_arguments="{}",
)
await function_tool.on_invoke_tool(tool_context, "{}")
assert server.tool_metas[-1] == {"request_id": "req-123", "locale": "en", "extra": "value"}
assert captured["server_name"] == server.name
assert captured["tool_name"] == "test_tool_1"
assert captured["arguments"] == {}
@pytest.mark.asyncio
async def test_mcp_invoke_bad_json_errors(caplog: pytest.LogCaptureFixture):
caplog.set_level(logging.DEBUG)
"""Test that bad JSON input errors are logged and re-raised."""
server = FakeMCPServer()
server.add_tool("test_tool_1", {})
ctx = RunContextWrapper(context=None)
tool = MCPTool(name="test_tool_1", inputSchema={})
with pytest.raises(ModelBehaviorError):
await MCPUtil.invoke_mcp_tool(server, tool, ctx, "not_json")
assert "Invalid JSON input for tool test_tool_1" in caplog.text
class CrashingFakeMCPServer(FakeMCPServer):
async def call_tool(
self,
tool_name: str,
arguments: dict[str, Any] | None,
meta: dict[str, Any] | None = None,
):
raise Exception("Crash!")
class CancelledFakeMCPServer(FakeMCPServer):
async def call_tool(
self,
tool_name: str,
arguments: dict[str, Any] | None,
meta: dict[str, Any] | None = None,
):
raise asyncio.CancelledError("synthetic mcp cancel")
class SlowFakeMCPServer(FakeMCPServer):
async def call_tool(
self,
tool_name: str,
arguments: dict[str, Any] | None,
meta: dict[str, Any] | None = None,
):
await asyncio.sleep(60)
return await super().call_tool(tool_name, arguments, meta=meta)
class CleanupOnCancelFakeMCPServer(FakeMCPServer):
def __init__(self, cleanup_finished: asyncio.Event):
super().__init__()
self.cleanup_finished = cleanup_finished
async def call_tool(
self,
tool_name: str,
arguments: dict[str, Any] | None,
meta: dict[str, Any] | None = None,
):
try:
await asyncio.sleep(60)
except asyncio.CancelledError:
await asyncio.sleep(0.05)
self.cleanup_finished.set()
raise
@pytest.mark.asyncio
async def test_mcp_invocation_crash_causes_error(caplog: pytest.LogCaptureFixture):
caplog.set_level(logging.DEBUG)
"""Test that bad JSON input errors are logged and re-raised."""
server = CrashingFakeMCPServer()
server.add_tool("test_tool_1", {})
ctx = RunContextWrapper(context=None)
tool = MCPTool(name="test_tool_1", inputSchema={})
with pytest.raises(AgentsException):
await MCPUtil.invoke_mcp_tool(server, tool, ctx, "")
assert "Error invoking MCP tool test_tool_1" in caplog.text
@pytest.mark.asyncio
async def test_mcp_tool_inner_cancellation_becomes_tool_error():
server = CancelledFakeMCPServer()
server.add_tool("cancel_tool", {})
ctx = RunContextWrapper(context=None)
tool = MCPTool(name="cancel_tool", inputSchema={})
with pytest.raises(MCPToolCancellationError, match="tool execution was cancelled"):
await MCPUtil.invoke_mcp_tool(server, tool, ctx, "{}")
agent = Agent(name="test-agent")
function_tool = MCPUtil.to_function_tool(
tool, server, convert_schemas_to_strict=False, agent=agent
)
tool_context = ToolContext(
context=None,
tool_name="cancel_tool",
tool_call_id="test_call_cancelled",
tool_arguments="{}",
)
result = await function_tool.on_invoke_tool(tool_context, "{}")
assert isinstance(result, str)
assert "tool execution was cancelled" in result
@pytest.mark.asyncio
async def test_mcp_tool_inner_cancellation_still_becomes_tool_error_with_prior_cancel_state():
current_task = asyncio.current_task()
assert current_task is not None
current_task.cancel()
with pytest.raises(asyncio.CancelledError):
await asyncio.sleep(0)
server = CancelledFakeMCPServer()
server.add_tool("cancel_tool", {})
ctx = RunContextWrapper(context=None)
tool = MCPTool(name="cancel_tool", inputSchema={})
with pytest.raises(MCPToolCancellationError, match="tool execution was cancelled"):
await MCPUtil.invoke_mcp_tool(server, tool, ctx, "{}")
@pytest.mark.asyncio
async def test_mcp_tool_outer_cancellation_still_propagates():
server = SlowFakeMCPServer()
server.add_tool("slow_tool", {})
ctx = RunContextWrapper(context=None)
tool = MCPTool(name="slow_tool", inputSchema={})
task = asyncio.create_task(MCPUtil.invoke_mcp_tool(server, tool, ctx, "{}"))
await asyncio.sleep(0.05)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
@pytest.mark.asyncio
async def test_mcp_tool_outer_cancellation_after_inner_completion_still_propagates(
monkeypatch: pytest.MonkeyPatch,
):
server = FakeMCPServer()
server.add_tool("fast_tool", {})
ctx = RunContextWrapper(context=None)
tool = MCPTool(name="fast_tool", inputSchema={})
async def fake_wait(tasks, *, return_when):
del return_when
(task,) = tuple(tasks)
await task
raise asyncio.CancelledError("synthetic outer cancellation")
monkeypatch.setattr(asyncio, "wait", fake_wait)
with pytest.raises(asyncio.CancelledError):
await MCPUtil.invoke_mcp_tool(server, tool, ctx, "{}")
@pytest.mark.asyncio
async def test_mcp_tool_outer_cancellation_after_inner_exception_still_propagates(
monkeypatch: pytest.MonkeyPatch,
):
server = CrashingFakeMCPServer()
server.add_tool("boom_tool", {})
ctx = RunContextWrapper(context=None)
tool = MCPTool(name="boom_tool", inputSchema={})
async def fake_wait(tasks, *, return_when):
del return_when
(task,) = tuple(tasks)
try:
await task
except Exception:
pass
raise asyncio.CancelledError("synthetic outer cancellation")
monkeypatch.setattr(asyncio, "wait", fake_wait)
with pytest.raises(asyncio.CancelledError):
await MCPUtil.invoke_mcp_tool(server, tool, ctx, "{}")
@pytest.mark.asyncio
async def test_mcp_tool_outer_cancellation_after_inner_cancellation_still_propagates(
monkeypatch: pytest.MonkeyPatch,
):
server = SlowFakeMCPServer()
server.add_tool("slow_tool", {})
ctx = RunContextWrapper(context=None)
tool = MCPTool(name="slow_tool", inputSchema={})
async def fake_wait(tasks, *, return_when):
del return_when
(task,) = tuple(tasks)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
raise asyncio.CancelledError("synthetic combined cancellation")
monkeypatch.setattr(asyncio, "wait", fake_wait)
with pytest.raises(asyncio.CancelledError):
await MCPUtil.invoke_mcp_tool(server, tool, ctx, "{}")
@pytest.mark.asyncio
async def test_mcp_tool_outer_cancellation_waits_for_inner_cleanup():
cleanup_finished = asyncio.Event()
server = CleanupOnCancelFakeMCPServer(cleanup_finished)
server.add_tool("slow_tool", {})
ctx = RunContextWrapper(context=None)
tool = MCPTool(name="slow_tool", inputSchema={})
task = asyncio.create_task(MCPUtil.invoke_mcp_tool(server, tool, ctx, "{}"))
await asyncio.sleep(0.05)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert cleanup_finished.is_set()
@pytest.mark.asyncio
async def test_mcp_invocation_mcp_error_reraises(caplog: pytest.LogCaptureFixture):
"""Test that McpError from server.call_tool is re-raised so the FunctionTool failure
pipeline (failure_error_function) can handle it.
When an MCP server raises McpError (e.g. upstream HTTP 4xx/5xx), invoke_mcp_tool
re-raises so the configured failure_error_function shapes the model-visible error.
With the default failure_error_function the FunctionTool returns a string error
result; with failure_error_function=None the error is propagated to the caller.
"""
caplog.set_level(logging.DEBUG)
from mcp.shared.exceptions import McpError
from mcp.types import ErrorData
class McpErrorFakeMCPServer(FakeMCPServer):
async def call_tool(
self,
tool_name: str,
arguments: dict[str, Any] | None,
meta: dict[str, Any] | None = None,
):
raise McpError(ErrorData(code=-32000, message="upstream 422 Unprocessable Entity"))
server = McpErrorFakeMCPServer()
server.add_tool("search", {})
ctx = RunContextWrapper(context=None)
tool = MCPTool(name="search", inputSchema={})
# invoke_mcp_tool itself should re-raise McpError
with pytest.raises(McpError):
await MCPUtil.invoke_mcp_tool(server, tool, ctx, "{}")
# Warning (not error) should be logged before re-raising
assert "returned an error" in caplog.text
# Via FunctionTool with default failure_error_function: error becomes a string result
mcp_tool = MCPTool(name="search", inputSchema={})
agent = Agent(name="test-agent")
function_tool = MCPUtil.to_function_tool(
mcp_tool, server, convert_schemas_to_strict=False, agent=agent
)
tool_context = ToolContext(
context=None,
tool_name="search",
tool_call_id="test_call_mcp_error",
tool_arguments="{}",
)
result = await function_tool.on_invoke_tool(tool_context, "{}")
assert isinstance(result, str)
assert "upstream 422 Unprocessable Entity" in result or "error" in result.lower()
@pytest.mark.asyncio
async def test_mcp_tool_graceful_error_handling(caplog: pytest.LogCaptureFixture):
"""Test that MCP tool errors are handled gracefully when invoked via FunctionTool.
When an MCP tool is created via to_function_tool and then invoked, errors should be
caught and converted to error messages instead of raising exceptions. This allows
the agent to continue running after tool failures.
"""
caplog.set_level(logging.DEBUG)
# Create a server that will crash when calling a tool
server = CrashingFakeMCPServer()
server.add_tool("crashing_tool", {})
# Convert MCP tool to FunctionTool (this wraps invoke_mcp_tool with error handling)
mcp_tool = MCPTool(name="crashing_tool", inputSchema={})
agent = Agent(name="test-agent")
function_tool = MCPUtil.to_function_tool(
mcp_tool, server, convert_schemas_to_strict=False, agent=agent
)
# Create tool context
tool_context = ToolContext(
context=None,
tool_name="crashing_tool",
tool_call_id="test_call_1",
tool_arguments="{}",
)
# Invoke the tool - should NOT raise an exception, but return an error message
result = await function_tool.on_invoke_tool(tool_context, "{}")
# Verify that the result is an error message (not an exception)
assert isinstance(result, str)
assert "error" in result.lower() or "occurred" in result.lower()
# Verify that the error message matches what default_tool_error_function would return
# The error gets wrapped in AgentsException by invoke_mcp_tool, so we check for that format
# The error message now includes the server name
wrapped_error = AgentsException(
"Error invoking MCP tool crashing_tool on server 'fake_mcp_server': Crash!"
)
expected_error_msg = default_tool_error_function(tool_context, wrapped_error)
assert result == expected_error_msg
# Verify that the error was logged
assert (
"MCP tool crashing_tool failed" in caplog.text or "Error invoking MCP tool" in caplog.text
)
@pytest.mark.asyncio
async def test_mcp_tool_timeout_handling():
"""Test that MCP tool timeouts are handled gracefully.
This simulates a timeout scenario where the MCP server call_tool raises a timeout error.
The error should be caught and converted to an error message instead of halting the agent.
"""
class TimeoutFakeMCPServer(FakeMCPServer):
async def call_tool(
self,
tool_name: str,
arguments: dict[str, Any] | None,
meta: dict[str, Any] | None = None,
):
# Simulate a timeout error - this would normally be wrapped in AgentsException
# by invoke_mcp_tool
raise Exception(
"Timed out while waiting for response to ClientRequest. Waited 1.0 seconds."
)
server = TimeoutFakeMCPServer()
server.add_tool("timeout_tool", {})
# Convert MCP tool to FunctionTool
mcp_tool = MCPTool(name="timeout_tool", inputSchema={})
agent = Agent(name="test-agent")
function_tool = MCPUtil.to_function_tool(
mcp_tool, server, convert_schemas_to_strict=False, agent=agent
)
# Create tool context
tool_context = ToolContext(
context=None,
tool_name="timeout_tool",
tool_call_id="test_call_2",
tool_arguments="{}",
)
# Invoke the tool - should NOT raise an exception
result = await function_tool.on_invoke_tool(tool_context, "{}")
# Verify that the result is an error message
assert isinstance(result, str)
assert "error" in result.lower() or "occurred" in result.lower()
assert "Timed out" in result
@pytest.mark.asyncio
async def test_mcp_tool_cancellation_returns_error_message():
server = CancelledFakeMCPServer()
server.add_tool("cancelled_tool", {})
mcp_tool = MCPTool(name="cancelled_tool", inputSchema={})
agent = Agent(name="test-agent")
function_tool = MCPUtil.to_function_tool(
mcp_tool, server, convert_schemas_to_strict=False, agent=agent
)
tool_context = ToolContext(
context=None,
tool_name="cancelled_tool",
tool_call_id="test_call_cancelled",
tool_arguments="{}",
)
result = await function_tool.on_invoke_tool(tool_context, "{}")
assert isinstance(result, str)
assert "cancelled" in result.lower()
@pytest.mark.asyncio
async def test_to_function_tool_legacy_call_without_agent_uses_server_policy():
"""Legacy three-argument to_function_tool calls should honor server policy."""
server = FakeMCPServer(require_approval="always")
server.add_tool("legacy_tool", {})
# Backward compatibility: old call style omitted the `agent` argument.
function_tool = MCPUtil.to_function_tool(
MCPTool(name="legacy_tool", inputSchema={}),
server,
convert_schemas_to_strict=False,
)
# Legacy calls should still respect server-level approval settings.
assert function_tool.needs_approval is True
tool_context = ToolContext(
context=None,
tool_name="legacy_tool",
tool_call_id="legacy_call_1",
tool_arguments="{}",
)
result = await function_tool.on_invoke_tool(tool_context, "{}")
if isinstance(result, str):
assert "result_legacy_tool_" in result
elif isinstance(result, dict):
assert "result_legacy_tool_" in str(result.get("text", ""))
else:
pytest.fail(f"Unexpected tool result type: {type(result).__name__}")
@pytest.mark.asyncio
async def test_to_function_tool_legacy_call_callable_policy_requires_approval():
"""Legacy to_function_tool calls should default to approval for callable policies."""
server = FakeMCPServer()
server.add_tool("legacy_callable_tool", {})
def require_approval(
_run_context: RunContextWrapper[Any],
_agent: Agent,
_tool: MCPTool,
) -> bool:
return False
server._needs_approval_policy = require_approval # type: ignore[assignment]
function_tool = MCPUtil.to_function_tool(
MCPTool(name="legacy_callable_tool", inputSchema={}),
server,
convert_schemas_to_strict=False,
)
assert function_tool.needs_approval is True
@pytest.mark.asyncio
async def test_to_function_tool_callable_policy_uses_agent_and_tool():
"""Callable require_approval policies should bridge into FunctionTool.needs_approval."""
captured: dict[str, Any] = {}
def require_approval(
run_context: RunContextWrapper[Any],
agent: Agent,
tool: MCPTool,
) -> bool:
captured["run_context"] = run_context
captured["agent"] = agent
captured["tool"] = tool
return tool.name == "guarded_tool"
server = FakeMCPServer(require_approval=require_approval)
tool = MCPTool(name="guarded_tool", inputSchema={})
agent = Agent(name="test-agent")
function_tool = MCPUtil.to_function_tool(
tool,
server,
convert_schemas_to_strict=False,
agent=agent,
)
assert callable(function_tool.needs_approval)
run_context = RunContextWrapper(context={"request_id": "req_123"})
needs_approval = await function_tool.needs_approval(run_context, {}, "call_123")
assert needs_approval is True
assert captured["run_context"] is run_context
assert captured["agent"] is agent
assert captured["tool"].name == "guarded_tool"
@pytest.mark.asyncio
async def test_to_function_tool_async_callable_policy_is_awaited():
"""Async require_approval policies should be awaited before tool execution."""
async def require_approval(
_run_context: RunContextWrapper[Any],
_agent: Agent,
tool: MCPTool,
) -> bool:
await asyncio.sleep(0)
return tool.name == "async_guarded_tool"
server = FakeMCPServer(require_approval=require_approval)
tool = MCPTool(name="async_guarded_tool", inputSchema={})
agent = Agent(name="test-agent")
function_tool = MCPUtil.to_function_tool(
tool,
server,
convert_schemas_to_strict=False,
agent=agent,
)
assert callable(function_tool.needs_approval)
needs_approval = await function_tool.needs_approval(
RunContextWrapper(context=None),
{},
"call_async_123",
)
assert needs_approval is True
@pytest.mark.asyncio
async def test_mcp_tool_failure_error_function_agent_default():
"""Agent-level failure_error_function should handle MCP tool failures."""
def custom_failure(_ctx: RunContextWrapper[Any], _exc: Exception) -> str:
return "custom_mcp_failure"
server = CrashingFakeMCPServer()
server.add_tool("crashing_tool", {})
agent = Agent(
name="test-agent",
mcp_servers=[server],
mcp_config={"failure_error_function": custom_failure},
)
run_context = RunContextWrapper(context=None)
tools = await agent.get_mcp_tools(run_context)
function_tool = next(tool for tool in tools if tool.name == "crashing_tool")
assert isinstance(function_tool, FunctionTool)
tool_context = ToolContext(
context=None,
tool_name="crashing_tool",
tool_call_id="test_call_custom_1",
tool_arguments="{}",
)
result = await function_tool.on_invoke_tool(tool_context, "{}")
assert result == "custom_mcp_failure"
@pytest.mark.asyncio
async def test_mcp_tool_failure_error_function_server_override():
"""Server-level failure_error_function should override agent defaults."""
def agent_failure(_ctx: RunContextWrapper[Any], _exc: Exception) -> str:
return "agent_failure"
def server_failure(_ctx: RunContextWrapper[Any], _exc: Exception) -> str:
return "server_failure"
server = CrashingFakeMCPServer(failure_error_function=server_failure)
server.add_tool("crashing_tool", {})
agent = Agent(
name="test-agent",
mcp_servers=[server],
mcp_config={"failure_error_function": agent_failure},
)
run_context = RunContextWrapper(context=None)
tools = await agent.get_mcp_tools(run_context)
function_tool = next(tool for tool in tools if tool.name == "crashing_tool")
assert isinstance(function_tool, FunctionTool)
tool_context = ToolContext(
context=None,
tool_name="crashing_tool",
tool_call_id="test_call_custom_2",
tool_arguments="{}",
)
result = await function_tool.on_invoke_tool(tool_context, "{}")
assert result == "server_failure"
@pytest.mark.asyncio
async def test_mcp_tool_failure_error_function_server_none_raises():
"""Server-level None should re-raise MCP tool failures."""
server = CrashingFakeMCPServer(failure_error_function=None)
server.add_tool("crashing_tool", {})
agent = Agent(
name="test-agent",
mcp_servers=[server],
mcp_config={"failure_error_function": default_tool_error_function},
)
run_context = RunContextWrapper(context=None)
tools = await agent.get_mcp_tools(run_context)
function_tool = next(tool for tool in tools if tool.name == "crashing_tool")
assert isinstance(function_tool, FunctionTool)
tool_context = ToolContext(
context=None,
tool_name="crashing_tool",
tool_call_id="test_call_custom_3",
tool_arguments="{}",
)
with pytest.raises(AgentsException):
await function_tool.on_invoke_tool(tool_context, "{}")
@pytest.mark.asyncio
async def test_replaced_mcp_tool_normal_failure_uses_replaced_policy():
server = CrashingFakeMCPServer()
server.add_tool("crashing_tool", {})
agent = Agent(
name="test-agent",
mcp_servers=[server],
mcp_config={"failure_error_function": default_tool_error_function},
)
run_context = RunContextWrapper(context=None)
function_tools = await agent.get_mcp_tools(run_context)
original_tool = next(tool for tool in function_tools if tool.name == "crashing_tool")
assert isinstance(original_tool, FunctionTool)
replaced_tool = dataclasses.replace(
original_tool,
_failure_error_function=None,
_use_default_failure_error_function=False,
)
tool_context = ToolContext(
context=None,
tool_name=replaced_tool.name,
tool_call_id="test_call_custom_4",
tool_arguments="{}",
)
with pytest.raises(AgentsException):
await replaced_tool.on_invoke_tool(tool_context, "{}")
@pytest.mark.asyncio
async def test_agent_convert_schemas_true():
"""Test that setting convert_schemas_to_strict to True converts non-strict schemas to strict.
- 'foo' tool is already strict and remains strict.
- 'bar' tool is non-strict and becomes strict (additionalProperties set to False, etc).
"""
strict_schema = Foo.model_json_schema()
non_strict_schema = Baz.json_schema()
possible_to_convert_schema = _convertible_schema()
server = FakeMCPServer()
server.add_tool("foo", strict_schema)
server.add_tool("bar", non_strict_schema)
server.add_tool("baz", possible_to_convert_schema)
agent = Agent(
name="test_agent", mcp_servers=[server], mcp_config={"convert_schemas_to_strict": True}
)
run_context = RunContextWrapper(context=None)
tools = await agent.get_mcp_tools(run_context)
foo_tool = next(tool for tool in tools if tool.name == "foo")
assert isinstance(foo_tool, FunctionTool)
bar_tool = next(tool for tool in tools if tool.name == "bar")
assert isinstance(bar_tool, FunctionTool)
baz_tool = next(tool for tool in tools if tool.name == "baz")
assert isinstance(baz_tool, FunctionTool)
# Checks that additionalProperties is set to False
assert foo_tool.params_json_schema == snapshot(
{
"properties": {
"bar": {"title": "Bar", "type": "string"},
"baz": {"title": "Baz", "type": "integer"},
},
"required": ["bar", "baz"],
"title": "Foo",
"type": "object",
"additionalProperties": False,
}
)
assert foo_tool.strict_json_schema is True, "foo_tool should be strict"
# Checks that additionalProperties is set to False
assert bar_tool.params_json_schema == snapshot(
{"type": "object", "additionalProperties": {"type": "string"}, "properties": {}}
)
assert bar_tool.strict_json_schema is False, "bar_tool should not be strict"
# Checks that additionalProperties is set to False
assert baz_tool.params_json_schema == snapshot(
{
"properties": {
"bar": {"title": "Bar", "type": "string"},
"baz": {"title": "Baz", "type": "integer"},
},
"required": ["bar", "baz"],
"title": "Foo",
"type": "object",
"additionalProperties": False,
}
)
assert baz_tool.strict_json_schema is True, "baz_tool should be strict"
@pytest.mark.asyncio
async def test_agent_convert_schemas_false():
"""Test that setting convert_schemas_to_strict to False leaves tool schemas as non-strict.
- 'foo' tool remains strict.
- 'bar' tool remains non-strict (additionalProperties remains True).
"""
strict_schema = Foo.model_json_schema()
non_strict_schema = Baz.json_schema()
possible_to_convert_schema = _convertible_schema()
server = FakeMCPServer()
server.add_tool("foo", strict_schema)
server.add_tool("bar", non_strict_schema)
server.add_tool("baz", possible_to_convert_schema)
agent = Agent(
name="test_agent", mcp_servers=[server], mcp_config={"convert_schemas_to_strict": False}
)
run_context = RunContextWrapper(context=None)
tools = await agent.get_mcp_tools(run_context)
foo_tool = next(tool for tool in tools if tool.name == "foo")
assert isinstance(foo_tool, FunctionTool)
bar_tool = next(tool for tool in tools if tool.name == "bar")
assert isinstance(bar_tool, FunctionTool)
baz_tool = next(tool for tool in tools if tool.name == "baz")
assert isinstance(baz_tool, FunctionTool)
assert foo_tool.params_json_schema == strict_schema
assert foo_tool.strict_json_schema is False, "Shouldn't be converted unless specified"
assert bar_tool.params_json_schema == snapshot(
{"type": "object", "additionalProperties": {"type": "string"}, "properties": {}}
)
assert bar_tool.strict_json_schema is False
assert baz_tool.params_json_schema == possible_to_convert_schema
assert baz_tool.strict_json_schema is False, "Shouldn't be converted unless specified"
@pytest.mark.asyncio
async def test_mcp_fastmcp_behavior_verification():
"""Test that verifies the exact FastMCP _convert_to_content behavior we observed.
Based on our testing, FastMCP's _convert_to_content function behaves as follows:
- None → content=[] → MCPUtil returns "[]"
- [] → content=[] → MCPUtil returns "[]"
- {} → content=[TextContent(text="{}")] → MCPUtil returns full JSON
- [{}] → content=[TextContent(text="{}")] → MCPUtil returns full JSON (flattened)
- [[]] → content=[] → MCPUtil returns "[]" (recursive empty)
"""
from mcp.types import TextContent
server = FakeMCPServer()
server.add_tool("test_tool", {})
ctx = RunContextWrapper(context=None)
tool = MCPTool(name="test_tool", inputSchema={})
# Case 1: None -> [].