An MCP server (Effect's McpServer): tools, resources, resource
templates, prompts and completions served to MCP clients over stdio or
Streamable HTTP.
Register what the server offers with layers (toolkit, resource,
resource_template, prompt, skill), which need the McpServer,
or effects (register_*), and give them to a transport layer::
app = mcp_server.toolkit(NotesToolkit).pipe(layer.provide(NotesToolkit.to_layer(...)))
server = mcp_server.layer_stdio(
name="notes", version="1.0.0", protocols=(mcp_protocol.v2025_11_25,), registrations=app
)
server.pipe(layer.provide(stdio.layer)).launch()middleware and visibility run around the requests of the
registrations their layers are provided to. A handler runs with the request's
McpRequestContext and McpServerClient; elicit asks the client's
user for input and McpServerService.notify sends notifications.
Re-exports#
- From
pyfect.ai:McpServer - From
pyfect.ai.mcp_schema:CompletionContext - From
pyfect.errors:IllegalArgumentError - From
pyfect.platform_error:PlatformError
Values#
| Attribute | Type | Description |
|---|---|---|
layer | Layer[McpServer] | The |
INTERNAL_TOOL_ERROR_MESSAGE | Literal['Tool execution failed due to an internal server er…'] = 'Tool execution failed due to an internal server error.' |
Types#
| Type | Definition | Description |
|---|---|---|
MiddlewareMethod | type MiddlewareMethod = Literal['tools/call', 'resources/read', 'prompts/get', 'completion/complete', 'tools/list', 'resources/list', 'resources/templates/list', 'prompts/list', 'skills/list', 'skills/get', 'resources/directory/read'] | The requests that run MCP middleware. More may be added: a |
MiddlewareFunction | type MiddlewareFunction[P, E: McpError, R] = Callable[[Effect[MiddlewareSuccess, McpError, P], MiddlewareOptions], Effect[MiddlewareSuccess, E, R]] | A middleware: given the handler and the request, the handler run (with
the services |
VisibilityCheck | type VisibilityCheck[E: McpError, R] = Callable[[MiddlewareOptions], Effect[bool, E, R]] | Whether the request may see the registration. |
CompletionFunction | type CompletionFunction = Callable[[str, CompletionContext], Effect[Sequence[Any], Any, Any]] | Completes one argument: the values for what the user typed so far. |
ResourceContent | type ResourceContent = ReadResourceResult | str | bytes | What a resource handler gives: a result, a text or binary contents. |
SkillFileInput | type SkillFileInput = str | Buffer | SkillFile | A file of a skill: its text, its bytes, or either with a MIME type. |
Classes#
Functions#
make#
make() -> Effect[McpServerService]A server with nothing registered (Effect's McpServer.make).
Returns Effect[McpServerService]
def make() -> Effect[McpServerService]:
"""A server with nothing registered (Effect's ``McpServer.make``)."""
return succeed(None).map(lambda _: McpServerService())run_stdio#
run_stdio(*, name, version, protocols, title=None, description=None, website_url=None, icons=(), instructions=None, extensions=None, cache_hints=None) -> Effect[None, IllegalArgumentError | PlatformError, McpServer | Stdio]Serve the client on standard input and output and return once its
input ends and its requests are answered, so run_main exits 0.
protocols are the revisions spoken, the first the one offered to a
client asking for another.
| Parameter | Type | Description |
|---|---|---|
name | str | |
version | str | |
protocols | Sequence[AnyProtocolAdapter] | |
title | str | None = None | |
description | str | None = None | |
website_url | str | None = None | |
icons | Sequence[Icon] = () | |
instructions | str | None = None | |
extensions | Mapping[str, Any] | None = None | |
cache_hints | CacheHints | None = None |
Returns Effect[None, IllegalArgumentError | PlatformError, McpServer | Stdio]
def run_stdio(
*,
name: str,
version: str,
protocols: Sequence[AnyProtocolAdapter],
title: str | None = None,
description: str | None = None,
website_url: str | None = None,
icons: Sequence[Icon] = (),
instructions: str | None = None,
extensions: Mapping[str, Any] | None = None,
cache_hints: CacheHints | None = None,
) -> Effect[None, IllegalArgumentError | PlatformError, McpServer | Stdio]:
"""Serve the client on standard input and output and return once its
input ends and its requests are answered, so ``run_main`` exits 0.
``protocols`` are the revisions spoken, the first the one offered to a
client asking for another."""
info = _info(
name,
version,
title=title,
description=description,
website_url=website_url,
icons=icons,
instructions=instructions,
extensions=extensions,
cache_hints=cache_hints,
)
return info.flat_map(
lambda served: make_registry(protocols).flat_map(
lambda registry: _stdio.serve(served, registry)
)
)layer_stdio#
layer_stdio[RE = Never, RR = Never](*, name, version, protocols, title=None, description=None, website_url=None, icons=(), instructions=None, extensions=None, cache_hints=None, registrations=None) -> Layer[McpServer, IllegalArgumentError | RE, Stdio | RR]run_stdio in the background of a layer providing the
McpServer. As in Effect, the fiber that built the layer is interrupted
when the server ends: .launch() ends at the end of input, and
run_main exits 130. registrations are built before the server
starts.
| Parameter | Type | Description |
|---|---|---|
name | str | |
version | str | |
protocols | Sequence[AnyProtocolAdapter] | |
title | str | None = None | |
description | str | None = None | |
website_url | str | None = None | |
icons | Sequence[Icon] = () | |
instructions | str | None = None | |
extensions | Mapping[str, Any] | None = None | |
cache_hints | CacheHints | None = None | |
registrations | Layer[Any, RE, RR | McpServer | McpServerClient] | None = None |
Returns Layer[McpServer, IllegalArgumentError | RE, Stdio | RR]
def layer_stdio[RE = Never, RR = Never](
*,
name: str,
version: str,
protocols: Sequence[AnyProtocolAdapter],
title: str | None = None,
description: str | None = None,
website_url: str | None = None,
icons: Sequence[Icon] = (),
instructions: str | None = None,
extensions: Mapping[str, Any] | None = None,
cache_hints: CacheHints | None = None,
registrations: Layer[Any, RE, RR | McpServer | McpServerClient] | None = None,
) -> Layer[McpServer, IllegalArgumentError | RE, Stdio | RR]:
"""``run_stdio`` in the background of a layer providing the
``McpServer``. As in Effect, the fiber that built the layer is interrupted
when the server ends: ``.launch()`` ends at the end of input, and
``run_main`` exits 130. ``registrations`` are built before the server
starts."""
_require_registrations(registrations)
running = run_stdio(
name=name,
version=version,
protocols=protocols,
title=title,
description=description,
website_url=website_url,
icons=icons,
instructions=instructions,
extensions=extensions,
cache_hints=cache_hints,
)
@gen
def started():
yield from make_registry(protocols)
yield from _cache_hints.parse(cache_hints)
builder = yield from current_fiber()
ended = builder.interrupt().fork_daemon(start_immediately=True).as_void()
yield from running.ignore().ensuring(ended).fork_scoped()
return _serving(started, registrations)run#
run(*, name, version, protocols, title=None, description=None, website_url=None, icons=(), instructions=None, extensions=None, cache_hints=None) -> Effect[Never, IllegalArgumentError, McpServer | ServerProtocol]Serve every client of the RPC ServerProtocol in the context (a
custom transport; Effect's McpServer.run), each a session keyed by
the protocol's client id. A protocol without supports_notifications
serves no subscriptions: 2026-07-28 discovery advertises no list changes,
subscriptions/listen is method not found, and no notifications are
sent.
| Parameter | Type | Description |
|---|---|---|
name | str | |
version | str | |
protocols | Sequence[AnyProtocolAdapter] | |
title | str | None = None | |
description | str | None = None | |
website_url | str | None = None | |
icons | Sequence[Icon] = () | |
instructions | str | None = None | |
extensions | Mapping[str, Any] | None = None | |
cache_hints | CacheHints | None = None |
Returns Effect[Never, IllegalArgumentError, McpServer | ServerProtocol]
def run(
*,
name: str,
version: str,
protocols: Sequence[AnyProtocolAdapter],
title: str | None = None,
description: str | None = None,
website_url: str | None = None,
icons: Sequence[Icon] = (),
instructions: str | None = None,
extensions: Mapping[str, Any] | None = None,
cache_hints: CacheHints | None = None,
) -> Effect[Never, IllegalArgumentError, McpServer | ServerProtocol]:
"""Serve every client of the RPC ``ServerProtocol`` in the context (a
custom transport; Effect's ``McpServer.run``), each a session keyed by
the protocol's client id. A protocol without ``supports_notifications``
serves no subscriptions: 2026-07-28 discovery advertises no list changes,
``subscriptions/listen`` is method not found, and no notifications are
sent."""
info = _info(
name,
version,
title=title,
description=description,
website_url=website_url,
icons=icons,
instructions=instructions,
extensions=extensions,
cache_hints=cache_hints,
)
return info.flat_map(
lambda served: make_registry(protocols).flat_map(
lambda registry: _rpc_protocol.serve(served, registry)
)
)layer_rpc_protocol#
layer_rpc_protocol[RE = Never, RR = Never](*, name, version, protocols, title=None, description=None, website_url=None, icons=(), instructions=None, extensions=None, cache_hints=None, registrations=None) -> Layer[McpServer, IllegalArgumentError | RE, ServerProtocol | RR]run in the background of a layer providing the McpServer
(Effect's McpServer.layer): the server over the RPC
ServerProtocol the layer is given. registrations are built
before the server reads its first message.
| Parameter | Type | Description |
|---|---|---|
name | str | |
version | str | |
protocols | Sequence[AnyProtocolAdapter] | |
title | str | None = None | |
description | str | None = None | |
website_url | str | None = None | |
icons | Sequence[Icon] = () | |
instructions | str | None = None | |
extensions | Mapping[str, Any] | None = None | |
cache_hints | CacheHints | None = None | |
registrations | Layer[Any, RE, RR | McpServer | McpServerClient] | None = None |
Returns Layer[McpServer, IllegalArgumentError | RE, ServerProtocol | RR]
def layer_rpc_protocol[RE = Never, RR = Never](
*,
name: str,
version: str,
protocols: Sequence[AnyProtocolAdapter],
title: str | None = None,
description: str | None = None,
website_url: str | None = None,
icons: Sequence[Icon] = (),
instructions: str | None = None,
extensions: Mapping[str, Any] | None = None,
cache_hints: CacheHints | None = None,
registrations: Layer[Any, RE, RR | McpServer | McpServerClient] | None = None,
) -> Layer[McpServer, IllegalArgumentError | RE, ServerProtocol | RR]:
"""``run`` in the background of a layer providing the ``McpServer``
(Effect's ``McpServer.layer``): the server over the RPC
``ServerProtocol`` the layer is given. ``registrations`` are built
before the server reads its first message."""
_require_registrations(registrations)
running = run(
name=name,
version=version,
protocols=protocols,
title=title,
description=description,
website_url=website_url,
icons=icons,
instructions=instructions,
extensions=extensions,
cache_hints=cache_hints,
)
@gen
def started():
yield from make_registry(protocols)
yield from _cache_hints.parse(cache_hints)
yield from running.fork_scoped()
return _serving(started, registrations)layer_http#
layer_http[RE = Never, RR = Never](*, name, version, path, protocols, title=None, description=None, website_url=None, icons=(), instructions=None, extensions=None, allowed_origins=None, allow_session_termination=False, allow_subscriptions=True, max_sessions=_sessions.DEFAULT_MAX_SESSIONS, session_idle_timeout=_sessions.DEFAULT_IDLE_TIMEOUT, max_message_bytes=_sessions.DEFAULT_MAX_MESSAGE_BYTES, max_initialize_bytes=_sessions.DEFAULT_MAX_INITIALIZE_BYTES, cache_hints=None, registrations=None) -> Layer[McpServer, IllegalArgumentError | RE, HttpRouter | RR]Serve MCP's Streamable HTTP transport at path of the router.
A request with an Origin header not in allowed_origins is
refused (403); one without an Origin is served. With
allow_session_termination a client ends its session with DELETE.
At most max_sessions sessions are open (an initialize past
that gets 503); a session idle for session_idle_timeout ends;
a message larger than max_message_bytes, or an initialize
larger than max_initialize_bytes (64 KiB), gets 413. With
allow_subscriptions=False, 2026-07-28 discovery advertises no list
changes and subscriptions/listen is method not found; earlier
revisions are unchanged. registrations are built before the routes.
| Parameter | Type | Description |
|---|---|---|
name | str | |
version | str | |
path | str | |
protocols | Sequence[AnyProtocolAdapter] | |
title | str | None = None | |
description | str | None = None | |
website_url | str | None = None | |
icons | Sequence[Icon] = () | |
instructions | str | None = None | |
extensions | Mapping[str, Any] | None = None | |
allowed_origins | Sequence[str] | None = None | |
allow_session_termination | bool = False | |
allow_subscriptions | bool = True | |
max_sessions | int = _sessions.DEFAULT_MAX_SESSIONS | |
session_idle_timeout | DurationInput = _sessions.DEFAULT_IDLE_TIMEOUT | |
max_message_bytes | byte_size.Input = _sessions.DEFAULT_MAX_MESSAGE_BYTES | |
max_initialize_bytes | byte_size.Input = _sessions.DEFAULT_MAX_INITIALIZE_BYTES | |
cache_hints | CacheHints | None = None | |
registrations | Layer[Any, RE, RR | McpServer | McpServerClient] | None = None |
Returns Layer[McpServer, IllegalArgumentError | RE, HttpRouter | RR]
def layer_http[RE = Never, RR = Never](
*,
name: str,
version: str,
path: str,
protocols: Sequence[AnyProtocolAdapter],
title: str | None = None,
description: str | None = None,
website_url: str | None = None,
icons: Sequence[Icon] = (),
instructions: str | None = None,
extensions: Mapping[str, Any] | None = None,
allowed_origins: Sequence[str] | None = None,
allow_session_termination: bool = False,
allow_subscriptions: bool = True,
max_sessions: int = _sessions.DEFAULT_MAX_SESSIONS,
session_idle_timeout: DurationInput = _sessions.DEFAULT_IDLE_TIMEOUT,
max_message_bytes: byte_size.Input = _sessions.DEFAULT_MAX_MESSAGE_BYTES,
max_initialize_bytes: byte_size.Input = _sessions.DEFAULT_MAX_INITIALIZE_BYTES,
cache_hints: CacheHints | None = None,
registrations: Layer[Any, RE, RR | McpServer | McpServerClient] | None = None,
) -> Layer[McpServer, IllegalArgumentError | RE, HttpRouter | RR]:
"""Serve MCP's Streamable HTTP transport at ``path`` of the router.
A request with an ``Origin`` header not in ``allowed_origins`` is
refused (403); one without an ``Origin`` is served. With
``allow_session_termination`` a client ends its session with DELETE.
At most ``max_sessions`` sessions are open (an ``initialize`` past
that gets 503); a session idle for ``session_idle_timeout`` ends;
a message larger than ``max_message_bytes``, or an ``initialize``
larger than ``max_initialize_bytes`` (64 KiB), gets 413. With
``allow_subscriptions=False``, 2026-07-28 discovery advertises no list
changes and ``subscriptions/listen`` is method not found; earlier
revisions are unchanged. ``registrations`` are built before the routes."""
_require_registrations(registrations)
info = _info(
name,
version,
title=title,
description=description,
website_url=website_url,
icons=icons,
instructions=instructions,
extensions=extensions,
cache_hints=cache_hints,
)
@gen
def routes():
parsed = yield from _sessions.limits(
max_sessions, session_idle_timeout, max_message_bytes, max_initialize_bytes
)
registry = yield from make_registry(protocols)
yield from _http.serve(
(yield from info),
registry,
path=path,
allowed_origins=allowed_origins,
allow_session_termination=allow_session_termination,
limits=parsed,
allow_subscriptions=allow_subscriptions,
)
return _serving(routes, registrations)layer_http_request_scoped#
layer_http_request_scoped[RE = Never, RR = Never](*, name, version, path, protocols, title=None, description=None, website_url=None, icons=(), instructions=None, extensions=None, allowed_origins=None, max_message_bytes=_sessions.DEFAULT_MAX_MESSAGE_BYTES, cache_hints=None, registrations=None) -> Layer[McpServer, IllegalArgumentError | RE, HttpRouter | RR]Serve sessionless MCP at path with each POST's execution belonging
to that request: nothing keeps running after its response, and handlers see
the request's services over the layer's. Sessionful revisions are refused
(IllegalArgumentError, for an untyped caller).
Tools, resources, prompts, completions, InputRequired round trips and
a request's own progress and logs work as in layer_http. There are no
subscriptions (discovery advertises no list changes, subscriptions/listen
is method not found) or broadcast notifications, and DELETE gets 405.
| Parameter | Type | Description |
|---|---|---|
name | str | |
version | str | |
path | str | |
protocols | Sequence[ProtocolAdapter[Literal['2026-07-28']]] | |
title | str | None = None | |
description | str | None = None | |
website_url | str | None = None | |
icons | Sequence[Icon] = () | |
instructions | str | None = None | |
extensions | Mapping[str, Any] | None = None | |
allowed_origins | Sequence[str] | None = None | |
max_message_bytes | byte_size.Input = _sessions.DEFAULT_MAX_MESSAGE_BYTES | |
cache_hints | CacheHints | None = None | |
registrations | Layer[Any, RE, RR | McpServer | McpServerClient] | None = None |
Returns Layer[McpServer, IllegalArgumentError | RE, HttpRouter | RR]
def layer_http_request_scoped[RE = Never, RR = Never](
*,
name: str,
version: str,
path: str,
protocols: Sequence[ProtocolAdapter[Literal["2026-07-28"]]],
title: str | None = None,
description: str | None = None,
website_url: str | None = None,
icons: Sequence[Icon] = (),
instructions: str | None = None,
extensions: Mapping[str, Any] | None = None,
allowed_origins: Sequence[str] | None = None,
max_message_bytes: byte_size.Input = _sessions.DEFAULT_MAX_MESSAGE_BYTES,
cache_hints: CacheHints | None = None,
registrations: Layer[Any, RE, RR | McpServer | McpServerClient] | None = None,
) -> Layer[McpServer, IllegalArgumentError | RE, HttpRouter | RR]:
"""Serve sessionless MCP at ``path`` with each POST's execution belonging
to that request: nothing keeps running after its response, and handlers see
the request's services over the layer's. Sessionful revisions are refused
(``IllegalArgumentError``, for an untyped caller).
Tools, resources, prompts, completions, ``InputRequired`` round trips and
a request's own progress and logs work as in ``layer_http``. There are no
subscriptions (discovery advertises no list changes, ``subscriptions/listen``
is method not found) or broadcast notifications, and DELETE gets 405."""
_require_registrations(registrations)
info = _info(
name,
version,
title=title,
description=description,
website_url=website_url,
icons=icons,
instructions=instructions,
extensions=extensions,
cache_hints=cache_hints,
)
sessionful: tuple[AnyProtocolAdapter, ...] = tuple(p for p in protocols if not p.is_stateless)
if sessionful:
version_name = sessionful[0].protocol_version
refused = IllegalArgumentError(
"McpServer.layer_http_request_scoped does not support the sessionful "
f"MCP protocol {version_name}"
)
return _serving(fail(refused), registrations)
@gen
def routes():
parsed = yield from _sessions.limits(
_sessions.DEFAULT_MAX_SESSIONS, _sessions.DEFAULT_IDLE_TIMEOUT, max_message_bytes
)
registry = yield from make_registry(protocols)
yield from _http.serve(
(yield from info),
registry,
path=path,
allowed_origins=allowed_origins,
allow_session_termination=False,
limits=parsed,
allow_subscriptions=False,
request_services=True,
)
return _serving(routes, registrations)toolkit#
toolkit[N: LiteralString, RP, HE, R](toolkit) -> Layer[Never, Never, McpServer | Handlers[N] | R]A layer registering toolkit (see register_toolkit). It needs
the McpServer: pass it to a transport as registrations, or
provide the transport to it.
| Parameter | Type | Description |
|---|---|---|
toolkit | Toolkit[N, RP, HE, R] |
Returns Layer[Never, Never, McpServer | Handlers[N] | R]
def toolkit[N: LiteralString, RP, HE, R](
toolkit: Toolkit[N, RP, HE, R],
) -> Layer[Never, Never, McpServer | Handlers[N] | R]:
"""A layer registering ``toolkit`` (see ``register_toolkit``). It needs
the ``McpServer``: pass it to a transport as ``registrations``, or
provide the transport to it."""
return effect_discard(register_toolkit(toolkit))resource#
resource[E = Never, R = Never](*, uri, name, content, title=None, description=None, mime_type=None, audience=None, priority=None, annotations=None) -> Layer[Never, Never, McpServer | R]A layer registering a resource (see register_resource).
| Parameter | Type | Description |
|---|---|---|
uri | str | |
name | str | |
content | Effect[ResourceContent, E, R] | |
title | str | None = None | |
description | str | None = None | |
mime_type | str | None = None | |
audience | Sequence[Role] | None = None | |
priority | float | None = None | |
annotations | Context[Never] | None = None |
Returns Layer[Never, Never, McpServer | R]
def resource[E = Never, R = Never](
*,
uri: str,
name: str,
content: Effect[ResourceContent, E, R],
title: str | None = None,
description: str | None = None,
mime_type: str | None = None,
audience: Sequence[Role] | None = None,
priority: float | None = None,
annotations: Context[Never] | None = None,
) -> Layer[Never, Never, McpServer | R]:
"""A layer registering a resource (see ``register_resource``)."""
registered = register_resource(
uri=uri,
name=name,
content=content,
title=title,
description=description,
mime_type=mime_type,
audience=audience,
priority=priority,
annotations=annotations,
)
return effect_discard(registered)resource_template#
resource_template[*Ts, E = Never, R = Never](template, *, name, content, completion=None, title=None, description=None, mime_type=None, audience=None, priority=None, annotations=None) -> Layer[Never, Never, McpServer | R]A layer registering a resource template (see
register_resource_template).
| Parameter | Type | Description |
|---|---|---|
template | UriTemplate[*Ts,] | |
name | str | |
content | Callable[[str, *Ts], Effect[ResourceContent, E, R]] | |
completion | Mapping[str, CompletionFunction] | None = None | |
title | str | None = None | |
description | str | None = None | |
mime_type | str | None = None | |
audience | Sequence[Role] | None = None | |
priority | float | None = None | |
annotations | Context[Never] | None = None |
Returns Layer[Never, Never, McpServer | R]
def resource_template[*Ts, E = Never, R = Never](
template: UriTemplate[*Ts],
*,
name: str,
content: Callable[[str, *Ts], Effect[ResourceContent, E, R]],
completion: Mapping[str, CompletionFunction] | None = None,
title: str | None = None,
description: str | None = None,
mime_type: str | None = None,
audience: Sequence[Role] | None = None,
priority: float | None = None,
annotations: Context[Never] | None = None,
) -> Layer[Never, Never, McpServer | R]:
"""A layer registering a resource template (see
``register_resource_template``)."""
registered = register_resource_template(
template,
name=name,
content=content,
completion=completion,
title=title,
description=description,
mime_type=mime_type,
audience=audience,
priority=priority,
annotations=annotations,
)
return effect_discard(registered)prompt#
prompt[P = Mapping[str, Never], E = Never, R = Never](*, name, content, parameters=None, completion=None, title=None, description=None, annotations=None) -> Layer[Never, Never, McpServer | R]A layer registering a prompt (see register_prompt).
| Parameter | Type | Description |
|---|---|---|
name | str | |
content | Callable[[P], Effect[Sequence[PromptMessage] | str, E, R]] | |
parameters | Codec[P, Any, Any, Any] | None = None | |
completion | Mapping[str, CompletionFunction] | None = None | |
title | str | None = None | |
description | str | None = None | |
annotations | Context[Never] | None = None |
Returns Layer[Never, Never, McpServer | R]
def prompt[P = Mapping[str, Never], E = Never, R = Never](
*,
name: str,
content: Callable[[P], Effect[Sequence[PromptMessage] | str, E, R]],
parameters: Codec[P, Any, Any, Any] | None = None,
completion: Mapping[str, CompletionFunction] | None = None,
title: str | None = None,
description: str | None = None,
annotations: Context[Never] | None = None,
) -> Layer[Never, Never, McpServer | R]:
"""A layer registering a prompt (see ``register_prompt``)."""
registered = register_prompt(
name=name,
content=content,
parameters=parameters,
completion=completion,
title=title,
description=description,
annotations=annotations,
)
return effect_discard(registered)skill#
skill(uri, files, *, annotations=None) -> Layer[Never, IllegalArgumentError, McpServer]A layer registering an Agent Skill (see register_skill)::
refunds = mcp_server.skill(
"skill://billing/refunds/SKILL.md",
{
"SKILL.md": "---name: refunds description: Process refunds#
", "references/policy.md": "Refunds above CHF 500 need approval. ", }, )
| Parameter | Type | Description |
|---|---|---|
uri | str | |
files | Mapping[str, SkillFileInput] | |
annotations | Context[Never] | None = None |
Returns Layer[Never, IllegalArgumentError, McpServer]
def skill(
uri: str,
files: Mapping[str, SkillFileInput],
*,
annotations: Context[Never] | None = None,
) -> Layer[Never, IllegalArgumentError, McpServer]:
"""A layer registering an Agent Skill (see ``register_skill``)::
refunds = mcp_server.skill(
"skill://billing/refunds/SKILL.md",
{
"SKILL.md": "---\nname: refunds\ndescription: Process refunds\n---\n",
"references/policy.md": "Refunds above CHF 500 need approval.\n",
},
)
"""
return effect_discard(register_skill(uri, files, annotations=annotations))decode_name_header#
decode_name_header(value) -> str | NoneAn Mcp-Name header's name, base64-wrapped or not; None when
malformed. For HttpRouter middleware identifying the tool, prompt or
resource a 2026-07-28 request targets (earlier revisions name it only in
the JSON-RPC body).
| Parameter | Type | Description |
|---|---|---|
value | str |
Returns str | None
def decode_name_header(value: str) -> str | None:
"""An ``Mcp-Name`` header's name, base64-wrapped or not; ``None`` when
malformed. For ``HttpRouter`` middleware identifying the tool, prompt or
resource a 2026-07-28 request targets (earlier revisions name it only in
the JSON-RPC body)."""
return decode_routing_header(value)middleware#
middleware[E: McpError = Never, R = Never](fn: MiddlewareFunction[Never, E, R], /, *, global_: Literal[False] = False) -> Middleware[Never, R]
middleware[P, E: McpError = Never, R = Never](fn: MiddlewareFunction[P, E, R], /, *, provides: TagLike[Any, P] | tuple[TagLike[Any, P], ...], global_: Literal[False] = False) -> Middleware[P, R]
middleware[LE, E: McpError = Never, R = Never](fn: Effect[MiddlewareFunction[Never, E, R], LE, R], /, *, global_: Literal[False] = False) -> Middleware[Never, R, LE]
middleware[P, LE, E: McpError = Never, R = Never](fn: Effect[MiddlewareFunction[P, E, R], LE, R], /, *, provides: TagLike[Any, P] | tuple[TagLike[Any, P], ...], global_: Literal[False] = False) -> Middleware[P, R, LE]
middleware[P = Never, E: McpError = Never, R = Never](fn: MiddlewareFunction[P, E, R], /, *, provides: TagLike[Any, P] | tuple[TagLike[Any, P], ...] = (), global_: Literal[True]) -> Layer[P, Never, R | McpServer]
middleware[LE, P = Never, E: McpError = Never, R = Never](fn: Effect[MiddlewareFunction[P, E, R], LE, R], /, *, provides: TagLike[Any, P] | tuple[TagLike[Any, P], ...] = (), global_: Literal[True]) -> Layer[P, LE, R | McpServer]MCP middleware from a function (or an effect making one) run around
tools/call, resources/read, prompts/get and
completion/complete, and around list requests only when it wraps a
visibility. provides names the services it provides the handler
(the tags; only their types matter)::
auth = mcp_server.middleware(
lambda effect, options: effect.pipe(
fx.provide_service(CurrentUser, options.headers.get("authorization", ""))
),
provides=CurrentUser,
)A failure is an McpError, sent as a JSON-RPC error with its code,
message and data; a defect is logged, reported and sent as
Internal error; interruption propagates. Local middleware runs
inside global middleware. global_=True gives layer_global.
| Parameter | Type | Description |
|---|---|---|
fn | ||
provides | = () | |
global_ | = False |
@overload
def middleware[E: McpError = Never, R = Never](
fn: MiddlewareFunction[Never, E, R], /, *, global_: Literal[False] = False
) -> Middleware[Never, R]: ...
@overload
def middleware[P, E: McpError = Never, R = Never](
fn: MiddlewareFunction[P, E, R],
/,
*,
provides: TagLike[Any, P] | tuple[TagLike[Any, P], ...],
global_: Literal[False] = False,
) -> Middleware[P, R]: ...
@overload
def middleware[LE, E: McpError = Never, R = Never](
fn: Effect[MiddlewareFunction[Never, E, R], LE, R],
/,
*,
global_: Literal[False] = False,
) -> Middleware[Never, R, LE]: ...
@overload
def middleware[P, LE, E: McpError = Never, R = Never](
fn: Effect[MiddlewareFunction[P, E, R], LE, R],
/,
*,
provides: TagLike[Any, P] | tuple[TagLike[Any, P], ...],
global_: Literal[False] = False,
) -> Middleware[P, R, LE]: ...
@overload
def middleware[P = Never, E: McpError = Never, R = Never](
fn: MiddlewareFunction[P, E, R],
/,
*,
provides: TagLike[Any, P] | tuple[TagLike[Any, P], ...] = (),
global_: Literal[True],
) -> Layer[P, Never, R | McpServer]: ...
@overload
def middleware[LE, P = Never, E: McpError = Never, R = Never](
fn: Effect[MiddlewareFunction[P, E, R], LE, R],
/,
*,
provides: TagLike[Any, P] | tuple[TagLike[Any, P], ...] = (),
global_: Literal[True],
) -> Layer[P, LE, R | McpServer]: ...
def middleware(fn: object, /, *, provides: object = (), global_: bool = False) -> Any:
"""MCP middleware from a function (or an effect making one) run around
``tools/call``, ``resources/read``, ``prompts/get`` and
``completion/complete``, and around list requests only when it wraps a
``visibility``. ``provides`` names the services it provides the handler
(the tags; only their types matter)::
auth = mcp_server.middleware(
lambda effect, options: effect.pipe(
fx.provide_service(CurrentUser, options.headers.get("authorization", ""))
),
provides=CurrentUser,
)
A failure is an ``McpError``, sent as a JSON-RPC error with its code,
message and data; a defect is logged, reported and sent as
``Internal error``; interruption propagates. Local middleware runs
inside global middleware. ``global_=True`` gives ``layer_global``."""
del provides
made = Middleware[Any, Any, Any](_fn_layer(fn))
return made.layer_global if global_ else madevisibility#
visibility[E: McpError = Never, R = Never](check: VisibilityCheck[E, R], /, *, global_: Literal[False] = False) -> Middleware[Never, R]
visibility[LE, E: McpError = Never, R = Never](check: Effect[VisibilityCheck[E, R], LE, R], /, *, global_: Literal[False] = False) -> Middleware[Never, R, LE]
visibility[E: McpError = Never, R = Never](check: VisibilityCheck[E, R], /, *, global_: Literal[True]) -> Layer[Never, Never, R | McpServer]
visibility[LE, E: McpError = Never, R = Never](check: Effect[VisibilityCheck[E, R], LE, R], /, *, global_: Literal[True]) -> Layer[Never, LE, R | McpServer]Middleware hiding registrations per request: where check gives
False, the registration is left out of lists and a request for it
fails as if it were not registered. It runs on list requests and on
calls, reads, gets and completions, with the middleware outside it (once
per registration on a list; the middleware inside does not run there). A
failure of that middleware or of check fails the whole list.
Unlike EnabledWhen, middleware sees requests for hidden registrations
(as an McpError).
| Parameter | Type | Description |
|---|---|---|
check | ||
global_ | = False |
@overload
def visibility[E: McpError = Never, R = Never](
check: VisibilityCheck[E, R], /, *, global_: Literal[False] = False
) -> Middleware[Never, R]: ...
@overload
def visibility[LE, E: McpError = Never, R = Never](
check: Effect[VisibilityCheck[E, R], LE, R], /, *, global_: Literal[False] = False
) -> Middleware[Never, R, LE]: ...
@overload
def visibility[E: McpError = Never, R = Never](
check: VisibilityCheck[E, R], /, *, global_: Literal[True]
) -> Layer[Never, Never, R | McpServer]: ...
@overload
def visibility[LE, E: McpError = Never, R = Never](
check: Effect[VisibilityCheck[E, R], LE, R], /, *, global_: Literal[True]
) -> Layer[Never, LE, R | McpServer]: ...
def visibility(check: object, /, *, global_: bool = False) -> Any:
"""Middleware hiding registrations per request: where ``check`` gives
``False``, the registration is left out of lists and a request for it
fails as if it were not registered. It runs on list requests and on
calls, reads, gets and completions, with the middleware outside it (once
per registration on a list; the middleware inside does not run there). A
failure of that middleware or of ``check`` fails the whole list.
Unlike ``EnabledWhen``, middleware sees requests for hidden registrations
(as an ``McpError``)."""
if isinstance(check, Effect):
made: object = cast("Effect[Any, Any, Any]", check).map(_gate)
else:
made = _gate(cast("Callable[[MiddlewareOptions], Effect[bool, Any, Any]]", check))
built = Middleware[Any, Any, Any](_fn_layer(made))
return built.layer_global if global_ else builtclient_capabilities#
client_capabilities() -> Effect[ClientCapabilities, Never, McpRequestContext]The current request's client capabilities.
Returns Effect[ClientCapabilities, Never, McpRequestContext]
def client_capabilities() -> Effect[ClientCapabilities, Never, McpRequestContext]:
"""The current request's client capabilities."""
return McpRequestContext().map(lambda context: context.client_capabilities)elicit#
elicit[A, R = Never](*, message, schema) -> Effect[A, ElicitationDeclined, McpServerClient | R]Ask the user, through the client, for input matching schema.
Declining fails with ElicitationDeclined (so does a client that
cannot be asked), cancelling interrupts, and accepted content is
decoded with schema.
| Parameter | Type | Description |
|---|---|---|
message | str | |
schema | S.Codec[A, Any, R, Any] |
Returns Effect[A, ElicitationDeclined, McpServerClient | R]
def elicit[A, R = Never](
*, message: str, schema: S.Codec[A, Any, R, Any]
) -> Effect[A, ElicitationDeclined, McpServerClient | R]:
"""Ask the user, through the client, for input matching ``schema``.
Declining fails with ``ElicitationDeclined`` (so does a client that
cannot be asked), cancelling interrupts, and accepted content is
decoded with ``schema``."""
@gen
def run():
client = yield from McpServerClient()
reverse = yield from client.get_client
decode_request = cast(
"Callable[[object], Effect[ElicitRequestFormParams, S.SchemaError]]",
S.decode_unknown_effect(ELICIT_REQUEST_FORM_PARAMS),
)
request = yield from decode_request(
{
"mode": "form",
"message": message,
"requestedSchema": tool_json_schema(schema, strict=False),
}
).or_die()
result = yield from reverse.elicit(request).catch_cause(
lambda cause: fail(ElicitationDeclined(request, cause.raisable()))
)
action: Literal["accept", "decline", "cancel"] = result["action"]
if action == "cancel":
return (yield from fx.interrupt())
if action == "decline":
return (yield from fail(ElicitationDeclined(request)))
decode = cast(
"Callable[[object], Effect[A, S.SchemaError, R]]", S.decode_unknown_effect(schema)
)
return (yield from decode(result.get("content", {})).or_die())
return runregister_prompt#
register_prompt[P = Mapping[str, Never], E = Never, R = Never](*, name, content, parameters=None, completion=None, title=None, description=None, annotations=None) -> Effect[None, Never, McpServer | R]Serve a prompt: content gets the arguments parameters decodes
(a struct of strings) and gives messages, or a string as one user
message. completion completes arguments by name.
| Parameter | Type | Description |
|---|---|---|
name | str | |
content | Callable[[P], Effect[Sequence[PromptMessage] | str, E, R]] | |
parameters | S.Codec[P, Any, Any, Any] | None = None | |
completion | Mapping[str, CompletionFunction] | None = None | |
title | str | None = None | |
description | str | None = None | |
annotations | Context[Never] | None = None |
Returns Effect[None, Never, McpServer | R]
def register_prompt[P = Mapping[str, Never], E = Never, R = Never](
*,
name: str,
content: Callable[[P], Effect[Sequence[PromptMessage] | str, E, R]],
parameters: S.Codec[P, Any, Any, Any] | None = None,
completion: Mapping[str, CompletionFunction] | None = None,
title: str | None = None,
description: str | None = None,
annotations: Context[Never] | None = None,
) -> Effect[None, Never, McpServer | R]:
"""Serve a prompt: ``content`` gets the arguments ``parameters`` decodes
(a struct of strings) and gives messages, or a string as one user
message. ``completion`` completes arguments by name."""
@gen
def register():
services: Context[Any] = yield from fx.context()
server = yield from McpServer()
prompt: Prompt = {"name": name, "arguments": _prompt_arguments(parameters)}
if title is not None:
prompt["title"] = title
if description is not None:
prompt["description"] = description
decode: Callable[[object], Effect[Any, S.SchemaError]] = (
cast("Any", S.decode_unknown_effect(parameters))
if parameters is not None
else lambda _: succeed({})
)
fields: Mapping[str, Any] = getattr(parameters, "fields", {})
completions = {
argument: _completion(fields[argument], complete)
for argument, complete in (completion or {}).items()
}
def messages_of(messages: Sequence[PromptMessage] | str) -> GetPromptResult:
listed: list[PromptMessage] = (
[{"role": "user", "content": {"type": "text", "text": messages}}]
if isinstance(messages, str)
else list(messages)
)
result: GetPromptResult = {"messages": listed}
if description is not None:
result["description"] = description
return result
def handle(arguments: Mapping[str, str]) -> Effect[GetPromptResult, McpError, Any]:
got: Effect[GetPromptResult, McpError, Any] = (
decode(dict(arguments))
.map_error(lambda error: InvalidParams(error.message))
.flat_map(lambda decoded: _internal(suspend(lambda: content(decoded))))
.map(messages_of)
)
return got
yield from server.add_prompt(
PromptEntry(prompt, annotations or Context.empty(), completions, handle, services)
)
return registerregister_resource#
register_resource[E = Never, R = Never](*, uri, name, content, title=None, description=None, mime_type=None, audience=None, priority=None, annotations=None) -> Effect[None, Never, McpServer | R]Serve content at uri: a string is its text, bytes its blob.
A failure is answered as an internal error with its message, a defect
with a generic one.
| Parameter | Type | Description |
|---|---|---|
uri | str | |
name | str | |
content | Effect[ResourceContent, E, R] | |
title | str | None = None | |
description | str | None = None | |
mime_type | str | None = None | |
audience | Sequence[Role] | None = None | |
priority | float | None = None | |
annotations | Context[Never] | None = None |
Returns Effect[None, Never, McpServer | R]
def register_resource[E = Never, R = Never](
*,
uri: str,
name: str,
content: Effect[ResourceContent, E, R],
title: str | None = None,
description: str | None = None,
mime_type: str | None = None,
audience: Sequence[Role] | None = None,
priority: float | None = None,
annotations: Context[Never] | None = None,
) -> Effect[None, Never, McpServer | R]:
"""Serve ``content`` at ``uri``: a string is its text, bytes its blob.
A failure is answered as an internal error with its message, a defect
with a generic one."""
require_effect(content, "content")
@gen
def register():
services: Context[Any] = yield from fx.context()
server = yield from McpServer()
resource: Resource = _described(
{"uri": uri, "name": name},
title=title,
description=description,
mime_type=mime_type,
annotations=_resource_annotations(audience, priority),
)
handle: Effect[ReadResourceResult, McpError, Any] = _internal(
content.map(lambda c: _resolve_content(uri, c, mime_type=mime_type))
)
yield from server.add_resource(
ResourceEntry(resource, annotations or Context.empty(), handle, services)
)
return registerregister_resource_template#
register_resource_template[*Ts, E = Never, R = Never](template, *, name, content, completion=None, title=None, description=None, mime_type=None, audience=None, priority=None, annotations=None) -> Effect[None, Never, McpServer | R]Serve the URIs template matches: content gets the URI and
the decoded parameters. completion completes parameters by name.
| Parameter | Type | Description |
|---|---|---|
template | UriTemplate[*Ts,] | |
name | str | |
content | Callable[[str, *Ts], Effect[ResourceContent, E, R]] | |
completion | Mapping[str, CompletionFunction] | None = None | |
title | str | None = None | |
description | str | None = None | |
mime_type | str | None = None | |
audience | Sequence[Role] | None = None | |
priority | float | None = None | |
annotations | Context[Never] | None = None |
Returns Effect[None, Never, McpServer | R]
def register_resource_template[*Ts, E = Never, R = Never](
template: UriTemplate[*Ts],
*,
name: str,
content: Callable[[str, *Ts], Effect[ResourceContent, E, R]],
completion: Mapping[str, CompletionFunction] | None = None,
title: str | None = None,
description: str | None = None,
mime_type: str | None = None,
audience: Sequence[Role] | None = None,
priority: float | None = None,
annotations: Context[Never] | None = None,
) -> Effect[None, Never, McpServer | R]:
"""Serve the URIs ``template`` matches: ``content`` gets the URI and
the decoded parameters. ``completion`` completes parameters by name."""
@gen
def register():
services: Context[Any] = yield from fx.context()
server = yield from McpServer()
decode = cast(
"Callable[[object], Effect[tuple[Any, ...], S.SchemaError]]",
S.decode_unknown_effect(S.Tuple(*cast("Any", template.schemas))),
)
resource_template: ResourceTemplate = _described(
{"uriTemplate": template.uri_template, "name": name},
title=title,
description=description,
mime_type=mime_type,
annotations=_resource_annotations(audience, priority),
)
by_name = dict(zip(template.names, template.schemas, strict=True))
completions = {
param_name: _completion(by_name[param_name], complete)
for param_name, complete in (completion or {}).items()
}
def handle(
uri: str, params: Mapping[str, str]
) -> Effect[ReadResourceResult, McpError, Any]:
values = [params[n] for n in template.names]
read: Effect[ReadResourceResult, McpError, Any] = (
decode(values)
.map_error(lambda error: InvalidParams(error.message))
.flat_map(
lambda decoded: _internal(
suspend(lambda: cast("Any", content)(uri, *decoded)).map(
lambda c: _resolve_content(uri, c, mime_type=mime_type)
)
)
)
)
return read
yield from server.add_resource_template(
ResourceTemplateEntry(
resource_template,
annotations or Context.empty(),
template.match,
completions,
handle,
services,
)
)
return registerregister_toolkit#
register_toolkit[N: LiteralString, RP, HE, R](toolkit) -> Effect[None, Never, McpServer | Handlers[N] | R]Serve every tool of toolkit (Effect's registerToolkit).
A tool's inputSchema is its parameters' JSON Schema, which must be
an object; a success is the call's structuredContent and its JSON
text. Invalid parameters are a JSON-RPC invalid-params error, a declared
failure an isError result, and anything else is logged, reported and
answered with a generic isError result.
| Parameter | Type | Description |
|---|---|---|
toolkit | Toolkit[N, RP, HE, R] |
Returns Effect[None, Never, McpServer | Handlers[N] | R]
def register_toolkit[N: LiteralString, RP, HE, R](
toolkit: Toolkit[N, RP, HE, R],
) -> Effect[None, Never, McpServer | Handlers[N] | R]:
"""Serve every tool of ``toolkit`` (Effect's ``registerToolkit``).
A tool's ``inputSchema`` is its parameters' JSON Schema, which must be
an object; a success is the call's ``structuredContent`` and its JSON
text. Invalid parameters are a JSON-RPC invalid-params error, a declared
failure an ``isError`` result, and anything else is logged, reported and
answered with a generic ``isError`` result."""
@gen
def register():
server = yield from McpServer()
def without_request(context: Context[Any]) -> Context[Any]:
# A handler's layer may be built during a request: it keeps none of that request's.
return map_handler_contexts(toolkit, context, omit_request_services)
kit = yield from toolkit.pipe(fx.update_context(without_request))
services: Context[Any] = yield from fx.context()
def internal_tool_error(cause: Cause[object]) -> Effect[CallToolResult, InvalidParams]:
if cause.has_interrupts_only:
return fail_cause(cast("Cause[Never]", cause))
return (
fx.log_error(cause)
.and_then(error_reporter.report(cause))
.as_(_tool_error_result(INTERNAL_TOOL_ERROR_MESSAGE))
)
entries: list[ToolEntry] = []
for tool in kit.tools.values():
strict = tool.annotations.get_unsafe(Tool.Strict) is True
if strict and isinstance(tool, Tool.Dynamic) and tool.json_schema is not None:
yield from fx.die(
ValueError(
f"McpServer cannot strictly validate the raw JSON Schema for tool "
f"'{tool.name}'; use a schema instead"
)
)
input_schema = yield from _object_schema(tool, strict=strict)
mcp_tool: McpTool = {
"name": tool.name,
"inputSchema": input_schema,
"annotations": _tool_annotations(tool.annotations),
}
# Revisions before 2026-07-28 list it only for an object (projection).
mcp_tool["outputSchema"] = tool_json_schema(tool.success_schema, strict=False)
description = Tool.get_description(tool)
if description is not None:
mcp_tool["description"] = description
meta = tool.annotations.get_option(Tool.Meta)
if meta is not None:
mcp_tool["_meta"] = cast("JsonObject", meta.value)
entries.append(
ToolEntry(
mcp_tool,
tool.annotations,
_tool_handler(kit, tool, internal_tool_error),
services,
)
)
# Every tool is checked before any is added: a toolkit registers whole or not at all.
for entry in entries:
yield from server.add_tool(entry)
return registeruri_template#
uri_template[A](s0: str, p0: _Part[A], s1: str = '', /) -> UriTemplate[A]
uri_template[A, B](s0: str, p0: _Part[A], s1: str, p1: _Part[B], s2: str = '', /) -> UriTemplate[A, B]
uri_template[A, B, C](s0: str, p0: _Part[A], s1: str, p1: _Part[B], s2: str, p2: _Part[C], s3: str = '', /) -> UriTemplate[A, B, C]A URI template of literal text and parameters, in order::
uri_template("file:///notes/", S.String) # file:///notes/{param0}
uri_template("users://", param("id", S.Int), "/profile")A parameter is one path segment, percent-decoded, then decoded from its
text by its schema; a bare schema is named param<index>; two
parameters need text between them.
| Parameter | Type | Description |
|---|---|---|
parts | = () |
@overload
def uri_template[A](s0: str, p0: _Part[A], s1: str = "", /) -> UriTemplate[A]: ...
@overload
def uri_template[A, B](
s0: str, p0: _Part[A], s1: str, p1: _Part[B], s2: str = "", /
) -> UriTemplate[A, B]: ...
@overload
def uri_template[A, B, C](
s0: str, p0: _Part[A], s1: str, p1: _Part[B], s2: str, p2: _Part[C], s3: str = "", /
) -> UriTemplate[A, B, C]: ...
def uri_template(*parts: Any) -> UriTemplate[*tuple[Any, ...]]:
"""A URI template of literal text and parameters, in order::
uri_template("file:///notes/", S.String) # file:///notes/{param0}
uri_template("users://", param("id", S.Int), "/profile")
A parameter is one path segment, percent-decoded, then decoded from its
text by its schema; a bare schema is named ``param<index>``; two
parameters need text between them."""
texts: list[str] = [parts[0]]
names: list[str] = []
schemas: list[S.Top] = []
path = _router_text(parts[0])
for index in range(1, len(parts), 2):
part = parts[index]
name = part.name if isinstance(part, Param) else f"param{index // 2}"
schema: S.Top = cast("Param[Any]", part).schema if isinstance(part, Param) else part
literal = parts[index + 1] if index + 1 < len(parts) else ""
names.append(name)
schemas.append(S.to_codec_string_tree(cast("S.Codec[Any, Any, Any, Any]", schema)))
texts.append(f"{{{name}}}{literal}")
if literal == "" and index + 2 < len(parts):
raise ValueError(f"uri_template: parameter {name!r} needs text before the next one")
path += f":{index // 2}{_router_text(literal)}"
router = Router[None](RouterConfig(case_sensitive=True))
router.on("GET", f"/{path}", None)
return UriTemplate("".join(texts), tuple(names), tuple(schemas), router)register_skill#
register_skill(uri, files, *, annotations=None) -> Effect[None, IllegalArgumentError, McpServer]Register an Agent Skill under the MCP Skills extension (SEP-2640).
uri addresses its SKILL.md (skill://<skill-path>/SKILL.md),
whose last path segment is the skill's name; files maps paths under
the skill root to the files, SKILL.md included, served verbatim.
Each file is a resource, skills/list and skills/get list the
skill with every file's SHA-256 digest and size, and every directory of
the namespace is readable with resources/directory/read.
Fails with IllegalArgumentError when the skill breaks the extension's
rules (a name other than the URI's, a SKILL.md without YAML
frontmatter, frontmatter that is not SKILL_FRONTMATTER, a path
leaving the skill, more than 512 files or 16 MiB), when its directory
contains or lies in another skill's, or when one of its files is
already a resource. Registering a resource at a skill file's URI later
is a defect.
| Parameter | Type | Description |
|---|---|---|
uri | str | |
files | Mapping[str, SkillFileInput] | |
annotations | Context[Never] | None = None |
Returns Effect[None, IllegalArgumentError, McpServer]
def register_skill(
uri: str,
files: Mapping[str, SkillFileInput],
*,
annotations: Context[Never] | None = None,
) -> Effect[None, IllegalArgumentError, McpServer]:
"""Register an Agent Skill under the MCP Skills extension (SEP-2640).
``uri`` addresses its ``SKILL.md`` (``skill://<skill-path>/SKILL.md``),
whose last path segment is the skill's name; ``files`` maps paths under
the skill root to the files, ``SKILL.md`` included, served verbatim.
Each file is a resource, ``skills/list`` and ``skills/get`` list the
skill with every file's SHA-256 digest and size, and every directory of
the namespace is readable with ``resources/directory/read``.
Fails with ``IllegalArgumentError`` when the skill breaks the extension's
rules (a name other than the URI's, a ``SKILL.md`` without YAML
frontmatter, frontmatter that is not ``SKILL_FRONTMATTER``, a path
leaving the skill, more than 512 files or 16 MiB), when its directory
contains or lies in another skill's, or when one of its files is
already a resource. Registering a resource at a skill file's URI later
is a defect."""
shown: Context[Any] = annotations or Context.empty()
@gen
def register():
built = make_static_skill(uri, files)
if isinstance(built, IllegalArgumentError):
return (yield from fail(built))
server = yield from McpServer()
# Its handlers run under the middleware and services it was registered with.
services: Context[Any] = yield from fx.context()
invoke = Invoke.make(services, server.global_middleware)
registration = SkillRegistration(built.entry, shown, built.directories, invoke)
entries = [
ResourceEntry(Resource(**file.resource), shown, succeed(file.result), services)
for file in built.files
]
yield from server.add_skill(registration, entries)
return registerOn This Page
Re-exportsValuesTypesClassesFunctionsmakerun_stdiolayer_stdiorunlayer_rpc_protocollayer_httplayer_http_request_scopedtoolkitresourceresource_templatepromptskillname: refunds description: Process refundsdecode_name_headermiddlewarevisibilityclient_capabilitieselicitregister_promptregister_resourceregister_resource_templateregister_toolkituri_templateregister_skill