Repository navigation
Expand file tree
/
Copy pathtest_protocol.py
More file actions
1375 lines (1192 loc) · 51.6 KB
/
Copy pathtest_protocol.py
File metadata and controls
1375 lines (1192 loc) · 51.6 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
"""Characterization tests that drive ``serve()`` through the MCP protocol.
Every test here runs the real server in-process (see ``harness.connect``) and
talks to it with an SDK ``ClientSession``, so what is asserted is what a client
receives on the wire. Results are compared as wire JSON
(``model_dump(by_alias=True, mode="json")``) where practical, so the
assertions survive an SDK migration that renames Python attributes.
HTTP is served by ``harness.FakeWeb``; nothing here touches the network.
Tests marked "Characterizes" pin current behavior that an open issue asks to
change. They are meant to be updated by the PR that fixes that issue, not
read as an endorsement of the behavior.
"""
from __future__ import annotations
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from importlib.metadata import version
from typing import Any
from unittest.mock import patch
import anyio
import httpx
import pytest
from mcp import ClientSession
from mcp.shared.exceptions import MCPError
from mcp.shared.memory import create_client_server_memory_streams
from mcp.shared.message import SessionMessage
from mcp.types import INVALID_PARAMS, CallToolResult, JSONRPCError, JSONRPCRequest
from mcp_server_fetch.server import (
DEFAULT_USER_AGENT_AUTONOMOUS,
DEFAULT_USER_AGENT_MANUAL,
serve,
)
from .harness import PUBLIC_IP, FakeWeb, connect, raw_request
PAGE = "https://example.com/page"
ROBOTS = "https://example.com/robots.txt"
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
RAW_PREFIX_PLAIN = (
"Content type text/plain cannot be simplified to markdown, "
"but here is the raw content:\n"
)
ARTICLE_HTML = """<html><head><title>Test Page</title></head><body>
<article>
<h1>Hello World</h1>
<p>This is a <a href="https://example.com/x">link</a> in a test paragraph
with enough words to count as the main content of the page.</p>
<h2>Sub heading</h2>
<p>More text here.</p>
</article>
</body></html>"""
def wire(model: Any) -> dict[str, Any]:
# exclude_unset: SDK v2 result models default fields the 2025-11-25 wire
# does not carry (resultType, ttlMs, cacheScope), so only what the server
# actually sent is compared.
return model.model_dump(
by_alias=True, mode="json", exclude_none=True, exclude_unset=True
)
def text_of(result: CallToolResult) -> str:
data = wire(result)
assert len(data["content"]) == 1
assert data["content"][0]["type"] == "text"
return data["content"][0]["text"]
def plain(body: str, status: int = 200) -> httpx.Response:
return httpx.Response(
status, content=body.encode(), headers={"content-type": "text/plain"}
)
def html(body: str) -> httpx.Response:
return httpx.Response(
200, content=body.encode(), headers={"content-type": "text/html"}
)
async def call(session: ClientSession, arguments: dict[str, Any]) -> CallToolResult:
return await session.call_tool("fetch", arguments)
# MCPServer prefixes the message of a ToolError the tool raises (#5174).
TOOL_ERROR = "Error executing tool fetch: "
# MCPServer answers prompts/get with the prompt's own description, the same
# for every call, so it no longer names the URL or the failure (#5174).
PROMPT_DESCRIPTION = "Fetch a URL and extract its contents as markdown"
# --------------------------------------------------------------------------
# Initialization
# --------------------------------------------------------------------------
async def test_initialize_advertises_tools_and_prompts(web: FakeWeb) -> None:
async with connect() as (_, init):
data = wire(init)
assert data["serverInfo"]["name"] == "mcp-fetch"
assert data["capabilities"]["tools"] == {"listChanged": False}
assert data["capabilities"]["prompts"] == {"listChanged": False}
# MCPServer always serves resources/list; fetch registers none (#5174).
assert data["capabilities"]["resources"] == {
"subscribe": False,
"listChanged": False,
}
async def test_resources_list_is_empty(web: FakeWeb) -> None:
async with connect() as (session, _):
result = await session.list_resources()
assert result.resources == []
async def test_server_version_is_the_package_version(web: FakeWeb) -> None:
# #360: serverInfo.version is this package's version (from pyproject.toml
# via the installed metadata), not the `mcp` SDK's.
async with connect() as (_, init):
data = wire(init)
assert data["serverInfo"]["version"] == version("mcp-server-fetch")
assert data["serverInfo"]["version"] != version("mcp")
# --------------------------------------------------------------------------
# tools/list
# --------------------------------------------------------------------------
async def test_list_tools_wire_shape(web: FakeWeb) -> None:
async with connect() as (session, _):
result = await session.list_tools()
tools = wire(result)["tools"]
assert [t["name"] for t in tools] == ["fetch"]
tool = tools[0]
assert tool["description"].startswith(
"Fetches a URL from the internet and optionally extracts its contents as markdown."
)
assert "this tool now grants you internet access" in tool["description"]
assert "outputSchema" not in tool
# #3572: the tool declares what it does, for clients' approval policies.
assert tool["annotations"] == {
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": True,
}
# MCPServer derives the schema from the tool function's signature (#5174),
# so the model is named after the tool and carries no description.
assert tool["inputSchema"] == {
"properties": {
"url": {
"description": "URL to fetch",
"format": "uri",
"minLength": 1,
"title": "Url",
"type": "string",
},
# #1624: inclusive minimum/maximum, never exclusiveMinimum/
# exclusiveMaximum, which some clients (Gemini) reject.
"max_length": {
"default": 5000,
"description": "Maximum number of characters to return.",
"maximum": 999999,
"minimum": 1,
"title": "Max Length",
"type": "integer",
},
"start_index": {
"default": 0,
"description": "On return output starting at this character index, useful if a previous fetch was truncated and more context is required.",
"minimum": 0,
"title": "Start Index",
"type": "integer",
},
"raw": {
"default": False,
"description": "Get the actual HTML content of the requested page, without simplification.",
"title": "Raw",
"type": "boolean",
},
# #4448: the server-wide timeout is the advertised default.
"timeout_ms": {
"default": 30000,
"description": "How long to wait, in milliseconds, to connect to the server and for each read of its response before giving up. Raise it for a slow server or a large download; lower it to fail fast.",
"maximum": 600000,
"minimum": 100,
"title": "Timeout Ms",
"type": "integer",
},
},
"required": ["url"],
"title": "fetchArguments",
"type": "object",
}
# --------------------------------------------------------------------------
# tools/call: arguments and validation
# --------------------------------------------------------------------------
async def test_call_with_only_url_applies_defaults(web: FakeWeb) -> None:
# #2035: only `url` is required; max_length, start_index and raw default.
web.add(ROBOTS, plain("", status=404))
web.add(PAGE, plain("hello"))
async with connect() as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result) == {
"content": [
{"type": "text", "text": f"{RAW_PREFIX_PLAIN}Contents of {PAGE}:\nhello"}
],
"isError": False,
}
@pytest.mark.parametrize(
("arguments", "field"),
[
({}, "url"),
({"url": ""}, "url"),
({"url": 5}, "url"),
# #1624: the bounds are minimum 1 and maximum 999999, so the rejected
# values are the same as under the old exclusive 0 and 1000000.
({"url": PAGE, "max_length": 0}, "max_length"),
({"url": PAGE, "max_length": 1000000}, "max_length"),
({"url": PAGE, "start_index": -1}, "start_index"),
({"url": PAGE, "raw": "yes"}, "raw"),
# Strict: a string is not coerced to the integer or boolean the
# schema declares.
({"url": PAGE, "max_length": "10"}, "max_length"),
({"url": PAGE, "raw": "true"}, "raw"),
],
)
async def test_schema_violations_are_rejected_by_call_tool(
web: FakeWeb, arguments: dict[str, Any], field: str
) -> None:
# MCPServer validates the arguments against the tool's signature before
# the tool runs and returns pydantic's report as an isError result, naming
# the field. The rest is pydantic's wording, which varies by version.
async with connect() as (session, _):
result = await call(session, arguments)
assert wire(result)["isError"] is True
text = text_of(result)
assert text.startswith(
f"{TOOL_ERROR}1 validation error for fetchArguments\n{field}\n"
)
assert web.requests == []
@pytest.mark.parametrize("max_length", [1, 999999])
async def test_max_length_bounds_are_inclusive(web: FakeWeb, max_length: int) -> None:
# #1624: the edges of the inclusive range pass both the schema check
# and Fetch's own validation, and the page is fetched.
web.add(ROBOTS, plain("", status=404))
web.add(PAGE, plain("hello"))
async with connect() as (session, _):
result = await call(session, {"url": PAGE, "max_length": max_length})
assert wire(result)["isError"] is False
assert web.urls() == [ROBOTS, PAGE]
@pytest.mark.parametrize("url", ["not a url", "example.com/page", "http://"])
async def test_invalid_url_is_rejected_by_pydantic(web: FakeWeb, url: str) -> None:
# The `url` parameter is an AnyUrl, so pydantic rejects these before the
# tool runs, as an isError result.
async with connect() as (session, _):
result = await call(session, {"url": url})
assert wire(result)["isError"] is True
assert text_of(result).startswith(
f"{TOOL_ERROR}1 validation error for fetchArguments\nurl\n"
)
assert web.requests == []
async def test_unknown_tool_name_is_a_jsonrpc_error(web: FakeWeb) -> None:
# Both spec revisions make an unknown tool a protocol error, -32602
# (#5174); nothing is fetched.
web.add(ROBOTS, plain("", status=404))
web.add(PAGE, plain("fetched anyway"))
async with connect() as (session, _):
with pytest.raises(MCPError) as excinfo:
await session.call_tool("nope", {"url": PAGE})
assert wire(excinfo.value.error) == {
"code": INVALID_PARAMS,
"message": "Unknown tool: nope",
}
assert web.requests == []
@pytest.mark.parametrize(
("method", "params"),
[
("tools/call", {"name": [], "arguments": {}}),
("tools/call", {"name": {}, "arguments": {}}),
("prompts/get", {"name": [], "arguments": {}}),
("prompts/get", {"name": "fetch", "arguments": 1}),
],
ids=[
"tool-name-list",
"tool-name-object",
"prompt-name-list",
"prompt-arguments-number",
],
)
async def test_malformed_request_is_invalid_params_not_an_internal_error(
web: FakeWeb, method: str, params: dict[str, Any]
) -> None:
# #5175 review: the unknown-name middleware sees raw params, so it leaves
# a non-string name or non-mapping arguments to the SDK's validation,
# which answers -32602, instead of failing on them with -32603.
response = await raw_request(method, params)
assert isinstance(response, JSONRPCError), response
assert response.error.code == INVALID_PARAMS
assert web.requests == []
async def test_unknown_tool_name_is_rejected_before_argument_validation(
web: FakeWeb,
) -> None:
# An unknown name is reported as such, not as a missing `url` argument.
async with connect() as (session, _):
with pytest.raises(MCPError) as excinfo:
await session.call_tool("nope", {})
assert excinfo.value.error.code == INVALID_PARAMS
assert excinfo.value.error.message == "Unknown tool: nope"
assert web.requests == []
# --------------------------------------------------------------------------
# tools/call: robots.txt
# --------------------------------------------------------------------------
@pytest.mark.parametrize("status", [404, 410, 400, 499])
async def test_robots_4xx_other_than_401_403_allows_fetch(
web: FakeWeb, status: int
) -> None:
web.add(ROBOTS, plain("User-agent: *\nDisallow: /", status=status))
web.add(PAGE, plain("ok"))
async with connect() as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result)["isError"] is False
assert text_of(result).endswith("ok")
@pytest.mark.parametrize("status", [401, 403])
async def test_robots_401_403_blocks_fetch(web: FakeWeb, status: int) -> None:
web.add(ROBOTS, plain("", status=status))
async with connect() as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result) == {
"content": [
{
"type": "text",
"text": f"{TOOL_ERROR}When fetching robots.txt ({ROBOTS}), received status {status} "
"so assuming that autonomous fetching is not allowed, the user can "
"try manually fetching by using the fetch prompt",
}
],
"isError": True,
}
assert web.urls() == [ROBOTS]
async def test_robots_connection_failure_blocks_fetch(web: FakeWeb) -> None:
def refuse(request: httpx.Request) -> httpx.Response:
raise httpx.ConnectError("connection refused", request=request)
web.add(ROBOTS, refuse)
async with connect() as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result) == {
"content": [
{
"type": "text",
"text": f"{TOOL_ERROR}Failed to fetch robots.txt {ROBOTS} due to a connection issue",
}
],
"isError": True,
}
assert web.urls() == [ROBOTS]
async def test_robots_disallow_blocks_fetch(web: FakeWeb) -> None:
robots = "User-agent: *\nDisallow: /"
web.add(ROBOTS, plain(robots))
async with connect() as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result)["isError"] is True
assert text_of(result) == (
f"{TOOL_ERROR}The sites robots.txt ({ROBOTS}), specifies that autonomous fetching of this page is not allowed, "
f"<useragent>{DEFAULT_USER_AGENT_AUTONOMOUS}</useragent>\n"
f"<url>{PAGE}</url>"
f"<robots>\n{robots}\n</robots>\n"
"The assistant must let the user know that it failed to view the page. "
"The assistant may provide further guidance based on the above information.\n"
"The assistant can tell the user that they can try manually fetching the page "
"by using the fetch prompt within their UI."
)
assert web.urls() == [ROBOTS]
async def test_robots_allow_then_fetches_page(web: FakeWeb) -> None:
web.add(ROBOTS, plain("User-agent: *\nDisallow: /private"))
web.add(PAGE, plain("public"))
async with connect() as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result)["isError"] is False
assert web.urls() == [ROBOTS, PAGE]
for request in web.requests:
assert request.headers["user-agent"] == DEFAULT_USER_AGENT_AUTONOMOUS
async def test_robots_comment_lines_are_ignored(web: FakeWeb) -> None:
web.add(ROBOTS, plain("# User-agent: *\n# Disallow: /\nUser-agent: *\nAllow: /"))
web.add(PAGE, plain("ok"))
async with connect() as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result)["isError"] is False
async def test_robots_redirect_is_followed(web: FakeWeb) -> None:
web.add(
ROBOTS,
httpx.Response(301, headers={"location": "https://www.example.com/robots.txt"}),
)
web.add("https://www.example.com/robots.txt", plain("User-agent: *\nDisallow: /"))
async with connect() as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result)["isError"] is True
assert web.urls() == [ROBOTS, "https://www.example.com/robots.txt"]
async def test_robots_rules_match_the_custom_user_agent(web: FakeWeb) -> None:
web.add(ROBOTS, plain("User-agent: MyBot\nDisallow: /\n\nUser-agent: *\nAllow: /"))
async with connect(custom_user_agent="MyBot") as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result)["isError"] is True
assert "<useragent>MyBot</useragent>" in text_of(result)
assert web.requests[0].headers["user-agent"] == "MyBot"
async def test_ignore_robots_txt_skips_the_check(web: FakeWeb) -> None:
web.add(ROBOTS, plain("User-agent: *\nDisallow: /"))
web.add(PAGE, plain("ok"))
async with connect(ignore_robots_txt=True) as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result)["isError"] is False
assert web.urls() == [PAGE]
PRIVATE_ROBOTS = "User-agent: *\nDisallow: /private"
@pytest.mark.parametrize(
"path",
[
# An origin that merges slashes, decodes %2F, or removes dot segments
# serves /private for each of these spellings.
"//private",
"///private",
"/./private",
"/x/../private",
"/%2Fprivate",
"/%2fprivate",
"/a%2f..%2fprivate",
"/%2e/private",
"/x/%2E%2E/private",
"//private//report",
],
)
async def test_robots_disallow_matches_the_resolved_path(
web: FakeWeb, path: str
) -> None:
url = f"https://example.com{path}"
web.add(ROBOTS, plain(PRIVATE_ROBOTS))
web.add(url, plain("private-page"))
async with connect() as (session, _):
result = await call(session, {"url": url})
assert wire(result)["isError"] is True
text = text_of(result)
assert text.startswith(
f"{TOOL_ERROR}The sites robots.txt ({ROBOTS}), specifies that "
"autonomous fetching of this page is not allowed, "
)
assert "private-page" not in text
assert web.urls() == [ROBOTS]
@pytest.mark.parametrize(
"location",
[
"/%2e%2e/private",
"/%2E/private",
"/x/..%2Fprivate",
"/x/%2e%2e//private",
"/x//%2e%2e/private",
],
)
async def test_redirect_to_a_disallowed_path_spelled_otherwise_is_refused(
web: FakeWeb, location: str
) -> None:
web.add(ROBOTS, plain(PRIVATE_ROBOTS))
web.add(PAGE, httpx.Response(302, headers={"location": location}))
web.add(f"https://example.com{location}", plain("private-page"))
async with connect() as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result)["isError"] is True
assert "private-page" not in text_of(result)
assert web.urls() == [ROBOTS, PAGE, ROBOTS]
@pytest.mark.parametrize(
"path",
[
# Resolving never widens a rule: these resolve to allowed paths.
"//public",
"/%2Fpublic",
# Only separator and dot escapes are decoded; %20 stays as it is.
"/pri%20vate",
# Matching stays case-sensitive (RFC 9309 2.2.2).
"//Private",
],
)
async def test_robots_allows_a_path_that_resolves_outside_the_rule(
web: FakeWeb, path: str
) -> None:
url = f"https://example.com{path}"
web.add(ROBOTS, plain(PRIVATE_ROBOTS))
web.add(url, plain("public-page"))
async with connect() as (session, _):
result = await call(session, {"url": url})
assert wire(result)["isError"] is False
assert "public-page" in text_of(result)
assert web.urls() == [ROBOTS, url]
async def test_robots_disallow_still_matches_the_literal_spelling(
web: FakeWeb,
) -> None:
# A rule written for the unresolved spelling still refuses it, though the
# path resolves somewhere the rule does not cover. A redirect carries the
# spelling as it is; a tool argument would have its dots resolved first.
location = "/a/%2e%2e/public"
web.add(ROBOTS, plain("User-agent: *\nDisallow: /a/"))
web.add(PAGE, httpx.Response(302, headers={"location": location}))
web.add(f"https://example.com{location}", plain("public-page"))
async with connect() as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result)["isError"] is True
assert web.urls() == [ROBOTS, PAGE, ROBOTS]
OTHER_ROBOTS = "https://other.example.org/robots.txt"
OTHER_PAGE = "https://other.example.org/secret"
async def test_redirect_to_host_whose_robots_disallows_is_refused(
web: FakeWeb,
) -> None:
# robots.txt belongs to one origin, so a redirect to another host is
# checked against that host's robots.txt before it is requested.
other_robots = "User-agent: *\nDisallow: /"
web.add(ROBOTS, plain("", status=404))
web.add(PAGE, httpx.Response(302, headers={"location": OTHER_PAGE}))
web.add(OTHER_ROBOTS, plain(other_robots))
web.add(OTHER_PAGE, plain("other-secret"))
async with connect() as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result)["isError"] is True
text = text_of(result)
assert text.startswith(
f"{TOOL_ERROR}The sites robots.txt ({OTHER_ROBOTS}), specifies that "
"autonomous fetching of this page is not allowed, "
)
assert f"<url>{OTHER_PAGE}</url>" in text
assert "other-secret" not in text
# The redirect target itself is never requested.
assert web.urls() == [ROBOTS, PAGE, OTHER_ROBOTS]
async def test_redirect_to_a_disallowed_path_on_the_same_host_is_refused(
web: FakeWeb,
) -> None:
private = "https://example.com/private/report"
web.add(ROBOTS, plain("User-agent: *\nDisallow: /private"))
web.add(PAGE, httpx.Response(302, headers={"location": "/private/report"}))
web.add(private, plain("private-report"))
async with connect() as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result)["isError"] is True
assert f"<url>{private}</url>" in text_of(result)
assert web.urls() == [ROBOTS, PAGE, ROBOTS]
async def test_redirect_to_host_answering_robots_403_is_refused(
web: FakeWeb,
) -> None:
web.add(ROBOTS, plain("", status=404))
web.add(PAGE, httpx.Response(302, headers={"location": OTHER_PAGE}))
web.add(OTHER_ROBOTS, plain("", status=403))
web.add(OTHER_PAGE, plain("other-secret"))
async with connect() as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result)["isError"] is True
assert text_of(result).startswith(
f"{TOOL_ERROR}When fetching robots.txt ({OTHER_ROBOTS}), received status 403"
)
assert web.urls() == [ROBOTS, PAGE, OTHER_ROBOTS]
async def test_redirect_to_an_allowed_target_is_followed(web: FakeWeb) -> None:
web.add(ROBOTS, plain("", status=404))
web.add(PAGE, httpx.Response(302, headers={"location": OTHER_PAGE}))
web.add(OTHER_ROBOTS, plain("User-agent: *\nDisallow: /private"))
web.add(OTHER_PAGE, plain("other-page"))
async with connect() as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result)["isError"] is False
assert text_of(result) == f"{RAW_PREFIX_PLAIN}Contents of {PAGE}:\nother-page"
assert web.urls() == [ROBOTS, PAGE, OTHER_ROBOTS, OTHER_PAGE]
for request in web.requests:
assert request.headers["user-agent"] == DEFAULT_USER_AGENT_AUTONOMOUS
async def test_redirects_skip_robots_with_ignore_robots_txt_and_on_the_prompt(
web: FakeWeb,
) -> None:
# --ignore-robots-txt and the user-initiated prompt never consult
# robots.txt, for the requested URL or for any redirect hop.
web.add(ROBOTS, plain("User-agent: *\nDisallow: /"))
web.add(PAGE, httpx.Response(302, headers={"location": OTHER_PAGE}))
web.add(OTHER_ROBOTS, plain("User-agent: *\nDisallow: /"))
web.add(OTHER_PAGE, plain("other-page"))
async with connect(ignore_robots_txt=True) as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result)["isError"] is False
assert web.urls() == [PAGE, OTHER_PAGE]
web.requests.clear()
async with connect() as (session, _):
prompt = await session.get_prompt("fetch", {"url": PAGE})
assert "other-page" in wire(prompt)["messages"][0]["content"]["text"]
assert web.urls() == [PAGE, OTHER_PAGE]
# --------------------------------------------------------------------------
# tools/call: fetching and content handling
# --------------------------------------------------------------------------
@pytest.mark.usefixtures("node_readability")
async def test_html_is_extracted_to_markdown(web: FakeWeb) -> None:
web.add(PAGE, html(ARTICLE_HTML))
async with connect(ignore_robots_txt=True) as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result)["isError"] is False
text = text_of(result)
assert text.startswith(f"Contents of {PAGE}:\n")
assert "[link](https://example.com/x)" in text
assert "## Sub heading" in text
assert "<article>" not in text
@pytest.mark.usefixtures("node_readability")
async def test_html_without_content_type_is_sniffed(web: FakeWeb) -> None:
web.add(PAGE, httpx.Response(200, content=ARTICLE_HTML.encode()))
async with connect(ignore_robots_txt=True) as (session, _):
result = await call(session, {"url": PAGE})
text = text_of(result)
assert text.startswith(f"Contents of {PAGE}:\n")
assert "[link](https://example.com/x)" in text
@pytest.mark.usefixtures("node_readability")
async def test_html_tag_in_body_overrides_content_type(web: FakeWeb) -> None:
web.add(
PAGE,
httpx.Response(
200,
content=ARTICLE_HTML.encode(),
headers={"content-type": "application/octet-stream"},
),
)
async with connect(ignore_robots_txt=True) as (session, _):
result = await call(session, {"url": PAGE})
text = text_of(result)
assert text.startswith(f"Contents of {PAGE}:\n")
assert "[link](https://example.com/x)" in text
@pytest.mark.usefixtures("node_readability")
async def test_html_that_cannot_be_simplified(web: FakeWeb) -> None:
web.add(PAGE, html("<html><body></body></html>"))
async with connect(ignore_robots_txt=True) as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result) == {
"content": [
{
"type": "text",
"text": f"Contents of {PAGE}:\n<error>Page failed to be simplified from HTML</error>",
}
],
"isError": False,
}
@pytest.mark.usefixtures("python_readability")
async def test_html_without_node_falls_back_to_pure_python(web: FakeWeb) -> None:
# Without Node, readabilipy's pure-Python extractor is used: headings
# survive but link targets are dropped.
web.add(PAGE, html(ARTICLE_HTML))
async with connect(ignore_robots_txt=True) as (session, _):
result = await call(session, {"url": PAGE})
text = text_of(result)
assert "## Sub heading" in text
assert "This is a link in a test paragraph" in text
assert "https://example.com/x" not in text
@pytest.mark.usefixtures("python_readability")
async def test_empty_html_without_node_cannot_be_simplified(web: FakeWeb) -> None:
# The pure-Python extractor returns "<div></div>" for an empty page, which
# converts to an empty string. It reports the same simplification failure
# as the Node path, not "No more content available" at start_index 0.
web.add(PAGE, html("<html><body></body></html>"))
async with connect(ignore_robots_txt=True) as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result) == {
"content": [
{
"type": "text",
"text": f"Contents of {PAGE}:\n<error>Page failed to be simplified from HTML</error>",
}
],
"isError": False,
}
async def test_raw_returns_html_unsimplified(web: FakeWeb) -> None:
web.add(PAGE, html(ARTICLE_HTML))
async with connect(ignore_robots_txt=True) as (session, _):
result = await call(session, {"url": PAGE, "raw": True})
assert text_of(result) == (
"Content type text/html cannot be simplified to markdown, but here is the raw content:\n"
f"Contents of {PAGE}:\n{ARTICLE_HTML}"
)
async def test_non_html_is_returned_raw_with_prefix(web: FakeWeb) -> None:
body = '{"key": "value"}'
web.add(
PAGE,
httpx.Response(
200, content=body.encode(), headers={"content-type": "application/json"}
),
)
async with connect(ignore_robots_txt=True) as (session, _):
result = await call(session, {"url": PAGE})
assert text_of(result) == (
"Content type application/json cannot be simplified to markdown, but here is the raw content:\n"
f"Contents of {PAGE}:\n{body}"
)
@pytest.mark.parametrize("status", [400, 404, 500, 503])
async def test_http_error_status(web: FakeWeb, status: int) -> None:
web.add(PAGE, plain("nope", status=status))
async with connect(ignore_robots_txt=True) as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result) == {
"content": [
{
"type": "text",
"text": f"{TOOL_ERROR}Failed to fetch {PAGE} - status code {status}",
}
],
"isError": True,
}
async def test_connection_error(web: FakeWeb) -> None:
def refuse(request: httpx.Request) -> httpx.Response:
raise httpx.ConnectError("connection refused", request=request)
web.add(PAGE, refuse)
async with connect(ignore_robots_txt=True) as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result) == {
"content": [
{
"type": "text",
"text": f"{TOOL_ERROR}Failed to fetch {PAGE}: ConnectError('connection refused')",
}
],
"isError": True,
}
async def test_url_is_normalized_by_pydantic(web: FakeWeb) -> None:
# AnyUrl normalizes the URL (here, adds a trailing slash to a bare host),
# and the normalized form is what is fetched and echoed back.
web.add("https://example.com/", plain("root"))
async with connect(ignore_robots_txt=True) as (session, _):
result = await call(session, {"url": "https://example.com"})
assert (
text_of(result) == f"{RAW_PREFIX_PLAIN}Contents of https://example.com/:\nroot"
)
assert web.urls() == ["https://example.com/"]
# --------------------------------------------------------------------------
# tools/call: pagination
# --------------------------------------------------------------------------
@pytest.mark.parametrize(
("start_index", "max_length", "expected"),
[
# Truncated: there is more, so the continuation hint is appended.
(
0,
10,
(
"abcdefghij\n\n<error>Content truncated. Call the fetch tool with a "
"start_index of 10 to get more content.</error>"
),
),
(
10,
10,
(
"klmnopqrst\n\n<error>Content truncated. Call the fetch tool with a "
"start_index of 20 to get more content.</error>"
),
),
# A window that ends exactly at the end: full length, nothing remains.
(16, 10, "qrstuvwxyz"),
# A window that runs past the end: short slice, no hint.
(20, 10, "uvwxyz"),
# The whole thing fits.
(0, 5000, ALPHABET),
# At or past the end.
(26, 10, "<error>No more content available.</error>"),
(1000, 10, "<error>No more content available.</error>"),
],
)
async def test_pagination(
web: FakeWeb, start_index: int, max_length: int, expected: str
) -> None:
web.add(PAGE, plain(ALPHABET))
async with connect(ignore_robots_txt=True) as (session, _):
result = await call(
session,
{"url": PAGE, "start_index": start_index, "max_length": max_length},
)
assert wire(result) == {
"content": [
{
"type": "text",
"text": f"{RAW_PREFIX_PLAIN}Contents of {PAGE}:\n{expected}",
}
],
"isError": False,
}
async def test_pagination_walks_the_whole_document(web: FakeWeb) -> None:
web.add(PAGE, plain(ALPHABET))
pieces: list[str] = []
async with connect(ignore_robots_txt=True) as (session, _):
start = 0
# Four pages plus the exhaustion call. Bounded, so a regression that
# ignores start_index fails here instead of looping forever.
for _ in range(5):
text = text_of(
await call(
session, {"url": PAGE, "start_index": start, "max_length": 7}
)
)
body = text.split(f"Contents of {PAGE}:\n", 1)[1]
if body == "<error>No more content available.</error>":
break
chunk = body.split("\n\n<error>", 1)[0]
pieces.append(chunk)
start += len(chunk)
else:
pytest.fail(f"pagination did not reach the end; pages so far: {pieces}")
assert "".join(pieces) == ALPHABET
assert pieces == ["abcdefg", "hijklmn", "opqrstu", "vwxyz"]
# --------------------------------------------------------------------------
# tools/call: transport behavior pinned for open issues
# --------------------------------------------------------------------------
def refused(url: str, host: str, address: str) -> str:
return (
f"Refused to fetch {url}: {host} resolves to {address}, which is not a "
"public address. Start the server with --allow-private-ips to allow "
"private, loopback and link-local addresses."
)
async def test_redirect_to_private_address_is_refused(web: FakeWeb) -> None:
# #4838: every redirect hop is checked, so a public URL cannot bounce the
# server to a link-local metadata address.
metadata = "http://169.254.169.254/latest/meta-data/"
web.add(ROBOTS, plain("", status=404))
web.add(PAGE, httpx.Response(302, headers={"location": metadata}))
web.add(metadata, plain("instance-secret"))
async with connect() as (session, _):
result = await call(session, {"url": PAGE})
assert wire(result) == {
"content": [
{
"type": "text",
"text": TOOL_ERROR
+ refused(metadata, "169.254.169.254", "169.254.169.254"),
}
],
"isError": True,
}
# The metadata address is never requested.
assert web.urls() == [ROBOTS, PAGE]
@pytest.mark.parametrize(
"address",
[
"127.0.0.1",
"10.0.0.1",
"172.16.0.1",
"192.168.1.1",
"169.254.169.254",
"100.100.100.200",
"0.0.0.0",
"::1",
"fe80::1",
"fd00:ec2::254",
"::ffff:127.0.0.1",
# Read as global by is_global on older Python patch releases.
"192.0.0.8",
"64:ff9b:1::1",
"2002:7f00:1::",
# The well-known NAT64 prefix (64:ff9b::/96) wraps an IPv4 in its low
# 32 bits, and a NAT64 gateway forwards to that IPv4.
"64:ff9b::a9fe:a9fe",
"64:ff9b::7f00:1",
"64:ff9b::a00:1",
# Inside 2001::/23 but outside its global exceptions (benchmarking).
"2001:2::1",
# Multicast, which is_global does not exclude.
"224.0.0.251",
# Deprecated site-local (RFC 3879), which is_global reads as global.
"fec0::1",
# IPv6 documentation (RFC 9637), missing from older is_global tables.
"3fff::1",
# Outside IPv6 global unicast (2000::/3): SRv6 SIDs, IETF-reserved.
"5f00::1",
"feff::1",
"4000::1",
],
)
async def test_private_address_is_refused_before_any_request(
web: FakeWeb, address: str
) -> None:
# robots.txt is the first request on the tool path, so it is refused too.
host = f"[{address}]" if ":" in address else address
url = f"http://{host}/admin"
async with connect() as (session, _):
result = await call(session, {"url": url})
assert wire(result)["isError"] is True
# httpx normalizes the host (::ffff:127.0.0.1 becomes ::ffff:7f00:1), so
# only the shape of the message is pinned here.
text = text_of(result)
assert text.startswith(f"{TOOL_ERROR}Refused to fetch http://")
assert "/robots.txt: " in text
assert "which is not a public address" in text
assert web.requests == []
@pytest.mark.parametrize(
"address",
# Globally reachable assignments inside refused special-purpose ranges.
["192.0.0.9", "192.0.0.10", "2001:1::1", "2001:3::1", "2001:20::1"],
)
async def test_global_exceptions_in_special_ranges_are_allowed(
web: FakeWeb, address: str
) -> None:
web.dns["anycast.example.com"] = [address]
url = "https://anycast.example.com/"