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
182 changes: 169 additions & 13 deletions python/packages/core/agent_framework/_skills.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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."""

Expand Down Expand Up @@ -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):

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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] = []
Expand Down Expand Up @@ -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.

Expand Down
Loading
Loading