@smallwebco/tinypivot-mcp 0.2.10 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +25 -6
- package/dist/app/index.html +87 -86
- package/dist/{chunk-6I4RP5QJ.js → chunk-ZZOVYGIU.js} +915 -116
- package/dist/cli.js +37 -18
- package/dist/index.d.ts +218 -7
- package/dist/index.js +9 -1
- package/package.json +2 -1
- package/server.json +3 -3
- package/skills/tinypivot/SKILL.md +6 -3
|
@@ -5634,8 +5634,8 @@ var require_pgsql_ast_parser = __commonJS({
|
|
|
5634
5634
|
}
|
|
5635
5635
|
return x.path;
|
|
5636
5636
|
} },
|
|
5637
|
-
{ "name": "path", "symbols": ["open_path"], "postprocess": ([
|
|
5638
|
-
{ "name": "path", "symbols": ["closed_path"], "postprocess": ([
|
|
5637
|
+
{ "name": "path", "symbols": ["open_path"], "postprocess": ([path10]) => ({ closed: false, path: path10 }) },
|
|
5638
|
+
{ "name": "path", "symbols": ["closed_path"], "postprocess": ([path10]) => ({ closed: true, path: path10 }) },
|
|
5639
5639
|
{ "name": "open_path$macrocall$2", "symbols": [geometric_lexer_1.lexerAny.has("lbracket") ? { type: "lbracket" } : lbracket] },
|
|
5640
5640
|
{ "name": "open_path$macrocall$3", "symbols": [geometric_lexer_1.lexerAny.has("rbracket") ? { type: "rbracket" } : rbracket] },
|
|
5641
5641
|
{ "name": "open_path$macrocall$1$macrocall$2", "symbols": ["point"] },
|
|
@@ -8252,6 +8252,9 @@ function tokensToUsd(tokens, ratePerMillion) {
|
|
|
8252
8252
|
return Math.max(0, tokens) / 1e6 * ratePerMillion;
|
|
8253
8253
|
}
|
|
8254
8254
|
|
|
8255
|
+
// src/studio-protocol.ts
|
|
8256
|
+
var STUDIO_HEADER = "x-tinypivot";
|
|
8257
|
+
|
|
8255
8258
|
// src/store.ts
|
|
8256
8259
|
import fsSync from "fs";
|
|
8257
8260
|
import fs from "fs/promises";
|
|
@@ -9374,6 +9377,26 @@ function detectNonAdditiveSumWarning(dataset, chartConfig) {
|
|
|
9374
9377
|
const grain = sField ? `\`(${xField}, ${sField})\`` : `\`${xField}\``;
|
|
9375
9378
|
return `> **Data Integrity Warning:** \`${yField}\` appears to be a non-additive percentage/ratio, and **${collisions}** ${grain} bucket${collisions === 1 ? "" : "s"} contain multiple rows that were summed (\`aggregation: "sum"\`). Re-aggregate in SQL or Python to strictly 1 row per ${grain} using \`SUM(numerator) / SUM(denominator)\` before passing to TinyPivot.`;
|
|
9376
9379
|
}
|
|
9380
|
+
var SMALL_GRID_MAX_ROWS = 25;
|
|
9381
|
+
var SMALL_GRID_MAX_COLUMNS = 10;
|
|
9382
|
+
function tableCell(value2) {
|
|
9383
|
+
if (value2 === null || value2 === void 0)
|
|
9384
|
+
return "";
|
|
9385
|
+
const text = typeof value2 === "number" ? value2.toLocaleString("en-US", { maximumFractionDigits: 4 }) : String(value2);
|
|
9386
|
+
return text.replace(/\|/g, "\\|").replace(/\n/g, " ");
|
|
9387
|
+
}
|
|
9388
|
+
function smallGridTable(dataset) {
|
|
9389
|
+
if (dataset.viewMode !== "grid" || dataset.rows.length > SMALL_GRID_MAX_ROWS || dataset.columns.length > SMALL_GRID_MAX_COLUMNS)
|
|
9390
|
+
return null;
|
|
9391
|
+
const names = dataset.columns.map((column) => column.name);
|
|
9392
|
+
if (names.length === 0)
|
|
9393
|
+
return null;
|
|
9394
|
+
return [
|
|
9395
|
+
`| ${names.join(" | ")} |`,
|
|
9396
|
+
`|${names.map(() => "---").join("|")}|`,
|
|
9397
|
+
...dataset.rows.map((row) => `| ${names.map((name) => tableCell(row[name])).join(" | ")} |`)
|
|
9398
|
+
].join("\n");
|
|
9399
|
+
}
|
|
9377
9400
|
function pivotTableCard(dataset, options) {
|
|
9378
9401
|
const pivot = dataset.pivotConfig;
|
|
9379
9402
|
if (dataset.viewMode !== "pivot" || !pivot?.valueFields?.length)
|
|
@@ -9402,7 +9425,7 @@ function formatColumnNotes(columns) {
|
|
|
9402
9425
|
var REPRINT_NOTE = "Show the card above to the user verbatim.";
|
|
9403
9426
|
function formatDatasetSummary(dataset, companionUrl, options = {}) {
|
|
9404
9427
|
const cardOptions = { ...options, companionUrl: options.companionUrl ?? companionUrl };
|
|
9405
|
-
const chartBlock = pivotTableCard(dataset, cardOptions) ?? formatTerminalChart(dataset, dataset.chartConfig, cardOptions);
|
|
9428
|
+
const chartBlock = smallGridTable(dataset) ?? pivotTableCard(dataset, cardOptions) ?? formatTerminalChart(dataset, dataset.chartConfig, cardOptions);
|
|
9406
9429
|
const rowHeadline = dataset.truncatedForFreeTier ? `**${dataset.rows.length.toLocaleString()} of ${dataset.sourceTotalRows.toLocaleString()} rows (Free tier limit)**` : `**${dataset.rows.length.toLocaleString()} rows**`;
|
|
9407
9430
|
const parts = [
|
|
9408
9431
|
`Loaded **${dataset.name}** (\`${dataset.id}\`): ${rowHeadline}, ${dataset.columns.length} columns.`
|
|
@@ -9424,7 +9447,7 @@ function formatDatasetSummary(dataset, companionUrl, options = {}) {
|
|
|
9424
9447
|
}
|
|
9425
9448
|
parts.push("", formatColumnNotes(dataset.columns));
|
|
9426
9449
|
if (companionUrl && !chartBlock)
|
|
9427
|
-
parts.push(`
|
|
9450
|
+
parts.push(`Studio: ${companionUrl}`);
|
|
9428
9451
|
return parts.join("\n");
|
|
9429
9452
|
}
|
|
9430
9453
|
function formatPivotSummary(dataset, config, companionUrl, options = {}) {
|
|
@@ -10084,10 +10107,39 @@ var INTERACTIVE_ROW_LIMIT = 1e5;
|
|
|
10084
10107
|
var ROW_PAGE_SIZE = 25e3;
|
|
10085
10108
|
|
|
10086
10109
|
// src/companion.ts
|
|
10110
|
+
function isAllowedRequest(request, port) {
|
|
10111
|
+
const allowedHosts = [`127.0.0.1:${port}`, `localhost:${port}`];
|
|
10112
|
+
if (!request.host || !allowedHosts.includes(request.host))
|
|
10113
|
+
return false;
|
|
10114
|
+
if (request.method === "GET" || request.method === "HEAD")
|
|
10115
|
+
return true;
|
|
10116
|
+
if (request.studioHeader !== "1")
|
|
10117
|
+
return false;
|
|
10118
|
+
return !request.origin || allowedHosts.some((host) => request.origin === `http://${host}`);
|
|
10119
|
+
}
|
|
10120
|
+
function sendJson(res, status, body) {
|
|
10121
|
+
res.writeHead(status, { "Content-Type": "application/json" });
|
|
10122
|
+
res.end(JSON.stringify(body));
|
|
10123
|
+
}
|
|
10124
|
+
function errorMessage(error) {
|
|
10125
|
+
return error instanceof Error ? error.message : String(error);
|
|
10126
|
+
}
|
|
10127
|
+
var MAX_SQL_CHARS = 2e4;
|
|
10128
|
+
var MAX_NOTE_CHARS = 2e3;
|
|
10129
|
+
var MAX_BODY_BYTES = 256 * 1024;
|
|
10087
10130
|
function readJsonBody(req) {
|
|
10088
10131
|
return new Promise((resolve) => {
|
|
10089
10132
|
const chunks = [];
|
|
10090
|
-
|
|
10133
|
+
let size = 0;
|
|
10134
|
+
req.on("data", (c) => {
|
|
10135
|
+
size += c.length;
|
|
10136
|
+
if (size > MAX_BODY_BYTES) {
|
|
10137
|
+
resolve({});
|
|
10138
|
+
req.destroy();
|
|
10139
|
+
return;
|
|
10140
|
+
}
|
|
10141
|
+
chunks.push(c);
|
|
10142
|
+
});
|
|
10091
10143
|
req.on("end", () => {
|
|
10092
10144
|
try {
|
|
10093
10145
|
const text = Buffer.concat(chunks).toString("utf8").trim();
|
|
@@ -10139,11 +10191,8 @@ function buildFullCompanionPayload(store, datasetId, opts) {
|
|
|
10139
10191
|
}
|
|
10140
10192
|
async function startCompanionServer(options) {
|
|
10141
10193
|
const sseClients = /* @__PURE__ */ new Set();
|
|
10142
|
-
const
|
|
10143
|
-
const
|
|
10144
|
-
if (!payload)
|
|
10145
|
-
return;
|
|
10146
|
-
const frame = `event: update
|
|
10194
|
+
const send = (event, payload) => {
|
|
10195
|
+
const frame = `event: ${event}
|
|
10147
10196
|
data: ${JSON.stringify(payload)}
|
|
10148
10197
|
|
|
10149
10198
|
`;
|
|
@@ -10155,10 +10204,73 @@ data: ${JSON.stringify(payload)}
|
|
|
10155
10204
|
}
|
|
10156
10205
|
}
|
|
10157
10206
|
};
|
|
10207
|
+
const broadcastUpdate = () => {
|
|
10208
|
+
const payload = buildFullCompanionPayload(options.store, void 0, options);
|
|
10209
|
+
if (payload)
|
|
10210
|
+
send("update", payload);
|
|
10211
|
+
};
|
|
10212
|
+
const { studio } = options;
|
|
10213
|
+
studio?.subscribe(() => send("studio", studio.snapshot()));
|
|
10214
|
+
const handleStudioPost = async (pathname, body, res) => {
|
|
10215
|
+
if (!studio)
|
|
10216
|
+
return sendJson(res, 404, { error: "Studio is not available." });
|
|
10217
|
+
if (pathname === "/api/studio/query") {
|
|
10218
|
+
const sql = typeof body.sql === "string" ? body.sql.trim() : "";
|
|
10219
|
+
if (!sql || sql.length > MAX_SQL_CHARS)
|
|
10220
|
+
return sendJson(res, 400, { error: "Send one SELECT statement." });
|
|
10221
|
+
const name = typeof body.name === "string" && body.name.trim() ? body.name.trim().slice(0, 120) : void 0;
|
|
10222
|
+
try {
|
|
10223
|
+
const viewFromStepId = typeof body.fromStepId === "string" ? body.fromStepId : void 0;
|
|
10224
|
+
const { dataset, truncated } = await studio.runQuery({ sql, name, actor: "user", viewFromStepId });
|
|
10225
|
+
broadcastUpdate();
|
|
10226
|
+
return sendJson(res, 200, { datasetId: dataset.id, rows: dataset.rows.length, truncated });
|
|
10227
|
+
} catch (error) {
|
|
10228
|
+
return sendJson(res, 400, { error: errorMessage(error) });
|
|
10229
|
+
}
|
|
10230
|
+
}
|
|
10231
|
+
if (pathname === "/api/studio/note") {
|
|
10232
|
+
const text = typeof body.text === "string" ? body.text.trim() : "";
|
|
10233
|
+
if (!text || text.length > MAX_NOTE_CHARS)
|
|
10234
|
+
return sendJson(res, 400, { error: `Write a note of up to ${MAX_NOTE_CHARS.toLocaleString("en-US")} characters.` });
|
|
10235
|
+
const note = studio.addNote(text, typeof body.stepId === "string" ? body.stepId : void 0);
|
|
10236
|
+
return sendJson(res, 200, { note });
|
|
10237
|
+
}
|
|
10238
|
+
if (pathname === "/api/studio/note/delete") {
|
|
10239
|
+
return sendJson(res, 200, { removed: typeof body.id === "string" && studio.removeNote(body.id) });
|
|
10240
|
+
}
|
|
10241
|
+
if (pathname === "/api/studio/show") {
|
|
10242
|
+
try {
|
|
10243
|
+
const dataset = await studio.showStep(String(body.stepId ?? ""));
|
|
10244
|
+
broadcastUpdate();
|
|
10245
|
+
return sendJson(res, 200, { datasetId: dataset.id });
|
|
10246
|
+
} catch (error) {
|
|
10247
|
+
return sendJson(res, 400, { error: errorMessage(error) });
|
|
10248
|
+
}
|
|
10249
|
+
}
|
|
10250
|
+
if (pathname === "/api/studio/open") {
|
|
10251
|
+
try {
|
|
10252
|
+
const dataset = await studio.reopen(String(body.id ?? ""), { actor: "user" });
|
|
10253
|
+
broadcastUpdate();
|
|
10254
|
+
return sendJson(res, 200, { datasetId: dataset.id });
|
|
10255
|
+
} catch (error) {
|
|
10256
|
+
return sendJson(res, 400, { error: errorMessage(error) });
|
|
10257
|
+
}
|
|
10258
|
+
}
|
|
10259
|
+
return sendJson(res, 404, { error: "Not found" });
|
|
10260
|
+
};
|
|
10158
10261
|
const server = http.createServer(async (req, res) => {
|
|
10159
10262
|
const urlObj = new URL(req.url || "/", "http://127.0.0.1");
|
|
10160
10263
|
const pathname = urlObj.pathname;
|
|
10161
10264
|
res.setHeader("Cache-Control", "no-store");
|
|
10265
|
+
const port = server.address().port;
|
|
10266
|
+
const allowed = isAllowedRequest({
|
|
10267
|
+
method: req.method,
|
|
10268
|
+
host: req.headers.host,
|
|
10269
|
+
origin: req.headers.origin,
|
|
10270
|
+
studioHeader: req.headers[STUDIO_HEADER]
|
|
10271
|
+
}, port);
|
|
10272
|
+
if (!allowed)
|
|
10273
|
+
return sendJson(res, 403, { error: "Forbidden" });
|
|
10162
10274
|
if (req.method === "GET" && (pathname === "/" || pathname === "/index.html")) {
|
|
10163
10275
|
const html = await options.loadHtml();
|
|
10164
10276
|
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
@@ -10172,20 +10284,30 @@ data: ${JSON.stringify(payload)}
|
|
|
10172
10284
|
"Connection": "keep-alive"
|
|
10173
10285
|
});
|
|
10174
10286
|
res.write("retry: 2000\n\n");
|
|
10287
|
+
if (studio)
|
|
10288
|
+
res.write(`event: studio
|
|
10289
|
+
data: ${JSON.stringify(studio.snapshot())}
|
|
10290
|
+
|
|
10291
|
+
`);
|
|
10175
10292
|
sseClients.add(res);
|
|
10176
10293
|
req.on("close", () => sseClients.delete(res));
|
|
10177
10294
|
return;
|
|
10178
10295
|
}
|
|
10296
|
+
if (req.method === "GET" && pathname === "/api/studio") {
|
|
10297
|
+
return studio ? sendJson(res, 200, studio.snapshot()) : sendJson(res, 404, { error: "Studio is not available." });
|
|
10298
|
+
}
|
|
10299
|
+
if (req.method === "POST" && pathname.startsWith("/api/studio/")) {
|
|
10300
|
+
await handleStudioPost(pathname, await readJsonBody(req), res);
|
|
10301
|
+
return;
|
|
10302
|
+
}
|
|
10179
10303
|
if (req.method === "GET" && pathname === "/api/state") {
|
|
10180
10304
|
const dsId = urlObj.searchParams.get("datasetId") ?? void 0;
|
|
10181
10305
|
const payload = buildFullCompanionPayload(options.store, dsId, options);
|
|
10182
10306
|
if (!payload) {
|
|
10183
|
-
res
|
|
10184
|
-
res.end(JSON.stringify({ error: "Dataset not found" }));
|
|
10307
|
+
sendJson(res, 404, { error: "Dataset not found" });
|
|
10185
10308
|
return;
|
|
10186
10309
|
}
|
|
10187
|
-
res
|
|
10188
|
-
res.end(JSON.stringify(payload));
|
|
10310
|
+
sendJson(res, 200, payload);
|
|
10189
10311
|
return;
|
|
10190
10312
|
}
|
|
10191
10313
|
if (req.method === "POST" && pathname === "/api/model") {
|
|
@@ -10196,8 +10318,7 @@ data: ${JSON.stringify(payload)}
|
|
|
10196
10318
|
typeof body.customRatePerMillion === "number" ? body.customRatePerMillion : void 0
|
|
10197
10319
|
);
|
|
10198
10320
|
}
|
|
10199
|
-
res
|
|
10200
|
-
res.end(JSON.stringify({ session: options.store.getSessionSavings() }));
|
|
10321
|
+
sendJson(res, 200, { session: options.store.getSessionSavings() });
|
|
10201
10322
|
return;
|
|
10202
10323
|
}
|
|
10203
10324
|
if (req.method === "POST" && pathname === "/api/theme") {
|
|
@@ -10211,20 +10332,17 @@ data: ${JSON.stringify(payload)}
|
|
|
10211
10332
|
options.store.setVisualTheme(requested);
|
|
10212
10333
|
}
|
|
10213
10334
|
}
|
|
10214
|
-
res
|
|
10215
|
-
res.end(JSON.stringify({ chartTheme: isPro2 ? options.store.getVisualTheme() : "code" }));
|
|
10335
|
+
sendJson(res, 200, { chartTheme: isPro2 ? options.store.getVisualTheme() : "code" });
|
|
10216
10336
|
return;
|
|
10217
10337
|
}
|
|
10218
10338
|
if (req.method === "POST" && pathname === "/api/local-action") {
|
|
10219
10339
|
const body = await readJsonBody(req);
|
|
10220
10340
|
const dsId = typeof body.datasetId === "string" ? body.datasetId : void 0;
|
|
10221
10341
|
const result = options.store.recordLocalAction(dsId);
|
|
10222
|
-
res
|
|
10223
|
-
res.end(JSON.stringify(result));
|
|
10342
|
+
sendJson(res, 200, result);
|
|
10224
10343
|
return;
|
|
10225
10344
|
}
|
|
10226
|
-
res
|
|
10227
|
-
res.end(JSON.stringify({ error: "Not found" }));
|
|
10345
|
+
sendJson(res, 404, { error: "Not found" });
|
|
10228
10346
|
});
|
|
10229
10347
|
await new Promise((resolve, reject) => {
|
|
10230
10348
|
server.once("error", reject);
|
|
@@ -10244,6 +10362,7 @@ data: ${JSON.stringify(payload)}
|
|
|
10244
10362
|
url,
|
|
10245
10363
|
port: address.port,
|
|
10246
10364
|
broadcastUpdate,
|
|
10365
|
+
clientCount: () => sseClients.size,
|
|
10247
10366
|
close: () => {
|
|
10248
10367
|
if (closePromise)
|
|
10249
10368
|
return closePromise;
|
|
@@ -10501,7 +10620,7 @@ export default function (pi: any) {
|
|
|
10501
10620
|
|
|
10502
10621
|
if (typeof pi.registerCommand === "function") {
|
|
10503
10622
|
pi.registerCommand("tinypivot-theme", {
|
|
10504
|
-
description: "Switch TinyPivot visual theme (all 10 palettes, synced with
|
|
10623
|
+
description: "Switch TinyPivot visual theme (all 10 palettes, synced with Studio)",
|
|
10505
10624
|
handler: async (args: string, ctx: { ui?: { select?: (t: string, o: string[]) => Promise<string | undefined>; notify?: (m: string, t?: string) => void } }) => {
|
|
10506
10625
|
const active = readActiveThemeId();
|
|
10507
10626
|
let chosen = args?.trim().toLowerCase();
|
|
@@ -10546,11 +10665,11 @@ var RULE_HEADING = "## Charts & pivot tables (TinyPivot MCP)";
|
|
|
10546
10665
|
var RULE_USE = "Use the `tinypivot` MCP server for charts, pivot tables and data exploration instead of drawing them yourself.";
|
|
10547
10666
|
var TINYPIVOT_CLAUDE_RULE_BLOCK = `${RULE_START}
|
|
10548
10667
|
${RULE_HEADING}
|
|
10549
|
-
${RULE_USE} In a terminal, show its \`text\` card verbatim with the
|
|
10668
|
+
${RULE_USE} In a terminal, show its \`text\` card verbatim with the Studio link.
|
|
10550
10669
|
${RULE_END}`;
|
|
10551
10670
|
var TINYPIVOT_PI_RULE_BLOCK = `${RULE_START}
|
|
10552
10671
|
${RULE_HEADING}
|
|
10553
|
-
${RULE_USE} The TinyPivot pi extension already shows each card, so reply with the takeaways and the
|
|
10672
|
+
${RULE_USE} The TinyPivot pi extension already shows each card, so reply with the takeaways and the Studio link. \`/tinypivot-theme\` switches themes.
|
|
10554
10673
|
${RULE_END}`;
|
|
10555
10674
|
function upsertTinyPivotRuleBlock(existing, block = TINYPIVOT_CLAUDE_RULE_BLOCK) {
|
|
10556
10675
|
if (RULE_TEST_RE.test(existing)) {
|
|
@@ -11342,21 +11461,621 @@ async function executeReadOnlyPostgresQuery(config, sql) {
|
|
|
11342
11461
|
}
|
|
11343
11462
|
}
|
|
11344
11463
|
|
|
11464
|
+
// src/studio.ts
|
|
11465
|
+
import fs7 from "fs";
|
|
11466
|
+
import path7 from "path";
|
|
11467
|
+
|
|
11468
|
+
// src/duckdb.ts
|
|
11469
|
+
import { spawn } from "child_process";
|
|
11470
|
+
import fs5 from "fs";
|
|
11471
|
+
import { createRequire } from "module";
|
|
11472
|
+
import os4 from "os";
|
|
11473
|
+
import path5 from "path";
|
|
11474
|
+
var DUCKDB_PACKAGE = "@duckdb/node-api";
|
|
11475
|
+
var DUCKDB_VERSION = "2.0.1-r.1";
|
|
11476
|
+
var QUERY_ROW_LIMIT = 5e5;
|
|
11477
|
+
var INSTALL_TIMEOUT_MS = 5 * 60 * 1e3;
|
|
11478
|
+
function duckdbCacheDir() {
|
|
11479
|
+
const base = process.env.XDG_CACHE_HOME || path5.join(os4.homedir(), ".cache");
|
|
11480
|
+
return path5.join(base, "tinypivot", `duckdb-${DUCKDB_VERSION}`);
|
|
11481
|
+
}
|
|
11482
|
+
function requireFrom(dir) {
|
|
11483
|
+
try {
|
|
11484
|
+
return createRequire(path5.join(dir, "package.json"))(DUCKDB_PACKAGE);
|
|
11485
|
+
} catch {
|
|
11486
|
+
return void 0;
|
|
11487
|
+
}
|
|
11488
|
+
}
|
|
11489
|
+
function installInto(dir) {
|
|
11490
|
+
fs5.mkdirSync(dir, { recursive: true });
|
|
11491
|
+
fs5.writeFileSync(path5.join(dir, "package.json"), '{ "private": true }\n');
|
|
11492
|
+
const isWindows = process.platform === "win32";
|
|
11493
|
+
return new Promise((resolve, reject) => {
|
|
11494
|
+
const child = spawn(isWindows ? "npm.cmd" : "npm", [
|
|
11495
|
+
"install",
|
|
11496
|
+
"--prefix",
|
|
11497
|
+
dir,
|
|
11498
|
+
"--no-save",
|
|
11499
|
+
"--no-audit",
|
|
11500
|
+
"--no-fund",
|
|
11501
|
+
"--loglevel=error",
|
|
11502
|
+
`${DUCKDB_PACKAGE}@${DUCKDB_VERSION}`
|
|
11503
|
+
], { stdio: ["ignore", "ignore", "pipe"], shell: isWindows, timeout: INSTALL_TIMEOUT_MS });
|
|
11504
|
+
let stderr = "";
|
|
11505
|
+
child.stderr?.on("data", (chunk) => {
|
|
11506
|
+
stderr += String(chunk);
|
|
11507
|
+
});
|
|
11508
|
+
child.on("error", reject);
|
|
11509
|
+
child.on("exit", (code) => code === 0 ? resolve() : reject(new Error(`npm install failed (${code}): ${stderr.trim().slice(0, 300)}`)));
|
|
11510
|
+
});
|
|
11511
|
+
}
|
|
11512
|
+
var loading;
|
|
11513
|
+
function loadDuckDb() {
|
|
11514
|
+
loading ??= (async () => {
|
|
11515
|
+
try {
|
|
11516
|
+
const specifier = DUCKDB_PACKAGE;
|
|
11517
|
+
return await import(specifier);
|
|
11518
|
+
} catch {
|
|
11519
|
+
}
|
|
11520
|
+
const dir = duckdbCacheDir();
|
|
11521
|
+
const cached = requireFrom(dir);
|
|
11522
|
+
if (cached)
|
|
11523
|
+
return cached;
|
|
11524
|
+
console.error(`[tinypivot-mcp] Downloading DuckDB ${DUCKDB_VERSION} once into ${dir} for SQL queries...`);
|
|
11525
|
+
await installInto(dir);
|
|
11526
|
+
const installed = requireFrom(dir);
|
|
11527
|
+
if (!installed)
|
|
11528
|
+
throw new Error(`DuckDB installed into ${dir} but could not be loaded.`);
|
|
11529
|
+
return installed;
|
|
11530
|
+
})();
|
|
11531
|
+
loading.catch(() => {
|
|
11532
|
+
loading = void 0;
|
|
11533
|
+
});
|
|
11534
|
+
return loading;
|
|
11535
|
+
}
|
|
11536
|
+
function withinBudget(work, ms) {
|
|
11537
|
+
let timer;
|
|
11538
|
+
const budget = new Promise((resolve) => {
|
|
11539
|
+
timer = setTimeout(resolve, ms, "pending");
|
|
11540
|
+
});
|
|
11541
|
+
return Promise.race([work, budget]).finally(() => clearTimeout(timer));
|
|
11542
|
+
}
|
|
11543
|
+
function quoteLiteral(value2) {
|
|
11544
|
+
if (typeof value2 === "number" || typeof value2 === "boolean")
|
|
11545
|
+
return String(value2);
|
|
11546
|
+
return `'${value2.replace(/'/g, "''")}'`;
|
|
11547
|
+
}
|
|
11548
|
+
function quoteIdentifier(name) {
|
|
11549
|
+
return `"${name.replace(/"/g, '""')}"`;
|
|
11550
|
+
}
|
|
11551
|
+
var QueryRejected = class extends Error {
|
|
11552
|
+
};
|
|
11553
|
+
function toPlainValue(value2) {
|
|
11554
|
+
if (value2 === null || value2 === void 0)
|
|
11555
|
+
return null;
|
|
11556
|
+
if (typeof value2 === "bigint")
|
|
11557
|
+
return Number.isSafeInteger(Number(value2)) ? Number(value2) : value2.toString();
|
|
11558
|
+
if (value2 instanceof Date) {
|
|
11559
|
+
const iso = value2.toISOString();
|
|
11560
|
+
return iso.endsWith("T00:00:00.000Z") ? iso.slice(0, 10) : iso;
|
|
11561
|
+
}
|
|
11562
|
+
if (typeof value2 === "string" || typeof value2 === "number" || typeof value2 === "boolean")
|
|
11563
|
+
return value2;
|
|
11564
|
+
return JSON.stringify(value2, (_key, inner) => typeof inner === "bigint" ? inner.toString() : inner);
|
|
11565
|
+
}
|
|
11566
|
+
var DuckDbRunner = class {
|
|
11567
|
+
constructor(load = loadDuckDb) {
|
|
11568
|
+
this.load = load;
|
|
11569
|
+
}
|
|
11570
|
+
connection;
|
|
11571
|
+
duck;
|
|
11572
|
+
/** Starts loading DuckDB (downloading it if needed) without waiting. */
|
|
11573
|
+
prepare() {
|
|
11574
|
+
this.connection ??= (async () => {
|
|
11575
|
+
this.duck = await this.load();
|
|
11576
|
+
const instance = await this.duck.DuckDBInstance.create(":memory:", {
|
|
11577
|
+
autoinstall_known_extensions: "false",
|
|
11578
|
+
autoload_known_extensions: "false"
|
|
11579
|
+
});
|
|
11580
|
+
const connection = await instance.connect();
|
|
11581
|
+
await connection.run("SET lock_configuration = true");
|
|
11582
|
+
return connection;
|
|
11583
|
+
})();
|
|
11584
|
+
this.connection.catch(() => {
|
|
11585
|
+
this.connection = void 0;
|
|
11586
|
+
});
|
|
11587
|
+
return this.connection;
|
|
11588
|
+
}
|
|
11589
|
+
async run(sql, views, maxRows = QUERY_ROW_LIMIT) {
|
|
11590
|
+
const connection = await this.prepare();
|
|
11591
|
+
const statementTypes = this.duck.StatementType;
|
|
11592
|
+
for (const view of views)
|
|
11593
|
+
await connection.run(`CREATE OR REPLACE TEMP VIEW ${quoteIdentifier(view.name)} AS SELECT * FROM ${view.from}`);
|
|
11594
|
+
const query = sql.trim().replace(/;+\s*$/, "");
|
|
11595
|
+
const extracted = await connection.extractStatements(query);
|
|
11596
|
+
if (extracted.count !== 1)
|
|
11597
|
+
throw new QueryRejected("Send exactly one SELECT statement.");
|
|
11598
|
+
const prepared = await extracted.prepare(0);
|
|
11599
|
+
if (prepared.statementType !== statementTypes.SELECT)
|
|
11600
|
+
throw new QueryRejected("Only SELECT queries can run here: TinyPivot reads data, it never changes it.");
|
|
11601
|
+
const reader = await connection.runAndReadAll(`SELECT * FROM (${query}) AS tinypivot_query LIMIT ${maxRows + 1}`);
|
|
11602
|
+
const rows = reader.getRowObjectsJS().map(
|
|
11603
|
+
(row) => Object.fromEntries(Object.entries(row).map(([key, value2]) => [key, toPlainValue(value2)]))
|
|
11604
|
+
);
|
|
11605
|
+
return { columns: reader.columnNames(), rows: rows.slice(0, maxRows), truncated: rows.length > maxRows };
|
|
11606
|
+
}
|
|
11607
|
+
};
|
|
11608
|
+
|
|
11609
|
+
// src/history.ts
|
|
11610
|
+
import fs6 from "fs";
|
|
11611
|
+
import os5 from "os";
|
|
11612
|
+
import path6 from "path";
|
|
11613
|
+
import zlib from "zlib";
|
|
11614
|
+
var HISTORY_MAX_SAVED_ROWS = 2e5;
|
|
11615
|
+
var DEFAULT_RETENTION_DAYS = 30;
|
|
11616
|
+
function defaultHistoryDir() {
|
|
11617
|
+
const base = process.env.XDG_DATA_HOME || path6.join(os5.homedir(), ".local", "share");
|
|
11618
|
+
return path6.join(base, "tinypivot", "history");
|
|
11619
|
+
}
|
|
11620
|
+
function timestampId(date) {
|
|
11621
|
+
return date.toISOString().replace(/[-:]/g, "").replace("T", "-").replace(".", "-").replace("Z", "");
|
|
11622
|
+
}
|
|
11623
|
+
function slug(text) {
|
|
11624
|
+
return text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "data";
|
|
11625
|
+
}
|
|
11626
|
+
var HistoryStore = class {
|
|
11627
|
+
dir;
|
|
11628
|
+
enabled;
|
|
11629
|
+
retentionDays;
|
|
11630
|
+
constructor(options = {}) {
|
|
11631
|
+
this.dir = options.dir ?? defaultHistoryDir();
|
|
11632
|
+
this.enabled = options.enabled ?? process.env.TINYPIVOT_HISTORY !== "0";
|
|
11633
|
+
const envDays = Number(process.env.TINYPIVOT_HISTORY_DAYS);
|
|
11634
|
+
this.retentionDays = options.retentionDays ?? (Number.isFinite(envDays) && envDays > 0 ? envDays : DEFAULT_RETENTION_DAYS);
|
|
11635
|
+
}
|
|
11636
|
+
/** Saves a pull. Returns the entry, or null when history is off or the write failed. */
|
|
11637
|
+
record(dataset, input, now = /* @__PURE__ */ new Date()) {
|
|
11638
|
+
if (!this.enabled)
|
|
11639
|
+
return null;
|
|
11640
|
+
try {
|
|
11641
|
+
fs6.mkdirSync(this.dir, { recursive: true });
|
|
11642
|
+
const id = `${timestampId(now)}-${slug(dataset.name)}`;
|
|
11643
|
+
const saveRows = input.kind !== "file" && dataset.rows.length <= HISTORY_MAX_SAVED_ROWS;
|
|
11644
|
+
const entry = {
|
|
11645
|
+
id,
|
|
11646
|
+
name: dataset.name,
|
|
11647
|
+
kind: input.kind,
|
|
11648
|
+
createdAt: now.toISOString(),
|
|
11649
|
+
rows: dataset.rows.length,
|
|
11650
|
+
columns: dataset.columns.map((column) => column.name),
|
|
11651
|
+
source: input.source,
|
|
11652
|
+
...input.where?.length ? { where: input.where } : {},
|
|
11653
|
+
...saveRows ? { rowsFile: `${id}.jsonl.gz` } : {},
|
|
11654
|
+
...dataset.chartConfig ? { chartConfig: dataset.chartConfig } : {},
|
|
11655
|
+
...dataset.pivotConfig ? { pivotConfig: dataset.pivotConfig } : {}
|
|
11656
|
+
};
|
|
11657
|
+
if (entry.rowsFile) {
|
|
11658
|
+
const lines = dataset.rows.map((row) => JSON.stringify(row)).join("\n");
|
|
11659
|
+
fs6.writeFileSync(path6.join(this.dir, entry.rowsFile), zlib.gzipSync(lines));
|
|
11660
|
+
}
|
|
11661
|
+
fs6.writeFileSync(path6.join(this.dir, `${id}.json`), `${JSON.stringify(entry, null, 2)}
|
|
11662
|
+
`);
|
|
11663
|
+
return entry;
|
|
11664
|
+
} catch (error) {
|
|
11665
|
+
console.error(`[tinypivot-mcp] Could not save to history: ${error instanceof Error ? error.message : String(error)}`);
|
|
11666
|
+
return null;
|
|
11667
|
+
}
|
|
11668
|
+
}
|
|
11669
|
+
/** Newest first. */
|
|
11670
|
+
list(limit = Number.POSITIVE_INFINITY) {
|
|
11671
|
+
if (!fs6.existsSync(this.dir))
|
|
11672
|
+
return [];
|
|
11673
|
+
return fs6.readdirSync(this.dir).filter((name) => name.endsWith(".json")).sort().reverse().slice(0, limit).flatMap((name) => {
|
|
11674
|
+
try {
|
|
11675
|
+
return [JSON.parse(fs6.readFileSync(path6.join(this.dir, name), "utf8"))];
|
|
11676
|
+
} catch {
|
|
11677
|
+
return [];
|
|
11678
|
+
}
|
|
11679
|
+
});
|
|
11680
|
+
}
|
|
11681
|
+
get(id) {
|
|
11682
|
+
if (!/^[\w-]+$/.test(id))
|
|
11683
|
+
return void 0;
|
|
11684
|
+
const file = path6.join(this.dir, `${id}.json`);
|
|
11685
|
+
return fs6.existsSync(file) ? JSON.parse(fs6.readFileSync(file, "utf8")) : void 0;
|
|
11686
|
+
}
|
|
11687
|
+
/** Full path of an entry's saved rows, for reading back or querying with SQL. */
|
|
11688
|
+
rowsPath(entry) {
|
|
11689
|
+
return entry.rowsFile ? path6.join(this.dir, entry.rowsFile) : void 0;
|
|
11690
|
+
}
|
|
11691
|
+
readRows(entry) {
|
|
11692
|
+
const file = this.rowsPath(entry);
|
|
11693
|
+
if (!file)
|
|
11694
|
+
throw new Error(`History entry ${entry.id} has no saved rows.`);
|
|
11695
|
+
return zlib.gunzipSync(fs6.readFileSync(file)).toString("utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line));
|
|
11696
|
+
}
|
|
11697
|
+
/** Deletes entries older than the retention window. Returns how many were removed. */
|
|
11698
|
+
prune(now = /* @__PURE__ */ new Date()) {
|
|
11699
|
+
if (!fs6.existsSync(this.dir))
|
|
11700
|
+
return 0;
|
|
11701
|
+
const cutoff = now.getTime() - this.retentionDays * 24 * 60 * 60 * 1e3;
|
|
11702
|
+
let removed = 0;
|
|
11703
|
+
for (const entry of this.list()) {
|
|
11704
|
+
if (new Date(entry.createdAt).getTime() >= cutoff)
|
|
11705
|
+
continue;
|
|
11706
|
+
const rows = this.rowsPath(entry);
|
|
11707
|
+
if (rows)
|
|
11708
|
+
fs6.rmSync(rows, { force: true });
|
|
11709
|
+
fs6.rmSync(path6.join(this.dir, `${entry.id}.json`), { force: true });
|
|
11710
|
+
removed++;
|
|
11711
|
+
}
|
|
11712
|
+
return removed;
|
|
11713
|
+
}
|
|
11714
|
+
};
|
|
11715
|
+
function formatHistoryList(entries) {
|
|
11716
|
+
if (entries.length === 0)
|
|
11717
|
+
return "No saved pulls yet.";
|
|
11718
|
+
const lines = entries.map((entry) => {
|
|
11719
|
+
const when = entry.createdAt.slice(0, 16).replace("T", " ");
|
|
11720
|
+
return `\`${entry.id}\` ${when} \xB7 ${entry.name} \xB7 ${entry.rows.toLocaleString("en-US")} rows \xB7 ${entry.kind}`;
|
|
11721
|
+
});
|
|
11722
|
+
return [`Saved pulls (newest first). Reopen one with history({ open: id }):`, ...lines].join("\n");
|
|
11723
|
+
}
|
|
11724
|
+
|
|
11725
|
+
// src/studio.ts
|
|
11726
|
+
var STEPS_IN_MEMORY = 300;
|
|
11727
|
+
var HISTORY_IN_SNAPSHOT = 50;
|
|
11728
|
+
var TRACE_FILE_MAX_BYTES = 5 * 1024 * 1024;
|
|
11729
|
+
function describeView(dataset) {
|
|
11730
|
+
const pivot = dataset.pivotConfig;
|
|
11731
|
+
if (dataset.viewMode === "pivot" && pivot?.valueFields?.length) {
|
|
11732
|
+
const values = pivot.valueFields.map((v) => `${v.aggregation}(${v.field})`).join(", ");
|
|
11733
|
+
const rows = pivot.rowFields?.length ? ` \xB7 rows ${pivot.rowFields.join(", ")}` : "";
|
|
11734
|
+
const columns = pivot.columnFields?.length ? ` \xB7 columns ${pivot.columnFields.join(", ")}` : "";
|
|
11735
|
+
return `pivot: ${values}${rows}${columns}`;
|
|
11736
|
+
}
|
|
11737
|
+
const chart = dataset.chartConfig;
|
|
11738
|
+
if (dataset.viewMode === "chart" && chart?.xAxis && chart.yAxis) {
|
|
11739
|
+
const series = chart.seriesField ? `, split by ${chart.seriesField.field}` : "";
|
|
11740
|
+
return `${chart.type ?? "bar"} chart: ${chart.yAxis.aggregation ?? "sum"}(${chart.yAxis.field}) by ${chart.xAxis.field}${series}`;
|
|
11741
|
+
}
|
|
11742
|
+
return "table";
|
|
11743
|
+
}
|
|
11744
|
+
function whereSql(where) {
|
|
11745
|
+
return where.map((filter) => `CAST(${quoteIdentifier(filter.field)} AS VARCHAR) IN (${filter.equals.map((value2) => quoteLiteral(String(value2))).join(", ")})`).join(" AND ");
|
|
11746
|
+
}
|
|
11747
|
+
function fileStepSql(file, where) {
|
|
11748
|
+
return `SELECT *
|
|
11749
|
+
FROM ${quoteLiteral(file)}${where?.length ? `
|
|
11750
|
+
WHERE ${whereSql(where)}` : ""}`;
|
|
11751
|
+
}
|
|
11752
|
+
function viewFields(dataset) {
|
|
11753
|
+
const chart = dataset.chartConfig;
|
|
11754
|
+
const pivot = dataset.pivotConfig;
|
|
11755
|
+
return [
|
|
11756
|
+
chart?.xAxis?.field,
|
|
11757
|
+
chart?.yAxis?.field,
|
|
11758
|
+
chart?.seriesField?.field,
|
|
11759
|
+
...pivot?.rowFields ?? [],
|
|
11760
|
+
...pivot?.columnFields ?? [],
|
|
11761
|
+
...(pivot?.valueFields ?? []).map((value2) => value2.field)
|
|
11762
|
+
].filter((field) => Boolean(field));
|
|
11763
|
+
}
|
|
11764
|
+
function historyTableExpression(entry, rowsPath) {
|
|
11765
|
+
if (entry.kind === "file") {
|
|
11766
|
+
const file = quoteLiteral(entry.source);
|
|
11767
|
+
return entry.where?.length ? `(SELECT * FROM ${file} WHERE ${whereSql(entry.where)})` : file;
|
|
11768
|
+
}
|
|
11769
|
+
return rowsPath ? `read_json_auto(${quoteLiteral(rowsPath)})` : void 0;
|
|
11770
|
+
}
|
|
11771
|
+
var sequence = 0;
|
|
11772
|
+
function nextId(prefix) {
|
|
11773
|
+
sequence += 1;
|
|
11774
|
+
return `${prefix}-${Date.now().toString(36)}-${sequence.toString(36)}`;
|
|
11775
|
+
}
|
|
11776
|
+
var Studio = class {
|
|
11777
|
+
constructor(store, options = {}) {
|
|
11778
|
+
this.store = store;
|
|
11779
|
+
this.history = options.history ?? new HistoryStore();
|
|
11780
|
+
this.duck = options.duck ?? new DuckDbRunner();
|
|
11781
|
+
this.steps = this.readTraceFile();
|
|
11782
|
+
}
|
|
11783
|
+
history;
|
|
11784
|
+
duck;
|
|
11785
|
+
steps = [];
|
|
11786
|
+
notes = [];
|
|
11787
|
+
pullsByDataset = /* @__PURE__ */ new Map();
|
|
11788
|
+
listeners = /* @__PURE__ */ new Set();
|
|
11789
|
+
changeQueued = false;
|
|
11790
|
+
/** Calls `listener` (once per tick at most) whenever the trace or the notes change. */
|
|
11791
|
+
subscribe(listener) {
|
|
11792
|
+
this.listeners.add(listener);
|
|
11793
|
+
return () => this.listeners.delete(listener);
|
|
11794
|
+
}
|
|
11795
|
+
changed() {
|
|
11796
|
+
if (this.changeQueued)
|
|
11797
|
+
return;
|
|
11798
|
+
this.changeQueued = true;
|
|
11799
|
+
queueMicrotask(() => {
|
|
11800
|
+
this.changeQueued = false;
|
|
11801
|
+
for (const listener of this.listeners)
|
|
11802
|
+
listener();
|
|
11803
|
+
});
|
|
11804
|
+
}
|
|
11805
|
+
snapshot(sessionKey = DEFAULT_SESSION_KEY) {
|
|
11806
|
+
return {
|
|
11807
|
+
steps: this.steps.map((step) => ({
|
|
11808
|
+
...step,
|
|
11809
|
+
editableSql: step.sql ?? (step.file ? fileStepSql(step.file, step.where) : void 0)
|
|
11810
|
+
})),
|
|
11811
|
+
notes: this.pendingNotes(),
|
|
11812
|
+
history: this.history.enabled ? this.history.list(HISTORY_IN_SNAPSHOT) : [],
|
|
11813
|
+
historyEnabled: this.history.enabled,
|
|
11814
|
+
loadedIds: this.store.listMetadata(sessionKey).map((meta) => meta.id)
|
|
11815
|
+
};
|
|
11816
|
+
}
|
|
11817
|
+
get traceFile() {
|
|
11818
|
+
return path7.join(this.history.dir, "trace.jsonl");
|
|
11819
|
+
}
|
|
11820
|
+
readTraceFile() {
|
|
11821
|
+
if (!this.history.enabled || !fs7.existsSync(this.traceFile))
|
|
11822
|
+
return [];
|
|
11823
|
+
return fs7.readFileSync(this.traceFile, "utf8").split("\n").filter(Boolean).slice(-STEPS_IN_MEMORY).flatMap((line) => {
|
|
11824
|
+
try {
|
|
11825
|
+
return [JSON.parse(line)];
|
|
11826
|
+
} catch {
|
|
11827
|
+
return [];
|
|
11828
|
+
}
|
|
11829
|
+
});
|
|
11830
|
+
}
|
|
11831
|
+
appendToTraceFile(step) {
|
|
11832
|
+
if (!this.history.enabled)
|
|
11833
|
+
return;
|
|
11834
|
+
try {
|
|
11835
|
+
fs7.mkdirSync(this.history.dir, { recursive: true });
|
|
11836
|
+
fs7.appendFileSync(this.traceFile, `${JSON.stringify(step)}
|
|
11837
|
+
`);
|
|
11838
|
+
if (fs7.statSync(this.traceFile).size > TRACE_FILE_MAX_BYTES)
|
|
11839
|
+
fs7.writeFileSync(this.traceFile, `${this.steps.map((s) => JSON.stringify(s)).join("\n")}
|
|
11840
|
+
`);
|
|
11841
|
+
} catch (error) {
|
|
11842
|
+
console.error(`[tinypivot-mcp] Could not save the Studio trace: ${error instanceof Error ? error.message : String(error)}`);
|
|
11843
|
+
}
|
|
11844
|
+
}
|
|
11845
|
+
/** Adds a step to the trace and returns it. */
|
|
11846
|
+
record(step) {
|
|
11847
|
+
const full = { id: nextId("step"), at: (/* @__PURE__ */ new Date()).toISOString(), ...step };
|
|
11848
|
+
this.steps.push(full);
|
|
11849
|
+
if (this.steps.length > STEPS_IN_MEMORY)
|
|
11850
|
+
this.steps = this.steps.slice(-STEPS_IN_MEMORY);
|
|
11851
|
+
this.appendToTraceFile(full);
|
|
11852
|
+
this.changed();
|
|
11853
|
+
return full;
|
|
11854
|
+
}
|
|
11855
|
+
/** Records a step about a dataset, filling in its name, size, view and saved pull. */
|
|
11856
|
+
recordDatasetStep(dataset, step) {
|
|
11857
|
+
return this.record({
|
|
11858
|
+
...step,
|
|
11859
|
+
datasetId: dataset.id,
|
|
11860
|
+
datasetName: dataset.name,
|
|
11861
|
+
rows: dataset.rows.length,
|
|
11862
|
+
view: describeView(dataset),
|
|
11863
|
+
viewMode: dataset.viewMode,
|
|
11864
|
+
...dataset.chartConfig ? { chartConfig: structuredClone(dataset.chartConfig) } : {},
|
|
11865
|
+
...dataset.pivotConfig ? { pivotConfig: structuredClone(dataset.pivotConfig) } : {},
|
|
11866
|
+
historyId: this.pullsByDataset.get(dataset.id)?.id
|
|
11867
|
+
});
|
|
11868
|
+
}
|
|
11869
|
+
/**
|
|
11870
|
+
* Shows a step's dataset as it was right after the step, reopening it from history when it is
|
|
11871
|
+
* no longer loaded. Looking is not a step, so nothing is recorded.
|
|
11872
|
+
*/
|
|
11873
|
+
async showStep(stepId, sessionKey = DEFAULT_SESSION_KEY) {
|
|
11874
|
+
const step = this.steps.find((s) => s.id === stepId);
|
|
11875
|
+
if (!step?.datasetId)
|
|
11876
|
+
throw new Error("That step has no data to show.");
|
|
11877
|
+
let dataset = this.store.get(step.datasetId, sessionKey);
|
|
11878
|
+
if (!dataset) {
|
|
11879
|
+
if (!step.historyId)
|
|
11880
|
+
throw new Error("That data is no longer loaded and was not saved to history.");
|
|
11881
|
+
dataset = await this.reopen(step.historyId, { actor: "user", sessionKey, record: false });
|
|
11882
|
+
}
|
|
11883
|
+
return this.store.updateView(dataset.id, {
|
|
11884
|
+
...step.viewMode ? { viewMode: step.viewMode } : {},
|
|
11885
|
+
...step.chartConfig ? { chartConfig: { ...step.chartConfig, seriesField: step.chartConfig.seriesField } } : {},
|
|
11886
|
+
...step.pivotConfig ? { pivotConfig: step.pivotConfig } : {}
|
|
11887
|
+
}, sessionKey) ?? dataset;
|
|
11888
|
+
}
|
|
11889
|
+
recentSteps(limit = STEPS_IN_MEMORY) {
|
|
11890
|
+
return this.steps.slice(-limit);
|
|
11891
|
+
}
|
|
11892
|
+
/** Saves a pull to history and remembers which entry backs the dataset. */
|
|
11893
|
+
remember(dataset, input) {
|
|
11894
|
+
const entry = this.history.record(dataset, input);
|
|
11895
|
+
if (entry)
|
|
11896
|
+
this.pullsByDataset.set(dataset.id, entry);
|
|
11897
|
+
return entry;
|
|
11898
|
+
}
|
|
11899
|
+
/** Loaded datasets as tables SQL can read, named by dataset id. */
|
|
11900
|
+
queryViews(sessionKey = DEFAULT_SESSION_KEY) {
|
|
11901
|
+
return this.store.listMetadata(sessionKey).flatMap((meta) => {
|
|
11902
|
+
const entry = this.pullsByDataset.get(meta.id);
|
|
11903
|
+
const from = entry && historyTableExpression(entry, this.history.rowsPath(entry));
|
|
11904
|
+
return from ? [{ name: meta.id, from }] : [];
|
|
11905
|
+
});
|
|
11906
|
+
}
|
|
11907
|
+
/** Runs read-only SQL, loads the result as a dataset, saves it and records the step. */
|
|
11908
|
+
async runQuery(input) {
|
|
11909
|
+
const sessionKey = input.sessionKey ?? DEFAULT_SESSION_KEY;
|
|
11910
|
+
const result = await this.duck.run(input.sql, this.queryViews(sessionKey));
|
|
11911
|
+
const dataset = this.store.register({
|
|
11912
|
+
name: input.name ?? (input.actor === "user" ? "Your query" : "SQL query"),
|
|
11913
|
+
source: input.sql,
|
|
11914
|
+
ingestionMode: "direct",
|
|
11915
|
+
rows: result.rows,
|
|
11916
|
+
viewMode: input.viewMode,
|
|
11917
|
+
pivotConfig: input.pivotConfig,
|
|
11918
|
+
chartConfig: input.chartConfig,
|
|
11919
|
+
sessionKey,
|
|
11920
|
+
keepExisting: input.keepExisting ?? true
|
|
11921
|
+
});
|
|
11922
|
+
const shown = this.keepViewOf(input.viewFromStepId, dataset, sessionKey) ?? dataset;
|
|
11923
|
+
this.remember(shown, { kind: "query", source: input.sql });
|
|
11924
|
+
this.recordDatasetStep(shown, { actor: input.actor, tool: "query", why: input.why, sql: input.sql });
|
|
11925
|
+
return { dataset: shown, truncated: result.truncated };
|
|
11926
|
+
}
|
|
11927
|
+
/** Gives `dataset` the view of the step's dataset when every field that view uses is in the result. */
|
|
11928
|
+
keepViewOf(stepId, dataset, sessionKey) {
|
|
11929
|
+
const step = stepId ? this.steps.find((s) => s.id === stepId) : void 0;
|
|
11930
|
+
const source = step?.datasetId ? this.store.get(step.datasetId, sessionKey) : void 0;
|
|
11931
|
+
if (!source)
|
|
11932
|
+
return void 0;
|
|
11933
|
+
const columns = new Set(dataset.columns.map((column) => column.name));
|
|
11934
|
+
const fields = viewFields(source);
|
|
11935
|
+
if (fields.length === 0 || !fields.every((field) => columns.has(field)))
|
|
11936
|
+
return void 0;
|
|
11937
|
+
return this.store.updateView(dataset.id, {
|
|
11938
|
+
viewMode: source.viewMode,
|
|
11939
|
+
// Set the series explicitly, so one picked for the new result does not survive the merge.
|
|
11940
|
+
...source.chartConfig ? { chartConfig: { ...source.chartConfig, seriesField: source.chartConfig.seriesField } } : {},
|
|
11941
|
+
...source.pivotConfig ? { pivotConfig: source.pivotConfig } : {}
|
|
11942
|
+
}, sessionKey);
|
|
11943
|
+
}
|
|
11944
|
+
/** Reopens a saved pull without re-querying, and records the step. */
|
|
11945
|
+
async reopen(id, options) {
|
|
11946
|
+
const entry = this.history.get(id);
|
|
11947
|
+
if (!entry)
|
|
11948
|
+
throw new Error(`No saved pull "${id}".`);
|
|
11949
|
+
const sessionKey = options.sessionKey ?? DEFAULT_SESSION_KEY;
|
|
11950
|
+
const dataset = entry.kind === "file" ? await this.store.loadFromFile(entry.source, entry.name, { sessionKey, keepExisting: true, where: entry.where }) : this.store.register({ name: entry.name, source: entry.source, ingestionMode: "direct", rows: this.history.readRows(entry), sessionKey, keepExisting: true });
|
|
11951
|
+
this.store.updateView(dataset.id, {
|
|
11952
|
+
...entry.chartConfig ? { chartConfig: entry.chartConfig } : {},
|
|
11953
|
+
...entry.pivotConfig ? { pivotConfig: entry.pivotConfig } : {}
|
|
11954
|
+
}, sessionKey);
|
|
11955
|
+
this.pullsByDataset.set(dataset.id, entry);
|
|
11956
|
+
if (options.record === false)
|
|
11957
|
+
return dataset;
|
|
11958
|
+
this.recordDatasetStep(dataset, {
|
|
11959
|
+
actor: options.actor,
|
|
11960
|
+
tool: "history",
|
|
11961
|
+
why: options.why,
|
|
11962
|
+
...entry.kind === "file" ? { file: entry.source, where: entry.where } : { sql: entry.kind === "data" ? void 0 : entry.source }
|
|
11963
|
+
});
|
|
11964
|
+
return dataset;
|
|
11965
|
+
}
|
|
11966
|
+
/** Queues a note for the agent; it is delivered with the next TinyPivot reply. */
|
|
11967
|
+
addNote(text, stepId) {
|
|
11968
|
+
const note = { id: nextId("note"), at: (/* @__PURE__ */ new Date()).toISOString(), text: text.trim(), ...stepId ? { stepId } : {} };
|
|
11969
|
+
this.notes.push(note);
|
|
11970
|
+
this.record({ actor: "user", tool: "note", why: note.text });
|
|
11971
|
+
return note;
|
|
11972
|
+
}
|
|
11973
|
+
/** Drops a queued note the user no longer wants sent. */
|
|
11974
|
+
removeNote(id) {
|
|
11975
|
+
const before = this.notes.length;
|
|
11976
|
+
this.notes = this.notes.filter((note) => note.id !== id);
|
|
11977
|
+
if (this.notes.length !== before)
|
|
11978
|
+
this.changed();
|
|
11979
|
+
return this.notes.length !== before;
|
|
11980
|
+
}
|
|
11981
|
+
pendingNotes() {
|
|
11982
|
+
return [...this.notes];
|
|
11983
|
+
}
|
|
11984
|
+
/** The queued notes as text for the agent, emptying the queue. Empty when there are none. */
|
|
11985
|
+
takeNotes() {
|
|
11986
|
+
if (this.notes.length === 0)
|
|
11987
|
+
return "";
|
|
11988
|
+
const lines = this.notes.map((note) => {
|
|
11989
|
+
const step = note.stepId ? this.steps.find((s) => s.id === note.stepId) : void 0;
|
|
11990
|
+
const about = step ? ` (about "${step.why ?? step.view ?? step.tool}"${step.sql ? `, SQL: ${step.sql.replace(/\s+/g, " ")}` : ""})` : "";
|
|
11991
|
+
return `- ${note.text}${about}`;
|
|
11992
|
+
});
|
|
11993
|
+
this.notes = [];
|
|
11994
|
+
this.changed();
|
|
11995
|
+
return `
|
|
11996
|
+
|
|
11997
|
+
**Notes from the user in TinyPivot Studio** (act on these):
|
|
11998
|
+
${lines.join("\n")}`;
|
|
11999
|
+
}
|
|
12000
|
+
};
|
|
12001
|
+
|
|
11345
12002
|
// src/server.ts
|
|
11346
12003
|
import fsSync3 from "fs";
|
|
11347
|
-
import
|
|
11348
|
-
import
|
|
12004
|
+
import fs8 from "fs/promises";
|
|
12005
|
+
import path9 from "path";
|
|
11349
12006
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
11350
12007
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
11351
12008
|
import { z } from "zod";
|
|
11352
12009
|
|
|
12010
|
+
// src/profile.ts
|
|
12011
|
+
var TOP_VALUES = 3;
|
|
12012
|
+
function compactNumber(value2) {
|
|
12013
|
+
return Number.isInteger(value2) ? value2.toLocaleString("en-US") : value2.toLocaleString("en-US", { maximumFractionDigits: 2 });
|
|
12014
|
+
}
|
|
12015
|
+
function percent(part, whole) {
|
|
12016
|
+
if (whole === 0)
|
|
12017
|
+
return "0%";
|
|
12018
|
+
const share = part / whole * 100;
|
|
12019
|
+
return share > 0 && share < 1 ? "<1%" : `${Math.round(share)}%`;
|
|
12020
|
+
}
|
|
12021
|
+
function numberRange(values) {
|
|
12022
|
+
const numbers = values.map(Number).filter(Number.isFinite);
|
|
12023
|
+
if (numbers.length === 0)
|
|
12024
|
+
return "";
|
|
12025
|
+
let min = numbers[0];
|
|
12026
|
+
let max = numbers[0];
|
|
12027
|
+
let sum = 0;
|
|
12028
|
+
for (const value2 of numbers) {
|
|
12029
|
+
min = Math.min(min, value2);
|
|
12030
|
+
max = Math.max(max, value2);
|
|
12031
|
+
sum += value2;
|
|
12032
|
+
}
|
|
12033
|
+
return `${compactNumber(min)} to ${compactNumber(max)}, mean ${compactNumber(sum / numbers.length)}`;
|
|
12034
|
+
}
|
|
12035
|
+
function dateRange(values) {
|
|
12036
|
+
const texts = values.map(String).sort();
|
|
12037
|
+
return texts.length ? `${texts[0]} to ${texts[texts.length - 1]}` : "";
|
|
12038
|
+
}
|
|
12039
|
+
function topValues(values, total) {
|
|
12040
|
+
const counts = /* @__PURE__ */ new Map();
|
|
12041
|
+
for (const value2 of values)
|
|
12042
|
+
counts.set(String(value2), (counts.get(String(value2)) ?? 0) + 1);
|
|
12043
|
+
const top = [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, TOP_VALUES);
|
|
12044
|
+
const listed = top.map(([value2, count]) => `${value2} ${percent(count, total)}`).join(", ");
|
|
12045
|
+
return counts.size > TOP_VALUES ? `${counts.size.toLocaleString("en-US")} values, top: ${listed}` : listed;
|
|
12046
|
+
}
|
|
12047
|
+
function describe({ column, present, values }, total) {
|
|
12048
|
+
const missing = total - present;
|
|
12049
|
+
const parts = [`\`${column.name}\` ${column.type}`];
|
|
12050
|
+
if (missing > 0)
|
|
12051
|
+
parts.push(`${percent(missing, total)} empty`);
|
|
12052
|
+
if (column.type === "number")
|
|
12053
|
+
parts.push(numberRange(values));
|
|
12054
|
+
else if (column.type === "date")
|
|
12055
|
+
parts.push(dateRange(values));
|
|
12056
|
+
else
|
|
12057
|
+
parts.push(topValues(values, present));
|
|
12058
|
+
return parts.filter(Boolean).join(" \xB7 ");
|
|
12059
|
+
}
|
|
12060
|
+
function formatProfile(dataset) {
|
|
12061
|
+
const total = dataset.rows.length;
|
|
12062
|
+
const profiles = dataset.columns.map((column) => {
|
|
12063
|
+
const values = dataset.rows.map((row) => row[column.name]).filter((value2) => value2 !== null && value2 !== void 0 && value2 !== "");
|
|
12064
|
+
return { column, present: values.length, values };
|
|
12065
|
+
});
|
|
12066
|
+
return [
|
|
12067
|
+
`Profile of **${dataset.name}** (\`${dataset.id}\`): ${total.toLocaleString("en-US")} rows.`,
|
|
12068
|
+
...profiles.map((profile) => describe(profile, total))
|
|
12069
|
+
].join("\n");
|
|
12070
|
+
}
|
|
12071
|
+
|
|
11353
12072
|
// src/telemetry.ts
|
|
11354
12073
|
import crypto from "crypto";
|
|
11355
12074
|
import fsSync2 from "fs";
|
|
11356
|
-
import
|
|
11357
|
-
import
|
|
12075
|
+
import os6 from "os";
|
|
12076
|
+
import path8 from "path";
|
|
11358
12077
|
var DEFAULT_TELEMETRY_URL = "https://tiny-pivot.com/api/telemetry";
|
|
11359
|
-
var PACKAGE_VERSION = "0.
|
|
12078
|
+
var PACKAGE_VERSION = "0.4.0";
|
|
11360
12079
|
function isTelemetryEnabled() {
|
|
11361
12080
|
if (process.env.TINYPIVOT_TELEMETRY === "0" || process.env.TINYPIVOT_TELEMETRY === "false")
|
|
11362
12081
|
return false;
|
|
@@ -11376,8 +12095,8 @@ function bucketRowCount(rows) {
|
|
|
11376
12095
|
return "10k+";
|
|
11377
12096
|
}
|
|
11378
12097
|
function getPreferencesPath2() {
|
|
11379
|
-
const base = process.env.XDG_CONFIG_HOME?.trim() ||
|
|
11380
|
-
return
|
|
12098
|
+
const base = process.env.XDG_CONFIG_HOME?.trim() || path8.join(os6.homedir(), ".config");
|
|
12099
|
+
return path8.join(base, "tinypivot", "preferences.json");
|
|
11381
12100
|
}
|
|
11382
12101
|
var cachedAnonId = null;
|
|
11383
12102
|
function getAnonymousId() {
|
|
@@ -11395,7 +12114,7 @@ function getAnonymousId() {
|
|
|
11395
12114
|
const fresh = crypto.randomUUID();
|
|
11396
12115
|
cachedAnonId = fresh;
|
|
11397
12116
|
try {
|
|
11398
|
-
fsSync2.mkdirSync(
|
|
12117
|
+
fsSync2.mkdirSync(path8.dirname(prefPath), { recursive: true });
|
|
11399
12118
|
let existing = {};
|
|
11400
12119
|
try {
|
|
11401
12120
|
existing = JSON.parse(fsSync2.readFileSync(prefPath, "utf8"));
|
|
@@ -11436,12 +12155,13 @@ var APP_RESOURCE_URI = "ui://tinypivot/app.html";
|
|
|
11436
12155
|
var APP_MIME_TYPE = "text/html;profile=mcp-app";
|
|
11437
12156
|
var LOAD_DATA_ROW_GUIDE = 50;
|
|
11438
12157
|
function buildInstructions({ reprintCards = true } = {}) {
|
|
11439
|
-
const cards = reprintCards ? "In a terminal, show the returned ```text card verbatim with the
|
|
12158
|
+
const cards = reprintCards ? "In a terminal, show the returned ```text card verbatim with the Studio link in your reply, except in pi, whose TinyPivot extension already displays it." : "Do not reprint the ```text card: the user sees it in TinyPivot. Reply with the takeaways and the Studio link.";
|
|
11440
12159
|
return [
|
|
11441
12160
|
"Use TinyPivot for charts, pivot tables, period comparisons and tabular exploration instead of drawing them yourself (HTML, SVG, matplotlib, Markdown tables), passing chartConfig or pivotConfig in the same call.",
|
|
11442
|
-
`For files use load_file, so the rows stay out of your context. Use load_data only for rows you already have, up to about ${LOAD_DATA_ROW_GUIDE}; write larger sets to a file first.`,
|
|
12161
|
+
`For files use load_file, so the rows stay out of your context; to filter, join or aggregate files first, use query with SQL. Use load_data only for rows you already have, up to about ${LOAD_DATA_ROW_GUIDE}; write larger sets to a file first. history lists and reopens earlier pulls.`,
|
|
11443
12162
|
"Totals are exact. Compute ratios, shares and rates as numerator / denominator, one row per chart point, before loading; never add up percentage columns, and do not use percentOfTotal for a share within a period.",
|
|
11444
12163
|
"Use keepExisting: true only to compare datasets in one conversation; clear_datasets resets.",
|
|
12164
|
+
"Pass why on every data call: one short sentence the user sees in the TinyPivot Studio trace. Replies may end with notes the user wrote in the Studio; act on them.",
|
|
11445
12165
|
cards
|
|
11446
12166
|
].join(" ");
|
|
11447
12167
|
}
|
|
@@ -11522,6 +12242,14 @@ function clientSupportsMcpAppsUi(capabilities) {
|
|
|
11522
12242
|
function initialViewMode(requested, hasPivot, hasChart) {
|
|
11523
12243
|
return requested ?? (hasPivot && !hasChart ? "pivot" : "chart");
|
|
11524
12244
|
}
|
|
12245
|
+
function normalizePivot(pivotConfig) {
|
|
12246
|
+
return {
|
|
12247
|
+
...pivotConfig,
|
|
12248
|
+
valueFields: pivotConfig.valueFields.map((v) => ({ field: v.field, aggregation: v.aggregation }))
|
|
12249
|
+
};
|
|
12250
|
+
}
|
|
12251
|
+
var whyParam = z.string().max(240).optional();
|
|
12252
|
+
var DUCKDB_WAIT_MS = 45e3;
|
|
11525
12253
|
function toCoreChartConfig(input) {
|
|
11526
12254
|
return {
|
|
11527
12255
|
type: input.type,
|
|
@@ -11583,16 +12311,16 @@ function buildAppPayload(dataset, store, options) {
|
|
|
11583
12311
|
}
|
|
11584
12312
|
async function loadAppHtml(customPath) {
|
|
11585
12313
|
const envPath = process.env.TINYPIVOT_MCP_APP_HTML;
|
|
11586
|
-
const here =
|
|
12314
|
+
const here = path9.dirname(fileURLToPath2(import.meta.url));
|
|
11587
12315
|
const candidates = [
|
|
11588
12316
|
customPath,
|
|
11589
12317
|
envPath,
|
|
11590
|
-
|
|
11591
|
-
|
|
12318
|
+
path9.resolve(here, "app/index.html"),
|
|
12319
|
+
path9.resolve(here, "../dist/app/index.html")
|
|
11592
12320
|
].filter((p) => Boolean(p));
|
|
11593
12321
|
for (const candidate of candidates) {
|
|
11594
12322
|
try {
|
|
11595
|
-
const html = await
|
|
12323
|
+
const html = await fs8.readFile(candidate, "utf8");
|
|
11596
12324
|
if (html.trim().length > 0)
|
|
11597
12325
|
return html;
|
|
11598
12326
|
} catch {
|
|
@@ -11613,10 +12341,10 @@ function resolveLicenseKey(explicit) {
|
|
|
11613
12341
|
return explicit.trim();
|
|
11614
12342
|
if (process.env.TINYPIVOT_LICENSE_KEY?.trim())
|
|
11615
12343
|
return process.env.TINYPIVOT_LICENSE_KEY.trim();
|
|
11616
|
-
const here =
|
|
12344
|
+
const here = path9.dirname(fileURLToPath2(import.meta.url));
|
|
11617
12345
|
const candidates = [
|
|
11618
|
-
|
|
11619
|
-
|
|
12346
|
+
path9.resolve(here, "../.license"),
|
|
12347
|
+
path9.resolve(here, ".license")
|
|
11620
12348
|
];
|
|
11621
12349
|
for (const file of candidates) {
|
|
11622
12350
|
try {
|
|
@@ -11653,7 +12381,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11653
12381
|
const server = new McpServer(
|
|
11654
12382
|
{
|
|
11655
12383
|
name: "tinypivot",
|
|
11656
|
-
version: "0.
|
|
12384
|
+
version: "0.4.0"
|
|
11657
12385
|
},
|
|
11658
12386
|
{
|
|
11659
12387
|
capabilities: {
|
|
@@ -11678,6 +12406,28 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11678
12406
|
const content = [{ type: "text", text: summaryText }];
|
|
11679
12407
|
return clientRendersWidget() ? { content, structuredContent: payload } : { content };
|
|
11680
12408
|
};
|
|
12409
|
+
const replyWithDataset = async (ds, sessionKey, tool, note = "") => {
|
|
12410
|
+
const liveCompanionUrl = await resolveCompanionUrlForTool();
|
|
12411
|
+
const summaryText = withNotes(`${formatDatasetSummary(ds, liveCompanionUrl, cardFormat)}${note}`);
|
|
12412
|
+
const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, sessionKey });
|
|
12413
|
+
recordTelemetry({
|
|
12414
|
+
event: "tool_call",
|
|
12415
|
+
tool,
|
|
12416
|
+
rowBucket: bucketRowCount(ds.sourceTotalRows),
|
|
12417
|
+
client: getClientName(),
|
|
12418
|
+
tier,
|
|
12419
|
+
truncated: ds.truncatedForFreeTier
|
|
12420
|
+
});
|
|
12421
|
+
notifyCompanion();
|
|
12422
|
+
return dataToolResult(summaryText, payload);
|
|
12423
|
+
};
|
|
12424
|
+
const studio = options.studio ?? new Studio(store);
|
|
12425
|
+
try {
|
|
12426
|
+
studio.history.prune();
|
|
12427
|
+
} catch (error) {
|
|
12428
|
+
console.error(`[tinypivot-mcp] Could not prune history: ${error instanceof Error ? error.message : String(error)}`);
|
|
12429
|
+
}
|
|
12430
|
+
const withNotes = (text) => `${text}${studio.takeNotes()}`;
|
|
11681
12431
|
const widgetOnlyTools = [];
|
|
11682
12432
|
const widgetOnly = (tool) => {
|
|
11683
12433
|
widgetOnlyTools.push(tool);
|
|
@@ -11764,11 +12514,11 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11764
12514
|
"open_tinypivot",
|
|
11765
12515
|
{
|
|
11766
12516
|
title: "Open TinyPivot",
|
|
11767
|
-
description: "Open the TinyPivot
|
|
12517
|
+
description: "Open the TinyPivot Studio (grid, pivot, chart). Shows sample data when nothing is loaded.",
|
|
11768
12518
|
inputSchema: {
|
|
11769
12519
|
datasetId: z.string().optional(),
|
|
11770
12520
|
viewMode: z.enum(VIEW_MODE_VALUES).optional(),
|
|
11771
|
-
openBrowser: z.boolean().optional().describe("Also start the localhost
|
|
12521
|
+
openBrowser: z.boolean().optional().describe("Also start the localhost Studio in hosts with an inline widget")
|
|
11772
12522
|
},
|
|
11773
12523
|
_meta: PANE_UI_META
|
|
11774
12524
|
},
|
|
@@ -11809,6 +12559,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11809
12559
|
inputSchema: {
|
|
11810
12560
|
filePath: z.string(),
|
|
11811
12561
|
name: z.string().optional(),
|
|
12562
|
+
why: whyParam,
|
|
11812
12563
|
where: z.array(rowFilterSchema).optional().describe('Keep only matching rows, e.g. [{"field":"year","equals":[2026]}]'),
|
|
11813
12564
|
viewMode: z.enum(VIEW_MODE_VALUES).optional(),
|
|
11814
12565
|
pivotConfig: pivotConfigSchema.optional(),
|
|
@@ -11817,19 +12568,14 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11817
12568
|
},
|
|
11818
12569
|
_meta: INLINE_UI_META
|
|
11819
12570
|
},
|
|
11820
|
-
async ({ filePath, name, where, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
|
|
12571
|
+
async ({ filePath, name, why, where, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
|
|
11821
12572
|
try {
|
|
11822
12573
|
const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
|
|
11823
12574
|
const ds = await store.loadFromFile(filePath, name, { sessionKey, keepExisting: shouldKeep, where });
|
|
12575
|
+
studio.remember(ds, { kind: "file", source: ds.source, where });
|
|
11824
12576
|
const explicitChart = chartConfig ? toCoreChartConfig(chartConfig) : void 0;
|
|
11825
12577
|
if (pivotConfig) {
|
|
11826
|
-
const normalizedPivot =
|
|
11827
|
-
...pivotConfig,
|
|
11828
|
-
valueFields: pivotConfig.valueFields.map((v) => ({
|
|
11829
|
-
field: v.field,
|
|
11830
|
-
aggregation: v.aggregation
|
|
11831
|
-
}))
|
|
11832
|
-
};
|
|
12578
|
+
const normalizedPivot = normalizePivot(pivotConfig);
|
|
11833
12579
|
store.updateView(ds.id, {
|
|
11834
12580
|
viewMode: initialViewMode(viewMode, true, Boolean(explicitChart)),
|
|
11835
12581
|
pivotConfig: normalizedPivot,
|
|
@@ -11841,19 +12587,8 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11841
12587
|
...explicitChart ? { chartConfig: explicitChart } : {}
|
|
11842
12588
|
}, sessionKey);
|
|
11843
12589
|
}
|
|
11844
|
-
|
|
11845
|
-
|
|
11846
|
-
const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, sessionKey });
|
|
11847
|
-
recordTelemetry({
|
|
11848
|
-
event: "tool_call",
|
|
11849
|
-
tool: "load_file",
|
|
11850
|
-
rowBucket: bucketRowCount(ds.sourceTotalRows),
|
|
11851
|
-
client: getClientName(),
|
|
11852
|
-
tier,
|
|
11853
|
-
truncated: ds.truncatedForFreeTier
|
|
11854
|
-
});
|
|
11855
|
-
notifyCompanion();
|
|
11856
|
-
return dataToolResult(summaryText, payload);
|
|
12590
|
+
studio.recordDatasetStep(ds, { actor: "agent", tool: "load_file", why, file: ds.source, where });
|
|
12591
|
+
return replyWithDataset(ds, sessionKey, "load_file");
|
|
11857
12592
|
} catch (err) {
|
|
11858
12593
|
return {
|
|
11859
12594
|
isError: true,
|
|
@@ -11869,6 +12604,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11869
12604
|
description: "Chart or pivot rows you already have, up to about 50. Every row you pass is billed as output; for more, write a file and use load_file.",
|
|
11870
12605
|
inputSchema: {
|
|
11871
12606
|
name: z.string(),
|
|
12607
|
+
why: whyParam,
|
|
11872
12608
|
rows: z.array(z.record(z.string(), z.unknown())),
|
|
11873
12609
|
source: z.string().optional(),
|
|
11874
12610
|
viewMode: z.enum(VIEW_MODE_VALUES).optional(),
|
|
@@ -11878,39 +12614,22 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11878
12614
|
},
|
|
11879
12615
|
_meta: INLINE_UI_META
|
|
11880
12616
|
},
|
|
11881
|
-
async ({ name, rows, source, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
|
|
12617
|
+
async ({ name, why, rows, source, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
|
|
11882
12618
|
const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
|
|
11883
|
-
const normalizedPivot = pivotConfig ? {
|
|
11884
|
-
...pivotConfig,
|
|
11885
|
-
valueFields: pivotConfig.valueFields.map((v) => ({
|
|
11886
|
-
field: v.field,
|
|
11887
|
-
aggregation: v.aggregation
|
|
11888
|
-
}))
|
|
11889
|
-
} : void 0;
|
|
11890
12619
|
const ds = store.register({
|
|
11891
12620
|
name,
|
|
11892
12621
|
source: source ?? "inline JSON",
|
|
11893
12622
|
ingestionMode: "inline",
|
|
11894
12623
|
rows,
|
|
11895
12624
|
viewMode: initialViewMode(viewMode, Boolean(pivotConfig), Boolean(chartConfig)),
|
|
11896
|
-
pivotConfig:
|
|
12625
|
+
pivotConfig: pivotConfig ? normalizePivot(pivotConfig) : void 0,
|
|
11897
12626
|
chartConfig: chartConfig ? toCoreChartConfig(chartConfig) : void 0,
|
|
11898
12627
|
sessionKey,
|
|
11899
12628
|
keepExisting: shouldKeep
|
|
11900
12629
|
});
|
|
11901
|
-
|
|
11902
|
-
|
|
11903
|
-
|
|
11904
|
-
recordTelemetry({
|
|
11905
|
-
event: "tool_call",
|
|
11906
|
-
tool: "load_data",
|
|
11907
|
-
rowBucket: bucketRowCount(ds.sourceTotalRows),
|
|
11908
|
-
client: getClientName(),
|
|
11909
|
-
tier,
|
|
11910
|
-
truncated: ds.truncatedForFreeTier
|
|
11911
|
-
});
|
|
11912
|
-
notifyCompanion();
|
|
11913
|
-
return dataToolResult(summaryText, payload);
|
|
12630
|
+
studio.remember(ds, { kind: "data", source: source ?? "inline JSON" });
|
|
12631
|
+
studio.recordDatasetStep(ds, { actor: "agent", tool: "load_data", why });
|
|
12632
|
+
return replyWithDataset(ds, sessionKey, "load_data");
|
|
11914
12633
|
}
|
|
11915
12634
|
);
|
|
11916
12635
|
server.registerTool(
|
|
@@ -11923,12 +12642,13 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11923
12642
|
rowFields: z.array(z.string()).default([]),
|
|
11924
12643
|
columnFields: z.array(z.string()).default([]),
|
|
11925
12644
|
valueFields: z.array(pivotValueSchema).min(1),
|
|
12645
|
+
why: whyParam,
|
|
11926
12646
|
showRowTotals: z.boolean().default(true),
|
|
11927
12647
|
showColumnTotals: z.boolean().default(true)
|
|
11928
12648
|
},
|
|
11929
12649
|
_meta: INLINE_UI_META
|
|
11930
12650
|
},
|
|
11931
|
-
async ({ datasetId, rowFields, columnFields, valueFields, showRowTotals, showColumnTotals }, extra) => {
|
|
12651
|
+
async ({ datasetId, rowFields, columnFields, valueFields, why, showRowTotals, showColumnTotals }, extra) => {
|
|
11932
12652
|
const sessionKey = extractSessionKey(extra) ?? DEFAULT_SESSION_KEY;
|
|
11933
12653
|
const ds = store.get(datasetId, sessionKey);
|
|
11934
12654
|
if (!ds) {
|
|
@@ -11953,7 +12673,8 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11953
12673
|
chartConfig: chartConfigFromPivot(fullPivotConfig, ds.name) ?? ds.chartConfig
|
|
11954
12674
|
}, sessionKey);
|
|
11955
12675
|
const liveCompanionUrl = await resolveCompanionUrlForTool();
|
|
11956
|
-
const summary = formatPivotSummary(ds, fullPivotConfig, liveCompanionUrl, cardFormat);
|
|
12676
|
+
const summary = withNotes(formatPivotSummary(ds, fullPivotConfig, liveCompanionUrl, cardFormat));
|
|
12677
|
+
studio.recordDatasetStep(ds, { actor: "agent", tool: "configure_pivot", why });
|
|
11957
12678
|
const pivotTokensSaved = Math.max(0, ds.estimatedDatasetTokens - Math.round(Buffer.byteLength(summary, "utf8") / 4));
|
|
11958
12679
|
const payload = buildAppPayload(ds, store, {
|
|
11959
12680
|
licenseKey,
|
|
@@ -11987,11 +12708,12 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11987
12708
|
aggregation: z.enum(CHART_AGG_VALUES).default("sum"),
|
|
11988
12709
|
seriesField: z.string().optional(),
|
|
11989
12710
|
title: z.string().optional(),
|
|
12711
|
+
why: whyParam,
|
|
11990
12712
|
chartTheme: z.enum(VISUAL_THEME_VALUES).optional()
|
|
11991
12713
|
},
|
|
11992
12714
|
_meta: INLINE_UI_META
|
|
11993
12715
|
},
|
|
11994
|
-
async ({ datasetId, type, xAxisField, yAxisField, aggregation, seriesField, title, chartTheme }, extra) => {
|
|
12716
|
+
async ({ datasetId, type, xAxisField, yAxisField, aggregation, seriesField, title, why, chartTheme }, extra) => {
|
|
11995
12717
|
const sessionKey = extractSessionKey(extra) ?? DEFAULT_SESSION_KEY;
|
|
11996
12718
|
const ds = store.get(datasetId, sessionKey);
|
|
11997
12719
|
if (!ds) {
|
|
@@ -12027,8 +12749,9 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12027
12749
|
if (asciiChart)
|
|
12028
12750
|
summaryParts.push("", asciiChart);
|
|
12029
12751
|
if (liveCompanionUrl)
|
|
12030
|
-
summaryParts.push(`
|
|
12031
|
-
const summaryText = summaryParts.join("\n");
|
|
12752
|
+
summaryParts.push(`Studio: ${liveCompanionUrl}`);
|
|
12753
|
+
const summaryText = withNotes(summaryParts.join("\n"));
|
|
12754
|
+
studio.recordDatasetStep(ds, { actor: "agent", tool: "configure_chart", why });
|
|
12032
12755
|
const chartTokensSaved = Math.max(0, ds.estimatedDatasetTokens - Math.round(Buffer.byteLength(summaryText, "utf8") / 4));
|
|
12033
12756
|
const payload = buildAppPayload(ds, store, {
|
|
12034
12757
|
licenseKey,
|
|
@@ -12057,6 +12780,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12057
12780
|
description: "Run a read-only SELECT on the configured Postgres database and chart the result.",
|
|
12058
12781
|
inputSchema: {
|
|
12059
12782
|
sql: z.string(),
|
|
12783
|
+
why: whyParam,
|
|
12060
12784
|
name: z.string().optional(),
|
|
12061
12785
|
viewMode: z.enum(VIEW_MODE_VALUES).optional(),
|
|
12062
12786
|
pivotConfig: pivotConfigSchema.optional(),
|
|
@@ -12064,7 +12788,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12064
12788
|
},
|
|
12065
12789
|
_meta: INLINE_UI_META
|
|
12066
12790
|
},
|
|
12067
|
-
async ({ sql, name, viewMode, pivotConfig, keepExisting }, extra) => {
|
|
12791
|
+
async ({ sql, why, name, viewMode, pivotConfig, keepExisting }, extra) => {
|
|
12068
12792
|
if (!isPro2) {
|
|
12069
12793
|
return {
|
|
12070
12794
|
isError: true,
|
|
@@ -12083,30 +12807,13 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12083
12807
|
ingestionMode: "direct",
|
|
12084
12808
|
rows: res.rows,
|
|
12085
12809
|
viewMode: initialViewMode(viewMode, Boolean(pivotConfig), false),
|
|
12086
|
-
pivotConfig: pivotConfig ?
|
|
12087
|
-
...pivotConfig,
|
|
12088
|
-
valueFields: pivotConfig.valueFields.map((v) => ({
|
|
12089
|
-
field: v.field,
|
|
12090
|
-
aggregation: v.aggregation
|
|
12091
|
-
}))
|
|
12092
|
-
} : void 0,
|
|
12810
|
+
pivotConfig: pivotConfig ? normalizePivot(pivotConfig) : void 0,
|
|
12093
12811
|
sessionKey,
|
|
12094
12812
|
keepExisting: shouldKeep
|
|
12095
12813
|
});
|
|
12096
|
-
|
|
12097
|
-
|
|
12098
|
-
|
|
12099
|
-
const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, sessionKey });
|
|
12100
|
-
recordTelemetry({
|
|
12101
|
-
event: "tool_call",
|
|
12102
|
-
tool: "query_postgres",
|
|
12103
|
-
rowBucket: bucketRowCount(ds.sourceTotalRows),
|
|
12104
|
-
client: getClientName(),
|
|
12105
|
-
tier,
|
|
12106
|
-
truncated: ds.truncatedForFreeTier
|
|
12107
|
-
});
|
|
12108
|
-
notifyCompanion();
|
|
12109
|
-
return dataToolResult(summaryText, payload);
|
|
12814
|
+
studio.remember(ds, { kind: "postgres", source: sql });
|
|
12815
|
+
studio.recordDatasetStep(ds, { actor: "agent", tool: "query_postgres", why, sql });
|
|
12816
|
+
return replyWithDataset(ds, sessionKey, "query_postgres", res.truncated ? " (capped at max rows)" : "");
|
|
12110
12817
|
} catch (err) {
|
|
12111
12818
|
return {
|
|
12112
12819
|
isError: true,
|
|
@@ -12116,6 +12823,94 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12116
12823
|
}
|
|
12117
12824
|
);
|
|
12118
12825
|
}
|
|
12826
|
+
server.registerTool(
|
|
12827
|
+
"query",
|
|
12828
|
+
{
|
|
12829
|
+
title: "Query Files with SQL",
|
|
12830
|
+
description: "Run one read-only DuckDB SELECT over local CSV, Parquet or JSON files (FROM 'path') and loaded datasets (tables named by dataset id), then chart or pivot the result. Rows stay out of your context.",
|
|
12831
|
+
inputSchema: {
|
|
12832
|
+
sql: z.string(),
|
|
12833
|
+
why: whyParam,
|
|
12834
|
+
name: z.string().optional(),
|
|
12835
|
+
viewMode: z.enum(VIEW_MODE_VALUES).optional(),
|
|
12836
|
+
pivotConfig: pivotConfigSchema.optional(),
|
|
12837
|
+
chartConfig: chartConfigSchema.optional(),
|
|
12838
|
+
keepExisting: z.boolean().optional().describe("Keep earlier datasets loaded, to compare them")
|
|
12839
|
+
},
|
|
12840
|
+
_meta: INLINE_UI_META
|
|
12841
|
+
},
|
|
12842
|
+
async ({ sql, why, name, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
|
|
12843
|
+
const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
|
|
12844
|
+
try {
|
|
12845
|
+
if (await withinBudget(studio.duck.prepare(), DUCKDB_WAIT_MS) === "pending") {
|
|
12846
|
+
return { content: [{ type: "text", text: "DuckDB is downloading for its first use (about 20 MB, once). Run the same query again in a minute." }] };
|
|
12847
|
+
}
|
|
12848
|
+
const { dataset, truncated } = await studio.runQuery({
|
|
12849
|
+
sql,
|
|
12850
|
+
name,
|
|
12851
|
+
why,
|
|
12852
|
+
actor: "agent",
|
|
12853
|
+
sessionKey,
|
|
12854
|
+
keepExisting: shouldKeep,
|
|
12855
|
+
viewMode: initialViewMode(viewMode, Boolean(pivotConfig), Boolean(chartConfig)),
|
|
12856
|
+
pivotConfig: pivotConfig ? normalizePivot(pivotConfig) : void 0,
|
|
12857
|
+
chartConfig: chartConfig ? toCoreChartConfig(chartConfig) : void 0
|
|
12858
|
+
});
|
|
12859
|
+
return replyWithDataset(dataset, sessionKey, "query", truncated ? `
|
|
12860
|
+
_Result cut at ${dataset.rows.length.toLocaleString("en-US")} rows._` : "");
|
|
12861
|
+
} catch (error) {
|
|
12862
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
12863
|
+
return { isError: true, content: [{ type: "text", text: error instanceof QueryRejected ? message : `Query failed: ${message}` }] };
|
|
12864
|
+
}
|
|
12865
|
+
}
|
|
12866
|
+
);
|
|
12867
|
+
server.registerTool(
|
|
12868
|
+
"profile",
|
|
12869
|
+
{
|
|
12870
|
+
title: "Profile Dataset",
|
|
12871
|
+
description: "Describe each column of a loaded dataset: empty share, number and date ranges, commonest values.",
|
|
12872
|
+
inputSchema: {
|
|
12873
|
+
datasetId: z.string().optional(),
|
|
12874
|
+
why: whyParam
|
|
12875
|
+
}
|
|
12876
|
+
},
|
|
12877
|
+
async ({ datasetId, why }, extra) => {
|
|
12878
|
+
const { sessionKey } = resolveSessionContext(extra);
|
|
12879
|
+
const ds = store.get(datasetId, sessionKey);
|
|
12880
|
+
if (!ds)
|
|
12881
|
+
return { isError: true, content: [{ type: "text", text: `Dataset "${datasetId ?? "(active)"}" not found.` }] };
|
|
12882
|
+
studio.recordDatasetStep(ds, { actor: "agent", tool: "profile", why });
|
|
12883
|
+
return { content: [{ type: "text", text: withNotes(formatProfile(ds)) }] };
|
|
12884
|
+
}
|
|
12885
|
+
);
|
|
12886
|
+
server.registerTool(
|
|
12887
|
+
"history",
|
|
12888
|
+
{
|
|
12889
|
+
title: "Saved Pulls",
|
|
12890
|
+
description: "List data pulled in earlier sessions, or reopen one by id at no cost: nothing is re-queried.",
|
|
12891
|
+
inputSchema: {
|
|
12892
|
+
open: z.string().optional(),
|
|
12893
|
+
why: whyParam,
|
|
12894
|
+
limit: z.number().int().min(1).max(100).optional()
|
|
12895
|
+
},
|
|
12896
|
+
_meta: INLINE_UI_META
|
|
12897
|
+
},
|
|
12898
|
+
async ({ open, why, limit }, extra) => {
|
|
12899
|
+
const { history } = studio;
|
|
12900
|
+
if (!history.enabled)
|
|
12901
|
+
return { content: [{ type: "text", text: "History is off (TINYPIVOT_HISTORY=0)." }] };
|
|
12902
|
+
if (!open)
|
|
12903
|
+
return { content: [{ type: "text", text: withNotes(formatHistoryList(history.list(limit ?? 15))) }] };
|
|
12904
|
+
const { sessionKey } = resolveSessionContext(extra, true);
|
|
12905
|
+
try {
|
|
12906
|
+
const ds = await studio.reopen(open, { actor: "agent", why, sessionKey });
|
|
12907
|
+
return replyWithDataset(ds, sessionKey, "history");
|
|
12908
|
+
} catch (error) {
|
|
12909
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
12910
|
+
return { isError: true, content: [{ type: "text", text: `Could not reopen "${open}": ${message} ${formatHistoryList(history.list(5))}` }] };
|
|
12911
|
+
}
|
|
12912
|
+
}
|
|
12913
|
+
);
|
|
12119
12914
|
server.registerTool(
|
|
12120
12915
|
"list_datasets",
|
|
12121
12916
|
{
|
|
@@ -12280,7 +13075,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12280
13075
|
"set_visual_theme",
|
|
12281
13076
|
{
|
|
12282
13077
|
title: "Set Visual Theme",
|
|
12283
|
-
description: "Set the theme for charts, tables and the
|
|
13078
|
+
description: "Set the theme for charts, tables and the Studio.",
|
|
12284
13079
|
inputSchema: {
|
|
12285
13080
|
theme: z.enum(VISUAL_THEME_VALUES)
|
|
12286
13081
|
},
|
|
@@ -12332,6 +13127,7 @@ export {
|
|
|
12332
13127
|
DEFAULT_MODEL_PRICING,
|
|
12333
13128
|
resolveModelPricing,
|
|
12334
13129
|
tokensToUsd,
|
|
13130
|
+
STUDIO_HEADER,
|
|
12335
13131
|
getPreferencesPath,
|
|
12336
13132
|
loadSavedVisualTheme,
|
|
12337
13133
|
saveVisualThemePreference,
|
|
@@ -12355,6 +13151,9 @@ export {
|
|
|
12355
13151
|
runInitCommand,
|
|
12356
13152
|
listPostgresTables,
|
|
12357
13153
|
executeReadOnlyPostgresQuery,
|
|
13154
|
+
describeView,
|
|
13155
|
+
fileStepSql,
|
|
13156
|
+
Studio,
|
|
12358
13157
|
APP_RESOURCE_URI,
|
|
12359
13158
|
APP_MIME_TYPE,
|
|
12360
13159
|
TINYPIVOT_MCP_INSTRUCTIONS,
|