@agllama/mcp 0.18.0 → 0.19.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.
@@ -46,31 +46,87 @@ const MIME_MAP = {
46
46
  '.zip': 'application/zip',
47
47
  };
48
48
  const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
49
+ /** Business spec files (SOWs, signed documents). Matches the API's per-file cap. */
50
+ const MAX_SPEC_FILE_SIZE = 25 * 1024 * 1024; // 25MB
51
+ const TARGET_FIELDS = {
52
+ orgSlug: z.string().optional().describe('Org slug (session default)'),
53
+ projectKey: z.string().optional().describe('Project key (session default). Issues only'),
54
+ issueKey: z.string().optional().describe('Issue key (e.g., "PROJ-123"). Provide this OR specId'),
55
+ specId: z.string().optional().describe('Business spec ID. Provide this OR issueKey'),
56
+ };
57
+ /** Every attachment tool acts on exactly one of: an issue, a business spec. */
58
+ async function resolveTarget(input) {
59
+ if (input.issueKey && input.specId) {
60
+ return { error: 'Provide either issueKey or specId, not both.' };
61
+ }
62
+ if (!input.issueKey && !input.specId) {
63
+ return { error: 'Provide issueKey (for an issue) or specId (for a business spec).' };
64
+ }
65
+ if (input.specId) {
66
+ const context = await resolveOrg(input.orgSlug);
67
+ if ('error' in context)
68
+ return context;
69
+ return { kind: 'spec', orgSlug: context.orgSlug, specId: input.specId, label: `spec ${input.specId}` };
70
+ }
71
+ const context = await resolveOrgProject(input);
72
+ if ('error' in context)
73
+ return context;
74
+ return {
75
+ kind: 'issue',
76
+ orgSlug: context.orgSlug,
77
+ projectKey: context.projectKey,
78
+ issueKey: input.issueKey,
79
+ label: input.issueKey,
80
+ };
81
+ }
82
+ /** Never throws: a failed usage record must not fail the tool. */
83
+ async function recordCall(toolName, target) {
84
+ try {
85
+ await getApiClient().recordToolCall(toolName, target.kind === 'issue'
86
+ ? { orgSlug: target.orgSlug, projectKey: target.projectKey }
87
+ : { orgSlug: target.orgSlug, specId: target.specId });
88
+ }
89
+ catch {
90
+ // Ignore recording errors
91
+ }
92
+ }
93
+ function downloadUrlFor(target, attachmentId) {
94
+ const client = getApiClient();
95
+ return target.kind === 'issue'
96
+ ? client.getAttachmentDownloadUrl(target.orgSlug, target.projectKey, target.issueKey, attachmentId)
97
+ : client.getSpecAttachmentDownloadUrl(target.orgSlug, target.specId, attachmentId);
98
+ }
99
+ /** `{ issueKey }` or `{ specId }`, spread into a tool result. */
100
+ function targetRef(target) {
101
+ return target.kind === 'issue' ? { issueKey: target.issueKey } : { specId: target.specId };
102
+ }
49
103
  // ============================================
50
104
  // Attach File
51
105
  // ============================================
52
106
  export const attachFileToolName = 'llama_attach_file';
53
- export const attachFileToolDescription = `Upload local files to an issue. Max 10MB. Images, docs, archives supported.`;
107
+ export const attachFileToolDescription = `Upload local files to an issue (issueKey, max 10MB each) or a business spec (specId, max 25MB each). Images, PDFs, Office docs, text, archives. On a spec, setAsSpecDocument makes the file the spec document shown in the spec viewer.`;
54
108
  export const attachFileToolSchema = z.object({
55
- orgSlug: z.string().optional().describe('Org slug (session default)'),
56
- projectKey: z.string().optional().describe('Project key (session default)'),
57
- issueKey: z.string().describe('Issue key (e.g., "PROJ-123")'),
109
+ ...TARGET_FIELDS,
58
110
  filePaths: z.array(z.string()).min(1).describe('Absolute file paths to upload'),
59
- embedInDescription: z.boolean().optional().describe('If true, appends markdown image/link references to the issue description for uploaded files'),
111
+ embedInDescription: z.boolean().optional().describe('Issues only. If true, appends markdown image/link references to the issue description for uploaded files'),
112
+ setAsSpecDocument: z.boolean().optional().describe('Specs only. If true, the first file becomes the spec document (e.g. the SOW PDF), replacing any current one'),
60
113
  });
61
114
  export async function executeAttachFile(input) {
62
115
  try {
63
- const context = await resolveOrgProject(input);
64
- if ('error' in context) {
65
- return JSON.stringify({ success: false, error: context.error });
116
+ const target = await resolveTarget(input);
117
+ if ('error' in target) {
118
+ return JSON.stringify({ success: false, error: target.error });
66
119
  }
67
- const client = getApiClient();
68
- try {
69
- await client.recordToolCall('llama_attach_file', { orgSlug: context.orgSlug, projectKey: context.projectKey });
120
+ if (target.kind === 'spec' && input.embedInDescription) {
121
+ return JSON.stringify({ success: false, error: 'embedInDescription applies to issues only.' });
70
122
  }
71
- catch {
72
- // Ignore recording errors
123
+ if (target.kind === 'issue' && input.setAsSpecDocument) {
124
+ return JSON.stringify({ success: false, error: 'setAsSpecDocument applies to business specs only (use specId).' });
73
125
  }
126
+ const client = getApiClient();
127
+ await recordCall('llama_attach_file', target);
128
+ const maxFileSize = target.kind === 'spec' ? MAX_SPEC_FILE_SIZE : MAX_FILE_SIZE;
129
+ const maxLabel = `${maxFileSize / 1024 / 1024}MB`;
74
130
  // Validate all files before uploading any
75
131
  const validatedFiles = [];
76
132
  for (const filePath of input.filePaths) {
@@ -92,10 +148,10 @@ export async function executeAttachFile(input) {
92
148
  if (!stat.isFile()) {
93
149
  return JSON.stringify({ success: false, error: `Not a file: ${filePath}` });
94
150
  }
95
- if (stat.size > MAX_FILE_SIZE) {
151
+ if (stat.size > maxFileSize) {
96
152
  return JSON.stringify({
97
153
  success: false,
98
- error: `File too large (${(stat.size / 1024 / 1024).toFixed(1)}MB > 10MB limit): ${filePath}`,
154
+ error: `File too large (${(stat.size / 1024 / 1024).toFixed(1)}MB > ${maxLabel} limit): ${filePath}`,
99
155
  });
100
156
  }
101
157
  // Check MIME type
@@ -117,18 +173,30 @@ export async function executeAttachFile(input) {
117
173
  // Upload each file
118
174
  const results = [];
119
175
  const errors = [];
120
- for (const file of validatedFiles) {
176
+ for (const [index, file] of validatedFiles.entries()) {
121
177
  try {
122
178
  const buffer = await fs.readFile(file.filePath);
123
- const attachment = await client.uploadAttachmentBuffer(context.orgSlug, context.projectKey, input.issueKey, file.fileName, buffer, file.mimeType);
124
- const downloadUrl = client.getAttachmentDownloadUrl(context.orgSlug, context.projectKey, input.issueKey, attachment.id);
125
- results.push({
126
- fileName: file.fileName,
127
- size: file.size,
128
- attachmentId: attachment.id,
129
- downloadUrl,
130
- mimeType: file.mimeType,
131
- });
179
+ if (target.kind === 'spec') {
180
+ const attachment = await client.uploadSpecAttachmentBuffer(target.orgSlug, target.specId, file.fileName, buffer, file.mimeType, { isPrimary: input.setAsSpecDocument === true && index === 0 });
181
+ results.push({
182
+ fileName: file.fileName,
183
+ size: file.size,
184
+ attachmentId: attachment.id,
185
+ downloadUrl: downloadUrlFor(target, attachment.id),
186
+ mimeType: file.mimeType,
187
+ isSpecDocument: attachment.isPrimary,
188
+ });
189
+ }
190
+ else {
191
+ const attachment = await client.uploadAttachmentBuffer(target.orgSlug, target.projectKey, target.issueKey, file.fileName, buffer, file.mimeType);
192
+ results.push({
193
+ fileName: file.fileName,
194
+ size: file.size,
195
+ attachmentId: attachment.id,
196
+ downloadUrl: downloadUrlFor(target, attachment.id),
197
+ mimeType: file.mimeType,
198
+ });
199
+ }
132
200
  }
133
201
  catch (err) {
134
202
  errors.push({
@@ -144,10 +212,10 @@ export async function executeAttachFile(input) {
144
212
  errors,
145
213
  });
146
214
  }
147
- // Embed in description if requested
148
- if (input.embedInDescription && results.length > 0) {
215
+ // Embed in description if requested (issues only, checked above)
216
+ if (target.kind === 'issue' && input.embedInDescription && results.length > 0) {
149
217
  try {
150
- const issue = await client.getIssue(context.orgSlug, context.projectKey, input.issueKey);
218
+ const issue = await client.getIssue(target.orgSlug, target.projectKey, target.issueKey);
151
219
  const existingDesc = issue.description || '';
152
220
  const markdownLines = results.map((r) => {
153
221
  if (r.mimeType.startsWith('image/')) {
@@ -157,7 +225,7 @@ export async function executeAttachFile(input) {
157
225
  });
158
226
  const separator = existingDesc.length > 0 ? '\n\n' : '';
159
227
  const newDescription = existingDesc + separator + markdownLines.join('\n\n');
160
- await client.updateIssue(context.orgSlug, context.projectKey, input.issueKey, {
228
+ await client.updateIssue(target.orgSlug, target.projectKey, target.issueKey, {
161
229
  description: newDescription,
162
230
  });
163
231
  }
@@ -165,7 +233,7 @@ export async function executeAttachFile(input) {
165
233
  // Don't fail the whole operation if embed fails
166
234
  return JSON.stringify({
167
235
  success: true,
168
- message: `Uploaded ${results.length} file(s) to ${input.issueKey} (but failed to embed in description)`,
236
+ message: `Uploaded ${results.length} file(s) to ${target.label} (but failed to embed in description)`,
169
237
  attachments: results,
170
238
  ...(errors.length > 0 ? { errors } : {}),
171
239
  });
@@ -173,7 +241,7 @@ export async function executeAttachFile(input) {
173
241
  }
174
242
  return JSON.stringify({
175
243
  success: true,
176
- message: `Uploaded ${results.length} file(s) to ${input.issueKey}${input.embedInDescription ? ' and embedded in description' : ''}`,
244
+ message: `Uploaded ${results.length} file(s) to ${target.label}${input.embedInDescription ? ' and embedded in description' : ''}`,
177
245
  attachments: results,
178
246
  ...(errors.length > 0 ? { errors } : {}),
179
247
  });
@@ -186,29 +254,39 @@ export async function executeAttachFile(input) {
186
254
  // List Attachments
187
255
  // ============================================
188
256
  export const listAttachmentsToolName = 'llama_list_attachments';
189
- export const listAttachmentsToolDescription = `List all attachments on an issue.`;
257
+ export const listAttachmentsToolDescription = `List all attachments on an issue (issueKey) or a business spec (specId). On a spec, isSpecDocument marks the file that is the spec itself.`;
190
258
  export const listAttachmentsToolSchema = z.object({
191
- orgSlug: z.string().optional().describe('Org slug (session default)'),
192
- projectKey: z.string().optional().describe('Project key (session default)'),
193
- issueKey: z.string().describe('Issue key (e.g., "PROJ-123")'),
259
+ ...TARGET_FIELDS,
194
260
  });
195
261
  export async function executeListAttachments(input) {
196
262
  try {
197
- const context = await resolveOrgProject(input);
198
- if ('error' in context) {
199
- return JSON.stringify({ success: false, error: context.error });
263
+ const target = await resolveTarget(input);
264
+ if ('error' in target) {
265
+ return JSON.stringify({ success: false, error: target.error });
200
266
  }
201
267
  const client = getApiClient();
202
- try {
203
- await client.recordToolCall('llama_list_attachments', { orgSlug: context.orgSlug, projectKey: context.projectKey });
204
- }
205
- catch {
206
- // Ignore recording errors
268
+ await recordCall('llama_list_attachments', target);
269
+ if (target.kind === 'spec') {
270
+ const attachments = await client.listSpecAttachments(target.orgSlug, target.specId);
271
+ return JSON.stringify({
272
+ success: true,
273
+ specId: target.specId,
274
+ count: attachments.length,
275
+ attachments: attachments.map((a) => ({
276
+ id: a.id,
277
+ fileName: a.originalName,
278
+ fileSize: a.fileSize,
279
+ mimeType: a.mimeType,
280
+ isSpecDocument: a.isPrimary,
281
+ uploadedBy: a.uploadedBy?.name ?? null,
282
+ createdAt: a.createdAt,
283
+ })),
284
+ });
207
285
  }
208
- const attachments = await client.listAttachments(context.orgSlug, context.projectKey, input.issueKey);
286
+ const attachments = await client.listAttachments(target.orgSlug, target.projectKey, target.issueKey);
209
287
  return JSON.stringify({
210
288
  success: true,
211
- issueKey: input.issueKey,
289
+ issueKey: target.issueKey,
212
290
  count: attachments.length,
213
291
  attachments: attachments.map((a) => ({
214
292
  id: a.id,
@@ -228,30 +306,28 @@ export async function executeListAttachments(input) {
228
306
  // Delete Attachment
229
307
  // ============================================
230
308
  export const deleteAttachmentToolName = 'llama_delete_attachment';
231
- export const deleteAttachmentToolDescription = `Delete an attachment from an issue.`;
309
+ export const deleteAttachmentToolDescription = `Delete an attachment from an issue (issueKey) or a business spec (specId).`;
232
310
  export const deleteAttachmentToolSchema = z.object({
233
- orgSlug: z.string().optional().describe('Org slug (session default)'),
234
- projectKey: z.string().optional().describe('Project key (session default)'),
235
- issueKey: z.string().describe('Issue key (e.g., "PROJ-123")'),
311
+ ...TARGET_FIELDS,
236
312
  attachmentId: z.string().describe('Attachment ID to delete'),
237
313
  });
238
314
  export async function executeDeleteAttachment(input) {
239
315
  try {
240
- const context = await resolveOrgProject(input);
241
- if ('error' in context) {
242
- return JSON.stringify({ success: false, error: context.error });
316
+ const target = await resolveTarget(input);
317
+ if ('error' in target) {
318
+ return JSON.stringify({ success: false, error: target.error });
243
319
  }
244
320
  const client = getApiClient();
245
- try {
246
- await client.recordToolCall('llama_delete_attachment', { orgSlug: context.orgSlug, projectKey: context.projectKey });
321
+ await recordCall('llama_delete_attachment', target);
322
+ if (target.kind === 'spec') {
323
+ await client.deleteSpecAttachment(target.orgSlug, target.specId, input.attachmentId);
247
324
  }
248
- catch {
249
- // Ignore recording errors
325
+ else {
326
+ await client.deleteAttachment(target.orgSlug, target.projectKey, target.issueKey, input.attachmentId);
250
327
  }
251
- await client.deleteAttachment(context.orgSlug, context.projectKey, input.issueKey, input.attachmentId);
252
328
  return JSON.stringify({
253
329
  success: true,
254
- message: `Deleted attachment ${input.attachmentId} from ${input.issueKey}`,
330
+ message: `Deleted attachment ${input.attachmentId} from ${target.label}`,
255
331
  });
256
332
  }
257
333
  catch (error) {
@@ -273,57 +349,181 @@ const SKIPPED_MIME_PREFIXES = ['video/', 'audio/'];
273
349
  const MAX_EMBEDDED_SIZE = 1024 * 1024; // 1MB
274
350
  /** Retina screenshots are often over 1MB. Above this, return metadata only. */
275
351
  const MAX_IMAGE_EMBEDDED_SIZE = 5 * 1024 * 1024; // 5MB
352
+ /** Largest file `saveTo` writes to disk. Matches the API's upload ceiling. */
353
+ const MAX_SAVED_SIZE = 50 * 1024 * 1024; // 50MB
276
354
  function embeddedSizeLimit(mimeType) {
277
355
  return IMAGE_MIME_TYPES.has(mimeType) ? MAX_IMAGE_EMBEDDED_SIZE : MAX_EMBEDDED_SIZE;
278
356
  }
279
357
  function formatMegabytes(bytes) {
280
358
  return `${bytes / (1024 * 1024)}MB`;
281
359
  }
360
+ const SAVE_TO_HINT = 'Pass saveTo (an absolute local directory) to save the file to disk, then read it from savedPath.';
361
+ /**
362
+ * Extension a saved attachment gets, chosen by its type. Never taken from the
363
+ * uploaded name: whoever uploaded the file picked that name.
364
+ */
365
+ const SAVE_EXTENSION_BY_MIME = {
366
+ 'image/jpeg': '.jpg',
367
+ 'image/png': '.png',
368
+ 'image/gif': '.gif',
369
+ 'image/webp': '.webp',
370
+ 'application/pdf': '.pdf',
371
+ 'application/msword': '.doc',
372
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx',
373
+ 'application/vnd.ms-excel': '.xls',
374
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '.xlsx',
375
+ 'text/plain': '.txt',
376
+ 'text/markdown': '.md',
377
+ 'text/csv': '.csv',
378
+ 'application/json': '.json',
379
+ 'application/zip': '.zip',
380
+ 'application/x-zip-compressed': '.zip',
381
+ 'video/webm': '.webm',
382
+ 'video/mp4': '.mp4',
383
+ };
384
+ const MAX_SAVE_NAME_ATTEMPTS = 20;
385
+ /**
386
+ * The on-disk name for a saved attachment: `<readable stem>-<id><.ext>`.
387
+ *
388
+ * An attachment's name is chosen by its uploader, who may be anyone able to
389
+ * file feedback, and the directory is often an agent's working directory. A
390
+ * file saved under its uploaded name could land as `CLAUDE.md`, `.npmrc`,
391
+ * `.envrc` or `run.sh` and be picked up by the next tool that reads that
392
+ * directory. So the uploaded name contributes only a readable stem:
393
+ * - letters, digits, space, `_` and `-` survive; everything else, dots
394
+ * included, becomes `_` (no dotfiles, no path separators of either OS, no
395
+ * characters Windows refuses);
396
+ * - the attachment id is always appended, so the result can never equal a
397
+ * well-known file name or a Windows device name;
398
+ * - the extension comes from the type, from a fixed list.
399
+ */
400
+ function savedFileName(originalName, mimeType, attachmentId, attempt) {
401
+ const ext = SAVE_EXTENSION_BY_MIME[mimeType.toLowerCase().split(';')[0].trim()] ?? '.bin';
402
+ const base = originalName.split(/[\\/]/).pop() ?? '';
403
+ const stem = base
404
+ .replace(/\.[^.]*$/, '')
405
+ .replace(/[^A-Za-z0-9 _-]/g, '_')
406
+ .replace(/^[\s_-]+/, '')
407
+ .slice(0, 80)
408
+ .trim() || 'attachment';
409
+ const idPart = attachmentId.replace(/[^A-Za-z0-9]/g, '').slice(-8) || 'file';
410
+ const counter = attempt === 0 ? '' : `-${attempt + 1}`;
411
+ return `${stem}-${idPart}${counter}${ext}`;
412
+ }
413
+ /**
414
+ * Write a downloaded attachment into `directory`. Every write is exclusive
415
+ * (`wx`): an existing file, or a symlink sitting at the target name, is never
416
+ * written through. A name already taken gets a numbered sibling instead.
417
+ */
418
+ async function saveAttachment(directory, originalName, mimeType, attachmentId, buffer) {
419
+ for (let attempt = 0; attempt < MAX_SAVE_NAME_ATTEMPTS; attempt++) {
420
+ const target = path.join(directory, savedFileName(originalName, mimeType, attachmentId, attempt));
421
+ try {
422
+ await fs.writeFile(target, buffer, { flag: 'wx' });
423
+ return target;
424
+ }
425
+ catch (err) {
426
+ if (err.code !== 'EEXIST')
427
+ throw err;
428
+ }
429
+ }
430
+ throw new Error(`Could not save the file: ${MAX_SAVE_NAME_ATTEMPTS} copies already exist in ${directory}`);
431
+ }
282
432
  export const downloadAttachmentToolName = 'llama_download_attachment';
283
- export const downloadAttachmentToolDescription = `Download and view an attachment. Images are returned visually (up to ${formatMegabytes(MAX_IMAGE_EMBEDDED_SIZE)}), text files as readable content (up to ${formatMegabytes(MAX_EMBEDDED_SIZE)}). Skips video/audio (use llama_get_transcription instead). Larger files return metadata only.`;
433
+ export const downloadAttachmentToolDescription = `Download and view an attachment on an issue (issueKey) or a business spec (specId). Images are returned visually (up to ${formatMegabytes(MAX_IMAGE_EMBEDDED_SIZE)}), text files as readable content (up to ${formatMegabytes(MAX_EMBEDDED_SIZE)}). PDFs, Office files and anything larger: pass saveTo (a local directory) to save the file and read it from disk. Skips video/audio (use llama_get_transcription instead).`;
284
434
  export const downloadAttachmentToolSchema = z.object({
285
- orgSlug: z.string().optional().describe('Org slug (session default)'),
286
- projectKey: z.string().optional().describe('Project key (session default)'),
287
- issueKey: z.string().describe('Issue key (e.g., "PROJ-123")'),
435
+ ...TARGET_FIELDS,
288
436
  attachmentId: z.string().describe('Attachment ID (from llama_list_attachments)'),
437
+ saveTo: z.string().optional().describe('Absolute path of an existing local directory. The file is written there (any type, up to 50MB) under a generated name and its path returned as savedPath. Not available on the hosted connector'),
289
438
  });
439
+ function textBlock(payload) {
440
+ return [{ type: 'text', text: JSON.stringify(payload) }];
441
+ }
290
442
  export async function executeDownloadAttachment(input) {
291
443
  try {
292
- const context = await resolveOrgProject(input);
293
- if ('error' in context) {
294
- return [{ type: 'text', text: JSON.stringify({ success: false, error: context.error }) }];
444
+ const target = await resolveTarget(input);
445
+ if ('error' in target) {
446
+ return textBlock({ success: false, error: target.error });
295
447
  }
296
448
  const client = getApiClient();
297
- try {
298
- await client.recordToolCall('llama_download_attachment', {
299
- orgSlug: context.orgSlug, projectKey: context.projectKey,
300
- });
301
- }
302
- catch {
303
- // Ignore recording errors
449
+ if (input.saveTo !== undefined) {
450
+ // On the hosted connector this code runs inside the API server: a
451
+ // "local directory" there would be the server's own disk.
452
+ if (client.isHosted) {
453
+ return textBlock({ success: false, error: 'saveTo is not available on the hosted connector: there is no local disk to save to.' });
454
+ }
455
+ if (!path.isAbsolute(input.saveTo)) {
456
+ return textBlock({ success: false, error: `saveTo must be an absolute path: ${input.saveTo}` });
457
+ }
458
+ // A `..` path segment, not the substring: "C:\\work\\v1..2" is a real directory.
459
+ if (input.saveTo.split(/[\\/]/).includes('..')) {
460
+ return textBlock({ success: false, error: `Path traversal not allowed: ${input.saveTo}` });
461
+ }
462
+ let stat;
463
+ try {
464
+ stat = await fs.stat(input.saveTo);
465
+ }
466
+ catch {
467
+ return textBlock({ success: false, error: `saveTo directory not found: ${input.saveTo}` });
468
+ }
469
+ if (!stat.isDirectory()) {
470
+ return textBlock({ success: false, error: `saveTo is not a directory: ${input.saveTo}` });
471
+ }
304
472
  }
305
- const downloadUrl = client.getAttachmentDownloadUrl(context.orgSlug, context.projectKey, input.issueKey, input.attachmentId);
473
+ await recordCall('llama_download_attachment', target);
474
+ const downloadUrl = downloadUrlFor(target, input.attachmentId);
306
475
  // Fetch attachment metadata to check MIME type and size before downloading
307
- const allAttachments = await client.listAttachments(context.orgSlug, context.projectKey, input.issueKey);
476
+ const allAttachments = target.kind === 'issue'
477
+ ? await client.listAttachments(target.orgSlug, target.projectKey, target.issueKey)
478
+ : await client.listSpecAttachments(target.orgSlug, target.specId);
308
479
  const attachmentMeta = allAttachments.find((a) => a.id === input.attachmentId);
309
480
  if (!attachmentMeta) {
310
- return [{ type: 'text', text: JSON.stringify({ success: false, error: `Attachment ${input.attachmentId} not found on ${input.issueKey}` }) }];
481
+ return textBlock({ success: false, error: `Attachment ${input.attachmentId} not found on ${target.label}` });
311
482
  }
312
483
  const metaMimeType = attachmentMeta.mimeType;
313
484
  const metaFileSize = attachmentMeta.fileSize;
485
+ const ref = targetRef(target);
486
+ const download = () => target.kind === 'issue'
487
+ ? client.downloadAttachment(target.orgSlug, target.projectKey, target.issueKey, input.attachmentId)
488
+ : client.downloadSpecAttachment(target.orgSlug, target.specId, input.attachmentId);
489
+ // Save to disk: any type, no embed limits. The caller reads it from there.
490
+ if (input.saveTo !== undefined) {
491
+ if (metaFileSize > MAX_SAVED_SIZE) {
492
+ return textBlock({
493
+ success: false,
494
+ error: `File too large to save (${(metaFileSize / 1024 / 1024).toFixed(1)}MB > ${formatMegabytes(MAX_SAVED_SIZE)} limit).`,
495
+ });
496
+ }
497
+ const { buffer, contentType } = await download();
498
+ const savedPath = await saveAttachment(input.saveTo, attachmentMeta.originalName, metaMimeType, input.attachmentId, buffer);
499
+ return textBlock({
500
+ success: true,
501
+ attachmentId: input.attachmentId,
502
+ ...ref,
503
+ fileName: attachmentMeta.originalName,
504
+ contentType,
505
+ fileSize: buffer.length,
506
+ savedPath,
507
+ note: 'Saved to disk. Read the file at savedPath.',
508
+ });
509
+ }
314
510
  // Skip video/audio — automatically include transcription if available
315
511
  if (SKIPPED_MIME_PREFIXES.some((p) => metaMimeType.startsWith(p))) {
316
512
  const result = {
317
513
  success: true,
318
514
  attachmentId: input.attachmentId,
319
- issueKey: input.issueKey,
515
+ ...ref,
320
516
  fileName: attachmentMeta.originalName,
321
517
  contentType: metaMimeType,
322
518
  fileSize: metaFileSize,
323
519
  };
520
+ if (target.kind === 'spec') {
521
+ result.note = `${metaMimeType} file — no transcription available.`;
522
+ return textBlock(result);
523
+ }
324
524
  // Try to fetch transcription for this specific attachment
325
525
  try {
326
- const transcriptions = await client.getTranscriptions(context.orgSlug, context.projectKey, input.issueKey);
526
+ const transcriptions = await client.getTranscriptions(target.orgSlug, target.projectKey, target.issueKey);
327
527
  const match = transcriptions.find((t) => t.id === input.attachmentId);
328
528
  if (match?.transcription) {
329
529
  const t = match.transcription;
@@ -341,32 +541,44 @@ export async function executeDownloadAttachment(input) {
341
541
  catch {
342
542
  result.note = `${metaMimeType} file — could not fetch transcription.`;
343
543
  }
344
- return [{ type: 'text', text: JSON.stringify(result) }];
544
+ return textBlock(result);
345
545
  }
546
+ const canSave = !client.isHosted;
346
547
  // Size guard: don't download files we will not embed. Images get a
347
548
  // higher cap than text — a screenshot the caller cannot see is useless.
348
549
  const embedLimit = embeddedSizeLimit(metaMimeType);
349
550
  if (metaFileSize > embedLimit) {
350
- return [{
351
- type: 'text',
352
- text: JSON.stringify({
353
- success: true,
354
- attachmentId: input.attachmentId,
355
- issueKey: input.issueKey,
356
- fileName: attachmentMeta.originalName,
357
- contentType: metaMimeType,
358
- fileSize: metaFileSize,
359
- downloadUrl,
360
- note: `File too large to embed (${(metaFileSize / 1024 / 1024).toFixed(1)}MB > ${formatMegabytes(embedLimit)} limit). Use the download URL to access it.`,
361
- }),
362
- }];
551
+ return textBlock({
552
+ success: true,
553
+ attachmentId: input.attachmentId,
554
+ ...ref,
555
+ fileName: attachmentMeta.originalName,
556
+ contentType: metaMimeType,
557
+ fileSize: metaFileSize,
558
+ downloadUrl,
559
+ note: `File too large to embed (${(metaFileSize / 1024 / 1024).toFixed(1)}MB > ${formatMegabytes(embedLimit)} limit). ${canSave ? SAVE_TO_HINT : 'Use the download URL to access it.'}`,
560
+ });
561
+ }
562
+ // A binary type is never embedded, so do not pull its bytes just to drop them.
563
+ const embeddable = IMAGE_MIME_TYPES.has(metaMimeType) || TEXT_MIME_TYPES.has(metaMimeType) || metaMimeType.startsWith('text/');
564
+ if (!embeddable) {
565
+ return textBlock({
566
+ success: true,
567
+ attachmentId: input.attachmentId,
568
+ ...ref,
569
+ fileName: attachmentMeta.originalName,
570
+ contentType: metaMimeType,
571
+ fileSize: metaFileSize,
572
+ downloadUrl,
573
+ note: `Binary file (${metaMimeType}) cannot be displayed inline. ${canSave ? SAVE_TO_HINT : 'Use the download URL to access it.'}`,
574
+ });
363
575
  }
364
576
  // Download the file
365
- const { buffer, contentType } = await client.downloadAttachment(context.orgSlug, context.projectKey, input.issueKey, input.attachmentId);
577
+ const { buffer, contentType } = await download();
366
578
  const metadata = {
367
579
  success: true,
368
580
  attachmentId: input.attachmentId,
369
- issueKey: input.issueKey,
581
+ ...ref,
370
582
  contentType,
371
583
  fileSize: buffer.length,
372
584
  downloadUrl,
@@ -386,13 +598,10 @@ export async function executeDownloadAttachment(input) {
386
598
  ];
387
599
  }
388
600
  // Other binary (PDF, docx, zip, etc.): can't embed, provide link
389
- return [{
390
- type: 'text',
391
- text: JSON.stringify({
392
- ...metadata,
393
- note: `Binary file (${contentType}) cannot be displayed inline. Use the download URL to access it.`,
394
- }),
395
- }];
601
+ return textBlock({
602
+ ...metadata,
603
+ note: `Binary file (${contentType}) cannot be displayed inline. ${canSave ? SAVE_TO_HINT : 'Use the download URL to access it.'}`,
604
+ });
396
605
  }
397
606
  catch (error) {
398
607
  return [{ type: 'text', text: formatError(error, 'download attachment') }];