Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 67 additions & 21 deletions python/packages/core/agent_framework/_skills.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -4985,14 +4990,18 @@ 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
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.

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.
"""
Expand All @@ -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"],
Expand All @@ -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)
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand All @@ -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``,
Expand All @@ -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,
Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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.

Expand Down
Loading
Loading