@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.
Files changed (100) hide show
  1. package/README.md +20 -25
  2. package/dist/check-QMTOCTRS.js +474 -0
  3. package/dist/check-QMTOCTRS.js.map +1 -0
  4. package/dist/check-VK4SOAUU.cjs +480 -0
  5. package/dist/check-VK4SOAUU.cjs.map +1 -0
  6. package/dist/{chunk-RU64F5RS.cjs → chunk-BNF352SA.cjs} +57 -146
  7. package/dist/chunk-BNF352SA.cjs.map +1 -0
  8. package/dist/{chunk-DRLVEHCD.js → chunk-DJS2FKBN.js} +21 -79
  9. package/dist/chunk-DJS2FKBN.js.map +1 -0
  10. package/dist/chunk-H3INUKA3.js +32 -0
  11. package/dist/chunk-H3INUKA3.js.map +1 -0
  12. package/dist/chunk-HQLSVUOR.cjs +667 -0
  13. package/dist/chunk-HQLSVUOR.cjs.map +1 -0
  14. package/dist/{chunk-NP7ROSH2.cjs → chunk-ISV6HFQE.cjs} +14 -7
  15. package/dist/chunk-ISV6HFQE.cjs.map +1 -0
  16. package/dist/chunk-TR2YNWZ5.js +658 -0
  17. package/dist/chunk-TR2YNWZ5.js.map +1 -0
  18. package/dist/{chunk-OYLZ5OCK.js → chunk-UKP4W6DI.js} +57 -146
  19. package/dist/chunk-UKP4W6DI.js.map +1 -0
  20. package/dist/{chunk-SZWHFTXV.cjs → chunk-YSL7KJNU.cjs} +21 -81
  21. package/dist/chunk-YSL7KJNU.cjs.map +1 -0
  22. package/dist/codegen/cli.cjs +41 -4
  23. package/dist/codegen/cli.cjs.map +1 -1
  24. package/dist/codegen/cli.js +41 -4
  25. package/dist/codegen/cli.js.map +1 -1
  26. package/dist/codegen/index.cjs +0 -1
  27. package/dist/codegen/index.d.cts +1 -1
  28. package/dist/codegen/index.d.ts +1 -1
  29. package/dist/codegen/index.js +0 -1
  30. package/dist/connect.iife.global.js +34 -34
  31. package/dist/{detect-DZMJsyvZ.d.cts → detect-DVGaL2bH.d.cts} +39 -33
  32. package/dist/{detect-DBwc8a21.d.ts → detect-DVGaL2bH.d.ts} +39 -33
  33. package/dist/host/index.cjs +17 -18
  34. package/dist/host/index.d.cts +11 -27
  35. package/dist/host/index.d.ts +11 -27
  36. package/dist/host/index.js +2 -3
  37. package/dist/index.cjs +30 -19
  38. package/dist/index.cjs.map +1 -1
  39. package/dist/index.d.cts +72 -26
  40. package/dist/index.d.ts +72 -26
  41. package/dist/index.js +8 -9
  42. package/dist/index.js.map +1 -1
  43. package/dist/react/index.cjs +9 -10
  44. package/dist/react/index.cjs.map +1 -1
  45. package/dist/react/index.d.cts +36 -8
  46. package/dist/react/index.d.ts +36 -8
  47. package/dist/react/index.js +3 -4
  48. package/dist/react/index.js.map +1 -1
  49. package/dist/schema-reader-776246MJ.js +3 -0
  50. package/dist/{schema-reader-GM4A4L44.js.map → schema-reader-776246MJ.js.map} +1 -1
  51. package/dist/{schema-reader-MWBRQ2TQ.cjs → schema-reader-B6LTGBMJ.cjs} +2 -3
  52. package/dist/{schema-reader-MWBRQ2TQ.cjs.map → schema-reader-B6LTGBMJ.cjs.map} +1 -1
  53. package/dist/{server-LR6T6C44.cjs → server-BR5MNFOB.cjs} +13 -14
  54. package/dist/server-BR5MNFOB.cjs.map +1 -0
  55. package/dist/{server-UHPEE55X.js → server-OOEEWAEG.js} +13 -14
  56. package/dist/server-OOEEWAEG.js.map +1 -0
  57. package/dist/synapse-runtime.iife.global.js +34 -34
  58. package/dist/synapse-ui.iife.global.js +4 -4
  59. package/dist/type-generator-MZ4X4DE5.js +3 -0
  60. package/dist/{type-generator-ZYSVFK3X.js.map → type-generator-MZ4X4DE5.js.map} +1 -1
  61. package/dist/{type-generator-YTPFWLVG.cjs → type-generator-UA3L4OIA.cjs} +2 -3
  62. package/dist/{type-generator-YTPFWLVG.cjs.map → type-generator-UA3L4OIA.cjs.map} +1 -1
  63. package/dist/{types-CG08aO82.d.cts → types-BxPfGHKO.d.cts} +35 -43
  64. package/dist/{types-CG08aO82.d.ts → types-BxPfGHKO.d.ts} +35 -43
  65. package/dist/ui/base.cjs +0 -1
  66. package/dist/ui/base.cjs.map +1 -1
  67. package/dist/ui/base.js +0 -1
  68. package/dist/ui/base.js.map +1 -1
  69. package/dist/ui/index.cjs +0 -1
  70. package/dist/ui/index.cjs.map +1 -1
  71. package/dist/ui/index.js +0 -1
  72. package/dist/ui/index.js.map +1 -1
  73. package/dist/vite/index.cjs +10 -10
  74. package/dist/vite/index.cjs.map +1 -1
  75. package/dist/vite/index.js +6 -6
  76. package/dist/vite/index.js.map +1 -1
  77. package/dist/{writer-HDRCQSX2.cjs → writer-NDK4U6C5.cjs} +3 -3
  78. package/dist/{writer-HDRCQSX2.cjs.map → writer-NDK4U6C5.cjs.map} +1 -1
  79. package/dist/{writer-QNDPMEYD.js → writer-ZNBXYUYC.js} +3 -3
  80. package/dist/{writer-QNDPMEYD.js.map → writer-ZNBXYUYC.js.map} +1 -1
  81. package/package.json +6 -3
  82. package/dist/chunk-54W6IAHM.js +0 -24
  83. package/dist/chunk-54W6IAHM.js.map +0 -1
  84. package/dist/chunk-DRLVEHCD.js.map +0 -1
  85. package/dist/chunk-NP7ROSH2.cjs.map +0 -1
  86. package/dist/chunk-OYLZ5OCK.js.map +0 -1
  87. package/dist/chunk-P5DBJFSQ.js +0 -8459
  88. package/dist/chunk-P5DBJFSQ.js.map +0 -1
  89. package/dist/chunk-PZ5AY32C.js +0 -9
  90. package/dist/chunk-PZ5AY32C.js.map +0 -1
  91. package/dist/chunk-Q7SFCCGT.cjs +0 -11
  92. package/dist/chunk-Q7SFCCGT.cjs.map +0 -1
  93. package/dist/chunk-QXDCA7QW.cjs +0 -8466
  94. package/dist/chunk-QXDCA7QW.cjs.map +0 -1
  95. package/dist/chunk-RU64F5RS.cjs.map +0 -1
  96. package/dist/chunk-SZWHFTXV.cjs.map +0 -1
  97. package/dist/schema-reader-GM4A4L44.js +0 -4
  98. package/dist/server-LR6T6C44.cjs.map +0 -1
  99. package/dist/server-UHPEE55X.js.map +0 -1
  100. package/dist/type-generator-ZYSVFK3X.js +0 -4
package/README.md CHANGED
@@ -15,13 +15,13 @@ Synapse is an optional enhancement layer over `@modelcontextprotocol/ext-apps`.
15
15
 
16
16
  - **Zero-config handshake** — `await connect()` resolves when the host is ready. You never see `ui/initialize`.
17
17
  - **Typed tool calls** — call MCP tools with full TypeScript input/output types
18
- - **Reactive data sync** — subscribe to data change events from the agent
18
+ - **Reactive data sync** — refresh when your server announces its data changed (`notifications/resources/list_changed`)
19
19
  - **Theme tracking** — automatic light/dark mode and custom design tokens
20
- - **State store** — Redux-like store with optional persistence and LLM visibility
20
+ - **Agent context** — push what the user is looking at to the model with `useModelContext`
21
21
  - **Keyboard forwarding** — forward shortcuts from sandboxed iframes to the host
22
22
  - **Code generation** — generate TypeScript types from manifests, running servers, or JSON schemas
23
23
 
24
- In non-NimbleBrain hosts (Claude Desktop, VS Code, ChatGPT), NB-specific features degrade gracefully to no-ops while ext-apps baseline behavior is preserved.
24
+ Every call checks what the host declared in `ui/initialize`. Where a capability is missing, the call does a documented thing: it sends nothing, it keeps its initial value, or it rejects with `HostCapabilityError` without sending. See [the portable-app contract](https://synapse.nimblebrain.ai/docs/concepts/degradation/).
25
25
 
26
26
  ## Why Synapse?
27
27
 
@@ -35,7 +35,7 @@ Synapse handles the plumbing so you can focus on the UI. See **[Why Synapse?](do
35
35
  npm install @nimblebrain/synapse
36
36
  ```
37
37
 
38
- **Peer dependency:** `@modelcontextprotocol/ext-apps@^1.7.5`
38
+ **Peer dependencies:** `@modelcontextprotocol/ext-apps@^1.7.5`, `@modelcontextprotocol/sdk@^1.29.0`
39
39
 
40
40
  **Building a Python MCP server?** The server half — one self-contained `ui://`
41
41
  component rendered across ChatGPT, Claude, and NimbleBrain — ships as the
@@ -72,7 +72,7 @@ These are the durable decisions behind the library; they rarely change.
72
72
  - **That includes typography — the SDK ships no fonts.** Font fallbacks are
73
73
  web-safe system stacks, so an app renders correctly with no host, no network,
74
74
  and no font files. A host that wants its own typeface sends `@font-face`
75
- descriptors on the theme; the library fetches nothing on its own. See
75
+ CSS in the host context (`styles.css.fonts`); the library fetches nothing on its own. See
76
76
  [Host fonts](#host-fonts).
77
77
  - **Theme via CSS, not React.** Components style with token-driven inline-style
78
78
  objects whose values are those `var()` refs, so theming — including light/dark —
@@ -98,32 +98,26 @@ These are the durable decisions behind the library; they rarely change.
98
98
  A CSS custom property can *name* a font family but cannot *load* one, and an app
99
99
  iframe is its own document — it inherits no `@font-face` from the host page. So a
100
100
  host that sends only tokens is naming a typeface the app has no way to render.
101
- `Theme.fontFaces` closes that gap: the host sends the faces alongside the
102
- tokens, and the SDK loads them into the app document.
101
+ The MCP Apps spec closes that gap with `styles.css.fonts`: the host sends
102
+ `@font-face` CSS in the host context, and the SDK loads it into the app document.
103
103
 
104
104
  ```ts
105
- // Host side — sent as the `synapse/fontFaces` host-context extension.
105
+ // Host side — the hostContext of ui/initialize.
106
106
  {
107
- mode: "dark",
108
- tokens: { "--font-sans": "'Your Sans', system-ui, sans-serif" },
109
- fontFaces: [
110
- { family: "Your Sans", src: "url('/fonts/your-sans.woff2') format('woff2')", weight: "400 700" },
111
- ],
107
+ theme: "dark",
108
+ styles: {
109
+ variables: { "--font-sans": "'Your Sans', system-ui, sans-serif" },
110
+ css: {
111
+ fonts: "@font-face { font-family: 'Your Sans'; src: url('/fonts/your-sans.woff2') format('woff2'); font-weight: 400 700; font-display: swap; }",
112
+ },
113
+ },
112
114
  }
113
115
  ```
114
116
 
115
- | Field | Notes |
116
- |---|---|
117
- | `family` | Must match the family named in the host's `--font-*` token value. |
118
- | `src` | Any CSS `src` descriptor — relative (`url('/fonts/x.woff2')`), absolute (`url('https://cdn.example/x.woff2')`), or `data:`. |
119
- | `weight` | Single weight (`400`) or a variable range (`400 700`). Optional. |
120
- | `style` | `normal`, `italic`, … Optional. |
121
- | `display` | Defaults to `swap`, so text paints in the fallback rather than blocking. Optional. |
122
-
123
117
  Three things worth knowing:
124
118
 
125
119
  - **Sending no fonts is a supported configuration, not a degraded one.** Omit
126
- `fontFaces` and the app renders in the web-safe fallbacks (`system-ui` for
120
+ `styles.css.fonts` and the app renders in the web-safe fallbacks (`system-ui` for
127
121
  both body and headings, `ui-monospace` for code).
128
122
  - **Give every `--font-*` token value a web-safe tail.** A bare family name with
129
123
  no matching face falls through to the browser default, not to your intended
@@ -358,9 +352,10 @@ action(app, "navigate", { entity: "board", id: "b1" });
358
352
  | Function | Description |
359
353
  |----------|-------------|
360
354
  | `callToolAsTask(app, name, args?, opts?)` | Call a long-running tool task-augmented; returns a `Promise<TaskHandle>`. See [Long-running tools](#long-running-tools-tasks). |
361
- | `action(app, name, params?)` | Trigger a NimbleBrain host action. No-op off a NimbleBrain host. |
362
- | `pickFile(app, options?)` | Native file picker, single file. Throws off a NimbleBrain host. |
363
- | `pickFiles(app, options?)` | Native file picker, multiple files. Throws off a NimbleBrain host. |
355
+ | `action(app, name, params?)` | Trigger a NimbleBrain host action. No-op unless the host declares `ai.nimblebrain/action`. |
356
+ | `pickFile(app, options?)` | Native file picker, single file. Rejects with `HostCapabilityError` unless the host declares `ai.nimblebrain/request-file`. |
357
+ | `pickFiles(app, options?)` | Native file picker, multiple files. Rejects with `HostCapabilityError` unless the host declares `ai.nimblebrain/request-file`. |
358
+ | `hostSupports(app, extension)` | Whether the host declared a NimbleBrain extension (`"action"`, `"requestFile"`, `"keydown"`). |
364
359
  | `downloadFile(app, name, content, mime?)` | Hand the user a file to save, over the spec's `ui/download-file`. Resolves with the host's result — `{ isError: true }` when the host declined or the user cancelled — and rejects, without sending, when the host did not advertise the `downloadFile` capability. |
365
360
 
366
361
  `app.supportsTasks` says whether the host negotiated the tasks utility for
@@ -0,0 +1,474 @@
1
+ import { RESOURCE_MIME_TYPE, EXTENSION_ID, RESOURCE_URI_META_KEY } from '@modelcontextprotocol/ext-apps/server';
2
+ import { extractWWWAuthenticateParams, discoverOAuthProtectedResourceMetadata, discoverAuthorizationServerMetadata } from '@modelcontextprotocol/sdk/client/auth.js';
3
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
4
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
5
+ import { ResultSchema, ListToolsResultSchema } from '@modelcontextprotocol/sdk/types.js';
6
+
7
+ // src/check/index.ts
8
+
9
+ // src/check/profiles.ts
10
+ var SPEC_MIME = "UI resources are served as text/html;profile=mcp-app.";
11
+ var RESOLVES = "A tool's ui.resourceUri must name a ui:// resource the server serves.";
12
+ var UI_META = "ui.visibility is a non-empty subset of model/app; csp and permissions belong on the resource, not the tool.";
13
+ var EXTENSION = "A client uses MCP Apps only when both sides declare io.modelcontextprotocol/ui.";
14
+ var CHALLENGE = "Sign-in starts from a 401 whose WWW-Authenticate carries resource_metadata.";
15
+ var PRM_RESOURCE = "The protected-resource metadata's resource must equal the connector URL exactly.";
16
+ var ISSUER = "The authorization server's metadata issuer must equal the advertised authorization server exactly (RFC 8414).";
17
+ var SPEC_CSP = "ui.csp is the frame's security policy for Claude and the NimbleBrain host, and OpenAI documents it as generally preferred for new UI; measured 2026-09-17 in ChatGPT developer mode, a resource carrying it alone got no policy.";
18
+ var PROFILES = {
19
+ nimblebrain: {
20
+ name: "nimblebrain",
21
+ description: "The NimbleBrain host.",
22
+ rules: {
23
+ "ui-resource-mime": { severity: "error", why: SPEC_MIME },
24
+ "tool-resource-uri": { severity: "error", why: RESOLVES },
25
+ "tool-ui-meta": { severity: "error", why: UI_META },
26
+ // The host resolves an app by its ui:// scheme and does not gate on the
27
+ // declaration, so a missing one is a portability risk, not a break.
28
+ "extension-declared": { severity: "warn", why: EXTENSION },
29
+ // Only reported when the server challenges at all.
30
+ "auth-challenge": { severity: "warn", why: CHALLENGE },
31
+ "auth-resource-metadata": { severity: "warn", why: PRM_RESOURCE },
32
+ "auth-issuer": { severity: "warn", why: ISSUER }
33
+ }
34
+ },
35
+ claude: {
36
+ name: "claude",
37
+ description: "claude.ai and Claude Desktop.",
38
+ rules: {
39
+ "ui-resource-mime": { severity: "error", why: SPEC_MIME },
40
+ "tool-resource-uri": { severity: "error", why: RESOLVES },
41
+ "tool-ui-meta": { severity: "error", why: UI_META },
42
+ "extension-declared": { severity: "error", why: EXTENSION },
43
+ "resource-csp": {
44
+ severity: "warn",
45
+ why: "Claude builds the frame's security policy from ui.csp; an undeclared origin is blocked."
46
+ },
47
+ "resource-data-fonts": {
48
+ severity: "error",
49
+ why: "Claude's default security policy blocks data: fonts unless the resource declares them."
50
+ },
51
+ "auth-challenge": { severity: "error", why: CHALLENGE },
52
+ "auth-resource-metadata": { severity: "error", why: PRM_RESOURCE },
53
+ // Claude has been observed to accept an issuer that differs by a trailing
54
+ // slash, so this is a correctness warning for Claude rather than a break.
55
+ "auth-issuer": { severity: "warn", why: ISSUER }
56
+ }
57
+ },
58
+ chatgpt: {
59
+ name: "chatgpt",
60
+ description: "ChatGPT apps.",
61
+ rules: {
62
+ "ui-resource-mime": { severity: "error", why: SPEC_MIME },
63
+ "tool-resource-uri": { severity: "error", why: RESOLVES },
64
+ "tool-ui-meta": { severity: "error", why: UI_META },
65
+ "extension-declared": { severity: "error", why: EXTENSION },
66
+ // A requirement the vendor documents and the host was not observed to
67
+ // enforce is what `warn` is for. openai/widgetCSP is what was measured.
68
+ "resource-csp": { severity: "warn", why: SPEC_CSP },
69
+ "resource-openai-csp": {
70
+ severity: "error",
71
+ why: "ChatGPT reads the frame's security policy from openai/widgetCSP (snake_case origin lists); measured 2026-09-17 in developer mode, a resource without it got no policy on the frame at all. OpenAI documents the key as a legacy compatibility surface."
72
+ },
73
+ "resource-openai-data-fonts": {
74
+ severity: "warn",
75
+ why: "A data: font is blocked by a security policy that does not declare it."
76
+ },
77
+ "auth-challenge": { severity: "error", why: CHALLENGE },
78
+ "auth-resource-metadata": { severity: "error", why: PRM_RESOURCE },
79
+ "auth-issuer": { severity: "error", why: ISSUER },
80
+ "tool-security-schemes": {
81
+ severity: "error",
82
+ why: "ChatGPT prompts for sign-in mid-conversation only for tools that declare securitySchemes."
83
+ }
84
+ }
85
+ }
86
+ };
87
+ function isTargetName(value) {
88
+ return Object.hasOwn(PROFILES, value);
89
+ }
90
+
91
+ // src/check/index.ts
92
+ var UI_SCHEME = "ui://";
93
+ var VISIBILITY = /* @__PURE__ */ new Set(["model", "app"]);
94
+ async function runChecks(url, options = {}) {
95
+ const results = [];
96
+ const add = (id, status, detail) => results.push({ id, status, detail });
97
+ let challenge;
98
+ let session;
99
+ let connectError;
100
+ try {
101
+ session = await openSession(url, void 0, (res) => {
102
+ if (res.status === 401) challenge ??= res;
103
+ });
104
+ } catch (err) {
105
+ connectError = err;
106
+ }
107
+ const authRequired = challenge !== void 0;
108
+ if (authRequired && options.token) {
109
+ try {
110
+ session = await openSession(url, options.token);
111
+ connectError = void 0;
112
+ } catch (err) {
113
+ connectError = err;
114
+ }
115
+ }
116
+ if (!session && (!authRequired || options.token)) {
117
+ throw new Error(
118
+ `could not connect to ${url}${authRequired ? " with the given token" : ""}: ${message(connectError)}`
119
+ );
120
+ }
121
+ await checkAuth(url, challenge, add);
122
+ if (!session) {
123
+ for (const id of SESSION_CHECKS) {
124
+ add(id, "skip", "the server requires auth; pass --token to run it");
125
+ }
126
+ return results;
127
+ }
128
+ checkSession(session, authRequired, add);
129
+ return results;
130
+ }
131
+ function applyProfiles(results, targets) {
132
+ return targets.map((target) => {
133
+ const rules = PROFILES[target].rules;
134
+ const scored = results.flatMap((r) => {
135
+ const rule = rules[r.id];
136
+ return rule ? [{ ...r, severity: rule.severity, why: rule.why }] : [];
137
+ });
138
+ return {
139
+ target,
140
+ results: scored,
141
+ failed: scored.some((r) => r.status === "fail" && r.severity === "error")
142
+ };
143
+ });
144
+ }
145
+ function formatReport(url, reports) {
146
+ const width = Math.max(...reports.flatMap((r) => r.results.map((c) => c.id.length)), 0);
147
+ const lines = [`synapse check ${url}`];
148
+ for (const report of reports) {
149
+ lines.push("", `${report.target}: ${report.failed ? "FAIL" : "ok"}`);
150
+ for (const r of report.results) {
151
+ const label = r.status === "fail" ? r.severity === "error" ? "FAIL" : "WARN" : r.status.toUpperCase();
152
+ lines.push(` ${label.padEnd(4)} ${r.id.padEnd(width)} ${r.detail}`);
153
+ if (r.status === "fail") lines.push(` ${"".padEnd(width)} ${r.why}`);
154
+ }
155
+ }
156
+ return lines.join("\n");
157
+ }
158
+ var SESSION_CHECKS = [
159
+ "extension-declared",
160
+ "ui-resource-mime",
161
+ "tool-resource-uri",
162
+ "tool-ui-meta",
163
+ "resource-csp",
164
+ "resource-openai-csp",
165
+ "resource-data-fonts",
166
+ "resource-openai-data-fonts",
167
+ "tool-security-schemes"
168
+ ];
169
+ async function openSession(url, token, onResponse) {
170
+ const ui = { mimeTypes: [RESOURCE_MIME_TYPE] };
171
+ const client = new Client(
172
+ { name: "synapse-check", version: "1" },
173
+ { capabilities: { extensions: { [EXTENSION_ID]: ui } } }
174
+ );
175
+ const transport = new StreamableHTTPClientTransport(new URL(url), {
176
+ requestInit: token ? { headers: { Authorization: `Bearer ${token}` } } : void 0,
177
+ fetch: async (input, init) => {
178
+ const res = await fetch(input, init);
179
+ onResponse?.(res);
180
+ return res;
181
+ }
182
+ });
183
+ await client.connect(transport);
184
+ try {
185
+ const capabilities = client.getServerCapabilities();
186
+ const tools = [];
187
+ const resources = [];
188
+ let cursor;
189
+ if (capabilities?.tools) {
190
+ do {
191
+ const raw = await client.request(
192
+ { method: "tools/list", params: cursor ? { cursor } : {} },
193
+ ResultSchema
194
+ );
195
+ const page = ListToolsResultSchema.parse(raw);
196
+ const rawTools = raw.tools ?? [];
197
+ page.tools.forEach((tool, i) => {
198
+ const schemes = rawTools[i]?.securitySchemes;
199
+ if (schemes !== void 0) tool.securitySchemes = schemes;
200
+ });
201
+ tools.push(...page.tools);
202
+ cursor = page.nextCursor;
203
+ } while (cursor);
204
+ }
205
+ if (capabilities?.resources) {
206
+ do {
207
+ const page = await client.listResources({ cursor });
208
+ resources.push(...page.resources);
209
+ cursor = page.nextCursor;
210
+ } while (cursor);
211
+ }
212
+ const uris = new Set(resources.map((r) => r.uri).filter((u) => u.startsWith(UI_SCHEME)));
213
+ for (const tool of tools) {
214
+ const uri = toolUi(tool)?.resourceUri;
215
+ if (typeof uri === "string") uris.add(uri);
216
+ }
217
+ const reads = /* @__PURE__ */ new Map();
218
+ for (const uri of uris) {
219
+ try {
220
+ reads.set(uri, (await client.readResource({ uri })).contents);
221
+ } catch (err) {
222
+ reads.set(uri, err instanceof Error ? err : new Error(String(err)));
223
+ }
224
+ }
225
+ return { capabilities, tools, resources, reads };
226
+ } finally {
227
+ await client.close();
228
+ }
229
+ }
230
+ function checkSession(s, authRequired, add) {
231
+ const boundTools = s.tools.filter((t) => toolUi(t)?.resourceUri !== void 0);
232
+ const uiResources = s.resources.filter((r) => r.uri.startsWith(UI_SCHEME));
233
+ const hasUi = boundTools.length > 0 || uiResources.length > 0 || s.tools.some(legacyBinding);
234
+ if (!hasUi) {
235
+ for (const id of SESSION_CHECKS) {
236
+ if (id !== "tool-security-schemes") add(id, "skip", "the server exposes no UI");
237
+ }
238
+ } else {
239
+ const declared = s.capabilities?.extensions?.[EXTENSION_ID] !== void 0;
240
+ add(
241
+ "extension-declared",
242
+ declared ? "pass" : "fail",
243
+ declared ? `${EXTENSION_ID} is declared` : `the server does not declare ${EXTENSION_ID} in capabilities.extensions`
244
+ );
245
+ const wrongMime = [];
246
+ for (const r of uiResources) {
247
+ if (r.mimeType !== void 0 && r.mimeType !== RESOURCE_MIME_TYPE) {
248
+ wrongMime.push(`${r.uri} is listed as ${r.mimeType}`);
249
+ }
250
+ }
251
+ for (const [uri, contents] of s.reads) {
252
+ if (contents instanceof Error) continue;
253
+ for (const c of contents) {
254
+ if (c.mimeType !== RESOURCE_MIME_TYPE) {
255
+ wrongMime.push(`${uri} is served as ${c.mimeType ?? "no MIME type"}`);
256
+ }
257
+ }
258
+ }
259
+ add(
260
+ "ui-resource-mime",
261
+ wrongMime.length ? "fail" : "pass",
262
+ wrongMime.length ? `${wrongMime.join("; ")}; expected ${RESOURCE_MIME_TYPE}` : `every ui:// resource is ${RESOURCE_MIME_TYPE}`
263
+ );
264
+ const unresolved = [];
265
+ for (const tool of s.tools) {
266
+ const uri = toolUi(tool)?.resourceUri;
267
+ if (uri === void 0) {
268
+ if (legacyBinding(tool)) {
269
+ unresolved.push(`${tool.name} binds its UI only through the deprecated flat key`);
270
+ }
271
+ continue;
272
+ }
273
+ if (typeof uri !== "string" || !uri.startsWith(UI_SCHEME)) {
274
+ unresolved.push(`${tool.name}: ui.resourceUri ${JSON.stringify(uri)} is not a ui:// URI`);
275
+ continue;
276
+ }
277
+ const read = s.reads.get(uri);
278
+ if (read instanceof Error || !read?.length) {
279
+ unresolved.push(
280
+ `${tool.name}: ${uri} cannot be read${read instanceof Error ? ` (${read.message})` : ""}`
281
+ );
282
+ }
283
+ }
284
+ if (boundTools.length === 0 && unresolved.length === 0) {
285
+ unresolved.push("no tool binds a UI through ui.resourceUri");
286
+ }
287
+ add(
288
+ "tool-resource-uri",
289
+ unresolved.length ? "fail" : "pass",
290
+ unresolved.length ? unresolved.join("; ") : `${boundTools.length} tool(s) bind a UI that resolves`
291
+ );
292
+ const badMeta = [];
293
+ for (const tool of s.tools) {
294
+ const ui = toolUi(tool);
295
+ if (!ui) continue;
296
+ const vis = ui.visibility;
297
+ if (vis !== void 0 && (!Array.isArray(vis) || vis.length === 0 || !vis.every((v) => VISIBILITY.has(v)))) {
298
+ badMeta.push(`${tool.name}: ui.visibility ${JSON.stringify(vis)}`);
299
+ }
300
+ for (const key of ["csp", "permissions"]) {
301
+ if (ui[key] !== void 0) {
302
+ badMeta.push(`${tool.name}: ui.${key} is on the tool, where hosts ignore it`);
303
+ }
304
+ }
305
+ }
306
+ add(
307
+ "tool-ui-meta",
308
+ badMeta.length ? "fail" : "pass",
309
+ badMeta.length ? badMeta.join("; ") : "tool ui metadata is well-formed"
310
+ );
311
+ const noCsp = [];
312
+ const noOpenAiCsp = [];
313
+ const dataFonts = [];
314
+ const openAiDataFonts = [];
315
+ for (const [uri, contents] of s.reads) {
316
+ if (contents instanceof Error) continue;
317
+ for (const c of contents) {
318
+ const listed = s.resources.find((r) => r.uri === uri);
319
+ const ui = resourceUi(c) ?? resourceUi(listed);
320
+ const csp = ui?.csp;
321
+ if (csp === void 0) {
322
+ noCsp.push(`${uri} declares no ui.csp`);
323
+ } else if (!isOriginLists(csp)) {
324
+ noCsp.push(`${uri}: ui.csp is not a map of origin lists`);
325
+ }
326
+ const openAi = openAiCsp(c) ?? openAiCsp(listed);
327
+ if (openAi === void 0) {
328
+ noOpenAiCsp.push(`${uri} declares no ${OPENAI_CSP_KEY}`);
329
+ } else if (!isOriginLists(openAi)) {
330
+ noOpenAiCsp.push(`${uri}: ${OPENAI_CSP_KEY} is not a map of origin lists`);
331
+ } else {
332
+ const camel = SPEC_CSP_KEYS.filter((k) => k in openAi);
333
+ if (camel.length) {
334
+ noOpenAiCsp.push(
335
+ `${uri}: ${OPENAI_CSP_KEY} names ${camel.join(", ")}, which ChatGPT does not read`
336
+ );
337
+ }
338
+ }
339
+ const html = "text" in c ? c.text : Buffer.from(c.blob, "base64").toString("utf-8");
340
+ if (hasDataFont(html)) {
341
+ if (!declaresData(csp, "resourceDomains")) {
342
+ dataFonts.push(`${uri} loads a data: font, and ui.csp.resourceDomains omits data:`);
343
+ }
344
+ if (!declaresData(openAi, "resource_domains")) {
345
+ openAiDataFonts.push(
346
+ `${uri} loads a data: font, and ${OPENAI_CSP_KEY}.resource_domains omits data:`
347
+ );
348
+ }
349
+ }
350
+ }
351
+ }
352
+ add(
353
+ "resource-csp",
354
+ noCsp.length ? "fail" : "pass",
355
+ noCsp.length ? noCsp.join("; ") : "every UI resource declares ui.csp"
356
+ );
357
+ add(
358
+ "resource-openai-csp",
359
+ noOpenAiCsp.length ? "fail" : "pass",
360
+ noOpenAiCsp.length ? noOpenAiCsp.join("; ") : `every UI resource declares ${OPENAI_CSP_KEY}`
361
+ );
362
+ add(
363
+ "resource-data-fonts",
364
+ dataFonts.length ? "fail" : "pass",
365
+ dataFonts.length ? dataFonts.join("; ") : "no data: font ui.csp omits"
366
+ );
367
+ add(
368
+ "resource-openai-data-fonts",
369
+ openAiDataFonts.length ? "fail" : "pass",
370
+ openAiDataFonts.length ? openAiDataFonts.join("; ") : `no data: font ${OPENAI_CSP_KEY} omits`
371
+ );
372
+ }
373
+ if (!authRequired) {
374
+ add("tool-security-schemes", "skip", "the server does not require auth");
375
+ } else {
376
+ const missing = s.tools.filter((t) => !hasSecuritySchemes(t)).map((t) => t.name);
377
+ add(
378
+ "tool-security-schemes",
379
+ missing.length ? "fail" : "pass",
380
+ missing.length ? `no securitySchemes on: ${missing.join(", ")}` : "every tool declares securitySchemes"
381
+ );
382
+ }
383
+ }
384
+ async function checkAuth(url, challenge, add) {
385
+ if (!challenge) {
386
+ const reason = "the server answered without a 401 challenge";
387
+ add("auth-challenge", "skip", reason);
388
+ add("auth-resource-metadata", "skip", reason);
389
+ add("auth-issuer", "skip", reason);
390
+ return;
391
+ }
392
+ const { resourceMetadataUrl } = extractWWWAuthenticateParams(challenge);
393
+ add(
394
+ "auth-challenge",
395
+ resourceMetadataUrl ? "pass" : "fail",
396
+ resourceMetadataUrl ? `401 names resource_metadata ${resourceMetadataUrl.href}` : `401 WWW-Authenticate carries no resource_metadata (${JSON.stringify(challenge.headers.get("www-authenticate"))})`
397
+ );
398
+ let prm;
399
+ try {
400
+ prm = await discoverOAuthProtectedResourceMetadata(url, { resourceMetadataUrl });
401
+ } catch (err) {
402
+ add(
403
+ "auth-resource-metadata",
404
+ "fail",
405
+ `protected-resource metadata unreadable: ${message(err)}`
406
+ );
407
+ add("auth-issuer", "skip", "no protected-resource metadata");
408
+ return;
409
+ }
410
+ add(
411
+ "auth-resource-metadata",
412
+ prm.resource === url ? "pass" : "fail",
413
+ prm.resource === url ? `resource equals ${url}` : `resource is ${JSON.stringify(prm.resource)}, not ${JSON.stringify(url)}`
414
+ );
415
+ const advertised = prm.authorization_servers?.[0];
416
+ if (!advertised) {
417
+ add("auth-issuer", "fail", "protected-resource metadata lists no authorization_servers");
418
+ return;
419
+ }
420
+ try {
421
+ const metadata = await discoverAuthorizationServerMetadata(advertised);
422
+ if (!metadata) {
423
+ add("auth-issuer", "fail", `no authorization server metadata found for ${advertised}`);
424
+ } else if (metadata.issuer !== advertised) {
425
+ add(
426
+ "auth-issuer",
427
+ "fail",
428
+ `issuer is ${JSON.stringify(metadata.issuer)}, advertised as ${JSON.stringify(advertised)}`
429
+ );
430
+ } else {
431
+ add("auth-issuer", "pass", `issuer equals ${advertised}`);
432
+ }
433
+ } catch (err) {
434
+ add("auth-issuer", "fail", `authorization server metadata unreadable: ${message(err)}`);
435
+ }
436
+ }
437
+ function toolUi(tool) {
438
+ const ui = tool._meta?.ui;
439
+ return ui && typeof ui === "object" ? ui : void 0;
440
+ }
441
+ function legacyBinding(tool) {
442
+ return tool._meta?.[RESOURCE_URI_META_KEY] !== void 0 && toolUi(tool)?.resourceUri === void 0;
443
+ }
444
+ function resourceUi(item) {
445
+ const ui = item?._meta?.ui;
446
+ return ui && typeof ui === "object" ? ui : void 0;
447
+ }
448
+ var OPENAI_CSP_KEY = "openai/widgetCSP";
449
+ var SPEC_CSP_KEYS = ["connectDomains", "resourceDomains"];
450
+ function openAiCsp(item) {
451
+ return item?._meta?.[OPENAI_CSP_KEY];
452
+ }
453
+ function isOriginLists(value) {
454
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((v) => Array.isArray(v) && v.every((o) => typeof o === "string"));
455
+ }
456
+ function declaresData(csp, key) {
457
+ return isOriginLists(csp) && (csp[key] ?? []).includes("data:");
458
+ }
459
+ function hasSecuritySchemes(tool) {
460
+ const schemes = tool._meta?.securitySchemes ?? tool.securitySchemes;
461
+ return Array.isArray(schemes) && schemes.length > 0;
462
+ }
463
+ var DATA_FONT_MIME = /data:(?:font\/|application\/(?:x-)?font|application\/vnd\.ms-fontobject)/i;
464
+ var FONT_FACE_DATA_URL = /@font-face\s*{[^}]*url\(\s*["']?data:/i;
465
+ function hasDataFont(html) {
466
+ return DATA_FONT_MIME.test(html) || FONT_FACE_DATA_URL.test(html);
467
+ }
468
+ function message(err) {
469
+ return err instanceof Error ? err.message : String(err);
470
+ }
471
+
472
+ export { PROFILES, applyProfiles, formatReport, isTargetName, runChecks };
473
+ //# sourceMappingURL=check-QMTOCTRS.js.map
474
+ //# sourceMappingURL=check-QMTOCTRS.js.map