@heyditto/cli 3.21.0 → 3.22.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.
@@ -0,0 +1,1076 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { once } from "node:events";
3
+ import { createWriteStream } from "node:fs";
4
+ import { mkdir, readFile, rename, stat, unlink } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
7
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
8
+ import { createKey, findEndpoint, listEndpoints, revokeKey, } from "./api.js";
9
+ import { claudeServerName, fetchMcpCatalog, mcpUnavailableLines, } from "./agents/claude-mcp.js";
10
+ import { clientHeaders, packageName, packageVersion } from "./config.js";
11
+ import { findProfileEndpoint, repoDefaultProfile } from "./dittoconfig/profiles.js";
12
+ import { SESSION_ID_PATTERN, resolveActiveSession } from "./mcp-session.js";
13
+ import { addProfileOption, explicitProfileEndpoint, readDefaultEndpoint } from "./profiles.js";
14
+ const DEFAULT_CALL_TIMEOUT_SECONDS = 120;
15
+ const MAX_TOOL_LIST_PAGES = 50;
16
+ /**
17
+ * Resolves the active inference endpoint for MCP catalog commands (`mcp-config`
18
+ * and `tools`). Precedence matches `heyditto claude` / `mcp-config`:
19
+ * 1. explicit `--endpoint <slug|name|id>`
20
+ * 2. explicit `--profile <name>` / `DITTO_PROFILE`
21
+ * 3. repository `.ditto` default endpoint profile
22
+ * 4. active profile / saved default endpoint
23
+ * 5. sole endpoint when the account has exactly one
24
+ */
25
+ export async function resolveMcpEndpoint(options = {}) {
26
+ const { endpoints, baseUrl } = await listEndpoints();
27
+ const explicit = options.endpoint?.trim() || (await explicitProfileEndpoint())?.endpoint;
28
+ let endpoint;
29
+ if (explicit) {
30
+ endpoint = findEndpoint(endpoints, explicit);
31
+ if (!endpoint) {
32
+ const available = endpoints.map((e) => e.slug).join(", ");
33
+ throw new Error(`No endpoint named "${explicit}"${available ? `. Available: ${available}` : " (no endpoints configured; create one with `heyditto endpoints create`)"}`);
34
+ }
35
+ }
36
+ else {
37
+ const profile = await repoDefaultProfile(options.cwd ?? process.cwd());
38
+ if (profile) {
39
+ endpoint = await findProfileEndpoint(profile, endpoints);
40
+ if (!endpoint)
41
+ throw new Error("Repository .ditto profile has no applied endpoint; run heyditto repo apply");
42
+ }
43
+ else {
44
+ const saved = await readDefaultEndpoint();
45
+ endpoint = saved ? findEndpoint(endpoints, saved) : endpoints.length === 1 ? endpoints[0] : undefined;
46
+ }
47
+ }
48
+ if (!endpoint) {
49
+ const available = endpoints.map((e) => e.slug).join(", ");
50
+ throw new Error(`No unambiguous MCP endpoint; select one with --endpoint or heyditto endpoints use${available ? `. Available: ${available}` : ""}`);
51
+ }
52
+ return { endpoint, baseUrl };
53
+ }
54
+ /**
55
+ * Resolves the MCP session id: explicit `--session`, `T3CODE_THREAD_ID`, active
56
+ * CLI session (`DITTO_SESSION_ID` or `heyditto session new`), or a fresh id.
57
+ */
58
+ export async function resolveToolsSessionId(explicit) {
59
+ if (explicit !== undefined) {
60
+ const trimmed = explicit.trim();
61
+ if (!trimmed || !SESSION_ID_PATTERN.test(trimmed)) {
62
+ throw new Error(`--session must match ${SESSION_ID_PATTERN}`);
63
+ }
64
+ return trimmed;
65
+ }
66
+ const t3 = process.env.T3CODE_THREAD_ID?.trim();
67
+ if (t3 && SESSION_ID_PATTERN.test(t3))
68
+ return t3;
69
+ const active = await resolveActiveSession();
70
+ if (active?.id)
71
+ return active.id;
72
+ return `cli-tools-${randomUUID()}`;
73
+ }
74
+ /** Replaces any occurrence of a secret token before text reaches stdout or stderr. */
75
+ export function sanitizeSecret(text, secret) {
76
+ if (!secret)
77
+ return text;
78
+ return text.split(secret).join("[REDACTED]");
79
+ }
80
+ function sanitizeError(error, secret) {
81
+ if (!secret)
82
+ return error instanceof Error ? error : new Error(String(error));
83
+ if (error instanceof Error) {
84
+ const cleaned = new Error(sanitizeSecret(error.message, secret));
85
+ cleaned.name = error.name;
86
+ if (error.stack)
87
+ cleaned.stack = sanitizeSecret(error.stack, secret);
88
+ return cleaned;
89
+ }
90
+ return new Error(sanitizeSecret(String(error), secret));
91
+ }
92
+ /** Strips query string and fragment from a URL so presigned signatures are never printed. */
93
+ export function redactUrl(rawUrl) {
94
+ try {
95
+ const u = new URL(rawUrl);
96
+ return `${u.origin}${u.pathname}`;
97
+ }
98
+ catch {
99
+ const idx = rawUrl.indexOf("?");
100
+ return idx >= 0 ? rawUrl.slice(0, idx) : rawUrl;
101
+ }
102
+ }
103
+ /**
104
+ * Mints a one-hour ephemeral key on `endpoint`, passes it to `fn`, and always
105
+ * revokes the key in `finally` (and on SIGINT/SIGTERM). Never prints the key.
106
+ */
107
+ export async function withEphemeralMcpKey(endpoint, sessionId, fn) {
108
+ const keyName = `cli-tools:${sessionId}`.slice(0, 128);
109
+ const created = await createKey(endpoint.id, { name: keyName, expiresIn: "1h" });
110
+ const secret = created.key;
111
+ if (!secret)
112
+ throw new Error("MCP key response did not contain a key");
113
+ let revoked = false;
114
+ const revokeOnce = async () => {
115
+ if (revoked)
116
+ return;
117
+ revoked = true;
118
+ await revokeKey(endpoint.id, created.id).catch(() => {
119
+ process.stderr.write(`warning: could not revoke ephemeral MCP key ${created.id}; it may remain valid until its one-hour expiry\n`);
120
+ });
121
+ };
122
+ const onSignal = (signal) => {
123
+ void revokeOnce().finally(() => {
124
+ process.exit(signal === "SIGINT" ? 130 : 143);
125
+ });
126
+ };
127
+ process.once("SIGINT", onSignal);
128
+ process.once("SIGTERM", onSignal);
129
+ try {
130
+ return await fn(secret);
131
+ }
132
+ catch (error) {
133
+ throw sanitizeError(error, secret);
134
+ }
135
+ finally {
136
+ process.off("SIGINT", onSignal);
137
+ process.off("SIGTERM", onSignal);
138
+ await revokeOnce();
139
+ }
140
+ }
141
+ function normalizeServerToken(value) {
142
+ return value.trim().toLowerCase().replace(/^ditto[-_]/, "").replace(/[-_\s]+/g, "");
143
+ }
144
+ /**
145
+ * Resolves a user-supplied server name against the endpoint's MCP catalog.
146
+ * Accepts canonical names (`ditto-googledrive`), short aliases (`googledrive`),
147
+ * and separator variants (`google-drive`, `google_drive`).
148
+ */
149
+ export function resolveCatalogServer(catalog, wanted) {
150
+ const raw = wanted.trim();
151
+ if (!raw)
152
+ throw new Error("provide a server name (run `heyditto tools` to list available servers)");
153
+ const active = catalog.servers.filter((s) => s.tools.length > 0);
154
+ const wrap = (server) => ({
155
+ server,
156
+ displayName: claudeServerName(server.name),
157
+ alias: server.name,
158
+ });
159
+ // 1. Exact canonical or raw name.
160
+ const exact = active.find((s) => claudeServerName(s.name) === raw || s.name === raw);
161
+ if (exact)
162
+ return wrap(exact);
163
+ // 2. Case-insensitive canonical or raw name.
164
+ const lower = raw.toLowerCase();
165
+ const ci = active.filter((s) => claudeServerName(s.name).toLowerCase() === lower || s.name.toLowerCase() === lower);
166
+ if (ci.length === 1)
167
+ return wrap(ci[0]);
168
+ // 3. Normalized separator / optional ditto- prefix match.
169
+ const norm = normalizeServerToken(raw);
170
+ if (norm) {
171
+ const fuzzy = active.filter((s) => normalizeServerToken(s.name) === norm);
172
+ if (fuzzy.length === 1)
173
+ return wrap(fuzzy[0]);
174
+ if (fuzzy.length > 1) {
175
+ throw new Error(`server "${raw}" is ambiguous. Matches: ${fuzzy.map((s) => claudeServerName(s.name)).join(", ")}`);
176
+ }
177
+ }
178
+ // 4. Helpful message if the server is currently disconnected.
179
+ const unavailable = Array.isArray(catalog.unavailable) ? catalog.unavailable : [];
180
+ const dropped = unavailable.find((u) => {
181
+ const candidates = [u.prefix, claudeServerName(u.prefix), u.name].filter(Boolean);
182
+ return candidates.some((c) => c.toLowerCase() === lower || (norm.length > 0 && normalizeServerToken(c) === norm));
183
+ });
184
+ if (dropped) {
185
+ const [line] = mcpUnavailableLines({ unavailable: [dropped] });
186
+ throw new Error(line ?? `server "${raw}" is disconnected`);
187
+ }
188
+ const available = active
189
+ .map((s) => {
190
+ const display = claudeServerName(s.name);
191
+ return display === s.name ? display : `${display} (${s.name})`;
192
+ })
193
+ .join(", ");
194
+ throw new Error(`no connected MCP server named "${raw}".${available ? ` Available: ${available}` : " This endpoint has no connected MCP servers."}`);
195
+ }
196
+ /** Opens a Streamable HTTP MCP client session against one catalog server. */
197
+ export async function connectCatalogServer(server, baseUrl, apiKey, sessionId) {
198
+ const resolvedUrl = new URL(server.url, `${baseUrl.replace(/\/+$/, "")}/`);
199
+ const client = new Client({ name: packageName, version: packageVersion });
200
+ const transport = new StreamableHTTPClientTransport(resolvedUrl, {
201
+ requestInit: {
202
+ headers: {
203
+ Authorization: `Bearer ${apiKey}`,
204
+ "X-Ditto-Session-Id": sessionId,
205
+ ...clientHeaders(),
206
+ },
207
+ },
208
+ });
209
+ await client.connect(transport);
210
+ return client;
211
+ }
212
+ /** Fetches all tools from an MCP server, following `nextCursor` pagination. */
213
+ export async function listAllServerTools(client) {
214
+ const all = [];
215
+ let cursor;
216
+ const seenCursors = new Set();
217
+ for (let page = 0; page < MAX_TOOL_LIST_PAGES; page += 1) {
218
+ const res = await client.listTools(cursor ? { cursor } : undefined);
219
+ for (const tool of res.tools ?? []) {
220
+ all.push(tool);
221
+ }
222
+ if (!res.nextCursor || seenCursors.has(res.nextCursor))
223
+ break;
224
+ seenCursors.add(res.nextCursor);
225
+ cursor = res.nextCursor;
226
+ }
227
+ return all;
228
+ }
229
+ // ---------------------------------------------------------------------------
230
+ // Argument parsing for `tools call`
231
+ // ---------------------------------------------------------------------------
232
+ /**
233
+ * Parses a single `--arg key=value` value: JSON booleans, null, strict finite
234
+ * numbers, quoted strings, arrays and objects parse as JSON; everything else
235
+ * stays a plain string.
236
+ */
237
+ export function parseArgValue(raw) {
238
+ if (raw === "true")
239
+ return true;
240
+ if (raw === "false")
241
+ return false;
242
+ if (raw === "null")
243
+ return null;
244
+ if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(raw)) {
245
+ const n = Number(raw);
246
+ if (Number.isFinite(n))
247
+ return n;
248
+ }
249
+ if ((raw.startsWith("{") && raw.endsWith("}")) ||
250
+ (raw.startsWith("[") && raw.endsWith("]")) ||
251
+ (raw.startsWith('"') && raw.endsWith('"'))) {
252
+ try {
253
+ return JSON.parse(raw);
254
+ }
255
+ catch {
256
+ return raw;
257
+ }
258
+ }
259
+ return raw;
260
+ }
261
+ function splitKeyValue(pair, flagName) {
262
+ const idx = pair.indexOf("=");
263
+ if (idx <= 0) {
264
+ throw new Error(`${flagName} must be "key=value", got "${pair}"`);
265
+ }
266
+ const key = pair.slice(0, idx).trim();
267
+ if (!key)
268
+ throw new Error(`${flagName} key cannot be empty`);
269
+ return [key, pair.slice(idx + 1)];
270
+ }
271
+ async function readAllStdin() {
272
+ if (process.stdin.isTTY) {
273
+ throw new Error("reading tool arguments from stdin requires piped input (stdin is a TTY)");
274
+ }
275
+ const chunks = [];
276
+ for await (const chunk of process.stdin) {
277
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
278
+ }
279
+ return Buffer.concat(chunks).toString("utf8");
280
+ }
281
+ function parseJsonObject(raw, source) {
282
+ let parsed;
283
+ try {
284
+ parsed = JSON.parse(raw);
285
+ }
286
+ catch (err) {
287
+ throw new Error(`${source} must be valid JSON: ${err instanceof Error ? err.message : String(err)}`);
288
+ }
289
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
290
+ throw new Error(`${source} must be a JSON object (e.g. '{"key":"value"}')`);
291
+ }
292
+ return parsed;
293
+ }
294
+ async function loadJsonSource(spec, label) {
295
+ if (spec === "-") {
296
+ const raw = await readAllStdin();
297
+ if (!raw.trim())
298
+ return {};
299
+ return parseJsonObject(raw, "stdin");
300
+ }
301
+ if (spec.startsWith("@")) {
302
+ const filePath = spec.slice(1);
303
+ if (!filePath)
304
+ throw new Error(`${label} "@" must be followed by a file path`);
305
+ let raw;
306
+ try {
307
+ raw = await readFile(filePath, "utf8");
308
+ }
309
+ catch (err) {
310
+ throw new Error(`failed to read ${filePath}: ${err instanceof Error ? err.message : String(err)}`);
311
+ }
312
+ return parseJsonObject(raw, filePath);
313
+ }
314
+ return parseJsonObject(spec, label);
315
+ }
316
+ export async function parseToolCallArgs(positionalInput, options) {
317
+ const baseSources = [
318
+ positionalInput !== undefined ? "positional input" : undefined,
319
+ options.json !== undefined ? "--json" : undefined,
320
+ options.stdin ? "--stdin" : undefined,
321
+ ].filter(Boolean);
322
+ if (baseSources.length > 1) {
323
+ throw new Error(`use only one JSON payload source (got ${baseSources.join(" and ")})`);
324
+ }
325
+ let args = {};
326
+ if (options.stdin) {
327
+ const raw = await readAllStdin();
328
+ if (raw.trim())
329
+ args = parseJsonObject(raw, "--stdin");
330
+ }
331
+ else if (options.json !== undefined) {
332
+ args = await loadJsonSource(options.json, "--json");
333
+ }
334
+ else if (positionalInput !== undefined) {
335
+ args = await loadJsonSource(positionalInput, "input");
336
+ }
337
+ for (const pair of options.arg ?? []) {
338
+ const [key, value] = splitKeyValue(pair, "--arg");
339
+ args[key] = parseArgValue(value);
340
+ }
341
+ for (const pair of options.rawArg ?? []) {
342
+ const [key, value] = splitKeyValue(pair, "--raw-arg");
343
+ args[key] = value;
344
+ }
345
+ return args;
346
+ }
347
+ const PRESIGNED_URL_KEYS = [
348
+ "s3url",
349
+ "s3_url",
350
+ "download_url",
351
+ "downloadUrl",
352
+ "presigned_url",
353
+ "presignedUrl",
354
+ ];
355
+ const FILENAME_KEYS = ["name", "filename", "fileName", "file_name"];
356
+ const MIMETYPE_KEYS = ["mimetype", "mime_type", "mimeType", "contentType", "content_type"];
357
+ function firstString(obj, keys) {
358
+ for (const k of keys) {
359
+ const v = obj[k];
360
+ if (typeof v === "string" && v.trim())
361
+ return v.trim();
362
+ }
363
+ return undefined;
364
+ }
365
+ function isPlainObject(v) {
366
+ return typeof v === "object" && v !== null && !Array.isArray(v);
367
+ }
368
+ function isHttpUrl(v) {
369
+ try {
370
+ const u = new URL(v);
371
+ return u.protocol === "https:" || u.protocol === "http:";
372
+ }
373
+ catch {
374
+ return false;
375
+ }
376
+ }
377
+ function findUrlInObject(value, depth = 0, parentFilename, parentMime) {
378
+ if (depth > 6 || value === null || value === undefined)
379
+ return undefined;
380
+ if (Array.isArray(value)) {
381
+ for (const item of value) {
382
+ const hit = findUrlInObject(item, depth + 1, parentFilename, parentMime);
383
+ if (hit)
384
+ return hit;
385
+ }
386
+ return undefined;
387
+ }
388
+ if (!isPlainObject(value))
389
+ return undefined;
390
+ const ownFilename = firstString(value, FILENAME_KEYS) ?? parentFilename;
391
+ const ownMime = firstString(value, MIMETYPE_KEYS) ?? parentMime;
392
+ // Priority 1: `downloaded_file_content` object (e.g. Google Drive download_file).
393
+ const dfc = value.downloaded_file_content;
394
+ if (isPlainObject(dfc)) {
395
+ const url = firstString(dfc, [...PRESIGNED_URL_KEYS, "url"]);
396
+ if (url && isHttpUrl(url)) {
397
+ return {
398
+ kind: "url",
399
+ url,
400
+ filename: firstString(dfc, FILENAME_KEYS) ?? ownFilename,
401
+ mimeType: firstString(dfc, MIMETYPE_KEYS) ?? ownMime,
402
+ };
403
+ }
404
+ }
405
+ // Priority 2: explicit presigned/download URL key on this object.
406
+ const direct = firstString(value, PRESIGNED_URL_KEYS);
407
+ if (direct && isHttpUrl(direct)) {
408
+ return { kind: "url", url: direct, filename: ownFilename, mimeType: ownMime };
409
+ }
410
+ // Recurse into nested objects.
411
+ for (const child of Object.values(value)) {
412
+ if (isPlainObject(child) || Array.isArray(child)) {
413
+ const hit = findUrlInObject(child, depth + 1, ownFilename, ownMime);
414
+ if (hit)
415
+ return hit;
416
+ }
417
+ }
418
+ return undefined;
419
+ }
420
+ /**
421
+ * Extracts a downloadable file payload (presigned URL or embedded binary blob)
422
+ * from an MCP `CallToolResult`.
423
+ */
424
+ export function extractDownloadTarget(result) {
425
+ if (!isPlainObject(result))
426
+ return undefined;
427
+ // Check structuredContent first if present.
428
+ if (result.structuredContent !== undefined) {
429
+ const hit = findUrlInObject(result.structuredContent);
430
+ if (hit)
431
+ return hit;
432
+ }
433
+ const content = Array.isArray(result.content) ? result.content : [];
434
+ // Check JSON inside text blocks for presigned download payloads.
435
+ for (const block of content) {
436
+ if (!isPlainObject(block))
437
+ continue;
438
+ if (block.type === "text" && typeof block.text === "string") {
439
+ try {
440
+ const parsed = JSON.parse(block.text);
441
+ const hit = findUrlInObject(parsed);
442
+ if (hit)
443
+ return hit;
444
+ }
445
+ catch {
446
+ // Non-JSON text block; ignore.
447
+ }
448
+ }
449
+ }
450
+ // Fall back to embedded binary resource / image / audio blocks.
451
+ for (const block of content) {
452
+ if (!isPlainObject(block))
453
+ continue;
454
+ if (block.type === "resource" && isPlainObject(block.resource)) {
455
+ const res = block.resource;
456
+ if (typeof res.blob === "string" && res.blob.length > 0) {
457
+ const uriName = typeof res.uri === "string" ? path.posix.basename(res.uri) : undefined;
458
+ return {
459
+ kind: "base64",
460
+ data: res.blob,
461
+ filename: firstString(res, FILENAME_KEYS) ?? uriName,
462
+ mimeType: firstString(res, MIMETYPE_KEYS),
463
+ };
464
+ }
465
+ }
466
+ if ((block.type === "image" || block.type === "audio") && typeof block.data === "string" && block.data.length > 0) {
467
+ return {
468
+ kind: "base64",
469
+ data: block.data,
470
+ mimeType: firstString(block, MIMETYPE_KEYS),
471
+ };
472
+ }
473
+ }
474
+ return undefined;
475
+ }
476
+ /** Sanitizes a remote filename so it can never escape a destination directory. */
477
+ export function sanitizeFilename(raw) {
478
+ if (!raw)
479
+ return "download.bin";
480
+ // Split on both POSIX and Windows separators and take the final segment.
481
+ const segments = raw.split(/[\\/]+/).filter(Boolean);
482
+ const last = (segments.at(-1) ?? "").replace(/[\x00-\x1f\x7f]/g, "").trim();
483
+ if (!last || last === "." || last === "..")
484
+ return "download.bin";
485
+ return last;
486
+ }
487
+ function filenameFromContentDisposition(header) {
488
+ if (!header)
489
+ return undefined;
490
+ const star = /filename\*\s*=\s*(?:UTF-8''|utf-8'')([^;\r\n]+)/i.exec(header);
491
+ if (star?.[1]) {
492
+ try {
493
+ return decodeURIComponent(star[1].trim().replace(/^"|"$/g, ""));
494
+ }
495
+ catch {
496
+ return star[1].trim().replace(/^"|"$/g, "");
497
+ }
498
+ }
499
+ const plain = /filename\s*=\s*"([^"]+)"|filename\s*=\s*([^;\r\n]+)/i.exec(header);
500
+ return (plain?.[1] ?? plain?.[2])?.trim();
501
+ }
502
+ function filenameFromUrl(rawUrl) {
503
+ try {
504
+ const base = path.posix.basename(new URL(rawUrl).pathname);
505
+ return base && base !== "/" ? decodeURIComponent(base) : undefined;
506
+ }
507
+ catch {
508
+ return undefined;
509
+ }
510
+ }
511
+ async function resolveDownloadPath(destArg, suggestedFilename) {
512
+ const trimmed = destArg.trim();
513
+ if (!trimmed)
514
+ throw new Error("--download requires a file or directory path");
515
+ const endsWithSep = trimmed.endsWith("/") || trimmed.endsWith(path.sep);
516
+ let isDir = endsWithSep;
517
+ if (!isDir) {
518
+ try {
519
+ isDir = (await stat(trimmed)).isDirectory();
520
+ }
521
+ catch {
522
+ isDir = false;
523
+ }
524
+ }
525
+ if (isDir) {
526
+ await mkdir(trimmed, { recursive: true });
527
+ return path.join(trimmed, sanitizeFilename(suggestedFilename));
528
+ }
529
+ await mkdir(path.dirname(path.resolve(trimmed)), { recursive: true });
530
+ return trimmed;
531
+ }
532
+ /**
533
+ * Streams a `DownloadTarget` to disk without sending Ditto auth headers to
534
+ * presigned URLs and without returning or logging any presigned URL.
535
+ */
536
+ export async function downloadToolPayload(target, destArg, options = {}) {
537
+ const fetchImpl = options.fetchImpl ?? fetch;
538
+ const timeoutMs = options.timeoutMs ?? DEFAULT_CALL_TIMEOUT_SECONDS * 1000;
539
+ if (target.kind === "base64") {
540
+ const buf = Buffer.from(target.data, "base64");
541
+ const destPath = await resolveDownloadPath(destArg, target.filename ?? "download.bin");
542
+ const tmpPath = `${destPath}.ditto-dl-${randomUUID()}.tmp`;
543
+ try {
544
+ const hash = createHash("sha256").update(buf).digest("hex");
545
+ const out = createWriteStream(tmpPath, { mode: 0o600 });
546
+ out.end(buf);
547
+ await once(out, "finish");
548
+ await rename(tmpPath, destPath);
549
+ return {
550
+ downloaded: true,
551
+ path: destPath,
552
+ filename: path.basename(destPath),
553
+ bytes: buf.length,
554
+ ...(target.mimeType ? { contentType: target.mimeType } : {}),
555
+ sha256: hash,
556
+ };
557
+ }
558
+ catch (err) {
559
+ await unlink(tmpPath).catch(() => undefined);
560
+ throw err;
561
+ }
562
+ }
563
+ if (!isHttpUrl(target.url)) {
564
+ throw new Error("download payload URL must use http or https");
565
+ }
566
+ // Deliberately send NO Authorization header to presigned storage URLs.
567
+ const response = await fetchImpl(target.url, {
568
+ method: "GET",
569
+ redirect: "follow",
570
+ signal: AbortSignal.timeout(timeoutMs),
571
+ });
572
+ if (!response.ok) {
573
+ throw new Error(`download failed: HTTP ${response.status} from ${redactUrl(target.url)}`);
574
+ }
575
+ const suggested = target.filename ??
576
+ filenameFromContentDisposition(response.headers.get("content-disposition")) ??
577
+ filenameFromUrl(target.url) ??
578
+ "download.bin";
579
+ const contentType = target.mimeType ?? response.headers.get("content-type")?.split(";")[0]?.trim() ?? undefined;
580
+ const destPath = await resolveDownloadPath(destArg, suggested);
581
+ const tmpPath = `${destPath}.ditto-dl-${randomUUID()}.tmp`;
582
+ const hash = createHash("sha256");
583
+ let bytes = 0;
584
+ const out = createWriteStream(tmpPath);
585
+ const streamError = new Promise((_resolve, reject) => {
586
+ out.once("error", reject);
587
+ });
588
+ try {
589
+ if (response.body) {
590
+ const reader = response.body.getReader();
591
+ try {
592
+ for (;;) {
593
+ const { done, value } = await reader.read();
594
+ if (done)
595
+ break;
596
+ if (!value || value.byteLength === 0)
597
+ continue;
598
+ const chunk = Buffer.from(value.buffer, value.byteOffset, value.byteLength);
599
+ hash.update(chunk);
600
+ bytes += chunk.byteLength;
601
+ if (!out.write(chunk)) {
602
+ await Promise.race([once(out, "drain"), streamError]);
603
+ }
604
+ }
605
+ }
606
+ finally {
607
+ reader.releaseLock();
608
+ }
609
+ }
610
+ out.end();
611
+ await Promise.race([once(out, "finish"), streamError]);
612
+ await rename(tmpPath, destPath);
613
+ }
614
+ catch (err) {
615
+ out.destroy();
616
+ await unlink(tmpPath).catch(() => undefined);
617
+ throw err;
618
+ }
619
+ return {
620
+ downloaded: true,
621
+ path: destPath,
622
+ filename: path.basename(destPath),
623
+ bytes,
624
+ ...(contentType ? { contentType } : {}),
625
+ sha256: hash.digest("hex"),
626
+ };
627
+ }
628
+ // ---------------------------------------------------------------------------
629
+ // Output formatting helpers
630
+ // ---------------------------------------------------------------------------
631
+ function pad(value, width) {
632
+ return value.length >= width ? value : value + " ".repeat(width - value.length);
633
+ }
634
+ function printTable(header, rows) {
635
+ if (rows.length === 0)
636
+ return;
637
+ const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length)));
638
+ const line = (r) => r.map((c, i) => (i === r.length - 1 ? c : pad(c ?? "", widths[i] ?? 0))).join(" ");
639
+ process.stdout.write(`${line(header)}\n`);
640
+ for (const r of rows)
641
+ process.stdout.write(`${line(r)}\n`);
642
+ }
643
+ function writeJSON(value) {
644
+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
645
+ }
646
+ function wantsJSON(options) {
647
+ return options.json === true || options.output === "json" || options.output === "raw";
648
+ }
649
+ function oneLine(text, max = 96) {
650
+ if (!text)
651
+ return "";
652
+ const flat = text.replace(/\s+/g, " ").trim();
653
+ return flat.length <= max ? flat : `${flat.slice(0, max - 1)}…`;
654
+ }
655
+ function extractTextBlocks(result) {
656
+ if (!isPlainObject(result) || !Array.isArray(result.content))
657
+ return [];
658
+ const texts = [];
659
+ for (const block of result.content) {
660
+ if (isPlainObject(block) && block.type === "text" && typeof block.text === "string") {
661
+ texts.push(block.text);
662
+ }
663
+ }
664
+ return texts;
665
+ }
666
+ function formatCallOutput(result, outputFormat) {
667
+ if (outputFormat === "raw")
668
+ return JSON.stringify(result, null, 2);
669
+ const texts = extractTextBlocks(result);
670
+ if (outputFormat === "json") {
671
+ if (isPlainObject(result) && result.structuredContent !== undefined) {
672
+ return JSON.stringify(result.structuredContent, null, 2);
673
+ }
674
+ if (texts.length === 1) {
675
+ try {
676
+ return JSON.stringify(JSON.parse(texts[0]), null, 2);
677
+ }
678
+ catch {
679
+ return JSON.stringify({ text: texts[0] }, null, 2);
680
+ }
681
+ }
682
+ if (texts.length > 1) {
683
+ const parsed = texts.map((t) => {
684
+ try {
685
+ return JSON.parse(t);
686
+ }
687
+ catch {
688
+ return t;
689
+ }
690
+ });
691
+ return JSON.stringify({ content: parsed }, null, 2);
692
+ }
693
+ return JSON.stringify(result, null, 2);
694
+ }
695
+ if (texts.length > 0)
696
+ return texts.join("\n");
697
+ if (isPlainObject(result) && result.structuredContent !== undefined) {
698
+ return JSON.stringify(result.structuredContent, null, 2);
699
+ }
700
+ return JSON.stringify(result, null, 2);
701
+ }
702
+ function formatSchemaType(prop) {
703
+ if (!isPlainObject(prop))
704
+ return "any";
705
+ if (Array.isArray(prop.enum) && prop.enum.length > 0) {
706
+ return prop.enum.map((v) => JSON.stringify(v)).join(" | ");
707
+ }
708
+ if (typeof prop.type === "string") {
709
+ if (prop.type === "array" && isPlainObject(prop.items) && typeof prop.items.type === "string") {
710
+ return `${prop.items.type}[]`;
711
+ }
712
+ return prop.type;
713
+ }
714
+ if (Array.isArray(prop.type))
715
+ return prop.type.join(" | ");
716
+ if (Array.isArray(prop.anyOf))
717
+ return prop.anyOf.map(formatSchemaType).join(" | ");
718
+ if (Array.isArray(prop.oneOf))
719
+ return prop.oneOf.map(formatSchemaType).join(" | ");
720
+ return "any";
721
+ }
722
+ function parseTimeoutSeconds(raw) {
723
+ if (raw === undefined)
724
+ return DEFAULT_CALL_TIMEOUT_SECONDS;
725
+ const n = Number(raw);
726
+ if (!Number.isFinite(n) || n <= 0 || n > 3600) {
727
+ throw new Error("--timeout must be a positive number of seconds (up to 3600)");
728
+ }
729
+ return n;
730
+ }
731
+ export async function cmdToolsServers(options) {
732
+ const { endpoint, baseUrl } = await resolveMcpEndpoint({ endpoint: options.endpoint });
733
+ const sessionId = await resolveToolsSessionId(options.session);
734
+ const catalog = await withEphemeralMcpKey(endpoint, sessionId, (apiKey) => fetchMcpCatalog(baseUrl, apiKey, sessionId));
735
+ const active = catalog.servers.filter((s) => s.tools.length > 0);
736
+ const unavailable = Array.isArray(catalog.unavailable) ? catalog.unavailable : [];
737
+ if (wantsJSON(options)) {
738
+ writeJSON({
739
+ endpoint: { id: endpoint.id, slug: endpoint.slug, name: endpoint.name },
740
+ sessionId,
741
+ approvalMode: catalog.approvalMode,
742
+ clientApprovals: catalog.clientApprovals,
743
+ servers: active.map((s) => ({
744
+ name: claudeServerName(s.name),
745
+ alias: s.name,
746
+ url: s.url,
747
+ toolCount: s.tools.length,
748
+ gatedCount: s.tools.filter((t) => t.approval).length,
749
+ tools: s.tools,
750
+ })),
751
+ unavailable,
752
+ });
753
+ return;
754
+ }
755
+ for (const line of mcpUnavailableLines(catalog)) {
756
+ process.stderr.write(`warning: ${line}\n`);
757
+ }
758
+ if (active.length === 0) {
759
+ process.stdout.write(`No connected MCP servers on endpoint "${endpoint.slug}".\n`);
760
+ return;
761
+ }
762
+ printTable(["SERVER", "ALIAS", "TOOLS", "GATED"], active.map((s) => [
763
+ claudeServerName(s.name),
764
+ s.name,
765
+ String(s.tools.length),
766
+ String(s.tools.filter((t) => t.approval).length),
767
+ ]));
768
+ process.stderr.write(`\nEndpoint: ${endpoint.slug} (inspect tools with \`heyditto tools list <server>\`)\n`);
769
+ }
770
+ export async function cmdToolsList(serverArg, options) {
771
+ const { endpoint, baseUrl } = await resolveMcpEndpoint({ endpoint: options.endpoint });
772
+ const sessionId = await resolveToolsSessionId(options.session);
773
+ const search = options.search?.trim().toLowerCase() ?? "";
774
+ if (!serverArg) {
775
+ const catalog = await withEphemeralMcpKey(endpoint, sessionId, (apiKey) => fetchMcpCatalog(baseUrl, apiKey, sessionId));
776
+ const entries = [];
777
+ for (const s of catalog.servers) {
778
+ if (s.tools.length === 0)
779
+ continue;
780
+ const display = claudeServerName(s.name);
781
+ for (const t of s.tools) {
782
+ if (search &&
783
+ !t.name.toLowerCase().includes(search) &&
784
+ !s.name.toLowerCase().includes(search) &&
785
+ !display.toLowerCase().includes(search)) {
786
+ continue;
787
+ }
788
+ entries.push({ server: display, alias: s.name, name: t.name, tier: t.tier, approval: t.approval });
789
+ }
790
+ }
791
+ if (wantsJSON(options)) {
792
+ writeJSON({
793
+ endpoint: { id: endpoint.id, slug: endpoint.slug },
794
+ sessionId,
795
+ ...(search ? { search } : {}),
796
+ tools: entries,
797
+ });
798
+ return;
799
+ }
800
+ for (const line of mcpUnavailableLines(catalog)) {
801
+ process.stderr.write(`warning: ${line}\n`);
802
+ }
803
+ if (entries.length === 0) {
804
+ process.stdout.write(search ? `No tools matching "${options.search}" on endpoint "${endpoint.slug}".\n` : `No tools available on endpoint "${endpoint.slug}".\n`);
805
+ return;
806
+ }
807
+ printTable(["SERVER", "TOOL", "TIER", "APPROVAL"], entries.map((e) => [e.server, e.name, e.tier, e.approval ? "gated" : "auto"]));
808
+ return;
809
+ }
810
+ const { resolved, tools } = await withEphemeralMcpKey(endpoint, sessionId, async (apiKey) => {
811
+ const catalog = await fetchMcpCatalog(baseUrl, apiKey, sessionId);
812
+ const resolvedServer = resolveCatalogServer(catalog, serverArg);
813
+ const client = await connectCatalogServer(resolvedServer.server, baseUrl, apiKey, sessionId);
814
+ try {
815
+ const listed = await listAllServerTools(client);
816
+ return { resolved: resolvedServer, tools: listed };
817
+ }
818
+ finally {
819
+ await client.close().catch(() => undefined);
820
+ }
821
+ });
822
+ const catalogByName = new Map(resolved.server.tools.map((t) => [t.name, t]));
823
+ const merged = tools
824
+ .map((t) => {
825
+ const meta = catalogByName.get(t.name);
826
+ return {
827
+ name: t.name,
828
+ ...(t.title ? { title: t.title } : {}),
829
+ ...(t.description ? { description: t.description } : {}),
830
+ ...(meta ? { tier: meta.tier, approval: meta.approval } : {}),
831
+ ...(t.inputSchema ? { inputSchema: t.inputSchema } : {}),
832
+ ...(t.annotations ? { annotations: t.annotations } : {}),
833
+ };
834
+ })
835
+ .filter((t) => {
836
+ if (!search)
837
+ return true;
838
+ return (t.name.toLowerCase().includes(search) ||
839
+ (t.title ?? "").toLowerCase().includes(search) ||
840
+ (t.description ?? "").toLowerCase().includes(search));
841
+ });
842
+ if (wantsJSON(options)) {
843
+ writeJSON({
844
+ endpoint: { id: endpoint.id, slug: endpoint.slug },
845
+ sessionId,
846
+ server: resolved.displayName,
847
+ alias: resolved.alias,
848
+ ...(search ? { search } : {}),
849
+ tools: merged,
850
+ });
851
+ return;
852
+ }
853
+ if (merged.length === 0) {
854
+ process.stdout.write(search
855
+ ? `No tools matching "${options.search}" on ${resolved.displayName}.\n`
856
+ : `No tools advertised by ${resolved.displayName}.\n`);
857
+ return;
858
+ }
859
+ printTable(["TOOL", "APPROVAL", "DESCRIPTION"], merged.map((t) => [
860
+ t.name,
861
+ t.approval === undefined ? "" : t.approval ? "gated" : "auto",
862
+ oneLine(t.description ?? t.title),
863
+ ]));
864
+ process.stderr.write(`\nInspect one tool: \`heyditto tools describe ${resolved.alias} <tool>\`\n`);
865
+ }
866
+ export async function cmdToolsDescribe(serverArg, toolArg, options) {
867
+ const { endpoint, baseUrl } = await resolveMcpEndpoint({ endpoint: options.endpoint });
868
+ const sessionId = await resolveToolsSessionId(options.session);
869
+ const wantedTool = toolArg.trim();
870
+ if (!wantedTool)
871
+ throw new Error("provide a tool name");
872
+ const { resolved, listed } = await withEphemeralMcpKey(endpoint, sessionId, async (apiKey) => {
873
+ const catalog = await fetchMcpCatalog(baseUrl, apiKey, sessionId);
874
+ const resolvedServer = resolveCatalogServer(catalog, serverArg);
875
+ const client = await connectCatalogServer(resolvedServer.server, baseUrl, apiKey, sessionId);
876
+ try {
877
+ const tools = await listAllServerTools(client);
878
+ return { resolved: resolvedServer, listed: tools };
879
+ }
880
+ finally {
881
+ await client.close().catch(() => undefined);
882
+ }
883
+ });
884
+ const match = listed.find((t) => t.name === wantedTool) ??
885
+ listed.find((t) => t.name.toLowerCase() === wantedTool.toLowerCase());
886
+ if (!match) {
887
+ const needle = wantedTool.toLowerCase();
888
+ const similar = listed
889
+ .map((t) => t.name)
890
+ .filter((n) => n.toLowerCase().includes(needle))
891
+ .slice(0, 8);
892
+ const hint = similar.length
893
+ ? ` Matching tools: ${similar.join(", ")}`
894
+ : listed.length > 0
895
+ ? ` Available: ${listed.slice(0, 12).map((t) => t.name).join(", ")}${listed.length > 12 ? ` (+${listed.length - 12} more)` : ""}`
896
+ : "";
897
+ throw new Error(`tool "${wantedTool}" not found on ${resolved.displayName}.${hint}`);
898
+ }
899
+ const meta = resolved.server.tools.find((t) => t.name === match.name);
900
+ if (options.output === "raw") {
901
+ writeJSON(match);
902
+ return;
903
+ }
904
+ if (wantsJSON(options)) {
905
+ writeJSON({
906
+ endpoint: { id: endpoint.id, slug: endpoint.slug },
907
+ sessionId,
908
+ server: resolved.displayName,
909
+ alias: resolved.alias,
910
+ tool: {
911
+ name: match.name,
912
+ ...(match.title ? { title: match.title } : {}),
913
+ ...(match.description ? { description: match.description } : {}),
914
+ ...(meta ? { tier: meta.tier, approval: meta.approval } : {}),
915
+ inputSchema: match.inputSchema ?? { type: "object", properties: {} },
916
+ ...(match.annotations ? { annotations: match.annotations } : {}),
917
+ },
918
+ });
919
+ return;
920
+ }
921
+ process.stdout.write(`${resolved.displayName} / ${match.name}\n`);
922
+ if (meta) {
923
+ process.stdout.write(`tier: ${meta.tier} approval: ${meta.approval ? "gated" : "auto"}\n`);
924
+ }
925
+ if (match.description) {
926
+ process.stdout.write(`\n${match.description.trim()}\n`);
927
+ }
928
+ const schema = isPlainObject(match.inputSchema) ? match.inputSchema : undefined;
929
+ const props = schema && isPlainObject(schema.properties) ? schema.properties : undefined;
930
+ const required = new Set(schema && Array.isArray(schema.required)
931
+ ? schema.required.filter((r) => typeof r === "string")
932
+ : []);
933
+ if (props && Object.keys(props).length > 0) {
934
+ process.stdout.write("\nParameters:\n");
935
+ printTable(["NAME", "TYPE", "REQUIRED", "DESCRIPTION"], Object.entries(props).map(([key, def]) => [
936
+ key,
937
+ formatSchemaType(def),
938
+ required.has(key) ? "yes" : "no",
939
+ isPlainObject(def) && typeof def.description === "string" ? oneLine(def.description, 120) : "",
940
+ ]));
941
+ }
942
+ if (schema) {
943
+ process.stdout.write(`\nInput schema:\n${JSON.stringify(schema, null, 2)}\n`);
944
+ }
945
+ }
946
+ export async function cmdToolsCall(serverArg, toolArg, positionalInput, options) {
947
+ const outputFormat = options.output ?? "text";
948
+ const timeoutSeconds = parseTimeoutSeconds(options.timeout);
949
+ const timeoutMs = timeoutSeconds * 1000;
950
+ const toolName = toolArg.trim();
951
+ if (!toolName)
952
+ throw new Error("provide a tool name");
953
+ // Parse and validate local arguments BEFORE minting an ephemeral key.
954
+ const args = await parseToolCallArgs(positionalInput, options);
955
+ const { endpoint, baseUrl } = await resolveMcpEndpoint({ endpoint: options.endpoint });
956
+ const sessionId = await resolveToolsSessionId(options.session);
957
+ const { result, renderedOutput } = await withEphemeralMcpKey(endpoint, sessionId, async (apiKey) => {
958
+ const catalog = await fetchMcpCatalog(baseUrl, apiKey, sessionId);
959
+ const resolved = resolveCatalogServer(catalog, serverArg);
960
+ const client = await connectCatalogServer(resolved.server, baseUrl, apiKey, sessionId);
961
+ let callResult;
962
+ try {
963
+ callResult = await client.callTool({ name: toolName, arguments: args }, undefined, { timeout: timeoutMs });
964
+ }
965
+ finally {
966
+ await client.close().catch(() => undefined);
967
+ }
968
+ if (callResult.isError) {
969
+ const message = formatCallOutput(callResult, "text");
970
+ throw new Error(message || `tool "${toolName}" returned an error`);
971
+ }
972
+ return {
973
+ result: callResult,
974
+ renderedOutput: sanitizeSecret(formatCallOutput(callResult, outputFormat), apiKey),
975
+ };
976
+ });
977
+ if (options.download !== undefined) {
978
+ const target = extractDownloadTarget(result);
979
+ if (!target) {
980
+ throw new Error(`tool "${toolName}" did not return a downloadable file payload (expected downloaded_file_content.s3url, download_url, or binary resource)`);
981
+ }
982
+ const downloaded = await downloadToolPayload(target, options.download, { timeoutMs });
983
+ if (outputFormat === "json" || outputFormat === "raw") {
984
+ writeJSON(downloaded);
985
+ }
986
+ else {
987
+ const mimeNote = downloaded.contentType ? ` (${downloaded.contentType})` : "";
988
+ process.stdout.write(`Downloaded ${downloaded.bytes} bytes to ${downloaded.path}${mimeNote}\n`);
989
+ }
990
+ return;
991
+ }
992
+ process.stdout.write(`${renderedOutput}\n`);
993
+ }
994
+ // ---------------------------------------------------------------------------
995
+ // Registration
996
+ // ---------------------------------------------------------------------------
997
+ function collectOption(value, previous) {
998
+ return [...(previous ?? []), value];
999
+ }
1000
+ export function registerToolsCommands(program, addExamples, outputOption) {
1001
+ const tools = program
1002
+ .command("tools")
1003
+ .description("discover, inspect, and invoke connected-app MCP tools from the shell")
1004
+ .summary("connected-app MCP tools")
1005
+ .showHelpAfterError()
1006
+ .addHelpText("after", `
1007
+ Connected-app MCP servers (Google Drive, Gmail, Google Docs, Jira, Backroom,
1008
+ etc.) are resolved from your active endpoint's MCP catalog. Each invocation
1009
+ mints a short-lived ephemeral key, never prints it, and revokes it on exit.
1010
+
1011
+ Server names accept both canonical names (\`ditto-googledrive\`) and short
1012
+ aliases (\`googledrive\`, \`google-drive\`, \`gmail\`, \`ditto\`).`);
1013
+ const serversCmd = addProfileOption(tools
1014
+ .command("servers", { isDefault: true })
1015
+ .description("list connected MCP servers on the active endpoint")
1016
+ .option("-e, --endpoint <endpoint>", "endpoint slug, name, or id")
1017
+ .option("--session <id>", "MCP session id (default: T3CODE_THREAD_ID, active session, or auto-generated)")
1018
+ .option("--json", "print machine-readable JSON output")
1019
+ .addOption(outputOption())
1020
+ .action(cmdToolsServers));
1021
+ addExamples(serversCmd, ` heyditto tools
1022
+ heyditto tools --endpoint my-endpoint --json`);
1023
+ const listCmd = addProfileOption(tools
1024
+ .command("list")
1025
+ .alias("ls")
1026
+ .description("list tools on one connected MCP server (or across all servers when omitted)")
1027
+ .argument("[server]", "MCP server name or alias (e.g. googledrive, ditto-googledrive, ditto)")
1028
+ .option("-s, --search <query>", "filter tools by substring match on name or description")
1029
+ .option("-e, --endpoint <endpoint>", "endpoint slug, name, or id")
1030
+ .option("--session <id>", "MCP session id (default: T3CODE_THREAD_ID, active session, or auto-generated)")
1031
+ .option("--json", "print machine-readable JSON output")
1032
+ .addOption(outputOption())
1033
+ .action(cmdToolsList));
1034
+ addExamples(listCmd, ` heyditto tools list googledrive
1035
+ heyditto tools list googledrive --search download
1036
+ heyditto tools list --search gmail --json`);
1037
+ const describeCmd = addProfileOption(tools
1038
+ .command("describe")
1039
+ .alias("schema")
1040
+ .alias("inspect")
1041
+ .alias("show")
1042
+ .description("inspect one tool's description, required parameters, and JSON input schema")
1043
+ .argument("<server>", "MCP server name or alias (e.g. googledrive, gmail, ditto)")
1044
+ .argument("<tool>", "tool name")
1045
+ .option("-e, --endpoint <endpoint>", "endpoint slug, name, or id")
1046
+ .option("--session <id>", "MCP session id (default: T3CODE_THREAD_ID, active session, or auto-generated)")
1047
+ .option("--json", "print machine-readable JSON output")
1048
+ .addOption(outputOption())
1049
+ .action(cmdToolsDescribe));
1050
+ addExamples(describeCmd, ` heyditto tools describe googledrive download_file
1051
+ heyditto tools schema gmail search_messages --json`);
1052
+ const callCmd = addProfileOption(tools
1053
+ .command("call")
1054
+ .alias("run")
1055
+ .alias("invoke")
1056
+ .description("call a tool on a connected MCP server over Streamable HTTP")
1057
+ .argument("<server>", "MCP server name or alias (e.g. googledrive, gmail, ditto)")
1058
+ .argument("<tool>", "tool name")
1059
+ .argument("[input]", "optional JSON object, @file.json, or - for stdin")
1060
+ .option("--json <payload>", "tool arguments as a JSON object string, @file.json, or - for stdin")
1061
+ .option("--stdin", "read tool arguments JSON object from stdin")
1062
+ .option("-a, --arg <key=value>", "set one tool argument (repeatable; parses JSON numbers, booleans, arrays, and objects)", collectOption)
1063
+ .option("--raw-arg <key=value>", "set one string tool argument without JSON parsing (repeatable)", collectOption)
1064
+ .option("--download <path-or-dir>", "stream a returned presigned file (e.g. downloaded_file_content.s3url) or binary resource to disk without printing presigned URLs")
1065
+ .option("--timeout <seconds>", `tool call timeout in seconds (default ${DEFAULT_CALL_TIMEOUT_SECONDS})`)
1066
+ .option("-e, --endpoint <endpoint>", "endpoint slug, name, or id")
1067
+ .option("--session <id>", "MCP session id (default: T3CODE_THREAD_ID, active session, or auto-generated)")
1068
+ .addOption(outputOption())
1069
+ .action(cmdToolsCall));
1070
+ addExamples(callCmd, ` heyditto tools call googledrive list_files --arg page_size=10 --output json
1071
+ heyditto tools call googledrive download_file --arg file_id=1abc --download ./downloads/
1072
+ heyditto tools call gmail search_messages --json '{"query":"from:alice"}' --output json
1073
+ echo '{"query":"roadmap"}' | heyditto tools call googledrive search_files --stdin --output json
1074
+ heyditto tools call jira create_issue @issue.json --output json`);
1075
+ }
1076
+ //# sourceMappingURL=tools-commands.js.map