@smallwebco/tinypivot-mcp 0.1.0 → 0.1.2

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.js CHANGED
@@ -3,405 +3,138 @@ import {
3
3
  DatasetStore,
4
4
  FREE_TIER_ROW_LIMIT,
5
5
  createTinyPivotMcpServer,
6
+ formatDatasetSummary,
7
+ formatPivotSummary,
8
+ formatTerminalChart,
9
+ isMcpLicenseKey,
6
10
  loadAppHtml,
11
+ parseDelimitedText,
7
12
  resolveLicenseKey,
13
+ runInitCommand,
14
+ runTuiCommand,
8
15
  startCompanionServer
9
- } from "./chunk-VLD3SN2I.js";
16
+ } from "./chunk-LZGTF5CC.js";
10
17
  import "./chunk-2ESYSVXG.js";
11
18
 
12
19
  // src/cli.ts
13
20
  import { spawn } from "child_process";
21
+ import { PassThrough } from "stream";
14
22
  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) {
23
+ function openInBrowser(url) {
24
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
25
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
87
26
  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;
27
+ const child = spawn(cmd, args, { stdio: "ignore", detached: true });
28
+ child.unref();
92
29
  } catch {
93
30
  }
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
31
  }
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");
32
+ function normalizeJsonRow(input) {
33
+ if (!input || typeof input !== "object" || Array.isArray(input))
34
+ return { value: input ?? null };
35
+ return input;
110
36
  }
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
- };
37
+ function parsePipedStdinData(rawText) {
38
+ const cleaned = rawText.charCodeAt(0) === 65279 ? rawText.slice(1) : rawText;
39
+ const trimmed = cleaned.trim();
40
+ if (!trimmed)
41
+ return { rows: [], format: "csv" };
42
+ if (trimmed.startsWith("[") || trimmed.startsWith("{")) {
43
+ try {
44
+ const parsed = JSON.parse(trimmed);
45
+ if (Array.isArray(parsed)) {
46
+ return { rows: parsed.map(normalizeJsonRow), format: "json" };
47
+ }
48
+ if (parsed && typeof parsed === "object") {
49
+ const firstArray = Object.values(parsed).find((v) => Array.isArray(v));
50
+ if (firstArray)
51
+ return { rows: firstArray.map(normalizeJsonRow), format: "json" };
52
+ return { rows: [normalizeJsonRow(parsed)], format: "json" };
53
+ }
54
+ } catch {
136
55
  }
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" };
56
+ const lines = trimmed.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
57
+ if (lines.length > 0) {
58
+ try {
59
+ const jsonlRows = lines.map((line) => normalizeJsonRow(JSON.parse(line)));
60
+ return { rows: jsonlRows, format: "jsonl" };
61
+ } catch {
62
+ }
141
63
  }
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
64
  }
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
- };
65
+ const firstLine = trimmed.split(/\r?\n/, 1)[0] ?? "";
66
+ const tabCount = (firstLine.match(/\t/g) ?? []).length;
67
+ const commaCount = (firstLine.match(/,/g) ?? []).length;
68
+ if (tabCount > 0 && tabCount >= commaCount) {
69
+ return { rows: parseDelimitedText(cleaned, " "), format: "tsv" };
213
70
  }
71
+ return { rows: parseDelimitedText(cleaned, ","), format: "csv" };
214
72
  }
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
- }
73
+ function looksLikeMcpJsonRpc(chunkText) {
74
+ const trimmed = chunkText.trimStart();
75
+ if (trimmed.startsWith("Content-Length:"))
76
+ return true;
77
+ return trimmed.startsWith("{") && /"jsonrpc"\s*:\s*"2\.0"/.test(trimmed);
273
78
  }
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"
79
+ function probeNonTtyStdin() {
80
+ return new Promise((resolve) => {
81
+ const chunks = [];
82
+ let totalBytes = 0;
83
+ let settled = false;
84
+ const finish = (mode, ended) => {
85
+ if (settled)
86
+ return;
87
+ settled = true;
88
+ process.stdin.off("data", onData);
89
+ process.stdin.off("end", onEnd);
90
+ process.stdin.off("error", onError);
91
+ process.stdin.pause();
92
+ resolve({ mode, buffered: Buffer.concat(chunks), ended });
93
+ };
94
+ const onData = (chunk) => {
95
+ const buf = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
96
+ chunks.push(buf);
97
+ totalBytes += buf.length;
98
+ const preview = Buffer.concat(chunks).toString("utf8");
99
+ const trimmed = preview.trimStart();
100
+ if (!trimmed)
101
+ return;
102
+ if (looksLikeMcpJsonRpc(trimmed)) {
103
+ finish("mcp", false);
104
+ return;
105
+ }
106
+ if (trimmed.includes("\n") || totalBytes >= 512 || !trimmed.startsWith("{") && !trimmed.startsWith("C")) {
107
+ finish("pipe", false);
108
+ }
305
109
  };
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)
110
+ const onEnd = () => {
111
+ const combined = Buffer.concat(chunks);
112
+ const text = combined.toString("utf8").trim();
113
+ if (!text) {
114
+ finish("empty", true);
115
+ return;
116
+ }
117
+ finish(looksLikeMcpJsonRpc(text) ? "mcp" : "pipe", true);
313
118
  };
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("");
119
+ const onError = () => finish("empty", true);
120
+ process.stdin.on("data", onData);
121
+ process.stdin.on("end", onEnd);
122
+ process.stdin.on("error", onError);
123
+ process.stdin.resume();
124
+ });
394
125
  }
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
- }
126
+ async function readRemainingStdin(initial, alreadyEnded) {
127
+ if (alreadyEnded)
128
+ return initial.toString("utf8");
129
+ const chunks = initial.length > 0 ? [initial] : [];
130
+ return new Promise((resolve, reject) => {
131
+ process.stdin.on("data", (chunk) => {
132
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk);
133
+ });
134
+ process.stdin.once("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
135
+ process.stdin.once("error", reject);
136
+ process.stdin.resume();
137
+ });
405
138
  }
406
139
  async function main() {
407
140
  const args = process.argv.slice(2);
@@ -409,60 +142,151 @@ async function main() {
409
142
  await runInitCommand(args.slice(1));
410
143
  return;
411
144
  }
412
- const licenseKey = resolveLicenseKey();
145
+ if (args[0] === "tui" || args[0] === "attach") {
146
+ await runTuiCommand(args.slice(1));
147
+ return;
148
+ }
149
+ const rawLicenseKey = resolveLicenseKey();
150
+ const licenseKey = isMcpLicenseKey(rawLicenseKey) ? rawLicenseKey : void 0;
413
151
  const demoToken = process.env.TINYPIVOT_DEMO_TOKEN;
414
- const isPro = Boolean(licenseKey && licenseKey.startsWith("TP-") || demoToken);
152
+ const isPro = Boolean(licenseKey || demoToken);
415
153
  const store = new DatasetStore({
416
154
  maxRowsPerDataset: isPro ? Number.POSITIVE_INFINITY : FREE_TIER_ROW_LIMIT
417
155
  });
418
156
  let appHtmlPath;
157
+ let explicitPort = false;
419
158
  let port = process.env.TINYPIVOT_PORT ? Number(process.env.TINYPIVOT_PORT) : 0;
420
159
  let disableCompanion = process.env.TINYPIVOT_NO_COMPANION === "1";
421
160
  let autoOpen = false;
161
+ let forceStdinPipe = false;
162
+ let showPivotOutput = false;
163
+ let datasetName;
422
164
  const filesToLoad = [];
423
165
  for (const arg of args) {
424
166
  if (arg.startsWith("--app-html=")) {
425
167
  appHtmlPath = arg.slice("--app-html=".length);
426
168
  } else if (arg.startsWith("--port=")) {
427
169
  port = Number(arg.slice("--port=".length)) || 0;
170
+ explicitPort = true;
428
171
  } else if (arg.startsWith("--theme=")) {
429
172
  const requestedTheme = arg.slice("--theme=".length);
430
173
  if (isPro || requestedTheme.trim().toLowerCase() === "code") {
431
174
  store.setVisualTheme(requestedTheme);
432
175
  }
176
+ } else if (arg.startsWith("--name=")) {
177
+ datasetName = arg.slice("--name=".length).trim() || void 0;
433
178
  } else if (arg === "--no-companion") {
434
179
  disableCompanion = true;
435
180
  } else if (arg === "--open") {
436
181
  autoOpen = true;
182
+ } else if (arg === "--stdin" || arg === "-") {
183
+ forceStdinPipe = true;
184
+ } else if (arg === "--pivot") {
185
+ showPivotOutput = true;
437
186
  } else if (!arg.startsWith("--")) {
438
187
  filesToLoad.push(arg);
439
188
  }
440
189
  }
190
+ let companion;
191
+ let companionPromise = null;
192
+ const ensureCompanionStarted = () => {
193
+ if (disableCompanion)
194
+ return Promise.resolve(void 0);
195
+ if (companion)
196
+ return Promise.resolve(companion);
197
+ if (companionPromise)
198
+ return companionPromise;
199
+ companionPromise = startCompanionServer({
200
+ store,
201
+ loadHtml: () => loadAppHtml(appHtmlPath),
202
+ licenseKey,
203
+ demoToken,
204
+ port
205
+ }).then((handle) => {
206
+ companion = handle;
207
+ console.error(`[tinypivot-mcp] Companion Data IDE ready at ${handle.url}`);
208
+ if (autoOpen)
209
+ openInBrowser(handle.url);
210
+ return handle;
211
+ }).catch((err) => {
212
+ console.error("[tinypivot-mcp] Companion server disabled (could not bind localhost):", err instanceof Error ? err.message : err);
213
+ return void 0;
214
+ });
215
+ return companionPromise;
216
+ };
217
+ let shuttingDown = false;
218
+ const cleanup = () => {
219
+ if (shuttingDown)
220
+ return;
221
+ shuttingDown = true;
222
+ void (companion?.close() ?? Promise.resolve()).finally(() => process.exit(0));
223
+ };
224
+ process.on("SIGINT", cleanup);
225
+ process.on("SIGTERM", cleanup);
226
+ let probe = null;
227
+ if (forceStdinPipe) {
228
+ const raw = await readRemainingStdin(Buffer.alloc(0), false);
229
+ probe = { mode: raw.trim() ? "pipe" : "empty", buffered: Buffer.from(raw, "utf8"), ended: true };
230
+ } else if (!process.stdin.isTTY && filesToLoad.length === 0) {
231
+ probe = await probeNonTtyStdin();
232
+ }
233
+ if (probe?.mode === "pipe") {
234
+ const rawText = await readRemainingStdin(probe.buffered, probe.ended);
235
+ const { rows, format } = parsePipedStdinData(rawText);
236
+ if (rows.length === 0) {
237
+ console.error("[tinypivot-mcp] No tabular rows detected on stdin.");
238
+ process.exit(1);
239
+ }
240
+ const ds = store.register({
241
+ name: datasetName || `stdin (${format.toUpperCase()})`,
242
+ source: `stdin:${format}`,
243
+ ingestionMode: "direct",
244
+ rows
245
+ });
246
+ const truncSuffix = ds.truncatedForFreeTier ? ` (truncated from ${ds.sourceTotalRows.toLocaleString()} \u2014 Free tier limit: ${FREE_TIER_ROW_LIMIT.toLocaleString()} rows)` : "";
247
+ console.error(`[tinypivot-mcp] Loaded ${ds.name} (${ds.rows.length.toLocaleString()} rows)${truncSuffix}`);
248
+ const chartCard = formatTerminalChart(ds, ds.chartConfig, { showBranding: !isPro });
249
+ if (chartCard) {
250
+ console.log(chartCard);
251
+ } else {
252
+ console.log(formatDatasetSummary(ds, void 0, { showBranding: !isPro }));
253
+ }
254
+ if (showPivotOutput && ds.pivotConfig?.valueFields?.length) {
255
+ const pivotCard = formatPivotSummary(ds, {
256
+ rowFields: ds.pivotConfig.rowFields ?? [],
257
+ columnFields: ds.pivotConfig.columnFields ?? [],
258
+ valueFields: ds.pivotConfig.valueFields,
259
+ showRowTotals: ds.pivotConfig.showRowTotals ?? true,
260
+ showColumnTotals: ds.pivotConfig.showColumnTotals ?? true
261
+ }, void 0, { showBranding: !isPro });
262
+ console.log(`
263
+ ${pivotCard}`);
264
+ }
265
+ if ((autoOpen || explicitPort) && !disableCompanion) {
266
+ const handle = await ensureCompanionStarted();
267
+ if (handle) {
268
+ console.error(`[tinypivot-mcp] Serving live Companion IDE at ${handle.url} (press Ctrl+C to stop)`);
269
+ await new Promise(() => {
270
+ });
271
+ }
272
+ }
273
+ return;
274
+ }
275
+ if (probe?.mode === "empty") {
276
+ return;
277
+ }
441
278
  for (const filePath of filesToLoad) {
442
279
  try {
443
- const ds = await store.loadFromFile(filePath);
280
+ const ds = await store.loadFromFile(filePath, datasetName);
444
281
  const truncSuffix = ds.truncatedForFreeTier ? ` (truncated from ${ds.sourceTotalRows.toLocaleString()} \u2014 Free tier limit: ${FREE_TIER_ROW_LIMIT.toLocaleString()} rows)` : "";
445
282
  console.error(`[tinypivot-mcp] Loaded ${ds.name} (${ds.rows.length} rows)${truncSuffix}`);
446
283
  } catch (err) {
447
284
  console.error(`[tinypivot-mcp] Warning: failed to load "${filePath}":`, err instanceof Error ? err.message : err);
448
285
  }
449
286
  }
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
- }
287
+ const eagerCompanion = autoOpen || explicitPort || filesToLoad.length > 0;
288
+ if (eagerCompanion && !disableCompanion) {
289
+ await ensureCompanionStarted();
466
290
  }
467
291
  const { server } = createTinyPivotMcpServer({
468
292
  store,
@@ -470,16 +294,31 @@ async function main() {
470
294
  licenseKey,
471
295
  demoToken,
472
296
  companionUrl: companion?.url,
297
+ ensureCompanion: disableCompanion ? void 0 : async () => (await ensureCompanionStarted())?.url,
473
298
  onStateChanged: () => companion?.broadcastUpdate()
474
299
  });
475
- const transport = new StdioServerTransport();
300
+ let transport;
301
+ if (probe?.mode === "mcp") {
302
+ const passthrough = new PassThrough();
303
+ if (probe.buffered.length > 0)
304
+ passthrough.write(probe.buffered);
305
+ if (probe.ended)
306
+ passthrough.end();
307
+ else
308
+ process.stdin.pipe(passthrough);
309
+ transport = new StdioServerTransport(passthrough, process.stdout);
310
+ } else {
311
+ transport = new StdioServerTransport();
312
+ }
313
+ transport.onclose = cleanup;
476
314
  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);
315
+ console.error("[tinypivot-mcp] Ready on stdio (TinyPivot MCP App + Lazy Companion)");
316
+ if (probe?.ended) {
317
+ setTimeout(cleanup, 100);
318
+ } else {
319
+ process.stdin.once("end", cleanup);
320
+ process.stdin.once("close", cleanup);
321
+ }
483
322
  }
484
323
  main().catch((err) => {
485
324
  console.error("[tinypivot-mcp] Fatal startup error:", err);