@surfaces-ui/mcp 0.0.0-stage → 0.2.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/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { McpServer } from "@modelcontextprotocol/server";
5
+ import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
6
+ import { CONFIG_FILES, createSurfacesServer, loadConfig, loadEnvFile, openSources, serverOptions } from "@surfaces-ui/dev-server";
7
+ import { installMcpServer, readAppHtml } from "./node.js";
8
+ import { registerSurfacesApps } from "./server.js";
9
+ const args = process.argv.slice(2);
10
+ const flag = (name) => {
11
+ const at = args.indexOf(name);
12
+ return at === -1 ? undefined : args[at + 1];
13
+ };
14
+ // stdout carries the MCP protocol, so everything a person should read goes to stderr.
15
+ const say = (text) => process.stderr.write(`${text}\n`);
16
+ try {
17
+ if (args[0] === "install") {
18
+ const dir = flag("--dir") ?? process.cwd();
19
+ const config = flag("--config") ?? CONFIG_FILES.find((f) => fs.existsSync(path.resolve(dir, f)));
20
+ const { file, replaced } = installMcpServer({ dir, config, name: flag("--name") });
21
+ say(`${replaced ? "Updated" : "Added"} the Surfaces server in ${file}.`);
22
+ if (!config)
23
+ say(`No config found in ${dir}. Create ${CONFIG_FILES[0]} with your data sources before starting the server.`);
24
+ }
25
+ else {
26
+ const file = flag("--config") ?? CONFIG_FILES.find((f) => fs.existsSync(path.resolve(f)));
27
+ // 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.
28
+ const secrets = loadEnvFile(path.dirname(path.resolve(file ?? CONFIG_FILES[0])));
29
+ if (secrets.names.length > 0)
30
+ say(`Read ${secrets.names.join(", ")} from ${secrets.file}.`);
31
+ // With no config, serve the six sample industry models.
32
+ const { config, dir } = file ? await loadConfig(file) : { config: { seeds: true }, dir: process.cwd() };
33
+ const sources = await openSources(config, dir);
34
+ const backend = await createSurfacesServer(await serverOptions(config, sources, dir));
35
+ const server = new McpServer({ name: "surfaces", version: "0.0.0" });
36
+ registerSurfacesApps(server, { dataSource: backend.dataSource, discovery: backend.discovery, ...(backend.pipelines ? { pipelines: backend.pipelines } : {}), appHtml: readAppHtml });
37
+ await server.connect(new StdioServerTransport());
38
+ say(`Surfaces MCP server ready (${sources.map((s) => s.id).join(", ")}${file ? "" : "; sample data, no config found"}).`);
39
+ const stop = () => void backend.close().then(() => process.exit(0));
40
+ process.on("SIGINT", stop);
41
+ process.on("SIGTERM", stop);
42
+ }
43
+ }
44
+ catch (error) {
45
+ say(error instanceof Error ? error.message : String(error));
46
+ process.exit(1);
47
+ }
48
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +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,oBAAoB,EAAE,UAAU,EAAE,WAAW,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAClI,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,CAAC,CAAC,CAAC;AACnC,MAAM,IAAI,GAAG,CAAC,IAAY,EAAE,EAAE;IAC5B,MAAM,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9B,OAAO,EAAE,KA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,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,gCAAgC,IAAI,CAAC,CAAC;QAC1H,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, 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 const file = flag(\"--config\") ?? CONFIG_FILES.find((f) => fs.existsSync(path.resolve(f)));\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, serve the six sample industry models.\n const { config, dir } = file ? await loadConfig(file) : { config: { 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 ? \"\" : \"; 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"]}
@@ -0,0 +1,40 @@
1
+ import type { Transport } from "@modelcontextprotocol/client";
2
+ import type { AgentConnector, RunnableTool } from "@surfaces-ui/agent";
3
+ export interface McpConnectorOptions {
4
+ /** The connector's id in a chat's Connectors menu, e.g. "github". Tool names start with it. */
5
+ id: string;
6
+ name: string;
7
+ description?: string;
8
+ /** How to reach the server: stdio (`stdioTransport` in `@surfaces-ui/mcp/node`) or Streamable HTTP. Opened once, when first connected. */
9
+ transport(): Transport | Promise<Transport>;
10
+ /** Ask a person before every tool, not only the ones that may change things. */
11
+ approveAll?: boolean;
12
+ /** Give up connecting after this long. Default 10 seconds. */
13
+ timeoutMs?: number;
14
+ }
15
+ export interface McpConnection {
16
+ /** For `AgentOffer.connectors`: unavailable, with the reason, when the server could not be reached. */
17
+ connector: AgentConnector;
18
+ /** For `toolCallingAgent`'s `tools`. Empty when the server could not be reached. */
19
+ tools: RunnableTool[];
20
+ close(): Promise<void>;
21
+ }
22
+ /**
23
+ * An MCP server's tools as one connector an agent can be given. The server's
24
+ * tools become runnable tools named `<id>__<tool>`; one the server does not
25
+ * mark read-only (`readOnlyHint`) asks a person before it runs, and so does
26
+ * every tool with `approveAll`. Nothing here holds a credential: the
27
+ * transport carries whatever the host gave it. A server that cannot be
28
+ * reached gives a connector marked unavailable with the reason, and no tools,
29
+ * so the agent still starts.
30
+ */
31
+ export declare function mcpConnector(options: McpConnectorOptions): Promise<McpConnection>;
32
+ /**
33
+ * A server over Streamable HTTP. `token` is called per connection and its
34
+ * value sent as a bearer token; the host reads it from its own environment
35
+ * or vault, never from config.
36
+ */
37
+ export declare function httpTransport(url: string, options?: {
38
+ token?(): string | undefined;
39
+ headers?: Record<string, string>;
40
+ }): () => Transport;
@@ -0,0 +1,80 @@
1
+ import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
2
+ import { ApprovalRisk } from "@surfaces-ui/proto";
3
+ /** A tool name a model accepts: letters, digits, `_` and `-`, at most 64 characters. */
4
+ const toolName = (id, name) => `${id}__${name}`.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64);
5
+ const textOf = (content) => (Array.isArray(content) ? content : [])
6
+ .map((c) => (c.type === "text" ? (c.text ?? "") : `[${c.type}]`))
7
+ .join("\n")
8
+ .trim();
9
+ /**
10
+ * An MCP server's tools as one connector an agent can be given. The server's
11
+ * tools become runnable tools named `<id>__<tool>`; one the server does not
12
+ * mark read-only (`readOnlyHint`) asks a person before it runs, and so does
13
+ * every tool with `approveAll`. Nothing here holds a credential: the
14
+ * transport carries whatever the host gave it. A server that cannot be
15
+ * reached gives a connector marked unavailable with the reason, and no tools,
16
+ * so the agent still starts.
17
+ */
18
+ export async function mcpConnector(options) {
19
+ const base = { id: options.id, name: options.name, ...(options.description ? { description: options.description } : {}) };
20
+ const client = new Client({ name: "surfaces-agent", version: "0" });
21
+ try {
22
+ const transport = await options.transport();
23
+ const timeout = options.timeoutMs ?? 10_000;
24
+ await Promise.race([client.connect(transport), new Promise((_, reject) => setTimeout(() => reject(new Error(`no answer within ${timeout / 1000} seconds`)), timeout))]);
25
+ // A tool an MCP App keeps for its own page (`visibility` without "model") is not offered to a model.
26
+ const forModel = (tool) => {
27
+ const visibility = tool._meta?.ui?.visibility;
28
+ return !visibility || visibility.includes("model");
29
+ };
30
+ const listed = (await client.listTools()).tools.filter(forModel);
31
+ const asks = (readOnly) => options.approveAll || readOnly !== true;
32
+ const tools = listed.map((tool) => {
33
+ const name = toolName(options.id, tool.name);
34
+ const label = tool.annotations?.title || tool.title || tool.name;
35
+ return {
36
+ name,
37
+ description: `${tool.description ?? label} (from ${options.name})`,
38
+ inputSchema: (tool.inputSchema ?? { type: "object" }),
39
+ ...(asks(tool.annotations?.readOnlyHint)
40
+ ? {
41
+ approval: (input) => ({
42
+ title: `${label} in ${options.name}`,
43
+ detail: tool.annotations?.destructiveHint === false ? `${options.name} may change something; nothing is removed.` : `${options.name} may change or remove something. Check what it is sent before allowing it.`,
44
+ subject: { tool: tool.name, arguments: (input ?? {}) },
45
+ risk: tool.annotations?.destructiveHint === false ? ApprovalRisk.LOW : ApprovalRisk.HIGH,
46
+ basis: options.name,
47
+ }),
48
+ }
49
+ : {}),
50
+ run: async (input, signal, approved) => {
51
+ // A tool that asked runs only what the person allowed.
52
+ const args = approved ? (approved.subject.arguments ?? {}) : (input ?? {});
53
+ const result = await client.callTool({ name: tool.name, arguments: args }, { signal });
54
+ const text = textOf(result.content);
55
+ if (result.isError)
56
+ throw new Error(text || `${options.name} reported an error.`);
57
+ return result.structuredContent ?? text;
58
+ },
59
+ };
60
+ });
61
+ return { connector: { ...base, tools: tools.map((t) => t.name), requiresApproval: tools.some((t) => t.approval) }, tools, close: () => client.close() };
62
+ }
63
+ catch (error) {
64
+ await client.close().catch(() => { });
65
+ const reason = error instanceof Error ? error.message : String(error);
66
+ return { connector: { ...base, tools: [], status: "unavailable", reason: `Could not reach ${options.name}: ${reason}` }, tools: [], close: async () => { } };
67
+ }
68
+ }
69
+ /**
70
+ * A server over Streamable HTTP. `token` is called per connection and its
71
+ * value sent as a bearer token; the host reads it from its own environment
72
+ * or vault, never from config.
73
+ */
74
+ export function httpTransport(url, options = {}) {
75
+ return () => {
76
+ const token = options.token?.();
77
+ return new StreamableHTTPClientTransport(new URL(url), { requestInit: { headers: { ...options.headers, ...(token ? { Authorization: `Bearer ${token}` } : {}) } } });
78
+ };
79
+ }
80
+ //# sourceMappingURL=connector.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connector.js","sourceRoot":"","sources":["../src/connector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,6BAA6B,EAAE,MAAM,8BAA8B,CAAC;AAGrF,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAuBlD,wFAAwF;AACxF,MAAM,QAAQ,GAAG,CAAC,EAAU,EAAE,IAAY,EAAE,EAAE,CAAC,GAAG,EAAE,KAAK,IAAI,EAAE,CAAC,OAAO,CAAC,iBAAiB,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAG7G,MAAM,MAAM,GAAG,CAAC,OAAgB,EAAE,EAAE,CAClC,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAE,OAAyB,CAAC,CAAC,CAAC,EAAE,CAAC;KACvD,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,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AE,GAAE,CAAC,CAAC,CAAC;QACrC,MAAM,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACtE,OAAO,EAAE,SAAS,EAAE,EAAE,GAAG,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,mBAAmB,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,IAAI,EAAE,GAAE,CAAC,EAAE,CAAC;IAC9J,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,GAAW,EAAE,OAAO,GAAuE,EAAE;IACzH,OAAO,GAAG,EAAE;QACV,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC;QAChC,OAAO,IAAI,6BAA6B,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,EAAE,EAAE,WAAW,EAAE,EAAE,OAAO,EAAE,EAAE,GAAG,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,UAAU,KAAK,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IACvK,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { Client, StreamableHTTPClientTransport } from \"@modelcontextprotocol/client\";\nimport type { Transport } from \"@modelcontextprotocol/client\";\nimport type { AgentConnector, RunnableTool } from \"@surfaces-ui/agent\";\nimport { ApprovalRisk } from \"@surfaces-ui/proto\";\n\nexport interface McpConnectorOptions {\n /** The connector's id in a chat's Connectors menu, e.g. \"github\". Tool names start with it. */\n id: string;\n name: string;\n description?: string;\n /** How to reach the server: stdio (`stdioTransport` in `@surfaces-ui/mcp/node`) or Streamable HTTP. Opened once, when first connected. */\n transport(): Transport | Promise<Transport>;\n /** Ask a person before every tool, not only the ones that may change things. */\n approveAll?: boolean;\n /** Give up connecting after this long. Default 10 seconds. */\n timeoutMs?: number;\n}\n\nexport interface McpConnection {\n /** For `AgentOffer.connectors`: unavailable, with the reason, when the server could not be reached. */\n connector: AgentConnector;\n /** For `toolCallingAgent`'s `tools`. Empty when the server could not be reached. */\n tools: RunnableTool[];\n close(): Promise<void>;\n}\n\n/** A tool name a model accepts: letters, digits, `_` and `-`, at most 64 characters. */\nconst toolName = (id: string, name: string) => `${id}__${name}`.replace(/[^A-Za-z0-9_-]/g, \"_\").slice(0, 64);\n\ntype ToolContent = { type: string; text?: string };\nconst textOf = (content: unknown) =>\n (Array.isArray(content) ? (content as ToolContent[]) : [])\n .map((c) => (c.type === \"text\" ? (c.text ?? \"\") : `[${c.type}]`))\n .join(\"\\n\")\n .trim();\n\n/**\n * An MCP server's tools as one connector an agent can be given. The server's\n * tools become runnable tools named `<id>__<tool>`; one the server does not\n * mark read-only (`readOnlyHint`) asks a person before it runs, and so does\n * every tool with `approveAll`. Nothing here holds a credential: the\n * transport carries whatever the host gave it. A server that cannot be\n * reached gives a connector marked unavailable with the reason, and no tools,\n * so the agent still starts.\n */\nexport async function mcpConnector(options: McpConnectorOptions): Promise<McpConnection> {\n const base = { id: options.id, name: options.name, ...(options.description ? { description: options.description } : {}) };\n const client = new Client({ name: \"surfaces-agent\", version: \"0\" });\n try {\n const transport = await options.transport();\n const timeout = options.timeoutMs ?? 10_000;\n await Promise.race([client.connect(transport), new Promise((_, reject) => setTimeout(() => reject(new Error(`no answer within ${timeout / 1000} seconds`)), timeout))]);\n // A tool an MCP App keeps for its own page (`visibility` without \"model\") is not offered to a model.\n const forModel = (tool: { _meta?: Record<string, unknown> }) => {\n const visibility = (tool._meta?.ui as { visibility?: string[] } | undefined)?.visibility;\n return !visibility || visibility.includes(\"model\");\n };\n const listed = (await client.listTools()).tools.filter(forModel);\n const asks = (readOnly: boolean | undefined) => options.approveAll || readOnly !== true;\n const tools: RunnableTool[] = listed.map((tool) => {\n const name = toolName(options.id, tool.name);\n const label = tool.annotations?.title || tool.title || tool.name;\n return {\n name,\n description: `${tool.description ?? label} (from ${options.name})`,\n inputSchema: (tool.inputSchema ?? { type: \"object\" }) as Record<string, unknown>,\n ...(asks(tool.annotations?.readOnlyHint)\n ? {\n approval: (input: unknown) => ({\n title: `${label} in ${options.name}`,\n detail: tool.annotations?.destructiveHint === false ? `${options.name} may change something; nothing is removed.` : `${options.name} may change or remove something. Check what it is sent before allowing it.`,\n subject: { tool: tool.name, arguments: (input ?? {}) as Record<string, never> },\n risk: tool.annotations?.destructiveHint === false ? ApprovalRisk.LOW : ApprovalRisk.HIGH,\n basis: options.name,\n }),\n }\n : {}),\n run: async (input, signal, approved) => {\n // A tool that asked runs only what the person allowed.\n const args = approved ? ((approved.subject as { arguments?: Record<string, unknown> }).arguments ?? {}) : ((input ?? {}) as Record<string, unknown>);\n const result = await client.callTool({ name: tool.name, arguments: args }, { signal });\n const text = textOf(result.content);\n if (result.isError) throw new Error(text || `${options.name} reported an error.`);\n return result.structuredContent ?? text;\n },\n };\n });\n return { connector: { ...base, tools: tools.map((t) => t.name), requiresApproval: tools.some((t) => t.approval) }, tools, close: () => client.close() };\n } catch (error) {\n await client.close().catch(() => {});\n const reason = error instanceof Error ? error.message : String(error);\n return { connector: { ...base, tools: [], status: \"unavailable\", reason: `Could not reach ${options.name}: ${reason}` }, tools: [], close: async () => {} };\n }\n}\n\n/**\n * A server over Streamable HTTP. `token` is called per connection and its\n * value sent as a bearer token; the host reads it from its own environment\n * or vault, never from config.\n */\nexport function httpTransport(url: string, options: { token?(): string | undefined; headers?: Record<string, string> } = {}): () => Transport {\n return () => {\n const token = options.token?.();\n return new StreamableHTTPClientTransport(new URL(url), { requestInit: { headers: { ...options.headers, ...(token ? { Authorization: `Bearer ${token}` } : {}) } } });\n };\n}\n"]}
@@ -0,0 +1,3 @@
1
+ export * from "./protocol.js";
2
+ export * from "./server.js";
3
+ export * from "./connector.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./protocol.js";
2
+ export * from "./server.js";
3
+ export * from "./connector.js";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,cAAc,aAAa,CAAC;AAC5B,cAAc,gBAAgB,CAAC","sourcesContent":["export * from \"./protocol.js\";\nexport * from \"./server.js\";\nexport * from \"./connector.js\";\n"]}
package/dist/node.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ import type { Transport } from "@modelcontextprotocol/client";
2
+ /** Reads the built single-file app page that ships with this package. */
3
+ export declare function readAppHtml(): string;
4
+ export interface InstallOptions {
5
+ /** Repository to install into. */
6
+ dir: string;
7
+ /** Config file the server should load, relative to `dir`. */
8
+ config?: string;
9
+ /** Name of the server entry. Defaults to "surfaces". */
10
+ name?: string;
11
+ }
12
+ /**
13
+ * Adds the Surfaces MCP server to a repository's `.mcp.json`, keeping any
14
+ * servers already listed there. Returns the file path and whether an
15
+ * existing entry was replaced.
16
+ */
17
+ export declare function installMcpServer(options: InstallOptions): {
18
+ file: string;
19
+ replaced: boolean;
20
+ };
21
+ /**
22
+ * A server started as a local program over stdio. Only the environment
23
+ * variables named in `env` are passed on, read from this process; nothing
24
+ * else of the server's environment reaches it.
25
+ */
26
+ export declare function stdioTransport(command: string, args?: string[], options?: {
27
+ env?: string[];
28
+ cwd?: string;
29
+ }): () => Transport;
package/dist/node.js ADDED
@@ -0,0 +1,56 @@
1
+ import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ /** Reads the built single-file app page that ships with this package. */
6
+ export function readAppHtml() {
7
+ const file = path.join(path.dirname(fileURLToPath(import.meta.url)), "app.html");
8
+ if (!fs.existsSync(file))
9
+ throw new Error("The Surfaces app page has not been built. Run the @surfaces-ui/mcp build.");
10
+ return fs.readFileSync(file, "utf8");
11
+ }
12
+ /**
13
+ * Adds the Surfaces MCP server to a repository's `.mcp.json`, keeping any
14
+ * servers already listed there. Returns the file path and whether an
15
+ * existing entry was replaced.
16
+ */
17
+ export function installMcpServer(options) {
18
+ const file = path.join(path.resolve(options.dir), ".mcp.json");
19
+ const name = options.name ?? "surfaces";
20
+ let current = {};
21
+ if (fs.existsSync(file)) {
22
+ try {
23
+ current = JSON.parse(fs.readFileSync(file, "utf8"));
24
+ }
25
+ catch {
26
+ throw new Error(`${file} is not valid JSON. Fix or remove it, then run install again.`);
27
+ }
28
+ if (current === null || typeof current !== "object" || Array.isArray(current))
29
+ throw new Error(`${file} must contain a JSON object.`);
30
+ }
31
+ const servers = current.mcpServers ?? {};
32
+ const replaced = Object.hasOwn(servers, name);
33
+ const next = {
34
+ ...current,
35
+ mcpServers: { ...servers, [name]: { command: "npx", args: ["-y", "@surfaces-ui/mcp", "--config", options.config ?? "surfaces.config.ts"] } },
36
+ };
37
+ fs.writeFileSync(file, `${JSON.stringify(next, null, 2)}\n`);
38
+ return { file, replaced };
39
+ }
40
+ /**
41
+ * A server started as a local program over stdio. Only the environment
42
+ * variables named in `env` are passed on, read from this process; nothing
43
+ * else of the server's environment reaches it.
44
+ */
45
+ export function stdioTransport(command, args = [], options = {}) {
46
+ return () => {
47
+ const env = { PATH: process.env.PATH ?? "" };
48
+ for (const name of options.env ?? []) {
49
+ const value = process.env[name];
50
+ if (value !== undefined)
51
+ env[name] = value;
52
+ }
53
+ return new StdioClientTransport({ command, args, env, ...(options.cwd ? { cwd: options.cwd } : {}) });
54
+ };
55
+ }
56
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.js","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAE1E,OAAO,EAAE,MAAM,SAAS,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,CAAC","sourcesContent":["import { StdioClientTransport } from \"@modelcontextprotocol/client/stdio\";\nimport type { Transport } from \"@modelcontextprotocol/client\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/** Reads the built single-file app page that ships with this package. */\nexport function readAppHtml(): string {\n const file = path.join(path.dirname(fileURLToPath(import.meta.url)), \"app.html\");\n if (!fs.existsSync(file)) throw new Error(\"The Surfaces app page has not been built. Run the @surfaces-ui/mcp build.\");\n return fs.readFileSync(file, \"utf8\");\n}\n\nexport interface InstallOptions {\n /** Repository to install into. */\n dir: string;\n /** Config file the server should load, relative to `dir`. */\n config?: string;\n /** Name of the server entry. Defaults to \"surfaces\". */\n name?: string;\n}\n\n/**\n * Adds the Surfaces MCP server to a repository's `.mcp.json`, keeping any\n * servers already listed there. Returns the file path and whether an\n * existing entry was replaced.\n */\nexport function installMcpServer(options: InstallOptions): { file: string; replaced: boolean } {\n const file = path.join(path.resolve(options.dir), \".mcp.json\");\n const name = options.name ?? \"surfaces\";\n let current: { mcpServers?: Record<string, unknown> } = {};\n if (fs.existsSync(file)) {\n try {\n current = JSON.parse(fs.readFileSync(file, \"utf8\")) as typeof current;\n } catch {\n throw new Error(`${file} is not valid JSON. Fix or remove it, then run install again.`);\n }\n if (current === null || typeof current !== \"object\" || Array.isArray(current)) throw new Error(`${file} must contain a JSON object.`);\n }\n const servers = current.mcpServers ?? {};\n const replaced = Object.hasOwn(servers, name);\n const next = {\n ...current,\n mcpServers: { ...servers, [name]: { command: \"npx\", args: [\"-y\", \"@surfaces-ui/mcp\", \"--config\", options.config ?? \"surfaces.config.ts\"] } },\n };\n fs.writeFileSync(file, `${JSON.stringify(next, null, 2)}\\n`);\n return { file, replaced };\n}\n\n/**\n * A server started as a local program over stdio. Only the environment\n * variables named in `env` are passed on, read from this process; nothing\n * else of the server's environment reaches it.\n */\nexport function stdioTransport(command: string, args: string[] = [], options: { env?: string[]; cwd?: string } = {}): () => Transport {\n return () => {\n const env: Record<string, string> = { PATH: process.env.PATH ?? \"\" };\n for (const name of options.env ?? []) {\n const value = process.env[name];\n if (value !== undefined) env[name] = value;\n }\n return new StdioClientTransport({ command, args, env, ...(options.cwd ? { cwd: options.cwd } : {}) });\n };\n}\n"]}
@@ -0,0 +1,103 @@
1
+ import { type DescMessage } from "@bufbuild/protobuf";
2
+ import type { DataSource, Pipelines } from "@surfaces-ui/data";
3
+ /** URI of the single app page every Surfaces tool renders into. */
4
+ export declare const APP_RESOURCE_URI = "ui://surfaces/app.html";
5
+ /** The tool the app page uses to reach data. Hidden from the model. */
6
+ export declare const RPC_TOOL = "surfaces_rpc";
7
+ /**
8
+ * The tool the app page uses to reach pipelines. Hidden from the model, and
9
+ * kept apart from the data channel because it can change things: a save the
10
+ * person approved in the page, and a run the person started there.
11
+ */
12
+ export declare const PIPELINE_RPC_TOOL = "surfaces_pipeline_rpc";
13
+ /** What a UI tool tells the app to show. Travels as the tool result's structured content. */
14
+ export type AppView = {
15
+ view: "grid";
16
+ sourceId: string;
17
+ sql: string;
18
+ title?: string;
19
+ } | {
20
+ view: "chart";
21
+ sourceId: string;
22
+ sql: string;
23
+ title?: string;
24
+ type: string;
25
+ x: string;
26
+ y: unknown[];
27
+ splitBy?: string;
28
+ xGrain?: string;
29
+ xBins?: number;
30
+ stacked?: boolean;
31
+ legend?: string;
32
+ } | {
33
+ view: "pivot";
34
+ sourceId: string;
35
+ sql: string;
36
+ title?: string;
37
+ rows: unknown[];
38
+ columns?: unknown[];
39
+ measures: unknown[];
40
+ } | {
41
+ view: "result";
42
+ sourceId: string;
43
+ sql: string;
44
+ title?: string;
45
+ } | {
46
+ view: "editor";
47
+ sourceId: string;
48
+ sql: string;
49
+ } | {
50
+ view: "schema";
51
+ sourceId: string;
52
+ } | {
53
+ view: "surface";
54
+ messages: unknown[];
55
+ }
56
+ /** Both draw their own heading, so they carry no title. */
57
+ | {
58
+ view: "pipeline";
59
+ pipelineId: string;
60
+ sourceId: string;
61
+ } | {
62
+ view: "datasetReview";
63
+ /** The proposed pipeline, as PipelineDraft protobuf JSON, filled in by the server. */
64
+ pipeline: unknown;
65
+ dataset: string;
66
+ expectedVersion: number;
67
+ digest: string;
68
+ sourceId: string;
69
+ proposedBy?: string;
70
+ };
71
+ export type RpcMethod = Exclude<keyof DataSource, never>;
72
+ /** Request and response message types for each DataSource method, used to carry them as JSON. */
73
+ export declare const RPC: Record<RpcMethod, {
74
+ request: DescMessage;
75
+ response: DescMessage;
76
+ stream?: boolean;
77
+ }>;
78
+ export declare const isRpcMethod: (method: string) => method is RpcMethod;
79
+ /** Calls a tool and returns its structured content, or throws its error text. */
80
+ export type CallTool = (name: string, args: Record<string, unknown>) => Promise<{
81
+ structuredContent?: unknown;
82
+ content?: unknown;
83
+ isError?: boolean;
84
+ }>;
85
+ /**
86
+ * A DataSource whose calls travel as MCP tool calls. An MCP App page uses it
87
+ * to reach the server that showed it: rows still come back as Arrow, and the
88
+ * page still asks only for the window it is showing.
89
+ */
90
+ export declare function mcpDataSource(callTool: CallTool): DataSource;
91
+ export type PipelineRpcMethod = Exclude<keyof Pipelines, "inspectFiles">;
92
+ /** Request and response message types for the pipeline calls the app page may make. */
93
+ export declare const PIPELINE_RPC: Record<PipelineRpcMethod, {
94
+ request: DescMessage;
95
+ response: DescMessage;
96
+ }>;
97
+ export declare const isPipelineRpcMethod: (method: string) => method is PipelineRpcMethod;
98
+ /**
99
+ * A Pipelines backend whose calls travel as MCP tool calls, for the app page.
100
+ * The server decides what each call may do: it refuses a full refresh, and a
101
+ * save still needs the approver, the digest and the version it was made against.
102
+ */
103
+ export declare function mcpPipelines(callTool: CallTool): Pipelines;
@@ -0,0 +1,102 @@
1
+ import { create, fromJson, toJson } from "@bufbuild/protobuf";
2
+ import { CancelRunRequestSchema, CancelRunResponseSchema, GetPipelineRequestSchema, GetPipelineResponseSchema, GetRunRequestSchema, GetRunResponseSchema, ListPipelineVersionsRequestSchema, ListPipelineVersionsResponseSchema, ListPipelinesRequestSchema, ListPipelinesResponseSchema, ListRunsRequestSchema, ListRunsResponseSchema, SavePipelineRequestSchema, SavePipelineResponseSchema, StartRunRequestSchema, StartRunResponseSchema, CancelRequestSchema, CancelResponseSchema, CountRequestSchema, CountResponseSchema, DescribeTableRequestSchema, DescribeTableResponseSchema, ExecuteRequestSchema, ExecuteResponseSchema, ExplainRequestSchema, ExplainResponseSchema, ListCatalogsRequestSchema, ListCatalogsResponseSchema, ListSchemasRequestSchema, ListSchemasResponseSchema, ListSnapshotsRequestSchema, ListSnapshotsResponseSchema, ListSourcesRequestSchema, ListFilesRequestSchema, ListFilesResponseSchema, TestSourceRequestSchema, TestSourceResponseSchema, ListSourcesResponseSchema, ListTablesRequestSchema, ListTablesResponseSchema, } from "@surfaces-ui/proto";
3
+ /** URI of the single app page every Surfaces tool renders into. */
4
+ export const APP_RESOURCE_URI = "ui://surfaces/app.html";
5
+ /** The tool the app page uses to reach data. Hidden from the model. */
6
+ export const RPC_TOOL = "surfaces_rpc";
7
+ /**
8
+ * The tool the app page uses to reach pipelines. Hidden from the model, and
9
+ * kept apart from the data channel because it can change things: a save the
10
+ * person approved in the page, and a run the person started there.
11
+ */
12
+ export const PIPELINE_RPC_TOOL = "surfaces_pipeline_rpc";
13
+ /** Request and response message types for each DataSource method, used to carry them as JSON. */
14
+ export const RPC = {
15
+ execute: { request: ExecuteRequestSchema, response: ExecuteResponseSchema, stream: true },
16
+ count: { request: CountRequestSchema, response: CountResponseSchema },
17
+ explain: { request: ExplainRequestSchema, response: ExplainResponseSchema },
18
+ cancel: { request: CancelRequestSchema, response: CancelResponseSchema },
19
+ listSources: { request: ListSourcesRequestSchema, response: ListSourcesResponseSchema },
20
+ testSource: { request: TestSourceRequestSchema, response: TestSourceResponseSchema },
21
+ listFiles: { request: ListFilesRequestSchema, response: ListFilesResponseSchema },
22
+ listCatalogs: { request: ListCatalogsRequestSchema, response: ListCatalogsResponseSchema },
23
+ listSchemas: { request: ListSchemasRequestSchema, response: ListSchemasResponseSchema },
24
+ listTables: { request: ListTablesRequestSchema, response: ListTablesResponseSchema },
25
+ describeTable: { request: DescribeTableRequestSchema, response: DescribeTableResponseSchema },
26
+ listSnapshots: { request: ListSnapshotsRequestSchema, response: ListSnapshotsResponseSchema },
27
+ };
28
+ export const isRpcMethod = (method) => Object.hasOwn(RPC, method);
29
+ /**
30
+ * A DataSource whose calls travel as MCP tool calls. An MCP App page uses it
31
+ * to reach the server that showed it: rows still come back as Arrow, and the
32
+ * page still asks only for the window it is showing.
33
+ */
34
+ export function mcpDataSource(callTool) {
35
+ const call = async (method, init) => {
36
+ const shape = RPC[method];
37
+ const request = toJson(shape.request, create(shape.request, init));
38
+ const result = await callTool(RPC_TOOL, { method, request });
39
+ if (result.isError) {
40
+ const first = Array.isArray(result.content) ? result.content[0]?.text : undefined;
41
+ throw new Error(first ?? "The request failed.");
42
+ }
43
+ return (result.structuredContent?.messages ?? []);
44
+ };
45
+ const unary = (method) => async (init) => {
46
+ const [message] = await call(method, init);
47
+ return fromJson(RPC[method].response, message ?? {});
48
+ };
49
+ return {
50
+ async *execute(init) {
51
+ for (const message of await call("execute", init))
52
+ yield fromJson(ExecuteResponseSchema, message);
53
+ },
54
+ count: unary("count"),
55
+ explain: unary("explain"),
56
+ cancel: unary("cancel"),
57
+ listSources: unary("listSources"),
58
+ testSource: unary("testSource"),
59
+ listFiles: unary("listFiles"),
60
+ listCatalogs: unary("listCatalogs"),
61
+ listSchemas: unary("listSchemas"),
62
+ listTables: unary("listTables"),
63
+ describeTable: unary("describeTable"),
64
+ listSnapshots: unary("listSnapshots"),
65
+ };
66
+ }
67
+ /** Request and response message types for the pipeline calls the app page may make. */
68
+ export const PIPELINE_RPC = {
69
+ listPipelines: { request: ListPipelinesRequestSchema, response: ListPipelinesResponseSchema },
70
+ getPipeline: { request: GetPipelineRequestSchema, response: GetPipelineResponseSchema },
71
+ listRuns: { request: ListRunsRequestSchema, response: ListRunsResponseSchema },
72
+ getRun: { request: GetRunRequestSchema, response: GetRunResponseSchema },
73
+ startRun: { request: StartRunRequestSchema, response: StartRunResponseSchema },
74
+ cancelRun: { request: CancelRunRequestSchema, response: CancelRunResponseSchema },
75
+ savePipeline: { request: SavePipelineRequestSchema, response: SavePipelineResponseSchema },
76
+ listPipelineVersions: { request: ListPipelineVersionsRequestSchema, response: ListPipelineVersionsResponseSchema },
77
+ };
78
+ export const isPipelineRpcMethod = (method) => Object.hasOwn(PIPELINE_RPC, method);
79
+ /**
80
+ * A Pipelines backend whose calls travel as MCP tool calls, for the app page.
81
+ * The server decides what each call may do: it refuses a full refresh, and a
82
+ * save still needs the approver, the digest and the version it was made against.
83
+ */
84
+ export function mcpPipelines(callTool) {
85
+ const unary = (method) => async (init) => {
86
+ const shape = PIPELINE_RPC[method];
87
+ const request = toJson(shape.request, create(shape.request, init));
88
+ const result = await callTool(PIPELINE_RPC_TOOL, { method, request });
89
+ if (result.isError) {
90
+ const first = Array.isArray(result.content) ? result.content[0]?.text : undefined;
91
+ throw new Error(first ?? "The request failed.");
92
+ }
93
+ return fromJson(shape.response, (result.structuredContent?.message ?? {}));
94
+ };
95
+ return {
96
+ ...Object.fromEntries(Object.keys(PIPELINE_RPC).map((method) => [method, unary(method)])),
97
+ inspectFiles: async () => {
98
+ throw new Error("Inspecting files is not offered in this app.");
99
+ },
100
+ };
101
+ }
102
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAA2C,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAEvG,OAAO,EACL,sBAAsB,EACtB,uBAAuB,EACvB,wBAAwB,EACxB,yBAAyB,EACzB,mBAAmB,EACnB,oBAAoB,EACpB,iCAAiC,EACjC,kCAAkC,EAClC,0BAA0B,EAC1B,2BAA2B,EAC3B,qBAAqB,EACrB,sBAAsB,EACtB,yBAAyB,EACzB,0BAA0B,EAC1B,qBA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AC,CAAC,CAAC,SAAS,CAAC;YACrH,MAAM,IAAI,KAAK,CAAC,KAAK,IAAI,qBAAqB,CAAC,CAAC;QAClD,CAAC;QACD,OAAO,QAAQ,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAE,MAAM,CAAC,iBAAoD,EAAE,OAAO,IAAI,EAAE,CAAS,CAAC,CAAC;IACzH,CAAC,CAAC;IACF,OAAO;QACL,GAAI,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,KAAK,CAAC,MAA2B,CAAC,CAAC,CAAC,CAAgD;QAC9J,YAAY,EAAE,KAAK,IAAI,EAAE;YACvB,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;QAClE,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { type DescMessage, type MessageInitShape, create, fromJson, toJson } from \"@bufbuild/protobuf\";\nimport type { DataSource, Pipelines } from \"@surfaces-ui/data\";\nimport {\n CancelRunRequestSchema,\n CancelRunResponseSchema,\n GetPipelineRequestSchema,\n GetPipelineResponseSchema,\n GetRunRequestSchema,\n GetRunResponseSchema,\n ListPipelineVersionsRequestSchema,\n ListPipelineVersionsResponseSchema,\n ListPipelinesRequestSchema,\n ListPipelinesResponseSchema,\n ListRunsRequestSchema,\n ListRunsResponseSchema,\n SavePipelineRequestSchema,\n SavePipelineResponseSchema,\n StartRunRequestSchema,\n StartRunResponseSchema,\n CancelRequestSchema,\n CancelResponseSchema,\n CountRequestSchema,\n CountResponseSchema,\n DescribeTableRequestSchema,\n DescribeTableResponseSchema,\n ExecuteRequestSchema,\n ExecuteResponseSchema,\n ExplainRequestSchema,\n ExplainResponseSchema,\n ListCatalogsRequestSchema,\n ListCatalogsResponseSchema,\n ListSchemasRequestSchema,\n ListSchemasResponseSchema,\n ListSnapshotsRequestSchema,\n ListSnapshotsResponseSchema,\n ListSourcesRequestSchema,\n ListFilesRequestSchema,\n ListFilesResponseSchema,\n TestSourceRequestSchema,\n TestSourceResponseSchema,\n ListSourcesResponseSchema,\n ListTablesRequestSchema,\n ListTablesResponseSchema,\n} from \"@surfaces-ui/proto\";\n\n/** URI of the single app page every Surfaces tool renders into. */\nexport const APP_RESOURCE_URI = \"ui://surfaces/app.html\";\n\n/** The tool the app page uses to reach data. Hidden from the model. */\nexport const RPC_TOOL = \"surfaces_rpc\";\n\n/**\n * The tool the app page uses to reach pipelines. Hidden from the model, and\n * kept apart from the data channel because it can change things: a save the\n * person approved in the page, and a run the person started there.\n */\nexport const PIPELINE_RPC_TOOL = \"surfaces_pipeline_rpc\";\n\n/** What a UI tool tells the app to show. Travels as the tool result's structured content. */\nexport type AppView =\n | { view: \"grid\"; sourceId: string; sql: string; title?: string }\n | {\n view: \"chart\";\n sourceId: string;\n sql: string;\n title?: string;\n type: string;\n x: string;\n y: unknown[];\n splitBy?: string;\n xGrain?: string;\n xBins?: number;\n stacked?: boolean;\n legend?: string;\n }\n | { view: \"pivot\"; sourceId: string; sql: string; title?: string; rows: unknown[]; columns?: unknown[]; measures: unknown[] }\n | { view: \"result\"; sourceId: string; sql: string; title?: string }\n | { view: \"editor\"; sourceId: string; sql: string }\n | { view: \"schema\"; sourceId: string }\n | { view: \"surface\"; messages: unknown[] }\n /** Both draw their own heading, so they carry no title. */\n | { view: \"pipeline\"; pipelineId: string; sourceId: string }\n | {\n view: \"datasetReview\";\n /** The proposed pipeline, as PipelineDraft protobuf JSON, filled in by the server. */\n pipeline: unknown;\n dataset: string;\n expectedVersion: number;\n digest: string;\n sourceId: string;\n proposedBy?: string;\n };\n\nexport type RpcMethod = Exclude<keyof DataSource, never>;\n\n/** Request and response message types for each DataSource method, used to carry them as JSON. */\nexport const RPC: Record<RpcMethod, { request: DescMessage; response: DescMessage; stream?: boolean }> = {\n execute: { request: ExecuteRequestSchema, response: ExecuteResponseSchema, stream: true },\n count: { request: CountRequestSchema, response: CountResponseSchema },\n explain: { request: ExplainRequestSchema, response: ExplainResponseSchema },\n cancel: { request: CancelRequestSchema, response: CancelResponseSchema },\n listSources: { request: ListSourcesRequestSchema, response: ListSourcesResponseSchema },\n testSource: { request: TestSourceRequestSchema, response: TestSourceResponseSchema },\n listFiles: { request: ListFilesRequestSchema, response: ListFilesResponseSchema },\n listCatalogs: { request: ListCatalogsRequestSchema, response: ListCatalogsResponseSchema },\n listSchemas: { request: ListSchemasRequestSchema, response: ListSchemasResponseSchema },\n listTables: { request: ListTablesRequestSchema, response: ListTablesResponseSchema },\n describeTable: { request: DescribeTableRequestSchema, response: DescribeTableResponseSchema },\n listSnapshots: { request: ListSnapshotsRequestSchema, response: ListSnapshotsResponseSchema },\n};\n\nexport const isRpcMethod = (method: string): method is RpcMethod => Object.hasOwn(RPC, method);\n\ntype Json = Parameters<typeof fromJson>[1];\n\n/** Calls a tool and returns its structured content, or throws its error text. */\nexport type CallTool = (name: string, args: Record<string, unknown>) => Promise<{ structuredContent?: unknown; content?: unknown; isError?: boolean }>;\n\n/**\n * A DataSource whose calls travel as MCP tool calls. An MCP App page uses it\n * to reach the server that showed it: rows still come back as Arrow, and the\n * page still asks only for the window it is showing.\n */\nexport function mcpDataSource(callTool: CallTool): DataSource {\n const call = async (method: RpcMethod, init: unknown): Promise<Json[]> => {\n const shape = RPC[method];\n const request = toJson(shape.request, create(shape.request, init as MessageInitShape<DescMessage>));\n const result = await callTool(RPC_TOOL, { method, request });\n if (result.isError) {\n const first = Array.isArray(result.content) ? (result.content[0] as { text?: string } | undefined)?.text : undefined;\n throw new Error(first ?? \"The request failed.\");\n }\n return ((result.structuredContent as { messages?: Json[] } | undefined)?.messages ?? []) as Json[];\n };\n const unary = (method: RpcMethod) => async (init: unknown) => {\n const [message] = await call(method, init);\n return fromJson(RPC[method].response, message ?? {});\n };\n return {\n async *execute(init: unknown) {\n for (const message of await call(\"execute\", init)) yield fromJson(ExecuteResponseSchema, message);\n },\n count: unary(\"count\"),\n explain: unary(\"explain\"),\n cancel: unary(\"cancel\"),\n listSources: unary(\"listSources\"),\n testSource: unary(\"testSource\"),\n listFiles: unary(\"listFiles\"),\n listCatalogs: unary(\"listCatalogs\"),\n listSchemas: unary(\"listSchemas\"),\n listTables: unary(\"listTables\"),\n describeTable: unary(\"describeTable\"),\n listSnapshots: unary(\"listSnapshots\"),\n } as unknown as DataSource;\n}\n\nexport type PipelineRpcMethod = Exclude<keyof Pipelines, \"inspectFiles\">;\n\n/** Request and response message types for the pipeline calls the app page may make. */\nexport const PIPELINE_RPC: Record<PipelineRpcMethod, { request: DescMessage; response: DescMessage }> = {\n listPipelines: { request: ListPipelinesRequestSchema, response: ListPipelinesResponseSchema },\n getPipeline: { request: GetPipelineRequestSchema, response: GetPipelineResponseSchema },\n listRuns: { request: ListRunsRequestSchema, response: ListRunsResponseSchema },\n getRun: { request: GetRunRequestSchema, response: GetRunResponseSchema },\n startRun: { request: StartRunRequestSchema, response: StartRunResponseSchema },\n cancelRun: { request: CancelRunRequestSchema, response: CancelRunResponseSchema },\n savePipeline: { request: SavePipelineRequestSchema, response: SavePipelineResponseSchema },\n listPipelineVersions: { request: ListPipelineVersionsRequestSchema, response: ListPipelineVersionsResponseSchema },\n};\n\nexport const isPipelineRpcMethod = (method: string): method is PipelineRpcMethod => Object.hasOwn(PIPELINE_RPC, method);\n\n/**\n * A Pipelines backend whose calls travel as MCP tool calls, for the app page.\n * The server decides what each call may do: it refuses a full refresh, and a\n * save still needs the approver, the digest and the version it was made against.\n */\nexport function mcpPipelines(callTool: CallTool): Pipelines {\n const unary = (method: PipelineRpcMethod) => async (init: unknown) => {\n const shape = PIPELINE_RPC[method];\n const request = toJson(shape.request, create(shape.request, init as MessageInitShape<DescMessage>));\n const result = await callTool(PIPELINE_RPC_TOOL, { method, request });\n if (result.isError) {\n const first = Array.isArray(result.content) ? (result.content[0] as { text?: string } | undefined)?.text : undefined;\n throw new Error(first ?? \"The request failed.\");\n }\n return fromJson(shape.response, ((result.structuredContent as { message?: Json } | undefined)?.message ?? {}) as Json);\n };\n return {\n ...(Object.fromEntries(Object.keys(PIPELINE_RPC).map((method) => [method, unary(method as PipelineRpcMethod)])) as unknown as Omit<Pipelines, \"inspectFiles\">),\n inspectFiles: async () => {\n throw new Error(\"Inspecting files is not offered in this app.\");\n },\n };\n}\n"]}
@@ -0,0 +1,36 @@
1
+ import type { McpServer } from "@modelcontextprotocol/server";
2
+ import type { DataSource, Discovery, Pipelines } from "@surfaces-ui/data";
3
+ import { type Catalog } from "@surfaces-ui/spec";
4
+ export interface SurfacesAppsOptions {
5
+ /** Where data comes from. Queries stay on this side; the app page receives only the rows it shows. */
6
+ dataSource: DataSource;
7
+ /** The single-file app page (HTML), or a function that returns it. See `readAppHtml` in `@surfaces-ui/mcp/node`. */
8
+ appHtml: string | (() => string | Promise<string>);
9
+ /** The catalog search backend. With it the model gets `search_data`, which finds tables and columns by words or meaning. */
10
+ discovery?: Pick<Discovery, "search">;
11
+ /**
12
+ * The pipeline backend. With it the model gets `list_pipelines`,
13
+ * `describe_pipeline`, `check_pipeline`, `get_run`, `show_pipeline`,
14
+ * `propose_dataset` and `run_pipeline`. `show_pipeline` and
15
+ * `propose_dataset` draw the pipeline and the proposal for review in the
16
+ * app page, filled in here so the model never copies a definition.
17
+ * `run_pipeline` is marked destructive, so the host asks the person before
18
+ * it runs. A full refresh is not offered anywhere in this channel.
19
+ */
20
+ pipelines?: Pipelines;
21
+ /** Source used when a tool call does not name one. Defaults to the first source. */
22
+ defaultSourceId?: string;
23
+ /** Catalog agents may use with `render_surface`. Defaults to the analytics catalog. */
24
+ catalog?: Catalog;
25
+ /** Most rows the app's data tool returns per request. Defaults to 1,000. */
26
+ maxRowsPerRequest?: number;
27
+ }
28
+ /**
29
+ * Adds the Surfaces tools and app page to an MCP server.
30
+ *
31
+ * Tools the model can call show a view (table, chart, explorer, editor,
32
+ * schema, or an A2UI surface) in the host's UI. One further tool, hidden
33
+ * from the model, lets the app page fetch data. SQL is checked before a view
34
+ * is shown, so a mistake comes back to the model as an error it can fix.
35
+ */
36
+ export declare function registerSurfacesApps(server: McpServer, options: SurfacesAppsOptions): void;