@dbx-tools/appkit-mastra 0.1.112 → 0.3.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/config.ts ADDED
@@ -0,0 +1,443 @@
1
+ /**
2
+ * Plugin configuration types and shared `RequestContext` keys.
3
+ *
4
+ * Kept in a leaf module so `plugin.ts`, `server.ts`, `model.ts`, and
5
+ * `memory.ts` can import them without creating a cycle.
6
+ */
7
+
8
+ import type { BasePluginConfig } from "@databricks/appkit";
9
+ import type { AgentConfig } from "@mastra/core/agent";
10
+ import { MASTRA_RESOURCE_ID_KEY, MASTRA_THREAD_ID_KEY } from "@mastra/core/request-context";
11
+ import type { PgVectorConfig, PostgresStoreConfig } from "@mastra/pg";
12
+
13
+ import type { MastraAgentDefinition, MastraTools } from "./agents";
14
+ import type { GenieSpacesConfig } from "./genie";
15
+ import { appkit } from "@dbx-tools/appkit";
16
+
17
+ /**
18
+ * `RequestContext` key under which {@link MastraServer} stores the
19
+ * resolved AppKit user. `model.ts` reads it to mint user-scoped
20
+ * Databricks tokens.
21
+ */
22
+ export const MASTRA_USER_KEY = "mastra__user";
23
+
24
+ /**
25
+ * `RequestContext` keys for AppKit user metadata stamped by
26
+ * {@link MastraServer}. Surfaced as trace metadata via
27
+ * {@link TRACE_REQUEST_CONTEXT_KEYS} so traces are filterable by who
28
+ * issued the request without leaking the full user object.
29
+ */
30
+ export const MASTRA_USER_NAME_KEY = "mastra__userName";
31
+ export const MASTRA_USER_EMAIL_KEY = "mastra__userEmail";
32
+
33
+ /**
34
+ * `RequestContext` key for the per-HTTP-request id stamped by
35
+ * {@link MastraServer}. Reads `X-Request-Id` from the incoming
36
+ * headers when present (so an upstream load balancer / API gateway
37
+ * can keep its trace correlation), falls back to a freshly minted
38
+ * UUID. Echoed back on the response and surfaced on every span via
39
+ * {@link TRACE_REQUEST_CONTEXT_KEYS} so logs and traces share a
40
+ * join key.
41
+ */
42
+ export const MASTRA_REQUEST_ID_KEY = "mastra__requestId";
43
+
44
+ /**
45
+ * `RequestContext` key for OAuth scopes parsed from the forwarded
46
+ * access token by {@link MastraServer.configureRequestContextScopes}.
47
+ * Workspace mounts that touch Databricks workspace files require
48
+ * `workspace` or `all-apis` in this list.
49
+ */
50
+ export const MASTRA_SCOPES_KEY = "mastra__scopes";
51
+
52
+ /**
53
+ * Canonical list of `RequestContext` keys we want Mastra to extract
54
+ * as metadata on every observability span (agent runs, model calls,
55
+ * tool invocations, workflow steps).
56
+ *
57
+ * Mirrors {@link https://mastra.ai/docs/observability/tracing/overview#automatic-metadata-from-requestcontext}:
58
+ * passed verbatim into `Observability.configs[*].requestContextKeys`,
59
+ * so any key listed here is read from `RequestContext` at trace
60
+ * start and attached as scalar span metadata. Keep the set to plain
61
+ * scalars - never include {@link MASTRA_USER_KEY} (it carries the
62
+ * full AppKit execution context with a `WorkspaceClient` reference).
63
+ *
64
+ * Order is purely cosmetic; Mastra de-dupes internally.
65
+ */
66
+ export const TRACE_REQUEST_CONTEXT_KEYS: readonly string[] = [
67
+ MASTRA_RESOURCE_ID_KEY,
68
+ MASTRA_THREAD_ID_KEY,
69
+ MASTRA_REQUEST_ID_KEY,
70
+ MASTRA_USER_NAME_KEY,
71
+ MASTRA_USER_EMAIL_KEY,
72
+ // Model override key is owned by `serving.ts`; spelled inline here
73
+ // so this module stays leaf-level (no cycles with `serving.ts`).
74
+ "mastra__model_override",
75
+ ];
76
+
77
+ /** AppKit execution context plus the canonical user id. */
78
+ export interface User {
79
+ id: string;
80
+ executionContext: appkit.ExecutionContextLike;
81
+ }
82
+
83
+ /** PgVector config with an optional Mastra store id. */
84
+ export type MastraMemoryConfig = PgVectorConfig & {
85
+ id?: string;
86
+ };
87
+
88
+ /**
89
+ * Fine-grained control for the optional MCP server exposure
90
+ * ({@link MastraPluginConfig.mcp}). Every field is optional; the object
91
+ * form only needs to set what differs from the defaults.
92
+ */
93
+ export interface MastraMcpConfig {
94
+ /**
95
+ * Server id used in the route path (`/mcp/<serverId>/...`) and as the
96
+ * MCP registry id. Defaults to the plugin's registered name.
97
+ */
98
+ serverId?: string;
99
+ /** Display name advertised over MCP. Defaults to `"<displayName> MCP"`. */
100
+ name?: string;
101
+ /** Semantic version advertised over MCP. Defaults to `"1.0.0"`. */
102
+ version?: string;
103
+ /** Optional human-readable description advertised over MCP. */
104
+ description?: string;
105
+ /**
106
+ * Expose every registered agent as an `ask_<agentId>` MCP tool.
107
+ * Defaults to `true` - this is the "leverage the Mastra agents over
108
+ * MCP" behavior most callers want.
109
+ */
110
+ agents?: boolean;
111
+ /**
112
+ * Also expose the plugin's ambient tools (the built-in `render_data`
113
+ * plus anything in `config.tools`) as MCP tools. Defaults to `false`:
114
+ * the ambient tools assume an in-process chat turn (they publish
115
+ * writer events the chat UI consumes), so they aren't useful to a
116
+ * standalone MCP client. Turn this on only when those tools are safe
117
+ * to call out-of-band.
118
+ */
119
+ tools?: boolean;
120
+ /**
121
+ * Extra tools to expose over MCP beyond the agent / ambient sets.
122
+ * Use this for tools written specifically for MCP consumers.
123
+ */
124
+ extraTools?: MastraTools;
125
+ }
126
+
127
+ /** Configuration accepted by the Mastra AppKit plugin. */
128
+ export interface MastraPluginConfig extends BasePluginConfig {
129
+ /** Mastra OpenAI-compatible provider id. Defaults to `"databricks"`. */
130
+ providerId?: string;
131
+ /**
132
+ * PostgresStore for Mastra threads/messages. `true` reuses the
133
+ * `lakebase` plugin's pool; an object opens a dedicated store.
134
+ */
135
+ storage?: boolean | PostgresStoreConfig;
136
+ /**
137
+ * PgVector store for Mastra memory recall. `true` reuses the
138
+ * `lakebase` plugin's pool; an object opens a dedicated store.
139
+ */
140
+ memory?: boolean | MastraMemoryConfig;
141
+ /**
142
+ * Code-defined agents. Accepts three shapes for convenience:
143
+ *
144
+ * - **Record**: `{ analyst: def, helper: def }` - keys become the
145
+ * registered ids and the first key is the default.
146
+ * - **Single definition**: `def` - registered under
147
+ * `slugify(def.name)` (or `"default"` when `name` is omitted) and
148
+ * automatically marked as the default agent.
149
+ * - **Array**: `[def1, def2]` - each registered under
150
+ * `slugify(def.name)` (or `agent_${i}` when `name` is omitted);
151
+ * the first entry is the default.
152
+ *
153
+ * Each entry becomes a Mastra `Agent` reachable at
154
+ * `/api/<plugin>/route/chat/<id>` (the chat route also matches
155
+ * `:agentId`). When `agents` is omitted entirely, the plugin
156
+ * registers a single built-in `default` analyst so the bare
157
+ * `mastra()` call still mounts a working chat endpoint.
158
+ *
159
+ * @example Single-agent shorthand
160
+ * ```ts
161
+ * mastra({
162
+ * agents: createAgent({ instructions: "..." }),
163
+ * });
164
+ * ```
165
+ *
166
+ * @example Array
167
+ * ```ts
168
+ * mastra({
169
+ * agents: [
170
+ * createAgent({ name: "analyst", instructions: "..." }),
171
+ * createAgent({ name: "helper", instructions: "..." }),
172
+ * ],
173
+ * });
174
+ * ```
175
+ *
176
+ * @example Record (explicit ids)
177
+ * ```ts
178
+ * mastra({
179
+ * agents: {
180
+ * analyst: createAgent({ instructions: "..." }),
181
+ * helper: createAgent({ instructions: "..." }),
182
+ * },
183
+ * defaultAgent: "analyst",
184
+ * });
185
+ * ```
186
+ */
187
+ agents?: Record<string, MastraAgentDefinition> | MastraAgentDefinition | MastraAgentDefinition[];
188
+ /**
189
+ * Ambient tools spread into every registered agent's tools record;
190
+ * per-agent tools win on key collision. Use for a small shared
191
+ * library; for per-agent tools set `agents[id].tools` instead.
192
+ */
193
+ tools?: MastraTools;
194
+ /**
195
+ * Agent id used when the client doesn't specify one (the bare,
196
+ * un-suffixed history / suggestions routes resolve to it).
197
+ * Defaults to the first key in `agents` (or `"default"` when
198
+ * `agents` is omitted). Must match an id in `agents` when both are
199
+ * set; a mismatch throws at setup with the available candidates.
200
+ */
201
+ defaultAgent?: string;
202
+ /**
203
+ * Plugin-level default model applied to every agent that omits its
204
+ * own `model`. Mirrors AppKit's `agents({ defaultModel })`.
205
+ *
206
+ * - `string`: shorthand for "use the OBO auto-resolver but swap the
207
+ * `modelId`" (e.g. `"databricks-claude-sonnet-4-6"`).
208
+ * - Any other Mastra `DynamicArgument<MastraModelConfig>`: passed
209
+ * through verbatim. Use this when you need full control over auth
210
+ * or `providerId`.
211
+ *
212
+ * Resolution order per agent: `def.model` → `defaultModel` →
213
+ * built-in `/serving-endpoints` resolver.
214
+ */
215
+ defaultModel?: AgentConfig["model"] | string;
216
+ /**
217
+ * Allow loose model names (`"claude sonnet"`) to be fuzzy-matched
218
+ * against the workspace's Model Serving endpoints. Defaults to
219
+ * `true`; set `false` to require exact endpoint names everywhere.
220
+ */
221
+ modelFuzzyMatch?: boolean;
222
+ /**
223
+ * Fuse.js score threshold for the fuzzy matcher (0 = exact match,
224
+ * 1 = anything matches). Defaults to `0.4`. Lower values reject
225
+ * loose matches; raise it if you have a sprawling endpoint
226
+ * catalogue with similar-looking names.
227
+ */
228
+ modelFuzzyThreshold?: number;
229
+ /**
230
+ * TTL for the in-memory serving-endpoints list cache, in
231
+ * milliseconds. Defaults to 5 minutes. The cache is per workspace
232
+ * host and shared across users; concurrent callers coalesce on a
233
+ * single in-flight fetch.
234
+ */
235
+ modelCacheTtlMs?: number;
236
+ /**
237
+ * Allow clients to override the active model per request via the
238
+ * `X-Mastra-Model` header, `?model=` query string, or `model` body
239
+ * field. Defaults to `true`. Disable when running multi-tenant
240
+ * where untrusted clients shouldn't pick the backing endpoint.
241
+ */
242
+ modelOverride?: boolean;
243
+ /**
244
+ * Priority-ordered list of endpoint names tried *first* when no
245
+ * agent / plugin / env / request-override model id is set, ahead of
246
+ * the dynamic score-classified catalogue. The resolver picks the
247
+ * first id that is actually present in the workspace's
248
+ * `/serving-endpoints` listing.
249
+ *
250
+ * When unset, resolution is driven by the live Foundation Model API
251
+ * `quality` / `speed` / `cost` scores: endpoints are classified into
252
+ * chat classes (`classifyEndpoints`) and walked best-first
253
+ * (ChatThinking -> ChatBalanced -> ChatFast), with the small built-in
254
+ * `FALLBACK_MODEL_IDS` list as the floor when the catalogue can't be
255
+ * read. Set this to
256
+ * pin a regulated workspace to an approved subset, or to put custom
257
+ * endpoints in front of the auto-classified catalogue.
258
+ */
259
+ defaultModelFallbacks?: readonly string[];
260
+ /**
261
+ * When `true` (default), every agent gets a built-in input
262
+ * processor that strips `chartId` fields from prior assistant
263
+ * tool-invocation results before they reach the model. This
264
+ * prevents the model from reusing turn-scoped chartIds it sees
265
+ * in memory recall (which would leave `[chart:<id>]` markers
266
+ * pointing at writer events that no longer exist).
267
+ *
268
+ * Set to `false` to opt out - useful if a non-default agent
269
+ * needs full visibility into prior chartIds (e.g. an audit
270
+ * agent reasoning about chart lineage).
271
+ */
272
+ stripStaleCharts?: boolean;
273
+ /**
274
+ * Style guardrails appended to every agent's `instructions` to curb
275
+ * common LLM-isms (em dashes, emojis, sycophantic openers, throwaway
276
+ * closers, excessive hedging).
277
+ *
278
+ * - `undefined` (default): use the built-in
279
+ * `DEFAULT_STYLE_INSTRUCTIONS` from `agents.ts`.
280
+ * - `string`: replace the default with the supplied block.
281
+ * - `false`: disable entirely (agents see only their bespoke
282
+ * `instructions`).
283
+ *
284
+ * Appended (not prepended) so the agent's role and rules come first
285
+ * and the style block leans on the model's recency bias.
286
+ */
287
+ styleInstructions?: string | false;
288
+ /**
289
+ * Genie spaces this plugin's agents can delegate to. One Mastra
290
+ * tool is registered per alias (`genie` for the well-known
291
+ * `default` alias, `genie_<alias>` otherwise). Each tool spins
292
+ * up a per-question Genie sub-agent that runs Databricks
293
+ * "agent mode" against the space, broadcasts wire events to the
294
+ * UI, fetches statement rows for non-empty results, and returns
295
+ * a `(string | data | chart)[]` summary the host UI renders
296
+ * inline.
297
+ *
298
+ * Entries accept either a full {@link GenieSpaceConfig} object
299
+ * or a bare `space_id` string when no extras are needed:
300
+ *
301
+ * ```ts
302
+ * mastra({
303
+ * genieSpaces: {
304
+ * default: "01ef0d3c0e1b1f4a8d2c3e4f5a6b7c8d",
305
+ * forecasts: { spaceId: "01ef...", hint: "weekly demand forecasts" },
306
+ * },
307
+ * });
308
+ * ```
309
+ *
310
+ * Reach the spaces from an agent's `tools(plugins)` callback via
311
+ * `plugins.genie?.toolkit()`; the resulting tools accept
312
+ * `{ content, conversationId? }` and return a hydrated summary.
313
+ *
314
+ * **Fallback discovery** (highest precedence first): if this
315
+ * field is omitted, the Genie agent also picks up spaces from
316
+ * (1) the AppKit `genie({ spaces: { ... } })` plugin instance
317
+ * when registered, and (2) the `DATABRICKS_GENIE_SPACE_ID`
318
+ * env var (registered under the `default` alias). This keeps
319
+ * existing AppKit deployments working without restating the
320
+ * spaces config in two places.
321
+ */
322
+ genieSpaces?: GenieSpacesConfig;
323
+ /**
324
+ * TTL for the in-memory Genie space metadata cache, in
325
+ * milliseconds. Defaults to 5 minutes. The Genie agent calls
326
+ * `client.genie.getSpace(...)` on every cold-start to get the
327
+ * title / description / warehouse id; cached responses skip the
328
+ * round-trip and concurrent callers coalesce on a single
329
+ * in-flight fetch. Drop to a smaller value when analysts are
330
+ * actively editing space metadata and you want changes visible
331
+ * within seconds; raise it to amortise the round-trip when
332
+ * space metadata is effectively frozen.
333
+ *
334
+ * Backed by AppKit's `CacheManager`, so the cache participates
335
+ * in telemetry spans (`cache.getOrExecute`) and benefits from
336
+ * Lakebase persistence when the `lakebase` plugin is wired up.
337
+ */
338
+ genieSpaceCacheTtlMs?: number;
339
+ /**
340
+ * Maximum LLM steps each agent gets per turn. One step = one
341
+ * round-trip to the underlying model (a tool call consumes a
342
+ * step, the final-text reply consumes one too). Applies to
343
+ * every agent registered through {@link MastraPluginConfig.agents}
344
+ * - per-agent overrides aren't surfaced yet because the same
345
+ * ceiling has been sufficient across every workload we've run.
346
+ *
347
+ * Defaults to {@link DEFAULT_AGENT_MAX_STEPS} (25), sized to fit
348
+ * a decomposed Genie turn (grounding + several `ask_genie` calls
349
+ * + `prepare_chart` per dataset + the final-text reply) with
350
+ * headroom for the model to chain a couple of follow-ups before
351
+ * answering. Mastra's own `agent.generate` default of 5 would
352
+ * cut multi-step orchestration off after 2-3 tool calls, so
353
+ * explicitly raising the ceiling here is what lets the
354
+ * agent-mode loop play out.
355
+ *
356
+ * Lower when an unusually slow or expensive model makes long
357
+ * turns unaffordable; raise for exploratory workloads that need
358
+ * to drill deep into a dataset within a single turn.
359
+ */
360
+ agentMaxSteps?: number;
361
+ /**
362
+ * Wire Mastra spans into AppKit's global OTel pipeline via
363
+ * `@mastra/otel-bridge`.
364
+ *
365
+ * - `undefined` (default, auto): on only when
366
+ * `OTEL_EXPORTER_OTLP_ENDPOINT` or
367
+ * `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` is set. When unset, the
368
+ * bridge is skipped so Mastra does not log
369
+ * `[OtelBridge] No OTEL span found` on the noop tracer.
370
+ * - `true`: force on even without an OTLP endpoint.
371
+ * - `false`: force off.
372
+ */
373
+ observability?: boolean;
374
+ /**
375
+ * Log user feedback (thumbs up/down + freeform comments) to MLflow as
376
+ * trace assessments, and surface the feedback controls in the chat UI.
377
+ *
378
+ * - `undefined` (default, auto): enabled only when MLflow tracing is
379
+ * wired - an OTLP exporter endpoint is set and an MLflow experiment
380
+ * is named (the same signals the observability pipeline needs to
381
+ * ship traces to MLflow). Otherwise off, since there'd be no trace
382
+ * to attach feedback to.
383
+ * - `true`: force on. Feedback controls show and writes are attempted
384
+ * regardless of env detection (use when the env is configured in a
385
+ * way the auto-probe doesn't recognize).
386
+ * - `false`: force off. No trace-id header, no feedback route, no UI.
387
+ *
388
+ * Feedback attaches to a turn's MLflow trace via the OpenTelemetry
389
+ * trace id the server stamps on each response; see `mlflow.ts`.
390
+ */
391
+ feedback?: boolean;
392
+ /**
393
+ * Expose the plugin's agents (and optionally tools) as a Mastra MCP
394
+ * server so external MCP clients - Claude Desktop, Cursor, the Mastra
395
+ * playground, or another agent - can call them over the standard MCP
396
+ * transports. Enabled by default (agents only): wrapping the
397
+ * already-registered agents costs nothing extra, so the endpoint is on
398
+ * out of the box; only the ambient tools (which assume an in-process
399
+ * chat turn) stay off unless explicitly opted in.
400
+ *
401
+ * - `undefined` (default) / `true`: expose every registered agent as
402
+ * an `ask_<agentId>` MCP tool under a server whose id is the plugin
403
+ * name.
404
+ * - `false`: no MCP endpoints.
405
+ * - {@link MastraMcpConfig}: fine-grained control over the server id,
406
+ * advertised metadata, and which agents / tools are exposed.
407
+ *
408
+ * When enabled, the stock Mastra MCP routes mount under the plugin's
409
+ * base path (no bespoke route is added - the server is handed to the
410
+ * `Mastra` instance via `mcpServers`, which `@mastra/express` serves):
411
+ *
412
+ * - Streamable HTTP: `POST /api/<plugin>/mcp/<serverId>/mcp`
413
+ * - SSE (legacy): `GET /api/<plugin>/mcp/<serverId>/sse`
414
+ * `POST /api/<plugin>/mcp/<serverId>/messages`
415
+ *
416
+ * Requests run under the same AppKit OBO scope as the chat routes, so
417
+ * an agent invoked over MCP resolves its model and tools as the
418
+ * calling user.
419
+ */
420
+ mcp?: boolean | MastraMcpConfig;
421
+ /**
422
+ * How much of the stock `@mastra/express` management API is reachable
423
+ * through the plugin mount. `@mastra/express` registers its full route
424
+ * table (agent inference plus admin / mutating routes: direct tool
425
+ * execution, workflow control, raw memory read/write, telemetry, logs,
426
+ * scores). AppKit already authenticates every request as the OBO user,
427
+ * but nothing there restricts *which* of those operations the browser
428
+ * client may invoke.
429
+ *
430
+ * - `"scoped"` (default): only the routes the chat client legitimately
431
+ * needs are dispatched to Mastra - agent inference
432
+ * (`stream` / `generate` / `network`), read-only agent metadata, this
433
+ * plugin's own OBO- and resource-scoped `/route/*` routes (history /
434
+ * threads), and, when {@link mcp} is enabled, the MCP transport.
435
+ * Everything else (tool execution, workflow control, raw memory,
436
+ * telemetry, logs, scores, and other mutations) is rejected with
437
+ * `403` before it reaches Mastra.
438
+ * - `"full"`: dispatch the entire stock Mastra API. Use only for a
439
+ * trusted first-party console that genuinely needs the management
440
+ * surface.
441
+ */
442
+ apiAccess?: "scoped" | "full";
443
+ }