π The fast, Pythonic way to build MCP servers and clients.
Add SEP-2640 Skills extension foundation (#5057)
Bill Eastonadf90b661038
diff --git a/docs/clients/client.mdx b/docs/clients/client.mdxindex bb862188f..26fbeb018 100644--- a/docs/clients/client.mdx+++ b/docs/clients/client.mdx@@ -313,6 +313,36 @@ client = Client()```+### Skills extension++To discover skills from a server that implements the MCP Skills extension+(SEP-2640), opt in with `SkillsClientExtension`. The client then exposes+`list_skills_mcp()` for one protocol page, `list_skills()` for automatic+pagination, and `get_skill_mcp()` or `get_skill()` for authoritative lookup by+the URI of a skill's `SKILL.md`.++```python+from fastmcp import Client+from fastmcp.skills import SkillsClientExtension++client = Client(+ "https://example.com/mcp",+ extensions=[SkillsClientExtension()],+)++async with client:+ skills = await client.list_skills()+ skill = await client.get_skill("skill://code-review/SKILL.md")+```++The Skills extension is available only on modern MCP connections. These methods+raise before sending a request when the client did not opt in or the negotiated+server did not advertise `io.modelcontextprotocol/skills`.++Both protocol results carry the server's response-cache hints. A client created+with `cache=True` honors those hints; pass `cache_mode="refresh"` or+`cache_mode="bypass"` to a Skills method to override the cache for one call.+## OperationsFastMCP clients interact with three types of server components.diff --git a/fastmcp_slim/fastmcp/client/caching.py b/fastmcp_slim/fastmcp/client/caching.pyindex 75423819f..f14b908b1 100644--- a/fastmcp_slim/fastmcp/client/caching.py+++ b/fastmcp_slim/fastmcp/client/caching.py@@ -47,6 +47,7 @@ from mcp.client.caching import CacheEntry, CacheKeyfrom mcp_types import CacheableResultfrom mcp_types.methods import MONOLITH_RESULTS+from fastmcp.skills.models import GetSkillResult, ListSkillsResultfrom fastmcp.utilities.logging import get_loggerfrom fastmcp.utilities.types import FastMCPBaseModel@@ -57,12 +58,13 @@ DEFAULT_CACHE_COLLECTION = "fastmcp_response_cache"def _cacheable_result_models() -> dict[str, type[CacheableResult]]:- """Allowlist of `{class name: model}` for every cacheable result type.+ """Allowlist of `{class name: model}` for cacheable result types.Derived from `MONOLITH_RESULTS` (the SDK's per-method result registry) so it- tracks the CACHEABLE_METHODS surface automatically. The class name is the- type tag written into the envelope; reconstruction looks the model up here- rather than importing an arbitrary name from store contents.+ tracks the core surface automatically, then extended with FastMCP's built-in+ extension results. The class name is the type tag written into the envelope;+ reconstruction looks the model up here rather than importing an arbitrary name+ from store contents."""models: dict[str, type[CacheableResult]] = {}for row in MONOLITH_RESULTS.values():@@ -70,6 +72,8 @@ def _cacheable_result_models() -> dict[str, type[CacheableResult]]:for arm in arms:if isinstance(arm, type) and issubclass(arm, CacheableResult):models[arm.__name__] = arm+ for model in (ListSkillsResult, GetSkillResult):+ models[model.__name__] = modelreturn modelsdiff --git a/fastmcp_slim/fastmcp/client/client.py b/fastmcp_slim/fastmcp/client/client.pyindex c0d023d09..49318f87b 100644--- a/fastmcp_slim/fastmcp/client/client.py+++ b/fastmcp_slim/fastmcp/client/client.py@@ -66,6 +66,7 @@ from fastmcp.client.messages import MessageHandler, MessageHandlerTfrom fastmcp.client.mixins import (ClientPromptsMixin,ClientResourcesMixin,+ ClientSkillsMixin,ClientToolsMixin,)from fastmcp.client.progress import ProgressHandler, default_progress_handler@@ -261,6 +262,7 @@ class CallToolResult:class Client(Generic[ClientTransportT],+ ClientSkillsMixin,ClientResourcesMixin,ClientPromptsMixin,ClientToolsMixin,@@ -1230,17 +1232,18 @@ class Client(method: str,*,cursor: str | None,+ params_key: str = "",cache_mode: CacheMode,send: Callable[[], Coroutine[Any, Any, CacheableT]],absorb: Callable[[CacheableT], CacheableT] | None = None,) -> CacheableT:- """Serve one of the cacheable list verbs through the response cache.+ """Serve a cacheable request through the response cache.- Mirrors the SDK Client's `_cached_fetch`: cursorless `use` calls are served- from (and stored to) the cache; a cursor page skips the cache (and evicts on- an expired-cursor `INVALID_PARAMS`, which signals the listing changed). The- cache is inert on legacy connections because the SDK cache reads no TTL/scope- hints below the modern era, so nothing is ever stored to serve.+ Mirrors the SDK Client's list caching while also supporting cacheable+ extension methods whose request parameters form part of the cache key.+ Cursor pages skip the cache and evict a listing on an expired-cursor+ `INVALID_PARAMS`. The cache is inert on legacy connections because the SDK+ cache reads no TTL/scope hints below the modern era.`absorb` (tools/list only) re-applies the session's derived per-tool state to aserved cache hit, since a hit skips `session.list_tools`.@@ -1259,12 +1262,15 @@ class Client(if e.code == mcp_types.INVALID_PARAMS:await cache.evict_method(method)raise- if cache_mode == "use" and (hit := await cache.read(method, "")) is not None:+ if (+ cache_mode == "use"+ and (hit := await cache.read(method, params_key)) is not None+ ):served = cast(CacheableT, hit)return served if absorb is None else absorb(served)- gen = cache.capture(method, "")+ gen = cache.capture(method, params_key)result = await send()- await cache.write(method, "", result, gen, cache_mode)+ await cache.write(method, params_key, result, gen, cache_mode)return resultasync def _drive_input_required(diff --git a/fastmcp_slim/fastmcp/client/mixins/__init__.py b/fastmcp_slim/fastmcp/client/mixins/__init__.pyindex f0c8ff85e..b2692c292 100644--- a/fastmcp_slim/fastmcp/client/mixins/__init__.py+++ b/fastmcp_slim/fastmcp/client/mixins/__init__.py@@ -2,10 +2,12 @@from fastmcp.client.mixins.prompts import ClientPromptsMixinfrom fastmcp.client.mixins.resources import ClientResourcesMixin+from fastmcp.client.mixins.skills import ClientSkillsMixinfrom fastmcp.client.mixins.tools import ClientToolsMixin__all__ = ["ClientPromptsMixin","ClientResourcesMixin",+ "ClientSkillsMixin","ClientToolsMixin",]diff --git a/fastmcp_slim/fastmcp/client/mixins/skills.py b/fastmcp_slim/fastmcp/client/mixins/skills.pynew file mode 100644index 000000000..602f40d8c--- /dev/null+++ b/fastmcp_slim/fastmcp/client/mixins/skills.py@@ -0,0 +1,214 @@+"""Skills-extension methods for the FastMCP client."""++from __future__ import annotations++from typing import TYPE_CHECKING, cast++import mcp_types+from mcp.client.caching import CacheMode+from mcp_types.version import MODERN_PROTOCOL_VERSIONS++from fastmcp.client.telemetry import client_span+from fastmcp.skills._constants import SKILLS_EXTENSION_ID+from fastmcp.skills.models import (+ GetSkillParams,+ GetSkillRequest,+ GetSkillResult,+ ListSkillsParams,+ ListSkillsRequest,+ ListSkillsResult,+ Skill,+)+from fastmcp.telemetry import inject_trace_context+from fastmcp.utilities.logging import get_logger++if TYPE_CHECKING:+ from fastmcp.client.client import Client++logger = get_logger(__name__)++AUTO_PAGINATION_MAX_PAGES = 250+++def _trace_meta() -> mcp_types.RequestParamsMeta | None:+ return cast("mcp_types.RequestParamsMeta | None", inject_trace_context(None))+++class ClientSkillsMixin:+ """Mixin providing SEP-2640 Skills methods for `Client`."""++ def _require_skills_extension(self: Client) -> None:+ if self.protocol_version is None:+ raise RuntimeError(+ "Client is not connected. Use the 'async with client:' context "+ "manager first."+ )+ if self.protocol_version not in MODERN_PROTOCOL_VERSIONS:+ raise RuntimeError("The Skills extension requires a modern MCP connection")++ client_extensions = self._session_kwargs.get("extensions") or {}+ if SKILLS_EXTENSION_ID not in client_extensions:+ raise RuntimeError(+ "This client did not opt into the Skills extension; pass "+ "SkillsClientExtension() in Client(extensions=[...])"+ )++ capabilities = self.server_capabilities+ server_extensions = capabilities.extensions if capabilities else None+ if not server_extensions or SKILLS_EXTENSION_ID not in server_extensions:+ raise RuntimeError("The server does not advertise the Skills extension")++ async def list_skills_mcp(+ self: Client,+ *,+ cursor: str | None = None,+ cache_mode: CacheMode = "use",+ ) -> ListSkillsResult:+ """Send one `skills/list` request and return its protocol result.++ Args:+ cursor: Optional pagination cursor from a previous result.+ cache_mode: Response-cache behavior for this call.++ Returns:+ The complete protocol result, including cache and pagination fields.++ Raises:+ RuntimeError: If the client is disconnected or Skills was not negotiated.+ MCPError: If the server rejects the request.+ """+ self._require_skills_extension()+ with client_span(+ "skills/list",+ "skills/list",+ "",+ session_id=self.transport.get_session_id(),+ ):++ async def _send() -> ListSkillsResult:+ request = ListSkillsRequest(+ params=ListSkillsParams(cursor=cursor, meta=_trace_meta())+ )+ return await self._await_with_session_monitoring(+ self.session.send_request(request, ListSkillsResult)+ )++ return await self._cached_fetch(+ "skills/list",+ cursor=cursor,+ cache_mode=cache_mode,+ send=_send,+ )++ async def list_skills(+ self: Client,+ max_pages: int = AUTO_PAGINATION_MAX_PAGES,+ *,+ cache_mode: CacheMode = "use",+ ) -> list[Skill]:+ """Retrieve every page returned by `skills/list`.++ Args:+ max_pages: Maximum number of pages to fetch before raising.+ cache_mode: Response-cache behavior for the first page.++ Returns:+ Every skill entry returned across the server's pages.++ Raises:+ RuntimeError: If Skills was not negotiated or the page limit is reached.+ MCPError: If the server rejects a request.+ """+ skills: list[Skill] = []+ cursor: str | None = None+ seen_cursors: set[str] = set()++ for _ in range(max_pages):+ result = await self.list_skills_mcp(cursor=cursor, cache_mode=cache_mode)+ skills.extend(result.skills)+ if not result.next_cursor:+ break+ if result.next_cursor in seen_cursors:+ logger.warning(+ "[%s] Server returned duplicate pagination cursor %r for "+ "list_skills; stopping pagination",+ self.name,+ result.next_cursor,+ )+ break+ seen_cursors.add(result.next_cursor)+ cursor = result.next_cursor+ else:+ raise RuntimeError(+ f"[{self.name}] Reached auto-pagination limit ({max_pages} pages) "+ "for list_skills. Use list_skills_mcp() for manual pagination, "+ "or increase max_pages."+ )++ return skills++ async def get_skill_mcp(+ self: Client,+ uri: str,+ *,+ cache_mode: CacheMode = "use",+ ) -> GetSkillResult:+ """Send a `skills/get` request and return its protocol result.++ Args:+ uri: URI of the skill's `SKILL.md` resource.+ cache_mode: Response-cache behavior for this call.++ Returns:+ The complete protocol result, including cache fields.++ Raises:+ RuntimeError: If the client is disconnected or Skills was not negotiated.+ MCPError: If the server rejects the request.+ """+ self._require_skills_extension()+ with client_span(+ "skills/get",+ "skills/get",+ uri,+ session_id=self.transport.get_session_id(),+ resource_uri=uri,+ ):++ async def _send() -> GetSkillResult:+ request = GetSkillRequest(+ params=GetSkillParams(uri=uri, meta=_trace_meta())+ )+ return await self._await_with_session_monitoring(+ self.session.send_request(request, GetSkillResult)+ )++ return await self._cached_fetch(+ "skills/get",+ cursor=None,+ params_key=uri,+ cache_mode=cache_mode,+ send=_send,+ )++ async def get_skill(+ self: Client,+ uri: str,+ *,+ cache_mode: CacheMode = "use",+ ) -> Skill:+ """Retrieve one skill entry by its `SKILL.md` resource URI.++ Args:+ uri: URI of the skill's `SKILL.md` resource.+ cache_mode: Response-cache behavior for this call.++ Returns:+ The skill entry returned by the server.++ Raises:+ RuntimeError: If the client is disconnected or Skills was not negotiated.+ MCPError: If the server rejects the request.+ """+ result = await self.get_skill_mcp(uri, cache_mode=cache_mode)+ return result.skilldiff --git a/fastmcp_slim/fastmcp/skills/__init__.py b/fastmcp_slim/fastmcp/skills/__init__.pynew file mode 100644index 000000000..70e709b54--- /dev/null+++ b/fastmcp_slim/fastmcp/skills/__init__.py@@ -0,0 +1,31 @@+"""Protocol support for the MCP Skills extension (SEP-2640)."""++from typing import TYPE_CHECKING+from fastmcp.skills.models import (+ GetSkillResult,+ ListSkillsResult,+ Skill,+ SkillFrontmatter,+ SkillResource,+)++__all__ = [+ "GetSkillResult",+ "ListSkillsResult",+ "Skill",+ "SkillFrontmatter",+ "SkillResource",+ "SkillsClientExtension",+]+++if TYPE_CHECKING:+ from fastmcp.skills.client import SkillsClientExtension as SkillsClientExtension+++def __getattr__(name: str) -> object:+ if name == "SkillsClientExtension":+ from fastmcp.skills.client import SkillsClientExtension++ return SkillsClientExtension+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")diff --git a/fastmcp_slim/fastmcp/skills/_constants.py b/fastmcp_slim/fastmcp/skills/_constants.pynew file mode 100644index 000000000..38199bb05--- /dev/null+++ b/fastmcp_slim/fastmcp/skills/_constants.py@@ -0,0 +1,3 @@+"""Shared constants for the MCP Skills extension."""++SKILLS_EXTENSION_ID = "io.modelcontextprotocol/skills"diff --git a/fastmcp_slim/fastmcp/skills/_source.py b/fastmcp_slim/fastmcp/skills/_source.pynew file mode 100644index 000000000..d37a1a69f--- /dev/null+++ b/fastmcp_slim/fastmcp/skills/_source.py@@ -0,0 +1,23 @@+"""Private source contract consumed by `SkillsExtension`."""++from __future__ import annotations++from collections.abc import Sequence+from typing import Any, Protocol, runtime_checkable++from mcp.server.context import ServerRequestContext++from fastmcp.skills.models import Skill+++@runtime_checkable+class _SkillSource(Protocol):+ """A provider capable of producing caller-scoped Skills entries."""++ async def _list_skill_entries(+ self, context: ServerRequestContext[Any, Any]+ ) -> Sequence[Skill]: ...++ async def _get_skill_entry(+ self, uri: str, context: ServerRequestContext[Any, Any]+ ) -> Skill | None: ...diff --git a/fastmcp_slim/fastmcp/skills/client.py b/fastmcp_slim/fastmcp/skills/client.pynew file mode 100644index 000000000..5585edcdf--- /dev/null+++ b/fastmcp_slim/fastmcp/skills/client.py@@ -0,0 +1,11 @@+"""Client capability declaration for the MCP Skills extension."""++from mcp.client.extension import ClientExtension++from fastmcp.skills._constants import SKILLS_EXTENSION_ID+++class SkillsClientExtension(ClientExtension):+ """Declare support for the SEP-2640 Skills extension."""++ identifier = SKILLS_EXTENSION_IDdiff --git a/fastmcp_slim/fastmcp/skills/extension.py b/fastmcp_slim/fastmcp/skills/extension.pynew file mode 100644index 000000000..c5933e238--- /dev/null+++ b/fastmcp_slim/fastmcp/skills/extension.py@@ -0,0 +1,139 @@+"""FastMCP server implementation of the MCP Skills extension."""++from __future__ import annotations++from collections import Counter+from collections.abc import Sequence+from typing import TYPE_CHECKING, Any, cast++from mcp.server.context import ServerRequestContext+from mcp.shared.exceptions import MCPError+from mcp_types import INVALID_PARAMS+from mcp_types.version import MODERN_PROTOCOL_VERSIONS++from fastmcp.server.extensions import MethodBinding, ServerExtension+from fastmcp.server.mixins.mcp_operations import _apply_pagination+from fastmcp.server.providers.base import Provider+from fastmcp.skills._constants import SKILLS_EXTENSION_ID+from fastmcp.skills._source import _SkillSource+from fastmcp.skills.models import (+ GetSkillParams,+ GetSkillResult,+ ListSkillsParams,+ ListSkillsResult,+)+from fastmcp.utilities.async_utils import gather+from fastmcp.utilities.logging import get_logger++if TYPE_CHECKING:+ from fastmcp.server.server import FastMCP++logger = get_logger(__name__)++_SKILLS_METHOD_VERSIONS = frozenset(MODERN_PROTOCOL_VERSIONS)+++class SkillsExtension(ServerExtension):+ """Expose caller-scoped skill sources through SEP-2640 methods."""++ identifier = SKILLS_EXTENSION_ID++ def __init__(self, *, providers: Sequence[Provider]) -> None:+ if not providers:+ raise ValueError("SkillsExtension requires at least one provider")+ if len({id(provider) for provider in providers}) != len(providers):+ raise ValueError("SkillsExtension providers must be unique")+ self._providers = tuple(providers)++ def _bind(self, server: FastMCP) -> None:+ self._validate_configuration(server)+ super()._bind(server)++ def _validate_configuration(self, server: FastMCP) -> None:+ if server.transforms:+ raise ValueError(+ "SkillsExtension does not yet support server-level transforms"+ )++ for provider in self._providers:+ if not any(registered is provider for registered in server.providers):+ raise ValueError(+ "SkillsExtension providers must be registered directly on the "+ "same FastMCP server before the extension"+ )+ if provider.transforms:+ raise ValueError(+ "SkillsExtension does not yet support transformed providers"+ )+ if not isinstance(provider, _SkillSource):+ raise TypeError(+ f"{type(provider).__name__} is not a SkillsExtension source"+ )++ @property+ def _sources(self) -> tuple[_SkillSource, ...]:+ return cast("tuple[_SkillSource, ...]", self._providers)++ def methods(self) -> Sequence[MethodBinding]:+ return (+ MethodBinding(+ method="skills/list",+ params_type=ListSkillsParams,+ handler=self._handle_list,+ protocol_versions=_SKILLS_METHOD_VERSIONS,+ ),+ MethodBinding(+ method="skills/get",+ params_type=GetSkillParams,+ handler=self._handle_get,+ protocol_versions=_SKILLS_METHOD_VERSIONS,+ ),+ )++ def _validate_live_configuration(self) -> None:+ self._validate_configuration(self.server)++ async def _handle_list(+ self,+ context: ServerRequestContext[Any, Any],+ params: ListSkillsParams,+ ) -> ListSkillsResult:+ self._validate_live_configuration()++ source_entries = await gather(+ source._list_skill_entries(context) for source in self._sources+ )+ entries = [entry for group in source_entries for entry in group]+ counts = Counter(entry.uri for entry in entries)+ collisions = sorted(uri for uri, count in counts.items() if count > 1)+ if collisions:+ logger.warning(+ "Omitting duplicate Skills entries for URIs: %s",+ ", ".join(collisions),+ )+ entries = sorted(+ (entry for entry in entries if counts[entry.uri] == 1),+ key=lambda entry: entry.uri,+ )+ page, next_cursor = _apply_pagination(+ entries, params.cursor, self.server._list_page_size+ )+ return ListSkillsResult(skills=page, next_cursor=next_cursor)++ async def _handle_get(+ self,+ context: ServerRequestContext[Any, Any],+ params: GetSkillParams,+ ) -> GetSkillResult:+ self._validate_live_configuration()++ results = await gather(+ source._get_skill_entry(params.uri, context) for source in self._sources+ )+ matches = [entry for entry in results if entry is not None]+ if len(matches) != 1 or matches[0].uri != params.uri:+ raise MCPError(+ code=INVALID_PARAMS,+ message=f"Unknown skill URI: {params.uri}",+ )+ return GetSkillResult(skill=matches[0])diff --git a/fastmcp_slim/fastmcp/skills/models.py b/fastmcp_slim/fastmcp/skills/models.pynew file mode 100644index 000000000..8bd8dec72--- /dev/null+++ b/fastmcp_slim/fastmcp/skills/models.py@@ -0,0 +1,223 @@+"""Wire models for the MCP Skills extension (SEP-2640)."""++from __future__ import annotations++import math+import re+from typing import Literal, cast+from urllib.parse import unquote, urlsplit++import mcp_types+from pydantic import (+ BaseModel,+ ConfigDict,+ Field,+ JsonValue,+ RootModel,+ field_validator,+ model_validator,+)++_SKILL_NAME_PATTERN = re.compile(r"^(?!-)(?!.*--)[a-z0-9-]+(?<!-)$")+_SHA256_PATTERN = r"^sha256:[0-9a-f]{64}$"+++def _parse_resource_uri(uri: str) -> tuple[str, str, tuple[str, ...]]:+ parsed = urlsplit(uri)+ if not parsed.scheme:+ raise ValueError("resource URI must include a scheme")++ segments: list[str] = []+ for raw_segment in parsed.path.split("/"):+ if not raw_segment:+ continue+ segment = unquote(raw_segment)+ if segment in {".", ".."} or "/" in segment or "\\" in segment:+ raise ValueError("resource URI path contains an invalid segment")+ segments.append(segment)+ return parsed.scheme.lower(), parsed.netloc, tuple(segments)+++class SkillFrontmatter(RootModel[dict[str, JsonValue]]):+ """Agent Skills frontmatter carried verbatim as JSON-compatible values."""++ @model_validator(mode="after")+ def validate_agent_skills_fields(self) -> SkillFrontmatter:+ name = self.root.get("name")+ if (+ not isinstance(name, str)+ or len(name) > 64+ or not _SKILL_NAME_PATTERN.fullmatch(name)+ ):+ raise ValueError(+ "name must be 1-64 lowercase letters, digits, or hyphens; "+ "it cannot start or end with a hyphen or contain consecutive hyphens"+ )++ description = self.root.get("description")+ if (+ not isinstance(description, str)+ or not description.strip()+ or len(description) > 1024+ ):+ raise ValueError("description must contain 1-1024 characters")++ for field_name in ("license", "allowed-tools"):+ value = self.root.get(field_name)+ if field_name in self.root and not isinstance(value, str):+ raise ValueError(f"{field_name} must be a string")++ compatibility = self.root.get("compatibility")+ if "compatibility" in self.root and not isinstance(compatibility, str):+ raise ValueError("compatibility must be a string")+ if isinstance(compatibility, str) and not 1 <= len(compatibility) <= 500:+ raise ValueError("compatibility must contain 1-500 characters")++ metadata = self.root.get("metadata")+ if "metadata" in self.root and (+ not isinstance(metadata, dict)+ or any(not isinstance(value, str) for value in metadata.values())+ ):+ raise ValueError("metadata must map string keys to string values")++ _reject_non_finite(self.root)+ return self++ @property+ def name(self) -> str:+ return cast("str", self.root["name"])++ @property+ def description(self) -> str:+ return cast("str", self.root["description"])++ @property+ def license(self) -> str | None:+ return cast("str | None", self.root.get("license"))++ @property+ def compatibility(self) -> str | None:+ return cast("str | None", self.root.get("compatibility"))++ @property+ def metadata(self) -> dict[str, str] | None:+ return cast("dict[str, str] | None", self.root.get("metadata"))++ @property+ def allowed_tools(self) -> str | None:+ return cast("str | None", self.root.get("allowed-tools"))+++def _reject_non_finite(value: JsonValue) -> None:+ if isinstance(value, float) and not math.isfinite(value):+ raise ValueError("frontmatter numbers must be finite")+ if isinstance(value, list):+ for item in value:+ _reject_non_finite(item)+ elif isinstance(value, dict):+ for item in value.values():+ _reject_non_finite(item)+++class SkillResource(BaseModel):+ """One file in a static skill manifest."""++ model_config = ConfigDict(extra="forbid")++ uri: str+ digest: str = Field(pattern=_SHA256_PATTERN)+ size: int = Field(ge=0)++ @field_validator("size", mode="before")+ @classmethod+ def validate_size_type(cls, value: object) -> object:+ if isinstance(value, bool) or not isinstance(value, int | float):+ raise ValueError("size must be a non-negative integer")+ if isinstance(value, float) and (+ not math.isfinite(value) or not value.is_integer()+ ):+ raise ValueError("size must be a non-negative integer")+ return value+++class Skill(BaseModel):+ """A complete SEP-2640 skill entry."""++ model_config = ConfigDict(extra="forbid")++ uri: str+ frontmatter: SkillFrontmatter+ resources: list[SkillResource] | Literal["dynamic"]+ meta: dict[str, JsonValue] | None = Field(default=None, alias="_meta")++ @model_validator(mode="after")+ def validate_entry(self) -> Skill:+ scheme, authority, path_segments = _parse_resource_uri(self.uri)+ if not path_segments or path_segments[-1] != "SKILL.md":+ raise ValueError("uri must identify a SKILL.md resource")++ skill_path = path_segments[:-1]+ uri_name = skill_path[-1] if skill_path else unquote(authority)+ if not uri_name or uri_name != self.frontmatter.name:+ raise ValueError(+ "the final skill-path segment in uri must equal frontmatter.name"+ )++ if isinstance(self.resources, list):+ resource_uris = [resource.uri for resource in self.resources]+ if len(resource_uris) != len(set(resource_uris)):+ raise ValueError("resources must contain each URI exactly once")+ if self.uri not in resource_uris:+ raise ValueError("resources must include the skill's SKILL.md URI")+ for resource_uri in resource_uris:+ resource_scheme, resource_authority, resource_path = (+ _parse_resource_uri(resource_uri)+ )+ if (+ resource_scheme != scheme+ or resource_authority != authority+ or len(resource_path) <= len(skill_path)+ or resource_path[: len(skill_path)] != skill_path+ ):+ raise ValueError(+ "every resource URI must identify a file within the skill directory"+ )+ return self+++class ListSkillsParams(mcp_types.PaginatedRequestParams):+ """Parameters for `skills/list`."""+++class GetSkillParams(mcp_types.RequestParams):+ """Parameters for `skills/get`."""++ uri: str+++class ListSkillsResult(mcp_types.PaginatedResult, mcp_types.CacheableResult):+ """Result from `skills/list`."""++ skills: list[Skill]+ result_type: Literal["complete"] = "complete"+++class GetSkillResult(mcp_types.CacheableResult):+ """Result from `skills/get`."""++ skill: Skill+ result_type: Literal["complete"] = "complete"+++class ListSkillsRequest(mcp_types.Request[ListSkillsParams, Literal["skills/list"]]):+ """Client request envelope for `skills/list`."""++ method: Literal["skills/list"] = "skills/list"+ params: ListSkillsParams+++class GetSkillRequest(mcp_types.Request[GetSkillParams, Literal["skills/get"]]):+ """Client request envelope for `skills/get`."""++ method: Literal["skills/get"] = "skills/get"+ params: GetSkillParamsdiff --git a/tests/client/client/test_kv_response_cache.py b/tests/client/client/test_kv_response_cache.pyindex 108bf3e60..4a0a6df91 100644--- a/tests/client/client/test_kv_response_cache.py+++ b/tests/client/client/test_kv_response_cache.py@@ -196,12 +196,14 @@ class TestAllowlist:assert await store.get(key) is Nonedef test_allowlist_matches_cacheable_methods(self):- """The allowlist covers exactly the SDK's cacheable result models."""+ """The allowlist covers SDK and built-in extension cacheable results."""assert set(CACHEABLE_RESULT_MODELS) == {"DiscoverResult",+ "GetSkillResult","ListPromptsResult","ListResourceTemplatesResult","ListResourcesResult",+ "ListSkillsResult","ListToolsResult","ReadResourceResult",}diff --git a/tests/client/test_slim_package_boundaries.py b/tests/client/test_slim_package_boundaries.pyindex c0167f37a..a24f468e6 100644--- a/tests/client/test_slim_package_boundaries.py+++ b/tests/client/test_slim_package_boundaries.py@@ -94,6 +94,10 @@ def test_bare_slim_import_needs_only_mcp_types() -> None:import fastmcpimport fastmcp.settingsimport fastmcp.types+ from fastmcp.skills import Skill+ from fastmcp.skills.models import Skill as DirectSkill++ assert Skill is DirectSkillassert "mcp_types" in sys.modules, "mcp_types should load on a bare install"assert "mcp" not in sys.modules, "full mcp must not load on a bare install"diff --git a/tests/skills/__init__.py b/tests/skills/__init__.pynew file mode 100644index 000000000..b38b32736--- /dev/null+++ b/tests/skills/__init__.py@@ -0,0 +1 @@+"""Tests for the MCP Skills extension."""diff --git a/tests/skills/test_client_cache.py b/tests/skills/test_client_cache.pynew file mode 100644index 000000000..be9bbd3fb--- /dev/null+++ b/tests/skills/test_client_cache.py@@ -0,0 +1,69 @@+from __future__ import annotations++import time++import pytest+from mcp.client.caching import CacheEntry, CacheKey++from fastmcp.client.caching import KeyValueResponseCacheStore+from fastmcp.skills.models import GetSkillResult, ListSkillsResult, Skill++DIGEST = f"sha256:{'a' * 64}"+++def make_skill() -> Skill:+ return Skill.model_validate(+ {+ "uri": "skill://review/SKILL.md",+ "frontmatter": {+ "name": "review",+ "description": "Review a change",+ },+ "resources": [+ {+ "uri": "skill://review/SKILL.md",+ "digest": DIGEST,+ "size": 42,+ }+ ],+ }+ )+++ ("method", "params_key", "result"),+ [+ (+ "skills/list",+ "",+ ListSkillsResult(+ skills=[make_skill()], ttl_ms=60_000, cache_scope="public"+ ),+ ),+ (+ "skills/get",+ "skill://review/SKILL.md",+ GetSkillResult(skill=make_skill(), ttl_ms=60_000, cache_scope="public"),+ ),+ ],+ ids=["list", "get"],+)+async def test_persistent_cache_round_trips_skills_results(+ method: str,+ params_key: str,+ result: ListSkillsResult | GetSkillResult,+) -> None:+ store = KeyValueResponseCacheStore()+ key = CacheKey(method, params_key, "test")+ entry = CacheEntry(+ value=result,+ scope="public",+ expires_at=time.time() + 60,+ )++ await store.set(key, entry)+ cached = await store.get(key)++ assert cached is not None+ assert type(cached.value) is type(result)+ assert cached.value == resultdiff --git a/tests/skills/test_extension.py b/tests/skills/test_extension.pynew file mode 100644index 000000000..7ea19a049--- /dev/null+++ b/tests/skills/test_extension.py@@ -0,0 +1,403 @@+from __future__ import annotations++import hashlib+from collections.abc import Sequence+from typing import Any++import pytest+from mcp.server.context import ServerRequestContext+from mcp.shared.exceptions import MCPError+from mcp_types import (+ INTERNAL_ERROR,+ INVALID_PARAMS,+ METHOD_NOT_FOUND,+ TextResourceContents,+)+from pydantic import AnyUrl++from fastmcp import Client, FastMCP+from fastmcp.resources.base import Resource+from fastmcp.resources.function_resource import FunctionResource+from fastmcp.server.providers import Provider+from fastmcp.server.transforms import Namespace+from fastmcp.skills import Skill, SkillsClientExtension+from fastmcp.skills._constants import SKILLS_EXTENSION_ID+from fastmcp.skills.extension import SkillsExtension+from fastmcp.skills.models import (+ GetSkillParams,+ GetSkillRequest,+ GetSkillResult,+ ListSkillsParams,+ ListSkillsResult,+)+from fastmcp.utilities.versions import VersionSpec++SKILL_CONTENT = "# Review\n"+DIGEST = f"sha256:{hashlib.sha256(SKILL_CONTENT.encode()).hexdigest()}"+++def make_skill(name: str) -> Skill:+ uri = f"skill://{name}/SKILL.md"+ return Skill.model_validate(+ {+ "uri": uri,+ "frontmatter": {"name": name, "description": f"Use {name}"},+ "resources": [+ {"uri": uri, "digest": DIGEST, "size": len(SKILL_CONTENT.encode())}+ ],+ }+ )+++class MemorySkillProvider(Provider):+ def __init__(+ self,+ *,+ listed: Sequence[Skill],+ addressable: Sequence[Skill] | None = None,+ ) -> None:+ super().__init__()+ self.listed = list(listed)+ self.addressable = {+ skill.uri: skill+ for skill in (addressable if addressable is not None else listed)+ }+ self.contexts: list[ServerRequestContext[Any, Any]] = []++ async def _list_skill_entries(+ self, context: ServerRequestContext[Any, Any]+ ) -> Sequence[Skill]:+ self.contexts.append(context)+ return self.listed++ async def _get_skill_entry(+ self, uri: str, context: ServerRequestContext[Any, Any]+ ) -> Skill | None:+ self.contexts.append(context)+ return self.addressable.get(uri)++ async def _get_resource(+ self, uri: str, version: VersionSpec | None = None+ ) -> Resource | None:+ skill = self.addressable.get(uri)+ if skill is None:+ return None+ return FunctionResource(+ uri=AnyUrl(uri),+ name=skill.frontmatter.name,+ mime_type="text/markdown",+ fn=lambda: SKILL_CONTENT,+ )+++class CachedSkillsExtension(SkillsExtension):+ async def _handle_list(+ self,+ context: ServerRequestContext[Any, Any],+ params: ListSkillsParams,+ ) -> ListSkillsResult:+ result = await super()._handle_list(context, params)+ return result.model_copy(update={"ttl_ms": 60_000, "cache_scope": "public"})++ async def _handle_get(+ self,+ context: ServerRequestContext[Any, Any],+ params: GetSkillParams,+ ) -> GetSkillResult:+ result = await super()._handle_get(context, params)+ return result.model_copy(update={"ttl_ms": 60_000, "cache_scope": "public"})+++def make_server(+ provider: MemorySkillProvider,+ *,+ page_size: int | None = None,+ cached: bool = False,+) -> FastMCP:+ server = FastMCP("skills", providers=[provider], list_page_size=page_size)+ extension_type = CachedSkillsExtension if cached else SkillsExtension+ server.add_extension(extension_type(providers=[provider]))+ return server+++def skills_client(server: FastMCP) -> Client:+ return Client(+ server,+ mode="auto",+ extensions=[SkillsClientExtension()],+ )+++async def test_advertises_skills_and_resources_capabilities() -> None:+ server = make_server(MemorySkillProvider(listed=[]))++ async with skills_client(server) as client:+ assert client.server_capabilities is not None+ assert client.server_capabilities.resources is not None+ assert client.server_capabilities.extensions is not None+ assert client.server_capabilities.extensions[SKILLS_EXTENSION_ID] == {}+++async def test_list_skills_auto_paginates_in_uri_order() -> None:+ provider = MemorySkillProvider(+ listed=[make_skill("zeta"), make_skill("alpha"), make_skill("middle")]+ )+ server = make_server(provider, page_size=1)++ async with skills_client(server) as client:+ first = await client.list_skills_mcp()+ all_skills = await client.list_skills()++ assert [skill.frontmatter.name for skill in first.skills] == ["alpha"]+ assert first.next_cursor is not None+ assert [skill.frontmatter.name for skill in all_skills] == [+ "alpha",+ "middle",+ "zeta",+ ]+++async def test_list_skills_enforces_page_limit() -> None:+ provider = MemorySkillProvider(listed=[make_skill("alpha"), make_skill("beta")])+ server = make_server(provider, page_size=1)++ async with skills_client(server) as client:+ with pytest.raises(RuntimeError, match="Reached auto-pagination limit"):+ await client.list_skills(max_pages=1)+++async def test_get_skill_is_authoritative_for_unlisted_skill() -> None:+ hidden_from_list = make_skill("direct-only")+ provider = MemorySkillProvider(listed=[], addressable=[hidden_from_list])+ server = make_server(provider)++ async with skills_client(server) as client:+ assert await client.list_skills() == []+ skill = await client.get_skill(hidden_from_list.uri)+ contents = await client.read_resource(hidden_from_list.uri)++ assert skill == hidden_from_list+ assert len(contents) == 1+ assert isinstance(contents[0], TextResourceContents)+ assert contents[0].text == SKILL_CONTENT+ assert isinstance(skill.resources, list)+ payload = contents[0].text.encode()+ assert skill.resources[0].size == len(payload)+ assert skill.resources[0].digest == (+ f"sha256:{hashlib.sha256(payload).hexdigest()}"+ )+ assert [context.method for context in provider.contexts] == [+ "skills/list",+ "skills/get",+ ]+++async def test_skill_protocol_methods_preserve_cache_hints() -> None:+ skill = make_skill("review")+ server = make_server(MemorySkillProvider(listed=[skill]), cached=True)++ async with skills_client(server) as client:+ listed = await client.list_skills_mcp()+ fetched = await client.get_skill_mcp(skill.uri)++ assert listed.ttl_ms == fetched.ttl_ms == 60_000+ assert listed.cache_scope == fetched.cache_scope == "public"+++async def test_skill_client_cache_serves_list_and_keys_get_by_uri() -> None:+ alpha = make_skill("alpha")+ beta = make_skill("beta")+ provider = MemorySkillProvider(listed=[alpha, beta])+ server = make_server(provider, cached=True)+ client = Client(+ server,+ mode="auto",+ extensions=[SkillsClientExtension()],+ cache=True,+ )++ async with client:+ first_listing = await client.list_skills()+ cached_listing = await client.list_skills()+ first_alpha = await client.get_skill(alpha.uri)+ cached_alpha = await client.get_skill(alpha.uri)+ fetched_beta = await client.get_skill(beta.uri)++ assert first_listing == cached_listing == [alpha, beta]+ assert first_alpha == cached_alpha == alpha+ assert fetched_beta == beta++ assert [context.method for context in provider.contexts] == [+ "skills/list",+ "skills/get",+ "skills/get",+ ]+++async def test_skill_client_cache_mode_bypass_reaches_server() -> None:+ skill = make_skill("review")+ provider = MemorySkillProvider(listed=[skill])+ server = make_server(provider, cached=True)+ client = Client(+ server,+ mode="auto",+ extensions=[SkillsClientExtension()],+ cache=True,+ )++ async with client:+ await client.get_skill(skill.uri)+ await client.get_skill(skill.uri, cache_mode="bypass")++ assert [context.method for context in provider.contexts] == [+ "skills/get",+ "skills/get",+ ]+++async def test_get_unknown_skill_returns_invalid_params() -> None:+ server = make_server(MemorySkillProvider(listed=[]))++ async with skills_client(server) as client:+ with pytest.raises(MCPError) as exc_info:+ await client.get_skill("skill://missing/SKILL.md")++ assert exc_info.value.error.code == INVALID_PARAMS+++async def test_list_rejects_invalid_cursor() -> None:+ server = make_server(+ MemorySkillProvider(listed=[make_skill("review")]), page_size=1+ )++ async with skills_client(server) as client:+ with pytest.raises(MCPError) as exc_info:+ await client.list_skills_mcp(cursor="not-a-cursor")++ assert exc_info.value.error.code == INVALID_PARAMS+++async def test_server_accepts_raw_request_after_capability_discovery() -> None:+ skill = make_skill("review")+ server = make_server(MemorySkillProvider(listed=[skill]))++ async with Client(server, mode="auto") as client:+ assert client.server_capabilities is not None+ assert client.server_capabilities.extensions is not None+ assert SKILLS_EXTENSION_ID in client.server_capabilities.extensions+ request = GetSkillRequest(params=GetSkillParams(uri=skill.uri))+ result = await client.session.send_request(request, GetSkillResult)++ assert result.skill == skill+++async def test_server_rejects_skills_method_on_legacy_protocol() -> None:+ skill = make_skill("review")+ server = make_server(MemorySkillProvider(listed=[skill]))++ async with Client(server, mode="legacy") as client:+ request = GetSkillRequest(params=GetSkillParams(uri=skill.uri))+ with pytest.raises(MCPError) as exc_info:+ await client.session.send_request(request, GetSkillResult)++ assert exc_info.value.error.code == METHOD_NOT_FOUND+++async def test_client_requires_explicit_opt_in() -> None:+ server = make_server(MemorySkillProvider(listed=[]))++ async with Client(server, mode="auto") as client:+ with pytest.raises(RuntimeError, match="did not opt into"):+ await client.list_skills()+++async def test_client_requires_connection() -> None:+ client = skills_client(make_server(MemorySkillProvider(listed=[])))++ with pytest.raises(RuntimeError, match="Client is not connected"):+ await client.list_skills()+++async def test_client_rejects_server_without_extension() -> None:+ server = FastMCP("no-skills")++ async with skills_client(server) as client:+ with pytest.raises(RuntimeError, match="server does not advertise"):+ await client.list_skills()+++def test_extension_requires_provider_registered_directly() -> None:+ provider = MemorySkillProvider(listed=[])+ server = FastMCP("skills")++ with pytest.raises(ValueError, match="registered directly"):+ server.add_extension(SkillsExtension(providers=[provider]))+++def test_extension_requires_at_least_one_provider() -> None:+ with pytest.raises(ValueError, match="at least one provider"):+ SkillsExtension(providers=[])+++def test_extension_rejects_duplicate_provider_reference() -> None:+ provider = MemorySkillProvider(listed=[])++ with pytest.raises(ValueError, match="providers must be unique"):+ SkillsExtension(providers=[provider, provider])+++def test_extension_rejects_provider_without_source_contract() -> None:+ provider = Provider()+ server = FastMCP("skills", providers=[provider])++ with pytest.raises(TypeError, match="not a SkillsExtension source"):+ server.add_extension(SkillsExtension(providers=[provider]))+++def test_extension_rejects_transformed_provider() -> None:+ provider = MemorySkillProvider(listed=[])+ provider.add_transform(Namespace("docs"))+ server = FastMCP("skills", providers=[provider])++ with pytest.raises(ValueError, match="transformed providers"):+ server.add_extension(SkillsExtension(providers=[provider]))+++def test_extension_rejects_server_level_transform() -> None:+ provider = MemorySkillProvider(listed=[])+ server = FastMCP("skills", providers=[provider], transforms=[Namespace("docs")])++ with pytest.raises(ValueError, match="server-level transforms"):+ server.add_extension(SkillsExtension(providers=[provider]))+++async def test_extension_rejects_transform_added_after_registration() -> None:+ provider = MemorySkillProvider(listed=[])+ server = make_server(provider)+ provider.add_transform(Namespace("docs"))++ async with skills_client(server) as client:+ with pytest.raises(MCPError) as exc_info:+ await client.list_skills()++ assert exc_info.value.error.code == INTERNAL_ERROR+++async def test_duplicate_uris_are_omitted_from_list_and_get(+ caplog: pytest.LogCaptureFixture,+) -> None:+ duplicate = make_skill("duplicate")+ server = FastMCP("skills")+ first = MemorySkillProvider(listed=[duplicate])+ second = MemorySkillProvider(listed=[duplicate])+ server.add_provider(first)+ server.add_provider(second)+ server.add_extension(SkillsExtension(providers=[first, second]))++ async with skills_client(server) as client:+ assert await client.list_skills() == []+ with pytest.raises(MCPError) as exc_info:+ await client.get_skill(duplicate.uri)++ assert exc_info.value.error.code == INVALID_PARAMS+ assert "Omitting duplicate Skills entries" in caplog.textdiff --git a/tests/skills/test_models.py b/tests/skills/test_models.pynew file mode 100644index 000000000..900314c61--- /dev/null+++ b/tests/skills/test_models.py@@ -0,0 +1,259 @@+from __future__ import annotations++import math++import pytest+from pydantic import ValidationError++from fastmcp.skills.models import (+ GetSkillResult,+ ListSkillsResult,+ Skill,+ SkillFrontmatter,+ SkillResource,+)++DIGEST = f"sha256:{'a' * 64}"+++def make_skill(**overrides: object) -> Skill:+ values: dict[str, object] = {+ "uri": "skill://acme/review/SKILL.md",+ "frontmatter": {+ "name": "review",+ "description": "Review a change",+ "metadata": {"author": "acme"},+ "future": {"modes": ["quick", "deep"], "enabled": True},+ },+ "resources": [+ {+ "uri": "skill://acme/review/SKILL.md",+ "digest": DIGEST,+ "size": 42,+ }+ ],+ }+ values.update(overrides)+ return Skill.model_validate(values)+++def test_frontmatter_preserves_unknown_json_fields() -> None:+ skill = make_skill()++ assert skill.frontmatter.model_dump() == {+ "name": "review",+ "description": "Review a change",+ "metadata": {"author": "acme"},+ "future": {"modes": ["quick", "deep"], "enabled": True},+ }+++def test_frontmatter_preserves_allowed_tools_wire_name() -> None:+ frontmatter = SkillFrontmatter(+ {+ "name": "review",+ "description": "Review a change",+ "allowed-tools": "Read Grep",+ }+ )++ assert frontmatter.model_dump()["allowed-tools"] == "Read Grep"++[email protected]("name", ["Review", "-review", "review-", "deep--review"])+def test_frontmatter_rejects_invalid_names(name: str) -> None:+ with pytest.raises(ValidationError, match="name must be"):+ SkillFrontmatter({"name": name, "description": "Review a change"})+++def test_frontmatter_rejects_whitespace_description() -> None:+ with pytest.raises(ValidationError, match="description must contain"):+ SkillFrontmatter({"name": "review", "description": " "})+++def test_frontmatter_rejects_non_json_extra_values() -> None:+ with pytest.raises(ValidationError):+ SkillFrontmatter.model_validate(+ {"name": "review", "description": "Review a change", "future": object()}+ )+++def test_frontmatter_rejects_non_finite_extra_values() -> None:+ with pytest.raises(ValidationError):+ SkillFrontmatter(+ {"name": "review", "description": "Review a change", "future": math.inf}+ )+++ ("field", "value", "message"),+ [+ ("license", None, "license must be a string"),+ ("compatibility", None, "compatibility must be a string"),+ ("metadata", None, "metadata must map"),+ ("metadata", {"version": 1}, "metadata must map"),+ ("allowed-tools", None, "allowed-tools must be a string"),+ ],+)+def test_frontmatter_rejects_invalid_known_optional_fields(+ field: str, value: object, message: str+) -> None:+ with pytest.raises(ValidationError, match=message):+ SkillFrontmatter.model_validate(+ {"name": "review", "description": "Review a change", field: value}+ )+++def test_frontmatter_rejects_empty_compatibility() -> None:+ with pytest.raises(ValidationError, match="compatibility must contain"):+ SkillFrontmatter.model_validate(+ {+ "name": "review",+ "description": "Review a change",+ "compatibility": "",+ }+ )+++def test_frontmatter_dump_does_not_add_absent_optional_fields() -> None:+ frontmatter = SkillFrontmatter({"name": "review", "description": "Review a change"})++ assert frontmatter.model_dump() == {+ "name": "review",+ "description": "Review a change",+ }+++def test_skill_accepts_dynamic_resources() -> None:+ skill = make_skill(resources="dynamic")++ assert skill.resources == "dynamic"+++def test_skill_requires_uri_name_to_match_frontmatter() -> None:+ with pytest.raises(ValidationError, match="must equal frontmatter.name"):+ make_skill(uri="skill://acme/other/SKILL.md")+++def test_skill_accepts_non_skill_scheme_and_nested_path() -> None:+ uri = "github://acme/repository/skills/review/SKILL.md"+ skill = make_skill(+ uri=uri,+ resources=[+ {"uri": uri, "digest": DIGEST, "size": 42},+ {+ "uri": "github://acme/repository/skills/review/examples/good.md",+ "digest": DIGEST,+ "size": 8,+ },+ ],+ )++ assert skill.uri == uri+++def test_static_manifest_requires_skill_md() -> None:+ with pytest.raises(ValidationError, match="must include"):+ make_skill(+ resources=[+ {+ "uri": "skill://acme/review/reference.md",+ "digest": DIGEST,+ "size": 42,+ }+ ]+ )+++def test_static_manifest_rejects_duplicate_uris() -> None:+ resource = SkillResource(uri="skill://acme/review/SKILL.md", digest=DIGEST, size=42)+ with pytest.raises(ValidationError, match="exactly once"):+ make_skill(resources=[resource, resource])+++ "uri",+ [+ "skill://other/reference.md",+ "https://acme/review/reference.md",+ "skill://acme/outside/reference.md",+ "skill://acme/review/../outside.md",+ "skill://acme/review/%2e%2e/outside.md",+ ],+)+def test_static_manifest_rejects_resources_outside_skill(uri: str) -> None:+ with pytest.raises(+ ValidationError, match="within the skill directory|invalid segment"+ ):+ make_skill(+ resources=[+ {+ "uri": "skill://acme/review/SKILL.md",+ "digest": DIGEST,+ "size": 42,+ },+ {"uri": uri, "digest": DIGEST, "size": 8},+ ]+ )+++ "digest",+ [+ "sha256:abc",+ f"sha256:{'A' * 64}",+ f"sha512:{'a' * 64}",+ ],+)+def test_resource_requires_canonical_sha256(digest: str) -> None:+ with pytest.raises(ValidationError):+ SkillResource(uri="skill://review/SKILL.md", digest=digest, size=1)+++def test_resource_rejects_negative_size() -> None:+ with pytest.raises(ValidationError):+ SkillResource(uri="skill://review/SKILL.md", digest=DIGEST, size=-1)++[email protected]("size", [True, "1", 1.5, math.inf])+def test_resource_rejects_non_integer_size_types(size: object) -> None:+ with pytest.raises(ValidationError, match="size must be a non-negative integer"):+ SkillResource.model_validate(+ {"uri": "skill://review/SKILL.md", "digest": DIGEST, "size": size}+ )+++def test_resource_accepts_integral_json_number() -> None:+ resource = SkillResource.model_validate(+ {"uri": "skill://review/SKILL.md", "digest": DIGEST, "size": 1.0}+ )++ assert resource.size == 1+++def test_list_result_uses_protocol_wire_names() -> None:+ wire = ListSkillsResult(skills=[make_skill()]).model_dump(+ by_alias=True, mode="json", exclude_none=True+ )++ assert wire["resultType"] == "complete"+ assert wire["ttlMs"] == 0+ assert wire["cacheScope"] == "private"+++def test_get_result_uses_protocol_cache_fields() -> None:+ wire = GetSkillResult(skill=make_skill()).model_dump(+ by_alias=True, mode="json", exclude_none=True+ )++ assert wire["resultType"] == "complete"+ assert wire["ttlMs"] == 0+ assert wire["cacheScope"] == "private"+++def test_skill_preserves_protocol_metadata() -> None:+ metadata = {"io.modelcontextprotocol.skills/example": {"revision": 3}}+ skill = make_skill(_meta=metadata)+ assert skill.meta == metadata+ assert skill.model_dump(by_alias=True)["_meta"] == metadata+ assert make_skill().meta is None