-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathtest_mcp.py
More file actions
1271 lines (1069 loc) · 48 KB
/
Copy pathtest_mcp.py
File metadata and controls
1271 lines (1069 loc) · 48 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 (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import typing
import unittest
import json
import asyncio
from dataclasses import dataclass
from unittest.mock import patch
from typing import List, Optional
import azure.functions as func
from azure.functions import (DataType, MCPToolContext,
PromptInvocationContext, PromptArgument)
from azure.functions.decorators.core import BindingDirection
from azure.functions.decorators.mcp import (_MCPToolTrigger,
MCPResourceTrigger,
MCPPromptTrigger)
from azure.functions.mcp import (_MCPToolTriggerConverter,
MCPResourceTriggerConverter)
from azure.functions.meta import Datum
from mcp.types import (
ResourceLink,
TextContent,
ImageContent,
CallToolResult
)
class TestMCP(unittest.TestCase):
def test_mcp_tool_trigger_valid_creation(self):
trigger = _MCPToolTrigger(
name="context",
tool_name="hello",
description="Hello world.",
tool_properties="[]",
metadata='{"key": "value"}',
use_result_schema=True,
data_type=DataType.UNDEFINED,
dummy_field="dummy",
)
self.assertEqual(trigger.get_binding_name(), "mcpToolTrigger")
self.assertEqual(
trigger.get_dict_repr(),
{
"name": "context",
"toolName": "hello",
"description": "Hello world.",
"toolProperties": "[]",
"type": "mcpToolTrigger",
"dataType": DataType.UNDEFINED,
"dummyField": "dummy",
"metadata": '{"key": "value"}',
'useResultSchema': True,
"direction": BindingDirection.IN,
},
)
def test_trigger_converter(self):
# Test with string data
datum = Datum(value='{"arguments":{}}', type='string')
result = _MCPToolTriggerConverter.decode(datum, trigger_metadata={})
self.assertEqual(result, '{"arguments":{}}')
self.assertIsInstance(result, str)
# Test with json data
datum_json = Datum(value={"arguments": {}}, type='json')
result_json = _MCPToolTriggerConverter.decode(datum_json, trigger_metadata={})
self.assertEqual(result_json, {"arguments": {}})
self.assertIsInstance(result_json, dict)
class TestMcpToolDecorator(unittest.TestCase):
def setUp(self):
self.app = func.FunctionApp()
def tearDown(self):
self.app = None
def test_simple_signature(self):
@self.app.mcp_tool()
def add_numbers(a: int, b: int) -> int:
"""Add two numbers."""
return a + b
trigger = add_numbers._function._bindings[0]
self.assertEqual(trigger.description, "Add two numbers.")
self.assertEqual(trigger.name, "context")
self.assertEqual(trigger.tool_name, "add_numbers")
self.assertEqual(trigger.tool_properties,
'[{"propertyName": "a", '
'"propertyType": "integer", '
'"description": "", '
'"isArray": false, '
'"isRequired": true}, '
'{"propertyName": "b", '
'"propertyType": "integer", '
'"description": "", '
'"isArray": false, '
'"isRequired": true}]')
def test_long_pydocs(self):
@self.app.mcp_tool()
def add_numbers(a: int, b: int) -> int:
"""
Add two numbers.
Args:
a (int): The first number to add.
b (int): The second number to add.
Returns:
int: The sum of the two numbers.
"""
return a + b
trigger = add_numbers._function._bindings[0]
self.assertEqual(trigger.description, '''Add two numbers.
Args:
a (int): The first number to add.
b (int): The second number to add.
Returns:
int: The sum of the two numbers.''')
self.assertEqual(trigger.name, "context")
self.assertEqual(trigger.tool_name, "add_numbers")
self.assertEqual(trigger.tool_properties,
'[{"propertyName": "a", '
'"propertyType": "integer", '
'"description": "", '
'"isArray": false, '
'"isRequired": true}, '
'{"propertyName": "b", '
'"propertyType": "integer", '
'"description": "", '
'"isArray": false, '
'"isRequired": true}]')
def test_simple_signature_defaults(self):
@self.app.mcp_tool()
def add_numbers(a, b):
return a + b
trigger = add_numbers._function._bindings[0]
self.assertEqual(trigger.description, "")
self.assertEqual(trigger.name, "context")
self.assertEqual(trigger.tool_name, "add_numbers")
self.assertEqual(trigger.tool_properties,
'[{"propertyName": "a", '
'"propertyType": "string", '
'"description": "", '
'"isArray": false, '
'"isRequired": true}, '
'{"propertyName": "b", '
'"propertyType": "string", '
'"description": "", '
'"isArray": false, '
'"isRequired": true}]')
def test_simple_signature_defaults_metadata(self):
@self.app.mcp_tool(metadata='{"key": "value"}')
def add_numbers(a, b):
return a + b
trigger = add_numbers._function._bindings[0]
self.assertEqual(trigger.description, "")
self.assertEqual(trigger.name, "context")
self.assertEqual(trigger.tool_name, "add_numbers")
self.assertEqual(trigger.metadata, '{"key": "value"}')
self.assertEqual(trigger.tool_properties,
'[{"propertyName": "a", '
'"propertyType": "string", '
'"description": "", '
'"isArray": false, '
'"isRequired": true}, '
'{"propertyName": "b", '
'"propertyType": "string", '
'"description": "", '
'"isArray": false, '
'"isRequired": true}]')
def test_with_binding_argument(self):
@self.app.mcp_tool()
@self.app.blob_input(arg_name="file", path="", connection="Test")
def save_snippet(file, snippetname: str, snippet: str):
"""Save snippet."""
return f"Saved {snippetname}"
trigger = save_snippet._function._bindings[1]
self.assertEqual(trigger.description, "Save snippet.")
self.assertEqual(trigger.name, "context")
self.assertEqual(trigger.tool_name, "save_snippet")
self.assertEqual(trigger.tool_properties,
'[{"propertyName": "snippetname", '
'"propertyType": "string", '
'"description": "", '
'"isArray": false, '
'"isRequired": true}, '
'{"propertyName": "snippet", '
'"propertyType": "string", '
'"description": "", '
'"isArray": false, '
'"isRequired": true}]')
def test_with_context_argument(self):
@self.app.mcp_tool()
def process_data(data: str, context: MCPToolContext):
"""Process data with context."""
return f"Processed {data}"
trigger = process_data._function._bindings[0]
self.assertEqual(trigger.description, "Process data with context.")
self.assertEqual(trigger.name, "context")
self.assertEqual(trigger.tool_name, "process_data")
self.assertEqual(trigger.tool_properties,
'[{"propertyName": "data", '
'"propertyType": "string", '
'"description": "", '
'"isArray": false, '
'"isRequired": true}]')
def test_with_only_context(self):
@self.app.mcp_tool()
def process_data(context: MCPToolContext):
"""Process data with context."""
return f"Processed {context}"
trigger = process_data._function._bindings[0]
self.assertEqual(trigger.description, "Process data with context.")
self.assertEqual(trigger.name, "context")
self.assertEqual(trigger.tool_name, "process_data")
self.assertEqual(trigger.tool_properties,
'[]')
def test_is_required(self):
@self.app.mcp_tool()
def add_numbers(a: typing.Optional[int] = 0) -> int:
"""Add two numbers."""
return a
trigger = add_numbers._function._bindings[0]
self.assertEqual(trigger.description, "Add two numbers.")
self.assertEqual(trigger.name, "context")
self.assertEqual(trigger.tool_name, "add_numbers")
self.assertEqual(trigger.tool_properties,
'[{"propertyName": "a", '
'"propertyType": "integer", '
'"description": "", '
'"isArray": false, '
'"isRequired": false}]')
def test_is_required_default_value(self):
@self.app.mcp_tool()
def add_numbers(a: int = 0) -> int:
"""Add two numbers."""
return a
trigger = add_numbers._function._bindings[0]
self.assertEqual(trigger.description, "Add two numbers.")
self.assertEqual(trigger.name, "context")
self.assertEqual(trigger.tool_name, "add_numbers")
self.assertEqual(trigger.tool_properties,
'[{"propertyName": "a", '
'"propertyType": "integer", '
'"description": "", '
'"isArray": false, '
'"isRequired": false}]')
def test_as_array(self):
@self.app.mcp_tool()
def add_numbers(a: typing.List[int]) -> typing.List[int]:
"""Add two numbers."""
return a
trigger = add_numbers._function._bindings[0]
self.assertEqual(trigger.description, "Add two numbers.")
self.assertEqual(trigger.name, "context")
self.assertEqual(trigger.tool_name, "add_numbers")
self.assertEqual(trigger.tool_properties,
'[{"propertyName": "a", '
'"propertyType": "integer", '
'"description": "", '
'"isArray": true, '
'"isRequired": true}]')
def test_as_array_pep(self):
@self.app.mcp_tool()
def add_numbers(a: list[int]) -> list[int]:
"""Add two numbers."""
return a
trigger = add_numbers._function._bindings[0]
self.assertEqual(trigger.description, "Add two numbers.")
self.assertEqual(trigger.name, "context")
self.assertEqual(trigger.tool_name, "add_numbers")
self.assertEqual(trigger.tool_properties,
'[{"propertyName": "a", '
'"propertyType": "integer", '
'"description": "", '
'"isArray": true, '
'"isRequired": true}]')
def test_is_optional_array(self):
@self.app.mcp_tool()
def add_numbers(a: typing.Optional[typing.List[int]]):
"""Add two numbers."""
return a
trigger = add_numbers._function._bindings[0]
self.assertEqual(trigger.description, "Add two numbers.")
self.assertEqual(trigger.name, "context")
self.assertEqual(trigger.tool_name, "add_numbers")
self.assertEqual(trigger.tool_properties,
'[{"propertyName": "a", '
'"propertyType": "integer", '
'"description": "", '
'"isArray": true, '
'"isRequired": false}]')
def test_mcp_property_input_all_props(self):
@self.app.mcp_tool()
@self.app.mcp_tool_property(arg_name="a",
description="The first number",
property_type=func.McpPropertyType.INTEGER,
is_required=False,
as_array=True)
def add_numbers(a, b: int) -> int:
"""Add two numbers."""
return a + b
trigger = add_numbers._function._bindings[0]
self.assertEqual(trigger.description, "Add two numbers.")
self.assertEqual(trigger.name, "context")
self.assertEqual(trigger.tool_name, "add_numbers")
self.assertEqual(trigger.tool_properties,
'[{"propertyName": "a", '
'"propertyType": "integer", '
'"description": "The first number", '
'"isArray": true, '
'"isRequired": false}, '
'{"propertyName": "b", '
'"propertyType": "integer", '
'"description": "", '
'"isArray": false, '
'"isRequired": true}]')
def test_mcp_property_input_one_prop(self):
@self.app.mcp_tool()
@self.app.mcp_tool_property(arg_name="a", description="The first number")
def add_numbers(a: int, b: int) -> int:
"""Add two numbers."""
return a + b
trigger = add_numbers._function._bindings[0]
self.assertEqual(trigger.description, "Add two numbers.")
self.assertEqual(trigger.name, "context")
self.assertEqual(trigger.tool_name, "add_numbers")
self.assertEqual(trigger.tool_properties,
'[{"propertyName": "a", '
'"propertyType": "integer", '
'"description": "The first number", '
'"isArray": false, '
'"isRequired": true}, '
'{"propertyName": "b", '
'"propertyType": "integer", '
'"description": "", '
'"isArray": false, '
'"isRequired": true}]')
def test_mcp_property_input_enum_float(self):
@self.app.mcp_tool()
@self.app.mcp_tool_property(arg_name="a", property_type=func.McpPropertyType.FLOAT)
def add_numbers(a) -> int:
"""Add two numbers."""
return a
trigger = add_numbers._function._bindings[0]
self.assertEqual(trigger.description, "Add two numbers.")
self.assertEqual(trigger.name, "context")
self.assertEqual(trigger.tool_name, "add_numbers")
self.assertEqual(trigger.tool_properties,
'[{"propertyName": "a", '
'"propertyType": "float", '
'"description": "", '
'"isArray": false, '
'"isRequired": true}]')
def test_mcp_property_input_enum_string(self):
@self.app.mcp_tool()
@self.app.mcp_tool_property(arg_name="a", property_type=func.McpPropertyType.STRING)
def add_numbers(a) -> int:
"""Add two numbers."""
return a
trigger = add_numbers._function._bindings[0]
self.assertEqual(trigger.description, "Add two numbers.")
self.assertEqual(trigger.name, "context")
self.assertEqual(trigger.tool_name, "add_numbers")
self.assertEqual(trigger.tool_properties,
'[{"propertyName": "a", '
'"propertyType": "string", '
'"description": "", '
'"isArray": false, '
'"isRequired": true}]')
def test_mcp_property_input_enum_bool(self):
@self.app.mcp_tool()
@self.app.mcp_tool_property(arg_name="a", property_type=func.McpPropertyType.BOOLEAN)
def add_numbers(a) -> int:
"""Add two numbers."""
return a
trigger = add_numbers._function._bindings[0]
self.assertEqual(trigger.description, "Add two numbers.")
self.assertEqual(trigger.name, "context")
self.assertEqual(trigger.tool_name, "add_numbers")
self.assertEqual(trigger.tool_properties,
'[{"propertyName": "a", '
'"propertyType": "boolean", '
'"description": "", '
'"isArray": false, '
'"isRequired": true}]')
def test_mcp_property_input_enum_object(self):
@self.app.mcp_tool()
@self.app.mcp_tool_property(arg_name="a", property_type=func.McpPropertyType.OBJECT)
def add_numbers(a) -> int:
"""Add two numbers."""
return a
trigger = add_numbers._function._bindings[0]
self.assertEqual(trigger.description, "Add two numbers.")
self.assertEqual(trigger.name, "context")
self.assertEqual(trigger.tool_name, "add_numbers")
self.assertEqual(trigger.tool_properties,
'[{"propertyName": "a", '
'"propertyType": "object", '
'"description": "", '
'"isArray": false, '
'"isRequired": true}]')
def test_mcp_property_input_enum_datetime(self):
@self.app.mcp_tool()
@self.app.mcp_tool_property(arg_name="a", property_type=func.McpPropertyType.DATETIME)
def add_numbers(a) -> int:
"""Add two numbers."""
return a
trigger = add_numbers._function._bindings[0]
self.assertEqual(trigger.description, "Add two numbers.")
self.assertEqual(trigger.name, "context")
self.assertEqual(trigger.tool_name, "add_numbers")
self.assertEqual(trigger.tool_properties,
'[{"propertyName": "a", '
'"propertyType": "string", '
'"description": "", '
'"isArray": false, '
'"isRequired": true}]')
class TestMCPResourceTrigger(unittest.TestCase):
def test_mcp_resource_trigger_valid_creation(self):
trigger = MCPResourceTrigger(
name="context",
uri="file://readme.md",
resource_name="myresource",
title="my title",
description="my resource description",
mime_type="Text/Markdown",
size=1024,
metadata="",
data_type=DataType.UNDEFINED,
dummy_field="dummy",
)
self.assertEqual(trigger.get_binding_name(), "mcpResourceTrigger")
self.assertEqual(
trigger.get_dict_repr(),
{
"name": "context",
"uri": "file://readme.md",
"resourceName": "myresource",
"title": "my title",
"description": "my resource description",
"mimeType": "Text/Markdown",
"size": 1024,
"metadata": "",
"type": "mcpResourceTrigger",
"dataType": DataType.UNDEFINED,
"dummyField": "dummy",
"direction": BindingDirection.IN,
},
)
def test_mcp_resource_trigger_only_required_args_creation(self):
trigger = MCPResourceTrigger(
name="context",
uri="file://readme.md",
resource_name="myresource"
)
self.assertEqual(trigger.get_binding_name(), "mcpResourceTrigger")
self.assertEqual(
trigger.get_dict_repr(),
{
"name": "context",
"uri": "file://readme.md",
"resourceName": "myresource",
"type": "mcpResourceTrigger",
"direction": BindingDirection.IN,
},
)
def test_trigger_converter(self):
# Test with string data
datum = Datum(value='{"arguments":{}}', type='string')
result = MCPResourceTriggerConverter.decode(datum, trigger_metadata={})
self.assertEqual(result, '{"arguments":{}}')
self.assertIsInstance(result, str)
# Test with json data
datum_json = Datum(value={"arguments": {}}, type='json')
result_json = MCPResourceTriggerConverter.decode(datum_json, trigger_metadata={})
self.assertEqual(result_json, {"arguments": {}})
self.assertIsInstance(result_json, dict)
class TestStructuredContent(unittest.TestCase):
"""Tests for structured content functionality"""
def setUp(self):
self.app = func.FunctionApp()
def tearDown(self):
self.app = None
def test_mcp_content_decorator(self):
"""Test that @mcp_content decorator marks a class properly"""
from azure.functions.decorators.mcp import has_mcp_content_marker
@func.mcp_content
class TestData:
def __init__(self, value: str):
self.value = value
instance = TestData("test")
self.assertTrue(has_mcp_content_marker(instance))
self.assertTrue(hasattr(TestData, '__mcp_content__'))
self.assertEqual(TestData.__mcp_content__, True)
def test_should_create_structured_content_for_marked_class(self):
"""Test that marked classes generate structured content"""
from azure.functions.decorators.mcp import should_create_structured_content
@func.mcp_content
class MarkedData:
def __init__(self, name: str):
self.name = name
instance = MarkedData("test")
self.assertTrue(should_create_structured_content(instance))
def test_should_not_create_structured_content_for_primitives(self):
"""Test that primitive types don't generate structured content"""
from azure.functions.decorators.mcp import should_create_structured_content
self.assertFalse(should_create_structured_content("string"))
self.assertFalse(should_create_structured_content(42))
self.assertFalse(should_create_structured_content(3.14))
self.assertFalse(should_create_structured_content(True))
self.assertFalse(should_create_structured_content(None))
def test_should_not_create_structured_content_for_unmarked_class(self):
"""Test that unmarked classes don't generate structured content"""
from azure.functions.decorators.mcp import should_create_structured_content
class UnmarkedData:
def __init__(self, value: str):
self.value = value
instance = UnmarkedData("test")
self.assertFalse(should_create_structured_content(instance))
def test_mcp_tool_with_use_result_schema_parameter(self):
"""Test that use_result_schema parameter is passed to trigger"""
@self.app.mcp_tool(use_result_schema=True)
def test_tool(value: str):
"""Test tool with result schema"""
return value
trigger = test_tool._function._bindings[0]
self.assertEqual(trigger.use_result_schema, True)
self.assertEqual(trigger.tool_name, "test_tool")
def test_mcp_content_with_dataclass(self):
"""Test mcp_content decorator works with dataclasses"""
from dataclasses import dataclass
from azure.functions.decorators.mcp import should_create_structured_content
@func.mcp_content
@dataclass
class DataModel:
name: str
count: int
instance = DataModel(name="test", count=5)
self.assertTrue(should_create_structured_content(instance))
self.assertTrue(hasattr(DataModel, '__mcp_content__'))
class TestAutoUseResultSchema(unittest.TestCase):
"""Tests for automatic use_result_schema detection"""
def setUp(self):
self.app = func.FunctionApp()
def tearDown(self):
self.app = None
def test_auto_detect_mcp_resource_link(self):
"""Test auto-detection of MCP SDK ResourceLink return type"""
@self.app.mcp_tool()
def get_logo() -> ResourceLink:
"""Returns a logo"""
return ResourceLink(
type="resource_link",
uri="file://logo.png",
name="Logo"
)
trigger = get_logo._function._bindings[0]
self.assertTrue(trigger.use_result_schema)
def test_auto_detect_mcp_text_content(self):
"""Test auto-detection of MCP SDK TextContent return type"""
@self.app.mcp_tool()
def get_text() -> TextContent:
"""Returns text"""
return TextContent(type="text", text="Hello")
trigger = get_text._function._bindings[0]
self.assertTrue(trigger.use_result_schema)
def test_auto_detect_mcp_image_content(self):
"""Test auto-detection of MCP SDK ImageContent return type"""
@self.app.mcp_tool()
def get_image() -> ImageContent:
"""Returns image"""
return ImageContent(
type="image",
data="base64data",
mimeType="image/png"
)
trigger = get_image._function._bindings[0]
self.assertTrue(trigger.use_result_schema)
def test_auto_detect_mcp_call_tool_result(self):
"""Test auto-detection of MCP SDK CallToolResult return type"""
@self.app.mcp_tool()
def get_result() -> CallToolResult:
"""Returns CallToolResult"""
return CallToolResult(
content=[TextContent(type="text", text="result")]
)
trigger = get_result._function._bindings[0]
self.assertTrue(trigger.use_result_schema)
def test_auto_detect_list_mcp_text_content(self):
"""Test auto-detection of List[TextContent] return type"""
@self.app.mcp_tool()
def get_texts() -> List[TextContent]:
"""Returns text blocks"""
return [TextContent(type="text", text="test")]
trigger = get_texts._function._bindings[0]
self.assertTrue(trigger.use_result_schema)
def test_auto_detect_list_union_mcp_types(self):
"""Test auto-detection of List[Union[MCP types]] return type"""
from typing import Union
@self.app.mcp_tool()
def get_mixed_content() -> List[Union[TextContent, ImageContent]]:
"""Returns mixed content blocks"""
return [TextContent(type="text", text="test")]
trigger = get_mixed_content._function._bindings[0]
self.assertTrue(trigger.use_result_schema)
def test_auto_detect_optional_mcp_image_content(self):
"""Test auto-detection of Optional[ImageContent] return type"""
@self.app.mcp_tool()
def maybe_image() -> Optional[ImageContent]:
"""Maybe returns image"""
return None
trigger = maybe_image._function._bindings[0]
self.assertTrue(trigger.use_result_schema)
def test_auto_detect_mcp_content_class(self):
"""Test auto-detection of @mcp_content decorated class"""
@func.mcp_content
class MyData:
def __init__(self, value: str):
self.value = value
@self.app.mcp_tool()
def get_data() -> MyData:
"""Returns custom data"""
return MyData("test")
trigger = get_data._function._bindings[0]
self.assertTrue(trigger.use_result_schema)
def test_no_auto_detect_string(self):
"""Test that plain string return type doesn't trigger auto-detection"""
@self.app.mcp_tool()
def get_string() -> str:
"""Returns string"""
return "Hello"
trigger = get_string._function._bindings[0]
self.assertFalse(trigger.use_result_schema)
def test_no_auto_detect_int(self):
"""Test that int return type doesn't trigger auto-detection"""
@self.app.mcp_tool()
def get_number() -> int:
"""Returns number"""
return 42
trigger = get_number._function._bindings[0]
self.assertFalse(trigger.use_result_schema)
def test_no_auto_detect_dict(self):
"""Test that dict return type doesn't trigger auto-detection"""
@self.app.mcp_tool()
def get_dict() -> dict:
"""Returns dict"""
return {"key": "value"}
trigger = get_dict._function._bindings[0]
self.assertFalse(trigger.use_result_schema)
def test_no_auto_detect_no_annotation(self):
"""Test that no return annotation doesn't trigger auto-detection"""
@self.app.mcp_tool()
def no_annotation():
"""No annotation"""
return "test"
trigger = no_annotation._function._bindings[0]
self.assertFalse(trigger.use_result_schema)
def test_explicit_use_result_schema_true(self):
"""Test that explicit use_result_schema=True is preserved"""
@self.app.mcp_tool(use_result_schema=True)
def explicit_true() -> str:
"""Explicit True"""
return "test"
trigger = explicit_true._function._bindings[0]
self.assertTrue(trigger.use_result_schema)
def test_explicit_use_result_schema_false(self):
"""Test that explicit use_result_schema=False works"""
@self.app.mcp_tool(use_result_schema=False)
def explicit_false() -> str:
"""Explicit False"""
return "test"
trigger = explicit_false._function._bindings[0]
self.assertFalse(trigger.use_result_schema)
class TestStructuredContentInResponses(unittest.TestCase):
"""Tests for structuredContent field in MCP responses with official MCP SDK types"""
def setUp(self):
self.app = func.FunctionApp()
def tearDown(self):
self.app = None
def test_structured_content_in_call_tool_result(self):
"""Test that MCP SDK CallToolResult includes structuredContent"""
@self.app.mcp_tool()
def test_func() -> CallToolResult:
"""Test function"""
return CallToolResult(
content=[TextContent(type="text", text="test")],
structuredContent={"key": "value"}
)
# Get the wrapper function
wrapper = test_func._function._func
# Call the wrapper
context = json.dumps({"arguments": {}})
result = asyncio.run(wrapper(context))
# Parse the result
result_obj = json.loads(result)
# Verify structure
self.assertIn("type", result_obj)
self.assertIn("content", result_obj)
self.assertIn("structuredContent", result_obj)
self.assertEqual(result_obj["type"], "call_tool_result")
self.assertIsNotNone(result_obj["structuredContent"])
# Verify structuredContent value
structured_obj = json.loads(result_obj["structuredContent"])
self.assertEqual(structured_obj, {"key": "value"})
def test_structured_content_in_resource_link(self):
"""Test that MCP SDK ResourceLink includes structuredContent"""
@self.app.mcp_tool()
def test_func() -> ResourceLink:
"""Test function"""
return ResourceLink(
type="resource_link",
uri="file://test.png",
name="Test",
mimeType="image/png"
)
wrapper = test_func._function._func
context = json.dumps({"arguments": {}})
result = asyncio.run(wrapper(context))
result_obj = json.loads(result)
self.assertIn("type", result_obj)
self.assertIn("content", result_obj)
self.assertIn("structuredContent", result_obj)
self.assertEqual(result_obj["type"], "resource_link")
self.assertIsNotNone(result_obj["structuredContent"])
# Verify structuredContent matches content
content_obj = json.loads(result_obj["content"])
structured_obj = json.loads(result_obj["structuredContent"])
self.assertEqual(content_obj, structured_obj)
def test_structured_content_in_text_content(self):
"""Test that MCP SDK TextContent includes structuredContent"""
@self.app.mcp_tool()
def test_func() -> TextContent:
"""Test function"""
return TextContent(type="text", text="Hello World")
wrapper = test_func._function._func
context = json.dumps({"arguments": {}})
result = asyncio.run(wrapper(context))
result_obj = json.loads(result)
self.assertIn("type", result_obj)
self.assertEqual(result_obj["type"], "text")
self.assertIn("content", result_obj)
self.assertIn("structuredContent", result_obj)
self.assertIsNotNone(result_obj["structuredContent"])
def test_structured_content_with_mcp_content_decorator(self):
"""Test that @mcp_content decorated class includes structuredContent"""
@func.mcp_content
@dataclass
class MyData:
name: str
value: int
@self.app.mcp_tool()
def test_func() -> MyData:
"""Test function"""
return MyData(name="test", value=42)
wrapper = test_func._function._func
context = json.dumps({"arguments": {}})
result = asyncio.run(wrapper(context))
result_obj = json.loads(result)
self.assertIn("type", result_obj)
self.assertIn("content", result_obj)
self.assertIn("structuredContent", result_obj)
self.assertIsNotNone(result_obj["structuredContent"])
# Verify structured content contains the data
structured_obj = json.loads(result_obj["structuredContent"])
self.assertEqual(structured_obj["name"], "test")
self.assertEqual(structured_obj["value"], 42)
def test_backwards_compatibility_string_without_use_result_schema(self):
"""Test that plain string returns work without use_result_schema"""
@self.app.mcp_tool()
def test_func() -> str:
"""Test function"""
return "Hello!"
wrapper = test_func._function._func
context = json.dumps({"arguments": {}})
result = asyncio.run(wrapper(context))
# Should return the raw string, not a JSON structure
self.assertEqual(result, "Hello!")
self.assertIsInstance(result, str)
def test_explicit_use_result_schema_with_string(self):
"""Test that explicit use_result_schema=True structures string response"""
@self.app.mcp_tool(use_result_schema=True)
def test_func() -> str:
"""Test function"""
return "Hello!"
wrapper = test_func._function._func
context = json.dumps({"arguments": {}})
result = asyncio.run(wrapper(context))
# Should return structured JSON
result_obj = json.loads(result)
self.assertIn("type", result_obj)
self.assertIn("content", result_obj)
self.assertIn("structuredContent", result_obj)
def test_structured_content_in_list_of_mcp_types(self):
"""Test that List[MCP SDK types] includes structuredContent"""
@self.app.mcp_tool()
def test_func() -> List[TextContent]:
"""Test function"""
return [
TextContent(type="text", text="First item"),
TextContent(type="text", text="Second item")
]
wrapper = test_func._function._func
context = json.dumps({"arguments": {}})
result = asyncio.run(wrapper(context))
result_obj = json.loads(result)
# List of content blocks is wrapped as CallToolResult
self.assertIn("type", result_obj)
self.assertEqual(result_obj["type"], "call_tool_result")
self.assertIn("content", result_obj)
self.assertIn("structuredContent", result_obj)
# Content contains the CallToolResult structure with the blocks
content_obj = json.loads(result_obj["content"])
self.assertIn("content", content_obj)
self.assertEqual(len(content_obj["content"]), 2)
self.assertEqual(content_obj["content"][0]["text"], "First item")
self.assertEqual(content_obj["content"][1]["text"], "Second item")
class TestMCPPackageNotInstalled(unittest.TestCase):
"""Tests for graceful degradation when mcp package is not installed"""
def setUp(self):
self.app = func.FunctionApp()
def tearDown(self):
self.app = None
def test_no_auto_detect_when_mcp_not_installed(self):
"""Test that auto-detection doesn't happen when mcp package is not available"""
# Mock sys.modules to simulate mcp not being installed
import sys
with patch.dict(sys.modules, {'mcp': None, 'mcp.types': None}):
# Clear any cached imports
import importlib
if 'azure.functions.decorators.function_app' in sys.modules:
importlib.reload(sys.modules['azure.functions.decorators.function_app'])
# Create a new app after mocking
test_app = func.FunctionApp()
@test_app.mcp_tool()
def get_data() -> str:
"""Returns data"""
return "test"
trigger = get_data._function._bindings[0]
# Should not auto-detect when mcp is not available
self.assertFalse(trigger.use_result_schema)
def test_mcp_content_decorator_still_works_without_mcp(self):
"""Test that @mcp_content decorator works even when mcp package is not installed"""
@func.mcp_content
class MyData:
def __init__(self, value: str):
self.value = value
# Decorator should still mark the class
self.assertTrue(hasattr(MyData, '__mcp_content__'))
self.assertEqual(MyData.__mcp_content__, True)
def test_explicit_use_result_schema_works_without_mcp(self):
"""Test that explicit use_result_schema=True works without mcp package"""
@self.app.mcp_tool(use_result_schema=True)
def test_func() -> str:
"""Test function"""
return "Hello!"
trigger = test_func._function._bindings[0]