@smallwebco/tinypivot-mcp 0.2.10 → 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 +4 -0
- package/dist/{chunk-6I4RP5QJ.js → chunk-AFGC2C4J.js} +510 -82
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +79 -0
- package/dist/index.js +1 -1
- package/package.json +3 -2
- package/server.json +2 -2
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tinypivot",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Interactive Data IDE inside Claude — turn CSV, TSV, JSON, JSONL, API/MCP outputs, and SQL results from any database into interactive charts, deterministic pivot tables, data grids, screenshot-ready terminal cards, and Excel exports.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Small Web, LLC",
|
package/README.md
CHANGED
|
@@ -119,11 +119,14 @@ Unlock Pro or Team at [tiny-pivot.com/pricing](https://tiny-pivot.com/pricing).
|
|
|
119
119
|
|---|---|
|
|
120
120
|
| `open_tinypivot` | Opens TinyPivot (side pane, sidebar, or inline). Works with `{}` using the built-in sample dataset. |
|
|
121
121
|
| `load_file` | Loads a local `.csv`, `.tsv`, `.json`, or `.jsonl` file (including SQL CLI exports from any database) with 0 raw rows entering LLM context; pass `chartConfig` / `pivotConfig` to render in 1 call. Pass `where` (for example `[{"field":"year","equals":[2026]}]`) to load only the rows a question is about; filtering runs on disk. |
|
|
122
|
+
| `query` | Runs one read-only DuckDB `SELECT` over local CSV, Parquet or JSON files and over loaded datasets (tables named by dataset id), then charts or pivots the result. Rows never enter the model's context. DuckDB (about 20 MB) downloads once, on first use, into `~/.cache/tinypivot`. |
|
|
122
123
|
| `load_data` | Loads flat JSON rows already in memory (<500 rows) from any other MCP tool, API, or small SQL query without writing a temp CSV; renders chart + pivot in 1 call. |
|
|
123
124
|
| `configure_pivot` | Computes a deterministic pivot table via `@smallwebco/tinypivot-core` (zero LLM math errors). |
|
|
124
125
|
| `configure_chart` | Configures and opens the interactive Chart Builder (`bar`, `stackedBar`, `line`, `area`, `pie`, `donut`, etc.). |
|
|
125
126
|
| `query_postgres` | *(Optional Pro)* Runs AST-validated read-only `SELECT` queries directly against `DATABASE_URL` and opens results in TinyPivot. |
|
|
126
127
|
| `list_datasets` | Lists all loaded datasets, row counts, and inferred schemas. |
|
|
128
|
+
| `profile` | Describes each column of a loaded dataset: empty share, number and date ranges, commonest values. |
|
|
129
|
+
| `history` | Lists every earlier pull, or reopens one by id without re-querying. Pulls are saved locally under `~/.local/share/tinypivot/history` for 30 days. |
|
|
127
130
|
|
|
128
131
|
## Environment Variables (Optional)
|
|
129
132
|
|
|
@@ -134,6 +137,7 @@ Unlock Pro or Team at [tiny-pivot.com/pricing](https://tiny-pivot.com/pricing).
|
|
|
134
137
|
- `TINYPIVOT_NO_COMPANION=1` — Disable the localhost Companion Data IDE server
|
|
135
138
|
- `TINYPIVOT_PORT` — Fixed localhost port for the Companion Data IDE server
|
|
136
139
|
- `TINYPIVOT_REPRINT_CARDS` — Set to `0` so the model does not reprint each chart card in a terminal. Saves about 400 output tokens per question; the card stays visible in the Data IDE, the `tui` pane and pi.
|
|
140
|
+
- `TINYPIVOT_HISTORY` — Set to `0` to stop saving pulls to history. `TINYPIVOT_HISTORY_DAYS` sets how long they are kept (default 30).
|
|
137
141
|
|
|
138
142
|
## Privacy & Telemetry
|
|
139
143
|
|
|
@@ -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)
|
|
@@ -9402,7 +9422,7 @@ function formatColumnNotes(columns) {
|
|
|
9402
9422
|
var REPRINT_NOTE = "Show the card above to the user verbatim.";
|
|
9403
9423
|
function formatDatasetSummary(dataset, companionUrl, options = {}) {
|
|
9404
9424
|
const cardOptions = { ...options, companionUrl: options.companionUrl ?? companionUrl };
|
|
9405
|
-
const chartBlock = pivotTableCard(dataset, cardOptions) ?? formatTerminalChart(dataset, dataset.chartConfig, cardOptions);
|
|
9425
|
+
const chartBlock = smallGridTable(dataset) ?? pivotTableCard(dataset, cardOptions) ?? formatTerminalChart(dataset, dataset.chartConfig, cardOptions);
|
|
9406
9426
|
const rowHeadline = dataset.truncatedForFreeTier ? `**${dataset.rows.length.toLocaleString()} of ${dataset.sourceTotalRows.toLocaleString()} rows (Free tier limit)**` : `**${dataset.rows.length.toLocaleString()} rows**`;
|
|
9407
9427
|
const parts = [
|
|
9408
9428
|
`Loaded **${dataset.name}** (\`${dataset.id}\`): ${rowHeadline}, ${dataset.columns.length} columns.`
|
|
@@ -11344,19 +11364,338 @@ async function executeReadOnlyPostgresQuery(config, sql) {
|
|
|
11344
11364
|
|
|
11345
11365
|
// src/server.ts
|
|
11346
11366
|
import fsSync3 from "fs";
|
|
11347
|
-
import
|
|
11348
|
-
import
|
|
11367
|
+
import fs7 from "fs/promises";
|
|
11368
|
+
import path8 from "path";
|
|
11349
11369
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
11350
11370
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
11351
11371
|
import { z } from "zod";
|
|
11352
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
|
+
|
|
11353
11692
|
// src/telemetry.ts
|
|
11354
11693
|
import crypto from "crypto";
|
|
11355
11694
|
import fsSync2 from "fs";
|
|
11356
|
-
import
|
|
11357
|
-
import
|
|
11695
|
+
import os6 from "os";
|
|
11696
|
+
import path7 from "path";
|
|
11358
11697
|
var DEFAULT_TELEMETRY_URL = "https://tiny-pivot.com/api/telemetry";
|
|
11359
|
-
var PACKAGE_VERSION = "0.
|
|
11698
|
+
var PACKAGE_VERSION = "0.3.0";
|
|
11360
11699
|
function isTelemetryEnabled() {
|
|
11361
11700
|
if (process.env.TINYPIVOT_TELEMETRY === "0" || process.env.TINYPIVOT_TELEMETRY === "false")
|
|
11362
11701
|
return false;
|
|
@@ -11376,8 +11715,8 @@ function bucketRowCount(rows) {
|
|
|
11376
11715
|
return "10k+";
|
|
11377
11716
|
}
|
|
11378
11717
|
function getPreferencesPath2() {
|
|
11379
|
-
const base = process.env.XDG_CONFIG_HOME?.trim() ||
|
|
11380
|
-
return
|
|
11718
|
+
const base = process.env.XDG_CONFIG_HOME?.trim() || path7.join(os6.homedir(), ".config");
|
|
11719
|
+
return path7.join(base, "tinypivot", "preferences.json");
|
|
11381
11720
|
}
|
|
11382
11721
|
var cachedAnonId = null;
|
|
11383
11722
|
function getAnonymousId() {
|
|
@@ -11395,7 +11734,7 @@ function getAnonymousId() {
|
|
|
11395
11734
|
const fresh = crypto.randomUUID();
|
|
11396
11735
|
cachedAnonId = fresh;
|
|
11397
11736
|
try {
|
|
11398
|
-
fsSync2.mkdirSync(
|
|
11737
|
+
fsSync2.mkdirSync(path7.dirname(prefPath), { recursive: true });
|
|
11399
11738
|
let existing = {};
|
|
11400
11739
|
try {
|
|
11401
11740
|
existing = JSON.parse(fsSync2.readFileSync(prefPath, "utf8"));
|
|
@@ -11439,7 +11778,7 @@ function buildInstructions({ reprintCards = true } = {}) {
|
|
|
11439
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.";
|
|
11440
11779
|
return [
|
|
11441
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.",
|
|
11442
|
-
`For files use load_file, so the rows stay out of your context. Use load_data only for rows you already have, up to about ${LOAD_DATA_ROW_GUIDE}; write larger sets to a file first.`,
|
|
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.`,
|
|
11443
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.",
|
|
11444
11783
|
"Use keepExisting: true only to compare datasets in one conversation; clear_datasets resets.",
|
|
11445
11784
|
cards
|
|
@@ -11522,6 +11861,23 @@ function clientSupportsMcpAppsUi(capabilities) {
|
|
|
11522
11861
|
function initialViewMode(requested, hasPivot, hasChart) {
|
|
11523
11862
|
return requested ?? (hasPivot && !hasChart ? "pivot" : "chart");
|
|
11524
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
|
+
}
|
|
11525
11881
|
function toCoreChartConfig(input) {
|
|
11526
11882
|
return {
|
|
11527
11883
|
type: input.type,
|
|
@@ -11583,16 +11939,16 @@ function buildAppPayload(dataset, store, options) {
|
|
|
11583
11939
|
}
|
|
11584
11940
|
async function loadAppHtml(customPath) {
|
|
11585
11941
|
const envPath = process.env.TINYPIVOT_MCP_APP_HTML;
|
|
11586
|
-
const here =
|
|
11942
|
+
const here = path8.dirname(fileURLToPath2(import.meta.url));
|
|
11587
11943
|
const candidates = [
|
|
11588
11944
|
customPath,
|
|
11589
11945
|
envPath,
|
|
11590
|
-
|
|
11591
|
-
|
|
11946
|
+
path8.resolve(here, "app/index.html"),
|
|
11947
|
+
path8.resolve(here, "../dist/app/index.html")
|
|
11592
11948
|
].filter((p) => Boolean(p));
|
|
11593
11949
|
for (const candidate of candidates) {
|
|
11594
11950
|
try {
|
|
11595
|
-
const html = await
|
|
11951
|
+
const html = await fs7.readFile(candidate, "utf8");
|
|
11596
11952
|
if (html.trim().length > 0)
|
|
11597
11953
|
return html;
|
|
11598
11954
|
} catch {
|
|
@@ -11613,10 +11969,10 @@ function resolveLicenseKey(explicit) {
|
|
|
11613
11969
|
return explicit.trim();
|
|
11614
11970
|
if (process.env.TINYPIVOT_LICENSE_KEY?.trim())
|
|
11615
11971
|
return process.env.TINYPIVOT_LICENSE_KEY.trim();
|
|
11616
|
-
const here =
|
|
11972
|
+
const here = path8.dirname(fileURLToPath2(import.meta.url));
|
|
11617
11973
|
const candidates = [
|
|
11618
|
-
|
|
11619
|
-
|
|
11974
|
+
path8.resolve(here, "../.license"),
|
|
11975
|
+
path8.resolve(here, ".license")
|
|
11620
11976
|
];
|
|
11621
11977
|
for (const file of candidates) {
|
|
11622
11978
|
try {
|
|
@@ -11653,7 +12009,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11653
12009
|
const server = new McpServer(
|
|
11654
12010
|
{
|
|
11655
12011
|
name: "tinypivot",
|
|
11656
|
-
version: "0.
|
|
12012
|
+
version: "0.3.0"
|
|
11657
12013
|
},
|
|
11658
12014
|
{
|
|
11659
12015
|
capabilities: {
|
|
@@ -11678,6 +12034,39 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11678
12034
|
const content = [{ type: "text", text: summaryText }];
|
|
11679
12035
|
return clientRendersWidget() ? { content, structuredContent: payload } : { content };
|
|
11680
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
|
+
});
|
|
11681
12070
|
const widgetOnlyTools = [];
|
|
11682
12071
|
const widgetOnly = (tool) => {
|
|
11683
12072
|
widgetOnlyTools.push(tool);
|
|
@@ -11821,15 +12210,10 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11821
12210
|
try {
|
|
11822
12211
|
const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
|
|
11823
12212
|
const ds = await store.loadFromFile(filePath, name, { sessionKey, keepExisting: shouldKeep, where });
|
|
12213
|
+
remember(ds, { kind: "file", source: ds.source, where });
|
|
11824
12214
|
const explicitChart = chartConfig ? toCoreChartConfig(chartConfig) : void 0;
|
|
11825
12215
|
if (pivotConfig) {
|
|
11826
|
-
const normalizedPivot =
|
|
11827
|
-
...pivotConfig,
|
|
11828
|
-
valueFields: pivotConfig.valueFields.map((v) => ({
|
|
11829
|
-
field: v.field,
|
|
11830
|
-
aggregation: v.aggregation
|
|
11831
|
-
}))
|
|
11832
|
-
};
|
|
12216
|
+
const normalizedPivot = normalizePivot(pivotConfig);
|
|
11833
12217
|
store.updateView(ds.id, {
|
|
11834
12218
|
viewMode: initialViewMode(viewMode, true, Boolean(explicitChart)),
|
|
11835
12219
|
pivotConfig: normalizedPivot,
|
|
@@ -11841,19 +12225,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11841
12225
|
...explicitChart ? { chartConfig: explicitChart } : {}
|
|
11842
12226
|
}, sessionKey);
|
|
11843
12227
|
}
|
|
11844
|
-
|
|
11845
|
-
const summaryText = formatDatasetSummary(ds, liveCompanionUrl, cardFormat);
|
|
11846
|
-
const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, sessionKey });
|
|
11847
|
-
recordTelemetry({
|
|
11848
|
-
event: "tool_call",
|
|
11849
|
-
tool: "load_file",
|
|
11850
|
-
rowBucket: bucketRowCount(ds.sourceTotalRows),
|
|
11851
|
-
client: getClientName(),
|
|
11852
|
-
tier,
|
|
11853
|
-
truncated: ds.truncatedForFreeTier
|
|
11854
|
-
});
|
|
11855
|
-
notifyCompanion();
|
|
11856
|
-
return dataToolResult(summaryText, payload);
|
|
12228
|
+
return replyWithDataset(ds, sessionKey, "load_file");
|
|
11857
12229
|
} catch (err) {
|
|
11858
12230
|
return {
|
|
11859
12231
|
isError: true,
|
|
@@ -11880,37 +12252,19 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
11880
12252
|
},
|
|
11881
12253
|
async ({ name, rows, source, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
|
|
11882
12254
|
const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
|
|
11883
|
-
const normalizedPivot = pivotConfig ? {
|
|
11884
|
-
...pivotConfig,
|
|
11885
|
-
valueFields: pivotConfig.valueFields.map((v) => ({
|
|
11886
|
-
field: v.field,
|
|
11887
|
-
aggregation: v.aggregation
|
|
11888
|
-
}))
|
|
11889
|
-
} : void 0;
|
|
11890
12255
|
const ds = store.register({
|
|
11891
12256
|
name,
|
|
11892
12257
|
source: source ?? "inline JSON",
|
|
11893
12258
|
ingestionMode: "inline",
|
|
11894
12259
|
rows,
|
|
11895
12260
|
viewMode: initialViewMode(viewMode, Boolean(pivotConfig), Boolean(chartConfig)),
|
|
11896
|
-
pivotConfig:
|
|
12261
|
+
pivotConfig: pivotConfig ? normalizePivot(pivotConfig) : void 0,
|
|
11897
12262
|
chartConfig: chartConfig ? toCoreChartConfig(chartConfig) : void 0,
|
|
11898
12263
|
sessionKey,
|
|
11899
12264
|
keepExisting: shouldKeep
|
|
11900
12265
|
});
|
|
11901
|
-
|
|
11902
|
-
|
|
11903
|
-
const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, sessionKey });
|
|
11904
|
-
recordTelemetry({
|
|
11905
|
-
event: "tool_call",
|
|
11906
|
-
tool: "load_data",
|
|
11907
|
-
rowBucket: bucketRowCount(ds.sourceTotalRows),
|
|
11908
|
-
client: getClientName(),
|
|
11909
|
-
tier,
|
|
11910
|
-
truncated: ds.truncatedForFreeTier
|
|
11911
|
-
});
|
|
11912
|
-
notifyCompanion();
|
|
11913
|
-
return dataToolResult(summaryText, payload);
|
|
12266
|
+
remember(ds, { kind: "data", source: source ?? "inline JSON" });
|
|
12267
|
+
return replyWithDataset(ds, sessionKey, "load_data");
|
|
11914
12268
|
}
|
|
11915
12269
|
);
|
|
11916
12270
|
server.registerTool(
|
|
@@ -12083,30 +12437,12 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12083
12437
|
ingestionMode: "direct",
|
|
12084
12438
|
rows: res.rows,
|
|
12085
12439
|
viewMode: initialViewMode(viewMode, Boolean(pivotConfig), false),
|
|
12086
|
-
pivotConfig: pivotConfig ?
|
|
12087
|
-
...pivotConfig,
|
|
12088
|
-
valueFields: pivotConfig.valueFields.map((v) => ({
|
|
12089
|
-
field: v.field,
|
|
12090
|
-
aggregation: v.aggregation
|
|
12091
|
-
}))
|
|
12092
|
-
} : void 0,
|
|
12440
|
+
pivotConfig: pivotConfig ? normalizePivot(pivotConfig) : void 0,
|
|
12093
12441
|
sessionKey,
|
|
12094
12442
|
keepExisting: shouldKeep
|
|
12095
12443
|
});
|
|
12096
|
-
|
|
12097
|
-
|
|
12098
|
-
const summaryText = `${formatDatasetSummary(ds, liveCompanionUrl, cardFormat)}${truncNote}`;
|
|
12099
|
-
const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, sessionKey });
|
|
12100
|
-
recordTelemetry({
|
|
12101
|
-
event: "tool_call",
|
|
12102
|
-
tool: "query_postgres",
|
|
12103
|
-
rowBucket: bucketRowCount(ds.sourceTotalRows),
|
|
12104
|
-
client: getClientName(),
|
|
12105
|
-
tier,
|
|
12106
|
-
truncated: ds.truncatedForFreeTier
|
|
12107
|
-
});
|
|
12108
|
-
notifyCompanion();
|
|
12109
|
-
return dataToolResult(summaryText, payload);
|
|
12444
|
+
remember(ds, { kind: "postgres", source: sql });
|
|
12445
|
+
return replyWithDataset(ds, sessionKey, "query_postgres", res.truncated ? " (capped at max rows)" : "");
|
|
12110
12446
|
} catch (err) {
|
|
12111
12447
|
return {
|
|
12112
12448
|
isError: true,
|
|
@@ -12116,6 +12452,98 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12116
12452
|
}
|
|
12117
12453
|
);
|
|
12118
12454
|
}
|
|
12455
|
+
server.registerTool(
|
|
12456
|
+
"query",
|
|
12457
|
+
{
|
|
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.",
|
|
12460
|
+
inputSchema: {
|
|
12461
|
+
sql: z.string(),
|
|
12462
|
+
name: z.string().optional(),
|
|
12463
|
+
viewMode: z.enum(VIEW_MODE_VALUES).optional(),
|
|
12464
|
+
pivotConfig: pivotConfigSchema.optional(),
|
|
12465
|
+
chartConfig: chartConfigSchema.optional(),
|
|
12466
|
+
keepExisting: z.boolean().optional().describe("Keep earlier datasets loaded, to compare them")
|
|
12467
|
+
},
|
|
12468
|
+
_meta: INLINE_UI_META
|
|
12469
|
+
},
|
|
12470
|
+
async ({ sql, name, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
|
|
12471
|
+
const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
|
|
12472
|
+
try {
|
|
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));
|
|
12477
|
+
const ds = store.register({
|
|
12478
|
+
name: name ?? "SQL query",
|
|
12479
|
+
source: sql,
|
|
12480
|
+
ingestionMode: "direct",
|
|
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,
|
|
12485
|
+
sessionKey,
|
|
12486
|
+
keepExisting: shouldKeep
|
|
12487
|
+
});
|
|
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)}` }] };
|
|
12544
|
+
}
|
|
12545
|
+
}
|
|
12546
|
+
);
|
|
12119
12547
|
server.registerTool(
|
|
12120
12548
|
"list_datasets",
|
|
12121
12549
|
{
|
package/dist/cli.js
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { DataGridViewMode, PivotConfig, ChartConfig, ChartThemePreset } from '@smallwebco/tinypivot-core';
|
|
2
2
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
3
|
+
import * as _duckdb_node_api from '@duckdb/node-api';
|
|
4
|
+
import { DuckDBConnection } from '@duckdb/node-api';
|
|
3
5
|
|
|
4
6
|
interface ModelPricing {
|
|
5
7
|
id: string;
|
|
@@ -178,6 +180,79 @@ interface PostgresQueryResult {
|
|
|
178
180
|
declare function listPostgresTables(config: PostgresConfig): Promise<string[]>;
|
|
179
181
|
declare function executeReadOnlyPostgresQuery(config: PostgresConfig, sql: string): Promise<PostgresQueryResult>;
|
|
180
182
|
|
|
183
|
+
type DuckDbModule = typeof _duckdb_node_api;
|
|
184
|
+
/** A named table the query can use: an earlier pull, read back from its file. */
|
|
185
|
+
interface QueryView {
|
|
186
|
+
name: string;
|
|
187
|
+
/** A DuckDB table expression, e.g. `'orders.csv'` or `read_json_auto('…jsonl.gz')`. */
|
|
188
|
+
from: string;
|
|
189
|
+
}
|
|
190
|
+
interface QueryResult {
|
|
191
|
+
columns: string[];
|
|
192
|
+
rows: Record<string, unknown>[];
|
|
193
|
+
/** True when the result had more than QUERY_ROW_LIMIT rows and was cut there. */
|
|
194
|
+
truncated: boolean;
|
|
195
|
+
}
|
|
196
|
+
/** One DuckDB connection per server, locked down: no extension downloads, no setting changes. */
|
|
197
|
+
declare class DuckDbRunner {
|
|
198
|
+
private readonly load;
|
|
199
|
+
private connection?;
|
|
200
|
+
private duck?;
|
|
201
|
+
constructor(load?: () => Promise<DuckDbModule>);
|
|
202
|
+
/** Starts loading DuckDB (downloading it if needed) without waiting. */
|
|
203
|
+
prepare(): Promise<DuckDBConnection>;
|
|
204
|
+
run(sql: string, views: QueryView[], maxRows?: number): Promise<QueryResult>;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Every pull a session makes, kept on disk so it can be reopened later without re-querying or
|
|
209
|
+
* re-sending anything to the model. Local only, under the user's data folder.
|
|
210
|
+
*
|
|
211
|
+
* Files are remembered by path and filter, since the file is still there to re-read. Ephemeral
|
|
212
|
+
* pulls (rows passed in, query results, Postgres results) are saved with their rows.
|
|
213
|
+
*/
|
|
214
|
+
type HistoryKind = 'file' | 'data' | 'query' | 'postgres';
|
|
215
|
+
interface HistoryEntry {
|
|
216
|
+
id: string;
|
|
217
|
+
name: string;
|
|
218
|
+
kind: HistoryKind;
|
|
219
|
+
createdAt: string;
|
|
220
|
+
rows: number;
|
|
221
|
+
columns: string[];
|
|
222
|
+
/** File path for `file`, a source label for `data`, the SQL text for `query` and `postgres`. */
|
|
223
|
+
source: string;
|
|
224
|
+
where?: RowFilter[];
|
|
225
|
+
/** Saved rows, gzipped JSON lines, for pulls that cannot be re-read from a file. */
|
|
226
|
+
rowsFile?: string;
|
|
227
|
+
chartConfig?: Partial<ChartConfig>;
|
|
228
|
+
pivotConfig?: Partial<PivotConfig>;
|
|
229
|
+
}
|
|
230
|
+
interface RecordInput {
|
|
231
|
+
kind: HistoryKind;
|
|
232
|
+
source: string;
|
|
233
|
+
where?: RowFilter[];
|
|
234
|
+
}
|
|
235
|
+
declare class HistoryStore {
|
|
236
|
+
readonly dir: string;
|
|
237
|
+
readonly enabled: boolean;
|
|
238
|
+
private readonly retentionDays;
|
|
239
|
+
constructor(options?: {
|
|
240
|
+
dir?: string;
|
|
241
|
+
enabled?: boolean;
|
|
242
|
+
retentionDays?: number;
|
|
243
|
+
});
|
|
244
|
+
/** Saves a pull. Returns the entry, or null when history is off or the write failed. */
|
|
245
|
+
record(dataset: StoredDataset, input: RecordInput, now?: Date): HistoryEntry | null;
|
|
246
|
+
/** Newest first. */
|
|
247
|
+
list(limit?: number): HistoryEntry[];
|
|
248
|
+
get(id: string): HistoryEntry | undefined;
|
|
249
|
+
/** Full path of an entry's saved rows, for reading back or querying with SQL. */
|
|
250
|
+
rowsPath(entry: HistoryEntry): string | undefined;
|
|
251
|
+
readRows(entry: HistoryEntry): Record<string, unknown>[];
|
|
252
|
+
/** Deletes entries older than the retention window. Returns how many were removed. */
|
|
253
|
+
prune(now?: Date): number;
|
|
254
|
+
}
|
|
255
|
+
|
|
181
256
|
declare const APP_RESOURCE_URI = "ui://tinypivot/app.html";
|
|
182
257
|
declare const APP_MIME_TYPE = "text/html;profile=mcp-app";
|
|
183
258
|
declare const TINYPIVOT_MCP_INSTRUCTIONS: string;
|
|
@@ -197,6 +272,10 @@ interface CreateTinyPivotMcpServerOptions {
|
|
|
197
272
|
* Defaults to TINYPIVOT_REPRINT_CARDS, which turns it off with "0".
|
|
198
273
|
*/
|
|
199
274
|
reprintCards?: boolean;
|
|
275
|
+
/** Where pulls are saved; defaults to the user's data folder. */
|
|
276
|
+
history?: HistoryStore;
|
|
277
|
+
/** SQL engine for the query tool; defaults to an embedded DuckDB, downloaded on first use. */
|
|
278
|
+
duckdb?: DuckDbRunner;
|
|
200
279
|
}
|
|
201
280
|
declare function clientSupportsMcpAppsUi(capabilities?: {
|
|
202
281
|
extensions?: Record<string, unknown>;
|
package/dist/index.js
CHANGED
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@smallwebco/tinypivot-mcp",
|
|
3
3
|
"mcpName": "io.github.Small-Web-Co/tinypivot",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"version": "0.
|
|
5
|
+
"version": "0.3.0",
|
|
6
6
|
"description": "TinyPivot MCP Server, Interactive MCP App & Claude Plugin — turn CSV, JSON, API/MCP outputs, and queries from any database into interactive charts, pivot tables, terminal cards, live TUI, drill-through, and Excel exports inside AI agents.",
|
|
7
7
|
"author": "Small Web, LLC",
|
|
8
8
|
"license": "MIT",
|
|
@@ -67,6 +67,7 @@
|
|
|
67
67
|
"zod": "^4.0.0"
|
|
68
68
|
},
|
|
69
69
|
"devDependencies": {
|
|
70
|
+
"@duckdb/node-api": "2.0.1-r.1",
|
|
70
71
|
"@modelcontextprotocol/ext-apps": "^1.0.1",
|
|
71
72
|
"@types/node": "^20.19.41",
|
|
72
73
|
"@types/pg": "^8.11.6",
|
|
@@ -79,8 +80,8 @@
|
|
|
79
80
|
"typescript": "~5.6.2",
|
|
80
81
|
"vite": "^6.4.6",
|
|
81
82
|
"vite-plugin-singlefile": "^2.2.0",
|
|
82
|
-
"@smallwebco/tinypivot-core": "1.4.5",
|
|
83
83
|
"@smallwebco/tinypivot-react": "1.4.5",
|
|
84
|
+
"@smallwebco/tinypivot-core": "1.4.5",
|
|
84
85
|
"@smallwebco/tinypivot-server": "1.4.5"
|
|
85
86
|
},
|
|
86
87
|
"scripts": {
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "io.github.Small-Web-Co/tinypivot",
|
|
4
4
|
"title": "TinyPivot — Interactive Data IDE for AI Agents",
|
|
5
5
|
"description": "Interactive charts, pivot tables, terminal cards, live TUI, and Excel export inside AI agents.",
|
|
6
|
-
"version": "0.
|
|
6
|
+
"version": "0.3.0",
|
|
7
7
|
"websiteUrl": "https://tiny-pivot.com",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/Small-Web-Co/tinypivot",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
{
|
|
15
15
|
"registryType": "npm",
|
|
16
16
|
"identifier": "@smallwebco/tinypivot-mcp",
|
|
17
|
-
"version": "0.
|
|
17
|
+
"version": "0.3.0",
|
|
18
18
|
"transport": {
|
|
19
19
|
"type": "stdio"
|
|
20
20
|
},
|