switch-ext-kit 0.0.0-stage → 0.2.0

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