@nimblebrain/synapse 0.19.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -25
- package/dist/check-QMTOCTRS.js +474 -0
- package/dist/check-QMTOCTRS.js.map +1 -0
- package/dist/check-VK4SOAUU.cjs +480 -0
- package/dist/check-VK4SOAUU.cjs.map +1 -0
- package/dist/{chunk-RU64F5RS.cjs → chunk-BNF352SA.cjs} +57 -146
- package/dist/chunk-BNF352SA.cjs.map +1 -0
- package/dist/{chunk-DRLVEHCD.js → chunk-DJS2FKBN.js} +21 -79
- package/dist/chunk-DJS2FKBN.js.map +1 -0
- package/dist/chunk-H3INUKA3.js +32 -0
- package/dist/chunk-H3INUKA3.js.map +1 -0
- package/dist/chunk-HQLSVUOR.cjs +667 -0
- package/dist/chunk-HQLSVUOR.cjs.map +1 -0
- package/dist/{chunk-NP7ROSH2.cjs → chunk-ISV6HFQE.cjs} +14 -7
- package/dist/chunk-ISV6HFQE.cjs.map +1 -0
- package/dist/chunk-TR2YNWZ5.js +658 -0
- package/dist/chunk-TR2YNWZ5.js.map +1 -0
- package/dist/{chunk-OYLZ5OCK.js → chunk-UKP4W6DI.js} +57 -146
- package/dist/chunk-UKP4W6DI.js.map +1 -0
- package/dist/{chunk-SZWHFTXV.cjs → chunk-YSL7KJNU.cjs} +21 -81
- package/dist/chunk-YSL7KJNU.cjs.map +1 -0
- package/dist/codegen/cli.cjs +41 -4
- package/dist/codegen/cli.cjs.map +1 -1
- package/dist/codegen/cli.js +41 -4
- package/dist/codegen/cli.js.map +1 -1
- package/dist/codegen/index.cjs +0 -1
- package/dist/codegen/index.d.cts +1 -1
- package/dist/codegen/index.d.ts +1 -1
- package/dist/codegen/index.js +0 -1
- package/dist/connect.iife.global.js +34 -34
- package/dist/{detect-DZMJsyvZ.d.cts → detect-DVGaL2bH.d.cts} +39 -33
- package/dist/{detect-DBwc8a21.d.ts → detect-DVGaL2bH.d.ts} +39 -33
- package/dist/host/index.cjs +17 -18
- package/dist/host/index.d.cts +11 -27
- package/dist/host/index.d.ts +11 -27
- package/dist/host/index.js +2 -3
- package/dist/index.cjs +30 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +72 -26
- package/dist/index.d.ts +72 -26
- package/dist/index.js +8 -9
- package/dist/index.js.map +1 -1
- package/dist/react/index.cjs +9 -10
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.cts +36 -8
- package/dist/react/index.d.ts +36 -8
- package/dist/react/index.js +3 -4
- package/dist/react/index.js.map +1 -1
- package/dist/schema-reader-776246MJ.js +3 -0
- package/dist/{schema-reader-GM4A4L44.js.map → schema-reader-776246MJ.js.map} +1 -1
- package/dist/{schema-reader-MWBRQ2TQ.cjs → schema-reader-B6LTGBMJ.cjs} +2 -3
- package/dist/{schema-reader-MWBRQ2TQ.cjs.map → schema-reader-B6LTGBMJ.cjs.map} +1 -1
- package/dist/{server-LR6T6C44.cjs → server-BR5MNFOB.cjs} +13 -14
- package/dist/server-BR5MNFOB.cjs.map +1 -0
- package/dist/{server-UHPEE55X.js → server-OOEEWAEG.js} +13 -14
- package/dist/server-OOEEWAEG.js.map +1 -0
- package/dist/synapse-runtime.iife.global.js +34 -34
- package/dist/synapse-ui.iife.global.js +4 -4
- package/dist/type-generator-MZ4X4DE5.js +3 -0
- package/dist/{type-generator-ZYSVFK3X.js.map → type-generator-MZ4X4DE5.js.map} +1 -1
- package/dist/{type-generator-YTPFWLVG.cjs → type-generator-UA3L4OIA.cjs} +2 -3
- package/dist/{type-generator-YTPFWLVG.cjs.map → type-generator-UA3L4OIA.cjs.map} +1 -1
- package/dist/{types-CG08aO82.d.cts → types-BxPfGHKO.d.cts} +35 -43
- package/dist/{types-CG08aO82.d.ts → types-BxPfGHKO.d.ts} +35 -43
- package/dist/ui/base.cjs +0 -1
- package/dist/ui/base.cjs.map +1 -1
- package/dist/ui/base.js +0 -1
- package/dist/ui/base.js.map +1 -1
- package/dist/ui/index.cjs +0 -1
- package/dist/ui/index.cjs.map +1 -1
- package/dist/ui/index.js +0 -1
- package/dist/ui/index.js.map +1 -1
- package/dist/vite/index.cjs +10 -10
- package/dist/vite/index.cjs.map +1 -1
- package/dist/vite/index.js +6 -6
- package/dist/vite/index.js.map +1 -1
- package/dist/{writer-HDRCQSX2.cjs → writer-NDK4U6C5.cjs} +3 -3
- package/dist/{writer-HDRCQSX2.cjs.map → writer-NDK4U6C5.cjs.map} +1 -1
- package/dist/{writer-QNDPMEYD.js → writer-ZNBXYUYC.js} +3 -3
- package/dist/{writer-QNDPMEYD.js.map → writer-ZNBXYUYC.js.map} +1 -1
- package/package.json +6 -3
- package/dist/chunk-54W6IAHM.js +0 -24
- package/dist/chunk-54W6IAHM.js.map +0 -1
- package/dist/chunk-DRLVEHCD.js.map +0 -1
- package/dist/chunk-NP7ROSH2.cjs.map +0 -1
- package/dist/chunk-OYLZ5OCK.js.map +0 -1
- package/dist/chunk-P5DBJFSQ.js +0 -8459
- package/dist/chunk-P5DBJFSQ.js.map +0 -1
- package/dist/chunk-PZ5AY32C.js +0 -9
- package/dist/chunk-PZ5AY32C.js.map +0 -1
- package/dist/chunk-Q7SFCCGT.cjs +0 -11
- package/dist/chunk-Q7SFCCGT.cjs.map +0 -1
- package/dist/chunk-QXDCA7QW.cjs +0 -8466
- package/dist/chunk-QXDCA7QW.cjs.map +0 -1
- package/dist/chunk-RU64F5RS.cjs.map +0 -1
- package/dist/chunk-SZWHFTXV.cjs.map +0 -1
- package/dist/schema-reader-GM4A4L44.js +0 -4
- package/dist/server-LR6T6C44.cjs.map +0 -1
- package/dist/server-UHPEE55X.js.map +0 -1
- package/dist/type-generator-ZYSVFK3X.js +0 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/internals.ts","../src/result-parser.ts","../src/task-handle.ts","../src/content-parser.ts","../src/keyboard.ts","../src/resize.ts","../src/connect.ts","../src/extensions.ts"],"names":["raw","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AA4B;AACtD,EAAA,IACE,OAAO,UAAU,QAAA,IACjB,KAAA,KAAU,QACV,OAAQ,KAAA,CAA2B,OAAO,QAAA,EAC1C;AACA,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAIF;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT","file":"chunk-TR2YNWZ5.js","sourcesContent":["/**\n * Thrown when an app asks for something the host did not declare in\n * `ui/initialize`.\n *\n * The request is never sent. A host that does not implement a request may never\n * answer it, and this SDK's requests carry no deadline, so sending anyway would\n * leave the caller waiting forever rather than failing.\n *\n * `capability` names what was missing, as the host would have declared it: a\n * `hostCapabilities` field (`serverTools`, `downloadFile`) or an extension\n * identifier (`ai.nimblebrain/request-file`, `io.modelcontextprotocol/tasks`).\n */\nexport class HostCapabilityError extends Error {\n readonly capability: string;\n\n constructor(feature: string, capability: string) {\n super(`${feature} is not supported in this host: it did not declare ${capability}`);\n this.name = \"HostCapabilityError\";\n this.capability = capability;\n }\n}\n","/**\n * The plumbing the SDK's own composable helpers reach through — the file\n * picker, `action`, `downloadFile`, `callToolAsTask`.\n *\n * It lives in a module-private `WeakMap` rather than on the `App` object,\n * because those two options are not equivalent. A `_internals` member is still\n * a member: it type-checks, autocompletes, survives `Object.keys`, and hands\n * every consumer a transport the SDK does not model a use for. Underscore and\n * an `@internal` tag are a request, not a boundary, and a request is what the\n * removed `Synapse._request` was — which is exactly how a bridge script ended\n * up hand-rolling its own `tools/call`.\n *\n * So the public type is the protocol surface and nothing else, and the seam is\n * genuinely closed: a caller who needs something the SDK does not expose gets a\n * named method for it, or the SDK is missing a feature.\n */\nimport type { App, AppInternals } from \"./types.js\";\n\nconst INTERNALS = new WeakMap<App, AppInternals>();\n\n/** Called once by `connect()` for each app it builds. */\nexport function registerInternals(app: App, internals: AppInternals): void {\n INTERNALS.set(app, internals);\n}\n\n/**\n * The plumbing behind an app. Throws if `app` did not come from this copy of\n * the SDK — which is what a duplicated install looks like, and is worth failing\n * loudly for rather than as an undefined-property read three frames later.\n */\nexport function internalsFor(app: App): AppInternals {\n const internals = INTERNALS.get(app);\n if (!internals) {\n throw new Error(\n \"This App did not come from this copy of @nimblebrain/synapse. \" +\n \"Two copies of the package are installed (check for a duplicate in your \" +\n \"lockfile, or a bundler resolving the ESM and CJS builds separately).\",\n );\n }\n return internals;\n}\n","import type { ToolCallResult } from \"./types.js\";\n\n/**\n * Normalize a raw tool call response into a consistent `ToolCallResult`.\n *\n * Handles three shapes:\n * 1. MCP `CallToolResult` — has a `content` array with typed blocks.\n * 2. Raw JSON object (NimbleBrain bridge) — used as-is.\n * 3. Null / undefined — returns `{ data: null, isError: false }`.\n *\n * `_meta` on a `CallToolResult` is preserved on the parsed output as a\n * whole-object passthrough — notably `io.modelcontextprotocol/related-task`\n * (`{ taskId }`) for MCP 2025-11-25 task-augmented results, but any other\n * namespaced `_meta` keys propagate for free.\n */\nexport function parseToolResult(raw: unknown): ToolCallResult {\n if (raw == null) {\n return { data: null, isError: false };\n }\n\n if (isCallToolResult(raw)) {\n return parseCallToolResult(raw);\n }\n\n // Raw JSON object — pass through.\n return { data: raw, isError: false };\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\ninterface McpTextBlock {\n type: \"text\";\n text: string;\n}\n\ninterface McpCallToolResult {\n content: unknown[];\n isError?: boolean;\n _meta?: { [key: string]: unknown };\n}\n\nfunction isCallToolResult(value: unknown): value is McpCallToolResult {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n return Array.isArray((value as Record<string, unknown>).content);\n}\n\nfunction isTextBlock(block: unknown): block is McpTextBlock {\n if (block === null || typeof block !== \"object\" || Array.isArray(block)) {\n return false;\n }\n const obj = block as Record<string, unknown>;\n return obj.type === \"text\" && typeof obj.text === \"string\";\n}\n\n/**\n * Extract `_meta` as a shallow-copied object if present and object-shaped.\n *\n * Key-preserving by design: every `_meta` entry propagates without\n * selective copying, so future spec additions flow through without code\n * changes. Returns `undefined` when the input has no meaningful `_meta`.\n */\nfunction extractMeta(result: McpCallToolResult): { [key: string]: unknown } | undefined {\n const meta = result._meta;\n if (!meta || typeof meta !== \"object\" || Array.isArray(meta)) return undefined;\n // Shallow spread so mutations on either side don't leak. Preserves the\n // full key set including `io.modelcontextprotocol/related-task`.\n return { ...meta };\n}\n\nfunction parseCallToolResult(result: McpCallToolResult): ToolCallResult {\n const isError = result.isError === true;\n const content = result.content;\n const meta = extractMeta(result);\n\n if (content.length === 0) {\n return { data: null, isError, content, ...(meta && { _meta: meta }) };\n }\n\n const firstText = content.find(isTextBlock);\n\n if (!firstText) {\n // No text blocks — return the full content array so callers can inspect it.\n return { data: content, isError, content, ...(meta && { _meta: meta }) };\n }\n\n // Try to parse JSON from the text block.\n try {\n return { data: JSON.parse(firstText.text), isError, content, ...(meta && { _meta: meta }) };\n } catch {\n // Invalid JSON — return the raw string.\n return { data: firstText.text, isError, content, ...(meta && { _meta: meta }) };\n }\n}\n","import type { McpUiHostCapabilities } from \"@modelcontextprotocol/ext-apps\";\nimport type {\n CallToolRequest,\n CancelTaskRequest,\n CancelTaskResult,\n CreateTaskResult,\n GetTaskPayloadRequest,\n GetTaskPayloadResult,\n GetTaskRequest,\n GetTaskResult,\n Task,\n TaskStatus,\n TaskStatusNotification,\n TaskStatusNotificationParams,\n} from \"@modelcontextprotocol/sdk/types.js\";\n\nimport { HostCapabilityError } from \"./errors.js\";\nimport { TOOLS_CALL_METHOD } from \"./event-map.js\";\nimport { internalsFor } from \"./internals.js\";\nimport { parseToolResult } from \"./result-parser.js\";\nimport type {\n App,\n CallToolAsTaskOptions,\n TaskHandle,\n TaskStatusRouter,\n TaskStatusUpdate,\n TasksCapability,\n ToolCallResult,\n} from \"./types.js\";\n\nexport type { TaskStatusRouter, TaskStatusUpdate };\n\n// -----------------------------------------------------------------------------\n// Host capability\n// -----------------------------------------------------------------------------\n\n/** The MCP Tasks extension identifier. */\nexport const TASKS_EXTENSION_ID = \"io.modelcontextprotocol/tasks\";\n\n/**\n * The host's tasks capability, from the `ui/initialize` result.\n *\n * It lives in `hostCapabilities.experimental`, under the MCP Tasks extension\n * identifier. The ext-apps host capability type has no `tasks` field, so a client that\n * validates the handshake against the spec's schema strips a top-level `tasks`;\n * `experimental` is the one slot whose contents survive that parse (ext-apps\n * 1.7.5 and later). A top-level `tasks` is therefore not read at all — reading\n * it would make a capability visible here that no spec client can see.\n *\n * One key, and only that one: the identifier is the extension registry's, and a\n * host publishing the capability under any other name is not advertising this\n * extension.\n */\nexport function readHostTasksCapability(\n capabilities: McpUiHostCapabilities | undefined,\n): TasksCapability | undefined {\n const entry = capabilities?.experimental?.[TASKS_EXTENSION_ID];\n return entry && typeof entry === \"object\" && !Array.isArray(entry)\n ? (entry as TasksCapability)\n : undefined;\n}\n\n// -----------------------------------------------------------------------------\n// Spec method constants\n// -----------------------------------------------------------------------------\n//\n// The MCP SDK publishes task-method strings only inside Zod `z.literal(...)`s,\n// not as top-level `*_METHOD` constants. Derive each from its request's\n// `method` type so an upstream rename surfaces here as a compile error\n// (same pattern as `READ_RESOURCE_METHOD` in event-map.ts, where the core-MCP\n// method constants live).\n//\n// When adding a new method here, also mirror it in `src/_shims/ext-apps.ts`\n// per the IIFE build instructions in CLAUDE.md — the shim must export the\n// same string constants any source file consumes.\n\nexport const TASKS_GET_METHOD: GetTaskRequest[\"method\"] = \"tasks/get\";\nexport const TASKS_RESULT_METHOD: GetTaskPayloadRequest[\"method\"] = \"tasks/result\";\nexport const TASKS_CANCEL_METHOD: CancelTaskRequest[\"method\"] = \"tasks/cancel\";\nexport const TASKS_STATUS_NOTIFICATION_METHOD: TaskStatusNotification[\"method\"] =\n \"notifications/tasks/status\";\n\n// -----------------------------------------------------------------------------\n// Status router\n// -----------------------------------------------------------------------------\n\n/** Subscribe to a wire method, and return the unsubscribe. */\ntype SubscribeFn = (\n method: string,\n handler: (params: Record<string, unknown> | undefined) => void,\n) => () => void;\n\nexport function createTaskStatusRouter(subscribe: SubscribeFn): TaskStatusRouter {\n const listeners = new Map<string, Set<(update: TaskStatusUpdate) => void>>();\n\n // A single subscription to the wire method. All per-handle listeners filter\n // in-memory by taskId off this one handler.\n const unsub = subscribe(TASKS_STATUS_NOTIFICATION_METHOD, (rawParams) => {\n if (!rawParams) return;\n const params = rawParams as unknown as TaskStatusNotificationParams;\n const taskId = params.taskId;\n if (typeof taskId !== \"string\") return;\n\n const set = listeners.get(taskId);\n if (!set || set.size === 0) return;\n\n // Forward the spec-guaranteed fields verbatim. We deliberately don't\n // fabricate `createdAt`/`lastUpdatedAt`/`ttl` here — the handle merges\n // these from its initial `CreateTaskResult.task` so consumers always\n // see a real Task with no placeholder strings.\n const update: TaskStatusUpdate = {\n taskId: params.taskId,\n status: params.status,\n ...(params.statusMessage !== undefined && { statusMessage: params.statusMessage }),\n };\n\n for (const cb of set) cb(update);\n });\n\n return {\n subscribe(taskId, cb) {\n let set = listeners.get(taskId);\n if (!set) {\n set = new Set();\n listeners.set(taskId, set);\n }\n set.add(cb);\n return () => {\n const s = listeners.get(taskId);\n if (!s) return;\n s.delete(cb);\n if (s.size === 0) listeners.delete(taskId);\n };\n },\n dispose() {\n listeners.clear();\n unsub();\n },\n };\n}\n\n// -----------------------------------------------------------------------------\n// Caller-facing factory\n// -----------------------------------------------------------------------------\n\n/**\n * Task-augment a `tools/call` per the MCP 2025-11-25 tasks utility.\n *\n * A composable helper over {@link App} rather than a method on it: the object\n * `connect()` returns carries the ext-apps surface, and tasks ride alongside.\n * The receiver answers a task-augmented call with a `CreateTaskResult`\n * promptly; the actual `CallToolResult` arrives later via `tasks/result`.\n *\n * ```ts\n * const handle = await callToolAsTask(app, \"deep_research\", { topic });\n * handle.onStatus((t) => setStatus(t.status));\n * const result = await handle.result();\n * ```\n *\n * Rejects with `HostCapabilityError` if the host did not advertise\n * `tasks.requests.tools.call` — per spec a requestor MUST NOT task-augment\n * without matching receiver capability. Check `app.supportsTasks` first, and\n * fall back to `app.callTool`.\n */\nexport async function callToolAsTask<TOutput = unknown>(\n app: App,\n toolName: string,\n args?: unknown,\n options?: CallToolAsTaskOptions,\n): Promise<TaskHandle<TOutput>> {\n const deps = internalsFor(app);\n const hostTasks = deps.hostTasksCapability;\n if (!hostTasks?.requests?.tools?.call) {\n throw new HostCapabilityError(\n \"callToolAsTask\",\n `${TASKS_EXTENSION_ID} with requests.tools.call`,\n );\n }\n\n // Per spec, `task` is an object even when the caller provides no hints —\n // its presence is the signal to the receiver that augmentation is\n // requested. An empty `{}` is valid.\n const taskParam: { ttl?: number } = {};\n if (options?.ttl !== undefined) taskParam.ttl = options.ttl;\n\n // Build `tools/call` params. We layer our own shape on the SDK's\n // `CallToolRequest[\"params\"]` via `satisfies` so any rename upstream\n // (`name` → `toolName`, `arguments` → `args`, etc.) trips tsc.\n const callParams = {\n name: toolName,\n arguments: (args as Record<string, unknown> | undefined) ?? {},\n task: taskParam,\n } satisfies CallToolRequest[\"params\"];\n\n const raw = await deps.request(\n TOOLS_CALL_METHOD,\n callParams as unknown as Record<string, unknown>,\n );\n\n // Spec: task-augmented `tools/call` returns a `CreateTaskResult`. If a\n // receiver that advertised the capability returns a bare\n // `CallToolResult` instead, that's a protocol violation — surface it.\n const createResult = raw as CreateTaskResult | null | undefined;\n const initialTask = createResult?.task;\n if (!initialTask || typeof initialTask !== \"object\" || typeof initialTask.taskId !== \"string\") {\n throw new Error(\n \"callToolAsTask: receiver returned a response without `task` per CreateTaskResult \" +\n \"(expected shape: `{ task: { taskId, status, ... } }`). Receiver may not honor \" +\n \"the advertised tasks capability.\",\n );\n }\n\n const taskId = initialTask.taskId;\n\n // Preserve the Set-semantic dedup contract on `onStatus`: registering the\n // same callback twice collapses to one wire subscription, and either\n // returned unsub releases it. Without this, every `onStatus(cb)` would\n // create a fresh wrapper that the router treats as distinct.\n const localCallbacks = new Map<(task: Task) => void, () => void>();\n\n const handle: TaskHandle<TOutput> = {\n task: initialTask,\n\n async result(): Promise<ToolCallResult<TOutput>> {\n const params = { taskId } satisfies GetTaskPayloadRequest[\"params\"];\n const rawResult = await deps.request(\n TASKS_RESULT_METHOD,\n params as unknown as Record<string, unknown>,\n );\n // Per spec §: `tasks/result` returns exactly what the non-task\n // response would return. Parse through the shared tool-result\n // parser so `_meta[\"io.modelcontextprotocol/related-task\"]`\n // propagates unchanged (key-preserving spread).\n //\n // Type note: `GetTaskPayloadResult` is a union of result shapes\n // (one per augmentable request type). For `tools/call` tasks,\n // the runtime shape is `CallToolResult`, which `parseToolResult`\n // already handles.\n const typed = rawResult as GetTaskPayloadResult;\n return parseToolResult(typed) as ToolCallResult<TOutput>;\n },\n\n async refresh(): Promise<Task> {\n const params = { taskId } satisfies GetTaskRequest[\"params\"];\n const raw = await deps.request(\n TASKS_GET_METHOD,\n params as unknown as Record<string, unknown>,\n );\n // Per spec, `tasks/get` returns the task shape FLAT (taskId, status,\n // ttl, createdAt, lastUpdatedAt, ... at the top level) — NOT\n // wrapped in a `{ task }` field (unlike `CreateTaskResult`).\n return projectTask(raw as GetTaskResult);\n },\n\n async cancel(): Promise<Task> {\n const params = { taskId } satisfies CancelTaskRequest[\"params\"];\n const raw = await deps.request(\n TASKS_CANCEL_METHOD,\n params as unknown as Record<string, unknown>,\n );\n // `CancelTaskResult` is flat like `GetTaskResult`.\n return projectTask(raw as CancelTaskResult);\n },\n\n onStatus(cb) {\n // Idempotent-in-callback: if the same `cb` is already subscribed,\n // return the existing unsub.\n const existing = localCallbacks.get(cb);\n if (existing) return existing;\n\n // Merge the notification's spec-guaranteed fields (taskId, status,\n // statusMessage) with the handle's initial `CreateTaskResult.task`\n // so the consumer always sees a full valid `Task`. `lastUpdatedAt`\n // is stamped at SDK-receive time (an approximation of the host's\n // update time — the spec doesn't wire the host's timestamp through\n // the notification, so this is the closest signal we have).\n // `createdAt`, `ttl`, `pollInterval` come from the initial task\n // because they don't change over a task's lifetime.\n const wireUnsub = deps.taskRouter.subscribe(taskId, (update) => {\n const merged: Task = {\n taskId: update.taskId,\n status: update.status,\n ttl: initialTask.ttl,\n createdAt: initialTask.createdAt,\n lastUpdatedAt: new Date().toISOString(),\n ...(initialTask.pollInterval !== undefined && {\n pollInterval: initialTask.pollInterval,\n }),\n ...(update.statusMessage !== undefined && { statusMessage: update.statusMessage }),\n };\n cb(merged);\n });\n\n const unsub = () => {\n localCallbacks.delete(cb);\n wireUnsub();\n };\n localCallbacks.set(cb, unsub);\n return unsub;\n },\n };\n\n return handle;\n}\n\n// -----------------------------------------------------------------------------\n// Internal helpers\n// -----------------------------------------------------------------------------\n\n/**\n * Project a `GetTaskResult` / `CancelTaskResult` down to the canonical\n * `Task` shape. Both result types are structurally `Task` with an\n * optional `_meta` field on top; we project explicitly so consumers\n * don't see protocol-level `_meta` leaking onto the task state they\n * get back from `refresh()` / `cancel()`.\n *\n * Asymmetry note: `parseToolResult` (for `tools/call` / `tasks/result`\n * payloads) is key-preserving — `_meta` flows through end-to-end, which\n * matters for `io.modelcontextprotocol/related-task` correlation. Here\n * we drop `_meta` because no downstream consumer reads it on `Task` state\n * today. If a host starts stamping useful keys on `tasks/get`/`tasks/cancel`\n * responses, switch to a key-preserving projection.\n */\nfunction projectTask(raw: GetTaskResult | CancelTaskResult): Task {\n return {\n taskId: raw.taskId,\n status: raw.status,\n ttl: raw.ttl,\n createdAt: raw.createdAt,\n lastUpdatedAt: raw.lastUpdatedAt,\n ...(raw.pollInterval !== undefined && { pollInterval: raw.pollInterval }),\n ...(raw.statusMessage !== undefined && { statusMessage: raw.statusMessage }),\n };\n}\n","import type { ToolResultData } from \"./types.js\";\n\nexport type { ToolResultData };\n\n/**\n * Parse inbound `ui/notifications/tool-result` notification params into\n * a consistent `ToolResultData` shape.\n *\n * Implements the 5-step parsing algorithm from the RFC:\n * 1. If `params.structuredContent` exists → use it as content.\n * 2. Else if `params.content` is an array of `{type:\"text\", text}` blocks →\n * join the text values and try JSON.parse.\n * 3. Else if `params.content` is a string → try JSON.parse.\n * 4. If JSON.parse fails in steps 2 or 3 → deliver the raw string.\n * 5. Return `{ content, structuredContent, raw }`.\n */\nexport function parseToolResultParams(params: Record<string, unknown> | undefined): ToolResultData {\n const raw = params ?? {};\n const structuredContent = raw.structuredContent ?? null;\n\n // Step 1: If structuredContent exists, use it as content\n if (structuredContent != null) {\n return { content: structuredContent, structuredContent, raw };\n }\n\n const rawContent = raw.content;\n\n // Step 2: If content is array of {type:\"text\", text} blocks, join texts and try JSON.parse\n if (Array.isArray(rawContent)) {\n const texts = rawContent\n .filter(\n (block: unknown) =>\n block != null &&\n typeof block === \"object\" &&\n (block as Record<string, unknown>).type === \"text\" &&\n typeof (block as Record<string, unknown>).text === \"string\",\n )\n .map((block: unknown) => (block as Record<string, unknown>).text as string);\n\n if (texts.length > 0) {\n const joined = texts.join(\"\");\n try {\n return { content: JSON.parse(joined), structuredContent: null, raw };\n } catch {\n return { content: joined, structuredContent: null, raw };\n }\n }\n\n // No text blocks — return raw content array\n return { content: rawContent, structuredContent: null, raw };\n }\n\n // Step 3: If content is string, try JSON.parse\n if (typeof rawContent === \"string\") {\n try {\n return { content: JSON.parse(rawContent), structuredContent: null, raw };\n } catch {\n return { content: rawContent, structuredContent: null, raw };\n }\n }\n\n // Fallback: return content as-is (could be null, object, etc.)\n return { content: rawContent ?? null, structuredContent: null, raw };\n}\n","import { KEYDOWN_METHOD } from \"./event-map.js\";\nimport type { KeyForwardConfig } from \"./types.js\";\n\n/** Send a notification to the host. */\ntype SendFn = (method: string, params: Record<string, unknown>) => void;\n\n/**\n * Forward keyboard shortcuts from the iframe document to the host.\n *\n * By default, forwards all Ctrl/Cmd+key combos and Escape.\n * Apps can customize via `forwardKeys` config.\n */\nexport class KeyboardForwarder {\n private listener: (event: KeyboardEvent) => void;\n private destroyed = false;\n\n constructor(send: SendFn, customKeys?: KeyForwardConfig[]) {\n const config = customKeys ?? null; // null = default behavior\n\n this.listener = (event: KeyboardEvent) => {\n if (this.destroyed) return;\n if (this.shouldForward(event, config)) {\n event.preventDefault();\n send(KEYDOWN_METHOD, {\n key: event.key,\n ctrlKey: event.ctrlKey,\n metaKey: event.metaKey,\n shiftKey: event.shiftKey,\n altKey: event.altKey,\n });\n }\n };\n\n document.addEventListener(\"keydown\", this.listener);\n }\n\n destroy(): void {\n if (this.destroyed) return;\n this.destroyed = true;\n document.removeEventListener(\"keydown\", this.listener);\n }\n\n private shouldForward(event: KeyboardEvent, config: KeyForwardConfig[] | null): boolean {\n // Empty array = forwarding disabled\n if (config && config.length === 0) return false;\n\n // Custom config: match exactly\n if (config) {\n return config.some(\n (k) =>\n event.key.toLowerCase() === k.key.toLowerCase() &&\n (k.ctrl === undefined || event.ctrlKey === k.ctrl) &&\n (k.meta === undefined || event.metaKey === k.meta) &&\n (k.shift === undefined || event.shiftKey === k.shift) &&\n (k.alt === undefined || event.altKey === k.alt),\n );\n }\n\n // Default: forward all Ctrl/Cmd combos + Escape,\n // EXCEPT clipboard shortcuts (c, v, x, a) which the browser must handle natively.\n if (event.key === \"Escape\") return true;\n if (event.ctrlKey || event.metaKey) {\n const key = event.key.toLowerCase();\n if (key === \"c\" || key === \"v\" || key === \"x\" || key === \"a\") return false;\n return true;\n }\n return false;\n }\n}\n","import { SIZE_CHANGED_METHOD } from \"@modelcontextprotocol/ext-apps\";\n\ntype SendFn = (method: string, params: Record<string, unknown>) => void;\n\ninterface Resizer {\n resize(width?: number, height?: number): void;\n measureAndSend(): void;\n destroy(): void;\n}\n\nexport function createResizer(send: SendFn, autoResize: boolean): Resizer {\n let destroyed = false;\n let observer: ResizeObserver | null = null;\n let rafId: number | null = null;\n\n function measureAndSend(): void {\n if (destroyed) return;\n const width = document.body.scrollWidth;\n const height = document.body.scrollHeight;\n send(SIZE_CHANGED_METHOD, { width, height });\n }\n\n function resize(width?: number, height?: number): void {\n if (destroyed) return;\n if (width !== undefined && height !== undefined) {\n send(SIZE_CHANGED_METHOD, { width, height });\n } else {\n measureAndSend();\n }\n }\n\n // Auto mode: attach ResizeObserver, debounced at 16ms via requestAnimationFrame\n if (autoResize && typeof ResizeObserver !== \"undefined\") {\n observer = new ResizeObserver(() => {\n if (destroyed) return;\n if (rafId !== null) cancelAnimationFrame(rafId);\n rafId = requestAnimationFrame(() => {\n rafId = null;\n measureAndSend();\n });\n });\n observer.observe(document.body);\n }\n\n function destroy(): void {\n if (destroyed) return;\n destroyed = true;\n if (rafId !== null) cancelAnimationFrame(rafId);\n observer?.disconnect();\n observer = null;\n }\n\n return { resize, measureAndSend, destroy };\n}\n","import type {\n AppEventMap,\n AppNotification,\n AppRequest,\n McpUiHostCapabilities,\n McpUiHostContext,\n McpUiInitializeRequest,\n McpUiMessageRequest,\n McpUiOpenLinkRequest,\n McpUiUpdateModelContextRequest,\n} from \"@modelcontextprotocol/ext-apps\";\nimport {\n applyHostFonts,\n App as ExtAppsApp,\n HOST_CONTEXT_CHANGED_METHOD,\n RESOURCE_TEARDOWN_METHOD,\n TOOL_CANCELLED_METHOD,\n TOOL_INPUT_METHOD,\n TOOL_INPUT_PARTIAL_METHOD,\n TOOL_RESULT_METHOD,\n} from \"@modelcontextprotocol/ext-apps\";\nimport type { RequestOptions } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n CallToolRequest,\n ReadResourceRequest,\n ReadResourceResult,\n TextContent,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { CallToolResultSchema, ResultSchema } from \"@modelcontextprotocol/sdk/types.js\";\n\nimport { parseToolResultParams } from \"./content-parser.js\";\nimport { extractHostFontCss, extractTheme } from \"./detection.js\";\nimport { HostCapabilityError } from \"./errors.js\";\nimport { NIMBLEBRAIN_EXTENSIONS, resolveEventMethod, TOOLS_CALL_METHOD } from \"./event-map.js\";\nimport { registerInternals } from \"./internals.js\";\nimport { KeyboardForwarder } from \"./keyboard.js\";\nimport { createResizer } from \"./resize.js\";\nimport { parseToolResult } from \"./result-parser.js\";\nimport { createTaskStatusRouter, readHostTasksCapability } from \"./task-handle.js\";\nimport { applyTheme } from \"./theme-defaults.js\";\nimport type {\n App,\n ConnectOptions,\n Dimensions,\n TasksCapability,\n Theme,\n ToolCallResult,\n} from \"./types.js\";\n\n/**\n * The host name that identifies a NimbleBrain host in the handshake. Identity\n * only: the NimbleBrain host extensions are gated on the host declaring each one.\n */\nconst NIMBLEBRAIN_HOST = \"nimblebrain\";\n\n/** The `_meta` key a `ui/message` text block carries the NimbleBrain chat context under. */\nconst CHAT_CONTEXT_META_KEY = \"ai.nimblebrain/context\";\n\n/**\n * Requests this SDK sends carry no deadline.\n *\n * The MCP SDK gives every request a 60-second one, which is wrong for all three\n * kinds of request an app makes: a file picker waits on a person, `tasks/result`\n * blocks until the task finishes, and a tool call takes as long as the tool\n * takes. A deadline here would reject a call the host is still working on, and\n * the app would report a failure that did not happen.\n *\n * `Infinity` is not usable — `setTimeout` coerces it to `0` and the timer fires\n * immediately — so this is the largest delay a browser timer accepts, about 24\n * days.\n */\nconst NO_DEADLINE: RequestOptions = { timeout: 2_147_483_647 };\n\n/**\n * The events `App` models, paired with the wire method each one carries.\n *\n * Every one is registered exactly once, before the handshake, and fans out to\n * this SDK's own subscribers underneath. Two reasons it has to be this way: a\n * second registration for the same method through the `on*` setters throws, and\n * `App` warns when a handler for a one-shot event (the tool ones) is registered\n * after `connect()` resolves, which is when every hook subscribes.\n */\nconst MAPPED_EVENTS = [\n [\"toolinput\", TOOL_INPUT_METHOD],\n [\"toolinputpartial\", TOOL_INPUT_PARTIAL_METHOD],\n [\"toolresult\", TOOL_RESULT_METHOD],\n [\"toolcancelled\", TOOL_CANCELLED_METHOD],\n] as const satisfies ReadonlyArray<readonly [keyof AppEventMap, string]>;\n\n/**\n * Connect to an MCP Apps host.\n *\n * The one entry point. The protocol underneath is the spec's own client,\n * `@modelcontextprotocol/ext-apps`'s `App`: it owns the transport, the\n * handshake and the wire schemas. What this adds is the framework on top —\n * theme injection, the parsed payloads, multi-subscriber events, resize, and\n * the NimbleBrain extensions — and it resolves to a ready {@link App}.\n *\n * The `App` it returns stays deliberately small. NimbleBrain's own extensions\n * (`action`, the file picker), `downloadFile` and the MCP tasks utility are\n * composable functions over it — import them from the package root.\n */\nexport async function connect(options: ConnectOptions): Promise<App> {\n const { name, version, autoResize = false, forwardKeys } = options;\n\n let destroyed = false;\n\n // --- Mutable state ---\n //\n // The host context lives in `App`, which merges each delta into it, so it is\n // read back rather than copied. `theme` is a derived view of it.\n let hostInfo: { name: string; version: string } = { name: \"unknown\", version: \"unknown\" };\n let isNimbleBrainHost = false;\n let toolInfo: { tool: Record<string, unknown> } | null = null;\n let containerDimensions: Dimensions | null = null;\n let hostCapabilities: McpUiHostCapabilities = {};\n let hostTasksCapability: TasksCapability | undefined;\n let keyboard: KeyboardForwarder | null = null;\n\n // The theme currently applied to the document. Tracked rather than derived at\n // dispatch time, because `App` merges a host-context delta into the context it\n // holds *before* it calls listeners — so by the time this SDK hears about a\n // change, \"the theme before it\" is no longer recoverable from the context.\n // Comparing against what is actually loaded is also the honest question: the\n // filter exists to skip a re-render when nothing visible moved.\n let appliedTheme: Theme = { mode: \"light\", tokens: {} };\n\n // `appCapabilities` is typed as `McpUiAppCapabilities` by the ext-apps spec\n // package, which does not yet model the MCP 2025-11-25 tasks utility. We\n // extend structurally via `TasksCapability` and `satisfies` the extension so\n // the nested objects match the spec literally — empty objects `{}` as\n // presence flags, NOT booleans.\n const appCapabilities = {\n tasks: {\n cancel: {},\n requests: { tools: { call: {} } },\n } satisfies TasksCapability,\n };\n\n // `autoResize` is handed to `App`, which observes the document and reports\n // size after the handshake. Ours must not observe as well: two observers mean\n // two `size-changed` streams for one document.\n const client = new ExtAppsApp(\n { name, version },\n appCapabilities as unknown as McpUiInitializeRequest[\"params\"][\"appCapabilities\"],\n { autoResize },\n );\n\n function currentContext(): McpUiHostContext {\n return client.getHostContext() ?? {};\n }\n\n /**\n * The theme as reported to consumers, derived from the context. Every public\n * view goes through here — the `theme` getter, the `theme-changed` payload,\n * and its equality filter — so they cannot disagree with each other or with\n * what is actually applied.\n */\n function resolveTheme(): Theme {\n return extractTheme(currentContext());\n }\n\n /**\n * Load the host's `@font-face` CSS (`styles.css.fonts`) into the document.\n *\n * The spec's helper injects it once and leaves it in place, so a later\n * host-context change that carries no `css` — a theme toggle, say — keeps the\n * host's typeface loaded rather than unloading it.\n */\n function applyFontsFrom(ctx: Partial<McpUiHostContext> | undefined): void {\n const css = extractHostFontCss(ctx);\n if (css !== undefined && typeof document !== \"undefined\") applyHostFonts(css);\n }\n\n /** Apply the current theme to the document, and record what was applied. */\n function applyResolvedTheme(): Theme {\n const theme = resolveTheme();\n applyTheme(theme.mode, theme.tokens);\n appliedTheme = theme;\n return theme;\n }\n\n // --- Event handlers ---\n //\n // Generic wire methods share one registry keyed by method. The two events\n // that are a *view* over a wire message rather than the message itself\n // (theme, host context) get their own sets, because they ride the same\n // notification and hand their subscribers different payloads.\n const handlers = new Map<string, Set<(params: unknown) => void>>();\n const themeCallbacks = new Set<(theme: Theme) => void>();\n const hostContextCallbacks = new Set<(ctx: McpUiHostContext) => void>();\n\n /** Deliver a payload to everyone subscribed to a wire method. */\n function fanOut(method: string, payload: unknown): void {\n const set = handlers.get(method);\n if (!set) return;\n for (const handler of set) handler(payload);\n }\n\n /**\n * Send a notification `App` does not model. The NimbleBrain host extensions have\n * no spec equivalent and so no place in its notification union; the cast is\n * the one place that is admitted, and the method still comes from a constant\n * rather than a literal spelled at the call site.\n */\n function sendRaw(method: string, params?: Record<string, unknown>): void {\n if (destroyed) return;\n void client\n .notification({ method, params } as unknown as AppNotification)\n // A closed transport is the ordinary way this rejects, during teardown.\n .catch(() => {});\n }\n\n /** Send a request `App` does not model, and resolve with the host's result. */\n function requestRaw(method: string, params?: Record<string, unknown>): Promise<unknown> {\n return client.request({ method, params } as unknown as AppRequest, ResultSchema, NO_DEADLINE);\n }\n\n // --- Route what the host sends ---\n //\n // Registered before `connect()`, so a notification the host sends the instant\n // the handshake completes is already routed.\n\n for (const [event, method] of MAPPED_EVENTS) {\n client.addEventListener(event, (params) => {\n if (destroyed) return;\n // `tool-result` is delivered parsed — the payload every subscriber gets,\n // however they subscribed — because the wire shape is three shapes and\n // picking between them is work each app would otherwise repeat.\n fanOut(\n method,\n method === TOOL_RESULT_METHOD\n ? parseToolResultParams(params as Record<string, unknown>)\n : params,\n );\n });\n }\n\n client.addEventListener(\"hostcontextchanged\", (params) => {\n if (destroyed) return;\n const prevTheme = appliedTheme;\n\n // `App` has already merged this delta into the context it holds — shallowly,\n // which is what the spec asks for: `styles.variables` is a complete map when\n // the host sends one, so a deep merge would leave a host no way to remove a\n // variable. Fonts are read from the delta as sent, because a merged\n // context loses `styles.css` whenever the host sends `styles.variables`\n // alone.\n applyFontsFrom(params as Partial<McpUiHostContext>);\n const nextTheme = applyResolvedTheme();\n\n // Subscribers to the short event get the merged snapshot, because that is\n // what `app.hostContext` means and a delta cannot distinguish an omitted\n // field from a cleared one. A caller who genuinely wants the notification as\n // sent subscribes to the wire method instead, which is passed through\n // untouched.\n const merged = currentContext();\n for (const cb of hostContextCallbacks) cb(merged);\n fanOut(HOST_CONTEXT_CHANGED_METHOD, params);\n // Theme subscribers see only real theme movement: a host-context change\n // that leaves the derived theme identical (a workspace switch, say) must\n // not re-render every themed component in the app.\n if (!themesEqual(prevTheme, nextTheme)) {\n for (const cb of themeCallbacks) cb(nextTheme);\n }\n });\n\n // Teardown is a *request* in the spec, not a notification: the host asks, and\n // the view is expected to answer. Subscribers see it as the `teardown` event;\n // answering it is this SDK's job, not theirs.\n client.onteardown = (params) => {\n if (!destroyed) fanOut(RESOURCE_TEARDOWN_METHOD, params);\n return {};\n };\n\n // Everything else the host sends: vendor extension notifications, the server's\n // `notifications/resources/list_changed`, and `notifications/tasks/status`.\n // `App` routes a notification here when no typed handler claims its method,\n // and one handler with a fan-out under it is the only safe shape —\n // registering a second handler for a method would silently replace the first.\n client.fallbackNotificationHandler = async (notification) => {\n if (destroyed) return;\n fanOut(notification.method, notification.params);\n };\n\n /** Register one handler and return its unsubscribe. */\n function subscribe(event: string, handler: (params: any) => void): () => void {\n switch (event) {\n case \"theme-changed\":\n themeCallbacks.add(handler);\n return () => {\n themeCallbacks.delete(handler);\n };\n case \"host-context-changed\":\n hostContextCallbacks.add(handler);\n return () => {\n hostContextCallbacks.delete(handler);\n };\n default: {\n const method = resolveEventMethod(event);\n if (!handlers.has(method)) handlers.set(method, new Set());\n handlers.get(method)?.add(handler);\n return () => {\n const set = handlers.get(method);\n if (set) {\n set.delete(handler);\n if (set.size === 0) handlers.delete(method);\n }\n };\n }\n }\n }\n\n // Handlers from `options.on` are registered before the handshake goes out, so\n // a tool result the host sends in the same turn as `initialized` is not lost.\n if (options.on) {\n for (const [event, handler] of Object.entries(options.on)) {\n if (typeof handler === \"function\") subscribe(event, handler);\n }\n }\n\n // --- The handshake: `ui/initialize`, then `initialized` ---\n await client.connect();\n\n const hostVersion = client.getHostVersion();\n hostInfo = {\n name: hostVersion?.name ?? \"unknown\",\n version: hostVersion?.version ?? \"unknown\",\n };\n isNimbleBrainHost = hostInfo.name === NIMBLEBRAIN_HOST;\n\n // Everything an app may ask of the host is decided here, once: each method\n // below and each helper beside `App` checks the declaration before sending.\n hostCapabilities = client.getHostCapabilities() ?? {};\n hostTasksCapability = readHostTasksCapability(hostCapabilities);\n\n const initialContext = client.getHostContext();\n if (initialContext) {\n if (initialContext.toolInfo && typeof initialContext.toolInfo === \"object\") {\n toolInfo = {\n tool: (initialContext.toolInfo.tool as unknown as Record<string, unknown>) ?? {},\n };\n }\n if (\n initialContext.containerDimensions &&\n typeof initialContext.containerDimensions === \"object\"\n ) {\n containerDimensions = initialContext.containerDimensions as Dimensions;\n }\n\n // Inject the theme into the DOM: the host's values go inline, and the\n // neutral defaults for the mode go in a cascade layer, where they back any\n // var nobody declares and lose to every var that is declared. The host's\n // `@font-face` CSS loads alongside — a token names a family, it cannot load\n // one.\n applyFontsFrom(initialContext);\n applyResolvedTheme();\n }\n\n // Keyboard forwarding is a NimbleBrain extension. Forwarding to a host that\n // did not declare it would `preventDefault` a key for a host that does\n // nothing with it, so the gate is on the declaration, not just the option.\n if (\n forwardKeys &&\n hostCapabilities.experimental?.[NIMBLEBRAIN_EXTENSIONS.keydown.capability] !== undefined\n ) {\n keyboard = new KeyboardForwarder(sendRaw, forwardKeys === true ? undefined : forwardKeys);\n }\n\n // The resizer serves `app.resize()`. It never observes: under `autoResize`\n // that is `App`'s job, and it has already reported the first size.\n const resizer = createResizer(sendRaw, false);\n if (!autoResize) resizer.measureAndSend();\n\n // Shared router for `notifications/tasks/status`. Created eagerly so the\n // subscription registers exactly once — every `TaskHandle` filters off this\n // single wire subscription by taskId.\n const taskRouter = createTaskStatusRouter((method, handler) =>\n subscribe(method, handler as (params: any) => void),\n );\n\n // --- The App this SDK hands out ---\n const app: App = {\n get theme() {\n return resolveTheme();\n },\n get hostInfo() {\n return { ...hostInfo };\n },\n get hostContext() {\n return currentContext();\n },\n get hostCapabilities() {\n return hostCapabilities;\n },\n get isNimbleBrainHost() {\n return isNimbleBrainHost;\n },\n get toolInfo() {\n return toolInfo;\n },\n get containerDimensions() {\n return containerDimensions;\n },\n get destroyed() {\n return destroyed;\n },\n get supportsTasks() {\n return hostTasksCapability?.requests?.tools?.call !== undefined;\n },\n\n on(event: string, handler: (params: any) => void): () => void {\n return subscribe(event, handler);\n },\n\n resize(width?: number, height?: number): void {\n resizer.resize(width, height);\n },\n\n openLink(url: string): void {\n if (destroyed) return;\n if (!hostCapabilities.openLinks) {\n window.open(url, \"_blank\", \"noopener\");\n return;\n }\n const params: McpUiOpenLinkRequest[\"params\"] = { url };\n client.openLink(params, NO_DEADLINE).catch(() => {\n // The host refused or does not serve it: open directly instead.\n window.open(url, \"_blank\", \"noopener\");\n });\n },\n\n updateModelContext(state: Record<string, unknown>, summary?: string): void {\n if (destroyed || !hostCapabilities.updateModelContext) return;\n const params: McpUiUpdateModelContextRequest[\"params\"] = {\n structuredContent: state,\n ...(summary !== undefined && {\n content: [{ type: \"text\", text: summary } satisfies TextContent],\n }),\n };\n client.updateModelContext(params, NO_DEADLINE).catch(() => {});\n },\n\n async callTool<TOutput = unknown>(\n toolName: string,\n args?: Record<string, unknown>,\n ): Promise<ToolCallResult<TOutput>> {\n if (!hostCapabilities.serverTools) {\n throw new HostCapabilityError(\"callTool\", \"serverTools\");\n }\n // No target. A host scopes an app's call to the server that mounted it,\n // so `params` carries what the spec names and nothing else.\n const params: CallToolRequest[\"params\"] = {\n name: toolName,\n arguments: args ?? {},\n };\n // Sent through the generic request path rather than `callServerTool`,\n // which asks for a progress token: that puts `_meta.progressToken` on\n // every call, and nothing here subscribes to progress. The result is\n // validated against the spec's schema either way.\n const raw = await client.request(\n { method: TOOLS_CALL_METHOD, params },\n CallToolResultSchema,\n NO_DEADLINE,\n );\n return parseToolResult(raw) as ToolCallResult<TOutput>;\n },\n\n async readServerResource(params: ReadResourceRequest[\"params\"]): Promise<ReadResourceResult> {\n if (!hostCapabilities.serverResources) {\n throw new HostCapabilityError(\"readServerResource\", \"serverResources\");\n }\n return await client.readServerResource(params, NO_DEADLINE);\n },\n\n sendMessage(text: string, context?: { action?: string; entity?: string }): void {\n if (destroyed || !hostCapabilities.message) return;\n const textBlock: TextContent = {\n type: \"text\",\n text,\n // The chat context is a NimbleBrain host field; other hosts ignore it,\n // but there is no reason to spend the bytes off one.\n ...(isNimbleBrainHost && context && { _meta: { [CHAT_CONTEXT_META_KEY]: context } }),\n };\n const params: McpUiMessageRequest[\"params\"] = {\n role: \"user\",\n content: [textBlock],\n };\n client.sendMessage(params, NO_DEADLINE).catch(() => {});\n },\n\n destroy(): void {\n if (destroyed) return;\n destroyed = true;\n keyboard?.destroy();\n resizer.destroy();\n taskRouter.dispose();\n handlers.clear();\n themeCallbacks.clear();\n hostContextCallbacks.clear();\n void client.close();\n },\n };\n\n registerInternals(app, {\n send(method, params) {\n sendRaw(method, params);\n },\n request(method, params) {\n return requestRaw(method, params);\n },\n onMessage(method, handler) {\n return subscribe(method, handler as (params: any) => void);\n },\n taskRouter,\n get hostTasksCapability() {\n return hostTasksCapability;\n },\n });\n\n return app;\n}\n\n/**\n * Shallow equality for `Theme` — used to filter host-context changes that\n * don't actually move the theme (e.g. a workspace switch that leaves\n * theme/styles untouched). Cheap; tokens are ~40 entries.\n */\nfunction themesEqual(a: Theme, b: Theme): boolean {\n if (a.mode !== b.mode) return false;\n const aKeys = Object.keys(a.tokens);\n const bKeys = Object.keys(b.tokens);\n if (aKeys.length !== bKeys.length) return false;\n // Iterating only over `a`'s keys is sufficient: under equal length, any key\n // in `a` missing from `b` reads `b[k] === undefined`, which fails the strict\n // inequality check. Symmetric difference is covered.\n for (const k of aKeys) {\n if (a.tokens[k] !== b.tokens[k]) return false;\n }\n return true;\n}\n","/**\n * NimbleBrain host extensions — composable functions over {@link App}.\n *\n * These are not ext-apps spec surface. They are the NimbleBrain host's own\n * `ai.nimblebrain/*` methods, which this package implements a client for, and\n * `NIMBLEBRAIN_EXTENSIONS` in `event-map.ts` is the complete list. They\n * live here rather than on the `App` object so the object stays the spec\n * surface plus the handshake state, and so an app that never picks a file\n * never pulls this code in.\n *\n * Every one of them is gated on the host declaring it in `ui/initialize`: where\n * it is not declared, the fire-and-forget ones are no-ops and the ones with a\n * return value throw `HostCapabilityError`, because a picker that silently\n * resolves `null` forever is worse than one that says it isn't there.\n * `keydown` has no function here; `connect({ forwardKeys })` applies the same\n * gate.\n */\nimport { HostCapabilityError } from \"./errors.js\";\nimport { NIMBLEBRAIN_EXTENSIONS, type NimbleBrainExtension } from \"./event-map.js\";\nimport { internalsFor } from \"./internals.js\";\nimport type { App, FileResult, RequestFileOptions } from \"./types.js\";\n\n/**\n * Whether the host declared a NimbleBrain extension. Use it to decide what to\n * offer, e.g. to hide an upload button on a host with no file picker.\n */\nexport function hostSupports(app: App, extension: NimbleBrainExtension): boolean {\n const { capability } = NIMBLEBRAIN_EXTENSIONS[extension];\n return app.hostCapabilities.experimental?.[capability] !== undefined;\n}\n\n/** 25 MB — the host's default cap on a single picked file. */\nconst DEFAULT_MAX_FILE_SIZE = 26_214_400;\n\n/**\n * Trigger a host-side action.\n *\n * Sends a command *to* the host (navigate, open a panel). A no-op when the host\n * did not declare `ai.nimblebrain/action`.\n */\nexport function action(app: App, name: string, params?: Record<string, unknown>): void {\n if (!hostSupports(app, \"action\")) return;\n internalsFor(app).send(NIMBLEBRAIN_EXTENSIONS.action.method, { action: name, ...params });\n}\n\n/**\n * Request one file from the user via the host's native file picker.\n *\n * Resolves `null` if the user cancels. Rejects with `HostCapabilityError` when\n * the host did not declare `ai.nimblebrain/request-file`.\n */\nexport async function pickFile(app: App, options?: RequestFileOptions): Promise<FileResult | null> {\n requireRequestFile(\"pickFile\", app);\n const files = await requestFile(app, options, false);\n // One pick, so the first entry is the answer; an empty list is a cancel.\n return files[0] ?? null;\n}\n\n/**\n * Request several files from the user.\n *\n * Resolves `[]` if the user cancels. Rejects with `HostCapabilityError` when\n * the host did not declare `ai.nimblebrain/request-file`.\n */\nexport async function pickFiles(app: App, options?: RequestFileOptions): Promise<FileResult[]> {\n requireRequestFile(\"pickFiles\", app);\n return await requestFile(app, options, true);\n}\n\nfunction requireRequestFile(feature: string, app: App): void {\n if (!hostSupports(app, \"requestFile\")) {\n throw new HostCapabilityError(feature, NIMBLEBRAIN_EXTENSIONS.requestFile.capability);\n }\n}\n\n/**\n * Shared request path for `pickFile` / `pickFiles`.\n *\n * The host answers with `{ files }` — an empty array when the user cancelled.\n * A JSON-RPC result is an object by definition, and MCP types it as one, so the\n * files travel under a field rather than as a bare array or a bare `null`: a\n * spec client refuses to parse anything else, and the call would hang rather\n * than resolve.\n *\n * Entries are shape-checked here. The type promises a string `id`, and without\n * the guard a consumer reads `undefined.id` three frames later, where nothing\n * says which side is mismatched.\n */\nasync function requestFile(\n app: App,\n options: RequestFileOptions | undefined,\n multiple: boolean,\n): Promise<FileResult[]> {\n const result = await internalsFor(app).request(NIMBLEBRAIN_EXTENSIONS.requestFile.method, {\n accept: options?.accept,\n maxSize: options?.maxSize ?? DEFAULT_MAX_FILE_SIZE,\n multiple,\n });\n const files = (result as { files?: unknown } | null | undefined)?.files;\n if (files === undefined) {\n throw new Error(\n \"ai.nimblebrain/request-file returned no `files`. The host is older than this \" +\n \"SDK targets: it answers the picker with a bare array or `null`, which \" +\n \"a spec-compliant client cannot parse.\",\n );\n }\n if (!Array.isArray(files)) {\n throw new Error(\"ai.nimblebrain/request-file returned a `files` field that is not an array.\");\n }\n return files.map(validateFileResult);\n}\n\nfunction validateFileResult(value: unknown): FileResult {\n if (\n typeof value !== \"object\" ||\n value === null ||\n typeof (value as { id?: unknown }).id !== \"string\"\n ) {\n throw new Error(\n \"ai.nimblebrain/request-file returned a result without a string `id`. \" +\n \"The host appears to be on a version older than this SDK targets — \" +\n \"@nimblebrain/synapse 0.8.0+ requires a host with POST /v1/resources \" +\n \"(NimbleBrain ≥ the version that ships PR #93).\",\n );\n }\n return value as FileResult;\n}\n"]}
|
|
@@ -1,11 +1,20 @@
|
|
|
1
|
-
import { applyTheme,
|
|
1
|
+
import { applyTheme, extractHostFontCss } from './chunk-DJS2FKBN.js';
|
|
2
2
|
|
|
3
3
|
// src/host/theme.ts
|
|
4
4
|
function applyHostTheme(theme) {
|
|
5
5
|
if (typeof document !== "undefined") {
|
|
6
6
|
document.documentElement.setAttribute("data-theme", theme.mode);
|
|
7
7
|
}
|
|
8
|
-
applyTheme(theme.mode, theme.tokens
|
|
8
|
+
applyTheme(theme.mode, theme.tokens);
|
|
9
|
+
}
|
|
10
|
+
var HOST_FONTS_STYLE_ID = "__mcp-host-fonts";
|
|
11
|
+
function injectHostFonts(css) {
|
|
12
|
+
if (typeof document === "undefined") return;
|
|
13
|
+
if (document.getElementById(HOST_FONTS_STYLE_ID)) return;
|
|
14
|
+
const style = document.createElement("style");
|
|
15
|
+
style.id = HOST_FONTS_STYLE_ID;
|
|
16
|
+
style.textContent = css;
|
|
17
|
+
document.head.appendChild(style);
|
|
9
18
|
}
|
|
10
19
|
function preferredMode(win) {
|
|
11
20
|
try {
|
|
@@ -25,13 +34,27 @@ var HostUnsupportedError = class extends Error {
|
|
|
25
34
|
this.name = "HostUnsupportedError";
|
|
26
35
|
}
|
|
27
36
|
};
|
|
37
|
+
var ToolCallError = class extends Error {
|
|
38
|
+
result;
|
|
39
|
+
constructor(name, result) {
|
|
40
|
+
super(toolErrorText(result) ?? `tool "${name}" returned an error`);
|
|
41
|
+
this.name = "ToolCallError";
|
|
42
|
+
this.result = result;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
function toolErrorText(result) {
|
|
46
|
+
const content = result?.content;
|
|
47
|
+
if (!Array.isArray(content)) return void 0;
|
|
48
|
+
for (const block of content) {
|
|
49
|
+
const b = block;
|
|
50
|
+
if (b?.type === "text" && typeof b.text === "string" && b.text !== "") return b.text;
|
|
51
|
+
}
|
|
52
|
+
return void 0;
|
|
53
|
+
}
|
|
54
|
+
function isToolError(result) {
|
|
55
|
+
return result != null && typeof result === "object" && result.isError === true;
|
|
56
|
+
}
|
|
28
57
|
var SYNAPSE_DATA_ELEMENT_ID = "synapse-ui-data";
|
|
29
|
-
var MCPUI_READY = "ui-lifecycle-iframe-ready";
|
|
30
|
-
var MCPUI_RENDER_DATA = "ui-lifecycle-iframe-render-data";
|
|
31
|
-
var MCPUI_SIZE_CHANGE = "ui-size-change";
|
|
32
|
-
var MCPUI_LINK = "link";
|
|
33
|
-
var MCPUI_PROMPT = "prompt";
|
|
34
|
-
var OPENAI_SET_GLOBALS = "openai:set_globals";
|
|
35
58
|
var MCPAPP_PROTOCOL_VERSION = "2026-01-26";
|
|
36
59
|
var MCPAPP_INITIALIZE = "ui/initialize";
|
|
37
60
|
var MCPAPP_INITIALIZED = "ui/notifications/initialized";
|
|
@@ -43,84 +66,6 @@ var MCPAPP_MESSAGE = "ui/message";
|
|
|
43
66
|
var MCPAPP_TEARDOWN = "ui/resource-teardown";
|
|
44
67
|
var MCP_TOOLS_CALL = "tools/call";
|
|
45
68
|
|
|
46
|
-
// src/host/adapters/chatgpt.ts
|
|
47
|
-
function createChatGPTAdapter(win, _options) {
|
|
48
|
-
const openai = () => win.openai;
|
|
49
|
-
let currentData = openai()?.toolOutput ?? null;
|
|
50
|
-
let currentTheme = {
|
|
51
|
-
mode: coerceMode(openai()?.theme, "light"),
|
|
52
|
-
tokens: {}
|
|
53
|
-
};
|
|
54
|
-
const dataCbs = /* @__PURE__ */ new Set();
|
|
55
|
-
const themeCbs = /* @__PURE__ */ new Set();
|
|
56
|
-
let destroyed = false;
|
|
57
|
-
const onSetGlobals = (event) => {
|
|
58
|
-
if (destroyed) return;
|
|
59
|
-
const globals = event.detail?.globals;
|
|
60
|
-
if (!globals) return;
|
|
61
|
-
if ("toolOutput" in globals && globals.toolOutput != null) {
|
|
62
|
-
currentData = globals.toolOutput;
|
|
63
|
-
for (const cb of dataCbs) cb(currentData);
|
|
64
|
-
}
|
|
65
|
-
if ("theme" in globals && globals.theme != null) {
|
|
66
|
-
const mode = coerceMode(globals.theme, currentTheme.mode);
|
|
67
|
-
if (mode !== currentTheme.mode) {
|
|
68
|
-
currentTheme = { mode, tokens: {} };
|
|
69
|
-
for (const cb of themeCbs) cb(currentTheme);
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
};
|
|
73
|
-
return {
|
|
74
|
-
host: "chatgpt",
|
|
75
|
-
getData: () => currentData,
|
|
76
|
-
onData(cb) {
|
|
77
|
-
dataCbs.add(cb);
|
|
78
|
-
return () => dataCbs.delete(cb);
|
|
79
|
-
},
|
|
80
|
-
getTheme: () => currentTheme,
|
|
81
|
-
onTheme(cb) {
|
|
82
|
-
themeCbs.add(cb);
|
|
83
|
-
return () => themeCbs.delete(cb);
|
|
84
|
-
},
|
|
85
|
-
async callTool(name, args) {
|
|
86
|
-
const call = openai()?.callTool;
|
|
87
|
-
if (!call) throw new HostUnsupportedError("callTool", "chatgpt");
|
|
88
|
-
return await call(name, args ?? {});
|
|
89
|
-
},
|
|
90
|
-
sendPrompt(text) {
|
|
91
|
-
const o = openai();
|
|
92
|
-
const send = o?.sendFollowUpMessage ?? o?.sendFollowupMessage;
|
|
93
|
-
send?.({ prompt: text });
|
|
94
|
-
},
|
|
95
|
-
openLink(url) {
|
|
96
|
-
const open = openai()?.openExternal;
|
|
97
|
-
if (open) open({ href: url });
|
|
98
|
-
else win.open(url, "_blank", "noopener,noreferrer");
|
|
99
|
-
},
|
|
100
|
-
resize() {
|
|
101
|
-
},
|
|
102
|
-
capabilities() {
|
|
103
|
-
const o = openai();
|
|
104
|
-
return {
|
|
105
|
-
pull: typeof o?.callTool === "function",
|
|
106
|
-
sendPrompt: typeof o?.sendFollowUpMessage === "function" || typeof o?.sendFollowupMessage === "function",
|
|
107
|
-
openLink: true
|
|
108
|
-
};
|
|
109
|
-
},
|
|
110
|
-
start() {
|
|
111
|
-
win.addEventListener(OPENAI_SET_GLOBALS, onSetGlobals, { passive: true });
|
|
112
|
-
currentData = openai()?.toolOutput ?? currentData;
|
|
113
|
-
},
|
|
114
|
-
destroy() {
|
|
115
|
-
if (destroyed) return;
|
|
116
|
-
destroyed = true;
|
|
117
|
-
win.removeEventListener(OPENAI_SET_GLOBALS, onSetGlobals);
|
|
118
|
-
dataCbs.clear();
|
|
119
|
-
themeCbs.clear();
|
|
120
|
-
}
|
|
121
|
-
};
|
|
122
|
-
}
|
|
123
|
-
|
|
124
69
|
// src/host/data.ts
|
|
125
70
|
function readInlineData(doc, elementId) {
|
|
126
71
|
if (!doc) return null;
|
|
@@ -134,15 +79,6 @@ function readInlineData(doc, elementId) {
|
|
|
134
79
|
return null;
|
|
135
80
|
}
|
|
136
81
|
}
|
|
137
|
-
function unwrapRenderData(payload) {
|
|
138
|
-
if (payload == null || typeof payload !== "object") return null;
|
|
139
|
-
const rec = payload;
|
|
140
|
-
const nested = rec.renderData;
|
|
141
|
-
const source = nested != null && typeof nested === "object" ? nested : rec;
|
|
142
|
-
if (source.toolOutput != null) return source.toolOutput;
|
|
143
|
-
if (source.structuredContent != null) return source.structuredContent;
|
|
144
|
-
return source;
|
|
145
|
-
}
|
|
146
82
|
|
|
147
83
|
// src/host/adapters/inline.ts
|
|
148
84
|
function createInlineAdapter(win, options) {
|
|
@@ -213,7 +149,7 @@ function createMcpAppsAdapter(win, options) {
|
|
|
213
149
|
const dataCbs = /* @__PURE__ */ new Set();
|
|
214
150
|
const themeCbs = /* @__PURE__ */ new Set();
|
|
215
151
|
let destroyed = false;
|
|
216
|
-
let
|
|
152
|
+
let initialized = false;
|
|
217
153
|
let nextId = 1;
|
|
218
154
|
const pending = /* @__PURE__ */ new Map();
|
|
219
155
|
let lastReportedHeight = -1;
|
|
@@ -223,10 +159,6 @@ function createMcpAppsAdapter(win, options) {
|
|
|
223
159
|
function post(message) {
|
|
224
160
|
parent().postMessage(message, "*");
|
|
225
161
|
}
|
|
226
|
-
function postLegacy(message) {
|
|
227
|
-
if (standardConfirmed) return;
|
|
228
|
-
post(message);
|
|
229
|
-
}
|
|
230
162
|
function notify(method, params) {
|
|
231
163
|
post({ jsonrpc: "2.0", method, params: params ?? {} });
|
|
232
164
|
}
|
|
@@ -248,7 +180,9 @@ function createMcpAppsAdapter(win, options) {
|
|
|
248
180
|
}
|
|
249
181
|
function applyHostContext(ctx) {
|
|
250
182
|
if (!ctx || typeof ctx !== "object") return;
|
|
251
|
-
|
|
183
|
+
const fontCss = extractHostFontCss(ctx);
|
|
184
|
+
if (fontCss !== void 0) injectHostFonts(fontCss);
|
|
185
|
+
let { mode, tokens } = currentTheme;
|
|
252
186
|
let changed = false;
|
|
253
187
|
if (ctx.theme != null) {
|
|
254
188
|
const next = coerceMode(ctx.theme, mode);
|
|
@@ -262,23 +196,17 @@ function createMcpAppsAdapter(win, options) {
|
|
|
262
196
|
tokens = { ...tokens, ...styles.variables };
|
|
263
197
|
changed = true;
|
|
264
198
|
}
|
|
265
|
-
const nextFaces = foldFontFaces(fontFaces, ctx);
|
|
266
|
-
if (fontFacesKey(nextFaces) !== fontFacesKey(fontFaces)) {
|
|
267
|
-
fontFaces = nextFaces;
|
|
268
|
-
changed = true;
|
|
269
|
-
}
|
|
270
199
|
if (changed) {
|
|
271
|
-
currentTheme = { mode, tokens
|
|
200
|
+
currentTheme = { mode, tokens };
|
|
272
201
|
for (const cb of themeCbs) cb(currentTheme);
|
|
273
202
|
}
|
|
274
203
|
}
|
|
275
204
|
function reportSize(height) {
|
|
276
|
-
if (destroyed) return;
|
|
205
|
+
if (destroyed || !initialized) return;
|
|
277
206
|
const h = typeof height === "number" ? height : Math.ceil(win.document.body.scrollHeight);
|
|
278
207
|
if (h === lastReportedHeight) return;
|
|
279
208
|
lastReportedHeight = h;
|
|
280
|
-
|
|
281
|
-
postLegacy({ type: MCPUI_SIZE_CHANGE, payload: { height: h } });
|
|
209
|
+
notify(MCPAPP_SIZE_CHANGED, { height: h });
|
|
282
210
|
}
|
|
283
211
|
function handleResponse(d) {
|
|
284
212
|
const id = Number(d.id);
|
|
@@ -296,7 +224,7 @@ function createMcpAppsAdapter(win, options) {
|
|
|
296
224
|
function handleNotification(method, params) {
|
|
297
225
|
if (method === MCPAPP_TOOL_RESULT) {
|
|
298
226
|
const structured = params.structuredContent;
|
|
299
|
-
emitData(structured != null ? structured :
|
|
227
|
+
emitData(structured != null ? structured : params);
|
|
300
228
|
} else if (method === MCPAPP_HOST_CONTEXT_CHANGED) {
|
|
301
229
|
applyHostContext(params);
|
|
302
230
|
}
|
|
@@ -306,22 +234,11 @@ function createMcpAppsAdapter(win, options) {
|
|
|
306
234
|
post({ jsonrpc: "2.0", id: d.id, result: {} });
|
|
307
235
|
}
|
|
308
236
|
}
|
|
309
|
-
function handleLegacy(d) {
|
|
310
|
-
if (d.type === MCPUI_RENDER_DATA || d.type === "renderData") {
|
|
311
|
-
const { theme, ...rest } = d.payload ?? {};
|
|
312
|
-
if (theme != null) applyHostContext({ theme });
|
|
313
|
-
if (Object.keys(rest).length > 0) emitData(unwrapRenderData(rest));
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
237
|
const onMessage = (event) => {
|
|
317
238
|
if (destroyed) return;
|
|
318
239
|
if (event.source && event.source !== parent()) return;
|
|
319
240
|
const d = event.data;
|
|
320
|
-
if (!d || typeof d !== "object") return;
|
|
321
|
-
if (d.jsonrpc !== "2.0") {
|
|
322
|
-
handleLegacy(d);
|
|
323
|
-
return;
|
|
324
|
-
}
|
|
241
|
+
if (!d || typeof d !== "object" || d.jsonrpc !== "2.0") return;
|
|
325
242
|
if (d.id != null && ("result" in d || "error" in d)) {
|
|
326
243
|
handleResponse(d);
|
|
327
244
|
} else if (typeof d.method === "string") {
|
|
@@ -338,7 +255,7 @@ function createMcpAppsAdapter(win, options) {
|
|
|
338
255
|
}
|
|
339
256
|
}
|
|
340
257
|
return {
|
|
341
|
-
host: "
|
|
258
|
+
host: "mcp-apps",
|
|
342
259
|
getData: () => currentData,
|
|
343
260
|
onData(cb) {
|
|
344
261
|
dataCbs.add(cb);
|
|
@@ -357,12 +274,10 @@ function createMcpAppsAdapter(win, options) {
|
|
|
357
274
|
() => {
|
|
358
275
|
}
|
|
359
276
|
);
|
|
360
|
-
postLegacy({ type: MCPUI_PROMPT, payload: { prompt: text } });
|
|
361
277
|
},
|
|
362
278
|
openLink(url) {
|
|
363
279
|
void request(MCPAPP_OPEN_LINK, { url }).catch(() => {
|
|
364
280
|
});
|
|
365
|
-
postLegacy({ type: MCPUI_LINK, payload: { url } });
|
|
366
281
|
},
|
|
367
282
|
resize(height) {
|
|
368
283
|
reportSize(height);
|
|
@@ -374,21 +289,18 @@ function createMcpAppsAdapter(win, options) {
|
|
|
374
289
|
win.addEventListener("message", onMessage);
|
|
375
290
|
currentData = readInlineData(win.document, dataElementId);
|
|
376
291
|
if (autoResize) setupResize();
|
|
377
|
-
post({ type: MCPUI_READY });
|
|
378
292
|
request(MCPAPP_INITIALIZE, {
|
|
379
293
|
appInfo: { name: options.name ?? "synapse-ui", version: options.version ?? "0.0.0" },
|
|
380
294
|
appCapabilities: { availableDisplayModes: ["inline"] },
|
|
381
295
|
protocolVersion: MCPAPP_PROTOCOL_VERSION
|
|
382
296
|
}).then((result) => {
|
|
383
297
|
if (destroyed) return;
|
|
384
|
-
standardConfirmed = true;
|
|
385
298
|
applyHostContext(result?.hostContext);
|
|
386
299
|
notify(MCPAPP_INITIALIZED, {});
|
|
387
|
-
|
|
300
|
+
initialized = true;
|
|
388
301
|
reportSize();
|
|
389
302
|
}).catch(() => {
|
|
390
303
|
});
|
|
391
|
-
reportSize();
|
|
392
304
|
},
|
|
393
305
|
destroy() {
|
|
394
306
|
if (destroyed) return;
|
|
@@ -411,24 +323,17 @@ function createMcpAppsAdapter(win, options) {
|
|
|
411
323
|
|
|
412
324
|
// src/host/detect.ts
|
|
413
325
|
function detectHostKind(win) {
|
|
414
|
-
if (win.openai != null) return "chatgpt";
|
|
415
326
|
try {
|
|
416
|
-
if (win.parent != null && win.parent !== win) return "
|
|
327
|
+
if (win.parent != null && win.parent !== win) return "mcp-apps";
|
|
417
328
|
} catch {
|
|
418
|
-
return "
|
|
329
|
+
return "mcp-apps";
|
|
419
330
|
}
|
|
420
331
|
return "generic";
|
|
421
332
|
}
|
|
422
333
|
function adapterForKind(kind, win, options) {
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
case "claude":
|
|
427
|
-
case "nimblebrain":
|
|
428
|
-
return createMcpAppsAdapter(win, options);
|
|
429
|
-
default:
|
|
430
|
-
return createInlineAdapter(win, options);
|
|
431
|
-
}
|
|
334
|
+
if (kind === "mcp-apps") return createMcpAppsAdapter(win, options);
|
|
335
|
+
if (kind === "generic") return createInlineAdapter(win, options);
|
|
336
|
+
throw new TypeError(`unknown host "${String(kind)}": expected "mcp-apps" or "generic"`);
|
|
432
337
|
}
|
|
433
338
|
function selectAdapter(win, options) {
|
|
434
339
|
const kind = options.host ?? detectHostKind(win);
|
|
@@ -448,7 +353,13 @@ function connectUI(options = {}) {
|
|
|
448
353
|
onData: (cb) => adapter.onData(cb),
|
|
449
354
|
theme: () => adapter.getTheme(),
|
|
450
355
|
onTheme: (cb) => adapter.onTheme(cb),
|
|
451
|
-
|
|
356
|
+
// Decided here rather than per adapter: every host reports a failed or
|
|
357
|
+
// refused call inside the result, because that is how MCP defines one.
|
|
358
|
+
async callTool(name, args) {
|
|
359
|
+
const result = await adapter.callTool(name, args);
|
|
360
|
+
if (isToolError(result)) throw new ToolCallError(name, result);
|
|
361
|
+
return result;
|
|
362
|
+
},
|
|
452
363
|
sendPrompt: (text) => adapter.sendPrompt(text),
|
|
453
364
|
openLink: (url) => adapter.openLink(url),
|
|
454
365
|
resize: (height) => adapter.resize(height),
|
|
@@ -463,6 +374,6 @@ function connectUI(options = {}) {
|
|
|
463
374
|
};
|
|
464
375
|
}
|
|
465
376
|
|
|
466
|
-
export { HostUnsupportedError, SYNAPSE_DATA_ELEMENT_ID, adapterForKind, applyHostTheme, coerceMode, connectUI,
|
|
467
|
-
//# sourceMappingURL=chunk-
|
|
468
|
-
//# sourceMappingURL=chunk-
|
|
377
|
+
export { HostUnsupportedError, SYNAPSE_DATA_ELEMENT_ID, ToolCallError, adapterForKind, applyHostTheme, coerceMode, connectUI, createInlineAdapter, createMcpAppsAdapter, detectHostKind, preferredMode, selectAdapter };
|
|
378
|
+
//# sourceMappingURL=chunk-UKP4W6DI.js.map
|
|
379
|
+
//# sourceMappingURL=chunk-UKP4W6DI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/host/theme.ts","../src/host/types.ts","../src/host/data.ts","../src/host/adapters/inline.ts","../src/host/adapters/mcpapps.ts","../src/host/detect.ts","../src/host/connect.ts"],"names":[],"mappings":";;;AAqBO,SAAS,eAAe,KAAA,EAA6B;AAC1D,EAAA,IAAI,OAAO,aAAa,WAAA,EAAa;AACnC,IAAA,QAAA,CAAS,eAAA,CAAgB,YAAA,CAAa,YAAA,EAAc,KAAA,CAAM,IAAI,CAAA;AAAA,EAChE;AACA,EAAA,UAAA,CAAW,KAAA,CAAM,IAAA,EAAM,KAAA,CAAM,MAAM,CAAA;AACrC;AAIO,IAAM,mBAAA,GAAsB,kBAAA;AAY5B,SAAS,gBAAgB,GAAA,EAAmB;AACjD,E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Q;AAAA,IAClB;AAAA,GACF;AACF","file":"chunk-UKP4W6DI.js","sourcesContent":["import { applyTheme } from \"../theme-defaults.js\";\nimport type { SynapseUITheme } from \"./types.js\";\n\n/**\n * Apply a resolved theme to the DOM for the cross-host client.\n *\n * Two conventions coexist across Synapse components, so the client drives both:\n *\n * - `document.documentElement[data-theme=\"light\"|\"dark\"]` — how self-contained\n * HTML components (Bassethound's report) gate their `--var` palettes, and the\n * lever a host's light/dark signal actually flips.\n * - CSS custom properties via {@link applyTheme} — how the\n * `@nimblebrain/synapse/ui` token components consume theme, backed by the\n * SDK's neutral defaults so every referenced var resolves in both modes.\n *\n * Setting both means an app can use either convention (and a host that supplies\n * only a mode string still themes correctly). SSR-safe.\n *\n * Fonts travel separately, as the host's `@font-face` CSS: see\n * {@link injectHostFonts}.\n */\nexport function applyHostTheme(theme: SynapseUITheme): void {\n if (typeof document !== \"undefined\") {\n document.documentElement.setAttribute(\"data-theme\", theme.mode);\n }\n applyTheme(theme.mode, theme.tokens);\n}\n\n/** The style element the host's font CSS goes in — the same id the spec's\n * `applyHostFonts` uses, so both clients agree on one element. */\nexport const HOST_FONTS_STYLE_ID = \"__mcp-host-fonts\";\n\n/**\n * Load the host's `@font-face` CSS (the spec's `hostContext.styles.css.fonts`)\n * into the document.\n *\n * Mirrors ext-apps `applyHostFonts`, which this client cannot import without\n * pulling the ext-apps runtime into its IIFE: the CSS is injected once and left\n * in place, so a later host-context change without `css` keeps the typeface\n * loaded. A host that sends none leaves the web-safe fallbacks in force.\n * SSR-safe.\n */\nexport function injectHostFonts(css: string): void {\n if (typeof document === \"undefined\") return;\n if (document.getElementById(HOST_FONTS_STYLE_ID)) return;\n const style = document.createElement(\"style\");\n style.id = HOST_FONTS_STYLE_ID;\n style.textContent = css;\n document.head.appendChild(style);\n}\n\n/** Read the OS-level color scheme as a sane default for hosts that don't push a\n * theme until the handshake completes, or ever (standalone). */\nexport function preferredMode(win: Window | undefined): \"light\" | \"dark\" {\n try {\n if (win?.matchMedia?.(\"(prefers-color-scheme: dark)\").matches) return \"dark\";\n } catch {\n // matchMedia unavailable (older test envs) — fall through to light.\n }\n return \"light\";\n}\n\n/** Coerce an arbitrary host-supplied theme signal to a mode. Accepts the string\n * form (`\"dark\"`) both hosts use; anything else falls back. */\nexport function coerceMode(value: unknown, fallback: \"light\" | \"dark\"): \"light\" | \"dark\" {\n return value === \"light\" || value === \"dark\" ? value : fallback;\n}\n","/**\n * Cross-host UI client — types and wire constants.\n *\n * The cross-host client (`connectUI`) renders one Synapse-authored component in\n * any MCP Apps host (ChatGPT, Claude, NimbleBrain) and standalone. Apps code\n * against `synapse.*` and never touch the bridge. This is a **push-first** surface: the tool output that spawned\n * the widget is delivered at render (`data()` / `onData()`); `callTool()` is the\n * pull escape hatch, advertised per host via `capabilities()`.\n *\n * This layer intentionally has ZERO dependency on `@modelcontextprotocol/*` — the\n * bridge is JSON-RPC over `postMessage`, spoken by hand, so the IIFE that apps\n * inline stays tiny (no Zod, no ext-apps schemas).\n */\n\n/**\n * The bridge the client resolved to, as reported by `synapse.host()`:\n * `\"mcp-apps\"` in a frame, `\"generic\"` standalone. It names the bridge, not the\n * product — every framing host speaks the same one. Apps should rarely branch on\n * it; `capabilities()` is the supported way to feature-detect.\n */\nexport type HostKind = \"mcp-apps\" | \"generic\";\n\n/** Resolved theme. `mode` always resolves to light or dark. `tokens` are CSS\n * custom properties the host publishes — the MCP Apps adapter reads them from\n * `hostContext.styles.variables`; where a host sends none they stay empty and the\n * SDK's neutral defaults back them. */\nexport interface SynapseUITheme {\n mode: \"light\" | \"dark\";\n tokens: Record<string, string>;\n}\n\n/** What the active host actually supports. `data()`/`onData()`/`theme()`/\n * `resize()` work everywhere; these three vary. */\nexport interface HostCapabilities {\n /** `callTool()` can reach the server (widget→server fetch). */\n pull: boolean;\n /** `sendPrompt()` reaches the agent conversation. */\n sendPrompt: boolean;\n /** `openLink()` opens an external URL through the host. */\n openLink: boolean;\n}\n\n/** Thrown by `callTool()` when the active host offers no widget→server call. */\nexport class HostUnsupportedError extends Error {\n constructor(feature: string, host: HostKind) {\n super(`\"${feature}\" is not supported by the \"${host}\" host`);\n this.name = \"HostUnsupportedError\";\n }\n}\n\n/**\n * Thrown by `callTool()` when the tool result says the call failed\n * (`isError: true`). MCP reports a tool failure inside the result rather than as\n * a JSON-RPC error, and a host reports a refusal the same way — ChatGPT answers a\n * call to a tool the app may not see with an `isError` result — so without this a\n * failure would resolve as if it were data. The message is the result's first\n * text block; the whole result is on `result`.\n */\nexport class ToolCallError extends Error {\n readonly result: unknown;\n constructor(name: string, result: unknown) {\n super(toolErrorText(result) ?? `tool \"${name}\" returned an error`);\n this.name = \"ToolCallError\";\n this.result = result;\n }\n}\n\nfunction toolErrorText(result: unknown): string | undefined {\n const content = (result as { content?: unknown } | null)?.content;\n if (!Array.isArray(content)) return undefined;\n for (const block of content) {\n const b = block as { type?: unknown; text?: unknown } | null;\n if (b?.type === \"text\" && typeof b.text === \"string\" && b.text !== \"\") return b.text;\n }\n return undefined;\n}\n\n/** True when a tool result reports failure, as MCP defines it. */\nexport function isToolError(result: unknown): boolean {\n return (\n result != null &&\n typeof result === \"object\" &&\n (result as { isError?: unknown }).isError === true\n );\n}\n\nexport interface ConnectUIOptions {\n /** App name — informational; forwarded to hosts that accept an appInfo. */\n name?: string;\n /** App semver — informational. */\n version?: string;\n /**\n * Force a host adapter instead of auto-detecting. Used by preview harnesses,\n * SSR, and tests; production apps omit it and let the SDK feature-detect.\n * `\"mcp-apps\"` → MCP Apps standard adapter, `\"generic\"` → inline adapter.\n */\n host?: HostKind;\n /**\n * `id` of the `<script type=\"application/json\">` element carrying pushed data\n * baked into the HTML (the SSR / standalone path). Defaults to\n * {@link SYNAPSE_DATA_ELEMENT_ID}.\n */\n dataElementId?: string;\n /**\n * Auto-report content height to the host on layout changes (MCP Apps only).\n * Defaults to `true`. Set `false` to size manually via `resize()`.\n */\n autoResize?: boolean;\n /** Window to bind to. Defaults to the global `window`. Injectable for tests. */\n window?: Window & typeof globalThis;\n}\n\n/**\n * The public cross-host client. Bound to `synapse` by convention.\n *\n * ```ts\n * const synapse = connectUI();\n * synapse.onData(render); // future pushes/updates\n * render(synapse.data()); // current value (may be null → empty state)\n * ```\n */\nexport interface SynapseUIClient {\n /** The current pushed data, or `null` before anything has been delivered. */\n data<T = unknown>(): T | null;\n /** Subscribe to data updates (NOT replayed — read `data()` for the current\n * value). Returns an unsubscribe. */\n onData<T = unknown>(cb: (data: T) => void): () => void;\n\n /** The current resolved theme. */\n theme(): SynapseUITheme;\n /** Subscribe to theme changes. The client already applies the theme to the DOM\n * (`data-theme` attribute + CSS variables) before this fires. */\n onTheme(cb: (theme: SynapseUITheme) => void): () => void;\n\n /** Widget→server tool call. Resolves with the tool result. Rejects with\n * {@link ToolCallError} when the result reports failure (`isError: true`), and\n * with {@link HostUnsupportedError} where the host advertises no pull\n * (`capabilities().pull === false`). */\n callTool<O = unknown>(name: string, args?: Record<string, unknown>): Promise<O>;\n /** Send a follow-up message to the agent conversation. No-op where unsupported. */\n sendPrompt(text: string): void;\n /** Open an external URL through the host (falls back to `window.open`). */\n openLink(url: string): void;\n /** Report content height to the host. Omit `height` to measure `document.body`. */\n resize(height?: number): void;\n\n /** What the active host supports. */\n capabilities(): HostCapabilities;\n /** The resolved host — an escape hatch; prefer `capabilities()`. */\n host(): HostKind;\n /** Tear down listeners/observers. */\n destroy(): void;\n}\n\n/**\n * Internal adapter contract. One per host bridge; the client is a thin façade\n * over the selected adapter.\n */\nexport interface HostAdapter {\n readonly host: HostKind;\n getData<T = unknown>(): T | null;\n onData<T = unknown>(cb: (data: T) => void): () => void;\n getTheme(): SynapseUITheme;\n onTheme(cb: (theme: SynapseUITheme) => void): () => void;\n callTool<O = unknown>(name: string, args?: Record<string, unknown>): Promise<O>;\n sendPrompt(text: string): void;\n openLink(url: string): void;\n resize(height?: number): void;\n capabilities(): HostCapabilities;\n /** Begin listening / send the ready handshake / read baked-in data. Called once\n * by `connectUI` synchronously so `getData()` is populated on return. */\n start(): void;\n destroy(): void;\n}\n\n// ---------------------------------------------------------------------------\n// Wire constants — the bridge message shapes. Centralized so a\n// host protocol tweak is a one-line change, not a grep-and-pray.\n// ---------------------------------------------------------------------------\n\n/** Default `id` of the baked-in data `<script type=\"application/json\">`. */\nexport const SYNAPSE_DATA_ELEMENT_ID = \"synapse-ui-data\";\n\n// ---------------------------------------------------------------------------\n// MCP Apps standard (SEP-1865) — the bridge every framing host speaks. The View iframe is an MCP client and the\n// host an MCP server; they exchange raw JSON-RPC 2.0 objects over `postMessage`\n// (no wrapper envelope). Method names are canonical to the ext-apps spec.\n// ---------------------------------------------------------------------------\n\n/** Protocol version exchanged in the `ui/initialize` handshake. */\nexport const MCPAPP_PROTOCOL_VERSION = \"2026-01-26\";\n/** View → host handshake request; the result carries the host context. */\nexport const MCPAPP_INITIALIZE = \"ui/initialize\";\n/** View → host notification sent once after the init result — the host holds all\n * pushes until it arrives. */\nexport const MCPAPP_INITIALIZED = \"ui/notifications/initialized\";\n/** Host → view notification carrying the tool output. `params` IS the\n * `CallToolResult` (data at `params.structuredContent`) — no `result` wrapper. */\nexport const MCPAPP_TOOL_RESULT = \"ui/notifications/tool-result\";\n/** Host → view notification carrying a partial host context (theme, styles, …). */\nexport const MCPAPP_HOST_CONTEXT_CHANGED = \"ui/notifications/host-context-changed\";\n/** View → host notification reporting intrinsic size (`{ width?, height? }`). A\n * host may keep the frame hidden until it receives one, so it is sent promptly. */\nexport const MCPAPP_SIZE_CHANGED = \"ui/notifications/size-changed\";\n/** View → host request: open an external URL (`{ url }`). */\nexport const MCPAPP_OPEN_LINK = \"ui/open-link\";\n/** View → host request: send a follow-up to the conversation\n * (`{ role: \"user\", content: ContentBlock[] }`). */\nexport const MCPAPP_MESSAGE = \"ui/message\";\n/** Host → view request: graceful teardown; the view replies `{}`. */\nexport const MCPAPP_TEARDOWN = \"ui/resource-teardown\";\n/** Standard MCP method the View may call over the same channel (pull). */\nexport const MCP_TOOLS_CALL = \"tools/call\";\n","/**\n * Read data baked into the HTML as `<script type=\"application/json\" id=…>`.\n *\n * This is how a server delivers tool output with no round-trip, for first paint\n * and for a standalone render: the server helper escapes the payload\n * and substitutes it into the element (see the Python `SynapseUI.render_html`).\n * A data-free template leaves the marker comment in place, which fails\n * `JSON.parse` and reads back as `null` — exactly the \"no data yet\" state.\n */\nexport function readInlineData<T = unknown>(\n doc: Document | undefined,\n elementId: string,\n): T | null {\n if (!doc) return null;\n const el = doc.getElementById(elementId);\n const text = el?.textContent;\n if (!text) return null;\n try {\n const parsed = JSON.parse(text);\n return (parsed ?? null) as T | null;\n } catch {\n // Unreplaced marker or malformed blob — treat as no data.\n return null;\n }\n}\n","import { readInlineData } from \"../data.js\";\nimport { coerceMode, preferredMode } from \"../theme.js\";\nimport {\n type ConnectUIOptions,\n type HostAdapter,\n type HostCapabilities,\n HostUnsupportedError,\n SYNAPSE_DATA_ELEMENT_ID,\n type SynapseUITheme,\n} from \"../types.js\";\n\n/**\n * Inline / standalone fallback adapter.\n *\n * No live host bridge — used for SSR, previews, and a plain browser render. Data\n * comes only from the baked-in `<script type=\"application/json\">` blob; there is\n * nothing to push, so `onData` never fires after `start()`. Theme follows the OS\n * color scheme and tracks `prefers-color-scheme` changes. `openLink` opens a new\n * tab; `sendPrompt`/`callTool` have no destination.\n */\nexport function createInlineAdapter(\n win: Window & typeof globalThis,\n options: ConnectUIOptions,\n): HostAdapter {\n const dataElementId = options.dataElementId ?? SYNAPSE_DATA_ELEMENT_ID;\n\n let currentData: unknown = null;\n let currentTheme: SynapseUITheme = { mode: preferredMode(win), tokens: {} };\n\n const themeCbs = new Set<(t: SynapseUITheme) => void>();\n let destroyed = false;\n let media: MediaQueryList | null = null;\n\n const onSchemeChange = (event: MediaQueryListEvent) => {\n if (destroyed) return;\n const mode = coerceMode(event.matches ? \"dark\" : \"light\", currentTheme.mode);\n if (mode === currentTheme.mode) return;\n currentTheme = { mode, tokens: {} };\n for (const cb of themeCbs) cb(currentTheme);\n };\n\n return {\n host: \"generic\",\n getData: <T>() => currentData as T | null,\n onData() {\n // Static render — no updates after the initial baked-in read.\n return () => {};\n },\n getTheme: () => currentTheme,\n onTheme(cb) {\n themeCbs.add(cb);\n return () => themeCbs.delete(cb);\n },\n async callTool<O>(_name: string): Promise<O> {\n throw new HostUnsupportedError(\"callTool\", \"generic\");\n },\n sendPrompt() {\n // No agent to reach in a standalone render.\n },\n openLink(url: string) {\n win.open(url, \"_blank\", \"noopener,noreferrer\");\n },\n resize() {\n // No host to size for.\n },\n capabilities(): HostCapabilities {\n return { pull: false, sendPrompt: false, openLink: true };\n },\n start() {\n currentData = readInlineData(win.document, dataElementId);\n try {\n media = win.matchMedia?.(\"(prefers-color-scheme: dark)\") ?? null;\n media?.addEventListener?.(\"change\", onSchemeChange);\n } catch {\n media = null;\n }\n },\n destroy() {\n if (destroyed) return;\n destroyed = true;\n media?.removeEventListener?.(\"change\", onSchemeChange);\n media = null;\n themeCbs.clear();\n },\n };\n}\n","// `detection` is type-only against `@modelcontextprotocol/*`, so importing it\n// keeps this adapter free of the ext-apps runtime (and Zod) that the lean\n// `window.SynapseUI` IIFE deliberately excludes.\nimport { extractHostFontCss } from \"../../detection.js\";\nimport { readInlineData } from \"../data.js\";\nimport { coerceMode, injectHostFonts, preferredMode } from \"../theme.js\";\nimport {\n type ConnectUIOptions,\n type HostAdapter,\n type HostCapabilities,\n MCP_TOOLS_CALL,\n MCPAPP_HOST_CONTEXT_CHANGED,\n MCPAPP_INITIALIZE,\n MCPAPP_INITIALIZED,\n MCPAPP_MESSAGE,\n MCPAPP_OPEN_LINK,\n MCPAPP_PROTOCOL_VERSION,\n MCPAPP_SIZE_CHANGED,\n MCPAPP_TEARDOWN,\n MCPAPP_TOOL_RESULT,\n SYNAPSE_DATA_ELEMENT_ID,\n type SynapseUITheme,\n} from \"../types.js\";\n\n/** How long a widget→host request (`callTool`, `openLink`, `sendPrompt`) waits\n * for its response before rejecting, so a silent host never hangs a promise. */\nconst REQUEST_TIMEOUT_MS = 30_000;\n\ninterface PendingRequest {\n resolve: (value: unknown) => void;\n reject: (reason: unknown) => void;\n timer: ReturnType<typeof setTimeout>;\n}\n\n/**\n * MCP Apps standard (SEP-1865) adapter — the bridge for every framed host.\n * ChatGPT, Claude and NimbleBrain all implement the standard, so there is one.\n *\n * The View iframe is an MCP client speaking JSON-RPC 2.0 to `window.parent`:\n *\n * 1. posts `ui/initialize` and awaits the host context (theme, style variables);\n * 2. posts `ui/notifications/initialized`, then a `size-changed` — a host keeps\n * the frame hidden until it has both the handshake and a size;\n * 3. receives data via `ui/notifications/tool-result` (`params` IS the\n * `CallToolResult`, so data is at `params.structuredContent`) and theme via\n * `ui/notifications/host-context-changed`.\n *\n * Actions go up as requests: `ui/open-link`, `ui/message` (follow-up), and\n * `tools/call` (pull).\n */\nexport function createMcpAppsAdapter(\n win: Window & typeof globalThis,\n options: ConnectUIOptions,\n): HostAdapter {\n const dataElementId = options.dataElementId ?? SYNAPSE_DATA_ELEMENT_ID;\n const autoResize = options.autoResize !== false;\n\n let currentData: unknown = null;\n let currentTheme: SynapseUITheme = { mode: preferredMode(win), tokens: {} };\n\n const dataCbs = new Set<(d: unknown) => void>();\n const themeCbs = new Set<(t: SynapseUITheme) => void>();\n let destroyed = false;\n // Set once the host has answered `ui/initialize` and been told `initialized`.\n let initialized = false;\n let nextId = 1;\n const pending = new Map<number, PendingRequest>();\n let lastReportedHeight = -1;\n let resizeObserver: ResizeObserver | null = null;\n let onWindowResize: (() => void) | null = null;\n\n const parent = () => win.parent ?? win;\n\n function post(message: Record<string, unknown>): void {\n parent().postMessage(message, \"*\");\n }\n\n function notify(method: string, params?: Record<string, unknown>): void {\n post({ jsonrpc: \"2.0\", method, params: params ?? {} });\n }\n\n function request<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T> {\n const id = nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n pending.delete(id);\n reject(new Error(`\"${method}\" timed out`));\n }, REQUEST_TIMEOUT_MS);\n pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n post({ jsonrpc: \"2.0\", id, method, params: params ?? {} });\n });\n }\n\n function emitData(next: unknown): void {\n if (next == null) return;\n currentData = next;\n for (const cb of dataCbs) cb(next);\n }\n\n /** Merge a full or partial host context into the resolved theme (mode, tokens),\n * and load the host's `@font-face` CSS from the spec's `styles.css.fonts`. */\n function applyHostContext(ctx: Record<string, unknown> | null | undefined): void {\n if (!ctx || typeof ctx !== \"object\") return;\n const fontCss = extractHostFontCss(ctx);\n if (fontCss !== undefined) injectHostFonts(fontCss);\n let { mode, tokens } = currentTheme;\n let changed = false;\n if (ctx.theme != null) {\n const next = coerceMode(ctx.theme, mode);\n if (next !== mode) {\n mode = next;\n changed = true;\n }\n }\n const styles = ctx.styles as { variables?: Record<string, string> } | undefined;\n if (styles?.variables && typeof styles.variables === \"object\") {\n tokens = { ...tokens, ...styles.variables };\n changed = true;\n }\n if (changed) {\n currentTheme = { mode, tokens };\n for (const cb of themeCbs) cb(currentTheme);\n }\n }\n\n function reportSize(height?: number): void {\n // `ui/initialize` is the app's first word on this bridge, and a strict host\n // drops anything that arrives before it — leaving the frame hidden. The\n // handshake reports a size as soon as it completes, so nothing is lost.\n if (destroyed || !initialized) return;\n const h = typeof height === \"number\" ? height : Math.ceil(win.document.body.scrollHeight);\n if (h === lastReportedHeight) return;\n lastReportedHeight = h;\n notify(MCPAPP_SIZE_CHANGED, { height: h });\n }\n\n function handleResponse(d: Record<string, unknown>): void {\n // Normalize the echoed id: JSON-RPC requires a same-type echo, but a lax host\n // that returned \"1\" for 1 would otherwise miss the numeric-keyed pending map.\n const id = Number(d.id);\n const p = pending.get(id);\n if (!p) return;\n pending.delete(id);\n clearTimeout(p.timer);\n if (d.error != null) {\n const err = d.error as { message?: string };\n p.reject(new Error(err.message ?? \"request failed\"));\n } else {\n p.resolve(d.result);\n }\n }\n\n function handleNotification(method: string, params: Record<string, unknown>): void {\n if (method === MCPAPP_TOOL_RESULT) {\n // `params` is the CallToolResult: the render data lives at structuredContent.\n const structured = params.structuredContent;\n emitData(structured != null ? structured : params);\n } else if (method === MCPAPP_HOST_CONTEXT_CHANGED) {\n applyHostContext(params);\n }\n }\n\n function handleRequest(d: Record<string, unknown>): void {\n // The one host→view request we honor: acknowledge teardown so the host can\n // dispose the frame cleanly.\n if (d.method === MCPAPP_TEARDOWN) {\n post({ jsonrpc: \"2.0\", id: d.id, result: {} });\n }\n }\n\n const onMessage = (event: MessageEvent) => {\n if (destroyed) return;\n // Accept only frames from the host window when the browser sets a source.\n if (event.source && event.source !== parent()) return;\n const d = event.data as Record<string, unknown> | null | undefined;\n if (!d || typeof d !== \"object\" || d.jsonrpc !== \"2.0\") return;\n if (d.id != null && (\"result\" in d || \"error\" in d)) {\n handleResponse(d);\n } else if (typeof d.method === \"string\") {\n if (d.id != null) handleRequest(d);\n else handleNotification(d.method, (d.params ?? {}) as Record<string, unknown>);\n }\n };\n\n function setupResize(): void {\n onWindowResize = () => reportSize();\n win.addEventListener(\"resize\", onWindowResize);\n if (typeof win.ResizeObserver !== \"undefined\") {\n resizeObserver = new win.ResizeObserver(() => reportSize());\n resizeObserver.observe(win.document.body);\n }\n }\n\n return {\n host: \"mcp-apps\",\n getData: <T>() => currentData as T | null,\n onData(cb) {\n dataCbs.add(cb as (d: unknown) => void);\n return () => dataCbs.delete(cb as (d: unknown) => void);\n },\n getTheme: () => currentTheme,\n onTheme(cb) {\n themeCbs.add(cb);\n return () => themeCbs.delete(cb);\n },\n async callTool<O>(name: string, args?: Record<string, unknown>): Promise<O> {\n return (await request(MCP_TOOLS_CALL, { name, arguments: args ?? {} })) as O;\n },\n sendPrompt(text: string) {\n void request(MCPAPP_MESSAGE, { role: \"user\", content: [{ type: \"text\", text }] }).catch(\n () => {},\n );\n },\n openLink(url: string) {\n void request(MCPAPP_OPEN_LINK, { url }).catch(() => {});\n },\n resize(height?: number) {\n reportSize(height);\n },\n capabilities(): HostCapabilities {\n // An MCP Apps host answers `tools/call`, `ui/message` and `ui/open-link`\n // over this bridge.\n return { pull: true, sendPrompt: true, openLink: true };\n },\n start() {\n win.addEventListener(\"message\", onMessage as EventListener);\n\n // Baked-in data → available on first paint, before the handshake resolves.\n currentData = readInlineData(win.document, dataElementId);\n\n if (autoResize) setupResize();\n\n request<{ hostContext?: Record<string, unknown> }>(MCPAPP_INITIALIZE, {\n appInfo: { name: options.name ?? \"synapse-ui\", version: options.version ?? \"0.0.0\" },\n appCapabilities: { availableDisplayModes: [\"inline\"] },\n protocolVersion: MCPAPP_PROTOCOL_VERSION,\n })\n .then((result) => {\n if (destroyed) return;\n applyHostContext(result?.hostContext);\n notify(MCPAPP_INITIALIZED, {});\n initialized = true;\n // A host keeps the frame hidden until it gets a size after init, and\n // this is the first point at which sending one is allowed.\n reportSize();\n })\n .catch(() => {\n // The parent never answered: it is not an MCP Apps host, and nothing\n // reaches the component over this bridge. Baked-in data still renders.\n });\n },\n destroy() {\n if (destroyed) return;\n destroyed = true;\n win.removeEventListener(\"message\", onMessage as EventListener);\n if (onWindowResize) win.removeEventListener(\"resize\", onWindowResize);\n onWindowResize = null;\n resizeObserver?.disconnect();\n resizeObserver = null;\n for (const p of pending.values()) {\n clearTimeout(p.timer);\n p.reject(new Error(\"adapter destroyed\"));\n }\n pending.clear();\n dataCbs.clear();\n themeCbs.clear();\n },\n };\n}\n","import { createInlineAdapter } from \"./adapters/inline.js\";\nimport { createMcpAppsAdapter } from \"./adapters/mcpapps.js\";\nimport type { ConnectUIOptions, HostAdapter, HostKind } from \"./types.js\";\n\n/**\n * Minimal window shape the detector inspects. Kept structural so detection is\n * unit-testable with a plain object — no full `Window` fake required.\n */\ninterface DetectableWindow {\n parent?: unknown;\n}\n\n/**\n * Detect the bridge from the browsing context.\n *\n * - a nested browsing context (`parent !== self`, or a cross-origin access that\n * throws) → **mcp-apps**: every host that frames a component speaks the MCP\n * Apps standard.\n * - top-level document → **generic** (inline / standalone).\n *\n * Nothing on the window names the host. `window.openai` in particular does not:\n * ChatGPT injects it into every frame it serves, whatever the component is.\n * Which host answered is in the handshake, not here.\n */\nexport function detectHostKind(win: DetectableWindow): HostKind {\n try {\n if (win.parent != null && win.parent !== win) return \"mcp-apps\";\n } catch {\n // Cross-origin parent access throws → we are framed by another origin.\n return \"mcp-apps\";\n }\n return \"generic\";\n}\n\n/** Build the adapter for an explicit host kind (`options.host` or a detected one). */\nexport function adapterForKind(\n kind: HostKind,\n win: Window & typeof globalThis,\n options: ConnectUIOptions,\n): HostAdapter {\n if (kind === \"mcp-apps\") return createMcpAppsAdapter(win, options);\n if (kind === \"generic\") return createInlineAdapter(win, options);\n // A script-tag caller has no compiler to reject a value outside `HostKind`, and\n // treating one as standalone inside a frame sends no handshake: the host keeps\n // the frame hidden and the component is blank with nothing to say why.\n throw new TypeError(`unknown host \"${String(kind)}\": expected \"mcp-apps\" or \"generic\"`);\n}\n\n/** Select and construct the host adapter, honoring `options.host` when set. */\nexport function selectAdapter(\n win: Window & typeof globalThis,\n options: ConnectUIOptions,\n): HostAdapter {\n const kind = options.host ?? detectHostKind(win as unknown as DetectableWindow);\n return adapterForKind(kind, win, options);\n}\n","import { selectAdapter } from \"./detect.js\";\nimport { applyHostTheme } from \"./theme.js\";\nimport {\n type ConnectUIOptions,\n isToolError,\n type SynapseUIClient,\n ToolCallError,\n} from \"./types.js\";\n\n/**\n * Connect a Synapse-authored component to whatever host it renders in — any MCP\n * Apps host, or a plain/standalone page — behind one push-first API. Detects\n * whether it is framed, selects an adapter, and applies the\n * host theme to the DOM before returning.\n *\n * Synchronous: `data()` is populated from baked-in data (where present) on\n * return, and pushed updates arrive via `onData`. Bind the result to `synapse`:\n *\n * ```ts\n * const synapse = connectUI({ name: \"my-widget\", version: \"1.0.0\" });\n * synapse.onData(render); // future pushes/updates\n * render(synapse.data()); // current value (null → empty state)\n * ```\n */\nexport function connectUI(options: ConnectUIOptions = {}): SynapseUIClient {\n const win = options.window ?? (globalThis as unknown as Window & typeof globalThis);\n const adapter = selectAdapter(win, options);\n\n // The client owns theme application: adapters resolve mode/tokens; this puts\n // them on the DOM (data-theme + CSS vars) so apps never wire theme by hand.\n applyHostTheme(adapter.getTheme());\n const unsubTheme = adapter.onTheme(applyHostTheme);\n\n adapter.start();\n\n let destroyed = false;\n\n return {\n data: <T>() => adapter.getData<T>(),\n onData: <T>(cb: (data: T) => void) => adapter.onData<T>(cb),\n theme: () => adapter.getTheme(),\n onTheme: (cb) => adapter.onTheme(cb),\n // Decided here rather than per adapter: every host reports a failed or\n // refused call inside the result, because that is how MCP defines one.\n async callTool<O>(name: string, args?: Record<string, unknown>): Promise<O> {\n const result = await adapter.callTool<O>(name, args);\n if (isToolError(result)) throw new ToolCallError(name, result);\n return result;\n },\n sendPrompt: (text: string) => adapter.sendPrompt(text),\n openLink: (url: string) => adapter.openLink(url),\n resize: (height?: number) => adapter.resize(height),\n capabilities: () => adapter.capabilities(),\n host: () => adapter.host,\n destroy() {\n if (destroyed) return;\n destroyed = true;\n unsubTheme();\n adapter.destroy();\n },\n };\n}\n"]}
|