diff --git a/python/packages/core/agent_framework/_skills.py b/python/packages/core/agent_framework/_skills.py index 3a9e9cc232..4725548e68 100644 --- a/python/packages/core/agent_framework/_skills.py +++ b/python/packages/core/agent_framework/_skills.py @@ -88,7 +88,12 @@ from ._feature_stage import ExperimentalFeature, experimental from ._filesystem import _is_link_or_reparse_point # pyright: ignore[reportPrivateUsage] -from ._mcp import _as_mcp_connection, _log_mcp_exception, _MCPConnection # pyright: ignore[reportPrivateUsage] +from ._mcp import ( + _DEFAULT_MCP_DISCOVERY_MAX_ITEMS, + _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 @@ -4985,7 +4990,7 @@ def _compute_skill_root_uri(skill_md_uri: str) -> str: class _ListedMCPSkill(MCPSkill): - """Retain a static Skills-extension descriptor and borrow its originating Client. + """Retain a 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 @@ -4993,6 +4998,10 @@ class _ListedMCPSkill(MCPSkill): a connection provider to a replacement connection. Its content cache and manifest belong only to this descriptor on this connection. + A static manifest restricts supporting reads to its exact URIs. A ``dynamic`` + manifest has no list, so any safe relative path within the skill directory + is read on demand. + Advertised fields other than name and description remain opaque, including allowed-tools: server metadata never grants tool permissions. """ @@ -5007,11 +5016,11 @@ def __init__( ) -> 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._dynamic_resources = resources == "dynamic" self._server_name = server_name - self._resource_uris = frozenset(resource.uri for resource in resources) + self._resource_uris: frozenset[str] | None = ( + None if self._dynamic_resources else frozenset(resource.uri for resource in resources) + ) super().__init__( frontmatter=SkillFrontmatter( name=self._advertised_skill.frontmatter["name"], @@ -5038,21 +5047,27 @@ def skill_uri(self) -> str: return self._skill_md_uri async def get_content(self) -> str: - """Fetch SKILL.md only when its exact URI is in the static manifest. + """Fetch SKILL.md, requiring exact manifest membership for static descriptors. Raises: ValueError: If the advertised SKILL.md URI is absent from the static manifest. """ - if self._skill_md_uri not in self._resource_uris: + if not self._dynamic_resources and ( + self._resource_uris is None or 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.""" + """Fetch a safe relative resource, requiring exact manifest membership for static descriptors. + + Dynamic descriptors have no manifest, so any safe relative path within the + skill directory is read on demand. + """ normalized = self._validate_resource_name(name) if normalized is None: return None - if self._skill_root_uri + normalized not in self._resource_uris: + if self._resource_uris is not None and 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) @@ -5541,9 +5556,15 @@ class MCPSkillsSource(SkillsSource): """A :class:`SkillsSource` that discovers Agent Skills served over MCP. 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. + advertises it, discovery uses ``skills/list``. Listed skills with a static + manifest read only its exact URIs. Skills with a ``dynamic`` manifest read + any safe relative path within their skill directory on demand, without + listing files in advance. Extension errors propagate without falling back + to the legacy index. + + Skills catalog discovery publishes at most 1,000 entries per fetch by + default; ``None`` disables the limit. The MCP SDK fetches every page before + the limit applies, so it bounds what is published, not network traffic. Otherwise, the source reads the deprecated SEP-2640 ``skill://index.json`` resource and constructs one :class:`Skill` per index entry. @@ -5646,6 +5667,7 @@ def __init__( *, session_provider: Callable[[], Client | ClientSession] | None = None, _result_adapter_factory: _SkillResultAdapterFactory | None = None, + max_discovery_items: int | None = _DEFAULT_MCP_DISCOVERY_MAX_ITEMS, archive_resource_extensions: tuple[str, ...] | None = None, archive_resource_search_depth: int = DEFAULT_SEARCH_DEPTH, archive_max_file_count: int = _DEFAULT_ARCHIVE_MAX_FILE_COUNT, @@ -5671,6 +5693,11 @@ def __init__( or closes it. _result_adapter_factory: Private factory for adapting successful MCP resource reads at the built-in skill tool boundary. + max_discovery_items: Maximum entries published per skills catalog + fetch. Defaults to 1,000; ``None`` disables the limit. The MCP SDK + fetches every page before the limit applies, so it bounds what + is published, not network traffic. Entries beyond the limit are + dropped with a warning. archive_resource_extensions: Allowed file extensions for resources discovered in ``archive``-type skills. When ``None`` (the default), the file-source default set (``.md``, ``.json``, ``.yaml``, ``.yml``, ``.csv``, ``.xml``, @@ -5690,9 +5717,14 @@ def __init__( Raises: ValueError: If both or neither of *client* and *session_provider* are provided. + Also raised if *max_discovery_items* is non-positive and not ``None``. """ + if max_discovery_items is not None and max_discovery_items <= 0: + raise ValueError("max_discovery_items must be positive or None.") + self._connection_provider = _resolve_mcp_connection_provider(client, session_provider) self._result_adapter_factory = _result_adapter_factory + self._max_discovery_items = max_discovery_items self._archive_loader = _ArchiveEntryLoader( self._connection_provider, resource_extensions=archive_resource_extensions, @@ -5724,7 +5756,7 @@ async def get_skills(self, context: SkillsSourceContext) -> list[Skill]: 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) + return await self._get_listed_skills(connection.client) index = await self._try_read_index() @@ -5784,10 +5816,10 @@ def _negotiated_skills_client(connection: _MCPConnection) -> SkillsClient | None return None return client.extension(Skills) - async def _get_listed_skills(self, skills_client: SkillsClient, client: Client) -> list[Skill]: + async def _get_listed_skills(self, 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() + advertised_skills = await self._list_skills_pages(client) except Exception as ex: _log_mcp_exception( logging.WARNING, @@ -5801,13 +5833,9 @@ async def _get_listed_skills(self, skills_client: SkillsClient, client: Client) 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, @@ -5832,6 +5860,24 @@ async def _get_listed_skills(self, skills_client: SkillsClient, client: Client) logger.info("Successfully listed %d skills from MCP server", len(skills)) return skills + async def _list_skills_pages(self, client: Client) -> list[MCPListedSkill]: + """Fetch the complete skills catalog through the SDK, then apply the publication cap. + + The SDK follows every page, rejects repeated cursors, and keeps the first copy of a + duplicate URI; it returns the whole catalog or raises, so no partial catalog is published. + """ + from mcp.client.extensions.skills import Skills + + skills = await client.extension(Skills).list_skills() + if self._max_discovery_items is not None and len(skills) > self._max_discovery_items: + logger.warning( + "MCP skills discovery returned %d skills; publishing the first %d (max_discovery_items).", + len(skills), + self._max_discovery_items, + ) + skills = skills[: self._max_discovery_items] + 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 99358886e6..bf3f4185fe 100644 --- a/python/packages/core/tests/core/test_mcp_skills.py +++ b/python/packages/core/tests/core/test_mcp_skills.py @@ -850,11 +850,18 @@ async def test_skill_uri_absent_from_manifest_is_never_read( "skill://unit-converter/references/checklist.md", cache_mode="use" ) - def test_dynamic_manifest_is_rejected(self, descriptor: MCPListedSkill, client: AsyncMock) -> None: + async def test_dynamic_manifest_reads_safe_relative_paths_on_demand( + 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() + skill = _ListedMCPSkill(descriptor, server_name="origin", client=client) + + assert await skill.get_resource("references/unlisted.md") is not None + client.read_resource.assert_awaited_once_with("skill://unit-converter/references/unlisted.md", cache_mode="use") + + for unsafe in ("../other/SKILL.md", "/etc/passwd", "%2e%2e/x", "https://example.com/x"): + assert await skill.get_resource(unsafe) is None + client.read_resource.assert_awaited_once() class TestMCPSkillsSource: @@ -1225,6 +1232,7 @@ def _server( *, advertise: bool = True, list_skills: Callable[..., Any] | None = None, + extra_resources: Mapping[str, str] | None = None, ) -> tuple[Any, list[str]]: from mcp.server.mcpserver import MCPServer from mcp.server.skills import Skills as ServerSkills @@ -1240,7 +1248,14 @@ 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 [] + [ + ServerSkills( + list_skills=list_skills or default_list_skills, + get_skill=get_skill, + ) + ] + if advertise + else [] ) server = MCPServer("catalog", extensions=extensions) @@ -1253,6 +1268,8 @@ def _read() -> str: register("skill://index.json", SAMPLE_SKILL_INDEX) register("skill://unit-converter/SKILL.md", SAMPLE_SKILL_MD) register(cls._CHECKLIST_URI, "Checklist") + for uri, text in (extra_resources or {}).items(): + register(uri, text) return server, reads async def test_negotiated_extension_lists_skills_without_reading_index(self) -> None: @@ -1277,6 +1294,109 @@ async def test_negotiated_extension_lists_skills_without_reading_index(self) -> assert reads == ["skill://unit-converter/SKILL.md", self._CHECKLIST_URI] + async def test_skills_catalog_is_paged_and_identical_cross_page_entries_are_deduplicated(self) -> None: + from mcp.client.extensions.skills import Skills + from mcp.shared.skills import ListSkillsResult + + calls: list[str | None] = [] + first = self._listed_skill() + second = self._listed_skill("another-skill") + + async def list_skills(_ctx: Any, params: Any) -> ListSkillsResult: + calls.append(params.cursor) + if params.cursor is None: + return ListSkillsResult(skills=[first], next_cursor="next") + return ListSkillsResult(skills=[first, second]) + + 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", "another-skill"] + assert calls == [None, "next"] + assert reads == [] + + async def test_conflicting_cross_page_skill_descriptors_keep_first_copy(self) -> None: + from mcp.client.extensions.skills import Skills + from mcp.shared.skills import ListSkillsResult + + calls = 0 + original = self._listed_skill() + conflicting = self._listed_skill() + conflicting.frontmatter["description"] = "A changed description." + + async def list_skills(_ctx: Any, _params: Any) -> ListSkillsResult: + nonlocal calls + calls += 1 + return ListSkillsResult( + skills=[original if calls == 1 else conflicting], + next_cursor="next" if calls == 1 else None, + ) + + 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 len(skills) == 1 + assert isinstance(skills[0], _ListedMCPSkill) + assert skills[0].advertised_skill == original + assert calls == 2 + assert reads == [] + + async def test_skills_catalog_item_limit_publishes_first_entries_with_warning( + self, caplog: pytest.LogCaptureFixture + ) -> None: + from mcp.client.extensions.skills import Skills + from mcp.shared.skills import ListSkillsResult + + async def list_skills(_ctx: Any, params: Any) -> ListSkillsResult: + if params.cursor is None: + return ListSkillsResult(skills=[self._listed_skill("skill-0")], next_cursor="next") + return ListSkillsResult(skills=[self._listed_skill("skill-1"), self._listed_skill("skill-2")]) + + server, reads = self._server(list_skills=list_skills) + async with Client(server, extensions=[Skills()]) as client: + with caplog.at_level("WARNING"): + skills = await MCPSkillsSource(client=client, max_discovery_items=2).get_skills(_SOURCE_CTX) + + assert [skill.frontmatter.name for skill in skills] == ["skill-0", "skill-1"] + assert "max_discovery_items" in caplog.text + assert reads == [] + + async def test_repeated_skills_cursor_fails(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()], next_cursor="") + + server, reads = self._server(list_skills=list_skills) + async with Client(server, extensions=[Skills()]) as client: + with pytest.raises(ValueError, match="repeated skills/list pagination cursor"): + await MCPSkillsSource(client=client).get_skills(_SOURCE_CTX) + + assert reads == [] + + async def test_mid_pagination_error_does_not_publish_catalog(self) -> None: + from mcp.client.extensions.skills import Skills + from mcp.shared.skills import ListSkillsResult + + calls: list[str | None] = [] + + async def list_skills(_ctx: Any, params: Any) -> ListSkillsResult: + calls.append(params.cursor) + if params.cursor is None: + return ListSkillsResult(skills=[self._listed_skill()], next_cursor="next") + raise MCPError(INVALID_PARAMS, "second page failed") + + server, reads = self._server(list_skills=list_skills) + async with Client(server, extensions=[Skills()]) as client: + with pytest.raises(MCPError, match="second page failed"): + await MCPSkillsSource(client=client).get_skills(_SOURCE_CTX) + + assert calls == [None, "next"] + assert reads == [] + @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")], @@ -1334,7 +1454,8 @@ async def failing_list_skills(_ctx: Any, _params: Any) -> ListSkillsResult: 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 + from mcp.client.extensions.skills import Skills + from mcp.shared.skills import ListSkillsResult malformed = MCPListedSkill.model_construct( uri="skill://Bad_Name/SKILL.md", @@ -1342,17 +1463,17 @@ async def test_non_conformant_listed_skill_propagates_without_partial_catalog( 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]) + page = ListSkillsResult.model_construct(skills=[self._listed_skill(), malformed], next_cursor=None) async with Client(server, extensions=[Skills()]) as client: source = MCPSkillsSource(client=client) with ( - patch.object(SkillsClient, "list_skills", list_skills), + patch.object(client.session, "send_request", AsyncMock(return_value=page)) as send_request, caplog.at_level("WARNING"), pytest.raises(ValueError, match="Bad_Name"), ): await source.get_skills(_SOURCE_CTX) - list_skills.assert_awaited_once() + send_request.assert_awaited_once() assert reads == [] assert ("Bad_Name" in caplog.text) is enable_sensitive_data if not enable_sensitive_data: @@ -1367,19 +1488,39 @@ async def test_sdk_without_skills_extension_uses_index(self) -> None: assert [type(skill) for skill in skills] == [MCPSkill] assert reads == ["skill://index.json"] - async def test_dynamic_manifest_is_skipped(self) -> None: + async def test_dynamic_manifest_reads_requested_paths_without_directory_read(self) -> None: from mcp.client.extensions.skills import Skills from mcp.shared.skills import ListSkillsResult + skill_md_uri = "skill://dynamic-skill/SKILL.md" + nested_resource_uri = "skill://dynamic-skill/references/checklist.md" + 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) + server, reads = self._server( + list_skills=list_skills, + extra_resources={skill_md_uri: SAMPLE_SKILL_MD, nested_resource_uri: "Checklist"}, + ) 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", "dynamic-skill"] + skill = skills[1] + assert isinstance(skill, _ListedMCPSkill) + assert reads == [] - assert [skill.frontmatter.name for skill in skills] == ["unit-converter"] - assert reads == [] + 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("../unit-converter/SKILL.md") is None + + assert reads == [skill_md_uri, nested_resource_uri] + + @pytest.mark.parametrize("value", [0, -1]) + def test_discovery_item_limit_must_be_positive_or_none(self, value: int) -> None: + with pytest.raises(ValueError, match="max_discovery_items must be positive or None"): + MCPSkillsSource(client=AsyncMock(), max_discovery_items=value) # ---------------------------------------------------------------------------