Skip to content

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

Add SkillManifestProvider to serve skills without loading their files (#6465)

Jake Kaplan937d4beab193
diff --git a/docs/servers/skills.mdx b/docs/servers/skills.mdx
index cf1969c58..5c80fdebc 100644
--- a/docs/servers/skills.mdx
+++ b/docs/servers/skills.mdx
@@ -70,6 +70,32 @@ class StoredSkills(SkillCatalogProvider):
]
```
+A `Skill` holds the bytes of every file, so a catalog of large skills is a lot to keep in memory. When the files already live somewhere else, such as object storage, subclass `SkillManifestProvider` instead. Discovery only needs each skill's frontmatter and the digest and size of each file, which a `SkillManifest` holds. FastMCP calls `read_file()` only when a client reads that file.
+
+```python
+from fastmcp import FastMCP
+from fastmcp.skills import Skill, SkillManifest
+from fastmcp.skills.provider import SkillFileResource, SkillManifestProvider
+
+review = Skill(name="review", description="Review changes.", instructions="# Review\n")
+blobs = {
+ file.digest: review.files[path] for path, file in review.manifest.files.items()
+}
+
+
+class StoredSkills(SkillManifestProvider):
+ async def load_manifests(self) -> dict[str, SkillManifest]:
+ return {"review": review.manifest}
+
+ async def read_file(self, resource: SkillFileResource) -> bytes:
+ return blobs[resource.file.digest]
+
+
+mcp = FastMCP("Stored Skills", providers=[StoredSkills()])
+```
+
+Like `load_skills()`, `load_manifests()` runs once per request. Clients check what they read against the manifest, so `read_file()` must return exactly the bytes each digest describes, and the frontmatter in `SKILL.md` must match the manifest's.
+
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:
```python
diff --git a/fastmcp_slim/fastmcp/skills/__init__.py b/fastmcp_slim/fastmcp/skills/__init__.py
index 0d46da4cb..35223bc06 100644
--- a/fastmcp_slim/fastmcp/skills/__init__.py
+++ b/fastmcp_slim/fastmcp/skills/__init__.py
@@ -8,14 +8,16 @@ from fastmcp.skills.models import (
SkillFrontmatter,
SkillResource,
)
-from fastmcp.skills.skill import Skill
+from fastmcp.skills.skill import Skill, SkillFile, SkillManifest
__all__ = [
"GetSkillResult",
"ListSkillsResult",
"MCPSkill",
"Skill",
+ "SkillFile",
"SkillFrontmatter",
+ "SkillManifest",
"SkillResource",
"SkillsClientExtension",
]
diff --git a/fastmcp_slim/fastmcp/skills/provider.py b/fastmcp_slim/fastmcp/skills/provider.py
index 992ce2ece..3f3e11b19 100644
--- a/fastmcp_slim/fastmcp/skills/provider.py
+++ b/fastmcp_slim/fastmcp/skills/provider.py
@@ -2,20 +2,19 @@
from __future__ import annotations
-import hashlib
import json
import mimetypes
import os
import re
-from collections.abc import Iterable, Mapping, Sequence
+from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence
from contextlib import suppress
from pathlib import Path
-from typing import TYPE_CHECKING, Annotated, Any, cast
+from typing import TYPE_CHECKING, Any, TypeVar, cast
from urllib.parse import quote, unquote
import anyio
from mcp.server.context import ServerRequestContext
-from pydantic import AnyUrl, BeforeValidator, ConfigDict, ValidationError
+from pydantic import AnyUrl, ConfigDict, Field, ValidationError
from fastmcp.resources.base import Resource, ResourceContent, ResourceResult
from fastmcp.server.dependencies import get_context
@@ -24,8 +23,9 @@ from fastmcp.skills._routing import _may_read, _resolve_read
from fastmcp.skills.models import MCPSkill
from fastmcp.skills.skill import (
Skill,
+ SkillFile,
+ SkillManifest,
_is_authored_skill,
- _require_authored_skill,
_validate_relative_path,
)
from fastmcp.utilities.logging import get_logger
@@ -38,20 +38,159 @@ logger = get_logger(__name__)
mimetypes.add_type("text/markdown", ".md")
+_T = TypeVar("_T")
+
SkillCatalog = Mapping[str, Skill] | Iterable[Skill]
+class SkillManifestProvider(Provider):
+ """Serve skills from their manifests, and read each file only when a client reads it.
+
+ Discovery needs only each skill's frontmatter and the digest and size of its
+ files. A provider whose files live in object storage or a database can
+ advertise every skill without loading any file, and fetch one file when a
+ client reads it.
+
+ Subclass and override `load_manifests()` and `read_file()`.
+ `load_manifests()` is called once per MCP request.
+
+ Example:
+ ```python
+ from fastmcp import FastMCP, Skill
+ from fastmcp.skills import SkillManifest
+ from fastmcp.skills.provider import SkillFileResource, SkillManifestProvider
+
+ review = Skill(name="review", description="Review changes.", instructions="")
+ blobs = {review.manifest.files["SKILL.md"].digest: review.files["SKILL.md"]}
+
+
+ class StoredSkills(SkillManifestProvider):
+ async def load_manifests(self) -> dict[str, SkillManifest]:
+ return {"review": review.manifest}
+
+ async def read_file(self, resource: SkillFileResource) -> bytes:
+ return blobs[resource.file.digest]
+
+
+ mcp = FastMCP("Skills", providers=[StoredSkills()])
+ ```
+ """
+
+ def required_extensions(self) -> Sequence[ServerExtension]:
+ from fastmcp.skills.extension import SkillsExtension
+
+ return (SkillsExtension(),)
+
+ async def load_manifests(self) -> Mapping[str, SkillManifest]:
+ """Return the skills to serve, keyed by the path each is served under."""
+ raise NotImplementedError
+
+ async def read_file(self, resource: SkillFileResource) -> bytes:
+ """Return the content of the skill file that a client reads."""
+ raise NotImplementedError
+
+ async def _request_manifests(self) -> dict[str, SkillManifest]:
+ async def load() -> dict[str, SkillManifest]:
+ manifests = {
+ _validate_relative_path(path): manifest
+ for path, manifest in (await self.load_manifests()).items()
+ }
+ _validate_skill_paths(
+ {
+ path: manifest.frontmatter.name
+ for path, manifest in manifests.items()
+ }
+ )
+ return manifests
+
+ return await _once_per_request(self, "manifests", load)
+
+ # -------------------------------------------------------------------------
+ # Resources
+ # -------------------------------------------------------------------------
+
+ async def _list_resources(self) -> Sequence[Resource]:
+ resources: list[Resource] = []
+ for path, manifest in (await self._request_manifests()).items():
+ resources.extend(
+ _file_resource(self, path, manifest, file_path, file)
+ for file_path, file in manifest.files.items()
+ )
+ resources.append(_manifest_resource(path, manifest))
+ return resources
+
+ async def _get_resource(
+ self, uri: str, version: VersionSpec | None = None
+ ) -> Resource | None:
+ located = _locate(uri, await self._request_manifests())
+ if located is None:
+ return None
+ path, manifest, file_path = located
+ if file_path == "_manifest":
+ return _manifest_resource(path, manifest)
+ file = manifest.files.get(file_path)
+ if file is None:
+ return None
+ return _file_resource(self, path, manifest, file_path, file)
+
+ # -------------------------------------------------------------------------
+ # Skills extension source
+ # -------------------------------------------------------------------------
+
+ def _owns_skill_resource(self, uri: str) -> bool:
+ return uri.startswith("skill://")
+
+ async def _skill_uris(self, uri: str | None = None) -> Sequence[str]:
+ uris = [_skill_md_uri(path) for path in await self._request_manifests()]
+ 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 [
+ manifest.to_mcp_skill(path)
+ for path, manifest in (await self._request_manifests()).items()
+ if await self._is_served(path, manifest)
+ ]
+
+ async def _get_skill_entry(
+ self, uri: str, context: ServerRequestContext[Any, Any]
+ ) -> MCPSkill | None:
+ for path, manifest in (await self._request_manifests()).items():
+ if _skill_md_uri(path) == uri and await self._is_served(path, manifest):
+ return manifest.to_mcp_skill(path)
+ return None
+
+ async def _is_served(self, path: str, manifest: SkillManifest) -> bool:
+ """Advertise a skill only when this caller can read every file as listed."""
+ server = get_context().fastmcp
+ for file_path, file in manifest.files.items():
+ uri = _file_uri(path, file_path)
+ served = await _resolve_read(server, uri)
+ if not (
+ isinstance(served, SkillFileResource)
+ and served.file == file
+ and await _may_read(server, uri)
+ ):
+ return False
+ return True
+
+ def __repr__(self) -> str:
+ return f"{type(self).__name__}()"
+
+
class SkillFileResource(Resource):
- """One file of a `Skill`, served with its exact bytes."""
+ """One file of a skill, read from its provider when a client reads it."""
model_config = ConfigDict(arbitrary_types_allowed=True)
- skill: Annotated[Skill, BeforeValidator(_require_authored_skill)]
+ provider: SkillManifestProvider = Field(exclude=True, repr=False)
skill_path: str
file_path: str
+ file: SkillFile
async def read(self) -> ResourceResult:
- content = self.skill.files[self.file_path]
+ content = await self.provider.read_file(self)
value: str | bytes = content
if self.mime_type.startswith("text/"):
with suppress(UnicodeDecodeError):
@@ -62,23 +201,19 @@ class SkillFileResource(Resource):
class SkillManifestResource(Resource):
"""The `_manifest` file listing `Client.read_skill` uses without the Skills extension."""
- model_config = ConfigDict(arbitrary_types_allowed=True)
-
- skill: Annotated[Skill, BeforeValidator(_require_authored_skill)]
+ manifest: SkillManifest
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()
+ {"path": path, "size": file.size, "hash": file.digest}
+ for path, file in self.manifest.files.items()
]
- return json.dumps({"skill": self.skill.name, "files": files}, indent=2)
+ return json.dumps(
+ {"skill": self.manifest.frontmatter.name, "files": files}, indent=2
+ )
-class SkillCatalogProvider(Provider):
+class SkillCatalogProvider(SkillManifestProvider):
"""Serve `Skill` objects as MCP resources and Skills extension entries.
Each skill's files are served under `skill://{path}/`, where `path` defaults
@@ -112,57 +247,23 @@ class SkillCatalogProvider(Provider):
super().__init__()
self._static = _normalize(skills or ())
- def required_extensions(self) -> Sequence[ServerExtension]:
- from fastmcp.skills.extension import SkillsExtension
-
- return (SkillsExtension(),)
-
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]
+ async def load_manifests(self) -> Mapping[str, SkillManifest]:
+ return {
+ path: skill._manifest for path, skill in (await self._catalog()).items()
+ }
- # -------------------------------------------------------------------------
- # Resources
- # -------------------------------------------------------------------------
+ async def read_file(self, resource: SkillFileResource) -> bytes:
+ return (await self._catalog())[resource.skill_path].files[resource.file_path]
- 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 _catalog(self) -> dict[str, Skill]:
+ async def load() -> dict[str, Skill]:
+ return _normalize(await self.load_skills())
- 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
- # -------------------------------------------------------------------------
+ return await _once_per_request(self, "catalog", load)
def _owns_skill_resource(self, uri: str) -> bool:
# A static catalog knows its URIs; a loaded one may serve any skill:// URI.
@@ -170,44 +271,6 @@ class SkillCatalogProvider(Provider):
return _locate(uri, self._static) is not None
return uri.startswith("skill://")
- 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 _resolve_read(server, uri)
- if not (
- isinstance(served, SkillFileResource)
- and served.skill == skill
- and await _may_read(server, uri)
- ):
- return False
- return True
-
- def __repr__(self) -> str:
- return f"{type(self).__name__}()"
-
class SkillsDirectoryProvider(SkillCatalogProvider):
"""Serve every skill folder found below one or more root directories.
@@ -388,16 +451,40 @@ def _normalize(skills: SkillCatalog) -> dict[str, Skill]:
for path, skill in catalog.items():
if not _is_authored_skill(skill):
raise TypeError(f"Expected a Skill at {path!r}, got {type(skill).__name__}")
- if path.split("/")[-1] != skill.name:
+ _validate_skill_paths({path: skill.name for path, skill in catalog.items()})
+ return catalog
+
+
+def _validate_skill_paths(names: Mapping[str, str]) -> None:
+ """Check that each path ends with its skill's name and holds no other skill."""
+ for path, name in names.items():
+ if path.split("/")[-1] != name:
raise ValueError(
- f"Skill path {path!r} must end with the skill's name {skill.name!r}"
+ f"Skill path {path!r} must end with the skill's name {name!r}"
)
- for path in catalog:
+ for path in names:
parts = path.split("/")
for index in range(1, len(parts)):
- if "/".join(parts[:index]) in catalog:
+ if "/".join(parts[:index]) in names:
raise ValueError(f"Skill path {path!r} is nested inside another skill")
- return catalog
+
+
+async def _once_per_request(
+ provider: Provider, name: str, load: Callable[[], Awaitable[_T]]
+) -> _T:
+ context = None
+ with suppress(RuntimeError):
+ context = get_context()
+ if context is None:
+ return await load()
+ # Concurrent lookups in one request wait on the same lock, so `load` runs
+ # once and every caller sees the same result.
+ key = f"_fastmcp_skill_{name}:{id(provider)}"
+ lock = context._request_state.setdefault(f"{key}:lock", anyio.Lock())
+ async with lock:
+ if key not in context._request_state:
+ context._request_state[key] = await load()
+ return context._request_state[key]
def _file_uri(path: str, file: str) -> str:
@@ -408,7 +495,7 @@ 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:
+def _locate(uri: str, catalog: Mapping[str, _T]) -> tuple[str, _T, str] | None:
if not uri.startswith("skill://"):
return None
decoded = unquote(uri[len("skill://") :])
@@ -418,24 +505,33 @@ def _locate(uri: str, catalog: Mapping[str, Skill]) -> tuple[str, Skill, str] |
return None
-def _file_resource(path: str, skill: Skill, file: str) -> SkillFileResource:
- mime_type = mimetypes.guess_type(file)[0] or "application/octet-stream"
+def _file_resource(
+ provider: SkillManifestProvider,
+ path: str,
+ manifest: SkillManifest,
+ file_path: str,
+ file: SkillFile,
+) -> SkillFileResource:
+ mime_type = mimetypes.guess_type(file_path)[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,
+ uri=AnyUrl(_file_uri(path, file_path)),
+ name=f"{path}/{file_path}",
+ description=manifest.frontmatter.description
+ if file_path == "SKILL.md"
+ else None,
mime_type=mime_type,
- skill=skill,
+ provider=provider,
skill_path=path,
- file_path=file,
+ file_path=file_path,
+ file=file,
)
-def _manifest_resource(path: str, skill: Skill) -> SkillManifestResource:
+def _manifest_resource(path: str, manifest: SkillManifest) -> SkillManifestResource:
return SkillManifestResource(
uri=AnyUrl(_file_uri(path, "_manifest")),
name=f"{path}/_manifest",
- description=f"File listing for {skill.name}",
+ description=f"File listing for {manifest.frontmatter.name}",
mime_type="application/json",
- skill=skill,
+ manifest=manifest,
)
diff --git a/fastmcp_slim/fastmcp/skills/skill.py b/fastmcp_slim/fastmcp/skills/skill.py
index 9048453f2..f6500d9db 100644
--- a/fastmcp_slim/fastmcp/skills/skill.py
+++ b/fastmcp_slim/fastmcp/skills/skill.py
@@ -13,12 +13,24 @@ from types import MappingProxyType
from typing import Any, Self, TypeGuard, cast
from urllib.parse import quote
-from pydantic import GetCoreSchemaHandler, JsonValue
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ GetCoreSchemaHandler,
+ JsonValue,
+ model_validator,
+)
from pydantic_core import CoreSchema, core_schema
from fastmcp._warnings import FastMCPDeprecationWarning
from fastmcp.skills._constants import MAX_SKILL_BYTES, MAX_SKILL_FILES
-from fastmcp.skills.models import MCPSkill, SkillFrontmatter, SkillResource
+from fastmcp.skills.models import (
+ _SHA256_PATTERN,
+ MCPSkill,
+ SkillFrontmatter,
+ SkillResource,
+)
def _warn_wire_model(call: str) -> None:
@@ -55,6 +67,64 @@ def _validate_relative_path(path: str) -> str:
return path
+def _validate_files(sizes: Mapping[str, int]) -> None:
+ for path in sizes:
+ _validate_relative_path(path)
+ if "SKILL.md" not in sizes:
+ raise ValueError("A skill must contain SKILL.md")
+ _validate_limits(len(sizes), sum(sizes.values()))
+ for path in sizes:
+ parts = path.split("/")
+ for index in range(1, len(parts)):
+ if "/".join(parts[:index]) in sizes:
+ raise ValueError(f"Skill file is also used as a directory: {path!r}")
+
+
+class SkillFile(BaseModel):
+ """One file of a skill, described by its digest and size instead of its bytes."""
+
+ model_config = ConfigDict(extra="forbid", frozen=True)
+
+ digest: str = Field(pattern=_SHA256_PATTERN)
+ size: int = Field(ge=0)
+
+
+class SkillManifest(BaseModel):
+ """A skill's frontmatter and files, without the files' contents.
+
+ A provider can advertise a skill from its manifest and read a file only when
+ a client reads it. See `SkillManifestProvider`.
+ """
+
+ model_config = ConfigDict(extra="forbid", frozen=True)
+
+ frontmatter: SkillFrontmatter
+ files: dict[str, SkillFile]
+ """Every file in the skill, keyed by relative path, including `SKILL.md`."""
+
+ @model_validator(mode="after")
+ def validate_files(self) -> Self:
+ _validate_files({path: file.size for path, file in self.files.items()})
+ return self
+
+ 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.frontmatter.name, safe='/')}/"
+ resources = [
+ SkillResource(
+ uri=prefix + quote(file_path, safe="/"),
+ digest=file.digest,
+ size=file.size,
+ )
+ for file_path, file in self.files.items()
+ ]
+ return MCPSkill(
+ uri=f"{prefix}SKILL.md",
+ frontmatter=self.frontmatter.model_copy(deep=True),
+ resources=resources,
+ )
+
+
def _render_skill_md(frontmatter: Mapping[str, JsonValue], instructions: str) -> bytes:
import yaml
@@ -76,12 +146,6 @@ def _is_authored_skill(value: object) -> TypeGuard[Skill]:
return issubclass(type(value), Skill)
-def _require_authored_skill(value: object) -> Skill:
- if not _is_authored_skill(value):
- raise ValueError("Expected an authored Skill with file contents")
- return value
-
-
class Skill(metaclass=_SkillMeta):
"""An agent skill: a `SKILL.md` plus supporting files, independent of storage.
@@ -103,10 +167,10 @@ class Skill(metaclass=_SkillMeta):
```
"""
- __slots__ = ("_files", "_frontmatter")
+ __slots__ = ("_files", "_manifest")
_files: Mapping[str, bytes]
- _frontmatter: SkillFrontmatter
+ _manifest: SkillManifest
@classmethod
def __get_pydantic_core_schema__(
@@ -170,28 +234,27 @@ class Skill(metaclass=_SkillMeta):
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")
- _validate_limits(len(normalized), sum(map(len, normalized.values())))
- 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())))
+ normalized = {
+ path: content.encode("utf-8")
+ if isinstance(content, str)
+ else bytes(content)
+ for path, content in files.items()
+ }
+ _validate_files({path: len(content) for path, content in normalized.items()})
+ contents = dict(sorted(normalized.items()))
+ # Validated above, so the manifest skips validating the same files again.
+ manifest = SkillManifest.model_construct(
+ frontmatter=parse_frontmatter(contents["SKILL.md"]),
+ files={
+ path: SkillFile.model_construct(
+ digest=f"sha256:{hashlib.sha256(content).hexdigest()}",
+ size=len(content),
+ )
+ for path, content in contents.items()
+ },
)
+ object.__setattr__(self, "_files", MappingProxyType(contents))
+ object.__setattr__(self, "_manifest", manifest)
def __setattr__(self, name: str, value: object) -> None:
raise AttributeError("Skill is immutable")
@@ -311,16 +374,21 @@ class Skill(metaclass=_SkillMeta):
@property
def name(self) -> str:
- return self._frontmatter.name
+ return self._manifest.frontmatter.name
@property
def description(self) -> str:
- return self._frontmatter.description
+ return self._manifest.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)
+ return self._manifest.frontmatter.model_copy(deep=True)
+
+ @property
+ def manifest(self) -> SkillManifest:
+ """A copy of the skill's frontmatter and file digests; changing it does not change the skill."""
+ return self._manifest.model_copy(deep=True)
@property
def files(self) -> Mapping[str, bytes]:
@@ -329,18 +397,7 @@ class Skill(metaclass=_SkillMeta):
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
- )
+ return self._manifest.to_mcp_skill(path)
def __eq__(self, other: object) -> bool:
return _is_authored_skill(other) and self._files == other._files
diff --git a/tests/skills/test_deprecated_paths.py b/tests/skills/test_deprecated_paths.py
index d425350b9..720d44132 100644
--- a/tests/skills/test_deprecated_paths.py
+++ b/tests/skills/test_deprecated_paths.py
@@ -13,12 +13,7 @@ from fastmcp import Client, FastMCP
from fastmcp._warnings import FastMCPDeprecationWarning
from fastmcp.skills import MCPSkill, Skill, SkillsClientExtension
from fastmcp.skills.extension import SkillsExtension
-from fastmcp.skills.provider import (
- SkillCatalogProvider,
- SkillFileResource,
- SkillManifestResource,
- SkillsDirectoryProvider,
-)
+from fastmcp.skills.provider import SkillCatalogProvider, SkillsDirectoryProvider
from fastmcp.utilities.tests import temporary_settings
REVIEW = Skill(name="review", description="Review changes", instructions="# Review\n")
@@ -277,17 +272,6 @@ def test_wire_skill_is_not_an_authored_catalog_value():
SkillCatalogProvider([entry])
[email protected]("resource_cls", [SkillFileResource, SkillManifestResource])
-def test_skill_resources_require_authored_file_contents(resource_cls: type):
- with pytest.raises(ValidationError, match="Expected an authored Skill"):
- resource_cls(
- uri="skill://review/SKILL.md",
- skill=REVIEW.to_mcp_skill(),
- skill_path="review",
- file_path="SKILL.md",
- )
-
-
def test_wire_skill_does_not_satisfy_an_authoring_subclass():
class CustomSkill(Skill):
pass
diff --git a/tests/skills/test_manifest_provider.py b/tests/skills/test_manifest_provider.py
new file mode 100644
index 000000000..491768d56
--- /dev/null
+++ b/tests/skills/test_manifest_provider.py
@@ -0,0 +1,77 @@
+from __future__ import annotations
+
+import pytest
+from mcp_types import TextResourceContents
+
+from fastmcp import Client, FastMCP
+from fastmcp.skills import Skill, SkillManifest, SkillsClientExtension
+from fastmcp.skills.provider import SkillFileResource, SkillManifestProvider
+
+REVIEW = Skill(
+ name="review",
+ description="Review changes",
+ instructions="# Review\n\nRead notes.md first.\n",
+ files={"notes.md": "line one\n"},
+)
+
+
+class StoredSkills(SkillManifestProvider):
+ def __init__(self, *skills: Skill) -> None:
+ super().__init__()
+ self.manifests = {skill.name: skill.manifest for skill in skills}
+ self.blobs = {
+ file.digest: skill.files[file_path]
+ for skill in skills
+ for file_path, file in skill.manifest.files.items()
+ }
+ self.reads: list[str] = []
+
+ async def load_manifests(self) -> dict[str, SkillManifest]:
+ return self.manifests
+
+ async def read_file(self, resource: SkillFileResource) -> bytes:
+ self.reads.append(f"{resource.skill_path}/{resource.file_path}")
+ return self.blobs[resource.file.digest]
+
+
+def skills_client(provider: SkillManifestProvider) -> Client:
+ server = FastMCP("Skills", providers=[provider])
+ return Client(server, extensions=[SkillsClientExtension()])
+
+
+async def test_lists_skills_without_reading_their_files():
+ store = StoredSkills(REVIEW)
+
+ async with skills_client(store) as client:
+ entries = await client.list_skills()
+ await client.list_resources()
+
+ assert entries == [REVIEW.to_mcp_skill()]
+ assert store.reads == []
+
+
+async def test_reads_only_the_file_a_client_reads():
+ store = StoredSkills(REVIEW)
+
+ async with skills_client(store) as client:
+ (content,) = await client.read_resource("skill://review/notes.md")
+
+ assert isinstance(content, TextResourceContents)
+ assert content.text == "line one\n"
+ assert store.reads == ["review/notes.md"]
+
+
+async def test_read_skill_returns_the_stored_skill():
+ async with skills_client(StoredSkills(REVIEW)) as client:
+ skill = await client.read_skill("skill://review/SKILL.md")
+
+ assert skill == REVIEW
+
+
+def test_manifest_requires_skill_md():
+ files = {
+ path: file for path, file in REVIEW.manifest.files.items() if path != "SKILL.md"
+ }
+
+ with pytest.raises(ValueError, match="must contain SKILL.md"):
+ SkillManifest(frontmatter=REVIEW.manifest.frontmatter, files=files)
diff --git a/tests/skills/test_skill.py b/tests/skills/test_skill.py
index 3da916177..ee73c3f39 100644
--- a/tests/skills/test_skill.py
+++ b/tests/skills/test_skill.py
@@ -179,8 +179,11 @@ 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"
+ skill.manifest.frontmatter.root["description"] = "changed"
+ skill.manifest.files.clear()
assert skill.description == "Review"
assert skill.to_mcp_skill().frontmatter.description == "Review"
+ assert skill.manifest.files.keys() == {"SKILL.md"}
def test_to_mcp_skill_describes_every_file(tmp_path: Path):