@dbx-tools/appkit-mastra 0.1.67 → 0.1.68

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/plugin.ts DELETED
@@ -1,666 +0,0 @@
1
- /**
2
- * AppKit plugin that builds one or more Mastra `Agent` instances and
3
- * mounts the `@mastra/express` server. Clients drive the conversation
4
- * over the standard Mastra agent stream (`@mastra/client-js`'s
5
- * `getAgent(id).stream()`), so there's no bespoke chat transport to
6
- * keep in sync.
7
- *
8
- * - Agents: registered through `config.agents` at plugin creation
9
- * ({@link MastraAgentDefinition}). Each entry's `tools` field accepts
10
- * either a plain record or a `(plugins) => tools` callback that gets
11
- * a typed sibling-plugin index ({@link MastraPlugins}). Omit
12
- * `config.agents` to get a single built-in `default` analyst.
13
- * - Model: each agent call resolves a `MastraModelConfig` via
14
- * {@link buildModel} from `./model.js`. Per-agent `model` overrides
15
- * (`AgentConfig["model"]` or a `modelId` string) flow through
16
- * {@link buildAgents}.
17
- * - Memory / storage: per-agent, built by {@link createMemoryBuilder}
18
- * from `./memory.js`. Both auto-default to `true` when the
19
- * `lakebase` plugin is registered (unless the caller passed
20
- * `false` or a custom config). Storage namespaces per agent via
21
- * `schemaName: "mastra_<agentId>"`; the vector store is a single
22
- * shared singleton across every agent.
23
- * - Server: the Express subapp wiring lives in `./server.js`.
24
- * - HTTP: AppKit mounts this plugin under `/api/mastra`. Alongside the
25
- * Mastra agent routes, the plugin registers `/route/history`
26
- * (load + clear thread history), `/models`, `/suggestions`, and the
27
- * generic `/embed/:type/:id` resolver for inline chart / data
28
- * markers.
29
- * - MCP: opt in with `config.mcp` to expose the agents (and optionally
30
- * tools) as a Mastra `MCPServer`. It is registered on the `Mastra`
31
- * instance via `mcpServers`, so `@mastra/express` serves the stock
32
- * MCP transport routes (`/mcp/<serverId>/...`) under the mount. See
33
- * `./mcp.js`.
34
- */
35
-
36
- import {
37
- genie,
38
- getExecutionContext,
39
- lakebase,
40
- Plugin,
41
- toPlugin,
42
- type IAppRouter,
43
- type PluginManifest,
44
- type ResourceRequirement,
45
- } from "@databricks/appkit";
46
- import { apiUtils, appkitUtils, commonUtils, logUtils } from "@dbx-tools/shared";
47
- import type { Agent } from "@mastra/core/agent";
48
- import { Mastra } from "@mastra/core/mastra";
49
- import express from "express";
50
- import type { Pool } from "pg";
51
-
52
- import {
53
- MASTRA_ROUTES,
54
- type MastraClientConfig,
55
- type StatementData,
56
- } from "@dbx-tools/appkit-mastra-shared";
57
- import {
58
- clearServingEndpointsCache,
59
- listServingEndpoints,
60
- type ServingEndpointSummary,
61
- } from "@dbx-tools/model";
62
- import { buildAgents, FALLBACK_AGENT_ID, type BuiltAgents } from "./agents.js";
63
- import { fetchChart } from "./chart.js";
64
- import type { MastraPluginConfig } from "./config.js";
65
- import { collectSpaceSuggestions, resolveGenieSpaces } from "./genie.js";
66
- import { historyRoute } from "./history.js";
67
- import { buildMcpServer, type ResolvedMcp } from "./mcp.js";
68
- import {
69
- createMemoryBuilder,
70
- createServicePrincipalPool,
71
- needsLakebase,
72
- } from "./memory.js";
73
- import { buildObservability } from "./observability.js";
74
- import { attachRoutePatchMiddleware, MastraServer } from "./server.js";
75
- import { resolveServingConfig } from "./serving.js";
76
- import { fetchStatementData, STATEMENT_ROW_CAP } from "./statement.js";
77
-
78
- const GENIE_MANIFEST = appkitUtils.data(genie).plugin.manifest;
79
- const LAKEBASE_MANIFEST = appkitUtils.data(lakebase).plugin.manifest;
80
-
81
- /**
82
- * AppKit plugin (registered name: `mastra`) that hosts Mastra agents
83
- * with optional Lakebase-backed memory and AI SDK chat routes under
84
- * the plugin mount (typically `/api/mastra`).
85
- */
86
- export class MastraPlugin extends Plugin<MastraPluginConfig> {
87
- static manifest = {
88
- name: "mastra",
89
- displayName: "Mastra",
90
- description:
91
- "Builds a Mastra Agent with user-scoped workspace auth (asUser) " +
92
- "and optional Postgres-backed Mastra Memory via the `lakebase` plugin.",
93
- stability: "beta",
94
- resources: {
95
- required: [],
96
- optional: [
97
- // Surface the Genie resource binding (space id) declared by
98
- // AppKit's `genie` plugin manifest. The Mastra plugin no
99
- // longer uses the genie plugin's tools at runtime - the
100
- // built-in Genie agent talks to Genie directly via
101
- // `@dbx-tools/genie` - but reusing the manifest keeps the
102
- // resource-binding shape identical to AppKit's so existing
103
- // `app.yaml` configs and `genie({ spaces })` wiring keep
104
- // working without change.
105
- ...GENIE_MANIFEST.resources.required,
106
- ...LAKEBASE_MANIFEST.resources.required,
107
- ],
108
- },
109
- } satisfies PluginManifest<"mastra">;
110
-
111
- /**
112
- * Tighten resource requirements based on which features are enabled.
113
- * AppKit calls this at registration time (config-aware) so disabled
114
- * features don't surface their resource asks to the host app.
115
- */
116
- static getResourceRequirements(config: MastraPluginConfig): ResourceRequirement[] {
117
- const resources: ResourceRequirement[] = [];
118
- const enabledManifests: PluginManifest<string>[] = [];
119
-
120
- if (needsLakebase(config)) {
121
- enabledManifests.push(LAKEBASE_MANIFEST);
122
- }
123
- for (const m of enabledManifests) {
124
- for (const resource of m.resources.required) {
125
- resources.push({ ...resource, required: true } as ResourceRequirement);
126
- }
127
- }
128
- return resources;
129
- }
130
-
131
- private log = logUtils.logger(this);
132
- private built: BuiltAgents | null = null;
133
- private mastra: Mastra | null = null;
134
- private mastraApp: express.Express | null = null;
135
- private mastraServer: MastraServer | null = null;
136
- /**
137
- * The optional MCP server exposing this plugin's agents / tools, or
138
- * `null` when `config.mcp` is disabled (the default). Built in
139
- * {@link buildAgentAndServer} and registered on the Mastra instance.
140
- */
141
- private mcp: ResolvedMcp | null = null;
142
- /**
143
- * Dedicated service-principal Lakebase pool backing Mastra memory /
144
- * storage. Built once in {@link buildAgentAndServer} (outside any
145
- * `asUser` scope, so it never inherits a request's OBO identity) and
146
- * drained in {@link abortActiveOperations}. `null` until setup runs
147
- * or when Lakebase isn't needed.
148
- */
149
- private servicePrincipalPool: Pool | null = null;
150
-
151
- override async setup(): Promise<void> {
152
- // Wait until sibling plugins (e.g. `lakebase`) finish `setup()` so
153
- // the lakebase pool is valid when storage/memory are enabled.
154
- this.context?.onLifecycle("setup:complete", async () => {
155
- this.applyLakebaseAutoDefaults();
156
- this.log.info("setup:complete");
157
- await this.buildAgentAndServer();
158
- });
159
- }
160
-
161
- /**
162
- * When the `lakebase` plugin is registered, auto-enable `storage`
163
- * and `memory` unless the caller opted out explicitly (`false` or a
164
- * custom config object). Run after `setup:complete` so the lookup
165
- * is reliable: any plugin that registers itself synchronously is
166
- * already in the registry by the time this fires.
167
- */
168
- private applyLakebaseAutoDefaults(): void {
169
- const hasLakebase = appkitUtils.instance(this.context, lakebase) !== undefined;
170
- if (!hasLakebase) return;
171
- if (this.config.storage === undefined) this.config.storage = true;
172
- if (this.config.memory === undefined) this.config.memory = true;
173
- }
174
-
175
- /**
176
- * Drain the memory service-principal pool on shutdown. AppKit calls
177
- * this during teardown; the lakebase plugin closes its own SP / OBO
178
- * pools the same way. Fire-and-forget so shutdown isn't blocked on a
179
- * slow drain, and clear the handle so a re-`setup()` rebuilds it.
180
- */
181
- override abortActiveOperations(): void {
182
- super.abortActiveOperations();
183
- if (this.servicePrincipalPool) {
184
- this.log.info("closing memory SP pool");
185
- const pool = this.servicePrincipalPool;
186
- this.servicePrincipalPool = null;
187
- pool.end().catch((err) => {
188
- this.log.error("error closing memory SP pool", {
189
- error: commonUtils.errorMessage(err),
190
- });
191
- });
192
- }
193
- }
194
-
195
- override exports() {
196
- return {
197
- /**
198
- * Ids of every registered agent in registration order. Matches
199
- * AppKit `agents.list()` so callers can iterate the registry the
200
- * same way under both plugins.
201
- */
202
- list: (): string[] => Object.keys(this.built?.agents ?? {}),
203
- /**
204
- * Look up a registered agent by id. Returns `null` (not
205
- * undefined) when unknown so call sites can early-return without
206
- * a separate `in` check.
207
- */
208
- get: (id: string): Agent | null => this.built?.agents[id] ?? null,
209
- /**
210
- * The agent the client converses with when it doesn't name one.
211
- * Resolves to `config.defaultAgent`, the first registered id, or
212
- * the built-in `default` fallback.
213
- */
214
- getDefault: (): Agent | null =>
215
- (this.built && this.built.agents[this.built.defaultAgentId]) ?? null,
216
- /** Underlying Mastra instance for advanced use (custom routes etc.). */
217
- getMastra: () => this.mastra,
218
- /**
219
- * MCP endpoint info when `config.mcp` is enabled, else `null`.
220
- * Paths are absolute (under the plugin mount), ready to hand to an
221
- * MCP client. Streamable HTTP is `http`; the SSE pair is the
222
- * legacy transport.
223
- */
224
- getMcp: (): {
225
- serverId: string;
226
- http: string;
227
- sse: string;
228
- messages: string;
229
- } | null =>
230
- this.mcp
231
- ? {
232
- serverId: this.mcp.serverId,
233
- http: `/api/${this.name}${this.mcp.httpPath}`,
234
- sse: `/api/${this.name}${this.mcp.ssePath}`,
235
- messages: `/api/${this.name}${this.mcp.messagePath}`,
236
- }
237
- : null,
238
- /** Express subapp Mastra is mounted on; mostly for tests. */
239
- getMastraServer: () => this.mastraServer,
240
- /**
241
- * Fetch the workspace's Model Serving endpoints (cached). Same
242
- * payload the `GET /models` route returns; surfaced here so
243
- * other plugins / scripts can introspect the catalogue without
244
- * an HTTP round-trip. AppKit wraps this with `asUser(req)` for
245
- * OBO scoping automatically.
246
- */
247
- listModels: (): Promise<ServingEndpointSummary[]> => this.listModels(),
248
- /**
249
- * Force-evict cached endpoint listings via AppKit's
250
- * `CacheManager`. Useful in tests or right after an admin
251
- * deploys a new endpoint and doesn't want to wait for the TTL.
252
- * Returns the underlying `CacheManager.delete`/`clear` promise.
253
- */
254
- clearModelsCache: (host?: string): Promise<void> =>
255
- clearServingEndpointsCache(host),
256
- };
257
- }
258
-
259
- override clientConfig(): Record<string, unknown> {
260
- // AppKit mounts every plugin at `/api/<plugin.name>`. `this.name`
261
- // honors `config.name` overrides, so publishing `basePath` is
262
- // enough for the client to stay correct under a custom mount id -
263
- // the per-route segments are fixed (`MASTRA_ROUTES`) and the
264
- // client (`MastraPluginClient`) derives every endpoint from
265
- // `basePath`.
266
- // Return widens to `Record<string, unknown>` to satisfy the
267
- // base-class signature; consumers read it through the typed
268
- // `MastraClientConfig` shape via `usePluginClientConfig<...>(...)`.
269
- const config: MastraClientConfig = {
270
- basePath: `/api/${this.name}`,
271
- defaultAgent: this.built?.defaultAgentId ?? FALLBACK_AGENT_ID,
272
- agents: Object.keys(this.built?.agents ?? {}),
273
- };
274
- return config as unknown as Record<string, unknown>;
275
- }
276
-
277
- override injectRoutes(router: IAppRouter): void {
278
- // `GET /models` exposes the cached endpoint list so clients can
279
- // populate model pickers, validate `?model=` choices, etc. Must
280
- // be registered before the catch-all that forwards everything to
281
- // the Mastra subapp. Errors propagate to Express's default error
282
- // handler via `next(err)` so callers see the real SDK message.
283
- router.get(MASTRA_ROUTES.models, (req, res, next) => {
284
- this.userScopedSelf(req)
285
- .listModels()
286
- .then((endpoints) => res.json({ endpoints }))
287
- .catch(next);
288
- });
289
-
290
- // `GET /embed/:type/:id` is the single resolver for every embed
291
- // marker the agent emits in prose (`[chart:<id>]`,
292
- // `[data:<id>]`, ...). `:type` selects a resolver from the
293
- // registry below; `:id` is that resolver's lookup key. The
294
- // grammar (see `marker.ts`) is type-agnostic on purpose - new
295
- // embed kinds are added by registering a resolver here, with no
296
- // client or grammar change.
297
- //
298
- // Status codes:
299
- // - 200 with the resolver's JSON body when the id resolves.
300
- // - 404 when `:type` isn't registered (unsupported embed
301
- // type) OR a registered resolver can't find `:id` (unknown
302
- // / expired - e.g. a chart past its 1h TTL or a fabricated
303
- // id the model never minted).
304
- // - 400 when `:id` is empty.
305
- //
306
- // Per-type query knobs and behavior:
307
- // - `chart`: long-polls the chart cache until the entry
308
- // settles (`result` / `error`) or the budget elapses (then
309
- // returns the still-processing entry to poll again).
310
- // `?timeoutMs=<n>` (default 60s, capped 5min) tunes it.
311
- // - `data`: one OBO-scoped Statement Execution fetch.
312
- // `?limit=<n>` caps rows (clamped to STATEMENT_ROW_CAP).
313
- //
314
- // Built once (this handler is registered once) and keyed by the
315
- // raw `:type` token. Each resolver gets the request (for query
316
- // parsing + OBO scoping) and an `AbortSignal` bridged off the
317
- // connection `close` event so a long-poll unblocks the instant
318
- // the client disconnects. `undefined` from a resolver maps to a
319
- // clean 404; thrown errors bubble through `next(err)`.
320
- const embedResolvers: Record<string, EmbedResolver> = {
321
- chart: (req, id, signal) => {
322
- const timeoutMs = parseTimeoutMs(req.query["timeoutMs"]);
323
- return fetchChart(id, {
324
- ...(timeoutMs !== undefined ? { timeoutMs } : {}),
325
- signal,
326
- });
327
- },
328
- data: (req, id, signal) => {
329
- const limit = parseStatementLimit(req.query["limit"]);
330
- return this.userScopedSelf(req).fetchStatement(id, {
331
- ...(limit !== undefined ? { limit } : {}),
332
- signal,
333
- });
334
- },
335
- };
336
-
337
- router.get(`${MASTRA_ROUTES.embed}/:type/:id`, (req, res, next) => {
338
- const type = req.params["type"] ?? "";
339
- const id = req.params["id"];
340
- const resolve = embedResolvers[type];
341
- if (!resolve) {
342
- res.status(404).json({ error: `unsupported embed type: ${type}` });
343
- return;
344
- }
345
- if (!id) {
346
- res.status(400).json({ error: "id is required" });
347
- return;
348
- }
349
- // Express's `req` predates `AbortSignal`; bridge the `close`
350
- // event onto an `AbortController` so a closed connection
351
- // unblocks any long-poll immediately and frees the request
352
- // thread. The listener is GC'd with the request on normal
353
- // completion.
354
- const controller = new AbortController();
355
- req.on("close", () => controller.abort());
356
- resolve(req, id, controller.signal)
357
- .then((entry) => {
358
- if (entry === undefined) {
359
- res.status(404).json({ error: `${type} not found` });
360
- return;
361
- }
362
- res.json(entry);
363
- })
364
- .catch(next);
365
- });
366
-
367
- // `GET /suggestions` (and `/suggestions/:agentId`) returns the
368
- // curated starter questions for the agent's Genie space(s) - the
369
- // author-configured `sample_questions`, surfaced as one-tap
370
- // prompts on the chat empty state. Returns `{ questions: [] }`
371
- // when no Genie space is wired so the client renders a bare
372
- // empty state (no built-in example prompts). The `:agentId`
373
- // segment is accepted for URL symmetry with the chat / history
374
- // routes; Genie spaces are resolved per-plugin, not per-agent,
375
- // so it doesn't change the result. OBO-scoped like the other
376
- // data routes so the space lookup runs as the calling user.
377
- const handleSuggestions = (req: express.Request, res: express.Response): void => {
378
- const controller = new AbortController();
379
- req.on("close", () => controller.abort());
380
- this.userScopedSelf(req)
381
- .fetchSuggestions(controller.signal)
382
- .then((questions) => res.json({ questions }))
383
- .catch((err: unknown) => {
384
- // Suggestions are a non-critical enhancement; a lookup
385
- // failure should leave the chat usable with a bare empty
386
- // state rather than surfacing a 500. Log and degrade.
387
- this.log.warn("suggestions:error", {
388
- error: commonUtils.errorMessage(err),
389
- });
390
- res.json({ questions: [] });
391
- });
392
- };
393
- router.get(MASTRA_ROUTES.suggestions, handleSuggestions);
394
- router.get(`${MASTRA_ROUTES.suggestions}/:agentId`, handleSuggestions);
395
-
396
- router.use((req, res, next) => {
397
- if (!this.mastraApp) return res.status(503).end();
398
- // Dispatch through a real method, NOT the `mastraApp` property. The
399
- // AppKit `asUser(req)` proxy wraps function-valued props with
400
- // `value.bind(target)`. `mastraApp` is an express app whose `.bind` is
401
- // the HTTP BIND route registrar (express defines a method per HTTP verb,
402
- // and BIND is one), not `Function.prototype.bind` - so binding it through
403
- // the proxy registers a bogus route and crashes `pathToRegexp`
404
- // ("path must be a string ..."). This only manifests in production where
405
- // an OBO token makes `userScopedSelf` return the proxy. `dispatchMastra`
406
- // is a plain method (its `.bind` is the normal one) and invokes
407
- // `this.mastraApp` off the real target, keeping the OBO scope active.
408
- return this.userScopedSelf(req).dispatchMastra(req, res, next);
409
- });
410
- }
411
-
412
- /**
413
- * Invoke the Mastra express sub-app. Exists as a method (instead of reading
414
- * `this.mastraApp` through the `asUser(req)` proxy at the call site) so the
415
- * proxy binds this plain method - whose `.bind` is `Function.prototype.bind`
416
- * - rather than the express app, whose `.bind` is the HTTP BIND route
417
- * registrar (see the note in `injectRoutes`). Runs inside the user scope so
418
- * `getExecutionContext()` returns the OBO client for the agent/model
419
- * resolvers.
420
- */
421
- private dispatchMastra(
422
- req: express.Request,
423
- res: express.Response,
424
- next: express.NextFunction,
425
- ): void {
426
- this.mastraApp!(req, res, next);
427
- }
428
-
429
- /**
430
- * Implementation backing the `/suggestions` route. Runs inside the
431
- * AppKit user-context proxy so `getExecutionContext()` returns the
432
- * OBO-scoped client. Resolves the plugin's Genie spaces and merges
433
- * their curated `sample_questions` (see {@link collectSpaceSuggestions}).
434
- * Returns `[]` when no Genie space is configured so the client
435
- * shows a bare empty state instead of built-in example prompts.
436
- */
437
- private async fetchSuggestions(signal?: AbortSignal): Promise<string[]> {
438
- const spaces = resolveGenieSpaces(this.config, this.context);
439
- if (Object.keys(spaces).length === 0) return [];
440
- const client = getExecutionContext().client;
441
- return collectSpaceSuggestions({
442
- spaces,
443
- client,
444
- ...(signal ? { signal } : {}),
445
- });
446
- }
447
-
448
- /**
449
- * Implementation backing the `data` embed resolver
450
- * (`GET /embed/data/:id`). Runs inside the AppKit user-context proxy so
451
- * `getExecutionContext()` returns the OBO-scoped workspace
452
- * client, then reuses the same `fetchStatementData` pipeline
453
- * the `get_statement` tool runs so the LLM and the UI see the
454
- * exact same shape for the same statement.
455
- *
456
- * Returns `undefined` for upstream 404s so the route can map
457
- * them to a clean HTTP 404; any other failure bubbles up.
458
- */
459
- private async fetchStatement(
460
- statementId: string,
461
- options: { limit?: number; signal?: AbortSignal } = {},
462
- ): Promise<StatementData | undefined> {
463
- const client = getExecutionContext().client;
464
- const limit = Math.min(options.limit ?? STATEMENT_ROW_CAP, STATEMENT_ROW_CAP);
465
- try {
466
- const data = await fetchStatementData(client, statementId, {
467
- limit,
468
- ...(options.signal ? { signal: options.signal } : {}),
469
- });
470
- return {
471
- columns: data.columns,
472
- rows: data.rows,
473
- rowCount: data.rowCount,
474
- truncated: data.rows.length < data.rowCount,
475
- };
476
- } catch (err) {
477
- // The Databricks SDK throws on 404; surface as `undefined`
478
- // so the route maps to a clean HTTP 404 instead of a 500.
479
- if (apiUtils.isNotFoundError(err)) return undefined;
480
- throw err;
481
- }
482
- }
483
-
484
- /**
485
- * Return `this.asUser(req)` when the request carries an OBO token,
486
- * otherwise return `this` directly. Prevents the noisy AppKit warn
487
- * (`asUser() called without user token in development mode. Skipping
488
- * user impersonation.`) on every request in local dev where the
489
- * browser never sends `x-forwarded-access-token`. Behavior is
490
- * unchanged in production: a missing token always means a real OBO
491
- * proxy call (and AppKit will throw upstream if that's wrong).
492
- */
493
- private userScopedSelf(req: express.Request): this {
494
- return req.header("x-forwarded-access-token") ? (this.asUser(req) as this) : this;
495
- }
496
-
497
- /**
498
- * Implementation backing both the `/models` route and the
499
- * `listModels` export. Runs inside the AppKit user-context proxy so
500
- * `getExecutionContext()` returns the OBO-scoped client.
501
- */
502
- private async listModels(): Promise<ServingEndpointSummary[]> {
503
- const client = getExecutionContext().client;
504
- const host = (await client.config.getHost()).toString();
505
- const serving = resolveServingConfig(this.config);
506
- return listServingEndpoints(client, host, { ttlMs: serving.ttlMs });
507
- }
508
-
509
- private async buildAgentAndServer(): Promise<void> {
510
- // Per-agent memory factory. When any storage / memory setting needs
511
- // Postgres, stand up a dedicated service-principal pool first so
512
- // memory acts as the app SP (owner of the `mastra_*` schemas),
513
- // never the per-request OBO identity the chat turn runs under.
514
- // `getPgConfig()` is read here, outside any `asUser` scope, so it
515
- // returns the SP connection target + token refresh plus any
516
- // `lakebase({ pool })` overrides; `require` turns a missing
517
- // sibling into a clear wiring error. The builder caches the shared
518
- // `PgVector` singleton so registering N agents stays cheap. See
519
- // `./memory.js`.
520
- if (needsLakebase(this.config)) {
521
- const spPgConfig = appkitUtils
522
- .require(this.context, lakebase, this.config)
523
- .exports()
524
- .getPgConfig();
525
- this.servicePrincipalPool = await createServicePrincipalPool(spPgConfig);
526
- }
527
- const memoryBuilder = this.servicePrincipalPool
528
- ? createMemoryBuilder(this.config, this.servicePrincipalPool)
529
- : undefined;
530
-
531
- this.log.debug("build:start", {
532
- lakebase: memoryBuilder !== undefined,
533
- stripStaleCharts: this.config.stripStaleCharts !== false,
534
- });
535
-
536
- // Build every agent declared in `config.agents` (or the built-in
537
- // fallback when none are declared). Each agent's `model` resolves
538
- // workspace URL + bearer at call time so concurrent requests get
539
- // distinct user identities; the `asUser(req)` scope around
540
- // `handleChat` is what lets `getExecutionContext()` return the
541
- // right user inside the resolver.
542
- this.built = await buildAgents({
543
- config: this.config,
544
- context: this.context,
545
- memoryBuilder,
546
- log: this.log,
547
- });
548
-
549
- // `mastra.server.apiRoutes` is only honored by Mastra's standalone
550
- // dev server. Since we're hosting Mastra inside our own Express
551
- // subapp via `@mastra/express`, custom routes must be passed to
552
- // the `MastraServer` constructor directly.
553
- //
554
- // `storage` here is *Mastra-instance-level* and persists workflow
555
- // snapshots (where suspended `requireApproval` tool calls live).
556
- // It's separate from each agent's `Memory.storage`, which only
557
- // covers thread / message history. Without it,
558
- // `agent.resumeStream()` errors with "could not find a suspended
559
- // run" and the approval UI hangs after the user clicks Approve.
560
- const instanceStorage = memoryBuilder?.instanceStorage();
561
- // Wire Mastra's tracer into AppKit's global OTel pipeline via
562
- // `@mastra/otel-bridge`. Mastra spans become native OTel spans on
563
- // whatever tracer provider `TelemetryManager` registered during
564
- // `createApp`, so the OTLP endpoint / headers / sampling are
565
- // env-driven and shared with every other AppKit plugin.
566
- const observability = await buildObservability({ serviceName: this.name });
567
- // Optional MCP exposure: build a Mastra MCP server from the
568
- // registered agents (and, opt-in, the ambient tools) and register
569
- // it on the Mastra instance. `@mastra/express` serves the stock MCP
570
- // transport routes (`/mcp/<serverId>/...`) off `mcpServers`, so the
571
- // catch-all dispatch below already routes MCP requests under OBO -
572
- // no bespoke route needed. See `./mcp.js`.
573
- this.mcp = buildMcpServer({
574
- config: this.config,
575
- pluginName: this.name,
576
- displayName: MastraPlugin.manifest.displayName,
577
- agents: this.built.agents,
578
- ambientTools: this.built.ambientTools,
579
- });
580
- this.mastra = new Mastra({
581
- agents: this.built.agents,
582
- ...(instanceStorage ? { storage: instanceStorage } : {}),
583
- ...(observability ? { observability } : {}),
584
- ...(this.mcp ? { mcpServers: { [this.mcp.serverId]: this.mcp.server } } : {}),
585
- });
586
- this.mastraApp = express();
587
- attachRoutePatchMiddleware(this.mastraApp);
588
- this.mastraServer = new MastraServer(this.config, {
589
- app: this.mastraApp,
590
- mastra: this.mastra,
591
- prefix: "",
592
- customApiRoutes: [
593
- // `historyRoute` registers both GET (load) and DELETE
594
- // (clear) on the same path, so it returns an array we
595
- // splice in.
596
- ...historyRoute({
597
- path: MASTRA_ROUTES.history,
598
- agent: this.built.defaultAgentId,
599
- }),
600
- // Assert the `:agentId` template type: the per-package build's
601
- // NodeNext resolution widens the imported `MASTRA_ROUTES.history`
602
- // to `string` (the source/bundler typecheck keeps it a literal),
603
- // which would otherwise drop this out of the dynamic-agent
604
- // overload and demand a fixed `agent`.
605
- ...historyRoute({
606
- path: `${MASTRA_ROUTES.history}/:agentId` as `${string}:agentId`,
607
- }),
608
- ],
609
- });
610
- await this.mastraServer.init();
611
- this.log.debug("build:done", {
612
- agents: Object.keys(this.built.agents),
613
- defaultAgent: this.built.defaultAgentId,
614
- routes: ["/route/history", "/models", "/suggestions", "/embed/:type/:id"],
615
- instanceStorage: instanceStorage !== undefined,
616
- observability: observability !== undefined ? "mlflow" : "off",
617
- mcp: this.mcp ? `/api/${this.name}${this.mcp.httpPath}` : "off",
618
- });
619
- }
620
- }
621
-
622
- /**
623
- * Resolver for one embed `<type>` behind the generic
624
- * `GET /embed/:type/:id` route. Returns the JSON body to send on
625
- * success, or `undefined` to signal a 404 (unknown / expired id).
626
- * `signal` aborts when the client disconnects so long-polling
627
- * resolvers (e.g. `chart`) unblock immediately.
628
- */
629
- type EmbedResolver = (
630
- req: express.Request,
631
- id: string,
632
- signal: AbortSignal,
633
- ) => Promise<unknown | undefined>;
634
-
635
- /**
636
- * Parse the optional `?timeoutMs=<n>` query parameter from a
637
- * `GET /embed/chart/:id` request. Accepts a positive integer up
638
- * to 5 minutes (clamped) and rejects everything else as
639
- * `undefined` so {@link fetchChart} falls back to its default.
640
- * Express produces `string | string[] | undefined`; we normalize
641
- * to the first scalar before parsing.
642
- */
643
- function parseTimeoutMs(raw: unknown): number | undefined {
644
- const v = Array.isArray(raw) ? raw[0] : raw;
645
- if (typeof v !== "string") return undefined;
646
- const n = Number(v);
647
- if (!Number.isFinite(n) || n <= 0) return undefined;
648
- return Math.min(Math.floor(n), 5 * 60_000);
649
- }
650
-
651
- /**
652
- * Parse the optional `?limit=<n>` query parameter from a
653
- * `GET /embed/data/:id` request. Accepts a non-negative
654
- * integer and lets the route clamp to `STATEMENT_ROW_CAP`;
655
- * rejects anything else as `undefined` so the route falls back
656
- * to the server-side cap.
657
- */
658
- function parseStatementLimit(raw: unknown): number | undefined {
659
- const v = Array.isArray(raw) ? raw[0] : raw;
660
- if (typeof v !== "string") return undefined;
661
- const n = Number(v);
662
- if (!Number.isFinite(n) || n < 0) return undefined;
663
- return Math.floor(n);
664
- }
665
-
666
- export const mastra = toPlugin(MastraPlugin);