@smallwebco/tinypivot-mcp 0.4.0 → 0.5.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 +15 -2
- package/dist/app/index.html +89 -87
- package/dist/{chunk-ZZOVYGIU.js → chunk-E6DYPT62.js} +467 -24
- package/dist/cli.js +2 -3
- package/dist/index.d.ts +91 -2
- package/dist/index.js +1 -1
- package/package.json +4 -4
- package/server.json +2 -2
|
@@ -10102,6 +10102,65 @@ import fs3 from "fs/promises";
|
|
|
10102
10102
|
import http from "http";
|
|
10103
10103
|
import path3 from "path";
|
|
10104
10104
|
|
|
10105
|
+
// src/analyst-endpoint.ts
|
|
10106
|
+
var ANALYST_ROW_LIMIT = 1e4;
|
|
10107
|
+
function schemaFor(dataset) {
|
|
10108
|
+
return {
|
|
10109
|
+
table: dataset.id,
|
|
10110
|
+
columns: dataset.columns.map((column) => ({
|
|
10111
|
+
name: column.name,
|
|
10112
|
+
type: column.type === "null" ? "unknown" : column.type,
|
|
10113
|
+
nullable: true
|
|
10114
|
+
}))
|
|
10115
|
+
};
|
|
10116
|
+
}
|
|
10117
|
+
function queryableDatasets(studio) {
|
|
10118
|
+
return studio.queryViews().flatMap((view) => studio.store.get(view.name) ?? []);
|
|
10119
|
+
}
|
|
10120
|
+
function chatTurns(messages) {
|
|
10121
|
+
if (!Array.isArray(messages))
|
|
10122
|
+
return [];
|
|
10123
|
+
return messages.flatMap((message) => {
|
|
10124
|
+
const { role, content } = message ?? {};
|
|
10125
|
+
return (role === "user" || role === "assistant") && typeof content === "string" ? [{ role, content }] : [];
|
|
10126
|
+
});
|
|
10127
|
+
}
|
|
10128
|
+
async function runQuery(studio, sql) {
|
|
10129
|
+
if (typeof sql !== "string" || !sql.trim())
|
|
10130
|
+
return { status: 400, body: { success: false, error: "Send one SELECT statement." } };
|
|
10131
|
+
try {
|
|
10132
|
+
const result = await studio.duck.run(sql, studio.queryViews(), ANALYST_ROW_LIMIT);
|
|
10133
|
+
return { status: 200, body: { success: true, data: result.rows, rowCount: result.rows.length, truncated: result.truncated } };
|
|
10134
|
+
} catch (error) {
|
|
10135
|
+
return { status: 200, body: { success: false, error: error instanceof Error ? error.message : String(error) } };
|
|
10136
|
+
}
|
|
10137
|
+
}
|
|
10138
|
+
async function chat(studio, messages) {
|
|
10139
|
+
const turns = chatTurns(messages);
|
|
10140
|
+
const question = turns.filter((turn) => turn.role === "user").at(-1)?.content.trim();
|
|
10141
|
+
if (!question)
|
|
10142
|
+
return { status: 400, body: { error: "Ask a question." } };
|
|
10143
|
+
return { status: 200, body: { content: await studio.ask(question, { turns }) } };
|
|
10144
|
+
}
|
|
10145
|
+
async function handleAnalystAction(studio, body) {
|
|
10146
|
+
switch (body.action) {
|
|
10147
|
+
case "list-tables":
|
|
10148
|
+
return { status: 200, body: { tables: queryableDatasets(studio).map((ds) => ({ name: ds.id, description: `${ds.name}: ${ds.rows.length.toLocaleString("en-US")} rows` })) } };
|
|
10149
|
+
case "get-schema": {
|
|
10150
|
+
const wanted = new Set(Array.isArray(body.tables) ? body.tables.map(String) : []);
|
|
10151
|
+
return { status: 200, body: { schemas: queryableDatasets(studio).filter((ds) => wanted.has(ds.id)).map(schemaFor) } };
|
|
10152
|
+
}
|
|
10153
|
+
case "get-all-schemas":
|
|
10154
|
+
return { status: 200, body: { schemas: queryableDatasets(studio).map(schemaFor) } };
|
|
10155
|
+
case "query":
|
|
10156
|
+
return runQuery(studio, body.sql);
|
|
10157
|
+
case "chat":
|
|
10158
|
+
return chat(studio, body.messages);
|
|
10159
|
+
default:
|
|
10160
|
+
return { status: 400, body: { error: `Unknown action: ${String(body.action)}` } };
|
|
10161
|
+
}
|
|
10162
|
+
}
|
|
10163
|
+
|
|
10105
10164
|
// src/limits.ts
|
|
10106
10165
|
var INTERACTIVE_ROW_LIMIT = 1e5;
|
|
10107
10166
|
var ROW_PAGE_SIZE = 25e3;
|
|
@@ -10113,9 +10172,35 @@ function isAllowedRequest(request, port) {
|
|
|
10113
10172
|
return false;
|
|
10114
10173
|
if (request.method === "GET" || request.method === "HEAD")
|
|
10115
10174
|
return true;
|
|
10116
|
-
if (request.
|
|
10117
|
-
return
|
|
10118
|
-
return
|
|
10175
|
+
if (request.origin)
|
|
10176
|
+
return allowedHosts.some((host) => request.origin === `http://${host}`);
|
|
10177
|
+
return request.studioHeader === "1";
|
|
10178
|
+
}
|
|
10179
|
+
function parseAttachment(value2) {
|
|
10180
|
+
const { label, text } = value2 ?? {};
|
|
10181
|
+
return typeof label === "string" && typeof text === "string" && text.trim() ? { label, text } : void 0;
|
|
10182
|
+
}
|
|
10183
|
+
function openAgentStream(studio, agentName, req, res) {
|
|
10184
|
+
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive" });
|
|
10185
|
+
res.write(": connected\n\n");
|
|
10186
|
+
const disconnect = studio.agent.connect({
|
|
10187
|
+
name: agentName,
|
|
10188
|
+
push: (note, text) => {
|
|
10189
|
+
if (res.writableEnded)
|
|
10190
|
+
return false;
|
|
10191
|
+
res.write(`event: message
|
|
10192
|
+
data: ${JSON.stringify({ id: note.id, kind: note.kind, text })}
|
|
10193
|
+
|
|
10194
|
+
`);
|
|
10195
|
+
return true;
|
|
10196
|
+
}
|
|
10197
|
+
});
|
|
10198
|
+
const keepAlive = setInterval(() => res.write(": ping\n\n"), 25e3);
|
|
10199
|
+
keepAlive.unref();
|
|
10200
|
+
req.on("close", () => {
|
|
10201
|
+
clearInterval(keepAlive);
|
|
10202
|
+
disconnect();
|
|
10203
|
+
});
|
|
10119
10204
|
}
|
|
10120
10205
|
function sendJson(res, status, body) {
|
|
10121
10206
|
res.writeHead(status, { "Content-Type": "application/json" });
|
|
@@ -10232,12 +10317,30 @@ data: ${JSON.stringify(payload)}
|
|
|
10232
10317
|
const text = typeof body.text === "string" ? body.text.trim() : "";
|
|
10233
10318
|
if (!text || text.length > MAX_NOTE_CHARS)
|
|
10234
10319
|
return sendJson(res, 400, { error: `Write a note of up to ${MAX_NOTE_CHARS.toLocaleString("en-US")} characters.` });
|
|
10235
|
-
const note = studio.addNote(text,
|
|
10320
|
+
const note = studio.addNote(text, {
|
|
10321
|
+
stepId: typeof body.stepId === "string" ? body.stepId : void 0,
|
|
10322
|
+
attachment: parseAttachment(body.attachment)
|
|
10323
|
+
});
|
|
10236
10324
|
return sendJson(res, 200, { note });
|
|
10237
10325
|
}
|
|
10238
10326
|
if (pathname === "/api/studio/note/delete") {
|
|
10239
10327
|
return sendJson(res, 200, { removed: typeof body.id === "string" && studio.removeNote(body.id) });
|
|
10240
10328
|
}
|
|
10329
|
+
if (pathname === "/api/studio/reply") {
|
|
10330
|
+
const text = typeof body.text === "string" ? body.text.trim() : "";
|
|
10331
|
+
if (!text)
|
|
10332
|
+
return sendJson(res, 400, { error: "Send the reply text." });
|
|
10333
|
+
studio.reply(text.slice(0, 2e4), typeof body.re === "string" ? body.re : void 0);
|
|
10334
|
+
return sendJson(res, 200, { ok: true });
|
|
10335
|
+
}
|
|
10336
|
+
if (pathname === "/api/studio/agent-status") {
|
|
10337
|
+
studio.setAgentBusy(body.busy === true);
|
|
10338
|
+
return sendJson(res, 200, { ok: true });
|
|
10339
|
+
}
|
|
10340
|
+
if (pathname === "/api/studio/analyst") {
|
|
10341
|
+
const result = await handleAnalystAction(studio, body);
|
|
10342
|
+
return sendJson(res, result.status, result.body);
|
|
10343
|
+
}
|
|
10241
10344
|
if (pathname === "/api/studio/show") {
|
|
10242
10345
|
try {
|
|
10243
10346
|
const dataset = await studio.showStep(String(body.stepId ?? ""));
|
|
@@ -10293,6 +10396,13 @@ data: ${JSON.stringify(studio.snapshot())}
|
|
|
10293
10396
|
req.on("close", () => sseClients.delete(res));
|
|
10294
10397
|
return;
|
|
10295
10398
|
}
|
|
10399
|
+
if (req.method === "GET" && pathname === "/api/studio/agent-stream") {
|
|
10400
|
+
if (!studio || req.headers[STUDIO_HEADER] !== "1")
|
|
10401
|
+
return sendJson(res, 403, { error: "Forbidden" });
|
|
10402
|
+
const agentName = (urlObj.searchParams.get("agent") || "agent").slice(0, 40);
|
|
10403
|
+
openAgentStream(studio, agentName, req, res);
|
|
10404
|
+
return;
|
|
10405
|
+
}
|
|
10296
10406
|
if (req.method === "GET" && pathname === "/api/studio") {
|
|
10297
10407
|
return studio ? sendJson(res, 200, studio.snapshot()) : sendJson(res, 404, { error: "Studio is not available." });
|
|
10298
10408
|
}
|
|
@@ -10465,7 +10575,7 @@ async function syncCompanionTheme(themeId: string): Promise<void> {
|
|
|
10465
10575
|
if (!parsed.url) return;
|
|
10466
10576
|
await fetch(\`\${parsed.url}/api/theme\`, {
|
|
10467
10577
|
method: "POST",
|
|
10468
|
-
headers: { "Content-Type": "application/json" },
|
|
10578
|
+
headers: { "Content-Type": "application/json", "x-tinypivot": "1" },
|
|
10469
10579
|
body: JSON.stringify({ theme: themeId }),
|
|
10470
10580
|
});
|
|
10471
10581
|
} catch {
|
|
@@ -10582,8 +10692,113 @@ interface TinyPivotCardEntryData {
|
|
|
10582
10692
|
themeId: string;
|
|
10583
10693
|
}
|
|
10584
10694
|
|
|
10695
|
+
// TinyPivot Studio bridge: messages the user sends from the Studio arrive here, go into this
|
|
10696
|
+
// session as a turn, and the agent's final answer goes back to the Studio.
|
|
10697
|
+
// The Studio link TinyPivot puts in its replies ("Studio: \u2026" or a card's "Live: \u2026").
|
|
10698
|
+
const STUDIO_LINK = /(?:Studio|Live): (http:[/][/]127[.]0[.]0[.]1:[0-9]+)/;
|
|
10699
|
+
const STUDIO_HEADERS = { "Content-Type": "application/json", "x-tinypivot": "1" };
|
|
10700
|
+
|
|
10701
|
+
function lastAssistantText(messages: unknown): string {
|
|
10702
|
+
if (!Array.isArray(messages)) return "";
|
|
10703
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
10704
|
+
const message = messages[i] as { role?: string; content?: unknown };
|
|
10705
|
+
if (message?.role !== "assistant") continue;
|
|
10706
|
+
if (typeof message.content === "string") return message.content.trim();
|
|
10707
|
+
if (!Array.isArray(message.content)) return "";
|
|
10708
|
+
return message.content
|
|
10709
|
+
.map(part => (part && typeof part === "object" && (part as { type?: string }).type === "text" ? String((part as { text?: unknown }).text ?? "") : ""))
|
|
10710
|
+
.join("\\n")
|
|
10711
|
+
.trim();
|
|
10712
|
+
}
|
|
10713
|
+
return "";
|
|
10714
|
+
}
|
|
10715
|
+
|
|
10716
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
10717
|
+
function createStudioBridge(pi: any) {
|
|
10718
|
+
let studioUrl: string | undefined;
|
|
10719
|
+
let stream: AbortController | undefined;
|
|
10720
|
+
let awaiting: string | undefined;
|
|
10721
|
+
|
|
10722
|
+
function handleFrame(frame: string): void {
|
|
10723
|
+
if (!frame.startsWith("event: message")) return;
|
|
10724
|
+
const data = frame.split("\\n").find(line => line.startsWith("data: "));
|
|
10725
|
+
if (!data) return;
|
|
10726
|
+
const message = JSON.parse(data.slice(6)) as { id: string; text: string };
|
|
10727
|
+
awaiting = message.id;
|
|
10728
|
+
pi.sendMessage(
|
|
10729
|
+
{ customType: "tinypivot-studio", content: message.text, display: true },
|
|
10730
|
+
{ triggerTurn: true, deliverAs: "steer" },
|
|
10731
|
+
);
|
|
10732
|
+
}
|
|
10733
|
+
|
|
10734
|
+
async function listen(url: string, signal: AbortSignal): Promise<void> {
|
|
10735
|
+
let delay = 1000;
|
|
10736
|
+
while (!signal.aborted) {
|
|
10737
|
+
try {
|
|
10738
|
+
const res = await fetch(url + "/api/studio/agent-stream?agent=pi", { headers: STUDIO_HEADERS, signal });
|
|
10739
|
+
if (!res.ok || !res.body) throw new Error("Studio stream " + res.status);
|
|
10740
|
+
delay = 1000;
|
|
10741
|
+
const reader = res.body.getReader();
|
|
10742
|
+
const decoder = new TextDecoder();
|
|
10743
|
+
let buffer = "";
|
|
10744
|
+
for (;;) {
|
|
10745
|
+
const { value, done } = await reader.read();
|
|
10746
|
+
if (done) break;
|
|
10747
|
+
buffer += decoder.decode(value, { stream: true });
|
|
10748
|
+
let end = buffer.indexOf("\\n\\n");
|
|
10749
|
+
while (end >= 0) {
|
|
10750
|
+
handleFrame(buffer.slice(0, end));
|
|
10751
|
+
buffer = buffer.slice(end + 2);
|
|
10752
|
+
end = buffer.indexOf("\\n\\n");
|
|
10753
|
+
}
|
|
10754
|
+
}
|
|
10755
|
+
} catch {
|
|
10756
|
+
// The Studio restarted or closed; try again after a pause.
|
|
10757
|
+
}
|
|
10758
|
+
if (signal.aborted) return;
|
|
10759
|
+
await new Promise(resolve => setTimeout(resolve, delay));
|
|
10760
|
+
delay = Math.min(delay * 2, 30000);
|
|
10761
|
+
}
|
|
10762
|
+
}
|
|
10763
|
+
|
|
10764
|
+
return {
|
|
10765
|
+
/** Starts listening to the Studio named in a TinyPivot tool reply. */
|
|
10766
|
+
noticeToolText(text: string): void {
|
|
10767
|
+
const url = STUDIO_LINK.exec(text)?.[1];
|
|
10768
|
+
if (!url || url === studioUrl) return;
|
|
10769
|
+
stream?.abort();
|
|
10770
|
+
studioUrl = url;
|
|
10771
|
+
stream = new AbortController();
|
|
10772
|
+
void listen(url, stream.signal);
|
|
10773
|
+
void this.status(true);
|
|
10774
|
+
},
|
|
10775
|
+
/** Tells the Studio whether pi is working, so it can show progress. */
|
|
10776
|
+
async status(busy: boolean): Promise<void> {
|
|
10777
|
+
if (!studioUrl) return;
|
|
10778
|
+
await fetch(studioUrl + "/api/studio/agent-status", { method: "POST", headers: STUDIO_HEADERS, body: JSON.stringify({ busy }) }).catch(() => {});
|
|
10779
|
+
},
|
|
10780
|
+
async onAgentEnd(messages: unknown): Promise<void> {
|
|
10781
|
+
if (!awaiting || !studioUrl) return;
|
|
10782
|
+
const re = awaiting;
|
|
10783
|
+
awaiting = undefined;
|
|
10784
|
+
const text = lastAssistantText(messages);
|
|
10785
|
+
if (!text) return;
|
|
10786
|
+
await fetch(studioUrl + "/api/studio/reply", { method: "POST", headers: STUDIO_HEADERS, body: JSON.stringify({ re, text }) }).catch(() => {});
|
|
10787
|
+
},
|
|
10788
|
+
stop(): void {
|
|
10789
|
+
stream?.abort();
|
|
10790
|
+
stream = undefined;
|
|
10791
|
+
},
|
|
10792
|
+
};
|
|
10793
|
+
}
|
|
10794
|
+
|
|
10585
10795
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
10586
10796
|
export default function (pi: any) {
|
|
10797
|
+
const studio = createStudioBridge(pi);
|
|
10798
|
+
pi.on("agent_start", () => studio.status(true));
|
|
10799
|
+
pi.on("agent_end", (event: { messages?: unknown }) => studio.onAgentEnd(event?.messages));
|
|
10800
|
+
pi.on("agent_settled", () => studio.status(false));
|
|
10801
|
+
pi.on("session_shutdown", () => studio.stop());
|
|
10587
10802
|
if (typeof pi.registerEntryRenderer === "function") {
|
|
10588
10803
|
pi.registerEntryRenderer("tinypivot-card", (entry: { data?: TinyPivotCardEntryData }) => {
|
|
10589
10804
|
const data = entry?.data;
|
|
@@ -10604,11 +10819,12 @@ export default function (pi: any) {
|
|
|
10604
10819
|
}
|
|
10605
10820
|
|
|
10606
10821
|
pi.on("tool_execution_end", (event: { toolName?: string; result?: unknown; isError?: boolean }, ctx: { hasUI?: boolean }) => {
|
|
10607
|
-
if (
|
|
10608
|
-
if (!event?.toolName || !isTinyPivotTool(event.toolName)) return;
|
|
10609
|
-
|
|
10822
|
+
if (event?.isError) return;
|
|
10610
10823
|
const text = extractResultText(event.result);
|
|
10611
10824
|
if (!text) return;
|
|
10825
|
+
// TinyPivot calls made through codemode arrive under another tool's name, so look at the text.
|
|
10826
|
+
studio.noticeToolText(text);
|
|
10827
|
+
if (!event?.toolName || !isTinyPivotTool(event.toolName) || ctx?.hasUI === false) return;
|
|
10612
10828
|
const cards = extractTinyPivotCards(text);
|
|
10613
10829
|
if (cards.length === 0) return;
|
|
10614
10830
|
|
|
@@ -11465,6 +11681,60 @@ async function executeReadOnlyPostgresQuery(config, sql) {
|
|
|
11465
11681
|
import fs7 from "fs";
|
|
11466
11682
|
import path7 from "path";
|
|
11467
11683
|
|
|
11684
|
+
// src/agent-bridge.ts
|
|
11685
|
+
var AgentBridge = class {
|
|
11686
|
+
constructor(onChange) {
|
|
11687
|
+
this.onChange = onChange;
|
|
11688
|
+
}
|
|
11689
|
+
connectors = /* @__PURE__ */ new Set();
|
|
11690
|
+
waiters = /* @__PURE__ */ new Map();
|
|
11691
|
+
/** Adds a way to reach the agent; the returned function removes it. */
|
|
11692
|
+
connect(connector) {
|
|
11693
|
+
this.connectors.add(connector);
|
|
11694
|
+
this.onChange();
|
|
11695
|
+
return () => {
|
|
11696
|
+
if (this.connectors.delete(connector))
|
|
11697
|
+
this.onChange();
|
|
11698
|
+
};
|
|
11699
|
+
}
|
|
11700
|
+
/** Names of the ways that reach the agent right now. */
|
|
11701
|
+
live() {
|
|
11702
|
+
return [...this.connectors].map((connector) => connector.name);
|
|
11703
|
+
}
|
|
11704
|
+
/** Delivers into the conversation through the first connector that can. */
|
|
11705
|
+
push(note, text) {
|
|
11706
|
+
for (const connector of this.connectors) {
|
|
11707
|
+
if (connector.push?.(note, text))
|
|
11708
|
+
return connector.name;
|
|
11709
|
+
}
|
|
11710
|
+
return void 0;
|
|
11711
|
+
}
|
|
11712
|
+
completer() {
|
|
11713
|
+
return [...this.connectors].find((connector) => connector.complete)?.complete;
|
|
11714
|
+
}
|
|
11715
|
+
/** Resolves with the agent's answer to `id`, or undefined after `ms`. */
|
|
11716
|
+
waitForReply(id, ms) {
|
|
11717
|
+
return new Promise((resolve) => {
|
|
11718
|
+
const timer = setTimeout(() => {
|
|
11719
|
+
this.waiters.delete(id);
|
|
11720
|
+
resolve(void 0);
|
|
11721
|
+
}, ms);
|
|
11722
|
+
timer.unref?.();
|
|
11723
|
+
this.waiters.set(id, (text) => {
|
|
11724
|
+
clearTimeout(timer);
|
|
11725
|
+
this.waiters.delete(id);
|
|
11726
|
+
resolve(text);
|
|
11727
|
+
});
|
|
11728
|
+
});
|
|
11729
|
+
}
|
|
11730
|
+
/** Hands an answer to whoever waits for `re`, or to the oldest waiter when `re` is unknown. */
|
|
11731
|
+
answer(text, re) {
|
|
11732
|
+
const waiter = re && this.waiters.get(re) || this.waiters.values().next().value;
|
|
11733
|
+
waiter?.(text);
|
|
11734
|
+
return Boolean(waiter);
|
|
11735
|
+
}
|
|
11736
|
+
};
|
|
11737
|
+
|
|
11468
11738
|
// src/duckdb.ts
|
|
11469
11739
|
import { spawn } from "child_process";
|
|
11470
11740
|
import fs5 from "fs";
|
|
@@ -11725,6 +11995,21 @@ function formatHistoryList(entries) {
|
|
|
11725
11995
|
// src/studio.ts
|
|
11726
11996
|
var STEPS_IN_MEMORY = 300;
|
|
11727
11997
|
var HISTORY_IN_SNAPSHOT = 50;
|
|
11998
|
+
var ANSWER_WAIT_MS = 4 * 60 * 1e3;
|
|
11999
|
+
var ATTACHMENT_MAX_CHARS = 6e3;
|
|
12000
|
+
var AGENT_NAMES = {
|
|
12001
|
+
"claude-code": "Claude Code",
|
|
12002
|
+
"claude-ai": "Claude Desktop",
|
|
12003
|
+
"pi": "pi",
|
|
12004
|
+
"opencode": "OpenCode",
|
|
12005
|
+
"cursor-vscode": "Cursor",
|
|
12006
|
+
"codex-mcp-client": "Codex",
|
|
12007
|
+
"antigravity": "Antigravity",
|
|
12008
|
+
"Visual Studio Code": "VS Code"
|
|
12009
|
+
};
|
|
12010
|
+
function agentLabel(clientName) {
|
|
12011
|
+
return clientName && (AGENT_NAMES[clientName] ?? clientName) || "your agent";
|
|
12012
|
+
}
|
|
11728
12013
|
var TRACE_FILE_MAX_BYTES = 5 * 1024 * 1024;
|
|
11729
12014
|
function describeView(dataset) {
|
|
11730
12015
|
const pivot = dataset.pivotConfig;
|
|
@@ -11768,6 +12053,10 @@ function historyTableExpression(entry, rowsPath) {
|
|
|
11768
12053
|
}
|
|
11769
12054
|
return rowsPath ? `read_json_auto(${quoteLiteral(rowsPath)})` : void 0;
|
|
11770
12055
|
}
|
|
12056
|
+
function withoutCards(text) {
|
|
12057
|
+
const stripped = text.replace(/```text\n[\s\S]*?```\n?/g, (block) => /[╭╰│┤├]/.test(block) ? "" : block);
|
|
12058
|
+
return stripped.replace(/\n{3,}/g, "\n\n").trim() || text.trim();
|
|
12059
|
+
}
|
|
11771
12060
|
var sequence = 0;
|
|
11772
12061
|
function nextId(prefix) {
|
|
11773
12062
|
sequence += 1;
|
|
@@ -11787,6 +12076,10 @@ var Studio = class {
|
|
|
11787
12076
|
pullsByDataset = /* @__PURE__ */ new Map();
|
|
11788
12077
|
listeners = /* @__PURE__ */ new Set();
|
|
11789
12078
|
changeQueued = false;
|
|
12079
|
+
/** Ways to reach the user's agent: live channels, sampling, or nothing (queued notes). */
|
|
12080
|
+
agent = new AgentBridge(() => this.changed());
|
|
12081
|
+
agentName;
|
|
12082
|
+
agentBusy = false;
|
|
11790
12083
|
/** Calls `listener` (once per tick at most) whenever the trace or the notes change. */
|
|
11791
12084
|
subscribe(listener) {
|
|
11792
12085
|
this.listeners.add(listener);
|
|
@@ -11811,9 +12104,22 @@ var Studio = class {
|
|
|
11811
12104
|
notes: this.pendingNotes(),
|
|
11812
12105
|
history: this.history.enabled ? this.history.list(HISTORY_IN_SNAPSHOT) : [],
|
|
11813
12106
|
historyEnabled: this.history.enabled,
|
|
11814
|
-
loadedIds: this.store.listMetadata(sessionKey).map((meta) => meta.id)
|
|
12107
|
+
loadedIds: this.store.listMetadata(sessionKey).map((meta) => meta.id),
|
|
12108
|
+
agent: { name: this.agentName ? agentLabel(this.agentName) : void 0, live: this.agent.live(), busy: this.agentBusy }
|
|
11815
12109
|
};
|
|
11816
12110
|
}
|
|
12111
|
+
/** Whether the agent is in the middle of a turn, as its extension reports it. */
|
|
12112
|
+
setAgentBusy(busy) {
|
|
12113
|
+
if (busy === this.agentBusy)
|
|
12114
|
+
return;
|
|
12115
|
+
this.agentBusy = busy;
|
|
12116
|
+
this.changed();
|
|
12117
|
+
}
|
|
12118
|
+
/** The MCP client's name, e.g. `claude-code`, shown in the Studio. */
|
|
12119
|
+
setAgentName(name) {
|
|
12120
|
+
this.agentName = name;
|
|
12121
|
+
this.changed();
|
|
12122
|
+
}
|
|
11817
12123
|
get traceFile() {
|
|
11818
12124
|
return path7.join(this.history.dir, "trace.jsonl");
|
|
11819
12125
|
}
|
|
@@ -11963,13 +12269,68 @@ var Studio = class {
|
|
|
11963
12269
|
});
|
|
11964
12270
|
return dataset;
|
|
11965
12271
|
}
|
|
11966
|
-
/**
|
|
11967
|
-
|
|
11968
|
-
|
|
11969
|
-
|
|
11970
|
-
|
|
12272
|
+
/**
|
|
12273
|
+
* Sends the user's message to the agent: straight into its conversation when a live connector
|
|
12274
|
+
* takes it, otherwise queued for its next TinyPivot reply.
|
|
12275
|
+
*/
|
|
12276
|
+
addNote(text, options = {}) {
|
|
12277
|
+
const attachment = options.attachment && { label: options.attachment.label.slice(0, 120), text: options.attachment.text.slice(0, ATTACHMENT_MAX_CHARS) };
|
|
12278
|
+
const note = {
|
|
12279
|
+
id: nextId(options.kind === "question" ? "ask" : "note"),
|
|
12280
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
12281
|
+
text: text.trim(),
|
|
12282
|
+
kind: options.kind ?? "note",
|
|
12283
|
+
delivery: "queued",
|
|
12284
|
+
...options.stepId ? { stepId: options.stepId } : {},
|
|
12285
|
+
...attachment ? { attachment } : {}
|
|
12286
|
+
};
|
|
12287
|
+
if (this.agent.push(note, this.describeNote(note, { withSource: true })))
|
|
12288
|
+
note.delivery = "live";
|
|
12289
|
+
else
|
|
12290
|
+
this.notes.push(note);
|
|
12291
|
+
this.record({ actor: "user", tool: note.kind === "question" ? "ask" : "note", why: note.text, ...attachment ? { view: `with ${attachment.label}` } : {} });
|
|
11971
12292
|
return note;
|
|
11972
12293
|
}
|
|
12294
|
+
/**
|
|
12295
|
+
* How a message reads to the agent: the text, the step it is about, and any attached data.
|
|
12296
|
+
* `withSource` says where it came from, for messages that arrive on their own in the conversation.
|
|
12297
|
+
*/
|
|
12298
|
+
describeNote(note, { withSource = false } = {}) {
|
|
12299
|
+
const step = note.stepId ? this.steps.find((s) => s.id === note.stepId) : void 0;
|
|
12300
|
+
const source = withSource || note.kind === "question" ? `${note.kind === "question" ? "Question" : "Message"} from the user in TinyPivot Studio: ` : "";
|
|
12301
|
+
const lines = [`${source}${note.text}`];
|
|
12302
|
+
if (step)
|
|
12303
|
+
lines.push(`About the step "${step.why ?? step.view ?? step.tool}"${step.datasetId ? ` on dataset \`${step.datasetId}\`` : ""}${step.sql ? `, SQL: ${step.sql.replace(/\s+/g, " ")}` : ""}`);
|
|
12304
|
+
if (note.attachment)
|
|
12305
|
+
lines.push(`Attached (${note.attachment.label}):`, note.attachment.text);
|
|
12306
|
+
return lines.join("\n");
|
|
12307
|
+
}
|
|
12308
|
+
/**
|
|
12309
|
+
* Answers an AI Analyst question with the user's own agent: its model directly when the host
|
|
12310
|
+
* offers sampling, otherwise through its conversation, waiting for the reply.
|
|
12311
|
+
*/
|
|
12312
|
+
async ask(question, options = {}) {
|
|
12313
|
+
const complete = this.agent.completer();
|
|
12314
|
+
if (complete) {
|
|
12315
|
+
this.record({ actor: "user", tool: "ask", why: question });
|
|
12316
|
+
const answer2 = await complete(options.turns?.length ? options.turns : [{ role: "user", content: question }]);
|
|
12317
|
+
this.reply(answer2);
|
|
12318
|
+
return answer2;
|
|
12319
|
+
}
|
|
12320
|
+
const note = this.addNote(question, { kind: "question", attachment: options.attachment });
|
|
12321
|
+
const name = agentLabel(this.agentName);
|
|
12322
|
+
if (note.delivery === "queued")
|
|
12323
|
+
return `${name} is not connected to the Studio live, so this question goes to it with its next TinyPivot reply. To ask now, use Copy as prompt in the Studio and paste it into ${name}.`;
|
|
12324
|
+
const answer = await this.agent.waitForReply(note.id, options.waitMs ?? ANSWER_WAIT_MS);
|
|
12325
|
+
return answer ?? `${name} is still working on this. Its answer will appear in the Studio trace.`;
|
|
12326
|
+
}
|
|
12327
|
+
/** The agent's answer to a Studio message: recorded in the trace and handed to whoever waits for it. */
|
|
12328
|
+
reply(text, re) {
|
|
12329
|
+
const answer = withoutCards(text);
|
|
12330
|
+
const step = this.record({ actor: "agent", tool: "reply", why: answer });
|
|
12331
|
+
this.agent.answer(answer, re);
|
|
12332
|
+
return step;
|
|
12333
|
+
}
|
|
11973
12334
|
/** Drops a queued note the user no longer wants sent. */
|
|
11974
12335
|
removeNote(id) {
|
|
11975
12336
|
const before = this.notes.length;
|
|
@@ -11985,11 +12346,7 @@ var Studio = class {
|
|
|
11985
12346
|
takeNotes() {
|
|
11986
12347
|
if (this.notes.length === 0)
|
|
11987
12348
|
return "";
|
|
11988
|
-
const lines = this.notes.map((note) => {
|
|
11989
|
-
const step = note.stepId ? this.steps.find((s) => s.id === note.stepId) : void 0;
|
|
11990
|
-
const about = step ? ` (about "${step.why ?? step.view ?? step.tool}"${step.sql ? `, SQL: ${step.sql.replace(/\s+/g, " ")}` : ""})` : "";
|
|
11991
|
-
return `- ${note.text}${about}`;
|
|
11992
|
-
});
|
|
12349
|
+
const lines = this.notes.map((note) => `- ${this.describeNote(note).replace(/\n/g, "\n ")}`);
|
|
11993
12350
|
this.notes = [];
|
|
11994
12351
|
this.changed();
|
|
11995
12352
|
return `
|
|
@@ -12007,6 +12364,43 @@ import { fileURLToPath as fileURLToPath2 } from "url";
|
|
|
12007
12364
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
12008
12365
|
import { z } from "zod";
|
|
12009
12366
|
|
|
12367
|
+
// src/claude-channel.ts
|
|
12368
|
+
import { execFileSync } from "child_process";
|
|
12369
|
+
import process2 from "process";
|
|
12370
|
+
var CHANNEL_NOTIFICATION = "notifications/claude/channel";
|
|
12371
|
+
var CHANNEL_FLAGS = ["--channels", "--dangerously-load-development-channels"];
|
|
12372
|
+
var ANCESTORS_TO_CHECK = 5;
|
|
12373
|
+
function commandEnablesChannel(command, serverName) {
|
|
12374
|
+
if (!/\bclaude\b/.test(command) || !CHANNEL_FLAGS.some((flag) => command.includes(flag)))
|
|
12375
|
+
return false;
|
|
12376
|
+
return new RegExp(`(?:server:)?${serverName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`).test(command);
|
|
12377
|
+
}
|
|
12378
|
+
function processInfo(pid) {
|
|
12379
|
+
try {
|
|
12380
|
+
const out = execFileSync("ps", ["-o", "ppid=,command=", "-p", String(pid)], { encoding: "utf8", timeout: 2e3 }).trim();
|
|
12381
|
+
const match = /^(\d+)\s+(.*)$/s.exec(out);
|
|
12382
|
+
return match ? { ppid: Number(match[1]), command: match[2] } : void 0;
|
|
12383
|
+
} catch {
|
|
12384
|
+
return void 0;
|
|
12385
|
+
}
|
|
12386
|
+
}
|
|
12387
|
+
function claudeChannelEnabled(serverName = "tinypivot", env = process2.env) {
|
|
12388
|
+
if (env.TINYPIVOT_CLAUDE_CHANNEL === "1")
|
|
12389
|
+
return true;
|
|
12390
|
+
if (env.TINYPIVOT_CLAUDE_CHANNEL === "0" || process2.platform === "win32")
|
|
12391
|
+
return false;
|
|
12392
|
+
let pid = process2.ppid;
|
|
12393
|
+
for (let i = 0; i < ANCESTORS_TO_CHECK && pid > 1; i++) {
|
|
12394
|
+
const info = processInfo(pid);
|
|
12395
|
+
if (!info)
|
|
12396
|
+
return false;
|
|
12397
|
+
if (commandEnablesChannel(info.command, serverName))
|
|
12398
|
+
return true;
|
|
12399
|
+
pid = info.ppid;
|
|
12400
|
+
}
|
|
12401
|
+
return false;
|
|
12402
|
+
}
|
|
12403
|
+
|
|
12010
12404
|
// src/profile.ts
|
|
12011
12405
|
var TOP_VALUES = 3;
|
|
12012
12406
|
function compactNumber(value2) {
|
|
@@ -12075,7 +12469,7 @@ import fsSync2 from "fs";
|
|
|
12075
12469
|
import os6 from "os";
|
|
12076
12470
|
import path8 from "path";
|
|
12077
12471
|
var DEFAULT_TELEMETRY_URL = "https://tiny-pivot.com/api/telemetry";
|
|
12078
|
-
var PACKAGE_VERSION = "0.
|
|
12472
|
+
var PACKAGE_VERSION = "0.5.0";
|
|
12079
12473
|
function isTelemetryEnabled() {
|
|
12080
12474
|
if (process.env.TINYPIVOT_TELEMETRY === "0" || process.env.TINYPIVOT_TELEMETRY === "false")
|
|
12081
12475
|
return false;
|
|
@@ -12154,7 +12548,7 @@ function recordTelemetry(ev) {
|
|
|
12154
12548
|
var APP_RESOURCE_URI = "ui://tinypivot/app.html";
|
|
12155
12549
|
var APP_MIME_TYPE = "text/html;profile=mcp-app";
|
|
12156
12550
|
var LOAD_DATA_ROW_GUIDE = 50;
|
|
12157
|
-
function buildInstructions({ reprintCards = true } = {}) {
|
|
12551
|
+
function buildInstructions({ reprintCards = true, claudeChannel = false } = {}) {
|
|
12158
12552
|
const cards = reprintCards ? "In a terminal, show the returned ```text card verbatim with the Studio link in your reply, except in pi, whose TinyPivot extension already displays it." : "Do not reprint the ```text card: the user sees it in TinyPivot. Reply with the takeaways and the Studio link.";
|
|
12159
12553
|
return [
|
|
12160
12554
|
"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.",
|
|
@@ -12162,6 +12556,7 @@ function buildInstructions({ reprintCards = true } = {}) {
|
|
|
12162
12556
|
"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.",
|
|
12163
12557
|
"Use keepExisting: true only to compare datasets in one conversation; clear_datasets resets.",
|
|
12164
12558
|
"Pass why on every data call: one short sentence the user sees in the TinyPivot Studio trace. Replies may end with notes the user wrote in the Studio; act on them.",
|
|
12559
|
+
...claudeChannel ? ['Messages from TinyPivot Studio arrive as <channel source="tinypivot"> events: do what they ask, then answer with studio_reply, passing the message id as re.'] : [],
|
|
12165
12560
|
cards
|
|
12166
12561
|
].join(" ");
|
|
12167
12562
|
}
|
|
@@ -12373,6 +12768,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12373
12768
|
options.onStateChanged?.();
|
|
12374
12769
|
};
|
|
12375
12770
|
const reprintCards = options.reprintCards ?? process.env.TINYPIVOT_REPRINT_CARDS !== "0";
|
|
12771
|
+
const claudeChannel = options.claudeChannel ?? claudeChannelEnabled();
|
|
12376
12772
|
const cardFormat = { showBranding: !isPro2, reprintNote: reprintCards };
|
|
12377
12773
|
const postgresConfig = options.postgres ?? (process.env.DATABASE_URL ? {
|
|
12378
12774
|
connectionString: process.env.DATABASE_URL,
|
|
@@ -12381,14 +12777,15 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12381
12777
|
const server = new McpServer(
|
|
12382
12778
|
{
|
|
12383
12779
|
name: "tinypivot",
|
|
12384
|
-
version: "0.
|
|
12780
|
+
version: "0.5.0"
|
|
12385
12781
|
},
|
|
12386
12782
|
{
|
|
12387
12783
|
capabilities: {
|
|
12388
12784
|
resources: {},
|
|
12389
|
-
tools: {}
|
|
12785
|
+
tools: {},
|
|
12786
|
+
...claudeChannel ? { experimental: { "claude/channel": {} } } : {}
|
|
12390
12787
|
},
|
|
12391
|
-
instructions: buildInstructions({ reprintCards })
|
|
12788
|
+
instructions: buildInstructions({ reprintCards, claudeChannel })
|
|
12392
12789
|
}
|
|
12393
12790
|
);
|
|
12394
12791
|
const clientRendersWidget = () => clientSupportsMcpAppsUi(server.server.getClientCapabilities());
|
|
@@ -12428,6 +12825,47 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12428
12825
|
console.error(`[tinypivot-mcp] Could not prune history: ${error instanceof Error ? error.message : String(error)}`);
|
|
12429
12826
|
}
|
|
12430
12827
|
const withNotes = (text) => `${text}${studio.takeNotes()}`;
|
|
12828
|
+
const connectAgent = () => {
|
|
12829
|
+
studio.setAgentName(server.server.getClientVersion()?.name);
|
|
12830
|
+
if (claudeChannel) {
|
|
12831
|
+
studio.agent.connect({
|
|
12832
|
+
name: "Claude Code channel",
|
|
12833
|
+
push: (note, text) => {
|
|
12834
|
+
const content = `${text}
|
|
12835
|
+
|
|
12836
|
+
Answer with studio_reply (re: "${note.id}") so the user sees it in TinyPivot Studio.`;
|
|
12837
|
+
server.server.notification({ method: CHANNEL_NOTIFICATION, params: { content, meta: { message_id: note.id, kind: note.kind } } }).catch((error) => console.error("[tinypivot-mcp] Could not reach the Claude Code channel:", error));
|
|
12838
|
+
return true;
|
|
12839
|
+
}
|
|
12840
|
+
});
|
|
12841
|
+
}
|
|
12842
|
+
if (server.server.getClientCapabilities()?.sampling) {
|
|
12843
|
+
studio.agent.connect({
|
|
12844
|
+
name: "sampling",
|
|
12845
|
+
complete: async (turns) => {
|
|
12846
|
+
const result = await server.server.createMessage({
|
|
12847
|
+
messages: turns.map((turn) => ({ role: turn.role, content: { type: "text", text: turn.content } })),
|
|
12848
|
+
maxTokens: 2e3
|
|
12849
|
+
});
|
|
12850
|
+
return result.content.type === "text" ? result.content.text : "";
|
|
12851
|
+
}
|
|
12852
|
+
});
|
|
12853
|
+
}
|
|
12854
|
+
};
|
|
12855
|
+
if (claudeChannel) {
|
|
12856
|
+
server.registerTool(
|
|
12857
|
+
"studio_reply",
|
|
12858
|
+
{
|
|
12859
|
+
title: "Reply in TinyPivot Studio",
|
|
12860
|
+
description: "Answer a message from TinyPivot Studio. The user reads it there.",
|
|
12861
|
+
inputSchema: { text: z.string().min(1).max(8e3), re: z.string().max(80).optional() }
|
|
12862
|
+
},
|
|
12863
|
+
async ({ text, re }) => {
|
|
12864
|
+
studio.reply(text, re);
|
|
12865
|
+
return { content: [{ type: "text", text: "Shown in TinyPivot Studio." }] };
|
|
12866
|
+
}
|
|
12867
|
+
);
|
|
12868
|
+
}
|
|
12431
12869
|
const widgetOnlyTools = [];
|
|
12432
12870
|
const widgetOnly = (tool) => {
|
|
12433
12871
|
widgetOnlyTools.push(tool);
|
|
@@ -12453,6 +12891,11 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12453
12891
|
if (!clientRendersWidget())
|
|
12454
12892
|
widgetOnlyTools.forEach((tool) => tool.disable());
|
|
12455
12893
|
detectedClientName = server.server.getClientVersion()?.name;
|
|
12894
|
+
try {
|
|
12895
|
+
connectAgent();
|
|
12896
|
+
} catch (error) {
|
|
12897
|
+
console.error("[tinypivot-mcp] Could not connect the Studio to the agent:", error);
|
|
12898
|
+
}
|
|
12456
12899
|
recordTelemetry({
|
|
12457
12900
|
event: "server_start",
|
|
12458
12901
|
client: detectedClientName,
|
package/dist/cli.js
CHANGED
|
@@ -19,7 +19,7 @@ import {
|
|
|
19
19
|
runTuiCommand,
|
|
20
20
|
saveVisualThemePreference,
|
|
21
21
|
startCompanionServer
|
|
22
|
-
} from "./chunk-
|
|
22
|
+
} from "./chunk-E6DYPT62.js";
|
|
23
23
|
import "./chunk-2ESYSVXG.js";
|
|
24
24
|
|
|
25
25
|
// src/cli.ts
|
|
@@ -355,8 +355,7 @@ async function main() {
|
|
|
355
355
|
if (companionPromise)
|
|
356
356
|
return companionPromise;
|
|
357
357
|
companionPromise = startCompanion(port).catch((err) => {
|
|
358
|
-
|
|
359
|
-
throw err;
|
|
358
|
+
console.error(`[tinypivot-mcp] Port ${port} is taken (${err instanceof Error ? err.message : err}); using a free port for the Studio.`);
|
|
360
359
|
return startCompanion(0);
|
|
361
360
|
}).then((handle) => {
|
|
362
361
|
companion = handle;
|