@brainbox-labs/sdk 0.0.0-stage → 0.22.1

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.
@@ -0,0 +1,63 @@
1
+ import {
2
+ convertToMarkdown,
3
+ convertedName,
4
+ expandDocPatterns,
5
+ htmlToMarkdown,
6
+ inlineText,
7
+ needsConversion
8
+ } from "../chunk-ANGBZHCB.js";
9
+ import {
10
+ ColumnProfiler,
11
+ connectAndProfile,
12
+ detectDialect,
13
+ detectFormatHint,
14
+ extractJsonShape,
15
+ parseProfileMode,
16
+ parseSkipColumns,
17
+ quoteIdentifier
18
+ } from "../chunk-VEXUCOXR.js";
19
+ import {
20
+ introspectTrinoSchema,
21
+ introspectTrinoSchemaWithConnection,
22
+ openTrinoConnection,
23
+ parseTrinoUrl
24
+ } from "../chunk-43LDD7YT.js";
25
+ import {
26
+ introspectAthenaSchema,
27
+ introspectAthenaSchemaWithConnection,
28
+ openAthenaConnection,
29
+ parseAthenaUrl
30
+ } from "../chunk-YRH35U57.js";
31
+ import {
32
+ SUPPORTED_INTROSPECTION_DIALECTS,
33
+ detectIntrospectionDialect,
34
+ introspectDatabaseSchema
35
+ } from "../chunk-AJR44IFE.js";
36
+ import "../chunk-MLKGABMK.js";
37
+ export {
38
+ ColumnProfiler,
39
+ SUPPORTED_INTROSPECTION_DIALECTS,
40
+ connectAndProfile,
41
+ convertToMarkdown,
42
+ convertedName,
43
+ detectDialect,
44
+ detectFormatHint,
45
+ detectIntrospectionDialect,
46
+ expandDocPatterns,
47
+ extractJsonShape,
48
+ htmlToMarkdown,
49
+ inlineText,
50
+ introspectAthenaSchema,
51
+ introspectAthenaSchemaWithConnection,
52
+ introspectDatabaseSchema,
53
+ introspectTrinoSchema,
54
+ introspectTrinoSchemaWithConnection,
55
+ needsConversion,
56
+ openAthenaConnection,
57
+ openTrinoConnection,
58
+ parseAthenaUrl,
59
+ parseProfileMode,
60
+ parseSkipColumns,
61
+ parseTrinoUrl,
62
+ quoteIdentifier
63
+ };
@@ -0,0 +1,9 @@
1
+ import {
2
+ IngestPartialFailureError,
3
+ performIngest
4
+ } from "./chunk-OOHPBQXX.js";
5
+ import "./chunk-MLKGABMK.js";
6
+ export {
7
+ IngestPartialFailureError,
8
+ performIngest
9
+ };
@@ -0,0 +1,11 @@
1
+ import {
2
+ SUPPORTED_INTROSPECTION_DIALECTS,
3
+ detectIntrospectionDialect,
4
+ introspectDatabaseSchema
5
+ } from "./chunk-AJR44IFE.js";
6
+ import "./chunk-MLKGABMK.js";
7
+ export {
8
+ SUPPORTED_INTROSPECTION_DIALECTS,
9
+ detectIntrospectionDialect,
10
+ introspectDatabaseSchema
11
+ };
@@ -0,0 +1,150 @@
1
+ import "./chunk-MLKGABMK.js";
2
+
3
+ // src/ingest/schema-reader.ts
4
+ import pg from "pg";
5
+ var { Client } = pg;
6
+ async function introspectSchema(connectionString) {
7
+ const client = new Client({ connectionString });
8
+ await client.connect();
9
+ try {
10
+ const tablesResult = await client.query(`
11
+ SELECT table_name, table_schema
12
+ FROM information_schema.tables
13
+ WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
14
+ AND table_type = 'BASE TABLE'
15
+ ORDER BY table_name
16
+ `);
17
+ const tables = [];
18
+ for (const tableRow of tablesResult.rows) {
19
+ const tableName = tableRow.table_name;
20
+ const tableSchema = tableRow.table_schema;
21
+ const columnsResult = await client.query(
22
+ `SELECT column_name, data_type, is_nullable, column_default
23
+ FROM information_schema.columns
24
+ WHERE table_schema = $1 AND table_name = $2
25
+ ORDER BY ordinal_position`,
26
+ [tableSchema, tableName]
27
+ );
28
+ const pkResult = await client.query(
29
+ `SELECT kcu.column_name
30
+ FROM information_schema.table_constraints tc
31
+ JOIN information_schema.key_column_usage kcu
32
+ ON tc.constraint_name = kcu.constraint_name
33
+ WHERE tc.constraint_type = 'PRIMARY KEY'
34
+ AND tc.table_schema = $1
35
+ AND tc.table_name = $2`,
36
+ [tableSchema, tableName]
37
+ );
38
+ const primaryKeyColumns = new Set(pkResult.rows.map((r) => r.column_name));
39
+ const fkResult = await client.query(
40
+ `SELECT kcu.column_name, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name
41
+ FROM information_schema.table_constraints tc
42
+ JOIN information_schema.key_column_usage kcu
43
+ ON tc.constraint_name = kcu.constraint_name
44
+ JOIN information_schema.constraint_column_usage ccu
45
+ ON tc.constraint_name = ccu.constraint_name
46
+ WHERE tc.constraint_type = 'FOREIGN KEY'
47
+ AND tc.table_schema = $1
48
+ AND tc.table_name = $2`,
49
+ [tableSchema, tableName]
50
+ );
51
+ const fkMap = /* @__PURE__ */ new Map();
52
+ for (const fk of fkResult.rows) {
53
+ fkMap.set(fk.column_name, {
54
+ table: fk.foreign_table_name,
55
+ column: fk.foreign_column_name
56
+ });
57
+ }
58
+ const columns = columnsResult.rows.map((col) => {
59
+ const fkRef = fkMap.get(col.column_name);
60
+ const column = {
61
+ name: col.column_name,
62
+ type: col.data_type,
63
+ nullable: col.is_nullable === "YES",
64
+ isPrimaryKey: primaryKeyColumns.has(col.column_name),
65
+ isForeignKey: fkMap.has(col.column_name)
66
+ };
67
+ if (fkRef !== void 0) column.references = fkRef;
68
+ if (col.column_default !== null) column.defaultValue = col.column_default;
69
+ return column;
70
+ });
71
+ const indexResult = await client.query(
72
+ `SELECT i.relname AS index_name, a.attname AS column_name, ix.indisunique AS is_unique
73
+ FROM pg_class t
74
+ JOIN pg_index ix ON t.oid = ix.indrelid
75
+ JOIN pg_class i ON i.oid = ix.indexrelid
76
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
77
+ WHERE t.relkind = 'r' AND t.relname = $1
78
+ ORDER BY i.relname`,
79
+ [tableName]
80
+ );
81
+ const indexMap = /* @__PURE__ */ new Map();
82
+ for (const idxRow of indexResult.rows) {
83
+ const existing = indexMap.get(idxRow.index_name);
84
+ if (existing !== void 0) {
85
+ existing.columns.push(idxRow.column_name);
86
+ } else {
87
+ indexMap.set(idxRow.index_name, {
88
+ columns: [idxRow.column_name],
89
+ isUnique: idxRow.is_unique
90
+ });
91
+ }
92
+ }
93
+ const indexes = Array.from(indexMap.entries()).map(([name, val]) => ({
94
+ name,
95
+ columns: val.columns,
96
+ isUnique: val.isUnique
97
+ }));
98
+ const constraintResult = await client.query(
99
+ `SELECT tc.constraint_name, tc.constraint_type, kcu.column_name
100
+ FROM information_schema.table_constraints tc
101
+ JOIN information_schema.key_column_usage kcu
102
+ ON tc.constraint_name = kcu.constraint_name
103
+ WHERE tc.table_schema = $1 AND tc.table_name = $2`,
104
+ [tableSchema, tableName]
105
+ );
106
+ const constraintMap = /* @__PURE__ */ new Map();
107
+ for (const cRow of constraintResult.rows) {
108
+ const existing = constraintMap.get(cRow.constraint_name);
109
+ if (existing !== void 0) {
110
+ existing.columns.push(cRow.column_name);
111
+ } else {
112
+ constraintMap.set(cRow.constraint_name, {
113
+ type: cRow.constraint_type,
114
+ columns: [cRow.column_name]
115
+ });
116
+ }
117
+ }
118
+ const constraints = Array.from(constraintMap.entries()).map(([name, val]) => {
119
+ const type = val.type;
120
+ const constraint = { name, type, columns: val.columns };
121
+ if (type === "FOREIGN KEY") {
122
+ const firstCol = val.columns[0];
123
+ if (firstCol !== void 0) {
124
+ const fkRef = fkMap.get(firstCol);
125
+ if (fkRef !== void 0) {
126
+ constraint.referencedTable = fkRef.table;
127
+ constraint.referencedColumns = [fkRef.column];
128
+ }
129
+ }
130
+ }
131
+ return constraint;
132
+ }).filter(
133
+ (c) => c.type === "PRIMARY KEY" || c.type === "FOREIGN KEY" || c.type === "UNIQUE" || c.type === "CHECK"
134
+ );
135
+ tables.push({
136
+ name: tableName,
137
+ schema: tableSchema,
138
+ columns,
139
+ indexes,
140
+ constraints
141
+ });
142
+ }
143
+ return { tables, extractedAt: (/* @__PURE__ */ new Date()).toISOString() };
144
+ } finally {
145
+ await client.end();
146
+ }
147
+ }
148
+ export {
149
+ introspectSchema
150
+ };
@@ -0,0 +1,2 @@
1
+ export { C as ContextTool, b as CustomExecutor, a as MCP, M as MCPOptions, c as MiddlewareFn, S as SqlClient, d as StartOptions, T as ToolContext, e as ToolHandlerFn } from '../index-qV0gq2eJ.js';
2
+ export { ContextToolExecution, ContextToolInputSchema } from '@brainbox-labs/types';
@@ -0,0 +1,7 @@
1
+ import {
2
+ MCP
3
+ } from "../chunk-YWH6IOQG.js";
4
+ import "../chunk-MLKGABMK.js";
5
+ export {
6
+ MCP
7
+ };
@@ -0,0 +1,198 @@
1
+ import "./chunk-MLKGABMK.js";
2
+
3
+ // src/ingest/sql-parser.ts
4
+ import { parse } from "pgsql-ast-parser";
5
+ import * as fs from "fs/promises";
6
+ import * as path from "path";
7
+ function extractQueryName(filename, sql) {
8
+ const lines = sql.split("\n");
9
+ for (const line of lines) {
10
+ const trimmed = line.trim();
11
+ if (!trimmed.startsWith("--")) break;
12
+ const nameMatch = trimmed.match(/^--\s*name:\s*(\S+)/i);
13
+ if (nameMatch !== null && nameMatch[1] !== void 0) return nameMatch[1];
14
+ const singleWordMatch = trimmed.match(/^--\s+([A-Za-z][A-Za-z0-9_]+)\s*$/);
15
+ if (singleWordMatch !== null && singleWordMatch[1] !== void 0) return singleWordMatch[1];
16
+ }
17
+ return path.basename(filename, path.extname(filename));
18
+ }
19
+ function extractComments(sql) {
20
+ const comments = [];
21
+ for (const line of sql.split("\n")) {
22
+ const trimmed = line.trim();
23
+ if (trimmed.startsWith("--")) comments.push(trimmed);
24
+ }
25
+ return comments;
26
+ }
27
+ function inferParameterName(sql, position) {
28
+ const paramToken = `$${position}`;
29
+ const pattern = /(\w+)\s*(?:=|>|<|>=|<=|LIKE|ILIKE|!=|<>)\s*\$(\d+)/gi;
30
+ let match;
31
+ while ((match = pattern.exec(sql)) !== null) {
32
+ if (match[2] === String(position)) return match[1] ?? paramToken;
33
+ }
34
+ return paramToken;
35
+ }
36
+ function extractParameters(sql) {
37
+ const paramRegex = /\$(\d+)/g;
38
+ const seen = /* @__PURE__ */ new Set();
39
+ const params = [];
40
+ let match;
41
+ while ((match = paramRegex.exec(sql)) !== null) {
42
+ const pos = parseInt(match[1] ?? "0", 10);
43
+ if (!seen.has(pos)) {
44
+ seen.add(pos);
45
+ params.push({ position: pos, inferredName: inferParameterName(sql, pos) });
46
+ }
47
+ }
48
+ params.sort((a, b) => a.position - b.position);
49
+ return params;
50
+ }
51
+ function collectTablesFromFrom(froms, tables) {
52
+ if (!froms) return;
53
+ for (const from of froms) {
54
+ if (from.type === "table") {
55
+ const ft = from;
56
+ tables.add(ft.name.name.toLowerCase());
57
+ } else if (from.type === "statement") {
58
+ walkStatementForTables(from.statement, tables);
59
+ }
60
+ }
61
+ }
62
+ function walkStatementForTables(stmt, tables) {
63
+ if (stmt.type === "select") {
64
+ const sel = stmt;
65
+ collectTablesFromFrom(sel.from ?? null, tables);
66
+ } else if (stmt.type === "with" || stmt.type === "with recursive") {
67
+ if ("bind" in stmt && Array.isArray(stmt.bind)) {
68
+ for (const binding of stmt.bind) {
69
+ if ("statement" in binding) walkStatementForTables(binding.statement, tables);
70
+ }
71
+ }
72
+ if ("in" in stmt) walkStatementForTables(stmt.in, tables);
73
+ } else if (stmt.type === "union" || stmt.type === "union all") {
74
+ walkStatementForTables(stmt.left, tables);
75
+ walkStatementForTables(stmt.right, tables);
76
+ }
77
+ }
78
+ function collectColumnsFromSelect(columns, selected) {
79
+ if (!columns) return;
80
+ for (const col of columns) {
81
+ const expr = col.expr;
82
+ if (expr && "type" in expr && expr.type === "ref") {
83
+ const ref = expr;
84
+ if (ref.name !== "*") selected.push(ref.name.toLowerCase());
85
+ }
86
+ }
87
+ }
88
+ function collectColumnsFromWhere(where, filtered) {
89
+ if (!where) return;
90
+ if ("type" in where && where.type === "binary") {
91
+ const bin = where;
92
+ if ("type" in bin.left && bin.left.type === "ref") {
93
+ const ref = bin.left;
94
+ if (ref.name !== "*") filtered.push(ref.name.toLowerCase());
95
+ }
96
+ collectColumnsFromWhere(bin.left, filtered);
97
+ collectColumnsFromWhere(bin.right, filtered);
98
+ }
99
+ }
100
+ function formatExprRef(expr) {
101
+ if (!expr || !("type" in expr)) return null;
102
+ if (expr.type === "ref") {
103
+ const ref = expr;
104
+ if (ref.table) return `${ref.table.name}.${ref.name}`;
105
+ return ref.name;
106
+ }
107
+ return null;
108
+ }
109
+ function buildJoinPatterns(froms) {
110
+ if (!froms) return [];
111
+ const patterns = [];
112
+ for (const from of froms) {
113
+ if (from.type === "table") {
114
+ const ft = from;
115
+ if (ft.join) {
116
+ const joinType = ft.join.type;
117
+ const tableName = ft.name.name;
118
+ let onClause = "";
119
+ if (ft.join.on && "type" in ft.join.on && ft.join.on.type === "binary") {
120
+ const bin = ft.join.on;
121
+ const left = formatExprRef(bin.left);
122
+ const right = formatExprRef(bin.right);
123
+ if (left && right) onClause = ` ON ${left} = ${right}`;
124
+ }
125
+ patterns.push(`${joinType} ${tableName}${onClause}`);
126
+ }
127
+ }
128
+ }
129
+ return patterns;
130
+ }
131
+ function parseSqlFile(filename, sql, warnings) {
132
+ const name = extractQueryName(filename, sql);
133
+ const comments = extractComments(sql);
134
+ const parameters = extractParameters(sql);
135
+ const tablesReferenced = [];
136
+ const columnsSelected = [];
137
+ const columnsFiltered = [];
138
+ const joinPatterns = [];
139
+ try {
140
+ const statements = parse(sql);
141
+ for (const stmt of statements) {
142
+ const tableSet = /* @__PURE__ */ new Set();
143
+ walkStatementForTables(stmt, tableSet);
144
+ for (const t of tableSet) {
145
+ if (!tablesReferenced.includes(t)) tablesReferenced.push(t);
146
+ }
147
+ if (stmt.type === "select") {
148
+ const sel = stmt;
149
+ collectColumnsFromSelect(sel.columns ?? null, columnsSelected);
150
+ collectColumnsFromWhere(sel.where ?? null, columnsFiltered);
151
+ joinPatterns.push(...buildJoinPatterns(sel.from ?? null));
152
+ }
153
+ }
154
+ } catch (err) {
155
+ const msg = err instanceof Error ? err.message : String(err);
156
+ warnings?.push(`SQL parse failed for ${filename}: ${msg}`);
157
+ }
158
+ return {
159
+ name,
160
+ filename,
161
+ sql,
162
+ tablesReferenced,
163
+ columnsSelected: [...new Set(columnsSelected)],
164
+ columnsFiltered: [...new Set(columnsFiltered)],
165
+ joinPatterns,
166
+ parameters,
167
+ comments
168
+ };
169
+ }
170
+ async function parseSqlDirectory(dirPath, warnings) {
171
+ const entries = await fs.readdir(dirPath);
172
+ const sqlFiles = entries.filter((f) => f.endsWith(".sql"));
173
+ const results = [];
174
+ for (const file of sqlFiles) {
175
+ const filePath = path.join(dirPath, file);
176
+ const content = await fs.readFile(filePath, "utf-8");
177
+ results.push(parseSqlFile(file, content, warnings));
178
+ }
179
+ return results;
180
+ }
181
+ async function parseSqlInputs(inputs, warnings) {
182
+ const results = [];
183
+ for (const input of inputs) {
184
+ const stat2 = await fs.stat(input);
185
+ if (stat2.isDirectory()) {
186
+ results.push(...await parseSqlDirectory(input, warnings));
187
+ } else {
188
+ const content = await fs.readFile(input, "utf-8");
189
+ results.push(parseSqlFile(input, content, warnings));
190
+ }
191
+ }
192
+ return results;
193
+ }
194
+ export {
195
+ parseSqlDirectory,
196
+ parseSqlFile,
197
+ parseSqlInputs
198
+ };
@@ -0,0 +1,13 @@
1
+ import {
2
+ introspectTrinoSchema,
3
+ introspectTrinoSchemaWithConnection,
4
+ openTrinoConnection,
5
+ parseTrinoUrl
6
+ } from "./chunk-43LDD7YT.js";
7
+ import "./chunk-MLKGABMK.js";
8
+ export {
9
+ introspectTrinoSchema,
10
+ introspectTrinoSchemaWithConnection,
11
+ openTrinoConnection,
12
+ parseTrinoUrl
13
+ };
package/package.json CHANGED
@@ -1,6 +1,81 @@
1
1
  {
2
2
  "name": "@brainbox-labs/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.22.1",
4
+ "description": "BrainBox JavaScript/TypeScript SDK — MCP server + API client",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "bin": {
9
+ "brainbox-mcp": "./dist/bin.js"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "import": "./dist/index.js",
14
+ "types": "./dist/index.d.ts"
15
+ },
16
+ "./serve": {
17
+ "import": "./dist/serve/index.js",
18
+ "types": "./dist/serve/index.d.ts"
19
+ },
20
+ "./ingest": {
21
+ "import": "./dist/ingest/public.js",
22
+ "types": "./dist/ingest/public.d.ts"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "scripts": {
29
+ "build": "tsup",
30
+ "lint": "tsc --noEmit",
31
+ "test": "vitest run"
32
+ },
33
+ "dependencies": {
34
+ "@brainbox-labs/api": "*",
35
+ "@brainbox-labs/types": "^1.30.0",
36
+ "@modelcontextprotocol/sdk": "^1.27.1",
37
+ "dotenv": "^16.4.5",
38
+ "express": "^5.0.0",
39
+ "glob": "^11.0.0",
40
+ "pg": "^8.13.3",
41
+ "pgsql-ast-parser": "^12.0.2"
42
+ },
43
+ "optionalDependencies": {
44
+ "@aws-sdk/client-athena": "^3.1088.0",
45
+ "@duckdb/node-api": "^1.5.3-r.3",
46
+ "better-sqlite3": "^12.10.0",
47
+ "mammoth": "^1.12.0",
48
+ "mysql2": "^3.11.3",
49
+ "pdf-parse": "^2.4.5",
50
+ "trino-client": "^0.2.9",
51
+ "turndown": "^7.2.4"
52
+ },
53
+ "devDependencies": {
54
+ "@types/better-sqlite3": "^7.6.13",
55
+ "@types/express": "^5.0.0",
56
+ "@types/pg": "^8.11.10",
57
+ "@types/turndown": "^5.0.6",
58
+ "tsup": "^8.1.0",
59
+ "typescript": "^5.4.5",
60
+ "vitest": "^2.0.0"
61
+ },
62
+ "engines": {
63
+ "node": ">=18"
64
+ },
65
+ "keywords": [
66
+ "brainbox",
67
+ "semantic-layer",
68
+ "sdk",
69
+ "mcp"
70
+ ],
71
+ "license": "Apache-2.0",
72
+ "repository": {
73
+ "type": "git",
74
+ "url": "git+https://github.com/brainbox-labs/ctx-layer-clients.git",
75
+ "directory": "packages/sdk"
76
+ },
77
+ "publishConfig": {
78
+ "registry": "https://registry.npmjs.org",
79
+ "access": "public"
80
+ }
81
+ }