|
| 1 | +"""`docs/advanced/uri-templates.md`: every claim the page makes, proved against the real SDK.""" |
| 2 | + |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +import pytest |
| 6 | +from inline_snapshot import snapshot |
| 7 | +from mcp_types import INVALID_PARAMS, ErrorData, ResourceTemplate, TextResourceContents |
| 8 | + |
| 9 | +from docs_src.uri_templates import tutorial001, tutorial002, tutorial003, tutorial004, tutorial005 |
| 10 | +from mcp import Client, MCPError |
| 11 | +from mcp.shared.path_security import PathEscapeError, contains_path_traversal, safe_join |
| 12 | + |
| 13 | +# See test_index.py for why this is a per-module mark and not a conftest hook. |
| 14 | +pytestmark = [pytest.mark.anyio, pytest.mark.filterwarnings("error::mcp.MCPDeprecationWarning")] |
| 15 | + |
| 16 | + |
| 17 | +async def test_simple_expansion_maps_the_segment_to_the_argument() -> None: |
| 18 | + """tutorial001: `books://{isbn}` reads `books://978-...` and the matched string is the argument.""" |
| 19 | + async with Client(tutorial001.mcp) as client: |
| 20 | + (content,) = (await client.read_resource("books://978-0441172719")).contents |
| 21 | + assert isinstance(content, TextResourceContents) |
| 22 | + assert content.text == snapshot('{\n "title": "Dune",\n "author": "Frank Herbert"\n}') |
| 23 | + |
| 24 | + |
| 25 | +async def test_an_int_parameter_is_converted_from_the_uri_string() -> None: |
| 26 | + """tutorial001: `order_id: int` receives `12345`, not `"12345"`, so `order_id + 1` is `12346`.""" |
| 27 | + async with Client(tutorial001.mcp) as client: |
| 28 | + (content,) = (await client.read_resource("orders://12345")).contents |
| 29 | + assert isinstance(content, TextResourceContents) |
| 30 | + assert content.text == snapshot('{\n "order_id": 12345,\n "next_order": 12346,\n "status": "shipped"\n}') |
| 31 | + |
| 32 | + |
| 33 | +async def test_plus_keeps_the_slashes_in_the_captured_value() -> None: |
| 34 | + """tutorial001: `{+path}` matches `printing/setup.md` as one value; a plain `{path}` would not.""" |
| 35 | + async with Client(tutorial001.mcp) as client: |
| 36 | + (content,) = (await client.read_resource("manuals://printing/setup.md")).contents |
| 37 | + assert isinstance(content, TextResourceContents) |
| 38 | + assert content.text == "# Printer setup\n\nLoad paper, then power on." |
| 39 | + |
| 40 | + |
| 41 | +async def test_omitted_query_params_fall_through_to_function_defaults() -> None: |
| 42 | + """tutorial001: `{?limit,sort}` is lenient. No query string means `limit=10, sort="newest"`.""" |
| 43 | + async with Client(tutorial001.mcp) as client: |
| 44 | + (content,) = (await client.read_resource("reviews://978-0441172719")).contents |
| 45 | + assert isinstance(content, TextResourceContents) |
| 46 | + assert content.text == "10 newest reviews of Dune" |
| 47 | + |
| 48 | + |
| 49 | +async def test_a_query_param_overrides_only_the_default_it_names() -> None: |
| 50 | + """tutorial001: `?sort=top` sets `sort` and leaves `limit` at its default.""" |
| 51 | + async with Client(tutorial001.mcp) as client: |
| 52 | + (content,) = (await client.read_resource("reviews://978-0441172719?sort=top")).contents |
| 53 | + assert isinstance(content, TextResourceContents) |
| 54 | + assert content.text == "10 top reviews of Dune" |
| 55 | + |
| 56 | + |
| 57 | +async def test_exploded_path_arrives_as_a_list_of_segments() -> None: |
| 58 | + """tutorial001: `{/path*}` splits `/fiction/sci-fi` into `["fiction", "sci-fi"]`.""" |
| 59 | + async with Client(tutorial001.mcp) as client: |
| 60 | + (content,) = (await client.read_resource("shelves://browse/fiction/sci-fi")).contents |
| 61 | + assert isinstance(content, TextResourceContents) |
| 62 | + assert content.text == "catalog > fiction > sci-fi" |
| 63 | + |
| 64 | + |
| 65 | +async def test_traversal_is_rejected_before_the_handler_runs() -> None: |
| 66 | + """The `!!! check`: `../` triggers `-32602` "Unknown resource" and `read_manual` is never called.""" |
| 67 | + async with Client(tutorial001.mcp) as client: |
| 68 | + with pytest.raises(MCPError) as exc_info: |
| 69 | + await client.read_resource("manuals://../etc/passwd") |
| 70 | + assert exc_info.value.error == snapshot( |
| 71 | + ErrorData( |
| 72 | + code=INVALID_PARAMS, |
| 73 | + message="Unknown resource: manuals://../etc/passwd", |
| 74 | + data={"uri": "manuals://../etc/passwd"}, |
| 75 | + ) |
| 76 | + ) |
| 77 | + |
| 78 | + |
| 79 | +def test_dotdot_is_a_component_check_not_a_substring_scan() -> None: |
| 80 | + """The page's prose: `v1.0..v2.0` passes because `..` is not a standalone path segment.""" |
| 81 | + assert contains_path_traversal("../etc") is True |
| 82 | + assert contains_path_traversal("v1.0..v2.0") is False |
| 83 | + |
| 84 | + |
| 85 | +async def test_safe_join_serves_a_file_inside_the_base_directory( |
| 86 | + tmp_path: Path, monkeypatch: pytest.MonkeyPatch |
| 87 | +) -> None: |
| 88 | + """tutorial002: `safe_join(DOCS_ROOT, path).read_text()` returns the file under the base.""" |
| 89 | + (tmp_path / "printing").mkdir() |
| 90 | + (tmp_path / "printing" / "setup.md").write_text("# Printer setup") |
| 91 | + monkeypatch.setattr(tutorial002, "DOCS_ROOT", tmp_path) |
| 92 | + async with Client(tutorial002.mcp) as client: |
| 93 | + (content,) = (await client.read_resource("manuals://printing/setup.md")).contents |
| 94 | + assert isinstance(content, TextResourceContents) |
| 95 | + assert content.text == "# Printer setup" |
| 96 | + |
| 97 | + |
| 98 | +def test_safe_join_raises_when_the_resolved_path_escapes_the_base(tmp_path: Path) -> None: |
| 99 | + """tutorial002: a path that climbs out of `DOCS_ROOT` raises `PathEscapeError`.""" |
| 100 | + with pytest.raises(PathEscapeError): |
| 101 | + safe_join(tmp_path, "../etc/passwd") |
| 102 | + |
| 103 | + |
| 104 | +async def test_exempt_params_lets_an_absolute_path_through() -> None: |
| 105 | + """tutorial003: `exempt_params={"source"}` skips the checks for that one parameter.""" |
| 106 | + async with Client(tutorial003.mcp) as client: |
| 107 | + (content,) = (await client.read_resource("imports://preview//srv/incoming/catalog.csv")).contents |
| 108 | + assert isinstance(content, TextResourceContents) |
| 109 | + assert content.text == "Would import from /srv/incoming/catalog.csv" |
| 110 | + |
| 111 | + |
| 112 | +async def test_server_wide_resource_security_relaxes_every_resource() -> None: |
| 113 | + """tutorial003: `resource_security=ResourceSecurity(reject_path_traversal=False)` exempts the whole server.""" |
| 114 | + async with Client(tutorial003.relaxed) as client: |
| 115 | + (content,) = (await client.read_resource("imports://preview/../sibling/catalog.csv")).contents |
| 116 | + assert isinstance(content, TextResourceContents) |
| 117 | + assert content.text == "Would import from ../sibling/catalog.csv" |
| 118 | + |
| 119 | + |
| 120 | +async def test_lowlevel_static_dispatch_lists_and_reads_by_exact_uri() -> None: |
| 121 | + """tutorial004: the registry is the listing, and a known URI returns its text.""" |
| 122 | + async with Client(tutorial004.server) as client: |
| 123 | + listed = (await client.list_resources()).resources |
| 124 | + assert [r.uri for r in listed] == ["config://shop", "status://health"] |
| 125 | + (content,) = (await client.read_resource("status://health")).contents |
| 126 | + assert content == TextResourceContents(uri="status://health", text="ok") |
| 127 | + |
| 128 | + |
| 129 | +async def test_lowlevel_unknown_uri_raises() -> None: |
| 130 | + """tutorial004: a URI outside the registry raises and surfaces as a protocol error.""" |
| 131 | + async with Client(tutorial004.server) as client: |
| 132 | + with pytest.raises(MCPError): |
| 133 | + await client.read_resource("config://missing") |
| 134 | + |
| 135 | + |
| 136 | +def test_uritemplate_match_returns_a_dict_or_none() -> None: |
| 137 | + """tutorial005: `match()` extracts decoded variables, or `None` when the URI doesn't fit.""" |
| 138 | + assert tutorial005.TEMPLATES["manuals"].match("manuals://printing/setup.md") == {"path": "printing/setup.md"} |
| 139 | + assert tutorial005.TEMPLATES["books"].match("manuals://nope") is None |
| 140 | + |
| 141 | + |
| 142 | +async def test_lowlevel_match_routes_the_request_to_the_right_template() -> None: |
| 143 | + """tutorial005: two templates, one handler. Each concrete URI lands in its own branch.""" |
| 144 | + async with Client(tutorial005.server) as client: |
| 145 | + (manual,) = (await client.read_resource("manuals://printing/setup.md")).contents |
| 146 | + assert manual == TextResourceContents(uri="manuals://printing/setup.md", text="# Printer setup") |
| 147 | + (book,) = (await client.read_resource("books://978-0441172719")).contents |
| 148 | + assert book == TextResourceContents(uri="books://978-0441172719", text="Dune by Frank Herbert") |
| 149 | + |
| 150 | + |
| 151 | +async def test_lowlevel_handler_applies_the_safety_checks_itself() -> None: |
| 152 | + """tutorial005: there is no default policy down here; `read_manual_safely` is the gate.""" |
| 153 | + async with Client(tutorial005.server) as client: |
| 154 | + with pytest.raises(MCPError): |
| 155 | + await client.read_resource("manuals://../etc/passwd") |
| 156 | + with pytest.raises(MCPError): |
| 157 | + await client.read_resource("nothing://matches") |
| 158 | + |
| 159 | + |
| 160 | +async def test_str_of_a_template_round_trips_to_the_original_string() -> None: |
| 161 | + """tutorial005: `str(template)` is the source string, so the listing reuses the parsed templates.""" |
| 162 | + assert str(tutorial005.TEMPLATES["manuals"]) == "manuals://{+path}" |
| 163 | + async with Client(tutorial005.server) as client: |
| 164 | + result = await client.list_resource_templates() |
| 165 | + assert result.resource_templates == snapshot( |
| 166 | + [ |
| 167 | + ResourceTemplate(name="manuals", uri_template="manuals://{+path}"), |
| 168 | + ResourceTemplate(name="books", uri_template="books://{isbn}"), |
| 169 | + ] |
| 170 | + ) |
0 commit comments