@botiverse/porthole 0.4.1 → 0.5.1

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 (77) hide show
  1. package/README.md +3 -1
  2. package/dist/bridge/bridge.d.ts +24 -2
  3. package/dist/bridge/bridge.js +102 -17
  4. package/dist/bridge/navigation.d.ts +11 -0
  5. package/dist/bridge/navigation.js +30 -0
  6. package/dist/bridge/refusal.d.ts +53 -0
  7. package/dist/bridge/refusal.js +121 -0
  8. package/dist/bridge/types.d.ts +51 -6
  9. package/dist/check/lint.js +2 -2
  10. package/dist/check/page-source.js +1 -1
  11. package/dist/check/page.js +10 -0
  12. package/dist/compile/policy.d.ts +5 -0
  13. package/dist/compile/policy.js +18 -1
  14. package/dist/config/capabilities.d.ts +30 -2
  15. package/dist/config/capabilities.js +13 -0
  16. package/dist/config/schema.d.ts +7 -0
  17. package/dist/config/validate.js +14 -3
  18. package/dist/conformance/harness/page.js +1 -0
  19. package/dist/conformance/harness-source.js +1 -1
  20. package/dist/displays/displays.d.ts +1 -1
  21. package/dist/guide/guide.js +58 -8
  22. package/dist/host/create-host.js +18 -3
  23. package/dist/host/types.d.ts +25 -1
  24. package/dist/index.d.ts +5 -3
  25. package/dist/index.js +4 -1
  26. package/dist/libraries/files.generated.d.ts +1 -0
  27. package/dist/libraries/files.generated.js +8 -0
  28. package/dist/libraries/libraries.d.ts +36 -0
  29. package/dist/libraries/libraries.js +40 -0
  30. package/dist/mcp/adapter.js +49 -5
  31. package/dist/presets/presets.d.ts +15 -0
  32. package/dist/presets/presets.js +27 -2
  33. package/dist/protocol/live-data.d.ts +27 -0
  34. package/dist/protocol/live-data.js +98 -0
  35. package/dist/protocol/mcp-apps.d.ts +15 -0
  36. package/dist/protocol/mcp-apps.js +17 -0
  37. package/dist/protocol/shell-adapter.js +49 -4
  38. package/dist/react/dialog.js +2 -0
  39. package/dist/react/frame.d.ts +30 -1
  40. package/dist/react/frame.js +63 -1
  41. package/dist/server/libraries.d.ts +7 -0
  42. package/dist/server/libraries.js +27 -0
  43. package/dist/server/server.js +2 -1
  44. package/dist/shell/runtime.d.ts +5 -1
  45. package/dist/shell/runtime.js +196 -6
  46. package/docs/ADOPTING.md +89 -3
  47. package/docs/DECISIONS.md +221 -0
  48. package/docs/DESIGN.md +28 -10
  49. package/package.json +3 -1
  50. package/src/bridge/bridge.ts +136 -16
  51. package/src/bridge/navigation.ts +34 -0
  52. package/src/bridge/refusal.ts +151 -0
  53. package/src/bridge/types.ts +57 -4
  54. package/src/check/lint.ts +2 -1
  55. package/src/check/page.ts +12 -0
  56. package/src/compile/policy.ts +19 -1
  57. package/src/config/capabilities.ts +26 -1
  58. package/src/config/schema.ts +7 -0
  59. package/src/config/validate.ts +21 -3
  60. package/src/conformance/harness/page.ts +1 -0
  61. package/src/displays/displays.ts +1 -1
  62. package/src/guide/guide.ts +71 -7
  63. package/src/host/create-host.ts +19 -3
  64. package/src/host/types.ts +23 -1
  65. package/src/index.ts +22 -0
  66. package/src/libraries/files.generated.ts +8 -0
  67. package/src/libraries/libraries.ts +64 -0
  68. package/src/mcp/adapter.ts +63 -5
  69. package/src/presets/presets.ts +46 -3
  70. package/src/protocol/live-data.ts +138 -0
  71. package/src/protocol/mcp-apps.ts +19 -0
  72. package/src/protocol/shell-adapter.ts +50 -5
  73. package/src/react/dialog.tsx +2 -0
  74. package/src/react/frame.tsx +93 -0
  75. package/src/server/libraries.ts +28 -0
  76. package/src/server/server.ts +2 -1
  77. package/src/shell/runtime.ts +196 -6
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Porthole's vendored libraries (P079): a small fixed set, pinned, copied byte for byte from their
3
+ * npm packages when Porthole is built (`scripts/vendor-libraries.ts`), and served by `/server` on
4
+ * every content origin under `LIBRARY_PATH`. A config that sets `egress.libraries` loads scripts
5
+ * from there (its own origin) and the manual teaches the lines below; nothing else is fetched.
6
+ *
7
+ * A path, once released, keeps serving the same bytes: a new version is a new path beside it.
8
+ */
9
+
10
+ /** Where the libraries are served on a content origin (inside Porthole's reserved prefix). */
11
+ export const LIBRARY_PATH = "/__porthole/lib/";
12
+
13
+ export interface VendoredLibrary {
14
+ /** What the manual calls it. */
15
+ readonly title: string;
16
+ /** The npm package. */
17
+ readonly name: string;
18
+ /** Its exact version (published at least two weeks before it was vendored). */
19
+ readonly version: string;
20
+ /** The file served, as a path inside the package (a classic script: it defines `global`). */
21
+ readonly file: string;
22
+ /** The global the script defines. */
23
+ readonly global: string;
24
+ /** Its license (SPDX), and the package's license file, served beside it. */
25
+ readonly license: string;
26
+ readonly licenseFile: string;
27
+ /** What it is for, for the manual. */
28
+ readonly use: string;
29
+ }
30
+
31
+ /**
32
+ * What agent-made widgets reach for most: Chart.js for charts, D3 for anything drawn from data
33
+ * (scales, axes, shapes, time and number formats). Both run as classic scripts.
34
+ */
35
+ export const VENDORED_LIBRARIES: readonly VendoredLibrary[] = [
36
+ {
37
+ title: "Chart.js",
38
+ name: "chart.js",
39
+ version: "4.5.1",
40
+ file: "dist/chart.umd.min.js",
41
+ global: "Chart",
42
+ license: "MIT",
43
+ licenseFile: "LICENSE.md",
44
+ use: "charts",
45
+ },
46
+ {
47
+ title: "D3",
48
+ name: "d3",
49
+ version: "7.9.0",
50
+ file: "dist/d3.min.js",
51
+ global: "d3",
52
+ license: "ISC",
53
+ licenseFile: "LICENSE",
54
+ use: "scales, axes, shapes, time and number formats",
55
+ },
56
+ ];
57
+
58
+ /** Where a library's file is served, on the frame's own origin. */
59
+ export const libraryPath = (library: VendoredLibrary): string =>
60
+ `${LIBRARY_PATH}${library.name}@${library.version}/${library.file}`;
61
+
62
+ /** Where its license is served, beside it. */
63
+ export const licensePath = (library: VendoredLibrary): string =>
64
+ `${LIBRARY_PATH}${library.name}@${library.version}/${library.licenseFile}`;
@@ -14,7 +14,13 @@ import {
14
14
  MCP_APPS_PROTOCOL_VERSION,
15
15
  type HostContext,
16
16
  } from "../protocol/mcp-apps.ts";
17
- import { COPY_TEXT_METHOD, MCP_APPS_STYLE_VARIABLES } from "../protocol/mcp-apps.ts";
17
+ import {
18
+ COPY_TEXT_METHOD,
19
+ MCP_APPS_STYLE_VARIABLES,
20
+ NAVIGATION_BLOCKED_METHOD,
21
+ } from "../protocol/mcp-apps.ts";
22
+ import { liveData } from "../protocol/live-data.ts";
23
+ import { reasonFor } from "../bridge/refusal.ts";
18
24
 
19
25
  /**
20
26
  * The MCP Apps adapter (P004, P007): the host side of the protocol for full MCP Apps views, written
@@ -131,6 +137,10 @@ function connect(session: AdapterSession, options: McpAppsAdapterOptions): McpAp
131
137
  }
132
138
  };
133
139
  const answer = (id: JsonRpcId, result: unknown): void => send({ jsonrpc: "2.0", id, result });
140
+ // Live data (P079): reads, subscriptions and the host's updates, through the bridge.
141
+ const live = liveData(bridge, (uri) => notify(MCP_APPS_METHODS.resourceUpdated, { uri }), {
142
+ userActivated: hostActivation,
143
+ });
134
144
  const refuse = (id: JsonRpcId, code: number, message: string): void =>
135
145
  send({ jsonrpc: "2.0", id, error: { code, message } });
136
146
 
@@ -150,7 +160,9 @@ function connect(session: AdapterSession, options: McpAppsAdapterOptions): McpAp
150
160
  ...(declared("openLink") ? { openLinks: {} } : {}),
151
161
  ...(declared("downloadFile") ? { downloadFile: {} } : {}),
152
162
  ...(declared("callTool") ? { serverTools: {} } : {}),
153
- ...(declared("readData") ? { serverResources: {} } : {}),
163
+ ...(declared("readData")
164
+ ? { serverResources: declared("subscribeData") ? { subscribe: true } : {} }
165
+ : {}),
154
166
  ...(declared("sendPrompt") ? { message: { text: {} } } : {}),
155
167
  ...(declared("setModelContext")
156
168
  ? { updateModelContext: { text: {}, structuredContent: {} } }
@@ -183,13 +195,32 @@ function connect(session: AdapterSession, options: McpAppsAdapterOptions): McpAp
183
195
  refuse(request.id, JSON_RPC_ERRORS.internal, `${request.method} failed`);
184
196
  return;
185
197
  }
198
+ reply(request, capability, outcome, result);
199
+ }
200
+
201
+ /** Answers a request with a capability's outcome. */
202
+ function reply(
203
+ request: JsonRpcRequest,
204
+ capability: CapabilityName,
205
+ outcome: CallOutcome<unknown>,
206
+ result: (value: unknown) => unknown,
207
+ ): void {
186
208
  if (outcome.ok) {
187
209
  answer(request.id, result(outcome.value));
188
210
  } else if (outcome.refusal === "not-declared") {
189
211
  refuse(request.id, JSON_RPC_ERRORS.methodNotFound, `${request.method} isn't offered here`);
190
212
  } else {
191
- // The spec's "implementation-defined" error for a refused request.
192
- refuse(request.id, -32_000, `${request.method} refused (${outcome.refusal})`);
213
+ // The spec's "implementation-defined" error for a refused request, with why in its data
214
+ // (`{ code, message }`, P080).
215
+ send({
216
+ jsonrpc: "2.0",
217
+ id: request.id,
218
+ error: {
219
+ code: -32_000,
220
+ message: `${request.method} refused (${outcome.refusal})`,
221
+ data: reasonFor(capability, outcome),
222
+ },
223
+ });
193
224
  }
194
225
  }
195
226
 
@@ -259,10 +290,31 @@ function connect(session: AdapterSession, options: McpAppsAdapterOptions): McpAp
259
290
  invalid("needs a uri");
260
291
  return;
261
292
  }
262
- await call(request, "readData", { uri: params.uri }, (value) =>
293
+ reply(request, "readData", await live.read(params.uri), (value) =>
263
294
  isRecord(value) ? value : { contents: [] },
264
295
  );
265
296
  return;
297
+ case MCP_APPS_METHODS.subscribeResource:
298
+ case MCP_APPS_METHODS.unsubscribeResource:
299
+ if (!bridge.declared("subscribeData")) {
300
+ refuse(
301
+ request.id,
302
+ JSON_RPC_ERRORS.methodNotFound,
303
+ `${request.method} isn't offered here`,
304
+ );
305
+ return;
306
+ }
307
+ if (typeof params.uri !== "string") {
308
+ invalid("needs a uri");
309
+ return;
310
+ }
311
+ if (request.method === MCP_APPS_METHODS.unsubscribeResource) {
312
+ live.unsubscribe(params.uri);
313
+ answer(request.id, {});
314
+ return;
315
+ }
316
+ reply(request, "subscribeData", await live.subscribe(params.uri), () => ({}));
317
+ return;
266
318
  case MCP_APPS_METHODS.updateModelContext:
267
319
  if (
268
320
  (params.content !== undefined && !Array.isArray(params.content)) ||
@@ -351,6 +403,11 @@ function connect(session: AdapterSession, options: McpAppsAdapterOptions): McpAp
351
403
  });
352
404
  }
353
405
  return;
406
+ case NAVIGATION_BLOCKED_METHOD:
407
+ // The shell, hardening the view's frame, stopped a navigation (P080): an error report,
408
+ // with its address.
409
+ void bridge.call("reportError", { navigationBlocked: params.url });
410
+ return;
354
411
  case MCP_APPS_METHODS.requestTeardown:
355
412
  session.emit({ type: "teardown-requested" });
356
413
  return;
@@ -404,6 +461,7 @@ function connect(session: AdapterSession, options: McpAppsAdapterOptions): McpAp
404
461
  },
405
462
  close() {
406
463
  closed = true;
464
+ live.close();
407
465
  unlisten();
408
466
  queue = [];
409
467
  for (const waiting of pending.values()) {
@@ -14,7 +14,7 @@ import type {
14
14
  UrlPermission,
15
15
  UrlSandboxExtra,
16
16
  } from "../config/schema.ts";
17
- import { validateConfig } from "../config/validate.ts";
17
+ import { ConfigError, validateConfig } from "../config/validate.ts";
18
18
  import { DEFAULT_THEME_EVENT, DEFAULT_THEME_VARIABLES } from "../theme/variables.ts";
19
19
 
20
20
  /**
@@ -52,6 +52,12 @@ export interface PresetOptions {
52
52
  readonly errors?: "agent" | "host" | "none";
53
53
  }
54
54
 
55
+ /**
56
+ * The live widget's options (P079): a widget's, less egress, which stays closed (Porthole's own
57
+ * libraries come with domain isolation). A host adds capabilities, or changes the data ones' gates.
58
+ */
59
+ export type LiveWidgetOptions = Omit<PresetOptions, "egress">;
60
+
55
61
  /** The url preset's options: where the app is served, and the embedding page's extra frames. */
56
62
  export interface UrlPresetOptions {
57
63
  readonly contentOrigins: readonly string[];
@@ -137,6 +143,9 @@ const mergeEgress = (base: EgressConfig, extra: EgressConfig | undefined): Egres
137
143
  if (passive.length > 0) {
138
144
  merged.anyHttps = passive;
139
145
  }
146
+ if (base.libraries === true || extra?.libraries === true) {
147
+ merged.libraries = true;
148
+ }
140
149
  return merged;
141
150
  };
142
151
 
@@ -157,11 +166,16 @@ function themeVariables(
157
166
 
158
167
  function build(
159
168
  mode: PortholeConfig["mode"],
160
- defaults: { readonly limits?: Partial<Limits> },
169
+ defaults: {
170
+ readonly limits?: Partial<Limits>;
171
+ readonly capabilities?: CapabilityMap;
172
+ readonly egress?: EgressConfig;
173
+ },
161
174
  options: PresetOptions,
162
175
  ): PortholeConfig {
163
176
  const capabilities: { -readonly [N in CapabilityName]?: CapabilityConfig } = {
164
177
  ...BASE_CAPABILITIES,
178
+ ...defaults.capabilities,
165
179
  };
166
180
  if (options.errors === "none") {
167
181
  delete capabilities.reportError;
@@ -180,7 +194,7 @@ function build(
180
194
  mode,
181
195
  isolation: options.isolation ?? "opaque",
182
196
  capabilities,
183
- egress: mergeEgress({}, options.egress),
197
+ egress: mergeEgress(defaults.egress ?? {}, options.egress),
184
198
  theme: {
185
199
  variables: themeVariables(options.theme?.variables),
186
200
  event: options.theme?.event ?? DEFAULT_THEME_EVENT,
@@ -203,6 +217,35 @@ export const presets = {
203
217
  */
204
218
  inlineWidget: (options: PresetOptions = {}): PortholeConfig => build("inline", {}, options),
205
219
 
220
+ /**
221
+ * A widget that shows its host's data, live, and has no network of its own (P079): an inline
222
+ * widget whose egress stays closed (no option opens it). It reads the host's data (`readData`,
223
+ * MCP `resources/read`) and subscribes to it (`subscribeData`, `resources/subscribe`), each
224
+ * behind the viewer's consent (the host's `consent`, asked once per display) and a rate. In
225
+ * domain isolation its scripts load from Porthole's own libraries on its origin
226
+ * (`egress.libraries`: Chart.js, D3), and nowhere else. A host adds what any widget may have (a
227
+ * link, a copy button), or changes the data capabilities' gates.
228
+ */
229
+ liveWidget: (options: LiveWidgetOptions = {}): PortholeConfig => {
230
+ if ((options as PresetOptions).egress !== undefined) {
231
+ throw new ConfigError(
232
+ "options.egress",
233
+ "a live widget has no network of its own: its egress stays closed (P079)",
234
+ );
235
+ }
236
+ return build(
237
+ "inline",
238
+ {
239
+ capabilities: {
240
+ readData: { gates: ["consent", { rateLimit: { perMinute: 120 } }] },
241
+ subscribeData: { gates: ["consent", { rateLimit: { perMinute: 60 } }] },
242
+ },
243
+ egress: options.isolation === "domain" ? { libraries: true } : {},
244
+ },
245
+ options,
246
+ );
247
+ },
248
+
206
249
  /**
207
250
  * A whole HTML page: written into an opaque frame by the shell where the host has the page, or
208
251
  * served on its own origin (`isolation: "domain"`). A document scrolls inside past a shorter cap.
@@ -0,0 +1,138 @@
1
+ import type { CallOutcome, HostFunctionBridge } from "../bridge/types.ts";
2
+ import { STALE_META } from "./mcp-apps.ts";
3
+
4
+ /**
5
+ * Live data for one frame (P079), as both adapters speak it (MCP `resources/read`,
6
+ * `resources/subscribe`, `resources/unsubscribe`, `notifications/resources/updated`): the frame's
7
+ * subscriptions by URI, each ended by its controller, and a fresh result the host gave for one
8
+ * (pushed through `changed(result)`, or read after a stale answer), kept for the frame's next read
9
+ * of it. Every call goes through the bridge, which gates it; the adapter only says what to send.
10
+ */
11
+ export interface LiveData {
12
+ /** A read: a fresh result kept for it, else the host's (its cache first, when subscribed). */
13
+ read(uri: unknown): Promise<CallOutcome<unknown>>;
14
+ /** Starts the host's subscription; a second for a URI is a no-op. */
15
+ subscribe(uri: unknown): Promise<CallOutcome<undefined>>;
16
+ /** Ends one: never gated, it stops what the host was doing for this frame. */
17
+ unsubscribe(uri: unknown): void;
18
+ /** The frame is gone: every subscription ends. */
19
+ close(): void;
20
+ }
21
+
22
+ /** Where MCP results carry their metadata. */
23
+ const META = "_meta";
24
+
25
+ /** A `resources/read` result marked as the host's cached copy (`STALE_META`). */
26
+ export function markedStale(value: unknown): unknown {
27
+ const result =
28
+ value !== null && typeof value === "object" ? (value as Record<string, unknown>) : {};
29
+ const given = result[META];
30
+ const meta =
31
+ given !== null && typeof given === "object" ? (given as Record<string, unknown>) : {};
32
+ return { ...result, [META]: { ...meta, [STALE_META]: true } };
33
+ }
34
+
35
+ /**
36
+ * `updated(uri)` sends the frame `notifications/resources/updated`; it is called only for a URI
37
+ * the frame subscribes to.
38
+ */
39
+ export function liveData(
40
+ bridge: HostFunctionBridge,
41
+ updated: (uri: string) => void,
42
+ options: { readonly userActivated?: () => boolean | undefined } = {},
43
+ ): LiveData {
44
+ const subscriptions = new Map<string, AbortController>();
45
+ const fresh = new Map<string, unknown>();
46
+ let closed = false;
47
+ const tell = (uri: string) => {
48
+ if (!closed && subscriptions.has(uri)) {
49
+ updated(uri);
50
+ }
51
+ };
52
+ const activation = () => {
53
+ const userActivated = options.userActivated?.();
54
+ return userActivated === undefined ? {} : { userActivated };
55
+ };
56
+ const end = (uri: string) => {
57
+ subscriptions.get(uri)?.abort();
58
+ subscriptions.delete(uri);
59
+ fresh.delete(uri);
60
+ };
61
+
62
+ return {
63
+ async read(uri) {
64
+ if (typeof uri === "string" && fresh.has(uri)) {
65
+ const value = fresh.get(uri);
66
+ fresh.delete(uri);
67
+ return { ok: true, value };
68
+ }
69
+ const subscribed = typeof uri === "string" && subscriptions.has(uri);
70
+ const outcome = await bridge.call(
71
+ "readData",
72
+ { uri },
73
+ { ...activation(), stale: subscribed },
74
+ );
75
+ if (!outcome.ok || outcome.stale !== true || typeof uri !== "string") {
76
+ return outcome;
77
+ }
78
+ // Answered from the host's cache: the fresh result, for the frame's next read, is told once
79
+ // it is here.
80
+ void bridge.call("readData", { uri }, activation()).then((next) => {
81
+ if (next.ok && !closed && subscriptions.has(uri)) {
82
+ fresh.set(uri, next.value);
83
+ tell(uri);
84
+ }
85
+ });
86
+ return { ok: true, value: markedStale(outcome.value) };
87
+ },
88
+
89
+ async subscribe(uri) {
90
+ if (typeof uri === "string" && subscriptions.has(uri)) {
91
+ return { ok: true, value: undefined };
92
+ }
93
+ const controller = new AbortController();
94
+ if (typeof uri === "string") {
95
+ subscriptions.set(uri, controller);
96
+ }
97
+ const outcome = await bridge.call(
98
+ "subscribeData",
99
+ { uri },
100
+ {
101
+ ...activation(),
102
+ subscription: {
103
+ signal: controller.signal,
104
+ changed: (result?: unknown) => {
105
+ if (controller.signal.aborted || closed || typeof uri !== "string") {
106
+ return;
107
+ }
108
+ if (result !== undefined) {
109
+ fresh.set(uri, result);
110
+ }
111
+ tell(uri);
112
+ },
113
+ },
114
+ },
115
+ );
116
+ if (!outcome.ok) {
117
+ controller.abort();
118
+ if (typeof uri === "string" && subscriptions.get(uri) === controller) {
119
+ subscriptions.delete(uri);
120
+ }
121
+ }
122
+ return outcome;
123
+ },
124
+
125
+ unsubscribe(uri) {
126
+ if (typeof uri === "string") {
127
+ end(uri);
128
+ }
129
+ },
130
+
131
+ close() {
132
+ closed = true;
133
+ for (const uri of subscriptions.keys()) {
134
+ end(uri);
135
+ }
136
+ },
137
+ };
138
+ }
@@ -17,6 +17,10 @@ export const MCP_APPS_METHODS = {
17
17
  updateModelContext: "ui/update-model-context",
18
18
  callTool: "tools/call",
19
19
  readResource: "resources/read",
20
+ // MCP's own resource subscriptions (P079), which MCP Apps doesn't list: the view is the host's
21
+ // MCP client here, as for resources/read.
22
+ subscribeResource: "resources/subscribe",
23
+ unsubscribeResource: "resources/unsubscribe",
20
24
  // View → host notifications.
21
25
  initialized: "ui/notifications/initialized",
22
26
  sizeChanged: "ui/notifications/size-changed",
@@ -28,6 +32,7 @@ export const MCP_APPS_METHODS = {
28
32
  toolResult: "ui/notifications/tool-result",
29
33
  toolCancelled: "ui/notifications/tool-cancelled",
30
34
  hostContextChanged: "ui/notifications/host-context-changed",
35
+ resourceUpdated: "notifications/resources/updated",
31
36
  // Host → view requests.
32
37
  resourceTeardown: "ui/resource-teardown",
33
38
  // Sandbox proxy (a second origin that relays between host and view).
@@ -121,6 +126,20 @@ export const PORTHOLE_STYLES = "porthole/styles";
121
126
  */
122
127
  export const COPY_TEXT_METHOD = "porthole/copy-text";
123
128
 
129
+ /**
130
+ * The `_meta` key that marks a `resources/read` result as the host's cached copy (P079): stale,
131
+ * with the fresh one to follow as `notifications/resources/updated`. Only for a resource the view
132
+ * subscribes to.
133
+ */
134
+ export const STALE_META = "porthole/stale";
135
+
136
+ /**
137
+ * Porthole's own notification from the shell (P080): it cancelled a navigation of the frame to
138
+ * `{ url }` (P079). The content's word, sent only where `reportError` is declared, and counted as
139
+ * one of its reports; the host's adapter carries it into `reportError`.
140
+ */
141
+ export const NAVIGATION_BLOCKED_METHOD = "porthole/navigation-blocked";
142
+
124
143
  /** The logger name the shell's error reports (`notifications/message`, level `error`) carry. */
125
144
  export const SHELL_LOGGER = "porthole";
126
145
 
@@ -8,12 +8,15 @@ import {
8
8
  type JsonRpcRequest,
9
9
  type JsonRpcResponse,
10
10
  } from "./jsonrpc.ts";
11
+ import { reasonFor, type RefusalReason } from "../bridge/refusal.ts";
11
12
  import {
12
13
  COPY_TEXT_METHOD,
14
+ NAVIGATION_BLOCKED_METHOD,
13
15
  MCP_APPS_METHODS as M,
14
16
  MCP_APPS_PROTOCOL_VERSION,
15
17
  type HostContext,
16
18
  } from "./mcp-apps.ts";
19
+ import { liveData } from "./live-data.ts";
17
20
 
18
21
  /**
19
22
  * The core's adapter: the host side of the MCP Apps subset the shell speaks, which content using
@@ -56,7 +59,6 @@ const REQUESTS: Readonly<
56
59
  capability: "callTool",
57
60
  args: (params) => ({ name: params.name, arguments: params.arguments }),
58
61
  },
59
- [M.readResource]: { capability: "readData", args: (params) => ({ uri: params.uri }) },
60
62
  [M.updateModelContext]: {
61
63
  capability: "setModelContext",
62
64
  args: (params) => ({ content: params.content, structuredContent: params.structuredContent }),
@@ -67,7 +69,7 @@ const REQUESTS: Readonly<
67
69
  function answer(
68
70
  capability: CapabilityName,
69
71
  outcome: CallOutcome<unknown>,
70
- ): { result: unknown } | { error: { code: number; message: string } } {
72
+ ): { result: unknown } | { error: { code: number; message: string; data?: RefusalReason } } {
71
73
  const flagged =
72
74
  capability === "sendPrompt" ||
73
75
  capability === "openLink" ||
@@ -76,7 +78,14 @@ function answer(
76
78
  if (!outcome.ok) {
77
79
  return flagged
78
80
  ? { result: { isError: true } }
79
- : { error: { code: -32000, message: `Refused (${outcome.refusal})` } };
81
+ : {
82
+ // Why, in the error's data (`{ code, message }`, P080).
83
+ error: {
84
+ code: -32000,
85
+ message: `Refused (${outcome.refusal})`,
86
+ data: reasonFor(capability, outcome),
87
+ },
88
+ };
80
89
  }
81
90
  if (flagged) {
82
91
  return { result: outcome.value === true ? {} : { isError: true } };
@@ -102,7 +111,8 @@ export function hostCapabilities(
102
111
  offered.serverTools = {};
103
112
  }
104
113
  if (declared("readData")) {
105
- offered.serverResources = {};
114
+ // MCP's own flag for resources/subscribe (P079), in the field that mirrors MCP's capability.
115
+ offered.serverResources = declared("subscribeData") ? { subscribe: true } : {};
106
116
  }
107
117
  if (declared("setModelContext")) {
108
118
  offered.updateModelContext = { text: {} };
@@ -124,7 +134,6 @@ export const shellAdapter: ProtocolAdapter<ShellConnection> = {
124
134
  let sentWhole = false;
125
135
  let nextId = 1;
126
136
  const pending = new Map<JsonRpcId, (response: JsonRpcResponse) => void>();
127
-
128
137
  const respond = (
129
138
  id: JsonRpcId,
130
139
  body: { result: unknown } | { error: { code: number; message: string } },
@@ -132,6 +141,9 @@ export const shellAdapter: ProtocolAdapter<ShellConnection> = {
132
141
  const notify = (method: string, params: Record<string, unknown>) =>
133
142
  transport.send({ jsonrpc: "2.0", method, params });
134
143
 
144
+ // Live data (P079): reads, subscriptions and the host's updates, through the bridge.
145
+ const live = liveData(bridge, (uri) => notify(M.resourceUpdated, { uri }));
146
+
135
147
  const flush = () => {
136
148
  if (!initialized || closed || content === null || sentWhole) {
137
149
  return;
@@ -168,6 +180,34 @@ export const shellAdapter: ProtocolAdapter<ShellConnection> = {
168
180
  respond(request.id, { result: { mode: "inline" } });
169
181
  return;
170
182
  }
183
+ if (request.method === M.readResource) {
184
+ const outcome = await live.read(params.uri);
185
+ if (!closed) {
186
+ respond(request.id, answer("readData", outcome));
187
+ }
188
+ return;
189
+ }
190
+ if (request.method === M.subscribeResource || request.method === M.unsubscribeResource) {
191
+ if (!bridge.declared("subscribeData")) {
192
+ respond(request.id, {
193
+ error: {
194
+ code: JSON_RPC_ERRORS.methodNotFound,
195
+ message: `${request.method} isn't offered here`,
196
+ },
197
+ });
198
+ return;
199
+ }
200
+ if (request.method === M.subscribeResource) {
201
+ const outcome = await live.subscribe(params.uri);
202
+ if (!closed) {
203
+ respond(request.id, outcome.ok ? { result: {} } : answer("subscribeData", outcome));
204
+ }
205
+ } else {
206
+ live.unsubscribe(params.uri);
207
+ respond(request.id, { result: {} });
208
+ }
209
+ return;
210
+ }
171
211
  const mapped = REQUESTS[request.method];
172
212
  if (mapped === undefined) {
173
213
  respond(request.id, {
@@ -205,6 +245,10 @@ export const shellAdapter: ProtocolAdapter<ShellConnection> = {
205
245
  });
206
246
  }
207
247
  return;
248
+ case NAVIGATION_BLOCKED_METHOD:
249
+ // The shell stopped a navigation (P080): an error report, with its address.
250
+ void bridge.call("reportError", { navigationBlocked: params.url });
251
+ return;
208
252
  case M.requestTeardown:
209
253
  session.emit({ type: "teardown-requested" });
210
254
  return;
@@ -264,6 +308,7 @@ export const shellAdapter: ProtocolAdapter<ShellConnection> = {
264
308
  closed = true;
265
309
  stop();
266
310
  pending.clear();
311
+ live.close();
267
312
  },
268
313
  };
269
314
  },
@@ -66,6 +66,8 @@ function words(request: ConfirmRequest): Words {
66
66
  return { heading: "Share this with the agent?", accept: "Share", detail: json(request.args) };
67
67
  case "readData":
68
68
  return { heading: "Let it read this?", accept: "Allow", detail: request.args.uri };
69
+ case "subscribeData":
70
+ return { heading: "Let it follow this?", accept: "Allow", detail: request.args.uri };
69
71
  case "copyText":
70
72
  return { heading: "Copy this text?", accept: "Copy", detail: request.args.text };
71
73
  default: