π The fast, Pythonic way to build MCP servers and clients.
Add a strict SkillsDirectoryProvider to fastmcp.skills.provider (#6278)
nate nowackbc855f3854df
diff --git a/docs/servers/skills.mdx b/docs/servers/skills.mdxindex 7b2280681..6c835ac49 100644--- a/docs/servers/skills.mdx+++ b/docs/servers/skills.mdx@@ -70,43 +70,19 @@ class StoredSkills(SkillCatalogProvider):]```-A folder you're still editing is the same shape. Re-read it on every request and changes show up live:--```python-from pathlib import Path--from fastmcp import Skill-from fastmcp.skills.provider import SkillCatalogProvider---class FolderSkills(SkillCatalogProvider):- def __init__(self, root: Path) -> None:- super().__init__()- self.root = root-- async def load_skills(self) -> list[Skill]:- folders = sorted(self.root.iterdir())- return [- Skill.from_directory(folder)- for folder in folders- if (folder / "SKILL.md").is_file()- ]-```--For recursive folder discovery that skips invalid skills, use `SkillsDirectoryProvider(path, experimental_skills=True)`. To discover a coding agent's own skills folder through the extension, pass its path explicitly:+To serve a folder of skills, point `SkillsDirectoryProvider` at it. Every subfolder with a `SKILL.md` becomes a skill, served at its path below the root, so `ops/deploy/SKILL.md` becomes `skill://ops/deploy/SKILL.md`. A coding agent's own skills folder works the same way:```pythonfrom pathlib import Pathfrom fastmcp import FastMCP-from fastmcp.server.providers.skills import SkillsDirectoryProvider+from fastmcp.skills.provider import SkillsDirectoryProviderroot = Path.home() / ".claude" / "skills"-provider = SkillsDirectoryProvider(root, experimental_skills=True)-mcp = FastMCP("Local Skills", providers=[provider])+mcp = FastMCP("Local Skills", providers=[SkillsDirectoryProvider(root)])```-Presets such as `ClaudeSkillsProvider` expose ordinary resources and do not accept the `experimental_skills` option.+Each `SKILL.md` must follow the [Agent Skills spec](https://agentskills.io/specification): YAML frontmatter with a `description` and a `name` of lowercase letters, digits and hyphens that matches its folder. A folder that breaks the rules stops the server at startup with an error naming the fix for each one, so a server never comes up quietly missing skills. Hidden folders such as `.git` are skipped. Pass several roots and the first one wins when two contain the same path. The provider reads the folders once at startup; pass `reload=True` to re-read them on every request while you're editing a skill. If a re-read finds a broken folder, the error is logged and the last valid skills keep serving until you fix it.## Access controldiff --git a/examples/skills/README.md b/examples/skills/README.mdindex a2c74e66c..2b6a57254 100644--- a/examples/skills/README.md+++ b/examples/skills/README.md@@ -1,8 +1,8 @@# Skills over MCP-The server loads the two sample folders into `Skill` values and publishes them-through `SkillCatalogProvider`. Each `SKILL.md` declares its name and description;-supporting files retain their exact bytes.+The server publishes the two sample folders with `SkillsDirectoryProvider`. Each+`SKILL.md` declares its name and description; supporting files retain their+exact bytes.Run the client from the repository root:@@ -25,10 +25,8 @@ To launch the server over stdio for another MCP client:uv run python -m examples.skills.server```-For live recursive folder discovery, use-`SkillsDirectoryProvider(root, experimental_skills=True)`. The catalog in this-example holds snapshots: changing a source file does not mutate an existing-`Skill`.+The provider reads the folders once at startup. Pass `reload=True` to pick up+edits on every request while you're writing a skill.See [Skills over MCP](https://gofastmcp.com/servers/skills) for custom loaders,access control, mounts and installing skills into a local agent.diff --git a/examples/skills/server.py b/examples/skills/server.pyindex eef184262..97139b5c7 100644--- a/examples/skills/server.py+++ b/examples/skills/server.py@@ -2,12 +2,11 @@from pathlib import Path-from fastmcp import FastMCP, Skill-from fastmcp.skills.provider import SkillCatalogProvider+from fastmcp import FastMCP+from fastmcp.skills.provider import SkillsDirectoryProviderroot = Path(__file__).parent / "sample_skills"-skills = [Skill.from_directory(folder) for folder in sorted(root.iterdir())]-mcp = FastMCP("Skills Server", providers=[SkillCatalogProvider(skills)])+mcp = FastMCP("Skills Server", providers=[SkillsDirectoryProvider(root)])if __name__ == "__main__":diff --git a/fastmcp_slim/fastmcp/skills/_snapshot.py b/fastmcp_slim/fastmcp/skills/_snapshot.pyindex b36ac6588..2db083ff3 100644--- a/fastmcp_slim/fastmcp/skills/_snapshot.py+++ b/fastmcp_slim/fastmcp/skills/_snapshot.py@@ -64,7 +64,10 @@ def parse_frontmatter(content: bytes) -> SkillFrontmatter:match = re.match(r"\A---\r?\n(.*?)\r?\n---(?:\r?\n|\Z)", text, re.DOTALL)if match is None:raise ValueError("SKILL.md must begin with YAML frontmatter")- value = yaml.load(match.group(1), Loader=_FrontmatterLoader) # noqa: S506 - SafeLoader subclass rejects duplicate keys+ try:+ value = yaml.load(match.group(1), Loader=_FrontmatterLoader) # noqa: S506 - SafeLoader subclass rejects duplicate keys+ except (yaml.YAMLError, RecursionError) as exc:+ raise ValueError(f"frontmatter is not valid YAML: {exc}") from excif not isinstance(value, dict):raise ValueError("frontmatter must be a mapping")_validate_json(value, set())diff --git a/fastmcp_slim/fastmcp/skills/provider.py b/fastmcp_slim/fastmcp/skills/provider.pyindex a745d94bb..60846a2cb 100644--- a/fastmcp_slim/fastmcp/skills/provider.py+++ b/fastmcp_slim/fastmcp/skills/provider.py@@ -1,18 +1,21 @@-"""Provider that serves `Skill` objects defined in code or loaded from any source."""+"""Providers that serve `Skill` objects defined in code, loaded from folders, or from any source."""from __future__ import annotationsimport hashlibimport jsonimport mimetypes+import os+import refrom collections.abc import Iterable, Mapping, Sequencefrom contextlib import suppress+from pathlib import Pathfrom typing import TYPE_CHECKING, Any, castfrom urllib.parse import quote, unquoteimport anyiofrom mcp.server.context import ServerRequestContext-from pydantic import AnyUrl, ConfigDict+from pydantic import AnyUrl, ConfigDict, ValidationErrorfrom fastmcp.resources.base import Resource, ResourceContent, ResourceResultfrom fastmcp.server.dependencies import get_context@@ -204,6 +207,168 @@ class SkillCatalogProvider(Provider):return f"{type(self).__name__}()"+class SkillsDirectoryProvider(SkillCatalogProvider):+ """Serve every skill folder found below one or more root directories.++ A folder containing a `SKILL.md` is a skill, served at its path relative to+ the root, so `root/ops/deploy/SKILL.md` becomes `skill://ops/deploy/SKILL.md`.+ Each `SKILL.md` must follow the [Agent Skills spec](https://agentskills.io/specification):+ YAML frontmatter with a `description` and a `name` of lowercase letters,+ digits and hyphens that matches its folder. An invalid folder raises+ `ValueError` naming the fix, so a server never starts with skills missing.+ Hidden folders are skipped. When a path appears under more than one root,+ the first root wins.++ Skills are read once, at construction. Pass `reload=True` to re-read the+ folders on every request while you're editing them; if a re-read finds an+ invalid folder, the error is logged and the last valid skills keep serving.++ Example:+ ```python+ from pathlib import Path++ from fastmcp import FastMCP+ from fastmcp.skills.provider import SkillsDirectoryProvider++ mcp = FastMCP("Local Skills")+ mcp.add_provider(SkillsDirectoryProvider(Path.home() / ".claude" / "skills"))+ ```+ """++ def __init__(+ self,+ roots: str | os.PathLike[str] | Sequence[str | os.PathLike[str]],+ *,+ reload: bool = False,+ ) -> None:+ if isinstance(roots, str | os.PathLike):+ roots = [roots]+ self._roots = tuple(Path(root).expanduser().absolute() for root in roots)+ self._reload = reload+ # Scan even with reload=True so an invalid folder fails at startup.+ self._last_good = self._scan()+ super().__init__(self._last_good)++ async def load_skills(self) -> SkillCatalog:+ if not self._reload:+ return self._static+ try:+ self._last_good = await anyio.to_thread.run_sync(self._scan)+ except ValueError as exc:+ # A folder broke mid-edit: keep serving the last good scan.+ logger.error("Keeping the last valid skills; %s", exc)+ return self._last_good++ def _owns_skill_resource(self, uri: str) -> bool:+ if self._reload:+ return uri.startswith("skill://")+ return _locate(uri, self._static) is not None++ def _scan(self) -> dict[str, Skill]:+ skills, invalid = _scan_skill_roots(self._roots)+ if invalid:+ raise ValueError(+ f"{len(invalid)} skill folder(s) are not valid Agent Skills "+ "(https://agentskills.io/specification):\n" + "\n".join(invalid)+ )+ return skills++ def __repr__(self) -> str:+ return (+ f"{type(self).__name__}(roots={list(self._roots)!r}, reload={self._reload})"+ )+++def _scan_skill_roots(roots: Sequence[Path]) -> tuple[dict[str, Skill], list[str]]:+ """Load every skill folder below `roots`.++ Returns the valid skills by relative path, plus one line per invalid folder+ saying what is wrong and how to fix it. The first root wins a duplicate path.+ """+ skills: dict[str, Skill] = {}+ invalid: list[str] = []+ for root in roots:+ for path, folder in _skill_folders(root):+ if path in skills:+ logger.debug("Skipping duplicate skill %r from %s", path, root)+ continue+ if any(_nested(path, other) for other in skills):+ logger.warning("Skipping skill %r nested in another skill", path)+ continue+ folder_name = path.rsplit("/", 1)[-1]+ try:+ skill = Skill.from_directory(folder)+ if skill.name != folder_name:+ raise ValueError(+ f"folder name must match its SKILL.md name {skill.name!r}"+ )+ except (OSError, ValueError) as exc:+ invalid.append(_invalid_folder(root / path, folder_name, exc))+ continue+ skills[path] = skill+ return skills, invalid+++def _invalid_folder(folder: Path, folder_name: str, exc: Exception) -> str:+ """One line per invalid folder: what's wrong, then how to fix it."""+ if isinstance(exc, ValidationError):+ reason = exc.errors()[0]["msg"].removeprefix("Value error, ")+ else:+ reason = str(exc).splitlines()[0] if str(exc) else type(exc).__name__+ if isinstance(exc, OSError) or any(+ word in reason for word in ("symlink", "non-regular", "at most")+ ):+ return f"- {folder}: {reason}"+ name = re.sub(r"-+", "-", re.sub(r"[^a-z0-9]+", "-", folder_name.lower()))+ name = name.strip("-")[:64] or "my-skill"+ rename = f"rename the folder to {name!r} and " if name != folder_name else ""+ return (+ f"- {folder}: {reason}. Fix: {rename}start SKILL.md with "+ f"'---\\nname: {name}\\ndescription: <what it does and when to use it>\\n---'"+ )+++def _skill_folders(root: Path) -> list[tuple[str, Path]]:+ """Find skill folders below `root` as (relative path, folder) pairs.++ A skill folder's subfolders belong to the skill, so the walk stops there.+ A symlink is followed only when it points at a skill folder. Hidden folders,+ such as `.git`, are skipped.+ """+ found: list[tuple[str, Path]] = []++ def visit(directory: Path, prefix: str) -> None:+ try:+ entries = sorted(directory.iterdir())+ except OSError as exc:+ logger.warning("Skipping unreadable skills folder %s: %s", directory, exc)+ return+ for entry in entries:+ if entry.name.startswith("."):+ continue+ path = f"{prefix}{entry.name}"+ try:+ if not entry.is_dir():+ continue+ if (entry / "SKILL.md").is_file():+ found.append((path, entry.resolve()))+ continue+ descend = not entry.is_symlink()+ except OSError as exc:+ logger.warning("Skipping unreadable skills folder %s: %s", entry, exc)+ continue+ if descend:+ visit(entry, f"{path}/")++ if root.is_dir():+ visit(root, "")+ return found+++def _nested(path: str, other: str) -> bool:+ return path.startswith(f"{other}/") or other.startswith(f"{path}/")++def _normalize(skills: SkillCatalog) -> dict[str, Skill]:if isinstance(skills, Mapping):mapping = cast("Mapping[str, Skill]", skills)diff --git a/tests/skills/test_directory_provider.py b/tests/skills/test_directory_provider.pynew file mode 100644index 000000000..ac437732b--- /dev/null+++ b/tests/skills/test_directory_provider.py@@ -0,0 +1,232 @@+"""Tests for `SkillsDirectoryProvider`, which serves skill folders from disk."""++from __future__ import annotations++import os+import sys+from pathlib import Path++import pytest++from fastmcp import Client, FastMCP+from fastmcp.server.middleware.caching import ResponseCachingMiddleware+from fastmcp.skills import Skill, SkillsClientExtension+from fastmcp.skills.provider import SkillsDirectoryProvider+++def write_skill(folder: Path, name: str | None = None, body: str = "# Body\n") -> Path:+ folder.mkdir(parents=True, exist_ok=True)+ (folder / "SKILL.md").write_bytes(+ f"---\nname: {name or folder.name}\ndescription: Use {folder.name}\n---\n{body}".encode()+ )+ return folder+++def skills_client(server: FastMCP) -> Client:+ return Client(server, extensions=[SkillsClientExtension()])+++async def listed(provider: SkillsDirectoryProvider) -> list[str]:+ async with skills_client(FastMCP("Skills", providers=[provider])) as client:+ return [entry.uri for entry in await client.list_skills()]+++async def test_serves_folders_at_their_relative_paths(tmp_path: Path):+ write_skill(tmp_path / "review")+ deploy = write_skill(tmp_path / "ops" / "deploy")+ (deploy / "refs").mkdir()+ (deploy / "refs" / "checklist.md").write_bytes(b"- tests\n")++ provider = SkillsDirectoryProvider(tmp_path)+ async with skills_client(FastMCP("Skills", providers=[provider])) as client:+ uris = [entry.uri for entry in await client.list_skills()]+ skill = await client.read_skill("skill://ops/deploy/SKILL.md")++ assert uris == ["skill://ops/deploy/SKILL.md", "skill://review/SKILL.md"]+ assert skill == Skill.from_directory(deploy)+++async def test_a_skill_folder_owns_everything_below_it(tmp_path: Path):+ outer = write_skill(tmp_path / "outer")+ write_skill(outer / "examples" / "inner")++ provider = SkillsDirectoryProvider(tmp_path)+ async with skills_client(FastMCP("Skills", providers=[provider])) as client:+ (entry,) = await client.list_skills()+ skill = await client.read_skill(entry.uri)++ assert entry.uri == "skill://outer/SKILL.md"+ assert "examples/inner/SKILL.md" in skill.files+++def test_invalid_folders_stop_startup_with_a_fix_for_each(tmp_path: Path):+ write_skill(tmp_path / "good")+ write_skill(tmp_path / "renamed", name="other")+ (tmp_path / "use_cli").mkdir()+ (tmp_path / "use_cli" / "SKILL.md").write_bytes(b"# Just text\n")+ (tmp_path / "bad-yaml").mkdir()+ (tmp_path / "bad-yaml" / "SKILL.md").write_bytes(b"---\nname: [\n---\n")++ with pytest.raises(ValueError, match="3 skill folder") as exc_info:+ SkillsDirectoryProvider(tmp_path)++ lines = str(exc_info.value).splitlines()[1:]+ assert [line.split(": ")[0] for line in lines] == [+ f"- {tmp_path / 'bad-yaml'}",+ f"- {tmp_path / 'renamed'}",+ f"- {tmp_path / 'use_cli'}",+ ]+ assert "rename the folder to 'use-cli'" in lines[2]+ assert "name: use-cli" in lines[2]+ assert "rename the folder" not in lines[1]+++def test_reload_also_validates_at_startup(tmp_path: Path):+ write_skill(tmp_path / "renamed", name="other")+ with pytest.raises(ValueError, match="must match"):+ SkillsDirectoryProvider(tmp_path, reload=True)+++async def test_hidden_folders_are_not_walked(tmp_path: Path):+ write_skill(tmp_path / ".system" / "secret")+ write_skill(tmp_path / ".hidden")+ write_skill(tmp_path / "review")++ assert await listed(SkillsDirectoryProvider(tmp_path)) == [+ "skill://review/SKILL.md"+ ]+++async def test_first_root_wins(tmp_path: Path):+ write_skill(tmp_path / "a" / "review", body="# First\n")+ write_skill(tmp_path / "b" / "review", body="# Second\n")+ write_skill(tmp_path / "b" / "deploy")++ provider = SkillsDirectoryProvider([tmp_path / "a", tmp_path / "b"])+ async with skills_client(FastMCP("Skills", providers=[provider])) as client:+ uris = [entry.uri for entry in await client.list_skills()]+ skill = await client.read_skill("skill://review/SKILL.md")++ assert uris == ["skill://deploy/SKILL.md", "skill://review/SKILL.md"]+ assert skill.files["SKILL.md"].endswith(b"# First\n")+++async def test_skill_nested_in_another_roots_skill_is_skipped(tmp_path: Path):+ write_skill(tmp_path / "a" / "ops")+ write_skill(tmp_path / "b" / "ops" / "deploy")++ provider = SkillsDirectoryProvider([tmp_path / "a", tmp_path / "b"])+ assert await listed(provider) == ["skill://ops/SKILL.md"]+++async def test_missing_root_serves_nothing(tmp_path: Path):+ assert await listed(SkillsDirectoryProvider(tmp_path / "missing")) == []++[email protected](sys.platform == "win32", reason="symlinks need privileges")+async def test_symlinked_skill_folder_is_followed(tmp_path: Path):+ target = write_skill(tmp_path / "elsewhere" / "review")+ root = tmp_path / "skills"+ root.mkdir()+ os.symlink(target, root / "review", target_is_directory=True)++ assert await listed(SkillsDirectoryProvider(root)) == ["skill://review/SKILL.md"]++[email protected](sys.platform == "win32", reason="symlinks need privileges")+def test_symlink_inside_a_skill_rejects_it(tmp_path: Path):+ folder = write_skill(tmp_path / "review")+ (tmp_path / "secret.txt").write_text("secret")+ os.symlink(tmp_path / "secret.txt", folder / "notes.md")++ with pytest.raises(ValueError, match="symlink"):+ SkillsDirectoryProvider(tmp_path)+++async def test_without_reload_folders_are_read_once(tmp_path: Path):+ folder = write_skill(tmp_path / "review", body="# Before\n")+ server = FastMCP("Skills", providers=[SkillsDirectoryProvider(tmp_path)])+ write_skill(folder, body="# After\n")+ write_skill(tmp_path / "deploy")++ async with skills_client(server) as client:+ uris = [entry.uri for entry in await client.list_skills()]+ skill = await client.read_skill("skill://review/SKILL.md")++ assert uris == ["skill://review/SKILL.md"]+ assert skill.files["SKILL.md"].endswith(b"# Before\n")+++async def test_reload_shows_edits_through_the_response_cache(tmp_path: Path):+ folder = write_skill(tmp_path / "review", body="# Before\n")+ server = FastMCP(+ "Skills",+ providers=[SkillsDirectoryProvider(tmp_path, reload=True)],+ middleware=[ResponseCachingMiddleware()],+ )++ async with skills_client(server) as client:+ before = await client.read_skill("skill://review/SKILL.md")+ write_skill(folder, body="# After\n")+ write_skill(tmp_path / "deploy")+ after = await client.read_skill("skill://review/SKILL.md")+ uris = [entry.uri for entry in await client.list_skills()]++ assert before.files["SKILL.md"].endswith(b"# Before\n")+ assert after.files["SKILL.md"].endswith(b"# After\n")+ assert uris == ["skill://deploy/SKILL.md", "skill://review/SKILL.md"]++[email protected](sys.platform == "win32", reason="symlinks need privileges")+def test_symlink_named_differently_from_its_skill_is_rejected(tmp_path: Path):+ target = write_skill(tmp_path / "elsewhere" / "review")+ root = tmp_path / "skills"+ root.mkdir()+ os.symlink(target, root / "renamed", target_is_directory=True)++ with pytest.raises(ValueError, match="renamed"):+ SkillsDirectoryProvider(root)+++async def test_unreadable_folder_is_skipped(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ write_skill(tmp_path / "review")+ locked = tmp_path / "lost+found"+ locked.mkdir()+ is_file = Path.is_file++ def deny(path: Path) -> bool:+ if path.parent == locked:+ raise PermissionError(13, "Permission denied", str(path))+ return is_file(path)++ monkeypatch.setattr(Path, "is_file", deny)+ provider = SkillsDirectoryProvider(tmp_path)+ monkeypatch.undo()++ assert await listed(provider) == ["skill://review/SKILL.md"]+++async def test_only_a_reloading_provider_claims_unknown_skill_uris(tmp_path: Path):+ write_skill(tmp_path / "review")++ fixed = SkillsDirectoryProvider(tmp_path)+ assert fixed._owns_skill_resource("skill://review/SKILL.md")+ assert not fixed._owns_skill_resource("skill://other/SKILL.md")+ assert SkillsDirectoryProvider(tmp_path, reload=True)._owns_skill_resource(+ "skill://other/SKILL.md"+ )+++async def test_reload_keeps_the_last_valid_skills_when_a_folder_breaks(tmp_path: Path):+ write_skill(tmp_path / "review")+ provider = SkillsDirectoryProvider(tmp_path, reload=True)+ async with skills_client(FastMCP("Skills", providers=[provider])) as client:+ (tmp_path / "Bad Skill").mkdir()+ (tmp_path / "Bad Skill" / "SKILL.md").write_text("hi")+ uris = [entry.uri for entry in await client.list_skills()]+ skill = await client.read_skill("skill://review/SKILL.md")++ assert uris == ["skill://review/SKILL.md"]+ assert skill.name == "review"