Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Check skill limits before reading directory and remote files (#6092)

nate nowackd3e5ee06e987
diff --git a/fastmcp_slim/fastmcp/client/mixins/skills.py b/fastmcp_slim/fastmcp/client/mixins/skills.py
index e95c72966..2df76ed6e 100644
--- a/fastmcp_slim/fastmcp/client/mixins/skills.py
+++ b/fastmcp_slim/fastmcp/client/mixins/skills.py
@@ -27,7 +27,7 @@ from fastmcp.skills.models import (
SkillResource,
_parse_resource_uri,
)
-from fastmcp.skills.skill import Skill, _validate_relative_path
+from fastmcp.skills.skill import Skill, _validate_limits, _validate_relative_path
from fastmcp.telemetry import inject_trace_context
from fastmcp.utilities.logging import get_logger
@@ -260,6 +260,9 @@ class ClientSkillsMixin:
if not segments or segments[-1] != "SKILL.md":
raise ValueError(f"read_skill takes a skill's SKILL.md URI, got {uri!r}")
manifest, entry = await self._skill_manifest(uri, cache_mode)
+ _validate_limits(
+ len(manifest), sum(record.size for record in manifest.values())
+ )
for path in manifest:
_validate_relative_path(path)
files: dict[str, bytes] = {}
diff --git a/fastmcp_slim/fastmcp/skills/_snapshot.py b/fastmcp_slim/fastmcp/skills/_snapshot.py
index 2754fbaec..04ba83aff 100644
--- a/fastmcp_slim/fastmcp/skills/_snapshot.py
+++ b/fastmcp_slim/fastmcp/skills/_snapshot.py
@@ -13,9 +13,8 @@ import yaml
from mcp.shared.path_security import safe_join
from yaml.nodes import MappingNode
-from fastmcp.skills._constants import MAX_SKILL_BYTES, MAX_SKILL_FILES
from fastmcp.skills.models import MCPSkill, SkillFrontmatter
-from fastmcp.skills.skill import Skill
+from fastmcp.skills.skill import Skill, _validate_limits
class _FrontmatterLoader(yaml.SafeLoader):
@@ -96,10 +95,7 @@ def snapshot(root: Path, skill_path: str) -> Snapshot:
main = root / "SKILL.md"
if main not in paths:
raise ValueError("skill must contain SKILL.md")
- if len(paths) > MAX_SKILL_FILES:
- raise ValueError(f"skill has more than {MAX_SKILL_FILES} files")
- if sum(path.stat().st_size for path in paths) > MAX_SKILL_BYTES:
- raise ValueError(f"skill is larger than {MAX_SKILL_BYTES} bytes")
+ _validate_limits(len(paths), sum(path.stat().st_size for path in paths))
contents: dict[str, bytes] = {}
files: list[tuple[str, Path]] = []
for path in paths:
diff --git a/fastmcp_slim/fastmcp/skills/skill.py b/fastmcp_slim/fastmcp/skills/skill.py
index 8a3909a7d..53b0709e6 100644
--- a/fastmcp_slim/fastmcp/skills/skill.py
+++ b/fastmcp_slim/fastmcp/skills/skill.py
@@ -18,6 +18,13 @@ from fastmcp.skills._constants import MAX_SKILL_BYTES, MAX_SKILL_FILES
from fastmcp.skills.models import MCPSkill, SkillFrontmatter, SkillResource
+def _validate_limits(file_count: int, total_bytes: int) -> None:
+ if file_count > MAX_SKILL_FILES:
+ raise ValueError(f"A skill may contain at most {MAX_SKILL_FILES} files")
+ if total_bytes > MAX_SKILL_BYTES:
+ raise ValueError(f"A skill may contain at most {MAX_SKILL_BYTES} bytes")
+
+
def _validate_relative_path(path: str) -> str:
if not isinstance(path, str) or not path:
raise ValueError("Skill file paths must be non-empty strings")
@@ -103,10 +110,7 @@ class Skill:
)
if "SKILL.md" not in normalized:
raise ValueError("A skill must contain SKILL.md")
- if len(normalized) > MAX_SKILL_FILES:
- raise ValueError(f"A skill may contain at most {MAX_SKILL_FILES} files")
- if sum(map(len, normalized.values())) > MAX_SKILL_BYTES:
- raise ValueError(f"A skill may contain at most {MAX_SKILL_BYTES} bytes")
+ _validate_limits(len(normalized), sum(map(len, normalized.values())))
for path in normalized:
parts = path.split("/")
for index in range(1, len(parts)):
@@ -144,10 +148,9 @@ class Skill:
from fastmcp.skills._snapshot import scan_files
root = Path(path).absolute()
- files = {
- file.relative_to(root).as_posix(): file.read_bytes()
- for file in scan_files(root)
- }
+ paths = scan_files(root)
+ _validate_limits(len(paths), sum(file.stat().st_size for file in paths))
+ files = {file.relative_to(root).as_posix(): file.read_bytes() for file in paths}
skill = cls.from_files(files)
if skill.name != root.name:
raise ValueError(
diff --git a/tests/experimental/skills/test_snapshot.py b/tests/experimental/skills/test_snapshot.py
index e41b5f742..a239a74bb 100644
--- a/tests/experimental/skills/test_snapshot.py
+++ b/tests/experimental/skills/test_snapshot.py
@@ -6,7 +6,7 @@ from pathlib import Path
import pytest
-from fastmcp.skills import _snapshot
+from fastmcp.skills import skill as skill_module
from fastmcp.skills._snapshot import parse_frontmatter, snapshot
@@ -128,6 +128,6 @@ def test_snapshot_rejects_skills_over_spec_limits(
"---\nname: review\ndescription: Review code\n---\n"
)
(tmp_path / "notes.md").write_bytes(b"x" * 64)
- monkeypatch.setattr(_snapshot, limit, value)
+ monkeypatch.setattr(skill_module, limit, value)
with pytest.raises(ValueError, match="skill"):
snapshot(tmp_path, "review")
diff --git a/tests/skills/test_read_skill.py b/tests/skills/test_read_skill.py
index 4dde37456..965847902 100644
--- a/tests/skills/test_read_skill.py
+++ b/tests/skills/test_read_skill.py
@@ -16,8 +16,9 @@ from mcp_types import INTERNAL_ERROR
from fastmcp import Client, ClientGroup, FastMCP
from fastmcp.server.providers.skills import SkillProvider, SkillsDirectoryProvider
from fastmcp.skills import Skill, SkillsClientExtension
+from fastmcp.skills._constants import MAX_SKILL_BYTES, MAX_SKILL_FILES
from fastmcp.skills.extension import SkillsExtension
-from fastmcp.skills.models import MCPSkill, SkillFrontmatter
+from fastmcp.skills.models import MCPSkill, SkillFrontmatter, SkillResource
from fastmcp.skills.provider import SkillCatalogProvider
REVIEW = Skill(
@@ -298,6 +299,45 @@ async def test_read_skill_requires_a_connection():
await client.read_skill("skill://review/SKILL.md")
[email protected]("limit", ["count", "size"])
+async def test_read_skill_rejects_oversized_entries_before_reading_files(limit: str):
+ original = Skill(name="review", description="Review", instructions="# Review\n")
+ reads = 0
+
+ class Oversized(SkillCatalogProvider):
+ async def _get_skill_entry(
+ self, uri: str, context: ServerRequestContext[Any, Any]
+ ) -> MCPSkill | None:
+ entry = original.to_mcp_skill()
+ assert isinstance(entry.resources, list)
+ records = entry.resources
+ if limit == "count":
+ records.extend(
+ SkillResource(
+ uri=f"skill://review/{index}.txt",
+ digest=f"sha256:{hashlib.sha256(b'').hexdigest()}",
+ size=0,
+ )
+ for index in range(MAX_SKILL_FILES)
+ )
+ else:
+ records[0] = records[0].model_copy(update={"size": MAX_SKILL_BYTES + 1})
+ return entry.model_copy(update={"resources": records})
+
+ server = FastMCP("Skills", providers=[Oversized([original])])
+
+ @server.resource("skill://review/SKILL.md")
+ def observed_file() -> bytes:
+ nonlocal reads
+ reads += 1
+ return original.files["SKILL.md"]
+
+ async with skills_client(server) as client:
+ with pytest.raises(ValueError, match="at most"):
+ await client.read_skill("skill://review/SKILL.md")
+ assert reads == 0
+
+
async def test_a_read_skill_can_be_served_again():
origin = FastMCP(
"Origin", providers=[SkillCatalogProvider({"team/review": REVIEW})]
diff --git a/tests/skills/test_skill.py b/tests/skills/test_skill.py
index 66e854370..177d29a44 100644
--- a/tests/skills/test_skill.py
+++ b/tests/skills/test_skill.py
@@ -8,6 +8,7 @@ from pathlib import Path
import pytest
from fastmcp.skills import Skill
+from fastmcp.skills._constants import MAX_SKILL_BYTES, MAX_SKILL_FILES
def write_skill(root: Path, name: str = "review") -> Path:
@@ -90,6 +91,30 @@ def test_from_directory_requires_matching_name(tmp_path: Path):
Skill.from_directory(renamed)
[email protected]("limit", ["count", "size"])
+def test_from_directory_checks_limits_before_reading_files(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, limit: str
+):
+ folder = write_skill(tmp_path)
+ if limit == "count":
+ for index in range(MAX_SKILL_FILES):
+ (folder / f"extra-{index}.txt").touch()
+ else:
+ with (folder / "large.bin").open("wb") as file:
+ file.truncate(MAX_SKILL_BYTES + 1)
+ reads = []
+ read_bytes = Path.read_bytes
+
+ def observed_read(path: Path) -> bytes:
+ reads.append(path)
+ return read_bytes(path)
+
+ monkeypatch.setattr(Path, "read_bytes", observed_read)
+ with pytest.raises(ValueError, match="at most"):
+ Skill.from_directory(folder)
+ assert reads == []
+
+
@pytest.mark.skipif(sys.platform == "win32", reason="symlinks need privileges")
def test_from_directory_rejects_symlinks(tmp_path: Path):
folder = write_skill(tmp_path)