π The fast, Pythonic way to build MCP servers and clients.
Add Client.read_skill and tighten skills docs (#6087)
nate nowack7ebabb2e0db6
diff --git a/docs/servers/skills.mdx b/docs/servers/skills.mdxindex bf10d579e..c30509b33 100644--- a/docs/servers/skills.mdx+++ b/docs/servers/skills.mdx@@ -30,7 +30,7 @@ That's a skills server. Every client can read `skill://release-notes/SKILL.md` a## Where skills come from-A `Skill` is just files. Write it in Python as above, or load what you already have:+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:```pythonfrom fastmcp import Skill@@ -40,22 +40,33 @@ 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; 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.+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.-If your skills live somewhere that changes, like a database, override `load_skills()`. FastMCP calls it once per request:+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:```python+from pathlib import Path+from fastmcp import Skillfrom fastmcp.skills.provider import SkillCatalogProvider+ROWS = [{"name": "triage", "description": "Triage issues.", "body": "# Triage\n"}]+class StoredSkills(SkillCatalogProvider):async def load_skills(self) -> list[Skill]:- rows = [{"SKILL.md": "---\nname: triage\ndescription: Triage issues.\n---\n"}]- return [Skill.from_files(files) for files in rows]+ return [+ Skill(name=row["name"], description=row["description"], instructions=row["body"])+ for row in ROWS+ ]+++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()]```-If you're still editing a folder and want changes to show up live, serve it straight from disk with `SkillsDirectoryProvider(path, experimental_skills=True)`. Presets like `ClaudeSkillsProvider` do the same for a coding agent's own skills folder.+`SkillsDirectoryProvider` and presets like `ClaudeSkillsProvider` also serve folders straight from disk; pass `experimental_skills=True` to make them discoverable.## Access control@@ -67,36 +78,37 @@ Skills come along when you [mount](/servers/composition) a server, at the URIs t## Read skills from a client-### Install skills into a local agent+### Discover and read skills-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:+Opt the client into the extension, list what the server offers, and read a whole skill with `read_skill()`:```python-from pathlib import Path-from fastmcp import Client-from fastmcp.utilities.skills import sync_skills+from fastmcp.skills import SkillsClientExtension-async with Client("http://localhost:8000/mcp") as client:- await sync_skills(client, Path.home() / ".claude" / "skills", overwrite=True)+client = Client("http://localhost:8000/mcp", extensions=[SkillsClientExtension()])+async with client:+ for entry in await client.list_skills():+ print(entry.uri, entry.frontmatter.description)+ skill = await client.read_skill("skill://release-notes/SKILL.md")```-### Discover skills with the Skills extension+`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.++### Install skills into a local agent-Opt the client into the extension and ask:+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:```python+from pathlib import Path+from fastmcp import Client-from fastmcp.skills import SkillsClientExtension+from fastmcp.utilities.skills import sync_skills-client = Client("http://localhost:8000/mcp", extensions=[SkillsClientExtension()])-async with client:- for skill in await client.list_skills():- print(skill.uri, skill.frontmatter.description)+async with Client("http://localhost:8000/mcp") as client:+ await sync_skills(client, Path.home() / ".claude" / "skills", overwrite=True)```-You get metadata, not content. Read the files you need with `read_resource()`, and check each against its manifest `digest` before trusting it. [`ClientGroup.list_skills()`](/clients/client-groups) does the same across several servers.-## 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/mixins/skills.py b/fastmcp_slim/fastmcp/client/mixins/skills.pyindex 56bd42390..9a320194d 100644--- a/fastmcp_slim/fastmcp/client/mixins/skills.py+++ b/fastmcp_slim/fastmcp/client/mixins/skills.py@@ -2,6 +2,8 @@from __future__ import annotations+import base64+import hashlibfrom typing import TYPE_CHECKING, castimport mcp_types@@ -18,12 +20,14 @@ from fastmcp.skills.models import (ListSkillsRequest,ListSkillsResult,MCPSkill,+ _parse_resource_uri,)from fastmcp.telemetry import inject_trace_contextfrom fastmcp.utilities.logging import get_loggerif TYPE_CHECKING:from fastmcp.client.client import Client+ from fastmcp.skills.skill import Skilllogger = get_logger(__name__)@@ -219,3 +223,49 @@ 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`.++ 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`.++ Args:+ uri: URI of the skill's `SKILL.md` resource.++ Returns:+ The skill, with every file's exact bytes.++ 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.+ 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+ 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:+ raise ValueError(+ f"Skill file {record.uri!r} does not match its manifest digest"+ )+ relative = "/".join(_parse_resource_uri(record.uri)[2][root_depth:])+ files[relative] = data+ return Skill.from_files(files)diff --git a/tests/skills/test_provider.py b/tests/skills/test_provider.pyindex 55e05c986..c5a48e7f9 100644--- a/tests/skills/test_provider.py+++ b/tests/skills/test_provider.py@@ -194,3 +194,42 @@ async def test_shadowed_file_hides_skill():def test_invalid_catalogs(skills: object, message: str):with pytest.raises(ValueError, match=message):SkillCatalogProvider(skills) # ty: ignore[invalid-argument-type]+++async def test_read_skill_returns_the_served_skill():+ server = serve(SkillCatalogProvider({"team/review": REVIEW, "deploy": DEPLOY}))+ async with skills_client(server) as client:+ assert await client.read_skill("skill://team/review/SKILL.md") == REVIEW+ assert await client.read_skill("skill://deploy/SKILL.md") == DEPLOY+++async def test_read_skill_can_be_served_again():+ source = serve(SkillCatalogProvider([REVIEW]))+ async with skills_client(source) as client:+ skill = await client.read_skill("skill://review/SKILL.md")++ mirror = serve(SkillCatalogProvider([skill]))+ async with skills_client(mirror) as client:+ assert await client.read_skill("skill://review/SKILL.md") == REVIEW+++async def test_read_skill_rejects_bytes_that_miss_the_manifest():+ provider = SkillCatalogProvider([REVIEW])+ server = serve(provider)++ @server.resource("skill://review/notes.md")+ def tampered() -> str:+ 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