-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathtest_proxy_server.py
More file actions
1617 lines (1315 loc) · 65.8 KB
/
Copy pathtest_proxy_server.py
File metadata and controls
1617 lines (1315 loc) · 65.8 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 inspect
import json
import time
from typing import Any, cast
from unittest.mock import AsyncMock, patch
import httpx2
import mcp_types
import pytest
from anyio import create_task_group
from dirty_equals import Contains
from mcp import MCPError
from mcp_types import Icon, TextContent, TextResourceContents
from mcp_types.version import MODERN_PROTOCOL_VERSIONS
from pydantic import AnyUrl
from fastmcp import FastMCP
from fastmcp.client import Client
from fastmcp.client.transports import FastMCPTransport, StreamableHttpTransport
from fastmcp.client.transports.base import TransportOptions
from fastmcp.exceptions import ToolError
from fastmcp.mcp_config import MCPConfig
from fastmcp.resources import ResourceContent, ResourceResult
from fastmcp.server import create_proxy
from fastmcp.server.middleware import Middleware
from fastmcp.server.providers.proxy import (
FastMCPProxy,
ProxyClient,
ProxyProvider,
_ForwardingClientSession,
)
from fastmcp.tools.base import ToolResult
from fastmcp.tools.tool_transform import (
ToolTransformConfig,
)
from fastmcp.utilities.http import find_available_port
from fastmcp.utilities.tests import run_server_async
USERS = [
{"id": "1", "name": "Alice", "active": True},
{"id": "2", "name": "Bob", "active": True},
{"id": "3", "name": "Charlie", "active": False},
]
@pytest.fixture
def fastmcp_server():
server = FastMCP("TestServer")
# --- Tools ---
@server.tool(
tags={"greet"},
title="Greet",
icons=[Icon(src="https://example.com/greet-icon.png")],
)
def greet(name: str) -> str:
"""Greet someone by name."""
return f"Hello, {name}!"
@server.tool
def tool_without_description() -> str:
return "Hello?"
@server.tool
def add(a: int, b: int) -> int:
"""Add two numbers together."""
return a + b
@server.tool
def error_tool():
"""This tool always raises an error."""
raise ValueError("This is a test error")
# --- Resources ---
@server.resource(
uri="resource://wave",
tags={"wave"},
title="Wave",
icons=[Icon(src="https://example.com/wave-icon.png")],
)
def wave() -> str:
return "👋"
@server.resource(uri="data://users")
async def get_users() -> str:
import json
return json.dumps(USERS, separators=(",", ":"))
@server.resource(
uri="data://user/{user_id}",
tags={"users"},
title="User Template",
icons=[Icon(src="https://example.com/user-icon.png")],
)
async def get_user(user_id: str) -> str:
import json
user = next((user for user in USERS if user["id"] == user_id), None)
return json.dumps(user, separators=(",", ":")) if user else "null"
@server.resource(uri="data://multi")
def get_multi_content() -> ResourceResult:
"""Resource that returns multiple content items."""
return ResourceResult(
contents=[
ResourceContent(content="First item", mime_type="text/plain"),
ResourceContent(
content='{"key": "value"}', mime_type="application/json"
),
ResourceContent(
content="# Markdown\nContent", mime_type="text/markdown"
),
],
meta={"count": 3},
)
@server.resource(uri="data://multi/{id}")
def get_multi_template(id: str) -> ResourceResult:
"""Resource template that returns multiple content items."""
return ResourceResult(
contents=[
ResourceContent(content=f"Item {id} - First", mime_type="text/plain"),
ResourceContent(
content=f'{{"id": "{id}", "status": "active"}}',
mime_type="application/json",
),
],
meta={"id": id},
)
# --- Prompts ---
@server.prompt(
tags={"welcome"},
title="Welcome",
icons=[Icon(src="https://example.com/welcome-icon.png")],
)
def welcome(name: str) -> str:
return f"Welcome to FastMCP, {name}!"
@server.prompt
def image_prompt():
"""A prompt that returns an image."""
from fastmcp.prompts.base import Message, PromptResult
return PromptResult(
messages=[
Message("Here is an image:"),
Message(
content=mcp_types.ImageContent(
type="image",
data="iVBORw0KGgoAAAANSUhEUg==",
mime_type="image/png",
),
role="user",
),
]
)
return server
@pytest.fixture
async def proxy_server(fastmcp_server):
"""Fixture that creates a FastMCP proxy server.
Passing an already-constructed `ProxyClient` as the target (rather than a
raw `FastMCP`/URL/etc.) means `create_proxy` reuses that client as-is
instead of building one through the era-mirroring factory — so this
backend stays pinned to `ProxyClient`'s own default of `mode="legacy"`
regardless of what era the front client negotiates. A test that actually
forwards a tool *call* through this fixture (not just a listing) needs
its own front `Client` pinned to `mode="legacy"` too: otherwise a modern
front's request `_meta` carries the reserved modern-envelope keys, which
`ProxyTool.run`'s legacy-backend path forwards verbatim onto this
legacy-locked backend session, and the backend server rejects it as a
protocol violation.
"""
return create_proxy(ProxyClient(transport=FastMCPTransport(fastmcp_server)))
async def test_create_proxy_with_client(fastmcp_server):
"""Test create_proxy with a Client."""
client = ProxyClient(transport=FastMCPTransport(fastmcp_server))
server = create_proxy(client)
assert isinstance(server, FastMCPProxy)
assert isinstance(server, FastMCP)
assert server.name.startswith("FastMCPProxy-")
async def test_create_proxy_with_server(fastmcp_server):
"""create_proxy should accept a FastMCP instance."""
proxy = create_proxy(fastmcp_server)
async with Client(proxy) as client:
result = await client.call_tool("greet", {"name": "Test"})
assert result.data == "Hello, Test!"
async def test_create_proxy_with_transport(fastmcp_server):
"""create_proxy should accept a ClientTransport."""
proxy = create_proxy(FastMCPTransport(fastmcp_server))
async with Client(proxy) as client:
result = await client.call_tool("greet", {"name": "Test"})
assert result.data == "Hello, Test!"
async def test_proxy_forwards_upstream_instructions():
"""A proxy should surface the upstream server's instructions in the handshake.
`FastMCPProxy` registers a `server/discover` handler that forwards the
upstream's instructions, mirroring what `ProxyInitializeMiddleware.on_initialize`
already does for the legacy handshake, so `client.session.instructions`
(era-neutral) resolves the same way on both protocol eras.
"""
upstream = FastMCP(name="upstream", instructions="USE_THIS_MARKER_123")
proxy = create_proxy(upstream, name="proxy")
async with Client(proxy) as client:
assert client.session.instructions == "USE_THIS_MARKER_123"
async def test_proxy_own_instructions_take_precedence():
"""Instructions explicitly set on the proxy override the upstream's."""
upstream = FastMCP(name="upstream", instructions="upstream instructions")
proxy = create_proxy(upstream, name="proxy", instructions="proxy instructions")
async with Client(proxy) as client:
assert client.session.instructions == "proxy instructions"
async def test_proxy_instructions_none_when_upstream_has_none():
"""A proxy over an upstream without instructions reports no instructions."""
upstream = FastMCP(name="upstream")
proxy = create_proxy(upstream, name="proxy")
async with Client(proxy) as client:
assert client.session.instructions is None
def test_create_proxy_with_url():
"""create_proxy should accept a URL without connecting."""
proxy = create_proxy("http://example.com/mcp/")
assert isinstance(proxy, FastMCPProxy)
client = cast(Client, proxy.client_factory())
assert isinstance(client.transport, StreamableHttpTransport)
assert client.transport.url == "http://example.com/mcp/"
async def test_proxy_with_async_client_factory():
"""FastMCPProxy should accept an async client_factory."""
async def async_factory():
return Client("http://example.com/mcp/")
proxy = FastMCPProxy(client_factory=async_factory)
assert isinstance(proxy, FastMCPProxy)
assert inspect.iscoroutinefunction(proxy.client_factory)
client = proxy.client_factory()
if inspect.isawaitable(client):
client = await client
assert isinstance(client, Client)
assert isinstance(client.transport, StreamableHttpTransport)
assert client.transport.url == "http://example.com/mcp/"
async def test_proxy_ping_forwards_to_remote_server(fastmcp_server):
proxy = create_proxy(fastmcp_server)
async with Client(proxy, mode="legacy") as client:
assert await client.ping() is True
async def test_proxy_ping_surfaces_wrong_remote_path():
remote = FastMCP("remote")
async with run_server_async(remote, transport="http") as url:
proxy = create_proxy(StreamableHttpTransport(url.removesuffix("/mcp")))
# This asserts the error surfaces from merely *connecting* to the proxy,
# with no operation performed. That only happens on the legacy handshake:
# `ProxyInitializeMiddleware.on_initialize` eagerly probes the backend
# during the front's own `initialize` call. A modern front negotiates
# `server/discover` instead, which never runs that middleware hook, so
# connecting succeeds regardless of backend health and the failure would
# only surface on first real use. Pinned because the subject here is
# that eager, handshake-time probe.
#
# SDK v2 surfaces a wrong remote path as an HTTP "Not Found" rather than
# the v1 "Session terminated" message.
with pytest.raises(MCPError, match="Not Found"):
async with Client(proxy, mode="legacy"):
pass
async def test_proxy_initialize_forwards_remote_connection_error():
port = find_available_port()
proxy = create_proxy(
StreamableHttpTransport(f"http://127.0.0.1:{port}/mcp"),
provider_error_strategy="raise",
)
# Same reasoning as test_proxy_ping_surfaces_wrong_remote_path above: the
# error surfaces from connecting alone only via the legacy handshake's
# eager backend probe in `ProxyInitializeMiddleware.on_initialize`.
with pytest.raises(MCPError, match="Client failed to connect"):
async with Client(proxy, mode="legacy"):
pass
async def test_proxy_list_tools_surfaces_remote_connection_error():
"""A dead backend surfaces as an MCPError naming the connection failure.
The provider normalizes transport failures into `MCPError` (rather than
letting the client's `RuntimeError` escape) so the error survives the
modern era's wire boundary, which masks any non-MCPError as a generic
"Internal server error".
"""
port = find_available_port()
proxy = create_proxy(
StreamableHttpTransport(f"http://127.0.0.1:{port}/mcp"),
provider_error_strategy="raise",
)
with pytest.raises(MCPError, match="Client failed to connect"):
await proxy.list_tools()
async def test_proxy_list_tools_client_surfaces_remote_connection_error():
"""With a modern front, connecting succeeds (no eager backend probe — see
test_proxy_ping_surfaces_wrong_remote_path) and the failure only surfaces
once `list_tools()` actually hits the dead backend. `ProxyProvider._list_tools`
now normalizes the raw `httpx2.ConnectError` from the failed backend connect
into the `MCPError("Client failed to connect...")` this test expects, the
same way `ProxyInitializeMiddleware.on_initialize` and `ProxyTool.run`
already did.
"""
port = find_available_port()
proxy = create_proxy(
StreamableHttpTransport(f"http://127.0.0.1:{port}/mcp"),
provider_error_strategy="raise",
)
with pytest.raises(MCPError, match="Client failed to connect"):
async with Client(proxy) as client:
await client.list_tools()
class TestTools:
async def test_get_tools(self, proxy_server):
tools = await proxy_server.list_tools()
assert any(t.name == "greet" for t in tools)
assert any(t.name == "add" for t in tools)
assert any(t.name == "error_tool" for t in tools)
assert any(t.name == "tool_without_description" for t in tools)
async def test_get_tools_meta(self, proxy_server):
tools = await proxy_server.list_tools()
greet_tool = next(t for t in tools if t.name == "greet")
assert greet_tool.title == "Greet"
assert greet_tool.meta == {"fastmcp": {"tags": ["greet"]}}
assert greet_tool.icons == [Icon(src="https://example.com/greet-icon.png")]
async def test_get_transformed_tools(self):
"""Test that tool transformations are applied to proxied tools."""
from fastmcp.server.transforms import ToolTransform
# Create server with transformation
server = FastMCP("TestServer")
@server.tool
def add(a: int, b: int) -> int:
"""Add two numbers together."""
return a + b
server.add_transform(
ToolTransform({"add": ToolTransformConfig(name="add_transformed")})
)
proxy = create_proxy(server)
tools = await proxy.list_tools()
assert any(t.name == "add_transformed" for t in tools)
assert not any(t.name == "add" for t in tools)
async def test_call_transformed_tools(self):
"""Test calling a transformed tool through a proxy."""
from fastmcp.server.transforms import ToolTransform
# Create server with transformation
server = FastMCP("TestServer")
@server.tool
def add(a: int, b: int) -> int:
"""Add two numbers together."""
return a + b
server.add_transform(
ToolTransform({"add": ToolTransformConfig(name="add_transformed")})
)
proxy = create_proxy(server)
async with Client(proxy) as client:
result = await client.call_tool("add_transformed", {"a": 1, "b": 2})
assert result.data == 3
async def test_tool_without_description(self, proxy_server):
tools = await proxy_server.list_tools()
tool = next(t for t in tools if t.name == "tool_without_description")
assert tool.description is None
async def test_list_tools_same_as_original(self, fastmcp_server, proxy_server):
async with Client(fastmcp_server) as original_client:
original = await original_client.list_tools()
async with Client(proxy_server) as proxy_client:
proxied = await proxy_client.list_tools()
assert proxied == original
async def test_call_tool_result_same_as_original(
self, fastmcp_server: FastMCP, proxy_server: FastMCPProxy
):
# proxy_server's backend is pinned to legacy (see its fixture docstring);
# match the front so a real tool call doesn't cross eras.
async with Client(fastmcp_server) as original_client:
result = await original_client.call_tool("greet", {"name": "Alice"})
async with Client(proxy_server, mode="legacy") as proxy_client:
proxy_result = await proxy_client.call_tool("greet", {"name": "Alice"})
assert result.content == proxy_result.content
assert result.data == proxy_result.data
async def test_call_tool_calls_tool(self, proxy_server):
# See proxy_server fixture docstring: its backend is pinned to legacy.
async with Client(proxy_server, mode="legacy") as client:
proxy_result = await client.call_tool("add", {"a": 1, "b": 2})
assert proxy_result.data == 3
async def test_error_tool_raises_error(self, proxy_server):
# See proxy_server fixture docstring: its backend is pinned to legacy.
with pytest.raises(ToolError, match="This is a test error"):
async with Client(proxy_server, mode="legacy") as client:
await client.call_tool("error_tool", {})
async def test_error_tool_with_image_content(self, proxy_server):
"""Non-TextContent error responses should not crash with AttributeError."""
error_result = mcp_types.CallToolResult(
content=[
mcp_types.ImageContent(
type="image", data="abc123", mime_type="image/png"
)
],
is_error=True,
)
with patch.object(
Client, "call_tool_mcp", new_callable=AsyncMock, return_value=error_result
):
with pytest.raises(ToolError):
async with Client(proxy_server) as client:
await client.call_tool("error_tool", {})
async def test_error_tool_with_empty_content(self, proxy_server):
"""Error responses with empty content should not crash."""
error_result = mcp_types.CallToolResult(
content=[],
is_error=True,
)
with patch.object(
Client, "call_tool_mcp", new_callable=AsyncMock, return_value=error_result
):
with pytest.raises(ToolError):
async with Client(proxy_server) as client:
await client.call_tool("error_tool", {})
async def test_error_tool_passthrough_preserves_content(self, proxy_server):
"""Upstream error results pass through with content intact, not flattened."""
error_result = mcp_types.CallToolResult(
content=[
mcp_types.ImageContent(
type="image", data="abc123", mime_type="image/png"
)
],
structured_content={"detail": "boom"},
is_error=True,
)
with patch.object(
Client, "call_tool_mcp", new_callable=AsyncMock, return_value=error_result
):
async with Client(proxy_server) as client:
result = await client.call_tool("error_tool", {}, raise_on_error=False)
assert result.is_error is True
assert isinstance(result.content[0], mcp_types.ImageContent)
assert result.content[0].data == "abc123"
assert result.structured_content == {"detail": "boom"}
async def test_call_tool_forwards_meta(self, fastmcp_server, proxy_server):
"""Test that metadata from proxied tool results is properly forwarded."""
@fastmcp_server.tool
def tool_with_meta(value: str) -> ToolResult:
"""A tool that returns metadata in its result."""
return ToolResult(
content=f"Result: {value}",
meta={"custom_key": "custom_value", "processed": True},
)
# See proxy_server fixture docstring: its backend is pinned to legacy.
async with Client(proxy_server, mode="legacy") as client:
result = await client.call_tool("tool_with_meta", {"value": "test"})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "Result: test"
assert result.meta == {"custom_key": "custom_value", "processed": True}
async def test_proxy_can_overwrite_proxied_tool(self, proxy_server):
"""
Test that a tool defined on the proxy can overwrite the proxied tool with the same name.
"""
@proxy_server.tool
def greet(name: str, extra: str = "extra") -> str:
return f"Overwritten, {name}! {extra}"
async with Client(proxy_server) as client:
result = await client.call_tool("greet", {"name": "Marvin", "extra": "abc"})
assert result.data == "Overwritten, Marvin! abc"
async def test_proxy_can_list_overwritten_tool(self, proxy_server):
"""
Test that a tool defined on the proxy is listed instead of the proxied tool
"""
@proxy_server.tool
def greet(name: str, extra: str = "extra") -> str:
return f"Overwritten, {name}! {extra}"
async with Client(proxy_server) as client:
tools = await client.list_tools()
greet_tool = next(t for t in tools if t.name == "greet")
assert "extra" in greet_tool.input_schema["properties"]
class TestResources:
async def test_get_resources(self, proxy_server):
resources = await proxy_server.list_resources()
assert [r.uri for r in resources] == Contains(
AnyUrl("data://users"),
AnyUrl("resource://wave"),
)
assert [r.name for r in resources] == Contains("get_users", "wave")
async def test_get_resources_meta(self, proxy_server):
resources = await proxy_server.list_resources()
wave_resource = next(r for r in resources if str(r.uri) == "resource://wave")
assert wave_resource.title == "Wave"
assert wave_resource.meta == {"fastmcp": {"tags": ["wave"]}}
assert wave_resource.icons == [Icon(src="https://example.com/wave-icon.png")]
async def test_list_resources_same_as_original(self, fastmcp_server, proxy_server):
async with Client(fastmcp_server) as original_client:
original = await original_client.list_resources()
async with Client(proxy_server) as proxy_client:
proxied = await proxy_client.list_resources()
assert proxied == original
async def test_read_resource(self, proxy_server: FastMCPProxy):
async with Client(proxy_server) as client:
result = await client.read_resource("resource://wave")
assert isinstance(result[0], TextResourceContents)
assert result[0].text == "👋"
async def test_read_resource_same_as_original(self, fastmcp_server, proxy_server):
async with Client(fastmcp_server) as client:
result = await client.read_resource("resource://wave")
async with Client(proxy_server) as client:
proxy_result = await client.read_resource("resource://wave")
assert proxy_result == result
async def test_read_json_resource(self, proxy_server: FastMCPProxy):
async with Client(proxy_server) as client:
result = await client.read_resource("data://users")
assert len(result) == 1
assert isinstance(result[0], TextResourceContents)
# The resource returns all users serialized as JSON
users = json.loads(result[0].text)
assert users == USERS
async def test_proxy_returns_all_resource_contents(
self, fastmcp_server, proxy_server
):
"""Test that proxy correctly returns all resource contents, not just the first one."""
# Read from original server
async with Client(fastmcp_server) as client:
original_result = await client.read_resource("data://multi")
# Read from proxy server
async with Client(proxy_server) as client:
proxy_result = await client.read_resource("data://multi")
# Both should return the same number of contents
assert len(original_result) == len(proxy_result)
assert len(original_result) == 3
# Verify all contents match
for i, (original, proxied) in enumerate(zip(original_result, proxy_result)):
assert isinstance(original, TextResourceContents)
assert isinstance(proxied, TextResourceContents)
assert original.text == proxied.text, f"Content {i} text mismatch"
assert original.mime_type == proxied.mime_type, (
f"Content {i} mimeType mismatch"
)
assert original.meta == proxied.meta, f"Content {i} meta mismatch"
# Verify the contents are what we expect
assert original_result[0].text == "First item"
assert original_result[0].mime_type == "text/plain"
assert original_result[1].text == '{"key": "value"}'
assert original_result[1].mime_type == "application/json"
assert original_result[2].text == "# Markdown\nContent"
assert original_result[2].mime_type == "text/markdown"
async def test_read_resource_returns_none_if_not_found(self, proxy_server):
with pytest.raises(
MCPError, match="Resource not found: 'resource://nonexistent'"
):
async with Client(proxy_server) as client:
await client.read_resource("resource://nonexistent")
async def test_proxy_can_overwrite_proxied_resource(self, proxy_server):
"""
Test that a resource defined on the proxy can overwrite the proxied resource with the same URI.
"""
@proxy_server.resource(uri="resource://wave")
def overwritten_wave() -> str:
return "Overwritten wave! 🌊"
async with Client(proxy_server) as client:
result = await client.read_resource("resource://wave")
assert isinstance(result[0], TextResourceContents)
assert result[0].text == "Overwritten wave! 🌊"
async def test_proxy_can_list_overwritten_resource(self, proxy_server):
"""
Test that a resource defined on the proxy is listed instead of the proxied resource
"""
@proxy_server.resource(uri="resource://wave", name="overwritten_wave")
def overwritten_wave() -> str:
return "Overwritten wave! 🌊"
async with Client(proxy_server) as client:
resources = await client.list_resources()
wave_resource = next(
r for r in resources if str(r.uri) == "resource://wave"
)
assert wave_resource.name == "overwritten_wave"
class TestResourceTemplates:
async def test_get_resource_templates(self, proxy_server):
templates = await proxy_server.list_resource_templates()
assert [t.name for t in templates] == Contains("get_user")
async def test_get_resource_templates_meta(self, proxy_server):
templates = await proxy_server.list_resource_templates()
get_user_template = next(
t for t in templates if t.uri_template == "data://user/{user_id}"
)
assert get_user_template.title == "User Template"
assert get_user_template.meta == {"fastmcp": {"tags": ["users"]}}
assert get_user_template.icons == [
Icon(src="https://example.com/user-icon.png")
]
async def test_list_resource_templates_same_as_original(
self, fastmcp_server, proxy_server
):
async with Client(fastmcp_server) as original_client:
result = await original_client.list_resource_templates()
async with Client(proxy_server) as proxy_client:
proxy_result = await proxy_client.list_resource_templates()
assert proxy_result == result
@pytest.mark.parametrize("id", [1, 2, 3])
async def test_read_resource_template(self, proxy_server: FastMCPProxy, id: int):
async with Client(proxy_server) as client:
result = await client.read_resource(f"data://user/{id}")
assert isinstance(result[0], TextResourceContents)
assert json.loads(result[0].text) == USERS[id - 1]
async def test_read_resource_template_same_as_original(
self, fastmcp_server, proxy_server
):
async with Client(fastmcp_server) as client:
result = await client.read_resource("data://user/1")
async with Client(proxy_server) as client:
proxy_result = await client.read_resource("data://user/1")
assert proxy_result == result
async def test_proxy_template_returns_all_resource_contents(
self, fastmcp_server, proxy_server
):
"""Test that proxy template correctly returns all resource contents."""
# Read from original server
async with Client(fastmcp_server) as client:
original_result = await client.read_resource("data://multi/test123")
# Read from proxy server
async with Client(proxy_server) as client:
proxy_result = await client.read_resource("data://multi/test123")
# Both should return the same number of contents
assert len(original_result) == len(proxy_result)
assert len(original_result) == 2
# Verify all contents match
for i, (original, proxied) in enumerate(zip(original_result, proxy_result)):
assert isinstance(original, TextResourceContents)
assert isinstance(proxied, TextResourceContents)
assert original.text == proxied.text, f"Content {i} text mismatch"
assert original.mime_type == proxied.mime_type, (
f"Content {i} mimeType mismatch"
)
# Verify the contents are what we expect
assert original_result[0].text == "Item test123 - First"
assert original_result[0].mime_type == "text/plain"
assert original_result[1].text == '{"id": "test123", "status": "active"}'
assert original_result[1].mime_type == "application/json"
async def test_proxy_can_overwrite_proxied_resource_template(self, proxy_server):
"""
Test that a resource template defined on the proxy can overwrite the proxied template with the same URI template.
"""
@proxy_server.resource(uri="data://user/{user_id}", name="overwritten_get_user")
def overwritten_get_user(user_id: str) -> str:
return json.dumps(
{
"id": user_id,
"name": "Overwritten User",
"active": True,
"extra": "data",
}
)
async with Client(proxy_server) as client:
result = await client.read_resource("data://user/1")
assert isinstance(result[0], TextResourceContents)
user_data = json.loads(result[0].text)
assert user_data["name"] == "Overwritten User"
assert user_data["extra"] == "data"
async def test_proxy_can_list_overwritten_resource_template(self, proxy_server):
"""
Test that a resource template defined on the proxy is listed instead of the proxied template
"""
@proxy_server.resource(uri="data://user/{user_id}", name="overwritten_get_user")
def overwritten_get_user(user_id: str) -> dict[str, Any]:
return {"id": user_id, "name": "Overwritten User", "active": True}
async with Client(proxy_server) as client:
templates = await client.list_resource_templates()
user_template = next(
t for t in templates if t.uri_template == "data://user/{user_id}"
)
assert user_template.name == "overwritten_get_user"
class TestResourceTemplateQueryParams:
"""Resource templates with RFC 6570 {?param} query params work through proxy."""
async def test_query_param_forwarded(self):
remote = FastMCP("Remote")
@remote.resource("data://{id}{?format}")
def get_data(id: str, format: str = "json") -> str:
return f"id={id} format={format}"
proxy = create_proxy(Client(remote))
async with Client(proxy) as client:
result = await client.read_resource("data://123?format=xml")
assert isinstance(result[0], TextResourceContents)
assert result[0].text == "id=123 format=xml"
async def test_query_param_default_used_when_omitted(self):
remote = FastMCP("Remote")
@remote.resource("data://{id}{?format}")
def get_data(id: str, format: str = "json") -> str:
return f"id={id} format={format}"
proxy = create_proxy(Client(remote))
async with Client(proxy) as client:
result = await client.read_resource("data://123")
assert isinstance(result[0], TextResourceContents)
assert result[0].text == "id=123 format=json"
async def test_multiple_query_params_forwarded(self):
remote = FastMCP("Remote")
@remote.resource("data://{id}{?limit,offset}")
def get_data(id: str, limit: int = 10, offset: int = 0) -> str:
return f"id={id} limit={limit} offset={offset}"
proxy = create_proxy(Client(remote))
async with Client(proxy) as client:
result = await client.read_resource("data://abc?limit=5&offset=20")
assert isinstance(result[0], TextResourceContents)
assert result[0].text == "id=abc limit=5 offset=20"
async def test_encoded_path_param_preserved(self):
remote = FastMCP("Remote")
@remote.resource("data://{id}")
def get_data(id: str) -> str:
return f"id={id}"
proxy = create_proxy(Client(remote))
async with Client(proxy) as client:
result = await client.read_resource("data://a%2Fb")
assert isinstance(result[0], TextResourceContents)
assert result[0].text == "id=a/b"
async def test_hyphenated_query_param_forwarded(self):
remote = FastMCP("Remote")
@remote.resource("data://{id}{?api-version}")
def get_data(id: str, api_version: str = "v1") -> str:
return f"id={id} api_version={api_version}"
proxy = create_proxy(Client(remote))
async with Client(proxy) as client:
result = await client.read_resource("data://123?api-version=v2")
assert isinstance(result[0], TextResourceContents)
assert result[0].text == "id=123 api_version=v2"
def test_same_name_in_path_and_query_is_rejected(self):
remote = FastMCP("Remote")
with pytest.raises(ValueError, match="must be optional"):
@remote.resource("data://{id}{?id}")
def get_data(id: str) -> str:
return id
async def test_hyphenated_query_param_not_double_encoded(self):
remote = FastMCP("Remote")
@remote.resource("data://{id}{?api-version}")
def get_data(id: str, api_version: str = "v1") -> str:
return f"id={id} api_version={api_version}"
proxy = create_proxy(Client(remote))
async with Client(proxy) as client:
result = await client.read_resource("data://123?api-version=a%2Fb")
assert isinstance(result[0], TextResourceContents)
assert result[0].text == "id=123 api_version=a/b"
class TestPrompts:
async def test_get_prompts_server_method(self, proxy_server: FastMCPProxy):
prompts = await proxy_server.list_prompts()
assert [p.name for p in prompts] == Contains("welcome")
async def test_get_prompts_meta(self, proxy_server):
prompts = await proxy_server.list_prompts()
welcome_prompt = next(p for p in prompts if p.name == "welcome")
assert welcome_prompt.title == "Welcome"
assert welcome_prompt.meta == {"fastmcp": {"tags": ["welcome"]}}
assert welcome_prompt.icons == [
Icon(src="https://example.com/welcome-icon.png")
]
async def test_list_prompts_same_as_original(self, fastmcp_server, proxy_server):
async with Client(fastmcp_server) as client:
result = await client.list_prompts()
async with Client(proxy_server) as client:
proxy_result = await client.list_prompts()
assert proxy_result == result
async def test_render_prompt_same_as_original(
self, fastmcp_server: FastMCP, proxy_server: FastMCPProxy
):
async with Client(fastmcp_server) as client:
result = await client.get_prompt("welcome", {"name": "Alice"})
async with Client(proxy_server) as client:
proxy_result = await client.get_prompt("welcome", {"name": "Alice"})
assert proxy_result == result
async def test_render_prompt_calls_prompt(self, proxy_server):
async with Client(proxy_server) as client:
result = await client.get_prompt("welcome", {"name": "Alice"})
assert result.messages[0].role == "user"
assert isinstance(result.messages[0].content, TextContent)
assert result.messages[0].content.text == "Welcome to FastMCP, Alice!"
async def test_proxy_can_overwrite_proxied_prompt(self, proxy_server):
"""
Test that a prompt defined on the proxy can overwrite the proxied prompt with the same name.
"""
@proxy_server.prompt
def welcome(name: str, extra: str = "friend") -> str:
return f"Overwritten welcome, {name}! You are my {extra}."
async with Client(proxy_server) as client:
result = await client.get_prompt(
"welcome", {"name": "Alice", "extra": "colleague"}
)
assert result.messages[0].role == "user"
assert isinstance(result.messages[0].content, TextContent)
assert (
result.messages[0].content.text
== "Overwritten welcome, Alice! You are my colleague."
)
async def test_proxy_can_list_overwritten_prompt(self, proxy_server):
"""
Test that a prompt defined on the proxy is listed instead of the proxied prompt
"""
@proxy_server.prompt
def welcome(name: str, extra: str = "friend") -> str:
return f"Overwritten welcome, {name}! You are my {extra}."
async with Client(proxy_server) as client:
prompts = await client.list_prompts()
welcome_prompt = next(p for p in prompts if p.name == "welcome")
# Check that the overwritten prompt has the additional 'extra' parameter
param_names = [arg.name for arg in welcome_prompt.arguments or []]
assert "extra" in param_names
async def test_proxy_prompt_preserves_image_content(
self, fastmcp_server: FastMCP, proxy_server: FastMCPProxy
):
"""Test that ProxyPrompt preserves ImageContent without lossy conversion."""
async with Client(fastmcp_server) as client:
result = await client.get_prompt("image_prompt")
async with Client(proxy_server) as client:
proxy_result = await client.get_prompt("image_prompt")
# The proxy result should match the original exactly
assert proxy_result == result
# Verify the image content is preserved as ImageContent, not JSON text
assert isinstance(proxy_result.messages[1].content, mcp_types.ImageContent)
assert proxy_result.messages[1].content.data == "iVBORw0KGgoAAAANSUhEUg=="
assert proxy_result.messages[1].content.mime_type == "image/png"
async def test_proxy_handles_multiple_concurrent_tasks_correctly(
proxy_server: FastMCPProxy,
):
results = {}
async def get_and_store(name, coro):
results[name] = await coro()
async with create_task_group() as tg:
tg.start_soon(get_and_store, "prompts", proxy_server.list_prompts)
tg.start_soon(get_and_store, "resources", proxy_server.list_resources)
tg.start_soon(get_and_store, "tools", proxy_server.list_tools)
assert list(results) == Contains("resources", "prompts", "tools")
assert [p.name for p in results["prompts"]] == Contains("welcome")
assert [r.uri for r in results["resources"]] == Contains(
AnyUrl("data://users"),
AnyUrl("resource://wave"),
)
assert [r.name for r in results["resources"]] == Contains("get_users", "wave")
assert [t.name for t in results["tools"]] == Contains(
"greet", "add", "error_tool", "tool_without_description"
)
class TestProxyComponentEnableDisable:
"""Test that enable/disable on proxy components guides users to server-level methods."""
async def test_proxy_tool_enable_raises_not_implemented(self, proxy_server):
"""Test that enable() on proxy tools raises NotImplementedError."""
tools = await proxy_server.list_tools()
tool = next(t for t in tools if t.name == "greet")
with pytest.raises(NotImplementedError, match="server.enable"):
tool.enable()
async def test_proxy_tool_disable_raises_not_implemented(self, proxy_server):
"""Test that disable() on proxy tools raises NotImplementedError."""
tools = await proxy_server.list_tools()
tool = next(t for t in tools if t.name == "greet")
with pytest.raises(NotImplementedError, match="server.disable"):
tool.disable()
async def test_proxy_resource_enable_raises_not_implemented(self, proxy_server):
"""Test that enable() on proxy resources raises NotImplementedError."""
resources = await proxy_server.list_resources()
resource = next(r for r in resources if str(r.uri) == "resource://wave")