Add a pluggable server extension API with MCP Apps (#3003)

Co-authored-by: Max Isbey <224885523+maxisbey@users.noreply.github.com>
This commit is contained in:
Marcelo Trylesinski 2026-06-29 11:58:05 +02:00 • committed by GitHub
commit 4b519782f1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 2598 additions and 24 deletions

View file

@ -1,14 +1,40 @@
# apps
MCP Apps: a tool result carries a `_meta.ui` reference to a `ui://` resource
that the host renders as an interactive surface. The story will register a
`@ui` resource and return it from a tool.
MCP Apps: a tool carries a `_meta.ui.resourceUri` reference to a `ui://`
resource that the host renders as an interactive surface. The server opts in via
the `Apps` extension (`io.modelcontextprotocol/ui`); the client negotiates it by
advertising the `text/html;profile=mcp-app` MIME type.
**Status: not yet implemented** ([#2896](https://github.com/modelcontextprotocol/python-sdk/issues/2896)).
The `extensions` capability map is not yet surfaced on `MCPServer`, so a server
cannot advertise Apps support and a client cannot negotiate it.
## Run it
```bash
# stdio (default — the client spawns the server as a subprocess)
uv run python -m stories.apps.client
# HTTP — the client self-hosts the server on a free port, runs, then tears it down
uv run python -m stories.apps.client --http
```
## What to look at
- `server.py` `MCPServer("apps-example", extensions=[apps])` — the extension
advertises `io.modelcontextprotocol/ui` under `ServerCapabilities.extensions`
and contributes the UI-bound tool and its `ui://` resource. `MCPServer` itself
never learns about "ui"; it applies a closed set of contributions.
- `server.py` `@apps.tool(resource_uri=...)` — stamps `_meta.ui.resourceUri` on
the tool; `add_html_resource` registers the matching `ui://` resource at
`text/html;profile=mcp-app`.
- `server.py` `client_supports_apps(ctx)` — SEP-2133 graceful degradation: a
client that did not negotiate Apps gets a text-only result.
- `client.py` `Client(target, extensions={...})` — the client advertises Apps
support so the server returns the UI-enabled result, then reads the tool's
`_meta.ui.resourceUri` and fetches that resource.
## Spec
[MCP Apps — extensions](https://modelcontextprotocol.io/specification/draft/extensions/apps)
· [SEP-2133 — extensions capability](https://github.com/modelcontextprotocol/modelcontextprotocol/issues/2133)
## See also
`custom_methods/` (registering a non-spec method without an extension).

View file

View file

@ -0,0 +1,35 @@
"""Negotiate MCP Apps, discover a tool's `ui://` UI, fetch it, and call the tool."""
from mcp_types import TextContent, TextResourceContents
from mcp.client import Client
from mcp.server.apps import APP_MIME_TYPE, EXTENSION_ID
from stories._harness import Target, run_client
async def main(target: Target, *, mode: str = "auto") -> None:
# Advertise MCP Apps support so the server returns the UI-enabled result; a
# client that omits this gets the text-only fallback (graceful degradation).
async with Client(target, mode=mode, extensions={EXTENSION_ID: {"mimeTypes": [APP_MIME_TYPE]}}) as client:
# The extensions capability map rides `server/discover` (modern only). On a
# legacy connection (today's stdio) it is absent, so assert it only when present.
if client.server_capabilities.extensions is not None:
assert client.server_capabilities.extensions == {EXTENSION_ID: {}}, client.server_capabilities.extensions
listed = await client.list_tools()
tool = next(t for t in listed.tools if t.name == "get_time")
assert tool.meta is not None, tool
assert tool.meta["ui"]["resourceUri"] == "ui://get-time/app.html", tool.meta
ui = await client.read_resource("ui://get-time/app.html")
contents = ui.contents[0]
assert isinstance(contents, TextResourceContents)
assert contents.mime_type == APP_MIME_TYPE, contents.mime_type
result = await client.call_tool("get_time", {})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "2026-06-26T00:00:00Z", result.content[0].text
if __name__ == "__main__":
run_client(main)

View file

@ -0,0 +1,43 @@
"""MCP Apps: a tool bound to a `ui://` resource the host renders as an interactive surface.
`Apps` is an opt-in `Extension` passed to `MCPServer(extensions=[...])`. The
`@apps.tool(resource_uri=...)` decorator stamps `_meta.ui.resourceUri` onto the
tool; `add_html_resource` registers the matching `ui://` HTML resource. The tool
degrades gracefully: `client_supports_apps(ctx)` reports whether the client
negotiated Apps, so it returns text-only output otherwise.
"""
from mcp.server.apps import Apps, client_supports_apps
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.context import Context
from stories._hosting import run_server_from_args
RESOURCE_URI = "ui://get-time/app.html"
CLOCK_HTML = """<!doctype html>
<title>Current time</title>
<h1 id="now">…</h1>
<script>
window.addEventListener("message", (event) => {
const text = event.data?.result?.content?.[0]?.text;
if (text) document.getElementById("now").textContent = text;
});
</script>
"""
def build_server() -> MCPServer:
apps = Apps()
@apps.tool(resource_uri=RESOURCE_URI, title="Get Time", description="Return the current time.")
def get_time(ctx: Context) -> str:
now = "2026-06-26T00:00:00Z"
if not client_supports_apps(ctx):
return f"The time is {now}."
return now
apps.add_html_resource(RESOURCE_URI, CLOCK_HTML, title="Clock")
return MCPServer("apps-example", extensions=[apps])
if __name__ == "__main__":
run_server_from_args(build_server)

View file

@ -0,0 +1,41 @@
# extensions
Writing your own extension (SEP-2133): one identifier bundles a settings entry
under `ServerCapabilities.extensions`, a contributed tool, and a vendor request
method gated on the client declaring the extension back.
## Run it
```bash
# stdio (default — the client spawns the server as a subprocess)
uv run python -m stories.extensions.client
# HTTP — the client self-hosts the server on a free port, runs, then tears it down
uv run python -m stories.extensions.client --http
```
## What to look at
- `server.py` `class Catalog(Extension)` — the whole extension: `settings()`
becomes the advertised capability entry, `tools()` contributes a regular tool,
`methods()` registers a vendor verb. The extension never holds the server; it
declares contributions and `MCPServer(extensions=[...])` consumes them.
- `server.py` `require_client_extension(ctx, EXTENSION_ID)` — the vendor method
rejects clients that did not declare the extension with `-32021` (missing
required client capability) and a machine-readable `requiredCapabilities`
payload.
- `client.py` `Client(target, extensions={EXTENSION_ID: {}})` — the client-side
half of the negotiation; on 2026-07-28 it travels in the per-request `_meta`
envelope.
- `client.py` `client.session.send_request(...)` — vendor methods have no
`Client`-level helper; the session escape hatch sends them.
## Spec
[SEP-2133 — extensions capability](https://github.com/modelcontextprotocol/modelcontextprotocol/issues/2133)
· [Capabilities — `_meta` key grammar](https://modelcontextprotocol.io/specification/draft/basic/index)
## See also
`apps/` (the built-in MCP Apps extension) · `custom_methods/` (the same verb
registered on the lowlevel `Server` by hand, without an extension).

View file

View file

@ -0,0 +1,54 @@
"""Discover an extension's capability entry, call its tool, then send its vendor method."""
from typing import Literal, cast
import mcp_types as types
from mcp_types import TextContent
from mcp.client import Client
from stories._harness import Target, run_client
EXTENSION_ID = "com.example/catalog"
class SearchParams(types.RequestParams):
query: str
limit: int = 3
class SearchRequest(types.Request[SearchParams, Literal["com.example/search"]]):
method: Literal["com.example/search"] = "com.example/search"
params: SearchParams
class SearchResult(types.Result):
items: list[str]
async def main(target: Target, *, mode: str = "auto") -> None:
# Declare the extension client-side so the server's `require_client_extension`
# gate on `com.example/search` passes.
async with Client(target, mode=mode, extensions={EXTENSION_ID: {}}) as client:
# The extensions capability map rides `server/discover` (modern only). On a
# legacy connection it is absent, so assert it only when present.
if client.server_capabilities.extensions is not None:
assert client.server_capabilities.extensions == {EXTENSION_ID: {"suggest": True}}, (
client.server_capabilities.extensions
)
# The extension's tool is a regular tool: listed and callable like any other.
listed = await client.list_tools()
assert [tool.name for tool in listed.tools] == ["suggest"], listed
result = await client.call_tool("suggest", {"prefix": "mcp"})
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "mcp-suggestion", result.content[0].text
# Vendor methods drop one layer to `client.session` (see custom_methods/);
# the cast is needed because `send_request` is typed against the spec union.
request = SearchRequest(params=SearchParams(query="mcp", limit=3))
found = await client.session.send_request(cast("types.ClientRequest", request), SearchResult)
assert found.items == ["mcp-0", "mcp-1", "mcp-2"], found
if __name__ == "__main__":
run_client(main)

View file

@ -0,0 +1,64 @@
"""Package a vendor verb and a tool as a reusable, advertised extension (SEP-2133).
`custom_methods/` registers a verb on the lowlevel `Server` by hand; this story
bundles the same idea as an `Extension`: declared contributions, a settings entry
under `ServerCapabilities.extensions`, and a `require_client_extension` gate on
the vendor method.
"""
from collections.abc import Sequence
from typing import Any
import mcp_types as types
from pydantic import Field
from mcp.server.context import ServerRequestContext
from mcp.server.extension import Extension, MethodBinding, ToolBinding
from mcp.server.mcpserver import MCPServer, require_client_extension
from stories._hosting import run_server_from_args
EXTENSION_ID = "com.example/catalog"
class SearchParams(types.RequestParams):
"""Subclass `RequestParams` so `_meta` (and the 2026 envelope keys) parse uniformly."""
query: str
limit: int = Field(default=3, ge=1, le=25)
class SearchResult(types.Result):
items: list[str]
def suggest(prefix: str) -> str:
"""Suggest a catalog entry for a prefix."""
return f"{prefix}-suggestion"
async def search(ctx: ServerRequestContext[Any, Any], params: SearchParams) -> SearchResult:
require_client_extension(ctx, EXTENSION_ID)
return SearchResult(items=[f"{params.query}-{n}" for n in range(params.limit)])
class Catalog(Extension):
"""One identifier, three contributions: settings, a tool, a vendor method."""
identifier = EXTENSION_ID
def settings(self) -> dict[str, Any]:
return {"suggest": True}
def tools(self) -> Sequence[ToolBinding]:
return [ToolBinding(fn=suggest)]
def methods(self) -> Sequence[MethodBinding]:
return [MethodBinding("com.example/search", SearchParams, search)]
def build_server() -> MCPServer:
return MCPServer("extensions-example", extensions=[Catalog()])
if __name__ == "__main__":
run_server_from_args(build_server)

View file

@ -48,6 +48,21 @@ status = "deprecated"
[story.custom_methods]
lowlevel = false
[story.apps]
# Extension API is MCPServer-tier (Apps decorators + extensions=[...]); no lowlevel variant.
# The extensions capability map (SEP-2133) rides server/discover, a modern-only path, so
# `main` pins "auto" (legacy initialize cannot carry it) and the leg is http-asgi.
lowlevel = false
transports = ["in-memory", "http-asgi"]
era = "dual-in-body"
[story.extensions]
# Same constraints as `apps`: MCPServer-tier extension API, capability map rides
# server/discover (modern only), client guards the capability assert by presence.
lowlevel = false
transports = ["in-memory", "http-asgi"]
era = "dual-in-body"
[story.schema_validators]
[story.middleware]
@ -147,7 +162,6 @@ fixed_port = 8000 # issuer/PRM metadata bake in :8
[deferred]
caching = "client honouring + per-result override unlanded"
subscriptions = "#2901 — Client.listen / ServerEventBus"
tasks = "extensions capability map + tasks runtime"
apps = "#2896 — extensions capability map"
tasks = "SEP-2663 — tasks extension runtime (server-decided augmentation, CreateTaskResult)"
skills = "#2896 — SEP-2640"
events = "#2901 + #2896"

View file

@ -1,16 +1,24 @@
# tasks
The `io.modelcontextprotocol/tasks` extension: long-running work registered
with `@task`, polled via `tasks/get`, updated mid-flight, and cancelled with
`tasks/cancel`. The story will show a task that outlives the request that
started it.
Task-augmented execution: a requestor augments a `tools/call` with a `task`, the
receiver returns a `CreateTaskResult` immediately, and the requestor polls
`tasks/get` and retrieves the deferred result.
**Status: not yet implemented.** The extension types exist but the `extensions`
capability map is not yet surfaced on `MCPServer`, and the runtime trails the
release. The TypeScript SDK deliberately removed its tasks example pending the
same work.
**Status: deferred.** Tasks ship in 2026-07-28 as
[SEP-2663](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/seps/2663-tasks-extension.md),
an `io.modelcontextprotocol/tasks` extension that is wire-incompatible with the
2025-11-25 in-core design still carried (types-only) in `mcp_types`. The runtime
needs to be built to the SEP — server-decided augmentation (ignoring the legacy
`params.task`), the `{tasks/get, tasks/update, tasks/cancel}` method set, the
`resultType: "task"` envelope, `execution.taskSupport` gating, and `ttlMs`
fields — so it lands in a separate PR with the conformance `tasks-*` scenarios
wired in.
## Spec
[Tasks — basic utilities](https://modelcontextprotocol.io/specification/draft/basic/utilities/tasks)
[SEP-2663 — Tasks extension](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/seps/2663-tasks-extension.md)
· [SEP-2133 — extensions capability](https://github.com/modelcontextprotocol/modelcontextprotocol/issues/2133)
## See also
`apps/` (the additive half of the extension API).