contract.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. /**
  2. * MCP Apps 协议契约:agent、host、renderer 与 main 共用的常量、工具 UI 元数据类型、沙箱句柄与登记载荷。
  3. * 页面 ↔ 宿主的线协议(`ui/*` 方法、握手、版本协商、JSON-RPC)由官方 `@modelcontextprotocol/ext-apps` 定义,
  4. * 这里只保留 ZCode 自己的扩展键与限额。只放类型与常量;归一化与 schema 在同目录其他文件,经 index.ts 导出。
  5. */
  6. /** MCP 扩展标识(规范「Extension Identifier」);与官方 SDK `EXTENSION_ID` 一致。 */
  7. export const MCP_APPS_EXTENSION_ID = "io.modelcontextprotocol/ui";
  8. /** UI 资源 mimeType(规范 MUST);与官方 SDK `RESOURCE_MIME_TYPE` 一致。 */
  9. export const MCP_APPS_RESOURCE_MIME_TYPE = "text/html;profile=mcp-app";
  10. /** 弃用的扁平键 `_meta["ui/resourceUri"]`;规范要求宿主 MUST 同时兼容,与官方 SDK `RESOURCE_URI_META_KEY` 一致。 */
  11. export const MCP_APPS_LEGACY_RESOURCE_URI_META_KEY = "ui/resourceUri";
  12. /**
  13. * MCP client `initialize` 里的 ui 扩展能力声明(规范「Client (Host) Capabilities」)。
  14. * 用 type 而不是 interface:MCP SDK 的 `ClientCapabilities.extensions` 要求值带字符串索引签名。
  15. */
  16. export type McpAppsClientCapability = { mimeTypes: string[] };
  17. /** agent 对每个 MCP server 宣告的能力片段;放进 `Client` 构造参数的 `capabilities.extensions`。 */
  18. export function buildMcpAppsClientCapabilities(): {
  19. extensions: { [extensionId: string]: McpAppsClientCapability };
  20. } {
  21. return { extensions: { [MCP_APPS_EXTENSION_ID]: { mimeTypes: [MCP_APPS_RESOURCE_MIME_TYPE] } } };
  22. }
  23. /** 宿主 hostInfo.name;hostInfo.version 只供页面 feature detect,与应用版本无关。 */
  24. export const MCP_APPS_HOST_NAME = "zcode";
  25. export const MCP_APPS_HOST_VERSION = "1";
  26. /** `ui/initialize` 握手超时(端口到达起算)与卸载前 `ui/resource-teardown` 的等待上限。 */
  27. export const MCP_APPS_HANDSHAKE_TIMEOUT_MS = 15_000;
  28. export const MCP_APPS_TEARDOWN_TIMEOUT_MS = 500;
  29. export type McpAppsDisplayMode = "inline" | "fullscreen" | "pip";
  30. export type McpAppsToolVisibility = "model" | "app";
  31. export const MCP_APPS_DEFAULT_TOOL_VISIBILITY: readonly McpAppsToolVisibility[] = ["model", "app"];
  32. /** MCP Apps 资源级 CSP(`McpUiResourceCsp`):四类域。资源 `_meta` 为主,工具级 `_meta.ui.csp` 只在资源没有声明时兜底。 */
  33. export interface McpToolUiCsp {
  34. connectDomains?: string[];
  35. resourceDomains?: string[];
  36. frameDomains?: string[];
  37. baseUriDomains?: string[];
  38. }
  39. /**
  40. * 资源级 `_meta["zcode/csp"]`:宿主缺省按规范块(只有 'self' 'unsafe-inline'),不放行 `'unsafe-eval'` /
  41. * `'wasm-unsafe-eval'`;需要 eval / WebAssembly 的资源在这里显式声明。宿主经
  42. * `hostCapabilities.experimental["zcode/csp"].flags` 宣告支持的键。
  43. */
  44. export const MCP_APPS_CSP_RELAXATION_META_KEY = "zcode/csp";
  45. export const MCP_APPS_CSP_RELAXATION_FLAGS = ["unsafeEval", "wasmUnsafeEval"] as const;
  46. export type McpAppCspRelaxationFlag = (typeof MCP_APPS_CSP_RELAXATION_FLAGS)[number];
  47. export type McpAppCspRelaxations = Partial<Record<McpAppCspRelaxationFlag, boolean>>;
  48. export function buildMcpAppsCspExperimentalCapability(): {
  49. [MCP_APPS_CSP_RELAXATION_META_KEY]: { flags: McpAppCspRelaxationFlag[] };
  50. } {
  51. return { [MCP_APPS_CSP_RELAXATION_META_KEY]: { flags: [...MCP_APPS_CSP_RELAXATION_FLAGS] } };
  52. }
  53. /**
  54. * 资源可声明的浏览器权限(规范草案 `UIResourceMeta.permissions` 的四键),顺序即归一化顺序。
  55. * 宿主:未声明一律拒绝;camera / microphone / geolocation 首次使用时原生弹框确认,clipboardWrite 按声明放行。
  56. */
  57. export const MCP_APPS_RESOURCE_PERMISSIONS = [
  58. "camera",
  59. "microphone",
  60. "geolocation",
  61. "clipboardWrite",
  62. ] as const;
  63. export type McpAppsResourcePermission = (typeof MCP_APPS_RESOURCE_PERMISSIONS)[number];
  64. /** 规范权限键 → 插件 iframe `allow` 的 Permissions Policy 特性名。 */
  65. export const MCP_APPS_IFRAME_ALLOW_TOKENS: Record<McpAppsResourcePermission, string> = {
  66. camera: "camera",
  67. microphone: "microphone",
  68. geolocation: "geolocation",
  69. clipboardWrite: "clipboard-write",
  70. };
  71. /** 与官方 SDK `buildAllowAttribute` 同形:`"camera; clipboard-write"`;没有声明返回空串。 */
  72. export function buildMcpAppsIframeAllow(
  73. permissions: readonly McpAppsResourcePermission[] | undefined,
  74. ): string {
  75. if (!permissions?.length) return "";
  76. return MCP_APPS_RESOURCE_PERMISSIONS.filter((key) => permissions.includes(key))
  77. .map((key) => MCP_APPS_IFRAME_ALLOW_TOKENS[key])
  78. .join("; ");
  79. }
  80. /**
  81. * `ui://` HTML 资源自己的 `_meta`(`resources/read` 内容项优先)。`heightHint` / `minFrameHeight` 是初始高度与
  82. * 最小高度(px);`showInline` 为 true 时卡片强制常驻、不进折叠区。
  83. */
  84. export interface McpAppResourceMeta {
  85. csp?: McpToolUiCsp;
  86. cspRelaxations?: McpAppCspRelaxations;
  87. /** `_meta.ui.permissions` 声明的浏览器权限(规范四键;顺序固定、去重)。 */
  88. permissions?: McpAppsResourcePermission[];
  89. prefersBorder?: boolean;
  90. heightHint?: number;
  91. minFrameHeight?: number;
  92. showInline?: boolean;
  93. }
  94. /** 随沙箱句柄回到 renderer 的资源级呈现信息;CSP 与放宽只在 main 生效,不回传。 */
  95. export type PluginSandboxResourceMeta = Omit<McpAppResourceMeta, "csp" | "cspRelaxations">;
  96. /** 工具 `_meta` 归一化后的 UI 描述;`resourceUri` 非法时整个描述不存在。 */
  97. export interface McpToolUiDescriptor {
  98. resourceUri: string;
  99. visibility?: McpAppsToolVisibility[];
  100. preferredDisplayMode?: McpAppsDisplayMode;
  101. csp?: McpToolUiCsp;
  102. prefersBorder?: boolean;
  103. /** 工具结果归属的面板 id(清单 `ui.surfaces[].id`)。 */
  104. surface?: string;
  105. /** 工具级 `openai/widgetShowCodexWidgetInline`,卡片强制常驻。 */
  106. showInline?: boolean;
  107. }
  108. /** `_meta.ui.surface` / 清单 surface id 的长度与字符集(与 sandboxId 同源:可进 CSP host-source)。 */
  109. export const MCP_APPS_SURFACE_ID_MAX_CHARS = 128;
  110. export const MCP_APPS_SURFACE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;
  111. export const MCP_APPS_UI_RESOURCE_SCHEME = "ui://";
  112. export const MCP_APPS_RESOURCE_URI_MAX_CHARS = 2048;
  113. /**
  114. * `display.ui.structuredContent` / `widgetMeta` / `content` 的持久化上限(JSON 文本的 UTF-8 字节)。
  115. * 超限不截断字符串(半截 JSON 没有意义):字段整个省略,`truncated: true` 且 `truncatedBytes` 记被丢弃的字节数;
  116. * 页面侧 `toolOutput` 为 null、`toolResponseMetadata["zcode/truncated"] = { bytes }`,可用 tools/call 重取。
  117. */
  118. export const MCP_APPS_STRUCTURED_CONTENT_MAX_BYTES = 64 * 1024;
  119. export const MCP_APPS_WIDGET_META_MAX_BYTES = 16 * 1024;
  120. export const MCP_APPS_CONTENT_MAX_BYTES = 32 * 1024;
  121. export const MCP_APPS_TRUNCATED_META_KEY = "zcode/truncated";
  122. /** host 侧接受的 `ui://` HTML 上限与 mimeType 白名单(规范只认带 profile 的;无 profile 的 text/html 是有意的宽松超集)。 */
  123. // 官方 pdf-server 示例的单文件页面(内联 pdf.js)就有 4.3 MB,4 MiB 会把它拒掉;放到 16 MiB。
  124. export const MCP_APPS_HTML_MAX_BYTES = 16 * 1024 * 1024;
  125. export const MCP_APPS_HTML_MIME_TYPES = [MCP_APPS_RESOURCE_MIME_TYPE, "text/html"] as const;
  126. /**
  127. * 页面经 ui/update-model-context 与 ui/message 送来的 image 块:白名单三种位图,单张解码后 ≤ 4 MiB;
  128. * 不在白名单或超限整个请求 -32602 `unsupported_content`。
  129. */
  130. export const MCP_APPS_IMAGE_MIME_TYPES = ["image/png", "image/jpeg", "image/webp"] as const;
  131. export const MCP_APPS_IMAGE_MAX_BYTES = 4 * 1024 * 1024;
  132. export {
  133. MCP_APPS_UI_READ_RESOURCE_MAX_BYTES,
  134. MCP_APPS_UI_READ_RESOURCE_MIME_ALLOWLIST,
  135. isMcpAppsUiReadResourceMimeAllowed,
  136. } from "./resourceMime.js";
  137. /**
  138. * `hostCapabilities.experimental` 里 ZCode 扩展的键。官方 SDK 的 zod 会剥掉标准位之外的未知能力键,
  139. * 扩展一律放 experimental(规范预留位),页面按键 feature detect。
  140. */
  141. export const MCP_APPS_WIDGET_STATE_EXPERIMENTAL_KEY = "zcode/widgetState";
  142. export const MCP_APPS_RESOURCE_SUBSCRIBE_EXPERIMENTAL_KEY = "zcode/resourceSubscribe";
  143. export const MCP_APPS_SURFACE_EXPERIMENTAL_KEY = "zcode/surface";
  144. /**
  145. * ZCode 扩展方法 `ui/set-widget-state { widgetState }`(MCP Apps 无 widgetState):页面把界面状态交给宿主
  146. * renderer 内存保存(不持久化,会话内重挂载可恢复);初值经 hostContext 的 `zcode/widgetState` 键随握手下发。
  147. */
  148. export const MCP_APPS_SET_WIDGET_STATE_METHOD = "ui/set-widget-state";
  149. export const MCP_APPS_WIDGET_STATE_CONTEXT_KEY = "zcode/widgetState";
  150. /** 宿主 renderer ↔ relay shell 之间唯一一条 MessageChannel 的名字;上面跑原始 JSON-RPC(官方 AppBridge / App)。 */
  151. export const PLUGIN_SANDBOX_PORT_NAME = "plugin-sandbox-rpc";
  152. /** MessagePort 的最小结构类型;宿主 renderer 的 Transport 与 relay shell 都只依赖这几个成员。 */
  153. export interface PluginSandboxTransportPort {
  154. postMessage(message: unknown): void;
  155. onmessage: ((event: { data: unknown }) => void) | null;
  156. start?(): void;
  157. close(): void;
  158. }
  159. /** main → 宿主 renderer 的端口事件(经 preload `window.postMessage` transfer)。 */
  160. export interface PluginSandboxPortsEvent {
  161. sandboxId: string;
  162. initId: number;
  163. port: PluginSandboxTransportPort;
  164. }
  165. /**
  166. * renderer 可用的沙箱平台端口,以 `IPlatformService.pluginSandbox` 可选字段挂载;web 端为 undefined,UI 据此回退。
  167. * 登记沙箱不在这里:它由 host 经 parentPort 完成,renderer 只拿句柄。
  168. */
  169. export interface PluginSandboxPlatformPort {
  170. /** preload 已安装限定的沙箱原子移动适配。 */
  171. supportsRetainedMove?: boolean;
  172. /** 仅宿主操作可用;Main 校验 owner/代次后复制当前页面内容。 */
  173. copyImage?(input: PluginSandboxCaptureRequest): Promise<void>;
  174. /** 宿主窗口 webContents id;prepareSandbox 用它作为 owner,main 在 will-attach 时校验。 */
  175. getOwnerWebContentsId(): Promise<number>;
  176. /**
  177. * 释放沙箱。带 initId 时只释放捕获的登记:新页面使用新 Agent 凭证和 sandboxId,
  178. * 两条 IPC 路径不同(host parentPort vs ipcMain),旧 dispose 到得晚也不能误杀新登记。
  179. */
  180. disposeSandbox(sandboxId: string, initId?: number): Promise<void>;
  181. consumeUserGesture(sandboxId: string): Promise<boolean>;
  182. onPorts(handler: (event: PluginSandboxPortsEvent) => void): () => void;
  183. }
  184. export interface PluginSandboxCaptureRequest {
  185. sandboxId: string;
  186. initId: number;
  187. captureRect: { x: number; y: number; width: number; height: number };
  188. viewportSize: { width: number; height: number };
  189. }
  190. /**
  191. * 沙箱作用域。工具卡片按 toolCallId,面板(清单 `ui.surfaces[]`)按 surfaceId;
  192. * 两者都映射到一个字符串 scopeId 进注册表幂等键与 widgetState 路由,避免 main / host 认识"面板"概念。
  193. */
  194. export type PluginUiScopeRef =
  195. | { kind: "toolCall"; toolCallId: string }
  196. | { kind: "surface"; surfaceId: string };
  197. export function buildPluginSandboxScopeId(scope: PluginUiScopeRef): string {
  198. return scope.kind === "toolCall" ? `tool:${scope.toolCallId}` : `surface:${scope.surfaceId}`;
  199. }
  200. /** host → main 登记沙箱内容的消息载荷(模式同 LocalMediaPreviewPathAuthorize*)。 */
  201. export interface PluginSandboxRegisterRequestPayload {
  202. instance: import("./instance.js").McpAppInstance;
  203. requestId: string;
  204. /** 工作区隔离;旧调用允许缺省,新宿主登记须贯穿实际 workspace 范围。 */
  205. workspacePath?: string;
  206. workspaceIdentity?: string;
  207. ownerWebContentsId: number;
  208. sessionId: string;
  209. /** Gen UI has Host provenance and never impersonates an MCP plugin. */
  210. contentKind?: "gen-ui";
  211. pluginId?: string;
  212. /** 资源所属的 MCP server 运行时名;沙箱 partition 按它派生(同一 server 的页面共享一份持久存储)。 */
  213. serverName?: string;
  214. /** `buildPluginSandboxScopeId` 的结果:`tool:<toolCallId>` 或 `surface:<surfaceId>`。 */
  215. scopeId: string;
  216. html: string;
  217. /** 有效 CSP:资源级优先,工具级兜底(host plugin-ui-bridge 已合并)。 */
  218. csp?: McpToolUiCsp;
  219. /** 资源级 `_meta["zcode/csp"]` 声明的放宽项。 */
  220. cspRelaxations?: McpAppCspRelaxations;
  221. /** 资源声明的浏览器权限;main 据此放宽 Permissions-Policy 与 iframe allow,并把权限请求交给闸门。 */
  222. permissions?: McpAppsResourcePermission[];
  223. prefersBorder?: boolean;
  224. /** 资源级尺寸提示,原样进句柄回给 renderer。 */
  225. heightHint?: number;
  226. minFrameHeight?: number;
  227. /** 资源级强制常驻标记,随句柄 resourceMeta 回 renderer。 */
  228. showInline?: boolean;
  229. }
  230. /** host 内部使用的登记输入:去掉传输层 requestId。 */
  231. export type PluginSandboxRegisterInput = Omit<PluginSandboxRegisterRequestPayload, "requestId">;
  232. export interface PluginSandboxHandle {
  233. instance: import("./instance.js").McpAppInstance;
  234. sandboxId: string;
  235. initId: number;
  236. shellUrl: string;
  237. partition: string;
  238. /** 资源级呈现信息(prefersBorder / heightHint / minFrameHeight / showInline);资源没声明时省略。 */
  239. resourceMeta?: PluginSandboxResourceMeta;
  240. }
  241. export type PluginSandboxRegisterResultPayload =
  242. | ({ requestId: string; ok: true } & PluginSandboxHandle)
  243. | { requestId: string; ok: false; error: string };