drizzle-cube 0.4.28 → 0.4.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/express/index.cjs +1 -1
- package/dist/adapters/express/index.js +2 -2
- package/dist/adapters/fastify/index.cjs +1 -1
- package/dist/adapters/fastify/index.js +2 -2
- package/dist/adapters/{handler-BV2_dul8.js → handler-BHguLZOY.js} +1 -1
- package/dist/adapters/{handler-LMRPeTNJ.cjs → handler-DOIyiFPg.cjs} +1 -1
- package/dist/adapters/hono/index.cjs +1 -1
- package/dist/adapters/hono/index.js +2 -2
- package/dist/adapters/mcp-transport-CWGqDQSI.cjs +259 -0
- package/dist/adapters/{mcp-transport-B6ZudTSk.js → mcp-transport-CyeHMDPl.js} +115 -70
- package/dist/adapters/nextjs/index.cjs +2 -2
- package/dist/adapters/nextjs/index.js +2 -2
- package/dist/server/index.cjs +13 -11
- package/dist/server/index.d.ts +13 -4
- package/dist/server/index.js +98 -53
- package/package.json +1 -1
- package/dist/adapters/mcp-transport-DCiSGtp1.cjs +0 -257
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("express"),H=require("cors"),c=require("../mcp-transport-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("express"),H=require("cors"),c=require("../mcp-transport-CWGqDQSI.cjs"),n=require("../utils.cjs");function $(C){const{cubes:v,drizzle:x,schema:I,extractSecurityContext:y,engineType:P,cors:S,basePath:f="/cubejs-api/v1",jsonLimit:Q="10mb",cache:O,mcp:E={enabled:!0},agent:h}=C;if(!v||v.length===0)throw new Error("At least one cube must be provided in the cubes array");const d=w.Router();S&&d.use(H(S)),d.use(w.json({limit:Q})),d.use(w.urlencoded({extended:!0,limit:Q}));const u=new c.SemanticLayerCompiler({drizzle:x,schema:I,engineType:P,cache:O});if(v.forEach(r=>{u.registerCube(r)}),d.post(`${f}/load`,async(r,t)=>{try{const e=r.body.query||r.body,o=await y(r,t),s=u.validateQuery(e);if(!s.isValid)return t.status(400).json(n.formatErrorResponse(`Query validation failed: ${s.errors.join(", ")}`,400));const a=r.headers["x-cache-control"]==="no-cache",i=await u.executeMultiCubeQuery(e,o,{skipCache:a});t.json(n.formatCubeResponse(e,i,u))}catch(e){console.error("Query execution error:",e),t.status(500).json(n.formatErrorResponse(e instanceof Error?e.message:"Query execution failed",500))}}),d.get(`${f}/load`,async(r,t)=>{try{const e=r.query.query;if(!e)return t.status(400).json(n.formatErrorResponse("Query parameter is required",400));let o;try{o=JSON.parse(e)}catch{return t.status(400).json(n.formatErrorResponse("Invalid JSON in query parameter",400))}const s=await y(r,t),a=u.validateQuery(o);if(!a.isValid)return t.status(400).json(n.formatErrorResponse(`Query validation failed: ${a.errors.join(", ")}`,400));const i=r.headers["x-cache-control"]==="no-cache",m=await u.executeMultiCubeQuery(o,s,{skipCache:i});t.json(n.formatCubeResponse(o,m,u))}catch(e){console.error("Query execution error:",e),t.status(500).json(n.formatErrorResponse(e instanceof Error?e.message:"Query execution failed",500))}}),d.post(`${f}/batch`,async(r,t)=>{try{const{queries:e}=r.body;if(!e||!Array.isArray(e))return t.status(400).json(n.formatErrorResponse('Request body must contain a "queries" array',400));if(e.length===0)return t.status(400).json(n.formatErrorResponse("Queries array cannot be empty",400));const o=await y(r,t),s=r.headers["x-cache-control"]==="no-cache",a=await n.handleBatchRequest(e,o,u,{skipCache:s});t.json(a)}catch(e){console.error("Batch execution error:",e),t.status(500).json(n.formatErrorResponse(e instanceof Error?e.message:"Batch execution failed",500))}}),d.get(`${f}/meta`,(r,t)=>{try{const e=u.getMetadata();t.json(n.formatMetaResponse(e))}catch(e){console.error("Metadata error:",e),t.status(500).json(n.formatErrorResponse(e instanceof Error?e.message:"Failed to fetch metadata",500))}}),d.post(`${f}/sql`,async(r,t)=>{try{const e=r.body,o=await y(r,t),s=u.validateQuery(e);if(!s.isValid)return t.status(400).json(n.formatErrorResponse(`Query validation failed: ${s.errors.join(", ")}`,400));const a=e.measures?.[0]||e.dimensions?.[0];if(!a)return t.status(400).json(n.formatErrorResponse("No measures or dimensions specified",400));const i=a.split(".")[0],m=await u.generateSQL(i,e,o);t.json(n.formatSqlResponse(e,m))}catch(e){console.error("SQL generation error:",e),t.status(500).json(n.formatErrorResponse(e instanceof Error?e.message:"SQL generation failed",500))}}),d.get(`${f}/sql`,async(r,t)=>{try{const e=r.query.query;if(!e)return t.status(400).json(n.formatErrorResponse("Query parameter is required",400));const o=JSON.parse(e),s=await y(r,t),a=u.validateQuery(o);if(!a.isValid)return t.status(400).json(n.formatErrorResponse(`Query validation failed: ${a.errors.join(", ")}`,400));const i=o.measures?.[0]||o.dimensions?.[0];if(!i)return t.status(400).json(n.formatErrorResponse("No measures or dimensions specified",400));const m=i.split(".")[0],R=await u.generateSQL(m,o,s);t.json(n.formatSqlResponse(o,R))}catch(e){console.error("SQL generation error:",e),t.status(500).json(n.formatErrorResponse(e instanceof Error?e.message:"SQL generation failed",500))}}),d.post(`${f}/dry-run`,async(r,t)=>{try{const e=r.body.query||r.body,o=await y(r,t),s=await n.handleDryRun(e,o,u);t.json(s)}catch(e){console.error("Dry-run error:",e),t.status(400).json({error:e instanceof Error?e.message:"Dry-run validation failed",valid:!1})}}),d.get(`${f}/dry-run`,async(r,t)=>{try{const e=r.query.query;if(!e)return t.status(400).json({error:"Query parameter is required",valid:!1});const o=JSON.parse(e),s=await y(r,t),a=await n.handleDryRun(o,s,u);t.json(a)}catch(e){console.error("Dry-run error:",e),t.status(400).json({error:e instanceof Error?e.message:"Dry-run validation failed",valid:!1})}}),d.post(`${f}/explain`,async(r,t)=>{try{const e=r.body.query||r.body,o=r.body.options||{},s=await y(r,t),a=u.validateQuery(e);if(!a.isValid)return t.status(400).json({error:`Query validation failed: ${a.errors.join(", ")}`});const i=await u.explainQuery(e,s,o);t.json(i)}catch(e){console.error("Explain error:",e),t.status(500).json({error:e instanceof Error?e.message:"Explain query failed"})}}),h&&d.post(`${f}/agent/chat`,async(r,t)=>{try{const{handleAgentChat:e}=await Promise.resolve().then(()=>require("../handler-DOIyiFPg.cjs")),{message:o,sessionId:s,history:a}=r.body;if(!o||typeof o!="string")return t.status(400).json({error:"message is required and must be a string"});let i=(h.apiKey||"").trim();if(h.allowClientApiKey){const p=r.headers["x-agent-api-key"];p&&(i=p.trim())}if(!i)return t.status(401).json({error:"No API key configured. Set agent.apiKey in server config or send X-Agent-Api-Key header."});const m=h.allowClientApiKey?r.headers["x-agent-provider"]:void 0,R=h.allowClientApiKey?r.headers["x-agent-model"]:void 0,l=h.allowClientApiKey?r.headers["x-agent-provider-endpoint"]:void 0,g=await y(r,t),b=h.buildSystemContext?.(g);t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});try{const p=e({message:o,sessionId:s,history:a,semanticLayer:u,securityContext:g,agentConfig:h,apiKey:i,systemContext:b,providerOverride:m,modelOverride:R,baseURLOverride:l});for await(const j of p)t.write(`data: ${JSON.stringify(j)}
|
|
2
2
|
|
|
3
3
|
`)}catch(p){const j={type:"error",data:{message:p instanceof Error?p.message:"Stream failed"}};t.write(`data: ${JSON.stringify(j)}
|
|
4
4
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import R, { Router as J } from "express";
|
|
2
2
|
import L from "cors";
|
|
3
|
-
import { S as K, v as D, b as x, a as _, n as V, p as z, w as T, d as B, i as I, M as U, c as F, e as Q, s as E } from "../mcp-transport-
|
|
3
|
+
import { S as K, v as D, b as x, a as _, n as V, p as z, w as T, d as B, i as I, M as U, c as F, e as Q, s as E } from "../mcp-transport-CyeHMDPl.js";
|
|
4
4
|
import { formatErrorResponse as u, formatCubeResponse as P, handleBatchRequest as X, formatMetaResponse as G, formatSqlResponse as H, handleDryRun as M } from "../utils.js";
|
|
5
5
|
function W(v) {
|
|
6
6
|
const {
|
|
@@ -198,7 +198,7 @@ function W(v) {
|
|
|
198
198
|
}
|
|
199
199
|
}), m && c.post(`${p}/agent/chat`, async (r, t) => {
|
|
200
200
|
try {
|
|
201
|
-
const { handleAgentChat: e } = await import("../handler-
|
|
201
|
+
const { handleAgentChat: e } = await import("../handler-BHguLZOY.js"), { message: o, sessionId: a, history: n } = r.body;
|
|
202
202
|
if (!o || typeof o != "string")
|
|
203
203
|
return t.status(400).json({ error: "message is required and must be a string" });
|
|
204
204
|
let s = (m.apiKey || "").trim();
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var N=Object.create;var j=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var L=Object.getPrototypeOf,K=Object.prototype.hasOwnProperty;var D=(l,n,v,S)=>{if(n&&typeof n=="object"||typeof n=="function")for(let f of J(n))!K.call(l,f)&&f!==v&&j(l,f,{get:()=>n[f],enumerable:!(S=k(n,f))||S.enumerable});return l};var H=(l,n,v)=>(v=l!=null?N(L(l)):{},D(n||!l||!l.__esModule?j(v,"default",{value:l,enumerable:!0}):v,l));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("../mcp-transport-
|
|
1
|
+
"use strict";var N=Object.create;var j=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var L=Object.getPrototypeOf,K=Object.prototype.hasOwnProperty;var D=(l,n,v,S)=>{if(n&&typeof n=="object"||typeof n=="function")for(let f of J(n))!K.call(l,f)&&f!==v&&j(l,f,{get:()=>n[f],enumerable:!(S=k(n,f))||S.enumerable});return l};var H=(l,n,v)=>(v=l!=null?N(L(l)):{},D(n||!l||!l.__esModule?j(v,"default",{value:l,enumerable:!0}):v,l));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("../mcp-transport-CWGqDQSI.cjs"),a=require("../utils.cjs"),Q=function(n,v,S){const{cubes:f,drizzle:A,schema:I,extractSecurityContext:m,engineType:O,cors:$,basePath:g="/cubejs-api/v1",bodyLimit:C=10485760,cache:M,mcp:q={enabled:!0},agent:b}=v;if(!f||f.length===0)return S(new Error("At least one cube must be provided in the cubes array"));$&&n.register(import("@fastify/cors"),$),n.addHook("onRequest",async(r,t)=>{r.method==="POST"&&(r.body=void 0)});const u=new d.SemanticLayerCompiler({drizzle:A,schema:I,engineType:O,cache:M});if(f.forEach(r=>{u.registerCube(r)}),n.post(`${g}/load`,{bodyLimit:C,schema:{body:{type:"object",additionalProperties:!0}}},async(r,t)=>{try{const e=r.body,o=e.query||e,s=await m(r),i=u.validateQuery(o);if(!i.isValid)return t.status(400).send(a.formatErrorResponse(`Query validation failed: ${i.errors.join(", ")}`,400));const c=r.headers["x-cache-control"]==="no-cache",p=await u.executeMultiCubeQuery(o,s,{skipCache:c});return a.formatCubeResponse(o,p,u)}catch(e){return r.log.error(e,"Query execution error"),t.status(500).send(a.formatErrorResponse(e instanceof Error?e.message:"Query execution failed",500))}}),n.get(`${g}/load`,{schema:{querystring:{type:"object",properties:{query:{type:"string"}},required:["query"]}}},async(r,t)=>{try{const{query:e}=r.query;let o;try{o=JSON.parse(e)}catch{return t.status(400).send(a.formatErrorResponse("Invalid JSON in query parameter",400))}const s=await m(r),i=u.validateQuery(o);if(!i.isValid)return t.status(400).send(a.formatErrorResponse(`Query validation failed: ${i.errors.join(", ")}`,400));const c=r.headers["x-cache-control"]==="no-cache",p=await u.executeMultiCubeQuery(o,s,{skipCache:c});return a.formatCubeResponse(o,p,u)}catch(e){return r.log.error(e,"Query execution error"),t.status(500).send(a.formatErrorResponse(e instanceof Error?e.message:"Query execution failed",500))}}),n.post(`${g}/batch`,{bodyLimit:C,schema:{body:{type:"object",required:["queries"],properties:{queries:{type:"array",items:{type:"object"}}}}}},async(r,t)=>{try{const{queries:e}=r.body;if(!e||!Array.isArray(e))return t.status(400).send(a.formatErrorResponse('Request body must contain a "queries" array',400));if(e.length===0)return t.status(400).send(a.formatErrorResponse("Queries array cannot be empty",400));const o=await m(r),s=r.headers["x-cache-control"]==="no-cache";return await a.handleBatchRequest(e,o,u,{skipCache:s})}catch(e){return r.log.error(e,"Batch execution error"),t.status(500).send(a.formatErrorResponse(e instanceof Error?e.message:"Batch execution failed",500))}}),n.get(`${g}/meta`,async(r,t)=>{try{const e=u.getMetadata();return a.formatMetaResponse(e)}catch(e){return r.log.error(e,"Metadata error"),t.status(500).send(a.formatErrorResponse(e instanceof Error?e.message:"Failed to fetch metadata",500))}}),n.post(`${g}/sql`,{bodyLimit:C,schema:{body:{type:"object",additionalProperties:!0}}},async(r,t)=>{try{const e=r.body,o=await m(r),s=u.validateQuery(e);if(!s.isValid)return t.status(400).send(a.formatErrorResponse(`Query validation failed: ${s.errors.join(", ")}`,400));const i=e.measures?.[0]||e.dimensions?.[0];if(!i)return t.status(400).send(a.formatErrorResponse("No measures or dimensions specified",400));const c=i.split(".")[0],p=await u.generateSQL(c,e,o);return a.formatSqlResponse(e,p)}catch(e){return r.log.error(e,"SQL generation error"),t.status(500).send(a.formatErrorResponse(e instanceof Error?e.message:"SQL generation failed",500))}}),n.get(`${g}/sql`,{schema:{querystring:{type:"object",properties:{query:{type:"string"}},required:["query"]}}},async(r,t)=>{try{const{query:e}=r.query,o=JSON.parse(e),s=await m(r),i=u.validateQuery(o);if(!i.isValid)return t.status(400).send(a.formatErrorResponse(`Query validation failed: ${i.errors.join(", ")}`,400));const c=o.measures?.[0]||o.dimensions?.[0];if(!c)return t.status(400).send(a.formatErrorResponse("No measures or dimensions specified",400));const p=c.split(".")[0],P=await u.generateSQL(p,o,s);return a.formatSqlResponse(o,P)}catch(e){return r.log.error(e,"SQL generation error"),t.status(500).send(a.formatErrorResponse(e instanceof Error?e.message:"SQL generation failed",500))}}),n.post(`${g}/dry-run`,{bodyLimit:C,schema:{body:{type:"object",additionalProperties:!0}}},async(r,t)=>{try{const e=r.body,o=e.query||e,s=await m(r);return await a.handleDryRun(o,s,u)}catch(e){return r.log.error(e,"Dry-run error"),t.status(400).send({error:e instanceof Error?e.message:"Dry-run validation failed",valid:!1})}}),n.get(`${g}/dry-run`,{schema:{querystring:{type:"object",properties:{query:{type:"string"}},required:["query"]}}},async(r,t)=>{try{const{query:e}=r.query,o=JSON.parse(e),s=await m(r);return await a.handleDryRun(o,s,u)}catch(e){return r.log.error(e,"Dry-run error"),t.status(400).send({error:e instanceof Error?e.message:"Dry-run validation failed",valid:!1})}}),n.post(`${g}/explain`,{bodyLimit:C,schema:{body:{type:"object",additionalProperties:!0}}},async(r,t)=>{try{const e=r.body,o=e.query||e,s=e.options||{},i=await m(r),c=u.validateQuery(o);return c.isValid?await u.explainQuery(o,i,s):t.status(400).send({error:`Query validation failed: ${c.errors.join(", ")}`})}catch(e){return r.log.error(e,"Explain error"),t.status(500).send({error:e instanceof Error?e.message:"Explain query failed"})}}),b&&n.post(`${g}/agent/chat`,{bodyLimit:C,schema:{body:{type:"object",additionalProperties:!0}}},async(r,t)=>{try{const{handleAgentChat:e}=await Promise.resolve().then(()=>require("../handler-DOIyiFPg.cjs")),o=r.body,{message:s,sessionId:i,history:c}=o;if(!s||typeof s!="string")return t.status(400).send({error:"message is required and must be a string"});let p=(b.apiKey||"").trim();if(b.allowClientApiKey){const h=r.headers["x-agent-api-key"];h&&(p=h.trim())}if(!p)return t.status(401).send({error:"No API key configured. Set agent.apiKey in server config or send X-Agent-Api-Key header."});const P=b.allowClientApiKey?r.headers["x-agent-provider"]:void 0,y=b.allowClientApiKey?r.headers["x-agent-model"]:void 0,E=b.allowClientApiKey?r.headers["x-agent-provider-endpoint"]:void 0,w=await m(r),R=b.buildSystemContext?.(w);t.raw.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});try{const h=e({message:s,sessionId:i,history:c,semanticLayer:u,securityContext:w,agentConfig:b,apiKey:p,systemContext:R,providerOverride:P,modelOverride:y,baseURLOverride:E});for await(const x of h)t.raw.write(`data: ${JSON.stringify(x)}
|
|
2
2
|
|
|
3
3
|
`)}catch(h){const x={type:"error",data:{message:h instanceof Error?h.message:"Stream failed"}};t.raw.write(`data: ${JSON.stringify(x)}
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as H, v as D, b as E, a as T, n as V, p as z, w as _, d as B, i as j, M as F, c as U, e as P, s as Q } from "../mcp-transport-
|
|
1
|
+
import { S as H, v as D, b as E, a as T, n as V, p as z, w as _, d as B, i as j, M as F, c as U, e as P, s as Q } from "../mcp-transport-CyeHMDPl.js";
|
|
2
2
|
import { formatErrorResponse as d, formatCubeResponse as A, handleBatchRequest as X, formatMetaResponse as G, formatSqlResponse as I, handleDryRun as O } from "../utils.js";
|
|
3
3
|
const M = function(i, N, $) {
|
|
4
4
|
const {
|
|
@@ -262,7 +262,7 @@ const M = function(i, N, $) {
|
|
|
262
262
|
}
|
|
263
263
|
}, async (t, r) => {
|
|
264
264
|
try {
|
|
265
|
-
const { handleAgentChat: e } = await import("../handler-
|
|
265
|
+
const { handleAgentChat: e } = await import("../handler-BHguLZOY.js"), a = t.body, { message: n, sessionId: o, history: s } = a;
|
|
266
266
|
if (!n || typeof n != "string")
|
|
267
267
|
return r.status(400).send({ error: "message is required and must be a string" });
|
|
268
268
|
let u = (h.apiKey || "").trim();
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("./mcp-transport-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("./mcp-transport-CWGqDQSI.cjs"),j=require("./utils.cjs");function Z(d){if(d.length===0)return"No cubes are currently available.";const s=["## Available Cubes",""];for(const a of d){if(s.push(`### ${a.name}`),a.description&&s.push(a.description),a.measures&&a.measures.length>0){s.push(""),s.push("**Measures:**");for(const o of a.measures){const y=o.description?` - ${o.description}`:"";s.push(`- \`${a.name}.${o.name}\` (${o.type})${y}`)}}if(a.dimensions&&a.dimensions.length>0){s.push(""),s.push("**Dimensions:**");for(const o of a.dimensions){const y=o.description?` - ${o.description}`:"";s.push(`- \`${a.name}.${o.name}\` (${o.type})${y}`)}}if(a.relationships&&a.relationships.length>0){s.push(""),s.push("**Joins:**");for(const o of a.relationships)s.push(`- → \`${o.targetCube}\` (${o.relationship})`)}a.meta?.eventStream&&(s.push(""),s.push("**Event Stream:** Yes (supports funnel, flow, retention queries)"),a.meta.eventStream.bindingKey&&s.push(`- Binding key: \`${a.name}.${a.meta.eventStream.bindingKey}\``),a.meta.eventStream.timeDimension&&s.push(`- Time dimension: \`${a.name}.${a.meta.eventStream.timeDimension}\``)),s.push("")}return s.join(`
|
|
2
2
|
`)}function M(d){return d.messages.map(s=>s.content.text).join(`
|
|
3
3
|
|
|
4
4
|
`)}function G(d){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 `CubeName.fieldName` with a DOT separator (e.g. `PullRequests.count`, `Teams.name`). NEVER use underscores, NEVER use just the cube name as a field — `PullRequests.PullRequests` and `Teams_count` are WRONG.","- 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',"","## 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.","","---","",M(I.MCP_GUIDE_PROMPT),"","---","",M(I.QUERY_RULES_PROMPT),"","---","",M(I.QUERY_BUILDING_PROMPT),"","---","",M(I.DATE_FILTERING_PROMPT),"","---","","## Save as Dashboard","","When the user asks to save, export, or convert the notebook into a dashboard, use the `save_as_dashboard` tool.","","### 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","","---","",Z(d)].join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const M=require("hono"),a=require("../mcp-transport-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const M=require("hono"),a=require("../mcp-transport-CWGqDQSI.cjs"),R=require("../utils.cjs");var L=g=>{const y={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...g},T=(d=>typeof d=="string"?d==="*"?()=>d:c=>d===c?c:null:typeof d=="function"?d:c=>d.includes(c)?c:null)(y.origin),h=(d=>typeof d=="function"?d:Array.isArray(d)?()=>d:()=>[])(y.allowMethods);return async function(c,q){function b(f,i){c.res.headers.set(f,i)}const E=await T(c.req.header("origin")||"",c);if(E&&b("Access-Control-Allow-Origin",E),y.credentials&&b("Access-Control-Allow-Credentials","true"),y.exposeHeaders?.length&&b("Access-Control-Expose-Headers",y.exposeHeaders.join(",")),c.req.method==="OPTIONS"){y.origin!=="*"&&b("Vary","Origin"),y.maxAge!=null&&b("Access-Control-Max-Age",y.maxAge.toString());const f=await h(c.req.header("origin")||"",c);f.length&&b("Access-Control-Allow-Methods",f.join(","));let i=y.allowHeaders;if(!i?.length){const s=c.req.header("Access-Control-Request-Headers");s&&(i=s.split(/\s*,\s*/))}return i?.length&&(b("Access-Control-Allow-Headers",i.join(",")),c.res.headers.append("Vary","Access-Control-Request-Headers")),c.res.headers.delete("Content-Length"),c.res.headers.delete("Content-Type"),new Response(null,{headers:c.res.headers,status:204,statusText:"No Content"})}await q(),y.origin!=="*"&&c.header("Vary","Origin",{append:!0})}};function N(g){const{cubes:j,drizzle:y,schema:T,extractSecurityContext:h,engineType:d,cors:c,basePath:q="/cubejs-api/v1",cache:b,mcp:E={enabled:!0},agent:f}=g;if(!g.semanticLayer&&(!j||j.length===0))throw new Error("Either semanticLayer or a non-empty cubes array must be provided");const i=new M.Hono;c&&i.use("/*",L(c));const s=g.semanticLayer??new a.SemanticLayerCompiler({drizzle:y,schema:T,engineType:d,cache:b});if(!g.semanticLayer&&j&&j.forEach(e=>{s.registerCube(e)}),i.post(`${q}/load`,async e=>{try{const r=await e.req.json(),n=r.query||r,o=await h(e),t=s.validateQuery(n);if(!t.isValid)return e.json({error:`Query validation failed: ${t.errors.join(", ")}`},400);const u=e.req.header("x-cache-control")==="no-cache",l=await s.executeMultiCubeQuery(n,o,{skipCache:u});return e.json(R.formatCubeResponse(n,l,s))}catch(r){return console.error("Query execution error:",r),e.json({error:r instanceof Error?r.message:"Query execution failed"},500)}}),i.get(`${q}/load`,async e=>{try{const r=e.req.query("query");if(!r)return e.json({error:"Query parameter is required"},400);let n;try{n=JSON.parse(r)}catch{return e.json({error:"Invalid JSON in query parameter"},400)}const o=await h(e),t=s.validateQuery(n);if(!t.isValid)return e.json({error:`Query validation failed: ${t.errors.join(", ")}`},400);const u=e.req.header("x-cache-control")==="no-cache",l=await s.executeMultiCubeQuery(n,o,{skipCache:u});return e.json(R.formatCubeResponse(n,l,s))}catch(r){return console.error("Query execution error:",r),e.json({error:r instanceof Error?r.message:"Query execution failed"},500)}}),i.post(`${q}/batch`,async e=>{try{const r=await e.req.json(),{queries:n}=r;if(!n||!Array.isArray(n))return e.json({error:'Request body must contain a "queries" array'},400);if(n.length===0)return e.json({error:"Queries array cannot be empty"},400);const o=await h(e),t=e.req.header("x-cache-control")==="no-cache",u=await R.handleBatchRequest(n,o,s,{skipCache:t});return e.json(u)}catch(r){return console.error("Batch execution error:",r),e.json({error:r instanceof Error?r.message:"Batch execution failed"},500)}}),i.get(`${q}/meta`,e=>{try{const r=s.getMetadata();return e.json(R.formatMetaResponse(r))}catch(r){return console.error("Metadata error:",r),e.json({error:r instanceof Error?r.message:"Failed to fetch metadata"},500)}}),i.post(`${q}/sql`,async e=>{try{const r=await e.req.json(),n=await h(e),o=s.validateQuery(r);if(!o.isValid)return e.json({error:`Query validation failed: ${o.errors.join(", ")}`},400);const t=r.measures?.[0]||r.dimensions?.[0];if(!t)return e.json({error:"No measures or dimensions specified"},400);const u=t.split(".")[0],l=await s.generateSQL(u,r,n);return e.json(R.formatSqlResponse(r,l))}catch(r){return console.error("SQL generation error:",r),e.json({error:r instanceof Error?r.message:"SQL generation failed"},500)}}),i.get(`${q}/sql`,async e=>{try{const r=e.req.query("query");if(!r)return e.json({error:"Query parameter is required"},400);const n=JSON.parse(r),o=await h(e),t=s.validateQuery(n);if(!t.isValid)return e.json({error:`Query validation failed: ${t.errors.join(", ")}`},400);const u=n.measures?.[0]||n.dimensions?.[0];if(!u)return e.json({error:"No measures or dimensions specified"},400);const l=u.split(".")[0],v=await s.generateSQL(l,n,o);return e.json(R.formatSqlResponse(n,v))}catch(r){return console.error("SQL generation error:",r),e.json({error:r instanceof Error?r.message:"SQL generation failed"},500)}}),i.post(`${q}/dry-run`,async e=>{try{const r=await e.req.json(),n=r.query||r,o=await h(e),t=await R.handleDryRun(n,o,s);return e.json(t)}catch(r){return console.error("Dry-run error:",r),e.json({error:r instanceof Error?r.message:"Dry-run validation failed",valid:!1},400)}}),i.get(`${q}/dry-run`,async e=>{try{const r=e.req.query("query");if(!r)return e.json({error:"Query parameter is required",valid:!1},400);const n=JSON.parse(r),o=await h(e),t=await R.handleDryRun(n,o,s);return e.json(t)}catch(r){return console.error("Dry-run error:",r),e.json({error:r instanceof Error?r.message:"Dry-run validation failed",valid:!1},400)}}),i.post(`${q}/explain`,async e=>{try{const r=await e.req.json(),n=r.query||r,o=r.options||{},t=await h(e),u=s.validateQuery(n);if(!u.isValid)return e.json({error:`Query validation failed: ${u.errors.join(", ")}`},400);const l=await s.explainQuery(n,t,o);return e.json(l)}catch(r){return console.error("Explain error:",r),e.json({error:r instanceof Error?r.message:"Explain query failed"},500)}}),f&&i.post(`${q}/agent/chat`,async e=>{try{const{handleAgentChat:r}=await Promise.resolve().then(()=>require("../handler-DOIyiFPg.cjs")),n=await e.req.json(),{message:o,sessionId:t,history:u}=n;if(!o||typeof o!="string")return e.json({error:"message is required and must be a string"},400);let l=(f.apiKey||"").trim();if(f.allowClientApiKey){const C=e.req.header("x-agent-api-key");C&&(l=C.trim())}if(!l)return e.json({error:"No API key configured. Set agent.apiKey in server config or send X-Agent-Api-Key header."},401);const v=f.allowClientApiKey?e.req.header("x-agent-provider"):void 0,Q=f.allowClientApiKey?e.req.header("x-agent-model"):void 0,m=f.allowClientApiKey?e.req.header("x-agent-provider-endpoint"):void 0,P=await h(e),H=f.buildSystemContext?.(P),p=new TextEncoder,A=new ReadableStream({async start(C){try{const w=r({message:o,sessionId:t,history:u,semanticLayer:s,securityContext:P,agentConfig:f,apiKey:l,systemContext:H,providerOverride:v,modelOverride:Q,baseURLOverride:m});for await(const x of w){const S=`data: ${JSON.stringify(x)}
|
|
2
2
|
|
|
3
3
|
`;C.enqueue(p.encode(S))}}catch(w){const x={type:"error",data:{message:w instanceof Error?w.message:"Stream failed"}};C.enqueue(p.encode(`data: ${JSON.stringify(x)}
|
|
4
4
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Hono as J } from "hono";
|
|
2
|
-
import { S as K, v as V, b as $, a as B, n as z, p as _, w as U, d as F, g as G, f as X, i as I, c as W, M as Y, e as N, s as T } from "../mcp-transport-
|
|
2
|
+
import { S as K, v as V, b as $, a as B, n as z, p as _, w as U, d as F, g as G, f as X, i as I, c as W, M as Y, e as N, s as T } from "../mcp-transport-CyeHMDPl.js";
|
|
3
3
|
import { formatCubeResponse as L, handleBatchRequest as Z, formatMetaResponse as ee, formatSqlResponse as k, handleDryRun as D } from "../utils.js";
|
|
4
4
|
var re = (g) => {
|
|
5
5
|
const d = {
|
|
@@ -212,7 +212,7 @@ function te(g) {
|
|
|
212
212
|
}
|
|
213
213
|
}), p && a.post(`${h}/agent/chat`, async (e) => {
|
|
214
214
|
try {
|
|
215
|
-
const { handleAgentChat: r } = await import("../handler-
|
|
215
|
+
const { handleAgentChat: r } = await import("../handler-BHguLZOY.js"), n = await e.req.json(), { message: o, sessionId: t, history: c } = n;
|
|
216
216
|
if (!o || typeof o != "string")
|
|
217
217
|
return e.json({ error: "message is required and must be a string" }, 400);
|
|
218
218
|
let u = (p.apiKey || "").trim();
|