@surfaces-ui/mcp 0.4.0 → 0.6.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.
@@ -1 +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,YAAY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ool } 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"]}
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;AAiCjJ,gJAAgJ;AAChJ,MAAM,SAAS,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,eAAe,EAAE,KAAK,EAAW,CAAC;AAE1E,MAAM,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,WAAW,EAAE,gBAAgB,EAAE,EAAE,CAAC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AAC;IACH,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { create, fromJson, toJson } from \"@bufbuild/protobuf\";\nimport { RESOURCE_MIME_TYPE, registerAppResource, 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 * Wraps each request the app page makes for data, so a host can time it\n * (`createTiming` in `@surfaces-ui/mcp/node`). It is given the method's\n * name and must return what `run` returns.\n */\n around?: <T>(method: string, run: () => Promise<T>) => Promise<T>;\n}\n\n/** A tool that only reads says so both ways: a host decides what to ask a person about from these, and a directory review asks for each one. */\nconst READ_ONLY = { readOnlyHint: true, destructiveHint: false } as const;\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: READ_ONLY,\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: READ_ONLY,\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: READ_ONLY,\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: READ_ONLY,\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: READ_ONLY,\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: READ_ONLY,\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: READ_ONLY,\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: READ_ONLY,\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: READ_ONLY,\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: READ_ONLY,\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: READ_ONLY,\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: READ_ONLY,\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: READ_ONLY,\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 const around = options.around ?? ((_method, run) => run());\n return around(method, async () => {\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\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: READ_ONLY }, call(\"list_pipelines\"));\n server.registerTool(\"describe_pipeline\", { title: \"Describe a pipeline\", description: describe(\"describe_pipeline\"), inputSchema: { pipelineId }, annotations: READ_ONLY }, call(\"describe_pipeline\"));\n server.registerTool(\"check_pipeline\", { title: \"Check a pipeline\", description: describe(\"check_pipeline\"), inputSchema: { pipelineId, select }, annotations: READ_ONLY }, call(\"check_pipeline\"));\n server.registerTool(\"get_run\", { title: \"A pipeline run\", description: describe(\"get_run\"), inputSchema: { pipelineId, runId: z.string() }, annotations: READ_ONLY }, 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: READ_ONLY,\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: READ_ONLY,\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"]}
@@ -0,0 +1,101 @@
1
+ /** The database types a source reached through its own MCP server can be. */
2
+ export declare const DIALECTS: readonly ["teradata", "postgres", "mysql", "duckdb"];
3
+ export type SetupDialect = (typeof DIALECTS)[number];
4
+ /** One entry of a desktop app's list of local MCP servers. */
5
+ export interface DesktopServer {
6
+ command?: string;
7
+ args?: string[];
8
+ env?: Record<string, string>;
9
+ }
10
+ interface DesktopConfig {
11
+ mcpServers?: Record<string, DesktopServer>;
12
+ [key: string]: unknown;
13
+ }
14
+ /** A local MCP server found in the desktop config that looks like a database's. */
15
+ export interface DatabaseServer {
16
+ /** Its name in the config (`teradata-community`). */
17
+ name: string;
18
+ /** The database type its name and command point to, when they point to one. */
19
+ dialect?: SetupDialect;
20
+ command: string;
21
+ args: string[];
22
+ /** The environment variable that holds its connection string, when one can be told. Never the value. */
23
+ secretName?: string;
24
+ /** Its other environment variables, by name. Surfaces hands a database's server one value, so these are not carried over. */
25
+ otherNames: string[];
26
+ }
27
+ /** Where the Claude desktop app keeps its list of local MCP servers. */
28
+ export declare function desktopConfigFile(platform?: NodeJS.Platform, env?: Record<string, string | undefined>, home?: string): string;
29
+ /** Reads the desktop config, or an empty one when the file is not there yet. */
30
+ export declare function readDesktopConfig(file: string): DesktopConfig;
31
+ /**
32
+ * The local servers in a desktop config that a Surfaces source could be made
33
+ * from: every one started by a command, except the Surfaces server itself.
34
+ * Those that look like a database's (by name, command or arguments) come
35
+ * first and carry the type they look like.
36
+ */
37
+ export declare function databaseServers(config: DesktopConfig, own?: string): DatabaseServer[];
38
+ /** A command and its arguments as the one line `SURFACES_SOURCE_SERVER` takes, quoting what holds a space. */
39
+ export declare function commandLine(command: string, args: string[]): string;
40
+ export interface SurfacesEntryOptions {
41
+ /** The exact version of `@surfaces-ui/mcp` to start. */
42
+ version: string;
43
+ dialect: SetupDialect;
44
+ /** The command that starts the database's MCP server, its program by full path where that is known. */
45
+ command: string;
46
+ args: string[];
47
+ /** The connection string. Left out, the database's server is started without one. */
48
+ secret?: string;
49
+ /** The variable the database's server reads it from. */
50
+ secretName?: string;
51
+ /** How to start `npx`; its full path where a desktop app would not find it. */
52
+ npx?: string;
53
+ }
54
+ /** The entry that starts the Surfaces server over one database. */
55
+ export declare function surfacesEntry(options: SurfacesEntryOptions): DesktopServer;
56
+ /** The entry that starts the Surfaces server on its sample data. */
57
+ export declare function sampleEntry(version: string, npx?: string): DesktopServer;
58
+ /**
59
+ * Writes the Surfaces entry into the desktop config, keeping every other
60
+ * server and setting as it was. The file is written beside itself and moved
61
+ * into place, so a crash cannot leave half a file, and it is kept readable
62
+ * by its owner only, since it can hold a connection string.
63
+ */
64
+ export declare function writeSurfacesEntry(file: string, entry: DesktopServer, name?: string): {
65
+ replaced: boolean;
66
+ };
67
+ /** What `runSetup` needs from the terminal, so it can be run in a test. */
68
+ export interface SetupTerminal {
69
+ say(text: string): void;
70
+ ask(question: string): Promise<string>;
71
+ /** Asks without showing what is typed. */
72
+ askHidden(question: string): Promise<string>;
73
+ }
74
+ export interface SetupOptions {
75
+ /** The desktop config file. */
76
+ file: string;
77
+ /** The version of `@surfaces-ui/mcp` the entry starts. */
78
+ version: string;
79
+ terminal: SetupTerminal;
80
+ /** Finds a program's full path, for a desktop app that starts servers without a shell's PATH. */
81
+ findProgram(command: string): string | undefined;
82
+ /** Use this server from the config, without asking. */
83
+ use?: string;
84
+ /** The database type, where it cannot be told or is to be overridden. */
85
+ dialect?: string;
86
+ /** Set up the sample data only. */
87
+ sample?: boolean;
88
+ }
89
+ /**
90
+ * Sets the Claude desktop app up to start the Surfaces server over a
91
+ * database, by copying the command and the sign-in of a database server the
92
+ * person already has in that app's config, or by asking for them. The sign-in
93
+ * goes from the file to the same file (or from the keyboard, unshown, to the
94
+ * file); it is never printed. Returns what it wrote, with no value in it.
95
+ */
96
+ export declare function runSetup(options: SetupOptions): Promise<{
97
+ wrote: "sample" | "database" | "nothing";
98
+ from?: string;
99
+ dialect?: SetupDialect;
100
+ }>;
101
+ export {};
package/dist/setup.js ADDED
@@ -0,0 +1,201 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ /** The database types a source reached through its own MCP server can be. */
5
+ export const DIALECTS = ["teradata", "postgres", "mysql", "duckdb"];
6
+ /** Where the Claude desktop app keeps its list of local MCP servers. */
7
+ export function desktopConfigFile(platform = process.platform, env = process.env, home = os.homedir()) {
8
+ if (platform === "darwin")
9
+ return path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
10
+ if (platform === "win32")
11
+ return path.join(env.APPDATA ?? path.join(home, "AppData", "Roaming"), "Claude", "claude_desktop_config.json");
12
+ return path.join(env.XDG_CONFIG_HOME ?? path.join(home, ".config"), "Claude", "claude_desktop_config.json");
13
+ }
14
+ /** Reads the desktop config, or an empty one when the file is not there yet. */
15
+ export function readDesktopConfig(file) {
16
+ if (!fs.existsSync(file))
17
+ return {};
18
+ let parsed;
19
+ try {
20
+ parsed = JSON.parse(fs.readFileSync(file, "utf8"));
21
+ }
22
+ catch {
23
+ throw new Error(`${file} is not valid JSON, so it was left as it is. Fix it (a missing comma or bracket is the usual cause), then run setup again.`);
24
+ }
25
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
26
+ throw new Error(`${file} must hold a JSON object. It was left as it is.`);
27
+ return parsed;
28
+ }
29
+ const HINTS = [
30
+ ["teradata", /teradata|vantage/i],
31
+ ["postgres", /postgres|\bpg\b|supabase|neon/i],
32
+ ["mysql", /mysql|mariadb/i],
33
+ ["duckdb", /duckdb|motherduck/i],
34
+ ];
35
+ /** The variable a server reads its connection string from: `DATABASE_URI`, else the only one that is named like one, else the only one there is. */
36
+ function secretNameOf(env) {
37
+ const names = Object.keys(env);
38
+ if (names.includes("DATABASE_URI"))
39
+ return "DATABASE_URI";
40
+ const likely = names.filter((name) => /URI|URL|DSN|CONNECTION/i.test(name));
41
+ if (likely.length === 1)
42
+ return likely[0];
43
+ return names.length === 1 ? names[0] : undefined;
44
+ }
45
+ /**
46
+ * The local servers in a desktop config that a Surfaces source could be made
47
+ * from: every one started by a command, except the Surfaces server itself.
48
+ * Those that look like a database's (by name, command or arguments) come
49
+ * first and carry the type they look like.
50
+ */
51
+ export function databaseServers(config, own = "surfaces") {
52
+ const found = [];
53
+ for (const [name, server] of Object.entries(config.mcpServers ?? {})) {
54
+ if (name === own || !server || typeof server.command !== "string" || server.command === "")
55
+ continue;
56
+ const args = Array.isArray(server.args) ? server.args.map(String) : [];
57
+ if (args.some((arg) => arg.startsWith("@surfaces-ui/mcp")))
58
+ continue;
59
+ const text = [name, server.command, ...args].join(" ");
60
+ const dialect = HINTS.find(([, pattern]) => pattern.test(text))?.[0];
61
+ const env = server.env && typeof server.env === "object" ? server.env : {};
62
+ const secretName = secretNameOf(env);
63
+ found.push({ name, dialect, command: server.command, args, secretName, otherNames: Object.keys(env).filter((key) => key !== secretName) });
64
+ }
65
+ return found.sort((a, b) => Number(b.dialect !== undefined) - Number(a.dialect !== undefined));
66
+ }
67
+ /** A command and its arguments as the one line `SURFACES_SOURCE_SERVER` takes, quoting what holds a space. */
68
+ export function commandLine(command, args) {
69
+ return [command, ...args].map((word) => (/\s/.test(word) ? `"${word}"` : word)).join(" ");
70
+ }
71
+ /** The entry that starts the Surfaces server over one database. */
72
+ export function surfacesEntry(options) {
73
+ const env = { SURFACES_SOURCE_DIALECT: options.dialect, SURFACES_SOURCE_SERVER: commandLine(options.command, options.args) };
74
+ if (options.secret !== undefined && options.secret !== "")
75
+ env.SURFACES_SOURCE_SECRET = options.secret;
76
+ if (options.secretName && options.secretName !== "DATABASE_URI")
77
+ env.SURFACES_SOURCE_SECRET_NAME = options.secretName;
78
+ return { command: options.npx ?? "npx", args: ["-y", `@surfaces-ui/mcp@${options.version}`], env };
79
+ }
80
+ /** The entry that starts the Surfaces server on its sample data. */
81
+ export function sampleEntry(version, npx = "npx") {
82
+ return { command: npx, args: ["-y", `@surfaces-ui/mcp@${version}`] };
83
+ }
84
+ /**
85
+ * Writes the Surfaces entry into the desktop config, keeping every other
86
+ * server and setting as it was. The file is written beside itself and moved
87
+ * into place, so a crash cannot leave half a file, and it is kept readable
88
+ * by its owner only, since it can hold a connection string.
89
+ */
90
+ export function writeSurfacesEntry(file, entry, name = "surfaces") {
91
+ const config = readDesktopConfig(file);
92
+ const servers = config.mcpServers ?? {};
93
+ const replaced = Object.hasOwn(servers, name);
94
+ const next = { ...config, mcpServers: { ...servers, [name]: entry } };
95
+ fs.mkdirSync(path.dirname(file), { recursive: true });
96
+ const draft = `${file}.surfaces-setup`;
97
+ fs.writeFileSync(draft, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
98
+ fs.renameSync(draft, file);
99
+ return { replaced };
100
+ }
101
+ const asDialect = (text) => DIALECTS.find((dialect) => dialect === text?.trim().toLowerCase());
102
+ /**
103
+ * Sets the Claude desktop app up to start the Surfaces server over a
104
+ * database, by copying the command and the sign-in of a database server the
105
+ * person already has in that app's config, or by asking for them. The sign-in
106
+ * goes from the file to the same file (or from the keyboard, unshown, to the
107
+ * file); it is never printed. Returns what it wrote, with no value in it.
108
+ */
109
+ export async function runSetup(options) {
110
+ const { file, version, terminal } = options;
111
+ const { say, ask } = terminal;
112
+ const config = readDesktopConfig(file);
113
+ const done = (replaced) => {
114
+ say(`${replaced ? "Updated" : "Added"} the Surfaces server in ${file}.`);
115
+ say("Next: quit the Claude app fully and open it again, then start a new chat.");
116
+ };
117
+ if (options.sample) {
118
+ done(writeSurfacesEntry(file, sampleEntry(version)).replaced);
119
+ say('Then ask: "Use the surfaces tools to show a chart of the sample retail data."');
120
+ return { wrote: "sample" };
121
+ }
122
+ const servers = databaseServers(config);
123
+ let chosen;
124
+ let manual = false;
125
+ if (options.use) {
126
+ chosen = servers.find((server) => server.name === options.use);
127
+ if (!chosen)
128
+ throw new Error(`There is no server named "${options.use}" in ${file}.${servers.length > 0 ? ` It has: ${servers.map((server) => server.name).join(", ")}.` : ""}`);
129
+ }
130
+ else if (servers.length === 0) {
131
+ say(`No database server was found in ${file}, so its details are asked for here.`);
132
+ manual = true;
133
+ }
134
+ else {
135
+ say("Servers already set up in the Claude app:");
136
+ servers.forEach((server, index) => say(` ${index + 1}. ${server.name}${server.dialect ? ` (${server.dialect})` : ""}`));
137
+ say(` ${servers.length + 1}. A database that is not in this list`);
138
+ say(` ${servers.length + 2}. No database: the sample data only`);
139
+ const suggested = servers[0].dialect ? "1" : "";
140
+ const answer = (await ask(`Which one should Surfaces show data from?${suggested ? " [1]" : ""} `)).trim() || suggested;
141
+ const picked = Number(answer);
142
+ if (!Number.isInteger(picked) || picked < 1 || picked > servers.length + 2) {
143
+ say("Nothing was changed.");
144
+ return { wrote: "nothing" };
145
+ }
146
+ if (picked === servers.length + 2) {
147
+ done(writeSurfacesEntry(file, sampleEntry(version)).replaced);
148
+ return { wrote: "sample" };
149
+ }
150
+ if (picked === servers.length + 1)
151
+ manual = true;
152
+ else
153
+ chosen = servers[picked - 1];
154
+ }
155
+ let dialect = asDialect(options.dialect) ?? chosen?.dialect;
156
+ if (options.dialect && !asDialect(options.dialect))
157
+ throw new Error(`The database type must be one of ${DIALECTS.join(", ")}, not "${options.dialect}".`);
158
+ if (!dialect) {
159
+ dialect = asDialect(await ask(`What kind of database is it? (${DIALECTS.join(", ")}) `));
160
+ if (!dialect) {
161
+ say(`Surfaces works with ${DIALECTS.join(", ")}. Nothing was changed.`);
162
+ return { wrote: "nothing" };
163
+ }
164
+ }
165
+ let command;
166
+ let args;
167
+ let secret;
168
+ let secretName;
169
+ if (chosen) {
170
+ ({ command, args, secretName } = chosen);
171
+ secret = secretName ? config.mcpServers?.[chosen.name]?.env?.[secretName] : undefined;
172
+ if (secret !== undefined)
173
+ say(`The sign-in ${chosen.name} uses (${secretName}) was copied inside that file. It was not shown and went nowhere else.`);
174
+ else if (chosen.otherNames.length > 0)
175
+ say(`${chosen.name} signs in with several settings (${chosen.otherNames.join(", ")}). Surfaces hands a database's server one connection string, so none was copied; inline views may not be able to sign in.`);
176
+ if (secret !== undefined && chosen.otherNames.length > 0)
177
+ say(`Its other settings (${chosen.otherNames.join(", ")}) were not copied: Surfaces hands a database's server only its connection string.`);
178
+ }
179
+ else if (manual) {
180
+ const line = (await ask("The command that starts that database's MCP server (for example: uvx teradata-mcp-server): ")).trim();
181
+ const parts = [...line.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].map((match) => match[1] ?? match[2] ?? match[3]);
182
+ if (parts.length === 0) {
183
+ say("Nothing was changed.");
184
+ return { wrote: "nothing" };
185
+ }
186
+ [command, ...args] = parts;
187
+ secretName = (await ask("The name that server reads its connection string from [DATABASE_URI]: ")).trim() || "DATABASE_URI";
188
+ secret = await terminal.askHidden("The connection string (what you type is not shown): ");
189
+ }
190
+ else
191
+ return { wrote: "nothing" };
192
+ const found = options.findProgram(command);
193
+ if (!found)
194
+ say(`The program ${command} was not found on this computer. The entry is written all the same; install ${command}, or inline views will not reach the database.`);
195
+ const entry = surfacesEntry({ version, dialect, command: found ?? command, args, secret, secretName });
196
+ done(writeSurfacesEntry(file, entry).replaced);
197
+ say('Then ask: "Use the surfaces tools to list my tables", and "show <a table> as a grid".');
198
+ say("That file holds the connection string as plain text, as it does for your other servers. Keep it to yourself.");
199
+ return { wrote: "database", from: chosen?.name, dialect };
200
+ }
201
+ //# sourceMappingURL=setup.js.map