switch-ext-kit 0.0.0-stage → 0.2.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.
package/src/app.ts ADDED
@@ -0,0 +1,852 @@
1
+ // The app convention: tools as MCP tools, events as MCP Events (SEP-3415, push delivery) with an
2
+ // Effect Schema and a version, widgets as A2UI (v1.0): `ui://` resources holding A2UI messages, each
3
+ // listed with its descriptor. Custom drawing is an MCP App inside, in A2UI's `McpApp` component.
4
+ import { Database } from "bun:sqlite"
5
+ import { randomUUID } from "node:crypto"
6
+ import { mkdirSync } from "node:fs"
7
+ import path from "node:path"
8
+ import { McpServer, ProtocolError } from "@modelcontextprotocol/server"
9
+ import type {
10
+ CallToolResult,
11
+ StandardSchemaWithJSON,
12
+ Transport,
13
+ } from "@modelcontextprotocol/server"
14
+ import {
15
+ Context,
16
+ Deferred,
17
+ Effect,
18
+ Exit,
19
+ FiberSet,
20
+ Layer,
21
+ Option,
22
+ PubSub,
23
+ Result,
24
+ Schema,
25
+ } from "effect"
26
+ import type { Scope } from "effect"
27
+
28
+ import { Rejected } from "./events.ts"
29
+ import type { Need } from "./manifest.ts"
30
+ import type { Draft, EventDef } from "./events.ts"
31
+ import { Peer } from "./models.ts"
32
+ import { uiEvents } from "./ui.ts"
33
+
34
+ export const EVENTS = "io.modelcontextprotocol/events"
35
+ export const SUBSCRIPTION = "io.modelcontextprotocol/subscriptionId"
36
+ /** An event type's version, in its `events/list` entry. */
37
+ export const VERSION = "ax.switch/version"
38
+ /** The connections an app needs, in its server capabilities' extensions. */
39
+ export const CONNECTIONS = "ax.switch/connections"
40
+ /**
41
+ * What an extension reaches beyond itself, in its handshake: other extensions' tools it calls
42
+ * (`switch/call`), the brain's event types it follows (`switch/follow`) and the work whose live
43
+ * sessions it may steer beyond its own side threads (`switch/steer`), each a name or a prefix
44
+ * ending in `*`. Nothing else is answered.
45
+ */
46
+ export const REACHES = "ax.switch/reaches"
47
+ /**
48
+ * Who asked for a tool call, in its `_meta`: the thread of the work that called it and that work's
49
+ * space. The core sets it on an agent's call, and passes on what an extension calling another's tool
50
+ * (`switch/call`) gives as its own call's.
51
+ */
52
+ export const CALLER = "ax.switch/caller"
53
+ export interface CallerShape {
54
+ readonly thread: string | null
55
+ readonly space: string | null
56
+ }
57
+ /** The work that asked for the tool call running now; nulls when the core didn't say. */
58
+ export const Caller: Context.Reference<CallerShape> = Context.Reference<CallerShape>(CALLER, {
59
+ defaultValue: () => ({ thread: null, space: null }),
60
+ })
61
+ const callerOf = Schema.decodeUnknownOption(
62
+ Schema.Struct({
63
+ [CALLER]: Schema.Struct({
64
+ thread: Schema.NullOr(Schema.String),
65
+ space: Schema.NullOr(Schema.String),
66
+ }),
67
+ }),
68
+ )
69
+ /**
70
+ * Tells whoever called the running tool how it's going (MCP's `notifications/progress`, when the
71
+ * call asked with a `progressToken`): a line of words, and how far along, else one step more.
72
+ */
73
+ export type ProgressShape = (
74
+ message: string,
75
+ progress?: number,
76
+ total?: number,
77
+ ) => Effect.Effect<void>
78
+ export const Progress: Context.Reference<ProgressShape> = Context.Reference<ProgressShape>(
79
+ "ax.switch/progress",
80
+ { defaultValue: () => () => Effect.void },
81
+ )
82
+ const progressTokenOf = Schema.decodeUnknownOption(
83
+ Schema.Struct({ progressToken: Schema.Union([Schema.String, Schema.Finite]) }),
84
+ )
85
+
86
+ /**
87
+ * A tool call made once, in its `_meta`: a stable id (an item's answer to the extension that raised
88
+ * it, say). The kit runs the tool once per id, across restarts (in the outbox's file): the same id
89
+ * again answers that it ran, and one cut off partway (the extension stopped) isn't run again but
90
+ * answers that it may have run. Every extension dedupes this way without code of its own.
91
+ */
92
+ export const ONCE = "ax.switch/once"
93
+ const onceOf = Schema.decodeUnknownOption(Schema.Struct({ [ONCE]: Schema.String }))
94
+
95
+ /**
96
+ * A tool's answer that's a check's refusal (`Rejected` with `check`), in its `_meta`: an error the
97
+ * caller fixes, never a sign the extension is failing.
98
+ */
99
+ export const REFUSED = "ax.switch/refused"
100
+
101
+ /** A widget's descriptor, in its `ui://` resource's `resources/list` entry. */
102
+ export const WIDGET = "ax.switch/widget"
103
+ /** What a widget's resource holds: a JSON array of A2UI messages. */
104
+ export const A2UI_MIME_TYPE = "application/a2ui+json"
105
+
106
+ /** A brain event an app publishes: `defineEvent`'s result. */
107
+ export interface AppEvent extends EventDef {
108
+ readonly payload: Schema.Top
109
+ }
110
+
111
+ export interface Tool<R> {
112
+ readonly name: string
113
+ readonly description: string
114
+ readonly readOnly: boolean
115
+ /** What it changes stays in Switch: the brain, or the user's own chat (MCP's openWorldHint false). */
116
+ readonly closed: boolean
117
+ /** It sends something out in the user's name: the Outbound gate reads it first. */
118
+ readonly speaks: boolean
119
+ /** Only the user's clients call it, never the agent (MCP Apps' `visibility: ["app"]`). */
120
+ readonly appOnly: boolean
121
+ readonly input: StandardSchemaWithJSON | undefined
122
+ readonly run: (input: unknown) => Effect.Effect<unknown, unknown, R>
123
+ }
124
+
125
+ const standard = (schema: Schema.Codec<unknown, unknown>): StandardSchemaWithJSON =>
126
+ Schema.toStandardJSONSchemaV1(Schema.toStandardSchemaV1(schema))
127
+
128
+ interface ToolOptions {
129
+ readonly description: string
130
+ /** It only looks, changing nothing. */
131
+ readonly readOnly?: boolean
132
+ /** What it changes stays in Switch: the brain, or the user's own chat. */
133
+ readonly closed?: boolean
134
+ /** It sends something out in the user's name (a text, an email, a call). */
135
+ readonly speaks?: boolean
136
+ /** Only the user's clients call it, never the agent. */
137
+ readonly appOnly?: boolean
138
+ }
139
+
140
+ /** A tool fails with a `Rejected`, or any error whose message is what went wrong. */
141
+ export function tool<I, A, E, R>(
142
+ name: string,
143
+ options: ToolOptions & { readonly input: Schema.Codec<I, unknown> },
144
+ run: (input: I) => Effect.Effect<A, E, R>,
145
+ ): Tool<R>
146
+ export function tool<A, E, R>(
147
+ name: string,
148
+ options: ToolOptions,
149
+ run: () => Effect.Effect<A, E, R>,
150
+ ): Tool<R>
151
+ export function tool<R>(
152
+ name: string,
153
+ options: ToolOptions & { readonly input?: Schema.Codec<unknown, unknown> },
154
+ run: (input?: unknown) => Effect.Effect<unknown, unknown, R>,
155
+ ): Tool<R> {
156
+ const { input } = options
157
+ return {
158
+ name,
159
+ description: options.description,
160
+ readOnly: options.readOnly === true,
161
+ closed: options.closed === true,
162
+ speaks: options.speaks === true,
163
+ appOnly: options.appOnly === true,
164
+ input: input && standard(input),
165
+ run: input ? (raw) => Effect.flatMap(Schema.decodeUnknownEffect(input)(raw), run) : () => run(),
166
+ }
167
+ }
168
+
169
+ /** Where a widget can show. */
170
+ export type Surface = "chat" | "space" | "liveActivity" | "wallet"
171
+ const surface = Schema.Literals(["chat", "space", "liveActivity", "wallet"])
172
+
173
+ /** A widget's shape: kept square, wider than tall, taller than wide, or as its content needs. */
174
+ export type Aspect = "square" | "wide" | "tall" | "auto"
175
+
176
+ /** A size in grid units: a unit is one square cell of the host's grid. */
177
+ export interface Units {
178
+ readonly cols: number
179
+ readonly rows: number
180
+ }
181
+
182
+ /** How a widget sits in a space's grid. */
183
+ export interface Size {
184
+ readonly aspect: Aspect
185
+ /** The width over height a wide or tall one keeps: 16 / 9. */
186
+ readonly ratio?: number
187
+ readonly min?: Units
188
+ readonly preferred?: Units
189
+ /** The most it takes, however much room there is: a watch face stays watch-sized. */
190
+ readonly max?: Units
191
+ /** It may take more than `preferred`, up to `max`: made bigger, or filling room left over. */
192
+ readonly grows?: boolean
193
+ /** With nothing to show (its view draws only an empty state): a single line, or hidden. */
194
+ readonly empty?: "line" | "hide"
195
+ }
196
+
197
+ const count = Schema.Int.check(Schema.isGreaterThan(0))
198
+ const units = Schema.Struct({ cols: count, rows: count })
199
+
200
+ export const size: Schema.Codec<Size> = Schema.Struct({
201
+ aspect: Schema.Literals(["square", "wide", "tall", "auto"]),
202
+ ratio: Schema.optionalKey(Schema.Finite.check(Schema.isGreaterThan(0))),
203
+ min: Schema.optionalKey(units),
204
+ preferred: Schema.optionalKey(units),
205
+ max: Schema.optionalKey(units),
206
+ grows: Schema.optionalKey(Schema.Boolean),
207
+ empty: Schema.optionalKey(Schema.Literals(["line", "hide"])),
208
+ })
209
+
210
+ /** A setting the user picks per placement of a widget: one of a few options. The host keeps the
211
+ * choice with the placement and calls the widget's tool with it, under `key`. */
212
+ export interface WidgetSetting {
213
+ readonly key: string
214
+ readonly label: string
215
+ readonly options: readonly { readonly value: string; readonly label: string }[]
216
+ /** Its value until the user picks one. */
217
+ readonly initial: string
218
+ }
219
+
220
+ export const widgetSetting: Schema.Codec<WidgetSetting> = Schema.Struct({
221
+ key: Schema.String,
222
+ label: Schema.String,
223
+ options: Schema.Array(Schema.Struct({ value: Schema.String, label: Schema.String })),
224
+ initial: Schema.String,
225
+ })
226
+
227
+ /** A descriptor only: what it is, where it can show, its view, and the data feeding it, if any. */
228
+ export interface Widget {
229
+ readonly name: string
230
+ readonly title: string
231
+ readonly surfaces: readonly Surface[]
232
+ /** Its content: a `ui://` resource of A2UI messages. */
233
+ readonly resource: string
234
+ /** The read-only tool whose structured result is its data model, and the events that refresh it
235
+ * (a type, or `*.<name>`: any extension's `<extension>.<name>`). */
236
+ readonly tool?: string
237
+ readonly refresh?: readonly string[]
238
+ /** How it sits in a space's grid; none is `auto`. */
239
+ readonly size?: Size
240
+ /** What the user can set on each placement, passed to its tool. */
241
+ readonly settings?: readonly WidgetSetting[]
242
+ }
243
+
244
+ export const widget: Schema.Codec<Widget> = Schema.Struct({
245
+ name: Schema.String,
246
+ title: Schema.String,
247
+ surfaces: Schema.Array(surface),
248
+ /** Its content: a `ui://` resource of A2UI messages. */
249
+ resource: Schema.String,
250
+ /** The read-only tool whose structured result is its data model, and the events that refresh it
251
+ * (a type, or `*.<name>`: any extension's `<extension>.<name>`). */
252
+ tool: Schema.optionalKey(Schema.String),
253
+ refresh: Schema.optionalKey(Schema.Array(Schema.String)),
254
+ /** How it sits in a space's grid; none is `auto`. */
255
+ size: Schema.optionalKey(size),
256
+ /** What the user can set on each placement, passed to its tool. */
257
+ settings: Schema.optionalKey(Schema.Array(widgetSetting)),
258
+ })
259
+
260
+ /** A widget as its app defines it: the descriptor, and its A2UI messages (one surface, any id). */
261
+ export interface WidgetDef extends Widget {
262
+ readonly a2ui: () => readonly unknown[] | Promise<readonly unknown[]>
263
+ }
264
+
265
+ const descriptor = ({ a2ui: _, ...w }: WidgetDef): Widget => w
266
+
267
+ export interface App<R = never> {
268
+ readonly name: string
269
+ readonly version: string
270
+ readonly instructions?: string
271
+ readonly connections: readonly Need[]
272
+ /** What it reaches beyond itself (`REACHES`): tools it calls, events it follows, work it steers. */
273
+ readonly reaches?: Reaches
274
+ readonly tools: readonly Tool<R>[]
275
+ /** Its own events plus the UI analytics family, which every app publishes. */
276
+ readonly events: readonly AppEvent[]
277
+ readonly widgets: readonly WidgetDef[]
278
+ }
279
+
280
+ /**
281
+ * Tools an extension calls (`switch/call`), brain event types it follows (`switch/follow`), and
282
+ * threads whose live sessions it steers beyond its own side threads (`switch/steer`): `task-*`,
283
+ * `space:*`, or one.
284
+ */
285
+ export interface Reaches {
286
+ readonly calls?: readonly string[]
287
+ readonly follows?: readonly string[]
288
+ readonly steers?: readonly string[]
289
+ }
290
+
291
+ export const defineApp = <R = never>(app: {
292
+ readonly name: string
293
+ readonly version: string
294
+ readonly instructions?: string
295
+ readonly connections?: readonly Need[]
296
+ readonly reaches?: Reaches
297
+ readonly tools: readonly Tool<R>[]
298
+ readonly events?: readonly AppEvent[]
299
+ readonly widgets?: readonly WidgetDef[]
300
+ }): App<R> => {
301
+ const events = app.events ?? []
302
+ for (const e of events) {
303
+ if (!e.type.startsWith(`${app.name}.`)) {
304
+ throw new Error(`${app.name}'s event ${e.type} must start with "${app.name}."`)
305
+ }
306
+ }
307
+ const widgets = app.widgets ?? []
308
+ for (const w of widgets) {
309
+ if (!w.resource.startsWith("ui://")) {
310
+ throw new Error(`Widget ${w.name}'s view must be a ui:// resource`)
311
+ }
312
+ const fed = app.tools.find((t) => t.name === w.tool)
313
+ if (w.tool !== undefined && fed?.readOnly !== true) {
314
+ throw new Error(`Widget ${w.name} needs a read-only tool ${w.tool}`)
315
+ }
316
+ }
317
+ return { ...app, connections: app.connections ?? [], events: [...events, ...uiEvents], widgets }
318
+ }
319
+
320
+ /** One MCP Events occurrence. `cursor` is its place in the extension's outbox. */
321
+ export interface Occurrence {
322
+ readonly eventId: string
323
+ readonly name: string
324
+ readonly timestamp: string
325
+ readonly data: unknown
326
+ readonly cursor: string
327
+ }
328
+
329
+ /**
330
+ * The client takes events in (`ACK`, `{ cursors }`): each one it has kept for good. Until then
331
+ * an event stays in the extension's outbox and is sent again on the next `events/stream` of its type,
332
+ * so the client keeps it once however often it's sent (by its `eventId`).
333
+ */
334
+ export const ACK = "notifications/events/ack"
335
+
336
+ /** Events of one type an outbox keeps unacknowledged; past it, the oldest go. */
337
+ const KEPT = 10_000
338
+
339
+ const OUTBOX = `
340
+ CREATE TABLE IF NOT EXISTS outbox (
341
+ seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL, name TEXT NOT NULL,
342
+ timestamp TEXT NOT NULL, data TEXT NOT NULL);
343
+ CREATE INDEX IF NOT EXISTS outbox_name ON outbox (name, seq);
344
+ CREATE TABLE IF NOT EXISTS once (id TEXT PRIMARY KEY, finished INTEGER NOT NULL);
345
+ `
346
+
347
+ /** Tool calls made once that it remembers; past it, the oldest go. */
348
+ const ONCE_KEPT = 10_000
349
+
350
+ /** What an `events/stream` sends: the type's events not yet acknowledged, then each one as it's emitted. */
351
+ export interface Subscribed {
352
+ readonly backlog: readonly Occurrence[]
353
+ /** Live occurrences of any type; those at or before `through` are in the backlog already. */
354
+ readonly live: PubSub.Subscription<Occurrence>
355
+ readonly through: number
356
+ }
357
+
358
+ /** How an app emits its events, to whoever subscribed (the gateway). */
359
+ export interface AppEventsShape {
360
+ /** Kept in the outbox before it returns, so it reaches the client even across a restart. */
361
+ readonly emit: (draft: Draft) => Effect.Effect<void, Rejected>
362
+ readonly subscribe: (name: string) => Effect.Effect<Subscribed, never, Scope.Scope>
363
+ /** The client kept these: they leave the outbox. */
364
+ readonly ack: (cursors: readonly string[]) => Effect.Effect<void>
365
+ /**
366
+ * A call made once (`ONCE`) begins: null when it's new, and it's recorded as begun; else whether
367
+ * the first one finished (not when it was cut off partway).
368
+ */
369
+ readonly claim: (id: string) => Effect.Effect<{ readonly finished: boolean } | null>
370
+ /** A call made once finished. */
371
+ readonly settle: (id: string) => Effect.Effect<void>
372
+ }
373
+
374
+ /** The `AppEvents` service's identifier, as a requirement. */
375
+ export interface AppEventsService {
376
+ readonly AppEvents: unique symbol
377
+ }
378
+
379
+ const appEventsKey: Context.Service<AppEventsService, AppEventsShape> = Context.Service<
380
+ AppEventsService,
381
+ AppEventsShape
382
+ >("switch/AppEvents")
383
+
384
+ interface OutboxRow {
385
+ readonly seq: number
386
+ readonly id: string
387
+ readonly name: string
388
+ readonly timestamp: string
389
+ readonly data: string
390
+ }
391
+
392
+ const parseJson: (json: string) => unknown = JSON.parse
393
+
394
+ const toOccurrence = (r: OutboxRow): Occurrence => ({
395
+ eventId: r.id,
396
+ name: r.name,
397
+ timestamp: r.timestamp,
398
+ data: parseJson(r.data),
399
+ cursor: String(r.seq),
400
+ })
401
+
402
+ const openOutbox = (file: string) => {
403
+ if (file !== ":memory:") {
404
+ mkdirSync(path.dirname(file), { recursive: true })
405
+ }
406
+ const db = new Database(file, { create: true, strict: true })
407
+ db.run("PRAGMA journal_mode = WAL")
408
+ db.run("PRAGMA synchronous = NORMAL")
409
+ db.run("PRAGMA busy_timeout = 5000")
410
+ db.run(OUTBOX)
411
+ return db
412
+ }
413
+
414
+ const appEventsLayer = (
415
+ app: { readonly events: readonly AppEvent[] },
416
+ file = ":memory:",
417
+ ): Layer.Layer<AppEventsService> =>
418
+ Layer.effect(
419
+ appEventsKey,
420
+ Effect.gen(function* making() {
421
+ const defs = new Map(app.events.map((e) => [e.type, e]))
422
+ const db = yield* Effect.acquireRelease(
423
+ Effect.sync(() => openOutbox(file)),
424
+ (d) =>
425
+ Effect.sync(() => {
426
+ d.close()
427
+ }),
428
+ )
429
+ const insert = db.query<{ seq: number }, [string, string, string, string]>(
430
+ "INSERT INTO outbox (id, name, timestamp, data) VALUES (?, ?, ?, ?) RETURNING seq",
431
+ )
432
+ const trim = db.query<unknown, [string, string, number]>(
433
+ "DELETE FROM outbox WHERE name = ? AND seq <= (SELECT seq FROM outbox WHERE name = ? ORDER BY seq DESC LIMIT 1 OFFSET ?)",
434
+ )
435
+ const pending = db.query<OutboxRow, [string]>(
436
+ "SELECT * FROM outbox WHERE name = ? ORDER BY seq",
437
+ )
438
+ const last = db.query<{ seq: number | null }, []>("SELECT max(seq) AS seq FROM outbox")
439
+ const remove = db.query<unknown, [number]>("DELETE FROM outbox WHERE seq = ?")
440
+ const removeAll = db.transaction((seqs: readonly number[]) => {
441
+ for (const seq of seqs) {
442
+ remove.run(seq)
443
+ }
444
+ })
445
+ const live = yield* PubSub.unbounded<Occurrence>()
446
+ const claimed = db.query<{ finished: number }, [string]>(
447
+ "SELECT finished FROM once WHERE id = ?",
448
+ )
449
+ const begin = db.query<unknown, [string]>("INSERT INTO once (id, finished) VALUES (?, 0)")
450
+ const trimOnce = db.query<unknown, [number]>(
451
+ "DELETE FROM once WHERE rowid <= (SELECT rowid FROM once ORDER BY rowid DESC LIMIT 1 OFFSET ?)",
452
+ )
453
+ const finish = db.query<unknown, [string]>("UPDATE once SET finished = 1 WHERE id = ?")
454
+
455
+ const emit = (draft: Draft) =>
456
+ Effect.suspend(() => {
457
+ const def = defs.get(draft.type)
458
+ if (!def) {
459
+ return Effect.fail(new Rejected({ reason: `Unknown type ${draft.type}` }))
460
+ }
461
+ const checked = def.check(draft.payload)
462
+ if (Result.isFailure(checked)) {
463
+ return Effect.fail(new Rejected({ reason: `${draft.type}: ${checked.failure}` }))
464
+ }
465
+ const eventId = draft.id ?? randomUUID()
466
+ const timestamp = draft.time ?? new Date().toISOString()
467
+ const data = JSON.stringify(checked.success)
468
+ const row = insert.get(eventId, draft.type, timestamp, data)
469
+ trim.run(draft.type, draft.type, KEPT)
470
+ const occurrence: Occurrence = {
471
+ eventId,
472
+ name: draft.type,
473
+ timestamp,
474
+ data: checked.success,
475
+ cursor: String(row?.seq ?? 0),
476
+ }
477
+ return Effect.asVoid(PubSub.publish(live, occurrence))
478
+ })
479
+
480
+ // Subscribed first, then the outbox read, so nothing falls between the two.
481
+ const subscribe = (name: string) =>
482
+ Effect.gen(function* subscribing() {
483
+ const subscription = yield* PubSub.subscribe(live)
484
+ return {
485
+ backlog: pending.all(name).map(toOccurrence),
486
+ live: subscription,
487
+ through: last.get()?.seq ?? 0,
488
+ }
489
+ })
490
+
491
+ const ack = (cursors: readonly string[]) =>
492
+ Effect.sync(() => {
493
+ removeAll(cursors.map(Number).filter(Number.isInteger))
494
+ })
495
+
496
+ const claim = (id: string) =>
497
+ Effect.sync(() => {
498
+ const was = claimed.get(id)
499
+ if (was !== null) {
500
+ return { finished: was.finished === 1 }
501
+ }
502
+ begin.run(id)
503
+ trimOnce.run(ONCE_KEPT)
504
+ return null
505
+ })
506
+
507
+ const settle = (id: string) =>
508
+ Effect.sync(() => {
509
+ finish.run(id)
510
+ })
511
+
512
+ return { emit, subscribe, ack, claim, settle }
513
+ }),
514
+ )
515
+
516
+ export const AppEvents: Context.Service<AppEventsService, AppEventsShape> & {
517
+ /**
518
+ * Emits `app`'s events through an outbox on `file` (in memory unless given), each kept until the
519
+ * client acknowledges it.
520
+ */
521
+ readonly layer: typeof appEventsLayer
522
+ } = Object.assign(appEventsKey, { layer: appEventsLayer })
523
+
524
+ const describe = (error: unknown): string => {
525
+ if (error instanceof Rejected) {
526
+ return error.reason
527
+ }
528
+ if (error instanceof Error) {
529
+ return error.message
530
+ }
531
+ return String(error)
532
+ }
533
+
534
+ const ANSWER: unique symbol = Symbol("answer")
535
+
536
+ /** A tool's answer with content of its own (an image, say) beside its structured result. */
537
+ export interface Answer {
538
+ readonly [ANSWER]: true
539
+ readonly structured: Record<string, unknown>
540
+ readonly content: CallToolResult["content"]
541
+ }
542
+
543
+ export const answer = (
544
+ structured: Record<string, unknown>,
545
+ content: CallToolResult["content"],
546
+ ): Answer => ({ [ANSWER]: true, structured, content })
547
+
548
+ const isAnswer = (value: unknown): value is Answer =>
549
+ typeof value === "object" && value !== null && ANSWER in value
550
+
551
+ const toResult = (value: unknown): CallToolResult => {
552
+ if (isAnswer(value)) {
553
+ return { content: value.content, structuredContent: value.structured }
554
+ }
555
+ if (typeof value === "string") {
556
+ return { content: [{ type: "text", text: value }] }
557
+ }
558
+ const text = JSON.stringify(value ?? null)
559
+ return value !== null && typeof value === "object" && !Array.isArray(value)
560
+ ? { content: [{ type: "text", text }], structuredContent: value }
561
+ : { content: [{ type: "text", text }] }
562
+ }
563
+
564
+ /** What a tool that failed answers. */
565
+ const failed = (failure: unknown) =>
566
+ Effect.succeed<CallToolResult>({
567
+ content: [{ type: "text", text: describe(failure) }],
568
+ isError: true,
569
+ ...(failure instanceof Rejected && failure.check === true && { _meta: { [REFUSED]: true } }),
570
+ })
571
+
572
+ /** A call made once, again: it ran, or was cut off partway and isn't run again, as it may have acted. */
573
+ const again = (name: string, finished: boolean): CallToolResult =>
574
+ finished
575
+ ? { content: [{ type: "text", text: `${name} already ran for this.` }] }
576
+ : {
577
+ content: [
578
+ {
579
+ type: "text",
580
+ text: `${name} was already running for this when the extension stopped, so whether it finished is unknown. It isn't run again.`,
581
+ },
582
+ ],
583
+ isError: true,
584
+ }
585
+
586
+ const anything = Schema.toStandardSchemaV1(Schema.Record(Schema.String, Schema.Unknown))
587
+ /** How long a request that says how it's going may go without a word before it's given up. */
588
+ const PROGRESS_SILENCE_MS = 90_000
589
+ const streamParams = Schema.toStandardSchemaV1(
590
+ Schema.Struct({
591
+ name: Schema.String,
592
+ heartbeatMs: Schema.optionalKey(Schema.NullOr(Schema.Number)),
593
+ }),
594
+ )
595
+
596
+ const ackParams = Schema.toStandardSchemaV1(Schema.Struct({ cursors: Schema.Array(Schema.String) }))
597
+
598
+ const jsonSchema = (schema: Schema.Top) => {
599
+ const doc = Schema.toJsonSchemaDocument(schema)
600
+ return Object.keys(doc.definitions).length > 0
601
+ ? { ...doc.schema, $defs: doc.definitions }
602
+ : doc.schema
603
+ }
604
+
605
+ /** Serves an app over MCP on `transport` until the scope closes. Returns what waits for the client to go. */
606
+ export const serve: <R>(
607
+ app: App<R>,
608
+ transport: Transport,
609
+ ) => Effect.Effect<Effect.Effect<void>, never, R | AppEventsService | Scope.Scope> =
610
+ Effect.fnUntraced(function* serving<R>(app: App<R>, transport: Transport) {
611
+ const events = yield* AppEvents
612
+ const run = yield* FiberSet.makeRuntimePromise<R | AppEventsService>()
613
+ const mcp = new McpServer(
614
+ { name: app.name, version: app.version },
615
+ {
616
+ capabilities: {
617
+ tools: {},
618
+ resources: {},
619
+ extensions: {
620
+ [EVENTS]: { listChanged: false },
621
+ ...(app.connections.length > 0 && {
622
+ [CONNECTIONS]: {
623
+ needs: app.connections.map((n) => ({ ...n, scopes: [...n.scopes] })),
624
+ },
625
+ }),
626
+ ...(app.reaches !== undefined && {
627
+ [REACHES]: {
628
+ ...(app.reaches.calls !== undefined && { calls: [...app.reaches.calls] }),
629
+ ...(app.reaches.follows !== undefined && { follows: [...app.reaches.follows] }),
630
+ ...(app.reaches.steers !== undefined && { steers: [...app.reaches.steers] }),
631
+ },
632
+ }),
633
+ },
634
+ },
635
+ ...(app.instructions === undefined ? {} : { instructions: app.instructions }),
636
+ },
637
+ )
638
+
639
+ const inFlight = new Map<string, Promise<CallToolResult>>()
640
+ for (const t of app.tools) {
641
+ // A tool names the UI resource its results show in (MCP Apps' field, which A2UI's MCP catalog
642
+ // reads too); a tool feeding several widgets names the first.
643
+ const fed = app.widgets.find((w) => w.tool === t.name)
644
+ const config = {
645
+ description: t.description,
646
+ annotations: {
647
+ readOnlyHint: t.readOnly,
648
+ ...(t.closed && { openWorldHint: false }),
649
+ ...(t.speaks && { speaksForPerson: true }),
650
+ },
651
+ _meta: {
652
+ ui: {
653
+ ...(fed && { resourceUri: fed.resource }),
654
+ ...(t.appOnly && { visibility: ["app"] }),
655
+ },
656
+ },
657
+ }
658
+ const call = async (
659
+ input: unknown,
660
+ meta: unknown,
661
+ notify: (n: { method: string; params: Record<string, unknown> }) => Promise<void>,
662
+ ) => {
663
+ let done = 0
664
+ const progress: ProgressShape = (message, at, total) =>
665
+ Option.match(progressTokenOf(meta), {
666
+ onNone: () => Effect.void,
667
+ onSome: ({ progressToken }) =>
668
+ Effect.promise(async () => {
669
+ done = at ?? done + 1
670
+ await notify({
671
+ method: "notifications/progress",
672
+ params: {
673
+ progressToken,
674
+ progress: done,
675
+ message,
676
+ ...(total !== undefined && { total }),
677
+ },
678
+ }).catch(() => {
679
+ /* the caller went */
680
+ })
681
+ }),
682
+ })
683
+ const answering = t.run(input).pipe(
684
+ Effect.provideService(Progress, progress),
685
+ Effect.provideService(
686
+ Caller,
687
+ Option.match(callerOf(meta), {
688
+ onNone: () => Caller.defaultValue(),
689
+ onSome: (m) => m[CALLER],
690
+ }),
691
+ ),
692
+ Effect.map(toResult),
693
+ Effect.catch(failed),
694
+ )
695
+ const id = Option.getOrNull(onceOf(meta))?.[ONCE] ?? null
696
+ if (id === null) {
697
+ return await run(answering)
698
+ }
699
+ // The same id while its first call runs waits for that one.
700
+ const key = `${t.name}\n${id}`
701
+ const under = inFlight.get(key)
702
+ if (under !== undefined) {
703
+ return await under
704
+ }
705
+ const first = run(
706
+ Effect.gen(function* onceOnly() {
707
+ const was = yield* events.claim(key)
708
+ if (was !== null) {
709
+ return again(t.name, was.finished)
710
+ }
711
+ const out = yield* answering
712
+ yield* events.settle(key)
713
+ return out
714
+ }),
715
+ )
716
+ inFlight.set(key, first)
717
+ try {
718
+ return await first
719
+ } finally {
720
+ inFlight.delete(key)
721
+ }
722
+ }
723
+ if (t.input) {
724
+ mcp.registerTool(
725
+ t.name,
726
+ { ...config, inputSchema: t.input },
727
+ async (input, ctx) => await call(input, ctx.mcpReq._meta, ctx.mcpReq.notify),
728
+ )
729
+ } else {
730
+ mcp.registerTool(
731
+ t.name,
732
+ config,
733
+ async (ctx) => await call({}, ctx.mcpReq._meta, ctx.mcpReq.notify),
734
+ )
735
+ }
736
+ }
737
+
738
+ for (const w of app.widgets) {
739
+ mcp.registerResource(
740
+ w.title,
741
+ w.resource,
742
+ { mimeType: A2UI_MIME_TYPE, _meta: { [WIDGET]: descriptor(w) } },
743
+ async () => ({
744
+ contents: [
745
+ { uri: w.resource, mimeType: A2UI_MIME_TYPE, text: JSON.stringify(await w.a2ui()) },
746
+ ],
747
+ }),
748
+ )
749
+ }
750
+
751
+ const list = app.events.map((e) => ({
752
+ name: e.type,
753
+ description: "",
754
+ delivery: ["push"],
755
+ inputSchema: { type: "object", properties: {} },
756
+ payloadSchema: jsonSchema(e.payload),
757
+ _meta: { [VERSION]: e.version },
758
+ }))
759
+ mcp.server.setRequestHandler("events/list", { params: anything }, () => ({ events: list }))
760
+
761
+ // A push subscription: confirm, then the type's events not yet acknowledged, then each one as
762
+ // it's emitted, with a heartbeat when quiet, until the client cancels.
763
+ mcp.server.setRequestHandler("events/stream", { params: streamParams }, async (params, ctx) => {
764
+ if (!app.events.some((e) => e.type === params.name)) {
765
+ throw new ProtocolError(-32_023, "NotFound", { kind: "event" })
766
+ }
767
+ const heartbeatMs = Math.max(5000, Math.min(params.heartbeatMs ?? 30_000, 300_000))
768
+ const meta = { [SUBSCRIPTION]: ctx.mcpReq.id }
769
+ const notify = (method: string, p: Record<string, unknown>) =>
770
+ Effect.promise(async () => {
771
+ await ctx.mcpReq.notify({ method, params: { ...p, _meta: meta } })
772
+ })
773
+ return await run(
774
+ Effect.scoped(
775
+ Effect.gen(function* streaming() {
776
+ const { backlog, live, through } = yield* events.subscribe(params.name)
777
+ yield* notify("notifications/events/active", {
778
+ cursor: null,
779
+ truncated: false,
780
+ heartbeatMs,
781
+ })
782
+ for (const o of backlog) {
783
+ yield* notify("notifications/events/event", { ...o })
784
+ }
785
+ for (;;) {
786
+ const next = yield* Effect.timeoutOption(PubSub.take(live), heartbeatMs)
787
+ if (Option.isNone(next)) {
788
+ yield* notify("notifications/events/heartbeat", { cursor: null })
789
+ } else if (next.value.name === params.name && Number(next.value.cursor) > through) {
790
+ yield* notify("notifications/events/event", { ...next.value })
791
+ }
792
+ }
793
+ }),
794
+ ),
795
+ { signal: ctx.mcpReq.signal },
796
+ ).then(() => ({ _meta: meta }))
797
+ })
798
+ mcp.server.setNotificationHandler(ACK, { params: ackParams }, async (params) => {
799
+ await run(events.ack(params.cursors))
800
+ })
801
+
802
+ const closed = yield* Deferred.make<boolean>()
803
+ // Models through the client, once it's connected. A client that doesn't answer them (no
804
+ // `ax.switch/models`) fails each request, and the call with it.
805
+ const peer = yield* Effect.serviceOption(Peer)
806
+ // A request that says how it's going (`progress`) waits as long as it does: each word of it
807
+ // starts the wait again.
808
+ const send = async (
809
+ method: string,
810
+ params: Readonly<Record<string, unknown>>,
811
+ progress?: (message: string) => void,
812
+ ) =>
813
+ await mcp.server.request(
814
+ { method, params: { ...params } },
815
+ anything,
816
+ progress === undefined
817
+ ? undefined
818
+ : {
819
+ timeout: PROGRESS_SILENCE_MS,
820
+ resetTimeoutOnProgress: true,
821
+ onprogress: (p) => {
822
+ progress(p.message ?? "")
823
+ },
824
+ },
825
+ )
826
+ // MCP's own hooks, not DOM targets.
827
+ Object.assign(mcp.server, {
828
+ onclose: () => {
829
+ Deferred.doneUnsafe(closed, Exit.succeed(true))
830
+ },
831
+ oninitialized: () => {
832
+ if (Option.isSome(peer)) {
833
+ peer.value.attach(send)
834
+ }
835
+ },
836
+ })
837
+ mcp.server.setNotificationHandler("switch/event", { params: anything }, (params) => {
838
+ if (Option.isSome(peer)) {
839
+ peer.value.heard?.(params)
840
+ }
841
+ })
842
+ yield* Effect.acquireRelease(
843
+ Effect.promise(async () => {
844
+ await mcp.connect(transport)
845
+ }),
846
+ () =>
847
+ Effect.promise(async () => {
848
+ await mcp.close()
849
+ }),
850
+ )
851
+ return Effect.asVoid(Deferred.await(closed))
852
+ })