-
Notifications
You must be signed in to change notification settings - Fork 612
Expand file tree
/
Copy pathtest_mcp.py
More file actions
1255 lines (1044 loc) · 37 KB
/
test_mcp.py
File metadata and controls
1255 lines (1044 loc) · 37 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
"""
Unit tests for the MCP (Model Context Protocol) integration.
This test suite covers:
- Tool handlers (sync and async)
- Prompt handlers (sync and async)
- Resource handlers (sync and async)
- Error handling for each handler type
- Request context data extraction (request_id, session_id, transport)
- Tool result content extraction (various formats)
- Span data validation
- Origin tracking
The tests mock the MCP server components and request context to verify
that the integration properly instruments MCP handlers with Sentry spans.
"""
from urllib.parse import urlparse, parse_qs
import anyio
import asyncio
import httpx
from .streaming_asgi_transport import StreamingASGITransport
import pytest
import json
from unittest import mock
try:
from unittest.mock import AsyncMock
except ImportError:
class AsyncMock(mock.MagicMock):
async def __call__(self, *args, **kwargs):
return super(AsyncMock, self).__call__(*args, **kwargs)
from mcp.server.lowlevel import Server
from mcp.server.lowlevel.server import request_ctx
from mcp.types import GetPromptResult, PromptMessage, TextContent
from mcp.server.lowlevel.helper_types import ReadResourceContents
try:
from mcp.server.lowlevel.server import request_ctx
except ImportError:
request_ctx = None
from sentry_sdk import start_transaction
from sentry_sdk.consts import SPANDATA, OP
from sentry_sdk.integrations.mcp import MCPIntegration
from mcp.server.sse import SseServerTransport
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
from starlette.routing import Mount, Route
from starlette.applications import Starlette
from starlette.responses import Response
@pytest.fixture(autouse=True)
def reset_request_ctx():
"""Reset request context before and after each test"""
if request_ctx is not None:
try:
if request_ctx.get() is not None:
request_ctx.set(None)
except LookupError:
pass
yield
if request_ctx is not None:
try:
request_ctx.set(None)
except LookupError:
pass
class MockRequestContext:
"""Mock MCP request context"""
def __init__(self, request_id=None, session_id=None, transport="stdio"):
self.request_id = request_id
if transport in ("http", "sse"):
self.request = MockHTTPRequest(session_id, transport)
else:
self.request = None
class MockHTTPRequest:
"""Mock HTTP request for SSE/StreamableHTTP transport"""
def __init__(self, session_id=None, transport="http"):
self.headers = {}
self.query_params = {}
if transport == "sse":
# SSE transport uses query parameter
if session_id:
self.query_params["session_id"] = session_id
else:
# StreamableHTTP transport uses header
if session_id:
self.headers["mcp-session-id"] = session_id
class MockTextContent:
"""Mock TextContent object"""
def __init__(self, text):
self.text = text
async def json_rpc_sse(
app, method: str, params, request_id: str, keep_sse_alive: "asyncio.Event"
):
context = {}
stream_complete = asyncio.Event()
endpoint_parsed = asyncio.Event()
# https://github.com/Kludex/starlette/issues/104#issuecomment-729087925
async with httpx.AsyncClient(
transport=StreamingASGITransport(app=app, keep_sse_alive=keep_sse_alive),
base_url="http://test",
) as client:
async def parse_stream():
async with client.stream("GET", "/sse") as stream:
# Read directly from stream.stream instead of aiter_bytes()
async for chunk in stream.stream:
if b"event: endpoint" in chunk:
sse_text = chunk.decode("utf-8")
url = sse_text.split("data: ")[1]
parsed = urlparse(url)
query_params = parse_qs(parsed.query)
context["session_id"] = query_params["session_id"][0]
endpoint_parsed.set()
continue
if b"event: message" in chunk and b"structuredContent" in chunk:
sse_text = chunk.decode("utf-8")
json_str = sse_text.split("data: ")[1]
context["response"] = json.loads(json_str)
break
stream_complete.set()
task = asyncio.create_task(parse_stream())
await endpoint_parsed.wait()
await client.post(
f"/messages/?session_id={context['session_id']}",
headers={
"Content-Type": "application/json",
},
json={
"jsonrpc": "2.0",
"method": "initialize",
"params": {
"clientInfo": {"name": "test-client", "version": "1.0"},
"protocolVersion": "2025-11-25",
"capabilities": {},
},
"id": request_id,
},
)
# Notification response is mandatory.
# https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle
await client.post(
f"/messages/?session_id={context['session_id']}",
headers={
"Content-Type": "application/json",
"mcp-session-id": context["session_id"],
},
json={
"jsonrpc": "2.0",
"method": "notifications/initialized",
"params": {},
},
)
await client.post(
f"/messages/?session_id={context['session_id']}",
headers={
"Content-Type": "application/json",
"mcp-session-id": context["session_id"],
},
json={
"jsonrpc": "2.0",
"method": method,
"params": params,
"id": request_id,
},
)
await stream_complete.wait()
keep_sse_alive.set()
return task, context["session_id"], context["response"]
def test_integration_patches_server(sentry_init):
"""Test that MCPIntegration patches the Server class"""
# Get original methods before integration
original_call_tool = Server.call_tool
original_get_prompt = Server.get_prompt
original_read_resource = Server.read_resource
sentry_init(
integrations=[MCPIntegration()],
traces_sample_rate=1.0,
)
# After initialization, the methods should be patched
assert Server.call_tool is not original_call_tool
assert Server.get_prompt is not original_get_prompt
assert Server.read_resource is not original_read_resource
@pytest.mark.asyncio
@pytest.mark.parametrize(
"send_default_pii, include_prompts",
[(True, True), (True, False), (False, True), (False, False)],
)
async def test_tool_handler_stdio(
sentry_init, capture_events, send_default_pii, include_prompts, stdio
):
"""Test that synchronous tool handlers create proper spans"""
sentry_init(
integrations=[MCPIntegration(include_prompts=include_prompts)],
traces_sample_rate=1.0,
send_default_pii=send_default_pii,
)
events = capture_events()
server = Server("test-server")
@server.call_tool()
async def test_tool(tool_name, arguments):
return {"result": "success", "value": 42}
with start_transaction(name="mcp tx"):
result = await stdio(
server,
method="tools/call",
params={
"name": "calculate",
"arguments": {"x": 10, "y": 5},
},
request_id="req-123",
)
assert result.message.root.result["content"][0]["text"] == json.dumps(
{"result": "success", "value": 42},
indent=2,
)
(tx,) = events
assert tx["type"] == "transaction"
assert len(tx["spans"]) == 1
span = tx["spans"][0]
assert span["op"] == OP.MCP_SERVER
assert span["description"] == "tools/call calculate"
assert span["origin"] == "auto.ai.mcp"
# Check span data
assert span["data"][SPANDATA.MCP_TOOL_NAME] == "calculate"
assert span["data"][SPANDATA.MCP_METHOD_NAME] == "tools/call"
assert span["data"][SPANDATA.MCP_TRANSPORT] == "stdio"
assert span["data"][SPANDATA.MCP_REQUEST_ID] == "req-123"
assert span["data"]["mcp.request.argument.x"] == "10"
assert span["data"]["mcp.request.argument.y"] == "5"
# Check PII-sensitive data is only present when both flags are True
if send_default_pii and include_prompts:
assert span["data"][SPANDATA.MCP_TOOL_RESULT_CONTENT] == json.dumps(
{
"result": "success",
"value": 42,
}
)
assert span["data"][SPANDATA.MCP_TOOL_RESULT_CONTENT_COUNT] == 2
else:
assert SPANDATA.MCP_TOOL_RESULT_CONTENT not in span["data"]
assert SPANDATA.MCP_TOOL_RESULT_CONTENT_COUNT not in span["data"]
@pytest.mark.asyncio
@pytest.mark.parametrize(
"send_default_pii, include_prompts",
[(True, True), (True, False), (False, True), (False, False)],
)
async def test_tool_handler_streamable_http(
sentry_init,
capture_events,
send_default_pii,
include_prompts,
json_rpc,
select_mcp_transactions,
):
"""Test that async tool handlers create proper spans"""
sentry_init(
integrations=[MCPIntegration(include_prompts=include_prompts)],
traces_sample_rate=1.0,
send_default_pii=send_default_pii,
)
events = capture_events()
server = Server("test-server")
session_manager = StreamableHTTPSessionManager(
app=server,
json_response=True,
)
app = Starlette(
routes=[
Mount("/mcp", app=session_manager.handle_request),
],
lifespan=lambda app: session_manager.run(),
)
@server.call_tool()
async def test_tool_async(tool_name, arguments):
return [
TextContent(
type="text",
text=json.dumps({"status": "completed"}),
)
]
session_id, result = json_rpc(
app,
method="tools/call",
params={
"name": "process",
"arguments": {
"data": "test",
},
},
request_id="req-456",
)
assert result.json()["result"]["content"][0]["text"] == json.dumps(
{"status": "completed"}
)
transactions = select_mcp_transactions(events)
assert len(transactions) == 1
tx = transactions[0]
assert tx["type"] == "transaction"
assert tx["contexts"]["trace"]["op"] == OP.MCP_SERVER
assert tx["transaction"] == "tools/call process"
assert tx["contexts"]["trace"]["origin"] == "auto.ai.mcp"
# Check span data
assert tx["contexts"]["trace"]["data"][SPANDATA.MCP_TOOL_NAME] == "process"
assert tx["contexts"]["trace"]["data"][SPANDATA.MCP_METHOD_NAME] == "tools/call"
assert tx["contexts"]["trace"]["data"][SPANDATA.MCP_TRANSPORT] == "http"
assert tx["contexts"]["trace"]["data"][SPANDATA.MCP_REQUEST_ID] == "req-456"
assert tx["contexts"]["trace"]["data"][SPANDATA.MCP_SESSION_ID] == session_id
assert tx["contexts"]["trace"]["data"]["mcp.request.argument.data"] == '"test"'
# Check PII-sensitive data
if send_default_pii and include_prompts:
# TODO: Investigate why tool result is double-serialized.
assert tx["contexts"]["trace"]["data"][
SPANDATA.MCP_TOOL_RESULT_CONTENT
] == json.dumps(
json.dumps(
{"status": "completed"},
)
)
else:
assert SPANDATA.MCP_TOOL_RESULT_CONTENT not in tx["contexts"]["trace"]["data"]
@pytest.mark.asyncio
async def test_tool_handler_with_error(sentry_init, capture_events, stdio):
"""Test that tool handler errors are captured properly"""
sentry_init(
integrations=[MCPIntegration()],
traces_sample_rate=1.0,
)
events = capture_events()
server = Server("test-server")
@server.call_tool()
def failing_tool(tool_name, arguments):
raise ValueError("Tool execution failed")
with start_transaction(name="mcp tx"):
result = await stdio(
server,
method="tools/call",
params={
"name": "bad_tool",
"arguments": {},
},
request_id="req-error",
)
assert (
result.message.root.result["content"][0]["text"] == "Tool execution failed"
)
# Should have error event and transaction
assert len(events) == 2
error_event, tx = events
# Check error event
assert error_event["level"] == "error"
assert error_event["exception"]["values"][0]["type"] == "ValueError"
assert error_event["exception"]["values"][0]["value"] == "Tool execution failed"
# Check transaction and span
assert tx["type"] == "transaction"
assert len(tx["spans"]) == 1
span = tx["spans"][0]
# Error flag should be set for tools
assert span["data"][SPANDATA.MCP_TOOL_RESULT_IS_ERROR] is True
assert span["status"] == "internal_error"
assert span["tags"]["status"] == "internal_error"
@pytest.mark.asyncio
@pytest.mark.parametrize(
"send_default_pii, include_prompts",
[(True, True), (True, False), (False, True), (False, False)],
)
async def test_prompt_handler_stdio(
sentry_init, capture_events, send_default_pii, include_prompts, stdio
):
"""Test that synchronous prompt handlers create proper spans"""
sentry_init(
integrations=[MCPIntegration(include_prompts=include_prompts)],
traces_sample_rate=1.0,
send_default_pii=send_default_pii,
)
events = capture_events()
server = Server("test-server")
@server.get_prompt()
async def test_prompt(name, arguments):
return GetPromptResult(
description="A helpful test prompt",
messages=[
PromptMessage(
role="user",
content=TextContent(type="text", text="Tell me about Python"),
),
],
)
with start_transaction(name="mcp tx"):
result = await stdio(
server,
method="prompts/get",
params={
"name": "code_help",
"arguments": {"language": "python"},
},
request_id="req-prompt",
)
assert result.message.root.result["messages"][0]["role"] == "user"
assert (
result.message.root.result["messages"][0]["content"]["text"]
== "Tell me about Python"
)
(tx,) = events
assert tx["type"] == "transaction"
assert len(tx["spans"]) == 1
span = tx["spans"][0]
assert span["op"] == OP.MCP_SERVER
assert span["description"] == "prompts/get code_help"
assert span["origin"] == "auto.ai.mcp"
# Check span data
assert span["data"][SPANDATA.MCP_PROMPT_NAME] == "code_help"
assert span["data"][SPANDATA.MCP_METHOD_NAME] == "prompts/get"
assert span["data"][SPANDATA.MCP_TRANSPORT] == "stdio"
assert span["data"][SPANDATA.MCP_REQUEST_ID] == "req-prompt"
assert span["data"]["mcp.request.argument.name"] == '"code_help"'
assert span["data"]["mcp.request.argument.language"] == '"python"'
# Message count is always captured
assert span["data"][SPANDATA.MCP_PROMPT_RESULT_MESSAGE_COUNT] == 1
# For single message prompts, role and content should be captured only with PII
if send_default_pii and include_prompts:
assert span["data"][SPANDATA.MCP_PROMPT_RESULT_MESSAGE_ROLE] == "user"
assert (
span["data"][SPANDATA.MCP_PROMPT_RESULT_MESSAGE_CONTENT]
== "Tell me about Python"
)
else:
assert SPANDATA.MCP_PROMPT_RESULT_MESSAGE_ROLE not in span["data"]
assert SPANDATA.MCP_PROMPT_RESULT_MESSAGE_CONTENT not in span["data"]
@pytest.mark.asyncio
@pytest.mark.parametrize(
"send_default_pii, include_prompts",
[(True, True), (True, False), (False, True), (False, False)],
)
async def test_prompt_handler_streamable_http(
sentry_init,
capture_events,
send_default_pii,
include_prompts,
json_rpc,
select_mcp_transactions,
):
"""Test that async prompt handlers create proper spans"""
sentry_init(
integrations=[MCPIntegration(include_prompts=include_prompts)],
traces_sample_rate=1.0,
send_default_pii=send_default_pii,
)
events = capture_events()
server = Server("test-server")
session_manager = StreamableHTTPSessionManager(
app=server,
json_response=True,
)
app = Starlette(
routes=[
Mount("/mcp", app=session_manager.handle_request),
],
lifespan=lambda app: session_manager.run(),
)
@server.get_prompt()
async def test_prompt_async(name, arguments):
return GetPromptResult(
description="A helpful test prompt",
messages=[
PromptMessage(
role="user",
content=TextContent(
type="text", text="You are a helpful assistant"
),
),
PromptMessage(
role="user", content=TextContent(type="text", text="What is MCP?")
),
],
)
_, result = json_rpc(
app,
method="prompts/get",
params={
"name": "mcp_info",
"arguments": {},
},
request_id="req-async-prompt",
)
assert len(result.json()["result"]["messages"]) == 2
transactions = select_mcp_transactions(events)
assert len(transactions) == 1
tx = transactions[0]
assert tx["type"] == "transaction"
assert tx["contexts"]["trace"]["op"] == OP.MCP_SERVER
assert tx["transaction"] == "prompts/get mcp_info"
# For multi-message prompts, count is always captured
assert (
tx["contexts"]["trace"]["data"][SPANDATA.MCP_PROMPT_RESULT_MESSAGE_COUNT] == 2
)
# Role/content are never captured for multi-message prompts (even with PII)
assert (
SPANDATA.MCP_PROMPT_RESULT_MESSAGE_ROLE not in tx["contexts"]["trace"]["data"]
)
assert (
SPANDATA.MCP_PROMPT_RESULT_MESSAGE_CONTENT
not in tx["contexts"]["trace"]["data"]
)
@pytest.mark.asyncio
async def test_prompt_handler_with_error(sentry_init, capture_events, stdio):
"""Test that prompt handler errors are captured"""
sentry_init(
integrations=[MCPIntegration()],
traces_sample_rate=1.0,
)
events = capture_events()
server = Server("test-server")
@server.get_prompt()
async def failing_prompt(name, arguments):
raise RuntimeError("Prompt not found")
with start_transaction(name="mcp tx"):
response = await stdio(
server,
method="prompts/get",
params={
"name": "code_help",
"arguments": {"language": "python"},
},
request_id="req-error-prompt",
)
assert response.message.root.error.message == "Prompt not found"
# Should have error event and transaction
assert len(events) == 2
error_event, tx = events
assert error_event["level"] == "error"
assert error_event["exception"]["values"][0]["type"] == "RuntimeError"
@pytest.mark.asyncio
async def test_resource_handler_stdio(sentry_init, capture_events, stdio):
"""Test that synchronous resource handlers create proper spans"""
sentry_init(
integrations=[MCPIntegration()],
traces_sample_rate=1.0,
)
events = capture_events()
server = Server("test-server")
@server.read_resource()
async def test_resource(uri):
return [
ReadResourceContents(
content=json.dumps({"content": "file contents"}), mime_type="text/plain"
)
]
with start_transaction(name="mcp tx"):
result = await stdio(
server,
method="resources/read",
params={
"uri": "file:///path/to/file.txt",
},
request_id="req-resource",
)
assert result.message.root.result["contents"][0]["text"] == json.dumps(
{"content": "file contents"},
)
(tx,) = events
assert tx["type"] == "transaction"
assert len(tx["spans"]) == 1
span = tx["spans"][0]
assert span["op"] == OP.MCP_SERVER
assert span["description"] == "resources/read file:///path/to/file.txt"
assert span["origin"] == "auto.ai.mcp"
# Check span data
assert span["data"][SPANDATA.MCP_RESOURCE_URI] == "file:///path/to/file.txt"
assert span["data"][SPANDATA.MCP_METHOD_NAME] == "resources/read"
assert span["data"][SPANDATA.MCP_TRANSPORT] == "stdio"
assert span["data"][SPANDATA.MCP_REQUEST_ID] == "req-resource"
assert span["data"][SPANDATA.MCP_RESOURCE_PROTOCOL] == "file"
# Resources don't capture result content
assert SPANDATA.MCP_TOOL_RESULT_CONTENT not in span["data"]
@pytest.mark.asyncio
async def test_resource_handler_streamble_http(
sentry_init,
capture_events,
json_rpc,
select_mcp_transactions,
):
"""Test that async resource handlers create proper spans"""
sentry_init(
integrations=[MCPIntegration()],
traces_sample_rate=1.0,
)
events = capture_events()
server = Server("test-server")
session_manager = StreamableHTTPSessionManager(
app=server,
json_response=True,
)
app = Starlette(
routes=[
Mount("/mcp", app=session_manager.handle_request),
],
lifespan=lambda app: session_manager.run(),
)
@server.read_resource()
async def test_resource_async(uri):
return [
ReadResourceContents(
content=json.dumps({"data": "resource data"}), mime_type="text/plain"
)
]
session_id, result = json_rpc(
app,
method="resources/read",
params={
"uri": "https://example.com/resource",
},
request_id="req-async-resource",
)
assert result.json()["result"]["contents"][0]["text"] == json.dumps(
{"data": "resource data"}
)
transactions = select_mcp_transactions(events)
assert len(transactions) == 1
tx = transactions[0]
assert tx["type"] == "transaction"
assert tx["contexts"]["trace"]["op"] == OP.MCP_SERVER
assert tx["transaction"] == "resources/read https://example.com/resource"
assert (
tx["contexts"]["trace"]["data"][SPANDATA.MCP_RESOURCE_URI]
== "https://example.com/resource"
)
assert tx["contexts"]["trace"]["data"][SPANDATA.MCP_RESOURCE_PROTOCOL] == "https"
assert tx["contexts"]["trace"]["data"][SPANDATA.MCP_SESSION_ID] == session_id
@pytest.mark.asyncio
async def test_resource_handler_with_error(sentry_init, capture_events, stdio):
"""Test that resource handler errors are captured"""
sentry_init(
integrations=[MCPIntegration()],
traces_sample_rate=1.0,
)
events = capture_events()
server = Server("test-server")
@server.read_resource()
def failing_resource(uri):
raise FileNotFoundError("Resource not found")
with start_transaction(name="mcp tx"):
await stdio(
server,
method="resources/read",
params={
"uri": "file:///missing.txt",
},
request_id="req-error-resource",
)
# Should have error event and transaction
assert len(events) == 2
error_event, tx = events
assert error_event["level"] == "error"
assert error_event["exception"]["values"][0]["type"] == "FileNotFoundError"
@pytest.mark.asyncio
@pytest.mark.parametrize(
"send_default_pii, include_prompts",
[(True, True), (False, False)],
)
async def test_tool_result_extraction_tuple(
sentry_init, capture_events, send_default_pii, include_prompts, stdio
):
"""Test extraction of tool results from tuple format (UnstructuredContent, StructuredContent)"""
sentry_init(
integrations=[MCPIntegration(include_prompts=include_prompts)],
traces_sample_rate=1.0,
send_default_pii=send_default_pii,
)
events = capture_events()
server = Server("test-server")
@server.call_tool()
def test_tool_tuple(tool_name, arguments):
# Return CombinationContent: (UnstructuredContent, StructuredContent)
unstructured = [MockTextContent("Result text")]
structured = {"key": "value", "count": 5}
return (unstructured, structured)
with start_transaction(name="mcp tx"):
await stdio(
server,
method="tools/call",
params={
"name": "calculate",
"arguments": {},
},
request_id="req-tuple",
)
(tx,) = events
span = tx["spans"][0]
# Should extract the structured content (second element of tuple) only with PII
if send_default_pii and include_prompts:
assert span["data"][SPANDATA.MCP_TOOL_RESULT_CONTENT] == json.dumps(
{
"key": "value",
"count": 5,
}
)
assert span["data"][SPANDATA.MCP_TOOL_RESULT_CONTENT_COUNT] == 2
else:
assert SPANDATA.MCP_TOOL_RESULT_CONTENT not in span["data"]
assert SPANDATA.MCP_TOOL_RESULT_CONTENT_COUNT not in span["data"]
@pytest.mark.asyncio
@pytest.mark.parametrize(
"send_default_pii, include_prompts",
[(True, True), (False, False)],
)
async def test_tool_result_extraction_unstructured(
sentry_init, capture_events, send_default_pii, include_prompts, stdio
):
"""Test extraction of tool results from UnstructuredContent (list of content blocks)"""
sentry_init(
integrations=[MCPIntegration(include_prompts=include_prompts)],
traces_sample_rate=1.0,
send_default_pii=send_default_pii,
)
events = capture_events()
server = Server("test-server")
@server.call_tool()
def test_tool_unstructured(tool_name, arguments):
# Return UnstructuredContent as list of content blocks
return [
MockTextContent("First part"),
MockTextContent("Second part"),
]
with start_transaction(name="mcp tx"):
await stdio(
server,
method="tools/call",
params={
"name": "text_tool",
"arguments": {},
},
request_id="req-unstructured",
)
(tx,) = events
span = tx["spans"][0]
# Should extract and join text from content blocks only with PII
if send_default_pii and include_prompts:
assert (
span["data"][SPANDATA.MCP_TOOL_RESULT_CONTENT] == '"First part Second part"'
)
else:
assert SPANDATA.MCP_TOOL_RESULT_CONTENT not in span["data"]
@pytest.mark.asyncio
async def test_span_origin(sentry_init, capture_events, stdio):
"""Test that span origin is set correctly"""
sentry_init(
integrations=[MCPIntegration()],
traces_sample_rate=1.0,
)
events = capture_events()
server = Server("test-server")
@server.call_tool()
def test_tool(tool_name, arguments):
return {"result": "test"}
with start_transaction(name="mcp tx"):
await stdio(
server,
method="tools/call",
params={
"name": "calculate",
"arguments": {"x": 10, "y": 5},
},
request_id="req-origin",
)
(tx,) = events
assert tx["contexts"]["trace"]["origin"] == "manual"
assert tx["spans"][0]["origin"] == "auto.ai.mcp"
@pytest.mark.asyncio
async def test_multiple_handlers(sentry_init, capture_events, stdio):
"""Test that multiple handler calls create multiple spans"""
sentry_init(
integrations=[MCPIntegration()],
traces_sample_rate=1.0,
)
events = capture_events()
server = Server("test-server")
@server.call_tool()
def tool1(tool_name, arguments):
return {"result": "tool1"}
@server.call_tool()
def tool2(tool_name, arguments):
return {"result": "tool2"}
@server.get_prompt()
def prompt1(name, arguments):
return GetPromptResult(
description="A test prompt",
messages=[
PromptMessage(
role="user", content=TextContent(type="text", text="Test prompt")
)
],
)
with start_transaction(name="mcp tx"):
await stdio(
server,
method="tools/call",
params={
"name": "tool_a",
"arguments": {},
},
request_id="req-multi",
)
await stdio(
server,
method="tools/call",
params={
"name": "tool_b",
"arguments": {},
},
request_id="req-multi",
)
await stdio(
server,
method="prompts/get",
params={
"name": "prompt_a",
"arguments": {},
},
request_id="req-multi",
)
(tx,) = events
assert tx["type"] == "transaction"
assert len(tx["spans"]) == 3
# Check that we have different span types
span_ops = [span["op"] for span in tx["spans"]]
assert all(op == OP.MCP_SERVER for op in span_ops)
span_descriptions = [span["description"] for span in tx["spans"]]
assert "tools/call tool_a" in span_descriptions
assert "tools/call tool_b" in span_descriptions
assert "prompts/get prompt_a" in span_descriptions
@pytest.mark.asyncio
@pytest.mark.parametrize(
"send_default_pii, include_prompts",
[(True, True), (False, False)],
)
async def test_prompt_with_dict_result(
sentry_init, capture_events, send_default_pii, include_prompts, stdio
):
"""Test prompt handler with dict result instead of GetPromptResult object"""
sentry_init(
integrations=[MCPIntegration(include_prompts=include_prompts)],