pluginUiHostAppHandlers.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import type { CallToolResult } from "@modelcontextprotocol/client";
  2. import { INVALID_PARAMS, ProtocolError } from "@modelcontextprotocol/client";
  3. import type { McpUiDisplayMode, McpUiHostContext } from "@modelcontextprotocol/ext-apps/app-bridge";
  4. import type { IPluginUiBridgeService, PluginUiPluginScope } from "@zcode/services";
  5. import { resolveRequestedDisplayMode } from "../domain/buildPluginUiHostContext.js";
  6. import type { PluginUiHostBridge } from "./pluginUiHostBridge.js";
  7. /**
  8. * 页面发起的规范请求 / 通知接到官方 AppBridge:`ui/request-display-mode`、`tools/call`、`ui/open-link`、
  9. * `ui/notifications/size-changed`、`ui/notifications/request-teardown`、`notifications/message`。
  10. * 会话交互(ui/message 等)在 pluginUiInteractionPorts,资源请求在 pluginUiResourceSubscriptions。
  11. */
  12. export interface PluginUiHostAppHandlerDeps {
  13. currentContext(): McpUiHostContext;
  14. /** 宿主裁决后的模式写回 hostContext 并(已握手时)推 host-context-changed。 */
  15. applyDisplayMode(mode: McpUiDisplayMode): void;
  16. onDisplayModeRequest(mode: McpUiDisplayMode): McpUiDisplayMode;
  17. pluginScope(): PluginUiPluginScope;
  18. bridge: Pick<IPluginUiBridgeService, "callTool" | "cancelToolCall">;
  19. createCallId(): string;
  20. /** 进行中的页面工具调用 id;controller dispose 时逐个取消到 agent。 */
  21. activeCalls: Set<string>;
  22. onBusyChange?(): void;
  23. onOpenExternal(url: string): void;
  24. }
  25. const OPEN_LINK_PROTOCOLS = new Set(["http:", "https:"]);
  26. export function installPluginUiHostAppHandlers(
  27. bridge: PluginUiHostBridge,
  28. deps: PluginUiHostAppHandlerDeps,
  29. ): void {
  30. bridge.onrequestdisplaymode = async (params) => {
  31. const context = deps.currentContext();
  32. const current = context.displayMode ?? "inline";
  33. const available = context.availableDisplayModes ?? [current];
  34. const mode = deps.onDisplayModeRequest(
  35. resolveRequestedDisplayMode(params.mode, current, available),
  36. );
  37. if (mode !== context.displayMode) deps.applyDisplayMode(mode);
  38. return { mode };
  39. };
  40. bridge.oncalltool = async (params, ctx) => {
  41. const signal = ctx.mcpReq?.signal;
  42. signal?.throwIfAborted();
  43. const scope = deps.pluginScope();
  44. const callId = deps.createCallId();
  45. deps.activeCalls.add(callId);
  46. deps.onBusyChange?.();
  47. // 页面中止请求(SDK 的 cancelled 通知落到 ctx.mcpReq.signal)→ 取消到 agent 的 MCP client。
  48. const onAbort = () => {
  49. void deps.bridge.cancelToolCall({ ...scope, callId }).catch(() => undefined);
  50. };
  51. signal?.addEventListener("abort", onAbort, { once: true });
  52. try {
  53. const result = await deps.bridge.callTool({
  54. ...scope,
  55. toolName: params.name,
  56. ...(params.arguments ? { arguments: params.arguments } : {}),
  57. callId,
  58. });
  59. return result as CallToolResult;
  60. } finally {
  61. signal?.removeEventListener("abort", onAbort);
  62. deps.activeCalls.delete(callId);
  63. deps.onBusyChange?.();
  64. }
  65. };
  66. bridge.onopenlink = async (params) => {
  67. let url: URL;
  68. try {
  69. url = new URL(params.url);
  70. } catch {
  71. throw new ProtocolError(INVALID_PARAMS, `invalid link ${params.url}`);
  72. }
  73. // 只放行 http(s):file: / 自定义 scheme 交给系统会打开本地程序。
  74. if (!OPEN_LINK_PROTOCOLS.has(url.protocol)) {
  75. throw new ProtocolError(INVALID_PARAMS, `only http(s) links can be opened (${url.protocol})`);
  76. }
  77. deps.onOpenExternal(url.toString());
  78. return {};
  79. };
  80. }
  81. export function installPluginUiHostNotificationHandlers(
  82. bridge: PluginUiHostBridge,
  83. deps: {
  84. pluginId: string;
  85. onHeight(height: number): void;
  86. log?: (message: string, detail?: Record<string, unknown>) => void;
  87. },
  88. ): void {
  89. // 页面请求宿主拆掉自己:本宿主的实例生命周期跟随卡片 / 面板,只记录,不主动销毁。
  90. bridge.onrequestteardown = () => {
  91. deps.log?.("[plugin-ui] app requested teardown", { pluginId: deps.pluginId });
  92. };
  93. bridge.onsizechange = (params) => {
  94. if (typeof params.height === "number") deps.onHeight(params.height);
  95. };
  96. bridge.onloggingmessage = (params) => {
  97. deps.log?.(`[plugin-ui] app log (${params.level})`, {
  98. pluginId: deps.pluginId,
  99. data: params.data,
  100. });
  101. };
  102. }