@smallwebco/tinypivot-mcp 0.0.0-stage → 0.1.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/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/cli.js ADDED
@@ -0,0 +1,487 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ DatasetStore,
4
+ FREE_TIER_ROW_LIMIT,
5
+ createTinyPivotMcpServer,
6
+ loadAppHtml,
7
+ resolveLicenseKey,
8
+ startCompanionServer
9
+ } from "./chunk-VLD3SN2I.js";
10
+ import "./chunk-2ESYSVXG.js";
11
+
12
+ // src/cli.ts
13
+ import { spawn } from "child_process";
14
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
15
+
16
+ // src/init.ts
17
+ import fs from "fs/promises";
18
+ import os from "os";
19
+ import path from "path";
20
+ import { fileURLToPath } from "url";
21
+ var RULE_START = "<!-- tinypivot-mcp:start -->";
22
+ var RULE_END = "<!-- tinypivot-mcp:end -->";
23
+ var AGENT_RULE_BLOCK = `${RULE_START}
24
+ ## Tabular Data & Charts (TinyPivot MCP)
25
+ When the user asks to analyze, pivot, chart, filter, compare, or visualize tabular data (CSV/TSV/JSON files, SQL query outputs, or API/MCP records), prefer \`tinypivot\` (\`load_file\`, \`load_data\`, \`configure_pivot\`, \`configure_chart\`) instead of dumping raw rows into chat or writing throwaway matplotlib/HTML scripts. Pass \`chartConfig\` or \`pivotConfig\` directly on \`load_file\` / \`load_data\` so the chart renders in a single tool call.
26
+ ${RULE_END}`;
27
+ function printHelp() {
28
+ console.log(`
29
+ TinyPivot MCP \u2014 Multi-Harness Installer
30
+
31
+ Usage:
32
+ npx @smallwebco/tinypivot-mcp init [options]
33
+
34
+ Options:
35
+ --local Wire this local build (node <path>/dist/cli.js) instead of npx
36
+ --targets=<list> Comma-separated harnesses to configure:
37
+ claude, claude-desktop, cursor, opencode, antigravity, pi, codex
38
+ --all Configure all supported harnesses even if not yet detected
39
+ --license=<key> Write TINYPIVOT_LICENSE_KEY into each configured server env
40
+ --no-rules Skip adding the auto-use TinyPivot instruction to ~/.claude/CLAUDE.md
41
+ --dry-run Preview planned changes without writing files
42
+ -h, --help Show this help message
43
+
44
+ Privacy:
45
+ Anonymous, zero-PII telemetry (event, tool name, row bucket, client name, OS) is
46
+ enabled by default. Disable anytime with TINYPIVOT_TELEMETRY=0 or DO_NOT_TRACK=1.
47
+ `.trim());
48
+ }
49
+ function parseArgs(args) {
50
+ const opts = {
51
+ local: false,
52
+ all: false,
53
+ dryRun: false,
54
+ noRules: false,
55
+ targets: null
56
+ };
57
+ for (const arg of args) {
58
+ if (arg === "-h" || arg === "--help") {
59
+ printHelp();
60
+ return null;
61
+ } else if (arg === "--local") {
62
+ opts.local = true;
63
+ } else if (arg === "--all") {
64
+ opts.all = true;
65
+ } else if (arg === "--dry-run") {
66
+ opts.dryRun = true;
67
+ } else if (arg === "--no-rules") {
68
+ opts.noRules = true;
69
+ } else if (arg.startsWith("--targets=")) {
70
+ const list = arg.slice("--targets=".length).split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
71
+ opts.targets = new Set(list);
72
+ } else if (arg.startsWith("--license=")) {
73
+ opts.licenseKey = arg.slice("--license=".length).trim();
74
+ }
75
+ }
76
+ return opts;
77
+ }
78
+ async function exists(p) {
79
+ try {
80
+ await fs.access(p);
81
+ return true;
82
+ } catch {
83
+ return false;
84
+ }
85
+ }
86
+ async function readJsonSafe(filePath) {
87
+ try {
88
+ const raw = await fs.readFile(filePath, "utf8");
89
+ const parsed = JSON.parse(raw);
90
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
91
+ return parsed;
92
+ } catch {
93
+ }
94
+ return {};
95
+ }
96
+ async function writeJsonPretty(filePath, data, dryRun) {
97
+ if (dryRun)
98
+ return;
99
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
100
+ await fs.writeFile(filePath, `${JSON.stringify(data, null, 2)}
101
+ `, "utf8");
102
+ }
103
+ function getClaudeDesktopConfigPath() {
104
+ const home = os.homedir();
105
+ if (process.platform === "darwin")
106
+ return path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
107
+ if (process.platform === "win32")
108
+ return path.join(process.env.APPDATA || path.join(home, "AppData", "Roaming"), "Claude", "claude_desktop_config.json");
109
+ return path.join(process.env.XDG_CONFIG_HOME || path.join(home, ".config"), "Claude", "claude_desktop_config.json");
110
+ }
111
+ function buildStdioServerEntry(opts, cliPath) {
112
+ const command = opts.local ? process.execPath : "npx";
113
+ const args = opts.local ? [cliPath] : ["-y", "@smallwebco/tinypivot-mcp"];
114
+ const entry = { command, args };
115
+ if (opts.licenseKey) {
116
+ entry.env = { TINYPIVOT_LICENSE_KEY: opts.licenseKey };
117
+ }
118
+ return entry;
119
+ }
120
+ async function upsertStandardMcpJson(id, label, configPath, detectDir, opts, cliPath) {
121
+ const explicit = opts.targets?.has(id) ?? false;
122
+ const shouldInclude = opts.targets ? explicit : opts.all || await exists(configPath) || await exists(detectDir);
123
+ if (!shouldInclude) {
124
+ return { id, label, configPath, status: "skipped", detail: "not detected" };
125
+ }
126
+ try {
127
+ const json = await readJsonSafe(configPath);
128
+ const mcpServers = json.mcpServers && typeof json.mcpServers === "object" && !Array.isArray(json.mcpServers) ? { ...json.mcpServers } : {};
129
+ const nextEntry = buildStdioServerEntry(opts, cliPath);
130
+ const existing = mcpServers.tinypivot;
131
+ if (existing?.env && typeof existing.env === "object" && !Array.isArray(existing.env)) {
132
+ nextEntry.env = {
133
+ ...existing.env,
134
+ ...nextEntry.env ?? {}
135
+ };
136
+ }
137
+ const before = JSON.stringify(mcpServers.tinypivot);
138
+ const after = JSON.stringify(nextEntry);
139
+ if (before === after) {
140
+ return { id, label, configPath, status: "unchanged", detail: "already up to date" };
141
+ }
142
+ mcpServers.tinypivot = nextEntry;
143
+ json.mcpServers = mcpServers;
144
+ await writeJsonPretty(configPath, json, opts.dryRun);
145
+ return {
146
+ id,
147
+ label,
148
+ configPath,
149
+ status: "updated",
150
+ detail: opts.dryRun ? "would register tinypivot" : "registered tinypivot"
151
+ };
152
+ } catch (err) {
153
+ return {
154
+ id,
155
+ label,
156
+ configPath,
157
+ status: "error",
158
+ detail: err instanceof Error ? err.message : String(err)
159
+ };
160
+ }
161
+ }
162
+ async function upsertOpenCodeJson(opts, cliPath) {
163
+ const id = "opencode";
164
+ const label = "OpenCode";
165
+ const xdg = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
166
+ const configDir = path.join(xdg, "opencode");
167
+ const configPath = path.join(configDir, "opencode.json");
168
+ const explicit = opts.targets?.has(id) ?? false;
169
+ const shouldInclude = opts.targets ? explicit : opts.all || await exists(configPath) || await exists(configDir);
170
+ if (!shouldInclude) {
171
+ return { id, label, configPath, status: "skipped", detail: "not detected" };
172
+ }
173
+ try {
174
+ const json = await readJsonSafe(configPath);
175
+ const mcp = json.mcp && typeof json.mcp === "object" && !Array.isArray(json.mcp) ? { ...json.mcp } : {};
176
+ const command = opts.local ? [process.execPath, cliPath] : ["npx", "-y", "@smallwebco/tinypivot-mcp"];
177
+ const nextEntry = {
178
+ type: "local",
179
+ command,
180
+ enabled: true
181
+ };
182
+ const existing = mcp.tinypivot;
183
+ if (existing?.environment && typeof existing.environment === "object" && !Array.isArray(existing.environment)) {
184
+ nextEntry.environment = { ...existing.environment };
185
+ }
186
+ if (opts.licenseKey) {
187
+ nextEntry.environment = {
188
+ ...nextEntry.environment ?? {},
189
+ TINYPIVOT_LICENSE_KEY: opts.licenseKey
190
+ };
191
+ }
192
+ if (JSON.stringify(mcp.tinypivot) === JSON.stringify(nextEntry)) {
193
+ return { id, label, configPath, status: "unchanged", detail: "already up to date" };
194
+ }
195
+ mcp.tinypivot = nextEntry;
196
+ json.mcp = mcp;
197
+ await writeJsonPretty(configPath, json, opts.dryRun);
198
+ return {
199
+ id,
200
+ label,
201
+ configPath,
202
+ status: "updated",
203
+ detail: opts.dryRun ? "would register tinypivot" : "registered tinypivot"
204
+ };
205
+ } catch (err) {
206
+ return {
207
+ id,
208
+ label,
209
+ configPath,
210
+ status: "error",
211
+ detail: err instanceof Error ? err.message : String(err)
212
+ };
213
+ }
214
+ }
215
+ async function upsertCodexToml(opts, cliPath) {
216
+ const id = "codex";
217
+ const label = "Codex CLI";
218
+ const codexDir = path.join(os.homedir(), ".codex");
219
+ const configPath = path.join(codexDir, "config.toml");
220
+ const explicit = opts.targets?.has(id) ?? false;
221
+ const shouldInclude = opts.targets ? explicit : opts.all || await exists(configPath) || await exists(codexDir);
222
+ if (!shouldInclude) {
223
+ return { id, label, configPath, status: "skipped", detail: "not detected" };
224
+ }
225
+ try {
226
+ const existing = await exists(configPath) ? await fs.readFile(configPath, "utf8") : "";
227
+ const command = opts.local ? process.execPath : "npx";
228
+ const args = opts.local ? [cliPath] : ["-y", "@smallwebco/tinypivot-mcp"];
229
+ const argsToml = args.map((a) => JSON.stringify(a)).join(", ");
230
+ const envLines = opts.licenseKey ? `
231
+ [mcp_servers.tinypivot.env]
232
+ TINYPIVOT_LICENSE_KEY = ${JSON.stringify(opts.licenseKey)}
233
+ ` : "";
234
+ const block = `# tinypivot-mcp:start
235
+ [mcp_servers.tinypivot]
236
+ command = ${JSON.stringify(command)}
237
+ args = [${argsToml}]
238
+ ${envLines}# tinypivot-mcp:end
239
+ `;
240
+ let next;
241
+ const markerRe = /# tinypivot-mcp:start[\s\S]*?# tinypivot-mcp:end\n?/;
242
+ if (markerRe.test(existing)) {
243
+ next = existing.replace(markerRe, block);
244
+ } else if (/\[mcp_servers\.tinypivot\]/.test(existing)) {
245
+ return { id, label, configPath, status: "unchanged", detail: "existing [mcp_servers.tinypivot] section kept" };
246
+ } else {
247
+ const sep = existing.length > 0 && !existing.endsWith("\n") ? "\n\n" : existing.length > 0 ? "\n" : "";
248
+ next = `${existing}${sep}${block}`;
249
+ }
250
+ if (next === existing) {
251
+ return { id, label, configPath, status: "unchanged", detail: "already up to date" };
252
+ }
253
+ if (!opts.dryRun) {
254
+ await fs.mkdir(codexDir, { recursive: true });
255
+ await fs.writeFile(configPath, next, "utf8");
256
+ }
257
+ return {
258
+ id,
259
+ label,
260
+ configPath,
261
+ status: "updated",
262
+ detail: opts.dryRun ? "would register [mcp_servers.tinypivot]" : "registered [mcp_servers.tinypivot]"
263
+ };
264
+ } catch (err) {
265
+ return {
266
+ id,
267
+ label,
268
+ configPath,
269
+ status: "error",
270
+ detail: err instanceof Error ? err.message : String(err)
271
+ };
272
+ }
273
+ }
274
+ async function upsertClaudeRules(opts) {
275
+ if (opts.noRules)
276
+ return null;
277
+ const claudeDir = path.join(os.homedir(), ".claude");
278
+ const claudeMdPath = path.join(claudeDir, "CLAUDE.md");
279
+ if (!opts.all && !await exists(claudeDir))
280
+ return null;
281
+ try {
282
+ const existing = await exists(claudeMdPath) ? await fs.readFile(claudeMdPath, "utf8") : "";
283
+ const blockRe = new RegExp(`${RULE_START}[\\s\\S]*?${RULE_END}`);
284
+ let next;
285
+ if (blockRe.test(existing)) {
286
+ next = existing.replace(blockRe, AGENT_RULE_BLOCK);
287
+ } else {
288
+ const sep = existing.trim().length > 0 ? "\n\n" : "";
289
+ next = `${existing.trimEnd()}${sep}${AGENT_RULE_BLOCK}
290
+ `;
291
+ }
292
+ if (next === existing) {
293
+ return { id: "claude-rules", label: "Claude Code Rules", configPath: claudeMdPath, status: "unchanged", detail: "auto-use rule already present" };
294
+ }
295
+ if (!opts.dryRun) {
296
+ await fs.mkdir(claudeDir, { recursive: true });
297
+ await fs.writeFile(claudeMdPath, next, "utf8");
298
+ }
299
+ return {
300
+ id: "claude-rules",
301
+ label: "Claude Code Rules",
302
+ configPath: claudeMdPath,
303
+ status: "updated",
304
+ detail: opts.dryRun ? "would add auto-use TinyPivot rule" : "added auto-use TinyPivot rule"
305
+ };
306
+ } catch (err) {
307
+ return {
308
+ id: "claude-rules",
309
+ label: "Claude Code Rules",
310
+ configPath: claudeMdPath,
311
+ status: "error",
312
+ detail: err instanceof Error ? err.message : String(err)
313
+ };
314
+ }
315
+ }
316
+ async function runInitCommand(args) {
317
+ const opts = parseArgs(args);
318
+ if (!opts)
319
+ return;
320
+ const home = os.homedir();
321
+ const cliPath = fileURLToPath(import.meta.url);
322
+ console.log(`
323
+ TinyPivot MCP Installer (${opts.local ? `local: ${cliPath}` : "npx @smallwebco/tinypivot-mcp"})${opts.dryRun ? " [DRY RUN]" : ""}
324
+ `);
325
+ const results = [
326
+ await upsertStandardMcpJson(
327
+ "claude",
328
+ "Claude Code",
329
+ path.join(home, ".claude.json"),
330
+ path.join(home, ".claude"),
331
+ opts,
332
+ cliPath
333
+ ),
334
+ await upsertStandardMcpJson(
335
+ "claude-desktop",
336
+ "Claude Desktop",
337
+ getClaudeDesktopConfigPath(),
338
+ path.dirname(getClaudeDesktopConfigPath()),
339
+ opts,
340
+ cliPath
341
+ ),
342
+ await upsertStandardMcpJson(
343
+ "cursor",
344
+ "Cursor",
345
+ path.join(home, ".cursor", "mcp.json"),
346
+ path.join(home, ".cursor"),
347
+ opts,
348
+ cliPath
349
+ ),
350
+ await upsertStandardMcpJson(
351
+ "antigravity",
352
+ "Antigravity",
353
+ path.join(home, ".gemini", "antigravity", "mcp_config.json"),
354
+ path.join(home, ".gemini", "antigravity"),
355
+ opts,
356
+ cliPath
357
+ ),
358
+ await upsertStandardMcpJson(
359
+ "pi",
360
+ "pi",
361
+ path.join(home, ".pi", "agent", "mcp.json"),
362
+ path.join(home, ".pi"),
363
+ opts,
364
+ cliPath
365
+ ),
366
+ await upsertOpenCodeJson(opts, cliPath),
367
+ await upsertCodexToml(opts, cliPath)
368
+ ];
369
+ const rulesRes = await upsertClaudeRules(opts);
370
+ if (rulesRes)
371
+ results.push(rulesRes);
372
+ const iconFor = {
373
+ updated: "\u2713",
374
+ unchanged: "\xB7",
375
+ skipped: "-",
376
+ error: "\u2717"
377
+ };
378
+ for (const r of results) {
379
+ if (r.status === "skipped" && !opts.targets)
380
+ continue;
381
+ console.log(` ${iconFor[r.status]} ${r.label.padEnd(18)} ${r.detail} (${r.configPath})`);
382
+ }
383
+ const configuredCount = results.filter((r) => r.status === "updated" || r.status === "unchanged").length;
384
+ if (configuredCount === 0) {
385
+ console.log("\n No supported AI harness configs were detected. Re-run with --all or --targets=claude,cursor,opencode.");
386
+ } else {
387
+ console.log("\nNext steps:");
388
+ console.log(" 1. Restart your AI client(s) so the tinypivot MCP server loads.");
389
+ console.log(' 2. Try asking: "Open TinyPivot" or "Chart revenue by region from sales.csv".');
390
+ console.log(" 3. Free tier includes core charts, basic pivot, and up to 2,500 rows.");
391
+ console.log(" Unlock unlimited rows, drill-through, Excel export, Postgres, & 5 themes at https://tiny-pivot.com/mcp");
392
+ }
393
+ console.log("");
394
+ }
395
+
396
+ // src/cli.ts
397
+ function openInBrowser(url) {
398
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
399
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
400
+ try {
401
+ const child = spawn(cmd, args, { stdio: "ignore", detached: true });
402
+ child.unref();
403
+ } catch {
404
+ }
405
+ }
406
+ async function main() {
407
+ const args = process.argv.slice(2);
408
+ if (args[0] === "init") {
409
+ await runInitCommand(args.slice(1));
410
+ return;
411
+ }
412
+ const licenseKey = resolveLicenseKey();
413
+ const demoToken = process.env.TINYPIVOT_DEMO_TOKEN;
414
+ const isPro = Boolean(licenseKey && licenseKey.startsWith("TP-") || demoToken);
415
+ const store = new DatasetStore({
416
+ maxRowsPerDataset: isPro ? Number.POSITIVE_INFINITY : FREE_TIER_ROW_LIMIT
417
+ });
418
+ let appHtmlPath;
419
+ let port = process.env.TINYPIVOT_PORT ? Number(process.env.TINYPIVOT_PORT) : 0;
420
+ let disableCompanion = process.env.TINYPIVOT_NO_COMPANION === "1";
421
+ let autoOpen = false;
422
+ const filesToLoad = [];
423
+ for (const arg of args) {
424
+ if (arg.startsWith("--app-html=")) {
425
+ appHtmlPath = arg.slice("--app-html=".length);
426
+ } else if (arg.startsWith("--port=")) {
427
+ port = Number(arg.slice("--port=".length)) || 0;
428
+ } else if (arg.startsWith("--theme=")) {
429
+ const requestedTheme = arg.slice("--theme=".length);
430
+ if (isPro || requestedTheme.trim().toLowerCase() === "code") {
431
+ store.setVisualTheme(requestedTheme);
432
+ }
433
+ } else if (arg === "--no-companion") {
434
+ disableCompanion = true;
435
+ } else if (arg === "--open") {
436
+ autoOpen = true;
437
+ } else if (!arg.startsWith("--")) {
438
+ filesToLoad.push(arg);
439
+ }
440
+ }
441
+ for (const filePath of filesToLoad) {
442
+ try {
443
+ const ds = await store.loadFromFile(filePath);
444
+ const truncSuffix = ds.truncatedForFreeTier ? ` (truncated from ${ds.sourceTotalRows.toLocaleString()} \u2014 Free tier limit: ${FREE_TIER_ROW_LIMIT.toLocaleString()} rows)` : "";
445
+ console.error(`[tinypivot-mcp] Loaded ${ds.name} (${ds.rows.length} rows)${truncSuffix}`);
446
+ } catch (err) {
447
+ console.error(`[tinypivot-mcp] Warning: failed to load "${filePath}":`, err instanceof Error ? err.message : err);
448
+ }
449
+ }
450
+ let companion;
451
+ if (!disableCompanion) {
452
+ try {
453
+ companion = await startCompanionServer({
454
+ store,
455
+ loadHtml: () => loadAppHtml(appHtmlPath),
456
+ licenseKey,
457
+ demoToken,
458
+ port
459
+ });
460
+ console.error(`[tinypivot-mcp] Companion Data IDE ready at ${companion.url}`);
461
+ if (autoOpen)
462
+ openInBrowser(companion.url);
463
+ } catch (err) {
464
+ console.error("[tinypivot-mcp] Companion server disabled (could not bind localhost):", err instanceof Error ? err.message : err);
465
+ }
466
+ }
467
+ const { server } = createTinyPivotMcpServer({
468
+ store,
469
+ appHtmlPath,
470
+ licenseKey,
471
+ demoToken,
472
+ companionUrl: companion?.url,
473
+ onStateChanged: () => companion?.broadcastUpdate()
474
+ });
475
+ const transport = new StdioServerTransport();
476
+ await server.connect(transport);
477
+ console.error("[tinypivot-mcp] Ready on stdio (TinyPivot MCP App + Terminal Companion)");
478
+ const cleanup = () => {
479
+ void companion?.close().finally(() => process.exit(0));
480
+ };
481
+ process.on("SIGINT", cleanup);
482
+ process.on("SIGTERM", cleanup);
483
+ }
484
+ main().catch((err) => {
485
+ console.error("[tinypivot-mcp] Fatal startup error:", err);
486
+ process.exit(1);
487
+ });