Skip to content

🚀 The fast, Pythonic way to build MCP servers and clients.

Verify and export skills with resource-manifest fallback (#6086)

nate nowack4eea503d8220
diff --git a/docs/servers/skills.mdx b/docs/servers/skills.mdx
index c30509b33..4c6bd2342 100644
--- a/docs/servers/skills.mdx
+++ b/docs/servers/skills.mdx
@@ -30,43 +30,70 @@ That's a skills server. Every client can read `skill://release-notes/SKILL.md` a
## Where skills come from
-A `Skill` is a value: a name, a description, instructions, and any supporting files. Build one in Python as above, or load one from a folder, a package, or a mapping of files:
+A `Skill` is a value: a name, a description, instructions, and the files they refer to. It doesn't know where it came from or which URI it is served under. Build one in Python as above, or load what you already have on disk or in a package:
```python
from fastmcp import Skill
deploy = Skill.from_directory("skills/deploy")
review = Skill.from_package("my_package", "skills/review")
-triage = Skill.from_files({"SKILL.md": "---\nname: triage\ndescription: Triage issues.\n---\n"})
```
-Skills are validated when you build them and never change afterward. The `description` is what an agent reads to decide whether to use the skill, so make it say when.
+`Skill.from_files()` takes a mapping of relative paths to contents when the files are already in memory.
-If your skills change while the server runs, override `load_skills()`. FastMCP calls it once per request, so a database row or a folder you're still editing shows up on the next request:
+Skills are validated when you build them and never change afterward; editing the folder later doesn't touch the loaded skill. The `description` is what an agent reads to decide whether to use the skill, so make it say when.
-```python
-from pathlib import Path
+`SkillCatalogProvider` serves the skills you hand it. When the set of skills changes at runtime, override `load_skills()` instead and build the skills from wherever they live. FastMCP calls it once per request. Rows in a database are a fine source: the columns become the skill's fields, and no file is involved.
+```python
from fastmcp import Skill
from fastmcp.skills.provider import SkillCatalogProvider
-ROWS = [{"name": "triage", "description": "Triage issues.", "body": "# Triage\n"}]
+rows = [
+ {
+ "name": "triage",
+ "description": "Triage new issues.",
+ "body": "# Triage\n\nLabel the issue, then assign it.\n",
+ }
+]
class StoredSkills(SkillCatalogProvider):
async def load_skills(self) -> list[Skill]:
return [
- Skill(name=row["name"], description=row["description"], instructions=row["body"])
- for row in ROWS
+ Skill(
+ name=row["name"],
+ description=row["description"],
+ instructions=row["body"],
+ )
+ for row in rows
]
+```
+
+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
-class LiveFolder(SkillCatalogProvider):
async def load_skills(self) -> list[Skill]:
- return [Skill.from_directory(p) for p in Path("skills").iterdir() if p.is_dir()]
+ folders = sorted(self.root.iterdir())
+ return [
+ Skill.from_directory(folder)
+ for folder in folders
+ if (folder / "SKILL.md").is_file()
+ ]
```
-`SkillsDirectoryProvider` and presets like `ClaudeSkillsProvider` also serve folders straight from disk; pass `experimental_skills=True` to make them discoverable.
+For recursive folder discovery that skips invalid skills, use `SkillsDirectoryProvider(path, experimental_skills=True)`. Presets like `ClaudeSkillsProvider` point it at a coding agent's own skills folder.
## Access control
@@ -78,9 +105,9 @@ Skills come along when you [mount](/servers/composition) a server, at the URIs t
## Read skills from a client
-### Discover and read skills
+### Discover skills with the Skills extension
-Opt the client into the extension, list what the server offers, and read a whole skill with `read_skill()`:
+Opt the client into the extension and ask:
```python
from fastmcp import Client
@@ -88,16 +115,29 @@ from fastmcp.skills import SkillsClientExtension
client = Client("http://localhost:8000/mcp", extensions=[SkillsClientExtension()])
async with client:
- for entry in await client.list_skills():
- print(entry.uri, entry.frontmatter.description)
+ for skill in await client.list_skills():
+ print(skill.uri, skill.frontmatter.description)
+```
+
+You get metadata, not content. [`ClientGroup.list_skills()`](/clients/client-groups) does the same across several servers.
+
+### Read a whole skill
+
+`read_skill()` fetches every file in the skill's manifest, checks each one's size and SHA-256 digest, and returns a `Skill`. It uses `skills/get` when the extension was negotiated, falling back to FastMCP's `_manifest` resource when the extension is unavailable or doesn't know the skill:
+
+```python
+from fastmcp import Client
+
+async with Client("http://localhost:8000/mcp") as client:
skill = await client.read_skill("skill://release-notes/SKILL.md")
+ print(skill.description, sorted(skill.files))
```
-`list_skills()` returns metadata only. `read_skill()` reads every file in the skill's manifest, checks each against its digest, and returns a `Skill`, so you can inspect it or serve it again with `SkillCatalogProvider([skill])`. [`ClientGroup.list_skills()`](/clients/client-groups) lists skills across several servers.
+A skill you read is the same value as one you build, so you can hand it to a `SkillCatalogProvider` on another server or write it to disk with `skill.to_directory(path)`.
### Install skills into a local agent
-Most agents still only read skills from disk. `sync_skills()` copies a server's skills into a local folder, and works with any server that serves skills as resources, with or without the extension:
+Most agents still only read skills from disk. `sync_skills()` reads every skill a server lists and writes each one into a local folder, verified the same way:
```python
from pathlib import Path
@@ -109,6 +149,8 @@ async with Client("http://localhost:8000/mcp") as client:
await sync_skills(client, Path.home() / ".claude" / "skills", overwrite=True)
```
+Downloads now require valid `SKILL.md` frontmatter with a `name` matching the skill's URI and a `description`; add these fields to older resource-only skills before downloading them. Digest or size mismatches raise an error before writing. `overwrite=True` replaces the existing skill folder, including removing locally added files.
+
## Current limits
- Skills behind a proxy are readable as resources but don't show up in `skills/list`.
diff --git a/fastmcp_slim/fastmcp/client/group.py b/fastmcp_slim/fastmcp/client/group.py
index bebc4f5aa..9187e45aa 100644
--- a/fastmcp_slim/fastmcp/client/group.py
+++ b/fastmcp_slim/fastmcp/client/group.py
@@ -18,6 +18,7 @@ from fastmcp.client.client import CallToolResult, Client, ConnectMode
from fastmcp.client.progress import ProgressHandler
from fastmcp.mcp_config import MCPConfig
from fastmcp.skills.models import MCPSkill
+from fastmcp.skills.skill import Skill
from fastmcp.utilities.async_utils import gather
@@ -298,6 +299,20 @@ class ClientGroup:
)
return await client.get_skill(uri, cache_mode=cache_mode)
+ async def read_skill(
+ self, server_name: str, uri: str, *, cache_mode: CacheMode = "use"
+ ) -> Skill:
+ """Read one whole skill from the named server; see `Client.read_skill`."""
+ try:
+ client = self._clients[server_name]
+ except KeyError as exc:
+ raise KeyError(f"Unknown ClientGroup server: {server_name!r}") from exc
+ if not client.is_connected():
+ raise RuntimeError(
+ f"ClientGroup client for server {server_name!r} is not connected"
+ )
+ return await client.read_skill(uri, cache_mode=cache_mode)
+
async def resolve_tool(self, name: str) -> ToolRoute:
"""Resolve a public tool name to its client and upstream identity.
diff --git a/fastmcp_slim/fastmcp/client/mixins/skills.py b/fastmcp_slim/fastmcp/client/mixins/skills.py
index 9a320194d..847117dc6 100644
--- a/fastmcp_slim/fastmcp/client/mixins/skills.py
+++ b/fastmcp_slim/fastmcp/client/mixins/skills.py
@@ -4,10 +4,14 @@ from __future__ import annotations
import base64
import hashlib
+import json
from typing import TYPE_CHECKING, cast
+from urllib.parse import quote, unquote, urlsplit, urlunsplit
import mcp_types
from mcp.client.caching import CacheMode
+from mcp.shared.exceptions import MCPError
+from mcp_types import INVALID_PARAMS, METHOD_NOT_FOUND
from mcp_types.version import MODERN_PROTOCOL_VERSIONS
from fastmcp.client.telemetry import client_span
@@ -20,14 +24,15 @@ from fastmcp.skills.models import (
ListSkillsRequest,
ListSkillsResult,
MCPSkill,
+ SkillResource,
_parse_resource_uri,
)
+from fastmcp.skills.skill import Skill, _validate_relative_path
from fastmcp.telemetry import inject_trace_context
from fastmcp.utilities.logging import get_logger
if TYPE_CHECKING:
from fastmcp.client.client import Client
- from fastmcp.skills.skill import Skill
logger = get_logger(__name__)
@@ -224,48 +229,120 @@ class ClientSkillsMixin:
result = await self.get_skill_mcp(uri, cache_mode=cache_mode)
return result.skill
- async def read_skill(self: Client, uri: str) -> Skill:
- """Fetch a whole skill and return it as a `Skill`.
+ async def read_skill(
+ self: Client,
+ uri: str,
+ *,
+ cache_mode: CacheMode = "use",
+ ) -> Skill:
+ """Fetch every file of a skill, verify each one, and return a `Skill`.
- Gets the skill's entry, reads every file in its manifest, and checks
- each file's size and digest before building the `Skill`. The result
- can be saved, inspected, or served again from another server with
- `SkillCatalogProvider`.
+ The manifest comes from `skills/get` when the Skills extension was
+ negotiated, and otherwise from the `_manifest` resource that FastMCP
+ skill providers serve next to the files. Every file must match the
+ size and SHA-256 digest the manifest promised.
Args:
uri: URI of the skill's `SKILL.md` resource.
+ cache_mode: Response-cache behavior for the `skills/get` request.
Returns:
- The skill, with every file's exact bytes.
+ The skill, with the exact bytes of every file.
Raises:
- RuntimeError: If the client is disconnected or Skills was not negotiated.
- ValueError: If the skill has no static manifest, or a file's bytes
- don't match the manifest.
+ RuntimeError: If the client is disconnected.
+ ValueError: If the manifest is unusable, a file does not match it,
+ or the files do not form a valid skill.
MCPError: If the server rejects a request.
"""
- from fastmcp.skills.skill import Skill
-
- entry = await self.get_skill(uri)
- if entry.resources == "dynamic":
- raise ValueError(f"Skill {uri!r} has no static manifest to read")
-
- root_depth = len(_parse_resource_uri(entry.uri)[2]) - 1
+ _, authority, segments = _parse_resource_uri(uri)
+ if not segments or segments[-1] != "SKILL.md":
+ raise ValueError(f"read_skill takes a skill's SKILL.md URI, got {uri!r}")
+ manifest = await self._skill_manifest(uri, cache_mode)
+ for path in manifest:
+ _validate_relative_path(path)
files: dict[str, bytes] = {}
- for record in entry.resources:
- contents = await self.read_resource(record.uri)
- if len(contents) != 1:
- raise ValueError(f"Skill file {record.uri!r} did not return one file")
- content = contents[0]
- if isinstance(content, mcp_types.TextResourceContents):
- data = content.text.encode()
- else:
- data = base64.b64decode(content.blob)
- digest = f"sha256:{hashlib.sha256(data).hexdigest()}"
- if len(data) != record.size or digest != record.digest:
+ for path, record in manifest.items():
+ content = await self._read_skill_file(record.uri)
+ if len(content) != record.size:
raise ValueError(
- f"Skill file {record.uri!r} does not match its manifest digest"
+ f"Skill file {path!r} is {len(content)} bytes; "
+ f"the manifest promised {record.size}"
)
- relative = "/".join(_parse_resource_uri(record.uri)[2][root_depth:])
- files[relative] = data
- return Skill.from_files(files)
+ actual = f"sha256:{hashlib.sha256(content).hexdigest()}"
+ if actual != record.digest:
+ raise ValueError(
+ f"Skill file {path!r} does not match its manifest digest"
+ )
+ files[path] = content
+ skill = Skill.from_files(files)
+ expected = segments[-2] if len(segments) > 1 else unquote(authority)
+ if skill.name != expected:
+ raise ValueError(
+ f"Skill at {uri!r} is named {skill.name!r} in its SKILL.md"
+ )
+ return skill
+
+ async def _skill_manifest(
+ self: Client, uri: str, cache_mode: CacheMode
+ ) -> dict[str, SkillResource]:
+ """Relative path -> manifest record for every file in the skill.
+
+ A skill the server serves as resources but does not advertise through
+ the extension, such as one behind a proxy, still has a `_manifest`.
+ """
+ if self._skills_unavailable_reason() is None:
+ try:
+ entry = await self.get_skill(uri, cache_mode=cache_mode)
+ except MCPError as exc:
+ if exc.error.code not in (INVALID_PARAMS, METHOD_NOT_FOUND):
+ raise
+ entry = None
+ if entry is not None and entry.resources == "dynamic":
+ raise ValueError(f"Skill {uri!r} has no static manifest to read")
+ if entry is not None and isinstance(entry.resources, list):
+ root_depth = len(_parse_resource_uri(entry.uri)[2]) - 1
+ manifest: dict[str, SkillResource] = {}
+ for resource in entry.resources:
+ path = "/".join(_parse_resource_uri(resource.uri)[2][root_depth:])
+ if path in manifest:
+ raise ValueError(f"Duplicate skill file path: {path!r}")
+ manifest[path] = resource
+ return manifest
+ return await self._resource_mode_manifest(uri)
+
+ async def _resource_mode_manifest(
+ self: Client, uri: str
+ ) -> dict[str, SkillResource]:
+ parsed = urlsplit(uri)
+ prefix = parsed.path[: -len("SKILL.md")]
+ manifest_uri = urlunsplit(parsed._replace(path=f"{prefix}_manifest"))
+ try:
+ text = (await self._read_skill_file(manifest_uri)).decode("utf-8")
+ data = json.loads(text)
+ files = {
+ entry["path"]: SkillResource(
+ uri=urlunsplit(
+ parsed._replace(path=prefix + quote(entry["path"], safe="/"))
+ ),
+ digest=entry["hash"],
+ size=entry["size"],
+ )
+ for entry in data["files"]
+ }
+ except (ValueError, KeyError, TypeError) as exc:
+ raise ValueError(f"Invalid skill manifest at {manifest_uri}") from exc
+ if not files:
+ raise ValueError(f"Skill manifest at {manifest_uri} lists no files")
+ return files
+
+ async def _read_skill_file(self: Client, uri: str) -> bytes:
+ contents = await self.read_resource(uri)
+ if len(contents) != 1:
+ raise ValueError(
+ f"Expected one content block for {uri}, got {len(contents)}"
+ )
+ (content,) = contents
+ if isinstance(content, mcp_types.TextResourceContents):
+ return content.text.encode("utf-8")
+ return base64.b64decode(content.blob)
diff --git a/fastmcp_slim/fastmcp/server/providers/skills/skill_provider.py b/fastmcp_slim/fastmcp/server/providers/skills/skill_provider.py
index 688ac8387..45e94756e 100644
--- a/fastmcp_slim/fastmcp/server/providers/skills/skill_provider.py
+++ b/fastmcp_slim/fastmcp/server/providers/skills/skill_provider.py
@@ -64,7 +64,7 @@ class SkillResource(Resource):
main_file_path = resolve_within(
self.skill_info.path, self.skill_info.main_file
)
- return main_file_path.read_text(encoding="utf-8")
+ return main_file_path.read_bytes().decode("utf-8")
def _generate_manifest(self) -> str:
"""Generate JSON manifest for the skill."""
@@ -105,7 +105,7 @@ class SkillFileTemplate(ResourceTemplate):
# Determine if binary or text based on mime type
mime_type, _ = mimetypes.guess_type(str(full_path))
if mime_type and mime_type.startswith("text/"):
- return full_path.read_text(encoding="utf-8")
+ return full_path.read_bytes().decode("utf-8")
else:
return full_path.read_bytes()
@@ -177,7 +177,7 @@ class SkillFileResource(Resource):
mime_type, _ = mimetypes.guess_type(str(full_path))
if mime_type and mime_type.startswith("text/"):
- return full_path.read_text(encoding="utf-8")
+ return full_path.read_bytes().decode("utf-8")
else:
return full_path.read_bytes()
diff --git a/fastmcp_slim/fastmcp/skills/skill.py b/fastmcp_slim/fastmcp/skills/skill.py
index ecbf7f5d7..2694e97a9 100644
--- a/fastmcp_slim/fastmcp/skills/skill.py
+++ b/fastmcp_slim/fastmcp/skills/skill.py
@@ -4,8 +4,9 @@ from __future__ import annotations
import hashlib
import os
+import shutil
from collections.abc import Mapping
-from pathlib import Path
+from pathlib import Path, PureWindowsPath
from types import MappingProxyType
from typing import Any
from urllib.parse import quote
@@ -22,7 +23,12 @@ 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:
+ if (
+ path.startswith("/")
+ or PureWindowsPath(path).drive
+ 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):
@@ -178,6 +184,38 @@ class Skill:
)
return skill
+ def to_directory(
+ self, path: str | os.PathLike[str], *, overwrite: bool = False
+ ) -> Path:
+ """Write the skill's files into `path`, a folder named after the skill.
+
+ The folder name must match the skill's `name`, so `from_directory` can
+ read it back. An existing folder raises `FileExistsError` unless
+ `overwrite` is set, in which case it is replaced: files that aren't
+ part of the skill are removed.
+ """
+ root = Path(path)
+ if root.name != self.name:
+ raise ValueError(
+ f"Skill folder {root.name!r} must match the skill's name {self.name!r}"
+ )
+ if root.is_symlink():
+ raise ValueError(f"Skill folder is a symlink: {root}")
+ if root.exists():
+ if not overwrite:
+ raise FileExistsError(
+ f"Skill directory already exists: {root}. "
+ "Use overwrite=True to replace."
+ )
+ if not root.is_dir():
+ raise ValueError(f"Skill folder is not a directory: {root}")
+ shutil.rmtree(root)
+ for relative, content in self._files.items():
+ target = root / relative
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(content)
+ return root
+
@property
def name(self) -> str:
return self._frontmatter.name
diff --git a/fastmcp_slim/fastmcp/utilities/skills.py b/fastmcp_slim/fastmcp/utilities/skills.py
index 1ff807ef6..e91d36232 100644
--- a/fastmcp_slim/fastmcp/utilities/skills.py
+++ b/fastmcp_slim/fastmcp/utilities/skills.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import base64
import json
import warnings
from dataclasses import dataclass
@@ -155,25 +154,27 @@ async def download_skill(
*,
overwrite: bool = False,
) -> Path:
- """Download a skill and all its files to a local directory.
+ """Read a skill from the server and write it to a local directory.
Creates a subdirectory named after the skill containing all files. A
skill served at a nested path, such as a mounted server's `ops/deploy`,
is installed as `deploy`, since agents look for skill folders one level
- deep.
+ deep. Every file is checked against the server's manifest before it is
+ written; see `Client.read_skill`.
Args:
client: Connected FastMCP client
skill_name: Name or path of the skill to download
target_dir: Directory where skill folder will be created
- overwrite: If True, overwrite existing skill directory. If False
+ overwrite: If True, replace an existing skill directory. If False
(default), raise FileExistsError if directory exists.
Returns:
Path to the downloaded skill directory
Raises:
- ValueError: If skill cannot be found or downloaded
+ ValueError: If the skill cannot be found, fails verification, or is
+ not a valid skill
FileExistsError: If skill directory exists and overwrite=False
Example:
@@ -200,49 +201,14 @@ async def download_skill(
):
raise ValueError(f"Skill name {skill_name!r} would escape the target directory")
- # Check if directory exists
if skill_dir.exists() and not overwrite:
raise FileExistsError(
f"Skill directory already exists: {skill_dir}. "
"Use overwrite=True to replace."
)
- # Get manifest to know what files to download
- manifest = await get_skill_manifest(client, skill_name)
-
- # Create skill directory
- skill_dir.mkdir(parents=True, exist_ok=True)
-
- # Download each file
- for file_info in manifest.files:
- # Security: reject absolute paths and paths that escape skill_dir
- if Path(file_info.path).is_absolute():
- continue
- file_path = (skill_dir / file_info.path).resolve()
- if not file_path.is_relative_to(skill_dir):
- continue
-
- file_uri = f"skill://{skill_name}/{file_info.path}"
- result = await client.read_resource(file_uri)
-
- if not result:
- continue
-
- content = result[0]
-
- # Create parent directories if needed
- file_path.parent.mkdir(parents=True, exist_ok=True)
-
- # Write content
- if isinstance(content, mcp_types.TextResourceContents):
- file_path.write_text(content.text, encoding="utf-8")
- elif isinstance(content, mcp_types.BlobResourceContents):
- file_path.write_bytes(base64.b64decode(content.blob))
- else:
- # Skip unknown content types
- continue
-
- return skill_dir
+ skill = await client.read_skill(f"skill://{skill_name}/SKILL.md")
+ return skill.to_directory(skill_dir, overwrite=overwrite)
async def sync_skills(
diff --git a/tests/experimental/skills/test_opt_in.py b/tests/experimental/skills/test_opt_in.py
index 82ed19967..bbdc896ac 100644
--- a/tests/experimental/skills/test_opt_in.py
+++ b/tests/experimental/skills/test_opt_in.py
@@ -26,7 +26,7 @@ async def test_default_provider_keeps_legacy_publication(
"skill://review/_manifest",
}
contents = await client.read_resource("skill://review/SKILL.md")
- assert contents[0].text == "# No frontmatter\nLoose instructions\n"
+ assert contents[0].text == "# No frontmatter\r\nLoose instructions\r\n"
assert client.server_capabilities is not None
assert "io.modelcontextprotocol/skills" not in (
client.server_capabilities.extensions or {}
diff --git a/tests/server/providers/test_skill_main_files.py b/tests/server/providers/test_skill_main_files.py
index 7edad5c5d..ac449b78a 100644
--- a/tests/server/providers/test_skill_main_files.py
+++ b/tests/server/providers/test_skill_main_files.py
@@ -69,7 +69,7 @@ async def test_main_file_links_within_skill_directory_remain_readable(
skill.mkdir()
content = "# Instructions\n\nRésumé"
target = skill / "instructions.md"
- target.write_text(content, encoding="utf-8")
+ target.write_bytes(content.encode("utf-8"))
main_file = skill / main_file_name
main_file.parent.mkdir(exist_ok=True)
main_file.symlink_to(target)
diff --git a/tests/skills/test_provider.py b/tests/skills/test_provider.py
index c5a48e7f9..a54f3523c 100644
--- a/tests/skills/test_provider.py
+++ b/tests/skills/test_provider.py
@@ -5,9 +5,11 @@ import hashlib
import json
from collections.abc import Iterable
from pathlib import Path
+from typing import Any
import anyio
import pytest
+from mcp.server.context import ServerRequestContext
from mcp.shared.exceptions import MCPError
from mcp_types import BlobResourceContents, TextResourceContents
@@ -16,6 +18,7 @@ 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.models import MCPSkill
from fastmcp.skills.provider import SkillCatalogProvider
from fastmcp.utilities.skills import list_skill_summaries, sync_skills
@@ -214,22 +217,19 @@ async def test_read_skill_can_be_served_again():
async def test_read_skill_rejects_bytes_that_miss_the_manifest():
- provider = SkillCatalogProvider([REVIEW])
+ class PublishedManifest(SkillCatalogProvider):
+ async def _get_skill_entry(
+ self, uri: str, context: ServerRequestContext[Any, Any]
+ ) -> MCPSkill | None:
+ return REVIEW.to_mcp_skill()
+
+ provider = PublishedManifest([REVIEW])
server = serve(provider)
@server.resource("skill://review/notes.md")
def tampered() -> str:
- return "tampered\n"
+ return "tampered!\n"
async with skills_client(server) as client:
- entry = REVIEW.to_mcp_skill()
- client.get_skill = _returning(entry) # type: ignore[method-assign]
with pytest.raises(ValueError, match="does not match its manifest"):
- await client.read_skill(entry.uri)
-
-
-def _returning(entry: object):
- async def get_skill(uri: str, **kwargs: object) -> object:
- return entry
-
- return get_skill
+ await client.read_skill("skill://review/SKILL.md")
diff --git a/tests/skills/test_read_skill.py b/tests/skills/test_read_skill.py
new file mode 100644
index 000000000..b82eece7b
--- /dev/null
+++ b/tests/skills/test_read_skill.py
@@ -0,0 +1,337 @@
+"""Tests for `Client.read_skill`, which fetches and verifies a whole skill."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from collections.abc import Callable
+from pathlib import Path
+from typing import Any
+
+import pytest
+from mcp.server.context import ServerRequestContext
+from mcp.shared.exceptions import MCPError
+from mcp_types import INTERNAL_ERROR
+
+from fastmcp import Client, ClientGroup, FastMCP
+from fastmcp.server.providers.skills import SkillProvider, SkillsDirectoryProvider
+from fastmcp.skills import Skill, SkillsClientExtension
+from fastmcp.skills.extension import SkillsExtension
+from fastmcp.skills.models import MCPSkill
+from fastmcp.skills.provider import SkillCatalogProvider
+
+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"},
+)
+
+
+def skills_client(server: FastMCP) -> Client:
+ return Client(server, extensions=[SkillsClientExtension()])
+
+
+async def test_read_skill_returns_an_equal_skill_through_the_extension():
+ server = FastMCP("Skills", providers=[SkillCatalogProvider([REVIEW])])
+ async with skills_client(server) as client:
+ skill = await client.read_skill("skill://review/SKILL.md")
+ assert skill == REVIEW
+ assert skill.files["refs/logo.bin"] == b"\x00\xff\r\n"
+
+
+async def test_read_skill_falls_back_to_the_manifest_resource():
+ server = FastMCP("Skills", providers=[SkillCatalogProvider([REVIEW])])
+ async with Client(server) as client:
+ assert client._skills_unavailable_reason() is not None
+ skill = await client.read_skill("skill://review/SKILL.md")
+ assert skill == REVIEW
+
+
+async def test_read_skill_handles_nested_paths_and_encoded_names():
+ quoted = Skill(
+ name="deploy",
+ description="Deploy",
+ instructions="# Deploy\n",
+ files={"notes/read me.md": "spaces\n"},
+ )
+ provider = SkillCatalogProvider({"team/deploy": quoted})
+ server = FastMCP("Skills", providers=[provider])
+ for client in (skills_client(server), Client(server)):
+ async with client:
+ skill = await client.read_skill("skill://team/deploy/SKILL.md")
+ assert skill == quoted
+
+
+async def test_read_skill_reads_from_a_legacy_folder_provider(tmp_path: Path):
+ folder = tmp_path / "review"
+ folder.mkdir()
+ (folder / "SKILL.md").write_bytes(REVIEW.files["SKILL.md"])
+ (folder / "notes.md").write_bytes(b"line one\r\n")
+ (folder / "refs").mkdir()
+ (folder / "refs" / "logo.bin").write_bytes(b"\x00\xff\r\n")
+
+ for provider in (
+ SkillProvider(folder),
+ SkillProvider(folder, supporting_files="resources"),
+ SkillsDirectoryProvider(tmp_path),
+ SkillsDirectoryProvider(tmp_path, experimental_skills=True),
+ ):
+ server = FastMCP("Skills", providers=[provider])
+ async with Client(server) as client:
+ skill = await client.read_skill("skill://review/SKILL.md")
+ assert skill == REVIEW, provider
+
+
+async def test_read_skill_rejects_a_file_that_does_not_match_its_digest():
+ class Tampered(SkillCatalogProvider):
+ async def _get_skill_entry(
+ self, uri: str, context: ServerRequestContext[Any, Any]
+ ) -> MCPSkill | None:
+ entry = await super()._get_skill_entry(uri, context)
+ assert entry is not None and isinstance(entry.resources, list)
+ resources = [
+ record.model_copy(update={"digest": f"sha256:{'0' * 64}"})
+ if record.uri.endswith("/notes.md")
+ else record
+ for record in entry.resources
+ ]
+ return entry.model_copy(update={"resources": resources})
+
+ server = FastMCP("Skills", providers=[Tampered([REVIEW])])
+ async with skills_client(server) as client:
+ with pytest.raises(ValueError, match="'notes.md' does not match"):
+ await client.read_skill("skill://review/SKILL.md")
+
+
+async def test_read_skill_rejects_a_file_whose_size_changed():
+ class Tampered(SkillCatalogProvider):
+ async def _get_skill_entry(
+ self, uri: str, context: ServerRequestContext[Any, Any]
+ ) -> MCPSkill | None:
+ entry = await super()._get_skill_entry(uri, context)
+ assert entry is not None and isinstance(entry.resources, list)
+ resources = [
+ record.model_copy(update={"size": record.size + 1})
+ for record in entry.resources
+ ]
+ return entry.model_copy(update={"resources": resources})
+
+ server = FastMCP("Skills", providers=[Tampered([REVIEW])])
+ async with skills_client(server) as client:
+ with pytest.raises(ValueError, match="the manifest promised"):
+ await client.read_skill("skill://review/SKILL.md")
+
+
+def manifest_server(files: dict[str, bytes], manifest: dict[str, Any]) -> FastMCP:
+ server = FastMCP("Manual")
+
+ @server.resource("skill://manual/_manifest", mime_type="application/json")
+ def _manifest() -> str:
+ return json.dumps(manifest)
+
+ for path, content in files.items():
+ server.resource(f"skill://manual/{path}")(_constant(content))
+ return server
+
+
+def _constant(content: bytes) -> Callable[[], bytes]:
+ def _file() -> bytes:
+ return content
+
+ return _file
+
+
+def manifest_for(files: dict[str, bytes]) -> dict[str, Any]:
+ return {
+ "skill": "manual",
+ "files": [
+ {
+ "path": path,
+ "size": len(content),
+ "hash": f"sha256:{hashlib.sha256(content).hexdigest()}",
+ }
+ for path, content in files.items()
+ ],
+ }
+
+
+MANUAL_SKILL_MD = b"---\nname: manual\ndescription: Hand-rolled.\n---\n# Manual\n"
+
+
+async def test_read_skill_verifies_resource_mode_manifests():
+ files = {"SKILL.md": MANUAL_SKILL_MD, "data.bin": b"\x00\x01binary"}
+ async with Client(manifest_server(files, manifest_for(files))) as client:
+ skill = await client.read_skill("skill://manual/SKILL.md")
+ assert dict(skill.files) == files
+
+ tampered = manifest_for(files)
+ tampered["files"][1]["hash"] = f"sha256:{'0' * 64}"
+ async with Client(manifest_server(files, tampered)) as client:
+ with pytest.raises(ValueError, match="'data.bin' does not match"):
+ await client.read_skill("skill://manual/SKILL.md")
+
+
+async def test_read_skill_falls_back_when_the_extension_does_not_know_the_skill():
+ files = {"SKILL.md": MANUAL_SKILL_MD}
+ server = manifest_server(files, manifest_for(files))
+ server.add_provider(SkillCatalogProvider([REVIEW]))
+ async with skills_client(server) as client:
+ assert [entry.uri for entry in await client.list_skills()] == [
+ "skill://review/SKILL.md"
+ ]
+ skill = await client.read_skill("skill://manual/SKILL.md")
+ assert dict(skill.files) == files
+
+
+ ("manifest", "match"),
+ [
+ ({"skill": "manual"}, "Invalid skill manifest"),
+ ({"skill": "manual", "files": []}, "lists no files"),
+ (
+ {"skill": "manual", "files": [{"path": "SKILL.md", "size": "x"}]},
+ "Invalid skill manifest",
+ ),
+ ],
+)
+async def test_read_skill_rejects_unusable_manifests(
+ manifest: dict[str, Any], match: str
+):
+ files = {"SKILL.md": MANUAL_SKILL_MD}
+ async with Client(manifest_server(files, manifest)) as client:
+ with pytest.raises(ValueError, match=match):
+ await client.read_skill("skill://manual/SKILL.md")
+
+
+async def test_read_skill_rejects_manifest_paths_that_escape_the_skill():
+ files = {"SKILL.md": MANUAL_SKILL_MD}
+ manifest = manifest_for(files)
+ escape = b"owned"
+ manifest["files"].append(
+ {
+ "path": "../escape.txt",
+ "size": len(escape),
+ "hash": f"sha256:{hashlib.sha256(escape).hexdigest()}",
+ }
+ )
+ server = manifest_server(files, manifest)
+ requested: list[str] = []
+
+ @server.resource("skill://escape.txt")
+ def _escape() -> bytes:
+ requested.append("escape")
+ return escape
+
+ async with Client(server) as client:
+ with pytest.raises(ValueError, match="invalid segment"):
+ await client.read_skill("skill://manual/SKILL.md")
+ assert requested == []
+
+
+async def test_read_skill_requires_a_skill_that_matches_its_uri():
+ files = {"SKILL.md": MANUAL_SKILL_MD}
+ server = manifest_server(files, manifest_for(files))
+
+ @server.resource("skill://other/_manifest", mime_type="application/json")
+ def _other_manifest() -> str:
+ return json.dumps(manifest_for(files))
+
+ @server.resource("skill://other/SKILL.md")
+ def _other_skill() -> bytes:
+ return MANUAL_SKILL_MD
+
+ async with Client(server) as client:
+ with pytest.raises(ValueError, match="is named 'manual'"):
+ await client.read_skill("skill://other/SKILL.md")
+
+
+async def test_read_skill_takes_a_skill_md_uri():
+ server = FastMCP("Skills", providers=[SkillCatalogProvider([REVIEW])])
+ async with Client(server) as client:
+ with pytest.raises(ValueError, match="SKILL.md URI"):
+ await client.read_skill("skill://review/notes.md")
+
+
+async def test_read_skill_requires_a_connection():
+ client = Client(FastMCP("Skills", providers=[SkillCatalogProvider([REVIEW])]))
+ with pytest.raises(RuntimeError, match="not connected"):
+ await client.read_skill("skill://review/SKILL.md")
+
+
+async def test_a_read_skill_can_be_served_again():
+ origin = FastMCP(
+ "Origin", providers=[SkillCatalogProvider({"team/review": REVIEW})]
+ )
+ async with skills_client(origin) as client:
+ copied = await client.read_skill("skill://team/review/SKILL.md")
+
+ mirror = FastMCP("Mirror", providers=[SkillCatalogProvider([copied])])
+ async with skills_client(mirror) as client:
+ entries = await client.list_skills()
+ assert [entry.uri for entry in entries] == ["skill://review/SKILL.md"]
+ assert await client.read_skill("skill://review/SKILL.md") == REVIEW
+
+
+async def test_client_group_read_skill_uses_the_named_server():
+ group = ClientGroup(
+ {
+ "a": skills_client(
+ FastMCP("a", providers=[SkillCatalogProvider([REVIEW])])
+ ),
+ "b": Client(FastMCP("b")),
+ }
+ )
+ async with group:
+ assert await group.read_skill("a", "skill://review/SKILL.md") == REVIEW
+ with pytest.raises(KeyError, match="Unknown ClientGroup server"):
+ await group.read_skill("c", "skill://review/SKILL.md")
+ with pytest.raises(RuntimeError, match="not connected"):
+ await group.read_skill("a", "skill://review/SKILL.md")
+
+
+async def test_read_skill_preserves_extension_errors():
+ class Broken(SkillCatalogProvider):
+ async def _get_skill_entry(
+ self, uri: str, context: ServerRequestContext[Any, Any]
+ ) -> MCPSkill | None:
+ raise MCPError(code=INTERNAL_ERROR, message="Catalog unavailable")
+
+ server = FastMCP("Skills", providers=[Broken([REVIEW])])
+ async with skills_client(server) as client:
+ with pytest.raises(MCPError) as exc:
+ await client.read_skill("skill://review/SKILL.md")
+ assert exc.value.error.code == INTERNAL_ERROR
+
+
[email protected]("query", ["", "?ref=main"])
+async def test_read_skill_preserves_manifest_resource_uris(query: str):
+ main_uri = f"github://repo/review/SKILL.md{query}"
+ original = REVIEW.to_mcp_skill()
+ assert isinstance(original.resources, list)
+ records = [
+ record.model_copy(
+ update={
+ "uri": main_uri
+ if record.uri.endswith("/SKILL.md")
+ else record.uri.replace("skill://review/", "github://repo/review/")
+ + "?ref=main"
+ }
+ )
+ for record in original.resources
+ ]
+ entry = original.model_copy(update={"uri": main_uri, "resources": records})
+
+ class Published(SkillsExtension):
+ async def _get_entry(
+ self, uri: str, context: ServerRequestContext[Any, Any]
+ ) -> MCPSkill | None:
+ return entry if uri == main_uri else None
+
+ server = FastMCP("Custom URIs")
+ server.add_extension(Published())
+ for path, record in zip(REVIEW.files, records, strict=True):
+ server.resource(record.uri)(_constant(REVIEW.files[path]))
+
+ async with skills_client(server) as client:
+ assert await client.read_skill(main_uri) == REVIEW
diff --git a/tests/skills/test_skill.py b/tests/skills/test_skill.py
index 717b17be7..4929e0e23 100644
--- a/tests/skills/test_skill.py
+++ b/tests/skills/test_skill.py
@@ -47,6 +47,8 @@ def test_keyword_constructor_renders_skill_md():
({"files": {"SKILL.md": "x"}}, "instructions"),
({"files": {"../escape.md": "x"}}, "invalid segment"),
({"files": {"/abs.md": "x"}}, "relative POSIX"),
+ ({"files": {"C:/escape.md": "x"}}, "relative POSIX"),
+ ({"files": {"C:escape.md": "x"}}, "relative POSIX"),
({"files": {"a": "x", "a/b": "y"}}, "also used as a directory"),
],
)
@@ -144,3 +146,48 @@ def test_skill_is_exported_from_fastmcp():
import fastmcp
assert fastmcp.Skill is Skill
+
+
+def test_to_directory_round_trips_through_from_directory(tmp_path: Path):
+ skill = Skill(
+ name="review",
+ description="Review changes",
+ instructions="# Review\r\n",
+ files={"notes.md": "line one\r\n", "refs/logo.bin": b"\x00\xff\r\n"},
+ )
+ folder = skill.to_directory(tmp_path / "review")
+ assert folder == tmp_path / "review"
+ assert (folder / "refs" / "logo.bin").read_bytes() == b"\x00\xff\r\n"
+ assert Skill.from_directory(folder) == skill
+
+
+def test_to_directory_requires_a_matching_folder_name(tmp_path: Path):
+ skill = Skill(name="review", description="Review", instructions="# Review\n")
+ with pytest.raises(ValueError, match="must match the skill's name"):
+ skill.to_directory(tmp_path / "renamed")
+ assert not (tmp_path / "renamed").exists()
+
+
+def test_to_directory_overwrite_replaces_the_folder(tmp_path: Path):
+ skill = Skill(name="review", description="Review", instructions="# Review\n")
+ folder = tmp_path / "review"
+ folder.mkdir()
+ (folder / "stale.md").write_text("old")
+
+ with pytest.raises(FileExistsError, match="overwrite=True"):
+ skill.to_directory(folder)
+ assert (folder / "stale.md").exists()
+
+ assert skill.to_directory(folder, overwrite=True) == folder
+ assert sorted(p.name for p in folder.iterdir()) == ["SKILL.md"]
+
+
+def test_to_directory_refuses_a_symlink(tmp_path: Path):
+ skill = Skill(name="review", description="Review", instructions="# Review\n")
+ elsewhere = tmp_path / "elsewhere"
+ elsewhere.mkdir()
+ link = tmp_path / "review"
+ link.symlink_to(elsewhere, target_is_directory=True)
+ with pytest.raises(ValueError, match="symlink"):
+ skill.to_directory(link, overwrite=True)
+ assert elsewhere.exists()
diff --git a/tests/utilities/test_skills.py b/tests/utilities/test_skills.py
index 8dfeffd65..c0f285907 100644
--- a/tests/utilities/test_skills.py
+++ b/tests/utilities/test_skills.py
@@ -3,7 +3,6 @@
from __future__ import annotations
import base64
-import json
from pathlib import Path
from typing import cast
@@ -55,11 +54,11 @@ def skills_dir(tmp_path: Path) -> Path:
skills = tmp_path / "skills"
skills.mkdir()
- # Create pdf-processing skill
pdf_skill = skills / "pdf-processing"
pdf_skill.mkdir()
(pdf_skill / "SKILL.md").write_text(
"""---
+name: pdf-processing
description: Process PDF documents
---
@@ -70,11 +69,11 @@ Instructions for PDF handling.
)
(pdf_skill / "reference.md").write_text("# Reference\n\nSome reference docs.")
- # Create code-review skill
code_skill = skills / "code-review"
code_skill.mkdir()
(code_skill / "SKILL.md").write_text(
"""---
+name: code-review
description: Review code for quality
---
@@ -84,10 +83,17 @@ Instructions for reviewing code.
"""
)
- # Create skill with nested files
nested_skill = skills / "nested-skill"
nested_skill.mkdir()
- (nested_skill / "SKILL.md").write_text("# Nested\n\nHas nested files.")
+ (nested_skill / "SKILL.md").write_text(
+ """---
+name: nested-skill
+description: Has nested files
+---
+
+# Nested
+"""
+ )
scripts = nested_skill / "scripts"
scripts.mkdir()
(scripts / "helper.py").write_text("# Helper script\nprint('hello')")
@@ -279,53 +285,6 @@ class TestDownloadSkill:
downloaded = (result / "SKILL.md").read_text()
assert downloaded == original
- async def test_writes_text_resources_as_utf8(
- self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
- ):
- content = "Use the tool — then stop."
- manifest = {
- "skill": "unicode",
- "files": [
- {
- "path": "SKILL.md",
- "size": len(content.encode("utf-8")),
- "hash": "sha256:unicode",
- }
- ],
- }
- client = FakeResourceReader(
- {
- "skill://unicode/_manifest": [
- text_resource("skill://unicode/_manifest", json.dumps(manifest))
- ],
- "skill://unicode/SKILL.md": [
- text_resource("skill://unicode/SKILL.md", content)
- ],
- }
- )
- original_write_text = Path.write_text
-
- def locale_sensitive_write_text(
- path: Path,
- data: str,
- encoding: str | None = None,
- errors: str | None = None,
- newline: str | None = None,
- ) -> int:
- return original_write_text(
- path,
- data,
- encoding=encoding or "ascii",
- errors=errors,
- newline=newline,
- )
-
- monkeypatch.setattr(Path, "write_text", locale_sensitive_write_text)
-
- result = await download_skill(cast(Client, client), "unicode", tmp_path)
-
- assert (result / "SKILL.md").read_text(encoding="utf-8") == content
-
async def test_raises_if_exists_without_overwrite(
self, skills_server: FastMCP, tmp_path: Path
):
@@ -350,6 +309,28 @@ class TestDownloadSkill:
)
assert (result / "SKILL.md").exists()
+ assert not (result / "old-file.txt").exists()
+
+ async def test_rejects_a_file_that_does_not_match_the_manifest(
+ self, skills_server: FastMCP, skills_dir: Path, tmp_path: Path
+ ):
+ async with Client(skills_server) as client:
+ reference = skills_dir / "pdf-processing" / "reference.md"
+ reference.write_bytes(b"x" * len(reference.read_bytes()))
+ with pytest.raises(ValueError, match="does not match its manifest"):
+ await download_skill(client, "pdf-processing", tmp_path)
+ assert not (tmp_path / "pdf-processing").exists()
+
+ async def test_downloads_binary_files(self, skills_dir: Path, tmp_path: Path):
+ data = b"\x00\x01binary data"
+ (skills_dir / "pdf-processing" / "data.bin").write_bytes(data)
+ server = FastMCP("Skills Server")
+ server.add_provider(SkillsDirectoryProvider(roots=skills_dir))
+
+ async with Client(server) as client:
+ result = await download_skill(client, "pdf-processing", tmp_path)
+
+ assert (result / "data.bin").read_bytes() == data
async def test_expands_user_path(self, skills_server: FastMCP, tmp_path: Path):
# This tests that ~ expansion works (though we can't actually test ~)
@@ -358,58 +339,6 @@ class TestDownloadSkill:
assert result.exists()
- async def test_skips_manifest_paths_that_escape_target(self, tmp_path: Path):
- manifest = {
- "skill": "malicious",
- "files": [
- {"path": "SKILL.md", "size": 6, "hash": "sha256:safe"},
- {"path": "../escape.txt", "size": 6, "hash": "sha256:escape"},
- {"path": "/absolute.txt", "size": 8, "hash": "sha256:absolute"},
- ],
- }
-
- client = FakeResourceReader(
- {
- "skill://malicious/_manifest": [
- text_resource("skill://malicious/_manifest", json.dumps(manifest))
- ],
- "skill://malicious/SKILL.md": [
- text_resource("skill://malicious/SKILL.md", "# Safe")
- ],
- }
- )
-
- result = await download_skill(cast(Client, client), "malicious", tmp_path)
-
- assert (result / "SKILL.md").read_text() == "# Safe"
- assert not (tmp_path / "escape.txt").exists()
- assert client.requested_uris == [
- "skill://malicious/_manifest",
- "skill://malicious/SKILL.md",
- ]
-
- async def test_downloads_blob_resources(self, tmp_path: Path):
- data = b"\x00\x01binary data"
- manifest = {
- "skill": "binary",
- "files": [{"path": "data.bin", "size": len(data), "hash": "sha256:data"}],
- }
-
- client = FakeResourceReader(
- {
- "skill://binary/_manifest": [
- text_resource("skill://binary/_manifest", json.dumps(manifest))
- ],
- "skill://binary/data.bin": [
- blob_resource("skill://binary/data.bin", data)
- ],
- }
- )
-
- result = await download_skill(cast(Client, client), "binary", tmp_path)
-
- assert (result / "data.bin").read_bytes() == data
-
class TestSyncSkills:
async def test_downloads_all_skills(self, skills_server: FastMCP, tmp_path: Path):