Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions src/fetch/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,9 +185,12 @@ Optionally, you can add it to a file called `.vscode/mcp.json` in your workspace

By default, the server will obey a websites robots.txt file if the request came from the model (via a tool), but not if
the request was user initiated (via a prompt). Every redirect hop of a tool fetch is checked against the robots.txt of
the host it leads to, the same way as the requested URL. A path is matched against the rules both as it is spelled and
as an origin typically resolves it (`%2F` and `%2E` decoded, repeated slashes merged, `.` and `..` segments removed),
and the fetch is refused if either is disallowed, so `//private` or `/x/../private` cannot get past `Disallow: /private`.
the host it leads to, the same way as the requested URL. A path is matched against the rules as it is spelled, as an
origin typically resolves it (`%2F` and `%2E` decoded, repeated slashes merged, `.` and `..` segments removed), as an
origin with Windows path semantics resolves it (the same, with a backslash or `%5C` also read as a separator), and as a
servlet container resolves it (the same, with a `;` parameter dropped from each segment). The fetch is refused if any
of these is disallowed, so
`//private`, `/x/../private`, `/x%5C..%5Cprivate` or `/x/..;/private` cannot get past `Disallow: /private`.
Matching stays case-sensitive, as RFC 9309 specifies. If the robots.txt request fails to connect, or is answered
with 401, 403 or a server error (5xx), the tool refuses the fetch rather than reading the response as rules (RFC 9309
treats a 5xx robots.txt as complete disallow); any other 4xx is treated as no rules. This can be disabled by adding the
Expand Down
32 changes: 26 additions & 6 deletions src/fetch/src/mcp_server_fetch/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -721,6 +721,9 @@ def handle_starttag(
_ENCODED_SLASH = re.compile("%2f", re.IGNORECASE)
_ENCODED_DOT = re.compile("%2e", re.IGNORECASE)
_REPEATED_SLASHES = re.compile("/{2,}")
# A backslash, literal or escaped, which some origins (IIS, Windows-backed
# servers) read as a path separator.
_BACKSLASH = re.compile(r"\\|%5c", re.IGNORECASE)


def _remove_dot_segments(path: str) -> str:
Expand All @@ -742,7 +745,9 @@ def _remove_dot_segments(path: str) -> str:
return "/" + "/".join(resolved) + trailing


def _resolved_path_url(url: str) -> str:
def _resolved_path_url(
url: str, *, backslash_separator: bool = False, drop_parameters: bool = False
) -> str:
"""``url`` with its path spelled the way a typical origin resolves it.

robots.txt rules match the path a crawler requests, but an origin such as
Expand All @@ -751,9 +756,21 @@ def _resolved_path_url(url: str) -> str:
repeated slashes merged and dot segments removed before rules are matched
against it, as well as against the path as spelled. The query is kept as
it is, and matching stays case-sensitive (RFC 9309 2.2.2).

Origins with other path semantics are covered by further spellings, each
matched in addition to the others rather than in place of one, so each
only ever adds refusals: with ``backslash_separator`` a backslash (literal
or ``%5C``) is a separator, as on IIS; with ``drop_parameters`` a ``;``
path parameter is dropped from each segment, as in a Java servlet
container. They are separate spellings because no origin is assumed to
do both.
"""
parts = urlsplit(url)
path = _ENCODED_DOT.sub(".", _ENCODED_SLASH.sub("/", parts.path))
if backslash_separator:
path = _BACKSLASH.sub("/", path)
if drop_parameters:
path = "/".join(segment.split(";", 1)[0] for segment in path.split("/"))
path = _remove_dot_segments(_REPEATED_SLASHES.sub("/", path))
return urlunsplit(parts._replace(path=path))

Expand Down Expand Up @@ -804,12 +821,15 @@ async def check_may_autonomously_fetch_url(
line for line in robot_txt.splitlines() if not line.strip().startswith("#")
)
robot_parser = Protego.parse(processed_robot_txt)
# Refused when either spelling of the path is disallowed: resolving the
# Refused when any spelling of the path is disallowed: resolving the
# path only ever adds refusals.
if not (
robot_parser.can_fetch(url, user_agent)
and robot_parser.can_fetch(_resolved_path_url(url), user_agent)
):
spellings = (
url,
_resolved_path_url(url),
_resolved_path_url(url, backslash_separator=True),
_resolved_path_url(url, drop_parameters=True),
)
if not all(robot_parser.can_fetch(spelling, user_agent) for spelling in spellings):
raise ToolError(
f"The sites robots.txt ({robot_txt_url}), specifies that autonomous fetching of this page is not allowed, "
f"<useragent>{user_agent}</useragent>\n"
Expand Down
53 changes: 53 additions & 0 deletions src/fetch/tests/test_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,14 @@ async def test_ignore_robots_txt_skips_the_check(web: FakeWeb) -> None:
"/%2e/private",
"/x/%2E%2E/private",
"//private//report",
# An origin that reads a backslash as a separator (IIS) serves
# /private for these.
"/public%5c..%5cprivate",
"/public%5C..%5Cprivate",
# A servlet container drops ;parameters from each segment first.
"/public/..;/private",
"/public;x/..;y/private",
"/;x/private",
],
)
async def test_robots_disallow_matches_the_resolved_path(
Expand Down Expand Up @@ -503,6 +511,11 @@ async def test_robots_disallow_matches_the_resolved_path(
"/x/..%2Fprivate",
"/x/%2e%2e//private",
"/x//%2e%2e/private",
# A redirect carries a literal backslash as it is, where a tool
# argument would have it read as a separator first.
"/public\\..\\private",
"/public%5c..%5cprivate",
"/public/..;/private",
],
)
async def test_redirect_to_a_disallowed_path_spelled_otherwise_is_refused(
Expand All @@ -528,6 +541,8 @@ async def test_redirect_to_a_disallowed_path_spelled_otherwise_is_refused(
"/pri%20vate",
# Matching stays case-sensitive (RFC 9309 2.2.2).
"//Private",
"/public%5cprivate",
"/public;private",
],
)
async def test_robots_allows_a_path_that_resolves_outside_the_rule(
Expand All @@ -543,6 +558,44 @@ async def test_robots_allows_a_path_that_resolves_outside_the_rule(
assert web.urls() == [ROBOTS, url]


async def test_robots_disallow_still_matches_the_dot_resolved_spelling(
web: FakeWeb,
) -> None:
# Dropping ;parameters is matched in addition to the dot-resolved
# spelling, so a rule naming a parameter still refuses a path that only
# resolves to it once its dot segments are removed.
url = "https://example.com/x/%2e%2e/a;b"
web.add(ROBOTS, plain("User-agent: *\nDisallow: /a;b"))
web.add(url, plain("private-page"))
async with connect() as (session, _):
result = await call(session, {"url": url})
assert wire(result)["isError"] is True
assert "private-page" not in text_of(result)
assert web.urls() == [ROBOTS]


@pytest.mark.parametrize(
("rule", "path"),
[
# An origin that reads a backslash as a separator keeps ;parameters,
# and one that drops ;parameters keeps backslashes.
("/a;b", "/x%5c..%5ca;b"),
("/a%5Cb", "/x/..;/a%5Cb"),
],
)
async def test_robots_disallow_matches_each_resolution_on_its_own(
web: FakeWeb, rule: str, path: str
) -> None:
url = f"https://example.com{path}"
web.add(ROBOTS, plain(f"User-agent: *\nDisallow: {rule}"))
web.add(url, plain("private-page"))
async with connect() as (session, _):
result = await call(session, {"url": url})
assert wire(result)["isError"] is True
assert "private-page" not in text_of(result)
assert web.urls() == [ROBOTS]


async def test_robots_disallow_still_matches_the_literal_spelling(
web: FakeWeb,
) -> None:
Expand Down