🚀 The fast, Pythonic way to build MCP servers and clients.
Share filesystem skill supporting-file reads (#6102)
nate nowackb81a14e8c2b0
diff --git a/fastmcp_slim/fastmcp/server/providers/skills/skill_provider.py b/fastmcp_slim/fastmcp/server/providers/skills/skill_provider.pyindex 45e94756e..ea3dd72d8 100644--- a/fastmcp_slim/fastmcp/server/providers/skills/skill_provider.py+++ b/fastmcp_slim/fastmcp/server/providers/skills/skill_provider.py@@ -32,6 +32,21 @@ logger = get_logger(__name__)mimetypes.add_type("text/markdown", ".md")+def _resolve_supporting_file(root: Path, file_path: str) -> Path:+ try:+ return resolve_within(root, file_path)+ except PathEscapeError as exc:+ raise ValueError(f"Invalid path: {exc}") from exc+++def _read_supporting_file(path: Path) -> str | bytes:+ mime_type, _ = mimetypes.guess_type(str(path))+ content = path.read_bytes()+ if mime_type and mime_type.startswith("text/"):+ return content.decode("utf-8")+ return content++# -----------------------------------------------------------------------------# Skill-specific Resource and ResourceTemplate subclasses# -----------------------------------------------------------------------------@@ -89,12 +104,7 @@ class SkillFileTemplate(ResourceTemplate):if self.skill_info.preserve_bytes:return await run_sync(read_file, self.skill_info.path, file_path)- # Security: reject traversal, absolute-path injection, null bytes, and- # symlink escapes before touching the filesystem.- try:- full_path = resolve_within(self.skill_info.path, file_path)- except PathEscapeError as e:- raise ValueError(f"Invalid path: {e}") from e+ full_path = _resolve_supporting_file(self.skill_info.path, file_path)if not full_path.exists():raise FileNotFoundError(f"File not found: {file_path}")@@ -102,12 +112,7 @@ class SkillFileTemplate(ResourceTemplate):if not full_path.is_file():raise ValueError(f"Not a file: {file_path}")- # Determine if binary or text based on mime type- mime_type, _ = mimetypes.guess_type(str(full_path))- if mime_type and mime_type.startswith("text/"):- return full_path.read_bytes().decode("utf-8")- else:- return full_path.read_bytes()+ return _read_supporting_file(full_path)async def _read(self,@@ -127,12 +132,7 @@ class SkillFileTemplate(ResourceTemplate):"""file_path = params.get("path", "")- # Security: reject traversal, absolute-path injection, null bytes, and- # symlink escapes before touching the filesystem.- try:- full_path = resolve_within(self.skill_info.path, file_path)- except PathEscapeError as e:- raise ValueError(f"Invalid path: {e}") from e+ full_path = _resolve_supporting_file(self.skill_info.path, file_path)mime_type, _ = mimetypes.guess_type(str(full_path))@@ -165,21 +165,12 @@ class SkillFileResource(Resource):"""Read the file content."""if self.skill_info.preserve_bytes:return await run_sync(read_file, self.skill_info.path, self.file_path)- # Security: reject traversal, absolute-path injection, null bytes, and- # symlink escapes before touching the filesystem.- try:- full_path = resolve_within(self.skill_info.path, self.file_path)- except PathEscapeError as e:- raise ValueError(f"Invalid path: {e}") from e+ full_path = _resolve_supporting_file(self.skill_info.path, self.file_path)if not full_path.exists():raise FileNotFoundError(f"File not found: {self.file_path}")- mime_type, _ = mimetypes.guess_type(str(full_path))- if mime_type and mime_type.startswith("text/"):- return full_path.read_bytes().decode("utf-8")- else:- return full_path.read_bytes()+ return _read_supporting_file(full_path)# -----------------------------------------------------------------------------diff --git a/tests/server/providers/test_skill_supporting_reads.py b/tests/server/providers/test_skill_supporting_reads.pynew file mode 100644index 000000000..745bce8e7--- /dev/null+++ b/tests/server/providers/test_skill_supporting_reads.py@@ -0,0 +1,65 @@+"""Supporting-file content stays consistent across resource publication modes."""++import base64+from pathlib import Path+from typing import Literal++import pytest+from mcp_types import BlobResourceContents, TextResourceContents++from fastmcp import Client, FastMCP+from fastmcp.server.providers.skills import SkillProvider++[email protected]("supporting_files", ["template", "resources"])+ ("filename", "content", "is_text"),+ [+ ("notes.md", "Résumé\r\n".encode(), True),+ ("data.bin", b"\x00\xff\r\n", False),+ ("unknown-extension", b"\xff\x00", False),+ ],+)+async def test_supporting_file_preserves_content(+ tmp_path: Path,+ supporting_files: Literal["template", "resources"],+ filename: str,+ content: bytes,+ is_text: bool,+) -> None:+ root = tmp_path / "review"+ root.mkdir()+ (root / "SKILL.md").write_bytes(b"# Review\n")+ (root / filename).write_bytes(content)+ provider = SkillProvider(root, supporting_files=supporting_files)+ server = FastMCP("Skills", providers=[provider])++ async with Client(server) as client:+ (result,) = await client.read_resource(f"skill://review/{filename}")++ if is_text:+ assert isinstance(result, TextResourceContents)+ assert result.text.encode("utf-8") == content+ else:+ assert isinstance(result, BlobResourceContents)+ assert base64.b64decode(result.blob) == content++[email protected]("supporting_files", ["template", "resources"])+async def test_supporting_text_still_rejects_invalid_utf8(+ tmp_path: Path, supporting_files: Literal["template", "resources"]+) -> None:+ root = tmp_path / "review"+ root.mkdir()+ (root / "SKILL.md").write_bytes(b"# Review\n")+ (root / "notes.md").write_bytes(b"\xff")+ provider = SkillProvider(root, supporting_files=supporting_files)++ with pytest.raises(UnicodeDecodeError):+ if supporting_files == "template":+ (template,) = await provider.list_resource_templates()+ await template.read({"path": "notes.md"})+ else:+ resource = await provider.get_resource("skill://review/notes.md")+ assert resource is not None+ await resource.read()