moz-agent-tools 0.1.0__tar.gz

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,62 @@
1
+ *model
2
+ *model.zst
3
+ *model.zst.etag
4
+ *data_X
5
+ *data_y
6
+ *data_X.zst
7
+ *data_X.zst.etag
8
+ *data_y.zst
9
+ *data_y.zst.etag
10
+ feature_importance.png
11
+ importance.html
12
+ importances.json
13
+ metrics.json
14
+ probs.json
15
+ services/bugbug-api/models/*model*
16
+
17
+ data/
18
+ sheets/
19
+
20
+ .mypy_cache/
21
+ .pytest_cache/
22
+ *.pyc
23
+ .coverage
24
+
25
+ # Distribution / packaging
26
+ .Python
27
+ build/
28
+ develop-eggs/
29
+ dist/
30
+ downloads/
31
+ eggs/
32
+ .eggs/
33
+ lib/
34
+ lib64/
35
+ parts/
36
+ sdist/
37
+ var/
38
+ wheels/
39
+ pip-wheel-metadata/
40
+ share/python-wheels/
41
+ *.egg-info/
42
+ .installed.cfg
43
+ *.egg
44
+ MANIFEST
45
+ cache/
46
+ node_modules/
47
+
48
+ # Logs
49
+ *.log
50
+ # Desktop Service Store
51
+ *.DS_Store
52
+
53
+ # Local env files
54
+ .env
55
+ /services/bugbug-api/docker-compose.override.yml
56
+
57
+ # Local files
58
+ *.local.*
59
+
60
+ # Claude Code local state
61
+ .claude/worktrees/
62
+ .claude/.cc-writes/
@@ -0,0 +1,20 @@
1
+ Metadata-Version: 2.5
2
+ Name: moz-agent-tools
3
+ Version: 0.1.0
4
+ Summary: Reusable, framework-neutral agent tools (declaration + per-framework adapters)
5
+ Requires-Python: >=3.14
6
+ Requires-Dist: pydantic>=2.6.0
7
+ Provides-Extra: bugzilla
8
+ Requires-Dist: bugzilla-client; extra == 'bugzilla'
9
+ Provides-Extra: claude-sdk
10
+ Requires-Dist: claude-agent-sdk>=0.1.30; extra == 'claude-sdk'
11
+ Provides-Extra: firefox
12
+ Requires-Dist: grizzly-framework; extra == 'firefox'
13
+ Requires-Dist: prefpicker; extra == 'firefox'
14
+ Provides-Extra: mcp-server
15
+ Requires-Dist: fastmcp>=3.4.0; extra == 'mcp-server'
16
+ Requires-Dist: uvicorn; extra == 'mcp-server'
17
+ Provides-Extra: searchfox
18
+ Requires-Dist: searchfox>=0.20.3; extra == 'searchfox'
19
+ Provides-Extra: vcs
20
+ Requires-Dist: httpx; extra == 'vcs'
@@ -0,0 +1 @@
1
+ 0.1.0
@@ -0,0 +1,14 @@
1
+ """Reusable, framework-neutral agent tools.
2
+
3
+ Each tool is an async handler decorated with :func:`agent_tools.registry.tool`;
4
+ the decorator infers its name, namespace, description and argument schema. A
5
+ per-framework adapter (``agent_tools.claude_sdk`` today) turns a module's tools
6
+ into a runnable server. Import the submodule you need directly (e.g.
7
+ ``from agent_tools import bugzilla``) — this ``__init__`` imports no submodules,
8
+ so pulling one tool never drags in another's optional dependencies, and the
9
+ base package never imports any agent framework.
10
+ """
11
+
12
+ from agent_tools.registry import ToolDefinition, ToolError, tool, tools_in
13
+
14
+ __all__ = ["ToolDefinition", "ToolError", "tool", "tools_in"]
@@ -0,0 +1,553 @@
1
+ """Read-only Bugzilla tools backed by ``bugzilla_client``.
2
+
3
+ Framework-neutral: each tool is a ``@tool``-decorated handler whose first
4
+ parameter is a :class:`BugzillaContext`. Handlers return plain data and surface
5
+ proxy-level restrictions (code 101: endpoint not exposed, code 102: access
6
+ denied) as a structured :class:`~agent_tools.registry.ToolError`.
7
+ """
8
+
9
+ import base64
10
+ import functools
11
+ import mimetypes
12
+ from collections.abc import Awaitable, Callable
13
+ from dataclasses import dataclass
14
+ from pathlib import PurePosixPath
15
+ from typing import Annotated, Any
16
+
17
+ from bugzilla_client import BugzillaClient, BugzillaError
18
+ from pydantic import Field
19
+
20
+ from agent_tools.registry import ToolError, tool, tools_in
21
+
22
+ # What Claude can actually interpret once an attachment reaches it — as an image
23
+ # block via the built-in Read tool, or as text. Deliberately narrower than what
24
+ # Bugzilla accepts: a screencast costs a full download and tens of thousands of
25
+ # tokens and still comes back undecodable, which is what
26
+ # https://github.com/mozilla/ai-dev/issues/6701 was filed about. Anything absent
27
+ # is refused, so a new video or archive format needs no matching reject list.
28
+ ALLOWED_ATTACHMENT_TYPES = frozenset(
29
+ {
30
+ # The four image formats the Anthropic API accepts as image blocks.
31
+ "image/png",
32
+ "image/jpeg",
33
+ "image/gif",
34
+ "image/webp",
35
+ # Not rendered as an image, but readable as markup.
36
+ "image/svg+xml",
37
+ "application/pdf",
38
+ # Textual application/* types Bugzilla serves for logs, testcases, configs.
39
+ "application/json",
40
+ "application/xml",
41
+ "application/javascript",
42
+ "application/x-javascript",
43
+ }
44
+ )
45
+
46
+ # Every text/* subtype is allowed on top of the set above — text/plain, text/html,
47
+ # text/css, text/csv, text/x-log and text/x-phabricator-request are all just text,
48
+ # and enumerating them would only mean missing one.
49
+ _ALLOWED_TYPE_PREFIX = "text/"
50
+
51
+ # Bugzilla records the type the uploader chose, so a plain log routinely arrives
52
+ # as application/octet-stream, and so does a screencast saved without a type.
53
+ # Resolve those from the file name instead.
54
+ _OCTET_STREAM = "application/octet-stream"
55
+
56
+ # Python's built-in table, with the system mime database deliberately left out
57
+ # (`filenames=()`). Reading /etc/mime.types would make the verdict depend on the
58
+ # host: .log resolves to text/plain on a macOS dev box via /etc/apache2/mime.types
59
+ # and to nothing in the CI and agent containers, so an update.log would be
60
+ # readable on a laptop and refused in production. The built-in table already
61
+ # covers .md, .json, .csv, .html, .png and, on the reject side, .mp4, .webm,
62
+ # .mov, .zip and .tar.
63
+ _MIMETYPES = mimetypes.MimeTypes(filenames=())
64
+
65
+ # What the built-in table does not know, and Bugzilla reporters attach anyway.
66
+ _EXTENSION_TYPES = {
67
+ ".log": "text/plain",
68
+ ".diff": "text/plain",
69
+ ".patch": "text/plain",
70
+ }
71
+
72
+ # `claude_sdk._make_tool` can only emit {"type": "text"}, so a base64 image in a
73
+ # tool result is never an image block, just a very long string.
74
+ INLINEABLE_ATTACHMENT_TYPES = frozenset(
75
+ {
76
+ "application/json",
77
+ "application/xml",
78
+ "application/javascript",
79
+ "application/x-javascript",
80
+ # Markup, so the text is the content.
81
+ "image/svg+xml",
82
+ }
83
+ )
84
+
85
+ # Bugzilla accepts attachments up to 10MB, and base64 inflates by 4/3, so an
86
+ # unbounded inline is ~13MB of text for one file. 256KiB decoded is ~350KB of
87
+ # base64, on the order of 85k tokens: enough for an update.log or a testcase,
88
+ # and past that download_attachment plus Grep beats reading the whole thing.
89
+ MAX_INLINE_BYTES = 256 * 1024
90
+
91
+ MAX_INLINE_ATTACHMENTS = 10
92
+
93
+ # The allowlist in the form the agent reads back in an error payload.
94
+ _ALLOWED_SUMMARY = (
95
+ "text/*, images (png/jpeg/gif/webp/svg), PDF, and JSON/XML/JavaScript"
96
+ )
97
+
98
+
99
+ def _normalize_type(content_type: str | None) -> str:
100
+ """Lowercase a content type and drop its parameters.
101
+
102
+ Bugzilla passes through whatever the uploader sent, so ``TEXT/PLAIN`` and
103
+ ``text/plain; charset=UTF-8`` both turn up and both mean text/plain.
104
+ """
105
+ return (content_type or "").split(";", 1)[0].strip().lower()
106
+
107
+
108
+ def _effective_content_type(att: dict[str, Any]) -> str:
109
+ """Resolve what an attachment is, rather than only what it claims to be.
110
+
111
+ ``is_patch`` wins outright because a Bugzilla patch is text by definition —
112
+ ``hackbot_runtime.actions.bugzilla.add_attachment`` makes the same assumption
113
+ in the write direction. Returns "" when nothing identifies the attachment,
114
+ which the caller treats as not readable.
115
+ """
116
+ if att.get("is_patch"):
117
+ return "text/plain"
118
+ content_type = _normalize_type(att.get("content_type"))
119
+ if content_type and content_type != _OCTET_STREAM:
120
+ return content_type
121
+ file_name = att.get("file_name") or ""
122
+ suffix = PurePosixPath(file_name).suffix.lower()
123
+ guessed = _EXTENSION_TYPES.get(suffix) or _MIMETYPES.guess_type(file_name)[0]
124
+ return _normalize_type(guessed)
125
+
126
+
127
+ def attachment_type_allowed(att: dict[str, Any]) -> tuple[bool, str]:
128
+ """Return whether an attachment is readable, and the type that decided it.
129
+
130
+ The type comes back too so a caller can say *what* it refused instead of only
131
+ that it refused something.
132
+ """
133
+ effective = _effective_content_type(att)
134
+ allowed = (
135
+ effective.startswith(_ALLOWED_TYPE_PREFIX)
136
+ or effective in ALLOWED_ATTACHMENT_TYPES
137
+ )
138
+ return allowed, effective
139
+
140
+
141
+ def _inlineable(effective_content_type: str) -> bool:
142
+ """Whether this type is worth base64-ing into a tool result rather than a file."""
143
+ return (
144
+ effective_content_type.startswith(_ALLOWED_TYPE_PREFIX)
145
+ or effective_content_type in INLINEABLE_ATTACHMENT_TYPES
146
+ )
147
+
148
+
149
+ def _type_not_allowed_error(
150
+ attachment_id: int, att: dict[str, Any], effective: str
151
+ ) -> ToolError:
152
+ """Build the refusal an agent sees for an attachment it cannot read.
153
+
154
+ ``claude_sdk`` renders a ToolError payload as the tool result itself, so the
155
+ hint is the only place to keep the agent from burning turns retrying, and to
156
+ tell it to disclose that it never saw the attachment.
157
+ """
158
+ return ToolError(
159
+ f"attachment {attachment_id} is "
160
+ f"{effective or 'of an unrecognized type'}, which Claude cannot read",
161
+ payload={
162
+ "error": "attachment_type_not_allowed",
163
+ "attachment_id": attachment_id,
164
+ "file_name": att.get("file_name"),
165
+ "content_type": att.get("content_type"),
166
+ "effective_content_type": effective or None,
167
+ "allowed": _ALLOWED_SUMMARY,
168
+ "hint": (
169
+ "Video, audio, and archive attachments are refused on purpose — "
170
+ "Claude cannot interpret them and downloading one is expensive. "
171
+ "Do not retry. Work from the bug's text and say in your comment "
172
+ "that you did not view this attachment."
173
+ ),
174
+ },
175
+ )
176
+
177
+
178
+ @dataclass
179
+ class BugzillaContext:
180
+ """Holds the live Bugzilla client.
181
+
182
+ Every tool receives the same instance, so they share auth and one TCP
183
+ connection pool.
184
+ """
185
+
186
+ client: BugzillaClient
187
+
188
+
189
+ def _to_tool_error(e: Exception) -> ToolError:
190
+ """Turn a failed Bugzilla call into a structured ToolError.
191
+
192
+ The payload is friendly and machine-parseable so the agent can decide what
193
+ to do (skip the bug, try a different endpoint, ...) rather than just seeing
194
+ a stack trace. The client raises ``BugzillaError`` for Bugzilla-level errors
195
+ and non-JSON answers; a network failure surfaces as an ``httpx`` error.
196
+ """
197
+ if isinstance(e, BugzillaError):
198
+ if e.code == 101:
199
+ kind = "endpoint_not_exposed"
200
+ hint = "This Bugzilla proxy does not expose this endpoint."
201
+ elif e.code == 102:
202
+ kind = "access_denied"
203
+ hint = "Your API key cannot access this bug. Skip it."
204
+ else:
205
+ kind = "bugzilla_error"
206
+ hint = None
207
+ payload: dict[str, Any] = {"error": kind, "code": e.code, "message": e.message}
208
+ if hint:
209
+ payload["hint"] = hint
210
+ return ToolError(e.message, payload=payload)
211
+ return ToolError(
212
+ f"Bugzilla request failed: {type(e).__name__}: {e}",
213
+ payload={"error": "bugzilla_request_failed", "message": str(e)},
214
+ )
215
+
216
+
217
+ def _bugzilla_errors(fn: Callable[..., Awaitable]) -> Callable[..., Awaitable]:
218
+ """Let a tool call the client directly and still fail with a ToolError."""
219
+
220
+ @functools.wraps(fn)
221
+ async def wrapper(*args, **kwargs):
222
+ try:
223
+ return await fn(*args, **kwargs)
224
+ except ToolError:
225
+ raise
226
+ except Exception as e:
227
+ raise _to_tool_error(e) from e
228
+
229
+ return wrapper
230
+
231
+
232
+ @tool
233
+ @_bugzilla_errors
234
+ async def search_bugs(
235
+ ctx: BugzillaContext,
236
+ params: Annotated[
237
+ dict[str, Any],
238
+ Field(
239
+ description=(
240
+ "Bugzilla REST /bug query parameters. Values may be strings, "
241
+ "ints, or comma-separated lists. Example: "
242
+ '{"blocks": 12345, "keywords": "sec-low", '
243
+ '"include_fields": "id,summary,status,whiteboard,keywords"}'
244
+ )
245
+ ),
246
+ ],
247
+ ) -> dict:
248
+ """Search Bugzilla using raw REST query parameters.
249
+
250
+ Returns matching bugs in one bulk request. Parameters are ANDed together
251
+ (intersect). IMPORTANT: this proxy drops 'whiteboard' and 'keywords' from
252
+ _all / _default field sets — list them explicitly in include_fields if you
253
+ need them. Common params: id, keywords, blocks, depends_on, product,
254
+ component, status, resolution, priority, severity, assigned_to, whiteboard,
255
+ include_fields, limit.
256
+ """
257
+ result = (await ctx.client.bugs.search(params)).data
258
+ bugs = result.get("bugs", [])
259
+ return {"count": len(bugs), "bugs": bugs}
260
+
261
+
262
+ @tool
263
+ @_bugzilla_errors
264
+ async def get_bugs(
265
+ ctx: BugzillaContext,
266
+ ids: Annotated[list[int], Field(description="Bug IDs to fetch.")],
267
+ include_fields: Annotated[
268
+ str | None,
269
+ Field(
270
+ description=(
271
+ "Comma-separated field list, or '_default'/'_all'. Defaults to "
272
+ "a sensible triage set."
273
+ )
274
+ ),
275
+ ] = None,
276
+ include_comments: Annotated[
277
+ bool,
278
+ Field(
279
+ description=(
280
+ "If true, also bulk-fetch comments (one extra request total, "
281
+ "not one per bug)."
282
+ )
283
+ ),
284
+ ] = False,
285
+ ) -> dict:
286
+ """Fetch one or more bugs by ID in a single bulk request.
287
+
288
+ Inaccessible bugs are silently dropped by the proxy — this tool diffs
289
+ requested vs returned and reports them under 'inaccessible'. Remember:
290
+ request 'whiteboard' and 'keywords' explicitly in include_fields if you need
291
+ them.
292
+ """
293
+ if not ids:
294
+ return {"count": 0, "bugs": [], "inaccessible": []}
295
+ include = include_fields or (
296
+ "id,summary,status,resolution,product,component,priority,"
297
+ "severity,keywords,whiteboard,assigned_to,creator,"
298
+ "creation_time,last_change_time,blocks,depends_on,see_also,"
299
+ "cf_crash_signature,url,version,op_sys,platform"
300
+ )
301
+ result = (await ctx.client.bugs.get(ids, include_fields=include.split(","))).data
302
+ bugs = result.get("bugs", [])
303
+ returned = {b["id"] for b in bugs}
304
+ inaccessible = [i for i in ids if i not in returned]
305
+
306
+ payload = {"count": len(bugs), "bugs": bugs, "inaccessible": inaccessible}
307
+
308
+ if include_comments and bugs:
309
+ # Comments for all the bugs come back in one extra round trip total.
310
+ try:
311
+ cres = (await ctx.client.comments.get(bug_ids=[b["id"] for b in bugs])).data
312
+ comments_by_bug = {
313
+ int(bid): data["comments"] for bid, data in cres.get("bugs", {}).items()
314
+ }
315
+ for b in bugs:
316
+ b["comments"] = comments_by_bug.get(b["id"], [])
317
+ except BugzillaError as e:
318
+ payload["comments_error"] = {"code": e.code, "message": e.message}
319
+ except Exception as e:
320
+ payload["comments_error"] = {"message": f"{type(e).__name__}: {e}"}
321
+
322
+ return payload
323
+
324
+
325
+ @tool
326
+ @_bugzilla_errors
327
+ async def get_bug_comments(
328
+ ctx: BugzillaContext,
329
+ bug_id: Annotated[int, Field(description="Bug ID.")],
330
+ start: Annotated[
331
+ int,
332
+ Field(
333
+ ge=0,
334
+ description=(
335
+ "The number of the first comment to return, as Bugzilla numbers "
336
+ "them. Comment 0 is the description."
337
+ ),
338
+ ),
339
+ ] = 0,
340
+ limit: Annotated[
341
+ int | None,
342
+ Field(
343
+ ge=1,
344
+ description=(
345
+ "The maximum number of comments to return. To get all of them, do "
346
+ "not give it. Read a long thread in pages, so that each result stays "
347
+ "small."
348
+ ),
349
+ ),
350
+ ] = None,
351
+ ) -> dict:
352
+ """Fetch the comments of a single bug, all of them or one page.
353
+
354
+ `total` is the number of comments. `next_start` is the `start` of the next page,
355
+ and null on the last page.
356
+ """
357
+ result = (await ctx.client.comments.get(bug_ids=[bug_id])).data
358
+ comments = result.get("bugs", {}).get(str(bug_id), {}).get("comments", [])
359
+ later = [c for c in comments if c.get("count", 0) >= start]
360
+ page = later if limit is None else later[:limit]
361
+ more = len(page) < len(later)
362
+ return {
363
+ "bug_id": bug_id,
364
+ "total": len(comments),
365
+ "start": start,
366
+ "next_start": page[-1]["count"] + 1 if more else None,
367
+ "count": len(page),
368
+ "comments": page,
369
+ }
370
+
371
+
372
+ @tool
373
+ @_bugzilla_errors
374
+ async def get_bug_history(
375
+ ctx: BugzillaContext,
376
+ bug_id: Annotated[int, Field(description="Bug ID.")],
377
+ new_since: Annotated[
378
+ str | None,
379
+ Field(description="Only changes after this time (`2026-10-13T18:01:21Z`)."),
380
+ ] = None,
381
+ ) -> dict:
382
+ """Who changed which fields of a bug, and when.
383
+
384
+ Each entry has `when`, `who` and `changes`. Each change has `field_name`, `added`
385
+ and `removed`.
386
+ """
387
+ params = {"new_since": new_since} if new_since else {}
388
+ result = await ctx.client.request("GET", f"bug/{bug_id}/history", params=params)
389
+ history = (result.get("bugs") or [{}])[0].get("history") or []
390
+ return {"bug_id": bug_id, "count": len(history), "history": history}
391
+
392
+
393
+ @tool
394
+ @_bugzilla_errors
395
+ async def get_bug_attachments(
396
+ ctx: BugzillaContext,
397
+ bug_id: Annotated[int, Field(description="Bug ID.")],
398
+ include_data: Annotated[
399
+ bool,
400
+ Field(
401
+ description=(
402
+ "If true, inline base64 content for the textual attachments "
403
+ "only (text/*, JSON, XML, JavaScript, SVG) under 256KiB. Images "
404
+ "and PDFs are never inlined; use download_attachment for those."
405
+ )
406
+ ),
407
+ ] = False,
408
+ ) -> dict:
409
+ """Fetch attachments for a bug.
410
+
411
+ By default returns metadata only (cheap, safe for large binaries). Set
412
+ include_data=true to also inline the content, base64-encoded in each
413
+ attachment's 'data' field, for the textual types only: text/*, JSON, XML,
414
+ JavaScript, and SVG, under 256KiB, for the first 10 that qualify.
415
+
416
+ Anything else keeps its metadata and gains a 'data_omitted' note saying why.
417
+ Images and PDFs are among them on purpose: a tool result is text, so a
418
+ base64 image is a long string rather than something Claude can see. Use
419
+ download_attachment and read the file for those. An attachment the proxy
420
+ refuses gets a 'data_error' and does not take the rest of the response with
421
+ it.
422
+ """
423
+ result = (await ctx.client.attachments.get(bug_ids=[bug_id])).data
424
+ atts = result.get("bugs", {}).get(str(bug_id), [])
425
+ payload = {"bug_id": bug_id, "count": len(atts), "attachments": atts}
426
+ if not include_data:
427
+ return payload
428
+
429
+ # The list endpoint is all-or-nothing on `data`, so asking it for content
430
+ # would pull a screencast over the wire before we could drop it. Fetching the
431
+ # inlineable attachments one at a time never moves the bytes this is here to
432
+ # avoid, at the cost of one request each.
433
+ inlined = 0
434
+ omitted = 0
435
+ errors = 0
436
+ for att in atts:
437
+ allowed, effective = attachment_type_allowed(att)
438
+ size = att.get("size")
439
+ if not allowed:
440
+ note = f"{effective or 'unrecognized type'} is not readable by Claude"
441
+ elif not _inlineable(effective):
442
+ note = (
443
+ f"{effective} is binary, and a tool result is text, so inlining it "
444
+ "would cost the whole file in tokens without producing an image. "
445
+ "Use download_attachment and read the file."
446
+ )
447
+ elif isinstance(size, int) and size > MAX_INLINE_BYTES:
448
+ note = (
449
+ f"{size} bytes is over the {MAX_INLINE_BYTES}-byte inline limit. "
450
+ "Use download_attachment, then Grep the file for what you need."
451
+ )
452
+ elif inlined >= MAX_INLINE_ATTACHMENTS:
453
+ note = (
454
+ f"only the first {MAX_INLINE_ATTACHMENTS} attachments are inlined "
455
+ "per call. Use download_attachment for this one."
456
+ )
457
+ else:
458
+ try:
459
+ one = (
460
+ await ctx.client.attachments.get(
461
+ attachment_ids=[att["id"]], include_data=True
462
+ )
463
+ ).data
464
+ except Exception as e:
465
+ att["data_error"] = _to_tool_error(e).payload
466
+ errors += 1
467
+ continue
468
+ fetched = one.get("attachments", {}).get(str(att["id"]))
469
+ if fetched is None:
470
+ att["data_error"] = {"error": "attachment_not_returned"}
471
+ errors += 1
472
+ continue
473
+ att["data"] = fetched.get("data")
474
+ inlined += 1
475
+ continue
476
+ att["data_omitted"] = note
477
+ omitted += 1
478
+
479
+ payload["inlined_count"] = inlined
480
+ payload["omitted_count"] = omitted
481
+ payload["error_count"] = errors
482
+ return payload
483
+
484
+
485
+ @tool
486
+ @_bugzilla_errors
487
+ async def download_attachment(
488
+ ctx: BugzillaContext,
489
+ attachment_id: Annotated[
490
+ int, Field(description="Attachment ID (discover via get_bug_attachments).")
491
+ ],
492
+ dest_path: Annotated[
493
+ str,
494
+ Field(
495
+ description=(
496
+ "Local filesystem path to write the decoded attachment to. "
497
+ "Parent directory must already exist. Overwrites if present."
498
+ )
499
+ ),
500
+ ],
501
+ ) -> dict:
502
+ """Fetch a Bugzilla attachment by ID and write its decoded content to a file.
503
+
504
+ The inverse of add_attachment: it handles the base64 decode server-side so
505
+ the agent never has to round-trip the blob through its own context. Use
506
+ get_bug_attachments first to discover attachment IDs. Returns the written
507
+ path, size, and content_type.
508
+
509
+ Only types Claude can read are downloaded: text/*, png/jpeg/gif/webp/svg
510
+ images, PDF, and JSON/XML/JavaScript. Video, audio, and archives fail with
511
+ 'attachment_type_not_allowed' — a permanent answer, not a retryable one.
512
+ """
513
+ # Metadata first, so a refused attachment's bytes never leave Bugzilla. One
514
+ # extra round trip on the happy path buys that.
515
+ meta = (await ctx.client.attachments.get(attachment_ids=[attachment_id])).data
516
+
517
+ att = meta.get("attachments", {}).get(str(attachment_id))
518
+ if att is None:
519
+ raise ToolError(
520
+ f"attachment {attachment_id} not found",
521
+ payload={"error": "attachment_not_found", "attachment_id": attachment_id},
522
+ )
523
+
524
+ allowed, effective = attachment_type_allowed(att)
525
+ if not allowed:
526
+ raise _type_not_allowed_error(attachment_id, att, effective)
527
+
528
+ full = (
529
+ await ctx.client.attachments.get(
530
+ attachment_ids=[attachment_id], include_data=True
531
+ )
532
+ ).data
533
+ data = full.get("attachments", {}).get(str(attachment_id), {}).get("data")
534
+ if data is None:
535
+ raise ToolError(
536
+ f"attachment {attachment_id} came back without data",
537
+ payload={"error": "attachment_no_data", "attachment_id": attachment_id},
538
+ )
539
+
540
+ raw = base64.b64decode(data)
541
+ with open(dest_path, "wb") as fp:
542
+ fp.write(raw)
543
+
544
+ return {
545
+ "attachment_id": attachment_id,
546
+ "dest_path": dest_path,
547
+ "size_bytes": len(raw),
548
+ "file_name": att.get("file_name"),
549
+ "content_type": att.get("content_type"),
550
+ }
551
+
552
+
553
+ TOOLS = tools_in(__name__)