Skip to content
Closed
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
24 changes: 18 additions & 6 deletions src/mcp/shared/skills.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

import re
from typing import Annotated, Any, Literal
from urllib.parse import urlsplit
from urllib.parse import SplitResult, unquote, urlsplit

from mcp_types import CacheableResult, PaginatedRequestParams, PaginatedResult, Request, RequestParams, Resource
from pydantic import AfterValidator, BaseModel, ConfigDict, Field, model_validator
Expand Down Expand Up @@ -218,6 +218,14 @@ class ReadDirectoryRequest(Request[ReadDirectoryParams, Literal["resources/direc
params: ReadDirectoryParams


def _has_query_or_fragment(uri: str, parts: SplitResult) -> bool:
return bool(parts.query or parts.fragment) or "?" in uri or "#" in uri


def _has_dot_segment(path: str) -> bool:
return any(unquote(segment) in (".", "..") for segment in path.split("/"))


def skill_name_from_uri(uri: str) -> str:
"""Return the skill `name` encoded in a `SKILL.md` resource URI.

Expand All @@ -229,8 +237,10 @@ def skill_name_from_uri(uri: str) -> str:
ValueError: If `uri` is not an absolute URI ending in `/SKILL.md`.
"""
parts = urlsplit(uri)
if not parts.scheme or parts.query or parts.fragment:
if not parts.scheme or _has_query_or_fragment(uri, parts):
raise ValueError(f"skill URI {uri!r} is not a valid absolute resource URI")
if _has_dot_segment(parts.path):
raise ValueError(f"skill URI {uri!r} contains a traversal segment")
if not parts.path.endswith("/SKILL.md"):
raise ValueError(f"skill URI {uri!r} must end in /SKILL.md")
directory = parts.path[: -len("/SKILL.md")].strip("/")
Expand All @@ -247,7 +257,7 @@ def _validate_resource_uri_in_skill(skill_uri: str, resource_uri: str) -> None:
"""Raise `ValueError` unless `resource_uri` names a file within `skill_uri`'s directory."""
skill_parts = urlsplit(skill_uri)
resource_parts = urlsplit(resource_uri)
if not resource_parts.scheme or resource_parts.query or resource_parts.fragment:
if not resource_parts.scheme or _has_query_or_fragment(resource_uri, resource_parts):
raise ValueError(f"resource URI {resource_uri!r} is invalid")
if resource_uri.endswith("/"):
raise ValueError(f"resource URI {resource_uri!r} names a directory, not a file")
Expand All @@ -256,7 +266,7 @@ def _validate_resource_uri_in_skill(skill_uri: str, resource_uri: str) -> None:
root = skill_parts.path[: -len("/SKILL.md")]
if resource_parts.path != skill_parts.path and not resource_parts.path.startswith(root + "/"):
raise ValueError(f"resource URI {resource_uri!r} is outside the skill root {skill_uri!r}")
if any(segment in (".", "..") for segment in resource_parts.path.split("/")):
if _has_dot_segment(resource_parts.path):
raise ValueError(f"resource URI {resource_uri!r} contains a traversal segment")


Expand All @@ -270,8 +280,10 @@ def parse_directory_uri(uri: str) -> tuple[str, str, str]:
if uri.endswith("/"):
raise ValueError(f"directory URI {uri!r} must not have a trailing slash")
parts = urlsplit(uri)
if not parts.scheme or parts.query or parts.fragment:
if not parts.scheme or _has_query_or_fragment(uri, parts):
raise ValueError(f"directory URI {uri!r} is not a valid absolute resource URI")
if _has_dot_segment(parts.path):
raise ValueError(f"directory URI {uri!r} contains a traversal segment")
return parts.scheme, parts.netloc, parts.path


Expand All @@ -291,7 +303,7 @@ def validate_directory_result(uri: str, result: ReadDirectoryResult) -> None:
prefix = parent_path.rstrip("/") + "/" if parent_path.rstrip("/") else "/"
for resource in result.resources:
child = urlsplit(resource.uri)
if not child.scheme or child.query or child.fragment:
if not child.scheme or _has_query_or_fragment(resource.uri, child):
raise ValueError(f"directory {uri!r} child has invalid URI {resource.uri!r}")
if child.scheme != scheme or child.netloc != netloc:
raise ValueError(f"resource {resource.uri!r} is not a child of directory {uri!r}")
Expand Down
20 changes: 17 additions & 3 deletions tests/shared/test_skills.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,14 @@ def test_skill_name_from_uri_reads_the_final_path_segment(uri: str, name: str) -
"skill://git-workflow/README.md", # doesn't end in /SKILL.md
"not-a-uri", # no scheme
"skill://git-workflow/SKILL.md?x=1", # query component
"skill://git-workflow/SKILL.md?", # trailing empty query delimiter
"skill://git-workflow/SKILL.md#", # trailing empty fragment delimiter
"skill://org/../git-workflow/SKILL.md", # traversal segment
"skill://org/%2e%2e/git-workflow/SKILL.md", # percent-encoded traversal segment
],
)
def test_skill_name_from_uri_rejects_malformed_uris(uri: str) -> None:
with pytest.raises(ValueError, match="SKILL.md|absolute resource URI"):
with pytest.raises(ValueError, match="SKILL.md|absolute resource URI|traversal segment"):
skill_name_from_uri(uri)


Expand Down Expand Up @@ -300,9 +304,19 @@ def test_request_meta_is_camelcase_on_the_wire_but_snakecase_to_a_handler(
assert params.meta is not None and params.meta.get("progress_token") == "t" # snake_case to a handler


@pytest.mark.parametrize("uri", ["skill://pdf/templates/", "not-a-uri"])
@pytest.mark.parametrize(
"uri",
[
"skill://pdf/templates/",
"not-a-uri",
"skill://pdf?",
"skill://pdf#",
"skill://org/../../etc",
"skill://org/%2e%2e/etc",
],
)
def test_parse_directory_uri_rejects_malformed_uris(uri: str) -> None:
with pytest.raises(ValueError, match="directory URI"):
with pytest.raises(ValueError, match="directory URI|traversal segment"):
parse_directory_uri(uri)


Expand Down
Loading