@smallwebco/tinypivot-mcp 0.3.0 → 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 +21 -6
- package/dist/app/index.html +87 -86
- package/dist/{chunk-AFGC2C4J.js → chunk-ZZOVYGIU.js} +484 -113
- package/dist/cli.js +37 -18
- package/dist/index.d.ts +215 -83
- package/dist/index.js +9 -1
- package/package.json +2 -2
- 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";
|
|
@@ -9444,7 +9447,7 @@ function formatDatasetSummary(dataset, companionUrl, options = {}) {
|
|
|
9444
9447
|
}
|
|
9445
9448
|
parts.push("", formatColumnNotes(dataset.columns));
|
|
9446
9449
|
if (companionUrl && !chartBlock)
|
|
9447
|
-
parts.push(`
|
|
9450
|
+
parts.push(`Studio: ${companionUrl}`);
|
|
9448
9451
|
return parts.join("\n");
|
|
9449
9452
|
}
|
|
9450
9453
|
function formatPivotSummary(dataset, config, companionUrl, options = {}) {
|
|
@@ -10104,10 +10107,39 @@ var INTERACTIVE_ROW_LIMIT = 1e5;
|
|
|
10104
10107
|
var ROW_PAGE_SIZE = 25e3;
|
|
10105
10108
|
|
|
10106
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;
|
|
10107
10130
|
function readJsonBody(req) {
|
|
10108
10131
|
return new Promise((resolve) => {
|
|
10109
10132
|
const chunks = [];
|
|
10110
|
-
|
|
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
|
+
});
|
|
10111
10143
|
req.on("end", () => {
|
|
10112
10144
|
try {
|
|
10113
10145
|
const text = Buffer.concat(chunks).toString("utf8").trim();
|
|
@@ -10159,11 +10191,8 @@ function buildFullCompanionPayload(store, datasetId, opts) {
|
|
|
10159
10191
|
}
|
|
10160
10192
|
async function startCompanionServer(options) {
|
|
10161
10193
|
const sseClients = /* @__PURE__ */ new Set();
|
|
10162
|
-
const
|
|
10163
|
-
const
|
|
10164
|
-
if (!payload)
|
|
10165
|
-
return;
|
|
10166
|
-
const frame = `event: update
|
|
10194
|
+
const send = (event, payload) => {
|
|
10195
|
+
const frame = `event: ${event}
|
|
10167
10196
|
data: ${JSON.stringify(payload)}
|
|
10168
10197
|
|
|
10169
10198
|
`;
|
|
@@ -10175,10 +10204,73 @@ data: ${JSON.stringify(payload)}
|
|
|
10175
10204
|
}
|
|
10176
10205
|
}
|
|
10177
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
|
+
};
|
|
10178
10261
|
const server = http.createServer(async (req, res) => {
|
|
10179
10262
|
const urlObj = new URL(req.url || "/", "http://127.0.0.1");
|
|
10180
10263
|
const pathname = urlObj.pathname;
|
|
10181
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" });
|
|
10182
10274
|
if (req.method === "GET" && (pathname === "/" || pathname === "/index.html")) {
|
|
10183
10275
|
const html = await options.loadHtml();
|
|
10184
10276
|
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
@@ -10192,20 +10284,30 @@ data: ${JSON.stringify(payload)}
|
|
|
10192
10284
|
"Connection": "keep-alive"
|
|
10193
10285
|
});
|
|
10194
10286
|
res.write("retry: 2000\n\n");
|
|
10287
|
+
if (studio)
|
|
10288
|
+
res.write(`event: studio
|
|
10289
|
+
data: ${JSON.stringify(studio.snapshot())}
|
|
10290
|
+
|
|
10291
|
+
`);
|
|
10195
10292
|
sseClients.add(res);
|
|
10196
10293
|
req.on("close", () => sseClients.delete(res));
|
|
10197
10294
|
return;
|
|
10198
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
|
+
}
|
|
10199
10303
|
if (req.method === "GET" && pathname === "/api/state") {
|
|
10200
10304
|
const dsId = urlObj.searchParams.get("datasetId") ?? void 0;
|
|
10201
10305
|
const payload = buildFullCompanionPayload(options.store, dsId, options);
|
|
10202
10306
|
if (!payload) {
|
|
10203
|
-
res
|
|
10204
|
-
res.end(JSON.stringify({ error: "Dataset not found" }));
|
|
10307
|
+
sendJson(res, 404, { error: "Dataset not found" });
|
|
10205
10308
|
return;
|
|
10206
10309
|
}
|
|
10207
|
-
res
|
|
10208
|
-
res.end(JSON.stringify(payload));
|
|
10310
|
+
sendJson(res, 200, payload);
|
|
10209
10311
|
return;
|
|
10210
10312
|
}
|
|
10211
10313
|
if (req.method === "POST" && pathname === "/api/model") {
|
|
@@ -10216,8 +10318,7 @@ data: ${JSON.stringify(payload)}
|
|
|
10216
10318
|
typeof body.customRatePerMillion === "number" ? body.customRatePerMillion : void 0
|
|
10217
10319
|
);
|
|
10218
10320
|
}
|
|
10219
|
-
res
|
|
10220
|
-
res.end(JSON.stringify({ session: options.store.getSessionSavings() }));
|
|
10321
|
+
sendJson(res, 200, { session: options.store.getSessionSavings() });
|
|
10221
10322
|
return;
|
|
10222
10323
|
}
|
|
10223
10324
|
if (req.method === "POST" && pathname === "/api/theme") {
|
|
@@ -10231,20 +10332,17 @@ data: ${JSON.stringify(payload)}
|
|
|
10231
10332
|
options.store.setVisualTheme(requested);
|
|
10232
10333
|
}
|
|
10233
10334
|
}
|
|
10234
|
-
res
|
|
10235
|
-
res.end(JSON.stringify({ chartTheme: isPro2 ? options.store.getVisualTheme() : "code" }));
|
|
10335
|
+
sendJson(res, 200, { chartTheme: isPro2 ? options.store.getVisualTheme() : "code" });
|
|
10236
10336
|
return;
|
|
10237
10337
|
}
|
|
10238
10338
|
if (req.method === "POST" && pathname === "/api/local-action") {
|
|
10239
10339
|
const body = await readJsonBody(req);
|
|
10240
10340
|
const dsId = typeof body.datasetId === "string" ? body.datasetId : void 0;
|
|
10241
10341
|
const result = options.store.recordLocalAction(dsId);
|
|
10242
|
-
res
|
|
10243
|
-
res.end(JSON.stringify(result));
|
|
10342
|
+
sendJson(res, 200, result);
|
|
10244
10343
|
return;
|
|
10245
10344
|
}
|
|
10246
|
-
res
|
|
10247
|
-
res.end(JSON.stringify({ error: "Not found" }));
|
|
10345
|
+
sendJson(res, 404, { error: "Not found" });
|
|
10248
10346
|
});
|
|
10249
10347
|
await new Promise((resolve, reject) => {
|
|
10250
10348
|
server.once("error", reject);
|
|
@@ -10264,6 +10362,7 @@ data: ${JSON.stringify(payload)}
|
|
|
10264
10362
|
url,
|
|
10265
10363
|
port: address.port,
|
|
10266
10364
|
broadcastUpdate,
|
|
10365
|
+
clientCount: () => sseClients.size,
|
|
10267
10366
|
close: () => {
|
|
10268
10367
|
if (closePromise)
|
|
10269
10368
|
return closePromise;
|
|
@@ -10521,7 +10620,7 @@ export default function (pi: any) {
|
|
|
10521
10620
|
|
|
10522
10621
|
if (typeof pi.registerCommand === "function") {
|
|
10523
10622
|
pi.registerCommand("tinypivot-theme", {
|
|
10524
|
-
description: "Switch TinyPivot visual theme (all 10 palettes, synced with
|
|
10623
|
+
description: "Switch TinyPivot visual theme (all 10 palettes, synced with Studio)",
|
|
10525
10624
|
handler: async (args: string, ctx: { ui?: { select?: (t: string, o: string[]) => Promise<string | undefined>; notify?: (m: string, t?: string) => void } }) => {
|
|
10526
10625
|
const active = readActiveThemeId();
|
|
10527
10626
|
let chosen = args?.trim().toLowerCase();
|
|
@@ -10566,11 +10665,11 @@ var RULE_HEADING = "## Charts & pivot tables (TinyPivot MCP)";
|
|
|
10566
10665
|
var RULE_USE = "Use the `tinypivot` MCP server for charts, pivot tables and data exploration instead of drawing them yourself.";
|
|
10567
10666
|
var TINYPIVOT_CLAUDE_RULE_BLOCK = `${RULE_START}
|
|
10568
10667
|
${RULE_HEADING}
|
|
10569
|
-
${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.
|
|
10570
10669
|
${RULE_END}`;
|
|
10571
10670
|
var TINYPIVOT_PI_RULE_BLOCK = `${RULE_START}
|
|
10572
10671
|
${RULE_HEADING}
|
|
10573
|
-
${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.
|
|
10574
10673
|
${RULE_END}`;
|
|
10575
10674
|
function upsertTinyPivotRuleBlock(existing, block = TINYPIVOT_CLAUDE_RULE_BLOCK) {
|
|
10576
10675
|
if (RULE_TEST_RE.test(existing)) {
|
|
@@ -11362,13 +11461,9 @@ async function executeReadOnlyPostgresQuery(config, sql) {
|
|
|
11362
11461
|
}
|
|
11363
11462
|
}
|
|
11364
11463
|
|
|
11365
|
-
// src/
|
|
11366
|
-
import
|
|
11367
|
-
import
|
|
11368
|
-
import path8 from "path";
|
|
11369
|
-
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
11370
|
-
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
11371
|
-
import { z } from "zod";
|
|
11464
|
+
// src/studio.ts
|
|
11465
|
+
import fs7 from "fs";
|
|
11466
|
+
import path7 from "path";
|
|
11372
11467
|
|
|
11373
11468
|
// src/duckdb.ts
|
|
11374
11469
|
import { spawn } from "child_process";
|
|
@@ -11627,6 +11722,291 @@ function formatHistoryList(entries) {
|
|
|
11627
11722
|
return [`Saved pulls (newest first). Reopen one with history({ open: id }):`, ...lines].join("\n");
|
|
11628
11723
|
}
|
|
11629
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
|
+
|
|
12002
|
+
// src/server.ts
|
|
12003
|
+
import fsSync3 from "fs";
|
|
12004
|
+
import fs8 from "fs/promises";
|
|
12005
|
+
import path9 from "path";
|
|
12006
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
12007
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
12008
|
+
import { z } from "zod";
|
|
12009
|
+
|
|
11630
12010
|
// src/profile.ts
|
|
11631
12011
|
var TOP_VALUES = 3;
|
|
11632
12012
|
function compactNumber(value2) {
|
|
@@ -11693,9 +12073,9 @@ function formatProfile(dataset) {
|
|
|
11693
12073
|
import crypto from "crypto";
|
|
11694
12074
|
import fsSync2 from "fs";
|
|
11695
12075
|
import os6 from "os";
|
|
11696
|
-
import
|
|
12076
|
+
import path8 from "path";
|
|
11697
12077
|
var DEFAULT_TELEMETRY_URL = "https://tiny-pivot.com/api/telemetry";
|
|
11698
|
-
var PACKAGE_VERSION = "0.
|
|
12078
|
+
var PACKAGE_VERSION = "0.4.0";
|
|
11699
12079
|
function isTelemetryEnabled() {
|
|
11700
12080
|
if (process.env.TINYPIVOT_TELEMETRY === "0" || process.env.TINYPIVOT_TELEMETRY === "false")
|
|
11701
12081
|
return false;
|
|
@@ -11715,8 +12095,8 @@ function bucketRowCount(rows) {
|
|
|
11715
12095
|
return "10k+";
|
|
11716
12096
|
}
|
|
11717
12097
|
function getPreferencesPath2() {
|
|
11718
|
-
const base = process.env.XDG_CONFIG_HOME?.trim() ||
|
|
11719
|
-
return
|
|
12098
|
+
const base = process.env.XDG_CONFIG_HOME?.trim() || path8.join(os6.homedir(), ".config");
|
|
12099
|
+
return path8.join(base, "tinypivot", "preferences.json");
|
|
11720
12100
|
}
|
|
11721
12101
|
var cachedAnonId = null;
|
|
11722
12102
|
function getAnonymousId() {
|
|
@@ -11734,7 +12114,7 @@ function getAnonymousId() {
|
|
|
11734
12114
|
const fresh = crypto.randomUUID();
|
|
11735
12115
|
cachedAnonId = fresh;
|
|
11736
12116
|
try {
|
|
11737
|
-
fsSync2.mkdirSync(
|
|
12117
|
+
fsSync2.mkdirSync(path8.dirname(prefPath), { recursive: true });
|
|
11738
12118
|
let existing = {};
|
|
11739
12119
|
try {
|
|
11740
12120
|
existing = JSON.parse(fsSync2.readFileSync(prefPath, "utf8"));
|
|
@@ -11775,12 +12155,13 @@ var APP_RESOURCE_URI = "ui://tinypivot/app.html";
|
|
|
11775
12155
|
var APP_MIME_TYPE = "text/html;profile=mcp-app";
|
|
11776
12156
|
var LOAD_DATA_ROW_GUIDE = 50;
|
|
11777
12157
|
function buildInstructions({ reprintCards = true } = {}) {
|
|
11778
|
-
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.";
|
|
11779
12159
|
return [
|
|
11780
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.",
|
|
11781
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.`,
|
|
11782
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.",
|
|
11783
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.",
|
|
11784
12165
|
cards
|
|
11785
12166
|
].join(" ");
|
|
11786
12167
|
}
|
|
@@ -11867,17 +12248,8 @@ function normalizePivot(pivotConfig) {
|
|
|
11867
12248
|
valueFields: pivotConfig.valueFields.map((v) => ({ field: v.field, aggregation: v.aggregation }))
|
|
11868
12249
|
};
|
|
11869
12250
|
}
|
|
12251
|
+
var whyParam = z.string().max(240).optional();
|
|
11870
12252
|
var DUCKDB_WAIT_MS = 45e3;
|
|
11871
|
-
function whereSql(where) {
|
|
11872
|
-
return where.map((filter) => `CAST(${quoteIdentifier(filter.field)} AS VARCHAR) IN (${filter.equals.map((value2) => quoteLiteral(String(value2))).join(", ")})`).join(" AND ");
|
|
11873
|
-
}
|
|
11874
|
-
function historyTableExpression(entry, rowsPath) {
|
|
11875
|
-
if (entry.kind === "file") {
|
|
11876
|
-
const file = quoteLiteral(entry.source);
|
|
11877
|
-
return entry.where?.length ? `(SELECT * FROM ${file} WHERE ${whereSql(entry.where)})` : file;
|
|
11878
|
-
}
|
|
11879
|
-
return rowsPath ? `read_json_auto(${quoteLiteral(rowsPath)})` : void 0;
|
|
11880
|
-
}
|
|
11881
12253
|
function toCoreChartConfig(input) {
|
|
11882
12254
|
return {
|
|
11883
12255
|
type: input.type,
|
|
@@ -11939,16 +12311,16 @@ function buildAppPayload(dataset, store, options) {
|
|
|
11939
12311
|
}
|
|
11940
12312
|
async function loadAppHtml(customPath) {
|
|
11941
12313
|
const envPath = process.env.TINYPIVOT_MCP_APP_HTML;
|
|
11942
|
-
const here =
|
|
12314
|
+
const here = path9.dirname(fileURLToPath2(import.meta.url));
|
|
11943
12315
|
const candidates = [
|
|
11944
12316
|
customPath,
|
|
11945
12317
|
envPath,
|
|
11946
|
-
|
|
11947
|
-
|
|
12318
|
+
path9.resolve(here, "app/index.html"),
|
|
12319
|
+
path9.resolve(here, "../dist/app/index.html")
|
|
11948
12320
|
].filter((p) => Boolean(p));
|
|
11949
12321
|
for (const candidate of candidates) {
|
|
11950
12322
|
try {
|
|
11951
|
-
const html = await
|
|
12323
|
+
const html = await fs8.readFile(candidate, "utf8");
|
|
11952
12324
|
if (html.trim().length > 0)
|
|
11953
12325
|
return html;
|
|
11954
12326
|
} catch {
|
|
@@ -11969,10 +12341,10 @@ function resolveLicenseKey(explicit) {
|
|
|
11969
12341
|
return explicit.trim();
|
|
11970
12342
|
if (process.env.TINYPIVOT_LICENSE_KEY?.trim())
|
|
11971
12343
|
return process.env.TINYPIVOT_LICENSE_KEY.trim();
|
|
11972
|
-
const here =
|
|
12344
|
+
const here = path9.dirname(fileURLToPath2(import.meta.url));
|
|
11973
12345
|
const candidates = [
|
|
11974
|
-
|
|
11975
|
-
|
|
12346
|
+
path9.resolve(here, "../.license"),
|
|
12347
|
+
path9.resolve(here, ".license")
|
|
11976
12348
|
];
|
|
11977
12349
|
for (const file of candidates) {
|
|
11978
12350
|
try {
|
|
@@ -12009,7 +12381,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12009
12381
|
const server = new McpServer(
|
|
12010
12382
|
{
|
|
12011
12383
|
name: "tinypivot",
|
|
12012
|
-
version: "0.
|
|
12384
|
+
version: "0.4.0"
|
|
12013
12385
|
},
|
|
12014
12386
|
{
|
|
12015
12387
|
capabilities: {
|
|
@@ -12036,7 +12408,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12036
12408
|
};
|
|
12037
12409
|
const replyWithDataset = async (ds, sessionKey, tool, note = "") => {
|
|
12038
12410
|
const liveCompanionUrl = await resolveCompanionUrlForTool();
|
|
12039
|
-
const summaryText = `${formatDatasetSummary(ds, liveCompanionUrl, cardFormat)}${note}
|
|
12411
|
+
const summaryText = withNotes(`${formatDatasetSummary(ds, liveCompanionUrl, cardFormat)}${note}`);
|
|
12040
12412
|
const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, sessionKey });
|
|
12041
12413
|
recordTelemetry({
|
|
12042
12414
|
event: "tool_call",
|
|
@@ -12049,24 +12421,13 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12049
12421
|
notifyCompanion();
|
|
12050
12422
|
return dataToolResult(summaryText, payload);
|
|
12051
12423
|
};
|
|
12052
|
-
const
|
|
12424
|
+
const studio = options.studio ?? new Studio(store);
|
|
12053
12425
|
try {
|
|
12054
|
-
history.prune();
|
|
12426
|
+
studio.history.prune();
|
|
12055
12427
|
} catch (error) {
|
|
12056
12428
|
console.error(`[tinypivot-mcp] Could not prune history: ${error instanceof Error ? error.message : String(error)}`);
|
|
12057
12429
|
}
|
|
12058
|
-
const
|
|
12059
|
-
const remember = (ds, input) => {
|
|
12060
|
-
const entry = history.record(ds, input);
|
|
12061
|
-
if (entry)
|
|
12062
|
-
pullsByDataset.set(ds.id, entry);
|
|
12063
|
-
};
|
|
12064
|
-
const duck = options.duckdb ?? new DuckDbRunner();
|
|
12065
|
-
const queryViews = (sessionKey) => store.listMetadata(sessionKey).flatMap((meta) => {
|
|
12066
|
-
const entry = pullsByDataset.get(meta.id);
|
|
12067
|
-
const from = entry && historyTableExpression(entry, history.rowsPath(entry));
|
|
12068
|
-
return from ? [{ name: meta.id, from }] : [];
|
|
12069
|
-
});
|
|
12430
|
+
const withNotes = (text) => `${text}${studio.takeNotes()}`;
|
|
12070
12431
|
const widgetOnlyTools = [];
|
|
12071
12432
|
const widgetOnly = (tool) => {
|
|
12072
12433
|
widgetOnlyTools.push(tool);
|
|
@@ -12153,11 +12514,11 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12153
12514
|
"open_tinypivot",
|
|
12154
12515
|
{
|
|
12155
12516
|
title: "Open TinyPivot",
|
|
12156
|
-
description: "Open the TinyPivot
|
|
12517
|
+
description: "Open the TinyPivot Studio (grid, pivot, chart). Shows sample data when nothing is loaded.",
|
|
12157
12518
|
inputSchema: {
|
|
12158
12519
|
datasetId: z.string().optional(),
|
|
12159
12520
|
viewMode: z.enum(VIEW_MODE_VALUES).optional(),
|
|
12160
|
-
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")
|
|
12161
12522
|
},
|
|
12162
12523
|
_meta: PANE_UI_META
|
|
12163
12524
|
},
|
|
@@ -12198,6 +12559,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12198
12559
|
inputSchema: {
|
|
12199
12560
|
filePath: z.string(),
|
|
12200
12561
|
name: z.string().optional(),
|
|
12562
|
+
why: whyParam,
|
|
12201
12563
|
where: z.array(rowFilterSchema).optional().describe('Keep only matching rows, e.g. [{"field":"year","equals":[2026]}]'),
|
|
12202
12564
|
viewMode: z.enum(VIEW_MODE_VALUES).optional(),
|
|
12203
12565
|
pivotConfig: pivotConfigSchema.optional(),
|
|
@@ -12206,11 +12568,11 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12206
12568
|
},
|
|
12207
12569
|
_meta: INLINE_UI_META
|
|
12208
12570
|
},
|
|
12209
|
-
async ({ filePath, name, where, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
|
|
12571
|
+
async ({ filePath, name, why, where, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
|
|
12210
12572
|
try {
|
|
12211
12573
|
const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
|
|
12212
12574
|
const ds = await store.loadFromFile(filePath, name, { sessionKey, keepExisting: shouldKeep, where });
|
|
12213
|
-
remember(ds, { kind: "file", source: ds.source, where });
|
|
12575
|
+
studio.remember(ds, { kind: "file", source: ds.source, where });
|
|
12214
12576
|
const explicitChart = chartConfig ? toCoreChartConfig(chartConfig) : void 0;
|
|
12215
12577
|
if (pivotConfig) {
|
|
12216
12578
|
const normalizedPivot = normalizePivot(pivotConfig);
|
|
@@ -12225,6 +12587,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12225
12587
|
...explicitChart ? { chartConfig: explicitChart } : {}
|
|
12226
12588
|
}, sessionKey);
|
|
12227
12589
|
}
|
|
12590
|
+
studio.recordDatasetStep(ds, { actor: "agent", tool: "load_file", why, file: ds.source, where });
|
|
12228
12591
|
return replyWithDataset(ds, sessionKey, "load_file");
|
|
12229
12592
|
} catch (err) {
|
|
12230
12593
|
return {
|
|
@@ -12241,6 +12604,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12241
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.",
|
|
12242
12605
|
inputSchema: {
|
|
12243
12606
|
name: z.string(),
|
|
12607
|
+
why: whyParam,
|
|
12244
12608
|
rows: z.array(z.record(z.string(), z.unknown())),
|
|
12245
12609
|
source: z.string().optional(),
|
|
12246
12610
|
viewMode: z.enum(VIEW_MODE_VALUES).optional(),
|
|
@@ -12250,7 +12614,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12250
12614
|
},
|
|
12251
12615
|
_meta: INLINE_UI_META
|
|
12252
12616
|
},
|
|
12253
|
-
async ({ name, rows, source, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
|
|
12617
|
+
async ({ name, why, rows, source, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
|
|
12254
12618
|
const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
|
|
12255
12619
|
const ds = store.register({
|
|
12256
12620
|
name,
|
|
@@ -12263,7 +12627,8 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12263
12627
|
sessionKey,
|
|
12264
12628
|
keepExisting: shouldKeep
|
|
12265
12629
|
});
|
|
12266
|
-
remember(ds, { kind: "data", source: source ?? "inline JSON" });
|
|
12630
|
+
studio.remember(ds, { kind: "data", source: source ?? "inline JSON" });
|
|
12631
|
+
studio.recordDatasetStep(ds, { actor: "agent", tool: "load_data", why });
|
|
12267
12632
|
return replyWithDataset(ds, sessionKey, "load_data");
|
|
12268
12633
|
}
|
|
12269
12634
|
);
|
|
@@ -12277,12 +12642,13 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12277
12642
|
rowFields: z.array(z.string()).default([]),
|
|
12278
12643
|
columnFields: z.array(z.string()).default([]),
|
|
12279
12644
|
valueFields: z.array(pivotValueSchema).min(1),
|
|
12645
|
+
why: whyParam,
|
|
12280
12646
|
showRowTotals: z.boolean().default(true),
|
|
12281
12647
|
showColumnTotals: z.boolean().default(true)
|
|
12282
12648
|
},
|
|
12283
12649
|
_meta: INLINE_UI_META
|
|
12284
12650
|
},
|
|
12285
|
-
async ({ datasetId, rowFields, columnFields, valueFields, showRowTotals, showColumnTotals }, extra) => {
|
|
12651
|
+
async ({ datasetId, rowFields, columnFields, valueFields, why, showRowTotals, showColumnTotals }, extra) => {
|
|
12286
12652
|
const sessionKey = extractSessionKey(extra) ?? DEFAULT_SESSION_KEY;
|
|
12287
12653
|
const ds = store.get(datasetId, sessionKey);
|
|
12288
12654
|
if (!ds) {
|
|
@@ -12307,7 +12673,8 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12307
12673
|
chartConfig: chartConfigFromPivot(fullPivotConfig, ds.name) ?? ds.chartConfig
|
|
12308
12674
|
}, sessionKey);
|
|
12309
12675
|
const liveCompanionUrl = await resolveCompanionUrlForTool();
|
|
12310
|
-
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 });
|
|
12311
12678
|
const pivotTokensSaved = Math.max(0, ds.estimatedDatasetTokens - Math.round(Buffer.byteLength(summary, "utf8") / 4));
|
|
12312
12679
|
const payload = buildAppPayload(ds, store, {
|
|
12313
12680
|
licenseKey,
|
|
@@ -12341,11 +12708,12 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12341
12708
|
aggregation: z.enum(CHART_AGG_VALUES).default("sum"),
|
|
12342
12709
|
seriesField: z.string().optional(),
|
|
12343
12710
|
title: z.string().optional(),
|
|
12711
|
+
why: whyParam,
|
|
12344
12712
|
chartTheme: z.enum(VISUAL_THEME_VALUES).optional()
|
|
12345
12713
|
},
|
|
12346
12714
|
_meta: INLINE_UI_META
|
|
12347
12715
|
},
|
|
12348
|
-
async ({ datasetId, type, xAxisField, yAxisField, aggregation, seriesField, title, chartTheme }, extra) => {
|
|
12716
|
+
async ({ datasetId, type, xAxisField, yAxisField, aggregation, seriesField, title, why, chartTheme }, extra) => {
|
|
12349
12717
|
const sessionKey = extractSessionKey(extra) ?? DEFAULT_SESSION_KEY;
|
|
12350
12718
|
const ds = store.get(datasetId, sessionKey);
|
|
12351
12719
|
if (!ds) {
|
|
@@ -12381,8 +12749,9 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12381
12749
|
if (asciiChart)
|
|
12382
12750
|
summaryParts.push("", asciiChart);
|
|
12383
12751
|
if (liveCompanionUrl)
|
|
12384
|
-
summaryParts.push(`
|
|
12385
|
-
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 });
|
|
12386
12755
|
const chartTokensSaved = Math.max(0, ds.estimatedDatasetTokens - Math.round(Buffer.byteLength(summaryText, "utf8") / 4));
|
|
12387
12756
|
const payload = buildAppPayload(ds, store, {
|
|
12388
12757
|
licenseKey,
|
|
@@ -12411,6 +12780,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12411
12780
|
description: "Run a read-only SELECT on the configured Postgres database and chart the result.",
|
|
12412
12781
|
inputSchema: {
|
|
12413
12782
|
sql: z.string(),
|
|
12783
|
+
why: whyParam,
|
|
12414
12784
|
name: z.string().optional(),
|
|
12415
12785
|
viewMode: z.enum(VIEW_MODE_VALUES).optional(),
|
|
12416
12786
|
pivotConfig: pivotConfigSchema.optional(),
|
|
@@ -12418,7 +12788,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12418
12788
|
},
|
|
12419
12789
|
_meta: INLINE_UI_META
|
|
12420
12790
|
},
|
|
12421
|
-
async ({ sql, name, viewMode, pivotConfig, keepExisting }, extra) => {
|
|
12791
|
+
async ({ sql, why, name, viewMode, pivotConfig, keepExisting }, extra) => {
|
|
12422
12792
|
if (!isPro2) {
|
|
12423
12793
|
return {
|
|
12424
12794
|
isError: true,
|
|
@@ -12441,7 +12811,8 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12441
12811
|
sessionKey,
|
|
12442
12812
|
keepExisting: shouldKeep
|
|
12443
12813
|
});
|
|
12444
|
-
remember(ds, { kind: "postgres", source: sql });
|
|
12814
|
+
studio.remember(ds, { kind: "postgres", source: sql });
|
|
12815
|
+
studio.recordDatasetStep(ds, { actor: "agent", tool: "query_postgres", why, sql });
|
|
12445
12816
|
return replyWithDataset(ds, sessionKey, "query_postgres", res.truncated ? " (capped at max rows)" : "");
|
|
12446
12817
|
} catch (err) {
|
|
12447
12818
|
return {
|
|
@@ -12459,6 +12830,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12459
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.",
|
|
12460
12831
|
inputSchema: {
|
|
12461
12832
|
sql: z.string(),
|
|
12833
|
+
why: whyParam,
|
|
12462
12834
|
name: z.string().optional(),
|
|
12463
12835
|
viewMode: z.enum(VIEW_MODE_VALUES).optional(),
|
|
12464
12836
|
pivotConfig: pivotConfigSchema.optional(),
|
|
@@ -12467,27 +12839,25 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12467
12839
|
},
|
|
12468
12840
|
_meta: INLINE_UI_META
|
|
12469
12841
|
},
|
|
12470
|
-
async ({ sql, name, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
|
|
12842
|
+
async ({ sql, why, name, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
|
|
12471
12843
|
const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
|
|
12472
12844
|
try {
|
|
12473
|
-
if (await withinBudget(duck.prepare(), DUCKDB_WAIT_MS) === "pending") {
|
|
12845
|
+
if (await withinBudget(studio.duck.prepare(), DUCKDB_WAIT_MS) === "pending") {
|
|
12474
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." }] };
|
|
12475
12847
|
}
|
|
12476
|
-
const
|
|
12477
|
-
|
|
12478
|
-
name
|
|
12479
|
-
|
|
12480
|
-
|
|
12481
|
-
|
|
12848
|
+
const { dataset, truncated } = await studio.runQuery({
|
|
12849
|
+
sql,
|
|
12850
|
+
name,
|
|
12851
|
+
why,
|
|
12852
|
+
actor: "agent",
|
|
12853
|
+
sessionKey,
|
|
12854
|
+
keepExisting: shouldKeep,
|
|
12482
12855
|
viewMode: initialViewMode(viewMode, Boolean(pivotConfig), Boolean(chartConfig)),
|
|
12483
12856
|
pivotConfig: pivotConfig ? normalizePivot(pivotConfig) : void 0,
|
|
12484
|
-
chartConfig: chartConfig ? toCoreChartConfig(chartConfig) : void 0
|
|
12485
|
-
sessionKey,
|
|
12486
|
-
keepExisting: shouldKeep
|
|
12857
|
+
chartConfig: chartConfig ? toCoreChartConfig(chartConfig) : void 0
|
|
12487
12858
|
});
|
|
12488
|
-
|
|
12489
|
-
|
|
12490
|
-
_Result cut at ${result.rows.length.toLocaleString("en-US")} rows._` : "");
|
|
12859
|
+
return replyWithDataset(dataset, sessionKey, "query", truncated ? `
|
|
12860
|
+
_Result cut at ${dataset.rows.length.toLocaleString("en-US")} rows._` : "");
|
|
12491
12861
|
} catch (error) {
|
|
12492
12862
|
const message = error instanceof Error ? error.message : String(error);
|
|
12493
12863
|
return { isError: true, content: [{ type: "text", text: error instanceof QueryRejected ? message : `Query failed: ${message}` }] };
|
|
@@ -12500,15 +12870,17 @@ _Result cut at ${result.rows.length.toLocaleString("en-US")} rows._` : "");
|
|
|
12500
12870
|
title: "Profile Dataset",
|
|
12501
12871
|
description: "Describe each column of a loaded dataset: empty share, number and date ranges, commonest values.",
|
|
12502
12872
|
inputSchema: {
|
|
12503
|
-
datasetId: z.string().optional()
|
|
12873
|
+
datasetId: z.string().optional(),
|
|
12874
|
+
why: whyParam
|
|
12504
12875
|
}
|
|
12505
12876
|
},
|
|
12506
|
-
async ({ datasetId }, extra) => {
|
|
12877
|
+
async ({ datasetId, why }, extra) => {
|
|
12507
12878
|
const { sessionKey } = resolveSessionContext(extra);
|
|
12508
12879
|
const ds = store.get(datasetId, sessionKey);
|
|
12509
12880
|
if (!ds)
|
|
12510
12881
|
return { isError: true, content: [{ type: "text", text: `Dataset "${datasetId ?? "(active)"}" not found.` }] };
|
|
12511
|
-
|
|
12882
|
+
studio.recordDatasetStep(ds, { actor: "agent", tool: "profile", why });
|
|
12883
|
+
return { content: [{ type: "text", text: withNotes(formatProfile(ds)) }] };
|
|
12512
12884
|
}
|
|
12513
12885
|
);
|
|
12514
12886
|
server.registerTool(
|
|
@@ -12518,29 +12890,24 @@ _Result cut at ${result.rows.length.toLocaleString("en-US")} rows._` : "");
|
|
|
12518
12890
|
description: "List data pulled in earlier sessions, or reopen one by id at no cost: nothing is re-queried.",
|
|
12519
12891
|
inputSchema: {
|
|
12520
12892
|
open: z.string().optional(),
|
|
12893
|
+
why: whyParam,
|
|
12521
12894
|
limit: z.number().int().min(1).max(100).optional()
|
|
12522
12895
|
},
|
|
12523
12896
|
_meta: INLINE_UI_META
|
|
12524
12897
|
},
|
|
12525
|
-
async ({ open, limit }, extra) => {
|
|
12898
|
+
async ({ open, why, limit }, extra) => {
|
|
12899
|
+
const { history } = studio;
|
|
12526
12900
|
if (!history.enabled)
|
|
12527
12901
|
return { content: [{ type: "text", text: "History is off (TINYPIVOT_HISTORY=0)." }] };
|
|
12528
12902
|
if (!open)
|
|
12529
|
-
return { content: [{ type: "text", text: formatHistoryList(history.list(limit ?? 15)) }] };
|
|
12530
|
-
const entry = history.get(open);
|
|
12531
|
-
if (!entry)
|
|
12532
|
-
return { isError: true, content: [{ type: "text", text: `No saved pull "${open}". ${formatHistoryList(history.list(5))}` }] };
|
|
12903
|
+
return { content: [{ type: "text", text: withNotes(formatHistoryList(history.list(limit ?? 15))) }] };
|
|
12533
12904
|
const { sessionKey } = resolveSessionContext(extra, true);
|
|
12534
12905
|
try {
|
|
12535
|
-
const ds =
|
|
12536
|
-
store.updateView(ds.id, {
|
|
12537
|
-
...entry.chartConfig ? { chartConfig: entry.chartConfig } : {},
|
|
12538
|
-
...entry.pivotConfig ? { pivotConfig: entry.pivotConfig } : {}
|
|
12539
|
-
}, sessionKey);
|
|
12540
|
-
pullsByDataset.set(ds.id, entry);
|
|
12906
|
+
const ds = await studio.reopen(open, { actor: "agent", why, sessionKey });
|
|
12541
12907
|
return replyWithDataset(ds, sessionKey, "history");
|
|
12542
12908
|
} catch (error) {
|
|
12543
|
-
|
|
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))}` }] };
|
|
12544
12911
|
}
|
|
12545
12912
|
}
|
|
12546
12913
|
);
|
|
@@ -12708,7 +13075,7 @@ _Result cut at ${result.rows.length.toLocaleString("en-US")} rows._` : "");
|
|
|
12708
13075
|
"set_visual_theme",
|
|
12709
13076
|
{
|
|
12710
13077
|
title: "Set Visual Theme",
|
|
12711
|
-
description: "Set the theme for charts, tables and the
|
|
13078
|
+
description: "Set the theme for charts, tables and the Studio.",
|
|
12712
13079
|
inputSchema: {
|
|
12713
13080
|
theme: z.enum(VISUAL_THEME_VALUES)
|
|
12714
13081
|
},
|
|
@@ -12760,6 +13127,7 @@ export {
|
|
|
12760
13127
|
DEFAULT_MODEL_PRICING,
|
|
12761
13128
|
resolveModelPricing,
|
|
12762
13129
|
tokensToUsd,
|
|
13130
|
+
STUDIO_HEADER,
|
|
12763
13131
|
getPreferencesPath,
|
|
12764
13132
|
loadSavedVisualTheme,
|
|
12765
13133
|
saveVisualThemePreference,
|
|
@@ -12783,6 +13151,9 @@ export {
|
|
|
12783
13151
|
runInitCommand,
|
|
12784
13152
|
listPostgresTables,
|
|
12785
13153
|
executeReadOnlyPostgresQuery,
|
|
13154
|
+
describeView,
|
|
13155
|
+
fileStepSql,
|
|
13156
|
+
Studio,
|
|
12786
13157
|
APP_RESOURCE_URI,
|
|
12787
13158
|
APP_MIME_TYPE,
|
|
12788
13159
|
TINYPIVOT_MCP_INSTRUCTIONS,
|