@mastra/mcp-apps-components 0.1.0-alpha.0 → 0.1.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +131 -89
  2. package/dist/apps/observability-widget/tool.d.ts +31 -0
  3. package/dist/apps/observability-widget/tool.d.ts.map +1 -0
  4. package/dist/host.cjs +54 -0
  5. package/dist/host.cjs.map +1 -0
  6. package/dist/host.js +51 -0
  7. package/dist/host.js.map +1 -0
  8. package/dist/index.cjs +1094 -0
  9. package/dist/index.cjs.map +1 -0
  10. package/dist/index.d.ts +24 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +1084 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/observability-dashboard.d.ts +183 -0
  15. package/dist/observability-dashboard.d.ts.map +1 -0
  16. package/dist/tool-B4yU6CY0.cjs +67 -0
  17. package/dist/tool-B4yU6CY0.cjs.map +1 -0
  18. package/dist/tool-C601G1w9.js +38 -0
  19. package/dist/tool-C601G1w9.js.map +1 -0
  20. package/package.json +20 -25
  21. package/dist/apps/dashboard-renderer/input.d.ts +0 -1406
  22. package/dist/apps/dashboard-renderer/input.d.ts.map +0 -1
  23. package/dist/apps/dashboard-renderer/pin.d.ts +0 -1016
  24. package/dist/apps/dashboard-renderer/pin.d.ts.map +0 -1
  25. package/dist/dashboard-renderer.cjs +0 -76
  26. package/dist/dashboard-renderer.cjs.map +0 -1
  27. package/dist/dashboard-renderer.d.ts +0 -15
  28. package/dist/dashboard-renderer.d.ts.map +0 -1
  29. package/dist/dashboard-renderer.js +0 -71
  30. package/dist/dashboard-renderer.js.map +0 -1
  31. package/dist/define-mcp-app-resource.d.ts +0 -16
  32. package/dist/define-mcp-app-resource.d.ts.map +0 -1
  33. package/dist/observability-protocol.d.ts +0 -62
  34. package/dist/observability-protocol.d.ts.map +0 -1
  35. package/dist/observability-tools.cjs +0 -118
  36. package/dist/observability-tools.cjs.map +0 -1
  37. package/dist/observability-tools.d.ts +0 -18
  38. package/dist/observability-tools.d.ts.map +0 -1
  39. package/dist/observability-tools.js +0 -115
  40. package/dist/observability-tools.js.map +0 -1
  41. package/dist/types.d.ts +0 -9
  42. package/dist/types.d.ts.map +0 -1
package/README.md CHANGED
@@ -1,8 +1,6 @@
1
1
  # @mastra/mcp-apps-components
2
2
 
3
- Prebuilt [MCP Apps](https://mastra.ai/docs/connections/mcp) that render Mastra UI components inside any MCP App host, such as Mastra Studio. Each app ships as a self-contained HTML resource you register on an `MCPServer`, plus a server-side helper to link it to your tools.
4
-
5
- The apps never reach the network from their iframe. They read data by calling app-only observability tools on the same server, which agents don't see.
3
+ Prebuilt [MCP Apps](https://mastra.ai/docs/connections/mcp) that you register as app resources on an `MCPServer`. Each app is a single self-contained HTML page that follows the [MCP Apps spec](https://github.com/modelcontextprotocol/ext-apps), so it runs in any MCP Apps host, such as Mastra Studio.
6
4
 
7
5
  ## Installation
8
6
 
@@ -12,116 +10,160 @@ npm install @mastra/mcp-apps-components
12
10
 
13
11
  ## Usage
14
12
 
15
- Register the dashboard renderer and `observabilityAppTools` on an `MCPServer`, then return a dashboard definition from a tool linked to the app's `ui://` URI.
13
+ `greetingApp` greets someone by name. It talks to its host with standard MCP Apps messages only:
14
+
15
+ 1. The model calls the tool that opens the app. The host sends the app that tool's arguments (`ui/notifications/tool-input`); the app reads `name`.
16
+ 2. The app calls the app-only `getGreeting` tool on the same server (`tools/call`) and shows the `greeting` string from its structured content, or the tool's error.
17
+ 3. A **Say hi back** button posts a user message to the conversation (`ui/message`).
18
+
19
+ You write both tools. `getGreeting` runs on your server, so it can call any API with your server's credentials; the app's iframe has no network access.
16
20
 
17
21
  ```typescript
18
- import type { DashboardDefinition } from '@mastra/core/storage/dashboards';
19
22
  import { createTool } from '@mastra/core/tools';
20
23
  import { MCPServer } from '@mastra/mcp';
21
- import { dashboardRendererApp, dashboardRendererInputSchema } from '@mastra/mcp-apps-components/dashboard-renderer';
22
- import { observabilityAppTools } from '@mastra/mcp-apps-components/observability-tools';
24
+ import { greetingApp } from '@mastra/mcp-apps-components';
23
25
  import { z } from 'zod';
24
26
 
25
- const DASHBOARD_APP_URI = 'ui://mastra/dashboard';
26
-
27
- const agentRuns: DashboardDefinition = {
28
- schemaVersion: 1,
29
- defaults: { datePreset: '7d' },
30
- rows: [
31
- {
32
- widgets: [
33
- {
34
- id: 'runs',
35
- span: 12,
36
- kind: 'kpis',
37
- views: [
38
- {
39
- queries: [
40
- {
41
- id: 'runs',
42
- source: 'metrics',
43
- request: 'aggregate',
44
- name: ['mastra_agent_duration_ms'],
45
- aggregation: 'count',
46
- },
47
- ],
48
- options: { items: [{ label: 'Agent runs', format: 'count', value: { query: 'runs' } }] },
49
- },
50
- ],
51
- },
52
- ],
53
- },
54
- ],
55
- };
56
-
57
- const showAgentRuns = createTool({
58
- id: 'showAgentRuns',
59
- description: 'Shows how many agent runs happened in the last 7 days',
60
- inputSchema: z.object({}),
61
- outputSchema: dashboardRendererInputSchema,
62
- mcp: { _meta: { ui: { resourceUri: DASHBOARD_APP_URI } } },
63
- execute: async () => ({ definition: agentRuns, scope: 'project' as const }),
64
- });
27
+ const uri = 'ui://mastra/greeting';
65
28
 
66
- export const dashboardServer = new MCPServer({
67
- id: 'dashboard-server',
68
- name: 'Dashboard Server',
29
+ export const greetingServer = new MCPServer({
30
+ id: 'greeting',
31
+ name: 'Greeting',
69
32
  version: '1.0.0',
70
- appResources: { [DASHBOARD_APP_URI]: dashboardRendererApp() },
71
- tools: { showAgentRuns, ...observabilityAppTools },
33
+ appResources: { [uri]: greetingApp },
34
+ tools: {
35
+ // Visible to the model: opens the app.
36
+ showGreeting: createTool({
37
+ id: 'showGreeting',
38
+ description: 'Shows a greeting card for someone',
39
+ inputSchema: z.object({ name: z.string() }),
40
+ mcp: { _meta: { ui: { resourceUri: uri } } },
41
+ execute: async ({ name }) => ({ name }),
42
+ }),
43
+ // Visible to the app only: returns its data.
44
+ getGreeting: createTool({
45
+ id: 'getGreeting',
46
+ description: 'Returns the greeting for a name',
47
+ inputSchema: z.object({ name: z.string() }),
48
+ outputSchema: z.object({ greeting: z.string() }),
49
+ mcp: { _meta: { ui: { resourceUri: uri, visibility: ['app'] } } },
50
+ execute: async ({ name }) => ({ greeting: `Hello, ${name}!` }),
51
+ }),
52
+ },
72
53
  });
73
54
  ```
74
55
 
75
- Each tool runs its read-only observability route in-process as the caller, with the route's own validation, authentication, permission and FGA checks, so the app sees the same data the signed-in user can.
56
+ ### Observability dashboard
57
+
58
+ `observabilityDashboardApp` draws a Studio dashboard (rows of KPIs, time series, tables and scores widgets) with the same components Studio uses. Each widget loads and fails on its own.
76
59
 
77
- ### Pinning widgets
60
+ 1. The model calls the tool that opens the app. That tool must declare an `outputSchema` so its result reaches the app as structured content: `{ dashboard, datePreset? }`, where `dashboard` passes `dashboardDefinitionSchema` from `@mastra/core/storage/dashboards` and `datePreset` is one of `24h`, `3d`, `7d`, `14d` or `30d`. Without `datePreset`, the app uses the dashboard's `defaults.datePreset` when it is one of those, else `24h`. The window ends when the app opens. The dashboard's top-level `defaults.filters` chips filter every widget.
61
+ 2. The app reads its data through the app-only `queryObservability` tool (exported as `QUERY_OBSERVABILITY_TOOL`). It calls it once per read with `{ action, args }`, where `action` is one of `OBSERVABILITY_READ_ACTIONS`, the `MastraClient` observability reads the app sends (`aggregateTraces`, `getMetricBreakdown`, `getScoreTimeSeries`, `listScores`, …), and `args` are that method's arguments, with dates as ISO strings. The tool returns `{ data }`, the method's result; if it throws, that widget shows as failed.
78
62
 
79
- Each widget shows a pin button when the host says it can pin. The host owns the pinned widgets; the app only asks it to change them.
63
+ Use `observabilityDashboardInputSchema` as the opening tool's input and `toObservabilityDashboard` as its `execute`:
80
64
 
81
- 1. The host sets `mastra.ai/dashboard-pinned-widgets` in its host context to the ids of the widgets it has pinned (`[]` for none). Without it, no pin buttons show.
82
- 2. When the user clicks a widget's button, the app sends a `mastra.ai/dashboard-widget-pin` notification with `{ widget, scope, defaults, isPinned }`: the widget definition, the dashboard's scope, the date range and filters the user had on, and the state the user wants. Together, `widget`, `scope`, and `defaults` render the pinned widget on its own as the user saw it.
83
- 3. The host stores the change and sends the new list of ids back in its host context. Each button follows the host, not the click.
65
+ - The schema advertises every widget kind's options to the model, so the model can write its own widgets, and a wrong one fails input validation with errors the model can act on.
66
+ - The schema names the metrics Mastra records, but leaves metric names free: a name that doesn't exist reads as zero rather than failing. To make the model pick only metrics that have data, build the schema with `createObservabilityDashboardInputSchema({ metricNames })`, passing the names from `MastraClient#getMetricNames`. Unknown names are then rejected with the list of valid ones. Past `OBSERVABILITY_CATALOG_MAX_METRIC_NAMES` (200) names, or with none, they stay free. The schema is a snapshot, so rebuild the tool (`server.toolActions.add`) when the names change; `examples/agent` does this before each agent run.
67
+ - Label keys and values aren't listed. Give the model a tool that looks them up (for example with `MastraClient#getMetricLabelKeys` and `getMetricLabelValues`).
68
+ - Widgets without an `id` get a fresh UUID on every open, so the host can pin each one by an id that stays stable when the result is shown again.
84
69
 
85
- The params come from the app's iframe, so parse them with `dashboardWidgetPinNotificationParamsSchema` before storing or rendering anything.
70
+ The tools run on your server, so you decide which Mastra server the dashboard reads from and how it authenticates. Allow `OBSERVABILITY_READ_ACTIONS` and nothing else: a widget whose read is missing from the list fails.
86
71
 
87
72
  ```typescript
88
- import { AppBridge } from '@modelcontextprotocol/ext-apps/app-bridge';
73
+ import { MastraClient } from '@mastra/client-js';
74
+ import { createTool } from '@mastra/core/tools';
75
+ import { MCPServer } from '@mastra/mcp';
89
76
  import {
90
- DASHBOARD_PINNED_WIDGETS_CONTEXT_KEY,
91
- DASHBOARD_WIDGET_PIN_NOTIFICATION,
92
- dashboardWidgetPinNotificationParamsSchema,
93
- } from '@mastra/mcp-apps-components/dashboard-renderer';
94
-
95
- let hostContext = { theme: 'dark' as const, [DASHBOARD_PINNED_WIDGETS_CONTEXT_KEY]: [] as string[] };
96
- const bridge = new AppBridge(client, hostInfo, capabilities, { hostContext });
97
-
98
- bridge.fallbackNotificationHandler = async ({ method, params }) => {
99
- if (method !== DASHBOARD_WIDGET_PIN_NOTIFICATION) return;
100
- const parsed = dashboardWidgetPinNotificationParamsSchema.safeParse(params);
101
- if (!parsed.success) return;
102
- const { widget, scope, defaults, isPinned } = parsed.data;
103
-
104
- const pinned = hostContext[DASHBOARD_PINNED_WIDGETS_CONTEXT_KEY];
105
- if (isPinned === pinned.includes(widget.id)) return;
106
- await (isPinned ? savePinnedWidget({ widget, scope, defaults }) : deletePinnedWidget(widget.id));
107
-
108
- const ids = isPinned ? [...pinned, widget.id] : pinned.filter(id => id !== widget.id);
109
- // setHostContext replaces the whole context, so keep the other fields
110
- hostContext = { ...hostContext, [DASHBOARD_PINNED_WIDGETS_CONTEXT_KEY]: ids };
111
- bridge.setHostContext(hostContext);
112
- };
77
+ OBSERVABILITY_READ_ACTIONS,
78
+ QUERY_OBSERVABILITY_TOOL,
79
+ observabilityDashboardApp,
80
+ observabilityDashboardInputSchema,
81
+ observabilityDashboardOutputSchema,
82
+ toObservabilityDashboard,
83
+ } from '@mastra/mcp-apps-components';
84
+ import { z } from 'zod';
85
+
86
+ const uri = 'ui://mastra/observability-widget';
87
+ const client = new MastraClient({ baseUrl: process.env.MASTRA_URL! });
88
+
89
+ export const observabilityServer = new MCPServer({
90
+ id: 'observability',
91
+ name: 'Observability',
92
+ version: '1.0.0',
93
+ appResources: { [uri]: observabilityDashboardApp },
94
+ tools: {
95
+ // Visible to the model: opens the app with a dashboard.
96
+ showObservabilityDashboard: createTool({
97
+ id: 'showObservabilityDashboard',
98
+ description: 'Shows an observability dashboard of kpis, timeseries, table and scores widgets.',
99
+ inputSchema: observabilityDashboardInputSchema,
100
+ outputSchema: observabilityDashboardOutputSchema,
101
+ mcp: { _meta: { ui: { resourceUri: uri } } },
102
+ execute: async input => toObservabilityDashboard(input),
103
+ }),
104
+ // Visible to the app only: runs one read on the server's client.
105
+ [QUERY_OBSERVABILITY_TOOL]: createTool({
106
+ id: QUERY_OBSERVABILITY_TOOL,
107
+ description: 'Runs one observability read',
108
+ inputSchema: z.object({ action: z.enum(OBSERVABILITY_READ_ACTIONS), args: z.record(z.string(), z.unknown()) }),
109
+ outputSchema: z.object({ data: z.unknown() }),
110
+ mcp: { _meta: { ui: { resourceUri: uri, visibility: ['app'] } } },
111
+ execute: async ({ action, args }) => {
112
+ const read = client[action].bind(client) as (args: unknown) => Promise<unknown>;
113
+ return { data: await read(args) };
114
+ },
115
+ }),
116
+ },
117
+ });
118
+ ```
119
+
120
+ The input names each widget, read and column type by a key instead of a `kind`, `source` or `type` field, so a validation error points at the part that's wrong. Each number holds the read it comes from, so nothing points at a query by id:
121
+
122
+ ```ts
123
+ {
124
+ span: 6,
125
+ timeseries: {
126
+ chart: 'stackedBar',
127
+ format: 'count',
128
+ series: [{ label: 'Runs', color: 'green', value: { metricTimeSeries: { name: ['mastra_agent_duration_ms'], aggregation: 'count' } } }],
129
+ },
130
+ }
113
131
  ```
114
132
 
115
- Keep in mind:
133
+ `toObservabilityDashboard` gathers the reads into each view's queries, one per distinct read, and fills in what the stored definition points at: series keys, a chart's whole-range totals, a table's default sort.
134
+
135
+ A host can also build a dashboard itself: `toObservabilityDashboard({ dashboard: { rows: [{ widgets: [runsWidget] }] }, datePreset: '7d' })` returns `{ dashboard, datePreset? }` as a regular `dashboardDefinitionSchema` definition and throws when the input is invalid.
136
+
137
+ `examples/agent` has a complete version with every read action and an agent that opens dashboards.
138
+
139
+ #### Pinning widgets
140
+
141
+ When the chat host supports it, each widget shows a pin button. The host owns the pinned widgets: it sends their ids to the app, and the app reports each pin and unpin through `ui/update-model-context`. In a host built on `@mastra/playground-ui`, pass `observabilityWidgetPins` from `@mastra/mcp-apps-components/host` to `McpAppHostProvider`:
142
+
143
+ ```tsx
144
+ import { McpAppHostProvider } from '@mastra/playground-ui/domains/mcps';
145
+ import { observabilityWidgetPins } from '@mastra/mcp-apps-components/host';
146
+
147
+ const host = useMemo(
148
+ () =>
149
+ observabilityWidgetPins({
150
+ resourceUri: 'ui://mastra/observability-widget',
151
+ pinnedIds,
152
+ onPin: ({ widget, datePreset, filters }) => savePin(widget, datePreset, filters),
153
+ onUnpin: widgetId => removePin(widgetId),
154
+ }),
155
+ [pinnedIds],
156
+ );
157
+
158
+ <McpAppHostProvider value={host}>{chat}</McpAppHostProvider>;
159
+ ```
116
160
 
117
- - To turn pinning off, set the key to a non-array value such as `null`. Deleting the key does nothing, because `AppBridge` only sends the fields that changed, so the app keeps the last ids it got.
118
- - Widget ids are only unique within one dashboard definition. Keep pinned ids per bridge (one tool call), not across dashboards.
119
- - A widget that no longer parses shows no pin button, so the host owns unpinning it.
161
+ A pin carries the widget, the date preset it was drawn over and, when the dashboard had any, its `defaults.filters`. The button only shows when the host sends pinned ids and accepts structured model context. A click shows right away and holds until the host sends new ids.
120
162
 
121
163
  ## Documentation
122
164
 
123
- - [Build MCP Apps](https://mastra.ai/docs/connections/mcp)
124
- - [`MCPServer` reference](https://mastra.ai/reference/tools/mcp-server)
165
+ - [MCP Apps in Mastra](https://mastra.ai/docs/connections/mcp)
166
+ - [MCP Apps spec](https://github.com/modelcontextprotocol/ext-apps)
125
167
 
126
168
  ## Changelog
127
169
 
@@ -0,0 +1,31 @@
1
+ /** The app-only tool the observability widget calls, on the server that opened it, for every read. */
2
+ export declare const QUERY_OBSERVABILITY_TOOL = "queryObservability";
3
+ /**
4
+ * Every `MastraClient` method the app sends as a `queryObservability` action. All are reads; allow
5
+ * these and nothing else (`z.enum(OBSERVABILITY_READ_ACTIONS)`).
6
+ */
7
+ export declare const OBSERVABILITY_READ_ACTIONS: readonly ['aggregateTraces', 'aggregateSpans', 'getMetricAggregate', 'getMetricBreakdown', 'getMetricTimeSeries', 'getMetricPercentiles', 'getScoreAggregate', 'getScoreBreakdown', 'getScoreTimeSeries', 'getScorePercentiles', 'listScores'];
8
+ export type ObservabilityReadAction = (typeof OBSERVABILITY_READ_ACTIONS)[number];
9
+ /** The windows the widget can show, ending when it opens; the same presets as Studio's metrics. */
10
+ export declare const OBSERVABILITY_DATE_PRESETS: readonly ['24h', '3d', '7d', '14d', '30d'];
11
+ export type ObservabilityDatePreset = (typeof OBSERVABILITY_DATE_PRESETS)[number];
12
+ /**
13
+ * Host context key holding the ids of the widgets the host has pinned (`string[]`). The pin button
14
+ * only shows when the host sends it and supports `updateModelContext.structuredContent`.
15
+ */
16
+ export declare const OBSERVABILITY_WIDGET_PINNED_CONTEXT_KEY = "mastra.ai/observability-widget-pinned";
17
+ /** `structuredContent` key of the model context update the app sends when the user (un)pins. */
18
+ export declare const OBSERVABILITY_WIDGET_PIN_CONTEXT_KEY = "mastra.ai/observability-widget-pin";
19
+ /** What the app sends under `OBSERVABILITY_WIDGET_PIN_CONTEXT_KEY`: the state the user asked for. */
20
+ export type ObservabilityWidgetPin = {
21
+ pinned: boolean;
22
+ /** The stored dashboard widget, as the opening tool returned it. */
23
+ widget: {
24
+ id: string;
25
+ [key: string]: unknown;
26
+ };
27
+ datePreset: string;
28
+ /** The dashboard's `defaults.filters` the widget was drawn under, when it has any. */
29
+ filters?: unknown[];
30
+ };
31
+ //# sourceMappingURL=tool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../../../src/apps/observability-widget/tool.ts"],"names":[],"mappings":"AAAA,sGAAsG;AACtG,eAAO,MAAM,wBAAwB,uBAAuB,CAAC;AAE7D;;;GAGG;AACH,eAAO,MAAM,0BAA0B,YACrC,iBAAiB,EACjB,gBAAgB,EAChB,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,sBAAsB,EACtB,mBAAmB,EACnB,mBAAmB,EACnB,oBAAoB,EACpB,qBAAqB,EACrB,YAAY,CACJ,CAAC;AAEX,MAAM,MAAM,uBAAuB,GAAG,CAAC,OAAO,0BAA0B,CAAC,CAAC,MAAM,CAAC,CAAC;AAElF,mGAAmG;AACnG,eAAO,MAAM,0BAA0B,YAAI,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,CAAU,CAAC;AAErF,MAAM,MAAM,uBAAuB,GAAG,CAAC,OAAO,0BAA0B,CAAC,CAAC,MAAM,CAAC,CAAC;AAElF;;;GAGG;AACH,eAAO,MAAM,uCAAuC,0CAA0C,CAAC;AAE/F,gGAAgG;AAChG,eAAO,MAAM,oCAAoC,uCAAuC,CAAC;AAEzF,qGAAqG;AACrG,MAAM,MAAM,sBAAsB,GAAG;IACnC,MAAM,EAAE,OAAO,CAAC;IAChB,oEAAoE;IACpE,MAAM,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE,CAAC;IAC/C,UAAU,EAAE,MAAM,CAAC;IACnB,sFAAsF;IACtF,OAAO,CAAC,EAAE,OAAO,EAAE,CAAC;CACrB,CAAC"}
package/dist/host.cjs ADDED
@@ -0,0 +1,54 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_tool = require("./tool-B4yU6CY0.cjs");
3
+ // src/host.ts
4
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5
+ /** The app's pin update, checked by shape only: the widget itself is validated when it's drawn. */
6
+ function readPin(structuredContent) {
7
+ const pin = structuredContent?.[require_tool.OBSERVABILITY_WIDGET_PIN_CONTEXT_KEY];
8
+ if (!isRecord(pin) || typeof pin.pinned !== "boolean" || typeof pin.datePreset !== "string") return void 0;
9
+ if (!isRecord(pin.widget) || typeof pin.widget.id !== "string") return void 0;
10
+ if (pin.filters !== void 0 && !Array.isArray(pin.filters)) return void 0;
11
+ return {
12
+ pinned: pin.pinned,
13
+ widget: {
14
+ ...pin.widget,
15
+ id: pin.widget.id
16
+ },
17
+ datePreset: pin.datePreset,
18
+ ...pin.filters ? { filters: pin.filters } : {}
19
+ };
20
+ }
21
+ /**
22
+ * Lets the user pin observability widgets from the chat. The host owns the pinned widgets: it
23
+ * sends their ids to each widget app, and hears each pin and unpin.
24
+ *
25
+ * ```tsx
26
+ * const host = useMemo(
27
+ * () => observabilityWidgetPins({ resourceUri: 'ui://mastra/observability-widget', pinnedIds, onPin, onUnpin }),
28
+ * [pinnedIds, onPin, onUnpin],
29
+ * );
30
+ * <McpAppHostProvider value={host}>{chat}</McpAppHostProvider>
31
+ * ```
32
+ *
33
+ * A click shows on the button right away and holds until the host's ids next change, so a host
34
+ * that turns a click down leaves it showing until then.
35
+ */
36
+ function observabilityWidgetPins({ resourceUri, pinnedIds, onPin, onUnpin }) {
37
+ return {
38
+ hostContext: (app) => app.resourceUri === resourceUri ? { [require_tool.OBSERVABILITY_WIDGET_PINNED_CONTEXT_KEY]: pinnedIds } : void 0,
39
+ onModelContext: (app, params) => {
40
+ if (app.resourceUri !== resourceUri) return;
41
+ const pin = readPin(params.structuredContent);
42
+ if (!pin) return;
43
+ if (pin.pinned) {
44
+ const { pinned: _pinned, ...pinned } = pin;
45
+ onPin(pinned, app);
46
+ } else onUnpin(pin.widget.id, app);
47
+ }
48
+ };
49
+ }
50
+ exports.OBSERVABILITY_WIDGET_PINNED_CONTEXT_KEY = require_tool.OBSERVABILITY_WIDGET_PINNED_CONTEXT_KEY;
51
+ exports.OBSERVABILITY_WIDGET_PIN_CONTEXT_KEY = require_tool.OBSERVABILITY_WIDGET_PIN_CONTEXT_KEY;
52
+ exports.observabilityWidgetPins = observabilityWidgetPins;
53
+
54
+ //# sourceMappingURL=host.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.cjs","names":["OBSERVABILITY_WIDGET_PIN_CONTEXT_KEY","OBSERVABILITY_WIDGET_PINNED_CONTEXT_KEY"],"sources":["../src/host.ts"],"sourcesContent":["import {\n OBSERVABILITY_WIDGET_PIN_CONTEXT_KEY,\n OBSERVABILITY_WIDGET_PINNED_CONTEXT_KEY,\n} from './apps/observability-widget/tool';\nimport type { ObservabilityWidgetPin } from './apps/observability-widget/tool';\n\nexport {\n OBSERVABILITY_WIDGET_PIN_CONTEXT_KEY,\n OBSERVABILITY_WIDGET_PINNED_CONTEXT_KEY,\n} from './apps/observability-widget/tool';\nexport type { ObservabilityWidgetPin } from './apps/observability-widget/tool';\n\n/** The MCP App instance a host callback is about: one tool call's app. */\nexport type McpAppRef = { toolName: string; toolCallId: string; resourceUri: string };\n\n/**\n * What a chat host passes to `McpAppHostProvider` from `@mastra/playground-ui/domains/mcps`. Typed\n * here by shape, so this package doesn't depend on the host's UI package.\n */\nexport type McpAppHostValue = {\n hostContext?: (app: McpAppRef) => Record<string, unknown> | undefined;\n onModelContext?: (\n app: McpAppRef,\n params: { content?: unknown[]; structuredContent?: Record<string, unknown> },\n ) => void;\n};\n\nexport type ObservabilityWidgetPinsOptions = {\n /** The `ui://` URI the observability widget app is registered under; other apps are left alone. */\n resourceUri: string;\n /** The ids of the widgets the host has pinned. Pass new ids after `onPin`/`onUnpin` to answer. */\n pinnedIds: readonly string[];\n /** The user pinned `pin.widget` over `pin.datePreset`, under `pin.filters` when it has them. */\n onPin: (pin: Omit<ObservabilityWidgetPin, 'pinned'>, app: McpAppRef) => void;\n /** The user unpinned the widget with this id. */\n onUnpin: (widgetId: string, app: McpAppRef) => void;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/** The app's pin update, checked by shape only: the widget itself is validated when it's drawn. */\nfunction readPin(structuredContent: Record<string, unknown> | undefined): ObservabilityWidgetPin | undefined {\n const pin = structuredContent?.[OBSERVABILITY_WIDGET_PIN_CONTEXT_KEY];\n if (!isRecord(pin) || typeof pin.pinned !== 'boolean' || typeof pin.datePreset !== 'string') return undefined;\n if (!isRecord(pin.widget) || typeof pin.widget.id !== 'string') return undefined;\n if (pin.filters !== undefined && !Array.isArray(pin.filters)) return undefined;\n return {\n pinned: pin.pinned,\n widget: { ...pin.widget, id: pin.widget.id },\n datePreset: pin.datePreset,\n ...(pin.filters ? { filters: pin.filters } : {}),\n };\n}\n\n/**\n * Lets the user pin observability widgets from the chat. The host owns the pinned widgets: it\n * sends their ids to each widget app, and hears each pin and unpin.\n *\n * ```tsx\n * const host = useMemo(\n * () => observabilityWidgetPins({ resourceUri: 'ui://mastra/observability-widget', pinnedIds, onPin, onUnpin }),\n * [pinnedIds, onPin, onUnpin],\n * );\n * <McpAppHostProvider value={host}>{chat}</McpAppHostProvider>\n * ```\n *\n * A click shows on the button right away and holds until the host's ids next change, so a host\n * that turns a click down leaves it showing until then.\n */\nexport function observabilityWidgetPins({\n resourceUri,\n pinnedIds,\n onPin,\n onUnpin,\n}: ObservabilityWidgetPinsOptions): McpAppHostValue {\n return {\n hostContext: app =>\n app.resourceUri === resourceUri ? { [OBSERVABILITY_WIDGET_PINNED_CONTEXT_KEY]: pinnedIds } : undefined,\n onModelContext: (app, params) => {\n if (app.resourceUri !== resourceUri) return;\n const pin = readPin(params.structuredContent);\n if (!pin) return;\n if (pin.pinned) {\n const { pinned: _pinned, ...pinned } = pin;\n onPin(pinned, app);\n } else onUnpin(pin.widget.id, app);\n },\n };\n}\n"],"mappings":";;;AAsCA,MAAM,YAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;AAGrE,SAAS,QAAQ,mBAA4F;CAC3G,MAAM,MAAM,oBAAoBA,aAAAA;CAChC,IAAI,CAAC,SAAS,GAAG,KAAK,OAAO,IAAI,WAAW,aAAa,OAAO,IAAI,eAAe,UAAU,OAAO,KAAA;CACpG,IAAI,CAAC,SAAS,IAAI,MAAM,KAAK,OAAO,IAAI,OAAO,OAAO,UAAU,OAAO,KAAA;CACvE,IAAI,IAAI,YAAY,KAAA,KAAa,CAAC,MAAM,QAAQ,IAAI,OAAO,GAAG,OAAO,KAAA;CACrE,OAAO;EACL,QAAQ,IAAI;EACZ,QAAQ;GAAE,GAAG,IAAI;GAAQ,IAAI,IAAI,OAAO;EAAG;EAC3C,YAAY,IAAI;EAChB,GAAI,IAAI,UAAU,EAAE,SAAS,IAAI,QAAQ,IAAI,CAAC;CAChD;AACF;;;;;;;;;;;;;;;;AAiBA,SAAgB,wBAAwB,EACtC,aACA,WACA,OACA,WACkD;CAClD,OAAO;EACL,cAAa,QACX,IAAI,gBAAgB,cAAc,GAAGC,aAAAA,0CAA0C,UAAU,IAAI,KAAA;EAC/F,iBAAiB,KAAK,WAAW;GAC/B,IAAI,IAAI,gBAAgB,aAAa;GACrC,MAAM,MAAM,QAAQ,OAAO,iBAAiB;GAC5C,IAAI,CAAC,KAAK;GACV,IAAI,IAAI,QAAQ;IACd,MAAM,EAAE,QAAQ,SAAS,GAAG,WAAW;IACvC,MAAM,QAAQ,GAAG;GACnB,OAAO,QAAQ,IAAI,OAAO,IAAI,GAAG;EACnC;CACF;AACF"}
package/dist/host.js ADDED
@@ -0,0 +1,51 @@
1
+ import { i as OBSERVABILITY_WIDGET_PIN_CONTEXT_KEY, r as OBSERVABILITY_WIDGET_PINNED_CONTEXT_KEY } from "./tool-C601G1w9.js";
2
+ // src/host.ts
3
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4
+ /** The app's pin update, checked by shape only: the widget itself is validated when it's drawn. */
5
+ function readPin(structuredContent) {
6
+ const pin = structuredContent?.[OBSERVABILITY_WIDGET_PIN_CONTEXT_KEY];
7
+ if (!isRecord(pin) || typeof pin.pinned !== "boolean" || typeof pin.datePreset !== "string") return void 0;
8
+ if (!isRecord(pin.widget) || typeof pin.widget.id !== "string") return void 0;
9
+ if (pin.filters !== void 0 && !Array.isArray(pin.filters)) return void 0;
10
+ return {
11
+ pinned: pin.pinned,
12
+ widget: {
13
+ ...pin.widget,
14
+ id: pin.widget.id
15
+ },
16
+ datePreset: pin.datePreset,
17
+ ...pin.filters ? { filters: pin.filters } : {}
18
+ };
19
+ }
20
+ /**
21
+ * Lets the user pin observability widgets from the chat. The host owns the pinned widgets: it
22
+ * sends their ids to each widget app, and hears each pin and unpin.
23
+ *
24
+ * ```tsx
25
+ * const host = useMemo(
26
+ * () => observabilityWidgetPins({ resourceUri: 'ui://mastra/observability-widget', pinnedIds, onPin, onUnpin }),
27
+ * [pinnedIds, onPin, onUnpin],
28
+ * );
29
+ * <McpAppHostProvider value={host}>{chat}</McpAppHostProvider>
30
+ * ```
31
+ *
32
+ * A click shows on the button right away and holds until the host's ids next change, so a host
33
+ * that turns a click down leaves it showing until then.
34
+ */
35
+ function observabilityWidgetPins({ resourceUri, pinnedIds, onPin, onUnpin }) {
36
+ return {
37
+ hostContext: (app) => app.resourceUri === resourceUri ? { [OBSERVABILITY_WIDGET_PINNED_CONTEXT_KEY]: pinnedIds } : void 0,
38
+ onModelContext: (app, params) => {
39
+ if (app.resourceUri !== resourceUri) return;
40
+ const pin = readPin(params.structuredContent);
41
+ if (!pin) return;
42
+ if (pin.pinned) {
43
+ const { pinned: _pinned, ...pinned } = pin;
44
+ onPin(pinned, app);
45
+ } else onUnpin(pin.widget.id, app);
46
+ }
47
+ };
48
+ }
49
+ export { OBSERVABILITY_WIDGET_PINNED_CONTEXT_KEY, OBSERVABILITY_WIDGET_PIN_CONTEXT_KEY, observabilityWidgetPins };
50
+
51
+ //# sourceMappingURL=host.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.js","names":[],"sources":["../src/host.ts"],"sourcesContent":["import {\n OBSERVABILITY_WIDGET_PIN_CONTEXT_KEY,\n OBSERVABILITY_WIDGET_PINNED_CONTEXT_KEY,\n} from './apps/observability-widget/tool';\nimport type { ObservabilityWidgetPin } from './apps/observability-widget/tool';\n\nexport {\n OBSERVABILITY_WIDGET_PIN_CONTEXT_KEY,\n OBSERVABILITY_WIDGET_PINNED_CONTEXT_KEY,\n} from './apps/observability-widget/tool';\nexport type { ObservabilityWidgetPin } from './apps/observability-widget/tool';\n\n/** The MCP App instance a host callback is about: one tool call's app. */\nexport type McpAppRef = { toolName: string; toolCallId: string; resourceUri: string };\n\n/**\n * What a chat host passes to `McpAppHostProvider` from `@mastra/playground-ui/domains/mcps`. Typed\n * here by shape, so this package doesn't depend on the host's UI package.\n */\nexport type McpAppHostValue = {\n hostContext?: (app: McpAppRef) => Record<string, unknown> | undefined;\n onModelContext?: (\n app: McpAppRef,\n params: { content?: unknown[]; structuredContent?: Record<string, unknown> },\n ) => void;\n};\n\nexport type ObservabilityWidgetPinsOptions = {\n /** The `ui://` URI the observability widget app is registered under; other apps are left alone. */\n resourceUri: string;\n /** The ids of the widgets the host has pinned. Pass new ids after `onPin`/`onUnpin` to answer. */\n pinnedIds: readonly string[];\n /** The user pinned `pin.widget` over `pin.datePreset`, under `pin.filters` when it has them. */\n onPin: (pin: Omit<ObservabilityWidgetPin, 'pinned'>, app: McpAppRef) => void;\n /** The user unpinned the widget with this id. */\n onUnpin: (widgetId: string, app: McpAppRef) => void;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/** The app's pin update, checked by shape only: the widget itself is validated when it's drawn. */\nfunction readPin(structuredContent: Record<string, unknown> | undefined): ObservabilityWidgetPin | undefined {\n const pin = structuredContent?.[OBSERVABILITY_WIDGET_PIN_CONTEXT_KEY];\n if (!isRecord(pin) || typeof pin.pinned !== 'boolean' || typeof pin.datePreset !== 'string') return undefined;\n if (!isRecord(pin.widget) || typeof pin.widget.id !== 'string') return undefined;\n if (pin.filters !== undefined && !Array.isArray(pin.filters)) return undefined;\n return {\n pinned: pin.pinned,\n widget: { ...pin.widget, id: pin.widget.id },\n datePreset: pin.datePreset,\n ...(pin.filters ? { filters: pin.filters } : {}),\n };\n}\n\n/**\n * Lets the user pin observability widgets from the chat. The host owns the pinned widgets: it\n * sends their ids to each widget app, and hears each pin and unpin.\n *\n * ```tsx\n * const host = useMemo(\n * () => observabilityWidgetPins({ resourceUri: 'ui://mastra/observability-widget', pinnedIds, onPin, onUnpin }),\n * [pinnedIds, onPin, onUnpin],\n * );\n * <McpAppHostProvider value={host}>{chat}</McpAppHostProvider>\n * ```\n *\n * A click shows on the button right away and holds until the host's ids next change, so a host\n * that turns a click down leaves it showing until then.\n */\nexport function observabilityWidgetPins({\n resourceUri,\n pinnedIds,\n onPin,\n onUnpin,\n}: ObservabilityWidgetPinsOptions): McpAppHostValue {\n return {\n hostContext: app =>\n app.resourceUri === resourceUri ? { [OBSERVABILITY_WIDGET_PINNED_CONTEXT_KEY]: pinnedIds } : undefined,\n onModelContext: (app, params) => {\n if (app.resourceUri !== resourceUri) return;\n const pin = readPin(params.structuredContent);\n if (!pin) return;\n if (pin.pinned) {\n const { pinned: _pinned, ...pinned } = pin;\n onPin(pinned, app);\n } else onUnpin(pin.widget.id, app);\n },\n };\n}\n"],"mappings":";;AAsCA,MAAM,YAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;AAGrE,SAAS,QAAQ,mBAA4F;CAC3G,MAAM,MAAM,oBAAoB;CAChC,IAAI,CAAC,SAAS,GAAG,KAAK,OAAO,IAAI,WAAW,aAAa,OAAO,IAAI,eAAe,UAAU,OAAO,KAAA;CACpG,IAAI,CAAC,SAAS,IAAI,MAAM,KAAK,OAAO,IAAI,OAAO,OAAO,UAAU,OAAO,KAAA;CACvE,IAAI,IAAI,YAAY,KAAA,KAAa,CAAC,MAAM,QAAQ,IAAI,OAAO,GAAG,OAAO,KAAA;CACrE,OAAO;EACL,QAAQ,IAAI;EACZ,QAAQ;GAAE,GAAG,IAAI;GAAQ,IAAI,IAAI,OAAO;EAAG;EAC3C,YAAY,IAAI;EAChB,GAAI,IAAI,UAAU,EAAE,SAAS,IAAI,QAAQ,IAAI,CAAC;CAChD;AACF;;;;;;;;;;;;;;;;AAiBA,SAAgB,wBAAwB,EACtC,aACA,WACA,OACA,WACkD;CAClD,OAAO;EACL,cAAa,QACX,IAAI,gBAAgB,cAAc,GAAG,0CAA0C,UAAU,IAAI,KAAA;EAC/F,iBAAiB,KAAK,WAAW;GAC/B,IAAI,IAAI,gBAAgB,aAAa;GACrC,MAAM,MAAM,QAAQ,OAAO,iBAAiB;GAC5C,IAAI,CAAC,KAAK;GACV,IAAI,IAAI,QAAQ;IACd,MAAM,EAAE,QAAQ,SAAS,GAAG,WAAW;IACvC,MAAM,QAAQ,GAAG;GACnB,OAAO,QAAQ,IAAI,OAAO,IAAI,GAAG;EACnC;CACF;AACF"}