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
39 changes: 29 additions & 10 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 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,20 @@ class ReadDirectoryRequest(Request[ReadDirectoryParams, Literal["resources/direc
params: ReadDirectoryParams


def _has_query_or_fragment(uri: str) -> bool:
"""Return True if `uri` contains a `?` or `#` delimiter, including bare trailing ones."""
return "?" in uri or "#" in uri


def _is_dot_or_traversal_segment(segment: str) -> bool:
decoded = unquote(segment)
return segment in (".", "..") or decoded in (".", "..") or "/" in decoded


def _has_traversal_segment(path: str) -> bool:
return any(_is_dot_or_traversal_segment(segment) 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 @@ -226,11 +240,14 @@ def skill_name_from_uri(uri: str) -> str:
prefix) that segment is the authority.

Raises:
ValueError: If `uri` is not an absolute URI ending in `/SKILL.md`.
ValueError: If `uri` is not an absolute URI ending in `/SKILL.md`, or
contains query/fragment delimiters or traversal path segments.
"""
parts = urlsplit(uri)
if not parts.scheme or parts.query or parts.fragment:
if not parts.scheme or _has_query_or_fragment(uri):
raise ValueError(f"skill URI {uri!r} is not a valid absolute resource URI")
if _has_traversal_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 +264,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):
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,22 +273,24 @@ 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_traversal_segment(resource_parts.path):
raise ValueError(f"resource URI {resource_uri!r} contains a traversal segment")


def parse_directory_uri(uri: str) -> tuple[str, str, str]:
"""Split a directory resource URI into `(scheme, netloc, path)`.

Raises:
ValueError: If `uri` has a trailing slash, or is otherwise not a valid
absolute resource URI.
ValueError: If `uri` has a trailing slash, traversal segments, query or
fragment delimiters, or is otherwise not a valid absolute resource URI.
"""
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):
raise ValueError(f"directory URI {uri!r} is not a valid absolute resource URI")
if _has_traversal_segment(parts.path):
raise ValueError(f"directory URI {uri!r} contains a traversal segment")
return parts.scheme, parts.netloc, parts.path


Expand All @@ -291,12 +310,12 @@ 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):
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}")
relative = child.path.removeprefix(prefix)
if relative == child.path or not relative or "/" in relative or relative in (".", ".."):
if relative == child.path or not relative or "/" in relative or _is_dot_or_traversal_segment(relative):
raise ValueError(f"resource {resource.uri!r} is not a direct child of directory {uri!r}")
if resource.uri in seen_uris:
raise ValueError(f"directory {uri!r} contains a duplicate child {resource.uri!r}")
Expand Down
86 changes: 86 additions & 0 deletions tests/shared/test_skills.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,3 +354,89 @@ def test_validate_directory_result_rejects_a_uri_outside_the_directory() -> None
result = ReadDirectoryResult(resources=[Resource(uri="skill://other/file.md", name="file.md")])
with pytest.raises(ValueError, match="not a child"):
validate_directory_result("skill://pdf/templates", result)


@pytest.mark.parametrize(
"uri",
[
"skill://org/../my-skill/SKILL.md",
"skill://org/./my-skill/SKILL.md",
"skill://org/%2e%2e/my-skill/SKILL.md",
"skill://org/%2E/my-skill/SKILL.md",
],
)
def test_skill_name_from_uri_and_dynamic_skill_reject_traversal_segments(uri: str) -> None:
with pytest.raises(ValueError, match="traversal segment"):
skill_name_from_uri(uri)
with pytest.raises(ValidationError, match="traversal segment"):
Skill(uri=uri, frontmatter={"name": "my-skill", "description": "d"}, resources="dynamic")


@pytest.mark.parametrize(
"uri",
[
"skill://org/../../etc",
"skill://org/./templates",
"skill://org/%2e%2e/etc",
"skill://org/%2E%2E/etc",
],
)
def test_parse_directory_uri_rejects_traversal_segments(uri: str) -> None:
with pytest.raises(ValueError, match="traversal segment"):
parse_directory_uri(uri)


@pytest.mark.parametrize(
"uri",
[
"skill://my-skill/SKILL.md?",
"skill://my-skill/SKILL.md#",
],
)
def test_skill_name_from_uri_rejects_bare_query_and_fragment_delimiters(uri: str) -> None:
with pytest.raises(ValueError, match="absolute resource URI"):
skill_name_from_uri(uri)


@pytest.mark.parametrize(
"uri",
[
"skill://my-skill?",
"skill://my-skill#",
"skill://my-skill/templates?",
"skill://my-skill/templates#",
],
)
def test_parse_directory_uri_rejects_bare_query_and_fragment_delimiters(uri: str) -> None:
with pytest.raises(ValueError, match="absolute resource URI"):
parse_directory_uri(uri)


@pytest.mark.parametrize(
"resource_uri",
[
"skill://git-workflow/x.md?",
"skill://git-workflow/x.md#",
"skill://git-workflow/%2e%2e/evil.md",
"skill://git-workflow/%2E/evil.md",
],
)
def test_skill_rejects_bare_delimiters_and_encoded_traversal_in_resource_uri(resource_uri: str) -> None:
with pytest.raises(ValidationError, match="is invalid|traversal segment"):
_skill(extra_resources=[_resource(resource_uri)])


@pytest.mark.parametrize(
"child_uri",
[
"skill://pdf/templates/x.md?",
"skill://pdf/templates/x.md#",
"skill://pdf/templates/%2e",
"skill://pdf/templates/%2e%2e",
"skill://pdf/templates/a%2Fb.md",
],
)
def test_validate_directory_result_rejects_bare_delimiters_and_encoded_traversal(child_uri: str) -> None:
result = ReadDirectoryResult(resources=[Resource(uri=child_uri, name="x")])
with pytest.raises(ValueError, match="invalid URI|direct child"):
validate_directory_result("skill://pdf/templates", result)
Loading