diff --git a/python/packages/core/agent_framework/_skills.py b/python/packages/core/agent_framework/_skills.py index e2bd0f3f35..3a9e9cc232 100644 --- a/python/packages/core/agent_framework/_skills.py +++ b/python/packages/core/agent_framework/_skills.py @@ -88,7 +88,7 @@ from ._feature_stage import ExperimentalFeature, experimental from ._filesystem import _is_link_or_reparse_point # pyright: ignore[reportPrivateUsage] -from ._mcp import _as_mcp_connection, _MCPConnection # pyright: ignore[reportPrivateUsage] +from ._mcp import _as_mcp_connection, _log_mcp_exception, _MCPConnection # pyright: ignore[reportPrivateUsage] from ._middleware import FunctionInvocationContext from ._sessions import ContextProvider from ._telemetry import FeatureIndex, mark_feature_used @@ -103,6 +103,8 @@ if TYPE_CHECKING: from mcp import Client, ClientSession + from mcp.client.extensions.skills import SkillsClient + from mcp.shared.skills import Skill as MCPListedSkill from mcp.types import ReadResourceResult from ._agents import SupportsAgentRun @@ -4802,11 +4804,12 @@ def _fully_unquote(value: str, *, remaining_depth: int = _MAX_RESOURCE_NAME_DECO @experimental(feature_id=ExperimentalFeature.MCP_SKILLS) class MCPSkill(Skill): - """A :class:`Skill` discovered from an MCP server exposing the Agent Skills convention. + """A :class:`Skill` whose ``SKILL.md`` and supporting files are MCP resources. - The skill is constructed from ``skill://index.json`` discovery metadata; - :meth:`get_content` fetches the full ``SKILL.md`` content from the MCP - server on demand via ``resources/read``. + :class:`MCPSkillsSource` creates these from Skills-extension ``skills/list`` + results or, for servers without the extension, from ``skill://index.json`` + discovery metadata. :meth:`get_content` fetches the full ``SKILL.md`` content + from the MCP server on demand via ``resources/read``. Per SEP-2640, resources referenced inside SKILL.md are fetched on demand via the originating MCP server: :meth:`get_resource` resolves a relative @@ -4981,6 +4984,80 @@ def _compute_skill_root_uri(skill_md_uri: str) -> str: return skill_md_uri + "/" +class _ListedMCPSkill(MCPSkill): + """Retain a static Skills-extension descriptor and borrow its originating Client. + + Construction performs no I/O and does not discover or enable extensions. + :class:`MCPSkillsSource` supplies a descriptor returned by ``skills/list`` and + the already-entered high-level Client it was listed on. Unlike legacy MCPSkill instances, this object never follows + a connection provider to a replacement connection. Its content cache and + manifest belong only to this descriptor on this connection. + + Advertised fields other than name and description remain opaque, including + allowed-tools: server metadata never grants tool permissions. + """ + + def __init__( + self, + advertised_skill: MCPListedSkill, + *, + server_name: str | None, + client: Client, + _result_adapter_factory: _SkillResultAdapterFactory | None = None, + ) -> None: + self._advertised_skill = advertised_skill.model_copy(deep=True) + resources = self._advertised_skill.resources + if resources == "dynamic": + raise ValueError("Listed MCP skills require a static resource manifest.") + + self._server_name = server_name + self._resource_uris = frozenset(resource.uri for resource in resources) + super().__init__( + frontmatter=SkillFrontmatter( + name=self._advertised_skill.frontmatter["name"], + description=self._advertised_skill.frontmatter["description"], + ), + skill_md_uri=self._advertised_skill.uri, + client=client, + _result_adapter_factory=_result_adapter_factory, + ) + + @property + def advertised_skill(self) -> MCPListedSkill: + """Return a detached copy of the raw frontmatter, metadata, URI, and manifest.""" + return self._advertised_skill.model_copy(deep=True) + + @property + def server_name(self) -> str | None: + """Return the originating server's advertised name, or ``None`` for an anonymous server.""" + return self._server_name + + @property + def skill_uri(self) -> str: + """Return the advertised SKILL.md URI on the originating connection.""" + return self._skill_md_uri + + async def get_content(self) -> str: + """Fetch SKILL.md only when its exact URI is in the static manifest. + + Raises: + ValueError: If the advertised SKILL.md URI is absent from the static manifest. + """ + if self._skill_md_uri not in self._resource_uris: + raise ValueError(f"MCP skill URI '{self._skill_md_uri}' is not present in its static resource manifest.") + return await super().get_content() + + async def get_resource(self, name: str) -> SkillResource | None: + """Fetch a relative resource only when its exact URI is in the static manifest.""" + normalized = self._validate_resource_name(name) + if normalized is None: + return None + if self._skill_root_uri + normalized not in self._resource_uris: + logger.debug("Rejecting MCP skill resource absent from its static manifest: %r", name) + return None + return await super().get_resource(name) + + _DEFAULT_ARCHIVE_MAX_FILE_COUNT: Final[int] = 20 """Default maximum number of files that may be extracted from a single archive skill.""" @@ -5463,9 +5540,13 @@ def _build_resources(self, files: dict[str, bytes], skill_md_key: str, root_pref class MCPSkillsSource(SkillsSource): """A :class:`SkillsSource` that discovers Agent Skills served over MCP. - Discovery follows the SEP-2640 recommended approach: the source reads - the well-known ``skill://index.json`` resource and constructs one - :class:`Skill` per index entry. + When the Client registered the SDK ``Skills()`` extension and the server + advertises it, discovery uses ``skills/list``. Listed skills read only the + URIs in their static manifest; skills with a ``dynamic`` manifest are skipped. + Extension errors propagate without falling back to the legacy index. + + Otherwise, the source reads the deprecated SEP-2640 ``skill://index.json`` + resource and constructs one :class:`Skill` per index entry. Index entries are dispatched by their ``type`` (matched case-insensitively): @@ -5506,8 +5587,8 @@ class MCPSkillsSource(SkillsSource): their extension registration. MCP tools register it when created with ``extensions=[MCPSkillsExtension()]``. Caller-owned ``ClientSession`` connections remain legacy-only - (``skill://index.json``). Discovery in this source currently uses that legacy - resource for all connections; extension-based discovery is not yet implemented. + (``skill://index.json``). Listed skills stay bound to the Client they + were listed on. Archive digests: An archive entry's non-null ``digest`` must be ``sha256:`` followed by @@ -5625,9 +5706,10 @@ def __init__( async def get_skills(self, context: SkillsSourceContext) -> list[Skill]: """Discover and return skills from the MCP server. - Reads ``skill://index.json``, parses it, dispatches each entry to the - handler for its ``type`` (``skill-md`` or ``archive``), and returns the - aggregated skill list. + Uses ``skills/list`` when the Skills extension is both registered on the + Client and advertised by the server. Otherwise reads ``skill://index.json``, + parses it, dispatches each entry to the handler for its ``type`` + (``skill-md`` or ``archive``), and returns the aggregated skill list. Args: context: Contextual information about the agent and session @@ -5639,6 +5721,11 @@ async def get_skills(self, context: SkillsSourceContext) -> list[Skill]: A list of discovered :class:`Skill` instances. """ mark_feature_used(FeatureIndex.CORE_MCP_SKILLS_SOURCE) + connection = self._connection_provider() + skills_client = self._negotiated_skills_client(connection) + if skills_client is not None and connection.client is not None: + return await self._get_listed_skills(skills_client, connection.client) + index = await self._try_read_index() skill_md_entries: list[_McpSkillIndexEntry] = [] @@ -5676,6 +5763,75 @@ async def get_skills(self, context: SkillsSourceContext) -> list[Skill]: logger.info("Successfully loaded %d skills from MCP server", len(skills)) return skills + @staticmethod + def _negotiated_skills_client(connection: _MCPConnection) -> SkillsClient | None: + """Return the typed Skills API when the Client opted in and the server advertises it.""" + client = connection.client + if client is None: + return None + + try: + from mcp.client.extensions.skills import Skills + from mcp.shared.skills import EXTENSION_ID + except ImportError: + # Supported MCP SDK releases without the Skills extension can only use the legacy index. + return None + + if not any(isinstance(extension, Skills) for extension in client.extensions or ()): + return None + server_extensions = client.server_capabilities.extensions + if not isinstance(server_extensions, Mapping) or server_extensions.get(EXTENSION_ID) is None: + return None + return client.extension(Skills) + + async def _get_listed_skills(self, skills_client: SkillsClient, client: Client) -> list[Skill]: + """List skills through the negotiated extension without falling back to the legacy index.""" + try: + advertised_skills = await skills_client.list_skills() + except Exception as ex: + _log_mcp_exception( + logging.WARNING, + ex, + "skills/list failed on an MCP server that advertises the Skills extension: %s", + ex, + redacted_message="skills/list failed on an MCP server that advertises the Skills extension", + sensitive_exc_info=True, + ) + raise + + server_info = client.server_info + server_name = server_info.name if server_info is not None else None + skills: list[Skill] = [] + for advertised_skill in advertised_skills: + if advertised_skill.resources == "dynamic": + logger.warning( + "Skipping MCP skill '%s': dynamic resource manifests are not supported.", advertised_skill.uri + ) + continue + try: + skill = _ListedMCPSkill( + advertised_skill, + server_name=server_name, + client=client, + _result_adapter_factory=self._result_adapter_factory, + ) + except Exception as ex: + _log_mcp_exception( + logging.WARNING, + ex, + "skills/list returned a non-conformant skill '%s': %s", + advertised_skill.uri, + ex, + redacted_message="skills/list returned a non-conformant skill", + sensitive_exc_info=True, + ) + raise + skills.append(skill) + logger.info("Loaded MCP skill: %s", skill.frontmatter.name) + + logger.info("Successfully listed %d skills from MCP server", len(skills)) + return skills + async def _try_read_index(self) -> _McpSkillIndex | None: """Attempt to read and parse ``skill://index.json`` from the MCP server. diff --git a/python/packages/core/tests/core/test_mcp_skills.py b/python/packages/core/tests/core/test_mcp_skills.py index 5c3405c996..99358886e6 100644 --- a/python/packages/core/tests/core/test_mcp_skills.py +++ b/python/packages/core/tests/core/test_mcp_skills.py @@ -18,7 +18,9 @@ from urllib.parse import unquote import pytest -from mcp import MCPError +from mcp import Client, MCPError +from mcp.shared.skills import Skill as MCPListedSkill +from mcp.shared.skills import SkillResource as MCPListedSkillResource from mcp.types import ( INVALID_PARAMS, BlobResourceContents, @@ -38,7 +40,7 @@ SkillsSourceContext, ) from agent_framework._middleware import FunctionInvocationContext -from agent_framework._skills import InlineSkillResource, _fully_unquote, _parse_mcp_skill_index +from agent_framework._skills import InlineSkillResource, _fully_unquote, _ListedMCPSkill, _parse_mcp_skill_index from agent_framework._tools import _finalize_function_result # pyright: ignore[reportPrivateUsage] from .conftest import MockAgent @@ -652,6 +654,209 @@ def test_requires_exactly_one_of_client_or_session_provider(self) -> None: # --------------------------------------------------------------------------- +class TestListedMCPSkill: + """Exercise the runtime independently of skills/list discovery.""" + + @pytest.fixture + def descriptor(self) -> MCPListedSkill: + return MCPListedSkill( + uri="skill://unit-converter/SKILL.md", + frontmatter={ + "name": "unit-converter", + "description": "Convert between common units.", + "allowed-tools": "shell", + "metadata": {"owner": "example"}, + }, + resources=[ + MCPListedSkillResource( + uri="skill://unit-converter/SKILL.md", + digest="sha256:" + hashlib.sha256(SAMPLE_SKILL_MD.encode()).hexdigest(), + size=len(SAMPLE_SKILL_MD.encode()), + ), + MCPListedSkillResource( + uri="skill://unit-converter/references/checklist.md", + digest="sha256:" + hashlib.sha256(b"Checklist").hexdigest(), + size=len(b"Checklist"), + ), + ], + _meta={"origin": {"revision": 1}}, + ) + + @pytest.fixture + def client(self) -> AsyncMock: + return AsyncMock(spec=Client, read_resource=AsyncMock(return_value=_make_text_result(SAMPLE_SKILL_MD))) + + async def test_creation_retains_detached_advertisement_without_fetching( + self, descriptor: MCPListedSkill, client: AsyncMock + ) -> None: + skill = _ListedMCPSkill(descriptor, server_name="origin", client=client) + snapshot = skill.advertised_skill + + assert snapshot == descriptor + assert skill.server_name == "origin" + assert skill.skill_uri == descriptor.uri + assert skill.frontmatter.name == "unit-converter" + assert skill.frontmatter.description == "Convert between common units." + assert skill.frontmatter.allowed_tools is None + assert await skill.get_script("shell") is None + + descriptor.frontmatter["metadata"]["owner"] = "changed" + assert isinstance(descriptor.resources, list) + descriptor.resources.clear() + snapshot.frontmatter["metadata"]["owner"] = "also changed" + assert snapshot.meta is not None + snapshot.meta["origin"]["revision"] = 2 + retained = skill.advertised_skill + assert retained.frontmatter["metadata"] == {"owner": "example"} + assert retained.meta == {"origin": {"revision": 1}} + assert retained.resources != [] + client.read_resource.assert_not_awaited() + + async def test_content_is_lazy_and_cached_per_instance(self, descriptor: MCPListedSkill, client: AsyncMock) -> None: + first = _ListedMCPSkill(descriptor, server_name="origin", client=client) + second = _ListedMCPSkill(descriptor, server_name="origin", client=client) + client.read_resource.assert_not_awaited() + + assert await first.get_content() == SAMPLE_SKILL_MD + assert await first.get_content() == SAMPLE_SKILL_MD + client.read_resource.assert_awaited_once_with(descriptor.uri, cache_mode="use") + client.read_resource.return_value = _make_text_result("Updated content") + assert await second.get_content() == "Updated content" + assert await first.get_content() == SAMPLE_SKILL_MD + + @pytest.mark.parametrize( + ("result", "expected"), + [(_make_text_result("Checklist"), "Checklist"), (_make_blob_result(b"\x01\x02"), b"\x01\x02")], + ) + async def test_manifest_resource_is_fetched_only_on_request( + self, descriptor: MCPListedSkill, client: AsyncMock, result: ReadResourceResult, expected: str | bytes + ) -> None: + skill = _ListedMCPSkill(descriptor, server_name="origin", client=client) + client.read_resource.return_value = result + client.read_resource.assert_not_awaited() + + resource = await skill.get_resource("references\\checklist.md") + assert isinstance(resource, MCPSkillResource) + assert await resource.read() == expected + client.read_resource.assert_awaited_once_with( + "skill://unit-converter/references/checklist.md", cache_mode="use" + ) + await resource.read() + assert client.read_resource.await_count == 1 + + @pytest.mark.parametrize( + "name", + [ + "", + " ", + "references/unlisted.md", + "references/checklist.md?other=1", + "references/checklist.md#fragment", + "references/%63hecklist.md", + "../escape.md", + "references/../../escape.md", + "%252e%252e/escape.md", + "%252e%252e%255cescape.md", + "/references/checklist.md", + "skill://other/references/checklist.md", + "references/\x00checklist.md", + "references/%250achecklist.md", + _encode(33), + ], + ) + async def test_unlisted_and_unsafe_names_never_reach_server( + self, descriptor: MCPListedSkill, client: AsyncMock, name: str + ) -> None: + skill = _ListedMCPSkill(descriptor, server_name="origin", client=client) + assert await skill.get_resource(name) is None + client.read_resource.assert_not_awaited() + + async def test_manifest_mutation_does_not_authorize_another_resource( + self, descriptor: MCPListedSkill, client: AsyncMock + ) -> None: + skill = _ListedMCPSkill(descriptor, server_name="origin", client=client) + unlisted = MCPListedSkillResource( + uri="skill://unit-converter/unlisted.md", + digest="sha256:" + hashlib.sha256(b"unlisted").hexdigest(), + size=len(b"unlisted"), + ) + assert isinstance(descriptor.resources, list) + descriptor.resources.append(unlisted) + snapshot = skill.advertised_skill + assert isinstance(snapshot.resources, list) + snapshot.resources.append(unlisted) + descriptor.uri = "skill://other/SKILL.md" + snapshot.uri = "skill://other/SKILL.md" + assert await skill.get_resource("unlisted.md") is None + assert await skill.get_resource("references/checklist.md") is not None + client.read_resource.assert_awaited_once_with( + "skill://unit-converter/references/checklist.md", cache_mode="use" + ) + await skill.get_content() + client.read_resource.assert_awaited_with("skill://unit-converter/SKILL.md", cache_mode="use") + + async def test_same_uri_on_different_connections_preserves_provenance( + self, descriptor: MCPListedSkill, client: AsyncMock + ) -> None: + other_client = AsyncMock(spec=Client) + other_client.read_resource.return_value = _make_text_result("Other server") + first = _ListedMCPSkill(descriptor, server_name="first", client=client) + second = _ListedMCPSkill(descriptor, server_name="second", client=other_client) + assert await first.get_content() == SAMPLE_SKILL_MD + assert await second.get_content() == "Other server" + assert first.server_name != second.server_name + assert first.skill_uri == second.skill_uri + + client.read_resource.return_value = _make_text_result("First resource") + assert await first.get_content() == SAMPLE_SKILL_MD + first_resource = await first.get_resource("references/checklist.md") + second_resource = await second.get_resource("references/checklist.md") + assert first_resource is not None and second_resource is not None + assert await first_resource.read() == "First resource" + assert await second_resource.read() == "Other server" + + async def test_borrows_client_without_entering_or_closing( + self, descriptor: MCPListedSkill, client: AsyncMock + ) -> None: + skill = _ListedMCPSkill(descriptor, server_name="origin", client=client) + await skill.get_content() + await skill.get_resource("references/checklist.md") + client.__aenter__.assert_not_awaited() + client.__aexit__.assert_not_awaited() + + async def test_failed_content_read_is_not_cached(self, descriptor: MCPListedSkill, client: AsyncMock) -> None: + skill = _ListedMCPSkill(descriptor, server_name="origin", client=client) + client.read_resource.side_effect = RuntimeError("Connection closed") + with pytest.raises(RuntimeError, match="Connection closed"): + await skill.get_content() + client.read_resource.side_effect = None + assert await skill.get_content() == SAMPLE_SKILL_MD + + async def test_skill_uri_absent_from_manifest_is_never_read( + self, descriptor: MCPListedSkill, client: AsyncMock + ) -> None: + assert isinstance(descriptor.resources, list) + unvalidated = MCPListedSkill.model_construct( + uri=descriptor.uri, + frontmatter=descriptor.frontmatter, + resources=[resource for resource in descriptor.resources if resource.uri != descriptor.uri], + meta=None, + ) + skill = _ListedMCPSkill(unvalidated, server_name="origin", client=client) + with pytest.raises(ValueError, match="static resource manifest"): + await skill.get_content() + assert await skill.get_resource("references/checklist.md") is not None + client.read_resource.assert_awaited_once_with( + "skill://unit-converter/references/checklist.md", cache_mode="use" + ) + + def test_dynamic_manifest_is_rejected(self, descriptor: MCPListedSkill, client: AsyncMock) -> None: + descriptor.resources = "dynamic" + with pytest.raises(ValueError, match="static resource manifest"): + _ListedMCPSkill(descriptor, server_name="origin", client=client) + client.read_resource.assert_not_awaited() + + class TestMCPSkillsSource: """Tests for MCPSkillsSource.""" @@ -992,6 +1197,191 @@ def test_requires_exactly_one_of_client_or_session_provider(self) -> None: MCPSkillsSource(client=client, session_provider=lambda: client) +class TestMCPSkillsSourceExtensionDiscovery: + """Capability-based selection between skills/list and the legacy index.""" + + _CHECKLIST_URI = "skill://unit-converter/references/checklist.md" + + @staticmethod + def _listed_skill(name: str = "unit-converter", *, dynamic: bool = False) -> MCPListedSkill: + skill_md_uri = f"skill://{name}/SKILL.md" + resources: Any = "dynamic" + if not dynamic: + resources = [ + MCPListedSkillResource(uri=skill_md_uri, digest="sha256:" + "0" * 64, size=1), + MCPListedSkillResource( + uri=f"skill://{name}/references/checklist.md", digest="sha256:" + "0" * 64, size=1 + ), + ] + return MCPListedSkill( + uri=skill_md_uri, + frontmatter={"name": name, "description": f"The {name} skill."}, + resources=resources, + ) + + @classmethod + def _server( + cls, + *, + advertise: bool = True, + list_skills: Callable[..., Any] | None = None, + ) -> tuple[Any, list[str]]: + from mcp.server.mcpserver import MCPServer + from mcp.server.skills import Skills as ServerSkills + from mcp.shared.skills import GetSkillResult, ListSkillsResult + + reads: list[str] = [] + listed = cls._listed_skill() + + async def default_list_skills(_ctx: Any, _params: Any) -> ListSkillsResult: + return ListSkillsResult(skills=[listed]) + + async def get_skill(_ctx: Any, _params: Any) -> GetSkillResult: + return GetSkillResult(skill=listed) + + extensions = ( + [ServerSkills(list_skills=list_skills or default_list_skills, get_skill=get_skill)] if advertise else [] + ) + server = MCPServer("catalog", extensions=extensions) + + def register(uri: str, text: str) -> None: + @server.resource(uri) + def _read() -> str: + reads.append(uri) + return text + + register("skill://index.json", SAMPLE_SKILL_INDEX) + register("skill://unit-converter/SKILL.md", SAMPLE_SKILL_MD) + register(cls._CHECKLIST_URI, "Checklist") + return server, reads + + async def test_negotiated_extension_lists_skills_without_reading_index(self) -> None: + from mcp.client.extensions.skills import Skills + + server, reads = self._server() + async with Client(server, extensions=[Skills()]) as client: + skills = await MCPSkillsSource(client=client).get_skills(_SOURCE_CTX) + assert reads == [] + + assert len(skills) == 1 + skill = skills[0] + assert isinstance(skill, _ListedMCPSkill) + assert skill.server_name == "catalog" + assert skill.frontmatter.name == "unit-converter" + assert skill.advertised_skill == self._listed_skill() + assert await skill.get_content() == SAMPLE_SKILL_MD + resource = await skill.get_resource("references/checklist.md") + assert resource is not None + assert await resource.read() == "Checklist" + assert await skill.get_resource("references/other.md") is None + + assert reads == ["skill://unit-converter/SKILL.md", self._CHECKLIST_URI] + + @pytest.mark.parametrize( + ("client_opts_in", "server_advertises"), + [pytest.param(False, True, id="client-not-opted-in"), pytest.param(True, False, id="server-not-advertising")], + ) + async def test_falls_back_to_index_without_negotiated_extension( + self, client_opts_in: bool, server_advertises: bool + ) -> None: + from mcp.client.extensions.skills import Skills + + server, reads = self._server(advertise=server_advertises) + extensions = [Skills()] if client_opts_in else [] + async with Client(server, extensions=extensions) as client: + skills = await MCPSkillsSource(client=client).get_skills(_SOURCE_CTX) + + assert [type(skill) for skill in skills] == [MCPSkill] + assert reads == ["skill://index.json"] + + async def test_caller_owned_session_stays_legacy_only(self) -> None: + from mcp.client.extensions.skills import Skills + + server, reads = self._server() + async with Client(server, extensions=[Skills()]) as client: + skills = await MCPSkillsSource(client=client.session).get_skills(_SOURCE_CTX) + + assert [type(skill) for skill in skills] == [MCPSkill] + assert reads == ["skill://index.json"] + + @pytest.mark.parametrize("failure", ["error", "invalid"]) + @pytest.mark.parametrize("enable_sensitive_data", [True, False], indirect=True) + async def test_failed_extension_never_falls_back_to_index( + self, failure: str, span_exporter: Any, enable_sensitive_data: bool, caplog: pytest.LogCaptureFixture + ) -> None: + from mcp.client.extensions.skills import Skills + from mcp.shared.skills import ListSkillsResult + + async def failing_list_skills(_ctx: Any, _params: Any) -> ListSkillsResult: + if failure == "error": + raise MCPError(INVALID_PARAMS, "catalog unavailable") + result = ListSkillsResult(skills=[self._listed_skill()]) + result.skills[0].frontmatter["name"] = "other-name" + return result + + server, reads = self._server(list_skills=failing_list_skills) + async with Client(server, extensions=[Skills()]) as client: + with caplog.at_level("WARNING"), pytest.raises(MCPError) as exc_info: + await MCPSkillsSource(client=client).get_skills(_SOURCE_CTX) + + assert reads == [] + assert (str(exc_info.value) in caplog.text) is enable_sensitive_data + if not enable_sensitive_data: + assert "skills/list failed on an MCP server that advertises the Skills extension (MCPError)." in caplog.text + assert not any(record.exc_info for record in caplog.records) + + @pytest.mark.parametrize("enable_sensitive_data", [True, False], indirect=True) + async def test_non_conformant_listed_skill_propagates_without_partial_catalog( + self, span_exporter: Any, enable_sensitive_data: bool, caplog: pytest.LogCaptureFixture + ) -> None: + from mcp.client.extensions.skills import Skills, SkillsClient + + malformed = MCPListedSkill.model_construct( + uri="skill://Bad_Name/SKILL.md", + frontmatter={"name": "Bad_Name", "description": "Bypasses SDK validation."}, + resources=[MCPListedSkillResource(uri="skill://Bad_Name/SKILL.md", digest="sha256:" + "0" * 64, size=1)], + ) + server, reads = self._server() + list_skills = AsyncMock(return_value=[self._listed_skill(), malformed]) + async with Client(server, extensions=[Skills()]) as client: + source = MCPSkillsSource(client=client) + with ( + patch.object(SkillsClient, "list_skills", list_skills), + caplog.at_level("WARNING"), + pytest.raises(ValueError, match="Bad_Name"), + ): + await source.get_skills(_SOURCE_CTX) + + list_skills.assert_awaited_once() + assert reads == [] + assert ("Bad_Name" in caplog.text) is enable_sensitive_data + if not enable_sensitive_data: + assert "skills/list returned a non-conformant skill (ValueError)." in caplog.text + + async def test_sdk_without_skills_extension_uses_index(self) -> None: + server, reads = self._server() + async with Client(server) as client: + with patch.dict("sys.modules", {"mcp.client.extensions.skills": None}): + skills = await MCPSkillsSource(client=client).get_skills(_SOURCE_CTX) + + assert [type(skill) for skill in skills] == [MCPSkill] + assert reads == ["skill://index.json"] + + async def test_dynamic_manifest_is_skipped(self) -> None: + from mcp.client.extensions.skills import Skills + from mcp.shared.skills import ListSkillsResult + + async def list_skills(_ctx: Any, _params: Any) -> ListSkillsResult: + return ListSkillsResult(skills=[self._listed_skill(), self._listed_skill("dynamic-skill", dynamic=True)]) + + server, reads = self._server(list_skills=list_skills) + async with Client(server, extensions=[Skills()]) as client: + skills = await MCPSkillsSource(client=client).get_skills(_SOURCE_CTX) + + assert [skill.frontmatter.name for skill in skills] == ["unit-converter"] + assert reads == [] + + # --------------------------------------------------------------------------- # MCPError code branching tests # ---------------------------------------------------------------------------