drizzle-cube 0.5.0 → 0.5.3
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 +4 -0
- package/dist/adapters/express/index.cjs +2 -2
- package/dist/adapters/express/index.js +106 -102
- package/dist/adapters/fastify/index.cjs +2 -2
- package/dist/adapters/fastify/index.js +109 -105
- package/dist/adapters/{handler-3LGcjLtr.js → handler-BC3nFNxV.js} +2 -2
- package/dist/adapters/{handler-BzzbVpcl.cjs → handler-Cqf-CqAS.cjs} +2 -2
- package/dist/adapters/hono/index.cjs +1 -1
- package/dist/adapters/hono/index.js +41 -45
- package/dist/adapters/locale-BoiA6WiV.cjs +198 -0
- package/dist/adapters/{locale-DTnJrxm1.js → locale-D9VQkLXt.js} +442 -404
- package/dist/adapters/mcp-tools.cjs +1 -1
- package/dist/adapters/mcp-tools.d.ts +7 -3
- package/dist/adapters/mcp-tools.js +28 -28
- package/dist/adapters/mcp-transport-B0mgxRnJ.js +579 -0
- package/dist/adapters/mcp-transport-irsahKmD.cjs +39 -0
- package/dist/adapters/mcp-transport.d.ts +14 -2
- package/dist/adapters/nextjs/index.cjs +1 -1
- package/dist/adapters/nextjs/index.js +140 -136
- package/dist/adapters/{openai-C4BD8xnN.cjs → openai-B4N3KfTG.cjs} +1 -1
- package/dist/adapters/{openai-CaSQEduB.js → openai-BWdm0JvG.js} +1 -1
- package/dist/adapters/openai-CoqT_FM5.cjs +16 -0
- package/dist/{server/openai-CqZg6zYL.js → adapters/openai-D0Nsvc9L.js} +824 -720
- package/dist/adapters/{utils-DOg9oGdt.js → utils-CTYvfZ3I.js} +711 -713
- package/dist/adapters/{utils-DNrj-ryp.cjs → utils-XPOzzMdY.cjs} +5 -5
- package/dist/adapters/utils.cjs +1 -1
- package/dist/adapters/utils.d.ts +38 -2
- package/dist/adapters/utils.js +1 -1
- package/dist/cli/index.cjs +2 -2
- package/dist/client/charts.js +10 -10
- package/dist/client/chunks/{DashboardEditModal-cSSIAZGy.js → DashboardEditModal-IU_0dgfC.js} +12 -12
- package/dist/client/chunks/{DashboardEditModal-cSSIAZGy.js.map → DashboardEditModal-IU_0dgfC.js.map} +1 -1
- package/dist/client/chunks/{FieldSearchModal-CZNo4pNK.js → FieldSearchModal-BCWanpPX.js} +3 -3
- package/dist/client/chunks/{FieldSearchModal-CZNo4pNK.js.map → FieldSearchModal-BCWanpPX.js.map} +1 -1
- package/dist/client/chunks/KpiDelta-_igN6cJa.js +2 -0
- package/dist/client/chunks/KpiNumber-t5n8PtRU.js +2 -0
- package/dist/client/chunks/KpiText-BCZJJ6a0.js +2 -0
- package/dist/client/chunks/{RetentionCombinedChart-BD8tGeM_.js → RetentionCombinedChart-CQMBODsK.js} +2 -2
- package/dist/client/chunks/{RetentionCombinedChart-BD8tGeM_.js.map → RetentionCombinedChart-CQMBODsK.js.map} +1 -1
- package/dist/client/chunks/SchemaVisualization-BUUhlOvG.js +2 -0
- package/dist/client/chunks/SchemaVisualizationLazy-CwaPCUL0.js +2 -0
- package/dist/client/chunks/{analysis-builder-BeVZhiQ5.js → analysis-builder-Dm6eD_AX.js} +6 -6
- package/dist/client/chunks/{analysis-builder-BeVZhiQ5.js.map → analysis-builder-Dm6eD_AX.js.map} +1 -1
- package/dist/client/chunks/{analysis-builder-shared-BWc7ZZnG.js → analysis-builder-shared-DT5bXwCA.js} +6 -6
- package/dist/client/chunks/{analysis-builder-shared-BWc7ZZnG.js.map → analysis-builder-shared-DT5bXwCA.js.map} +1 -1
- package/dist/client/chunks/{chart-area-D63kG8OT.js → chart-area-DDti9Qtp.js} +2 -2
- package/dist/client/chunks/{chart-area-D63kG8OT.js.map → chart-area-DDti9Qtp.js.map} +1 -1
- package/dist/client/chunks/{chart-bar-BEfsCLjl.js → chart-bar-B3s9qDlh.js} +2 -2
- package/dist/client/chunks/{chart-bar-BEfsCLjl.js.map → chart-bar-B3s9qDlh.js.map} +1 -1
- package/dist/client/chunks/{chart-data-table-C3Xh9jwL.js → chart-data-table-Qrt6EAno.js} +17 -17
- package/dist/client/chunks/{chart-data-table-C3Xh9jwL.js.map → chart-data-table-Qrt6EAno.js.map} +1 -1
- package/dist/client/chunks/{chart-kpi-delta-CYE0S1x_.js → chart-kpi-delta-CgldZ7zO.js} +3 -3
- package/dist/client/chunks/{chart-kpi-delta-CYE0S1x_.js.map → chart-kpi-delta-CgldZ7zO.js.map} +1 -1
- package/dist/client/chunks/{chart-kpi-number-BlZ79xHW.js → chart-kpi-number-ByfuX1ki.js} +5 -5
- package/dist/client/chunks/{chart-kpi-number-BlZ79xHW.js.map → chart-kpi-number-ByfuX1ki.js.map} +1 -1
- package/dist/client/chunks/{chart-kpi-text-DY1BnxPe.js → chart-kpi-text-DeNuDraJ.js} +2 -2
- package/dist/client/chunks/{chart-kpi-text-DY1BnxPe.js.map → chart-kpi-text-DeNuDraJ.js.map} +1 -1
- package/dist/client/chunks/{chart-line-CBsTThTv.js → chart-line-RdZwtk27.js} +2 -2
- package/dist/client/chunks/{chart-line-CBsTThTv.js.map → chart-line-RdZwtk27.js.map} +1 -1
- package/dist/client/chunks/{chart-markdown-BWaWVkuz.js → chart-markdown-CiGRZdJj.js} +1203 -1139
- package/dist/client/chunks/chart-markdown-CiGRZdJj.js.map +1 -0
- package/dist/client/chunks/{chart-measure-profile-B41qCTBG.js → chart-measure-profile-Ckjw9bX6.js} +2 -2
- package/dist/client/chunks/{chart-measure-profile-B41qCTBG.js.map → chart-measure-profile-Ckjw9bX6.js.map} +1 -1
- package/dist/client/chunks/{chart-pie-Djbu8x2v.js → chart-pie-BvY4FY__.js} +2 -2
- package/dist/client/chunks/{chart-pie-Djbu8x2v.js.map → chart-pie-BvY4FY__.js.map} +1 -1
- package/dist/client/chunks/{chart-radar-BsTcKV0K.js → chart-radar-DjiiEAmc.js} +2 -2
- package/dist/client/chunks/{chart-radar-BsTcKV0K.js.map → chart-radar-DjiiEAmc.js.map} +1 -1
- package/dist/client/chunks/{chart-radial-bar-Du7XNnwE.js → chart-radial-bar-lla_JEYu.js} +2 -2
- package/dist/client/chunks/{chart-radial-bar-Du7XNnwE.js.map → chart-radial-bar-lla_JEYu.js.map} +1 -1
- package/dist/client/chunks/{chart-scatter-D8krEYsA.js → chart-scatter-DwXnI0rr.js} +2 -2
- package/dist/client/chunks/{chart-scatter-D8krEYsA.js.map → chart-scatter-DwXnI0rr.js.map} +1 -1
- package/dist/client/chunks/{chart-tree-map-C5C2iaWM.js → chart-tree-map-DJHoA26f.js} +2 -2
- package/dist/client/chunks/{chart-tree-map-C5C2iaWM.js.map → chart-tree-map-DJHoA26f.js.map} +1 -1
- package/dist/client/chunks/{chart-waterfall-BGdPrJ5Y.js → chart-waterfall-Y7c8csO5.js} +2 -2
- package/dist/client/chunks/{chart-waterfall-BGdPrJ5Y.js.map → chart-waterfall-Y7c8csO5.js.map} +1 -1
- package/dist/client/chunks/{core-DcfMGTVa.js → core-Dk6z6kC0.js} +2 -2
- package/dist/client/chunks/{core-DcfMGTVa.js.map → core-Dk6z6kC0.js.map} +1 -1
- package/dist/client/chunks/{exceljs.min-CcjgM-qg.js → exceljs.min-DaJsLlWM.js} +24 -24
- package/dist/client/chunks/{exceljs.min-CcjgM-qg.js.map → exceljs.min-DaJsLlWM.js.map} +1 -1
- package/dist/client/chunks/{schema-visualization-Xp60Ff2W.js → schema-visualization-DWwJukK7.js} +8 -8
- package/dist/client/chunks/{schema-visualization-Xp60Ff2W.js.map → schema-visualization-DWwJukK7.js.map} +1 -1
- package/dist/client/chunks/{syntaxHighlighting-CnDujqwg.js → syntaxHighlighting-D8J6Yt9j.js} +2 -2
- package/dist/client/chunks/{syntaxHighlighting-CnDujqwg.js.map → syntaxHighlighting-D8J6Yt9j.js.map} +1 -1
- package/dist/client/chunks/{useDebounce-CfmUMFau.js → useDebounce-DyJVREop.js} +2 -2
- package/dist/client/chunks/{useDebounce-CfmUMFau.js.map → useDebounce-DyJVREop.js.map} +1 -1
- package/dist/client/chunks/{useExplainAI-BKGmejIj.js → useExplainAI-CxSkjocM.js} +4 -4
- package/dist/client/chunks/{useExplainAI-BKGmejIj.js.map → useExplainAI-CxSkjocM.js.map} +1 -1
- package/dist/client/chunks/{utils-BldkcRHv.js → utils-BHZdKxua.js} +2 -2
- package/dist/client/chunks/{utils-BldkcRHv.js.map → utils-BHZdKxua.js.map} +1 -1
- package/dist/client/chunks/{vendor-ClXpIiea.js → vendor-CBD_Olr0.js} +8 -8
- package/dist/client/chunks/{vendor-ClXpIiea.js.map → vendor-CBD_Olr0.js.map} +1 -1
- package/dist/client/components.js +3 -3
- package/dist/client/hooks.js +3 -3
- package/dist/client/icons.js +1 -1
- package/dist/client/index.js +11 -11
- package/dist/client/providers.js +1 -1
- package/dist/client/schema.js +1 -1
- package/dist/client/utils.js +5 -5
- package/dist/client-bundle-stats.html +1 -1
- package/dist/mcp-app/mcp-app.html +39 -37
- package/dist/server/index.cjs +42 -42
- package/dist/server/index.js +1009 -971
- package/dist/server/{openai-D9Zjuby1.cjs → openai-BfiZU0rG.cjs} +1 -1
- package/dist/server/openai-BwsBio1K.cjs +16 -0
- package/dist/server/{openai-rwauPzCT.js → openai-CLWSwD-D.js} +1 -1
- package/dist/{adapters/openai-BAnEZgKZ.js → server/openai-zpXlGbbF.js} +824 -720
- package/package.json +2 -2
- package/dist/adapters/locale-DueXjqMh.cjs +0 -198
- package/dist/adapters/mcp-transport-45SiFcCH.cjs +0 -39
- package/dist/adapters/mcp-transport-Bxpc4mRy.js +0 -553
- package/dist/adapters/openai-4JP2B6pB.cjs +0 -16
- package/dist/client/chunks/KpiDelta-Dll_eCV1.js +0 -2
- package/dist/client/chunks/KpiNumber-BPlR92hI.js +0 -2
- package/dist/client/chunks/KpiText-BIxq7Jso.js +0 -2
- package/dist/client/chunks/SchemaVisualization-CCICjhvv.js +0 -2
- package/dist/client/chunks/SchemaVisualizationLazy-DraGsMx6.js +0 -2
- package/dist/client/chunks/chart-markdown-BWaWVkuz.js.map +0 -1
- package/dist/server/openai-DmuEbFd6.cjs +0 -16
|
@@ -1,46 +1,46 @@
|
|
|
1
|
-
import { a as e, f as t, i as n, o as r, r as i, u as a, v as o } from "../utils-
|
|
2
|
-
import { i as s, n as c, r as l, t as u } from "../locale-
|
|
3
|
-
import {
|
|
1
|
+
import { a as e, f as t, i as n, o as r, r as i, u as a, v as o } from "../utils-CTYvfZ3I.js";
|
|
2
|
+
import { i as s, n as c, r as l, t as u } from "../locale-D9VQkLXt.js";
|
|
3
|
+
import { S as d, _ as f, a as p, b as m, c as h, g, h as _, i as v, l as y, m as b, o as x, r as S, u as C, v as w, x as T, y as E } from "../mcp-transport-B0mgxRnJ.js";
|
|
4
4
|
//#region src/adapters/fastify/index.ts
|
|
5
|
-
var
|
|
6
|
-
let { cubes:
|
|
7
|
-
if (!
|
|
8
|
-
let
|
|
9
|
-
if (
|
|
5
|
+
var D = function(o, D, O) {
|
|
6
|
+
let { cubes: k, drizzle: A, schema: j, extractSecurityContext: M, engineType: N, cors: P, basePath: F = "/cubejs-api/v1", bodyLimit: I = 10485760, cache: L, mcp: R = { enabled: !0 }, agent: z } = D;
|
|
7
|
+
if (!k || k.length === 0) return O(/* @__PURE__ */ Error("At least one cube must be provided in the cubes array"));
|
|
8
|
+
let B = async (e) => l(await M(e), c((t) => e.headers[t.toLowerCase()]));
|
|
9
|
+
if (P) {
|
|
10
10
|
let e = {
|
|
11
|
-
...
|
|
12
|
-
allowedHeaders: u(
|
|
11
|
+
...P,
|
|
12
|
+
allowedHeaders: u(P.allowedHeaders)
|
|
13
13
|
};
|
|
14
14
|
o.register(import("@fastify/cors"), e);
|
|
15
15
|
}
|
|
16
16
|
o.addHook("onRequest", async (e, t) => {
|
|
17
17
|
e.method === "POST" && (e.body = void 0);
|
|
18
18
|
});
|
|
19
|
-
let
|
|
20
|
-
drizzle:
|
|
21
|
-
schema:
|
|
22
|
-
engineType:
|
|
23
|
-
cache:
|
|
24
|
-
rlsSetup:
|
|
19
|
+
let V = new s({
|
|
20
|
+
drizzle: A,
|
|
21
|
+
schema: j,
|
|
22
|
+
engineType: N,
|
|
23
|
+
cache: L,
|
|
24
|
+
rlsSetup: D.rlsSetup
|
|
25
25
|
});
|
|
26
|
-
if (
|
|
27
|
-
|
|
28
|
-
}), o.post(`${
|
|
29
|
-
bodyLimit:
|
|
26
|
+
if (k.forEach((e) => {
|
|
27
|
+
V.registerCube(e);
|
|
28
|
+
}), o.post(`${F}/load`, {
|
|
29
|
+
bodyLimit: I,
|
|
30
30
|
schema: { body: {
|
|
31
31
|
type: "object",
|
|
32
32
|
additionalProperties: !0
|
|
33
33
|
} }
|
|
34
34
|
}, async (e, t) => {
|
|
35
35
|
try {
|
|
36
|
-
let r = e.body, a = r.query || r, o = await
|
|
36
|
+
let r = e.body, a = r.query || r, o = await B(e), s = V.validateQuery(a);
|
|
37
37
|
if (!s.isValid) return t.status(400).send(n(`Query validation failed: ${s.errors.join(", ")}`, 400));
|
|
38
38
|
let c = e.headers["x-cache-control"] === "no-cache";
|
|
39
|
-
return i(a, await
|
|
39
|
+
return i(a, await V.executeMultiCubeQuery(a, o, { skipCache: c }), V);
|
|
40
40
|
} catch (r) {
|
|
41
41
|
return e.log.error(r, "Query execution error"), t.status(500).send(n(r instanceof Error ? r.message : "Query execution failed", 500));
|
|
42
42
|
}
|
|
43
|
-
}), o.get(`${
|
|
43
|
+
}), o.get(`${F}/load`, { schema: { querystring: {
|
|
44
44
|
type: "object",
|
|
45
45
|
properties: { query: { type: "string" } },
|
|
46
46
|
required: ["query"]
|
|
@@ -52,15 +52,15 @@ var T = function(o, T, E) {
|
|
|
52
52
|
} catch {
|
|
53
53
|
return t.status(400).send(n("Invalid JSON in query parameter", 400));
|
|
54
54
|
}
|
|
55
|
-
let o = await
|
|
55
|
+
let o = await B(e), s = V.validateQuery(a);
|
|
56
56
|
if (!s.isValid) return t.status(400).send(n(`Query validation failed: ${s.errors.join(", ")}`, 400));
|
|
57
|
-
let c = e.headers["x-cache-control"] === "no-cache", l = await
|
|
58
|
-
return i(a, l,
|
|
57
|
+
let c = e.headers["x-cache-control"] === "no-cache", l = await V.executeMultiCubeQuery(a, o, { skipCache: c });
|
|
58
|
+
return i(a, l, V);
|
|
59
59
|
} catch (r) {
|
|
60
60
|
return e.log.error(r, "Query execution error"), t.status(500).send(n(r instanceof Error ? r.message : "Query execution failed", 500));
|
|
61
61
|
}
|
|
62
|
-
}), o.post(`${
|
|
63
|
-
bodyLimit:
|
|
62
|
+
}), o.post(`${F}/batch`, {
|
|
63
|
+
bodyLimit: I,
|
|
64
64
|
schema: { body: {
|
|
65
65
|
type: "object",
|
|
66
66
|
required: ["queries"],
|
|
@@ -72,50 +72,50 @@ var T = function(o, T, E) {
|
|
|
72
72
|
}, async (e, t) => {
|
|
73
73
|
try {
|
|
74
74
|
let { queries: r } = e.body;
|
|
75
|
-
return !r || !Array.isArray(r) ? t.status(400).send(n("Request body must contain a \"queries\" array", 400)) : r.length === 0 ? t.status(400).send(n("Queries array cannot be empty", 400)) : await a(r, await
|
|
75
|
+
return !r || !Array.isArray(r) ? t.status(400).send(n("Request body must contain a \"queries\" array", 400)) : r.length === 0 ? t.status(400).send(n("Queries array cannot be empty", 400)) : await a(r, await B(e), V, { skipCache: e.headers["x-cache-control"] === "no-cache" });
|
|
76
76
|
} catch (r) {
|
|
77
77
|
return e.log.error(r, "Batch execution error"), t.status(500).send(n(r instanceof Error ? r.message : "Batch execution failed", 500));
|
|
78
78
|
}
|
|
79
|
-
}), o.get(`${
|
|
79
|
+
}), o.get(`${F}/meta`, async (t, r) => {
|
|
80
80
|
try {
|
|
81
|
-
return e(
|
|
81
|
+
return e(V.getMetadata());
|
|
82
82
|
} catch (e) {
|
|
83
83
|
return t.log.error(e, "Metadata error"), r.status(500).send(n(e instanceof Error ? e.message : "Failed to fetch metadata", 500));
|
|
84
84
|
}
|
|
85
|
-
}), o.post(`${
|
|
86
|
-
bodyLimit:
|
|
85
|
+
}), o.post(`${F}/sql`, {
|
|
86
|
+
bodyLimit: I,
|
|
87
87
|
schema: { body: {
|
|
88
88
|
type: "object",
|
|
89
89
|
additionalProperties: !0
|
|
90
90
|
} }
|
|
91
91
|
}, async (e, t) => {
|
|
92
92
|
try {
|
|
93
|
-
let i = e.body, a = await
|
|
93
|
+
let i = e.body, a = await B(e), o = V.validateQuery(i);
|
|
94
94
|
if (!o.isValid) return t.status(400).send(n(`Query validation failed: ${o.errors.join(", ")}`, 400));
|
|
95
95
|
let s = i.measures?.[0] || i.dimensions?.[0];
|
|
96
96
|
if (!s) return t.status(400).send(n("No measures or dimensions specified", 400));
|
|
97
97
|
let c = s.split(".")[0];
|
|
98
|
-
return r(i, await
|
|
98
|
+
return r(i, await V.generateSQL(c, i, a));
|
|
99
99
|
} catch (r) {
|
|
100
100
|
return e.log.error({ err: String(r).replace(/\n|\r/g, "") }, "SQL generation error"), t.status(500).send(n(r instanceof Error ? r.message : "SQL generation failed", 500));
|
|
101
101
|
}
|
|
102
|
-
}), o.get(`${
|
|
102
|
+
}), o.get(`${F}/sql`, { schema: { querystring: {
|
|
103
103
|
type: "object",
|
|
104
104
|
properties: { query: { type: "string" } },
|
|
105
105
|
required: ["query"]
|
|
106
106
|
} } }, async (e, t) => {
|
|
107
107
|
try {
|
|
108
|
-
let { query: i } = e.query, a = JSON.parse(i), o = await
|
|
108
|
+
let { query: i } = e.query, a = JSON.parse(i), o = await B(e), s = V.validateQuery(a);
|
|
109
109
|
if (!s.isValid) return t.status(400).send(n(`Query validation failed: ${s.errors.join(", ")}`, 400));
|
|
110
110
|
let c = a.measures?.[0] || a.dimensions?.[0];
|
|
111
111
|
if (!c) return t.status(400).send(n("No measures or dimensions specified", 400));
|
|
112
112
|
let l = c.split(".")[0];
|
|
113
|
-
return r(a, await
|
|
113
|
+
return r(a, await V.generateSQL(l, a, o));
|
|
114
114
|
} catch (r) {
|
|
115
115
|
return e.log.error({ err: String(r).replace(/\n|\r/g, "") }, "SQL generation error"), t.status(500).send(n(r instanceof Error ? r.message : "SQL generation failed", 500));
|
|
116
116
|
}
|
|
117
|
-
}), o.post(`${
|
|
118
|
-
bodyLimit:
|
|
117
|
+
}), o.post(`${F}/dry-run`, {
|
|
118
|
+
bodyLimit: I,
|
|
119
119
|
schema: { body: {
|
|
120
120
|
type: "object",
|
|
121
121
|
additionalProperties: !0
|
|
@@ -123,57 +123,57 @@ var T = function(o, T, E) {
|
|
|
123
123
|
}, async (e, n) => {
|
|
124
124
|
try {
|
|
125
125
|
let n = e.body;
|
|
126
|
-
return await t(n.query || n, await
|
|
126
|
+
return await t(n.query || n, await B(e), V);
|
|
127
127
|
} catch (t) {
|
|
128
128
|
return e.log.error(t, "Dry-run error"), n.status(400).send({
|
|
129
129
|
error: t instanceof Error ? t.message : "Dry-run validation failed",
|
|
130
130
|
valid: !1
|
|
131
131
|
});
|
|
132
132
|
}
|
|
133
|
-
}), o.get(`${
|
|
133
|
+
}), o.get(`${F}/dry-run`, { schema: { querystring: {
|
|
134
134
|
type: "object",
|
|
135
135
|
properties: { query: { type: "string" } },
|
|
136
136
|
required: ["query"]
|
|
137
137
|
} } }, async (e, n) => {
|
|
138
138
|
try {
|
|
139
139
|
let { query: n } = e.query;
|
|
140
|
-
return await t(JSON.parse(n), await
|
|
140
|
+
return await t(JSON.parse(n), await B(e), V);
|
|
141
141
|
} catch (t) {
|
|
142
142
|
return e.log.error(t, "Dry-run error"), n.status(400).send({
|
|
143
143
|
error: t instanceof Error ? t.message : "Dry-run validation failed",
|
|
144
144
|
valid: !1
|
|
145
145
|
});
|
|
146
146
|
}
|
|
147
|
-
}), o.post(`${
|
|
148
|
-
bodyLimit:
|
|
147
|
+
}), o.post(`${F}/explain`, {
|
|
148
|
+
bodyLimit: I,
|
|
149
149
|
schema: { body: {
|
|
150
150
|
type: "object",
|
|
151
151
|
additionalProperties: !0
|
|
152
152
|
} }
|
|
153
153
|
}, async (e, t) => {
|
|
154
154
|
try {
|
|
155
|
-
let n = e.body, r = n.query || n, i = n.options || {}, a = await
|
|
156
|
-
return o.isValid ? await
|
|
155
|
+
let n = e.body, r = n.query || n, i = n.options || {}, a = await B(e), o = V.validateQuery(r);
|
|
156
|
+
return o.isValid ? await V.explainQuery(r, a, i) : t.status(400).send({ error: `Query validation failed: ${o.errors.join(", ")}` });
|
|
157
157
|
} catch (n) {
|
|
158
158
|
return e.log.error(n, "Explain error"), t.status(500).send({ error: n instanceof Error ? n.message : "Explain query failed" });
|
|
159
159
|
}
|
|
160
|
-
}),
|
|
161
|
-
bodyLimit:
|
|
160
|
+
}), z && o.post(`${F}/agent/chat`, {
|
|
161
|
+
bodyLimit: I,
|
|
162
162
|
schema: { body: {
|
|
163
163
|
type: "object",
|
|
164
164
|
additionalProperties: !0
|
|
165
165
|
} }
|
|
166
166
|
}, async (e, t) => {
|
|
167
167
|
try {
|
|
168
|
-
let { handleAgentChat: n } = await import("../handler-
|
|
168
|
+
let { handleAgentChat: n } = await import("../handler-BC3nFNxV.js"), { message: r, sessionId: i, history: a } = e.body;
|
|
169
169
|
if (!r || typeof r != "string") return t.status(400).send({ error: "message is required and must be a string" });
|
|
170
|
-
let o = (
|
|
171
|
-
if (
|
|
170
|
+
let o = (z.apiKey || "").trim();
|
|
171
|
+
if (z.allowClientApiKey) {
|
|
172
172
|
let t = e.headers["x-agent-api-key"];
|
|
173
173
|
t && (o = t.trim());
|
|
174
174
|
}
|
|
175
175
|
if (!o) return t.status(401).send({ error: "No API key configured. Set agent.apiKey in server config or send X-Agent-Api-Key header." });
|
|
176
|
-
let s =
|
|
176
|
+
let s = z.allowClientApiKey ? e.headers["x-agent-provider"] : void 0, c = z.allowClientApiKey ? e.headers["x-agent-model"] : void 0, l = z.allowClientApiKey ? e.headers["x-agent-provider-endpoint"] : void 0, u = await B(e), d = z.buildSystemContext?.(u);
|
|
177
177
|
t.raw.writeHead(200, {
|
|
178
178
|
"Content-Type": "text/event-stream",
|
|
179
179
|
"Cache-Control": "no-cache",
|
|
@@ -184,9 +184,9 @@ var T = function(o, T, E) {
|
|
|
184
184
|
message: r,
|
|
185
185
|
sessionId: i,
|
|
186
186
|
history: a,
|
|
187
|
-
semanticLayer:
|
|
187
|
+
semanticLayer: V,
|
|
188
188
|
securityContext: u,
|
|
189
|
-
agentConfig:
|
|
189
|
+
agentConfig: z,
|
|
190
190
|
apiKey: o,
|
|
191
191
|
systemContext: d,
|
|
192
192
|
providerOverride: s,
|
|
@@ -206,66 +206,70 @@ var T = function(o, T, E) {
|
|
|
206
206
|
} catch (n) {
|
|
207
207
|
if (e.log.error(n, "Agent chat error"), !t.raw.headersSent) return t.status(500).send({ error: n instanceof Error ? n.message : "Agent chat failed" });
|
|
208
208
|
}
|
|
209
|
-
}),
|
|
210
|
-
let e =
|
|
211
|
-
o.post(`${
|
|
212
|
-
bodyLimit:
|
|
209
|
+
}), R.enabled !== !1) {
|
|
210
|
+
let e = x(V, R.resources), t = w(R.prompts), n = R.basePath ?? "/mcp";
|
|
211
|
+
o.post(`${n}`, {
|
|
212
|
+
bodyLimit: I,
|
|
213
213
|
schema: { body: {
|
|
214
214
|
type: "object",
|
|
215
215
|
additionalProperties: !0
|
|
216
216
|
} }
|
|
217
|
-
}, async (
|
|
218
|
-
if (
|
|
219
|
-
let
|
|
220
|
-
if (!
|
|
221
|
-
let
|
|
222
|
-
if (!
|
|
223
|
-
let
|
|
224
|
-
if (!
|
|
217
|
+
}, async (n, r) => {
|
|
218
|
+
if (R.resourceMetadataUrl && !C(n.headers.authorization)) return r.header("WWW-Authenticate", h(R.resourceMetadataUrl)), r.status(401).send({ error: "Bearer token required" });
|
|
219
|
+
let i = T(n.headers.origin, R.allowedOrigins ? { allowedOrigins: R.allowedOrigins } : {});
|
|
220
|
+
if (!i.valid) return r.status(403).send(v(null, -32600, i.reason));
|
|
221
|
+
let a = n.headers.accept;
|
|
222
|
+
if (!m(a)) return r.status(400).send(v(null, -32600, "Accept header must include both application/json and text/event-stream"));
|
|
223
|
+
let o = _(n.headers);
|
|
224
|
+
if (!o.ok) return r.status(426).send({
|
|
225
225
|
error: "Unsupported MCP protocol version",
|
|
226
|
-
supported:
|
|
226
|
+
supported: o.supported
|
|
227
227
|
});
|
|
228
|
-
let
|
|
229
|
-
if (!
|
|
230
|
-
let
|
|
228
|
+
let s = g(n.body);
|
|
229
|
+
if (!s) return r.status(400).send(v(null, -32600, "Invalid JSON-RPC 2.0 request"));
|
|
230
|
+
let c = d(a), l = s.method === "initialize";
|
|
231
231
|
try {
|
|
232
|
-
let
|
|
233
|
-
semanticLayer:
|
|
234
|
-
extractSecurityContext: (e, t) =>
|
|
235
|
-
rawRequest:
|
|
236
|
-
rawResponse:
|
|
237
|
-
negotiatedProtocol:
|
|
238
|
-
|
|
232
|
+
let i = await y(s.method, s.params, {
|
|
233
|
+
semanticLayer: V,
|
|
234
|
+
extractSecurityContext: (e, t) => B(e),
|
|
235
|
+
rawRequest: n,
|
|
236
|
+
rawResponse: r,
|
|
237
|
+
negotiatedProtocol: o.negotiated,
|
|
238
|
+
resources: e,
|
|
239
|
+
prompts: t,
|
|
240
|
+
appEnabled: !!R.app,
|
|
241
|
+
appConfig: typeof R.app == "object" ? R.app : void 0,
|
|
242
|
+
serverName: R.serverName
|
|
239
243
|
});
|
|
240
|
-
if (b(
|
|
241
|
-
let
|
|
242
|
-
|
|
243
|
-
let
|
|
244
|
-
if (
|
|
245
|
-
let e =
|
|
246
|
-
|
|
244
|
+
if (b(s)) return r.status(202).send();
|
|
245
|
+
let a = l && i && typeof i == "object" && "sessionId" in i ? i.sessionId : void 0;
|
|
246
|
+
a && r.header(S, a);
|
|
247
|
+
let u = p(s.id ?? null, i);
|
|
248
|
+
if (c) {
|
|
249
|
+
let e = f();
|
|
250
|
+
r.header("Content-Type", "text/event-stream").header("Cache-Control", "no-cache").header("Connection", "keep-alive").send(`id: ${e}\n\n${E(u, e)}`);
|
|
247
251
|
return;
|
|
248
252
|
}
|
|
249
|
-
return
|
|
250
|
-
} catch (
|
|
251
|
-
if (b(
|
|
252
|
-
|
|
253
|
-
let
|
|
254
|
-
if (
|
|
255
|
-
let e =
|
|
256
|
-
|
|
253
|
+
return r.send(u);
|
|
254
|
+
} catch (e) {
|
|
255
|
+
if (b(s)) return n.log.error({ err: String(e).replace(/\n|\r/g, "") }, "MCP notification processing error"), r.status(202).send();
|
|
256
|
+
n.log.error({ err: String(e).replace(/\n|\r/g, "") }, "MCP RPC error");
|
|
257
|
+
let t = e?.code ?? -32603, i = e?.data, a = e.message || "MCP request failed", o = v(s.id ?? null, t, a, i);
|
|
258
|
+
if (c) {
|
|
259
|
+
let e = f();
|
|
260
|
+
r.header("Content-Type", "text/event-stream").header("Cache-Control", "no-cache").header("Connection", "keep-alive").send(`id: ${e}\n\n${E(o, e)}`);
|
|
257
261
|
return;
|
|
258
262
|
}
|
|
259
|
-
return
|
|
263
|
+
return r.send(o);
|
|
260
264
|
}
|
|
261
|
-
}), o.get(`${
|
|
262
|
-
if (
|
|
263
|
-
let n =
|
|
265
|
+
}), o.get(`${n}`, async (e, t) => {
|
|
266
|
+
if (R.resourceMetadataUrl && !C(e.headers.authorization)) return t.header("WWW-Authenticate", h(R.resourceMetadataUrl)), t.status(401).send({ error: "Bearer token required" });
|
|
267
|
+
let n = f();
|
|
264
268
|
t.raw.writeHead(200, {
|
|
265
269
|
"Content-Type": "text/event-stream",
|
|
266
270
|
"Cache-Control": "no-cache",
|
|
267
271
|
Connection: "keep-alive"
|
|
268
|
-
}), t.raw.write(
|
|
272
|
+
}), t.raw.write(E({
|
|
269
273
|
jsonrpc: "2.0",
|
|
270
274
|
method: "mcp/ready",
|
|
271
275
|
params: { protocol: "streamable-http" }
|
|
@@ -276,16 +280,16 @@ var T = function(o, T, E) {
|
|
|
276
280
|
e.raw.on("close", () => {
|
|
277
281
|
clearInterval(r);
|
|
278
282
|
});
|
|
279
|
-
}), o.delete(`${
|
|
283
|
+
}), o.delete(`${n}`, async (e, t) => R.resourceMetadataUrl && !C(e.headers.authorization) ? (t.header("WWW-Authenticate", h(R.resourceMetadataUrl)), t.status(401).send({ error: "Bearer token required" })) : t.status(405).send({ error: "Session termination not supported" }));
|
|
280
284
|
}
|
|
281
|
-
o.setErrorHandler(async (e, t, r) => (t.log.error(e, "Fastify cube adapter error"), r.statusCode < 400 && r.status(500), n(e instanceof Error ? e : String(e), r.statusCode))),
|
|
285
|
+
o.setErrorHandler(async (e, t, r) => (t.log.error(e, "Fastify cube adapter error"), r.statusCode < 400 && r.status(500), n(e instanceof Error ? e : String(e), r.statusCode))), O();
|
|
282
286
|
};
|
|
283
|
-
async function
|
|
284
|
-
await e.register(
|
|
287
|
+
async function O(e, t) {
|
|
288
|
+
await e.register(D, t);
|
|
285
289
|
}
|
|
286
|
-
function
|
|
290
|
+
function k(e) {
|
|
287
291
|
let t = o("fastify")({ logger: !0 });
|
|
288
|
-
return t.register(
|
|
292
|
+
return t.register(D, e), t;
|
|
289
293
|
}
|
|
290
294
|
//#endregion
|
|
291
|
-
export {
|
|
295
|
+
export { k as createCubeApp, D as cubePlugin, O as registerCubeRoutes };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { _ as e, d as t, g as n, p as r } from "./utils-
|
|
1
|
+
import { _ as e, d as t, g as n, p as r } from "./utils-CTYvfZ3I.js";
|
|
2
2
|
import { a as i, n as a, r as o, t as s } from "./mcp-prompts-BUFyQLHQ.js";
|
|
3
3
|
//#region src/server/agent/system-prompt.ts
|
|
4
4
|
function c(e) {
|
|
@@ -2444,7 +2444,7 @@ async function v(e, t, n) {
|
|
|
2444
2444
|
return new e(t);
|
|
2445
2445
|
}
|
|
2446
2446
|
case "openai": {
|
|
2447
|
-
let { OpenAIProvider: e } = await import("./openai-
|
|
2447
|
+
let { OpenAIProvider: e } = await import("./openai-BWdm0JvG.js");
|
|
2448
2448
|
return new e(t, n);
|
|
2449
2449
|
}
|
|
2450
2450
|
case "google": {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const e=require(`./utils-
|
|
1
|
+
const e=require(`./utils-XPOzzMdY.cjs`),t=require(`./mcp-prompts-B_NvEJT_.cjs`);function n(e){if(e.length===0)return`No cubes are currently available.`;let t=[`## Available Cubes`,``];for(let n of e){if(t.push(`### ${n.name}`),n.description&&t.push(n.description),n.measures&&n.measures.length>0){t.push(``),t.push(`**Measures:**`);for(let e of n.measures){let r=e.description?` - ${e.description}`:``;t.push(`- \`${n.name}.${e.name}\` (${e.type})${r}`)}}if(n.dimensions&&n.dimensions.length>0){t.push(``),t.push(`**Dimensions:**`);for(let e of n.dimensions){let r=e.description?` - ${e.description}`:``;t.push(`- \`${n.name}.${e.name}\` (${e.type})${r}`)}}if(n.relationships&&n.relationships.length>0){t.push(``),t.push(`**Joins:**`);for(let e of n.relationships)t.push(`- → \`${e.targetCube}\` (${e.relationship})`)}n.meta?.eventStream&&(t.push(``),t.push(`**Event Stream:** Yes (supports funnel, flow, retention queries)`),n.meta.eventStream.bindingKey&&t.push(`- Binding key: \`${n.name}.${n.meta.eventStream.bindingKey}\``),n.meta.eventStream.timeDimension&&t.push(`- Time dimension: \`${n.name}.${n.meta.eventStream.timeDimension}\``)),t.push(``)}return t.join(`
|
|
2
2
|
`)}function r(e){return e.messages.map(e=>e.content.text).join(`
|
|
3
3
|
|
|
4
4
|
`)}function i(e){return[`# Drizzle Cube Analytics Agent`,``,`You are an analytics agent that helps users explore and visualize data.`,`You have access to a semantic layer with cubes (data models) that you can query.`,``,`## Your Workflow`,``,`For EACH insight, follow this cycle — do NOT batch all queries first:`,``,"1. **Discover** available cubes using `discover_cubes` (once at the start)",`2. **For each analysis point**, repeat this cycle:`," a. `execute_query` — get the data"," b. `add_markdown` — explain the results and insight"," c. `add_portlet` — visualize the results",``,`Call all three (query → markdown → portlet) in a single turn before moving on to the next analysis.`,`Do NOT run multiple queries first and add charts later — the user sees results in real-time.`,``,`## Important Guidelines`,``,`- ALWAYS discover cubes first before attempting queries`,"- Field names MUST be EXACTLY `CubeName.fieldName` — two parts separated by a single dot. Examples: `PullRequests.count`, `Teams.name`, `Employees.department`."," WRONG patterns that WILL FAIL: `Teams.Teams.name` (double-prefixed), `PullRequests.PullRequests.count` (double-prefixed), `PullRequests` (bare cube), `Teams_count` (underscore). Use the EXACT field names from discover results — copy them verbatim, do not prefix them again.",`- Order keys MUST be one of the measures or dimensions already listed in that query. You CANNOT order by a field that is not in measures or dimensions — add it to measures first, or remove it from order.`,"- After EVERY `execute_query`, IMMEDIATELY call `add_markdown` and `add_portlet` in the SAME turn — never defer visualizations to a later turn",`- Choose appropriate chart types: bar for categories, line for trends, table for detailed data`,`- If a query fails, explain the error and try an alternative approach`,``,`## Output Format Rules`,``,`### CRITICAL: Always think before acting`,`- EVERY single turn MUST begin with a text message (1-2 sentences) BEFORE any tool calls. This is your #1 rule — never violate it.`,`- This applies to EVERY turn, including turns where you are adding visualizations or explanations to the notebook.`,`- Even when adding multiple charts in sequence, each turn must start with a brief status like "Now I'll chart the productivity breakdown." or "Next, let me show the department comparison."`,`- Example good turn: "Let me see what data is available." → discover_cubes`,`- Example good turn: "I'll add a chart showing the top employees." → add_markdown → add_portlet`,`- Example bad turn: (no text) → add_portlet ← NEVER do this`,``,`### Text vs Notebook`,"- ALL analysis, findings, methodology, and insights MUST go through `add_markdown` tool calls — never in your text responses",`- Your text responses must be 1-2 short sentences (under 50 words) summarizing what you are about to do next — status updates only`,`- Never use markdown formatting (headers, bullets, bold, code blocks) in text responses — plain sentences only`,`- Write text responses as a friendly analyst would — use plain business language the user understands`,`- NEVER mention internal terms like "cube", "query syntax", "field names", "measures", "dimensions", "portlet", "prefix format", or tool names in text responses`,`- Instead of "Let me correct the query syntax and retry" → "Let me fix that and try again"`,`- Instead of "I'll query the PullRequests cube" → "I'll look at the pull request data"`,`- Instead of "Adding a portlet with the results" → "Here's a chart of the results"`,``,`### Notebook content rules`,"- Before each `add_portlet`, ALWAYS call `add_markdown` first to explain WHY you are adding this visualization and what it shows","- Before calling `add_portlet`, verify the query is valid: all fields in `order` must also appear in `measures` or `dimensions`",'- Never put data tables in markdown blocks — use `add_portlet` with chartType "table" instead',"- Think out loud in the notebook: use `add_markdown` to share your reasoning at each step so users can follow along",`- NEVER use emojis in text responses or markdown content — no 📊, 📈, ✅, 🔍, etc. Write in plain, professional language.`,``,`## Chart Selection Guide`,``,`Choose the chart type that best communicates the answer to the user's question. Think about what the data represents and what insight the user needs — do NOT default to the first option in this table. Consider the number of data points, whether values are categorical or temporal, and whether the user is comparing, trending, or summarizing.`,``,`| Intent / Data Shape | Chart Type |`,`|---|---|`,"| Compare discrete categories or rankings | `bar` |","| Trend over time (one or few series) | `line` |","| Trend over time showing volume/magnitude | `area` |","| Part-of-whole breakdown | `pie` (≤7 slices) |","| Correlation between two measures | `scatter` |","| Correlation with size/color third dimension | `bubble` |","| Intensity across two categorical dimensions | `heatmap` |","| Multi-variable comparison across categories | `radar` |","| Distribution/spread of values | `boxPlot` |","| Detailed row-level data or many columns | `table` |","| Single headline number — ONLY when user explicitly asks for a KPI card or single number | `kpiNumber` |","| Headline metric with period-over-period change — ONLY when user asks about change in a single metric | `kpiDelta` |",``,`Analysis-mode-specific chart types (require the corresponding analysis mode):`,``,`| Analysis Mode | Chart Type | Description |`,`|---|---|---|`,"| Funnel | `funnel` | Sequential step conversion bars with conversion rates |","| Flow | `sankey` | Flow diagram showing paths between states/steps |","| Flow | `sunburst` | Radial rings showing forward paths from a starting event |","| Retention | `retentionHeatmap` | Cohort × period retention matrix |","| Retention | `retentionCombined` | Retention with line chart, heatmap, or combined modes |",``,'**Chart selection priorities:** Default to `bar` for categories, `line` for time series, `table` for exploratory data. Use `kpiNumber`/`kpiDelta` only as a last resort — they are appropriate only when the user explicitly asks for a single headline number or KPI card. If the query returns multiple rows or the user asks a general question like "show me revenue", prefer `bar` or `table` over `kpiNumber`.',``,`## Chart Axis Configuration Rules`,``,"**Bar charts MUST have an xAxis.** Put a dimension in `chartConfig.xAxis` so bars have category labels. If your query has no dimensions, add one or use `table` instead.",``,"**Never duplicate xAxis in series.** Putting the same dimension in both `xAxis` and `series` creates a sparse, broken-looking chart. The `series` field is ONLY for splitting bars into grouped/stacked sub-series by a SECOND dimension.",``,`Correct bar chart examples:`,'- Categories only: `xAxis: ["Cube.category"], yAxis: ["Cube.count"]` — no series needed','- Grouped bars: `xAxis: ["Cube.category"], yAxis: ["Cube.count"], series: ["Cube.status"]` — series is a DIFFERENT dimension','- Multiple measures: `xAxis: ["Cube.category"], yAxis: ["Cube.count", "Cube.total"]` — each measure becomes a bar group',``,`Wrong:`,'- `xAxis: [], yAxis: ["Cube.avg1", "Cube.avg2"]` — missing xAxis, bars have no labels','- `xAxis: ["Cube.size"], series: ["Cube.size"]` — same field in both, creates sparse chart',``,"**Dual Y-axis for multi-measure charts.** When a `bar`, `line`, or `area` chart has 2+ measures with different scales (e.g. revenue in thousands vs conversion rate as a percentage), use `chartConfig.yAxisAssignment` to put them on separate axes:","```json",`{`,` "xAxis": ["Sales.month"],`,` "yAxis": ["Sales.revenue", "Sales.conversionRate"],`,` "yAxisAssignment": { "Sales.revenue": "left", "Sales.conversionRate": "right" }`,`}`,"```",`Only use dual axis when measures have genuinely different scales. If both measures share the same unit/scale, keep them on the same (left) axis — omit yAxisAssignment entirely.`,``,`## Analysis Mode Decision Tree`,``,`The default mode is **query** (standard measures/dimensions). Switch to a special mode only when the user's question matches:`,``,`- **Funnel mode** — "What is the conversion rate from step A → B → C?"`," - Requires: an event-stream cube with `capabilities.funnel = true` from `discover_cubes`"," - Execute: `execute_query` with `funnel` param:",' `{ bindingKey: "Events.userId", timeDimension: "Events.timestamp", steps: [{ name: "Signup", filter: { member: "Events.eventName", operator: "equals", values: ["signup"] }}, { name: "Purchase", filter: { member: "Events.eventName", operator: "equals", values: ["purchase"] }}] }`',' - Visualize: `add_portlet` with `chartType: "funnel"` and `query` as JSON string containing `{ "funnel": { ... } }`',``,`- **Flow mode** — "What paths do users take after signup?"`," - Requires: `capabilities.flow = true` from `discover_cubes`"," - Execute: `execute_query` with `flow` param:",' `{ bindingKey: "Events.userId", timeDimension: "Events.timestamp", eventDimension: "Events.eventName", startingStep: { name: "Signup", filter: { member: "Events.eventName", operator: "equals", values: ["signup"] }}, stepsBefore: 0, stepsAfter: 3 }`',' - Visualize: `add_portlet` with `chartType: "sankey"` (or `"sunburst"`) and `query` as JSON string containing `{ "flow": { ... } }`',``,`- **Retention mode** — "What % of users come back after 7 days?"`," - Requires: `capabilities.retention = true` from `discover_cubes`"," - Execute: `execute_query` with `retention` param:",' `{ timeDimension: "Events.timestamp", bindingKey: "Events.userId", dateRange: { start: "2024-01-01", end: "2024-03-31" }, granularity: "week", periods: 8, retentionType: "classic" }`',' - Visualize: `add_portlet` with `chartType: "retentionCombined"` (or `"retentionHeatmap"`) and `query` as JSON string containing `{ "retention": { ... } }`',``,"Before using funnel/flow/retention, check the `capabilities` object returned by `discover_cubes`. If the required capability is `false`, explain to the user that the data model does not support that analysis mode.",``,`Event-stream cubes are marked in the Available Cubes section below with **Event Stream: Yes** and list their binding key and time dimension.`,``,`---`,``,r(t.n),``,`---`,``,r(t.r),``,`---`,``,r(t.t),``,`---`,``,`## Save as Dashboard`,``,"ONLY call `save_as_dashboard` when the user EXPLICITLY asks to save, export, or convert the notebook into a dashboard. NEVER save a dashboard on your own initiative — wait for the user to request it.",``,`### Layout Rules`,`- Dashboard grid is 12 columns wide`,`- KPI cards: w=3, h=3 — place at the top in a row of 4`,`- Overview charts (bar, line, area): w=6, h=4`,`- Wide charts (heatmap, table): w=12, h=5`,`- Section headers (markdown): w=12, h=1`,``,`### Section Headers`,'Use `chartType: "markdown"` portlets as section headers to organize the dashboard:',"```json",`{`,` "id": "header-overview",`,` "title": "Overview",`,` "chartType": "markdown",`,` "displayConfig": {`,` "content": "## Overview",`,` "hideHeader": true,`,` "transparentBackground": true,`,` "autoHeight": true`,` },`,` "w": 12, "h": 1, "x": 0, "y": 0`,`}`,"```",``,`### Dashboard Filters`,"- ALWAYS include a universal date filter with `isUniversalTime: true`",`- Add dimension filters for key fields used across portlets (e.g., department, status, region)`,`- Use human-readable labels (e.g., "Department" not "Employees.departmentName")`,"- Map filters to portlets using `dashboardFilterMapping` — list the filter IDs that apply",`- When promoting a hardcoded filter to a dashboard filter, REMOVE that filter from the portlet query`,``,`### Analysis Types`,'- Standard query portlets: `analysisType: "query"` (default)','- Funnel portlets: `analysisType: "funnel"`, query contains `{ "funnel": {...} }`, chartType `"funnel"`','- Flow portlets: `analysisType: "flow"`, query contains `{ "flow": {...} }`, chartType `"sankey"` or `"sunburst"`','- Retention portlets: `analysisType: "retention"`, query contains `{ "retention": {...} }`, chartType `"retentionHeatmap"` or `"retentionCombined"`',``,`### CRITICAL: Only use portlets from the notebook`,"- ONLY include portlets that you already added to the notebook via `add_portlet` during this conversation",`- Do NOT invent new queries or charts that were not part of the analysis — the dashboard is a direct conversion of the notebook`,`- Reuse the exact same queries, chart types, and chart configs from the notebook portlets`,`- Arrange the existing portlets in a sensible layout (KPIs at top, charts in middle, tables at bottom)`,`- You may add section header markdown portlets to organize the layout, but do not add new data portlets`,``,`---`,``,n(e)].join(`
|
|
@@ -22,4 +22,4 @@ The query is validated before adding. The portlet fetches its own data.`,paramet
|
|
|
22
22
|
[IMPORTANT: Your next response MUST start with a brief text message BEFORE any tool calls. Now call add_markdown and add_portlet to visualize these results.]`}}catch(e){let n={measures:t.measures,dimensions:t.dimensions,filters:t.filters,timeDimensions:t.timeDimensions,order:t.order,limit:t.limit,...t.funnel?{funnel:t.funnel}:{},...t.flow?{flow:t.flow}:{},...t.retention?{retention:t.retention}:{}};return{result:`Query execution failed: ${e instanceof Error?e.message:`Unknown error`}\n\nAttempted query:\n${JSON.stringify(n,null,2)}`,isError:!0}}}),i.set(`add_portlet`,async t=>{let r={number:`kpiNumber`,retention:`retentionHeatmap`}[t.chartType]??t.chartType,i;try{i=JSON.parse(t.query)}catch{return{result:"Invalid query: could not parse JSON string. Ensure `query` is a valid JSON string.",isError:!0}}i=e.g(i);let a=n.validateQuery(i);if(!a.isValid)return{result:`Invalid query — fix these errors and retry:\n${a.errors.join(`
|
|
23
23
|
`)}\n\nAttempted query:\n${JSON.stringify(i,null,2)}`,isError:!0};let c=!!(i.funnel||i.flow||i.retention),l;if(c)l=t.chartConfig??{};else{let e=s(r,t.chartConfig,i),n=o(r,e,i);if(!n.isValid)return{result:`Chart config invalid — fix these errors and retry:\n${n.errors.join(`
|
|
24
24
|
`)}`,isError:!0};l=e}let u=`portlet-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,d={id:u,title:t.title,query:t.query,chartType:r,chartConfig:l,displayConfig:t.displayConfig};return{result:`Portlet "${t.title}" added to notebook (id: ${u}, chart: ${r}). [Reminder: in your next response, start with a brief sentence about what you will do next BEFORE making any tool calls.]`,sideEffect:{type:`add_portlet`,data:d}}}),i.set(`add_markdown`,async e=>{let t=`markdown-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,n=e.content||e.text||e.markdown||``,r={id:t,title:e.title,content:n};return{result:`Markdown block added to notebook (id: ${t}). [Reminder: in your next response, start with a brief sentence about what you will do next BEFORE making any tool calls.]`,sideEffect:{type:`add_markdown`,data:r}}}),i.set(`save_as_dashboard`,async t=>{try{let r=t.portlets;if(!r||r.length===0)return{result:`Dashboard must contain at least one portlet.`,isError:!0};let i=[];for(let t of r){if(t.chartType===`markdown`)continue;let r=t.query;if(!r){i.push(`Portlet "${t.title}": missing query`);continue}let a;try{a=JSON.parse(r)}catch{i.push(`Portlet "${t.title}": invalid JSON query`);continue}a=e.g(a);let o=n.validateQuery(a);o.isValid||i.push(`Portlet "${t.title}": ${o.errors.join(`, `)}`)}if(i.length>0)return{result:`Dashboard has invalid portlets — fix these errors and retry:\n${i.join(`
|
|
25
|
-
`)}`,isError:!0};let a={portlets:r.map(e=>{let t=e.chartType,n=t===`markdown`,r=n?`query`:e.analysisType||`query`,i=r===`funnel`?`funnel`:r===`flow`?`flow`:r===`retention`?`retention`:`query`,a=e.query||`{}`,o;try{o=JSON.parse(a)}catch{o={}}let s={version:1,analysisType:i,activeView:`chart`,charts:{[i]:{chartType:t,chartConfig:e.chartConfig||{},displayConfig:e.displayConfig||{}}},query:n?{}:o};return{id:e.id,title:e.title,analysisConfig:s,dashboardFilterMapping:e.dashboardFilterMapping,w:e.w,h:e.h,x:e.x,y:e.y}}),filters:t.filters,colorPalette:t.colorPalette},o=t.title;return{result:`Dashboard "${o}" created with ${a.portlets.length} portlets and ${a.filters?.length||0} filters.`,sideEffect:{type:`dashboard_saved`,data:{title:o,description:t.description,dashboardConfig:a}}}}catch(e){return{result:`Failed to save dashboard: ${e instanceof Error?e.message:`Unknown error`}`,isError:!0}}}),i}async function f(e,t,n){switch(e){case`anthropic`:{let{AnthropicProvider:e}=await Promise.resolve().then(()=>require(`./anthropic-Cto4Jxqt.cjs`));return new e(t)}case`openai`:{let{OpenAIProvider:e}=await Promise.resolve().then(()=>require(`./openai-
|
|
25
|
+
`)}`,isError:!0};let a={portlets:r.map(e=>{let t=e.chartType,n=t===`markdown`,r=n?`query`:e.analysisType||`query`,i=r===`funnel`?`funnel`:r===`flow`?`flow`:r===`retention`?`retention`:`query`,a=e.query||`{}`,o;try{o=JSON.parse(a)}catch{o={}}let s={version:1,analysisType:i,activeView:`chart`,charts:{[i]:{chartType:t,chartConfig:e.chartConfig||{},displayConfig:e.displayConfig||{}}},query:n?{}:o};return{id:e.id,title:e.title,analysisConfig:s,dashboardFilterMapping:e.dashboardFilterMapping,w:e.w,h:e.h,x:e.x,y:e.y}}),filters:t.filters,colorPalette:t.colorPalette},o=t.title;return{result:`Dashboard "${o}" created with ${a.portlets.length} portlets and ${a.filters?.length||0} filters.`,sideEffect:{type:`dashboard_saved`,data:{title:o,description:t.description,dashboardConfig:a}}}}catch(e){return{result:`Failed to save dashboard: ${e instanceof Error?e.message:`Unknown error`}`,isError:!0}}}),i}async function f(e,t,n){switch(e){case`anthropic`:{let{AnthropicProvider:e}=await Promise.resolve().then(()=>require(`./anthropic-Cto4Jxqt.cjs`));return new e(t)}case`openai`:{let{OpenAIProvider:e}=await Promise.resolve().then(()=>require(`./openai-B4N3KfTG.cjs`));return new e(t,n)}case`google`:{let{GoogleProvider:e}=await Promise.resolve().then(()=>require(`./google-BOAwi9Ib.cjs`));return new e(t)}default:throw Error(`Unknown LLM provider: "${e}". Supported providers: anthropic, openai, google`)}}var p={anthropic:`claude-sonnet-4-6`,openai:`gpt-4.1-mini`,google:`gemini-3-flash-preview`};async function*m(t){let{message:n,history:r,semanticLayer:a,securityContext:o,agentConfig:s,apiKey:c}=t,l=t.sessionId||crypto.randomUUID(),m=s.observability,h=crypto.randomUUID(),g=Date.now(),_=t.providerOverride||s.provider||`anthropic`,v=t.modelOverride||s.model||p[_]||`claude-sonnet-4-6`,y=t.baseURLOverride||s.baseURL,b=s.maxTurns||25,x=s.maxTokens||4096,S;try{S=await f(_,c,{baseURL:y})}catch(t){console.error(`[agent] Failed to create %s provider: %s`,String(_).replace(/\n|\r/g,``),String(t instanceof Error?t.message:t).replace(/\n|\r/g,``)),yield{type:`error`,data:{message:t instanceof Error?t.message:e._(`server.errors.llmInitFailed`)}};return}let C=u(),w=d({semanticLayer:a,securityContext:o}),T=i(a.getMetadata());t.systemContext&&(T+=`\n\n## User Context\n\n${t.systemContext}`);try{m?.onChatStart?.({traceId:h,sessionId:l,message:n,model:v,historyLength:r?.length??0})}catch{}let E=[];if(r&&r.length>0){for(let e of r)if(e.role===`user`)E.push({role:`user`,content:e.content});else if(e.role===`assistant`){let t=[];if(e.content&&t.push({type:`text`,text:e.content}),e.toolCalls&&e.toolCalls.length>0){for(let n of e.toolCalls)t.push({type:`tool_use`,id:n.id,name:n.name,input:n.input||{}});E.push({role:`assistant`,content:t});let n=e.toolCalls.map(e=>({toolUseId:e.id,toolName:e.name,content:typeof e.result==`string`?e.result:JSON.stringify(e.result??``),isError:e.status===`error`})),r=S.formatToolResults(n);if(Array.isArray(r))for(let e of r)E.push(e);else E.push(r)}else t.length>0&&E.push({role:`assistant`,content:e.content})}}E.push({role:`user`,content:n});let D=0;try{for(let e=0;e<b;e++){D=e+1;let t=await S.createStream({model:v,maxTokens:x,system:T,tools:C,messages:E}),n=[],r=``,i=``,a,o,s=Date.now(),c=!1;for await(let e of S.parseStreamEvents(t)){let t=e;switch(t.type){case`text_delta`:{let e=n[n.length-1];e&&e.type===`text`?e.text=(e.text||``)+t.text:n.push({type:`text`,text:t.text}),yield{type:`text_delta`,data:t.text};break}case`tool_use_start`:if(c&&r){let e=n[n.length-1];if(e?.type===`tool_use`)try{e.input=JSON.parse(r)}catch{}}n.push({type:`tool_use`,id:t.id,name:t.name,input:{},...t.metadata?{metadata:t.metadata}:{}}),r=``,c=!0,yield{type:`tool_use_start`,data:{id:t.id,name:t.name,input:void 0}};break;case`tool_input_delta`:r+=t.json;break;case`tool_use_end`:if(t.id&&t.input){let e=n.find(e=>e.type===`tool_use`&&e.id===t.id);e&&(e.input=t.input)}else if(c){let e=n[n.length-1];if(e?.type===`tool_use`&&r){try{e.input=JSON.parse(r)}catch{e.input={}}r=``}c=!1}break;case`message_meta`:t.inputTokens!=null&&(a=t.inputTokens),t.outputTokens!=null&&(o=t.outputTokens),t.stopReason&&(i=t.stopReason);break}}try{m?.onGenerationEnd?.({traceId:h,turn:e,model:v,stopReason:i,inputTokens:a,outputTokens:o,durationMs:Date.now()-s,input:E,output:n})}catch{}if(E.push({role:`assistant`,content:n}),!S.shouldContinue(i))break;let l=[];for(let t of n){if(t.type!==`tool_use`)continue;let n=t.name,r=t.input||{},i=t.id,a=w.get(n);if(!a){l.push({toolUseId:i,toolName:n,content:`Unknown tool: ${n}`,isError:!0}),yield{type:`tool_use_result`,data:{id:i,name:n,result:`Unknown tool: ${n}`,isError:!0}};continue}let o=Date.now();try{let t=await a(r);t.sideEffect&&(yield t.sideEffect),l.push({toolUseId:i,toolName:n,content:t.result,...t.isError?{isError:!0}:{}}),yield{type:`tool_use_result`,data:{id:i,name:n,result:t.result,...t.isError?{isError:!0}:{}}};try{m?.onToolEnd?.({traceId:h,turn:e,toolName:n,toolUseId:i,isError:!!t.isError,durationMs:Date.now()-o})}catch{}}catch(t){let r=t instanceof Error?t.message:`Tool execution failed`;l.push({toolUseId:i,toolName:n,content:r,isError:!0}),yield{type:`tool_use_result`,data:{id:i,name:n,result:r,isError:!0}};try{m?.onToolEnd?.({traceId:h,turn:e,toolName:n,toolUseId:i,isError:!0,durationMs:Date.now()-o})}catch{}}}yield{type:`turn_complete`,data:{}};let u=S.formatToolResults(l);if(Array.isArray(u))for(let e of u)E.push(e);else E.push(u)}try{m?.onChatEnd?.({traceId:h,sessionId:l,totalTurns:D,durationMs:Date.now()-g})}catch{}yield{type:`done`,data:{sessionId:l||``,traceId:h}}}catch(e){try{m?.onChatEnd?.({traceId:h,sessionId:l,totalTurns:0,durationMs:Date.now()-g,error:e instanceof Error?e.message:`Unknown error`})}catch{}console.error(`[agent] Chat error (provider=%s, model=%s): %s`,String(_).replace(/\n|\r/g,``),String(v).replace(/\n|\r/g,``),String(e instanceof Error?e.message:e).replace(/\n|\r/g,``)),yield{type:`error`,data:{message:S.formatError(e)}}}}exports.handleAgentChat=m;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../utils-DNrj-ryp.cjs`),t=require(`../locale-DueXjqMh.cjs`),n=require(`../mcp-transport-45SiFcCH.cjs`);let r=require(`hono`);var i=e=>{let t={origin:`*`,allowMethods:[`GET`,`HEAD`,`PUT`,`POST`,`DELETE`,`PATCH`],allowHeaders:[],exposeHeaders:[],...e},n=(e=>typeof e==`string`?e===`*`?t.credentials?e=>e||null:()=>e:t=>e===t?t:null:typeof e==`function`?e:t=>e.includes(t)?t:null)(t.origin),r=(e=>typeof e==`function`?e:Array.isArray(e)?()=>e:()=>[])(t.allowMethods);return async function(e,i){function a(t,n){e.res.headers.set(t,n)}let o=await n(e.req.header(`origin`)||``,e);if(o&&a(`Access-Control-Allow-Origin`,o),t.credentials&&a(`Access-Control-Allow-Credentials`,`true`),t.exposeHeaders?.length&&a(`Access-Control-Expose-Headers`,t.exposeHeaders.join(`,`)),e.req.method===`OPTIONS`){(t.origin!==`*`||t.credentials)&&a(`Vary`,`Origin`),t.maxAge!=null&&a(`Access-Control-Max-Age`,t.maxAge.toString());let n=await r(e.req.header(`origin`)||``,e);n.length&&a(`Access-Control-Allow-Methods`,n.join(`,`));let i=t.allowHeaders;if(!i?.length){let t=e.req.header(`Access-Control-Request-Headers`);t&&(i=t.split(/\s*,\s*/))}return i?.length&&(a(`Access-Control-Allow-Headers`,i.join(`,`)),e.res.headers.append(`Vary`,`Access-Control-Request-Headers`)),e.res.headers.delete(`Content-Length`),e.res.headers.delete(`Content-Type`),new Response(null,{headers:e.res.headers,status:204,statusText:`No Content`})}await i(),(t.origin!==`*`||t.credentials)&&e.header(`Vary`,`Origin`,{append:!0})}};function a(a){let{cubes:o,drizzle:s,schema:c,extractSecurityContext:l,engineType:u,cors:d,basePath:f=`/cubejs-api/v1`,cache:p,mcp:m={enabled:!0},agent:h}=a;if(!a.semanticLayer&&(!o||o.length===0))throw Error(`Either semanticLayer or a non-empty cubes array must be provided`);let g=new r.Hono,_=async e=>t.r(await l(e),t.n(t=>e.req.header(t)));if(d){let e={...d,allowHeaders:t.t(d.allowHeaders)};g.use(`/*`,i(e))}let v=a.semanticLayer??new t.i({drizzle:s,schema:c,engineType:u,cache:p,rlsSetup:a.rlsSetup});if(!a.semanticLayer&&o&&o.forEach(e=>{v.registerCube(e)}),g.post(`${f}/load`,async t=>{try{let n=await t.req.json(),r=n.query||n,i=await _(t),a=v.validateQuery(r);if(!a.isValid)return t.json({error:`Query validation failed: ${a.errors.join(`, `)}`},400);let o=t.req.header(`x-cache-control`)===`no-cache`,s=await v.executeMultiCubeQuery(r,i,{skipCache:o});return t.json(e.r(r,s,v))}catch(e){return console.error(`Query execution error:`,e),t.json({error:e instanceof Error?e.message:`Query execution failed`},500)}}),g.get(`${f}/load`,async t=>{try{let n=t.req.query(`query`);if(!n)return t.json({error:`Query parameter is required`},400);let r;try{r=JSON.parse(n)}catch{return t.json({error:`Invalid JSON in query parameter`},400)}let i=await _(t),a=v.validateQuery(r);if(!a.isValid)return t.json({error:`Query validation failed: ${a.errors.join(`, `)}`},400);let o=t.req.header(`x-cache-control`)===`no-cache`,s=await v.executeMultiCubeQuery(r,i,{skipCache:o});return t.json(e.r(r,s,v))}catch(e){return console.error(`Query execution error:`,e),t.json({error:e instanceof Error?e.message:`Query execution failed`},500)}}),g.post(`${f}/batch`,async t=>{try{let{queries:n}=await t.req.json();if(!n||!Array.isArray(n))return t.json({error:`Request body must contain a "queries" array`},400);if(n.length===0)return t.json({error:`Queries array cannot be empty`},400);let r=await e.u(n,await _(t),v,{skipCache:t.req.header(`x-cache-control`)===`no-cache`});return t.json(r)}catch(e){return console.error(`Batch execution error:`,e),t.json({error:e instanceof Error?e.message:`Batch execution failed`},500)}}),g.get(`${f}/meta`,t=>{try{let n=v.getMetadata();return t.json(e.a(n))}catch(e){return console.error(`Metadata error:`,e),t.json({error:e instanceof Error?e.message:`Failed to fetch metadata`},500)}}),g.post(`${f}/sql`,async t=>{try{let n=await t.req.json(),r=await _(t),i=v.validateQuery(n);if(!i.isValid)return t.json({error:`Query validation failed: ${i.errors.join(`, `)}`},400);let a=n.measures?.[0]||n.dimensions?.[0];if(!a)return t.json({error:`No measures or dimensions specified`},400);let o=a.split(`.`)[0],s=await v.generateSQL(o,n,r);return t.json(e.o(n,s))}catch(e){return console.error(`SQL generation error:`,e),t.json({error:e instanceof Error?e.message:`SQL generation failed`},500)}}),g.get(`${f}/sql`,async t=>{try{let n=t.req.query(`query`);if(!n)return t.json({error:`Query parameter is required`},400);let r=JSON.parse(n),i=await _(t),a=v.validateQuery(r);if(!a.isValid)return t.json({error:`Query validation failed: ${a.errors.join(`, `)}`},400);let o=r.measures?.[0]||r.dimensions?.[0];if(!o)return t.json({error:`No measures or dimensions specified`},400);let s=o.split(`.`)[0],c=await v.generateSQL(s,r,i);return t.json(e.o(r,c))}catch(e){return console.error(`SQL generation error:`,e),t.json({error:e instanceof Error?e.message:`SQL generation failed`},500)}}),g.post(`${f}/dry-run`,async t=>{try{let n=await t.req.json(),r=await e.f(n.query||n,await _(t),v);return t.json(r)}catch(e){return console.error(`Dry-run error:`,e),t.json({error:e instanceof Error?e.message:`Dry-run validation failed`,valid:!1},400)}}),g.get(`${f}/dry-run`,async t=>{try{let n=t.req.query(`query`);if(!n)return t.json({error:`Query parameter is required`,valid:!1},400);let r=await e.f(JSON.parse(n),await _(t),v);return t.json(r)}catch(e){return console.error(`Dry-run error:`,e),t.json({error:e instanceof Error?e.message:`Dry-run validation failed`,valid:!1},400)}}),g.post(`${f}/explain`,async e=>{try{let t=await e.req.json(),n=t.query||t,r=t.options||{},i=await _(e),a=v.validateQuery(n);if(!a.isValid)return e.json({error:`Query validation failed: ${a.errors.join(`, `)}`},400);let o=await v.explainQuery(n,i,r);return e.json(o)}catch(t){return console.error(`Explain error:`,t),e.json({error:t instanceof Error?t.message:`Explain query failed`},500)}}),h&&g.post(`${f}/agent/chat`,async e=>{try{let{handleAgentChat:t}=await Promise.resolve().then(()=>require(`../handler-BzzbVpcl.cjs`)),{message:n,sessionId:r,history:i}=await e.req.json();if(!n||typeof n!=`string`)return e.json({error:`message is required and must be a string`},400);let a=(h.apiKey||``).trim();if(h.allowClientApiKey){let t=e.req.header(`x-agent-api-key`);t&&(a=t.trim())}if(!a)return e.json({error:`No API key configured. Set agent.apiKey in server config or send X-Agent-Api-Key header.`},401);let o=h.allowClientApiKey?e.req.header(`x-agent-provider`):void 0,s=h.allowClientApiKey?e.req.header(`x-agent-model`):void 0,c=h.allowClientApiKey?e.req.header(`x-agent-provider-endpoint`):void 0,l=await _(e),u=h.buildSystemContext?.(l),d=new TextEncoder,f=new ReadableStream({async start(e){try{let f=t({message:n,sessionId:r,history:i,semanticLayer:v,securityContext:l,agentConfig:h,apiKey:a,systemContext:u,providerOverride:o,modelOverride:s,baseURLOverride:c});for await(let t of f){let n=`data: ${JSON.stringify(t)}\n\n`;e.enqueue(d.encode(n))}}catch(t){let n={type:`error`,data:{message:t instanceof Error?t.message:`Stream failed`}};e.enqueue(d.encode(`data: ${JSON.stringify(n)}\n\n`))}finally{e.close()}}});return new Response(f,{status:200,headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`}})}catch(t){return console.error(`Agent chat error:`,t),e.json({error:t instanceof Error?t.message:`Agent chat failed`},500)}}),m.enabled!==!1){let e={uri:`drizzle-cube://schema`,name:`Cube Schema`,description:`Current cube metadata as JSON`,mimeType:`application/json`,text:JSON.stringify(v.getMetadata(),null,2)},t=[...n.d(),e],r=n.u(),i=m.basePath??`/mcp`;g.post(`${i}`,async e=>{if(m.resourceMetadataUrl&&!n.l(e.req.header(`authorization`)))return e.header(`WWW-Authenticate`,n.s(m.resourceMetadataUrl)),e.json({error:`Bearer token required`},401);let i=n.y(e.req.header(`origin`),m.allowedOrigins?{allowedOrigins:m.allowedOrigins}:{});if(!i.valid)return e.json(n.i(null,-32600,i.reason),403);let a=e.req.header(`accept`);if(!n.v(a))return e.json(n.i(null,-32600,`Accept header must include both application/json and text/event-stream`),400);let o=n.m(e.req.header());if(!o.ok)return e.json({error:`Unsupported MCP protocol version`,supported:o.supported},426);let s=n.h(await e.req.json().catch(()=>null));if(!s)return e.json(n.i(null,-32600,`Invalid JSON-RPC 2.0 request`),400);let c=n.b(a),l=s.method===`initialize`;try{let i=await n.c(s.method,s.params,{semanticLayer:v,extractSecurityContext:(e,t)=>_(e),rawRequest:e,rawResponse:null,negotiatedProtocol:o.negotiated,resources:t,prompts:r,appEnabled:!!m.app});if(n.p(s))return e.body(null,202);let a=n.a(s.id??null,i),u=l&&i&&typeof i==`object`&&`sessionId`in i?i.sessionId:void 0,d={};if(u&&(d[n.r]=u),c){let e=new TextEncoder,t=n.g(),r=new ReadableStream({start(r){r.enqueue(e.encode(`id: ${t}\n\n`)),r.enqueue(e.encode(n._(a,t))),r.close()}});return new Response(r,{status:200,headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`,...d}})}return e.json(a,200,d)}catch(t){if(n.p(s))return console.error(`MCP notification processing error:`,t),e.body(null,202);console.error(`MCP RPC error:`,t);let r=t?.code??-32603,i=t?.data,a=t.message||`MCP request failed`,o=n.i(s.id??null,r,a,i);if(c){let e=new TextEncoder,t=n.g(),r=new ReadableStream({start(r){r.enqueue(e.encode(`id: ${t}\n\n`)),r.enqueue(e.encode(n._(o,t))),r.close()}});return new Response(r,{status:200,headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`}})}return e.json(o,200)}}),g.delete(`${i}`,e=>m.resourceMetadataUrl&&!n.l(e.req.header(`authorization`))?(e.header(`WWW-Authenticate`,n.s(m.resourceMetadataUrl)),e.json({error:`Bearer token required`},401)):e.json({error:`Session termination not supported`},405)),g.get(`${i}`,e=>{if(m.resourceMetadataUrl&&!n.l(e.req.header(`authorization`)))return e.header(`WWW-Authenticate`,n.s(m.resourceMetadataUrl)),e.json({error:`Bearer token required`},401);let t=new TextEncoder,r=n.g(),i,a=new ReadableStream({start(e){e.enqueue(t.encode(n._({jsonrpc:`2.0`,method:`mcp/ready`,params:{protocol:`streamable-http`}},r,15e3))),i=setInterval(()=>{e.enqueue(t.encode(`: keep-alive
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../utils-XPOzzMdY.cjs`),t=require(`../locale-BoiA6WiV.cjs`),n=require(`../mcp-transport-irsahKmD.cjs`);let r=require(`hono`);var i=e=>{let t={origin:`*`,allowMethods:[`GET`,`HEAD`,`PUT`,`POST`,`DELETE`,`PATCH`],allowHeaders:[],exposeHeaders:[],...e},n=(e=>typeof e==`string`?e===`*`?t.credentials?e=>e||null:()=>e:t=>e===t?t:null:typeof e==`function`?e:t=>e.includes(t)?t:null)(t.origin),r=(e=>typeof e==`function`?e:Array.isArray(e)?()=>e:()=>[])(t.allowMethods);return async function(e,i){function a(t,n){e.res.headers.set(t,n)}let o=await n(e.req.header(`origin`)||``,e);if(o&&a(`Access-Control-Allow-Origin`,o),t.credentials&&a(`Access-Control-Allow-Credentials`,`true`),t.exposeHeaders?.length&&a(`Access-Control-Expose-Headers`,t.exposeHeaders.join(`,`)),e.req.method===`OPTIONS`){(t.origin!==`*`||t.credentials)&&a(`Vary`,`Origin`),t.maxAge!=null&&a(`Access-Control-Max-Age`,t.maxAge.toString());let n=await r(e.req.header(`origin`)||``,e);n.length&&a(`Access-Control-Allow-Methods`,n.join(`,`));let i=t.allowHeaders;if(!i?.length){let t=e.req.header(`Access-Control-Request-Headers`);t&&(i=t.split(/\s*,\s*/))}return i?.length&&(a(`Access-Control-Allow-Headers`,i.join(`,`)),e.res.headers.append(`Vary`,`Access-Control-Request-Headers`)),e.res.headers.delete(`Content-Length`),e.res.headers.delete(`Content-Type`),new Response(null,{headers:e.res.headers,status:204,statusText:`No Content`})}await i(),(t.origin!==`*`||t.credentials)&&e.header(`Vary`,`Origin`,{append:!0})}};function a(a){let{cubes:o,drizzle:s,schema:c,extractSecurityContext:l,engineType:u,cors:d,basePath:f=`/cubejs-api/v1`,cache:p,mcp:m={enabled:!0},agent:h}=a;if(!a.semanticLayer&&(!o||o.length===0))throw Error(`Either semanticLayer or a non-empty cubes array must be provided`);let g=new r.Hono,_=async e=>t.r(await l(e),t.n(t=>e.req.header(t)));if(d){let e={...d,allowHeaders:t.t(d.allowHeaders)};g.use(`/*`,i(e))}let v=a.semanticLayer??new t.i({drizzle:s,schema:c,engineType:u,cache:p,rlsSetup:a.rlsSetup});if(!a.semanticLayer&&o&&o.forEach(e=>{v.registerCube(e)}),g.post(`${f}/load`,async t=>{try{let n=await t.req.json(),r=n.query||n,i=await _(t),a=v.validateQuery(r);if(!a.isValid)return t.json({error:`Query validation failed: ${a.errors.join(`, `)}`},400);let o=t.req.header(`x-cache-control`)===`no-cache`,s=await v.executeMultiCubeQuery(r,i,{skipCache:o});return t.json(e.r(r,s,v))}catch(e){return console.error(`Query execution error:`,e),t.json({error:e instanceof Error?e.message:`Query execution failed`},500)}}),g.get(`${f}/load`,async t=>{try{let n=t.req.query(`query`);if(!n)return t.json({error:`Query parameter is required`},400);let r;try{r=JSON.parse(n)}catch{return t.json({error:`Invalid JSON in query parameter`},400)}let i=await _(t),a=v.validateQuery(r);if(!a.isValid)return t.json({error:`Query validation failed: ${a.errors.join(`, `)}`},400);let o=t.req.header(`x-cache-control`)===`no-cache`,s=await v.executeMultiCubeQuery(r,i,{skipCache:o});return t.json(e.r(r,s,v))}catch(e){return console.error(`Query execution error:`,e),t.json({error:e instanceof Error?e.message:`Query execution failed`},500)}}),g.post(`${f}/batch`,async t=>{try{let{queries:n}=await t.req.json();if(!n||!Array.isArray(n))return t.json({error:`Request body must contain a "queries" array`},400);if(n.length===0)return t.json({error:`Queries array cannot be empty`},400);let r=await e.u(n,await _(t),v,{skipCache:t.req.header(`x-cache-control`)===`no-cache`});return t.json(r)}catch(e){return console.error(`Batch execution error:`,e),t.json({error:e instanceof Error?e.message:`Batch execution failed`},500)}}),g.get(`${f}/meta`,t=>{try{let n=v.getMetadata();return t.json(e.a(n))}catch(e){return console.error(`Metadata error:`,e),t.json({error:e instanceof Error?e.message:`Failed to fetch metadata`},500)}}),g.post(`${f}/sql`,async t=>{try{let n=await t.req.json(),r=await _(t),i=v.validateQuery(n);if(!i.isValid)return t.json({error:`Query validation failed: ${i.errors.join(`, `)}`},400);let a=n.measures?.[0]||n.dimensions?.[0];if(!a)return t.json({error:`No measures or dimensions specified`},400);let o=a.split(`.`)[0],s=await v.generateSQL(o,n,r);return t.json(e.o(n,s))}catch(e){return console.error(`SQL generation error:`,e),t.json({error:e instanceof Error?e.message:`SQL generation failed`},500)}}),g.get(`${f}/sql`,async t=>{try{let n=t.req.query(`query`);if(!n)return t.json({error:`Query parameter is required`},400);let r=JSON.parse(n),i=await _(t),a=v.validateQuery(r);if(!a.isValid)return t.json({error:`Query validation failed: ${a.errors.join(`, `)}`},400);let o=r.measures?.[0]||r.dimensions?.[0];if(!o)return t.json({error:`No measures or dimensions specified`},400);let s=o.split(`.`)[0],c=await v.generateSQL(s,r,i);return t.json(e.o(r,c))}catch(e){return console.error(`SQL generation error:`,e),t.json({error:e instanceof Error?e.message:`SQL generation failed`},500)}}),g.post(`${f}/dry-run`,async t=>{try{let n=await t.req.json(),r=await e.f(n.query||n,await _(t),v);return t.json(r)}catch(e){return console.error(`Dry-run error:`,e),t.json({error:e instanceof Error?e.message:`Dry-run validation failed`,valid:!1},400)}}),g.get(`${f}/dry-run`,async t=>{try{let n=t.req.query(`query`);if(!n)return t.json({error:`Query parameter is required`,valid:!1},400);let r=await e.f(JSON.parse(n),await _(t),v);return t.json(r)}catch(e){return console.error(`Dry-run error:`,e),t.json({error:e instanceof Error?e.message:`Dry-run validation failed`,valid:!1},400)}}),g.post(`${f}/explain`,async e=>{try{let t=await e.req.json(),n=t.query||t,r=t.options||{},i=await _(e),a=v.validateQuery(n);if(!a.isValid)return e.json({error:`Query validation failed: ${a.errors.join(`, `)}`},400);let o=await v.explainQuery(n,i,r);return e.json(o)}catch(t){return console.error(`Explain error:`,t),e.json({error:t instanceof Error?t.message:`Explain query failed`},500)}}),h&&g.post(`${f}/agent/chat`,async e=>{try{let{handleAgentChat:t}=await Promise.resolve().then(()=>require(`../handler-Cqf-CqAS.cjs`)),{message:n,sessionId:r,history:i}=await e.req.json();if(!n||typeof n!=`string`)return e.json({error:`message is required and must be a string`},400);let a=(h.apiKey||``).trim();if(h.allowClientApiKey){let t=e.req.header(`x-agent-api-key`);t&&(a=t.trim())}if(!a)return e.json({error:`No API key configured. Set agent.apiKey in server config or send X-Agent-Api-Key header.`},401);let o=h.allowClientApiKey?e.req.header(`x-agent-provider`):void 0,s=h.allowClientApiKey?e.req.header(`x-agent-model`):void 0,c=h.allowClientApiKey?e.req.header(`x-agent-provider-endpoint`):void 0,l=await _(e),u=h.buildSystemContext?.(l),d=new TextEncoder,f=new ReadableStream({async start(e){try{let f=t({message:n,sessionId:r,history:i,semanticLayer:v,securityContext:l,agentConfig:h,apiKey:a,systemContext:u,providerOverride:o,modelOverride:s,baseURLOverride:c});for await(let t of f){let n=`data: ${JSON.stringify(t)}\n\n`;e.enqueue(d.encode(n))}}catch(t){let n={type:`error`,data:{message:t instanceof Error?t.message:`Stream failed`}};e.enqueue(d.encode(`data: ${JSON.stringify(n)}\n\n`))}finally{e.close()}}});return new Response(f,{status:200,headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`}})}catch(t){return console.error(`Agent chat error:`,t),e.json({error:t instanceof Error?t.message:`Agent chat failed`},500)}}),m.enabled!==!1){let e=n.o(v,m.resources),t=n.v(m.prompts),r=m.basePath??`/mcp`;g.post(`${r}`,async r=>{if(m.resourceMetadataUrl&&!n.u(r.req.header(`authorization`)))return r.header(`WWW-Authenticate`,n.c(m.resourceMetadataUrl)),r.json({error:`Bearer token required`},401);let i=n.x(r.req.header(`origin`),m.allowedOrigins?{allowedOrigins:m.allowedOrigins}:{});if(!i.valid)return r.json(n.i(null,-32600,i.reason),403);let a=r.req.header(`accept`);if(!n.b(a))return r.json(n.i(null,-32600,`Accept header must include both application/json and text/event-stream`),400);let o=n.h(r.req.header());if(!o.ok)return r.json({error:`Unsupported MCP protocol version`,supported:o.supported},426);let s=n.g(await r.req.json().catch(()=>null));if(!s)return r.json(n.i(null,-32600,`Invalid JSON-RPC 2.0 request`),400);let c=n.S(a),l=s.method===`initialize`;try{let i=await n.l(s.method,s.params,{semanticLayer:v,extractSecurityContext:(e,t)=>_(e),rawRequest:r,rawResponse:null,negotiatedProtocol:o.negotiated,resources:e,prompts:t,appEnabled:!!m.app,appConfig:typeof m.app==`object`?m.app:void 0,serverName:m.serverName});if(n.m(s))return r.body(null,202);let a=n.a(s.id??null,i),u=l&&i&&typeof i==`object`&&`sessionId`in i?i.sessionId:void 0,d={};if(u&&(d[n.r]=u),c){let e=new TextEncoder,t=n._(),r=new ReadableStream({start(r){r.enqueue(e.encode(`id: ${t}\n\n`)),r.enqueue(e.encode(n.y(a,t))),r.close()}});return new Response(r,{status:200,headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`,...d}})}return r.json(a,200,d)}catch(e){if(n.m(s))return console.error(`MCP notification processing error:`,e),r.body(null,202);console.error(`MCP RPC error:`,e);let t=e?.code??-32603,i=e?.data,a=e.message||`MCP request failed`,o=n.i(s.id??null,t,a,i);if(c){let e=new TextEncoder,t=n._(),r=new ReadableStream({start(r){r.enqueue(e.encode(`id: ${t}\n\n`)),r.enqueue(e.encode(n.y(o,t))),r.close()}});return new Response(r,{status:200,headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`}})}return r.json(o,200)}}),g.delete(`${r}`,e=>m.resourceMetadataUrl&&!n.u(e.req.header(`authorization`))?(e.header(`WWW-Authenticate`,n.c(m.resourceMetadataUrl)),e.json({error:`Bearer token required`},401)):e.json({error:`Session termination not supported`},405)),g.get(`${r}`,e=>{if(m.resourceMetadataUrl&&!n.u(e.req.header(`authorization`)))return e.header(`WWW-Authenticate`,n.c(m.resourceMetadataUrl)),e.json({error:`Bearer token required`},401);let t=new TextEncoder,r=n._(),i,a=new ReadableStream({start(e){e.enqueue(t.encode(n.y({jsonrpc:`2.0`,method:`mcp/ready`,params:{protocol:`streamable-http`}},r,15e3))),i=setInterval(()=>{e.enqueue(t.encode(`: keep-alive
|
|
2
2
|
|
|
3
3
|
`))},15e3)},cancel(){clearInterval(i)}});return new Response(a,{status:200,headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`}})})}return g}function o(e,t){let n=a(t);return e.route(`/`,n),e}function s(e){return o(new r.Hono,e)}exports.createCubeApp=s,exports.createCubeRoutes=a,exports.mountCubeRoutes=o;
|