@surfaces-ui/engine-mcp 0.0.0-stage → 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/engine.js ADDED
@@ -0,0 +1,342 @@
1
+ import { EngineError } from "@surfaces-ui/engine";
2
+ import { arrowResult, columnType, createTeradataEngine } from "@surfaces-ui/engine-teradata";
3
+ import { ConnectionKind, Engine as EngineKind, SqlDialect, TableKind } from "@surfaces-ui/proto";
4
+ import { inlineParams, literal } from "./literal.js";
5
+ const SYSTEM_SCHEMAS = "('information_schema', 'pg_catalog', 'pg_toast')";
6
+ const MYSQL_SYSTEM_SCHEMAS = "('information_schema', 'mysql', 'performance_schema', 'sys')";
7
+ const DATE_TEXT = /^\d{4}-\d\d-\d\d$/;
8
+ const TIME_TEXT = /^\d{4}-\d\d-\d\d[ T]\d\d:\d\d(:\d\d(\.\d+)?)?$/;
9
+ /**
10
+ * A column's type from its values, for a database that will not say (MySQL).
11
+ * The values have come through the database's own JSON, so a number is a
12
+ * number and text is text; only whole numbers, dates and times are told
13
+ * apart here. A column with no values on this page is text.
14
+ */
15
+ export function typeOfValues(values) {
16
+ const present = values.filter((value) => value !== null && value !== undefined);
17
+ if (present.length === 0)
18
+ return "VARCHAR";
19
+ if (present.every((value) => typeof value === "number" || typeof value === "bigint"))
20
+ return present.every((value) => typeof value === "bigint" || Number.isInteger(value)) ? "BIGINT" : "FLOAT";
21
+ if (present.every((value) => typeof value === "boolean"))
22
+ return "BYTEINT";
23
+ if (present.every((value) => typeof value === "string" && DATE_TEXT.test(value)))
24
+ return "DATE";
25
+ if (present.every((value) => typeof value === "string" && TIME_TEXT.test(value)))
26
+ return "TIMESTAMP";
27
+ return "VARCHAR";
28
+ }
29
+ const quoted = (name) => `"${name.replace(/"/g, '""')}"`;
30
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
31
+ /**
32
+ * A statement without the `LIMIT n` and `OFFSET n` the rewriter ends a page
33
+ * with, and whether it had a limit. Found by looking for the words from the
34
+ * end, not with a pattern: the statement holds a person's own query, and a
35
+ * pattern that can backtrack over it is a way to stall the server.
36
+ */
37
+ export function paging(query) {
38
+ let base = query.trimEnd();
39
+ let limited = false;
40
+ for (const word of [" OFFSET ", " LIMIT "]) {
41
+ const at = base.toUpperCase().lastIndexOf(word);
42
+ if (at === -1)
43
+ continue;
44
+ const count = base.slice(at + word.length).trim();
45
+ if (count === "" || [...count].some((c) => c < "0" || c > "9"))
46
+ continue;
47
+ base = base.slice(0, at).trimEnd();
48
+ if (word === " LIMIT ")
49
+ limited = true;
50
+ }
51
+ return { base, limited };
52
+ }
53
+ /** A database's type name as one the Arrow builder knows. Anything else arrives as text. */
54
+ export function standardType(native) {
55
+ // No real type name is long. One that is has nothing to tell us, and the Arrow builder's own patterns should never be handed it.
56
+ if (native.length > 200)
57
+ return "VARCHAR";
58
+ // Words are told apart by splitting, not by a pattern: a type name comes from another server, and a pattern that can backtrack over it is a way to stall this one.
59
+ const text = native
60
+ .trim()
61
+ .toUpperCase()
62
+ .split(" ")
63
+ .filter((word) => word !== "" && word !== "UNSIGNED" && word !== "ZEROFILL")
64
+ .join(" ");
65
+ // The name without what is in brackets (a precision, a length), taken out one character at a time for the same reason.
66
+ let base = "";
67
+ let depth = 0;
68
+ for (const c of text) {
69
+ if (c === "(")
70
+ depth += 1;
71
+ else if (c === ")")
72
+ depth = Math.max(0, depth - 1);
73
+ else if (depth === 0)
74
+ base += c;
75
+ }
76
+ base = base.split(" ").filter(Boolean).join(" ");
77
+ if (base === "BOOLEAN" || base === "BOOL" || base === "TINYINT")
78
+ return "BYTEINT";
79
+ if (base === "INT2")
80
+ return "SMALLINT";
81
+ if (base === "INT4" || base === "USMALLINT" || base === "MEDIUMINT")
82
+ return "INTEGER";
83
+ // MySQL writes a display width after a whole number's type, which is not a precision.
84
+ if (base === "SMALLINT" || base === "INT" || base === "INTEGER" || base === "BIGINT")
85
+ return base;
86
+ if (base === "INT8" || base === "UINTEGER")
87
+ return "BIGINT";
88
+ if (base === "HUGEINT" || base === "UBIGINT" || base === "UHUGEINT")
89
+ return "DECIMAL(38,0)";
90
+ if (base === "TIMESTAMP WITHOUT TIME ZONE" || base === "DATETIME" || /^TIMESTAMP_(S|MS|NS)$/.test(base))
91
+ return "TIMESTAMP";
92
+ if (base === "TIMESTAMPTZ")
93
+ return "TIMESTAMP WITH TIME ZONE";
94
+ // Postgres says "numeric" without its precision, so the scale is not known and the column is a float.
95
+ if (base === "NUMERIC" && !text.includes("("))
96
+ return "FLOAT";
97
+ if (base === "FLOAT4" || base === "FLOAT8")
98
+ return "FLOAT";
99
+ if (base === "BYTEA")
100
+ return "VARBYTE";
101
+ return text;
102
+ }
103
+ /** The names Python gives the values the Teradata server read, as Teradata type names. */
104
+ const PYTHON_TYPES = { int: "BIGINT", float: "FLOAT", Decimal: "FLOAT", str: "VARCHAR", date: "DATE", datetime: "TIMESTAMP(6)", bool: "BYTEINT", bytes: "VARBYTE", bytearray: "VARBYTE" };
105
+ /**
106
+ * The Teradata MCP server as a transport for the Teradata engine, so the
107
+ * catalog, types and checks are the ones that engine already has. The
108
+ * server takes no bound values, so they are written into the statement as
109
+ * checked literals. It owns the session: the time zone and default database
110
+ * are whatever its own connection has.
111
+ */
112
+ export function teradataMcpClient(sql) {
113
+ return {
114
+ async query(text, params, options) {
115
+ const result = await sql.query(inlineParams(text, params, SqlDialect.TERADATA), options);
116
+ return { columns: result.columns.map((c) => ({ name: c.name, type: PYTHON_TYPES[c.type ?? ""] ?? "" })), rows: result.rows, truncated: result.truncated };
117
+ },
118
+ close: () => sql.close(),
119
+ };
120
+ }
121
+ /**
122
+ * A database reached through its own MCP server, behind the Engine
123
+ * interface. Every sort, filter, page and total is SQL sent through the
124
+ * server's query tool; rows come back as that tool's answer and never pass
125
+ * through a model.
126
+ *
127
+ * It only reads: there is no `store` or `materialize`, so views of a query
128
+ * run it again and pipelines cannot use this engine. A query cannot be
129
+ * cancelled once sent, and there is no time travel. A result the server cut
130
+ * short is an error, never a short result, so raise the server's row limit
131
+ * for a large export.
132
+ */
133
+ /**
134
+ * The engine over a query tool that is already reachable. `open` gets the
135
+ * arguments this dialect sends with every query (Teradata's row limit), for
136
+ * the caller to put under its own.
137
+ */
138
+ export async function createMcpEngineOver(open, options) {
139
+ if (options.dialect === "teradata") {
140
+ // The Teradata server stops at 1,000 rows unless asked; 50,000 is the most it gives.
141
+ const sql = open({ row_limit: 50_000 });
142
+ return createTeradataEngine({ client: teradataMcpClient(sql), database: options.database, databases: options.databases, address: options.address });
143
+ }
144
+ const postgres = options.dialect === "postgres";
145
+ const mysql = options.dialect === "mysql";
146
+ const dialect = postgres ? SqlDialect.POSTGRES : mysql ? SqlDialect.MYSQL : SqlDialect.DUCKDB;
147
+ const system = mysql ? MYSQL_SYSTEM_SCHEMAS : SYSTEM_SCHEMAS;
148
+ const named = (name) => (mysql ? `\`${name.replace(/`/g, "``")}\`` : quoted(name));
149
+ const sql = open({});
150
+ const batchRows = Math.max(1, Math.floor(options.batchRows ?? 4096));
151
+ const text = (value) => literal(value, dialect);
152
+ const complete = (rows) => {
153
+ if (rows.truncated)
154
+ throw new EngineError("UNSUPPORTED", "The data server cut this result short. Ask for fewer rows at a time, or raise the server's row limit.");
155
+ return rows;
156
+ };
157
+ /** Postgres: each row as one JSON object, so a number is a number and text is text whatever driver the server uses. */
158
+ const jsonRows = async (query, signal) => {
159
+ const answer = complete(await sql.query(`SELECT row_to_json(t) AS r FROM (${query}) AS t`, { signal }));
160
+ return answer.rows.map((row) => {
161
+ const value = row[0];
162
+ const parsed = typeof value === "string" ? JSON.parse(value) : value;
163
+ if (!isRecord(parsed))
164
+ throw new EngineError("ENGINE", "The data server answered in a form that is not rows.");
165
+ return parsed;
166
+ });
167
+ };
168
+ /**
169
+ * Postgres: a result's column names and types without running the query.
170
+ * Joined to one row on a condition that is never true, the query is never
171
+ * executed, yet its columns are there to name and to ask the type of.
172
+ */
173
+ const described = new Map();
174
+ const describe = async (query, names) => {
175
+ const key = paging(query).base;
176
+ const known = described.get(key);
177
+ if (known)
178
+ return known;
179
+ const never = `FROM (SELECT 1) AS o LEFT JOIN (${query}) AS q ON false`;
180
+ const found = names ?? Object.keys((await jsonRows(`SELECT q.* ${never}`))[0] ?? {});
181
+ if (found.length === 0)
182
+ return [];
183
+ const types = (await jsonRows(`SELECT ${found.map((name) => `pg_typeof(q.${quoted(name)})::text AS ${quoted(name)}`).join(", ")} ${never}`))[0] ?? {};
184
+ const columns = found.map((name) => ({ name, type: String(types[name] ?? "") }));
185
+ if (described.size > 200)
186
+ described.clear();
187
+ described.set(key, columns);
188
+ return columns;
189
+ };
190
+ /**
191
+ * MySQL: the column names of a result, by the same join that is never
192
+ * true. MySQL has no function that names a value's type, so the types come
193
+ * from the values (`typeOfValues`).
194
+ */
195
+ const namesOf = async (query) => {
196
+ const key = paging(query).base;
197
+ const known = described.get(key);
198
+ if (known)
199
+ return known.map((c) => c.name);
200
+ const probe = complete(await sql.query(`SELECT q.* FROM (SELECT 1 AS \`__one\`) AS o LEFT JOIN (${query}) AS q ON 1 = 0`));
201
+ if (described.size > 200)
202
+ described.clear();
203
+ described.set(key, probe.columns);
204
+ return probe.columns.map((c) => c.name);
205
+ };
206
+ /**
207
+ * MySQL: each row as one JSON object the database builds, so a decimal is
208
+ * a number and a time is the text the database holds, whatever the server's
209
+ * driver would have made of them (one sends decimals as text and moves
210
+ * times into its own zone). A derived table's order is kept only when it
211
+ * has a limit, so one is added when the query has none.
212
+ */
213
+ const mysqlRows = async (query, signal) => {
214
+ const names = await namesOf(query);
215
+ if (names.length === 0)
216
+ return complete(await sql.query(query, { signal }));
217
+ const limited = paging(query).limited ? query : `${query} LIMIT 18446744073709551615`;
218
+ const answer = complete(await sql.query(`SELECT JSON_OBJECT(${names.map((name) => `${text(name)}, q.${named(name)}`).join(", ")}) AS r FROM (${limited}) AS q`, { signal }));
219
+ const rows = answer.rows.map((row) => {
220
+ const parsed = typeof row[0] === "string" ? JSON.parse(row[0]) : row[0];
221
+ if (!isRecord(parsed))
222
+ throw new EngineError("ENGINE", "The data server answered in a form that is not rows.");
223
+ return names.map((name) => parsed[name] ?? null);
224
+ });
225
+ return { columns: names.map((name, i) => ({ name, type: typeOfValues(rows.map((row) => row[i])) })), rows };
226
+ };
227
+ /** Runs a statement and gives its rows with each column's type. */
228
+ const run = async (query, signal) => {
229
+ if (mysql)
230
+ return mysqlRows(query, signal);
231
+ if (!postgres)
232
+ return complete(await sql.query(query, { signal }));
233
+ const objects = await jsonRows(query, signal);
234
+ const columns = await describe(query, objects[0] ? Object.keys(objects[0]) : undefined);
235
+ return { columns, rows: objects.map((row) => columns.map((c) => row[c.name] ?? null)) };
236
+ };
237
+ const objectsOf = async (query) => {
238
+ const { columns, rows } = await run(query);
239
+ return rows.map((row) => Object.fromEntries(columns.map((c, i) => [c.name.toLowerCase(), row[i]])));
240
+ };
241
+ const schemaFilter = (schema) => (schema ? `table_schema = ${text(schema)}` : `table_schema NOT IN ${system}`);
242
+ const find = async (ref) => {
243
+ const table = ref?.table ?? "";
244
+ const rows = await objectsOf(`SELECT table_schema AS table_schema, table_name AS table_name, table_type AS table_type${mysql ? ", table_comment AS table_comment" : ""} FROM information_schema.tables WHERE lower(table_name) = lower(${text(table)}) AND ${schemaFilter(ref?.schema ?? "")} ORDER BY table_schema`);
245
+ if (!rows[0])
246
+ throw new EngineError("UNKNOWN_TABLE", `Table not found: ${table}`);
247
+ return { schema: String(rows[0].table_schema), table: String(rows[0].table_name), view: /VIEW/i.test(String(rows[0].table_type)), comment: rows[0].table_comment ? String(rows[0].table_comment) : "" };
248
+ };
249
+ return {
250
+ kind: postgres ? EngineKind.POSTGRES : mysql ? EngineKind.MYSQL : EngineKind.DUCKDB,
251
+ dialect,
252
+ capabilities: { cancel: false, explain: true, explainJson: false, timeTravel: false, keysetPaging: false, exactCount: true, columnStats: false },
253
+ connections: [{ name: options.dialect, kind: ConnectionKind.HTTP, scope: options.address ?? "" }],
254
+ async execute(query, params, executeOptions = {}) {
255
+ if (executeOptions.timeTravel?.at.case)
256
+ throw new EngineError("UNSUPPORTED", "This source cannot read tables as of an earlier time.");
257
+ const result = await run(inlineParams(query, params, dialect), executeOptions.signal);
258
+ const arrow = arrowResult({ columns: result.columns.map((c) => ({ name: c.name, type: c.type ? standardType(c.type) : "" })), rows: result.rows });
259
+ async function* batches() {
260
+ for (let at = 0; at < result.rows.length; at += batchRows)
261
+ yield arrow.batch(result.rows.slice(at, at + batchRows));
262
+ }
263
+ return { schema: arrow.schema, batches: batches() };
264
+ },
265
+ async explain(query, params) {
266
+ const plan = complete(await sql.query(`EXPLAIN ${inlineParams(query, params, dialect)}`));
267
+ return { planText: plan.rows.map((row) => String(row[row.length - 1] ?? "")).join("\n"), planJson: "" };
268
+ },
269
+ async check() {
270
+ const started = Date.now();
271
+ try {
272
+ const { tool, server } = await sql.describe();
273
+ await sql.query("SELECT 1 AS ok");
274
+ return [{ name: server || options.dialect, ok: true, message: `Reachable through the tool ${tool}`, elapsedMs: Date.now() - started }];
275
+ }
276
+ catch (error) {
277
+ return [{ name: options.dialect, ok: false, message: error instanceof Error ? error.message : String(error), elapsedMs: Date.now() - started }];
278
+ }
279
+ },
280
+ async listCatalogs() {
281
+ const rows = await objectsOf(mysql ? "SELECT DATABASE() AS name" : "SELECT current_database() AS name");
282
+ return [{ name: String(rows[0]?.name ?? options.dialect) }];
283
+ },
284
+ async listSchemas(catalog) {
285
+ const rows = await objectsOf(`SELECT DISTINCT table_schema AS name FROM information_schema.tables WHERE table_schema NOT IN ${system} ORDER BY 1`);
286
+ return rows.map((row) => ({ catalog, name: String(row.name) }));
287
+ },
288
+ async listTables({ schema, search }) {
289
+ const like = search ? ` AND lower(table_name) LIKE ${text(`%${search.toLowerCase().replace(/[\\%_]/g, "\\$&")}%`)} ${mysql ? "" : `ESCAPE ${text("\\")}`}` : "";
290
+ const rows = await objectsOf(`SELECT table_schema AS table_schema, table_name AS table_name, table_type AS table_type FROM information_schema.tables WHERE ${schemaFilter(schema)}${like} ORDER BY table_schema, table_name LIMIT 1000`);
291
+ return rows.map((row) => ({ ref: { catalog: "", schema: String(row.table_schema), table: String(row.table_name) }, kind: /VIEW/i.test(String(row.table_type)) ? TableKind.VIEW : TableKind.TABLE }));
292
+ },
293
+ async describeTable(ref, includeStats) {
294
+ const found = await find(ref);
295
+ const at = `table_schema = ${text(found.schema)} AND table_name = ${text(found.table)}`;
296
+ const columns = await objectsOf(`SELECT column_name AS column_name, ${mysql ? "column_type" : "data_type"} AS data_type, is_nullable AS is_nullable, ordinal_position AS ordinal_position${mysql ? ", column_comment AS column_comment" : ""} FROM information_schema.columns WHERE ${at} ORDER BY ordinal_position`);
297
+ // Keys and comments are extras: a database or a login that will not give them leaves them out, it does not fail the description.
298
+ const optional = async (query) => objectsOf(query).catch(() => []);
299
+ const keys = await optional(mysql
300
+ ? `SELECT column_name AS column_name FROM information_schema.key_column_usage WHERE constraint_name = 'PRIMARY' AND ${at}`
301
+ : postgres
302
+ ? // pg_catalog, because information_schema shows a table's constraints only to a role that owns it or may write to it.
303
+ `SELECT a.attname AS column_name FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ANY (con.conkey) WHERE con.contype = 'p' AND n.nspname = ${text(found.schema)} AND c.relname = ${text(found.table)}`
304
+ : `SELECT kcu.column_name FROM information_schema.table_constraints tc JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema AND kcu.table_name = tc.table_name WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = ${text(found.schema)} AND tc.table_name = ${text(found.table)}`);
305
+ const primary = new Set(keys.map((row) => String(row.column_name)));
306
+ const comments = postgres
307
+ ? await optional(`SELECT a.attname AS column_name, col_description(c.oid, a.attnum) AS comment, obj_description(c.oid) AS table_comment FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped WHERE n.nspname = ${text(found.schema)} AND c.relname = ${text(found.table)}`)
308
+ : [];
309
+ const comment = new Map((mysql ? columns.map((row) => ({ column_name: row.column_name, comment: row.column_comment })) : comments).map((row) => [String(row.column_name), row.comment ? String(row.comment) : ""]));
310
+ const references = postgres
311
+ ? await optional(`SELECT con.conname AS name, a.attname AS column_name, fn.nspname AS ref_schema, fc.relname AS ref_table, fa.attname AS ref_column, k.ord FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_class fc ON fc.oid = con.confrelid JOIN pg_namespace fn ON fn.oid = fc.relnamespace CROSS JOIN LATERAL unnest(con.conkey, con.confkey) WITH ORDINALITY AS k(col, fcol, ord) JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = k.col JOIN pg_attribute fa ON fa.attrelid = fc.oid AND fa.attnum = k.fcol WHERE con.contype = 'f' AND n.nspname = ${text(found.schema)} AND c.relname = ${text(found.table)} ORDER BY con.conname, k.ord`)
312
+ : mysql
313
+ ? await optional(`SELECT constraint_name AS name, column_name AS column_name, referenced_table_schema AS ref_schema, referenced_table_name AS ref_table, referenced_column_name AS ref_column FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL AND ${at} ORDER BY constraint_name, ordinal_position`)
314
+ : [];
315
+ const foreign = new Map();
316
+ for (const row of references) {
317
+ const key = foreign.get(String(row.name)) ?? { columns: [], references: { catalog: "", schema: String(row.ref_schema), table: String(row.ref_table) }, referencedColumns: [] };
318
+ key.columns.push(String(row.column_name));
319
+ key.referencedColumns.push(String(row.ref_column));
320
+ foreign.set(String(row.name), key);
321
+ }
322
+ const counted = includeStats ? (await objectsOf(`SELECT COUNT(*) AS n FROM ${named(found.schema)}.${named(found.table)}`))[0]?.n : undefined;
323
+ return {
324
+ summary: { ref: { catalog: "", schema: found.schema, table: found.table }, kind: found.view ? TableKind.VIEW : TableKind.TABLE, comment: found.comment || (comments[0]?.table_comment ? String(comments[0].table_comment) : "") },
325
+ columns: columns.map((row, i) => {
326
+ const native = String(row.data_type);
327
+ return { name: String(row.column_name), nativeType: native, arrowType: String(columnType(standardType(native)).arrow), nullable: String(row.is_nullable).toUpperCase() !== "NO", ordinal: Number(row.ordinal_position ?? i + 1), primaryKey: primary.has(String(row.column_name)), comment: comment.get(String(row.column_name)) ?? "" };
328
+ }),
329
+ rowCount: counted === undefined || counted === null ? undefined : BigInt(counted),
330
+ foreignKeys: [...foreign.values()],
331
+ };
332
+ },
333
+ listSnapshots: async () => [],
334
+ async version() {
335
+ const rows = await objectsOf(postgres ? "SELECT current_setting('server_version') AS v" : "SELECT VERSION() AS v");
336
+ const { server } = await sql.describe();
337
+ return `${postgres ? "PostgreSQL" : mysql ? "MySQL" : "DuckDB"} ${String(rows[0]?.v ?? "")}${server ? ` through ${server}` : ""}`.trim();
338
+ },
339
+ close: () => sql.close(),
340
+ };
341
+ }
342
+ //# sourceMappingURL=engine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.js","sourceRoot":"","sources":["../src/engine.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiC,WAAW,EAAsD,MAAM,qBAAqB,CAAC;AACrI,OAAO,EAAuB,WAAW,EAAE,UAAU,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAClH,OAAO,EAAE,cAAc,EAAE,MAAM,IAAI,UAAU,EAAE,UAAU,EAAE,SAAS,EAAiB,MAAM,oBAAoB,CAAC;AAGhH,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAerD,MAAM,cAAc,GAAG,kDAAkD,CAAC;AAC1E,MAAM,oBAAoB,GAAG,8DAA8D,CAAC;AAC5F,MAAM,SAAS,GAAG,mBAAmB,CAAC;AACtC,MAAM,SAAS,GAAG,gDAAgD,CAAC;AAEnE;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,MAAiB;IAC5C,MA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KAAK,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE;KACzB,CAAC;AACJ,CAAC","sourcesContent":["import { type Engine, type EngineCheck, EngineError, type EngineResult, type ExecuteOptions, type Param } from \"@surfaces-ui/engine\";\nimport { type TeradataClient, arrowResult, columnType, createTeradataEngine } from \"@surfaces-ui/engine-teradata\";\nimport { ConnectionKind, Engine as EngineKind, SqlDialect, TableKind, type TableRef } from \"@surfaces-ui/proto\";\nimport type { RecordBatch } from \"apache-arrow\";\nimport type { McpSql } from \"./sql.js\";\nimport { inlineParams, literal } from \"./literal.js\";\nimport type { SqlColumn, SqlRows } from \"./parse.js\";\n\nexport interface McpEngineSettings {\n /** The database behind the server, which decides the SQL that is written for it. */\n dialect: \"postgres\" | \"mysql\" | \"duckdb\" | \"teradata\";\n /** Shown as where this source connects, such as the server's address. Never a credential. */\n address?: string;\n /** Teradata: the default database, and the databases a listing covers when none is named. */\n database?: string;\n databases?: string[];\n /** Rows in one Arrow batch. Default 4096. */\n batchRows?: number;\n}\n\nconst SYSTEM_SCHEMAS = \"('information_schema', 'pg_catalog', 'pg_toast')\";\nconst MYSQL_SYSTEM_SCHEMAS = \"('information_schema', 'mysql', 'performance_schema', 'sys')\";\nconst DATE_TEXT = /^\\d{4}-\\d\\d-\\d\\d$/;\nconst TIME_TEXT = /^\\d{4}-\\d\\d-\\d\\d[ T]\\d\\d:\\d\\d(:\\d\\d(\\.\\d+)?)?$/;\n\n/**\n * A column's type from its values, for a database that will not say (MySQL).\n * The values have come through the database's own JSON, so a number is a\n * number and text is text; only whole numbers, dates and times are told\n * apart here. A column with no values on this page is text.\n */\nexport function typeOfValues(values: unknown[]): string {\n const present = values.filter((value) => value !== null && value !== undefined);\n if (present.length === 0) return \"VARCHAR\";\n if (present.every((value) => typeof value === \"number\" || typeof value === \"bigint\")) return present.every((value) => typeof value === \"bigint\" || Number.isInteger(value)) ? \"BIGINT\" : \"FLOAT\";\n if (present.every((value) => typeof value === \"boolean\")) return \"BYTEINT\";\n if (present.every((value) => typeof value === \"string\" && DATE_TEXT.test(value))) return \"DATE\";\n if (present.every((value) => typeof value === \"string\" && TIME_TEXT.test(value))) return \"TIMESTAMP\";\n return \"VARCHAR\";\n}\nconst quoted = (name: string) => `\"${name.replace(/\"/g, '\"\"')}\"`;\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * A statement without the `LIMIT n` and `OFFSET n` the rewriter ends a page\n * with, and whether it had a limit. Found by looking for the words from the\n * end, not with a pattern: the statement holds a person's own query, and a\n * pattern that can backtrack over it is a way to stall the server.\n */\nexport function paging(query: string): { base: string; limited: boolean } {\n let base = query.trimEnd();\n let limited = false;\n for (const word of [\" OFFSET \", \" LIMIT \"]) {\n const at = base.toUpperCase().lastIndexOf(word);\n if (at === -1) continue;\n const count = base.slice(at + word.length).trim();\n if (count === \"\" || [...count].some((c) => c < \"0\" || c > \"9\")) continue;\n base = base.slice(0, at).trimEnd();\n if (word === \" LIMIT \") limited = true;\n }\n return { base, limited };\n}\n\n/** A database's type name as one the Arrow builder knows. Anything else arrives as text. */\nexport function standardType(native: string): string {\n // No real type name is long. One that is has nothing to tell us, and the Arrow builder's own patterns should never be handed it.\n if (native.length > 200) return \"VARCHAR\";\n // Words are told apart by splitting, not by a pattern: a type name comes from another server, and a pattern that can backtrack over it is a way to stall this one.\n const text = native\n .trim()\n .toUpperCase()\n .split(\" \")\n .filter((word) => word !== \"\" && word !== \"UNSIGNED\" && word !== \"ZEROFILL\")\n .join(\" \");\n // The name without what is in brackets (a precision, a length), taken out one character at a time for the same reason.\n let base = \"\";\n let depth = 0;\n for (const c of text) {\n if (c === \"(\") depth += 1;\n else if (c === \")\") depth = Math.max(0, depth - 1);\n else if (depth === 0) base += c;\n }\n base = base.split(\" \").filter(Boolean).join(\" \");\n if (base === \"BOOLEAN\" || base === \"BOOL\" || base === \"TINYINT\") return \"BYTEINT\";\n if (base === \"INT2\") return \"SMALLINT\";\n if (base === \"INT4\" || base === \"USMALLINT\" || base === \"MEDIUMINT\") return \"INTEGER\";\n // MySQL writes a display width after a whole number's type, which is not a precision.\n if (base === \"SMALLINT\" || base === \"INT\" || base === \"INTEGER\" || base === \"BIGINT\") return base;\n if (base === \"INT8\" || base === \"UINTEGER\") return \"BIGINT\";\n if (base === \"HUGEINT\" || base === \"UBIGINT\" || base === \"UHUGEINT\") return \"DECIMAL(38,0)\";\n if (base === \"TIMESTAMP WITHOUT TIME ZONE\" || base === \"DATETIME\" || /^TIMESTAMP_(S|MS|NS)$/.test(base)) return \"TIMESTAMP\";\n if (base === \"TIMESTAMPTZ\") return \"TIMESTAMP WITH TIME ZONE\";\n // Postgres says \"numeric\" without its precision, so the scale is not known and the column is a float.\n if (base === \"NUMERIC\" && !text.includes(\"(\")) return \"FLOAT\";\n if (base === \"FLOAT4\" || base === \"FLOAT8\") return \"FLOAT\";\n if (base === \"BYTEA\") return \"VARBYTE\";\n return text;\n}\n\n/** The names Python gives the values the Teradata server read, as Teradata type names. */\nconst PYTHON_TYPES: Record<string, string> = { int: \"BIGINT\", float: \"FLOAT\", Decimal: \"FLOAT\", str: \"VARCHAR\", date: \"DATE\", datetime: \"TIMESTAMP(6)\", bool: \"BYTEINT\", bytes: \"VARBYTE\", bytearray: \"VARBYTE\" };\n\n/**\n * The Teradata MCP server as a transport for the Teradata engine, so the\n * catalog, types and checks are the ones that engine already has. The\n * server takes no bound values, so they are written into the statement as\n * checked literals. It owns the session: the time zone and default database\n * are whatever its own connection has.\n */\nexport function teradataMcpClient(sql: McpSql): TeradataClient {\n return {\n async query(text, params, options) {\n const result = await sql.query(inlineParams(text, params as Param[], SqlDialect.TERADATA), options);\n return { columns: result.columns.map((c) => ({ name: c.name, type: PYTHON_TYPES[c.type ?? \"\"] ?? \"\" })), rows: result.rows, truncated: result.truncated };\n },\n close: () => sql.close(),\n };\n}\n\n/**\n * A database reached through its own MCP server, behind the Engine\n * interface. Every sort, filter, page and total is SQL sent through the\n * server's query tool; rows come back as that tool's answer and never pass\n * through a model.\n *\n * It only reads: there is no `store` or `materialize`, so views of a query\n * run it again and pipelines cannot use this engine. A query cannot be\n * cancelled once sent, and there is no time travel. A result the server cut\n * short is an error, never a short result, so raise the server's row limit\n * for a large export.\n */\n/**\n * The engine over a query tool that is already reachable. `open` gets the\n * arguments this dialect sends with every query (Teradata's row limit), for\n * the caller to put under its own.\n */\nexport async function createMcpEngineOver(open: (always: Record<string, unknown>) => McpSql, options: McpEngineSettings): Promise<Engine> {\n if (options.dialect === \"teradata\") {\n // The Teradata server stops at 1,000 rows unless asked; 50,000 is the most it gives.\n const sql = open({ row_limit: 50_000 });\n return createTeradataEngine({ client: teradataMcpClient(sql), database: options.database, databases: options.databases, address: options.address });\n }\n const postgres = options.dialect === \"postgres\";\n const mysql = options.dialect === \"mysql\";\n const dialect = postgres ? SqlDialect.POSTGRES : mysql ? SqlDialect.MYSQL : SqlDialect.DUCKDB;\n const system = mysql ? MYSQL_SYSTEM_SCHEMAS : SYSTEM_SCHEMAS;\n const named = (name: string) => (mysql ? `\\`${name.replace(/`/g, \"``\")}\\`` : quoted(name));\n const sql = open({});\n const batchRows = Math.max(1, Math.floor(options.batchRows ?? 4096));\n const text = (value: string) => literal(value, dialect);\n\n const complete = (rows: SqlRows): SqlRows => {\n if (rows.truncated) throw new EngineError(\"UNSUPPORTED\", \"The data server cut this result short. Ask for fewer rows at a time, or raise the server's row limit.\");\n return rows;\n };\n\n /** Postgres: each row as one JSON object, so a number is a number and text is text whatever driver the server uses. */\n const jsonRows = async (query: string, signal?: AbortSignal): Promise<Record<string, unknown>[]> => {\n const answer = complete(await sql.query(`SELECT row_to_json(t) AS r FROM (${query}) AS t`, { signal }));\n return answer.rows.map((row) => {\n const value = row[0];\n const parsed: unknown = typeof value === \"string\" ? JSON.parse(value) : value;\n if (!isRecord(parsed)) throw new EngineError(\"ENGINE\", \"The data server answered in a form that is not rows.\");\n return parsed;\n });\n };\n\n /**\n * Postgres: a result's column names and types without running the query.\n * Joined to one row on a condition that is never true, the query is never\n * executed, yet its columns are there to name and to ask the type of.\n */\n const described = new Map<string, SqlColumn[]>();\n const describe = async (query: string, names?: string[]): Promise<SqlColumn[]> => {\n const key = paging(query).base;\n const known = described.get(key);\n if (known) return known;\n const never = `FROM (SELECT 1) AS o LEFT JOIN (${query}) AS q ON false`;\n const found = names ?? Object.keys((await jsonRows(`SELECT q.* ${never}`))[0] ?? {});\n if (found.length === 0) return [];\n const types = (await jsonRows(`SELECT ${found.map((name) => `pg_typeof(q.${quoted(name)})::text AS ${quoted(name)}`).join(\", \")} ${never}`))[0] ?? {};\n const columns = found.map((name) => ({ name, type: String(types[name] ?? \"\") }));\n if (described.size > 200) described.clear();\n described.set(key, columns);\n return columns;\n };\n\n /**\n * MySQL: the column names of a result, by the same join that is never\n * true. MySQL has no function that names a value's type, so the types come\n * from the values (`typeOfValues`).\n */\n const namesOf = async (query: string): Promise<string[]> => {\n const key = paging(query).base;\n const known = described.get(key);\n if (known) return known.map((c) => c.name);\n const probe = complete(await sql.query(`SELECT q.* FROM (SELECT 1 AS \\`__one\\`) AS o LEFT JOIN (${query}) AS q ON 1 = 0`));\n if (described.size > 200) described.clear();\n described.set(key, probe.columns);\n return probe.columns.map((c) => c.name);\n };\n\n /**\n * MySQL: each row as one JSON object the database builds, so a decimal is\n * a number and a time is the text the database holds, whatever the server's\n * driver would have made of them (one sends decimals as text and moves\n * times into its own zone). A derived table's order is kept only when it\n * has a limit, so one is added when the query has none.\n */\n const mysqlRows = async (query: string, signal?: AbortSignal): Promise<{ columns: SqlColumn[]; rows: unknown[][] }> => {\n const names = await namesOf(query);\n if (names.length === 0) return complete(await sql.query(query, { signal }));\n const limited = paging(query).limited ? query : `${query} LIMIT 18446744073709551615`;\n const answer = complete(await sql.query(`SELECT JSON_OBJECT(${names.map((name) => `${text(name)}, q.${named(name)}`).join(\", \")}) AS r FROM (${limited}) AS q`, { signal }));\n const rows = answer.rows.map((row) => {\n const parsed: unknown = typeof row[0] === \"string\" ? JSON.parse(row[0]) : row[0];\n if (!isRecord(parsed)) throw new EngineError(\"ENGINE\", \"The data server answered in a form that is not rows.\");\n return names.map((name) => parsed[name] ?? null);\n });\n return { columns: names.map((name, i) => ({ name, type: typeOfValues(rows.map((row) => row[i])) })), rows };\n };\n\n /** Runs a statement and gives its rows with each column's type. */\n const run = async (query: string, signal?: AbortSignal): Promise<{ columns: SqlColumn[]; rows: unknown[][] }> => {\n if (mysql) return mysqlRows(query, signal);\n if (!postgres) return complete(await sql.query(query, { signal }));\n const objects = await jsonRows(query, signal);\n const columns = await describe(query, objects[0] ? Object.keys(objects[0]) : undefined);\n return { columns, rows: objects.map((row) => columns.map((c) => row[c.name] ?? null)) };\n };\n const objectsOf = async (query: string): Promise<Record<string, unknown>[]> => {\n const { columns, rows } = await run(query);\n return rows.map((row) => Object.fromEntries(columns.map((c, i) => [c.name.toLowerCase(), row[i]])));\n };\n\n const schemaFilter = (schema: string) => (schema ? `table_schema = ${text(schema)}` : `table_schema NOT IN ${system}`);\n const find = async (ref: TableRef | undefined) => {\n const table = ref?.table ?? \"\";\n const rows = await objectsOf(\n `SELECT table_schema AS table_schema, table_name AS table_name, table_type AS table_type${mysql ? \", table_comment AS table_comment\" : \"\"} FROM information_schema.tables WHERE lower(table_name) = lower(${text(table)}) AND ${schemaFilter(ref?.schema ?? \"\")} ORDER BY table_schema`,\n );\n if (!rows[0]) throw new EngineError(\"UNKNOWN_TABLE\", `Table not found: ${table}`);\n return { schema: String(rows[0].table_schema), table: String(rows[0].table_name), view: /VIEW/i.test(String(rows[0].table_type)), comment: rows[0].table_comment ? String(rows[0].table_comment) : \"\" };\n };\n\n return {\n kind: postgres ? EngineKind.POSTGRES : mysql ? EngineKind.MYSQL : EngineKind.DUCKDB,\n dialect,\n capabilities: { cancel: false, explain: true, explainJson: false, timeTravel: false, keysetPaging: false, exactCount: true, columnStats: false },\n connections: [{ name: options.dialect, kind: ConnectionKind.HTTP, scope: options.address ?? \"\" }],\n\n async execute(query: string, params: Param[], executeOptions: ExecuteOptions = {}): Promise<EngineResult> {\n if (executeOptions.timeTravel?.at.case) throw new EngineError(\"UNSUPPORTED\", \"This source cannot read tables as of an earlier time.\");\n const result = await run(inlineParams(query, params, dialect), executeOptions.signal);\n const arrow = arrowResult({ columns: result.columns.map((c) => ({ name: c.name, type: c.type ? standardType(c.type) : \"\" })), rows: result.rows });\n async function* batches(): AsyncGenerator<RecordBatch> {\n for (let at = 0; at < result.rows.length; at += batchRows) yield arrow.batch(result.rows.slice(at, at + batchRows));\n }\n return { schema: arrow.schema, batches: batches() };\n },\n\n async explain(query, params) {\n const plan = complete(await sql.query(`EXPLAIN ${inlineParams(query, params, dialect)}`));\n return { planText: plan.rows.map((row) => String(row[row.length - 1] ?? \"\")).join(\"\\n\"), planJson: \"\" };\n },\n\n async check(): Promise<EngineCheck[]> {\n const started = Date.now();\n try {\n const { tool, server } = await sql.describe();\n await sql.query(\"SELECT 1 AS ok\");\n return [{ name: server || options.dialect, ok: true, message: `Reachable through the tool ${tool}`, elapsedMs: Date.now() - started }];\n } catch (error) {\n return [{ name: options.dialect, ok: false, message: error instanceof Error ? error.message : String(error), elapsedMs: Date.now() - started }];\n }\n },\n\n async listCatalogs() {\n const rows = await objectsOf(mysql ? \"SELECT DATABASE() AS name\" : \"SELECT current_database() AS name\");\n return [{ name: String(rows[0]?.name ?? options.dialect) }];\n },\n\n async listSchemas(catalog) {\n const rows = await objectsOf(`SELECT DISTINCT table_schema AS name FROM information_schema.tables WHERE table_schema NOT IN ${system} ORDER BY 1`);\n return rows.map((row) => ({ catalog, name: String(row.name) }));\n },\n\n async listTables({ schema, search }) {\n const like = search ? ` AND lower(table_name) LIKE ${text(`%${search.toLowerCase().replace(/[\\\\%_]/g, \"\\\\$&\")}%`)} ${mysql ? \"\" : `ESCAPE ${text(\"\\\\\")}`}` : \"\";\n const rows = await objectsOf(\n `SELECT table_schema AS table_schema, table_name AS table_name, table_type AS table_type FROM information_schema.tables WHERE ${schemaFilter(schema)}${like} ORDER BY table_schema, table_name LIMIT 1000`,\n );\n return rows.map((row) => ({ ref: { catalog: \"\", schema: String(row.table_schema), table: String(row.table_name) }, kind: /VIEW/i.test(String(row.table_type)) ? TableKind.VIEW : TableKind.TABLE }));\n },\n\n async describeTable(ref, includeStats) {\n const found = await find(ref);\n const at = `table_schema = ${text(found.schema)} AND table_name = ${text(found.table)}`;\n const columns = await objectsOf(\n `SELECT column_name AS column_name, ${mysql ? \"column_type\" : \"data_type\"} AS data_type, is_nullable AS is_nullable, ordinal_position AS ordinal_position${mysql ? \", column_comment AS column_comment\" : \"\"} FROM information_schema.columns WHERE ${at} ORDER BY ordinal_position`,\n );\n // Keys and comments are extras: a database or a login that will not give them leaves them out, it does not fail the description.\n const optional = async (query: string) => objectsOf(query).catch(() => []);\n const keys = await optional(\n mysql\n ? `SELECT column_name AS column_name FROM information_schema.key_column_usage WHERE constraint_name = 'PRIMARY' AND ${at}`\n : postgres\n ? // pg_catalog, because information_schema shows a table's constraints only to a role that owns it or may write to it.\n `SELECT a.attname AS column_name FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ANY (con.conkey) WHERE con.contype = 'p' AND n.nspname = ${text(found.schema)} AND c.relname = ${text(found.table)}`\n : `SELECT kcu.column_name FROM information_schema.table_constraints tc JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema AND kcu.table_name = tc.table_name WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = ${text(found.schema)} AND tc.table_name = ${text(found.table)}`,\n );\n const primary = new Set(keys.map((row) => String(row.column_name)));\n const comments = postgres\n ? await optional(\n `SELECT a.attname AS column_name, col_description(c.oid, a.attnum) AS comment, obj_description(c.oid) AS table_comment FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped WHERE n.nspname = ${text(found.schema)} AND c.relname = ${text(found.table)}`,\n )\n : [];\n const comment = new Map((mysql ? columns.map((row) => ({ column_name: row.column_name, comment: row.column_comment })) : comments).map((row) => [String(row.column_name), row.comment ? String(row.comment) : \"\"]));\n const references = postgres\n ? await optional(\n `SELECT con.conname AS name, a.attname AS column_name, fn.nspname AS ref_schema, fc.relname AS ref_table, fa.attname AS ref_column, k.ord FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_class fc ON fc.oid = con.confrelid JOIN pg_namespace fn ON fn.oid = fc.relnamespace CROSS JOIN LATERAL unnest(con.conkey, con.confkey) WITH ORDINALITY AS k(col, fcol, ord) JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = k.col JOIN pg_attribute fa ON fa.attrelid = fc.oid AND fa.attnum = k.fcol WHERE con.contype = 'f' AND n.nspname = ${text(found.schema)} AND c.relname = ${text(found.table)} ORDER BY con.conname, k.ord`,\n )\n : mysql\n ? await optional(\n `SELECT constraint_name AS name, column_name AS column_name, referenced_table_schema AS ref_schema, referenced_table_name AS ref_table, referenced_column_name AS ref_column FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL AND ${at} ORDER BY constraint_name, ordinal_position`,\n )\n : [];\n const foreign = new Map<string, { columns: string[]; references: { catalog: string; schema: string; table: string }; referencedColumns: string[] }>();\n for (const row of references) {\n const key = foreign.get(String(row.name)) ?? { columns: [], references: { catalog: \"\", schema: String(row.ref_schema), table: String(row.ref_table) }, referencedColumns: [] };\n key.columns.push(String(row.column_name));\n key.referencedColumns.push(String(row.ref_column));\n foreign.set(String(row.name), key);\n }\n const counted = includeStats ? (await objectsOf(`SELECT COUNT(*) AS n FROM ${named(found.schema)}.${named(found.table)}`))[0]?.n : undefined;\n return {\n summary: { ref: { catalog: \"\", schema: found.schema, table: found.table }, kind: found.view ? TableKind.VIEW : TableKind.TABLE, comment: found.comment || (comments[0]?.table_comment ? String(comments[0].table_comment) : \"\") },\n columns: columns.map((row, i) => {\n const native = String(row.data_type);\n return { name: String(row.column_name), nativeType: native, arrowType: String(columnType(standardType(native)).arrow), nullable: String(row.is_nullable).toUpperCase() !== \"NO\", ordinal: Number(row.ordinal_position ?? i + 1), primaryKey: primary.has(String(row.column_name)), comment: comment.get(String(row.column_name)) ?? \"\" };\n }),\n rowCount: counted === undefined || counted === null ? undefined : BigInt(counted as number | string | bigint),\n foreignKeys: [...foreign.values()],\n };\n },\n\n listSnapshots: async () => [],\n async version() {\n const rows = await objectsOf(postgres ? \"SELECT current_setting('server_version') AS v\" : \"SELECT VERSION() AS v\");\n const { server } = await sql.describe();\n return `${postgres ? \"PostgreSQL\" : mysql ? \"MySQL\" : \"DuckDB\"} ${String(rows[0]?.v ?? \"\")}${server ? ` through ${server}` : \"\"}`.trim();\n },\n close: () => sql.close(),\n };\n}\n"]}
@@ -0,0 +1,4 @@
1
+ export { type McpEngineSettings, createMcpEngineOver, standardType, teradataMcpClient, typeOfValues } from "./engine.js";
2
+ export { inlineParams, literal } from "./literal.js";
3
+ export { type SqlColumn, type SqlRows, type ToolAnswer, readRows, toolError } from "./parse.js";
4
+ export { type ListedTool, type McpSql, type QueryToolOptions, type ToolCaller, databaseError, findQueryTool, sqlOver } from "./sql.js";
package/dist/hosted.js ADDED
@@ -0,0 +1,8 @@
1
+ // The parts that need no MCP connection of their own: for a page whose host
2
+ // already holds the connection and calls tools for it (`ToolCaller`). Nothing
3
+ // here imports the MCP client, so a browser bundle does not carry it.
4
+ export { createMcpEngineOver, standardType, teradataMcpClient, typeOfValues } from "./engine.js";
5
+ export { inlineParams, literal } from "./literal.js";
6
+ export { readRows, toolError } from "./parse.js";
7
+ export { databaseError, findQueryTool, sqlOver } from "./sql.js";
8
+ //# sourceMappingURL=hosted.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hosted.js","sourceRoot":"","sources":["../src/hosted.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,8EAA8E;AAC9E,sEAAsE;AACtE,OAAO,EAA0B,mBAAmB,EAAE,YAAY,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACzH,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACrD,OAAO,EAAiD,QAAQ,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAChG,OAAO,EAAwE,aAAa,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC","sourcesContent":["// The parts that need no MCP connection of their own: for a page whose host\n// already holds the connection and calls tools for it (`ToolCaller`). Nothing\n// here imports the MCP client, so a browser bundle does not carry it.\nexport { type McpEngineSettings, createMcpEngineOver, standardType, teradataMcpClient, typeOfValues } from \"./engine.js\";\nexport { inlineParams, literal } from \"./literal.js\";\nexport { type SqlColumn, type SqlRows, type ToolAnswer, readRows, toolError } from \"./parse.js\";\nexport { type ListedTool, type McpSql, type QueryToolOptions, type ToolCaller, databaseError, findQueryTool, sqlOver } from \"./sql.js\";\n"]}
@@ -0,0 +1,22 @@
1
+ import type { Transport } from "@modelcontextprotocol/client";
2
+ import type { Engine } from "@surfaces-ui/engine";
3
+ import { type McpSqlOptions } from "./client.js";
4
+ import { type McpEngineSettings } from "./engine.js";
5
+ export { type ListedTool, type McpSql, type McpSqlOptions, type QueryToolOptions, type ToolCaller, DATABASE_CALL, databaseError, findQueryTool, mcpSql, sqlOver } from "./client.js";
6
+ export { type McpEngineSettings, createMcpEngineOver, standardType, teradataMcpClient, typeOfValues } from "./engine.js";
7
+ export interface McpEngineOptions extends McpSqlOptions, McpEngineSettings {
8
+ }
9
+ /** The engine over a database's MCP server that this process connects to. */
10
+ export declare function createMcpEngine(options: McpEngineOptions): Promise<Engine>;
11
+ export { inlineParams, literal } from "./literal.js";
12
+ export { type SqlColumn, type SqlRows, type ToolAnswer, readRows, toolError } from "./parse.js";
13
+ export { pythonLiteral } from "./python.js";
14
+ /**
15
+ * A database's MCP server over Streamable HTTP. `token` is called per
16
+ * connection and its value sent as a bearer token; the host reads it from
17
+ * its own environment or vault, never from config.
18
+ */
19
+ export declare function httpServer(url: string, options?: {
20
+ token?(): string | undefined;
21
+ headers?: Record<string, string>;
22
+ }): () => Transport;
package/dist/index.js ADDED
@@ -0,0 +1,24 @@
1
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
2
+ import { mcpSql } from "./client.js";
3
+ import { createMcpEngineOver } from "./engine.js";
4
+ export { DATABASE_CALL, databaseError, findQueryTool, mcpSql, sqlOver } from "./client.js";
5
+ export { createMcpEngineOver, standardType, teradataMcpClient, typeOfValues } from "./engine.js";
6
+ /** The engine over a database's MCP server that this process connects to. */
7
+ export function createMcpEngine(options) {
8
+ return createMcpEngineOver((always) => mcpSql({ ...options, arguments: { ...always, ...options.arguments } }), options);
9
+ }
10
+ export { inlineParams, literal } from "./literal.js";
11
+ export { readRows, toolError } from "./parse.js";
12
+ export { pythonLiteral } from "./python.js";
13
+ /**
14
+ * A database's MCP server over Streamable HTTP. `token` is called per
15
+ * connection and its value sent as a bearer token; the host reads it from
16
+ * its own environment or vault, never from config.
17
+ */
18
+ export function httpServer(url, options = {}) {
19
+ return () => {
20
+ const token = options.token?.();
21
+ return new StreamableHTTPClientTransport(new URL(url), { requestInit: { headers: { ...options.headers, ...(token ? { Authorization: `Bearer ${token}` } : {}) } } });
22
+ };
23
+ }
24
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,6BAA6B,EAAE,MAAM,8BAA8B,CAAC;AAI7E,OAAO,EAAsB,MAAM,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAA0B,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAE1E,OAAO,EAA4F,aAAa,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACrL,OAAO,EAA0B,mBAAmB,EAAE,YAAY,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAIzH,6EAA6E;AAC7E,MAAM,UAAU,eAAe,CAAC,OAAyB;IACvD,OAAO,mBAAmB,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,EAAE,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC;AAC1H,CAAC;AACD,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACrD,OAAO,EAAiD,QAAQ,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAChG,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C;;;;GAIG;AACH,MAAM,UAAU,UAAU,CAAC,GAAW,EAAE,OAAO,GAAuE,EAAE;IACtH,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 { StreamableHTTPClientTransport } from \"@modelcontextprotocol/client\";\nimport type { Transport } from \"@modelcontextprotocol/client\";\n\nimport type { Engine } from \"@surfaces-ui/engine\";\nimport { type McpSqlOptions, mcpSql } from \"./client.js\";\nimport { type McpEngineSettings, createMcpEngineOver } from \"./engine.js\";\n\nexport { type ListedTool, type McpSql, type McpSqlOptions, type QueryToolOptions, type ToolCaller, DATABASE_CALL, databaseError, findQueryTool, mcpSql, sqlOver } from \"./client.js\";\nexport { type McpEngineSettings, createMcpEngineOver, standardType, teradataMcpClient, typeOfValues } from \"./engine.js\";\n\nexport interface McpEngineOptions extends McpSqlOptions, McpEngineSettings {}\n\n/** The engine over a database's MCP server that this process connects to. */\nexport function createMcpEngine(options: McpEngineOptions): Promise<Engine> {\n return createMcpEngineOver((always) => mcpSql({ ...options, arguments: { ...always, ...options.arguments } }), options);\n}\nexport { inlineParams, literal } from \"./literal.js\";\nexport { type SqlColumn, type SqlRows, type ToolAnswer, readRows, toolError } from \"./parse.js\";\nexport { pythonLiteral } from \"./python.js\";\n\n/**\n * A database's MCP server over Streamable HTTP. `token` is called per\n * connection and its value sent as a bearer token; the host reads it from\n * its own environment or vault, never from config.\n */\nexport function httpServer(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,27 @@
1
+ import { type Param } from "@surfaces-ui/engine";
2
+ import { SqlDialect } from "@surfaces-ui/proto";
3
+ /**
4
+ * One value as SQL text. A database's MCP server takes a statement and
5
+ * nothing else, so values cannot be bound; they are written so that no value
6
+ * can change the statement.
7
+ *
8
+ * - Numbers are checked to be numbers.
9
+ * - Postgres text is dollar-quoted with a tag the value does not contain. A
10
+ * dollar-quoted string has no escapes at all, whatever the server's
11
+ * `standard_conforming_strings`, and is an untyped literal, so it compares
12
+ * with a date or a number column as a bound value would.
13
+ * - MySQL text is written as hexadecimal and decoded by the database, since
14
+ * MySQL reads a backslash in a string as an escape and a session setting
15
+ * can change that; hexadecimal digits have no such reading. MySQL compares
16
+ * text with a date or a number column without being told to.
17
+ * - DuckDB and Teradata text is single-quoted with quotes doubled. Neither
18
+ * reads a backslash as an escape in a plain string, so a doubled quote is
19
+ * the only thing with meaning inside one.
20
+ */
21
+ export declare function literal(value: Param, dialect: SqlDialect): string;
22
+ /**
23
+ * Replaces the placeholders the SQL rewriter produced (`?`, or `$1` for
24
+ * Postgres) with values. Placeholders inside string literals, quoted names
25
+ * and comments are left alone, and every placeholder must have a value.
26
+ */
27
+ export declare function inlineParams(sql: string, params: Param[], dialect: SqlDialect): string;
@@ -0,0 +1,70 @@
1
+ import { EngineError } from "@surfaces-ui/engine";
2
+ import { SqlDialect } from "@surfaces-ui/proto";
3
+ import { blankLiterals } from "@surfaces-ui/sql";
4
+ /**
5
+ * One value as SQL text. A database's MCP server takes a statement and
6
+ * nothing else, so values cannot be bound; they are written so that no value
7
+ * can change the statement.
8
+ *
9
+ * - Numbers are checked to be numbers.
10
+ * - Postgres text is dollar-quoted with a tag the value does not contain. A
11
+ * dollar-quoted string has no escapes at all, whatever the server's
12
+ * `standard_conforming_strings`, and is an untyped literal, so it compares
13
+ * with a date or a number column as a bound value would.
14
+ * - MySQL text is written as hexadecimal and decoded by the database, since
15
+ * MySQL reads a backslash in a string as an escape and a session setting
16
+ * can change that; hexadecimal digits have no such reading. MySQL compares
17
+ * text with a date or a number column without being told to.
18
+ * - DuckDB and Teradata text is single-quoted with quotes doubled. Neither
19
+ * reads a backslash as an escape in a plain string, so a doubled quote is
20
+ * the only thing with meaning inside one.
21
+ */
22
+ export function literal(value, dialect) {
23
+ if (typeof value === "bigint")
24
+ return value.toString();
25
+ if (typeof value === "number") {
26
+ if (!Number.isFinite(value))
27
+ throw new EngineError("UNSUPPORTED", "A filter value is not a finite number.");
28
+ return String(value);
29
+ }
30
+ if (typeof value === "boolean")
31
+ return dialect === SqlDialect.TERADATA ? (value ? "1" : "0") : value ? "TRUE" : "FALSE";
32
+ if (value.includes("\0"))
33
+ throw new EngineError("UNSUPPORTED", "A filter value holds a character a database cannot take.");
34
+ if (dialect === SqlDialect.POSTGRES) {
35
+ let tag = "v";
36
+ while (value.includes(`$${tag}$`))
37
+ tag += "v";
38
+ return `$${tag}$${value}$${tag}$`;
39
+ }
40
+ if (dialect === SqlDialect.MYSQL)
41
+ return `CONVERT(X'${Array.from(new TextEncoder().encode(value), (byte) => byte.toString(16).padStart(2, "0")).join("")}' USING utf8mb4)`;
42
+ if (dialect === SqlDialect.DUCKDB || dialect === SqlDialect.TERADATA)
43
+ return `'${value.replace(/'/g, "''")}'`;
44
+ throw new EngineError("UNSUPPORTED", "This SQL dialect cannot be sent to a data server yet.");
45
+ }
46
+ /**
47
+ * Replaces the placeholders the SQL rewriter produced (`?`, or `$1` for
48
+ * Postgres) with values. Placeholders inside string literals, quoted names
49
+ * and comments are left alone, and every placeholder must have a value.
50
+ */
51
+ export function inlineParams(sql, params, dialect) {
52
+ if (params.length === 0)
53
+ return sql;
54
+ const bare = blankLiterals(sql, dialect === SqlDialect.MYSQL);
55
+ const numbered = dialect === SqlDialect.POSTGRES;
56
+ let out = "";
57
+ let at = 0;
58
+ let next = 0;
59
+ for (const match of bare.matchAll(numbered ? /\$(\d+)/g : /\?/g)) {
60
+ const index = numbered ? Number(match[1]) - 1 : next++;
61
+ if (index < 0 || index >= params.length)
62
+ throw new EngineError("ENGINE", "The query refers to a value that was not given.");
63
+ out += sql.slice(at, match.index) + literal(params[index], dialect);
64
+ at = match.index + match[0].length;
65
+ }
66
+ if (!numbered && next !== params.length)
67
+ throw new EngineError("ENGINE", "The query was given more values than it has places for.");
68
+ return out + sql.slice(at);
69
+ }
70
+ //# sourceMappingURL=literal.js.map