@surfaces-ui/mcp 0.0.0-stage → 0.3.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/dist/server.js ADDED
@@ -0,0 +1,428 @@
1
+ import { create, fromJson, toJson } from "@bufbuild/protobuf";
2
+ import { RESOURCE_MIME_TYPE, registerAppResource, registerAppTool } from "@modelcontextprotocol/ext-apps/server";
3
+ import { pipelineTools, runSummary } from "@surfaces-ui/agent";
4
+ import { PagingSchema, RefreshKind, RunState, ViewQuerySchema } from "@surfaces-ui/proto";
5
+ import { analyticsCatalog, catalogDocs, catalogPrompt, fromJsonRender } from "@surfaces-ui/spec";
6
+ import { z } from "zod";
7
+ import { APP_RESOURCE_URI, PIPELINE_RPC, PIPELINE_RPC_TOOL, RPC, RPC_TOOL, isPipelineRpcMethod, isRpcMethod } from "./protocol.js";
8
+ const ui = { ui: { resourceUri: APP_RESOURCE_URI } };
9
+ const text = (value) => ({ content: [{ type: "text", text: value }] });
10
+ const failure = (value) => ({ ...text(value), isError: true });
11
+ const message = (error) => (error instanceof Error ? error.message : String(error)).replace(/^\[[a-z_]+\]\s*/i, "");
12
+ const sqlArg = z.string().describe("A single read-only SELECT statement. Do not add LIMIT for paging; the table pages by itself.");
13
+ const sourceArg = z.string().optional().describe("Data source ID. Omit to use the default source.");
14
+ /**
15
+ * Adds the Surfaces tools and app page to an MCP server.
16
+ *
17
+ * Tools the model can call show a view (table, chart, explorer, editor,
18
+ * schema, or an A2UI surface) in the host's UI. One further tool, hidden
19
+ * from the model, lets the app page fetch data. SQL is checked before a view
20
+ * is shown, so a mistake comes back to the model as an error it can fix.
21
+ */
22
+ export function registerSurfacesApps(server, options) {
23
+ const { dataSource } = options;
24
+ const catalog = options.catalog ?? analyticsCatalog;
25
+ const maxRows = options.maxRowsPerRequest ?? 1000;
26
+ const sourceOf = async (requested) => {
27
+ if (requested)
28
+ return requested;
29
+ if (options.defaultSourceId)
30
+ return options.defaultSourceId;
31
+ const first = (await dataSource.listSources({})).sources[0];
32
+ if (!first)
33
+ throw new Error("No data sources are configured.");
34
+ return first.id;
35
+ };
36
+ const show = (view, summary) => ({ ...text(summary), structuredContent: view });
37
+ /** Runs the query once, cheaply, so a bad query is reported to the model instead of to the person. */
38
+ const GRAINS = ["minute", "hour", "day", "week", "month", "quarter", "year"];
39
+ const AGGREGATES = ["sum", "avg", "count", "count_distinct", "min", "max", "median", "stddev", "variance", "percentile"];
40
+ const dimensionArg = z.union([z.string(), z.object({ column: z.string(), grain: z.enum(GRAINS).optional(), label: z.string().optional() })]);
41
+ const checked = async (view, describe) => {
42
+ try {
43
+ const { rowCount } = await dataSource.count({ sourceId: view.sourceId, query: { baseSql: view.sql } });
44
+ return show(view, describe(rowCount));
45
+ }
46
+ catch (error) {
47
+ return failure(`The query did not run: ${message(error)}`);
48
+ }
49
+ };
50
+ registerAppResource(server, "Surfaces app", APP_RESOURCE_URI, { mimeType: RESOURCE_MIME_TYPE, description: "Interactive data views." }, async () => ({
51
+ contents: [{ uri: APP_RESOURCE_URI, mimeType: RESOURCE_MIME_TYPE, text: typeof options.appHtml === "string" ? options.appHtml : await options.appHtml() }],
52
+ }));
53
+ registerAppTool(server, "show_data_grid", {
54
+ title: "Show a table",
55
+ description: "Shows the rows of a SQL query in an interactive table the person can scroll and sort. Use for looking at records.",
56
+ inputSchema: { sql: sqlArg, sourceId: sourceArg, title: z.string().optional() },
57
+ annotations: { readOnlyHint: true },
58
+ _meta: ui,
59
+ }, async ({ sql, sourceId, title }) => checked({ view: "grid", sourceId: await sourceOf(sourceId), sql, title }, (rows) => `Showing a table of ${rows} rows.`));
60
+ registerAppTool(server, "show_chart", {
61
+ title: "Show a chart",
62
+ description: "Charts a SQL query. Give each y measure an aggregate so the database summarises by x; without one the chart plots a random sample of rows. Set xGrain for a time series and xBins for a histogram. Each y entry is a series: give one its own type and axis for a compound chart (bars with a line on a second scale). Choose the form from the comparison: bars for amounts across categories (they are sorted largest first and start at zero), a line with xGrain for change over time, xBins for a distribution, scatter for two measures. Avoid a pie beyond five slices, more than five lines, and a second y scale (use two charts on the same x instead); the chart shows advice when its shape is hard to read.",
63
+ inputSchema: {
64
+ sql: sqlArg,
65
+ type: z.enum(["bar", "line", "area", "scatter", "pie"]),
66
+ x: z.string().describe("Column for the x axis, or the slices of a pie."),
67
+ xGrain: z.enum(GRAINS).optional().describe("Group a date or time x column into buckets of this size."),
68
+ xBins: z.number().int().min(2).max(200).optional().describe("Group a numeric x column into about this many bins."),
69
+ y: z
70
+ .array(z.object({
71
+ column: z.string().optional(),
72
+ aggregate: z.enum(AGGREGATES).optional(),
73
+ percentile: z.number().min(0).max(1).optional(),
74
+ label: z.string().optional(),
75
+ type: z.enum(["bar", "line", "area", "scatter"]).optional().describe("Draw this series differently from the chart type."),
76
+ axis: z.enum(["left", "right"]).optional().describe("Use the right axis for a measure on a different scale."),
77
+ }))
78
+ .min(1),
79
+ splitBy: z.string().optional().describe("Column whose values become separate series."),
80
+ stacked: z.boolean().optional(),
81
+ legend: z.enum(["top", "bottom", "right", "none"]).optional(),
82
+ sourceId: sourceArg,
83
+ title: z.string().optional(),
84
+ },
85
+ annotations: { readOnlyHint: true },
86
+ _meta: ui,
87
+ }, async ({ sql, type, x, xGrain, xBins, y, splitBy, stacked, legend, sourceId, title }) => checked({ view: "chart", sourceId: await sourceOf(sourceId), sql, type, x, xGrain, xBins, y, splitBy, stacked, legend, title }, (rows) => `Showing a ${type} chart over ${rows} rows.`));
88
+ registerAppTool(server, "show_pivot_table", {
89
+ title: "Show a pivot table",
90
+ description: "Shows a pivot table over a SQL query: row values down the side, column values across the top, summarised measures in the cells, with totals. The database does the grouping. Choose columns with few distinct values.",
91
+ inputSchema: {
92
+ sql: sqlArg,
93
+ rows: z.array(dimensionArg).min(1).max(4).describe("Columns whose values become the rows."),
94
+ columns: z.array(dimensionArg).max(2).optional().describe("Columns whose values become the columns."),
95
+ measures: z
96
+ .array(z.object({ column: z.string().optional(), aggregate: z.enum(AGGREGATES), percentile: z.number().min(0).max(1).optional(), label: z.string().optional() }))
97
+ .min(1)
98
+ .max(6),
99
+ sourceId: sourceArg,
100
+ title: z.string().optional(),
101
+ },
102
+ annotations: { readOnlyHint: true },
103
+ _meta: ui,
104
+ }, async ({ sql, rows, columns, measures, sourceId, title }) => checked({ view: "pivot", sourceId: await sourceOf(sourceId), sql, rows, columns, measures, title }, (count) => `Showing a pivot table over ${count} rows.`));
105
+ registerAppTool(server, "show_query_result", {
106
+ title: "Explore a query",
107
+ description: "Shows a query the person can explore themselves: filters, a table and a chart of the same result, and the SQL that ran.",
108
+ inputSchema: { sql: sqlArg, sourceId: sourceArg, title: z.string().optional() },
109
+ annotations: { readOnlyHint: true },
110
+ _meta: ui,
111
+ }, async ({ sql, sourceId, title }) => checked({ view: "result", sourceId: await sourceOf(sourceId), sql, title }, (rows) => `Showing an explorable result of ${rows} rows.`));
112
+ registerAppTool(server, "open_sql_editor", {
113
+ title: "Open the SQL editor",
114
+ description: "Opens a SQL editor with autocomplete for the source's tables, where the person can write and run queries.",
115
+ inputSchema: { sql: z.string().optional().describe("SQL to start with."), sourceId: sourceArg },
116
+ annotations: { readOnlyHint: true },
117
+ _meta: ui,
118
+ }, async ({ sql, sourceId }) => show({ view: "editor", sourceId: await sourceOf(sourceId), sql: sql ?? "" }, "Opened the SQL editor."));
119
+ registerAppTool(server, "show_schema_explorer", {
120
+ title: "Browse tables",
121
+ description: "Shows a searchable tree of the source's tables and their columns.",
122
+ inputSchema: { sourceId: sourceArg },
123
+ annotations: { readOnlyHint: true },
124
+ _meta: ui,
125
+ }, async ({ sourceId }) => show({ view: "schema", sourceId: await sourceOf(sourceId) }, "Showing the tables in this source."));
126
+ const render = (messages) => {
127
+ const issues = messages.flatMap((m, index) => catalog.validateMessage(m).map((issue) => `message ${index}${issue.path}: ${issue.message}`));
128
+ if (issues.length > 0)
129
+ return failure(`The surface was not shown because it does not match the catalog:\n${issues.slice(0, 20).join("\n")}`);
130
+ return show({ view: "surface", messages }, "Showing the surface.");
131
+ };
132
+ registerAppTool(server, "render_surface", {
133
+ title: "Show a custom view",
134
+ description: `Shows a custom layout (a dashboard, a summary) described as A2UI messages using catalog ${catalog.id}. Call get_component_docs first to learn the components.`,
135
+ inputSchema: { messages: z.array(z.record(z.string(), z.unknown())).min(1).describe("A2UI messages: createSurface, then updateComponents, then optionally updateDataModel.") },
136
+ annotations: { readOnlyHint: true },
137
+ _meta: ui,
138
+ }, async ({ messages }) => render(messages));
139
+ registerAppTool(server, "show_dashboard", {
140
+ title: "Show a dashboard",
141
+ description: "Shows a dashboard described as a json-render spec ({ root, elements, state }). Prefer render_surface for new work.",
142
+ inputSchema: {
143
+ spec: z.object({
144
+ root: z.string(),
145
+ elements: z.record(z.string(), z.object({ type: z.string(), props: z.record(z.string(), z.unknown()).optional(), children: z.array(z.string()).optional() })),
146
+ state: z.record(z.string(), z.unknown()).optional(),
147
+ }),
148
+ },
149
+ annotations: { readOnlyHint: true },
150
+ _meta: ui,
151
+ }, async ({ spec }) => render(fromJsonRender(spec, catalog)));
152
+ server.registerTool("get_component_docs", {
153
+ title: "Component documentation",
154
+ description: "Explains how to build a custom view: the message format and every component with its props and an example. Pass a component name for just that one.",
155
+ inputSchema: { component: z.string().optional() },
156
+ annotations: { readOnlyHint: true },
157
+ }, async ({ component }) => {
158
+ if (!component)
159
+ return text(catalogPrompt(catalog));
160
+ const docs = catalogDocs(catalog);
161
+ return Object.hasOwn(docs, component) ? text(docs[component]) : failure(`No component named ${component}. Available: ${Object.keys(docs).join(", ")}.`);
162
+ });
163
+ /** A table's name as SQL writes it. A schema with no catalog above it is a database (Teradata) and is part of the name. */
164
+ const tableName = (ref) => (!ref?.catalog && ref?.schema ? `${ref.schema}.${ref.table ?? ""}` : (ref?.table ?? ""));
165
+ const columnsOf = async (sourceId, ref) => (await dataSource.describeTable({ sourceId, ref: { catalog: ref?.catalog, schema: ref?.schema, table: ref?.table ?? "" } }).catch(() => undefined))?.table;
166
+ server.registerTool("list_tables", {
167
+ title: "List tables",
168
+ description: "Lists the data sources and the tables in one of them. A short list comes with each table's columns and types; a long one gives names only, so narrow it with `search` or `database`, or call describe_table. Call this before writing SQL.",
169
+ inputSchema: {
170
+ sourceId: sourceArg,
171
+ database: z.string().optional().describe("A database or schema to list. Omit for the ones the source covers by default."),
172
+ search: z.string().optional().describe("Part of a table name."),
173
+ },
174
+ annotations: { readOnlyHint: true },
175
+ }, async ({ sourceId, database, search }) => {
176
+ try {
177
+ const { sources } = await dataSource.listSources({});
178
+ const id = await sourceOf(sourceId);
179
+ const { tables } = await dataSource.listTables({ sourceId: id, schema: database ?? "", search: search ?? "" });
180
+ const lines = [`Sources: ${sources.map((s) => s.id).join(", ")}`, `Tables in ${id}${database ? `, ${database}` : ""}:`];
181
+ // Describing every table of a warehouse would take minutes: past a screenful, names only.
182
+ const detailed = tables.length <= 30;
183
+ for (const table of tables.slice(0, 200)) {
184
+ const name = tableName(table.ref);
185
+ const columns = detailed ? `(${(await columnsOf(id, table.ref))?.columns.map((c) => `${c.name} ${c.nativeType}`).join(", ") ?? ""})` : "";
186
+ lines.push(`- ${name}${columns}${table.comment ? ` — ${table.comment}` : ""}`);
187
+ }
188
+ if (tables.length > 200)
189
+ lines.push(`…and ${tables.length - 200} more. Narrow the list with search or database.`);
190
+ else if (!detailed)
191
+ lines.push("Names only: call describe_table for a table's columns.");
192
+ return text(lines.join("\n"));
193
+ }
194
+ catch (error) {
195
+ return failure(message(error));
196
+ }
197
+ });
198
+ server.registerTool("describe_table", {
199
+ title: "Describe a table",
200
+ description: "One table's columns: names, types, keys and descriptions, and the tables it declares joins to. Never data values.",
201
+ inputSchema: {
202
+ table: z.string().describe("The table's name, as list_tables gave it (database.table where it has a database)."),
203
+ sourceId: sourceArg,
204
+ },
205
+ annotations: { readOnlyHint: true },
206
+ }, async ({ table, sourceId }) => {
207
+ try {
208
+ const id = await sourceOf(sourceId);
209
+ const parts = table.split(".");
210
+ const ref = parts.length > 1 ? { schema: parts.slice(0, -1).join("."), table: parts.at(-1) } : { table };
211
+ const detail = (await dataSource.describeTable({ sourceId: id, ref })).table;
212
+ if (!detail)
213
+ return failure(`Table not found: ${table}`);
214
+ const lines = [`${tableName(detail.summary?.ref) || table}${detail.summary?.comment ? ` — ${detail.summary.comment}` : ""}`];
215
+ for (const column of detail.columns)
216
+ lines.push(`- ${column.name} ${column.nativeType}${column.primaryKey ? " (key)" : ""}${column.comment ? ` — ${column.comment}` : ""}`);
217
+ for (const key of detail.foreignKeys) {
218
+ const other = tableName(key.references);
219
+ lines.push(`Joins to ${other}: ${key.columns.map((c, i) => `${c} = ${other}.${key.referencedColumns[i] ?? c}`).join(" AND ")}`);
220
+ }
221
+ return text(lines.join("\n"));
222
+ }
223
+ catch (error) {
224
+ return failure(message(error));
225
+ }
226
+ });
227
+ const { discovery } = options;
228
+ if (discovery) {
229
+ server.registerTool("search_data", {
230
+ title: "Search the catalog",
231
+ description: "Finds tables and columns by words or meaning, across the databases the catalog covers. Returns names, types and descriptions, never data values.",
232
+ inputSchema: { query: z.string().min(1).describe("What to look for, e.g. customer revenue."), sourceId: z.string().optional().describe("Search one source. Omit to search all.") },
233
+ annotations: { readOnlyHint: true },
234
+ }, async ({ query, sourceId }) => {
235
+ try {
236
+ const found = await discovery.search({ query, sourceIds: sourceId ? [sourceId] : [], pageSize: 20 });
237
+ if (found.hits.length === 0)
238
+ return text(`Nothing in the catalog matches "${query}".`);
239
+ const lines = found.hits.map((hit) => {
240
+ const ref = hit.object?.ref;
241
+ const name = `${ref?.sourceId}: ${tableName(ref)}${ref?.column ? `.${ref.column}` : ""}`;
242
+ return `- ${name}${hit.object?.nativeType ? ` ${hit.object.nativeType}` : ""}${hit.object?.description ? ` — ${hit.object.description}` : ""}`;
243
+ });
244
+ return text([`${found.total} matches for "${query}"; the best ${lines.length}:`, ...lines].join("\n"));
245
+ }
246
+ catch (error) {
247
+ return failure(message(error));
248
+ }
249
+ });
250
+ }
251
+ if (options.pipelines)
252
+ registerPipelineTools(server, options.pipelines, show);
253
+ // The app page's data channel. Read-only, and capped per request.
254
+ registerAppTool(server, RPC_TOOL, {
255
+ title: "Surfaces data channel",
256
+ description: "Used by the Surfaces app page to fetch data. Not for direct use.",
257
+ inputSchema: { method: z.string(), request: z.record(z.string(), z.unknown()) },
258
+ annotations: { readOnlyHint: true },
259
+ _meta: { ui: { resourceUri: APP_RESOURCE_URI, visibility: ["app"] } },
260
+ }, async ({ method, request }) => {
261
+ if (!isRpcMethod(method))
262
+ return failure(`Unknown method ${method}.`);
263
+ const shape = RPC[method];
264
+ try {
265
+ // Requests arrive as protobuf JSON; decode them so enums, 64-bit numbers and oneofs are read correctly.
266
+ const decoded = fromJson(shape.request, request);
267
+ if (method === "execute") {
268
+ const execute = decoded;
269
+ execute.query ??= create(ViewQuerySchema);
270
+ execute.query.page ??= create(PagingSchema);
271
+ execute.query.page.limit = Math.min(execute.query.page.limit || maxRows, maxRows);
272
+ const messages = [];
273
+ for await (const part of dataSource.execute(execute))
274
+ messages.push(toJson(shape.response, part));
275
+ return { ...text(`${messages.length} messages`), structuredContent: { messages } };
276
+ }
277
+ const response = await dataSource[method](decoded);
278
+ return { ...text("ok"), structuredContent: { messages: [toJson(shape.response, response)] } };
279
+ }
280
+ catch (error) {
281
+ return failure(message(error));
282
+ }
283
+ });
284
+ }
285
+ /** The agent's pipeline tools as MCP tools: one implementation, so the two cannot drift. */
286
+ function registerPipelineTools(server, pipelines, show) {
287
+ const tools = new Map(pipelineTools(pipelines).map((tool) => [tool.name, tool]));
288
+ const toText = (value) => JSON.stringify(value, (_, v) => (typeof v === "bigint" ? Number(v) : v), 2);
289
+ const json = (value) => text(toText(value));
290
+ const call = (name) => async (input) => {
291
+ try {
292
+ return json(await tools.get(name).run(input));
293
+ }
294
+ catch (error) {
295
+ return failure(message(error));
296
+ }
297
+ };
298
+ const pipelineId = z.string().describe("The pipeline's id, from list_pipelines.");
299
+ const select = z.array(z.string()).optional().describe("Datasets to build: name alone, name+ with what reads it, +name with what it reads. Omit for all.");
300
+ const describe = (name) => tools.get(name).description;
301
+ server.registerTool("list_pipelines", { title: "List pipelines", description: describe("list_pipelines"), inputSchema: {}, annotations: { readOnlyHint: true } }, call("list_pipelines"));
302
+ server.registerTool("describe_pipeline", { title: "Describe a pipeline", description: describe("describe_pipeline"), inputSchema: { pipelineId }, annotations: { readOnlyHint: true } }, call("describe_pipeline"));
303
+ server.registerTool("check_pipeline", { title: "Check a pipeline", description: describe("check_pipeline"), inputSchema: { pipelineId, select }, annotations: { readOnlyHint: true } }, call("check_pipeline"));
304
+ server.registerTool("get_run", { title: "A pipeline run", description: describe("get_run"), inputSchema: { pipelineId, runId: z.string() }, annotations: { readOnlyHint: true } }, call("get_run"));
305
+ registerAppTool(server, "show_pipeline", {
306
+ title: "Show a pipeline",
307
+ description: "Shows a pipeline live to the person: its datasets and how they feed one another, its runs, and each dataset's query, grain, key, columns and check results. The person can run it, check it, rebuild one dataset or cancel from there.",
308
+ inputSchema: { pipelineId },
309
+ annotations: { readOnlyHint: true },
310
+ _meta: ui,
311
+ }, async ({ pipelineId: id }) => {
312
+ try {
313
+ const { pipeline } = await pipelines.getPipeline({ id });
314
+ if (!pipeline?.summary)
315
+ return failure(`Unknown pipeline ${id}.`);
316
+ const { runs } = await pipelines.listRuns({ pipelineId: id, pageSize: 1 });
317
+ const built = pipeline.datasets.filter((d) => d.sql).length;
318
+ const last = runs[0] ? `; the last run, ${runs[0].id}, is ${RunState[runs[0].state].toLowerCase()}` : "; it has not run yet";
319
+ return show({ view: "pipeline", pipelineId: id, sourceId: pipeline.summary.sourceId }, `Showing the pipeline ${pipeline.summary.name}: ${built} dataset${built === 1 ? "" : "s"}${last}.`);
320
+ }
321
+ catch (error) {
322
+ return failure(message(error));
323
+ }
324
+ });
325
+ registerAppTool(server, "propose_dataset", {
326
+ title: "Propose a dataset",
327
+ description: `${describe("propose_dataset")} The proposal is shown to the person for review, filled in here: do not draw it yourself. The person edits it, names themselves and approves, which saves it; their decision comes back as a message.`,
328
+ inputSchema: {
329
+ pipelineId: z.string().describe("The pipeline's id, from list_pipelines, or a new id to propose a new pipeline."),
330
+ sourceId: z.string().optional().describe("For a new pipeline only: the source it reads and builds in."),
331
+ pipelineName: z.string().optional().describe("For a new pipeline only: its name."),
332
+ name: z.string(),
333
+ sql: z.string(),
334
+ grain: z.string(),
335
+ description: z.string().optional(),
336
+ layer: z.enum(["bronze", "silver", "gold"]).optional(),
337
+ view: z.boolean().optional(),
338
+ depends: z.array(z.string()).optional(),
339
+ primaryKey: z.array(z.string()).optional(),
340
+ columns: z.array(z.object({ name: z.string(), type: z.string().optional(), description: z.string().optional() })).optional(),
341
+ checks: z
342
+ .array(z.object({
343
+ kind: z.enum(["unique", "not_null", "relationships", "accepted_values", "row_count"]),
344
+ columns: z.array(z.string()).optional(),
345
+ toTable: z.string().optional(),
346
+ toColumn: z.string().optional(),
347
+ values: z.array(z.string()).optional(),
348
+ min: z.number().optional(),
349
+ max: z.number().optional(),
350
+ warnOnly: z.boolean().optional(),
351
+ }))
352
+ .optional(),
353
+ },
354
+ annotations: { readOnlyHint: true },
355
+ _meta: ui,
356
+ }, async (input) => {
357
+ try {
358
+ const proposed = (await tools.get("propose_dataset").run(input));
359
+ return show({
360
+ view: "datasetReview",
361
+ pipeline: proposed.pipeline,
362
+ dataset: input.name,
363
+ expectedVersion: proposed.expectedVersion,
364
+ digest: proposed.digest,
365
+ sourceId: proposed.pipeline.sourceId ?? "",
366
+ proposedBy: "the agent",
367
+ }, `Showing the proposal (${proposed.change}, based on version ${proposed.expectedVersion}) for the person to review. Nothing is saved until they approve, and nothing is built until the pipeline runs.`);
368
+ }
369
+ catch (error) {
370
+ return failure(message(error));
371
+ }
372
+ });
373
+ server.registerTool("run_pipeline", {
374
+ title: "Run a pipeline",
375
+ description: "Builds a pipeline's datasets, replacing their tables, then runs their checks. Ask the person first. Waits up to a minute, then returns the run id for get_run.",
376
+ inputSchema: { pipelineId, select },
377
+ annotations: { destructiveHint: true, idempotentHint: true, readOnlyHint: false },
378
+ }, async ({ pipelineId: id, select: chosen }) => {
379
+ try {
380
+ const { pipelines: list } = await pipelines.listPipelines({});
381
+ if (!list.some((p) => p.id === id))
382
+ return failure(`Unknown pipeline ${id}.`);
383
+ let { run } = await pipelines.startRun({ pipelineId: id, select: chosen ?? [], trigger: "agent", startedBy: "agent over MCP" });
384
+ for (const until = Date.now() + 60_000; run && run.state === RunState.RUNNING && Date.now() < until;) {
385
+ await new Promise((resolve) => setTimeout(resolve, 250));
386
+ run = (await pipelines.getRun({ pipelineId: id, runId: run.id })).run;
387
+ }
388
+ return json(runSummary(run));
389
+ }
390
+ catch (error) {
391
+ return failure(message(error));
392
+ }
393
+ });
394
+ // The app page's pipeline channel. Hidden from the model. What changes
395
+ // anything comes from a person in the page: a run they press (never a full
396
+ // refresh here), or a save they approved, which the backend still checks for
397
+ // the approver, the digest of what they saw and the version it was made against.
398
+ registerAppTool(server, PIPELINE_RPC_TOOL, {
399
+ title: "Surfaces pipeline channel",
400
+ description: "Used by the Surfaces app page to show pipelines and act on a person's choices there. Not for direct use.",
401
+ inputSchema: { method: z.string(), request: z.record(z.string(), z.unknown()) },
402
+ annotations: { readOnlyHint: false, destructiveHint: false },
403
+ _meta: { ui: { resourceUri: APP_RESOURCE_URI, visibility: ["app"] } },
404
+ }, async ({ method, request }) => {
405
+ if (!isPipelineRpcMethod(method))
406
+ return failure(`Unknown method ${method}.`);
407
+ const handler = pipelines[method];
408
+ if (!handler)
409
+ return failure("This server keeps no saved pipelines.");
410
+ const shape = PIPELINE_RPC[method];
411
+ try {
412
+ const decoded = fromJson(shape.request, request);
413
+ if (method === "startRun") {
414
+ const start = decoded;
415
+ if (start.refreshKind === RefreshKind.FULL_REFRESH || start.confirmFullRefresh)
416
+ return failure("A full refresh is not offered here. Use the dev server's own page or the surfaces-pipelines CLI.");
417
+ start.trigger = "manual";
418
+ start.startedBy = "a person, in the MCP app";
419
+ }
420
+ const response = await handler.call(pipelines, decoded);
421
+ return { ...text("ok"), structuredContent: { message: toJson(shape.response, response) } };
422
+ }
423
+ catch (error) {
424
+ return failure(message(error));
425
+ }
426
+ });
427
+ }
428
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAEjH,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAE/D,OAAO,EAAuB,YAAY,EAAE,WAAW,EAAE,QAAQ,EAAwB,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrI,OAAO,EAAqC,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACpI,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,gBAAgB,EAAgB,YAAY,EAAE,iBAAiB,EAAE,GAAG,EAAE,QAAQ,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AA2BjJ,MAAM,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,WAAW,EAAE,gBAAgB,EAAE,EAAE,CAAC;AACrD,MAAM,IAAI,GAAG,CAAC,KAAa,EAAE,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;AACxF,MAAM,OAAO,GAAG,CAAC,KAAa,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;AACvE,MAAM,OAAO,GAAG,CAAC,KAAc,EAAE,EAAE,CAAC,CAAC,KAAK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registerAppTool } from \"@modelcontextprotocol/ext-apps/server\";\nimport type { McpServer } from \"@modelcontextprotocol/server\";\nimport { pipelineTools, runSummary } from \"@surfaces-ui/agent\";\nimport type { DataSource, Discovery, Pipelines } from \"@surfaces-ui/data\";\nimport { type ExecuteRequest, PagingSchema, RefreshKind, RunState, type StartRunRequest, ViewQuerySchema } from \"@surfaces-ui/proto\";\nimport { type Catalog, type JsonRenderSpec, analyticsCatalog, catalogDocs, catalogPrompt, fromJsonRender } from \"@surfaces-ui/spec\";\nimport { z } from \"zod\";\nimport { APP_RESOURCE_URI, type AppView, PIPELINE_RPC, PIPELINE_RPC_TOOL, RPC, RPC_TOOL, isPipelineRpcMethod, isRpcMethod } from \"./protocol.js\";\n\nexport interface SurfacesAppsOptions {\n /** Where data comes from. Queries stay on this side; the app page receives only the rows it shows. */\n dataSource: DataSource;\n /** The single-file app page (HTML), or a function that returns it. See `readAppHtml` in `@surfaces-ui/mcp/node`. */\n appHtml: string | (() => string | Promise<string>);\n /** The catalog search backend. With it the model gets `search_data`, which finds tables and columns by words or meaning. */\n discovery?: Pick<Discovery, \"search\">;\n /**\n * The pipeline backend. With it the model gets `list_pipelines`,\n * `describe_pipeline`, `check_pipeline`, `get_run`, `show_pipeline`,\n * `propose_dataset` and `run_pipeline`. `show_pipeline` and\n * `propose_dataset` draw the pipeline and the proposal for review in the\n * app page, filled in here so the model never copies a definition.\n * `run_pipeline` is marked destructive, so the host asks the person before\n * it runs. A full refresh is not offered anywhere in this channel.\n */\n pipelines?: Pipelines;\n /** Source used when a tool call does not name one. Defaults to the first source. */\n defaultSourceId?: string;\n /** Catalog agents may use with `render_surface`. Defaults to the analytics catalog. */\n catalog?: Catalog;\n /** Most rows the app's data tool returns per request. Defaults to 1,000. */\n maxRowsPerRequest?: number;\n}\n\nconst ui = { ui: { resourceUri: APP_RESOURCE_URI } };\nconst text = (value: string) => ({ content: [{ type: \"text\" as const, text: value }] });\nconst failure = (value: string) => ({ ...text(value), isError: true });\nconst message = (error: unknown) => (error instanceof Error ? error.message : String(error)).replace(/^\\[[a-z_]+\\]\\s*/i, \"\");\n\nconst sqlArg = z.string().describe(\"A single read-only SELECT statement. Do not add LIMIT for paging; the table pages by itself.\");\nconst sourceArg = z.string().optional().describe(\"Data source ID. Omit to use the default source.\");\n\n/**\n * Adds the Surfaces tools and app page to an MCP server.\n *\n * Tools the model can call show a view (table, chart, explorer, editor,\n * schema, or an A2UI surface) in the host's UI. One further tool, hidden\n * from the model, lets the app page fetch data. SQL is checked before a view\n * is shown, so a mistake comes back to the model as an error it can fix.\n */\nexport function registerSurfacesApps(server: McpServer, options: SurfacesAppsOptions): void {\n const { dataSource } = options;\n const catalog = options.catalog ?? analyticsCatalog;\n const maxRows = options.maxRowsPerRequest ?? 1000;\n\n const sourceOf = async (requested: string | undefined): Promise<string> => {\n if (requested) return requested;\n if (options.defaultSourceId) return options.defaultSourceId;\n const first = (await dataSource.listSources({})).sources[0];\n if (!first) throw new Error(\"No data sources are configured.\");\n return first.id;\n };\n const show = (view: AppView, summary: string) => ({ ...text(summary), structuredContent: view as unknown as Record<string, unknown> });\n /** Runs the query once, cheaply, so a bad query is reported to the model instead of to the person. */\n const GRAINS = [\"minute\", \"hour\", \"day\", \"week\", \"month\", \"quarter\", \"year\"] as const;\n const AGGREGATES = [\"sum\", \"avg\", \"count\", \"count_distinct\", \"min\", \"max\", \"median\", \"stddev\", \"variance\", \"percentile\"] as const;\n const dimensionArg = z.union([z.string(), z.object({ column: z.string(), grain: z.enum(GRAINS).optional(), label: z.string().optional() })]);\n\n const checked = async <T extends AppView>(view: T & { sourceId: string; sql: string }, describe: (rows: bigint) => string) => {\n try {\n const { rowCount } = await dataSource.count({ sourceId: view.sourceId, query: { baseSql: view.sql } });\n return show(view, describe(rowCount));\n } catch (error) {\n return failure(`The query did not run: ${message(error)}`);\n }\n };\n\n registerAppResource(server, \"Surfaces app\", APP_RESOURCE_URI, { mimeType: RESOURCE_MIME_TYPE, description: \"Interactive data views.\" }, async () => ({\n contents: [{ uri: APP_RESOURCE_URI, mimeType: RESOURCE_MIME_TYPE, text: typeof options.appHtml === \"string\" ? options.appHtml : await options.appHtml() }],\n }));\n\n registerAppTool(\n server,\n \"show_data_grid\",\n {\n title: \"Show a table\",\n description: \"Shows the rows of a SQL query in an interactive table the person can scroll and sort. Use for looking at records.\",\n inputSchema: { sql: sqlArg, sourceId: sourceArg, title: z.string().optional() },\n annotations: { readOnlyHint: true },\n _meta: ui,\n },\n async ({ sql, sourceId, title }) =>\n checked({ view: \"grid\", sourceId: await sourceOf(sourceId), sql, title }, (rows) => `Showing a table of ${rows} rows.`),\n );\n\n registerAppTool(\n server,\n \"show_chart\",\n {\n title: \"Show a chart\",\n description:\n \"Charts a SQL query. Give each y measure an aggregate so the database summarises by x; without one the chart plots a random sample of rows. Set xGrain for a time series and xBins for a histogram. Each y entry is a series: give one its own type and axis for a compound chart (bars with a line on a second scale). Choose the form from the comparison: bars for amounts across categories (they are sorted largest first and start at zero), a line with xGrain for change over time, xBins for a distribution, scatter for two measures. Avoid a pie beyond five slices, more than five lines, and a second y scale (use two charts on the same x instead); the chart shows advice when its shape is hard to read.\",\n inputSchema: {\n sql: sqlArg,\n type: z.enum([\"bar\", \"line\", \"area\", \"scatter\", \"pie\"]),\n x: z.string().describe(\"Column for the x axis, or the slices of a pie.\"),\n xGrain: z.enum(GRAINS).optional().describe(\"Group a date or time x column into buckets of this size.\"),\n xBins: z.number().int().min(2).max(200).optional().describe(\"Group a numeric x column into about this many bins.\"),\n y: z\n .array(\n z.object({\n column: z.string().optional(),\n aggregate: z.enum(AGGREGATES).optional(),\n percentile: z.number().min(0).max(1).optional(),\n label: z.string().optional(),\n type: z.enum([\"bar\", \"line\", \"area\", \"scatter\"]).optional().describe(\"Draw this series differently from the chart type.\"),\n axis: z.enum([\"left\", \"right\"]).optional().describe(\"Use the right axis for a measure on a different scale.\"),\n }),\n )\n .min(1),\n splitBy: z.string().optional().describe(\"Column whose values become separate series.\"),\n stacked: z.boolean().optional(),\n legend: z.enum([\"top\", \"bottom\", \"right\", \"none\"]).optional(),\n sourceId: sourceArg,\n title: z.string().optional(),\n },\n annotations: { readOnlyHint: true },\n _meta: ui,\n },\n async ({ sql, type, x, xGrain, xBins, y, splitBy, stacked, legend, sourceId, title }) =>\n checked(\n { view: \"chart\", sourceId: await sourceOf(sourceId), sql, type, x, xGrain, xBins, y, splitBy, stacked, legend, title },\n (rows) => `Showing a ${type} chart over ${rows} rows.`,\n ),\n );\n\n registerAppTool(\n server,\n \"show_pivot_table\",\n {\n title: \"Show a pivot table\",\n description:\n \"Shows a pivot table over a SQL query: row values down the side, column values across the top, summarised measures in the cells, with totals. The database does the grouping. Choose columns with few distinct values.\",\n inputSchema: {\n sql: sqlArg,\n rows: z.array(dimensionArg).min(1).max(4).describe(\"Columns whose values become the rows.\"),\n columns: z.array(dimensionArg).max(2).optional().describe(\"Columns whose values become the columns.\"),\n measures: z\n .array(z.object({ column: z.string().optional(), aggregate: z.enum(AGGREGATES), percentile: z.number().min(0).max(1).optional(), label: z.string().optional() }))\n .min(1)\n .max(6),\n sourceId: sourceArg,\n title: z.string().optional(),\n },\n annotations: { readOnlyHint: true },\n _meta: ui,\n },\n async ({ sql, rows, columns, measures, sourceId, title }) =>\n checked({ view: \"pivot\", sourceId: await sourceOf(sourceId), sql, rows, columns, measures, title }, (count) => `Showing a pivot table over ${count} rows.`),\n );\n\n registerAppTool(\n server,\n \"show_query_result\",\n {\n title: \"Explore a query\",\n description: \"Shows a query the person can explore themselves: filters, a table and a chart of the same result, and the SQL that ran.\",\n inputSchema: { sql: sqlArg, sourceId: sourceArg, title: z.string().optional() },\n annotations: { readOnlyHint: true },\n _meta: ui,\n },\n async ({ sql, sourceId, title }) =>\n checked({ view: \"result\", sourceId: await sourceOf(sourceId), sql, title }, (rows) => `Showing an explorable result of ${rows} rows.`),\n );\n\n registerAppTool(\n server,\n \"open_sql_editor\",\n {\n title: \"Open the SQL editor\",\n description: \"Opens a SQL editor with autocomplete for the source's tables, where the person can write and run queries.\",\n inputSchema: { sql: z.string().optional().describe(\"SQL to start with.\"), sourceId: sourceArg },\n annotations: { readOnlyHint: true },\n _meta: ui,\n },\n async ({ sql, sourceId }) => show({ view: \"editor\", sourceId: await sourceOf(sourceId), sql: sql ?? \"\" }, \"Opened the SQL editor.\"),\n );\n\n registerAppTool(\n server,\n \"show_schema_explorer\",\n {\n title: \"Browse tables\",\n description: \"Shows a searchable tree of the source's tables and their columns.\",\n inputSchema: { sourceId: sourceArg },\n annotations: { readOnlyHint: true },\n _meta: ui,\n },\n async ({ sourceId }) => show({ view: \"schema\", sourceId: await sourceOf(sourceId) }, \"Showing the tables in this source.\"),\n );\n\n const render = (messages: unknown[]) => {\n const issues = messages.flatMap((m, index) => catalog.validateMessage(m).map((issue) => `message ${index}${issue.path}: ${issue.message}`));\n if (issues.length > 0) return failure(`The surface was not shown because it does not match the catalog:\\n${issues.slice(0, 20).join(\"\\n\")}`);\n return show({ view: \"surface\", messages }, \"Showing the surface.\");\n };\n\n registerAppTool(\n server,\n \"render_surface\",\n {\n title: \"Show a custom view\",\n description: `Shows a custom layout (a dashboard, a summary) described as A2UI messages using catalog ${catalog.id}. Call get_component_docs first to learn the components.`,\n inputSchema: { messages: z.array(z.record(z.string(), z.unknown())).min(1).describe(\"A2UI messages: createSurface, then updateComponents, then optionally updateDataModel.\") },\n annotations: { readOnlyHint: true },\n _meta: ui,\n },\n async ({ messages }) => render(messages),\n );\n\n registerAppTool(\n server,\n \"show_dashboard\",\n {\n title: \"Show a dashboard\",\n description: \"Shows a dashboard described as a json-render spec ({ root, elements, state }). Prefer render_surface for new work.\",\n inputSchema: {\n spec: z.object({\n root: z.string(),\n elements: z.record(z.string(), z.object({ type: z.string(), props: z.record(z.string(), z.unknown()).optional(), children: z.array(z.string()).optional() })),\n state: z.record(z.string(), z.unknown()).optional(),\n }),\n },\n annotations: { readOnlyHint: true },\n _meta: ui,\n },\n async ({ spec }) => render(fromJsonRender(spec as JsonRenderSpec, catalog)),\n );\n\n server.registerTool(\n \"get_component_docs\",\n {\n title: \"Component documentation\",\n description: \"Explains how to build a custom view: the message format and every component with its props and an example. Pass a component name for just that one.\",\n inputSchema: { component: z.string().optional() },\n annotations: { readOnlyHint: true },\n },\n async ({ component }) => {\n if (!component) return text(catalogPrompt(catalog));\n const docs = catalogDocs(catalog);\n return Object.hasOwn(docs, component) ? text(docs[component]!) : failure(`No component named ${component}. Available: ${Object.keys(docs).join(\", \")}.`);\n },\n );\n\n /** A table's name as SQL writes it. A schema with no catalog above it is a database (Teradata) and is part of the name. */\n const tableName = (ref: { catalog?: string; schema?: string; table?: string } | undefined) => (!ref?.catalog && ref?.schema ? `${ref.schema}.${ref.table ?? \"\"}` : (ref?.table ?? \"\"));\n const columnsOf = async (sourceId: string, ref: { catalog?: string; schema?: string; table?: string } | undefined) =>\n (await dataSource.describeTable({ sourceId, ref: { catalog: ref?.catalog, schema: ref?.schema, table: ref?.table ?? \"\" } }).catch(() => undefined))?.table;\n\n server.registerTool(\n \"list_tables\",\n {\n title: \"List tables\",\n description:\n \"Lists the data sources and the tables in one of them. A short list comes with each table's columns and types; a long one gives names only, so narrow it with `search` or `database`, or call describe_table. Call this before writing SQL.\",\n inputSchema: {\n sourceId: sourceArg,\n database: z.string().optional().describe(\"A database or schema to list. Omit for the ones the source covers by default.\"),\n search: z.string().optional().describe(\"Part of a table name.\"),\n },\n annotations: { readOnlyHint: true },\n },\n async ({ sourceId, database, search }) => {\n try {\n const { sources } = await dataSource.listSources({});\n const id = await sourceOf(sourceId);\n const { tables } = await dataSource.listTables({ sourceId: id, schema: database ?? \"\", search: search ?? \"\" });\n const lines = [`Sources: ${sources.map((s) => s.id).join(\", \")}`, `Tables in ${id}${database ? `, ${database}` : \"\"}:`];\n // Describing every table of a warehouse would take minutes: past a screenful, names only.\n const detailed = tables.length <= 30;\n for (const table of tables.slice(0, 200)) {\n const name = tableName(table.ref);\n const columns = detailed ? `(${(await columnsOf(id, table.ref))?.columns.map((c) => `${c.name} ${c.nativeType}`).join(\", \") ?? \"\"})` : \"\";\n lines.push(`- ${name}${columns}${table.comment ? ` — ${table.comment}` : \"\"}`);\n }\n if (tables.length > 200) lines.push(`…and ${tables.length - 200} more. Narrow the list with search or database.`);\n else if (!detailed) lines.push(\"Names only: call describe_table for a table's columns.\");\n return text(lines.join(\"\\n\"));\n } catch (error) {\n return failure(message(error));\n }\n },\n );\n\n server.registerTool(\n \"describe_table\",\n {\n title: \"Describe a table\",\n description: \"One table's columns: names, types, keys and descriptions, and the tables it declares joins to. Never data values.\",\n inputSchema: {\n table: z.string().describe(\"The table's name, as list_tables gave it (database.table where it has a database).\"),\n sourceId: sourceArg,\n },\n annotations: { readOnlyHint: true },\n },\n async ({ table, sourceId }) => {\n try {\n const id = await sourceOf(sourceId);\n const parts = table.split(\".\");\n const ref = parts.length > 1 ? { schema: parts.slice(0, -1).join(\".\"), table: parts.at(-1)! } : { table };\n const detail = (await dataSource.describeTable({ sourceId: id, ref })).table;\n if (!detail) return failure(`Table not found: ${table}`);\n const lines = [`${tableName(detail.summary?.ref) || table}${detail.summary?.comment ? ` — ${detail.summary.comment}` : \"\"}`];\n for (const column of detail.columns) lines.push(`- ${column.name} ${column.nativeType}${column.primaryKey ? \" (key)\" : \"\"}${column.comment ? ` — ${column.comment}` : \"\"}`);\n for (const key of detail.foreignKeys) {\n const other = tableName(key.references);\n lines.push(`Joins to ${other}: ${key.columns.map((c, i) => `${c} = ${other}.${key.referencedColumns[i] ?? c}`).join(\" AND \")}`);\n }\n return text(lines.join(\"\\n\"));\n } catch (error) {\n return failure(message(error));\n }\n },\n );\n\n const { discovery } = options;\n if (discovery) {\n server.registerTool(\n \"search_data\",\n {\n title: \"Search the catalog\",\n description: \"Finds tables and columns by words or meaning, across the databases the catalog covers. Returns names, types and descriptions, never data values.\",\n inputSchema: { query: z.string().min(1).describe(\"What to look for, e.g. customer revenue.\"), sourceId: z.string().optional().describe(\"Search one source. Omit to search all.\") },\n annotations: { readOnlyHint: true },\n },\n async ({ query, sourceId }) => {\n try {\n const found = await discovery.search({ query, sourceIds: sourceId ? [sourceId] : [], pageSize: 20 });\n if (found.hits.length === 0) return text(`Nothing in the catalog matches \"${query}\".`);\n const lines = found.hits.map((hit) => {\n const ref = hit.object?.ref;\n const name = `${ref?.sourceId}: ${tableName(ref)}${ref?.column ? `.${ref.column}` : \"\"}`;\n return `- ${name}${hit.object?.nativeType ? ` ${hit.object.nativeType}` : \"\"}${hit.object?.description ? ` — ${hit.object.description}` : \"\"}`;\n });\n return text([`${found.total} matches for \"${query}\"; the best ${lines.length}:`, ...lines].join(\"\\n\"));\n } catch (error) {\n return failure(message(error));\n }\n },\n );\n }\n\n if (options.pipelines) registerPipelineTools(server, options.pipelines, show);\n\n // The app page's data channel. Read-only, and capped per request.\n registerAppTool(\n server,\n RPC_TOOL,\n {\n title: \"Surfaces data channel\",\n description: \"Used by the Surfaces app page to fetch data. Not for direct use.\",\n inputSchema: { method: z.string(), request: z.record(z.string(), z.unknown()) },\n annotations: { readOnlyHint: true },\n _meta: { ui: { resourceUri: APP_RESOURCE_URI, visibility: [\"app\"] } },\n },\n async ({ method, request }) => {\n if (!isRpcMethod(method)) return failure(`Unknown method ${method}.`);\n const shape = RPC[method];\n try {\n // Requests arrive as protobuf JSON; decode them so enums, 64-bit numbers and oneofs are read correctly.\n const decoded = fromJson(shape.request, request as never);\n if (method === \"execute\") {\n const execute = decoded as ExecuteRequest;\n execute.query ??= create(ViewQuerySchema);\n execute.query.page ??= create(PagingSchema);\n execute.query.page.limit = Math.min(execute.query.page.limit || maxRows, maxRows);\n const messages = [];\n for await (const part of dataSource.execute(execute)) messages.push(toJson(shape.response, part));\n return { ...text(`${messages.length} messages`), structuredContent: { messages } };\n }\n const response = await (dataSource[method] as (r: unknown) => Promise<never>)(decoded);\n return { ...text(\"ok\"), structuredContent: { messages: [toJson(shape.response, response)] } };\n } catch (error) {\n return failure(message(error));\n }\n },\n );\n}\n\n/** The agent's pipeline tools as MCP tools: one implementation, so the two cannot drift. */\nfunction registerPipelineTools(server: McpServer, pipelines: Pipelines, show: (view: AppView, summary: string) => ReturnType<typeof text> & { structuredContent: Record<string, unknown> }) {\n const tools = new Map(pipelineTools(pipelines).map((tool) => [tool.name, tool]));\n const toText = (value: unknown) => JSON.stringify(value, (_, v) => (typeof v === \"bigint\" ? Number(v) : v), 2);\n const json = (value: unknown) => text(toText(value));\n const call = (name: string) => async (input: unknown) => {\n try {\n return json(await tools.get(name)!.run(input));\n } catch (error) {\n return failure(message(error));\n }\n };\n const pipelineId = z.string().describe(\"The pipeline's id, from list_pipelines.\");\n const select = z.array(z.string()).optional().describe(\"Datasets to build: name alone, name+ with what reads it, +name with what it reads. Omit for all.\");\n const describe = (name: string) => tools.get(name)!.description;\n server.registerTool(\"list_pipelines\", { title: \"List pipelines\", description: describe(\"list_pipelines\"), inputSchema: {}, annotations: { readOnlyHint: true } }, call(\"list_pipelines\"));\n server.registerTool(\"describe_pipeline\", { title: \"Describe a pipeline\", description: describe(\"describe_pipeline\"), inputSchema: { pipelineId }, annotations: { readOnlyHint: true } }, call(\"describe_pipeline\"));\n server.registerTool(\"check_pipeline\", { title: \"Check a pipeline\", description: describe(\"check_pipeline\"), inputSchema: { pipelineId, select }, annotations: { readOnlyHint: true } }, call(\"check_pipeline\"));\n server.registerTool(\"get_run\", { title: \"A pipeline run\", description: describe(\"get_run\"), inputSchema: { pipelineId, runId: z.string() }, annotations: { readOnlyHint: true } }, call(\"get_run\"));\n\n registerAppTool(\n server,\n \"show_pipeline\",\n {\n title: \"Show a pipeline\",\n description:\n \"Shows a pipeline live to the person: its datasets and how they feed one another, its runs, and each dataset's query, grain, key, columns and check results. The person can run it, check it, rebuild one dataset or cancel from there.\",\n inputSchema: { pipelineId },\n annotations: { readOnlyHint: true },\n _meta: ui,\n },\n async ({ pipelineId: id }) => {\n try {\n const { pipeline } = await pipelines.getPipeline({ id });\n if (!pipeline?.summary) return failure(`Unknown pipeline ${id}.`);\n const { runs } = await pipelines.listRuns({ pipelineId: id, pageSize: 1 });\n const built = pipeline.datasets.filter((d) => d.sql).length;\n const last = runs[0] ? `; the last run, ${runs[0].id}, is ${RunState[runs[0].state].toLowerCase()}` : \"; it has not run yet\";\n return show(\n { view: \"pipeline\", pipelineId: id, sourceId: pipeline.summary.sourceId },\n `Showing the pipeline ${pipeline.summary.name}: ${built} dataset${built === 1 ? \"\" : \"s\"}${last}.`,\n );\n } catch (error) {\n return failure(message(error));\n }\n },\n );\n\n registerAppTool(\n server,\n \"propose_dataset\",\n {\n title: \"Propose a dataset\",\n description: `${describe(\"propose_dataset\")} The proposal is shown to the person for review, filled in here: do not draw it yourself. The person edits it, names themselves and approves, which saves it; their decision comes back as a message.`,\n inputSchema: {\n pipelineId: z.string().describe(\"The pipeline's id, from list_pipelines, or a new id to propose a new pipeline.\"),\n sourceId: z.string().optional().describe(\"For a new pipeline only: the source it reads and builds in.\"),\n pipelineName: z.string().optional().describe(\"For a new pipeline only: its name.\"),\n name: z.string(),\n sql: z.string(),\n grain: z.string(),\n description: z.string().optional(),\n layer: z.enum([\"bronze\", \"silver\", \"gold\"]).optional(),\n view: z.boolean().optional(),\n depends: z.array(z.string()).optional(),\n primaryKey: z.array(z.string()).optional(),\n columns: z.array(z.object({ name: z.string(), type: z.string().optional(), description: z.string().optional() })).optional(),\n checks: z\n .array(\n z.object({\n kind: z.enum([\"unique\", \"not_null\", \"relationships\", \"accepted_values\", \"row_count\"]),\n columns: z.array(z.string()).optional(),\n toTable: z.string().optional(),\n toColumn: z.string().optional(),\n values: z.array(z.string()).optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n warnOnly: z.boolean().optional(),\n }),\n )\n .optional(),\n },\n annotations: { readOnlyHint: true },\n _meta: ui,\n },\n async (input) => {\n try {\n const proposed = (await tools.get(\"propose_dataset\")!.run(input)) as { pipelineId: string; change: string; expectedVersion: number; digest: string; dataset: string; pipeline: { sourceId?: string; name?: string } };\n return show(\n {\n view: \"datasetReview\",\n pipeline: proposed.pipeline,\n dataset: input.name,\n expectedVersion: proposed.expectedVersion,\n digest: proposed.digest,\n sourceId: proposed.pipeline.sourceId ?? \"\",\n proposedBy: \"the agent\",\n },\n `Showing the proposal (${proposed.change}, based on version ${proposed.expectedVersion}) for the person to review. Nothing is saved until they approve, and nothing is built until the pipeline runs.`,\n );\n } catch (error) {\n return failure(message(error));\n }\n },\n );\n\n server.registerTool(\n \"run_pipeline\",\n {\n title: \"Run a pipeline\",\n description: \"Builds a pipeline's datasets, replacing their tables, then runs their checks. Ask the person first. Waits up to a minute, then returns the run id for get_run.\",\n inputSchema: { pipelineId, select },\n annotations: { destructiveHint: true, idempotentHint: true, readOnlyHint: false },\n },\n async ({ pipelineId: id, select: chosen }) => {\n try {\n const { pipelines: list } = await pipelines.listPipelines({});\n if (!list.some((p) => p.id === id)) return failure(`Unknown pipeline ${id}.`);\n let { run } = await pipelines.startRun({ pipelineId: id, select: chosen ?? [], trigger: \"agent\", startedBy: \"agent over MCP\" });\n for (const until = Date.now() + 60_000; run && run.state === RunState.RUNNING && Date.now() < until; ) {\n await new Promise((resolve) => setTimeout(resolve, 250));\n run = (await pipelines.getRun({ pipelineId: id, runId: run.id })).run;\n }\n return json(runSummary(run!));\n } catch (error) {\n return failure(message(error));\n }\n },\n );\n\n // The app page's pipeline channel. Hidden from the model. What changes\n // anything comes from a person in the page: a run they press (never a full\n // refresh here), or a save they approved, which the backend still checks for\n // the approver, the digest of what they saw and the version it was made against.\n registerAppTool(\n server,\n PIPELINE_RPC_TOOL,\n {\n title: \"Surfaces pipeline channel\",\n description: \"Used by the Surfaces app page to show pipelines and act on a person's choices there. Not for direct use.\",\n inputSchema: { method: z.string(), request: z.record(z.string(), z.unknown()) },\n annotations: { readOnlyHint: false, destructiveHint: false },\n _meta: { ui: { resourceUri: APP_RESOURCE_URI, visibility: [\"app\"] } },\n },\n async ({ method, request }) => {\n if (!isPipelineRpcMethod(method)) return failure(`Unknown method ${method}.`);\n const handler = pipelines[method] as ((r: unknown) => Promise<never>) | undefined;\n if (!handler) return failure(\"This server keeps no saved pipelines.\");\n const shape = PIPELINE_RPC[method];\n try {\n const decoded = fromJson(shape.request, request as never);\n if (method === \"startRun\") {\n const start = decoded as StartRunRequest;\n if (start.refreshKind === RefreshKind.FULL_REFRESH || start.confirmFullRefresh) return failure(\"A full refresh is not offered here. Use the dev server's own page or the surfaces-pipelines CLI.\");\n start.trigger = \"manual\";\n start.startedBy = \"a person, in the MCP app\";\n }\n const response = await handler.call(pipelines, decoded);\n return { ...text(\"ok\"), structuredContent: { message: toJson(shape.response, response) } };\n } catch (error) {\n return failure(message(error));\n }\n },\n );\n}\n"]}