π The fast, Pythonic way to build MCP servers and clients.
Add client utilities for downloading skills (#2948)
Jeremiah Lowinba18a716bf63
diff --git a/docs/servers/providers/skills.mdx b/docs/servers/providers/skills.mdxindex 1ea038f59..548259c27 100644--- a/docs/servers/providers/skills.mdx+++ b/docs/servers/providers/skills.mdx@@ -285,3 +285,55 @@ async def main():if __name__ == "__main__":asyncio.run(main())```++## Client Utilities++FastMCP provides utilities for downloading skills from any MCP server that exposes them. These are standalone functions in `fastmcp.utilities.skills`.++### Discovering Skills++Use `list_skills()` to see what skills are available on a server.++```python+from fastmcp import Client+from fastmcp.utilities.skills import list_skills++async with Client("http://skills-server/mcp") as client:+ skills = await list_skills(client)+ for skill in skills:+ print(f"{skill.name}: {skill.description}")+```++### Downloading Skills++Use `download_skill()` to download a single skill, or `sync_skills()` to download all available skills.++```python+from pathlib import Path++from fastmcp import Client+from fastmcp.utilities.skills import download_skill, sync_skills++async with Client("http://skills-server/mcp") as client:+ # Download one skill+ path = await download_skill(client, "pdf-processing", Path.home() / ".claude" / "skills")++ # Or download all skills+ paths = await sync_skills(client, Path.home() / ".claude" / "skills")+```++Both functions accept an `overwrite` parameter. When `False` (default), existing skills are skipped. When `True`, existing files are replaced.++### Inspecting Manifests++Use `get_skill_manifest()` to see what files a skill contains before downloading.++```python+from fastmcp import Client+from fastmcp.utilities.skills import get_skill_manifest++async with Client("http://skills-server/mcp") as client:+ manifest = await get_skill_manifest(client, "pdf-processing")+ for file in manifest.files:+ print(f"{file.path} ({file.size} bytes, {file.hash})")+```diff --git a/examples/skills/download_skills.py b/examples/skills/download_skills.pynew file mode 100644index 000000000..69b8d0373--- /dev/null+++ b/examples/skills/download_skills.py@@ -0,0 +1,82 @@+"""Example: Downloading skills from an MCP server.++This example shows how to use the skills client utilities to discover+and download skills from any MCP server that exposes them via SkillsProvider.++Run this script:+ uv run python examples/skills/download_skills.py++This example creates an in-memory server with sample skills. In practice,+you would connect to a remote server URL instead.+"""++import asyncio+import tempfile+from pathlib import Path++from rich.console import Console+from rich.panel import Panel+from rich.table import Table+from rich.tree import Tree++from fastmcp import Client, FastMCP+from fastmcp.server.providers.skills import SkillsDirectoryProvider+from fastmcp.utilities.skills import list_skills, sync_skills++console = Console()+++async def main():+ # For this example, we'll create an in-memory server with skills.+ # In practice, you'd connect to a remote server URL.+ skills_dir = Path(__file__).parent / "sample_skills"+ mcp = FastMCP("Skills Server")+ mcp.add_provider(SkillsDirectoryProvider(roots=skills_dir))++ async with Client(mcp) as client:+ # 1. Discover what skills are available on the server+ console.print()+ console.print(+ Panel.fit(+ "[bold]Discovering skills on MCP server...[/bold]",+ border_style="blue",+ )+ )++ skills = await list_skills(client)++ table = Table(title="Skills Available on Server", show_header=True)+ table.add_column("Skill", style="cyan")+ table.add_column("Description")+ for skill in sorted(skills, key=lambda s: s.name):+ table.add_row(skill.name, skill.description)+ console.print(table)++ # 2. Download all skills to a local directory+ console.print()+ console.print(+ Panel.fit(+ "[bold]Downloading all skills to local directory...[/bold]",+ border_style="green",+ )+ )++ with tempfile.TemporaryDirectory() as tmp:+ paths = await sync_skills(client, tmp)++ tree = Tree(f"[bold]{tmp}[/bold]")+ for skill_path in sorted(paths, key=lambda p: p.name):+ skill_branch = tree.add(f"[cyan]{skill_path.name}/[/cyan]")+ for f in sorted(skill_path.rglob("*")):+ if f.is_file():+ rel = f.relative_to(skill_path)+ skill_branch.add(str(rel))++ console.print(tree)+ console.print(+ f"\n[green]β[/green] Downloaded {len(paths)} skills to local directory"+ )+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/src/fastmcp/utilities/skills.py b/src/fastmcp/utilities/skills.pynew file mode 100644index 000000000..3c7e3c9bf--- /dev/null+++ b/src/fastmcp/utilities/skills.py@@ -0,0 +1,253 @@+"""Client utilities for discovering and downloading skills from MCP servers."""++from __future__ import annotations++import json+from dataclasses import dataclass+from pathlib import Path+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from fastmcp.client import Client+++@dataclass+class SkillSummary:+ """Summary information about a skill available on a server."""++ name: str+ description: str+ uri: str+++@dataclass+class SkillFile:+ """Information about a file within a skill."""++ path: str+ size: int+ hash: str+++@dataclass+class SkillManifest:+ """Full manifest of a skill including all files."""++ name: str+ files: list[SkillFile]+++async def list_skills(client: Client) -> list[SkillSummary]:+ """List all available skills from an MCP server.++ Discovers skills by finding resources with URIs matching the+ `skill://{name}/SKILL.md` pattern.++ Args:+ client: Connected FastMCP client++ Returns:+ List of SkillSummary objects with name, description, and URI++ Example:+ ```python+ from fastmcp import Client+ from fastmcp.utilities.skills import list_skills++ async with Client("http://skills-server/mcp") as client:+ skills = await list_skills(client)+ for skill in skills:+ print(f"{skill.name}: {skill.description}")+ ```+ """+ resources = await client.list_resources()+ skills = []++ for resource in resources:+ uri = str(resource.uri)+ # Match skill://{name}/SKILL.md pattern+ if uri.startswith("skill://") and uri.endswith("/SKILL.md"):+ # Extract skill name from URI+ path_part = uri[len("skill://") :]+ name = path_part.rsplit("/", 1)[0]+ skills.append(+ SkillSummary(+ name=name,+ description=resource.description or "",+ uri=uri,+ )+ )++ return skills+++async def get_skill_manifest(client: Client, skill_name: str) -> SkillManifest:+ """Get the manifest for a specific skill.++ Args:+ client: Connected FastMCP client+ skill_name: Name of the skill++ Returns:+ SkillManifest with file listing++ Raises:+ ValueError: If manifest cannot be read or parsed+ """+ manifest_uri = f"skill://{skill_name}/_manifest"+ result = await client.read_resource(manifest_uri)++ if not result:+ raise ValueError(f"Could not read manifest for skill: {skill_name}")++ content = result[0]+ if hasattr(content, "text"):+ try:+ manifest_data = json.loads(content.text)+ except json.JSONDecodeError as e:+ raise ValueError(f"Invalid manifest JSON for skill: {skill_name}") from e+ else:+ raise ValueError(f"Unexpected manifest format for skill: {skill_name}")++ try:+ return SkillManifest(+ name=manifest_data["skill"],+ files=[+ SkillFile(path=f["path"], size=f["size"], hash=f["hash"])+ for f in manifest_data["files"]+ ],+ )+ except (KeyError, TypeError) as e:+ raise ValueError(f"Invalid manifest format for skill: {skill_name}") from e+++async def download_skill(+ client: Client,+ skill_name: str,+ target_dir: str | Path,+ *,+ overwrite: bool = False,+) -> Path:+ """Download a skill and all its files to a local directory.++ Creates a subdirectory named after the skill containing all files.++ Args:+ client: Connected FastMCP client+ skill_name: Name of the skill to download+ target_dir: Directory where skill folder will be created+ overwrite: If True, overwrite 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+ FileExistsError: If skill directory exists and overwrite=False++ Example:+ ```python+ from fastmcp import Client+ from fastmcp.utilities.skills import download_skill++ async with Client("http://skills-server/mcp") as client:+ skill_path = await download_skill(+ client,+ "pdf-processing",+ "~/.claude/skills"+ )+ print(f"Downloaded to: {skill_path}")+ ```+ """+ target_dir = Path(target_dir).expanduser().resolve()+ skill_dir = target_dir / skill_name++ # 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 hasattr(content, "text"):+ file_path.write_text(content.text)+ elif hasattr(content, "blob"):+ # Handle base64-encoded binary content+ import base64++ file_path.write_bytes(base64.b64decode(content.blob))+ else:+ # Skip unknown content types+ continue++ return skill_dir+++async def sync_skills(+ client: Client,+ target_dir: str | Path,+ *,+ overwrite: bool = False,+) -> list[Path]:+ """Download all available skills from a server.++ Args:+ client: Connected FastMCP client+ target_dir: Directory where skill folders will be created+ overwrite: If True, overwrite existing files++ Returns:+ List of paths to downloaded skill directories++ Example:+ ```python+ from fastmcp import Client+ from fastmcp.utilities.skills import sync_skills++ async with Client("http://skills-server/mcp") as client:+ paths = await sync_skills(client, "~/.claude/skills")+ print(f"Downloaded {len(paths)} skills")+ ```+ """+ skills = await list_skills(client)+ downloaded = []++ for skill in skills:+ try:+ path = await download_skill(+ client, skill.name, target_dir, overwrite=overwrite+ )+ downloaded.append(path)+ except FileExistsError:+ # Skip existing skills when not overwriting+ continue++ return downloadeddiff --git a/tests/utilities/test_skills.py b/tests/utilities/test_skills.pynew file mode 100644index 000000000..28a3f4fd1--- /dev/null+++ b/tests/utilities/test_skills.py@@ -0,0 +1,269 @@+"""Tests for skills client utilities."""++from __future__ import annotations++from pathlib import Path++import pytest++from fastmcp import Client, FastMCP+from fastmcp.server.providers.skills import SkillsDirectoryProvider+from fastmcp.utilities.skills import (+ SkillFile,+ SkillManifest,+ SkillSummary,+ download_skill,+ get_skill_manifest,+ list_skills,+ sync_skills,+)+++def skills_dir(tmp_path: Path) -> Path:+ """Create a temporary skills directory with sample skills."""+ skills = tmp_path / "skills"+ skills.mkdir()++ # Create pdf-processing skill+ pdf_skill = skills / "pdf-processing"+ pdf_skill.mkdir()+ (pdf_skill / "SKILL.md").write_text(+ """---+description: Process PDF documents+---++# PDF Processing++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(+ """---+description: Review code for quality+---++# Code Review++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.")+ scripts = nested_skill / "scripts"+ scripts.mkdir()+ (scripts / "helper.py").write_text("# Helper script\nprint('hello')")++ return skills+++def skills_server(skills_dir: Path) -> FastMCP:+ """Create a FastMCP server with skills provider."""+ mcp = FastMCP("Skills Server")+ mcp.add_provider(SkillsDirectoryProvider(roots=skills_dir))+ return mcp+++class TestListSkills:+ async def test_lists_available_skills(self, skills_server: FastMCP):+ async with Client(skills_server) as client:+ skills = await list_skills(client)++ assert len(skills) == 3+ names = {s.name for s in skills}+ assert names == {"pdf-processing", "code-review", "nested-skill"}++ async def test_returns_skill_summary_objects(self, skills_server: FastMCP):+ async with Client(skills_server) as client:+ skills = await list_skills(client)++ for skill in skills:+ assert isinstance(skill, SkillSummary)+ assert skill.name+ assert skill.uri.startswith("skill://")+ assert skill.uri.endswith("/SKILL.md")++ async def test_includes_descriptions(self, skills_server: FastMCP):+ async with Client(skills_server) as client:+ skills = await list_skills(client)++ by_name = {s.name: s for s in skills}+ assert by_name["pdf-processing"].description == "Process PDF documents"+ assert by_name["code-review"].description == "Review code for quality"++ async def test_empty_server_returns_empty_list(self):+ mcp = FastMCP("Empty")+ async with Client(mcp) as client:+ skills = await list_skills(client)++ assert skills == []+++class TestGetSkillManifest:+ async def test_returns_manifest_with_files(self, skills_server: FastMCP):+ async with Client(skills_server) as client:+ manifest = await get_skill_manifest(client, "pdf-processing")++ assert isinstance(manifest, SkillManifest)+ assert manifest.name == "pdf-processing"+ assert len(manifest.files) == 2++ paths = {f.path for f in manifest.files}+ assert paths == {"SKILL.md", "reference.md"}++ async def test_files_have_size_and_hash(self, skills_server: FastMCP):+ async with Client(skills_server) as client:+ manifest = await get_skill_manifest(client, "pdf-processing")++ for file in manifest.files:+ assert isinstance(file, SkillFile)+ assert file.size > 0+ assert file.hash.startswith("sha256:")++ async def test_nested_files_use_posix_paths(self, skills_server: FastMCP):+ async with Client(skills_server) as client:+ manifest = await get_skill_manifest(client, "nested-skill")++ paths = {f.path for f in manifest.files}+ assert "scripts/helper.py" in paths++ async def test_nonexistent_skill_raises(self, skills_server: FastMCP):+ async with Client(skills_server) as client:+ with pytest.raises(Exception):+ await get_skill_manifest(client, "nonexistent")+++class TestDownloadSkill:+ async def test_downloads_skill_to_directory(+ self, skills_server: FastMCP, tmp_path: Path+ ):+ target = tmp_path / "downloaded"+ target.mkdir()++ async with Client(skills_server) as client:+ result = await download_skill(client, "pdf-processing", target)++ assert result == target / "pdf-processing"+ assert result.exists()+ assert (result / "SKILL.md").exists()+ assert (result / "reference.md").exists()++ async def test_creates_nested_directories(+ self, skills_server: FastMCP, tmp_path: Path+ ):+ target = tmp_path / "downloaded"+ target.mkdir()++ async with Client(skills_server) as client:+ result = await download_skill(client, "nested-skill", target)++ assert (result / "scripts" / "helper.py").exists()+ content = (result / "scripts" / "helper.py").read_text()+ assert "print('hello')" in content++ async def test_preserves_file_content(+ self, skills_server: FastMCP, tmp_path: Path, skills_dir: Path+ ):+ target = tmp_path / "downloaded"+ target.mkdir()++ async with Client(skills_server) as client:+ result = await download_skill(client, "pdf-processing", target)++ original = (skills_dir / "pdf-processing" / "SKILL.md").read_text()+ downloaded = (result / "SKILL.md").read_text()+ assert downloaded == original++ async def test_raises_if_exists_without_overwrite(+ self, skills_server: FastMCP, tmp_path: Path+ ):+ target = tmp_path / "downloaded"+ target.mkdir()+ (target / "pdf-processing").mkdir()++ async with Client(skills_server) as client:+ with pytest.raises(FileExistsError):+ await download_skill(client, "pdf-processing", target)++ async def test_overwrites_with_flag(self, skills_server: FastMCP, tmp_path: Path):+ target = tmp_path / "downloaded"+ target.mkdir()+ existing = target / "pdf-processing"+ existing.mkdir()+ (existing / "old-file.txt").write_text("old content")++ async with Client(skills_server) as client:+ result = await download_skill(+ client, "pdf-processing", target, overwrite=True+ )++ assert (result / "SKILL.md").exists()++ async def test_expands_user_path(self, skills_server: FastMCP, tmp_path: Path):+ # This tests that ~ expansion works (though we can't actually test ~)+ async with Client(skills_server) as client:+ result = await download_skill(client, "code-review", tmp_path)++ assert result.exists()+++class TestSyncSkills:+ async def test_downloads_all_skills(self, skills_server: FastMCP, tmp_path: Path):+ target = tmp_path / "synced"+ target.mkdir()++ async with Client(skills_server) as client:+ results = await sync_skills(client, target)++ assert len(results) == 3+ assert (target / "pdf-processing").exists()+ assert (target / "code-review").exists()+ assert (target / "nested-skill").exists()++ async def test_skips_existing_without_overwrite(+ self, skills_server: FastMCP, tmp_path: Path+ ):+ target = tmp_path / "synced"+ target.mkdir()+ (target / "pdf-processing").mkdir()++ async with Client(skills_server) as client:+ results = await sync_skills(client, target)++ # Should skip pdf-processing, download the other two+ assert len(results) == 2+ names = {r.name for r in results}+ assert "pdf-processing" not in names++ async def test_overwrites_with_flag(self, skills_server: FastMCP, tmp_path: Path):+ target = tmp_path / "synced"+ target.mkdir()+ (target / "pdf-processing").mkdir()++ async with Client(skills_server) as client:+ results = await sync_skills(client, target, overwrite=True)++ assert len(results) == 3++ async def test_returns_paths_to_downloaded_skills(+ self, skills_server: FastMCP, tmp_path: Path+ ):+ target = tmp_path / "synced"+ target.mkdir()++ async with Client(skills_server) as client:+ results = await sync_skills(client, target)++ for path in results:+ assert isinstance(path, Path)+ assert path.exists()+ assert (path / "SKILL.md").exists()