@databrainhq/mcp-server 0.3.0-rc.11 → 0.3.0-rc.12
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/README.md +8 -5
- package/dist/apps/server.d.ts +35 -7
- package/dist/apps/server.js +4 -4
- package/dist/apps/stdio.js +5 -5
- package/dist/{chunk-RHK62ZJ6.js → chunk-347U6GXR.js} +3 -3
- package/dist/chunk-347U6GXR.js.map +1 -0
- package/dist/{chunk-IBYBK5ZE.js → chunk-LACJHQYH.js} +4 -4
- package/dist/{chunk-ES2LUP4U.js → chunk-OLOC2MTA.js} +245 -89
- package/dist/chunk-OLOC2MTA.js.map +1 -0
- package/dist/{chunk-DM7S4R57.js → chunk-V3UW3B6U.js} +2 -2
- package/dist/{chunk-NBFUKVWP.js → chunk-ZTHGF27R.js} +99 -15
- package/dist/chunk-ZTHGF27R.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/index.js +4 -4
- package/dist/{main-JEYYFGJM.js → main-IUV24DMP.js} +28 -20
- package/dist/main-IUV24DMP.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-ES2LUP4U.js.map +0 -1
- package/dist/chunk-NBFUKVWP.js.map +0 -1
- package/dist/chunk-RHK62ZJ6.js.map +0 -1
- package/dist/main-JEYYFGJM.js.map +0 -1
- /package/dist/{chunk-IBYBK5ZE.js.map → chunk-LACJHQYH.js.map} +0 -0
- /package/dist/{chunk-DM7S4R57.js.map → chunk-V3UW3B6U.js.map} +0 -0
package/README.md
CHANGED
|
@@ -29,7 +29,7 @@ Your AI app opens a Databrain sign-in page, you pick one or more workspaces (or
|
|
|
29
29
|
|
|
30
30
|
When you approve more than one workspace, the AI names the workspace on each call (`workspace` or `workspaceName`); `whoami` lists the ones you approved. With "All workspaces I can access", workspaces you get later are included, and `create_workspace` can make a new one if your role allows it.
|
|
31
31
|
|
|
32
|
-
The hosted connector includes chart and KPI MCP Apps. `ask_question` returns an inline tile, and `list_widgets` opens a chart chooser in compatible hosts. Both current `_meta.ui.resourceUri` and legacy `_meta['ui/resourceUri']` pointers are included; other hosts retain the text summary and structured data. Tile controls retain the answer's granted workspace. Saving requires `mcp:dashboards:write`, `mcp:query`, the live workspace role, and `APPLY_TO_PRODUCTION` confirmation. No new environment variable is needed, including on self-hosted installs.
|
|
32
|
+
The hosted connector includes chart and KPI MCP Apps. `render_metric_tile` renders an existing saved metric directly without an embed, data app or datamart; `ask_question` returns a new answer as an inline tile, and `list_widgets` opens a chart chooser in compatible hosts. Both current `_meta.ui.resourceUri` and legacy `_meta['ui/resourceUri']` pointers are included; other hosts retain the text summary and structured data. Tile controls retain the answer's granted workspace. Saving requires `mcp:dashboards:write`, `mcp:query`, the live workspace role, and `APPLY_TO_PRODUCTION` confirmation. No new environment variable is needed, including on self-hosted installs. Saved category and measure settings drive bar, line, pie, doughnut, stacked and combo tiles. Gauges render inline, pivot/table tiles show a scrollable table, and text KPIs stay text. Large dashboard documents open a compact chart picker.
|
|
33
33
|
|
|
34
34
|
<details>
|
|
35
35
|
<summary><b>Claude (claude.ai and Claude Desktop)</b></summary>
|
|
@@ -448,13 +448,13 @@ Prompts are guided workflows your AI assistant can follow. Ask for them by name
|
|
|
448
448
|
| `ask_question` | Ask a natural language question — gets converted to SQL, returns data + chart suggestion |
|
|
449
449
|
| `get_semantic_layer` | Inspect semantic layer metadata (table/column descriptions, synonyms, completion score) |
|
|
450
450
|
| `update_semantic_layer` | Improve semantic layer quality (add descriptions, synonyms, example questions) |
|
|
451
|
-
| `start_semantic_layer_generation` | Start semantic-layer generation for a datamart |
|
|
452
|
-
| `get_semantic_layer_generation_status` | Check semantic-layer generation progress |
|
|
451
|
+
| `start_semantic_layer_generation` | Start semantic-layer generation for a datamart (hosted OAuth) |
|
|
452
|
+
| `get_semantic_layer_generation_status` | Check semantic-layer generation progress (hosted OAuth) |
|
|
453
453
|
| `search_semantic_model` | Find relevant v2 entities and their related entities |
|
|
454
454
|
| `get_semantic_entity` | Read one v2 entity by kind and name with the current content hash |
|
|
455
455
|
| `propose_semantic_change` | Validate candidate YAML or a patch and return its plan without writing |
|
|
456
456
|
| `apply_semantic_change` | Preview by default, or apply live with a reviewed hash and production confirmation |
|
|
457
|
-
| `eval_semantic_model` |
|
|
457
|
+
| `eval_semantic_model` | Check closed-world model assertions (id/question/exercises); does not run SQL |
|
|
458
458
|
|
|
459
459
|
Semantic-layer generation uses the datamart ID returned by `list_datamarts` and calls the service-token API. Pass `datamartId` directly when the ID is already known.
|
|
460
460
|
|
|
@@ -463,7 +463,7 @@ For a v2 model, the five model tools use `datamartId` and the configured service
|
|
|
463
463
|
1. Use `search_semantic_model` with `question` and optional `k` (default 10, maximum 100). If the server has no retrieval route, the tool pulls the model and ranks name, alias, synonyms and description, then includes adjacent entities. Hidden tables and columns are excluded from local search.
|
|
464
464
|
2. Use `get_semantic_entity` with `kind` and an exact `name`. Column names use `table.column`. Kinds are `table`, `column`, `measure`, `metric`, `join`, `entity`, `glossary`, `saved_query`, `instruction` and `access_rule`.
|
|
465
465
|
3. Use `propose_semantic_change` with exactly one of `source` (complete YAML), `yaml_patch`, or `change`. It returns the candidate source, validation errors, the server plan and `expected_content_hash`. Invalid source returns errors and no plan.
|
|
466
|
-
4. Use `eval_semantic_model` with the proposed `source` and optional `questions`. Omitting source evaluates the stored model.
|
|
466
|
+
4. Use `eval_semantic_model` with the proposed `source` and optional `questions`. Omitting source evaluates the stored model. Each question needs `id`, `question`, and `exercises` (exact model entity names). An omitted list becomes empty. This checks the model; it does not execute SQL.
|
|
467
467
|
5. Review the plan. Call `apply_semantic_change` with the exact returned `source` and `expected_content_hash`. Its `dry_run` defaults to true. A live apply requires `dry_run: false` and user supplied `confirm: "APPLY_TO_PRODUCTION"`. The assistant must never supply confirmation on its own. Explicit `expected_content_hash: null` selects the first apply only when no layer is stored. Apply changes the live model for all consumers.
|
|
468
468
|
|
|
469
469
|
A YAML patch merges mappings and named lists by name, including tables and columns. Other lists replace the original list. An empty list clears a list. Null removes a field. For example, `yaml_patch: "tables:\n - name: orders\n description: Customer purchases\n"` changes that description and preserves other tables and fields. Patch output normalizes YAML formatting and does not preserve comments. Review the returned source.
|
|
@@ -618,3 +618,6 @@ All tokens are managed automatically. You provide your service token once in the
|
|
|
618
618
|
## License
|
|
619
619
|
|
|
620
620
|
MIT
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
Saved hosted charts: call `list_dashboards`, then `get_dashboard` or `list_widgets` with its UUID/slug and workspace. Omit clientId for the saved dashboard view. Call `render_metric_tile({workspaceName, metricId, clientId?, display:"chart"})` to open a metricRef directly; the saved client must be supplied for a client-scoped metric. `display:"kpi"` returns the saved scalar, or labels the sum of a chart's sole numeric series across the full authorized result; multiple series refuse instead of guessing. Refresh and date-range controls recheck the same workspace and saved client. Use workspaceId for the wid in app links. Tenant/API-key reads still use embedId/clientId, with optional dataAppName for OAuth ambiguity. These operations create no dashboards, metrics or embeds.
|
package/dist/apps/server.d.ts
CHANGED
|
@@ -123,19 +123,37 @@ declare const configSchema: z.ZodEffects<z.ZodEffects<z.ZodObject<{
|
|
|
123
123
|
}>;
|
|
124
124
|
type Config = z.infer<typeof configSchema>;
|
|
125
125
|
|
|
126
|
-
declare const referenceSchema: z.ZodObject<{
|
|
126
|
+
declare const referenceSchema: z.ZodUnion<[z.ZodObject<{
|
|
127
127
|
embedId: z.ZodString;
|
|
128
128
|
clientId: z.ZodString;
|
|
129
129
|
widgetId: z.ZodString;
|
|
130
|
+
dataAppName: z.ZodOptional<z.ZodString>;
|
|
130
131
|
}, "strict", z.ZodTypeAny, {
|
|
131
132
|
clientId: string;
|
|
132
133
|
embedId: string;
|
|
133
134
|
widgetId: string;
|
|
135
|
+
dataAppName?: string | undefined;
|
|
134
136
|
}, {
|
|
135
137
|
clientId: string;
|
|
136
138
|
embedId: string;
|
|
137
139
|
widgetId: string;
|
|
138
|
-
|
|
140
|
+
dataAppName?: string | undefined;
|
|
141
|
+
}>, z.ZodObject<{
|
|
142
|
+
dashboardId: z.ZodString;
|
|
143
|
+
widgetId: z.ZodString;
|
|
144
|
+
clientId: z.ZodOptional<z.ZodString>;
|
|
145
|
+
display: z.ZodOptional<z.ZodEnum<["chart", "kpi"]>>;
|
|
146
|
+
}, "strict", z.ZodTypeAny, {
|
|
147
|
+
widgetId: string;
|
|
148
|
+
dashboardId: string;
|
|
149
|
+
clientId?: string | undefined;
|
|
150
|
+
display?: "chart" | "kpi" | undefined;
|
|
151
|
+
}, {
|
|
152
|
+
widgetId: string;
|
|
153
|
+
dashboardId: string;
|
|
154
|
+
clientId?: string | undefined;
|
|
155
|
+
display?: "chart" | "kpi" | undefined;
|
|
156
|
+
}>]>;
|
|
139
157
|
type ChartReference = z.infer<typeof referenceSchema>;
|
|
140
158
|
declare const viewSchema: z.ZodObject<{
|
|
141
159
|
cursor: z.ZodOptional<z.ZodString>;
|
|
@@ -172,8 +190,10 @@ declare const viewSchema: z.ZodObject<{
|
|
|
172
190
|
} | undefined;
|
|
173
191
|
}>;
|
|
174
192
|
declare const pageSchema: z.ZodEffects<z.ZodObject<{
|
|
175
|
-
kind: z.ZodEnum<["chart", "kpi"]>;
|
|
193
|
+
kind: z.ZodEnum<["chart", "kpi", "table"]>;
|
|
176
194
|
title: z.ZodString;
|
|
195
|
+
description: z.ZodOptional<z.ZodString>;
|
|
196
|
+
rowsTotal: z.ZodOptional<z.ZodNumber>;
|
|
177
197
|
chartSpec: z.ZodObject<{
|
|
178
198
|
type: z.ZodString;
|
|
179
199
|
}, "strict", z.ZodTypeAny, {
|
|
@@ -246,12 +266,14 @@ declare const pageSchema: z.ZodEffects<z.ZodObject<{
|
|
|
246
266
|
key: string;
|
|
247
267
|
drillId?: string | undefined;
|
|
248
268
|
}[];
|
|
249
|
-
kind: "chart" | "kpi";
|
|
269
|
+
kind: "chart" | "kpi" | "table";
|
|
250
270
|
chartSpec: {
|
|
251
271
|
type: string;
|
|
252
272
|
};
|
|
253
273
|
value?: string | number | boolean | null | undefined;
|
|
274
|
+
description?: string | undefined;
|
|
254
275
|
svg?: string | undefined;
|
|
276
|
+
rowsTotal?: number | undefined;
|
|
255
277
|
customChart?: {
|
|
256
278
|
options: Record<string, string | number | boolean>;
|
|
257
279
|
key: string;
|
|
@@ -275,12 +297,14 @@ declare const pageSchema: z.ZodEffects<z.ZodObject<{
|
|
|
275
297
|
key: string;
|
|
276
298
|
drillId?: string | undefined;
|
|
277
299
|
}[];
|
|
278
|
-
kind: "chart" | "kpi";
|
|
300
|
+
kind: "chart" | "kpi" | "table";
|
|
279
301
|
chartSpec: {
|
|
280
302
|
type: string;
|
|
281
303
|
};
|
|
282
304
|
value?: string | number | boolean | null | undefined;
|
|
305
|
+
description?: string | undefined;
|
|
283
306
|
svg?: string | undefined;
|
|
307
|
+
rowsTotal?: number | undefined;
|
|
284
308
|
customChart?: {
|
|
285
309
|
options: Record<string, string | number | boolean>;
|
|
286
310
|
key: string;
|
|
@@ -304,12 +328,14 @@ declare const pageSchema: z.ZodEffects<z.ZodObject<{
|
|
|
304
328
|
key: string;
|
|
305
329
|
drillId?: string | undefined;
|
|
306
330
|
}[];
|
|
307
|
-
kind: "chart" | "kpi";
|
|
331
|
+
kind: "chart" | "kpi" | "table";
|
|
308
332
|
chartSpec: {
|
|
309
333
|
type: string;
|
|
310
334
|
};
|
|
311
335
|
value?: string | number | boolean | null | undefined;
|
|
336
|
+
description?: string | undefined;
|
|
312
337
|
svg?: string | undefined;
|
|
338
|
+
rowsTotal?: number | undefined;
|
|
313
339
|
customChart?: {
|
|
314
340
|
options: Record<string, string | number | boolean>;
|
|
315
341
|
key: string;
|
|
@@ -333,12 +359,14 @@ declare const pageSchema: z.ZodEffects<z.ZodObject<{
|
|
|
333
359
|
key: string;
|
|
334
360
|
drillId?: string | undefined;
|
|
335
361
|
}[];
|
|
336
|
-
kind: "chart" | "kpi";
|
|
362
|
+
kind: "chart" | "kpi" | "table";
|
|
337
363
|
chartSpec: {
|
|
338
364
|
type: string;
|
|
339
365
|
};
|
|
340
366
|
value?: string | number | boolean | null | undefined;
|
|
367
|
+
description?: string | undefined;
|
|
341
368
|
svg?: string | undefined;
|
|
369
|
+
rowsTotal?: number | undefined;
|
|
342
370
|
customChart?: {
|
|
343
371
|
options: Record<string, string | number | boolean>;
|
|
344
372
|
key: string;
|
package/dist/apps/server.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
createChartAppServer
|
|
4
|
-
} from "../chunk-
|
|
5
|
-
import "../chunk-
|
|
6
|
-
import "../chunk-
|
|
7
|
-
import "../chunk-
|
|
4
|
+
} from "../chunk-LACJHQYH.js";
|
|
5
|
+
import "../chunk-ZTHGF27R.js";
|
|
6
|
+
import "../chunk-OLOC2MTA.js";
|
|
7
|
+
import "../chunk-347U6GXR.js";
|
|
8
8
|
import "../chunk-Q5EYDKSA.js";
|
|
9
9
|
export {
|
|
10
10
|
createChartAppServer
|
package/dist/apps/stdio.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
loadConfig
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-V3UW3B6U.js";
|
|
5
5
|
import {
|
|
6
6
|
createChartAppServer
|
|
7
|
-
} from "../chunk-
|
|
8
|
-
import "../chunk-
|
|
9
|
-
import "../chunk-
|
|
10
|
-
import "../chunk-
|
|
7
|
+
} from "../chunk-LACJHQYH.js";
|
|
8
|
+
import "../chunk-ZTHGF27R.js";
|
|
9
|
+
import "../chunk-OLOC2MTA.js";
|
|
10
|
+
import "../chunk-347U6GXR.js";
|
|
11
11
|
import "../chunk-Q5EYDKSA.js";
|
|
12
12
|
|
|
13
13
|
// src/apps/stdio.ts
|
|
@@ -79,7 +79,7 @@ var DatabrainApiError = class extends Error {
|
|
|
79
79
|
return "Hint: The requested resource was not found. Verify the ID or name is correct using the corresponding list tool.";
|
|
80
80
|
}
|
|
81
81
|
if (this.status === 409) {
|
|
82
|
-
return "Hint:
|
|
82
|
+
return "Hint: The request conflicts with the current resource state. Read the error above, inspect the resource, and retry after resolving it.";
|
|
83
83
|
}
|
|
84
84
|
if (this.status === 422) {
|
|
85
85
|
return "Hint: The request parameters are invalid. Check the required fields and their formats.";
|
|
@@ -143,7 +143,7 @@ var logger = {
|
|
|
143
143
|
var package_default = {
|
|
144
144
|
name: "@databrainhq/mcp-server",
|
|
145
145
|
mcpName: "com.usedatabrain/mcp-server",
|
|
146
|
-
version: "0.3.0-rc.
|
|
146
|
+
version: "0.3.0-rc.12",
|
|
147
147
|
description: "MCP server for Databrain embedded analytics - connect databases, create datamarts, configure embeds, and generate frontend code",
|
|
148
148
|
type: "module",
|
|
149
149
|
bin: {
|
|
@@ -881,4 +881,4 @@ export {
|
|
|
881
881
|
planUpload,
|
|
882
882
|
scaffoldProject
|
|
883
883
|
};
|
|
884
|
-
//# sourceMappingURL=chunk-
|
|
884
|
+
//# sourceMappingURL=chunk-347U6GXR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/errors.ts","../src/utils/logger.ts","../package.json","../src/version.ts","../src/custom-chart/studio.ts","../src/utils/cache.ts","../src/client/error-body.ts","../src/utils/tool-context.ts","../src/client/oauth-client-credentials.ts","../src/client/databrain-client.ts","../src/api/custom-charts-api.ts","../src/custom-chart/api.ts","../src/custom-chart/scaffold.ts"],"sourcesContent":["export class DatabrainApiError extends Error {\n constructor(\n public readonly status: number,\n public readonly code: string,\n message: string,\n public readonly details?: unknown,\n /** The server's own next step for this error class, when it sent one. */\n public readonly serverHint?: string,\n public readonly retryable?: boolean,\n ) {\n super(message);\n this.name = 'DatabrainApiError';\n }\n\n toToolResponse(): { content: Array<{ type: 'text'; text: string }>; isError: true } {\n const parts = [`Error: ${this.message}`];\n const detailDump = this.formatDetails();\n if (detailDump) parts.push(detailDump);\n const hint = this.serverHint ? `Hint: ${this.serverHint}` : this.hint();\n if (hint) parts.push(hint);\n return {\n content: [{ type: 'text', text: parts.join('\\n\\n') }],\n isError: true,\n };\n }\n\n /**\n * Surface API-returned details for 4xx errors so the LLM can recover or\n * report the real reason (validation messages, field names, etc.). Skips\n * fields already collapsed into `message`/`code`, and skips 5xx where the\n * payload usually isn't actionable.\n */\n private formatDetails(): string {\n if (this.status < 400 || this.status >= 500) return '';\n if (!this.details || typeof this.details !== 'object') return '';\n\n const skipKeys = new Set(['message', 'detail', 'error', 'code', 'data', 'hint', 'retryable']);\n const extra: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(this.details as Record<string, unknown>)) {\n if (skipKeys.has(k)) continue;\n if (v === null || v === undefined) continue;\n extra[k] = v;\n }\n if (Object.keys(extra).length === 0) return '';\n try {\n return `API details: ${JSON.stringify(extra)}`;\n } catch {\n return '';\n }\n }\n\n private hint(): string {\n // dashboard_snapshot: the API's own reasons, so the generic status hints below do not mislead.\n if (this.code === 'OAUTH_SIGN_IN_REQUIRED') {\n return 'Hint: Snapshots draw as a signed-in Databrain user. Connect this AI app with a Databrain sign-in (the hosted connector, or /mcp in Claude Code); a service token cannot take them.';\n }\n if (this.code === 'RENDER_IN_PROGRESS') {\n return 'Hint: Your other snapshot is still rendering. Wait a few seconds, then call the tool again.';\n }\n if (this.code === 'SNAPSHOT_TIMEOUT' || this.code === 'SNAPSHOT_TOO_LARGE') {\n return 'Hint: Ask for one chart with metricId, or a smaller width.';\n }\n if (this.code === 'UNAUTHORIZED_ORIGIN') {\n return 'Hint: The embed origin is not on the allowed domains list. Add the domain to the allowed domains in the Databrain settings; the token itself is fine.';\n }\n if (this.status === 401 || this.status === 403) {\n if (this.code === 'OAUTH_API_ERROR') {\n return 'Hint: Check that the backend accepts the configured OAuth issuer and resource, and that the service principal has permission for this operation. Static fallback applies only to token acquisition failures.';\n }\n if (\n this.code === 'INVALID_SERVICE_TOKEN' ||\n this.code === 'MISSING_SERVICE_TOKEN' ||\n this.message.toLowerCase().includes('service token')\n ) {\n return 'Hint: The service token (DATABRAIN_SERVICE_TOKEN) is invalid, expired, or missing. It must be set in the MCP server config (not at runtime). Check Settings > Service Tokens in the Databrain UI.';\n }\n return 'Hint: The per-data-app API token is invalid or expired. Use `create_api_token` to generate a new one. Do not ask the user — manage tokens via MCP tools.';\n }\n if (this.status === 400) {\n return 'Hint: The request was invalid. Check parameter values match expected types and formats. Use the corresponding list tool to verify IDs and names.';\n }\n if (this.status === 404) {\n return 'Hint: The requested resource was not found. Verify the ID or name is correct using the corresponding list tool.';\n }\n if (this.status === 409) {\n return 'Hint: The request conflicts with the current resource state. Read the error above, inspect the resource, and retry after resolving it.';\n }\n if (this.status === 422) {\n return 'Hint: The request parameters are invalid. Check the required fields and their formats.';\n }\n if (this.status === 429) {\n return 'Hint: API rate limit reached. Wait a moment and try again.';\n }\n if (this.status >= 500) {\n return 'Hint: The Databrain API is experiencing issues. Try again in a few moments.';\n }\n return '';\n }\n}\n\nexport function toolError(message: string): { content: Array<{ type: 'text'; text: string }>; isError: true } {\n return {\n content: [{ type: 'text', text: message }],\n isError: true,\n };\n}\n\nexport function stringify(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return String(value);\n }\n}\n\nexport function toolSuccess(text: string): { content: Array<{ type: 'text'; text: string }> } {\n return {\n content: [{ type: 'text', text }],\n };\n}\n","const LOG_LEVELS = { debug: 0, info: 1, warn: 2, error: 3 } as const;\ntype LogLevel = keyof typeof LOG_LEVELS;\n\nconst currentLevel: LogLevel =\n (process.env.DATABRAIN_LOG_LEVEL as LogLevel) || 'warn';\n\n/**\n * Credentials the process holds. Every log line is scrubbed of them before it\n * reaches stderr, because an API error body can quote the Authorization\n * header back and stderr is a terminal, a CI log or the MCP host's log.\n */\nconst secrets = new Set<string>();\n\nexport function registerSecret(value: string | undefined | null): void {\n if (typeof value === 'string' && value.length >= 8) secrets.add(value);\n}\n\nexport function redactSecrets(text: string): string {\n let out = text;\n for (const secret of secrets) out = out.split(secret).join('[redacted]');\n return out;\n}\n\nfunction log(level: LogLevel, message: string, data?: unknown): void {\n if (LOG_LEVELS[level] < LOG_LEVELS[currentLevel]) return;\n const line = `[databrain-mcp] [${level.toUpperCase()}] ${message}`;\n const text = data !== undefined ? `${line} ${JSON.stringify(data)}` : line;\n process.stderr.write(`${redactSecrets(text)}\\n`);\n}\n\nexport const logger = {\n debug: (msg: string, data?: unknown) => log('debug', msg, data),\n info: (msg: string, data?: unknown) => log('info', msg, data),\n warn: (msg: string, data?: unknown) => log('warn', msg, data),\n error: (msg: string, data?: unknown) => log('error', msg, data),\n};\n","{\n \"name\": \"@databrainhq/mcp-server\",\n \"mcpName\": \"com.usedatabrain/mcp-server\",\n \"version\": \"0.3.0-rc.12\",\n \"description\": \"MCP server for Databrain embedded analytics - connect databases, create datamarts, configure embeds, and generate frontend code\",\n \"type\": \"module\",\n \"bin\": {\n \"mcp-server\": \"dist/index.js\",\n \"databrain-mcp-server\": \"dist/index.js\",\n \"databrain-mcp-chart-apps\": \"dist/apps/stdio.js\",\n \"databrain\": \"dist/cli.js\"\n },\n \"main\": \"dist/index.js\",\n \"types\": \"dist/index.d.ts\",\n \"files\": [\n \"dist\",\n \"skills\",\n \".claude-plugin\",\n \".mcp.json\"\n ],\n \"scripts\": {\n \"build\": \"tsup && node scripts/copy-custom-chart-assets.mjs\",\n \"dev\": \"tsx src/index.ts\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:live\": \"vitest run tests/integration/prompt-flows.test.ts\",\n \"lint\": \"tsc --noEmit\",\n \"prepublishOnly\": \"npm run build\"\n },\n \"keywords\": [\n \"mcp\",\n \"databrain\",\n \"embedded-analytics\",\n \"ai\",\n \"model-context-protocol\"\n ],\n \"license\": \"MIT\",\n \"dependencies\": {\n \"@modelcontextprotocol/sdk\": \"^1.32.1\",\n \"@posthog/mcp\": \"^0.10.7\",\n \"esbuild\": \"0.27.3\",\n \"fflate\": \"0.8.3\",\n \"posthog-node\": \"^5.21.2\",\n \"yaml\": \"^2.9.1\",\n \"zod\": \"^3.24.0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^25.3.5\",\n \"tsup\": \"^8.4.0\",\n \"tsx\": \"^4.19.0\",\n \"typescript\": \"^5.7.0\",\n \"vitest\": \"^3.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/databrainhq/mcp-server.git\"\n },\n \"engines\": {\n \"node\": \">=18.0.0\"\n }\n}\n","import packageJson from '../package.json';\n\n// tsup embeds this package.json value in dist while tsx resolves the same file\n// during development. The handshake and request headers therefore share the\n// package version without maintaining a second release string.\nexport const MCP_SERVER_VERSION = packageJson.version;\n","import { z } from 'zod';\nimport type { DatabrainClient } from '../client/databrain-client.js';\nimport { DatabrainApiError } from '../utils/errors.js';\n\nconst studioCell = z.union([z.string().max(4096), z.number().finite(), z.boolean(), z.null()]);\nexport const studioDraftSchema = z.object({\n code: z.string().max(64_000), css: z.string().max(32_000), manifest: z.record(z.unknown()),\n sampleData: z.object({ columns: z.array(z.object({ id: z.string(), label: z.string(),\n type: z.enum(['string', 'number', 'boolean']), slotId: z.string().optional() }).strict()).max(64),\n rows: z.array(z.array(studioCell)).max(200) }).strict(),\n name: z.string().max(256), description: z.string().max(500), iconSvg: z.string().max(16_384),\n}).strict();\nexport type StudioDraft = z.infer<typeof studioDraftSchema>;\n\n/** Accept only the studio's domain result, never general SSE data or credentials. */\nexport function parseStudioStream(text: string): { draft?: StudioDraft; sessionId?: string; applied: boolean } {\n if (text.length > 4 * 1024 * 1024) throw new Error('Studio stream too large');\n let draft: StudioDraft | undefined;\n let sessionId: string | undefined;\n let failure = false;\n for (const frame of text.split(/\\r?\\n\\r?\\n/)) {\n const line = frame.split(/\\r?\\n/).filter(l => l.startsWith('data:')).map(l => l.slice(5).trimStart()).join('\\n');\n if (!line || line === '[DONE]') continue;\n const event = JSON.parse(line);\n if (event.type === 'session' && typeof event.sessionId === 'string') sessionId = event.sessionId;\n if (event.type === 'error') failure = true;\n if (event.type === 'tool_execution_end' && event.name === 'update_custom_chart' &&\n event.status === 'completed' && event.result?.kind === 'applied') {\n draft = studioDraftSchema.parse(event.result.draft);\n }\n }\n if (failure && !draft) throw new Error('Bryn did not complete an edit');\n return { draft, sessionId, applied: !!draft };\n}\n\n/** Only absence permits the old authoring path. An auth denial or outage is not absence. */\nexport async function editWithBryn(client: DatabrainClient, input: {\n key: string; workspaceId: string; message: string; draft: StudioDraft; sessionId?: string;\n}): Promise<{ available: boolean; draft: StudioDraft; sessionId?: string; applied: boolean }> {\n // Bryn requires a signed-in session. A stdio service token is still valid for\n // the existing authoring API; do not send it to a session-only route.\n if (!client.isHosted()) return { available: false, draft: input.draft, applied: false };\n try {\n const result = await client.request<ReturnType<typeof parseStudioStream>>({\n method: 'POST', path: `/api/v2/custom-charts/${encodeURIComponent(input.key)}/bryn/turn`, auth: 'service',\n body: { workspaceId: input.workspaceId, message: input.message, draft: input.draft,\n sessionId: input.sessionId, mode: 'build', viewingOldVersion: false },\n responseFormat: 'studio-sse', timeoutMs: 180_000, noRetryOnTimeout: true,\n });\n return { available: true, draft: result.draft ?? input.draft, applied: result.applied, sessionId: result.sessionId };\n } catch (error) {\n if (error instanceof DatabrainApiError && error.status === 404) {\n return { available: false, draft: input.draft, applied: false };\n }\n throw error;\n }\n}\n","interface CacheEntry<T> {\n value: T;\n expiresAt: number;\n}\n\nexport class TtlCache {\n private store = new Map<string, CacheEntry<unknown>>();\n\n get<T>(key: string): T | undefined {\n const entry = this.store.get(key);\n if (!entry) return undefined;\n if (Date.now() > entry.expiresAt) {\n this.store.delete(key);\n return undefined;\n }\n return entry.value as T;\n }\n\n set<T>(key: string, value: T, ttlMs: number): void {\n this.store.set(key, { value, expiresAt: Date.now() + ttlMs });\n }\n\n invalidateByPrefix(prefix: string): void {\n for (const key of this.store.keys()) {\n if (key.startsWith(prefix)) {\n this.store.delete(key);\n }\n }\n }\n\n clear(): void {\n this.store.clear();\n }\n}\n","/**\n * Reads a Databrain error body into one shape. The backend sends the same\n * envelope `{ code, message, hint, retryable, details }` in three places:\n * flat (`{ code, message }`), under `error` (public REST, datasource API) and\n * under `data.error` (the externalApis routes, which also send `error` as a\n * plain string). Reading only the flat form dropped the code and hint.\n */\nexport interface ParsedErrorBody {\n code?: string;\n message?: string;\n hint?: string;\n retryable?: boolean;\n details?: unknown;\n}\n\nconst isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v);\n\nconst str = (v: unknown): string | undefined =>\n typeof v === 'string' && v.trim() ? v : undefined;\n\nconst fromEnvelope = (v: unknown): ParsedErrorBody | undefined => {\n if (!isRecord(v)) return undefined;\n const out: ParsedErrorBody = {\n code: str(v.code),\n message: str(v.message) ?? str(v.detail),\n hint: str(v.hint),\n retryable: typeof v.retryable === 'boolean' ? v.retryable : undefined,\n details: v.details,\n };\n return out.code || out.message || out.hint ? out : undefined;\n};\n\nexport function parseErrorBody(body: unknown): ParsedErrorBody {\n if (!isRecord(body)) return {};\n const nested =\n fromEnvelope(isRecord(body.data) ? body.data.error : undefined) ??\n fromEnvelope(body.error) ??\n fromEnvelope(body);\n if (nested) {\n return { ...nested, message: nested.message ?? str(body.error) };\n }\n return { message: str(body.error) };\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\n\n/**\n * Per-tool-call intent metadata. Set when an MCP tool handler runs (see\n * registerAllTools, which wraps every handler), and read by DatabrainClient to\n * tag outbound API requests with X-Databrain-MCP-* headers. The backend\n * (mcpTracking) records these so usage can be attributed to a specific tool and\n * workflow intent — letting us see, e.g., embedding vs internal-analytics flows.\n */\nexport interface ToolCallContext {\n /** The MCP tool name being executed, e.g. 'create_workspace_metric'. */\n tool: string;\n /** Coarse domain bucket, e.g. 'embedding' | 'internal_analytics'. */\n category: string;\n /** Use-case bucket, e.g. 'sql_to_workspace_metric'. */\n workflowIntent: string;\n /** How the request was initiated; 'tool_call' for MCP tool invocations. */\n inputMode: string;\n}\n\nexport const toolContext = new AsyncLocalStorage<ToolCallContext>();\n","import { z } from 'zod';\n\n// Validate without transforming: issuer identity uses exact string comparison.\nexport const oauthHttpsUrl = z.string().refine(value => {\n try {\n const url = new URL(value);\n return url.protocol === 'https:' && !url.username && !url.password && !url.hash;\n } catch { return false; }\n}, 'OAuth URLs must use HTTPS without userinfo or fragments');\n\nexport const oauthConfigSchema = z.object({\n issuer: oauthHttpsUrl.refine(value => {\n try { return !new URL(value).search; } catch { return false; }\n }, 'OAuth issuer must not contain a query'),\n clientId: z.string().min(1),\n clientSecret: z.string().min(1),\n resource: oauthHttpsUrl,\n scope: z.string().min(1).optional(),\n authMethod: z.enum(['client_secret_basic', 'client_secret_post']).default('client_secret_basic'),\n});\n\nexport type OAuthConfig = z.infer<typeof oauthConfigSchema>;\n\nconst metadataSchema = z.object({\n issuer: z.string(),\n token_endpoint: oauthHttpsUrl,\n token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n grant_types_supported: z.array(z.string()).optional(),\n});\nconst tokenSchema = z.object({\n access_token: z.string().regex(/^[A-Za-z0-9\\-._~+/]+=*$/),\n token_type: z.string().refine(value => value.toLowerCase() === 'bearer'),\n expires_in: z.number().finite().positive().optional(),\n});\n\nconst TOKEN_TIMEOUT_MS = 10_000;\nconst FAILURE_COOLDOWN_MS = 30_000;\nconst MAX_REFRESH_SKEW_MS = 60_000;\n\nfunction authError(): Error {\n // Never retain an IdP body, a fetch error, or a schema error as a cause:\n // those can contain credentials and are serialized by callers/telemetry.\n return new Error('OAuth token acquisition failed. Check the configured issuer, client credentials, resource and scopes.');\n}\n\n/** One immutable credential/issuer/resource binding per MCP process client. */\nexport class OAuthClientCredentials {\n private readonly config: OAuthConfig;\n private tokenEndpoint?: string;\n private cached?: { value: string; renewAt: number };\n private pending?: Promise<string>;\n private retryAt = 0;\n\n constructor(config: OAuthConfig) {\n // Also validate programmatic callers; do not expose invalid values in errors.\n const parsed = oauthConfigSchema.safeParse(config);\n if (!parsed.success) throw authError();\n this.config = Object.freeze(parsed.data);\n }\n\n getStatus(): 'configured' | 'ready' | 'unavailable' {\n if (this.cached && Date.now() < this.cached.renewAt) return 'ready';\n if (this.retryAt > 0) return 'unavailable';\n return 'configured';\n }\n\n async getToken(): Promise<string> {\n if (this.cached && Date.now() < this.cached.renewAt) return this.cached.value;\n if (this.pending) return this.pending;\n if (Date.now() < this.retryAt) throw authError();\n\n this.cached = undefined;\n this.pending = this.acquire().catch(() => {\n this.retryAt = Date.now() + FAILURE_COOLDOWN_MS;\n throw authError();\n }).finally(() => { this.pending = undefined; });\n return this.pending;\n }\n\n private async discoverTokenEndpoint(signal: AbortSignal): Promise<string> {\n if (this.tokenEndpoint) return this.tokenEndpoint;\n const issuer = new URL(this.config.issuer);\n const path = issuer.pathname.replace(/\\/$/, '');\n const candidates = [...new Set([\n `${issuer.origin}/.well-known/oauth-authorization-server${path}`,\n `${issuer.origin}/.well-known/openid-configuration${path}`,\n `${issuer.origin}${path}/.well-known/openid-configuration`,\n ])];\n\n for (const url of candidates) {\n // No credentials, cookies, API headers, or redirects during discovery.\n const response = await fetch(url, {\n headers: { Accept: 'application/json' }, redirect: 'error', signal,\n });\n if (response.status === 404 || response.status === 405) continue;\n if (!response.ok) throw authError();\n const metadata = metadataSchema.parse(await response.json());\n if (metadata.issuer !== this.config.issuer) throw authError();\n const methods = metadata.token_endpoint_auth_methods_supported ?? ['client_secret_basic'];\n if (!methods.includes(this.config.authMethod)) throw authError();\n if (metadata.grant_types_supported && !metadata.grant_types_supported.includes('client_credentials')) {\n throw authError();\n }\n this.tokenEndpoint = metadata.token_endpoint;\n return this.tokenEndpoint;\n }\n throw authError();\n }\n\n private async acquire(): Promise<string> {\n // One time budget covers all discovery attempts and token acquisition.\n const signal = AbortSignal.timeout(TOKEN_TIMEOUT_MS);\n const endpoint = await this.discoverTokenEndpoint(signal);\n const body = new URLSearchParams({\n grant_type: 'client_credentials', resource: this.config.resource,\n });\n if (this.config.scope) body.set('scope', this.config.scope);\n const headers: Record<string, string> = {\n Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded',\n };\n if (this.config.authMethod === 'client_secret_post') {\n body.set('client_id', this.config.clientId);\n body.set('client_secret', this.config.clientSecret);\n } else {\n // RFC 6749 2.3.1: form-encode EACH value before constructing Basic auth.\n const encode = (value: string) => new URLSearchParams({ value }).toString().slice(6);\n headers.Authorization = `Basic ${Buffer.from(`${encode(this.config.clientId)}:${encode(this.config.clientSecret)}`).toString('base64')}`;\n }\n\n const startedAt = Date.now();\n const response = await fetch(endpoint, {\n method: 'POST', headers, body: body.toString(), redirect: 'error', signal,\n });\n if (!response.ok) throw authError();\n const token = tokenSchema.parse(await response.json());\n if (token.expires_in !== undefined) {\n const lifetimeMs = token.expires_in * 1000;\n const expiresAt = startedAt + lifetimeMs;\n if (!Number.isFinite(expiresAt) || Date.now() >= expiresAt) throw authError();\n this.cached = {\n value: token.access_token,\n renewAt: expiresAt - Math.min(MAX_REFRESH_SKEW_MS, lifetimeMs * 0.1),\n };\n }\n // With no expires_in, use the token for this call only. No JWT decoding,\n // assumed lifetime, refresh_token grant, disk storage, or background timer.\n this.retryAt = 0;\n return token.access_token;\n }\n}\n","import { parseStudioStream } from '../custom-chart/studio.js';\nimport { TtlCache } from '../utils/cache.js';\nimport type { Config } from '../utils/config.js';\nimport { DatabrainApiError } from '../utils/errors.js';\nimport { logger, registerSecret } from '../utils/logger.js';\nimport type { RequestOptions } from './types.js';\nimport { parseErrorBody } from './error-body.js';\nimport { MCP_SERVER_VERSION } from '../version.js';\nimport { toolContext } from '../utils/tool-context.js';\nimport { OAuthClientCredentials, oauthHttpsUrl } from './oauth-client-credentials.js';\n\nconst MCP_USER_AGENT = `databrain-mcp-server/${MCP_SERVER_VERSION}`;\n\nconst MAX_RETRIES = 3;\nconst REQUEST_TIMEOUT_MS = 30_000;\n\nconst NON_TRANSIENT_PATTERNS = [\n 'out of context',\n 'Definition not found',\n 'not a data question',\n 'Query generation failed',\n 'not found',\n 'not authenticated',\n 'Invalid Service Token',\n 'service token',\n];\n\nexport class DatabrainClient {\n private cache = new TtlCache();\n private runtimeApiToken: string | undefined;\n private readonly oauth?: OAuthClientCredentials;\n private oauthFallback = false;\n\n constructor(private config: Config) {\n registerSecret(config.serviceToken);\n registerSecret(config.apiToken);\n if (config.oauth) {\n if (!oauthHttpsUrl.safeParse(config.apiUrl).success) {\n throw new Error('OAuth requires an HTTPS Databrain API URL without userinfo or fragments.');\n }\n this.oauth = new OAuthClientCredentials(config.oauth);\n // Prevent later mutation of a caller-owned config from moving credentials\n // or the resource bearer to another API/issuer within this client session.\n this.config = Object.freeze({ ...config });\n }\n }\n\n hasApiToken(): boolean {\n return !!(this.runtimeApiToken || this.config.apiToken);\n }\n\n /** The hosted composition supplies a signed-in identity, unlike local API credentials. */\n isHosted(): boolean { return false; }\n\n setRuntimeApiToken(token: string): void {\n registerSecret(token);\n this.runtimeApiToken = token;\n logger.info('Runtime API token set for this session');\n }\n\n getServiceToken(): string | undefined {\n return this.config.serviceToken;\n }\n\n getApiUrl(): string {\n return this.config.apiUrl;\n }\n\n getDemoDomain(): string {\n return this.config.demoDomain;\n }\n\n /**\n * Describes which credential is currently used as the bearer for outgoing\n * API calls. Used by `whoami` so the LLM can give the user a truthful answer.\n */\n getActiveAuth():\n | { source: 'service-token'; oauthFallback?: boolean }\n | { source: 'oauth-client-credentials'; status: 'configured' | 'ready' | 'unavailable' }\n | { source: 'api-token' }\n | { source: 'none' } {\n if (this.oauth) {\n if (this.oauthFallback) return { source: 'service-token', oauthFallback: true };\n return { source: 'oauth-client-credentials', status: this.oauth.getStatus() };\n }\n if (this.config.serviceToken) return { source: 'service-token' };\n if (this.runtimeApiToken || this.config.apiToken) return { source: 'api-token' };\n return { source: 'none' };\n }\n\n private async getToken(auth: 'service' | 'api' | 'none'): Promise<string | undefined> {\n if (auth === 'none') return undefined;\n if (auth === 'service') {\n if (this.oauth) {\n try {\n const token = await this.oauth.getToken();\n this.oauthFallback = false;\n return token;\n } catch {\n if (!this.config.serviceToken) {\n throw new DatabrainApiError(0, 'OAUTH_TOKEN_ERROR',\n 'OAuth token acquisition failed. Check the configured issuer, client credentials, resource and scopes.');\n }\n if (!this.oauthFallback) logger.warn('OAuth unavailable; using the configured static service token.');\n this.oauthFallback = true;\n }\n }\n return this.config.serviceToken;\n }\n return this.runtimeApiToken || this.config.apiToken;\n }\n\n async request<T>(options: RequestOptions): Promise<T> {\n return this.requestInternal<T>(options);\n }\n\n private async requestInternal<T>(options: RequestOptions): Promise<T> {\n const usesOAuth = !!this.oauth && options.auth === 'service' && !options.token;\n // An OAuth renewal can switch to a differently scoped static principal.\n // Do not serve/store service response caches across that auth boundary.\n const cacheAllowed = !usesOAuth;\n // Invalidate caches first\n if (options.invalidateCache) {\n for (const prefix of options.invalidateCache) {\n this.cache.invalidateByPrefix(prefix);\n }\n }\n\n // Check cache\n if (cacheAllowed && options.cacheKey && options.cacheTtlMs) {\n const cached = this.cache.get<T>(options.cacheKey);\n if (cached !== undefined) {\n logger.debug(`Cache hit: ${options.cacheKey}`);\n return cached;\n }\n }\n\n let token = options.token ?? await this.getToken(options.auth);\n if (options.auth !== 'none' && !options.token && !token) {\n if (options.auth === 'service') {\n throw new DatabrainApiError(\n 401,\n 'MISSING_SERVICE_TOKEN',\n 'DATABRAIN_SERVICE_TOKEN is required for this operation (org-level token for discovery and data app management). It must be set in the MCP server configuration — do not ask the user for it at runtime.',\n );\n }\n throw new DatabrainApiError(\n 401,\n 'MISSING_API_TOKEN',\n 'A per-data-app API token is required for this embedding operation but none is configured. ' +\n 'Call `create_api_token` to generate one, or `set_api_token` if you already have the value. Do not ask the user for this token — create it via the MCP tools.',\n );\n }\n\n // Build URL\n let url = `${this.config.apiUrl}${options.path}`;\n if (options.query) {\n const params = new URLSearchParams(options.query);\n url += `?${params.toString()}`;\n }\n\n let lastError: Error | undefined;\n\n for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {\n try {\n if (usesOAuth && attempt > 1) token = await this.getToken(options.auth);\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': MCP_USER_AGENT,\n 'X-Databrain-Client': MCP_USER_AGENT,\n ...options.headers,\n };\n // Tag the call with the active tool's intent so backend telemetry can\n // attribute usage (embedding vs internal analytics, per-tool). Present\n // only when invoked from within a tool handler (see registry wrapper).\n const ctx = toolContext.getStore();\n if (ctx) {\n headers['X-Databrain-MCP-Tool'] = ctx.tool;\n headers['X-Databrain-MCP-Tool-Category'] = ctx.category;\n headers['X-Databrain-MCP-Workflow-Intent'] = ctx.workflowIntent;\n headers['X-Databrain-MCP-Input-Mode'] = ctx.inputMode;\n }\n if (token) {\n // Guest-token endpoints (auth: 'none' with a minted token) read the\n // token from `x-plugin-token` and require a whitelisted Origin.\n // DATABRAIN_DOMAINS includes `usedatabrain.com`, so `mcp.usedatabrain.com`\n // passes the whitelist without needing a per-company config.\n if (options.auth === 'none') {\n headers['x-plugin-token'] = token;\n headers['Origin'] = 'https://mcp.usedatabrain.com';\n } else {\n headers['Authorization'] = `Bearer ${token}`;\n }\n }\n\n const response = await fetch(url, {\n method: options.method,\n headers,\n body: options.body ? JSON.stringify(options.body) : undefined,\n signal: AbortSignal.timeout(options.timeoutMs || REQUEST_TIMEOUT_MS),\n ...(usesOAuth ? { redirect: 'error' as const } : {}),\n });\n\n if (!response.ok) {\n // An untrusted API can echo credentials in its error body. Keep\n // OAuth errors body-free in both tool output and telemetry. Never\n // retry/downgrade a backend denial with the static service token.\n if (usesOAuth) {\n throw new DatabrainApiError(response.status, 'OAUTH_API_ERROR',\n `Databrain API request failed with status ${response.status} using configured service credentials.`);\n }\n const errorBody = await response.text();\n logger.warn(`[API Error] ${options.method} ${options.path} status=${response.status} body=${errorBody.slice(0, 500)}`);\n let parsed: unknown = {};\n try {\n parsed = JSON.parse(errorBody);\n } catch {\n // not JSON\n }\n\n const envelope = parseErrorBody(parsed);\n const errorMsg = envelope.message || `API request failed with status ${response.status}`;\n const error = new DatabrainApiError(\n response.status,\n envelope.code || `HTTP_${response.status}`,\n errorMsg,\n parsed,\n envelope.hint,\n envelope.retryable,\n );\n\n // Retry on 429 or 5xx (but not when the error is clearly non-transient)\n // The server's own retryable flag wins over the status heuristic.\n const isTransient =\n envelope.retryable !== undefined\n ? envelope.retryable && (response.status === 429 || response.status >= 500)\n : response.status === 429 ||\n (response.status >= 500 &&\n !NON_TRANSIENT_PATTERNS.some((p) => errorMsg.includes(p)));\n if (isTransient && attempt < MAX_RETRIES) {\n const delay = Math.min(1000 * Math.pow(2, attempt - 1), 8000);\n logger.warn(`Retrying in ${delay}ms (attempt ${attempt}/${MAX_RETRIES})`, {\n status: response.status,\n path: options.path,\n });\n await new Promise((r) => setTimeout(r, delay));\n lastError = error;\n continue;\n }\n\n throw error;\n }\n\n const text = await response.text();\n let data = (options.responseFormat === 'studio-sse' ? parseStudioStream(text) : text ? JSON.parse(text) : {}) as T;\n\n // Databrain API wraps most responses in { data: ... } — unwrap automatically\n if (\n !options.skipDataUnwrap &&\n data &&\n typeof data === 'object' &&\n !Array.isArray(data) &&\n 'data' in data\n ) {\n const inner = (data as Record<string, unknown>).data;\n if (inner !== null && inner !== undefined) {\n data = inner as unknown as T;\n }\n }\n\n // Store in cache\n if (cacheAllowed && options.cacheKey && options.cacheTtlMs) {\n this.cache.set(options.cacheKey, data, options.cacheTtlMs);\n }\n\n return data;\n } catch (err) {\n if (err instanceof DatabrainApiError) throw err;\n\n if (attempt < MAX_RETRIES && (err as Error)?.name === 'TimeoutError' && !options.noRetryOnTimeout) {\n const delay = Math.min(1000 * Math.pow(2, attempt - 1), 8000);\n logger.warn(`Request timed out, retrying in ${delay}ms`, { path: options.path });\n await new Promise((r) => setTimeout(r, delay));\n lastError = err as Error;\n continue;\n }\n\n throw new DatabrainApiError(\n 0,\n 'NETWORK_ERROR',\n usesOAuth ? 'Failed to connect to Databrain API using configured service credentials.'\n : `Failed to connect to Databrain API: ${(err as Error).message}`,\n );\n }\n }\n\n throw lastError || new DatabrainApiError(0, 'UNKNOWN', 'Request failed after retries');\n }\n}\n","import type { DatabrainClient } from '../client/databrain-client.js';\nimport type { CustomChartBundle, Problem } from '../custom-chart/types.js';\n\n/**\n * Service-token custom chart API (brief section 5), mounted by the backend\n * under /api/mcp/custom-charts. Company scope comes from the token; nothing\n * here sends a company or tenant selector.\n */\nexport const CUSTOM_CHARTS_PATH = '/api/mcp/custom-charts';\nconst LIST_CACHE_KEY = 'list_custom_charts';\n\nexport interface CustomChartVersionSummary {\n id: string;\n versionNumber: number;\n contentHash: string;\n sizeBytes?: number;\n createdAt?: string;\n createdBy?: string | null;\n [key: string]: unknown;\n}\n\nexport interface CustomChartSummary {\n id: string;\n key: string;\n name: string;\n description?: string | null;\n status: 'private' | 'published' | string;\n chartType?: string;\n publishedVersionId?: string | null;\n previewVersionId?: string | null;\n publishedVersionNumber?: number | null;\n previewVersionNumber?: number | null;\n versionsCount?: number;\n iconSvg?: string;\n createdBy?: string | null;\n createdAt?: string;\n updatedAt?: string;\n [key: string]: unknown;\n}\n\nexport interface CustomChartDetail extends CustomChartSummary {\n versions?: CustomChartVersionSummary[];\n}\n\nexport interface ValidateResponse {\n ok: boolean;\n problems: Problem[];\n contentHash?: string;\n sizeBytes?: number;\n}\n\nexport interface UploadResponse {\n chart: CustomChartSummary;\n version: CustomChartVersionSummary;\n created: 'chart' | 'version' | 'none';\n}\n\nexport interface UploadBody extends CustomChartBundle {\n name?: string;\n description?: string;\n}\n\nconst encodeKey = (key: string): string => encodeURIComponent(key);\n\nexport class CustomChartsApi {\n constructor(private readonly client: DatabrainClient) {}\n\n async list(): Promise<CustomChartSummary[]> {\n const response = await this.client.request<{ charts?: CustomChartSummary[] } | CustomChartSummary[]>({\n method: 'GET',\n path: CUSTOM_CHARTS_PATH,\n auth: 'service',\n cacheKey: LIST_CACHE_KEY,\n cacheTtlMs: 30_000,\n });\n if (Array.isArray(response)) return response;\n return Array.isArray(response?.charts) ? response.charts : [];\n }\n\n async get(key: string): Promise<CustomChartDetail> {\n const response = await this.client.request<{ chart?: CustomChartDetail } | CustomChartDetail>({\n method: 'GET',\n path: `${CUSTOM_CHARTS_PATH}/${encodeKey(key)}`,\n auth: 'service',\n });\n const wrapped = response as { chart?: CustomChartDetail };\n return wrapped.chart ? wrapped.chart : (response as CustomChartDetail);\n }\n\n /** Never persists. The server repeats every client side check. */\n async validate(body: UploadBody): Promise<ValidateResponse> {\n const response = await this.client.request<ValidateResponse>({\n method: 'POST',\n path: `${CUSTOM_CHARTS_PATH}/validate`,\n auth: 'service',\n body,\n timeoutMs: 60_000,\n });\n return {\n ok: response.ok === true,\n problems: Array.isArray(response.problems) ? response.problems : [],\n contentHash: response.contentHash,\n sizeBytes: response.sizeBytes,\n };\n }\n\n /** Creates the chart (first upload) or a preview version; idempotent on contentHash. */\n async upload(body: UploadBody): Promise<UploadResponse> {\n return this.client.request<UploadResponse>({\n method: 'POST',\n path: CUSTOM_CHARTS_PATH,\n auth: 'service',\n body,\n timeoutMs: 60_000,\n invalidateCache: [LIST_CACHE_KEY],\n });\n }\n\n async bundle(key: string, versionId: string): Promise<CustomChartBundle> {\n return this.client.request<CustomChartBundle>({ method: 'GET',\n path: `${CUSTOM_CHARTS_PATH}/${encodeKey(key)}/versions/${encodeURIComponent(versionId)}/bundle`,\n auth: 'service' });\n }\n\n async publish(key: string, versionId?: string): Promise<{ chart: CustomChartSummary }> {\n return this.client.request<{ chart: CustomChartSummary }>({\n method: 'POST',\n path: `${CUSTOM_CHARTS_PATH}/${encodeKey(key)}/publish`,\n auth: 'service',\n body: versionId ? { versionId } : {},\n invalidateCache: [LIST_CACHE_KEY],\n });\n }\n\n async discardPreview(key: string): Promise<{ chart: CustomChartSummary }> {\n return this.client.request<{ chart: CustomChartSummary }>({\n method: 'POST',\n path: `${CUSTOM_CHARTS_PATH}/${encodeKey(key)}/discard-preview`,\n auth: 'service',\n body: {},\n invalidateCache: [LIST_CACHE_KEY],\n });\n }\n}\n","import type { DatabrainClient } from '../client/databrain-client.js';\nimport { CustomChartsApi } from '../api/custom-charts-api.js';\nimport type { CustomChartSummary } from '../api/custom-charts-api.js';\nimport { DatabrainApiError } from '../utils/errors.js';\nimport type { Problem } from './types.js';\n\nexport {\n CustomChartsApi,\n CUSTOM_CHARTS_PATH,\n type CustomChartDetail,\n type CustomChartSummary,\n type CustomChartVersionSummary,\n type UploadBody,\n type UploadResponse,\n type ValidateResponse,\n} from '../api/custom-charts-api.js';\n\nexport function createCustomChartsApi(client: DatabrainClient): CustomChartsApi {\n return new CustomChartsApi(client);\n}\n\n/** The backend error body is { error: { code, message, problems? } }. Pull the problems out. */\nexport function apiProblems(err: unknown): Problem[] {\n if (!(err instanceof DatabrainApiError)) return [];\n const details = err.details as { error?: { problems?: unknown }; problems?: unknown } | undefined;\n const list = details?.error?.problems ?? details?.problems;\n if (!Array.isArray(list)) return [];\n return list.filter(\n (item): item is Problem =>\n !!item && typeof item === 'object' && typeof (item as Problem).code === 'string' && typeof (item as Problem).message === 'string',\n );\n}\n\nexport interface UploadPlan {\n action: 'create chart' | 'create version' | 'no change';\n key: string;\n existing?: CustomChartSummary;\n nextVersionNumber: number;\n summary: string;\n}\n\n/**\n * What an apply will do, computed from the chart list (brief section 8):\n * \"will create chart\" when the key is new, \"will create version n\" when the\n * chart exists. The content-hash replay (\"none\") is only known to the server.\n */\nexport function planUpload(key: string, existing: CustomChartSummary | undefined, versionsKnown?: number): UploadPlan {\n if (!existing) {\n return { action: 'create chart', key, nextVersionNumber: 1, summary: `will create chart custom:${key} (version 1, status private)` };\n }\n const count = typeof versionsKnown === 'number' ? versionsKnown : typeof existing.versionsCount === 'number' ? existing.versionsCount : undefined;\n const next = count !== undefined ? count + 1 : NaN;\n const label = Number.isFinite(next) ? `version ${next}` : 'the next version';\n return {\n action: 'create version',\n key,\n existing,\n nextVersionNumber: Number.isFinite(next) ? next : 0,\n summary: `will create ${label} of custom:${key} in preview (status stays ${existing.status}; the published version keeps serving until you publish)`,\n };\n}\n","import { readTemplateFiles } from './assets.js';\nimport { isId, validateManifest } from './manifest.js';\nimport type { CustomChartOption, CustomChartSlot, Problem } from './types.js';\n\n/**\n * A chart project is the template folder with manifest.json and package.json\n * rewritten for the requested key, name, slots and options. Every other file\n * is copied verbatim so that the guide, the types and the sample chart stay\n * byte identical to what the tests exercise.\n */\nexport interface ScaffoldInput {\n key: string;\n name: string;\n description?: string;\n slots?: CustomChartSlot[];\n options?: CustomChartOption[];\n}\n\nexport interface ScaffoldResult {\n ok: boolean;\n problems: Problem[];\n files: Record<string, string>;\n nextStep: string;\n}\n\nconst DEFAULT_SLOTS: CustomChartSlot[] = [\n { id: 'category', label: 'Category', role: 'dimension', types: ['string'], required: true, description: 'One bar per value.' },\n { id: 'value', label: 'Value', role: 'measure', types: ['number'], required: true },\n { id: 'target', label: 'Target', role: 'measure', types: ['number'], required: false },\n];\n\nexport function scaffoldProject(input: ScaffoldInput): ScaffoldResult {\n const template = readTemplateFiles();\n const templateManifest = JSON.parse(template['manifest.json']) as {\n slots: CustomChartSlot[];\n options: CustomChartOption[];\n };\n const problems: Problem[] = [];\n if (!isId(input.key)) {\n problems.push({\n code: 'manifest.id.invalid',\n path: '/id',\n message: 'key must match ^[a-z][a-z0-9_-]{0,63}$ (lowercase letters, digits, _ and -).',\n });\n }\n const name = typeof input.name === 'string' ? input.name.trim() : '';\n if (name.length === 0 || name.length > 256) {\n problems.push({ code: 'manifest.name.invalid', path: '/name', message: 'name must be 1 to 256 characters.' });\n }\n\n const manifest: Record<string, unknown> = {\n schemaVersion: 2,\n id: input.key,\n name,\n version: '1.0.0',\n ...(input.description ? { description: input.description } : {}),\n slots: input.slots && input.slots.length > 0 ? input.slots : templateManifest.slots ?? DEFAULT_SLOTS,\n options: input.options ?? templateManifest.options,\n };\n problems.push(...validateManifest(manifest));\n\n const packageJson = JSON.parse(template['package.json']) as Record<string, unknown>;\n packageJson.name = input.key;\n\n const files: Record<string, string> = {};\n for (const [file, content] of Object.entries(template)) {\n if (file === 'manifest.json') files[file] = JSON.stringify(manifest, null, 2) + '\\n';\n else if (file === 'package.json') files[file] = JSON.stringify(packageJson, null, 2) + '\\n';\n else files[file] = content;\n }\n\n return {\n ok: problems.length === 0,\n problems,\n files,\n nextStep:\n 'Write these files into a folder, edit chart.ts, then run `databrain custom-chart validate` and ' +\n '`databrain custom-chart build`. Upload with `databrain custom-chart upload` or the custom_chart_upload tool.',\n };\n}\n"],"mappings":";;;;;;;;AAAO,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAC3C,YACkB,QACA,MAChB,SACgB,SAEA,YACA,WAChB;AACA,UAAM,OAAO;AARG;AACA;AAEA;AAEA;AACA;AAGhB,SAAK,OAAO;AAAA,EACd;AAAA,EAEA,iBAAoF;AAClF,UAAM,QAAQ,CAAC,UAAU,KAAK,OAAO,EAAE;AACvC,UAAM,aAAa,KAAK,cAAc;AACtC,QAAI,WAAY,OAAM,KAAK,UAAU;AACrC,UAAM,OAAO,KAAK,aAAa,SAAS,KAAK,UAAU,KAAK,KAAK,KAAK;AACtE,QAAI,KAAM,OAAM,KAAK,IAAI;AACzB,WAAO;AAAA,MACL,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,MAAM,KAAK,MAAM,EAAE,CAAC;AAAA,MACpD,SAAS;AAAA,IACX;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQQ,gBAAwB;AAC9B,QAAI,KAAK,SAAS,OAAO,KAAK,UAAU,IAAK,QAAO;AACpD,QAAI,CAAC,KAAK,WAAW,OAAO,KAAK,YAAY,SAAU,QAAO;AAE9D,UAAM,WAAW,oBAAI,IAAI,CAAC,WAAW,UAAU,SAAS,QAAQ,QAAQ,QAAQ,WAAW,CAAC;AAC5F,UAAM,QAAiC,CAAC;AACxC,eAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,KAAK,OAAkC,GAAG;AAC5E,UAAI,SAAS,IAAI,CAAC,EAAG;AACrB,UAAI,MAAM,QAAQ,MAAM,OAAW;AACnC,YAAM,CAAC,IA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AAK,MAAM,SAAS,cAAc,CAAC;AACvD,cAAY,OAAO,MAAM;AAEzB,QAAM,QAAgC,CAAC;AACvC,aAAW,CAAC,MAAM,OAAO,KAAK,OAAO,QAAQ,QAAQ,GAAG;AACtD,QAAI,SAAS,gBAAiB,OAAM,IAAI,IAAI,KAAK,UAAU,UAAU,MAAM,CAAC,IAAI;AAAA,aACvE,SAAS,eAAgB,OAAM,IAAI,IAAI,KAAK,UAAU,aAAa,MAAM,CAAC,IAAI;AAAA,QAClF,OAAM,IAAI,IAAI;AAAA,EACrB;AAEA,SAAO;AAAA,IACL,IAAI,SAAS,WAAW;AAAA,IACxB;AAAA,IACA;AAAA,IACA,UACE;AAAA,EAEJ;AACF;","names":["z"]}
|
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
registerChartApps
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-ZTHGF27R.js";
|
|
5
5
|
import {
|
|
6
6
|
enableChartApps,
|
|
7
7
|
registerAllPrompts,
|
|
8
8
|
registerAllResources,
|
|
9
9
|
registerAllTools
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-OLOC2MTA.js";
|
|
11
11
|
import {
|
|
12
12
|
DatabrainClient,
|
|
13
13
|
MCP_SERVER_VERSION
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-347U6GXR.js";
|
|
15
15
|
|
|
16
16
|
// src/apps/server.ts
|
|
17
17
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
@@ -31,4 +31,4 @@ function createChartAppServer(config, backend) {
|
|
|
31
31
|
export {
|
|
32
32
|
createChartAppServer
|
|
33
33
|
};
|
|
34
|
-
//# sourceMappingURL=chunk-
|
|
34
|
+
//# sourceMappingURL=chunk-LACJHQYH.js.map
|