|
| 1 | +"""Test that URL-encoded parameters are decoded in resource templates. |
| 2 | +
|
| 3 | +Regression test for https://github.com/modelcontextprotocol/python-sdk/issues/973 |
| 4 | +""" |
| 5 | + |
| 6 | +from mcp.server.fastmcp.resources import ResourceTemplate |
| 7 | + |
| 8 | + |
| 9 | +def test_template_matches_decodes_space(): |
| 10 | + """Test that %20 is decoded to space.""" |
| 11 | + |
| 12 | + def search(query: str) -> str: # pragma: no cover |
| 13 | + return f"Results for: {query}" |
| 14 | + |
| 15 | + template = ResourceTemplate.from_function( |
| 16 | + fn=search, |
| 17 | + uri_template="search://{query}", |
| 18 | + name="search", |
| 19 | + ) |
| 20 | + |
| 21 | + params = template.matches("search://hello%20world") |
| 22 | + assert params is not None |
| 23 | + assert params["query"] == "hello world" |
| 24 | + |
| 25 | + |
| 26 | +def test_template_matches_decodes_accented_characters(): |
| 27 | + """Test that %C3%A9 is decoded to e with accent.""" |
| 28 | + |
| 29 | + def search(query: str) -> str: # pragma: no cover |
| 30 | + return f"Results for: {query}" |
| 31 | + |
| 32 | + template = ResourceTemplate.from_function( |
| 33 | + fn=search, |
| 34 | + uri_template="search://{query}", |
| 35 | + name="search", |
| 36 | + ) |
| 37 | + |
| 38 | + params = template.matches("search://caf%C3%A9") |
| 39 | + assert params is not None |
| 40 | + assert params["query"] == "café" |
| 41 | + |
| 42 | + |
| 43 | +def test_template_matches_decodes_complex_phrase(): |
| 44 | + """Test complex French phrase from the original issue.""" |
| 45 | + |
| 46 | + def search(query: str) -> str: # pragma: no cover |
| 47 | + return f"Results for: {query}" |
| 48 | + |
| 49 | + template = ResourceTemplate.from_function( |
| 50 | + fn=search, |
| 51 | + uri_template="search://{query}", |
| 52 | + name="search", |
| 53 | + ) |
| 54 | + |
| 55 | + params = template.matches("search://stick%20correcteur%20teint%C3%A9%20anti-imperfections") |
| 56 | + assert params is not None |
| 57 | + assert params["query"] == "stick correcteur teinté anti-imperfections" |
| 58 | + |
| 59 | + |
| 60 | +def test_template_matches_preserves_plus_sign(): |
| 61 | + """Test that plus sign remains as plus (not converted to space). |
| 62 | +
|
| 63 | + In URI encoding, %20 is space. Plus-as-space is only for |
| 64 | + application/x-www-form-urlencoded (HTML forms). |
| 65 | + """ |
| 66 | + |
| 67 | + def search(query: str) -> str: # pragma: no cover |
| 68 | + return f"Results for: {query}" |
| 69 | + |
| 70 | + template = ResourceTemplate.from_function( |
| 71 | + fn=search, |
| 72 | + uri_template="search://{query}", |
| 73 | + name="search", |
| 74 | + ) |
| 75 | + |
| 76 | + params = template.matches("search://hello+world") |
| 77 | + assert params is not None |
| 78 | + assert params["query"] == "hello+world" |
0 commit comments