ruby-sdk/lib/mcp/apps.rb
Koichi ITO 7d9fda4360 Add Server-Side MCP Apps Helpers per SEP-1865
## Motivation and Context

SEP-1865 "MCP Apps - Interactive User Interfaces for MCP" is Final on the Extensions Track:
(https://github.com/modelcontextprotocol/modelcontextprotocol/pull/1865) an optional extension,
negotiated through the SEP-2133 `capabilities.extensions` mechanism, that lets a server ship
HTML user interfaces which the host renders for tool results.
The normative spec lives in the ext-apps repository (`specification/2026-01-26/apps.mdx`).
The Python SDK implements it in-SDK (python-sdk#3003, the `Apps` extension); the TypeScript
ecosystem ships it as the separate `@modelcontextprotocol/ext-apps` package on top of
the core SDK's SEP-2133 support.

Server-side support is a thin convention layer over primitives this SDK already has
(SEP-2133 extension capabilities, `_meta` on tools and resources, free-form resource URIs
and MIME types). New `MCP::Apps` module:

- Wire vocabulary constants shared with the reference implementations: `EXTENSION_ID`
  (`"io.modelcontextprotocol/ui"` - note `/ui`, not `/apps`), `RESOURCE_MIME_TYPE`
  (`"text/html;profile=mcp-app"`), `URI_SCHEME` (`"ui://"`), and the legacy flat meta key
  `RESOURCE_URI_META_KEY` (`"ui/resourceUri"`).
- `Apps.capability(mime_types:)` builds the `capabilities.extensions` fragment for
  `support_extensions` on the server or `connect` on the client.
- `Apps.ui_resource(uri:, name:, ...)` builds an `MCP::Resource` for a UI template,
  enforcing the spec's MUSTs (a `ui://` URI; the parameterized HTML MIME type by default).
- `Apps.tool_meta(resource_uri:, visibility:, meta:, legacy:)` builds the `_meta.ui.resourceUri`
  linkage (optionally also emitting the legacy flat alias, matching the reference server helper
  that keeps both shapes in sync), merged non-destructively into caller-supplied meta.
- `Apps.client_supports?(client_capabilities, mime_type:)` gates the text-only fallback
  the extension requires for clients that did not declare the capability (symbol/string tolerant).

Everything else the extension defines (the sandboxed iframe, the `ui/*` postMessage bridge methods,
consent for UI-initiated calls) is HOST responsibility and out of scope for a server SDK;
a server only ever receives ordinary `resources/read` and `tools/call` requests.
The README section states this boundary.

Resolves #376.

## How Has This Been Tested?

New `test/mcp/apps_test.rb` pins the wire vocabulary and covers the capability fragment,
`ui_resource` scheme validation and MIME default, `tool_meta` non-destructive merging,
visibility, the legacy alias, and `client_supports?` across symbol/string keys, mimeTypes narrowing,
and missing declarations.

New integration tests in `test/mcp/server_test.rb` drive a full server: the `initialize` result
advertises the extension, tools/list serializes `_meta.ui.resourceUri`, `resources/read` serves
the HTML template, and `client_supports?` distinguishes hosts with and without the declared extension.

`bundle exec rake` (tests, RuboCop, and conformance baseline) passes. Also verified end-to-end
over stdio: a client connecting with the extension declared negotiates the capability,
discovers the tool linkage via `_meta.ui.resourceUri`, and reads the `ui://` template
as `text/html;profile=mcp-app` content.

## Breaking Changes

None. Purely additive helper module; no existing code paths change.
2026-07-07 01:16:02 +09:00

109 lines
4.8 KiB
Ruby

# frozen_string_literal: true
module MCP
# Server-side helpers for the MCP Apps extension (SEP-1865, Extensions Track, Final):
# interactive user interfaces delivered as `ui://` HTML template resources that hosts
# render for tool results. The extension is negotiated per SEP-2133 through
# `capabilities.extensions` on both sides; a server declares {EXTENSION_ID}, registers
# UI templates as ordinary resources, and links tools to templates via `_meta`.
#
# Everything else defined by the extension (the sandboxed iframe, the `ui/*`
# postMessage bridge methods, consent for UI-initiated calls) is HOST responsibility:
# a server only ever receives ordinary `resources/read` and `tools/call` requests.
#
# Because the extension is optional, a UI-enabled tool MUST still return a meaningful
# text-only result for clients that did not declare the capability;
# use {Apps.client_supports?} to branch.
#
# @example Declaring an Apps-enabled server
# capabilities = MCP::Server::Capabilities.new
# capabilities.support_tools
# capabilities.support_resources
# capabilities.support_extensions(MCP::Apps.capability)
# server = MCP::Server.new(
# name: "weather_server",
# capabilities: capabilities,
# resources: [MCP::Apps.ui_resource(uri: "ui://weather-server/dashboard", name: "weather_dashboard")],
# )
# server.define_tool(
# name: "get_weather",
# meta: MCP::Apps.tool_meta(resource_uri: "ui://weather-server/dashboard"),
# ) { |server_context:|
# ...
# }
#
# https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx
module Apps
# Reverse-DNS extension identifier (note: `/ui`, not `/apps`), shared wire vocabulary with
# the reference `@modelcontextprotocol/ext-apps` package and the Python SDK's `Apps` extension.
EXTENSION_ID = "io.modelcontextprotocol/ui"
# UI template resources MUST use this parameterized MIME type.
RESOURCE_MIME_TYPE = "text/html;profile=mcp-app"
# UI template resource URIs MUST use this scheme.
URI_SCHEME = "ui://"
# Legacy flat `_meta` key linking a tool to its template; the canonical shape is
# the nested `_meta.ui.resourceUri`. {Apps.tool_meta} can emit both.
RESOURCE_URI_META_KEY = "ui/resourceUri"
extend self
# The `capabilities.extensions` fragment advertising Apps support. Pass to
# `MCP::Server::Capabilities.new(extensions: ...)` or `support_extensions(...)`,
# or merge into a client's `connect(capabilities: { extensions: ... })`.
def capability(mime_types: [RESOURCE_MIME_TYPE])
{ EXTENSION_ID => { mimeTypes: mime_types } }
end
# Builds an `MCP::Resource` for a UI template, enforcing the spec's MUSTs:
# a `ui://` URI and the `text/html;profile=mcp-app` MIME type by default.
def ui_resource(uri:, name:, mime_type: RESOURCE_MIME_TYPE, **rest)
unless uri.is_a?(String) && uri.start_with?(URI_SCHEME)
raise ArgumentError, "MCP Apps template URIs must start with #{URI_SCHEME.inspect} (got #{uri.inspect})"
end
Resource.new(uri: uri, name: name, mime_type: mime_type, **rest)
end
# Builds the tool `_meta` linking a tool to its UI template, merged non-destructively into
# caller-supplied `meta`. `visibility` restricts who sees the tool (an array of `"model"` / `"app"`).
# `legacy: true` also writes the flat `"ui/resourceUri"` alias, matching the reference server helper
# that keeps both key shapes in sync for older hosts.
def tool_meta(resource_uri:, visibility: nil, meta: nil, legacy: false)
unless resource_uri.is_a?(String) && resource_uri.start_with?(URI_SCHEME)
raise ArgumentError, "resource_uri must start with #{URI_SCHEME.inspect} (got #{resource_uri.inspect})"
end
ui_entry = { resourceUri: resource_uri }
ui_entry[:visibility] = visibility if visibility
merged = (meta || {}).merge(ui: ui_entry)
merged[RESOURCE_URI_META_KEY.to_sym] = resource_uri if legacy
merged
end
# Whether the client declared Apps support for `mime_type` in its `capabilities.extensions`
# (symbol or string keys). UI-enabled tools use this to fall back to a text-only result for
# clients without the extension.
def client_supports?(client_capabilities, mime_type: RESOURCE_MIME_TYPE)
extensions = read_key(client_capabilities, :extensions)
declaration = read_key(extensions, EXTENSION_ID)
return false unless declaration.is_a?(Hash)
mime_types = read_key(declaration, :mimeTypes)
# A declaration without mimeTypes advertises the extension without narrowing.
return true if mime_types.nil?
mime_types.is_a?(Array) && mime_types.include?(mime_type)
end
private
def read_key(hash, key)
return unless hash.is_a?(Hash)
value = hash[key.to_sym]
value.nil? ? hash[key.to_s] : value
end
end
end