-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathtest_server.py
More file actions
1661 lines (1330 loc) · 62.3 KB
/
test_server.py
File metadata and controls
1661 lines (1330 loc) · 62.3 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 base64
from pathlib import Path
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from inline_snapshot import snapshot
from pydantic import BaseModel
from starlette.applications import Starlette
from starlette.routing import Mount, Route
from mcp.client import Client
from mcp.server.context import ServerRequestContext
from mcp.server.experimental.request_context import Experimental
from mcp.server.mcpserver import Context, MCPServer
from mcp.server.mcpserver.exceptions import PromptError, ResourceError, ToolError
from mcp.server.mcpserver.prompts.base import Message, UserMessage
from mcp.server.mcpserver.resources import FileResource, FunctionResource
from mcp.server.mcpserver.utilities.types import Audio, Image
from mcp.server.transport_security import TransportSecuritySettings
from mcp.shared.exceptions import MCPError
from mcp.types import (
AudioContent,
BlobResourceContents,
Completion,
CompletionArgument,
CompletionContext,
ContentBlock,
EmbeddedResource,
GetPromptResult,
Icon,
ImageContent,
ListPromptsResult,
Prompt,
PromptArgument,
PromptMessage,
PromptReference,
ReadResourceResult,
Resource,
ResourceTemplate,
TextContent,
TextResourceContents,
)
pytestmark = pytest.mark.anyio
class TestServer:
async def test_create_server(self):
mcp = MCPServer(
title="MCPServer Server",
description="Server description",
instructions="Server instructions",
website_url="https://example.com/mcp_server",
version="1.0",
icons=[Icon(src="https://example.com/icon.png", mime_type="image/png", sizes=["48x48", "96x96"])],
)
assert mcp.name == "mcp-server"
assert mcp.title == "MCPServer Server"
assert mcp.description == "Server description"
assert mcp.instructions == "Server instructions"
assert mcp.website_url == "https://example.com/mcp_server"
assert mcp.version == "1.0"
assert isinstance(mcp.icons, list)
assert len(mcp.icons) == 1
assert mcp.icons[0].src == "https://example.com/icon.png"
def test_dependencies(self):
"""Dependencies list is read by `mcp install` / `mcp dev` CLI commands."""
mcp = MCPServer("test", dependencies=["pandas", "numpy"])
assert mcp.dependencies == ["pandas", "numpy"]
assert mcp.settings.dependencies == ["pandas", "numpy"]
mcp_no_deps = MCPServer("test")
assert mcp_no_deps.dependencies == []
async def test_sse_app_returns_starlette_app(self):
"""Test that sse_app returns a Starlette application with correct routes."""
mcp = MCPServer("test")
# Use host="0.0.0.0" to avoid auto DNS protection
app = mcp.sse_app(host="0.0.0.0")
assert isinstance(app, Starlette)
# Verify routes exist
sse_routes = [r for r in app.routes if isinstance(r, Route)]
mount_routes = [r for r in app.routes if isinstance(r, Mount)]
assert len(sse_routes) == 1, "Should have one SSE route"
assert len(mount_routes) == 1, "Should have one mount route"
assert sse_routes[0].path == "/sse"
assert mount_routes[0].path == "/messages"
async def test_non_ascii_description(self):
"""Test that MCPServer handles non-ASCII characters in descriptions correctly"""
mcp = MCPServer()
@mcp.tool(description=("🌟 This tool uses emojis and UTF-8 characters: á é í ó ú ñ 漢字 🎉"))
def hello_world(name: str = "世界") -> str:
return f"¡Hola, {name}! 👋"
async with Client(mcp) as client:
tools = await client.list_tools()
assert len(tools.tools) == 1
tool = tools.tools[0]
assert tool.description is not None
assert "🌟" in tool.description
assert "漢字" in tool.description
assert "🎉" in tool.description
result = await client.call_tool("hello_world", {})
assert len(result.content) == 1
content = result.content[0]
assert isinstance(content, TextContent)
assert "¡Hola, 世界! 👋" == content.text
async def test_add_tool_decorator(self):
mcp = MCPServer()
@mcp.tool()
def sum(x: int, y: int) -> int: # pragma: no cover
return x + y
assert len(mcp._tool_manager.list_tools()) == 1
async def test_add_tool_decorator_incorrect_usage(self):
mcp = MCPServer()
with pytest.raises(TypeError, match="The @tool decorator was used incorrectly"):
@mcp.tool # Missing parentheses #type: ignore
def sum(x: int, y: int) -> int: # pragma: no cover
return x + y
async def test_add_resource_decorator(self):
mcp = MCPServer()
@mcp.resource("r://{x}")
def get_data(x: str) -> str: # pragma: no cover
return f"Data: {x}"
assert len(mcp._resource_manager._templates) == 1
async def test_add_resource_decorator_incorrect_usage(self):
mcp = MCPServer()
with pytest.raises(TypeError, match="The @resource decorator was used incorrectly"):
@mcp.resource # Missing parentheses #type: ignore
def get_data(x: str) -> str: # pragma: no cover
return f"Data: {x}"
class TestDnsRebindingProtection:
"""Tests for automatic DNS rebinding protection on localhost.
DNS rebinding protection is now configured in sse_app() and streamable_http_app()
based on the host parameter passed to those methods.
"""
def test_auto_enabled_for_127_0_0_1_sse(self):
"""DNS rebinding protection should auto-enable for host=127.0.0.1 in SSE app."""
mcp = MCPServer()
# Call sse_app with host=127.0.0.1 to trigger auto-config
# We can't directly inspect the transport_security, but we can verify
# the app is created without error
app = mcp.sse_app(host="127.0.0.1")
assert app is not None
def test_auto_enabled_for_127_0_0_1_streamable_http(self):
"""DNS rebinding protection should auto-enable for host=127.0.0.1 in StreamableHTTP app."""
mcp = MCPServer()
app = mcp.streamable_http_app(host="127.0.0.1")
assert app is not None
def test_auto_enabled_for_localhost_sse(self):
"""DNS rebinding protection should auto-enable for host=localhost in SSE app."""
mcp = MCPServer()
app = mcp.sse_app(host="localhost")
assert app is not None
def test_auto_enabled_for_ipv6_localhost_sse(self):
"""DNS rebinding protection should auto-enable for host=::1 (IPv6 localhost) in SSE app."""
mcp = MCPServer()
app = mcp.sse_app(host="::1")
assert app is not None
def test_not_auto_enabled_for_other_hosts_sse(self):
"""DNS rebinding protection should NOT auto-enable for other hosts in SSE app."""
mcp = MCPServer()
app = mcp.sse_app(host="0.0.0.0")
assert app is not None
def test_explicit_settings_not_overridden_sse(self):
"""Explicit transport_security settings should not be overridden in SSE app."""
custom_settings = TransportSecuritySettings(
enable_dns_rebinding_protection=False,
)
mcp = MCPServer()
# Explicit transport_security passed to sse_app should be used as-is
app = mcp.sse_app(host="127.0.0.1", transport_security=custom_settings)
assert app is not None
def test_explicit_settings_not_overridden_streamable_http(self):
"""Explicit transport_security settings should not be overridden in StreamableHTTP app."""
custom_settings = TransportSecuritySettings(
enable_dns_rebinding_protection=False,
)
mcp = MCPServer()
# Explicit transport_security passed to streamable_http_app should be used as-is
app = mcp.streamable_http_app(host="127.0.0.1", transport_security=custom_settings)
assert app is not None
def tool_fn(x: int, y: int) -> int:
return x + y
def error_tool_fn() -> None:
raise ValueError("Test error")
def image_tool_fn(path: str) -> Image:
return Image(path)
def audio_tool_fn(path: str) -> Audio:
return Audio(path)
def mixed_content_tool_fn() -> list[ContentBlock]:
return [
TextContent(type="text", text="Hello"),
ImageContent(type="image", data="abc", mime_type="image/png"),
AudioContent(type="audio", data="def", mime_type="audio/wav"),
]
class TestServerTools:
async def test_add_tool(self):
mcp = MCPServer()
mcp.add_tool(tool_fn)
mcp.add_tool(tool_fn)
assert len(mcp._tool_manager.list_tools()) == 1
async def test_list_tools(self):
mcp = MCPServer()
mcp.add_tool(tool_fn)
async with Client(mcp) as client:
tools = await client.list_tools()
assert len(tools.tools) == 1
async def test_call_tool(self):
mcp = MCPServer()
mcp.add_tool(tool_fn)
async with Client(mcp) as client:
result = await client.call_tool("my_tool", {"arg1": "value"})
assert not hasattr(result, "error")
assert len(result.content) > 0
async def test_tool_exception_handling(self):
mcp = MCPServer()
mcp.add_tool(error_tool_fn)
async with Client(mcp) as client:
result = await client.call_tool("error_tool_fn", {})
assert len(result.content) == 1
content = result.content[0]
assert isinstance(content, TextContent)
assert "Test error" in content.text
assert result.is_error is True
async def test_tool_error_handling(self):
mcp = MCPServer()
mcp.add_tool(error_tool_fn)
async with Client(mcp) as client:
result = await client.call_tool("error_tool_fn", {})
assert len(result.content) == 1
content = result.content[0]
assert isinstance(content, TextContent)
assert "Test error" in content.text
assert result.is_error is True
async def test_tool_error_details(self):
"""Test that exception details are properly formatted in the response"""
mcp = MCPServer()
mcp.add_tool(error_tool_fn)
async with Client(mcp) as client:
result = await client.call_tool("error_tool_fn", {})
content = result.content[0]
assert isinstance(content, TextContent)
assert isinstance(content.text, str)
assert "Test error" in content.text
assert result.is_error is True
async def test_tool_return_value_conversion(self):
mcp = MCPServer()
mcp.add_tool(tool_fn)
async with Client(mcp) as client:
result = await client.call_tool("tool_fn", {"x": 1, "y": 2})
assert len(result.content) == 1
content = result.content[0]
assert isinstance(content, TextContent)
assert content.text == "3"
# Check structured content - int return type should have structured output
assert result.structured_content is not None
assert result.structured_content == {"result": 3}
async def test_tool_image_helper(self, tmp_path: Path):
# Create a test image
image_path = tmp_path / "test.png"
image_path.write_bytes(b"fake png data")
mcp = MCPServer()
mcp.add_tool(image_tool_fn)
async with Client(mcp) as client:
result = await client.call_tool("image_tool_fn", {"path": str(image_path)})
assert len(result.content) == 1
content = result.content[0]
assert isinstance(content, ImageContent)
assert content.type == "image"
assert content.mime_type == "image/png"
# Verify base64 encoding
decoded = base64.b64decode(content.data)
assert decoded == b"fake png data"
# Check structured content - Image return type should NOT have structured output
assert result.structured_content is None
async def test_tool_audio_helper(self, tmp_path: Path):
# Create a test audio
audio_path = tmp_path / "test.wav"
audio_path.write_bytes(b"fake wav data")
mcp = MCPServer()
mcp.add_tool(audio_tool_fn)
async with Client(mcp) as client:
result = await client.call_tool("audio_tool_fn", {"path": str(audio_path)})
assert len(result.content) == 1
content = result.content[0]
assert isinstance(content, AudioContent)
assert content.type == "audio"
assert content.mime_type == "audio/wav"
# Verify base64 encoding
decoded = base64.b64decode(content.data)
assert decoded == b"fake wav data"
# Check structured content - Image return type should NOT have structured output
assert result.structured_content is None
@pytest.mark.parametrize(
"filename,expected_mime_type",
[
("test.wav", "audio/wav"),
("test.mp3", "audio/mpeg"),
("test.ogg", "audio/ogg"),
("test.flac", "audio/flac"),
("test.aac", "audio/aac"),
("test.m4a", "audio/mp4"),
("test.unknown", "application/octet-stream"), # Unknown extension fallback
],
)
async def test_tool_audio_suffix_detection(self, tmp_path: Path, filename: str, expected_mime_type: str):
"""Test that Audio helper correctly detects MIME types from file suffixes"""
mcp = MCPServer()
mcp.add_tool(audio_tool_fn)
# Create a test audio file with the specific extension
audio_path = tmp_path / filename
audio_path.write_bytes(b"fake audio data")
async with Client(mcp) as client:
result = await client.call_tool("audio_tool_fn", {"path": str(audio_path)})
assert len(result.content) == 1
content = result.content[0]
assert isinstance(content, AudioContent)
assert content.type == "audio"
assert content.mime_type == expected_mime_type
# Verify base64 encoding
decoded = base64.b64decode(content.data)
assert decoded == b"fake audio data"
async def test_tool_mixed_content(self):
mcp = MCPServer()
mcp.add_tool(mixed_content_tool_fn)
async with Client(mcp) as client:
result = await client.call_tool("mixed_content_tool_fn", {})
assert len(result.content) == 3
content1, content2, content3 = result.content
assert isinstance(content1, TextContent)
assert content1.text == "Hello"
assert isinstance(content2, ImageContent)
assert content2.mime_type == "image/png"
assert content2.data == "abc"
assert isinstance(content3, AudioContent)
assert content3.mime_type == "audio/wav"
assert content3.data == "def"
assert result.structured_content is not None
assert "result" in result.structured_content
structured_result = result.structured_content["result"]
assert len(structured_result) == 3
expected_content = [
{"type": "text", "text": "Hello"},
{"type": "image", "data": "abc", "mimeType": "image/png"},
{"type": "audio", "data": "def", "mimeType": "audio/wav"},
]
for i, expected in enumerate(expected_content):
for key, value in expected.items():
assert structured_result[i][key] == value
async def test_tool_mixed_list_with_audio_and_image(self, tmp_path: Path):
"""Test that lists containing Image objects and other types are handled
correctly"""
# Create a test image
image_path = tmp_path / "test.png"
image_path.write_bytes(b"test image data")
# Create a test audio
audio_path = tmp_path / "test.wav"
audio_path.write_bytes(b"test audio data")
# TODO(Marcelo): It seems if we add the proper type hint, it generates an invalid JSON schema.
# We need to fix this.
def mixed_list_fn() -> list: # type: ignore
return [ # type: ignore
"text message",
Image(image_path),
Audio(audio_path),
{"key": "value"},
TextContent(type="text", text="direct content"),
]
mcp = MCPServer()
mcp.add_tool(mixed_list_fn) # type: ignore
async with Client(mcp) as client:
result = await client.call_tool("mixed_list_fn", {})
assert len(result.content) == 5
# Check text conversion
content1 = result.content[0]
assert isinstance(content1, TextContent)
assert content1.text == "text message"
# Check image conversion
content2 = result.content[1]
assert isinstance(content2, ImageContent)
assert content2.mime_type == "image/png"
assert base64.b64decode(content2.data) == b"test image data"
# Check audio conversion
content3 = result.content[2]
assert isinstance(content3, AudioContent)
assert content3.mime_type == "audio/wav"
assert base64.b64decode(content3.data) == b"test audio data"
# Check dict conversion
content4 = result.content[3]
assert isinstance(content4, TextContent)
assert '"key": "value"' in content4.text
# Check direct TextContent
content5 = result.content[4]
assert isinstance(content5, TextContent)
assert content5.text == "direct content"
# Check structured content - untyped list with Image objects should NOT have structured output
assert result.structured_content is None
async def test_tool_structured_output_basemodel(self):
"""Test tool with structured output returning BaseModel"""
class UserOutput(BaseModel):
name: str
age: int
active: bool = True
def get_user(user_id: int) -> UserOutput:
"""Get user by ID"""
return UserOutput(name="John Doe", age=30)
mcp = MCPServer()
mcp.add_tool(get_user)
async with Client(mcp) as client:
# Check that the tool has outputSchema
tools = await client.list_tools()
tool = next(t for t in tools.tools if t.name == "get_user")
assert tool.output_schema is not None
assert tool.output_schema["type"] == "object"
assert "name" in tool.output_schema["properties"]
assert "age" in tool.output_schema["properties"]
# Call the tool and check structured output
result = await client.call_tool("get_user", {"user_id": 123})
assert result.is_error is False
assert result.structured_content is not None
assert result.structured_content == {"name": "John Doe", "age": 30, "active": True}
# Content should be JSON serialized version
assert len(result.content) == 1
assert isinstance(result.content[0], TextContent)
assert '"name": "John Doe"' in result.content[0].text
async def test_tool_structured_output_primitive(self):
"""Test tool with structured output returning primitive type"""
def calculate_sum(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
mcp = MCPServer()
mcp.add_tool(calculate_sum)
async with Client(mcp) as client:
# Check that the tool has outputSchema
tools = await client.list_tools()
tool = next(t for t in tools.tools if t.name == "calculate_sum")
assert tool.output_schema is not None
# Primitive types are wrapped
assert tool.output_schema["type"] == "object"
assert "result" in tool.output_schema["properties"]
assert tool.output_schema["properties"]["result"]["type"] == "integer"
# Call the tool
result = await client.call_tool("calculate_sum", {"a": 5, "b": 7})
assert result.is_error is False
assert result.structured_content is not None
assert result.structured_content == {"result": 12}
async def test_tool_structured_output_list(self):
"""Test tool with structured output returning list"""
def get_numbers() -> list[int]:
"""Get a list of numbers"""
return [1, 2, 3, 4, 5]
mcp = MCPServer()
mcp.add_tool(get_numbers)
async with Client(mcp) as client:
result = await client.call_tool("get_numbers", {})
assert result.is_error is False
assert result.structured_content is not None
assert result.structured_content == {"result": [1, 2, 3, 4, 5]}
async def test_tool_structured_output_server_side_validation_error(self):
"""Test that server-side validation errors are handled properly"""
def get_numbers() -> list[int]:
return [1, 2, 3, 4, [5]] # type: ignore
mcp = MCPServer()
mcp.add_tool(get_numbers)
async with Client(mcp) as client:
result = await client.call_tool("get_numbers", {})
assert result.is_error is True
assert result.structured_content is None
assert len(result.content) == 1
assert isinstance(result.content[0], TextContent)
async def test_tool_structured_output_dict_str_any(self):
"""Test tool with dict[str, Any] structured output"""
def get_metadata() -> dict[str, Any]:
"""Get metadata dictionary"""
return {
"version": "1.0.0",
"enabled": True,
"count": 42,
"tags": ["production", "stable"],
"config": {"nested": {"value": 123}},
}
mcp = MCPServer()
mcp.add_tool(get_metadata)
async with Client(mcp) as client:
# Check schema
tools = await client.list_tools()
tool = next(t for t in tools.tools if t.name == "get_metadata")
assert tool.output_schema is not None
assert tool.output_schema["type"] == "object"
# dict[str, Any] should have minimal schema
assert (
"additionalProperties" not in tool.output_schema
or tool.output_schema.get("additionalProperties") is True
)
# Call tool
result = await client.call_tool("get_metadata", {})
assert result.is_error is False
assert result.structured_content is not None
expected = {
"version": "1.0.0",
"enabled": True,
"count": 42,
"tags": ["production", "stable"],
"config": {"nested": {"value": 123}},
}
assert result.structured_content == expected
async def test_tool_structured_output_dict_str_typed(self):
"""Test tool with dict[str, T] structured output for specific T"""
def get_settings() -> dict[str, str]:
"""Get settings as string dictionary"""
return {"theme": "dark", "language": "en", "timezone": "UTC"}
mcp = MCPServer()
mcp.add_tool(get_settings)
async with Client(mcp) as client:
# Check schema
tools = await client.list_tools()
tool = next(t for t in tools.tools if t.name == "get_settings")
assert tool.output_schema is not None
assert tool.output_schema["type"] == "object"
assert tool.output_schema["additionalProperties"]["type"] == "string"
# Call tool
result = await client.call_tool("get_settings", {})
assert result.is_error is False
assert result.structured_content == {"theme": "dark", "language": "en", "timezone": "UTC"}
async def test_remove_tool(self):
"""Test removing a tool from the server."""
mcp = MCPServer()
mcp.add_tool(tool_fn)
# Verify tool exists
assert len(mcp._tool_manager.list_tools()) == 1
# Remove the tool
mcp.remove_tool("tool_fn")
# Verify tool is removed
assert len(mcp._tool_manager.list_tools()) == 0
async def test_remove_nonexistent_tool(self):
"""Test that removing a non-existent tool raises ToolError."""
mcp = MCPServer()
with pytest.raises(ToolError, match="Unknown tool: nonexistent"):
mcp.remove_tool("nonexistent")
async def test_remove_tool_and_list(self):
"""Test that a removed tool doesn't appear in list_tools."""
mcp = MCPServer()
mcp.add_tool(tool_fn)
mcp.add_tool(error_tool_fn)
# Verify both tools exist
async with Client(mcp) as client:
tools = await client.list_tools()
assert len(tools.tools) == 2
tool_names = [t.name for t in tools.tools]
assert "tool_fn" in tool_names
assert "error_tool_fn" in tool_names
# Remove one tool
mcp.remove_tool("tool_fn")
# Verify only one tool remains
async with Client(mcp) as client:
tools = await client.list_tools()
assert len(tools.tools) == 1
assert tools.tools[0].name == "error_tool_fn"
async def test_remove_tool_and_call(self):
"""Test that calling a removed tool fails appropriately."""
mcp = MCPServer()
mcp.add_tool(tool_fn)
# Verify tool works before removal
async with Client(mcp) as client:
result = await client.call_tool("tool_fn", {"x": 1, "y": 2})
assert not result.is_error
content = result.content[0]
assert isinstance(content, TextContent)
assert content.text == "3"
# Remove the tool
mcp.remove_tool("tool_fn")
# Verify calling removed tool returns an error
async with Client(mcp) as client:
result = await client.call_tool("tool_fn", {"x": 1, "y": 2})
assert result.is_error
content = result.content[0]
assert isinstance(content, TextContent)
assert "Unknown tool" in content.text
class TestServerResources:
async def test_text_resource(self):
mcp = MCPServer()
def get_text():
return "Hello, world!"
resource = FunctionResource(uri="resource://test", name="test", fn=get_text)
mcp.add_resource(resource)
async with Client(mcp) as client:
result = await client.read_resource("resource://test")
assert isinstance(result.contents[0], TextResourceContents)
assert result.contents[0].text == "Hello, world!"
async def test_read_unknown_resource(self):
"""Test that reading an unknown resource raises MCPError."""
mcp = MCPServer()
async with Client(mcp) as client:
with pytest.raises(MCPError, match="Unknown resource: unknown://missing"):
await client.read_resource("unknown://missing")
async def test_read_resource_error(self):
"""Test that resource read errors are properly wrapped in MCPError."""
mcp = MCPServer()
@mcp.resource("resource://failing")
def failing_resource():
raise ValueError("Resource read failed")
async with Client(mcp) as client:
with pytest.raises(MCPError, match="Error reading resource resource://failing"):
await client.read_resource("resource://failing")
async def test_binary_resource(self):
mcp = MCPServer()
def get_binary():
return b"Binary data"
resource = FunctionResource(
uri="resource://binary",
name="binary",
fn=get_binary,
mime_type="application/octet-stream",
)
mcp.add_resource(resource)
async with Client(mcp) as client:
result = await client.read_resource("resource://binary")
assert isinstance(result.contents[0], BlobResourceContents)
assert result.contents[0].blob == base64.b64encode(b"Binary data").decode()
async def test_file_resource_text(self, tmp_path: Path):
mcp = MCPServer()
# Create a text file
text_file = tmp_path / "test.txt"
text_file.write_text("Hello from file!")
resource = FileResource(uri="file://test.txt", name="test.txt", path=text_file)
mcp.add_resource(resource)
async with Client(mcp) as client:
result = await client.read_resource("file://test.txt")
assert isinstance(result.contents[0], TextResourceContents)
assert result.contents[0].text == "Hello from file!"
async def test_file_resource_binary(self, tmp_path: Path):
mcp = MCPServer()
# Create a binary file
binary_file = tmp_path / "test.bin"
binary_file.write_bytes(b"Binary file data")
resource = FileResource(
uri="file://test.bin",
name="test.bin",
path=binary_file,
mime_type="application/octet-stream",
)
mcp.add_resource(resource)
async with Client(mcp) as client:
result = await client.read_resource("file://test.bin")
assert isinstance(result.contents[0], BlobResourceContents)
assert result.contents[0].blob == base64.b64encode(b"Binary file data").decode()
async def test_function_resource(self):
mcp = MCPServer()
@mcp.resource("function://test", name="test_get_data")
def get_data() -> str: # pragma: no cover
"""get_data returns a string"""
return "Hello, world!"
async with Client(mcp) as client:
resources = await client.list_resources()
assert len(resources.resources) == 1
resource = resources.resources[0]
assert resource.description == "get_data returns a string"
assert resource.uri == "function://test"
assert resource.name == "test_get_data"
assert resource.mime_type == "text/plain"
async def test_remove_resource(self):
"""Test removing a resource from the server."""
mcp = MCPServer()
@mcp.resource("resource://test")
def get_data() -> str: # pragma: no cover
return "Hello"
assert len(mcp._resource_manager.list_resources()) == 1
mcp.remove_resource("resource://test")
assert len(mcp._resource_manager.list_resources()) == 0
async def test_remove_nonexistent_resource(self):
"""Test that removing a non-existent resource raises ResourceError."""
mcp = MCPServer()
with pytest.raises(ResourceError, match="Unknown resource: resource://nonexistent"):
mcp.remove_resource("resource://nonexistent")
async def test_remove_resource_and_list(self):
"""Test that a removed resource doesn't appear in list_resources."""
mcp = MCPServer()
@mcp.resource("resource://first")
def first() -> str: # pragma: no cover
return "first"
@mcp.resource("resource://second")
def second() -> str: # pragma: no cover
return "second"
async with Client(mcp) as client:
resources = await client.list_resources()
assert len(resources.resources) == 2
mcp.remove_resource("resource://first")
async with Client(mcp) as client:
resources = await client.list_resources()
assert len(resources.resources) == 1
assert resources.resources[0].uri == "resource://second"
async def test_remove_resource_and_read(self):
"""Test that reading a removed resource fails appropriately."""
mcp = MCPServer()
@mcp.resource("resource://test")
def get_data() -> str:
return "Hello"
async with Client(mcp) as client:
result = await client.read_resource("resource://test")
assert isinstance(result.contents[0], TextResourceContents)
assert result.contents[0].text == "Hello"
mcp.remove_resource("resource://test")
async with Client(mcp) as client:
with pytest.raises(MCPError, match="Unknown resource"):
await client.read_resource("resource://test")
class TestServerResourceTemplates:
async def test_resource_with_params(self):
"""Test that a resource with function parameters raises an error if the URI
parameters don't match"""
mcp = MCPServer()
with pytest.raises(ValueError, match="Mismatch between URI parameters"):
@mcp.resource("resource://data")
def get_data_fn(param: str) -> str: # pragma: no cover
return f"Data: {param}"
async def test_resource_with_uri_params(self):
"""Test that a resource with URI parameters is automatically a template"""
mcp = MCPServer()
with pytest.raises(ValueError, match="Mismatch between URI parameters"):
@mcp.resource("resource://{param}")
def get_data() -> str: # pragma: no cover
return "Data"
async def test_resource_with_untyped_params(self):
"""Test that a resource with untyped parameters raises an error"""
mcp = MCPServer()
@mcp.resource("resource://{param}")
def get_data(param) -> str: # type: ignore # pragma: no cover
return "Data"
async def test_resource_matching_params(self):
"""Test that a resource with matching URI and function parameters works"""
mcp = MCPServer()
@mcp.resource("resource://{name}/data")
def get_data(name: str) -> str:
return f"Data for {name}"
async with Client(mcp) as client:
result = await client.read_resource("resource://test/data")
assert isinstance(result.contents[0], TextResourceContents)
assert result.contents[0].text == "Data for test"
async def test_resource_mismatched_params(self):
"""Test that mismatched parameters raise an error"""
mcp = MCPServer()
with pytest.raises(ValueError, match="Mismatch between URI parameters"):
@mcp.resource("resource://{name}/data")
def get_data(user: str) -> str: # pragma: no cover
return f"Data for {user}"
async def test_resource_multiple_params(self):
"""Test that multiple parameters work correctly"""
mcp = MCPServer()
@mcp.resource("resource://{org}/{repo}/data")
def get_data(org: str, repo: str) -> str:
return f"Data for {org}/{repo}"
async with Client(mcp) as client:
result = await client.read_resource("resource://cursor/myrepo/data")
assert isinstance(result.contents[0], TextResourceContents)
assert result.contents[0].text == "Data for cursor/myrepo"
async def test_resource_multiple_mismatched_params(self):
"""Test that mismatched parameters raise an error"""
mcp = MCPServer()
with pytest.raises(ValueError, match="Mismatch between URI parameters"):
@mcp.resource("resource://{org}/{repo}/data")
def get_data_mismatched(org: str, repo_2: str) -> str: # pragma: no cover
return f"Data for {org}"
"""Test that a resource with no parameters works as a regular resource"""
mcp = MCPServer()
@mcp.resource("resource://static")
def get_static_data() -> str:
return "Static data"
async with Client(mcp) as client:
result = await client.read_resource("resource://static")
assert isinstance(result.contents[0], TextResourceContents)
assert result.contents[0].text == "Static data"
async def test_template_to_resource_conversion(self):
"""Test that templates are properly converted to resources when accessed"""
mcp = MCPServer()
@mcp.resource("resource://{name}/data")
def get_data(name: str) -> str:
return f"Data for {name}"
# Should be registered as a template
assert len(mcp._resource_manager._templates) == 1
assert len(await mcp.list_resources()) == 0
# When accessed, should create a concrete resource
resource = await mcp._resource_manager.get_resource("resource://test/data", Context())
assert isinstance(resource, FunctionResource)
result = await resource.read()
assert result == "Data for test"
async def test_resource_template_includes_mime_type(self):
"""Test that list resource templates includes the correct mimeType."""
mcp = MCPServer()
@mcp.resource("resource://{user}/csv", mime_type="text/csv")
def get_csv(user: str) -> str:
return f"csv for {user}"
templates = await mcp.list_resource_templates()
assert templates == snapshot(
[
ResourceTemplate(
name="get_csv", uri_template="resource://{user}/csv", description="", mime_type="text/csv"
)
]
)
async with Client(mcp) as client:
result = await client.read_resource("resource://bob/csv")
assert result == snapshot(
ReadResourceResult(
contents=[TextResourceContents(uri="resource://bob/csv", mime_type="text/csv", text="csv for bob")]
)
)
async def test_remove_resource_template(self):
"""Test removing a resource template from the server."""
mcp = MCPServer()
@mcp.resource("resource://{name}/data")
def get_data(name: str) -> str: # pragma: no cover