π The fast, Pythonic way to build MCP servers and clients.
Make Skill a storage-neutral object with folders as one loader (#6065)
nate nowack169d3b19474c
diff --git a/docs/servers/skills.mdx b/docs/servers/skills.mdxindex 6ca81b03d..9987646d5 100644--- a/docs/servers/skills.mdx+++ b/docs/servers/skills.mdx@@ -176,7 +176,7 @@ skill://server-authoring/SKILL.md - Build, extend, and review MCP servers in thiskill://server-authoring/references/testing.md 88 sha256:a4ea8ebc...```-Listing returns metadata only. The agent reads the files it needs through `resources/read`, and should check each file against its manifest record before using it:+`client.list_skills()` and `client.get_skill()` return `MCPSkill` objects: the wire record for a skill, not the skill itself. Listing returns metadata only. The agent reads the files it needs through `resources/read`, and should check each file against its manifest record before using it:```pythonimport asyncio@@ -219,6 +219,55 @@ A mismatch means the file changed between discovery and the read. Refresh the enThe client methods only transport entries. Deciding when to load a skill, asking a user to approve it, and running anything it describes are the host's job.+## Define skills in code++A skill doesn't have to live in a folder. `Skill` holds a skill's files in memory, and `SkillCatalogProvider` serves any list of them, so you can write skills in Python, ship them inside a package, or build them from a database. A folder is just one way to create a `Skill`.++<VersionBadge version="4.2.0" />++```python+from fastmcp import FastMCP+from fastmcp.skills.provider import SkillCatalogProvider+from fastmcp.skills import Skill+from fastmcp.skills.extension import SkillsExtension++release_notes = Skill(+ name="release-notes",+ description="Write release notes from merged pull requests.",+ instructions="# Release notes\n\nGroup changes by theme. Follow template.md.\n",+ files={"template.md": "## Highlights\n\n## Fixes\n"},+)+deploy = Skill.from_directory("skills/deploy")+review = Skill.from_package("my_package", "skills/review")++mcp = FastMCP("Skills")+skills = SkillCatalogProvider([release_notes, deploy, review])+mcp.add_provider(skills)+mcp.add_extension(SkillsExtension(providers=[skills]))+```++The constructor writes `SKILL.md` from `name`, `description`, `instructions`, and any extra `frontmatter`. `Skill.from_directory()` and `Skill.from_package()` read a folder once and keep its exact bytes, so later edits to the folder don't change the served skill. Every `Skill` is validated when you create it: frontmatter follows the same strict rules as discovery mode, and a folder's name must match the `name` in its `SKILL.md`.++`SkillCatalogProvider` serves each skill at `skill://{name}/` both as resources and through Skills discovery, so plain MCP clients, `sync_skills()`, and discovery clients all see the same files. Pass a mapping to choose the path, such as `{"team/review": review}`; the last segment must match the skill's name.++To serve skills that change at runtime, subclass the provider and override `load_skills()`. FastMCP calls it once per MCP request, and every lookup in that request sees the same skills.++```python+from fastmcp.skills.provider import SkillCatalogProvider+from fastmcp.skills import Skill+++# Stands in for your storage: one dict of files per skill.+SKILL_ROWS = [+ {"SKILL.md": "---\nname: triage\ndescription: Triage new issues.\n---\n# Triage\n"},+]+++class StoredSkills(SkillCatalogProvider):+ async def load_skills(self) -> list[Skill]:+ return [Skill.from_files(files) for files in SKILL_ROWS]+```+## Configure the provider### Search several roots@@ -280,7 +329,7 @@ mcp = FastMCP("Release Skill")mcp.add_provider(SkillProvider(Path("skills") / "server-authoring"))```-`SkillProvider` serves resources only; Skills discovery reads from `SkillsDirectoryProvider`.+`SkillProvider` serves resources only. For discovery, serve `Skill.from_directory(path)` with `SkillCatalogProvider`.### Serve a coding agent's skills folder@@ -326,7 +375,7 @@ Skills discovery respects the same rules as resource reads. A skill is omitted f## Current limits-Skills discovery currently serves skills from `SkillsDirectoryProvider` instances registered directly on the server you run.+Skills discovery currently serves skills from `SkillsDirectoryProvider` and `SkillCatalogProvider` instances registered directly on the server you run.- `SkillsExtension` raises when the server or the skills provider has transforms, including namespaces, or when the provider is not registered directly on the same server.- Skills in a [mounted server](/servers/composition) are served as resources through the parent, but the parent does not list them in `skills/list`.diff --git a/fastmcp_slim/fastmcp/client/mixins/skills.py b/fastmcp_slim/fastmcp/client/mixins/skills.pyindex 602f40d8c..d76f33835 100644--- a/fastmcp_slim/fastmcp/client/mixins/skills.py+++ b/fastmcp_slim/fastmcp/client/mixins/skills.py@@ -17,7 +17,7 @@ from fastmcp.skills.models import (ListSkillsParams,ListSkillsRequest,ListSkillsResult,- Skill,+ MCPSkill,)from fastmcp.telemetry import inject_trace_contextfrom fastmcp.utilities.logging import get_logger@@ -105,7 +105,7 @@ class ClientSkillsMixin:max_pages: int = AUTO_PAGINATION_MAX_PAGES,*,cache_mode: CacheMode = "use",- ) -> list[Skill]:+ ) -> list[MCPSkill]:"""Retrieve every page returned by `skills/list`.Args:@@ -119,7 +119,7 @@ class ClientSkillsMixin:RuntimeError: If Skills was not negotiated or the page limit is reached.MCPError: If the server rejects a request."""- skills: list[Skill] = []+ skills: list[MCPSkill] = []cursor: str | None = Noneseen_cursors: set[str] = set()@@ -196,7 +196,7 @@ class ClientSkillsMixin:uri: str,*,cache_mode: CacheMode = "use",- ) -> Skill:+ ) -> MCPSkill:"""Retrieve one skill entry by its `SKILL.md` resource URI.Args:diff --git a/fastmcp_slim/fastmcp/server/providers/skills/directory_provider.py b/fastmcp_slim/fastmcp/server/providers/skills/directory_provider.pyindex c0b09fcd4..bc648dead 100644--- a/fastmcp_slim/fastmcp/server/providers/skills/directory_provider.py+++ b/fastmcp_slim/fastmcp/server/providers/skills/directory_provider.py@@ -27,7 +27,7 @@ from fastmcp.server.providers.skills.skill_provider import ()from fastmcp.skills._resources import is_skill_filefrom fastmcp.skills._snapshot import Snapshot, snapshot-from fastmcp.skills.models import Skill+from fastmcp.skills.models import MCPSkillfrom fastmcp.utilities.logging import get_loggerfrom fastmcp.utilities.versions import VersionSpec@@ -374,7 +374,7 @@ class SkillsDirectoryProvider(AggregateProvider):provider = self._resource_provider(root, name, relative)return await provider.get_resource_template(uri, version)- async def _visible_entry(self, snap: Snapshot) -> Skill | None:+ async def _visible_entry(self, snap: Snapshot) -> MCPSkill | None:server = get_context().fastmcpfor uri, path in snap.files:component: Resource | ResourceTemplate | None = await server.get_resource(@@ -404,7 +404,7 @@ class SkillsDirectoryProvider(AggregateProvider):async def _list_skill_entries(self, context: ServerRequestContext[Any, Any]- ) -> Sequence[Skill]:+ ) -> Sequence[MCPSkill]:entries = []for snap in await run_sync(self._snapshots):entry = await self._visible_entry(snap)@@ -414,7 +414,7 @@ class SkillsDirectoryProvider(AggregateProvider):async def _get_skill_entry(self, uri: str, context: ServerRequestContext[Any, Any]- ) -> Skill | None:+ ) -> MCPSkill | None:parts = self._uri_parts(uri)if parts is None or parts[-1] != "SKILL.md":return Nonediff --git a/fastmcp_slim/fastmcp/skills/__init__.py b/fastmcp_slim/fastmcp/skills/__init__.pyindex 70e709b54..0d46da4cb 100644--- a/fastmcp_slim/fastmcp/skills/__init__.py+++ b/fastmcp_slim/fastmcp/skills/__init__.py@@ -1,17 +1,19 @@-"""Protocol support for the MCP Skills extension (SEP-2640)."""+"""Agent skills and protocol support for the MCP Skills extension (SEP-2640)."""from typing import TYPE_CHECKINGfrom fastmcp.skills.models import (GetSkillResult,ListSkillsResult,- Skill,+ MCPSkill,SkillFrontmatter,SkillResource,)+from fastmcp.skills.skill import Skill__all__ = ["GetSkillResult","ListSkillsResult",+ "MCPSkill","Skill","SkillFrontmatter","SkillResource",diff --git a/fastmcp_slim/fastmcp/skills/_snapshot.py b/fastmcp_slim/fastmcp/skills/_snapshot.pyindex 59d6221cb..3b78f9be3 100644--- a/fastmcp_slim/fastmcp/skills/_snapshot.py+++ b/fastmcp_slim/fastmcp/skills/_snapshot.py@@ -14,7 +14,7 @@ import yamlfrom mcp.shared.path_security import safe_joinfrom yaml.nodes import MappingNode-from fastmcp.skills.models import Skill, SkillFrontmatter, SkillResource+from fastmcp.skills.models import MCPSkill, SkillFrontmatter, SkillResource# SEP-2640 per-skill limits; servers should not serve skills that exceed them.MAX_SKILL_RESOURCES = 512@@ -90,7 +90,7 @@ def scan_files(root: Path) -> list[Path]:@dataclass(frozen=True)class Snapshot:- entry: Skill+ entry: MCPSkillfiles: tuple[tuple[str, Path], ...]@@ -125,7 +125,7 @@ def snapshot(root: Path, skill_path: str) -> Snapshot:if sum(record.size for record in records) > MAX_SKILL_BYTES:raise ValueError(f"skill is larger than {MAX_SKILL_BYTES} bytes")assert frontmatter is not None- entry = Skill(+ entry = MCPSkill(uri=f"skill://{quote(skill_path, safe='/')}/SKILL.md",frontmatter=frontmatter,resources=records,diff --git a/fastmcp_slim/fastmcp/skills/_source.py b/fastmcp_slim/fastmcp/skills/_source.pyindex 3f37a713d..c7a46b907 100644--- a/fastmcp_slim/fastmcp/skills/_source.py+++ b/fastmcp_slim/fastmcp/skills/_source.py@@ -7,7 +7,7 @@ from typing import Any, Protocol, runtime_checkablefrom mcp.server.context import ServerRequestContext-from fastmcp.skills.models import Skill+from fastmcp.skills.models import MCPSkill@runtime_checkable@@ -16,11 +16,11 @@ class _SkillSource(Protocol):async def _list_skill_entries(self, context: ServerRequestContext[Any, Any]- ) -> Sequence[Skill]: ...+ ) -> Sequence[MCPSkill]: ...async def _get_skill_entry(self, uri: str, context: ServerRequestContext[Any, Any]- ) -> Skill | None: ...+ ) -> MCPSkill | None: ...def _validate_skill_source(self) -> None:"""Reject sources that have not opted into protocol publication."""diff --git a/fastmcp_slim/fastmcp/skills/extension.py b/fastmcp_slim/fastmcp/skills/extension.pyindex 1a491ab66..f4a965f31 100644--- a/fastmcp_slim/fastmcp/skills/extension.py+++ b/fastmcp_slim/fastmcp/skills/extension.py@@ -68,7 +68,8 @@ class SkillsExtension(ServerExtension):)if not isinstance(provider, _SkillSource):raise TypeError(- f"{type(provider).__name__} is not a SkillsExtension source"+ f"{type(provider).__name__} is not a SkillsExtension source; "+ "use SkillCatalogProvider to publish Skill objects")provider._validate_skill_source()diff --git a/fastmcp_slim/fastmcp/skills/models.py b/fastmcp_slim/fastmcp/skills/models.pyindex 8bd8dec72..f8d100d81 100644--- a/fastmcp_slim/fastmcp/skills/models.py+++ b/fastmcp_slim/fastmcp/skills/models.py@@ -140,7 +140,7 @@ class SkillResource(BaseModel):return value-class Skill(BaseModel):+class MCPSkill(BaseModel):"""A complete SEP-2640 skill entry."""model_config = ConfigDict(extra="forbid")@@ -151,7 +151,7 @@ class Skill(BaseModel):meta: dict[str, JsonValue] | None = Field(default=None, alias="_meta")@model_validator(mode="after")- def validate_entry(self) -> Skill:+ def validate_entry(self) -> MCPSkill:scheme, authority, path_segments = _parse_resource_uri(self.uri)if not path_segments or path_segments[-1] != "SKILL.md":raise ValueError("uri must identify a SKILL.md resource")@@ -198,14 +198,14 @@ class GetSkillParams(mcp_types.RequestParams):class ListSkillsResult(mcp_types.PaginatedResult, mcp_types.CacheableResult):"""Result from `skills/list`."""- skills: list[Skill]+ skills: list[MCPSkill]result_type: Literal["complete"] = "complete"class GetSkillResult(mcp_types.CacheableResult):"""Result from `skills/get`."""- skill: Skill+ skill: MCPSkillresult_type: Literal["complete"] = "complete"diff --git a/fastmcp_slim/fastmcp/skills/provider.py b/fastmcp_slim/fastmcp/skills/provider.pynew file mode 100644index 000000000..d57660b98--- /dev/null+++ b/fastmcp_slim/fastmcp/skills/provider.py@@ -0,0 +1,266 @@+"""Provider that serves `Skill` objects defined in code or loaded from any source."""++from __future__ import annotations++import hashlib+import json+import mimetypes+from collections.abc import Iterable, Mapping, Sequence+from contextlib import suppress+from typing import Any, cast+from urllib.parse import quote, unquote++import anyio+from mcp.server.context import ServerRequestContext+from pydantic import AnyUrl, ConfigDict++from fastmcp.exceptions import AuthorizationError+from fastmcp.resources.base import Resource, ResourceContent, ResourceResult+from fastmcp.server.dependencies import get_context+from fastmcp.server.providers.base import Provider+from fastmcp.skills.models import MCPSkill+from fastmcp.skills.skill import Skill, _validate_relative_path+from fastmcp.utilities.logging import get_logger+from fastmcp.utilities.versions import VersionSpec++logger = get_logger(__name__)++mimetypes.add_type("text/markdown", ".md")++SkillCatalog = Mapping[str, Skill] | Iterable[Skill]+++class SkillFileResource(Resource):+ """One file of a `Skill`, served with its exact bytes."""++ model_config = ConfigDict(arbitrary_types_allowed=True)++ skill: Skill+ skill_path: str+ file_path: str++ async def read(self) -> ResourceResult:+ content = self.skill.files[self.file_path]+ value: str | bytes = content+ if self.mime_type.startswith("text/"):+ with suppress(UnicodeDecodeError):+ value = content.decode("utf-8")+ return ResourceResult([ResourceContent(value, mime_type=self.mime_type)])+++class SkillManifestResource(Resource):+ """The resource-mode `_manifest` listing used by `sync_skills` and `download_skill`."""++ model_config = ConfigDict(arbitrary_types_allowed=True)++ skill: Skill++ async def read(self) -> str:+ files = [+ {+ "path": path,+ "size": len(content),+ "hash": f"sha256:{hashlib.sha256(content).hexdigest()}",+ }+ for path, content in self.skill.files.items()+ ]+ return json.dumps({"skill": self.skill.name, "files": files}, indent=2)+++class SkillCatalogProvider(Provider):+ """Serve `Skill` objects as MCP resources and Skills extension entries.++ Each skill's files are served under `skill://{path}/`, where `path` defaults+ to the skill's name. Pass a mapping to choose paths; the last path segment+ must equal the skill's name. Every client can read the files as resources,+ and the provider can be passed to `SkillsExtension` for `skills/list` and+ `skills/get` discovery.++ For skills that change at runtime, such as rows in a database, subclass and+ override `load_skills()`. It is called once per MCP request.++ Example:+ ```python+ from fastmcp import FastMCP+ from fastmcp.skills.provider import SkillCatalogProvider+ from fastmcp.skills import Skill+ from fastmcp.skills.extension import SkillsExtension++ review = Skill(+ name="code-review",+ description="Review a pull request for correctness and style.",+ instructions="# Code review\\n\\nRead the diff first...",+ )++ mcp = FastMCP("Skills")+ skills = SkillCatalogProvider([review, Skill.from_directory("./skills/deploy")])+ mcp.add_provider(skills)+ mcp.add_extension(SkillsExtension(providers=[skills]))+ ```+ """++ def __init__(self, skills: SkillCatalog | None = None) -> None:+ super().__init__()+ self._static = _normalize(skills or ())++ async def load_skills(self) -> SkillCatalog:+ """Return the skills to serve. Override to load them from another source."""+ return self._static++ async def _catalog(self) -> dict[str, Skill]:+ context = None+ with suppress(RuntimeError):+ context = get_context()+ if context is None:+ return _normalize(await self.load_skills())+ # Concurrent lookups in one request wait on the same lock, so+ # load_skills() runs once and every caller sees the same catalog.+ key = f"_fastmcp_skill_catalog:{id(self)}"+ lock = context._request_state.setdefault(f"{key}:lock", anyio.Lock())+ async with lock:+ if key not in context._request_state:+ context._request_state[key] = _normalize(await self.load_skills())+ return context._request_state[key]++ # -------------------------------------------------------------------------+ # Resources+ # -------------------------------------------------------------------------++ async def _list_resources(self) -> Sequence[Resource]:+ resources: list[Resource] = []+ for path, skill in (await self._catalog()).items():+ resources.extend(_file_resource(path, skill, file) for file in skill.files)+ resources.append(_manifest_resource(path, skill))+ return resources++ async def _get_resource(+ self, uri: str, version: VersionSpec | None = None+ ) -> Resource | None:+ located = _locate(uri, await self._catalog())+ if located is None:+ return None+ path, skill, file = located+ if file == "_manifest":+ return _manifest_resource(path, skill)+ if file in skill.files:+ return _file_resource(path, skill, file)+ return None++ # -------------------------------------------------------------------------+ # Skills extension source+ # -------------------------------------------------------------------------++ def _owns_skill_resource(self, uri: str) -> bool:+ # A static catalog knows its URIs; a loaded one may serve any skill:// URI.+ if type(self).load_skills is SkillCatalogProvider.load_skills:+ return _locate(uri, self._static) is not None+ return uri.startswith("skill://")++ def _validate_skill_source(self) -> None:+ return None++ async def _skill_uris(self, uri: str | None = None) -> Sequence[str]:+ uris = [_skill_md_uri(path) for path in await self._catalog()]+ return uris if uri is None else [u for u in uris if u == uri]++ async def _list_skill_entries(+ self, context: ServerRequestContext[Any, Any]+ ) -> Sequence[MCPSkill]:+ return [+ skill.to_mcp_skill(path)+ for path, skill in (await self._catalog()).items()+ if await self._is_served(path, skill)+ ]++ async def _get_skill_entry(+ self, uri: str, context: ServerRequestContext[Any, Any]+ ) -> MCPSkill | None:+ for path, skill in (await self._catalog()).items():+ if _skill_md_uri(path) == uri and await self._is_served(path, skill):+ return skill.to_mcp_skill(path)+ return None++ async def _is_served(self, path: str, skill: Skill) -> bool:+ """Advertise a skill only when this caller can read every file, byte for byte."""+ server = get_context().fastmcp+ for file in skill.files:+ uri = _file_uri(path, file)+ served = await server.get_resource(uri)+ if not isinstance(served, SkillFileResource) or served.skill != skill:+ return False+ try:+ await server._check_resource_access(uri)+ except AuthorizationError:+ return False+ return True++ def __repr__(self) -> str:+ return f"{type(self).__name__}()"+++def _normalize(skills: SkillCatalog) -> dict[str, Skill]:+ if isinstance(skills, Mapping):+ mapping = cast("Mapping[str, Skill]", skills)+ catalog = {+ _validate_relative_path(path): skill for path, skill in mapping.items()+ }+ else:+ catalog = {}+ for skill in skills:+ if skill.name in catalog:+ raise ValueError(f"Duplicate skill name: {skill.name!r}")+ catalog[skill.name] = skill+ for path, skill in catalog.items():+ if not isinstance(skill, Skill):+ raise TypeError(f"Expected a Skill at {path!r}, got {type(skill).__name__}")+ if path.split("/")[-1] != skill.name:+ raise ValueError(+ f"Skill path {path!r} must end with the skill's name {skill.name!r}"+ )+ for path in catalog:+ parts = path.split("/")+ for index in range(1, len(parts)):+ if "/".join(parts[:index]) in catalog:+ raise ValueError(f"Skill path {path!r} is nested inside another skill")+ return catalog+++def _file_uri(path: str, file: str) -> str:+ return f"skill://{quote(path, safe='/')}/{quote(file, safe='/')}"+++def _skill_md_uri(path: str) -> str:+ return _file_uri(path, "SKILL.md")+++def _locate(uri: str, catalog: Mapping[str, Skill]) -> tuple[str, Skill, str] | None:+ if not uri.startswith("skill://"):+ return None+ decoded = unquote(uri[len("skill://") :])+ for path, skill in catalog.items():+ if decoded.startswith(f"{path}/"):+ return path, skill, decoded[len(path) + 1 :]+ return None+++def _file_resource(path: str, skill: Skill, file: str) -> SkillFileResource:+ mime_type = mimetypes.guess_type(file)[0] or "application/octet-stream"+ return SkillFileResource(+ uri=AnyUrl(_file_uri(path, file)),+ name=f"{path}/{file}",+ description=skill.description if file == "SKILL.md" else None,+ mime_type=mime_type,+ skill=skill,+ skill_path=path,+ file_path=file,+ )+++def _manifest_resource(path: str, skill: Skill) -> SkillManifestResource:+ return SkillManifestResource(+ uri=AnyUrl(_file_uri(path, "_manifest")),+ name=f"{path}/_manifest",+ description=f"File listing for {skill.name}",+ mime_type="application/json",+ skill=skill,+ )diff --git a/fastmcp_slim/fastmcp/skills/skill.py b/fastmcp_slim/fastmcp/skills/skill.pynew file mode 100644index 000000000..ecbf7f5d7--- /dev/null+++ b/fastmcp_slim/fastmcp/skills/skill.py@@ -0,0 +1,221 @@+"""Storage-neutral agent skills."""++from __future__ import annotations++import hashlib+import os+from collections.abc import Mapping+from pathlib import Path+from types import MappingProxyType+from typing import Any+from urllib.parse import quote++from pydantic import JsonValue++from fastmcp.skills.models import MCPSkill, SkillFrontmatter, SkillResource++# SEP-2640 per-skill limits; servers should not serve skills that exceed them.+MAX_SKILL_FILES = 512+MAX_SKILL_BYTES = 16 * 1024 * 1024+++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")+ if path.startswith("/") or "\\" in path or "\x00" in path:+ raise ValueError(f"Skill file path must be relative POSIX: {path!r}")+ parts = path.split("/")+ if any(part in {"", ".", ".."} for part in parts):+ raise ValueError(f"Skill file path contains an invalid segment: {path!r}")+ return path+++def _render_skill_md(frontmatter: Mapping[str, JsonValue], instructions: str) -> bytes:+ import yaml++ header = yaml.safe_dump(dict(frontmatter), sort_keys=False, allow_unicode=True)+ return f"---\n{header}---\n{instructions}".encode()+++class Skill:+ """An agent skill: a `SKILL.md` plus supporting files, independent of storage.++ A `Skill` holds exact file bytes. It doesn't know where it came from or which+ URI it is served under; a provider decides that. Author one in Python with the+ keyword constructor, or snapshot one from a directory, package, or mapping of+ files.++ Example:+ ```python+ from fastmcp.skills import Skill++ skill = Skill(+ name="release-notes",+ description="Write release notes from merged pull requests.",+ instructions="# Release notes\\n\\nGroup changes by theme...",+ files={"template.md": "## Highlights\\n"},+ )+ ```+ """++ __slots__ = ("_files", "_frontmatter")++ _files: Mapping[str, bytes]+ _frontmatter: SkillFrontmatter++ def __init__(+ self,+ *,+ name: str,+ description: str,+ instructions: str,+ files: Mapping[str, str | bytes] | None = None,+ frontmatter: Mapping[str, JsonValue] | None = None,+ ) -> None:+ extra = dict(frontmatter or {})+ for key in ("name", "description"):+ if key in extra:+ raise ValueError(f"Pass {key!r} as a Skill argument, not frontmatter")+ header = SkillFrontmatter.model_validate(+ {"name": name, "description": description, **extra}+ )+ contents: dict[str, str | bytes] = {+ "SKILL.md": _render_skill_md(header.root, instructions)+ }+ for path, content in (files or {}).items():+ if path == "SKILL.md":+ raise ValueError("Pass SKILL.md content as `instructions`")+ contents[path] = content+ self._initialize(contents)++ def _initialize(self, files: Mapping[str, str | bytes]) -> None:+ from fastmcp.skills._snapshot import parse_frontmatter++ normalized: dict[str, bytes] = {}+ for path, content in files.items():+ clean = _validate_relative_path(path)+ normalized[clean] = (+ content.encode("utf-8") if isinstance(content, str) else bytes(content)+ )+ 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")+ for path in normalized:+ parts = path.split("/")+ for index in range(1, len(parts)):+ if "/".join(parts[:index]) in normalized:+ raise ValueError(+ f"Skill file is also used as a directory: {path!r}"+ )+ object.__setattr__(+ self, "_frontmatter", parse_frontmatter(normalized["SKILL.md"])+ )+ object.__setattr__(+ self, "_files", MappingProxyType(dict(sorted(normalized.items())))+ )++ def __setattr__(self, name: str, value: object) -> None:+ raise AttributeError("Skill is immutable")++ @classmethod+ def from_files(cls, files: Mapping[str, str | bytes]) -> Skill:+ """Create a skill from relative paths mapped to text or bytes.++ `files` must include `SKILL.md` with valid frontmatter.+ """+ skill = object.__new__(cls)+ skill._initialize(files)+ return skill++ @classmethod+ def from_directory(cls, path: str | os.PathLike[str]) -> Skill:+ """Read a skill folder once and return an immutable snapshot.++ The folder name must match the `name` in its `SKILL.md`. Symlinks and+ special files are rejected, so a snapshot never reaches outside the folder.+ """+ 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)+ }+ skill = cls.from_files(files)+ if skill.name != root.name:+ raise ValueError(+ f"Skill folder {root.name!r} must match its SKILL.md name {skill.name!r}"+ )+ return skill++ @classmethod+ def from_package(cls, package: str, path: str) -> Skill:+ """Load a skill folder shipped as package data, such as `("my_pkg", "skills/review")`."""+ from importlib.resources import files as package_files++ clean = _validate_relative_path(path)+ root = package_files(package).joinpath(*clean.split("/"))+ if not root.is_dir():+ raise ValueError(f"Skill package path is not a directory: {package}:{path}")+ contents: dict[str, bytes] = {}++ def visit(directory: Any, prefix: str) -> None:+ for entry in directory.iterdir():+ relative = f"{prefix}{entry.name}"+ if entry.is_dir():+ visit(entry, f"{relative}/")+ elif entry.is_file():+ contents[relative] = entry.read_bytes()++ visit(root, "")+ skill = cls.from_files(contents)+ if skill.name != root.name:+ raise ValueError(+ f"Skill folder {root.name!r} must match its SKILL.md name {skill.name!r}"+ )+ return skill++ @property+ def name(self) -> str:+ return self._frontmatter.name++ @property+ def description(self) -> str:+ return self._frontmatter.description++ @property+ def frontmatter(self) -> SkillFrontmatter:+ """A copy of the parsed frontmatter; changing it does not change the skill."""+ return self._frontmatter.model_copy(deep=True)++ @property+ def files(self) -> Mapping[str, bytes]:+ """Every file in the skill, keyed by relative path, including `SKILL.md`."""+ return self._files++ def to_mcp_skill(self, path: str | None = None) -> MCPSkill:+ """Build the Skills extension entry for this skill served at `skill://{path}/`."""+ prefix = f"skill://{quote(path or self.name, safe='/')}/"+ resources = [+ SkillResource(+ uri=prefix + quote(relative, safe="/"),+ digest=f"sha256:{hashlib.sha256(content).hexdigest()}",+ size=len(content),+ )+ for relative, content in self._files.items()+ ]+ return MCPSkill(+ uri=f"{prefix}SKILL.md", frontmatter=self.frontmatter, resources=resources+ )++ def __eq__(self, other: object) -> bool:+ return isinstance(other, Skill) and self._files == other._files++ def __hash__(self) -> int:+ return hash(tuple(self._files.items()))++ def __repr__(self) -> str:+ return f"Skill(name={self.name!r}, files={len(self._files)})"diff --git a/tests/client/test_slim_package_boundaries.py b/tests/client/test_slim_package_boundaries.pyindex a24f468e6..8ea5d1245 100644--- a/tests/client/test_slim_package_boundaries.py+++ b/tests/client/test_slim_package_boundaries.py@@ -94,10 +94,12 @@ def test_bare_slim_import_needs_only_mcp_types() -> None:import fastmcpimport fastmcp.settingsimport fastmcp.types- from fastmcp.skills import Skill- from fastmcp.skills.models import Skill as DirectSkill+ from fastmcp.skills import Skill, MCPSkill+ from fastmcp.skills.models import MCPSkill as DirectMCPSkill+ from fastmcp.skills.skill import Skill as DirectSkillassert Skill is DirectSkill+ assert MCPSkill is DirectMCPSkillassert "mcp_types" in sys.modules, "mcp_types should load on a bare install"assert "mcp" not in sys.modules, "full mcp must not load on a bare install"diff --git a/tests/skills/test_client_cache.py b/tests/skills/test_client_cache.pyindex be9bbd3fb..913f7fcc4 100644--- a/tests/skills/test_client_cache.py+++ b/tests/skills/test_client_cache.py@@ -6,13 +6,13 @@ import pytestfrom mcp.client.caching import CacheEntry, CacheKeyfrom fastmcp.client.caching import KeyValueResponseCacheStore-from fastmcp.skills.models import GetSkillResult, ListSkillsResult, Skill+from fastmcp.skills.models import GetSkillResult, ListSkillsResult, MCPSkillDIGEST = f"sha256:{'a' * 64}"-def make_skill() -> Skill:- return Skill.model_validate(+def make_skill() -> MCPSkill:+ return MCPSkill.model_validate({"uri": "skill://review/SKILL.md","frontmatter": {diff --git a/tests/skills/test_extension.py b/tests/skills/test_extension.pyindex bc7566c68..384f79213 100644--- a/tests/skills/test_extension.py+++ b/tests/skills/test_extension.py@@ -20,7 +20,7 @@ from fastmcp.resources.base import Resourcefrom fastmcp.resources.function_resource import FunctionResourcefrom fastmcp.server.providers import Providerfrom fastmcp.server.transforms import Namespace-from fastmcp.skills import Skill, SkillsClientExtension+from fastmcp.skills import MCPSkill, SkillsClientExtensionfrom fastmcp.skills._constants import SKILLS_EXTENSION_IDfrom fastmcp.skills.extension import SkillsExtensionfrom fastmcp.skills.models import (@@ -36,9 +36,9 @@ SKILL_CONTENT = "# Review\n"DIGEST = f"sha256:{hashlib.sha256(SKILL_CONTENT.encode()).hexdigest()}"-def make_skill(name: str) -> Skill:+def make_skill(name: str) -> MCPSkill:uri = f"skill://{name}/SKILL.md"- return Skill.model_validate(+ return MCPSkill.model_validate({"uri": uri,"frontmatter": {"name": name, "description": f"Use {name}"},@@ -53,8 +53,8 @@ class MemorySkillProvider(Provider):def __init__(self,*,- listed: Sequence[Skill],- addressable: Sequence[Skill] | None = None,+ listed: Sequence[MCPSkill],+ addressable: Sequence[MCPSkill] | None = None,) -> None:super().__init__()self.listed = list(listed)@@ -75,13 +75,13 @@ class MemorySkillProvider(Provider):async def _list_skill_entries(self, context: ServerRequestContext[Any, Any]- ) -> Sequence[Skill]:+ ) -> Sequence[MCPSkill]:self.contexts.append(context)return self.listedasync def _get_skill_entry(self, uri: str, context: ServerRequestContext[Any, Any]- ) -> Skill | None:+ ) -> MCPSkill | None:self.contexts.append(context)return self.addressable.get(uri)diff --git a/tests/skills/test_models.py b/tests/skills/test_models.pyindex 900314c61..a0ac1be5d 100644--- a/tests/skills/test_models.py+++ b/tests/skills/test_models.py@@ -8,7 +8,7 @@ from pydantic import ValidationErrorfrom fastmcp.skills.models import (GetSkillResult,ListSkillsResult,- Skill,+ MCPSkill,SkillFrontmatter,SkillResource,)@@ -16,7 +16,7 @@ from fastmcp.skills.models import (DIGEST = f"sha256:{'a' * 64}"-def make_skill(**overrides: object) -> Skill:+def make_skill(**overrides: object) -> MCPSkill:values: dict[str, object] = {"uri": "skill://acme/review/SKILL.md","frontmatter": {@@ -34,7 +34,7 @@ def make_skill(**overrides: object) -> Skill:],}values.update(overrides)- return Skill.model_validate(values)+ return MCPSkill.model_validate(values)def test_frontmatter_preserves_unknown_json_fields() -> None:diff --git a/tests/skills/test_provider.py b/tests/skills/test_provider.pynew file mode 100644index 000000000..55e05c986--- /dev/null+++ b/tests/skills/test_provider.py@@ -0,0 +1,196 @@+from __future__ import annotations++import base64+import hashlib+import json+from collections.abc import Iterable+from pathlib import Path++import anyio+import pytest+from mcp.shared.exceptions import MCPError+from mcp_types import BlobResourceContents, TextResourceContents++from fastmcp import Client, FastMCP+from fastmcp.server.middleware import Middleware+from fastmcp.server.middleware.authorization import AuthMiddleware+from fastmcp.skills import Skill, SkillsClientExtension+from fastmcp.skills.extension import SkillsExtension+from fastmcp.skills.provider import SkillCatalogProvider+from fastmcp.utilities.skills import list_skill_summaries, sync_skills++REVIEW = Skill(+ name="review",+ description="Review changes",+ instructions="# Review\r\n\r\nRead notes.md first.\r\n",+ files={"notes.md": "line one\r\n", "refs/logo.bin": b"\x00\xff\r\n"},+)+DEPLOY = Skill(name="deploy", description="Deploy the app", instructions="# Deploy\n")+++def serve(+ provider: SkillCatalogProvider, middleware: list[Middleware] | None = None+) -> FastMCP:+ server = FastMCP("Skills", providers=[provider], middleware=middleware)+ server.add_extension(SkillsExtension(providers=[provider]))+ return server+++def skills_client(server: FastMCP) -> Client:+ return Client(server, mode="auto", extensions=[SkillsClientExtension()])+++async def read_bytes(client: Client, uri: str) -> bytes:+ (content,) = await client.read_resource(uri)+ if isinstance(content, TextResourceContents):+ return content.text.encode()+ assert isinstance(content, BlobResourceContents)+ return base64.b64decode(content.blob)+++async def test_discovery_round_trip_preserves_bytes():+ server = serve(SkillCatalogProvider({"team/review": REVIEW, "deploy": DEPLOY}))+ async with skills_client(server) as client:+ entries = await client.list_skills()+ assert [entry.uri for entry in entries] == [+ "skill://deploy/SKILL.md",+ "skill://team/review/SKILL.md",+ ]+ for entry in entries:+ assert await client.get_skill(entry.uri) == entry+ assert isinstance(entry.resources, list)+ for record in entry.resources:+ data = await read_bytes(client, record.uri)+ assert f"sha256:{hashlib.sha256(data).hexdigest()}" == record.digest+++async def test_resources_work_without_the_extension():+ server = FastMCP("Skills", providers=[SkillCatalogProvider([REVIEW])])+ async with Client(server) as client:+ uris = sorted(str(r.uri) for r in await client.list_resources())+ assert uris == [+ "skill://review/SKILL.md",+ "skill://review/_manifest",+ "skill://review/notes.md",+ "skill://review/refs/logo.bin",+ ]+ assert await read_bytes(client, "skill://review/refs/logo.bin") == (+ b"\x00\xff\r\n"+ )+ manifest = json.loads(await read_bytes(client, "skill://review/_manifest"))+ assert {f["path"] for f in manifest["files"]} == set(REVIEW.files)+ summaries = await list_skill_summaries(client)+ assert [(s.name, s.description) for s in summaries] == [+ ("review", "Review changes")+ ]+++async def test_sync_skills_installs_code_defined_skills(tmp_path: Path):+ server = FastMCP("Skills", providers=[SkillCatalogProvider([REVIEW, DEPLOY])])+ async with Client(server) as client:+ await sync_skills(client, tmp_path)+ # download_skill writes text files in text mode, so compare file sets and+ # binary bytes rather than exact text bytes (Windows translates newlines).+ for skill in (REVIEW, DEPLOY):+ installed = Skill.from_directory(tmp_path / skill.name)+ assert installed.frontmatter == skill.frontmatter+ assert set(installed.files) == set(skill.files)+ review = Skill.from_directory(tmp_path / "review")+ assert review.files["refs/logo.bin"] == REVIEW.files["refs/logo.bin"]+++async def test_load_skills_is_called_once_per_request():+ calls = 0++ class Database(SkillCatalogProvider):+ async def load_skills(self) -> Iterable[Skill]:+ nonlocal calls+ calls += 1+ return [REVIEW, DEPLOY]++ server = serve(Database())+ async with skills_client(server) as client:+ calls = 0+ assert len(await client.list_skills()) == 2+ assert calls == 1+++async def test_concurrent_lookups_share_one_load():+ calls = 0++ class Slow(SkillCatalogProvider):+ async def load_skills(self) -> Iterable[Skill]:+ nonlocal calls+ calls += 1+ await anyio.sleep(0.01)+ return [REVIEW]++ server = FastMCP("Skills", providers=[Slow()])++ @server.tool+ async def read_two() -> None:+ async with anyio.create_task_group() as tg:+ tg.start_soon(server.get_resource, "skill://review/SKILL.md")+ tg.start_soon(server.get_resource, "skill://review/notes.md")++ async with Client(server) as client:+ calls = 0+ await client.call_tool("read_two")+ assert calls == 1+++async def test_runtime_catalog_changes_are_visible():+ current = [REVIEW]++ class Dynamic(SkillCatalogProvider):+ async def load_skills(self) -> Iterable[Skill]:+ return list(current)++ server = serve(Dynamic())+ async with skills_client(server) as client:+ assert [e.frontmatter.name for e in await client.list_skills()] == ["review"]+ current.append(DEPLOY)+ assert [e.frontmatter.name for e in await client.list_skills()] == [+ "deploy",+ "review",+ ]++[email protected]("denied", ["review/SKILL.md", "review/notes.md"])+async def test_denied_file_hides_skill(denied: str):+ blocked = {denied}+ server = serve(+ SkillCatalogProvider([REVIEW]),+ middleware=[AuthMiddleware(auth=lambda ctx: ctx.component.name not in blocked)],+ )+ async with skills_client(server) as client:+ assert await client.list_skills() == []+ with pytest.raises(MCPError, match="Unknown skill URI"):+ await client.get_skill("skill://review/SKILL.md")+ blocked.clear()+ assert len(await client.list_skills()) == 1+++async def test_shadowed_file_hides_skill():+ server = serve(SkillCatalogProvider([REVIEW]))++ @server.resource("skill://review/notes.md")+ def shadow() -> str:+ return "different bytes"++ async with skills_client(server) as client:+ assert await client.list_skills() == []+++ "skills, message",+ [+ ([REVIEW, REVIEW], "Duplicate skill name"),+ ({"team/other": REVIEW}, "must end with"),+ ({"review": REVIEW, "review/sub/deploy": DEPLOY}, "nested"),+ ({"../review": REVIEW}, "invalid segment"),+ ],+)+def test_invalid_catalogs(skills: object, message: str):+ with pytest.raises(ValueError, match=message):+ SkillCatalogProvider(skills) # ty: ignore[invalid-argument-type]diff --git a/tests/skills/test_skill.py b/tests/skills/test_skill.pynew file mode 100644index 000000000..271135661--- /dev/null+++ b/tests/skills/test_skill.py@@ -0,0 +1,140 @@+from __future__ import annotations++import hashlib+import os+import sys+from pathlib import Path++import pytest++from fastmcp.skills import Skill+++def write_skill(root: Path, name: str = "review") -> Path:+ folder = root / name+ (folder / "refs").mkdir(parents=True)+ (folder / "SKILL.md").write_bytes(+ f"---\r\nname: {name}\r\ndescription: Review changes\r\n---\r\n# Review\r\n".encode()+ )+ (folder / "refs" / "checklist.md").write_bytes(b"- tests\n")+ (folder / "logo.bin").write_bytes(b"\x00\xff")+ return folder+++def test_keyword_constructor_renders_skill_md():+ skill = Skill(+ name="release-notes",+ description="Write release notes.",+ instructions="# Release notes\n",+ files={"template.md": "## Highlights\n", "data.bin": b"\x00"},+ frontmatter={"license": "MIT"},+ )++ assert skill.name == "release-notes"+ assert skill.description == "Write release notes."+ assert skill.frontmatter.license == "MIT"+ assert list(skill.files) == ["SKILL.md", "data.bin", "template.md"]+ assert skill.files["SKILL.md"].endswith(b"---\n# Release notes\n")+ assert Skill.from_files(skill.files) == skill+++ "kwargs, message",+ [+ ({"name": "Bad Name"}, "name must be"),+ ({"description": ""}, "description must"),+ ({"frontmatter": {"name": "x"}}, "Pass 'name'"),+ ({"files": {"SKILL.md": "x"}}, "instructions"),+ ({"files": {"../escape.md": "x"}}, "invalid segment"),+ ({"files": {"/abs.md": "x"}}, "relative POSIX"),+ ({"files": {"a": "x", "a/b": "y"}}, "also used as a directory"),+ ],+)+def test_constructor_rejects_invalid_skills(kwargs: dict[str, object], message: str):+ arguments: dict[str, object] = {+ "name": "review",+ "description": "Review changes",+ "instructions": "# Review\n",+ **kwargs,+ }+ with pytest.raises(ValueError, match=message):+ Skill(**arguments) # ty: ignore[invalid-argument-type]+++def test_from_files_requires_valid_frontmatter():+ with pytest.raises(ValueError, match="SKILL.md"):+ Skill.from_files({"notes.md": "x"})+ with pytest.raises(ValueError, match="frontmatter"):+ Skill.from_files({"SKILL.md": "# no frontmatter\n"})+++def test_from_directory_snapshots_exact_bytes(tmp_path: Path):+ folder = write_skill(tmp_path)+ skill = Skill.from_directory(folder)++ assert skill.files == {+ "SKILL.md": (folder / "SKILL.md").read_bytes(),+ "logo.bin": b"\x00\xff",+ "refs/checklist.md": b"- tests\n",+ }+ (folder / "refs" / "checklist.md").write_bytes(b"changed")+ assert skill.files["refs/checklist.md"] == b"- tests\n"+++def test_from_directory_requires_matching_name(tmp_path: Path):+ folder = write_skill(tmp_path)+ renamed = folder.rename(tmp_path / "other")+ with pytest.raises(ValueError, match="must match"):+ Skill.from_directory(renamed)++[email protected](sys.platform == "win32", reason="symlinks need privileges")+def test_from_directory_rejects_symlinks(tmp_path: Path):+ folder = write_skill(tmp_path)+ outside = tmp_path / "secret.txt"+ outside.write_text("secret")+ os.symlink(outside, folder / "link.txt")+ with pytest.raises(ValueError, match="symlink"):+ Skill.from_directory(folder)+++def test_from_package(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ package = tmp_path / "skillpkg"+ (package / "skills").mkdir(parents=True)+ (package / "__init__.py").write_text("")+ write_skill(package / "skills")+ monkeypatch.syspath_prepend(str(tmp_path))++ skill = Skill.from_package("skillpkg", "skills/review")++ assert skill == Skill.from_directory(package / "skills" / "review")+++def test_skill_is_immutable():+ skill = Skill(name="review", description="Review", instructions="")+ with pytest.raises(AttributeError):+ skill.name = "other" # ty: ignore[invalid-assignment]+ with pytest.raises(TypeError):+ skill.files["SKILL.md"] = b"" # ty: ignore[invalid-assignment]+++def test_frontmatter_changes_do_not_leak_into_the_skill():+ skill = Skill(name="review", description="Review", instructions="")+ skill.frontmatter.root["description"] = "changed"+ skill.to_mcp_skill().frontmatter.root["description"] = "changed"+ assert skill.description == "Review"+ assert skill.to_mcp_skill().frontmatter.description == "Review"+++def test_to_mcp_skill_describes_every_file(tmp_path: Path):+ skill = Skill.from_directory(write_skill(tmp_path))+ entry = skill.to_mcp_skill("team/review")++ assert entry.uri == "skill://team/review/SKILL.md"+ assert entry.frontmatter == skill.frontmatter+ assert isinstance(entry.resources, list)+ records = {record.uri: record for record in entry.resources}+ for path, content in skill.files.items():+ record = records[f"skill://team/review/{path}"]+ assert record.size == len(content)+ assert record.digest == f"sha256:{hashlib.sha256(content).hexdigest()}"