-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Expand file tree
/
Copy pathtest_mcp_tool.py
More file actions
1493 lines (1240 loc) · 49.2 KB
/
Copy pathtest_mcp_tool.py
File metadata and controls
1493 lines (1240 loc) · 49.2 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
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import inspect
from unittest.mock import AsyncMock
from unittest.mock import create_autospec
from unittest.mock import Mock
from unittest.mock import patch
from google.adk.agents.context import Context
from google.adk.auth.auth_credential import AuthCredential
from google.adk.auth.auth_credential import AuthCredentialTypes
from google.adk.auth.auth_credential import HttpAuth
from google.adk.auth.auth_credential import HttpCredentials
from google.adk.auth.auth_credential import OAuth2Auth
from google.adk.auth.auth_credential import ServiceAccount
from google.adk.features import FeatureName
from google.adk.features._feature_registry import temporary_feature_override
from google.adk.tools.mcp_tool import mcp_tool
from google.adk.tools.mcp_tool.mcp_session_manager import MCPSessionManager
from google.adk.tools.mcp_tool.mcp_tool import MCPTool
from google.adk.tools.tool_context import ToolContext
from google.genai.types import FunctionDeclaration
from google.genai.types import Type
from mcp.types import CallToolResult
from mcp.types import TextContent
import pytest
# Mock MCP Tool from mcp.types
class MockMCPTool:
"""Mock MCP Tool for testing."""
def __init__(
self,
name="test_tool",
description="Test tool description",
outputSchema=None,
meta=None,
):
self.name = name
self.description = description
self.meta = meta
self.inputSchema = {
"type": "object",
"properties": {
"param1": {"type": "string", "description": "First parameter"},
"param2": {"type": "integer", "description": "Second parameter"},
},
"required": ["param1"],
}
self.outputSchema = outputSchema
class TestMCPToolLegacy:
"""Legacy tests for MCPTool."""
@pytest.fixture(autouse=True)
def disable_feature_flag(self):
with temporary_feature_override(
FeatureName.JSON_SCHEMA_FOR_FUNC_DECL, False
):
yield
def setup_method(self):
self.mock_mcp_tool = MockMCPTool()
self.mock_session_manager = Mock(spec=MCPSessionManager)
self.mock_session = AsyncMock()
self.mock_session_manager.create_session = AsyncMock(
return_value=self.mock_session
)
def test_get_declaration(self):
"""Test function declaration generation."""
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
)
declaration = tool._get_declaration()
assert isinstance(declaration, FunctionDeclaration)
assert declaration.name == "test_tool"
assert declaration.description == "Test tool description"
assert declaration.parameters is not None
class TestMCPToolWithJsonSchema:
"""Tests for MCPTool with JSON_SCHEMA_FOR_FUNC_DECL enabled."""
@pytest.fixture(autouse=True)
def enable_feature_flag(self):
with temporary_feature_override(
FeatureName.JSON_SCHEMA_FOR_FUNC_DECL, True
):
yield
def setup_method(self):
self.mock_mcp_tool = MockMCPTool()
self.mock_session_manager = Mock(spec=MCPSessionManager)
self.mock_session = AsyncMock()
self.mock_session_manager.create_session = AsyncMock(
return_value=self.mock_session
)
def test_get_declaration_with_json_schema_for_func_decl_enabled(self):
"""Test function declaration generation with json schema for func decl enabled."""
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
)
with temporary_feature_override(
FeatureName.JSON_SCHEMA_FOR_FUNC_DECL, True
):
declaration = tool._get_declaration()
assert isinstance(declaration, FunctionDeclaration)
assert declaration.name == "test_tool"
assert declaration.description == "Test tool description"
assert declaration.parameters is None
assert declaration.parameters_json_schema is not None
assert declaration.response is None
assert declaration.response_json_schema is None
def test_get_declaration_with_output_schema_and_json_schema_for_func_decl_enabled(
self,
):
"""Test function declaration generation with an output schema and json schema for func decl enabled."""
output_schema = {
"type": "object",
"properties": {
"status": {
"type": "string",
"description": "The status of the operation",
},
},
}
tool = MCPTool(
mcp_tool=MockMCPTool(outputSchema=output_schema),
mcp_session_manager=self.mock_session_manager,
)
with temporary_feature_override(
FeatureName.JSON_SCHEMA_FOR_FUNC_DECL, True
):
declaration = tool._get_declaration()
assert isinstance(declaration, FunctionDeclaration)
assert declaration.response is None
assert declaration.response_json_schema == output_schema
def test_get_declaration_with_empty_output_schema_and_json_schema_for_func_decl_enabled(
self,
):
"""Test function declaration with an empty output schema and json schema for func decl enabled."""
tool = MCPTool(
mcp_tool=MockMCPTool(outputSchema={}),
mcp_session_manager=self.mock_session_manager,
)
with temporary_feature_override(
FeatureName.JSON_SCHEMA_FOR_FUNC_DECL, True
):
declaration = tool._get_declaration()
assert declaration.response is None
assert not declaration.response_json_schema
class TestMCPTool:
"""Test suite for MCPTool class."""
def setup_method(self):
"""Set up test fixtures."""
self.mock_mcp_tool = MockMCPTool()
self.mock_session_manager = Mock(spec=MCPSessionManager)
self.mock_session = AsyncMock()
self.mock_session_manager.create_session = AsyncMock(
return_value=self.mock_session
)
def test_init_basic(self):
"""Test basic initialization without auth."""
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
)
assert tool.name == "test_tool"
assert tool.description == "Test tool description"
assert tool._mcp_tool == self.mock_mcp_tool
assert tool._mcp_session_manager == self.mock_session_manager
def test_init_with_auth(self):
"""Test initialization with authentication."""
# Create real auth scheme instances instead of mocks
from fastapi.openapi.models import OAuth2
auth_scheme = OAuth2(flows={})
auth_credential = AuthCredential(
auth_type=AuthCredentialTypes.OAUTH2,
oauth2=OAuth2Auth(client_id="test_id", client_secret="test_secret"),
)
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
auth_scheme=auth_scheme,
auth_credential=auth_credential,
)
# The auth config is stored in the parent class _credentials_manager
assert tool._credentials_manager is not None
assert tool._credentials_manager._auth_config.auth_scheme == auth_scheme
assert (
tool._credentials_manager._auth_config.raw_auth_credential
== auth_credential
)
def test_init_with_empty_description(self):
"""Test initialization with empty description."""
mock_tool = MockMCPTool(description=None)
tool = MCPTool(
mcp_tool=mock_tool,
mcp_session_manager=self.mock_session_manager,
)
assert tool.description == ""
@pytest.mark.asyncio
async def test_run_async_impl_no_auth(self):
"""Test running tool without authentication."""
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
)
# Mock the session response - must return CallToolResult
mcp_response = CallToolResult(
content=[TextContent(type="text", text="success")]
)
self.mock_session.call_tool = AsyncMock(return_value=mcp_response)
tool_context = ToolContext(invocation_context=Mock())
tool_context.function_call_id = "test-call-id"
args = {"param1": "test_value"}
result = await tool._run_async_impl(
args=args, tool_context=tool_context, credential=None
)
# Verify the result matches the model_dump output
assert result == mcp_response.model_dump(exclude_none=True, mode="json")
self.mock_session_manager.create_session.assert_called_once_with(
headers=None
)
# Fix: call_tool uses 'arguments' parameter, not positional args
self.mock_session.call_tool.assert_called_once_with(
"test_tool", arguments=args, progress_callback=None, meta=None
)
@pytest.mark.asyncio
async def test_run_async_impl_adds_ui_widget(self):
"""Test running tool adds UiWidget to actions."""
meta = {"ui": {"resourceUri": "ui://test-app"}}
mock_tool = MockMCPTool(meta=meta)
tool = MCPTool(
mcp_tool=mock_tool,
mcp_session_manager=self.mock_session_manager,
)
mcp_response = CallToolResult(
content=[TextContent(type="text", text="success")]
)
self.mock_session.call_tool = AsyncMock(return_value=mcp_response)
tool_context = ToolContext(invocation_context=Mock())
tool_context.function_call_id = "test-call-id"
args = {"param1": "test_value"}
# tool_context.actions.render_ui_widgets is None initially
result = await tool._run_async_impl(
args=args, tool_context=tool_context, credential=None
)
assert result == mcp_response.model_dump(exclude_none=True, mode="json")
assert tool_context.actions.render_ui_widgets is not None
assert len(tool_context.actions.render_ui_widgets) == 1
widget = tool_context.actions.render_ui_widgets[0]
assert widget.id == "test-call-id"
assert widget.provider == "mcp"
assert widget.payload["resource_uri"] == "ui://test-app"
assert widget.payload["tool"] == mock_tool
assert widget.payload["tool_args"] == args
@pytest.mark.asyncio
async def test_run_async_impl_with_oauth2(self):
"""Test running tool with OAuth2 authentication."""
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
)
# Create OAuth2 credential
oauth2_auth = OAuth2Auth(access_token="test_access_token")
credential = AuthCredential(
auth_type=AuthCredentialTypes.OAUTH2, oauth2=oauth2_auth
)
# Mock the session response - must return CallToolResult
mcp_response = CallToolResult(
content=[TextContent(type="text", text="success")]
)
self.mock_session.call_tool = AsyncMock(return_value=mcp_response)
tool_context = Mock(spec=ToolContext)
args = {"param1": "test_value"}
result = await tool._run_async_impl(
args=args, tool_context=tool_context, credential=credential
)
assert result == mcp_response.model_dump(exclude_none=True, mode="json")
# Check that headers were passed correctly
self.mock_session_manager.create_session.assert_called_once()
call_args = self.mock_session_manager.create_session.call_args
headers = call_args[1]["headers"]
assert headers == {"Authorization": "Bearer test_access_token"}
@patch.object(mcp_tool, "propagate", autospec=True)
@pytest.mark.asyncio
async def test_run_async_impl_with_trace_context(self, mock_propagate):
"""Test running tool with trace context injection."""
mock_propagator = Mock()
def inject_context(carrier, context=None) -> None:
carrier["traceparent"] = (
"00-1234567890abcdef1234567890abcdef-1234567890abcdef-01"
)
carrier["tracestate"] = "foo=bar"
carrier["baggage"] = "baz=qux"
mock_propagator.inject.side_effect = inject_context
mock_propagate.get_global_textmap.return_value = mock_propagator
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
)
mcp_response = CallToolResult(
content=[TextContent(type="text", text="success")]
)
self.mock_session.call_tool = AsyncMock(return_value=mcp_response)
tool_context = Mock(spec=ToolContext)
args = {"param1": "test_value"}
await tool._run_async_impl(
args=args, tool_context=tool_context, credential=None
)
self.mock_session_manager.create_session.assert_called_once_with(
headers=None
)
self.mock_session.call_tool.assert_called_once_with(
"test_tool",
arguments=args,
progress_callback=None,
meta={
"traceparent": (
"00-1234567890abcdef1234567890abcdef-1234567890abcdef-01"
),
"tracestate": "foo=bar",
"baggage": "baz=qux",
},
)
@pytest.mark.asyncio
async def test_get_headers_oauth2(self):
"""Test header generation for OAuth2 credentials."""
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
)
oauth2_auth = OAuth2Auth(access_token="test_token")
credential = AuthCredential(
auth_type=AuthCredentialTypes.OAUTH2, oauth2=oauth2_auth
)
tool_context = Mock(spec=ToolContext)
headers = await tool._get_headers(tool_context, credential)
assert headers == {"Authorization": "Bearer test_token"}
@pytest.mark.asyncio
async def test_get_headers_http_bearer(self):
"""Test header generation for HTTP Bearer credentials."""
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
)
http_auth = HttpAuth(
scheme="bearer", credentials=HttpCredentials(token="bearer_token")
)
credential = AuthCredential(
auth_type=AuthCredentialTypes.HTTP, http=http_auth
)
tool_context = Mock(spec=ToolContext)
headers = await tool._get_headers(tool_context, credential)
assert headers == {"Authorization": "Bearer bearer_token"}
@pytest.mark.asyncio
async def test_get_headers_http_basic(self):
"""Test header generation for HTTP Basic credentials."""
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
)
http_auth = HttpAuth(
scheme="basic",
credentials=HttpCredentials(username="user", password="pass"),
)
credential = AuthCredential(
auth_type=AuthCredentialTypes.HTTP, http=http_auth
)
tool_context = Mock(spec=ToolContext)
headers = await tool._get_headers(tool_context, credential)
# Should create Basic auth header with base64 encoded credentials
import base64
expected_encoded = base64.b64encode(b"user:pass").decode()
assert headers == {"Authorization": f"Basic {expected_encoded}"}
@pytest.mark.asyncio
@pytest.mark.parametrize(
"token, expected_headers",
[
(
"some-token",
{
"Authorization": "some-scheme some-token",
"X-Custom-Header": "custom-value",
},
),
(
None,
{"X-Custom-Header": "custom-value"},
),
],
)
async def test_get_headers_http_adds_additional_headers(
self, token, expected_headers
):
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
)
http_auth = HttpAuth(
scheme="some-scheme",
credentials=HttpCredentials(token=token),
additional_headers={"X-Custom-Header": "custom-value"},
)
credential = AuthCredential(
auth_type=AuthCredentialTypes.HTTP, http=http_auth
)
tool_context = create_autospec(ToolContext, instance=True)
headers = await tool._get_headers(tool_context, credential)
assert headers == expected_headers
@pytest.mark.asyncio
async def test_get_headers_api_key_with_valid_header_scheme(self):
"""Test header generation for API Key credentials with header-based auth scheme."""
from fastapi.openapi.models import APIKey
from fastapi.openapi.models import APIKeyIn
from google.adk.auth.auth_schemes import AuthSchemeType
# Create auth scheme for header-based API key
auth_scheme = APIKey(**{
"type": AuthSchemeType.apiKey,
"in": APIKeyIn.header,
"name": "X-Custom-API-Key",
})
auth_credential = AuthCredential(
auth_type=AuthCredentialTypes.API_KEY, api_key="my_api_key"
)
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
auth_scheme=auth_scheme,
auth_credential=auth_credential,
)
tool_context = Mock(spec=ToolContext)
headers = await tool._get_headers(tool_context, auth_credential)
assert headers == {"X-Custom-API-Key": "my_api_key"}
@pytest.mark.asyncio
async def test_get_headers_api_key_with_query_scheme_raises_error(self):
"""Test that API Key with query-based auth scheme raises ValueError."""
from fastapi.openapi.models import APIKey
from fastapi.openapi.models import APIKeyIn
from google.adk.auth.auth_schemes import AuthSchemeType
# Create auth scheme for query-based API key (not supported)
auth_scheme = APIKey(**{
"type": AuthSchemeType.apiKey,
"in": APIKeyIn.query,
"name": "api_key",
})
auth_credential = AuthCredential(
auth_type=AuthCredentialTypes.API_KEY, api_key="my_api_key"
)
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
auth_scheme=auth_scheme,
auth_credential=auth_credential,
)
tool_context = Mock(spec=ToolContext)
with pytest.raises(
ValueError,
match="McpTool only supports header-based API key authentication",
):
await tool._get_headers(tool_context, auth_credential)
@pytest.mark.asyncio
async def test_get_headers_api_key_with_cookie_scheme_raises_error(self):
"""Test that API Key with cookie-based auth scheme raises ValueError."""
from fastapi.openapi.models import APIKey
from fastapi.openapi.models import APIKeyIn
from google.adk.auth.auth_schemes import AuthSchemeType
# Create auth scheme for cookie-based API key (not supported)
auth_scheme = APIKey(**{
"type": AuthSchemeType.apiKey,
"in": APIKeyIn.cookie,
"name": "session_id",
})
auth_credential = AuthCredential(
auth_type=AuthCredentialTypes.API_KEY, api_key="my_api_key"
)
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
auth_scheme=auth_scheme,
auth_credential=auth_credential,
)
tool_context = Mock(spec=ToolContext)
with pytest.raises(
ValueError,
match="McpTool only supports header-based API key authentication",
):
await tool._get_headers(tool_context, auth_credential)
@pytest.mark.asyncio
async def test_get_headers_api_key_without_auth_config_raises_error(self):
"""Test that API Key without auth config raises ValueError."""
# Create tool without auth scheme/config
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
)
credential = AuthCredential(
auth_type=AuthCredentialTypes.API_KEY, api_key="my_api_key"
)
tool_context = Mock(spec=ToolContext)
with pytest.raises(
ValueError,
match="Cannot find corresponding auth scheme for API key credential",
):
await tool._get_headers(tool_context, credential)
@pytest.mark.asyncio
async def test_get_headers_api_key_without_credentials_manager_raises_error(
self,
):
"""Test that API Key without credentials manager raises ValueError."""
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
)
# Manually set credentials manager to None to simulate error condition
tool._credentials_manager = None
credential = AuthCredential(
auth_type=AuthCredentialTypes.API_KEY, api_key="my_api_key"
)
tool_context = Mock(spec=ToolContext)
with pytest.raises(
ValueError,
match="Cannot find corresponding auth scheme for API key credential",
):
await tool._get_headers(tool_context, credential)
@pytest.mark.asyncio
async def test_get_headers_no_credential(self):
"""Test header generation with no credentials."""
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
)
tool_context = Mock(spec=ToolContext)
headers = await tool._get_headers(tool_context, None)
assert headers is None
@pytest.mark.asyncio
async def test_get_headers_service_account(self):
"""Test header generation for service account credentials."""
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
)
# Create service account credential
service_account = ServiceAccount(
scopes=["test"], use_default_credential=True
)
credential = AuthCredential(
auth_type=AuthCredentialTypes.SERVICE_ACCOUNT,
service_account=service_account,
)
tool_context = Mock(spec=ToolContext)
headers = await tool._get_headers(tool_context, credential)
# Should return None as service account credentials are not supported for direct header generation
assert headers is None
@pytest.mark.asyncio
async def test_run_async_impl_with_api_key_header_auth(self):
"""Test running tool with API key header authentication end-to-end."""
from fastapi.openapi.models import APIKey
from fastapi.openapi.models import APIKeyIn
from google.adk.auth.auth_schemes import AuthSchemeType
# Create auth scheme for header-based API key
auth_scheme = APIKey(**{
"type": AuthSchemeType.apiKey,
"in": APIKeyIn.header,
"name": "X-Service-API-Key",
})
auth_credential = AuthCredential(
auth_type=AuthCredentialTypes.API_KEY, api_key="test_service_key"
)
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
auth_scheme=auth_scheme,
auth_credential=auth_credential,
)
# Mock the session response - must return CallToolResult
mcp_response = CallToolResult(
content=[TextContent(type="text", text="authenticated_success")]
)
self.mock_session.call_tool = AsyncMock(return_value=mcp_response)
tool_context = Mock(spec=ToolContext)
args = {"param1": "test_value"}
result = await tool._run_async_impl(
args=args, tool_context=tool_context, credential=auth_credential
)
assert result == mcp_response.model_dump(exclude_none=True, mode="json")
# Check that headers were passed correctly with custom API key header
self.mock_session_manager.create_session.assert_called_once()
call_args = self.mock_session_manager.create_session.call_args
headers = call_args[1]["headers"]
assert headers == {"X-Service-API-Key": "test_service_key"}
@pytest.mark.asyncio
async def test_run_async_impl_retry_decorator(self):
"""Test that the retry decorator is applied correctly."""
# This is more of an integration test to ensure the decorator is present
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
)
# Check that the method has the retry decorator
assert hasattr(tool._run_async_impl, "__wrapped__")
@pytest.mark.asyncio
async def test_get_headers_http_custom_scheme(self):
"""Test header generation for custom HTTP scheme."""
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
)
http_auth = HttpAuth(
scheme="custom", credentials=HttpCredentials(token="custom_token")
)
credential = AuthCredential(
auth_type=AuthCredentialTypes.HTTP, http=http_auth
)
tool_context = Mock(spec=ToolContext)
headers = await tool._get_headers(tool_context, credential)
assert headers == {"Authorization": "custom custom_token"}
@pytest.mark.asyncio
async def test_get_headers_api_key_error_logging(self):
"""Test that API key errors are logged correctly."""
from fastapi.openapi.models import APIKey
from fastapi.openapi.models import APIKeyIn
from google.adk.auth.auth_schemes import AuthSchemeType
# Create auth scheme for query-based API key (not supported)
auth_scheme = APIKey(**{
"type": AuthSchemeType.apiKey,
"in": APIKeyIn.query,
"name": "api_key",
})
auth_credential = AuthCredential(
auth_type=AuthCredentialTypes.API_KEY, api_key="my_api_key"
)
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
auth_scheme=auth_scheme,
auth_credential=auth_credential,
)
tool_context = Mock(spec=ToolContext)
# Test with logging
with patch("google.adk.tools.mcp_tool.mcp_tool.logger") as mock_logger:
with pytest.raises(ValueError):
await tool._get_headers(tool_context, auth_credential)
# Verify error was logged
mock_logger.error.assert_called_once()
logged_message = mock_logger.error.call_args[0][0]
assert (
"McpTool only supports header-based API key authentication"
in logged_message
)
@pytest.mark.asyncio
async def test_run_async_require_confirmation_true_no_confirmation(self):
"""Test require_confirmation=True with no confirmation in context."""
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
require_confirmation=True,
)
tool_context = Mock(spec=ToolContext)
tool_context.tool_confirmation = None
tool_context.request_confirmation = Mock()
args = {"param1": "test_value"}
result = await tool.run_async(args=args, tool_context=tool_context)
assert result == {
"error": (
"This tool call requires confirmation, please approve or reject."
)
}
tool_context.request_confirmation.assert_called_once()
@pytest.mark.asyncio
async def test_run_async_require_confirmation_true_rejected(self):
"""Test require_confirmation=True with rejection in context."""
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
require_confirmation=True,
)
tool_context = Mock(spec=ToolContext)
tool_context.tool_confirmation = Mock(confirmed=False)
args = {"param1": "test_value"}
result = await tool.run_async(args=args, tool_context=tool_context)
assert result == {"error": "This tool call is rejected."}
@pytest.mark.asyncio
async def test_run_async_require_confirmation_true_confirmed(self):
"""Test require_confirmation=True with confirmation in context."""
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
require_confirmation=True,
)
tool_context = Mock(spec=ToolContext)
tool_context.tool_confirmation = Mock(confirmed=True)
args = {"param1": "test_value"}
with patch(
"google.adk.tools.base_authenticated_tool.BaseAuthenticatedTool.run_async",
new_callable=AsyncMock,
) as mock_super_run_async:
await tool.run_async(args=args, tool_context=tool_context)
mock_super_run_async.assert_called_once_with(
args=args, tool_context=tool_context
)
@pytest.mark.asyncio
async def test_run_async_require_confirmation_callable_with_arg_filtering(
self,
):
"""Test require_confirmation=callable with argument filtering."""
async def _require_confirmation_func(
param1: str, tool_context: ToolContext
):
return True
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
require_confirmation=_require_confirmation_func,
)
tool_context = Mock(spec=ToolContext)
tool_context.tool_confirmation = None
tool_context.request_confirmation = Mock()
args = {"param1": "test_value", "extra_arg": 123}
with patch.object(
tool, "_invoke_callable", new_callable=AsyncMock
) as mock_invoke_callable:
mock_invoke_callable.return_value = (
True # Mock the return of require_confirmation
)
result = await tool.run_async(args=args, tool_context=tool_context)
expected_args_to_call = {
"param1": "test_value",
"tool_context": tool_context,
}
mock_invoke_callable.assert_called_once_with(
_require_confirmation_func, expected_args_to_call
)
assert result == {
"error": (
"This tool call requires confirmation, please approve or reject."
)
}
tool_context.request_confirmation.assert_called_once()
@pytest.mark.asyncio
async def test_run_async_require_confirmation_callable_true_no_confirmation(
self,
):
"""Test require_confirmation=callable with no confirmation in context."""
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
require_confirmation=lambda **kwargs: True,
)
tool_context = Mock(spec=ToolContext)
tool_context.tool_confirmation = None
tool_context.request_confirmation = Mock()
args = {"param1": "test_value"}
result = await tool.run_async(args=args, tool_context=tool_context)
assert result == {
"error": (
"This tool call requires confirmation, please approve or reject."
)
}
tool_context.request_confirmation.assert_called_once()
def test_init_validation(self):
"""Test that initialization validates required parameters."""
# This test ensures that the MCPTool properly handles its dependencies
with pytest.raises(TypeError):
MCPTool() # Missing required parameters
with pytest.raises(TypeError):
MCPTool(mcp_tool=self.mock_mcp_tool) # Missing session manager
@pytest.mark.asyncio
async def test_run_async_impl_with_header_provider_no_auth(self):
"""Test running tool with header_provider but no auth."""
expected_headers = {"X-Tenant-ID": "test-tenant"}
header_provider = Mock(return_value=expected_headers)
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
header_provider=header_provider,
)
# Mock the session response - must return CallToolResult
mcp_response = CallToolResult(
content=[TextContent(type="text", text="success")]
)
self.mock_session.call_tool = AsyncMock(return_value=mcp_response)
tool_context = Mock(spec=ToolContext)
tool_context._invocation_context = Mock()
args = {"param1": "test_value"}
result = await tool._run_async_impl(
args=args, tool_context=tool_context, credential=None
)
assert result == mcp_response.model_dump(exclude_none=True, mode="json")
header_provider.assert_called_once()
self.mock_session_manager.create_session.assert_called_once_with(
headers=expected_headers
)
self.mock_session.call_tool.assert_called_once_with(
"test_tool", arguments=args, progress_callback=None, meta=None
)
@pytest.mark.asyncio
async def test_run_async_impl_with_async_header_provider_no_auth(self):
"""Test running tool with an async header_provider but no auth."""
expected_headers = {"X-Tenant-ID": "test-tenant"}
async def header_provider(_context):
return expected_headers
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
header_provider=header_provider,
)
mcp_response = CallToolResult(
content=[TextContent(type="text", text="success")]
)
self.mock_session.call_tool = AsyncMock(return_value=mcp_response)
tool_context = Mock(spec=ToolContext)
tool_context._invocation_context = Mock()
args = {"param1": "test_value"}
result = await tool._run_async_impl(
args=args, tool_context=tool_context, credential=None
)
assert result == mcp_response.model_dump(exclude_none=True, mode="json")
self.mock_session_manager.create_session.assert_called_once_with(
headers=expected_headers
)
self.mock_session.call_tool.assert_called_once_with(
"test_tool", arguments=args, progress_callback=None, meta=None
)
@pytest.mark.asyncio
async def test_run_async_impl_with_header_provider_and_oauth2(self):
"""Test running tool with header_provider and OAuth2 auth."""
dynamic_headers = {"X-Tenant-ID": "test-tenant"}
header_provider = Mock(return_value=dynamic_headers)
tool = MCPTool(
mcp_tool=self.mock_mcp_tool,
mcp_session_manager=self.mock_session_manager,
header_provider=header_provider,
)
oauth2_auth = OAuth2Auth(access_token="test_access_token")
credential = AuthCredential(