@surfaces-ui/mcp 0.5.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.
- package/dist/app.html +50 -49
- package/dist/cli.js +108 -4
- package/dist/cli.js.map +1 -1
- package/dist/server.d.ts +6 -0
- package/dist/server.js +21 -18
- package/dist/server.js.map +1 -1
- package/dist/setup.d.ts +101 -0
- package/dist/setup.js +201 -0
- package/dist/setup.js.map +1 -0
- package/dist/timing.d.ts +27 -0
- package/dist/timing.js +84 -0
- package/dist/timing.js.map +1 -0
- package/package.json +12 -10
package/dist/cli.js
CHANGED
|
@@ -3,9 +3,12 @@ import fs from "node:fs";
|
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { McpServer } from "@modelcontextprotocol/server";
|
|
5
5
|
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
|
|
6
|
-
import
|
|
6
|
+
import readline from "node:readline";
|
|
7
|
+
import { CONFIG_FILES, configFromEnv, findConfig, findProgram, createSurfacesServer, loadConfig, loadEnvFile, openSources, serverOptions } from "@surfaces-ui/dev-server";
|
|
7
8
|
import { installMcpServer, readAppHtml } from "./node.js";
|
|
8
9
|
import { registerSurfacesApps } from "./server.js";
|
|
10
|
+
import { desktopConfigFile, runSetup } from "./setup.js";
|
|
11
|
+
import { createTiming } from "./timing.js";
|
|
9
12
|
const args = process.argv.slice(2);
|
|
10
13
|
const flag = (name) => {
|
|
11
14
|
const at = args.indexOf(name);
|
|
@@ -22,6 +25,48 @@ try {
|
|
|
22
25
|
if (!config)
|
|
23
26
|
say(`No config found in ${dir}. Create ${CONFIG_FILES[0]} with your data sources before starting the server.`);
|
|
24
27
|
}
|
|
28
|
+
else if (args[0] === "setup") {
|
|
29
|
+
// Sets the Claude desktop app up to start this server over a database the person already has there.
|
|
30
|
+
const version = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
31
|
+
const lines = readline.createInterface({ input: process.stdin, output: process.stderr, terminal: process.stdin.isTTY === true });
|
|
32
|
+
let hidden = false;
|
|
33
|
+
// What is typed for a connection string is not echoed.
|
|
34
|
+
const output = lines;
|
|
35
|
+
const write = output._writeToOutput.bind(lines);
|
|
36
|
+
output._writeToOutput = (text) => {
|
|
37
|
+
if (!hidden)
|
|
38
|
+
write(text);
|
|
39
|
+
};
|
|
40
|
+
const ask = (question) => new Promise((resolve) => lines.question(question, resolve));
|
|
41
|
+
try {
|
|
42
|
+
await runSetup({
|
|
43
|
+
file: flag("--file") ?? desktopConfigFile(),
|
|
44
|
+
version,
|
|
45
|
+
findProgram,
|
|
46
|
+
use: flag("--use"),
|
|
47
|
+
dialect: flag("--dialect"),
|
|
48
|
+
sample: args.includes("--sample"),
|
|
49
|
+
terminal: {
|
|
50
|
+
say,
|
|
51
|
+
ask,
|
|
52
|
+
askHidden: async (question) => {
|
|
53
|
+
process.stderr.write(question);
|
|
54
|
+
hidden = true;
|
|
55
|
+
try {
|
|
56
|
+
return await ask("");
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
hidden = false;
|
|
60
|
+
process.stderr.write("\n");
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
finally {
|
|
67
|
+
lines.close();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
25
70
|
else {
|
|
26
71
|
// A project's config in the working directory, or a person's own in ~/.surfaces, for a host with no project folder.
|
|
27
72
|
const file = flag("--config") ?? findConfig();
|
|
@@ -30,14 +75,73 @@ try {
|
|
|
30
75
|
if (secrets.names.length > 0)
|
|
31
76
|
say(`Read ${secrets.names.join(", ")} from ${secrets.file}.`);
|
|
32
77
|
// With no config file, a source named in the environment (a plugin's settings); with neither, the six sample industry models.
|
|
33
|
-
|
|
78
|
+
// Settings that cannot be used (a launcher that is not installed, a database type with no server named) do not stop
|
|
79
|
+
// the server: it starts on the sample data and says what is wrong through `check_setup`, where a person can act on it.
|
|
80
|
+
let fromEnv;
|
|
81
|
+
let problem;
|
|
82
|
+
if (!file) {
|
|
83
|
+
try {
|
|
84
|
+
fromEnv = configFromEnv();
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
problem = error instanceof Error ? error.message : String(error);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
34
90
|
const { config, dir } = file ? await loadConfig(file) : { config: fromEnv ?? { seeds: true }, dir: process.cwd() };
|
|
35
91
|
const sources = await openSources(config, dir);
|
|
36
92
|
const backend = await createSurfacesServer(await serverOptions(config, sources, dir));
|
|
37
93
|
const server = new McpServer({ name: "surfaces", version: "0.0.0" });
|
|
38
|
-
|
|
94
|
+
const timing = createTiming();
|
|
95
|
+
registerSurfacesApps(server, { around: timing.around, dataSource: backend.dataSource, discovery: backend.discovery, ...(backend.pipelines ? { pipelines: backend.pipelines } : {}), appHtml: readAppHtml });
|
|
96
|
+
const set = (name) => {
|
|
97
|
+
const value = process.env[name]?.trim() ?? "";
|
|
98
|
+
return value !== "" && !value.startsWith("${") && !/^(none|sample data)$/i.test(value);
|
|
99
|
+
};
|
|
100
|
+
server.registerTool("check_setup", {
|
|
101
|
+
title: "Check the data setup",
|
|
102
|
+
description: "Says where this server's data comes from (the person's own database, a config file, or the built-in sample data), whether it can be reached right now, and what to do if not. Call it first when a data tool fails, when someone asks to connect their database, or when only sample data shows and they expected their own. It reads settings and runs one harmless listing; it never shows a password.",
|
|
103
|
+
inputSchema: {},
|
|
104
|
+
annotations: { readOnlyHint: true, destructiveHint: false },
|
|
105
|
+
}, async () => {
|
|
106
|
+
const lines = [];
|
|
107
|
+
const own = fromEnv?.sources?.[0];
|
|
108
|
+
if (file)
|
|
109
|
+
lines.push(`Data comes from the config file ${file}: ${sources.map((s) => s.id).join(", ")}.`);
|
|
110
|
+
else if (own && own.engine === "mcp")
|
|
111
|
+
lines.push(`Data comes from the person's ${own.dialect} database, set in this plugin's settings, through ${"url" in own.server ? "a remote MCP server" : `the MCP server started by ${path.basename(own.server.command)}`}.`);
|
|
112
|
+
else
|
|
113
|
+
lines.push("Data is the built-in sample data (retail, healthcare, fraud, telco, transportation, manufacturing). No database is set up.");
|
|
114
|
+
if (problem)
|
|
115
|
+
lines.push(`The settings could not be used, so the sample data is shown instead: ${problem}`);
|
|
116
|
+
if (!file) {
|
|
117
|
+
lines.push(`Settings filled in: database type ${set("SURFACES_SOURCE_DIALECT") ? "yes" : "no"}, the database's MCP server ${set("SURFACES_SOURCE_SERVER") ? "yes" : "no"}, connection string or token ${set("SURFACES_SOURCE_SECRET") ? "yes" : "no"}.`);
|
|
118
|
+
}
|
|
119
|
+
if (own) {
|
|
120
|
+
try {
|
|
121
|
+
const { schemas } = await backend.dataSource.listSchemas({ sourceId: own.id, catalog: "" });
|
|
122
|
+
lines.push(`It works: the database answered, and ${schemas.length} ${schemas.length === 1 ? "database is" : "databases are"} visible${schemas.length > 0 ? ` (${schemas.slice(0, 8).map((x) => x.name).join(", ")}${schemas.length > 8 ? ", and more" : ""})` : ""}.`);
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
// The service puts its error code in brackets in front; a person needs the words.
|
|
126
|
+
lines.push(`It does not work yet: ${(error instanceof Error ? error.message : String(error)).replace(/^\[\w+\]\s*/, "")}`);
|
|
127
|
+
lines.push("What to check, in this order: (1) the connection string in the plugin's settings, typed there and never into this conversation; (2) that this computer can reach the database's host, which often needs a VPN; (3) that the first start has had a minute, since the database's MCP server is downloaded the first time it runs. After changing a setting, start a new session.");
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
else if (!file && !problem) {
|
|
131
|
+
lines.push("This server draws inline views from a database it connects to itself, which is the advanced route. For a page over the person's own database with nothing to set up here, use the artifact-pages skill: it reads through a connector they already have. To connect this server all the same, the plugin's README lists the three settings.");
|
|
132
|
+
}
|
|
133
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
134
|
+
});
|
|
135
|
+
server.registerTool("timing_report", {
|
|
136
|
+
title: "How long views took to load",
|
|
137
|
+
description: "Says how long the views this server drew took to get their data, and how much of that was the database and how much this server added. Numbers only: no query, table name or value. Call it when someone asks whether Surfaces is slow, or to compare it with querying the database directly.",
|
|
138
|
+
inputSchema: {},
|
|
139
|
+
annotations: { readOnlyHint: true, destructiveHint: false },
|
|
140
|
+
}, async () => ({ content: [{ type: "text", text: timing.report() }] }));
|
|
39
141
|
await server.connect(new StdioServerTransport());
|
|
40
|
-
say(`Surfaces MCP server ready (${sources.map((s) => s.id).join(", ")}${file ? "" : fromEnv ? "; from this plugin's settings" : "; sample data, no config found"}).`);
|
|
142
|
+
say(`Surfaces MCP server ready (${sources.map((s) => s.id).join(", ")}${file ? "" : fromEnv ? "; from this plugin's settings" : problem ? "; sample data, because the settings could not be used" : "; sample data, no config found"}).`);
|
|
143
|
+
if (problem)
|
|
144
|
+
say(problem);
|
|
41
145
|
const stop = () => void backend.close().then(() => process.exit(0));
|
|
42
146
|
process.on("SIGINT", stop);
|
|
43
147
|
process.on("SIGTERM", stop);
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AACzD,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAC1E,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,oBAAoB,EAAE,UAAU,EAAE,WAAW,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAC7J,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAC1D,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnD,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,C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AW,EAAE,CAAC,CAAC;QACrL,MAAM,MAAM,CAAC,OAAO,CAAC,IAAI,oBAAoB,EAAE,CAAC,CAAC;QACjD,GAAG,CAAC,8BAA8B,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,+BAA+B,CAAC,CAAC,CAAC,gCAAgC,IAAI,CAAC,CAAC;QACtK,MAAM,IAAI,GAAG,GAAG,EAAE,CAAC,KAAK,OAAO,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACpE,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QAC3B,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC;AAAC,OAAO,KAAK,EAAE,CAAC;IACf,GAAG,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IAC5D,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC","sourcesContent":["#!/usr/bin/env node\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { McpServer } from \"@modelcontextprotocol/server\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/server/stdio\";\nimport { CONFIG_FILES, configFromEnv, findConfig, createSurfacesServer, loadConfig, loadEnvFile, openSources, serverOptions } from \"@surfaces-ui/dev-server\";\nimport { installMcpServer, readAppHtml } from \"./node.js\";\nimport { registerSurfacesApps } from \"./server.js\";\n\nconst args = process.argv.slice(2);\nconst flag = (name: string) => {\n const at = args.indexOf(name);\n return at === -1 ? undefined : args[at + 1];\n};\n// stdout carries the MCP protocol, so everything a person should read goes to stderr.\nconst say = (text: string) => process.stderr.write(`${text}\\n`);\n\ntry {\n if (args[0] === \"install\") {\n const dir = flag(\"--dir\") ?? process.cwd();\n const config = flag(\"--config\") ?? CONFIG_FILES.find((f) => fs.existsSync(path.resolve(dir, f)));\n const { file, replaced } = installMcpServer({ dir, config, name: flag(\"--name\") });\n say(`${replaced ? \"Updated\" : \"Added\"} the Surfaces server in ${file}.`);\n if (!config) say(`No config found in ${dir}. Create ${CONFIG_FILES[0]} with your data sources before starting the server.`);\n } else {\n // A project's config in the working directory, or a person's own in ~/.surfaces, for a host with no project folder.\n const file = flag(\"--config\") ?? findConfig();\n // Secrets (a warehouse's host and password, a model key) come from the git-ignored .env.local beside the config, as on the dev server.\n const secrets = loadEnvFile(path.dirname(path.resolve(file ?? CONFIG_FILES[0]!)));\n if (secrets.names.length > 0) say(`Read ${secrets.names.join(\", \")} from ${secrets.file}.`);\n // With no config file, a source named in the environment (a plugin's settings); with neither, the six sample industry models.\n const fromEnv = file ? undefined : configFromEnv();\n const { config, dir } = file ? await loadConfig(file) : { config: fromEnv ?? { seeds: true }, dir: process.cwd() };\n const sources = await openSources(config, dir);\n const backend = await createSurfacesServer(await serverOptions(config, sources, dir));\n const server = new McpServer({ name: \"surfaces\", version: \"0.0.0\" });\n registerSurfacesApps(server, { dataSource: backend.dataSource, discovery: backend.discovery, ...(backend.pipelines ? { pipelines: backend.pipelines } : {}), appHtml: readAppHtml });\n await server.connect(new StdioServerTransport());\n say(`Surfaces MCP server ready (${sources.map((s) => s.id).join(\", \")}${file ? \"\" : fromEnv ? \"; from this plugin's settings\" : \"; sample data, no config found\"}).`);\n const stop = () => void backend.close().then(() => process.exit(0));\n process.on(\"SIGINT\", stop);\n process.on(\"SIGTERM\", stop);\n }\n} catch (error) {\n say(error instanceof Error ? error.message : String(error));\n process.exit(1);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"cli.js","sourceRoot":"","sources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E,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,+BAA+B,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,uDAAuD,CAAC,CAAC,CAAC,gCAAgC,IAAI,CAAC,CAAC;QAC1O,IAAI,OAAO;YAAE,GAAG,CAAC,OAAO,CAAC,CAAC;QAC1B,MAAM,IAAI,GAAG,GAAG,EAAE,CAAC,KAAK,OAAO,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACpE,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QAC3B,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC;AAAC,OAAO,KAAK,EAAE,CAAC;IACf,GAAG,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IAC5D,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC","sourcesContent":["#!/usr/bin/env node\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { McpServer } from \"@modelcontextprotocol/server\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/server/stdio\";\nimport readline from \"node:readline\";\nimport { CONFIG_FILES, configFromEnv, findConfig, findProgram, createSurfacesServer, loadConfig, loadEnvFile, openSources, serverOptions } from \"@surfaces-ui/dev-server\";\nimport { installMcpServer, readAppHtml } from \"./node.js\";\nimport { registerSurfacesApps } from \"./server.js\";\nimport { desktopConfigFile, runSetup } from \"./setup.js\";\nimport { createTiming } from \"./timing.js\";\n\nconst args = process.argv.slice(2);\nconst flag = (name: string) => {\n const at = args.indexOf(name);\n return at === -1 ? undefined : args[at + 1];\n};\n// stdout carries the MCP protocol, so everything a person should read goes to stderr.\nconst say = (text: string) => process.stderr.write(`${text}\\n`);\n\ntry {\n if (args[0] === \"install\") {\n const dir = flag(\"--dir\") ?? process.cwd();\n const config = flag(\"--config\") ?? CONFIG_FILES.find((f) => fs.existsSync(path.resolve(dir, f)));\n const { file, replaced } = installMcpServer({ dir, config, name: flag(\"--name\") });\n say(`${replaced ? \"Updated\" : \"Added\"} the Surfaces server in ${file}.`);\n if (!config) say(`No config found in ${dir}. Create ${CONFIG_FILES[0]} with your data sources before starting the server.`);\n } else if (args[0] === \"setup\") {\n // Sets the Claude desktop app up to start this server over a database the person already has there.\n const version = (JSON.parse(fs.readFileSync(new URL(\"../package.json\", import.meta.url), \"utf8\")) as { version: string }).version;\n const lines = readline.createInterface({ input: process.stdin, output: process.stderr, terminal: process.stdin.isTTY === true });\n let hidden = false;\n // What is typed for a connection string is not echoed.\n const output = lines as unknown as { _writeToOutput(text: string): void };\n const write = output._writeToOutput.bind(lines);\n output._writeToOutput = (text) => {\n if (!hidden) write(text);\n };\n const ask = (question: string) => new Promise<string>((resolve) => lines.question(question, resolve));\n try {\n await runSetup({\n file: flag(\"--file\") ?? desktopConfigFile(),\n version,\n findProgram,\n use: flag(\"--use\"),\n dialect: flag(\"--dialect\"),\n sample: args.includes(\"--sample\"),\n terminal: {\n say,\n ask,\n askHidden: async (question) => {\n process.stderr.write(question);\n hidden = true;\n try {\n return await ask(\"\");\n } finally {\n hidden = false;\n process.stderr.write(\"\\n\");\n }\n },\n },\n });\n } finally {\n lines.close();\n }\n } else {\n // A project's config in the working directory, or a person's own in ~/.surfaces, for a host with no project folder.\n const file = flag(\"--config\") ?? findConfig();\n // Secrets (a warehouse's host and password, a model key) come from the git-ignored .env.local beside the config, as on the dev server.\n const secrets = loadEnvFile(path.dirname(path.resolve(file ?? CONFIG_FILES[0]!)));\n if (secrets.names.length > 0) say(`Read ${secrets.names.join(\", \")} from ${secrets.file}.`);\n // With no config file, a source named in the environment (a plugin's settings); with neither, the six sample industry models.\n // Settings that cannot be used (a launcher that is not installed, a database type with no server named) do not stop\n // the server: it starts on the sample data and says what is wrong through `check_setup`, where a person can act on it.\n let fromEnv: ReturnType<typeof configFromEnv>;\n let problem: string | undefined;\n if (!file) {\n try {\n fromEnv = configFromEnv();\n } catch (error) {\n problem = error instanceof Error ? error.message : String(error);\n }\n }\n const { config, dir } = file ? await loadConfig(file) : { config: fromEnv ?? { seeds: true }, dir: process.cwd() };\n const sources = await openSources(config, dir);\n const backend = await createSurfacesServer(await serverOptions(config, sources, dir));\n const server = new McpServer({ name: \"surfaces\", version: \"0.0.0\" });\n const timing = createTiming();\n registerSurfacesApps(server, { around: timing.around, dataSource: backend.dataSource, discovery: backend.discovery, ...(backend.pipelines ? { pipelines: backend.pipelines } : {}), appHtml: readAppHtml });\n const set = (name: string) => {\n const value = process.env[name]?.trim() ?? \"\";\n return value !== \"\" && !value.startsWith(\"${\") && !/^(none|sample data)$/i.test(value);\n };\n server.registerTool(\n \"check_setup\",\n {\n title: \"Check the data setup\",\n description:\n \"Says where this server's data comes from (the person's own database, a config file, or the built-in sample data), whether it can be reached right now, and what to do if not. Call it first when a data tool fails, when someone asks to connect their database, or when only sample data shows and they expected their own. It reads settings and runs one harmless listing; it never shows a password.\",\n inputSchema: {},\n annotations: { readOnlyHint: true, destructiveHint: false },\n },\n async () => {\n const lines: string[] = [];\n const own = fromEnv?.sources?.[0];\n if (file) lines.push(`Data comes from the config file ${file}: ${sources.map((s) => s.id).join(\", \")}.`);\n else if (own && own.engine === \"mcp\") lines.push(`Data comes from the person's ${own.dialect} database, set in this plugin's settings, through ${\"url\" in own.server ? \"a remote MCP server\" : `the MCP server started by ${path.basename(own.server.command)}`}.`);\n else lines.push(\"Data is the built-in sample data (retail, healthcare, fraud, telco, transportation, manufacturing). No database is set up.\");\n if (problem) lines.push(`The settings could not be used, so the sample data is shown instead: ${problem}`);\n if (!file) {\n lines.push(`Settings filled in: database type ${set(\"SURFACES_SOURCE_DIALECT\") ? \"yes\" : \"no\"}, the database's MCP server ${set(\"SURFACES_SOURCE_SERVER\") ? \"yes\" : \"no\"}, connection string or token ${set(\"SURFACES_SOURCE_SECRET\") ? \"yes\" : \"no\"}.`);\n }\n if (own) {\n try {\n const { schemas } = await backend.dataSource.listSchemas({ sourceId: own.id, catalog: \"\" });\n lines.push(`It works: the database answered, and ${schemas.length} ${schemas.length === 1 ? \"database is\" : \"databases are\"} visible${schemas.length > 0 ? ` (${schemas.slice(0, 8).map((x) => x.name).join(\", \")}${schemas.length > 8 ? \", and more\" : \"\"})` : \"\"}.`);\n } catch (error) {\n // The service puts its error code in brackets in front; a person needs the words.\n lines.push(`It does not work yet: ${(error instanceof Error ? error.message : String(error)).replace(/^\\[\\w+\\]\\s*/, \"\")}`);\n lines.push(\n \"What to check, in this order: (1) the connection string in the plugin's settings, typed there and never into this conversation; (2) that this computer can reach the database's host, which often needs a VPN; (3) that the first start has had a minute, since the database's MCP server is downloaded the first time it runs. After changing a setting, start a new session.\",\n );\n }\n } else if (!file && !problem) {\n lines.push(\n\"This server draws inline views from a database it connects to itself, which is the advanced route. For a page over the person's own database with nothing to set up here, use the artifact-pages skill: it reads through a connector they already have. To connect this server all the same, the plugin's README lists the three settings.\",\n );\n }\n return { content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }] };\n },\n );\n server.registerTool(\n \"timing_report\",\n {\n title: \"How long views took to load\",\n description:\n \"Says how long the views this server drew took to get their data, and how much of that was the database and how much this server added. Numbers only: no query, table name or value. Call it when someone asks whether Surfaces is slow, or to compare it with querying the database directly.\",\n inputSchema: {},\n annotations: { readOnlyHint: true, destructiveHint: false },\n },\n async () => ({ content: [{ type: \"text\" as const, text: timing.report() }] }),\n );\n await server.connect(new StdioServerTransport());\n say(`Surfaces MCP server ready (${sources.map((s) => s.id).join(\", \")}${file ? \"\" : fromEnv ? \"; from this plugin's settings\" : problem ? \"; sample data, because the settings could not be used\" : \"; sample data, no config found\"}).`);\n if (problem) say(problem);\n const stop = () => void backend.close().then(() => process.exit(0));\n process.on(\"SIGINT\", stop);\n process.on(\"SIGTERM\", stop);\n }\n} catch (error) {\n say(error instanceof Error ? error.message : String(error));\n process.exit(1);\n}\n"]}
|
package/dist/server.d.ts
CHANGED
|
@@ -24,6 +24,12 @@ export interface SurfacesAppsOptions {
|
|
|
24
24
|
catalog?: Catalog;
|
|
25
25
|
/** Most rows the app's data tool returns per request. Defaults to 1,000. */
|
|
26
26
|
maxRowsPerRequest?: number;
|
|
27
|
+
/**
|
|
28
|
+
* Wraps each request the app page makes for data, so a host can time it
|
|
29
|
+
* (`createTiming` in `@surfaces-ui/mcp/node`). It is given the method's
|
|
30
|
+
* name and must return what `run` returns.
|
|
31
|
+
*/
|
|
32
|
+
around?: <T>(method: string, run: () => Promise<T>) => Promise<T>;
|
|
27
33
|
}
|
|
28
34
|
/**
|
|
29
35
|
* Adds the Surfaces tools and app page to an MCP server.
|
package/dist/server.js
CHANGED
|
@@ -263,25 +263,28 @@ export function registerSurfacesApps(server, options) {
|
|
|
263
263
|
if (!isRpcMethod(method))
|
|
264
264
|
return failure(`Unknown method ${method}.`);
|
|
265
265
|
const shape = RPC[method];
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
const
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
messages
|
|
277
|
-
|
|
266
|
+
const around = options.around ?? ((_method, run) => run());
|
|
267
|
+
return around(method, async () => {
|
|
268
|
+
try {
|
|
269
|
+
// Requests arrive as protobuf JSON; decode them so enums, 64-bit numbers and oneofs are read correctly.
|
|
270
|
+
const decoded = fromJson(shape.request, request);
|
|
271
|
+
if (method === "execute") {
|
|
272
|
+
const execute = decoded;
|
|
273
|
+
execute.query ??= create(ViewQuerySchema);
|
|
274
|
+
execute.query.page ??= create(PagingSchema);
|
|
275
|
+
execute.query.page.limit = Math.min(execute.query.page.limit || maxRows, maxRows);
|
|
276
|
+
const messages = [];
|
|
277
|
+
for await (const part of dataSource.execute(execute))
|
|
278
|
+
messages.push(toJson(shape.response, part));
|
|
279
|
+
return { ...text(`${messages.length} messages`), structuredContent: { messages } };
|
|
280
|
+
}
|
|
281
|
+
const response = await dataSource[method](decoded);
|
|
282
|
+
return { ...text("ok"), structuredContent: { messages: [toJson(shape.response, response)] } };
|
|
278
283
|
}
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
return failure(message(error));
|
|
284
|
-
}
|
|
284
|
+
catch (error) {
|
|
285
|
+
return failure(message(error));
|
|
286
|
+
}
|
|
287
|
+
});
|
|
285
288
|
});
|
|
286
289
|
}
|
|
287
290
|
/** The agent's pipeline tools as MCP tools: one implementation, so the two cannot drift. */
|
package/dist/server.js.map
CHANGED
|
@@ -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,gJAAgJ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AAC","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\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 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: 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"]}
|
|
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,EAA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AE,CAAC;QAC7F,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;QACjC,CAAC;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"]}
|