@brainbox-labs/sdk 0.0.0-stage → 0.23.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.
@@ -0,0 +1,178 @@
1
+ // src/ingest/athena.ts
2
+ var DEFAULT_POLL_TIMEOUT_MS = 3e5;
3
+ function parseAthenaUrl(url) {
4
+ let u;
5
+ try {
6
+ u = new URL(url);
7
+ } catch {
8
+ throw new Error("[BrainBox] Invalid Athena connection URL \u2014 expected athena://region/database.");
9
+ }
10
+ const scheme = u.protocol.replace(/:$/, "").toLowerCase();
11
+ if (scheme !== "athena" && scheme !== "awsathena") {
12
+ throw new Error(`[BrainBox] Not an Athena connection URL (scheme "${scheme}") \u2014 expected athena:// or awsathena://.`);
13
+ }
14
+ const region = u.hostname;
15
+ if (region === "") {
16
+ throw new Error("[BrainBox] Athena connection URL must include a region: athena://region/database.");
17
+ }
18
+ const segments = u.pathname.split("/").filter((s) => s.length > 0);
19
+ const database = segments[0];
20
+ if (database === void 0) {
21
+ throw new Error("[BrainBox] Athena connection URL must include a database: athena://region/database.");
22
+ }
23
+ const outputLocation = u.searchParams.get("output") ?? void 0;
24
+ const rawPollTimeout = u.searchParams.get("pollTimeoutMs");
25
+ const pollTimeoutMs = rawPollTimeout !== null ? Number(rawPollTimeout) : DEFAULT_POLL_TIMEOUT_MS;
26
+ if (!Number.isFinite(pollTimeoutMs) || pollTimeoutMs <= 0) {
27
+ throw new Error('[BrainBox] Athena connection URL "pollTimeoutMs" must be a positive number of milliseconds.');
28
+ }
29
+ const target = {
30
+ region: decodeURIComponent(region),
31
+ catalog: u.searchParams.get("catalog") ?? "AwsDataCatalog",
32
+ database: decodeURIComponent(database),
33
+ workgroup: u.searchParams.get("workgroup") ?? "primary",
34
+ pollTimeoutMs
35
+ };
36
+ if (outputLocation !== void 0) target.outputLocation = outputLocation;
37
+ return target;
38
+ }
39
+ var TERMINAL_STATES = /* @__PURE__ */ new Set(["SUCCEEDED", "FAILED", "CANCELLED"]);
40
+ async function openAthenaConnection(url) {
41
+ const target = parseAthenaUrl(url);
42
+ let mod;
43
+ try {
44
+ mod = await import("@aws-sdk/client-athena");
45
+ } catch {
46
+ throw new Error(
47
+ '[BrainBox] Athena support requires the optional dependency "@aws-sdk/client-athena". Install it with: npm install @aws-sdk/client-athena'
48
+ );
49
+ }
50
+ const client = new mod.AthenaClient({ region: target.region });
51
+ const runQuery = async (sql) => {
52
+ const startResult = await client.send(
53
+ new mod.StartQueryExecutionCommand({
54
+ QueryString: sql,
55
+ QueryExecutionContext: { Catalog: target.catalog, Database: target.database },
56
+ WorkGroup: target.workgroup,
57
+ ...target.outputLocation !== void 0 ? { ResultConfiguration: { OutputLocation: target.outputLocation } } : {}
58
+ })
59
+ );
60
+ const queryExecutionId = startResult.QueryExecutionId;
61
+ if (queryExecutionId === void 0) {
62
+ throw new Error("[BrainBox] Athena query did not return a QueryExecutionId.");
63
+ }
64
+ const deadline = Date.now() + target.pollTimeoutMs;
65
+ let state;
66
+ let reason;
67
+ for (; ; ) {
68
+ const status = await client.send(
69
+ new mod.GetQueryExecutionCommand({ QueryExecutionId: queryExecutionId })
70
+ );
71
+ state = status.QueryExecution?.Status?.State;
72
+ reason = status.QueryExecution?.Status?.StateChangeReason;
73
+ if (state !== void 0 && TERMINAL_STATES.has(state)) break;
74
+ if (Date.now() >= deadline) {
75
+ throw new Error(
76
+ `[BrainBox] Athena query ${queryExecutionId} did not reach a terminal state within ${target.pollTimeoutMs}ms (last state: ${state ?? "unknown"}). Increase pollTimeoutMs on the connection URL if the query is expected to run longer, or cancel it in the Athena console.`
77
+ );
78
+ }
79
+ await new Promise((resolve) => setTimeout(resolve, 500));
80
+ }
81
+ if (state !== "SUCCEEDED") {
82
+ throw new Error(`[BrainBox] Athena query ${state?.toLowerCase() ?? "failed"}: ${reason ?? "unknown error"}`);
83
+ }
84
+ const rows = [];
85
+ let columnNames;
86
+ let nextToken;
87
+ let firstPage = true;
88
+ do {
89
+ const page = await client.send(
90
+ new mod.GetQueryResultsCommand({ QueryExecutionId: queryExecutionId, NextToken: nextToken })
91
+ );
92
+ if (columnNames === void 0) {
93
+ columnNames = (page.ResultSet?.ResultSetMetadata?.ColumnInfo ?? []).map((c) => c.Name ?? "");
94
+ }
95
+ const pageRows = page.ResultSet?.Rows ?? [];
96
+ const startIndex = firstPage ? 1 : 0;
97
+ for (let i = startIndex; i < pageRows.length; i++) {
98
+ const values = pageRows[i]?.Data ?? [];
99
+ const row = {};
100
+ columnNames.forEach((name, idx) => {
101
+ row[name] = values[idx]?.VarCharValue ?? null;
102
+ });
103
+ rows.push(row);
104
+ }
105
+ nextToken = page.NextToken;
106
+ firstPage = false;
107
+ } while (nextToken !== void 0);
108
+ return rows;
109
+ };
110
+ return {
111
+ queryRows: runQuery,
112
+ // The AWS SDK client is a stateless HTTP wrapper — nothing to close.
113
+ close: async () => {
114
+ }
115
+ };
116
+ }
117
+ function escapeLiteral(value) {
118
+ return `'${value.replace(/'/g, "''")}'`;
119
+ }
120
+ async function introspectAthenaSchemaWithConnection(conn, database) {
121
+ const schemaCond = ` AND table_schema = ${escapeLiteral(database)}`;
122
+ const tableRows = await conn.queryRows(
123
+ `SELECT table_schema, table_name
124
+ FROM information_schema.tables
125
+ WHERE table_type = 'BASE TABLE'${schemaCond}
126
+ ORDER BY table_schema, table_name`
127
+ );
128
+ const columnRows = await conn.queryRows(
129
+ `SELECT table_schema, table_name, column_name, data_type, is_nullable, column_default
130
+ FROM information_schema.columns
131
+ WHERE 1=1${schemaCond}
132
+ ORDER BY table_schema, table_name, ordinal_position`
133
+ );
134
+ const columnsByTable = /* @__PURE__ */ new Map();
135
+ for (const col of columnRows) {
136
+ const key = `${col.table_schema}.${col.table_name}`;
137
+ const column = {
138
+ name: col.column_name,
139
+ type: col.data_type,
140
+ nullable: col.is_nullable === "YES",
141
+ isPrimaryKey: false,
142
+ isForeignKey: false
143
+ };
144
+ if (col.column_default !== null && col.column_default !== void 0) {
145
+ column.defaultValue = col.column_default;
146
+ }
147
+ const existing = columnsByTable.get(key);
148
+ if (existing !== void 0) {
149
+ existing.push(column);
150
+ } else {
151
+ columnsByTable.set(key, [column]);
152
+ }
153
+ }
154
+ const tables = tableRows.map((t) => ({
155
+ name: t.table_name,
156
+ schema: t.table_schema,
157
+ columns: columnsByTable.get(`${t.table_schema}.${t.table_name}`) ?? [],
158
+ indexes: [],
159
+ constraints: []
160
+ }));
161
+ return { tables, extractedAt: (/* @__PURE__ */ new Date()).toISOString() };
162
+ }
163
+ async function introspectAthenaSchema(connectionString) {
164
+ const target = parseAthenaUrl(connectionString);
165
+ const conn = await openAthenaConnection(connectionString);
166
+ try {
167
+ return await introspectAthenaSchemaWithConnection(conn, target.database);
168
+ } finally {
169
+ await conn.close();
170
+ }
171
+ }
172
+
173
+ export {
174
+ parseAthenaUrl,
175
+ openAthenaConnection,
176
+ introspectAthenaSchemaWithConnection,
177
+ introspectAthenaSchema
178
+ };
@@ -0,0 +1,23 @@
1
+ import {
2
+ ColumnProfiler,
3
+ connectAndProfile,
4
+ detectDialect,
5
+ detectFormatHint,
6
+ extractJsonShape,
7
+ openConnection,
8
+ parseProfileMode,
9
+ parseSkipColumns,
10
+ quoteIdentifier
11
+ } from "./chunk-VEXUCOXR.js";
12
+ import "./chunk-MLKGABMK.js";
13
+ export {
14
+ ColumnProfiler,
15
+ connectAndProfile,
16
+ detectDialect,
17
+ detectFormatHint,
18
+ extractJsonShape,
19
+ openConnection,
20
+ parseProfileMode,
21
+ parseSkipColumns,
22
+ quoteIdentifier
23
+ };
@@ -0,0 +1,25 @@
1
+ import { DocumentSource, AnalysisDepth } from '@brainbox-labs/types';
2
+
3
+ /** An object form of a `docs` entry: a file `path` or inline `content`, with optional sync identity. */
4
+ interface DocEntry {
5
+ /** File path or glob. With `sourceKey` it must match exactly one file. */
6
+ path?: string;
7
+ /** Inline content, used instead of `path`. */
8
+ content?: string;
9
+ /** Display name. Defaults to the file's base name; required with inline `content` unless `sourceKey` is set. */
10
+ name?: string;
11
+ type?: DocumentSource['type'];
12
+ /** Stable identity (1-256 chars, no '/'). Re-ingest of the same key updates the same page. */
13
+ sourceKey?: string;
14
+ /** Opaque version; the server skips an ingest whose key + version + namespace + depth are unchanged. Defaults to a content hash. */
15
+ sourceVersion?: string;
16
+ namespace?: string;
17
+ metadata?: Record<string, string>;
18
+ analysisDepth?: AnalysisDepth;
19
+ }
20
+ declare function expandDocPatterns(patterns: Array<string | DocEntry>, outputDir?: string, analysisDepth?: AnalysisDepth): Promise<DocumentSource[]>;
21
+ /** Wrap free-form text as an inline DocumentSource. Filename is fixed — callers
22
+ * should not see their `message` reflected back as a server-visible doc name. */
23
+ declare function inlineText(text: string, analysisDepth?: AnalysisDepth): DocumentSource;
24
+
25
+ export { type DocEntry as D, expandDocPatterns as e, inlineText as i };
@@ -0,0 +1,11 @@
1
+ import {
2
+ expandDocPatterns,
3
+ inlineText,
4
+ loadDocFile
5
+ } from "./chunk-4J77FNJJ.js";
6
+ import "./chunk-MLKGABMK.js";
7
+ export {
8
+ expandDocPatterns,
9
+ inlineText,
10
+ loadDocFile
11
+ };
@@ -0,0 +1,148 @@
1
+ import { ContextTool as ContextTool$1, ContextToolExecution, ContextToolInputSchema } from '@brainbox-labs/types';
2
+
3
+ interface ContextTool extends ContextTool$1 {
4
+ /**
5
+ * Which project this tool was synced from. Only set in tenant-key,
6
+ * multi-project sync mode — lets an agent (or dispatch) tell overlay
7
+ * tools from base tools instead of merging them into one anonymous list.
8
+ */
9
+ sourceProject?: {
10
+ projectId: string;
11
+ role: 'overlay' | 'base' | 'project';
12
+ };
13
+ }
14
+ /**
15
+ * SQL connector client — available in tool handlers as ctx.sql.
16
+ * Specific to the SQL connector. Future connectors (REST, MongoDB, etc.)
17
+ * will expose their own typed clients on ctx.
18
+ */
19
+ interface SqlClient {
20
+ /** Execute a parameterized SQL query, returning rows. Params are positional ($1, $2...). */
21
+ query(sql: string, params?: unknown[]): Promise<unknown[]>;
22
+ }
23
+ /** Context passed to middleware and tool handlers. */
24
+ interface ToolContext {
25
+ /**
26
+ * SQL connector client (available when connectors.sql is configured).
27
+ * Named ctx.sql — not ctx.db — to be explicit that it's the SQL connector.
28
+ * Future connectors will add ctx.rest, ctx.mongo, etc.
29
+ */
30
+ sql: SqlClient;
31
+ /** The SQL/query string from the approved model — for auto-tier and enhanced overrides. */
32
+ defaultQuery?: string;
33
+ /** Tool name being called. */
34
+ toolName: string;
35
+ /**
36
+ * HTTP headers from the incoming MCP request (Authorization, X-Tenant-ID, etc.).
37
+ * This is how middleware accesses end-user auth tokens for multi-tenant scenarios.
38
+ */
39
+ headers: Record<string, string | string[] | undefined>;
40
+ /** Arbitrary data set by middleware (e.g. user, tenantId). Use index signature to add custom fields. */
41
+ [key: string]: unknown;
42
+ }
43
+ /**
44
+ * A catch-all executor for tools that don't have a per-tool override and aren't auto-tier SQL.
45
+ * Used by NoSQL, REST, and other connector types where the user supplies query logic.
46
+ */
47
+ type CustomExecutor = (toolName: string, args: Record<string, unknown>) => Promise<unknown>;
48
+ type MiddlewareFn = (ctx: ToolContext, next: () => Promise<void>) => Promise<void>;
49
+ type ToolHandlerFn = (params: Record<string, unknown>, ctx: ToolContext) => Promise<unknown>;
50
+
51
+ interface MCPOptions {
52
+ /** BrainBox API key (bb_...) */
53
+ apiKey: string;
54
+ /**
55
+ * Project name/slug — same value as BRAINBOX_PROJECT in .env. Resolved to a
56
+ * project ID on startup. Omit for a tenant key (`bb_tenant_...`): the
57
+ * overlay + readable base projects are discovered automatically instead.
58
+ */
59
+ project?: string;
60
+ /**
61
+ * Connector configuration. Each key is a connector type.
62
+ * SQL is the first supported connector; REST, MongoDB, etc. will be added here.
63
+ */
64
+ connectors?: {
65
+ /** SQL connector (Postgres, MySQL, etc.). Required for auto-tier SQL tools. */
66
+ sql?: {
67
+ url: string;
68
+ };
69
+ /**
70
+ * Custom connector: a catch-all executor for tools not served by the SQL connector.
71
+ * Used for NoSQL, REST, or any data source where the user supplies query logic.
72
+ * Receives the tool name and arguments; returns the result.
73
+ */
74
+ custom?: {
75
+ execute: CustomExecutor;
76
+ };
77
+ };
78
+ /**
79
+ * Include brain (domain model) tools. Default: true.
80
+ * Set to false to exclude brain tools — useful for A/B experimentation.
81
+ */
82
+ brain?: boolean;
83
+ /** BrainBox base URL (no /api suffix). Defaults to https://ctx.brainbox-ai.app. For local dev: http://localhost:5002 */
84
+ apiUrl?: string;
85
+ /**
86
+ * How often to poll BrainBox for updated tool definitions (ms).
87
+ * Default: undefined — no polling, only the initial fetch on startup.
88
+ * Future: Firebase push notifications will replace polling.
89
+ */
90
+ pollIntervalMs?: number;
91
+ /**
92
+ * When true, custom tools without an override are registered and return a clear
93
+ * error when called. Default: false — unimplemented tools are excluded entirely.
94
+ */
95
+ serveUnimplementedTools?: boolean;
96
+ }
97
+ interface StartOptions {
98
+ port?: number;
99
+ }
100
+ declare class MCP {
101
+ private readonly middlewares;
102
+ private readonly overrides;
103
+ private readonly disabled;
104
+ private readonly syncCallbacks;
105
+ private readonly sqlClient;
106
+ private readonly customExecutor;
107
+ private readonly opts;
108
+ private sync;
109
+ private brainExecutor;
110
+ constructor(options: MCPOptions);
111
+ /** Register middleware that runs before every tool call. */
112
+ use(fn: MiddlewareFn): this;
113
+ /** Register a custom or enhanced tool handler. */
114
+ tool(name: string, fn: ToolHandlerFn): this;
115
+ /** Explicitly exclude a tool from the MCP server (won't appear in tools/list). */
116
+ disable(name: string): this;
117
+ /** Register a callback fired when tool definitions are refreshed. */
118
+ onSync(fn: (tools: ContextTool[]) => void): this;
119
+ /** Fetch tool definitions and start the MCP server. */
120
+ start(opts?: StartOptions): Promise<void>;
121
+ private activeTools;
122
+ private logStartupTable;
123
+ }
124
+
125
+ /**
126
+ * @brainbox-labs/sdk/serve — server-builder surface for the BrainBox Context Layer.
127
+ *
128
+ * Hosts the MCP server class, connector types, and middleware/handler types.
129
+ * @packageDocumentation
130
+ */
131
+
132
+ type index_ContextTool = ContextTool;
133
+ declare const index_ContextToolExecution: typeof ContextToolExecution;
134
+ declare const index_ContextToolInputSchema: typeof ContextToolInputSchema;
135
+ type index_CustomExecutor = CustomExecutor;
136
+ type index_MCP = MCP;
137
+ declare const index_MCP: typeof MCP;
138
+ type index_MCPOptions = MCPOptions;
139
+ type index_MiddlewareFn = MiddlewareFn;
140
+ type index_SqlClient = SqlClient;
141
+ type index_StartOptions = StartOptions;
142
+ type index_ToolContext = ToolContext;
143
+ type index_ToolHandlerFn = ToolHandlerFn;
144
+ declare namespace index {
145
+ export { type index_ContextTool as ContextTool, index_ContextToolExecution as ContextToolExecution, index_ContextToolInputSchema as ContextToolInputSchema, type index_CustomExecutor as CustomExecutor, index_MCP as MCP, type index_MCPOptions as MCPOptions, type index_MiddlewareFn as MiddlewareFn, type index_SqlClient as SqlClient, type index_StartOptions as StartOptions, type index_ToolContext as ToolContext, type index_ToolHandlerFn as ToolHandlerFn };
146
+ }
147
+
148
+ export { type ContextTool as C, type MCPOptions as M, type SqlClient as S, type ToolContext as T, MCP as a, type CustomExecutor as b, type MiddlewareFn as c, type StartOptions as d, type ToolHandlerFn as e, index as i };