@smallwebco/tinypivot-mcp 0.2.9 → 0.3.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 +1 -1
- package/README.md +6 -1
- package/dist/{chunk-3JPAVTJZ.js → chunk-AFGC2C4J.js} +631 -221
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +89 -2
- package/dist/index.js +1 -1
- package/package.json +3 -2
- package/server.json +2 -2
|
@@ -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": ([path9]) => ({ closed: false, path: path9 }) },
|
|
5638
|
+
{ "name": "path", "symbols": ["closed_path"], "postprocess": ([path9]) => ({ closed: true, path: path9 }) },
|
|
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"] },
|
|
@@ -9374,6 +9374,26 @@ function detectNonAdditiveSumWarning(dataset, chartConfig) {
|
|
|
9374
9374
|
const grain = sField ? `\`(${xField}, ${sField})\`` : `\`${xField}\``;
|
|
9375
9375
|
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
9376
|
}
|
|
9377
|
+
var SMALL_GRID_MAX_ROWS = 25;
|
|
9378
|
+
var SMALL_GRID_MAX_COLUMNS = 10;
|
|
9379
|
+
function tableCell(value2) {
|
|
9380
|
+
if (value2 === null || value2 === void 0)
|
|
9381
|
+
return "";
|
|
9382
|
+
const text = typeof value2 === "number" ? value2.toLocaleString("en-US", { maximumFractionDigits: 4 }) : String(value2);
|
|
9383
|
+
return text.replace(/\|/g, "\\|").replace(/\n/g, " ");
|
|
9384
|
+
}
|
|
9385
|
+
function smallGridTable(dataset) {
|
|
9386
|
+
if (dataset.viewMode !== "grid" || dataset.rows.length > SMALL_GRID_MAX_ROWS || dataset.columns.length > SMALL_GRID_MAX_COLUMNS)
|
|
9387
|
+
return null;
|
|
9388
|
+
const names = dataset.columns.map((column) => column.name);
|
|
9389
|
+
if (names.length === 0)
|
|
9390
|
+
return null;
|
|
9391
|
+
return [
|
|
9392
|
+
`| ${names.join(" | ")} |`,
|
|
9393
|
+
`|${names.map(() => "---").join("|")}|`,
|
|
9394
|
+
...dataset.rows.map((row) => `| ${names.map((name) => tableCell(row[name])).join(" | ")} |`)
|
|
9395
|
+
].join("\n");
|
|
9396
|
+
}
|
|
9377
9397
|
function pivotTableCard(dataset, options) {
|
|
9378
9398
|
const pivot = dataset.pivotConfig;
|
|
9379
9399
|
if (dataset.viewMode !== "pivot" || !pivot?.valueFields?.length)
|
|
@@ -9391,19 +9411,26 @@ function pivotTableCard(dataset, options) {
|
|
|
9391
9411
|
function formatDistinctCount(count) {
|
|
9392
9412
|
return count >= DISTINCT_COUNT_CAP ? `${DISTINCT_COUNT_CAP.toLocaleString("en-US")}+` : String(count);
|
|
9393
9413
|
}
|
|
9414
|
+
var LISTED_VALUES_MAX = 5;
|
|
9415
|
+
function formatColumnNotes(columns) {
|
|
9416
|
+
const notes = columns.map((column) => {
|
|
9417
|
+
const values = column.distinctCount <= LISTED_VALUES_MAX ? `: ${column.sampleValues.join(", ")}` : ` (${formatDistinctCount(column.distinctCount)} values)`;
|
|
9418
|
+
return `\`${column.name}\` ${column.type}${values}`;
|
|
9419
|
+
});
|
|
9420
|
+
return `Columns: ${notes.join(" \xB7 ") || "none"}`;
|
|
9421
|
+
}
|
|
9422
|
+
var REPRINT_NOTE = "Show the card above to the user verbatim.";
|
|
9394
9423
|
function formatDatasetSummary(dataset, companionUrl, options = {}) {
|
|
9395
|
-
const cols = dataset.columns.map((c) => `- \`${c.name}\` (${c.type}, ${formatDistinctCount(c.distinctCount)} distinct; e.g. ${c.sampleValues.slice(0, 3).join(", ")})`).join("\n");
|
|
9396
9424
|
const cardOptions = { ...options, companionUrl: options.companionUrl ?? companionUrl };
|
|
9397
|
-
const chartBlock = pivotTableCard(dataset, cardOptions) ?? formatTerminalChart(dataset, dataset.chartConfig, cardOptions);
|
|
9425
|
+
const chartBlock = smallGridTable(dataset) ?? pivotTableCard(dataset, cardOptions) ?? formatTerminalChart(dataset, dataset.chartConfig, cardOptions);
|
|
9398
9426
|
const rowHeadline = dataset.truncatedForFreeTier ? `**${dataset.rows.length.toLocaleString()} of ${dataset.sourceTotalRows.toLocaleString()} rows (Free tier limit)**` : `**${dataset.rows.length.toLocaleString()} rows**`;
|
|
9399
9427
|
const parts = [
|
|
9400
|
-
`Loaded
|
|
9401
|
-
`Source: ${dataset.source}`
|
|
9428
|
+
`Loaded **${dataset.name}** (\`${dataset.id}\`): ${rowHeadline}, ${dataset.columns.length} columns.`
|
|
9402
9429
|
];
|
|
9403
9430
|
if (dataset.truncatedForFreeTier) {
|
|
9404
9431
|
parts.push(
|
|
9405
9432
|
"",
|
|
9406
|
-
`> **
|
|
9433
|
+
`> **Free tier:** showing the first ${dataset.rows.length.toLocaleString()} of ${dataset.sourceTotalRows.toLocaleString()} rows, so totals cover only those. A license key unlocks every row: https://tiny-pivot.com/pricing`
|
|
9407
9434
|
);
|
|
9408
9435
|
}
|
|
9409
9436
|
const integrityWarning = detectNonAdditiveSumWarning(dataset, dataset.chartConfig);
|
|
@@ -9411,18 +9438,13 @@ function formatDatasetSummary(dataset, companionUrl, options = {}) {
|
|
|
9411
9438
|
parts.push("", integrityWarning);
|
|
9412
9439
|
}
|
|
9413
9440
|
if (chartBlock) {
|
|
9414
|
-
|
|
9415
|
-
|
|
9416
|
-
|
|
9417
|
-
chartBlock,
|
|
9418
|
-
"",
|
|
9419
|
-
echoNote
|
|
9420
|
-
);
|
|
9421
|
-
}
|
|
9422
|
-
parts.push("", "Columns:", cols || "(no columns)");
|
|
9423
|
-
if (companionUrl) {
|
|
9424
|
-
parts.push("", `Interactive Data IDE (live-updating): ${companionUrl}`);
|
|
9441
|
+
parts.push("", chartBlock);
|
|
9442
|
+
if (companionUrl && options.reprintNote !== false)
|
|
9443
|
+
parts.push(REPRINT_NOTE);
|
|
9425
9444
|
}
|
|
9445
|
+
parts.push("", formatColumnNotes(dataset.columns));
|
|
9446
|
+
if (companionUrl && !chartBlock)
|
|
9447
|
+
parts.push(`Data IDE: ${companionUrl}`);
|
|
9426
9448
|
return parts.join("\n");
|
|
9427
9449
|
}
|
|
9428
9450
|
function formatPivotSummary(dataset, config, companionUrl, options = {}) {
|
|
@@ -9540,20 +9562,9 @@ function formatPivotSummary(dataset, config, companionUrl, options = {}) {
|
|
|
9540
9562
|
tableLines.push("```");
|
|
9541
9563
|
}
|
|
9542
9564
|
const headline = dataset.truncatedForFreeTier ? `Pivot on **${dataset.name}** (**first ${dataset.rows.length.toLocaleString()} of ${dataset.sourceTotalRows.toLocaleString()} rows \u2014 Free tier subset**):` : `Pivot on **${dataset.name}** (${dataset.rows.length.toLocaleString()} source rows):`;
|
|
9543
|
-
const
|
|
9544
|
-
|
|
9545
|
-
|
|
9546
|
-
"",
|
|
9547
|
-
tableLines.join("\n"),
|
|
9548
|
-
"",
|
|
9549
|
-
echoNote
|
|
9550
|
-
];
|
|
9551
|
-
if (result.rowHeaders.length > maxRows) {
|
|
9552
|
-
out.push(`_\u2026and ${result.rowHeaders.length - maxRows} more rows visible interactively in TinyPivot._`);
|
|
9553
|
-
}
|
|
9554
|
-
if (companionUrl) {
|
|
9555
|
-
out.push("", `Interactive Data IDE (live-updating): ${companionUrl}`);
|
|
9556
|
-
}
|
|
9565
|
+
const out = [headline, "", tableLines.join("\n")];
|
|
9566
|
+
if (companionUrl && options.reprintNote !== false)
|
|
9567
|
+
out.push(REPRINT_NOTE);
|
|
9557
9568
|
return out.join("\n");
|
|
9558
9569
|
}
|
|
9559
9570
|
|
|
@@ -10551,17 +10562,15 @@ var RULE_START = "<!-- tinypivot:start -->";
|
|
|
10551
10562
|
var RULE_END = "<!-- tinypivot:end -->";
|
|
10552
10563
|
var RULE_TEST_RE = /<!-- tinypivot(?:-mcp)?:start -->[\s\S]*?<!-- tinypivot(?:-mcp)?:end -->/;
|
|
10553
10564
|
var RULE_REPLACE_RE = /<!-- tinypivot(?:-mcp)?:start -->[\s\S]*?<!-- tinypivot(?:-mcp)?:end -->/g;
|
|
10565
|
+
var RULE_HEADING = "## Charts & pivot tables (TinyPivot MCP)";
|
|
10566
|
+
var RULE_USE = "Use the `tinypivot` MCP server for charts, pivot tables and data exploration instead of drawing them yourself.";
|
|
10554
10567
|
var TINYPIVOT_CLAUDE_RULE_BLOCK = `${RULE_START}
|
|
10555
|
-
|
|
10556
|
-
|
|
10557
|
-
TinyPivot is a deterministic presentation & additive-rollup layer: for non-additive shares, rates, margins, or ratios over time (e.g. monthly share %, conversion rate, YoY %), pre-compute exact \`numerator / denominator\` ratios at the target chart grain (1 row per X \xD7 series) in SQL/Python before passing rows to TinyPivot\u2014never sum \`%\` columns across sub-segments and never use \`percentOfTotal\` for within-period share. Pass \`keepExisting: true\` only when comparing multiple datasets in the SAME conversation; use \`clear_datasets\` to reset.
|
|
10558
|
-
In terminal harnesses (pi, Claude Code, OpenCode, Codex CLI), there is NO inline GUI widget: ALWAYS include the returned fenced \`text\` TinyPivot chart/table card verbatim AND the localhost Companion IDE URL in your VERY FIRST reply\u2014never say "it is open in TinyPivot" without printing the card.
|
|
10568
|
+
${RULE_HEADING}
|
|
10569
|
+
${RULE_USE} In a terminal, show its \`text\` card verbatim with the Data IDE link.
|
|
10559
10570
|
${RULE_END}`;
|
|
10560
10571
|
var TINYPIVOT_PI_RULE_BLOCK = `${RULE_START}
|
|
10561
|
-
|
|
10562
|
-
|
|
10563
|
-
TinyPivot is a deterministic presentation & additive-rollup layer: for non-additive shares, rates, margins, or ratios over time (e.g. monthly share %, conversion rate, YoY %), pre-compute exact \`numerator / denominator\` ratios at the target chart grain (1 row per X \xD7 series) in SQL/Python before passing rows to TinyPivot\u2014never sum \`%\` columns across sub-segments and never use \`percentOfTotal\` for within-period share. Pass \`keepExisting: true\` only when comparing multiple datasets in the SAME conversation; use \`clear_datasets\` to reset.
|
|
10564
|
-
The TinyPivot pi extension automatically renders every TinyPivot chart/pivot card in full 24-bit color right in the terminal UI after the tool call\u2014follow up with 2\u20133 concise analytical takeaways and the live Companion IDE URL (no need to repeat a plain monochrome ASCII box unless the user asks). Users can switch themes anytime with \`/tinypivot-theme\` or \`set_visual_theme\`.
|
|
10572
|
+
${RULE_HEADING}
|
|
10573
|
+
${RULE_USE} The TinyPivot pi extension already shows each card, so reply with the takeaways and the Data IDE link. \`/tinypivot-theme\` switches themes.
|
|
10565
10574
|
${RULE_END}`;
|
|
10566
10575
|
function upsertTinyPivotRuleBlock(existing, block = TINYPIVOT_CLAUDE_RULE_BLOCK) {
|
|
10567
10576
|
if (RULE_TEST_RE.test(existing)) {
|
|
@@ -11355,19 +11364,338 @@ async function executeReadOnlyPostgresQuery(config, sql) {
|
|
|
11355
11364
|
|
|
11356
11365
|
// src/server.ts
|
|
11357
11366
|
import fsSync3 from "fs";
|
|
11358
|
-
import
|
|
11359
|
-
import
|
|
11367
|
+
import fs7 from "fs/promises";
|
|
11368
|
+
import path8 from "path";
|
|
11360
11369
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
11361
11370
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
11362
11371
|
import { z } from "zod";
|
|
11363
11372
|
|
|
11373
|
+
// src/duckdb.ts
|
|
11374
|
+
import { spawn } from "child_process";
|
|
11375
|
+
import fs5 from "fs";
|
|
11376
|
+
import { createRequire } from "module";
|
|
11377
|
+
import os4 from "os";
|
|
11378
|
+
import path5 from "path";
|
|
11379
|
+
var DUCKDB_PACKAGE = "@duckdb/node-api";
|
|
11380
|
+
var DUCKDB_VERSION = "2.0.1-r.1";
|
|
11381
|
+
var QUERY_ROW_LIMIT = 5e5;
|
|
11382
|
+
var INSTALL_TIMEOUT_MS = 5 * 60 * 1e3;
|
|
11383
|
+
function duckdbCacheDir() {
|
|
11384
|
+
const base = process.env.XDG_CACHE_HOME || path5.join(os4.homedir(), ".cache");
|
|
11385
|
+
return path5.join(base, "tinypivot", `duckdb-${DUCKDB_VERSION}`);
|
|
11386
|
+
}
|
|
11387
|
+
function requireFrom(dir) {
|
|
11388
|
+
try {
|
|
11389
|
+
return createRequire(path5.join(dir, "package.json"))(DUCKDB_PACKAGE);
|
|
11390
|
+
} catch {
|
|
11391
|
+
return void 0;
|
|
11392
|
+
}
|
|
11393
|
+
}
|
|
11394
|
+
function installInto(dir) {
|
|
11395
|
+
fs5.mkdirSync(dir, { recursive: true });
|
|
11396
|
+
fs5.writeFileSync(path5.join(dir, "package.json"), '{ "private": true }\n');
|
|
11397
|
+
const isWindows = process.platform === "win32";
|
|
11398
|
+
return new Promise((resolve, reject) => {
|
|
11399
|
+
const child = spawn(isWindows ? "npm.cmd" : "npm", [
|
|
11400
|
+
"install",
|
|
11401
|
+
"--prefix",
|
|
11402
|
+
dir,
|
|
11403
|
+
"--no-save",
|
|
11404
|
+
"--no-audit",
|
|
11405
|
+
"--no-fund",
|
|
11406
|
+
"--loglevel=error",
|
|
11407
|
+
`${DUCKDB_PACKAGE}@${DUCKDB_VERSION}`
|
|
11408
|
+
], { stdio: ["ignore", "ignore", "pipe"], shell: isWindows, timeout: INSTALL_TIMEOUT_MS });
|
|
11409
|
+
let stderr = "";
|
|
11410
|
+
child.stderr?.on("data", (chunk) => {
|
|
11411
|
+
stderr += String(chunk);
|
|
11412
|
+
});
|
|
11413
|
+
child.on("error", reject);
|
|
11414
|
+
child.on("exit", (code) => code === 0 ? resolve() : reject(new Error(`npm install failed (${code}): ${stderr.trim().slice(0, 300)}`)));
|
|
11415
|
+
});
|
|
11416
|
+
}
|
|
11417
|
+
var loading;
|
|
11418
|
+
function loadDuckDb() {
|
|
11419
|
+
loading ??= (async () => {
|
|
11420
|
+
try {
|
|
11421
|
+
const specifier = DUCKDB_PACKAGE;
|
|
11422
|
+
return await import(specifier);
|
|
11423
|
+
} catch {
|
|
11424
|
+
}
|
|
11425
|
+
const dir = duckdbCacheDir();
|
|
11426
|
+
const cached = requireFrom(dir);
|
|
11427
|
+
if (cached)
|
|
11428
|
+
return cached;
|
|
11429
|
+
console.error(`[tinypivot-mcp] Downloading DuckDB ${DUCKDB_VERSION} once into ${dir} for SQL queries...`);
|
|
11430
|
+
await installInto(dir);
|
|
11431
|
+
const installed = requireFrom(dir);
|
|
11432
|
+
if (!installed)
|
|
11433
|
+
throw new Error(`DuckDB installed into ${dir} but could not be loaded.`);
|
|
11434
|
+
return installed;
|
|
11435
|
+
})();
|
|
11436
|
+
loading.catch(() => {
|
|
11437
|
+
loading = void 0;
|
|
11438
|
+
});
|
|
11439
|
+
return loading;
|
|
11440
|
+
}
|
|
11441
|
+
function withinBudget(work, ms) {
|
|
11442
|
+
let timer;
|
|
11443
|
+
const budget = new Promise((resolve) => {
|
|
11444
|
+
timer = setTimeout(resolve, ms, "pending");
|
|
11445
|
+
});
|
|
11446
|
+
return Promise.race([work, budget]).finally(() => clearTimeout(timer));
|
|
11447
|
+
}
|
|
11448
|
+
function quoteLiteral(value2) {
|
|
11449
|
+
if (typeof value2 === "number" || typeof value2 === "boolean")
|
|
11450
|
+
return String(value2);
|
|
11451
|
+
return `'${value2.replace(/'/g, "''")}'`;
|
|
11452
|
+
}
|
|
11453
|
+
function quoteIdentifier(name) {
|
|
11454
|
+
return `"${name.replace(/"/g, '""')}"`;
|
|
11455
|
+
}
|
|
11456
|
+
var QueryRejected = class extends Error {
|
|
11457
|
+
};
|
|
11458
|
+
function toPlainValue(value2) {
|
|
11459
|
+
if (value2 === null || value2 === void 0)
|
|
11460
|
+
return null;
|
|
11461
|
+
if (typeof value2 === "bigint")
|
|
11462
|
+
return Number.isSafeInteger(Number(value2)) ? Number(value2) : value2.toString();
|
|
11463
|
+
if (value2 instanceof Date) {
|
|
11464
|
+
const iso = value2.toISOString();
|
|
11465
|
+
return iso.endsWith("T00:00:00.000Z") ? iso.slice(0, 10) : iso;
|
|
11466
|
+
}
|
|
11467
|
+
if (typeof value2 === "string" || typeof value2 === "number" || typeof value2 === "boolean")
|
|
11468
|
+
return value2;
|
|
11469
|
+
return JSON.stringify(value2, (_key, inner) => typeof inner === "bigint" ? inner.toString() : inner);
|
|
11470
|
+
}
|
|
11471
|
+
var DuckDbRunner = class {
|
|
11472
|
+
constructor(load = loadDuckDb) {
|
|
11473
|
+
this.load = load;
|
|
11474
|
+
}
|
|
11475
|
+
connection;
|
|
11476
|
+
duck;
|
|
11477
|
+
/** Starts loading DuckDB (downloading it if needed) without waiting. */
|
|
11478
|
+
prepare() {
|
|
11479
|
+
this.connection ??= (async () => {
|
|
11480
|
+
this.duck = await this.load();
|
|
11481
|
+
const instance = await this.duck.DuckDBInstance.create(":memory:", {
|
|
11482
|
+
autoinstall_known_extensions: "false",
|
|
11483
|
+
autoload_known_extensions: "false"
|
|
11484
|
+
});
|
|
11485
|
+
const connection = await instance.connect();
|
|
11486
|
+
await connection.run("SET lock_configuration = true");
|
|
11487
|
+
return connection;
|
|
11488
|
+
})();
|
|
11489
|
+
this.connection.catch(() => {
|
|
11490
|
+
this.connection = void 0;
|
|
11491
|
+
});
|
|
11492
|
+
return this.connection;
|
|
11493
|
+
}
|
|
11494
|
+
async run(sql, views, maxRows = QUERY_ROW_LIMIT) {
|
|
11495
|
+
const connection = await this.prepare();
|
|
11496
|
+
const statementTypes = this.duck.StatementType;
|
|
11497
|
+
for (const view of views)
|
|
11498
|
+
await connection.run(`CREATE OR REPLACE TEMP VIEW ${quoteIdentifier(view.name)} AS SELECT * FROM ${view.from}`);
|
|
11499
|
+
const query = sql.trim().replace(/;+\s*$/, "");
|
|
11500
|
+
const extracted = await connection.extractStatements(query);
|
|
11501
|
+
if (extracted.count !== 1)
|
|
11502
|
+
throw new QueryRejected("Send exactly one SELECT statement.");
|
|
11503
|
+
const prepared = await extracted.prepare(0);
|
|
11504
|
+
if (prepared.statementType !== statementTypes.SELECT)
|
|
11505
|
+
throw new QueryRejected("Only SELECT queries can run here: TinyPivot reads data, it never changes it.");
|
|
11506
|
+
const reader = await connection.runAndReadAll(`SELECT * FROM (${query}) AS tinypivot_query LIMIT ${maxRows + 1}`);
|
|
11507
|
+
const rows = reader.getRowObjectsJS().map(
|
|
11508
|
+
(row) => Object.fromEntries(Object.entries(row).map(([key, value2]) => [key, toPlainValue(value2)]))
|
|
11509
|
+
);
|
|
11510
|
+
return { columns: reader.columnNames(), rows: rows.slice(0, maxRows), truncated: rows.length > maxRows };
|
|
11511
|
+
}
|
|
11512
|
+
};
|
|
11513
|
+
|
|
11514
|
+
// src/history.ts
|
|
11515
|
+
import fs6 from "fs";
|
|
11516
|
+
import os5 from "os";
|
|
11517
|
+
import path6 from "path";
|
|
11518
|
+
import zlib from "zlib";
|
|
11519
|
+
var HISTORY_MAX_SAVED_ROWS = 2e5;
|
|
11520
|
+
var DEFAULT_RETENTION_DAYS = 30;
|
|
11521
|
+
function defaultHistoryDir() {
|
|
11522
|
+
const base = process.env.XDG_DATA_HOME || path6.join(os5.homedir(), ".local", "share");
|
|
11523
|
+
return path6.join(base, "tinypivot", "history");
|
|
11524
|
+
}
|
|
11525
|
+
function timestampId(date) {
|
|
11526
|
+
return date.toISOString().replace(/[-:]/g, "").replace("T", "-").replace(".", "-").replace("Z", "");
|
|
11527
|
+
}
|
|
11528
|
+
function slug(text) {
|
|
11529
|
+
return text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "data";
|
|
11530
|
+
}
|
|
11531
|
+
var HistoryStore = class {
|
|
11532
|
+
dir;
|
|
11533
|
+
enabled;
|
|
11534
|
+
retentionDays;
|
|
11535
|
+
constructor(options = {}) {
|
|
11536
|
+
this.dir = options.dir ?? defaultHistoryDir();
|
|
11537
|
+
this.enabled = options.enabled ?? process.env.TINYPIVOT_HISTORY !== "0";
|
|
11538
|
+
const envDays = Number(process.env.TINYPIVOT_HISTORY_DAYS);
|
|
11539
|
+
this.retentionDays = options.retentionDays ?? (Number.isFinite(envDays) && envDays > 0 ? envDays : DEFAULT_RETENTION_DAYS);
|
|
11540
|
+
}
|
|
11541
|
+
/** Saves a pull. Returns the entry, or null when history is off or the write failed. */
|
|
11542
|
+
record(dataset, input, now = /* @__PURE__ */ new Date()) {
|
|
11543
|
+
if (!this.enabled)
|
|
11544
|
+
return null;
|
|
11545
|
+
try {
|
|
11546
|
+
fs6.mkdirSync(this.dir, { recursive: true });
|
|
11547
|
+
const id = `${timestampId(now)}-${slug(dataset.name)}`;
|
|
11548
|
+
const saveRows = input.kind !== "file" && dataset.rows.length <= HISTORY_MAX_SAVED_ROWS;
|
|
11549
|
+
const entry = {
|
|
11550
|
+
id,
|
|
11551
|
+
name: dataset.name,
|
|
11552
|
+
kind: input.kind,
|
|
11553
|
+
createdAt: now.toISOString(),
|
|
11554
|
+
rows: dataset.rows.length,
|
|
11555
|
+
columns: dataset.columns.map((column) => column.name),
|
|
11556
|
+
source: input.source,
|
|
11557
|
+
...input.where?.length ? { where: input.where } : {},
|
|
11558
|
+
...saveRows ? { rowsFile: `${id}.jsonl.gz` } : {},
|
|
11559
|
+
...dataset.chartConfig ? { chartConfig: dataset.chartConfig } : {},
|
|
11560
|
+
...dataset.pivotConfig ? { pivotConfig: dataset.pivotConfig } : {}
|
|
11561
|
+
};
|
|
11562
|
+
if (entry.rowsFile) {
|
|
11563
|
+
const lines = dataset.rows.map((row) => JSON.stringify(row)).join("\n");
|
|
11564
|
+
fs6.writeFileSync(path6.join(this.dir, entry.rowsFile), zlib.gzipSync(lines));
|
|
11565
|
+
}
|
|
11566
|
+
fs6.writeFileSync(path6.join(this.dir, `${id}.json`), `${JSON.stringify(entry, null, 2)}
|
|
11567
|
+
`);
|
|
11568
|
+
return entry;
|
|
11569
|
+
} catch (error) {
|
|
11570
|
+
console.error(`[tinypivot-mcp] Could not save to history: ${error instanceof Error ? error.message : String(error)}`);
|
|
11571
|
+
return null;
|
|
11572
|
+
}
|
|
11573
|
+
}
|
|
11574
|
+
/** Newest first. */
|
|
11575
|
+
list(limit = Number.POSITIVE_INFINITY) {
|
|
11576
|
+
if (!fs6.existsSync(this.dir))
|
|
11577
|
+
return [];
|
|
11578
|
+
return fs6.readdirSync(this.dir).filter((name) => name.endsWith(".json")).sort().reverse().slice(0, limit).flatMap((name) => {
|
|
11579
|
+
try {
|
|
11580
|
+
return [JSON.parse(fs6.readFileSync(path6.join(this.dir, name), "utf8"))];
|
|
11581
|
+
} catch {
|
|
11582
|
+
return [];
|
|
11583
|
+
}
|
|
11584
|
+
});
|
|
11585
|
+
}
|
|
11586
|
+
get(id) {
|
|
11587
|
+
if (!/^[\w-]+$/.test(id))
|
|
11588
|
+
return void 0;
|
|
11589
|
+
const file = path6.join(this.dir, `${id}.json`);
|
|
11590
|
+
return fs6.existsSync(file) ? JSON.parse(fs6.readFileSync(file, "utf8")) : void 0;
|
|
11591
|
+
}
|
|
11592
|
+
/** Full path of an entry's saved rows, for reading back or querying with SQL. */
|
|
11593
|
+
rowsPath(entry) {
|
|
11594
|
+
return entry.rowsFile ? path6.join(this.dir, entry.rowsFile) : void 0;
|
|
11595
|
+
}
|
|
11596
|
+
readRows(entry) {
|
|
11597
|
+
const file = this.rowsPath(entry);
|
|
11598
|
+
if (!file)
|
|
11599
|
+
throw new Error(`History entry ${entry.id} has no saved rows.`);
|
|
11600
|
+
return zlib.gunzipSync(fs6.readFileSync(file)).toString("utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line));
|
|
11601
|
+
}
|
|
11602
|
+
/** Deletes entries older than the retention window. Returns how many were removed. */
|
|
11603
|
+
prune(now = /* @__PURE__ */ new Date()) {
|
|
11604
|
+
if (!fs6.existsSync(this.dir))
|
|
11605
|
+
return 0;
|
|
11606
|
+
const cutoff = now.getTime() - this.retentionDays * 24 * 60 * 60 * 1e3;
|
|
11607
|
+
let removed = 0;
|
|
11608
|
+
for (const entry of this.list()) {
|
|
11609
|
+
if (new Date(entry.createdAt).getTime() >= cutoff)
|
|
11610
|
+
continue;
|
|
11611
|
+
const rows = this.rowsPath(entry);
|
|
11612
|
+
if (rows)
|
|
11613
|
+
fs6.rmSync(rows, { force: true });
|
|
11614
|
+
fs6.rmSync(path6.join(this.dir, `${entry.id}.json`), { force: true });
|
|
11615
|
+
removed++;
|
|
11616
|
+
}
|
|
11617
|
+
return removed;
|
|
11618
|
+
}
|
|
11619
|
+
};
|
|
11620
|
+
function formatHistoryList(entries) {
|
|
11621
|
+
if (entries.length === 0)
|
|
11622
|
+
return "No saved pulls yet.";
|
|
11623
|
+
const lines = entries.map((entry) => {
|
|
11624
|
+
const when = entry.createdAt.slice(0, 16).replace("T", " ");
|
|
11625
|
+
return `\`${entry.id}\` ${when} \xB7 ${entry.name} \xB7 ${entry.rows.toLocaleString("en-US")} rows \xB7 ${entry.kind}`;
|
|
11626
|
+
});
|
|
11627
|
+
return [`Saved pulls (newest first). Reopen one with history({ open: id }):`, ...lines].join("\n");
|
|
11628
|
+
}
|
|
11629
|
+
|
|
11630
|
+
// src/profile.ts
|
|
11631
|
+
var TOP_VALUES = 3;
|
|
11632
|
+
function compactNumber(value2) {
|
|
11633
|
+
return Number.isInteger(value2) ? value2.toLocaleString("en-US") : value2.toLocaleString("en-US", { maximumFractionDigits: 2 });
|
|
11634
|
+
}
|
|
11635
|
+
function percent(part, whole) {
|
|
11636
|
+
if (whole === 0)
|
|
11637
|
+
return "0%";
|
|
11638
|
+
const share = part / whole * 100;
|
|
11639
|
+
return share > 0 && share < 1 ? "<1%" : `${Math.round(share)}%`;
|
|
11640
|
+
}
|
|
11641
|
+
function numberRange(values) {
|
|
11642
|
+
const numbers = values.map(Number).filter(Number.isFinite);
|
|
11643
|
+
if (numbers.length === 0)
|
|
11644
|
+
return "";
|
|
11645
|
+
let min = numbers[0];
|
|
11646
|
+
let max = numbers[0];
|
|
11647
|
+
let sum = 0;
|
|
11648
|
+
for (const value2 of numbers) {
|
|
11649
|
+
min = Math.min(min, value2);
|
|
11650
|
+
max = Math.max(max, value2);
|
|
11651
|
+
sum += value2;
|
|
11652
|
+
}
|
|
11653
|
+
return `${compactNumber(min)} to ${compactNumber(max)}, mean ${compactNumber(sum / numbers.length)}`;
|
|
11654
|
+
}
|
|
11655
|
+
function dateRange(values) {
|
|
11656
|
+
const texts = values.map(String).sort();
|
|
11657
|
+
return texts.length ? `${texts[0]} to ${texts[texts.length - 1]}` : "";
|
|
11658
|
+
}
|
|
11659
|
+
function topValues(values, total) {
|
|
11660
|
+
const counts = /* @__PURE__ */ new Map();
|
|
11661
|
+
for (const value2 of values)
|
|
11662
|
+
counts.set(String(value2), (counts.get(String(value2)) ?? 0) + 1);
|
|
11663
|
+
const top = [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, TOP_VALUES);
|
|
11664
|
+
const listed = top.map(([value2, count]) => `${value2} ${percent(count, total)}`).join(", ");
|
|
11665
|
+
return counts.size > TOP_VALUES ? `${counts.size.toLocaleString("en-US")} values, top: ${listed}` : listed;
|
|
11666
|
+
}
|
|
11667
|
+
function describe({ column, present, values }, total) {
|
|
11668
|
+
const missing = total - present;
|
|
11669
|
+
const parts = [`\`${column.name}\` ${column.type}`];
|
|
11670
|
+
if (missing > 0)
|
|
11671
|
+
parts.push(`${percent(missing, total)} empty`);
|
|
11672
|
+
if (column.type === "number")
|
|
11673
|
+
parts.push(numberRange(values));
|
|
11674
|
+
else if (column.type === "date")
|
|
11675
|
+
parts.push(dateRange(values));
|
|
11676
|
+
else
|
|
11677
|
+
parts.push(topValues(values, present));
|
|
11678
|
+
return parts.filter(Boolean).join(" \xB7 ");
|
|
11679
|
+
}
|
|
11680
|
+
function formatProfile(dataset) {
|
|
11681
|
+
const total = dataset.rows.length;
|
|
11682
|
+
const profiles = dataset.columns.map((column) => {
|
|
11683
|
+
const values = dataset.rows.map((row) => row[column.name]).filter((value2) => value2 !== null && value2 !== void 0 && value2 !== "");
|
|
11684
|
+
return { column, present: values.length, values };
|
|
11685
|
+
});
|
|
11686
|
+
return [
|
|
11687
|
+
`Profile of **${dataset.name}** (\`${dataset.id}\`): ${total.toLocaleString("en-US")} rows.`,
|
|
11688
|
+
...profiles.map((profile) => describe(profile, total))
|
|
11689
|
+
].join("\n");
|
|
11690
|
+
}
|
|
11691
|
+
|
|
11364
11692
|
// src/telemetry.ts
|
|
11365
11693
|
import crypto from "crypto";
|
|
11366
11694
|
import fsSync2 from "fs";
|
|
11367
|
-
import
|
|
11368
|
-
import
|
|
11695
|
+
import os6 from "os";
|
|
11696
|
+
import path7 from "path";
|
|
11369
11697
|
var DEFAULT_TELEMETRY_URL = "https://tiny-pivot.com/api/telemetry";
|
|
11370
|
-
var PACKAGE_VERSION = "0.
|
|
11698
|
+
var PACKAGE_VERSION = "0.3.0";
|
|
11371
11699
|
function isTelemetryEnabled() {
|
|
11372
11700
|
if (process.env.TINYPIVOT_TELEMETRY === "0" || process.env.TINYPIVOT_TELEMETRY === "false")
|
|
11373
11701
|
return false;
|
|
@@ -11387,8 +11715,8 @@ function bucketRowCount(rows) {
|
|
|
11387
11715
|
return "10k+";
|
|
11388
11716
|
}
|
|
11389
11717
|
function getPreferencesPath2() {
|
|
11390
|
-
const base = process.env.XDG_CONFIG_HOME?.trim() ||
|
|
11391
|
-
return
|
|
11718
|
+
const base = process.env.XDG_CONFIG_HOME?.trim() || path7.join(os6.homedir(), ".config");
|
|
11719
|
+
return path7.join(base, "tinypivot", "preferences.json");
|
|
11392
11720
|
}
|
|
11393
11721
|
var cachedAnonId = null;
|
|
11394
11722
|
function getAnonymousId() {
|
|
@@ -11406,7 +11734,7 @@ function getAnonymousId() {
|
|
|
11406
11734
|
const fresh = crypto.randomUUID();
|
|
11407
11735
|
cachedAnonId = fresh;
|
|
11408
11736
|
try {
|
|
11409
|
-
fsSync2.mkdirSync(
|
|
11737
|
+
fsSync2.mkdirSync(path7.dirname(prefPath), { recursive: true });
|
|
11410
11738
|
let existing = {};
|
|
11411
11739
|
try {
|
|
11412
11740
|
existing = JSON.parse(fsSync2.readFileSync(prefPath, "utf8"));
|
|
@@ -11445,14 +11773,18 @@ function recordTelemetry(ev) {
|
|
|
11445
11773
|
// src/server.ts
|
|
11446
11774
|
var APP_RESOURCE_URI = "ui://tinypivot/app.html";
|
|
11447
11775
|
var APP_MIME_TYPE = "text/html;profile=mcp-app";
|
|
11448
|
-
var
|
|
11449
|
-
|
|
11450
|
-
|
|
11451
|
-
|
|
11452
|
-
|
|
11453
|
-
|
|
11454
|
-
|
|
11455
|
-
|
|
11776
|
+
var LOAD_DATA_ROW_GUIDE = 50;
|
|
11777
|
+
function buildInstructions({ reprintCards = true } = {}) {
|
|
11778
|
+
const cards = reprintCards ? "In a terminal, show the returned ```text card verbatim with the Data IDE 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 Data IDE link.";
|
|
11779
|
+
return [
|
|
11780
|
+
"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
|
+
`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
|
+
"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
|
+
"Use keepExisting: true only to compare datasets in one conversation; clear_datasets resets.",
|
|
11784
|
+
cards
|
|
11785
|
+
].join(" ");
|
|
11786
|
+
}
|
|
11787
|
+
var TINYPIVOT_MCP_INSTRUCTIONS = buildInstructions();
|
|
11456
11788
|
var INLINE_PREVIEW_ROW_LIMIT = 200;
|
|
11457
11789
|
var AGGREGATION_VALUES = [
|
|
11458
11790
|
"sum",
|
|
@@ -11480,28 +11812,27 @@ var CHART_TYPE_VALUES = [
|
|
|
11480
11812
|
var CHART_AGG_VALUES = ["sum", "avg", "count", "min", "max"];
|
|
11481
11813
|
var VIEW_MODE_VALUES = ["grid", "pivot", "chart"];
|
|
11482
11814
|
var VISUAL_THEME_VALUES = CHART_THEME_IDS;
|
|
11483
|
-
var VISUAL_THEME_LIST = CHART_THEME_IDS.join(", ");
|
|
11484
11815
|
var pivotValueSchema = z.object({
|
|
11485
|
-
field: z.string()
|
|
11816
|
+
field: z.string(),
|
|
11486
11817
|
aggregation: z.enum(AGGREGATION_VALUES).default("sum")
|
|
11487
11818
|
});
|
|
11488
11819
|
var rowFilterSchema = z.object({
|
|
11489
|
-
field: z.string()
|
|
11490
|
-
equals: z.array(z.union([z.string(), z.number(), z.boolean()])).min(1).describe("Keep rows
|
|
11820
|
+
field: z.string(),
|
|
11821
|
+
equals: z.array(z.union([z.string(), z.number(), z.boolean()])).min(1).describe("Keep rows matching any of these")
|
|
11491
11822
|
});
|
|
11492
11823
|
var pivotConfigSchema = z.object({
|
|
11493
|
-
rowFields: z.array(z.string()).default([])
|
|
11494
|
-
columnFields: z.array(z.string()).default([])
|
|
11495
|
-
valueFields: z.array(pivotValueSchema).default([])
|
|
11824
|
+
rowFields: z.array(z.string()).default([]),
|
|
11825
|
+
columnFields: z.array(z.string()).default([]),
|
|
11826
|
+
valueFields: z.array(pivotValueSchema).default([]),
|
|
11496
11827
|
showRowTotals: z.boolean().default(true),
|
|
11497
11828
|
showColumnTotals: z.boolean().default(true)
|
|
11498
11829
|
});
|
|
11499
11830
|
var chartConfigSchema = z.object({
|
|
11500
11831
|
type: z.enum(CHART_TYPE_VALUES).default("bar"),
|
|
11501
|
-
xAxisField: z.string().describe("
|
|
11502
|
-
yAxisField: z.string().describe("
|
|
11503
|
-
aggregation: z.enum(CHART_AGG_VALUES).default("sum")
|
|
11504
|
-
seriesField: z.string().optional().describe("
|
|
11832
|
+
xAxisField: z.string().describe("Category or date column"),
|
|
11833
|
+
yAxisField: z.string().describe("Column to aggregate"),
|
|
11834
|
+
aggregation: z.enum(CHART_AGG_VALUES).default("sum"),
|
|
11835
|
+
seriesField: z.string().optional().describe("Column to split into series"),
|
|
11505
11836
|
title: z.string().optional()
|
|
11506
11837
|
});
|
|
11507
11838
|
function extractSessionKey(extra) {
|
|
@@ -11530,6 +11861,23 @@ function clientSupportsMcpAppsUi(capabilities) {
|
|
|
11530
11861
|
function initialViewMode(requested, hasPivot, hasChart) {
|
|
11531
11862
|
return requested ?? (hasPivot && !hasChart ? "pivot" : "chart");
|
|
11532
11863
|
}
|
|
11864
|
+
function normalizePivot(pivotConfig) {
|
|
11865
|
+
return {
|
|
11866
|
+
...pivotConfig,
|
|
11867
|
+
valueFields: pivotConfig.valueFields.map((v) => ({ field: v.field, aggregation: v.aggregation }))
|
|
11868
|
+
};
|
|
11869
|
+
}
|
|
11870
|
+
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
|
+
}
|
|
11533
11881
|
function toCoreChartConfig(input) {
|
|
11534
11882
|
return {
|
|
11535
11883
|
type: input.type,
|
|
@@ -11555,7 +11903,7 @@ function buildAppPayload(dataset, store, options) {
|
|
|
11555
11903
|
const summaryTokens = Math.round(summaryBytes / 4);
|
|
11556
11904
|
const defaultTurnBypass = dataset.ingestionMode === "direct" ? Math.max(0, dataset.estimatedDatasetTokens - summaryTokens) : 0;
|
|
11557
11905
|
const turnTokensSaved = options.overrideTurnTokensSaved ?? defaultTurnBypass;
|
|
11558
|
-
const sessionSavings = options.recordTurn !== false ? store.recordTurnSavings(turnTokensSaved
|
|
11906
|
+
const sessionSavings = options.recordTurn !== false ? store.recordTurnSavings(turnTokensSaved) : store.getSessionSavings();
|
|
11559
11907
|
const turnUsdSaved = tokensToUsd(turnTokensSaved, sessionSavings.model.ratePerMillion);
|
|
11560
11908
|
const validMcpKey = isMcpLicenseKey(options.licenseKey) ? options.licenseKey : null;
|
|
11561
11909
|
const isPro2 = Boolean(validMcpKey || options.demoToken);
|
|
@@ -11591,16 +11939,16 @@ function buildAppPayload(dataset, store, options) {
|
|
|
11591
11939
|
}
|
|
11592
11940
|
async function loadAppHtml(customPath) {
|
|
11593
11941
|
const envPath = process.env.TINYPIVOT_MCP_APP_HTML;
|
|
11594
|
-
const here =
|
|
11942
|
+
const here = path8.dirname(fileURLToPath2(import.meta.url));
|
|
11595
11943
|
const candidates = [
|
|
11596
11944
|
customPath,
|
|
11597
11945
|
envPath,
|
|
11598
|
-
|
|
11599
|
-
|
|
11946
|
+
path8.resolve(here, "app/index.html"),
|
|
11947
|
+
path8.resolve(here, "../dist/app/index.html")
|
|
11600
11948
|
].filter((p) => Boolean(p));
|
|
11601
11949
|
for (const candidate of candidates) {
|
|
11602
11950
|
try {
|
|
11603
|
-
const html = await
|
|
11951
|
+
const html = await fs7.readFile(candidate, "utf8");
|
|
11604
11952
|
if (html.trim().length > 0)
|
|
11605
11953
|
return html;
|
|
11606
11954
|
} catch {
|
|
@@ -11621,10 +11969,10 @@ function resolveLicenseKey(explicit) {
|
|
|
11621
11969
|
return explicit.trim();
|
|
11622
11970
|
if (process.env.TINYPIVOT_LICENSE_KEY?.trim())
|
|
11623
11971
|
return process.env.TINYPIVOT_LICENSE_KEY.trim();
|
|
11624
|
-
const here =
|
|
11972
|
+
const here = path8.dirname(fileURLToPath2(import.meta.url));
|
|
11625
11973
|
const candidates = [
|
|
11626
|
-
|
|
11627
|
-
|
|
11974
|
+
path8.resolve(here, "../.license"),
|
|
11975
|
+
path8.resolve(here, ".license")
|
|
11628
11976
|
];
|
|
11629
11977
|
for (const file of candidates) {
|
|
11630
11978
|
try {
|
|
@@ -11652,6 +12000,8 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11652
12000
|
const notifyCompanion = () => {
|
|
11653
12001
|
options.onStateChanged?.();
|
|
11654
12002
|
};
|
|
12003
|
+
const reprintCards = options.reprintCards ?? process.env.TINYPIVOT_REPRINT_CARDS !== "0";
|
|
12004
|
+
const cardFormat = { showBranding: !isPro2, reprintNote: reprintCards };
|
|
11655
12005
|
const postgresConfig = options.postgres ?? (process.env.DATABASE_URL ? {
|
|
11656
12006
|
connectionString: process.env.DATABASE_URL,
|
|
11657
12007
|
allowedTables: process.env.TINYPIVOT_ALLOWED_TABLES ? process.env.TINYPIVOT_ALLOWED_TABLES.split(",").map((s) => s.trim()).filter(Boolean) : void 0
|
|
@@ -11659,14 +12009,14 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11659
12009
|
const server = new McpServer(
|
|
11660
12010
|
{
|
|
11661
12011
|
name: "tinypivot",
|
|
11662
|
-
version: "0.
|
|
12012
|
+
version: "0.3.0"
|
|
11663
12013
|
},
|
|
11664
12014
|
{
|
|
11665
12015
|
capabilities: {
|
|
11666
12016
|
resources: {},
|
|
11667
12017
|
tools: {}
|
|
11668
12018
|
},
|
|
11669
|
-
instructions:
|
|
12019
|
+
instructions: buildInstructions({ reprintCards })
|
|
11670
12020
|
}
|
|
11671
12021
|
);
|
|
11672
12022
|
const clientRendersWidget = () => clientSupportsMcpAppsUi(server.server.getClientCapabilities());
|
|
@@ -11684,6 +12034,39 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11684
12034
|
const content = [{ type: "text", text: summaryText }];
|
|
11685
12035
|
return clientRendersWidget() ? { content, structuredContent: payload } : { content };
|
|
11686
12036
|
};
|
|
12037
|
+
const replyWithDataset = async (ds, sessionKey, tool, note = "") => {
|
|
12038
|
+
const liveCompanionUrl = await resolveCompanionUrlForTool();
|
|
12039
|
+
const summaryText = `${formatDatasetSummary(ds, liveCompanionUrl, cardFormat)}${note}`;
|
|
12040
|
+
const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, sessionKey });
|
|
12041
|
+
recordTelemetry({
|
|
12042
|
+
event: "tool_call",
|
|
12043
|
+
tool,
|
|
12044
|
+
rowBucket: bucketRowCount(ds.sourceTotalRows),
|
|
12045
|
+
client: getClientName(),
|
|
12046
|
+
tier,
|
|
12047
|
+
truncated: ds.truncatedForFreeTier
|
|
12048
|
+
});
|
|
12049
|
+
notifyCompanion();
|
|
12050
|
+
return dataToolResult(summaryText, payload);
|
|
12051
|
+
};
|
|
12052
|
+
const history = options.history ?? new HistoryStore();
|
|
12053
|
+
try {
|
|
12054
|
+
history.prune();
|
|
12055
|
+
} catch (error) {
|
|
12056
|
+
console.error(`[tinypivot-mcp] Could not prune history: ${error instanceof Error ? error.message : String(error)}`);
|
|
12057
|
+
}
|
|
12058
|
+
const pullsByDataset = /* @__PURE__ */ new Map();
|
|
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
|
+
});
|
|
11687
12070
|
const widgetOnlyTools = [];
|
|
11688
12071
|
const widgetOnly = (tool) => {
|
|
11689
12072
|
widgetOnlyTools.push(tool);
|
|
@@ -11770,16 +12153,15 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11770
12153
|
"open_tinypivot",
|
|
11771
12154
|
{
|
|
11772
12155
|
title: "Open TinyPivot",
|
|
11773
|
-
description: "Open the
|
|
12156
|
+
description: "Open the TinyPivot Data IDE (grid, pivot, chart). Shows sample data when nothing is loaded.",
|
|
11774
12157
|
inputSchema: {
|
|
11775
|
-
datasetId: z.string().optional()
|
|
11776
|
-
viewMode: z.enum(VIEW_MODE_VALUES).optional()
|
|
11777
|
-
|
|
11778
|
-
openBrowser: z.boolean().optional().describe("Set true to explicitly start the localhost Companion Data IDE URL even inside MCP Apps-capable hosts")
|
|
12158
|
+
datasetId: z.string().optional(),
|
|
12159
|
+
viewMode: z.enum(VIEW_MODE_VALUES).optional(),
|
|
12160
|
+
openBrowser: z.boolean().optional().describe("Also start the localhost Data IDE in hosts with an inline widget")
|
|
11779
12161
|
},
|
|
11780
12162
|
_meta: PANE_UI_META
|
|
11781
12163
|
},
|
|
11782
|
-
async ({ datasetId, viewMode,
|
|
12164
|
+
async ({ datasetId, viewMode, openBrowser }, extra) => {
|
|
11783
12165
|
const sessionKey = extractSessionKey(extra) ?? DEFAULT_SESSION_KEY;
|
|
11784
12166
|
const ds = store.get(datasetId, sessionKey);
|
|
11785
12167
|
if (!ds) {
|
|
@@ -11794,8 +12176,8 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11794
12176
|
store.setActive(ds.id, sessionKey);
|
|
11795
12177
|
}
|
|
11796
12178
|
const liveCompanionUrl = await resolveCompanionUrlForTool(Boolean(openBrowser));
|
|
11797
|
-
const summaryText = formatDatasetSummary(ds, liveCompanionUrl,
|
|
11798
|
-
const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText,
|
|
12179
|
+
const summaryText = formatDatasetSummary(ds, liveCompanionUrl, cardFormat);
|
|
12180
|
+
const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, sessionKey });
|
|
11799
12181
|
recordTelemetry({
|
|
11800
12182
|
event: "tool_call",
|
|
11801
12183
|
tool: "open_tinypivot",
|
|
@@ -11812,32 +12194,26 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11812
12194
|
"load_file",
|
|
11813
12195
|
{
|
|
11814
12196
|
title: "Load Data File into TinyPivot",
|
|
11815
|
-
description: "
|
|
12197
|
+
description: "Chart or pivot a local CSV, TSV, JSON or JSONL file without reading it: the rows stay out of your context.",
|
|
11816
12198
|
inputSchema: {
|
|
11817
|
-
filePath: z.string()
|
|
11818
|
-
name: z.string().optional()
|
|
11819
|
-
where: z.array(rowFilterSchema).optional().describe('Keep only rows
|
|
11820
|
-
viewMode: z.enum(VIEW_MODE_VALUES).optional()
|
|
11821
|
-
pivotConfig: pivotConfigSchema.optional()
|
|
11822
|
-
chartConfig: chartConfigSchema.optional()
|
|
11823
|
-
|
|
11824
|
-
keepExisting: z.boolean().optional().describe("Set true to keep previously loaded datasets in this chat switcher (for multi-dataset comparisons in the same conversation). Omit to start clean on shared hosts.")
|
|
12199
|
+
filePath: z.string(),
|
|
12200
|
+
name: z.string().optional(),
|
|
12201
|
+
where: z.array(rowFilterSchema).optional().describe('Keep only matching rows, e.g. [{"field":"year","equals":[2026]}]'),
|
|
12202
|
+
viewMode: z.enum(VIEW_MODE_VALUES).optional(),
|
|
12203
|
+
pivotConfig: pivotConfigSchema.optional(),
|
|
12204
|
+
chartConfig: chartConfigSchema.optional(),
|
|
12205
|
+
keepExisting: z.boolean().optional().describe("Keep earlier datasets loaded, to compare them")
|
|
11825
12206
|
},
|
|
11826
12207
|
_meta: INLINE_UI_META
|
|
11827
12208
|
},
|
|
11828
|
-
async ({ filePath, name, where, viewMode, pivotConfig, chartConfig,
|
|
12209
|
+
async ({ filePath, name, where, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
|
|
11829
12210
|
try {
|
|
11830
12211
|
const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
|
|
11831
12212
|
const ds = await store.loadFromFile(filePath, name, { sessionKey, keepExisting: shouldKeep, where });
|
|
12213
|
+
remember(ds, { kind: "file", source: ds.source, where });
|
|
11832
12214
|
const explicitChart = chartConfig ? toCoreChartConfig(chartConfig) : void 0;
|
|
11833
12215
|
if (pivotConfig) {
|
|
11834
|
-
const normalizedPivot =
|
|
11835
|
-
...pivotConfig,
|
|
11836
|
-
valueFields: pivotConfig.valueFields.map((v) => ({
|
|
11837
|
-
field: v.field,
|
|
11838
|
-
aggregation: v.aggregation
|
|
11839
|
-
}))
|
|
11840
|
-
};
|
|
12216
|
+
const normalizedPivot = normalizePivot(pivotConfig);
|
|
11841
12217
|
store.updateView(ds.id, {
|
|
11842
12218
|
viewMode: initialViewMode(viewMode, true, Boolean(explicitChart)),
|
|
11843
12219
|
pivotConfig: normalizedPivot,
|
|
@@ -11849,19 +12225,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11849
12225
|
...explicitChart ? { chartConfig: explicitChart } : {}
|
|
11850
12226
|
}, sessionKey);
|
|
11851
12227
|
}
|
|
11852
|
-
|
|
11853
|
-
const summaryText = formatDatasetSummary(ds, liveCompanionUrl, { showBranding: !isPro2 });
|
|
11854
|
-
const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, model, sessionKey });
|
|
11855
|
-
recordTelemetry({
|
|
11856
|
-
event: "tool_call",
|
|
11857
|
-
tool: "load_file",
|
|
11858
|
-
rowBucket: bucketRowCount(ds.sourceTotalRows),
|
|
11859
|
-
client: getClientName(),
|
|
11860
|
-
tier,
|
|
11861
|
-
truncated: ds.truncatedForFreeTier
|
|
11862
|
-
});
|
|
11863
|
-
notifyCompanion();
|
|
11864
|
-
return dataToolResult(summaryText, payload);
|
|
12228
|
+
return replyWithDataset(ds, sessionKey, "load_file");
|
|
11865
12229
|
} catch (err) {
|
|
11866
12230
|
return {
|
|
11867
12231
|
isError: true,
|
|
@@ -11874,71 +12238,51 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11874
12238
|
"load_data",
|
|
11875
12239
|
{
|
|
11876
12240
|
title: "Load JSON Rows into TinyPivot",
|
|
11877
|
-
description: "
|
|
12241
|
+
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.",
|
|
11878
12242
|
inputSchema: {
|
|
11879
|
-
name: z.string()
|
|
11880
|
-
rows: z.array(z.record(z.string(), z.unknown()))
|
|
11881
|
-
source: z.string().optional()
|
|
11882
|
-
viewMode: z.enum(VIEW_MODE_VALUES).optional()
|
|
11883
|
-
pivotConfig: pivotConfigSchema.optional()
|
|
12243
|
+
name: z.string(),
|
|
12244
|
+
rows: z.array(z.record(z.string(), z.unknown())),
|
|
12245
|
+
source: z.string().optional(),
|
|
12246
|
+
viewMode: z.enum(VIEW_MODE_VALUES).optional(),
|
|
12247
|
+
pivotConfig: pivotConfigSchema.optional(),
|
|
11884
12248
|
chartConfig: chartConfigSchema.optional(),
|
|
11885
|
-
|
|
11886
|
-
keepExisting: z.boolean().optional().describe("Set true to keep previously loaded datasets in this chat switcher (for multi-dataset comparisons in the same conversation). Omit to start clean on shared hosts.")
|
|
12249
|
+
keepExisting: z.boolean().optional().describe("Keep earlier datasets loaded, to compare them")
|
|
11887
12250
|
},
|
|
11888
12251
|
_meta: INLINE_UI_META
|
|
11889
12252
|
},
|
|
11890
|
-
async ({ name, rows, source, viewMode, pivotConfig, chartConfig,
|
|
12253
|
+
async ({ name, rows, source, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
|
|
11891
12254
|
const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
|
|
11892
|
-
const normalizedPivot = pivotConfig ? {
|
|
11893
|
-
...pivotConfig,
|
|
11894
|
-
valueFields: pivotConfig.valueFields.map((v) => ({
|
|
11895
|
-
field: v.field,
|
|
11896
|
-
aggregation: v.aggregation
|
|
11897
|
-
}))
|
|
11898
|
-
} : void 0;
|
|
11899
12255
|
const ds = store.register({
|
|
11900
12256
|
name,
|
|
11901
12257
|
source: source ?? "inline JSON",
|
|
11902
12258
|
ingestionMode: "inline",
|
|
11903
12259
|
rows,
|
|
11904
12260
|
viewMode: initialViewMode(viewMode, Boolean(pivotConfig), Boolean(chartConfig)),
|
|
11905
|
-
pivotConfig:
|
|
12261
|
+
pivotConfig: pivotConfig ? normalizePivot(pivotConfig) : void 0,
|
|
11906
12262
|
chartConfig: chartConfig ? toCoreChartConfig(chartConfig) : void 0,
|
|
11907
12263
|
sessionKey,
|
|
11908
12264
|
keepExisting: shouldKeep
|
|
11909
12265
|
});
|
|
11910
|
-
|
|
11911
|
-
|
|
11912
|
-
const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, model, sessionKey });
|
|
11913
|
-
recordTelemetry({
|
|
11914
|
-
event: "tool_call",
|
|
11915
|
-
tool: "load_data",
|
|
11916
|
-
rowBucket: bucketRowCount(ds.sourceTotalRows),
|
|
11917
|
-
client: getClientName(),
|
|
11918
|
-
tier,
|
|
11919
|
-
truncated: ds.truncatedForFreeTier
|
|
11920
|
-
});
|
|
11921
|
-
notifyCompanion();
|
|
11922
|
-
return dataToolResult(summaryText, payload);
|
|
12266
|
+
remember(ds, { kind: "data", source: source ?? "inline JSON" });
|
|
12267
|
+
return replyWithDataset(ds, sessionKey, "load_data");
|
|
11923
12268
|
}
|
|
11924
12269
|
);
|
|
11925
12270
|
server.registerTool(
|
|
11926
12271
|
"configure_pivot",
|
|
11927
12272
|
{
|
|
11928
12273
|
title: "Configure Pivot Table",
|
|
11929
|
-
description: "
|
|
12274
|
+
description: "Pivot the active dataset. Aggregations are exact; percentOfTotal divides by the grand total.",
|
|
11930
12275
|
inputSchema: {
|
|
11931
|
-
datasetId: z.string().optional()
|
|
11932
|
-
rowFields: z.array(z.string()).default([])
|
|
11933
|
-
columnFields: z.array(z.string()).default([])
|
|
11934
|
-
valueFields: z.array(pivotValueSchema).min(1)
|
|
12276
|
+
datasetId: z.string().optional(),
|
|
12277
|
+
rowFields: z.array(z.string()).default([]),
|
|
12278
|
+
columnFields: z.array(z.string()).default([]),
|
|
12279
|
+
valueFields: z.array(pivotValueSchema).min(1),
|
|
11935
12280
|
showRowTotals: z.boolean().default(true),
|
|
11936
|
-
showColumnTotals: z.boolean().default(true)
|
|
11937
|
-
model: z.string().optional().describe("Active LLM model name for dollarized token savings")
|
|
12281
|
+
showColumnTotals: z.boolean().default(true)
|
|
11938
12282
|
},
|
|
11939
12283
|
_meta: INLINE_UI_META
|
|
11940
12284
|
},
|
|
11941
|
-
async ({ datasetId, rowFields, columnFields, valueFields, showRowTotals, showColumnTotals
|
|
12285
|
+
async ({ datasetId, rowFields, columnFields, valueFields, showRowTotals, showColumnTotals }, extra) => {
|
|
11942
12286
|
const sessionKey = extractSessionKey(extra) ?? DEFAULT_SESSION_KEY;
|
|
11943
12287
|
const ds = store.get(datasetId, sessionKey);
|
|
11944
12288
|
if (!ds) {
|
|
@@ -11963,13 +12307,12 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11963
12307
|
chartConfig: chartConfigFromPivot(fullPivotConfig, ds.name) ?? ds.chartConfig
|
|
11964
12308
|
}, sessionKey);
|
|
11965
12309
|
const liveCompanionUrl = await resolveCompanionUrlForTool();
|
|
11966
|
-
const summary = formatPivotSummary(ds, fullPivotConfig, liveCompanionUrl,
|
|
12310
|
+
const summary = formatPivotSummary(ds, fullPivotConfig, liveCompanionUrl, cardFormat);
|
|
11967
12311
|
const pivotTokensSaved = Math.max(0, ds.estimatedDatasetTokens - Math.round(Buffer.byteLength(summary, "utf8") / 4));
|
|
11968
12312
|
const payload = buildAppPayload(ds, store, {
|
|
11969
12313
|
licenseKey,
|
|
11970
12314
|
demoToken,
|
|
11971
12315
|
summaryText: summary,
|
|
11972
|
-
model,
|
|
11973
12316
|
overrideTurnTokensSaved: pivotTokensSaved,
|
|
11974
12317
|
sessionKey
|
|
11975
12318
|
});
|
|
@@ -11989,21 +12332,20 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11989
12332
|
"configure_chart",
|
|
11990
12333
|
{
|
|
11991
12334
|
title: "Configure Chart",
|
|
11992
|
-
description: "
|
|
12335
|
+
description: "Chart the active dataset.",
|
|
11993
12336
|
inputSchema: {
|
|
11994
|
-
datasetId: z.string().optional()
|
|
12337
|
+
datasetId: z.string().optional(),
|
|
11995
12338
|
type: z.enum(CHART_TYPE_VALUES).default("bar"),
|
|
11996
12339
|
xAxisField: z.string(),
|
|
11997
12340
|
yAxisField: z.string(),
|
|
11998
12341
|
aggregation: z.enum(CHART_AGG_VALUES).default("sum"),
|
|
11999
12342
|
seriesField: z.string().optional(),
|
|
12000
12343
|
title: z.string().optional(),
|
|
12001
|
-
chartTheme: z.enum(VISUAL_THEME_VALUES).optional()
|
|
12002
|
-
model: z.string().optional().describe("Active LLM model name for dollarized token savings")
|
|
12344
|
+
chartTheme: z.enum(VISUAL_THEME_VALUES).optional()
|
|
12003
12345
|
},
|
|
12004
12346
|
_meta: INLINE_UI_META
|
|
12005
12347
|
},
|
|
12006
|
-
async ({ datasetId, type, xAxisField, yAxisField, aggregation, seriesField, title, chartTheme
|
|
12348
|
+
async ({ datasetId, type, xAxisField, yAxisField, aggregation, seriesField, title, chartTheme }, extra) => {
|
|
12007
12349
|
const sessionKey = extractSessionKey(extra) ?? DEFAULT_SESSION_KEY;
|
|
12008
12350
|
const ds = store.get(datasetId, sessionKey);
|
|
12009
12351
|
if (!ds) {
|
|
@@ -12039,14 +12381,13 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12039
12381
|
if (asciiChart)
|
|
12040
12382
|
summaryParts.push("", asciiChart);
|
|
12041
12383
|
if (liveCompanionUrl)
|
|
12042
|
-
summaryParts.push(
|
|
12384
|
+
summaryParts.push(`Data IDE: ${liveCompanionUrl}`);
|
|
12043
12385
|
const summaryText = summaryParts.join("\n");
|
|
12044
12386
|
const chartTokensSaved = Math.max(0, ds.estimatedDatasetTokens - Math.round(Buffer.byteLength(summaryText, "utf8") / 4));
|
|
12045
12387
|
const payload = buildAppPayload(ds, store, {
|
|
12046
12388
|
licenseKey,
|
|
12047
12389
|
demoToken,
|
|
12048
12390
|
summaryText,
|
|
12049
|
-
model,
|
|
12050
12391
|
overrideTurnTokensSaved: chartTokensSaved,
|
|
12051
12392
|
sessionKey
|
|
12052
12393
|
});
|
|
@@ -12062,75 +12403,144 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12062
12403
|
return dataToolResult(summaryText, payload);
|
|
12063
12404
|
}
|
|
12064
12405
|
);
|
|
12406
|
+
if (postgresConfig) {
|
|
12407
|
+
server.registerTool(
|
|
12408
|
+
"query_postgres",
|
|
12409
|
+
{
|
|
12410
|
+
title: "Query PostgreSQL Directly (Read-Only, Pro)",
|
|
12411
|
+
description: "Run a read-only SELECT on the configured Postgres database and chart the result.",
|
|
12412
|
+
inputSchema: {
|
|
12413
|
+
sql: z.string(),
|
|
12414
|
+
name: z.string().optional(),
|
|
12415
|
+
viewMode: z.enum(VIEW_MODE_VALUES).optional(),
|
|
12416
|
+
pivotConfig: pivotConfigSchema.optional(),
|
|
12417
|
+
keepExisting: z.boolean().optional().describe("Keep earlier datasets loaded, to compare them")
|
|
12418
|
+
},
|
|
12419
|
+
_meta: INLINE_UI_META
|
|
12420
|
+
},
|
|
12421
|
+
async ({ sql, name, viewMode, pivotConfig, keepExisting }, extra) => {
|
|
12422
|
+
if (!isPro2) {
|
|
12423
|
+
return {
|
|
12424
|
+
isError: true,
|
|
12425
|
+
content: [{
|
|
12426
|
+
type: "text",
|
|
12427
|
+
text: "Read-only PostgreSQL querying (`query_postgres`) requires a TinyPivot Pro license (TINYPIVOT_LICENSE_KEY). Free tier includes local CSV/TSV/JSON files and inline data up to 2,500 rows. Upgrade at https://tiny-pivot.com/pricing"
|
|
12428
|
+
}]
|
|
12429
|
+
};
|
|
12430
|
+
}
|
|
12431
|
+
try {
|
|
12432
|
+
const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
|
|
12433
|
+
const res = await executeReadOnlyPostgresQuery(postgresConfig, sql);
|
|
12434
|
+
const ds = store.register({
|
|
12435
|
+
name: name ?? "PostgreSQL Query",
|
|
12436
|
+
source: "postgresql",
|
|
12437
|
+
ingestionMode: "direct",
|
|
12438
|
+
rows: res.rows,
|
|
12439
|
+
viewMode: initialViewMode(viewMode, Boolean(pivotConfig), false),
|
|
12440
|
+
pivotConfig: pivotConfig ? normalizePivot(pivotConfig) : void 0,
|
|
12441
|
+
sessionKey,
|
|
12442
|
+
keepExisting: shouldKeep
|
|
12443
|
+
});
|
|
12444
|
+
remember(ds, { kind: "postgres", source: sql });
|
|
12445
|
+
return replyWithDataset(ds, sessionKey, "query_postgres", res.truncated ? " (capped at max rows)" : "");
|
|
12446
|
+
} catch (err) {
|
|
12447
|
+
return {
|
|
12448
|
+
isError: true,
|
|
12449
|
+
content: [{ type: "text", text: `PostgreSQL query failed: ${err instanceof Error ? err.message : String(err)}` }]
|
|
12450
|
+
};
|
|
12451
|
+
}
|
|
12452
|
+
}
|
|
12453
|
+
);
|
|
12454
|
+
}
|
|
12065
12455
|
server.registerTool(
|
|
12066
|
-
"
|
|
12456
|
+
"query",
|
|
12067
12457
|
{
|
|
12068
|
-
title: "Query
|
|
12069
|
-
description: "
|
|
12458
|
+
title: "Query Files with SQL",
|
|
12459
|
+
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.",
|
|
12070
12460
|
inputSchema: {
|
|
12071
|
-
sql: z.string()
|
|
12072
|
-
name: z.string().optional()
|
|
12461
|
+
sql: z.string(),
|
|
12462
|
+
name: z.string().optional(),
|
|
12073
12463
|
viewMode: z.enum(VIEW_MODE_VALUES).optional(),
|
|
12074
12464
|
pivotConfig: pivotConfigSchema.optional(),
|
|
12075
|
-
|
|
12076
|
-
keepExisting: z.boolean().optional().describe("
|
|
12465
|
+
chartConfig: chartConfigSchema.optional(),
|
|
12466
|
+
keepExisting: z.boolean().optional().describe("Keep earlier datasets loaded, to compare them")
|
|
12077
12467
|
},
|
|
12078
12468
|
_meta: INLINE_UI_META
|
|
12079
12469
|
},
|
|
12080
|
-
async ({ sql, name, viewMode, pivotConfig,
|
|
12081
|
-
|
|
12082
|
-
return {
|
|
12083
|
-
isError: true,
|
|
12084
|
-
content: [{
|
|
12085
|
-
type: "text",
|
|
12086
|
-
text: "Read-only PostgreSQL querying (`query_postgres`) requires a TinyPivot Pro license (TINYPIVOT_LICENSE_KEY). Free tier includes local CSV/TSV/JSON files and inline data up to 2,500 rows. Upgrade at https://tiny-pivot.com/pricing"
|
|
12087
|
-
}]
|
|
12088
|
-
};
|
|
12089
|
-
}
|
|
12090
|
-
if (!postgresConfig) {
|
|
12091
|
-
return {
|
|
12092
|
-
isError: true,
|
|
12093
|
-
content: [{ type: "text", text: "PostgreSQL is not configured. Set the DATABASE_URL environment variable when launching tinypivot-mcp." }]
|
|
12094
|
-
};
|
|
12095
|
-
}
|
|
12470
|
+
async ({ sql, name, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
|
|
12471
|
+
const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
|
|
12096
12472
|
try {
|
|
12097
|
-
|
|
12098
|
-
|
|
12473
|
+
if (await withinBudget(duck.prepare(), DUCKDB_WAIT_MS) === "pending") {
|
|
12474
|
+
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
|
+
}
|
|
12476
|
+
const result = await duck.run(sql, queryViews(sessionKey));
|
|
12099
12477
|
const ds = store.register({
|
|
12100
|
-
name: name ?? "
|
|
12101
|
-
source:
|
|
12478
|
+
name: name ?? "SQL query",
|
|
12479
|
+
source: sql,
|
|
12102
12480
|
ingestionMode: "direct",
|
|
12103
|
-
rows:
|
|
12104
|
-
viewMode: initialViewMode(viewMode, Boolean(pivotConfig),
|
|
12105
|
-
pivotConfig: pivotConfig ?
|
|
12106
|
-
|
|
12107
|
-
valueFields: pivotConfig.valueFields.map((v) => ({
|
|
12108
|
-
field: v.field,
|
|
12109
|
-
aggregation: v.aggregation
|
|
12110
|
-
}))
|
|
12111
|
-
} : void 0,
|
|
12481
|
+
rows: result.rows,
|
|
12482
|
+
viewMode: initialViewMode(viewMode, Boolean(pivotConfig), Boolean(chartConfig)),
|
|
12483
|
+
pivotConfig: pivotConfig ? normalizePivot(pivotConfig) : void 0,
|
|
12484
|
+
chartConfig: chartConfig ? toCoreChartConfig(chartConfig) : void 0,
|
|
12112
12485
|
sessionKey,
|
|
12113
12486
|
keepExisting: shouldKeep
|
|
12114
12487
|
});
|
|
12115
|
-
|
|
12116
|
-
|
|
12117
|
-
|
|
12118
|
-
|
|
12119
|
-
|
|
12120
|
-
|
|
12121
|
-
|
|
12122
|
-
|
|
12123
|
-
|
|
12124
|
-
|
|
12125
|
-
|
|
12126
|
-
|
|
12127
|
-
|
|
12128
|
-
|
|
12129
|
-
|
|
12130
|
-
|
|
12131
|
-
|
|
12132
|
-
|
|
12133
|
-
|
|
12488
|
+
remember(ds, { kind: "query", source: sql });
|
|
12489
|
+
return replyWithDataset(ds, sessionKey, "query", result.truncated ? `
|
|
12490
|
+
_Result cut at ${result.rows.length.toLocaleString("en-US")} rows._` : "");
|
|
12491
|
+
} catch (error) {
|
|
12492
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
12493
|
+
return { isError: true, content: [{ type: "text", text: error instanceof QueryRejected ? message : `Query failed: ${message}` }] };
|
|
12494
|
+
}
|
|
12495
|
+
}
|
|
12496
|
+
);
|
|
12497
|
+
server.registerTool(
|
|
12498
|
+
"profile",
|
|
12499
|
+
{
|
|
12500
|
+
title: "Profile Dataset",
|
|
12501
|
+
description: "Describe each column of a loaded dataset: empty share, number and date ranges, commonest values.",
|
|
12502
|
+
inputSchema: {
|
|
12503
|
+
datasetId: z.string().optional()
|
|
12504
|
+
}
|
|
12505
|
+
},
|
|
12506
|
+
async ({ datasetId }, extra) => {
|
|
12507
|
+
const { sessionKey } = resolveSessionContext(extra);
|
|
12508
|
+
const ds = store.get(datasetId, sessionKey);
|
|
12509
|
+
if (!ds)
|
|
12510
|
+
return { isError: true, content: [{ type: "text", text: `Dataset "${datasetId ?? "(active)"}" not found.` }] };
|
|
12511
|
+
return { content: [{ type: "text", text: formatProfile(ds) }] };
|
|
12512
|
+
}
|
|
12513
|
+
);
|
|
12514
|
+
server.registerTool(
|
|
12515
|
+
"history",
|
|
12516
|
+
{
|
|
12517
|
+
title: "Saved Pulls",
|
|
12518
|
+
description: "List data pulled in earlier sessions, or reopen one by id at no cost: nothing is re-queried.",
|
|
12519
|
+
inputSchema: {
|
|
12520
|
+
open: z.string().optional(),
|
|
12521
|
+
limit: z.number().int().min(1).max(100).optional()
|
|
12522
|
+
},
|
|
12523
|
+
_meta: INLINE_UI_META
|
|
12524
|
+
},
|
|
12525
|
+
async ({ open, limit }, extra) => {
|
|
12526
|
+
if (!history.enabled)
|
|
12527
|
+
return { content: [{ type: "text", text: "History is off (TINYPIVOT_HISTORY=0)." }] };
|
|
12528
|
+
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))}` }] };
|
|
12533
|
+
const { sessionKey } = resolveSessionContext(extra, true);
|
|
12534
|
+
try {
|
|
12535
|
+
const ds = entry.kind === "file" ? await store.loadFromFile(entry.source, entry.name, { sessionKey, keepExisting: true, where: entry.where }) : store.register({ name: entry.name, source: entry.source, ingestionMode: "direct", rows: history.readRows(entry), sessionKey, keepExisting: true });
|
|
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);
|
|
12541
|
+
return replyWithDataset(ds, sessionKey, "history");
|
|
12542
|
+
} catch (error) {
|
|
12543
|
+
return { isError: true, content: [{ type: "text", text: `Could not reopen "${open}": ${error instanceof Error ? error.message : String(error)}` }] };
|
|
12134
12544
|
}
|
|
12135
12545
|
}
|
|
12136
12546
|
);
|
|
@@ -12138,7 +12548,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12138
12548
|
"list_datasets",
|
|
12139
12549
|
{
|
|
12140
12550
|
title: "List Datasets",
|
|
12141
|
-
description: "List
|
|
12551
|
+
description: "List loaded datasets with their row counts and columns.",
|
|
12142
12552
|
inputSchema: {}
|
|
12143
12553
|
},
|
|
12144
12554
|
async (_args, extra) => {
|
|
@@ -12172,7 +12582,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12172
12582
|
"clear_datasets",
|
|
12173
12583
|
{
|
|
12174
12584
|
title: "Clear Session Datasets",
|
|
12175
|
-
description: "
|
|
12585
|
+
description: "Unload all datasets.",
|
|
12176
12586
|
inputSchema: {}
|
|
12177
12587
|
},
|
|
12178
12588
|
async (_args, extra) => {
|
|
@@ -12298,9 +12708,9 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12298
12708
|
"set_visual_theme",
|
|
12299
12709
|
{
|
|
12300
12710
|
title: "Set Visual Theme",
|
|
12301
|
-
description:
|
|
12711
|
+
description: "Set the theme for charts, tables and the Data IDE.",
|
|
12302
12712
|
inputSchema: {
|
|
12303
|
-
theme: z.enum(VISUAL_THEME_VALUES)
|
|
12713
|
+
theme: z.enum(VISUAL_THEME_VALUES)
|
|
12304
12714
|
},
|
|
12305
12715
|
_meta: {
|
|
12306
12716
|
ui: { visibility: ["model", "app"] }
|