host.ts 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. import { readWindowState, writeWindowState, type WindowState } from "#ui/windowStorage.ts";
  2. import { App, PostMessageTransport } from "@modelcontextprotocol/ext-apps";
  3. import { PLUGIN_VERSION, SERVER_NAME } from "#office/contract.ts";
  4. import { CAPTURE_EXAMPLES, TITLE } from "#office/wording.ts";
  5. type ListHandler = NonNullable<App["onlisttools"]>;
  6. type CallHandler = NonNullable<App["oncalltool"]>;
  7. type ListToolsResult = Awaited<ReturnType<ListHandler>>;
  8. export type ToolDefinition = ListToolsResult["tools"][number];
  9. export type CallToolResult = Awaited<ReturnType<CallHandler>>;
  10. export type PageToolHandler = (
  11. args: Record<string, unknown>,
  12. signal: AbortSignal | undefined,
  13. ) => Promise<CallToolResult>;
  14. /**
  15. * Tools the page exposes to the model while it is open (MCP Apps app-provided tools). The
  16. * definitions are static so the host sees them at the handshake; the UI bundle binds handlers later.
  17. */
  18. export const PAGE_TOOLS: ToolDefinition[] = [
  19. {
  20. name: "capture_view",
  21. title: `Capture ${TITLE} view`,
  22. description: `Take a picture of a rendered document location in the ${TITLE} panel so you can see layout, charts, images and formatting that text extraction misses. Pass an anchor such as ${CAPTURE_EXAMPLES} (the document must be open in the panel; call open_document first), or omit it to capture what the user currently sees.`,
  23. inputSchema: {
  24. type: "object",
  25. properties: {
  26. anchor: {
  27. type: "string",
  28. maxLength: 1200,
  29. description: "Location to capture; defaults to the visible view.",
  30. },
  31. maxWidth: {
  32. type: "integer",
  33. minimum: 320,
  34. maximum: 2000,
  35. description: "Maximum image width in pixels (default 1600).",
  36. },
  37. },
  38. additionalProperties: false,
  39. },
  40. annotations: { readOnlyHint: true, idempotentHint: true },
  41. },
  42. ];
  43. type ToolResult = Parameters<NonNullable<App["ontoolresult"]>>[0];
  44. /**
  45. * One App connection per page. The bootstrap loader creates it before the UI bundle exists, so it
  46. * keeps every tool result and the page tools are registered through a late-bound table.
  47. */
  48. function createHost() {
  49. const pageId = crypto.randomUUID();
  50. const currentViewId = () =>
  51. (
  52. app.getHostCapabilities()?.experimental?.["zcode/surface"] as
  53. | { stateKey?: string }
  54. | undefined
  55. )?.stateKey ?? pageId;
  56. const app = new App(
  57. { name: SERVER_NAME, version: PLUGIN_VERSION },
  58. { tools: { listChanged: true }, availableDisplayModes: ["inline", "fullscreen"] },
  59. { autoResize: false },
  60. );
  61. const results: ToolResult[] = [];
  62. const handlers = new Map<string, PageToolHandler>();
  63. const waiters = new Set<() => void>();
  64. let connection: Promise<void> | undefined;
  65. const emit = (name: string) => void window.dispatchEvent(new Event(`office:${name}`));
  66. // Handlers are installed before connect so nothing sent during the handshake is lost.
  67. app.ontoolresult = (result) => {
  68. results.push(result);
  69. if (results.length > 20) results.shift();
  70. emit("toolresult");
  71. };
  72. app.onhostcontextchanged = () => emit("hostchange");
  73. app.onlisttools = async (): Promise<ListToolsResult> => ({ tools: PAGE_TOOLS });
  74. app.oncalltool = async (params, extra) => {
  75. if (!PAGE_TOOLS.some((tool) => tool.name === params.name))
  76. return {
  77. isError: true,
  78. content: [{ type: "text", text: `The ${TITLE} page has no tool ${params.name}.` }],
  79. };
  80. try {
  81. // The UI bundle may still be loading when the first call arrives.
  82. const deadline = Date.now() + 20_000;
  83. while (!handlers.has(params.name) && Date.now() < deadline)
  84. await new Promise<void>((resolve) => {
  85. const done = () => (waiters.delete(done), resolve());
  86. waiters.add(done);
  87. setTimeout(done, 500);
  88. });
  89. const handler = handlers.get(params.name);
  90. if (!handler) throw new Error(`The ${TITLE} panel is still loading; try again in a moment.`);
  91. const scoped = extra as { mcpReq?: { signal?: AbortSignal }; signal?: AbortSignal };
  92. return await handler(params.arguments ?? {}, scoped.mcpReq?.signal ?? scoped.signal);
  93. } catch (error) {
  94. return {
  95. isError: true,
  96. content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }],
  97. };
  98. }
  99. };
  100. window.addEventListener("pagehide", () => {
  101. void app
  102. .callServerTool({ name: "release_view", arguments: { viewId: currentViewId() } })
  103. .catch(() => undefined);
  104. });
  105. const ready = () =>
  106. (connection ??= app
  107. .connect(new PostMessageTransport(window.parent, window.parent))
  108. .then(() => emit("hostchange")));
  109. return {
  110. app,
  111. get viewId() {
  112. return currentViewId();
  113. },
  114. ready,
  115. readWindow(): WindowState {
  116. const surface = app.getHostCapabilities()?.experimental?.["zcode/surface"] as
  117. | { stateKey?: string }
  118. | undefined;
  119. if (!surface?.stateKey) return {};
  120. try {
  121. return readWindowState(localStorage, surface.stateKey);
  122. } catch {
  123. return {};
  124. }
  125. },
  126. saveWindow(patch: WindowState): void {
  127. const surface = app.getHostCapabilities()?.experimental?.["zcode/surface"] as
  128. | { stateKey?: string }
  129. | undefined;
  130. if (!surface?.stateKey) return;
  131. try {
  132. writeWindowState(localStorage, surface.stateKey, patch);
  133. } catch {
  134. /* 存储不可用仍可预览。 */
  135. }
  136. },
  137. readDocument(): string | null {
  138. return this.readWindow().path ?? null;
  139. },
  140. saveDocument(path: string): void {
  141. this.saveWindow({ path });
  142. },
  143. /** Tool results received so far (oldest first); the UI drains them on mount. */
  144. takeResults: () => results.splice(0, results.length),
  145. handleTool(name: string, handler: PageToolHandler) {
  146. handlers.set(name, handler);
  147. for (const wake of waiters) wake();
  148. },
  149. get context() {
  150. return app.getHostContext();
  151. },
  152. get capabilities() {
  153. return app.getHostCapabilities();
  154. },
  155. };
  156. }
  157. export type Host = ReturnType<typeof createHost>;
  158. declare global {
  159. interface Window {
  160. __officeHost?: Host;
  161. }
  162. }
  163. /** The loader page and the UI bundle share this instance; never connect twice. */
  164. export function getHost(): Host {
  165. return (window.__officeHost ??= createHost());
  166. }