Skip to main content
Glama

Server Configuration

Describes the environment variables required to run the server.

NameRequiredDescriptionDefault
KILN_AUTH_KEYNoThe secret key used for authentication if enabled.
KILN_MMF_API_KEYNoMyMiniFactory API key for model searching and downloading.
KILN_SLICER_PATHNoExplicit path to the PrusaSlicer or OrcaSlicer binary if not in PATH.
KILN_AUTH_ENABLEDNoEnable optional API key authentication (0 or 1).
KILN_PRINTER_HOSTNoYour printer's IP or hostname (e.g., http://192.168.1.100).
KILN_PRINTER_TYPENoThe backend type for the printer.
KILN_MESHY_API_KEYNoMeshy API key for cloud text-to-3D generation.
KILN_BAMBU_TLS_MODENoTLS security mode for Bambu printers.pin
KILN_ENCRYPTION_KEYNoKey for G-code encryption at rest (Enterprise feature).
KILN_GEMINI_API_KEYNoAPI key for Gemini Deep Think to enable AI model generation.
KILN_CULTS3D_API_KEYNoCults3D API key for model searching.
KILN_PRINTER_API_KEYNoThe API key for the printer (required for OctoPrint, Moonraker, or Prusa Link).
KILN_TRIPO3D_API_KEYNoTripo3D API key for cloud text-to-3D generation.
KILN_CULTS3D_USERNAMENoCults3D username for model searching.
KILN_STABILITY_API_KEYNoStability AI API key for 3D generation.
KILN_THINGIVERSE_TOKENNoThingiverse API token (deprecated).
KILN_CRAFTCLOUD_API_KEYNoOptional API key to associate orders with a Craftcloud account.
KILN_FULFILLMENT_PROVIDERNoExternal manufacturing service provider (e.g., craftcloud).craftcloud

Instructions

Guidance the server publishes about itself, which clients place ahead of the tool catalog so the model reads it before choosing anything.

This server publishes no instructions, or was last inspected before Glama recorded them.

Capabilities

Features and capabilities supported by this server

Protocol revision2025-11-25

CapabilityDetails
tools
{
  "listChanged": false
}
prompts
{
  "listChanged": false
}
resources
{
  "subscribe": false,
  "listChanged": false
}

Tools

Functions exposed to the LLM to take actions

NameDescription
printer_statusA

Get printer state, temperatures, job progress, and capabilities.

Returns a JSON object with:
- ``printer``: connection status, operational state, tool/bed temperatures
- ``job``: current file name, completion percentage, elapsed and remaining time
- ``capabilities``: what this printer backend supports (``full`` only)

Use this as the first call to understand what the printer is doing.

Args:
    printer_name: Target printer.  Omit for the default printer.
    detail: ``"full"`` (default) for everything, or ``"lite"`` for
        frequent polling during a print — same field names, but
        ``capabilities`` is omitted and ``printer`` is trimmed to the
        readings that actually move.  Both levels carry every warning.

``detail`` exists so polling and inspection share ONE vocabulary.  The
retired ``print_status_lite`` returned the same numbers under different
names (``completion_pct``, ``hotend_temp``), which is why clients grew
defensive key-alias lists to read either shape.
monitor_printA

One-shot print status report (human-readable text: progress, temps, speed, cost, ETA).

Use for quick status checks. Returns a fixed-format text report with
progress, temps, speed, errors, cost estimate, camera snapshot, and
health commentary. For structured data + AI vision inspection, use
``monitor_print_vision``. For persistent background monitoring, use
``watch_print``.

This is the text report from the computer the printer is attached
to.  When Kiln's hosted connector (api.kiln3d.com) is also connected,
``monitor_printer`` there is the door for the inline live monitor and
camera; call that one to show the person a live panel.  The report's
closing ``Live monitor:`` line says whether a panel came with THIS
result or where the live monitor is instead — repeat it as written.

:param printer_name: Target printer name.  Omit for the default printer.
:param include_snapshot: Whether to capture and save a camera snapshot.
:param brief_id: Optional saved-goal id from ``design_session``.  When
    the brief resolves, the report appends a single ``Goal:`` line
    with the design's duty and environment — so the agent watching
    a print can answer "is this the right design for the goal?"
    without a separate lookup.  Best-effort: a missing kiln-pro
    install or an unresolvable brief silently skips the line.
:param show_panel: Open the inline live monitor panel again even
    though one opened by an earlier call is still live above.  Pass
    only when the person asks to see the panel again; the report
    itself is unchanged.  Read by the inline monitor's result hook
    (``kiln.local_monitor``), not here.

INLINE LIVE MONITOR: in apps that draw MCP Apps panels, this tool's result also carries Kiln's inline print monitor — a live panel with progress, temperatures, and the camera while a print runs. The result's own 'Live monitor:' line says whether that panel is open here, attached but unconfirmed, or not available in this app (then it names the web monitor instead); repeat what that line says and never tell the person a panel is open on the strength of this description. The panel polls the printer itself once open, so do not call this tool again to refresh it: later checks go through printer_status or first_layer_status, and a repeat while the panel is live returns the text report with a one-line card, not a second panel. Pass show_panel=True only when the person asks to see the panel again. Free with a Kiln sign-in; the text report below is always complete on its own.

printer_filesA

List all G-code files available on the printer.

Handles FTPS directory listing (Bambu), REST file API
(OctoPrint/Moonraker) automatically.

Returns a JSON array of file objects, each containing:
- ``name``: file name
- ``path``: full path on the printer
- ``size_bytes``: file size (may be null)
- ``date``: upload timestamp as Unix epoch (may be null)

When G-code metadata is available, files may also include:
- ``material``, ``estimated_time_seconds``, ``tool_temp``,
  ``bed_temp``, ``slicer``, ``layer_height``, ``filament_used_mm``

Use this to discover which files are ready to print.  Pass a file's
``name`` or ``path`` to ``start_print`` to begin printing it.
For detailed metadata on a specific file, use ``analyze_print_file()``.
upload_fileA

Upload a local G-code file to the printer.

Handles FTPS (Bambu), REST multipart upload (OctoPrint/Moonraker), and
serial file transfer automatically.

Args:
    file_path: Absolute path to the print file on the local filesystem.
        The file must exist and be readable.  Accepted extensions follow
        the TARGET PRINTER, not one fixed list — ``printer_status()``
        reports them per machine, and a Bambu declares ``.3mf`` FIRST
        because that is the only thing it will start a print from.
        Bare ``.gcode`` / ``.gco`` / ``.g`` is right for OctoPrint,
        Moonraker, PrusaLink and Duet; on a Bambu it has no start block
        and is refused by the homing gate below.

        When ``slice_model`` produced the file, upload the path it names
        in ``recommended_upload_path`` and do not choose between its
        outputs by hand — it already knows the printer.  (This docstring
        used to say the extension had to be ``.gcode``, ``.gco`` or
        ``.g``, which is narrower than this function's own behaviour and
        sent at least one caller to the one file its printer could not
        print.)
    printer_name: Which printer to upload to.  Omit to upload to the
        default printer, which is what this did before it could be
        aimed.  The G-code dialect scan and the bed-fit gate follow the
        named machine too, so the bytes are checked against the bed
        they are actually going to.

After a successful upload the file will appear in ``printer_files()`` and
can be started with ``start_print()``.
upload_file_confirmA

Confirm and execute a pending file upload.

When ``KILN_CONFIRM_UPLOAD`` is enabled, ``upload_file()`` returns a
confirmation token instead of uploading immediately.  Pass that token
here to proceed with the upload.

Args:
    token: The confirmation token returned by ``upload_file()``.
analyze_print_fileA

Analyze a G-code file on the printer and extract its metadata.

Reads the file header to extract slicer-embedded metadata such as
material type, estimated print time, temperatures, layer height,
and filament usage.  This is especially useful when filenames are
meaningless (e.g. ``test5112.gcode``) and the agent needs to
understand what a file will print.

.. note::
    For multi-object .gcode.3mf files, also consider using
    ``list_plate_objects()`` to see individual objects on the plate.

Args:
    filename: Name or path of the file as shown by ``printer_files()``.

Returns a JSON object with:
- ``filename``: the file name
- ``metadata``: extracted metadata (material, time, temps, slicer, etc.)
- ``has_metadata``: whether any metadata was found
delete_fileA

Delete a G-code file from the printer's storage.

Args:
    file_path: Path of the file as shown by ``printer_files()``.

This is irreversible -- the file cannot be recovered once deleted.
start_printA

Start printing a file already uploaded to the printer (file must exist on printer).

Use ``upload_file`` first, or use ``slice_and_print`` / ``run_quick_print``
to slice + upload + print in one step. Automatically runs pre-flight safety
checks before starting.  If any check fails the print is blocked and the
check results are returned so the agent can diagnose and fix the issue.

Args:
    file_name: Name or path of the file as shown by ``printer_files()``.
    use_ams: AMS filament feeding mode (Bambu only).  Tri-state:

        - ``"auto"`` (default): auto-detect AMS by probing the printer.
          If an AMS is connected with loaded trays, enables AMS
          automatically and selects the first loaded slot if no
          ``ams_mapping`` is provided.  Falls back to external spool
          if no AMS is detected.
        - ``"true"`` / ``True``: Force AMS on.  Use when you know AMS
          is connected.
        - ``"false"`` / ``False``: Force AMS off.  Use external spool.

    ams_mapping: The tray each extruder feeds from (Bambu only), by
        the printer's own tray id: ``unit * 4 + slot`` on a chained
        unit (unit B's first slot is 4), the unit id itself on an AMS
        HT (HT-A is 128).  ``ams_status()`` lists each tray's
        ``tray_id`` and its Studio name (``B1``, ``HT-A``).  Defaults to
        ``[0]`` when AMS feeding is on and ``[]`` (external spool) when
        it is off.  Use ``-1`` for unused positions.
    timelapse: Record a timelapse video (Bambu only).  Default ``False``.
    bed_leveling: Run automatic bed leveling before print (Bambu only).
        Default ``True``.  Set ``False`` to skip for reprints (~2 min saved).
    flow_cali: Run flow calibration (Bambu only).  Default ``True``.
    vibration_cali: Run vibration/resonance calibration (Bambu only).
        Default ``True``.
    layer_inspect: Enable first-layer lidar inspection pause (Bambu only).
        Default ``False``.
    nozzle_clog_detect: Enable nozzle clumping / blob detection by
        probing (Bambu only).  Default ``True``.  Set ``False`` to
        bypass HMS 0300-8014 errors on models that trigger false
        positives (thin first-layer geometry, certain grip/case models).
        Disables the A1/A1-mini eddy-current clump probe (first after
        the layer-3 walls, then once per ~8 g of filament; A1 series only).
        Kiln never turns the probe ON: with the default nothing is sent
        and the printer's own screen switch governs -- ``printer_status``
        and ``preflight_check`` read that switch and, when it is on,
        repeat the printer's own warning that the probe leaks onto the
        model unless the slice carries a purge tower.  ``False`` is not
        a per-print override: measured 2026-09-15, it turns the printer's
        own switch OFF -- so Kiln reads the switch first and, when it
        found it ON, turns it back on when the print ends (or at once if
        the print never starts).  Never forced on for a printer whose
        switch was off or could not be read.
    restore_nozzle_detection: With ``nozzle_clog_detect=False``, put the
        printer's own switch back on when the print ends (default
        ``True``).  ``False`` leaves it off on purpose, for a batch that
        wants the probe off across several prints.
    bed_type: Bed surface type (Bambu only).  Default ``"auto"``.
    plate_number: Plate index in multi-plate 3MF files (Bambu only).
        Default ``1``.
    resume_from_paused: When ``True``, the pre-flight ``printer_idle``
        check accepts ``paused`` as a valid state.  Use this when
        starting a resume-mode 3MF (mid-print decoration swap):
        the printer is paused, you upload the resume 3MF, and then
        ``start_print`` it with this flag.  The file is treated as
        a fresh print from the firmware's POV — the resume gcode
        carries its own preamble (heat → safety lift → home X/Y →
        travel → descend to resume Z).  Default ``False``.

        Auto-detected for files whose name contains ``_resume_``
        (case-insensitive) or starts with ``transformed_resume`` /
        ``original_resume`` — these are the conventional names
        produced by ``decorate_during_print`` and ``revert_mid_print``.
    skip_preheat_reassert: When the file is a resume-mode 3MF, the
        tool re-asserts the printer's pre-start hotend + bed targets
        immediately after the MQTT start command, because Bambu's
        resume 3MFs strip the M140/M190 pre-heat block (the original
        print already heated the bed) and the firmware's
        cool-on-new-job policy will otherwise drop the bed to 0
        before the resume preamble executes.  Set ``True`` to
        disable this safety net.  Default ``False``.
    printer_name: Which printer to start the job on.  Omit to start
        on the default printer, which is what this did before it
        could be aimed.  Everything the start decides — the pre-flight
        verdict, the preview token's printer, the emergency latch,
        the nozzle-wear consult, the watchdog that will be watching —
        follows the named machine, so upload the file to that same
        printer first (``upload_file(..., printer_name=...)``).
        Listed last so existing positional calls keep their meaning.

Branch on ``print_start`` — one field, three values:

- ``"started"``: the printer, asked after the command, is printing.
- ``"accepted"``: the command was sent and not refused, and the machine
  has not confirmed it is running.  Normal during the start-up transient
  (homing, AMS load, calibration).  Call ``printer_status()`` to watch.
- ``"failed"``: the printer, asked after the command, is idle or errored
  — it did not take the job.

``success`` is ``False`` only for ``"failed"``.
cancel_printA

Cancel the currently running print job.

Sends cancel via MQTT (Bambu) or REST API (OctoPrint/Moonraker)
automatically.

The printer must have an active job (printing or paused).

:param printer_name: Which printer to stop.  Omit to stop the default
    printer, which is what this did before it could be aimed.  Owning
    more than one printer is free at every tier (only running them at
    the same time is a fleet feature), so the second machine is a
    supported setup on a free licence — and control of a hot machine
    is never something a licence takes away.
:param preserve_temperatures: When ``True``, re-asserts the pre-cancel
    hotend + bed (+ chamber, if expected_chamber_target is provided)
    targets immediately after the cancel command, so the printer
    does NOT cool down.  Use this when you plan to swap in a
    different file (e.g., a mid-print decoration resume 3MF) and need
    bed adhesion + nozzle temperature held across the cancel-then-
    start-print transition.  Without this, Bambu firmware defaults
    to cooling on cancel, which can warp the existing part or kill
    bed adhesion on a partial print you're about to resume.
    Default ``False`` preserves legacy behaviour (cool down to idle).

:param expected_tool_target: Optional caller-supplied tool target to
    preserve.  When provided AND ``preserve_temperatures=True``,
    this overrides the introspected ``state.tool_temp_target``.
    Useful when the printer was paused and the firmware has already
    cleared the target (so a fresh state read returns 0) but the
    caller knows what the pre-pause target was.
:param expected_bed_target: Same as above, for the bed.  This is
    the primary fix for Bambu A1 long-pause-then-cancel: the bed
    target sometimes reads back as 0 from MQTT cache after a long
    pause, and without an explicit override the cancel preservation
    skips the bed restore.
:param expected_chamber_target: Optional chamber target (M141) to
    re-assert via raw G-code.  Not all printers expose chamber
    heating via the adapter API, so this is sent as a raw M141
    command best-effort.  Pass ``None`` to skip chamber preservation.

WARNING: Cancellation is irreversible -- the print cannot be resumed
from where it left off UNLESS a resume-mode 3MF has been pre-staged
(see ``decorate_during_print`` and ``revert_mid_print``).
calibrate_directA

Send calibration commands directly to the printer adapter.

For a full guided calibration pipeline (home + bed level + intelligence
guidance), use ``run_calibrate`` instead. This tool sends raw calibration commands via
MQTT (Bambu) or G-code (OctoPrint/Moonraker) automatically. The printer
must be idle — calibration cannot run during a print.

Available options (printer-specific -- not all printers support all):
- ``"bed_leveling"``: Auto bed mesh probing and Z offset calibration
- ``"vibration"``: Input shaper / vibration compensation tuning
- ``"flow"``: Extrusion flow / first-layer inspection calibration
- ``"all"``: Run all available calibration routines

When no options specified, defaults to bed leveling only.

Bambu printers support all options.  OctoPrint/Moonraker support
``bed_leveling`` and ``vibration``.  Other printers may not support
remote calibration.
emergency_stopA

Trigger an emergency stop on one or all printers.

Sends the strongest stop each printer accepts: Moonraker's emergency-stop
endpoint; ``M112`` on OctoPrint, Duet and USB-serial printers; a cancel
plus ``M112`` on Elegoo; a job cancel on Prusa Link, which has no raw
G-code endpoint; and on Bambu the print-stop command, a heater cut and
``M112``.  Creality printers use whichever of these their connection is.
Unlike ``cancel_print``, this is not meant to allow a graceful cooldown.

Only the Bambu stop is read back: its ``success`` means the printer
reported the job ended.  On every other printer ``success`` means the
stop command was delivered, not that anything was observed.  ``success``
is False for any printer whose stop failed or could not be confirmed;
when stopping all printers, ``not_confirmed_stopped`` lists each one with
the reason.  Tell the user to stop those at the machine; calling this tool
again for them is safe.

Use only in genuine safety emergencies (thermal runaway, collision,
spaghetti failure threatening the hotend, etc.).

WARNING: After an emergency stop the printer typically requires a
power cycle or firmware restart before it can print again.

Args:
    printer_name: Specific printer to stop. If None, stops ALL printers.
    reason: Reason code (e.g. ``user_request``, ``thermal_runaway``).
    source: Trigger source label for audit context.
    note: Optional operator note.
emergency_statusA

Get the emergency stop latch status for one printer or the entire fleet.

Returns whether an emergency stop is active and whether the printer is
locked from printing operations.  When an e-stop is active, all print
commands are blocked until ``clear_emergency_stop()`` is called with an
acknowledgement note.

:param printer_name: Query a specific printer, or omit for all printers.
:param include_unlatched: When True, include printers that have no active
    latch.  Defaults to False (only active latches).

:returns: Latch state per printer: ``active`` (bool), ``reason``,
    ``source``, ``timestamp``, and whether critical interlocks prevent
    clearing.

See also: ``emergency_stop()``, ``clear_emergency_stop()``.
clear_printer_errorA

Clear a latched error on the PRINTER so it will accept prints again.

Different from ``clear_emergency_stop``, which releases Kiln's own safety
latch.  This one acknowledges an error the FIRMWARE is holding — the state
the machine itself reports — after which pre-flight checks pass again.

Reach for it when ``printer_status`` reports ``error`` and the printer's
own screen looks fine.  That combination is not a Kiln bug; the firmware
really is still reporting the fault, and on some machines dismissing the
on-screen message clears the notification without clearing the state.
Before this existed there was no way out of that from Kiln at all — only a
power cycle — so one bad print locked the machine out of every later one.

What it does NOT do is fix the cause.  A printer that halted for a real
fault will halt again the moment it retries, which is the honest outcome:
this reconciles Kiln with the machine, it does not overrule the machine.
Nothing is cleared while a print is running.

:param printer_name: Target printer.  Omit for the default printer.
:returns: Whether the acknowledgement was sent, plus the printer state
    read back afterwards so the caller can see whether it took.

See also: ``printer_status()``, ``preflight_check()``, ``emergency_stop()``.
clear_emergency_stopA

Acknowledge and clear a printer's emergency stop latch.

This is a safety-critical operation.  The latch may be blocked from
clearing if critical interlocks are still active (e.g. thermal sensor
failure).  Call ``emergency_status()`` first to check whether clearing
is possible.

:param printer_name: Printer whose latch to clear.
:param acknowledgement_note: Free-text note explaining why the e-stop is
    being cleared (required -- cannot be empty).
:param acknowledged_by: Identity of the person or system clearing the
    latch (default ``"operator"``).

:returns: Updated latch state, or an error if critical interlocks prevent
    clearing.

See also: ``emergency_status()``, ``emergency_stop()``.
force_print_oversizeA

Briefly override the pre-print impossibility gate for ONE printer.

Kiln refuses a print that physically cannot succeed on the target
printer — geometry that exceeds the build volume (the nozzle would
crash) or a material whose minimum nozzle temperature exceeds the
printer's hotend ceiling (it cannot melt the filament).  Those are
hard physical limits, not warnings, so a normal print call is blocked.
It also refuses a file sliced for one nozzle size when the printer's
own setting says another is fitted; this override covers that too.

This is the human's "I understand — print it anyway" escape hatch, e.g.
when you are deliberately sending the file to a *different* printer than
the one connected.  It grants a short, per-printer override that lets the
NEXT otherwise-blocked print through, then expires.

Safety: classified ``confirm`` (see ``data/tool_safety.json``).  An
autonomous agent cannot self-approve it — the confirmation layer keeps a
human in the loop, exactly like ``emergency_stop``.  Designing and slicing
any size is never blocked; only the final print-to-hardware step is.

:param printer_id: Printer model to override (e.g. ``"bambu_a1"``).
    Empty resolves to the active printer.
:param ttl_minutes: Minutes the override stays active (default 5, max 60).
:returns: Grant confirmation, or a confirmation-required challenge.
emergency_trip_inputA

Trip emergency stop from an external hardware bridge.

Designed for physical input devices (ESP32, PLC, wired push buttons)
that call this endpoint over HTTP to trigger a software e-stop.  This
is different from ``emergency_stop()`` which is for agent/software-
initiated stops.

If ``KILN_ESTOP_INPUT_TOKEN`` is configured, the request must include
a matching ``token`` or it will be rejected.

:param printer_name: Printer to emergency-stop.
:param input_name: Label for the input source (default
    ``"external_button"``).
:param token: Authorization token -- required when
    ``KILN_ESTOP_INPUT_TOKEN`` is set.
:param note: Optional free-text note describing the trigger reason.

See also: ``emergency_stop()``, ``emergency_status()``.
pause_printA

Pause the currently running print job.

What happens next is decided by the printer's own firmware, not by
Kiln, and it differs a lot between machines.  Some lift the nozzle
and park the head; others leave it resting on the part.  Many lower
or switch off the nozzle heater while paused, and some switch the
heaters and motors off after a timeout, after which the print may
not be able to resume.  Do not tell the person the head will park or
that temperatures will hold; check ``printer_status`` instead.

One measured case:

  - Bambu A1 / A1 mini: the firmware sets a ~90°C hotend standby
    target IMMEDIATELY on pause, regardless of slicer settings (the
    bed target survives).  Measured 2026-08-14 on a real A1: the
    target moved 220°C -> 90°C in the same telemetry sample as the
    pause, and the nozzle fell to 139°C within 114 seconds — about
    0.7°C per second.  This docstring previously said the drop came
    "3-5 minutes into a pause", and the keep-alive was built to wait
    two minutes before its first assert on the strength of that; the
    measurement says the damage starts at once.  A resume onto a
    cooled nozzle can't extrude until it re-heats — and bed adhesion
    can fail in the meantime.

To fight this, ``pause_print`` spawns a best-effort daemon thread
that re-asserts the pre-pause hotend + bed targets immediately, and
then every 2 minutes until the printer leaves the PAUSED state
(resume, cancel, error, or manual button press).  This is enabled by
default.  The immediate assert is the part that matters on an A1:
without it, a pause shorter than the interval got no protection at
all, which is most pauses a person actually takes.  It can only help
on a printer Kiln can set temperatures on: Prusa Link offers no way
to, so on a Prusa the keep-alive does nothing.

Args:
    keep_temps: When ``True`` (default), capture the pre-pause tool
        and bed targets and re-assert them every ~2 minutes via a
        background daemon thread.  Set ``False`` to skip the
        keep-alive (legacy behaviour — printer may cool during long
        pauses).  The keep-alive thread is idempotent: repeat
        pause/resume cycles do not compound threads.
    printer_name: Which printer to pause.  Omit for the default
        printer.  Each paused machine gets its own keep-alive thread,
        re-asserting its own targets on its own adapter.

Use ``resume_print()`` to continue from where the print left off — pass
the same ``printer_name`` you paused with.  The keep-alive thread is
automatically stopped on that printer's resume or cancel.
skip_print_objectsA

Abandon one or more failed objects on a multi-object plate, mid-print.

When one part on a full plate fails — spaghetti, a knocked-loose object, a
detached corner — this tells the printer to stop printing just those
objects and finish the rest of the plate.  One bad part no longer scraps
the whole run.  A Kiln Pro feature.

The identifier is backend-specific — pass it as a string, Kiln routes it:

* **Bambu** — the ``label_id`` from ``list_plate_objects`` (e.g. ``"757"``).
* **Klipper / Moonraker / Creality** — the object NAME the slicer labelled
  (e.g. ``"Part1"``); the file must have been sliced with object labelling.
* **OctoPrint** — the zero-based ``M486`` object index (needs firmware
  M486 support).

Discover Bambu ids first::

    list_plate_objects("my_plate.gcode.3mf")   # -> objects[].label_id

Printer support (honest): Bambu and any Klipper/Moonraker printer can skip
(Voron, RatRig, Qidi, and Klipper-based Creality and Elegoo Neptune /
OrangeStorm); Marlin printers via OctoPrint or direct USB can if the
firmware speaks M486.  Prusa via Prusa Link can't be skipped remotely — an
API limitation, not the printer (it can cancel objects from its own
screen).  The Elegoo SDCP protocol (e.g. Centauri Carbon) has no skip
command.  A Klipper printer on a non-Klipper connection just needs
reconnecting as Moonraker.

AGENT DISPLAY CONTRACT: skipping is IRREVERSIBLE for the objects named —
confirm the exact objects with the user before calling, and only while a
multi-object plate is actively printing.  Skips are cumulative: an object
already skipped stays skipped.

Args:
    object_ids: Backend-specific object identifiers to abandon (see above).
    plate_number: Which plate the ids came from (1-based, default 1).
        Recorded for context; the ids are what the printer acts on.
    printer_name: Which printer is printing the plate.  Omit for the
        default printer.

Returns:
    Dict with the skipped objects and a confirmation message, or an error
    dict if no print is active or the printer can't skip objects.
resume_printA

Resume a paused print job.

The printer must currently be in a paused state.  Resuming will return
the nozzle to its previous position and continue extruding.

Kiln checks afterwards that the resume actually took, so a printer that
silently ignored the command reports a failure instead of a cheerful
"Print resumed."

A print paused at a planned hardware stop (a pause written into the file
so a nut, a magnet or a bearing can go in) is refused with
``code: "HARDWARE_NOT_CONFIRMED"`` and a ``hardware`` block saying what
goes in.  Tell the person, wait for them to say every piece is in and
sits level with or below the top of the print, then resume with
``hardware_confirmed=true``.  Never pass it on your own judgement.

Args:
    force: Send the resume even when Kiln believes the printer is not
        paused.  Use this when the printer's own screen disagrees with
        what Kiln reports — a printer can report ``RUNNING`` with
        perfectly fresh telemetry while standing still, and without this
        the wrong state word would leave you unable to recover the print.
    printer_name: Which printer to resume.  Omit for the default
        printer.  Pass the same name you paused with.
    hardware_confirmed: The person has said every piece of hardware for
        this stop is in and sits level with or below the top of the
        print.  Only on their word.
set_temperatureA

Set the target temperature for the hotend (tool) and/or heated bed.

Args:
    tool_temp: Target hotend temperature in Celsius.  Pass ``0`` to turn
        the heater off.  Omit or pass ``null`` to leave unchanged.
    bed_temp: Target bed temperature in Celsius.  Pass ``0`` to turn
        the heater off.  Omit or pass ``null`` to leave unchanged.
    printer_name: Which printer to heat.  Omit for the default printer,
        which is what this did before it could be aimed — so asking to
        preheat a second machine heated the default one instead.  The
        safety ceiling follows the named machine: a printer with no
        declared model is held to the generic floor (the least capable
        machine Kiln describes) rather than to the default printer's,
        which may be the more permissive of the two.  When that floor
        refuses a temperature, the fix is a model, not a number: set
        ``printer_model`` to a printer Kiln knows, or find the maker's
        limits and have the person confirm them (``add_safety_profile``).

At least one of ``tool_temp`` or ``bed_temp`` must be provided.

Common PLA temperatures: tool 200-210C, bed 60C.
Common PETG temperatures: tool 230-250C, bed 80-85C.
Common ABS temperatures: tool 240-260C, bed 100-110C.

Branch on ``outcome`` — one field, three values, the same shape
``start_print`` uses for ``print_start``:

- ``"confirmed"``: the printer, in a report AFTER the command, shows the
  effect. Reported per heater under ``tool`` and ``bed``.
- ``"accepted"``: the command was sent and not refused, and the printer
  has not shown the effect yet. Normal on a quiet printer. Read
  ``printer_status()`` before building on it.
- ``"failed"``: the printer's interface refused the command.

``accepted`` (the boolean) keeps its old meaning: sent, not refused. It
is never proof the printer acted. ``success`` is ``False`` only for
``"failed"``.
ams_statusA

Full AMS hardware dump — all trays, humidity, RFID (Bambu Lab only).

For just the currently-active material, use ``get_active_material``
instead. For Kiln's software material tracker, use ``get_material``.

Returns what's loaded in each AMS tray: filament type, color, remaining
percentage, RFID tag, temperature ranges, and humidity.

Each tray carries its unit's own ``slot`` (0-3), the printer's
``tray_id`` for it (``unit * 4 + slot`` on a chained unit, the unit id
itself on an AMS HT) and Studio's ``name`` (``A1``…``D4``, ``HT-A``);
each unit carries its ``name`` (``A``, ``HT-B``).  ``feeding`` is the
tray feeding the nozzle -- ``{tray_id, unit, slot, name, source}``, or
``None`` when nothing feeds -- and ``feeding_source`` says which field
of the printer's report it came from.  The raw ``tray_now`` is kept as
sent: ``"254"`` is the external spool,
``"255"`` no tray.  A1 / AMS Lite reports may keep ``tray_now`` at
``"255"`` while exposing loaded AMS trays and selected/target tray
fields such as ``tray_pre`` or ``tray_tar``.  The ``ams_exist_bits`` and
``tray_exist_bits`` fields are bitmasks showing which AMS units and
trays are physically present.

Use this to check filament levels before printing, verify the correct
material is loaded, or select the right ``ams_mapping`` for
``start_print()``.

This dump carries no fault line of its own.  To follow a print, poll
``printer_status(detail="lite")``: it reports the run state and every
fault code under ``faults``.  A fault the printer stops for on a
watched print also rides this and every other tool result as
``printer_fault`` while it stands.
cfs_statusA

Discover Creality CFS/CFS-C status through local Moonraker.

This is the Creality counterpart to ``ams_status()``, but the public
protocol is not equivalent to Bambu AMS. Creality documents CFS control
through Creality Print and printer UI; Kiln therefore performs read-only
Moonraker discovery (`/printer/objects/list`, candidate object queries,
and `/printer/gcode/help`) and reports any visible CFS slots/macros.

The response includes ``hardware_unverified=True`` and
``active_slot_control_supported=False`` until slot load/unload/mapping
commands are validated against real Creality hardware or official API docs.
set_speed_profileA

Set the print speed: a preset by name, or a percentage of the sliced speed.

One door for both ways a printer takes a speed.  Give exactly one of:

Args:
    profile: A preset — ``"silent"`` (50%), ``"standard"`` (100%),
        ``"sport"`` (124%) or ``"ludicrous"`` (166%).  Bambu Lab
        printers only; sport and ludicrous raise the nozzle
        temperature to keep up with the flow.
    percent: The speed as a percentage of the speed the file was
        sliced at — the feedrate override every FDM firmware has (100
        is the sliced speed; 10 to 300 is accepted).  A Bambu takes
        only its four presets, so the nearest one is set and the
        answer says which (``preset``, ``percent_actual``).
    printer_name: Which printer.  Omit for the default printer.

Nothing here judges whether a speed suits THIS printer or THIS layer:
Kiln's served ``set_speed_percent`` and ``set_speed_schedule`` do that
and hand the checked value here.  Use ``printer_status()`` to see the
current speed profile in ``printer.speed_profile``.

Branch on ``outcome`` — one field, three values, the same shape
``start_print`` uses for ``print_start``:

- ``"confirmed"``: the printer, in a report AFTER the command, shows the
  effect. For a Bambu, the reported speed level moved.
- ``"accepted"``: the command was sent and not refused, and the printer
  has not shown the effect yet. Normal on a quiet printer. Read
  ``printer_status()`` before building on it.
- ``"failed"``: the printer's interface refused the command.

``accepted`` (the boolean) keeps its old meaning: sent, not refused. It
is never proof the printer acted. ``success`` is ``False`` only for
``"failed"``.
run_speed_scheduleA

Run, report or stop a layer-based speed schedule on this computer.

A schedule is a list of ``{"from_layer", "to_layer", "speed_percent"}``
segments.  With ``action="run"`` it starts on the printer that is
printing now, replacing a schedule already running for that printer:
the printer is asked which layer it is on every few seconds and each
segment's speed is set once, as the print reaches it.  It stops on its
own when the print ends, when the printer is found running a different
print, or on ``action="stop"`` (the printer stays at the last speed set).
``action="status"`` reports what has been applied so far.

Only the schedule's shape is checked here.  Which speeds suit this
printer and which layers a speed is unsafe on is decided by Kiln's
served ``set_speed_schedule``, which hands the checked schedule here.

Args:
    schedule: The segments to run (``action="run"`` only).
    printer_name: Which printer.  Omit for the default printer.
    action: ``"run"`` (default), ``"status"`` or ``"stop"``.
get_speed_profileA

Get the current speed profile (Bambu Lab printers only).

Returns the active speed profile with:
- ``level``: numeric level 1–4
- ``name``: profile name — ``"silent"`` (50%), ``"standard"`` (100%),
  ``"sport"`` (124%), or ``"ludicrous"`` (166%)
- ``speed_magnitude``: actual speed multiplier percentage reported by the
  printer firmware

Use this to check the current speed before adjusting it with
``set_speed_profile()``.
set_printer_lightA

Control the printer's LED lights (Bambu Lab printers only).

Args:
    node: Which light to control — ``"chamber_light"`` (main
        illumination) or ``"work_light"`` (nozzle area).
        Defaults to ``"chamber_light"``.
    mode: Light mode — ``"on"``, ``"off"``, or ``"flashing"``.
        Required: a call that arrives without it is refused rather
        than turned on (the same rule as ``set_fan``'s ``percent``).

Use this to improve camera visibility, signal print completion
(flashing), or turn lights off for overnight prints.

Branch on ``outcome`` — one field, three values, the same shape
``start_print`` uses for ``print_start``:

- ``"confirmed"``: the printer, in a report AFTER the command, shows the
  effect. For a Bambu, the light report lists that node in that mode.
- ``"accepted"``: the command was sent and not refused, and the printer
  has not shown the effect yet. Normal on a quiet printer. Read
  ``printer_status()`` before building on it.
- ``"failed"``: the printer's interface refused the command.

``accepted`` (the boolean) keeps its old meaning: sent, not refused. It
is never proof the printer acted. ``success`` is ``False`` only for
``"failed"``.
set_fanA

Set the speed of a printer fan.

``percent`` has no default on purpose.  Measured 2026-09-18 on an A1:
a call meant to turn the fan OFF reached Kiln with no ``percent`` at
all (the caller's own argument name had been dropped before the
request arrived), the old default of 100 ran the fan flat out, and
the answer confirmed it.  A setpoint the caller did not send is
refused, never guessed.

Supported on Bambu Lab, OctoPrint, Moonraker/Klipper printers, and
Elegoo's Centauri Carbon (FDM). Prusa Link has no raw G-code endpoint, so
fan control isn't available there (a known limitation of Prusa Link
itself). An Elegoo machine with no part-cooling fan is refused.

Args:
    node: Which fan to set. ``"part"`` (part-cooling / model fan, the
        one that cools each layer) works on every supported printer.
        ``"aux"`` (auxiliary / big fan) and ``"chamber"`` (chamber /
        exhaust fan) are Bambu-only — generic Marlin/Klipper firmware has
        no standard auxiliary or chamber fan Kiln can address without
        knowing that machine's own G-code macros. Defaults to ``"part"``.
    percent: Fan speed 0-100. ``0`` turns the fan off, ``100`` is full
        speed. Required.

Use this to add cooling for bridges and overhangs (part fan), or — on
Bambu — pull heat with the auxiliary fan or run the chamber/exhaust fan
for materials like ABS/ASA. The Bambu chamber fan only exists on
enclosed models — X1 Carbon, X1E, P1S, P2S, H2S — not on open-frame
models (A1, A1 Mini, A2L, P1P), where a chamber command is a no-op. The
printer's own thermal management may override a manual fan speed during
a print.

Branch on ``outcome`` — one field, three values, the same shape
``start_print`` uses for ``print_start``:

- ``"confirmed"``: the printer, in a report AFTER the command, shows the
  effect. For a Bambu, that fan's reported level matches.
- ``"accepted"``: the command was sent and not refused, and the printer
  has not shown the effect yet. Normal on a quiet printer. Read
  ``printer_status()`` before building on it.
- ``"failed"``: the printer's interface refused the command.

``accepted`` (the boolean) keeps its old meaning: sent, not refused. It
is never proof the printer acted. ``success`` is ``False`` only for
``"failed"``.
wrap_gcode_as_3mfA

Wrap raw PrusaSlicer G-code in a Bambu-compatible 3MF (Bambu Lab only).

Bambu printers require the proprietary BambuStudio start/end sequences
(motor enable, AMS load, extrusion calibration) to function correctly.
This tool takes PrusaSlicer G-code output and packages it into a 3MF
that the printer will accept.

Args:
    gcode_path: Absolute path to a PrusaSlicer ``.gcode`` file on the
        local filesystem.  The file must have been sliced with
        ``--use-relative-e-distances`` and empty start/end G-code.
    hotend_temp: Hotend temperature in °C for the start sequence.
        Omitted, the temperature the G-code itself first heats to.
    bed_temp: Bed temperature in °C, likewise.
    filament_type: Filament type string — ``"PLA"``, ``"PETG"``,
        ``"ABS"``, etc.  Omitted, the type the slicer wrote into the
        G-code (every Kiln slice carries the material it was weighed
        as).  The response's ``filament_type`` is what the printer is
        told, in Bambu's own vocabulary.
    source_3mf_path: Optional path to a source 3MF to copy
        thumbnails and geometry from.
    num_filaments: Number of filaments (>1 for multi-color prints).
    filament_colors: List of hex color strings per filament
        (e.g. ``["#898989FF", "#161616FF"]``).
    filament_types: List of filament type strings per filament
        (e.g. ``["PLA", "PLA"]``).
    thumbnail_path: Optional path to a PNG image to embed as the
        3MF thumbnail (shown on the printer's display).
    stl_path: Optional path to the source STL file.  When provided,
        a thumbnail is auto-generated from the model geometry via
        OpenSCAD (512x512, shown on the Bambu printer screen).
    bed_type: The plate fitted: ``"textured_plate"``, ``"hot_plate"``
        (smooth PEI), ``"cool_plate"``, ``"eng_plate"`` or
        ``"supertack_plate"``.  Omitted, the textured plate.  The
        printer's start sequence trims the nozzle height for the plate
        it is told, so say it when the plate is not the textured one.

Returns a dict with ``output_path`` pointing to the generated 3MF.
Use ``upload_file()`` to send it to the printer, then ``start_print()``
to begin printing.

When ``filament_colors`` are given, the result says whether they are on
the printer, as ``colour_availability`` (absent when Kiln cannot see
what is loaded).  Relay its ``say`` as written and add nothing about
filament: never suggest buying filament unless the person asks for one
or says yes to the offer in ``say``.  On a yes, call
``find_closest_filaments`` with these colours and the print's material.
get_bed_meshA

Get the bed mesh / probe data (OctoPrint and Moonraker only).

Returns the probed bed leveling mesh including:
- ``probed_matrix``: 2D array of Z-offset measurements across the bed
- ``mesh_min`` / ``mesh_max``: bounding coordinates of the probed area
- ``variance``: overall variance of the mesh (lower = flatter bed)

Use this to diagnose first-layer adhesion issues.  High variance or
significant dips/peaks indicate a warped bed or loose leveling screws.

Not supported on Bambu Lab printers — Bambu handles bed leveling
internally and does not expose mesh data.
get_filament_statusA

Get the filament runout sensor status (OctoPrint and Moonraker only).

Returns sensor information including:
- ``detected``: whether filament is currently detected by the sensor
- ``sensor_enabled``: whether the runout sensor is active

Use this to verify filament is loaded before starting a print on
non-Bambu printers.

For Bambu Lab printers, use ``ams_status()`` instead — it provides
per-tray filament presence, type, color, and remaining percentage.
get_tool_positionA

Get the current nozzle / tool-head XYZ position (Moonraker and Serial).

Returns a dict with at least ``x``, ``y``, ``z`` coordinates in mm
relative to the printer's home position.  Some printers also report
``e`` (extruder position).

Use this for:
- Verifying the printer has been homed (coordinates are valid only
  after homing)
- Calibration sequences that need to know the current position
- Move planning when issuing manual jog commands

Not all adapters support this — returns an error if position data is
not available.
preflight_checkA

Run pre-print safety checks to verify the printer is ready.

Checks performed:
- Printer is connected and operational
- Printer is not currently printing
- No error flags are set
- Temperatures are within safe limits
- (Optional) Material loaded matches expected material
- (Optional) Local G-code file is valid and readable
- (Optional) Remote file exists on the printer
- Multi-material: what unit the printer carries (AMS, a Klipper MMU)
  and, with ``file_path``, whether the file's filaments are loaded.
  Advisory for a unit Kiln drives (the print gate decides at start);
  a FAILURE when a multi-filament file needs more colours than a
  unit Kiln does not drive has loaded — that print comes out wrong
  and nothing downstream stops it.  Absent for a single-feed printer;
  a read that failed is reported as such, never as "no unit".

Args:
    file_path: Optional path to a local G-code file to validate before
        upload.  If omitted, only printer-state checks are performed.
    expected_material: Optional material type (e.g. "PLA", "ABS", "PETG").
        If provided and a material is loaded, checks for a mismatch.

    remote_file: Optional filename to verify exists on the printer.
        If provided, checks the printer's file list for a matching file.
    accept_paused: When ``True``, the ``printer_idle`` check accepts
        the ``paused`` state in addition to ``idle``.  Used by
        ``start_print(resume_from_paused=True)`` for mid-print
        resume 3MFs (which start from a paused-state printer).
        Default ``False`` — only ``idle`` is accepted.
    printer_name: Which printer to check.  Omit to check the default
        printer, which is what this did before it could be aimed.
        The state, the temperature ceilings and the material profile
        all follow the named machine — a readiness verdict is about
        one printer, and it has to be the printer that will print.

Call this before ``start_print()`` to catch problems early.  The result
includes a ``ready`` boolean and detailed per-check breakdowns.
send_gcodeA

Send raw G-code commands directly to the printer.

Args:
    commands: One or more G-code commands separated by newlines or spaces.
        Examples: ``"G28"`` (home all axes), ``"G28\nG1 Z10 F300"``
        (home then move Z up 10mm), ``"M104 S200"`` (set hotend to 200C).
    dry_run: When ``True``, run the full validation pipeline (auth,
        rate-limit, G-code safety) but do **not** actually send commands
        to the printer.  Returns what *would* have been sent.

The commands are sent sequentially in order.  The printer must be
connected (unless ``dry_run`` is ``True``).

G-code is validated before sending.  Commands that exceed temperature
limits or modify firmware settings are blocked.  Use ``validate_gcode``
to preview what would be allowed without actually sending.

Raw G-code has no general read-back, so ``outcome`` here is
``"accepted"`` whenever the command was sent: the printer took the
bytes, and whether it EXECUTED them is not reported. Observe the
printer (``printer_status()``, or the machine itself) before building
on a G-code send. ``"failed"`` means the transport refused it.
issue_preview_tokenA

Issue a preview-confirmation token for a file about to be printed.

Call this AFTER the user has seen the print, and say WHICH door showed
it — ``door`` is required and is checked against what this server
itself recorded, never taken on your word:

1. ``door="stage"`` — the inline 3D stage (the MCP Apps panel that
   opens on a make, which the user can orbit).  This is the first and
   best option.  Accepted only when the panel actually fetched the
   geometry for this file (or for the design mesh it was sliced from).
2. ``door="url"`` — a hosted viewer link.  Use it when this host draws
   no panel.  Accepted only when ``show_on_stage(file_path)`` issued
   a ``viewer_url`` for this file that is still live (its result
   carries one on a host that draws no panel, while the machine is
   signed in).
3. ``door="png"`` — the stage's own still (``visualize_model`` with
   ``renderer`` ``stage`` or ``stage_paint``).  The total fallback.
   Accepted only when such a render is on record AND the stage is
   unavailable for a reason the server can name AND the link door
   refused for a reason it recorded.  A raw ``openscad`` render is
   inspection-only and is refused; a PNG claim on a host that draws
   the stage is refused and told to open the stage.

The user approves → you call this tool → you pass the returned token as
``preview_token`` to ``start_print`` (or any other tool that starts a
print) or ``fulfillment_order``.  Without a valid token those tools
refuse (unless ``KILN_SKIP_PREVIEW_GATE=1``).  This is the deepest
safety gate that prevents an agent from sending a print to the
physical printer without the user ever seeing what's about to be
printed.

Tokens are single-use and expire after ``ttl_seconds`` (default 600
seconds / 10 minutes).  Scoped to the specific file hash and
optionally to a specific printer_id so a token for one file can't
be reused to approve a different file.

Args:
    file_path: Path to the file to be printed (STL, 3MF, or .gcode).
        Hashed to bind the token to specific bytes.  If the file
        changes between issuing and using the token, the token is
        rejected.
    door: ``"stage"``, ``"url"`` or ``"png"`` — which door the user
        saw the print through.  Verified against the server's record.
    printer_id: Optional printer model ID to scope the token to a
        specific printer.  When set, using the token with a different
        printer will be rejected.
    ttl_seconds: Lifetime of the token (default 600).

Returns:
    Dict with ``token``, ``door``, ``evidence`` and ``expires_at``
    (unix timestamp); or a refusal whose message says which door to
    open and to call this tool again.
confirm_actionA

Execute a previously requested action that requires confirmation.

When ``KILN_CONFIRM_MODE`` is enabled, destructive tools (safety level
``"confirm"`` or ``"emergency"``) return a confirmation token instead of
executing immediately.  Pass that token here to proceed.

Args:
    token: The confirmation token returned by the original tool call.
fleet_statusA

Get live status of all fleet printers (state, temps, connection — current snapshot).

The multi-machine view is a fleet feature.  For ONE printer — which is
the single-printer experience at every tier — use ``printer_status``
(``detail="lite"`` for the cheap version), ``printer_snapshot`` or
``monitor_print``; each takes a ``printer_name`` and none of them is
tier-gated, so any machine you own can be inspected and stopped
whatever your licence.

For historical analytics (success rates, throughput), use ``fleet_analytics``.
For grouping by physical location, use ``fleet_status_by_site``.
Returns a list of printer snapshots including name, backend type,
connection status, operational state, and temperatures.  Printers
that fail to respond are reported as offline rather than raising.

If no printers are registered yet, the current adapter (from env config)
is auto-registered as "default".
register_printerA

Register a new printer in the fleet.

Registering is free at every tier and always has been — what the fleet
tier sells is running printers in PARALLEL, enforced when a print
starts, not when a machine is added.  So owning a second printer and
using them one at a time is a supported setup on Free and Pro: the
registration succeeds and the reply notes the concurrency limit.

Free and Pro run 1 printer at a time. Fleet starts at Business (3
printers included, $15/mo per additional to a cap of 50); Enterprise
is uncapped.

Args:
    name: Unique human-readable name (e.g. "voron-350", "bambu-x1c").
    printer_type: Backend type -- "octoprint", "moonraker", "bambu",
        "creality", "elegoo", "prusalink", "duet", or "usb".
        "serial" is accepted as a legacy alias for "usb".
    host: Base URL or IP address of the printer.  For USB printers,
        this is the port path (e.g. "/dev/ttyUSB0", "COM3").
    api_key: The printer's credential: an API key (OctoPrint, Prusa
        Link, a Moonraker or Creality printer with its login turned
        on), a Bambu Lab printer's LAN access code, or a Duet's
        machine password.  For OctoPrint it can be left out: Kiln asks
        OctoPrint for a key and the reply (code ``AWAITING_APPROVAL``)
        carries ``approve_url``, a page where the person clicks Allow.
        Give them that link, then call again with the same arguments;
        the request stays open for ten minutes.
    serial: A Bambu Lab printer's serial number (``discover_printers``
        reads it off the network).
    verify_ssl: Whether to verify SSL certificates (default True).
        Set to False for printers using self-signed certificates.
        For Bambu, True maps to TLS pin mode and False maps to
        insecure mode.
    printer_model: Optional safety/profile key (e.g. "k1_max").
    persist: Save the printer to ``~/.kiln/config.yaml`` so future MCP
        sessions load the same printer. Default ``True``.
    verify_connection: For Bambu printers, immediately query AMS status
        after registration and return a proof summary. Default ``True``.
    baudrate: Baud rate for USB printers.  Defaults to
        ``DEFAULT_SERIAL_BAUDRATE``; many Marlin boards are flashed
        for 250000 and will not talk at the default.
    camera_snapshot_url: A camera YOU point at the bed — an http(s)
        URL that answers with one image (a webcam's snapshot endpoint,
        an IP camera's still URL).  Any printer type; used instead of
        the printer's own camera by ``printer_snapshot``,
        ``monitor_print`` and every other frame reader.
    camera_stream_url: The same camera as a live feed — MJPEG over
        http(s), or an rtsp(s) stream (a frame is cut with ffmpeg).
        Either URL alone is enough.  A stream URL may embed a
        password; it is stored with the printer's other credentials
        and never repeated in a reply or a log.  Frames from your
        camera are what Kiln looks at; they do not switch on the
        printer's own failure detection, which runs on the printer
        against its own cameras.

When something this kind of printer needs is missing, the refusal
names it and says where the person finds it; ``discover_printers``
says the same for each printer it finds, before anything is asked.

Once the address has answered, Kiln reads the id the machine reports
for itself (a Prusa Link printer's serial, a Duet board's unique id,
the host serial Moonraker reports) and saves it with the printer, so a
later registration under this name at a new address is matched to the
same machine -- or refused as a different one -- by that id rather
than by the address.  The reply's ``machine_identity`` carries what
was read; a read that fails is noted in ``warnings`` and never fails
the registration.

Once registered the printer can be targeted by name — ``printer_status``,
``monitor_print``, ``cancel_print``, ``pause_print`` and ``resume_print``
all take a ``printer_name`` at every tier, so owning a second machine
never costs you sight of it or control over it.  Seeing them together
(``fleet_status``) and driving them together are Business features.
set_printer_modelA

Tell Kiln which printer model a saved printer is -- by name, or from a slicer file.

Kiln checks every print against the bed it will land on and the
temperatures the machine can take, and slices with the model's own
profile.  All three are read from the printer's model.  With no model
set, those checks are SKIPPED.  Use this as soon as ``kiln_health`` or a
log says the model is not configured.

Two ways to say it -- give exactly one:

* ``printer_model``: any name the catalogue recognises (``"Bambu Lab
  A1"``, ``"bambu_a1"``, ``"MK4"``, ``"K1 Max"``).
* ``slicer_file``: a project the user saved from Bambu Studio,
  OrcaSlicer or PrusaSlicer (File > Save Project), or a printer
  settings file exported from one.  It already names the printer it
  was set up for.  Ask a new user for one instead of asking them to
  look up a model key.

A printer that is NOT in Kiln's catalogue can still be set up, but only
from a slicer file: the file states its bed, which is the one fact Kiln
cannot do without.  Kiln then saves the printer on this machine with
that bed and its own generic limits (never a limit read from the file),
lays slices out on that bed and measures designs against it.  It has no
tuned profile for such a printer and will not move its head.  A name
alone for a printer outside the catalogue is refused (``UNKNOWN_MODEL``,
with the closest matches); ask for the slicer file.

Args:
    printer_model: The model, in any spelling the catalogue knows.
    slicer_file: Path to a saved slicer project or exported settings.
    printer_name: The saved printer to set.  Omit for the active one.
    replace: Allow changing a printer that already has a different
        model, or taking a newer file's bed for a printer set up from
        an earlier file.  Off by default: the model decides the limits
        Kiln checks against, so a wrong one is worse than none.

Returns ``applied`` (whether anything changed), the ``printer``, its
``printer_model`` and ``in_catalogue``, and a ``message`` to relay.
From a slicer file it also returns ``file`` -- the printer, bed, nozzle
size and material the file states -- and ``notes`` where the file's bed
or nozzle differs from what Kiln holds.  The notes change nothing:
relay them, and if the file's nozzle is the one fitted, record it.

Nothing is written for a model that does not suit the printer's
connection, or over another model unless ``replace`` is set.  Limits an
owner typed for a printer are never written over.
create_projectB

Create a project for cost tracking.

Manufacturing bureaus use projects to allocate printer time, material
costs, and fulfillment fees to specific client engagements.

Args:
    name: Project name (e.g. ``"Widget Batch 42"``).
    client: Client or cost-center identifier.
    description: Optional project description.
    budget: Optional budget cap in the configured currency.

Requires Enterprise license.
log_project_costA

Log a cost entry against a project.

Args:
    project_id: The project ID returned by ``create_project``.
    category: Cost category — ``"material"``, ``"printer_time"``,
        ``"fulfillment_fee"``, ``"labor"``, or ``"other"``.
    amount: Cost amount in the configured currency.
    description: What this cost entry is for.
    printer_name: Optional printer that incurred the cost.
    job_id: Optional job ID for traceability.

Requires Enterprise license.
project_cost_summaryA

Get cost breakdown for a project.

Returns total costs, per-category breakdown, and budget utilization
for a given project.

Args:
    project_id: The project ID returned by ``create_project``.

Requires Enterprise license.
client_cost_reportA

Get a cost report for all projects belonging to a client.

Aggregates costs across all projects for a given client identifier,
useful for invoicing and chargeback.

Args:
    client: Client or cost-center identifier.

Requires Enterprise license.
recent_eventsA

Get recent events from the Kiln event bus.

Args:
    limit: Maximum number of events to return (default 20, max 100).
    type: Filter by event type prefix (e.g. ``"print"`` matches
        ``print.started``, ``print.completed``; ``"job"`` matches
        ``job.submitted``, ``job.completed``).  Omit for all events.

Returns events covering job lifecycle, printer state changes,
safety warnings, and more.
license_statusA

Get the current license tier, validity, and key details.

Returns the active tier (free/pro/business), whether the license is
valid, expiration date, and how it was resolved (env/file/default).
No authentication required.

When the tier comes from a sign-in session (``source`` is
``"oauth"``), the answer also carries ``session_state``. If that
session has lapsed, ``is_valid`` is ``false`` and
``action_required`` says how to fix it — surface that line to the
user verbatim, because every hosted call will fail until they do.
activate_licenseA

Activate a Kiln Pro or Business license key.

Writes the key to ``~/.kiln/license`` and returns the resolved
tier info.  Use ``license_status`` to check the current tier first.

Args:
    key: License key string (format: ``kiln_pro_...`` or ``kiln_biz_...``).
restart_serverA

Restart the Kiln MCP server process.

Replaces the current process with a fresh instance using
``os.execve``.  The exec keeps the stdio pipe, so the MCP client sees
no disconnect and repeats no ``initialize`` handshake; the fresh
process takes up the handshake this connection already made, so the
client's next call simply works.  The client keeps the tool list it
cached when it connected: tools the new code adds reach it when it
reconnects.  The result's ``keeps_connection`` says whether the
handshake was handed on.

WHAT A RESTART REFRESHES depends on how this server was launched,
and the result says which happened.  A launcher script that
exported ``KILN_SERVE_WRAPPER`` is re-entered whole, so whatever
that script does before serving — syncing code, healing installs —
runs again.  Without it the restart re-execs ``python -m kiln
serve`` in place: a fresh process over however this interpreter
resolves ``kiln``, which picks up edits to those files but runs no
launcher logic.  (Measured 2026-08-19: an operator launcher synced
two runtime clones on every start, and a restart through this tool
silently skipped the sync — the served code was two revisions
stale while the restart reported success.)

Use after installing or updating kiln-pro plugins, changing
environment variables, or modifying server code — avoids the
need to fully restart the MCP client application.

:param clean_env: When ``True`` (default), strips ``KILN_PRINTER_*``
    environment variables from the child process if
    ``~/.kiln/config.yaml`` has a printer configured.  This defeats
    the "ghost env" footgun where a stale ``KILN_PRINTER_API_KEY``
    inherited from a past shell session silently shadows config.yaml
    edits for the lifetime of the MCP parent process.  Without this,
    every edit to config.yaml looks like it does nothing and the
    printer rejects MQTT auth with no hint why.  Set to ``False`` to
    preserve the full env (useful for CI or pure env-driven workflows
    where config.yaml is absent or deliberately overridden).
:returns: Confirmation that the restart is imminent, plus the list
    of env vars that were stripped (for debugging transparency).
    The exec happens ~0.5 seconds after this returns.
get_autonomy_levelA

Return the current autonomy tier and constraints.

Shows the autonomy level (0 = confirm all, 1 = pre-screened, 2 = full trust) and any Level 1 constraints that are configured. Call this early in a session to understand how much freedom you have.

set_autonomy_levelA

Set the autonomy tier (0, 1, or 2).

Level 0 (Confirm All): Every confirm-level tool requires approval.
Level 1 (Pre-screened): Confirm-level tools allowed if constraints pass.
Level 2 (Full Trust): All tools allowed except emergency-level.

Changing this updates the config file.  Requires human confirmation
because it affects how much control the agent has.
check_autonomyA

Check whether the agent may execute a tool without human confirmation.

Pass the tool name, its safety level, and optional operation context (material, time, temperatures) to get a decision. Use this before calling confirm-level tools to decide whether to proceed or ask.

marketplace_infoA

Show which 3D model marketplaces are connected and available.

Returns the list of connected marketplace sources and their
capabilities (search, download support, etc.).  Configure
marketplaces via environment variables.

**See also:** ``marketplace_status`` for per-credential diagnostics,
or ``marketplace_diagnostics`` for live connectivity probes.

**Safety note:** Community-uploaded models are unverified.  Always
review model dimensions and preview prints before starting.
Proven, popular models with high download counts are safer choices
than untested uploads.
download_and_uploadA

Download model file(s) from any marketplace and upload to a printer.

**Community models are unverified.** This tool downloads and uploads
but does NOT start printing automatically.  You must call
``start_print`` separately after reviewing the uploaded file.
3D printers are delicate hardware — misconfigured or malformed models
can cause physical damage.

When ``file_id`` is provided, downloads and uploads that single file.
When ``model_id`` is provided without ``file_id``, downloads and
uploads all printable files (.stl, .gcode, .3mf, .glb) for the model.
A GLB goes to the printer as an STL beside it, never as a GLB; the
upload's ``conversion`` names the original, which stays on disk.

Args:
    file_id: File ID (from ``model_files`` results).  For Thingiverse
        this is a numeric ID; for MyMiniFactory it's the file ID string.
        If omitted and ``model_id`` is given, all printable files are
        downloaded and uploaded.
    source: Which marketplace to download from — "thingiverse" (default)
        or "myminifactory".  Cults3D does not support direct downloads.
    printer_name: Target printer name.  Omit to use the default printer.
    model_id: Model/thing ID.  When ``file_id`` is omitted, all
        printable files for this model are downloaded and uploaded.

After uploading, review the model and call ``start_print`` to begin.
rotate_modelA

Rotate a 3D model file (STL or 3MF) by specified angles before slicing.

Useful for improving print quality — rotating a tall narrow part 45° around
the Z axis can reduce toolhead-induced wobble and ringing artifacts.

Args:
    input_path: Path to the STL or 3MF file to rotate.
    rotation_z: Rotation around Z axis in degrees (most common — rotates
        on the build plate).
    rotation_x: Rotation around X axis in degrees.
    rotation_y: Rotation around Y axis in degrees.
    output_path: Where to save the rotated file.  Defaults to
        ``<input>_rotated.<ext>``.

Returns dict with ``output_path`` (path to rotated file) and
``rotations_applied``.

Pair with ``reslice_with_overrides`` to re-slice the rotated model with
adjusted settings (e.g., stronger brim after rotation).

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

check_orientationA

Check if a model's orientation is stable for printing.

Analyzes the height-to-base ratio and warns if the model is likely to
wobble or fail mid-print.  Suggests reorientation if needed.

:param model_path: Path to the STL or OBJ model file.
:returns: Dict with stability assessment.
printer_snapshotA

Capture a webcam snapshot from the printer.

Handles TLS+JPEG camera protocol (Bambu A1/P1), MJPEG stream capture
(OctoPrint/Moonraker), and RTSPS (Bambu X1) automatically.  A camera the
user registered for the printer (``register_printer`` with
``camera_snapshot_url`` / ``camera_stream_url``) is used instead of the
printer's own; ``camera_source`` in the reply says which one answered.

:param printer_name: Target printer name.  Omit for the default printer.
:param save_path: Optional path to save the image file.  If omitted, the
    image is returned as a base64-encoded string.
list_materialsA

List built-in filament material profiles (density, cost, temps).

Returns Kiln's bundled material database — NOT what is physically loaded.
For loaded material, use ``get_material`` (software tracker) or
``get_active_material`` (live AMS hardware query).
set_materialA

Record which filament material is loaded in a printer.

This writes down a CLAIM, not a measurement: nothing verifies the spool,
and the record keeps saying the same thing after a filament swap.  Kiln
stamps it ``determined_by: user_reported`` and every reader says so, so
never report the recorded material back as confirmed or sensed.

Args:
    printer_name: Target printer name.
    material: Material type (PLA, PETG, ABS, etc.).
    color: Optional filament color.
    spool_id: Optional ID of a tracked spool (see ``list_spools``).
        Linking one is what lets Kiln count that spool down as this
        printer prints from it.
    tool_index: Extruder index for multi-tool printers (default 0).  On
        a printer with a multi-material unit, the tray's id as
        ``ams_status`` reports it.
get_materialA

Get material loaded in a printer (from Kiln's software tracker).

Returns what the user/agent told Kiln is loaded via ``set_material``.
For live AMS hardware reading (Bambu Lab), use ``get_active_material``.

Args:
    printer_name: Target printer.  Omit for the default printer.
check_material_matchA

Check whether the material Kiln has on record matches what a print expects.

Answers about Kiln's material RECORD, which normally holds what a person
or agent typed via ``set_material`` — not a sensor reading.  Three
answers, and the third one matters: ``match: true`` (the record agrees),
``match: false`` (it disagrees — worth stopping for), and ``match: null``
(nothing is recorded for this printer, so this is neither a match nor a
mismatch and the spool needs an eye on it).  ``sensed`` says whether a
machine reported the material; when it is false, do not tell the user
the material is confirmed.

Args:
    expected_material: The material the print file requires.
    printer_name: Target printer.  Omit to resolve the active printer.
list_spoolsA

List all tracked filament spools in inventory.

``remaining_grams`` is what Kiln believes is left on each spool, and
``remaining_determined_by`` says who set it: ``inferred`` is Kiln's own
count (what the spool held, less what the prints Kiln started were
sliced to use), ``observed`` is the printer's reading of a spool it can
measure, ``user_reported`` is what the person said.  A count misses
prints started outside Kiln, so report a counted figure as Kiln's
count, never as a measurement.  When the person says the figure is
wrong, correct it with ``add_spool(spool_id=..., remaining_grams=...)``;
when they say a spool is used up, ``remove_spool``.
add_spoolA

Add a filament spool to inventory, or correct how much is left on one.

To ADD a spool, give its ``material``.  ``remaining_grams`` is what is
left on a spool that is not new; left out, the spool is full.

To CORRECT a spool already on record, pass its ``spool_id`` (from
``list_spools``) with ``remaining_grams``: the person says they have
more left than Kiln shows, or less.  Only the amount changes.  Kiln
counts a spool down as the prints it starts use it, and a count drifts,
so the person's word wins.  ``remaining_grams=0`` records the spool as
used up and keeps it on the list; ``remove_spool`` takes it off.

Args:
    material: Material type (PLA, PETG, ABS, etc.).  Required to add.
    color: Filament color.
    brand: Manufacturer brand.
    weight_grams: Total spool weight in grams (default 1000).
    cost_usd: Cost of the spool in USD.
    remaining_grams: Grams left on the spool.
    spool_id: A spool already on record whose remaining amount to set.
remove_spoolA

Remove a filament spool from inventory.

When the person says a spool is used up, finished or gone, remove it
here (``list_spools`` gives its id) so Kiln stops treating it as
filament they have.  If they have more or less left than Kiln shows,
correct the figure with ``add_spool(spool_id=..., remaining_grams=...)``
instead.  A used-up spool is not a reason to suggest buying filament:
say nothing about that unless the person asks.

Args:
    spool_id: The spool's unique identifier.
bed_level_statusA

Check bed leveling status and whether leveling is needed.

Args:
    printer_name: Target printer.  Omit for the default printer.
trigger_bed_levelB

Trigger a bed leveling / mesh probe on the printer.

Sends the configured G-code command (G29 or BED_MESH_CALIBRATE)
to the printer.

Args:
    printer_name: Target printer.  Omit for the default printer.
set_leveling_policyB

Configure automatic bed leveling policy for a printer.

Args:
    enabled: Enable/disable auto-leveling checks.
    max_prints: Trigger leveling after this many prints.
    max_hours: Trigger leveling after this many hours.
    gcode_command: G-code command to send (G29 or BED_MESH_CALIBRATE).
    printer_name: Target printer.  Omit for the default printer.
webcam_streamA

Control the local live-video relay for the print monitor.

ONE connection to the printer's camera, re-served as an MJPEG stream on
this machine so every viewer shares it.  Reads an HTTP MJPEG webcam
(OctoPrint, Moonraker, a camera you registered) or a Bambu A1 / P1
camera's own port-6000 feed.  The reply's ``capability`` says whether
this printer can be relayed and, when not, why — an X1 / P2S / H2
camera streams RTSPS, which the relay does not carry (snapshots still
work).  ``stream`` carries the frame's age and the measured frame rate:
``live`` is false when the picture may be frozen.

Local-only: the relay reads the camera over your LAN and serves on
loopback, so on the hosted server it says so instead of starting.
Snapshots (``printer_snapshot``, ``monitor_print``) are unchanged.

A refused start on a printer type that has a camera check carries
``check_available: true``; ``action="check"`` then looks at what that
printer's likely camera addresses actually serve.

Args:
    printer_name: Target printer.  Omit for the default printer.
    action: One of ``"start"``, ``"stop"``, ``"status"``, or
        ``"check"``.  ``"check"`` runs only when asked: it tries each
        address this printer type's camera is known to answer on, on
        the printer's own host, with one GET each (a printer that gives
        out its camera address on request is asked for it first, as a
        start does), and replies with
        ``checks`` (what each served — a live stream, a still, a WebRTC
        page, a web page, an error, or nothing — and where the address
        comes from), a ``summary`` and a ``next_step``.  It registers
        nothing; when it finds a live stream, ``next_step`` says how to
        register that address as the printer's camera.  Local-only,
        like ``"start"``.
    port: Local port for the stream server (default 8081).
list_pluginsA

List all discovered plugins and their status.

register_webhookA

Register a webhook endpoint to receive Kiln event notifications.

Args:
    url: The HTTPS URL that will receive POST requests with event payloads.
    events: Optional list of event types to subscribe to (e.g.
        ["job.completed", "print.failed"]).  If omitted, all events are sent.
    secret: Optional shared secret for HMAC-SHA256 payload signing.
    description: Human-readable label for this endpoint.

Returns the registered endpoint ID.  Use ``list_webhooks`` to see all
endpoints and ``delete_webhook`` to remove one.
list_webhooksA

List all registered webhook endpoints.

Returns endpoint details including URL, subscribed events, and delivery statistics.

delete_webhookA

Delete a registered webhook endpoint.

Args:
    endpoint_id: The endpoint ID returned by ``register_webhook``.

Once deleted, the endpoint will no longer receive event notifications.
await_print_completionA

Wait for the current print to finish and return the final status.

Polls the printer (or a specific queued job) until it reaches a
terminal state: completed, failed, cancelled, or the timeout is
exceeded.  This lets agents fire-and-forget a print and pick up the
result later without managing their own polling loop.

Args:
    job_id: Optional job ID from ``submit_job()``.  When provided,
        tracks that specific job through the queue/scheduler.  When
        omitted, monitors the printer directly for idle/error state.
    timeout: Maximum seconds to wait (default 7200 = 2 hours).
    poll_interval: Seconds between status checks (default 15).
    brief_id: Optional saved-goal id from ``design_session``.  When
        the brief resolves, the terminal-outcome response gains a
        ``design_goal`` block with the design's duty / environment /
        safety notes — so the agent surfacing the print result can
        answer "did this match the goal?" without a separate
        lookup.  Best-effort: missing kiln-pro silently skips.

Returns a dict with ``outcome`` (completed / failed / cancelled /
timeout), final printer state, elapsed time, completion percentage
history, and (when ``brief_id`` resolves) a ``design_goal`` block.

A print carrying a hardware plan (pauses written in for nuts, magnets or
bearings) also returns early with ``outcome: "hardware_stop"`` and a
``hardware`` block: when a stop is a few minutes away, when the printer
has stopped for the parts, and when it went past a stop without
stopping.  Tell the person what the block says, then wait again.  A
finished print's ``hardware`` block names what goes in after the print.
compare_print_optionsA

Compare local printing cost vs. outsourced manufacturing.

Runs a local cost estimate and (if Craftcloud is configured) fetches
a fulfillment quote, then returns a side-by-side comparison to help
agents recommend the best option.

Args:
    file_path: Path to the G-code file (for local) or model file
        (STL/3MF for fulfillment).  If a G-code file is provided,
        only local estimate is returned.
    material: Filament material for the local estimate (PLA, PETG, …).
        Leave empty to use what the file was sliced for, PLA when it
        names nothing.  When kiln-pro (https://kiln3d.com) answers, the
        local estimate also carries a ``cost_intelligence`` field; what
        it holds depends on the tier (https://kiln3d.com/pricing).
    fulfillment_material_id: Material ID from ``fulfillment_materials``
        for the outsourced quote.  If omitted, the fulfillment quote
        is skipped.
    quantity: Number of copies for fulfillment (default 1).
    electricity_rate: Cost per kWh in USD (default 0.12).
    printer_wattage: Printer power consumption in watts (default 200).
    shipping_country: ISO country code for fulfillment shipping.
    printer_id: Optional registered printer the local print is for;
        passed on with the file when kiln-pro is asked.
analyze_print_failureA

Analyze a failed print job and suggest possible causes and fixes.

Examines the job record, related events (retries, errors, progress),
and printer state at the time of failure to produce a diagnosis.

Args:
    job_id: The failed job's ID from ``job_history`` or ``job_status``.

Returns a structured analysis with likely causes, observed symptoms,
and recommended next steps.
render_model_previewA

DEPRECATED — use visualize_model instead. This renders only 1 angle; visualize_model renders 6 angles with auto-framing, colored 3MF support, and quality scores.

INSPECTION-ONLY UNLESS THE STAGE DREW IT: the result's ``renderer`` says which look these pixels are. ``stage`` (the stage photographed) and ``stage_paint`` (the stage's look painted) are accepted by ``issue_preview_token(door="png")`` for print sign-off; a raw ``openscad`` render is not — it has no plate and none of the stage's lighting, and a person once approved the wrong colours from one. Use it to inspect, and sign off from the stage, the viewer link, or a stage still.


This tool is a thin wrapper around ``visualize_model`` with a single
isometric angle.  Prefer ``visualize_model`` directly for multi-angle
previews with proper auto-framing.

Args:
    file_path: Path to an ``.stl``, ``.3mf``, ``.obj``, or ``.scad`` file.
    width: Image width in pixels (default 800).
    height: Image height in pixels (default 600).
    color: Hex color for the model (e.g. ``"#F72323"``).
visualize_modelA

Still pictures of any 3D file from multiple camera angles — the still door, not the 3D stage.

FOR THE PERSON'S LOOK BEFORE A PRINT, OPEN THE STAGE: ``show_on_stage(file_path)`` puts a file that already exists — a mesh, or the sliced print file — on Kiln's interactive 3D stage, which the print gate asks for first (``issue_preview_token(door="stage")``). These renders are for checking a model yourself. When the user is signed in the result also carries a browser stage link (``viewer_url``), the door for a host that draws no panel.

INSPECTION-ONLY UNLESS THE STAGE DREW IT: the result's ``renderer`` says which look these pixels are. ``stage`` (the stage photographed) and ``stage_paint`` (the stage's look painted) are accepted by ``issue_preview_token(door="png")`` for print sign-off; a raw ``openscad`` render is not — it has no plate and none of the stage's lighting, and a person once approved the wrong colours from one. Use it to inspect, and sign off from the stage, the viewer link, or a stage still.


Universal visualization tool that works with ANY 3D file — STL, 3MF,
OBJ, or SCAD.  Returns PNG images from 6 angles: isometric, front,
right, top, bottom, and back.

**Colored 3MF support:** Multicolor 3MF files (with per-face color
groups from BambuStudio, PrusaSlicer, or procedural textures) are
automatically rendered with per-face colors — no slicer needed to
see what the multicolor print will look like.  Colorless 3MF and
STL/OBJ files render in uniform color via OpenSCAD as before.
Dark models get an adaptive lighter background for visibility.
Each view includes a ``quality_score`` and ``dark_material`` flag.

Use this to check a model from all sides — after each change, and
before printing.

**When to use this vs other preview tools:**
- ``show_on_stage`` — the interactive 3D stage on an existing file; what the person turns over before a print
- ``visualize_model`` — still renders of any file, 6 angles, to check it yourself
- ``preview_generated_model`` — after AI generation, includes bottom check
- ``render_model_preview`` — single angle, quick check

Args:
    file_path: Path to an STL, 3MF, OBJ, or SCAD file.
    angles: Optional subset of angles to render. Valid values:
        ``isometric``, ``front``, ``right``, ``top``, ``bottom``, ``back``.
        Defaults to all 6.
    width: Image width in pixels (default 800).
    height: Image height in pixels (default 600).
    color: Hex color for the model (e.g. ``"#F72323"`` for red).
        Defaults to neutral grey.  Pass the filament color to see
        a realistic preview matching the printed result.
        Ignored for colored 3MF files (per-face colors used instead).
compare_rendersA

Render 2-4 models side by side in a single comparison image.

General-purpose visual diff tool — compare any 3D models at the same
camera angle in one image.  Each model is rendered individually then
stitched together with labels.

**Use cases:**
- Texture or decoration variants (compare 3 pattern options)
- Design iterations (before vs after)
- Material color comparisons
- Parameter sweeps (small / medium / large)

Returns a single PNG image path that can be displayed inline.
Supports 2-4 models per comparison.  When 4 models are provided
they are arranged in a 2x2 grid; otherwise a single row.

Args:
    paths: 2-4 file paths (STL, 3MF, OBJ, or SCAD).
    labels: Custom labels for each model.  Defaults to A, B, C, D.
    angle: Camera angle for all renders.  One of ``isometric``,
        ``front``, ``right``, ``top``, ``bottom``, ``back``.
    width: Per-model image width in pixels (default 800).
    height: Per-model image height in pixels (default 600).
    colors: Optional hex color per model (e.g. ``["#F72323", "#2323F7"]``).
get_feedback_loop_statusB

Get the feedback loop history for a generated model.

Returns iteration data, whether the design was resolved, and
which iteration produced the best result.

Args:
    model_id: Model/job ID from a generation job.
list_design_templatesA

List every parametric part Kiln can build, with full parameters.

These are ready-made, print-verified FUNCTIONAL PARTS — brackets,
bins, stands, cases, hooks, jigs, clamps, plumbing and garden
parts — that render locally through OpenSCAD.  They are FREE and
need no AI provider or API key.  Whenever a user wants a functional
part to their own dimensions, check here before writing OpenSCAD
from scratch.

Each template includes:
- Every parameter with its default, unit, and description
- Pre-validated OpenSCAD (prints without supports)
- Category and a one-line description of the job it does

Prefer ``find_design_templates(use_case)`` when you know what the
user is making — it searches this library by use case and ranks
matches, instead of returning all of them.  Then call
``generate_from_template(template_id, {...})`` to render a printable STL.
generate_from_templateA

Build a printable STL from a parametric part, to the user's dimensions.

This is how Kiln makes a FUNCTIONAL PART without writing any
OpenSCAD: pick a template, pass the dimensions the user gave you,
and get a print-ready STL.  It runs LOCALLY through OpenSCAD — free,
no AI provider, no API key, and every template in the library is
print-verified at its default, minimum, and maximum parameters.

Reach for this the moment a user describes a functional part they
need in specific sizes ("a bracket for a 200 mm shelf", "a bin that
fits my 80 mm drawer", "a clip for an 8 mm cable"). Find the
template with ``find_design_templates(use_case)``, read its
parameters with ``get_design_template_info(id)`` or
``list_design_templates()``, then call this.

Only PARAMETRIC PARTS work here.  The design PATTERNS returned by
``find_design_templates`` with ``generatable: false`` (snap fits,
living hinges, press fits) are guidance for OpenSCAD you write
yourself — this tool rejects them.

For AI-assisted parameter inference plus structural analysis, use
``smart_generate_from_template``.

When the kiln-pro package is installed (Pro+ tier), the result MAY
carry an ``intent`` block describing the geometric assertions the
template parameters implied, and a sidecar ``<mesh>.intent.json``
is written next to the produced STL.  Free / public installs see
the result unchanged.  See https://kiln3d.com for tier details.

When you pass a parameter that sizes a hole for real hardware (a
screw or bolt hole, a bore, a dowel or pin hole, a magnet pocket),
the result carries a ``fastener_advice`` block saying the part was
built to your number and nothing sized it for a named fastener.
Kiln raises that once per session across every tool that can raise
it, so a later build may omit the block even though it qualifies.
Read its ``agent_instruction`` before repeating any of it to the user.

Args:
    brief_id: The saved goal's id from ``design_session``; pass it so
        this make joins the goal (recorded against it; Kiln Pro checks the
        result against it). Empty when there is no goal.
    template_id: Parametric part id, from ``find_design_templates``
        or ``list_design_templates`` (e.g. ``"shelf_bracket"``).
    parameters: Dict of parameter overrides carrying the user's own
        dimensions (e.g. ``{"arm_length": 200, "thickness": 8}``).
        Anything you leave out keeps the template's default.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

MAKE DOORS: design_session, Kiln's front door for making an object, is not installed here (signed in to Kiln it runs on Kiln's servers). On this install compile_scad IS the make → preview → iterate loop: make it, show the preview, iterate.

list_plate_objectsA

List named objects on the build plate of a Bambu .gcode.3mf file.

Parses the plate metadata embedded in .gcode.3mf files exported by
Bambu Studio or OrcaSlicer.  Returns every object that was on the
plate when the file was sliced, with its name, bounding box, area,
and layer height.

Works even when the 3MF contains NO mesh geometry (common for
.gcode.3mf exports).

Bambu Studio supports multiple plates (plate_1, plate_2, etc.).
Use ``plate_number`` to select which plate to inspect.  The response
includes a ``plates_available`` field listing all plate numbers found
in the archive.

Use this to discover which parts are in a multi-object file before
calling ``extract_plate_object`` to isolate one — or, if a part fails
mid-print, to get its ``label_id`` for ``skip_print_objects`` so you can
abandon just that object and save the rest of the plate.

:param file_path: Path to the .3mf or .gcode.3mf file.
:param plate_number: Which plate to inspect (1-based, default 1).
:returns: Dict with ``objects`` list (each with a ``label_id`` that
    ``skip_print_objects`` consumes), plate metadata (bed type,
    filament colours, nozzle diameter, sequential print flag),
    and ``plates_available``.
extract_plate_objectA

Extract a single object's G-code from a multi-object Bambu .gcode.3mf.

When a .gcode.3mf contains multiple objects (e.g. a lid and a body),
this tool extracts ONLY the G-code for the requested object, producing
a standalone .gcode file that can be printed directly.

The machine start-up (homing, levelling, heating) and end (cool-down,
park) sequences are preserved.  Only the per-layer toolpath sections
for other objects are removed.

Bambu Studio supports multiple plates (plate_1, plate_2, etc.).
Use ``plate_number`` to select which plate to extract from.

Object matching is case-insensitive and supports partial names:
``"cap"`` will match ``"TreatHolder - cap.stl"``.

Use ``list_plate_objects`` first to see available object names.

:param file_path: Path to the .gcode.3mf file.
:param object_name: Name (or partial name) of the object to extract.
:param output_dir: Directory for the output .gcode file. Defaults to
    the same directory as the input file.
:param plate_number: Which plate to extract from (1-based, default 1).
:returns: Dict with output path, matched object info, and line counts.
print_plate_objectA

Extract a single object from a multi-object .gcode.3mf and print it.

This is a compound workflow tool that performs the complete pipeline
in one call:

1. **Extract** the requested object's G-code (``extract_plate_object``)
2. **Upload** the extracted G-code to the printer (``upload_file``)
3. **Preflight + Start** the print (``start_print``, which runs its
   own preflight safety check)

Bambu Studio supports multiple plates (plate_1, plate_2, etc.).
Use ``plate_number`` to select which plate to extract and print from.

Object matching is case-insensitive and supports partial names:
``"cap"`` matches ``"TreatHolder - cap.stl"``.

Use ``list_plate_objects`` first if you want to preview what's
available before committing to a print.

:param file_path: Path to the .gcode.3mf file.
:param object_name: Name (or partial name) of the object to print.
:param use_ams: AMS mode — ``"auto"``, ``"true"``, or ``"false"``.
:param ams_mapping: The tray per extruder by the printer's tray id
    (e.g. ``[0]`` for slot A1, ``[5]`` for B2; see ``ams_status``).
:param bed_leveling: Run bed leveling before print.
:param flow_cali: Run flow calibration before print.
:param vibration_cali: Run vibration calibration before print.
:param bed_type: Bed surface type — ``"auto"``, ``"textured_plate"``,
    ``"cool_plate"``, or ``"engineering_plate"`` (Bambu only).
:param plate_number: Which plate to extract from (1-based, default 1).
:param printer_name: Which printer to print on.  Omit for the default
    printer.  Both steps are aimed at it, so the object is uploaded to
    and started on the same machine.
:returns: Dict with extraction info and print start status.
resolve_model_sourceA

Identify where a model file came from.

A file Kiln downloaded from a marketplace or a generator answers from
the note Kiln left beside it, in any format (``came_from`` says it in
a sentence).  Otherwise a .3mf or .gcode.3mf answers from its embedded
metadata: MakerWorld metadata and generic 3MF metadata (Title,
Designer, Application, License, etc.).

Returns the model title, designer, model URL (if available), slicer
application name, and a list of objects on the plate.

Use this when you need to trace a file back to its source — for
example, to find the original STL files on MakerWorld when the
.gcode.3mf only contains pre-sliced G-code without mesh geometry.

:param file_path: Path to the .3mf or .gcode.3mf file.
:returns: Dict with source marketplace, model URL, designer info,
    and plate object names.
validate_openscad_codeA

Validate OpenSCAD code without generating geometry.

Compiles the code and returns structured error/warning information
with line numbers.  Use this to check code before calling
generate_model with OpenSCAD.

:param scad_code: OpenSCAD source code to validate — the same parameter
    name ``compile_scad`` / ``analyze_scad_code`` / ``tweak_and_compile_scad``
    take, so a session that has been compiling can validate without
    learning a second spelling.
:param code: Alias of ``scad_code`` kept for callers that learned it.
:returns: Dict with ``valid``, ``errors``, and ``warnings``.
predict_print_failureA

Predict common 3D printing failure modes from mesh geometry.

Analyzes the mesh for thin walls, long unsupported bridges,
severe overhangs, top-heavy geometry, small features, and
non-manifold issues.  Returns a risk score (0-100) and
per-failure details with fix suggestions.

The thin-wall floor follows the nozzle: two lines of it, so 0.8 mm for
a 0.4 mm nozzle and 1.2 mm for a 0.6.  The answer says which nozzle it
was judged for and where that size came from.

:param file_path: Path to mesh file (.stl, .obj, .glb, or .3mf).
:param min_wall_mm: Minimum printable wall thickness.  Leave it out to
    use two lines of the nozzle.
:param max_bridge_mm: Maximum unsupported bridge length (default 15).
:param max_overhang_deg: Maximum overhang angle before failure (default 55).
:param printer_id: The printer the part is for.  Left out, the only
    printer Kiln knows of stands in.
:param nozzle_mm: The nozzle fitted, when you know it.  Left out, the
    nozzle on record for the printer, then the printer's own setting,
    then its stock size.
:returns: Dict with verdict, risk score, failure list, the wall floor
    used and the nozzle it was judged for.
search_design_templatesB

Search the template library by natural-language description.

Fuzzy keyword matching against template IDs, descriptions, categories,
and tags.  Returns scored matches ranked by relevance.

:param query: Natural-language search string (e.g. "phone stand", "hook").
:param max_results: Maximum number of results (default 10).
:param category_filter: Optional category to limit results (e.g. "hardware").
:returns: Dict with matches list, each containing template_id, score,
          description, and category.
design_to_gcode_pipelineA

End-to-end pipeline: description → template → STL → analysis → GCode.

One-call pipeline that:
1. Searches templates for best match
2. Generates STL via OpenSCAD
3. Runs structural risk analysis
4. Estimates weight
5. Slices to G-code (if slicer available)

:param brief_id: The saved goal's id from ``design_session``; pass it so
    this make joins the goal (recorded against it; Kiln Pro checks the
    result against it). Empty when there is no goal.
:param description: Natural-language design description.
:param output_dir: Directory for output files (uses tempdir if empty).
:param material: Material the slice is set for -- temperatures, melt
    rate and cooling -- and weighed as.
:param printer_model: Printer model for slicer profile lookup.
:param infill_percent: Infill percentage for weight estimation.
:returns: Dict with paths to SCAD, STL, G-code files, weight, risks.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

MAKE DOORS: design_session, Kiln's front door for making an object, is not installed here (signed in to Kiln it runs on Kiln's servers). On this install compile_scad IS the make → preview → iterate loop: make it, show the preview, iterate.

merge_stlA

Merge multiple STL files into a single mesh (supports positional offsets).

Use this when you need to position parts relative to each other.
For simple concatenation without positioning, ``merge_mesh_files`` also works.
Combines triangle data from multiple STL files into one output file.
Optionally translates each part to a specified position before merging.

:param file_paths: JSON array of STL file paths.
:param output_path: Where to write the merged STL.
:param positions: Optional JSON array of {"x", "y", "z"} offsets per file.
:returns: Dict with output_path, total_triangles, bounding_box.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

compose_multicolor_3mfA

Compose a multi-color / multi-material .3mf from multiple STL files.

Creates a **single .3mf, ready to slice**, containing all parts with
per-part AMS/extruder slot assignments.  This is the correct way to hand
a multi-color design to a slicer — it receives one file, not multiple.
It is a model, not a sliced plate, so no printer starts it as it stands:
slice it first.  ``fits_bed`` says whether the plate fits the bed it was
composed for; when it does not, the message says by how much and what to
do, and does not offer it for printing.

Compatible with:
* **BambuStudio / Bambu A1, X1, P1 + AMS** — reads ``Metadata/model_settings.config``
* **PrusaSlicer / MMU** — reads ``slic3rpe:extruder`` on each ``<item>``
* **Cura** and any 3MF-capable slicer

Typical two-color workflow::

    # 1. Export body STL (main color, e.g. grey PLA)
    # 2. Export accent STL (second color, same coordinate origin)
    # 3. Compose:
    result = compose_multicolor_3mf(parts=[
        {"stl_path": "/tmp/body.stl",    "extruder": 1,
         "name": "body",    "color": "#AAAAAA", "material": "PLA Grey"},
        {"stl_path": "/tmp/qr_pads.stl", "extruder": 2,
         "name": "qr_code", "color": "#111111", "material": "PLA Black"},
    ])
    # 4. Slice and print (or slice_model to look at the slice first):
    slice_and_print(result["output_path"])

Args:
    parts: List of part dicts.  Each dict requires:

        * ``stl_path`` (str) — absolute path to the STL for this part
        * ``extruder`` (int) — 1-indexed AMS slot (1 = AMS tray 1 on Bambu)

        Optional per-part keys:

        * ``name`` (str) — label shown in the slicer object list
        * ``color`` (str) — hex preview color e.g. ``"#AAAAAA"`` (display only)
        * ``material`` (str) — filament label e.g. ``"PLA Grey"`` (display only)

    output_path: Where to write the .3mf.  Defaults to a temp file whose
        path is returned in the result.
    plate_width: Print plate X dimension in mm (default 256 for legacy
        callers without a printer id).
    plate_depth: Print plate Y dimension in mm (default 256).
    material: Optional material the parts will be printed in (e.g.
        ``"PETG"``).  A spool on record in a clearly different
        material is then not named as one to load.
    printer_id: Optional supported printer model id.  When it resolves,
        its build volume overrides ``plate_width`` / ``plate_depth``.
        The composer centres an off-plate group on THIS plate, so name
        the printer whenever you know it — a group arranged for a
        larger or smaller bed and composed against the 256 default is
        re-centred onto a plate the machine does not have.

Returns:
    Dict with ``success``, ``output_path``, ``parts``, ``total_triangles``,
    ``total_vertices``, ``extruder_map``, ``fits_bed`` (``False`` when the
    plate is bigger than its bed, ``None`` when it could not be measured),
    ``bed_fit`` (the sizes behind that verdict), and ``message``.  It also says
    whether the part colours are on the printer, as
    ``colour_availability`` (absent when Kiln cannot see what is loaded).
    Relay its ``say`` as written and add nothing about filament: never
    suggest buying filament unless the person asks for one or says yes
    to the offer in ``say``.  On a yes, call ``find_closest_filaments``
    with these colours and the print's material.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

update_firmwareA

Start a firmware update on the default/connected printer (adapter-level, by component).

For fleet setups where you need to update a specific printer by name
or pin a target version, use ``update_printer_firmware`` instead.
For Moonraker printers, this triggers the Klipper update manager.
For OctoPrint printers, this uses the Software Update plugin.

Args:
    component: Optional component name to update (e.g. ``"klipper"``,
        ``"moonraker"``).  If omitted, all components with available
        updates will be upgraded.

The printer must not be actively printing.  Check ``firmware_status``
first to see which updates are available.
rollback_firmwareA

Roll back firmware on the default/connected printer (adapter-level, by component).

For fleet setups where you need to rollback a specific printer by name
or target a specific version, use ``rollback_printer_firmware`` instead.
Only supported on Moonraker printers.  The component must have a
known rollback version (check ``firmware_status``).

Args:
    component: Name of the component to roll back (e.g. ``"klipper"``).
print_historyB

Get recent print history with success/failure tracking.

Args:
    printer_name: Filter by printer name, or all printers if omitted.
    status: Filter by status (``"completed"`` or ``"failed"``).
    limit: Maximum records to return (default 20).

The response declares its own SCOPE.  These are the prints THIS
machine recorded — another computer running Kiln keeps its own
history — and ``scope.local.total_records`` gives the store's full
matching count when ``limit`` truncated the page.
printer_statsC

Get aggregate statistics for a printer: total prints, success rate, average duration.

Args:
    printer_name: Name of the printer to get stats for.
annotate_printB

Add notes to a completed print record (e.g., quality observations, issues).

Args:
    job_id: The job ID of the print to annotate.
    notes: The annotation text to attach.
export_safety_profileA

Export a safety profile as a shareable JSON object.

Returns the full safety limits for a printer model in a format
suitable for sharing with other users.  Looks up community profiles
first, then falls back to bundled profiles.

Args:
    printer_model: Printer model identifier (e.g. ``"ender3"``,
        ``"bambu_x1c"``).
get_material_recommendationA

Get printer-specific slicer settings for a material you have already chosen.

Use AFTER selecting a material — returns hotend/bed temps, fan speed, and
tips tuned to a specific printer model. For help choosing which material
to use, see ``recommend_material`` or ``recommend_design_material``.

Args:
    printer_id: Printer model identifier.
    material: Material name (e.g. ``"PLA"``, ``"PETG"``, ``"ABS"``,
        ``"TPU"``).
troubleshoot_printerA

Diagnose a printer issue by searching the known failure modes database.

Describe the symptom (e.g. ``"under-extrusion"``, ``"layer shifting"``,
``"stringing"``) and get possible causes and fixes specific to your
printer model.

On Bambu Lab printers you can also pass ``hms_code`` — the HMS error code
the printer's screen or app shows (e.g. ``"0300_1A00_0002_0001"``, in any
separator or case).  The response echoes the normalized code and a link to
Bambu's HMS wiki page for it.  With Kiln Pro (https://kiln3d.com/pricing)
the response also carries a decoded cause, fix, and severity for the code.

Two things in ``symptom`` are read as exact signals rather than as words,
and both narrow the answer sharply, so say them if you know them:

* a fault code anywhere in the text (``"1200-8007"``, ``"12008007"``);
* which step of a load/unload wizard failed (``"fails at step 5"``).

Every code the call names -- in ``hms_code`` or anywhere in ``symptom``,
so two codes read off ``printer_status`` fit in one call -- is read
through the same reader ``printer_status`` uses and returned under
``fault_readings`` (code, namespace, reading, and the fix when Kiln has
one).  When the printer's playbook carries none of the codes named, the
response says so in ``codes_without_a_playbook`` rather than answering
the codes with word matches alone.

A step number is the most useful sentence a user can offer about a load
failure: the response's ``load_step_reading`` says whether that step is
upstream of the melt zone, which rules a nozzle clog in or out before
anyone unscrews anything.

Args:
    printer_id: Printer model identifier.
    symptom: Description of the problem.  Optional when ``hms_code`` is
        given.
    hms_code: Optional Bambu HMS error code to look up.
run_quick_printA

Full print pipeline: validate + slice + safety-check + upload + print (recommended one-shot tool).

Preferred over ``slice_and_print`` — adds mesh-level pre-print
validation, G-code safety validation, and auto-detected bundled
slicer profiles.  For custom slicer parameter overrides, use
``run_reslice_and_print`` instead.  The full quick-print pipeline:
1. Validate mesh (printability, manifold, walls, bridges, bed-fit)
2. Resolve slicer profile (bundled, by printer_id)
3. Slice the (possibly auto-repaired) mesh to G-code
4. Safety-validate the G-code against printer limits
5. Upload G-code to the printer
6. Run preflight checks (always — cannot be skipped)
7. Start printing

Args:
    model_path: Path to input model (STL, 3MF, STEP, OBJ).
    printer_name: Registered printer name in fleet.
    printer_id: Printer model ID for auto-profile selection
        (e.g. ``"ender3"``, ``"bambu_x1c"``, ``"klipper_generic"``).
    profile_path: Explicit slicer profile. Overrides printer_id auto-selection.
    material: Filament material (e.g. ``"PLA"``).  It sets the slice's
        temperatures, melt rate and cooling, its density weighs the
        print (omitted: the spool the printer reports loaded, then PLA —
        the slice step says which), and AMS auto-routing prefers a
        loaded tray whose type matches.
    use_ams: AMS feeding mode (Bambu): ``"auto"`` (default — detect and
        route to a loaded tray), ``"true"``, or ``"false"``.
    ams_mapping: Explicit AMS slot mapping as a JSON array string,
        e.g. ``"[0]"`` or ``"[0, 2]"``.  Overrides auto-selection.
    skip_validation: Bypass the mesh-level pre-print validation step.
        Defaults to False — designs are pre-tested for printability
        before they reach the printer.  Use True for already-validated
        inputs or pre-sliced 3MFs the validator can't introspect.
    preview_token: Token from ``issue_preview_token`` after the user
        has seen ``model_path``.  Required: this tool ends at the
        printer, so it is gated exactly as ``start_print`` is.
    placement: Where the part goes when the plate still holds the last
        print: ``[x, y]`` in mm, a named region (``"front-left"``,
        ``"centre"``, …), or ``"keep"``.  Omitted, an occupied plate
        refuses at the slice step and lists the spots that would work.
        The clearance verdict is free; placing and starting a second
        print on an occupied plate is a kiln-pro feature
        (https://kiln3d.com/pricing).

On Bambu AMS printers the response carries ``ams_selection``
(``{slot, type, color}``) naming the tray actually used — routing is
never silent.
run_reslice_and_printA

Reslice with custom slicer overrides + print (use for retries with adjusted settings).

Use this when you need to tweak slicer parameters (speed, brim, infill, temps).
For standard prints without overrides, use ``run_quick_print`` instead.
One-shot pipeline: validate mesh → resolve profile with overrides →
slice → safety check → upload to printer → start print.

The overrides parameter is a JSON string of PrusaSlicer INI key-value pairs:
  {"brim_width": "8", "perimeter_speed": "30", "fill_density": "25%"}

Common override keys:
  Adhesion: brim_width (mm), skirts (count)
  Temperature: temperature, bed_temperature (degrees C)
  Speed: perimeter_speed, infill_speed, first_layer_speed (mm/s)
  Structure: fill_density (%), fill_pattern, layer_height (mm)
  Support: support_material (0/1)

Requires PrusaSlicer or OrcaSlicer installed locally.
The printer must be idle and connected.

Args:
    model_path: Path to input model (STL, 3MF, STEP, OBJ).
    printer_name: Registered printer name in fleet.
    printer_id: Printer model ID for auto-profile selection
        (e.g. ``"ender3"``, ``"bambu_x1c"``, ``"klipper_generic"``).
    overrides: JSON string of PrusaSlicer INI key-value pairs to override.
    profile_path: Explicit slicer profile. Overrides printer_id auto-selection.
    slicer_path: Explicit path to the slicer binary.
    material: Filament material (e.g. ``"PLA"``).  It sets the slice's
        temperatures, melt rate and cooling -- a setting you also pass in
        ``overrides`` stays yours -- and its density weighs the print
        (omitted: the spool the printer reports loaded, then PLA — the
        slice step says which).
        For fully-auto raw-gcode reslices, AMS routing prefers a loaded
        tray of this material.  (3MF plates carry their own filament
        map, so routing defers to the adapter there.)
    use_ams: Enable AMS filament feeding (Bambu printers). If omitted,
        auto-detected from 3MF metadata.
    ams_mapping: JSON string of AMS slot indices (e.g. ``"[0, 2]"``).
        Maps each extruder/filament to an AMS tray position.
    skip_validation: Bypass the mesh-level pre-print validation step.
        Defaults to False — designs are pre-tested for printability
        before they reach the printer.
    placement: Where the part goes when the plate still holds the last
        print: ``[x, y]`` in mm, a named region (``"front-left"``,
        ``"centre"``, …), or ``"keep"``.  Omitted, an occupied plate
        refuses at the slice step and lists the spots that would work.
        The clearance verdict is free; placing and starting a second
        print on an occupied plate is a kiln-pro feature
        (https://kiln3d.com/pricing).

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

multi_copy_printA

Print multiple copies of a model arranged on one build plate.

Automatically arranges copies in a grid with spacing so they don't
overlap, slices the plate as a single job, and prints.

Uses PrusaSlicer's ``--duplicate`` flag when available (handles placement,
collision avoidance, and travel optimization). Falls back to STL mesh
duplication for OrcaSlicer or when fine control is needed.  Copies that do
not all fit the bed are refused, saying so, never sliced short.

Requires a slicer (PrusaSlicer or OrcaSlicer) installed locally.
The printer must be idle and connected.

Args:
    model_path: Path to input model (STL, OBJ).
    copies: Number of copies to print (2-20).
    printer_name: Registered printer name in fleet.
    printer_id: Printer model ID for auto-profile selection.
    spacing_mm: Gap between copies in mm (default 10).
    overrides: JSON string of slicer parameter overrides.
    slicer_path: Explicit path to the slicer binary.
run_calibrateA

Full calibration pipeline: home + bed level + printer-specific guidance (recommended).

Higher-level than ``calibrate_direct`` — orchestrates the full sequence and
returns intelligence-based calibration tips. Performs physical calibration
steps (homing, auto bed leveling) and returns printer-specific calibration
guidance from the intelligence database.

Args:
    printer_name: Registered printer name.
    printer_id: Printer model ID for calibration guidance.
run_benchmarkA

Prepare a benchmark print: validate → slice → upload → report stats.

Slices a model with the printer's profile and uploads it, then
reports printer stats from history. The print is NOT started
automatically — benchmarks should be manually observed.

Args:
    model_path: Path to benchmark model (STL).
    printer_name: Registered printer name.
    printer_id: Printer model ID for profile selection.
    profile_path: Explicit slicer profile path.
    skip_validation: Bypass the pre-print mesh validation step.
        Defaults to False — user-supplied benchmark meshes are
        pre-tested for printability.  Set to True for known-good
        fixed reference benchmark models.
find_material_substituteA

Find substitute filament materials when your preferred material is unavailable (returns ranked list).

Checks a built-in knowledge base of FDM filament compatibility and returns
ranked alternatives with trade-off descriptions.  For a single best match,
use ``get_best_material_substitute`` instead.

Args:
    material: The original filament material (e.g. "PLA", "PETG", "ABS").
    reason: Optional filter — only return substitutions matching this reason
        (unavailable, cost, strength, finish_quality, heat_resistance, lead_time).
    min_score: Minimum compatibility score threshold (0.0–1.0).
get_best_material_substituteA

Get the single best substitute for a filament material (quick shortcut).

Returns one top-ranked alternative. For a full ranked list with trade-off
details and filtering, use ``find_material_substitute`` instead.

Args:
    material: The original filament material (e.g. "PLA", "PETG").
get_material_propertiesA

Get a material's public safety and printing-property profile.

Returns the public thermal, chemical-safety, and process-design floor.
Deeper engineering questions are answered one at a time by kiln-pro
(https://kiln3d.com).

Args:
    material_id: Material key (e.g. ``"petg"``, ``"tpu"``, ``"cf_pla"``).
        Case-insensitive.
check_printer_material_supportA

Check if a printer supports one specific material.

Returns compatibility status (``"compatible"`` or ``"needs_upgrade"``),
required hardware upgrades (enclosure, hardened nozzle, dry box, etc.),
and material-specific notes for the printer.

**See also:** ``check_printer_material_compatibility`` for the same
check with design-intelligence context and alternative suggestions.

Args:
    printer_id: Printer model identifier (e.g. ``"bambu_a1"``,
        ``"ender3"``, ``"prusa_mk4"``).
    material_id: Material to check (e.g. ``"petg"``). Required so this
        hosted surface cannot enumerate a printer's complete matrix.
compare_material_propertiesA

Compare two materials using a fixed public safety/process field set.

Use this when deciding between materials for a project (e.g. PLA vs PETG
for an outdoor bracket) or when switching materials for a reprint. Deeper
engineering trade-offs are answered one question at a time by kiln-pro
(https://kiln3d.com).

Args:
    material_a: First material (e.g. ``"pla"``).
    material_b: Second material (e.g. ``"petg"``).
build_material_overridesA

The slicer settings a material gets on a printer: temperatures, melt rate, cooling.

Every slicing door applies these itself when it is told the material --
``material=`` on ``slice_model``, ``slice_and_print``,
``reslice_with_overrides``, ``run_quick_print``, ``run_reslice_and_print``
and ``kiln slice`` -- so naming the material is all a slice needs.  This
tool shows what that will be and why, from the same resolver
(:mod:`kiln.slicer_material`): a product's own figures when you name one
(``"bambu_tpu_95a"``), else Kiln's settings for the material on this
printer, else the middle of the material's range, never above what the
printer is rated for.  The melt-rate ceiling
(``filament_max_volumetric_speed``) slows every feature of the print to
suit the material, the outer wall and the first layer included.

Its ``overrides`` can still be passed to ``reslice_with_overrides`` to
pin them; a setting passed that way is the caller's, and a slice leaves
it alone.

Example::

    build_material_overrides("tpu", "bambu_a1")
    # overrides: temperature 225, bed_temperature 50, max_fan_speed 50, ...

Args:
    material_id: Material (``"petg"``, ``"tpu"``, ``"PA-CF"``) or a
        product (``"bambu_tpu_95a"``).
    printer_id: Printer model, for its own settings and limits.
        Omitted, the material's own.
reprint_with_materialA

Reprint a model with a different material — the slice is set for it.

One-shot convenience tool: reslices the model for the new material
(its temperatures, melt rate and cooling, from the same resolver every
slice uses -- see ``build_material_overrides``), merges any extra
overrides you provide, runs a safety check, uploads to the printer, and
starts the print.  The file is labelled and weighed as the new material.

Use this when you want to reprint an existing model in a different
material (e.g. PLA → PETG for outdoor durability, or PLA → TPU for
flexibility). The tool handles all the slicer parameter changes
automatically.

Example: "Reprint my grip extension in PETG instead of PLA"::

    reprint_with_material(
        file_path="/path/to/grip_extension.stl",
        material_id="petg",
        printer_name="my_bambu",
        printer_id="bambu_a1",
        use_ams=True,
        ams_mapping="[1]",  # PETG is in slot A2 (tray id 1)
    )

Requires PrusaSlicer or OrcaSlicer installed locally.

Args:
    file_path: Path to the model file (STL, 3MF, STEP, OBJ).
    material_id: Target material (e.g. ``"petg"``, ``"tpu"``).
    printer_name: Registered printer name in fleet. If omitted,
        uses the default printer.
    printer_id: Printer model ID for profile selection
        (e.g. ``"bambu_a1"``, ``"ender3"``).
    extra_overrides: Optional JSON string of additional slicer
        overrides to merge on top of the material defaults
        (e.g. ``'{"fill_density": "30%"}'``).
    use_ams: Enable AMS filament feeding (Bambu printers).
    ams_mapping: JSON string of AMS slot indices (e.g. ``"[1]"``).
        Maps each extruder/filament to an AMS tray position.
smart_reprintA

Smart one-shot material-switch reprint — finds the model, detects the right AMS slot, adjusts slicer settings, and prints.

This is the highest-level reprinting tool. Give it a file name (or
partial name) and a target material, and it handles everything:

1. **Find the model**: Searches print history for the file name, then
   searches common local directories for the source STL/3MF/STEP file.
2. **Check AMS**: Reads AMS tray status to find which slot has the
   target material loaded. Auto-selects the matching slot.
3. **Build overrides**: Generates material-specific slicer overrides
   (temperature, speed, retraction) for the target material.
4. **Reslice + print**: Reslices the model with new settings and
   starts the print with the correct AMS mapping.

Example: "Reprint my grip extension in PETG"::

    smart_reprint(
        file_name="grip_extension",
        material_id="petg",
        printer_name="my_bambu",
        printer_id="bambu_a1",
    )

The tool will find ``grip_extension.stl`` on disk, detect that PETG
is loaded in AMS slot 1, adjust temps/speeds for PETG, reslice, and
start printing — all in one call.

Saved-goal carry-forward: when the source model on disk has a
``<file>.intent.json`` sidecar tagged with a saved goal, that
goal's id is auto-recovered and surfaced as ``brief_id`` in the
result so downstream ``record_print_outcome`` correctly links the
reprint back to the goal. Pass ``brief_id="..."`` explicitly to
override the sidecar derivation (rare — useful for one-off
re-attributions).

Args:
    file_name: Full or partial file name to search for (e.g.
        ``"grip_extension"`` or ``"grip_extension.stl"``).
        Searched in print history first, then in local directories.
    material_id: Target material (e.g. ``"petg"``, ``"tpu"``).
    printer_name: Registered printer name in fleet.
    printer_id: Printer model ID for profile selection.
    search_dirs: Optional JSON array of extra directories to search
        for the model file (e.g. ``'["/home/user/models"]'``).
    extra_overrides: Optional JSON string of additional slicer
        overrides (e.g. ``'{"fill_density": "30%"}'``).
    auto_ams: If ``True`` (default), automatically detect AMS slot
        for the target material. Set to ``False`` to skip AMS
        detection (useful for non-Bambu printers).
    brief_id: Optional saved-goal id from ``design_session``.  When
        omitted, the source model's intent sidecar (if any) is read
        and the saved goal's id is derived from its ``generator``
        field — so a reprint of a brief-attached design keeps the
        goal link automatically.  Best-effort: missing kiln-pro or
        missing sidecar silently skips.
multi_material_printA

Print multiple objects in different materials/colors on one build plate.

**Only a printer Kiln drives can make this print** — today a Bambu with
an AMS.  At any other printer (a Klipper MMU Kiln can read but not
route, or a single-feed machine) a multi-filament plate is REFUSED
before slicing with code ``MULTI_MATERIAL_NOT_DRIVEN``: the objects
would all come out in one filament.  The refusal carries what Kiln saw
on the printer (``multi_material``) and the composed file
(``multi_material_3mf``), so the user can slice it in a slicer that
drives their unit.  A single-filament plate is never refused.

Takes a JSON array of objects, each with a model file and material
assignment. Builds a multi-material 3MF file with per-object filament
assignments, slices it, auto-maps materials to AMS slots, and prints.

This is how you print "object A in red PLA, object B in black PETG"
in a single print job.

Example: Print a bracket in PETG and a cover in PLA::

    multi_material_print(
        objects_json='[
            {"file_path": "/path/to/bracket.stl", "material_id": "petg"},
            {"file_path": "/path/to/cover.stl", "material_id": "pla"}
        ]',
        printer_name="my_bambu",
        printer_id="bambu_a1",
    )

Each object in the JSON array supports:
    - ``file_path`` (required): Path to STL/OBJ/GLB mesh file.
    - ``material_id`` (required): Material identifier (e.g. ``"petg"``).
    - ``name`` (optional): Display name for the object.
    - ``color`` (optional): Hex color override (e.g. ``"#FF0000"``).
    - ``group`` (optional): Objects sharing a group index are placed
      coincident (for meshes that share one coordinate space, like a
      body and its inlay). By default every object is its own group
      and gets its own spot on the plate.

The tool automatically:
    1. Looks up each material's properties (temps, colors)
    2. Arranges the objects side by side on the plate (per ``group``)
       and builds a multi-object 3MF with per-object material assignments
    3. Sets the plate for its materials: the hottest one's temperatures,
       the slowest one's melt rate, the gentlest cooling
    4. Checks AMS slots for matching materials
    5. Slices and prints with correct AMS mapping

Requires PrusaSlicer or OrcaSlicer installed locally.

The emitted 3MF (``multi_material_3mf`` in the result) also opens in
Bambu Studio, which keeps the per-object materials but re-derives
print settings itself — the result's ``slicer_note`` explains this;
relay it to the user when handing over the file.

Args:
    objects_json: JSON array of objects with ``file_path`` and
        ``material_id`` keys (see example above).
    printer_name: Registered printer name in fleet.
    printer_id: Printer model ID for profile selection.
    auto_ams: Auto-detect AMS slot mapping (default ``True``).
    extra_overrides: Additional slicer overrides JSON.
    slicer_path: Explicit path to slicer binary.
merge_multicolor_gcodeA

Merge separately-sliced gcode files into one multi-tool gcode.

Uses a batched strategy that minimises tool changes for multi-color
prints.  Parts with overlapping Z ranges are printed in tool order
within the overlap zone, then remaining layers continue above.

This is the key step between slicing individual parts and wrapping
as a Bambu 3MF.  The merged gcode contains T0/T1/... tool change
commands that ``wrap_gcode_as_3mf`` converts to M620/M621 AMS
load sequences.

**Precondition:** Parts must be **XY-disjoint** (non-overlapping
footprints on the build plate).  The batched merge prints each
tool's layers independently in the overlap zone — overlapping XY
regions will cause collisions.

Args:
    parts: JSON array of part objects.  Each must have:

        - ``gcode_path``: Path to the sliced ``.gcode`` file.
        - ``tool_index``: Tool number (0, 1, ...) for AMS mapping.
        - ``name``: Human-readable name (e.g. ``"body_grey"``).

        Example::

            [
              {"gcode_path": "/path/body.gcode", "tool_index": 0, "name": "body"},
              {"gcode_path": "/path/qr.gcode", "tool_index": 1, "name": "qr_pads"}
            ]

    output_path: Output file path.  Defaults to a temp directory.

Returns a dict with ``output_path``, merge phases, layer count,
and estimated print time.
multi_color_copiesA

Print multiple copies of the same model, each in a different AMS color.

**Only a printer Kiln drives can make this print** — today a Bambu with
an AMS.  At any other printer the copies are REFUSED before slicing
with code ``MULTI_MATERIAL_NOT_DRIVEN`` (every copy would print in one
colour; the slot map below is a Bambu instruction).  The refusal
carries what Kiln saw on the printer (``multi_material``) and the
composed plate (``multi_material_3mf``) for slicing elsewhere.

Takes a single model file and produces a multi-color print where each
copy uses a different AMS filament slot.  Perfect for "print 4 lids
in 4 different colors" workflows.

**Auto-detect mode** (default): omit *copies*, *ams_slots*, and
*colors* — the tool queries the AMS, finds all loaded trays matching
*material*, and prints one copy per loaded tray.

**Manual mode**: specify *ams_slots* (and optionally *colors*) to
choose exactly which AMS trays to use and how many copies.

Requires PrusaSlicer or OrcaSlicer installed locally.  The printer
must be idle and have an AMS with loaded filament.

The emitted 3MF (``multi_color_3mf`` in the result) also opens in
Bambu Studio, which keeps the per-copy colors but re-derives print
settings itself — the result's ``slicer_note`` explains this; relay
it to the user when handing over the file.

:param model_path: Path to the model file (STL or OBJ).
:param copies: Number of copies.  Auto-detected from AMS if omitted.
:param ams_slots: The tray each copy prints from, by the printer's own
    tray id (``unit * 4 + slot`` on a chained unit, the unit id on an
    AMS HT; ``ams_status`` lists each tray's ``tray_id``).  E.g.
    ``[0, 1, 2, 3]`` for all 4 AMS Lite trays, ``[0, 5]`` for A1 and B2.
:param colors: Hex color strings per copy for slicer preview.
    E.g. ``["#FF0000", "#00FF00", "#0000FF", "#FFFF00"]``.
    Auto-read from AMS if omitted.
:param material: Material type filter for AMS auto-detect
    (default ``"PLA"``).  Only trays matching this type are used.
:param spacing_mm: Gap between copies on the plate (default 10 mm).
    Copies are arranged side by side, centered on the plate.
:param printer_id: Printer model ID for slicer profile selection and
    plate-size lookup when arranging the copies.
:param slicer_path: Explicit path to slicer binary.
:returns: Dict with print result, object details, and AMS mapping.
extract_file_metadataA

Extract metadata from a 3D printing file (.gcode, .3mf, .stl, .ufp).

Parses file headers for estimated print time, layer count, filament usage,
dimensions, slicer info, and material hints — without re-slicing.  A
project saved from Bambu Studio, OrcaSlicer or PrusaSlicer also gives the
printer, nozzle size, layer height and material it was set up for; hand
the same file to ``set_printer_model`` to set a saved printer up from it.

.. note::
    For multi-object .gcode.3mf files, also consider using
    ``list_plate_objects()`` to see individual objects on the plate.

Args:
    file_path: Path to the print file.
save_print_checkpointA

Save a checkpoint during an active print for accurate resume.

The checkpoint is keyed by ``(printer_name, job_id)`` and read
automatically by :func:`detect_print_failure` so that the resulting
:class:`FailureReport` carries known-good Z / layer / temps.  The
resume planner uses this for accurate ``resume_z_mm`` instead of
estimating from ``z_per_layer * resume_layer`` — meaningfully more
accurate when the print uses variable-layer-height slicing.

Args:
    printer_name: Name of the printer running the job.
    job_id: Unique job identifier.
    z_height: Current Z height in mm.
    layer_number: Current layer number (0-based).
    hotend_temp: Hotend temperature at checkpoint time (Celsius).
    bed_temp: Bed temperature at checkpoint time (Celsius).
    filament_used_mm: Filament consumed so far in mm.
    fan_speed_pct: Part-cooling fan speed (0-100).
    flow_rate_pct: Flow-rate multiplier (default 100).
plan_print_recoveryA

Plan a recovery strategy from a printer + job + failure type.

Convenience wrapper that synthesizes a :class:`FailureReport` from
the supplied args (using the latest checkpoint for the printer/job
when available) and runs it through the same planner used by
``plan_failure_recovery``.

**Which recovery tool to use:**

- Have a printer_name + job_id from a failed print? → ``plan_print_recovery`` (this tool)
- Have a failure_id from ``detect_print_failure``? → ``plan_failure_recovery``

Args:
    printer_name: Name of the printer that failed.
    job_id: The failed job's identifier.
    failure_type: Type of failure (thermal_runaway, layer_shift,
        adhesion_failure, filament_runout, nozzle_clog,
        communication_loss, power_loss, blob_detected, spaghetti,
        stringing, warping).  Defaults to ``communication_loss``.
firmware_resume_printA

Execute firmware-level print resume for OctoPrint+Marlin printers.

After a power loss or failure, this tool positions the printer at the
last known checkpoint and prepares it to resume printing. Uses Marlin
M413 power-loss recovery protocol: homes X/Y (never Z), re-heats bed
then hotend, sets Z position from checkpoint, primes the nozzle, and
restores fan/flow settings.

The printer will be positioned and ready after this call. Use
start_print with a re-sliced file (starting at the target layer) or
let the printer resume from its own recovery buffer.

Only works with OctoPrint printers running Marlin firmware. Moonraker/Klipper
printers should use Klipper's SAVE_VARIABLE system instead (not yet supported).

Args:
    printer_name: Name of the printer to resume on.
    job_id: The failed job's identifier (for checkpoint lookup).
    z_height_mm: Z height to resume from (from checkpoint).
    hotend_temp_c: Hotend temperature to restore.
    bed_temp_c: Bed temperature to restore.
    file_name: Original file name (for logging/tracking).
    layer_number: Layer number to resume from (informational).
    fan_speed_pct: Fan speed to restore (0-100).
    flow_rate_pct: Flow rate multiplier to restore (default 100).
    prime_length_mm: Filament to extrude for nozzle priming (mm).
    z_clearance_mm: How far above the part to raise the nozzle (mm).
check_printer_healthB

Run a comprehensive health check on a printer.

Monitors hotend/bed temperature stability, print progress, and
detects anomalies like temperature drift or unexpected shutdowns.

Args:
    printer_name: Name of the printer to check.
start_printer_health_monitoringA

Start continuous background health monitoring for a printer.

Runs periodic checks covering connectivity, temperature stability,
print job health (layer progress stalls, error codes), and active
error detection.  Alerts are generated when anomalies are found.

Kiln keeps a live watch on as many machines at once as your plan
runs — one on Free and Pro.  Checking a printer yourself is not a
watch and is never limited: ``printer_status``, ``monitor_print``
and ``printer_snapshot`` answer for any machine at any tier, and so
does stopping one.

:param printer_name: Printer to monitor.
:param interval_seconds: Seconds between health checks (default 30).

See also: ``stop_printer_health_monitoring()``,
``check_printer_health()``, ``printer_status()``.
stop_printer_health_monitoringA

Stop background health monitoring for a printer.

Cancels the periodic health-check loop started by
``start_printer_health_monitoring()``.  Active alerts are cleared.
Monitoring can be restarted at any time by calling
``start_printer_health_monitoring()`` again.

:param printer_name: Printer to stop monitoring.
analyze_print_snapshotA

Analyze a webcam snapshot for print monitoring quality.

Checks image brightness, variance, resolution, and format to determine
if the snapshot is usable for print monitoring.

Args:
    file_path: Path to the snapshot image file.
get_fulfillment_quote_cachedB

Get a cached fulfillment provider quote (or fetch fresh if expired).

Uses TTL-based caching to avoid redundant provider API calls.

Args:
    file_path: Path to the design file.
    provider: Fulfillment provider name.
    material: Material specification.
print_status_liteA

DEPRECATED — call printer_status(detail="lite") instead.

Kept so an existing caller does not break.  It now delegates, and
therefore returns ``printer_status``'s shape: nested ``printer`` /
``job`` blocks, not the flat ``completion_pct`` / ``hotend_temp``
keys this tool used to invent.  That rename was the whole problem —
two tools describing one nozzle temperature with two different words,
which is why clients grew alias lists to read either.

Args:
    printer_name: Target printer.  Omit for the default printer.
list_snapshotsA

List persisted snapshots from the database.

Returns metadata for snapshots captured during print monitoring,
timelapses, or manual captures.  Use this to review print history
visually or correlate snapshots with print outcomes.

Args:
    printer_name: Filter by printer name.
    job_id: Filter by job or timelapse ID.
    phase: Filter by capture phase (e.g. "first_layer", "timelapse", "mid_print").
    limit: Maximum records to return (default 20).
printer_trend_analysisA

Analyze local print history trends for a printer.

Uses only data already stored in the local database — nothing
leaves the machine.  Returns health score, failure rate trends,
duration trends, recurring failure modes, and material reliability.

Args:
    printer_name: Printer to analyze.
    lookback_days: How far back to look (default 30 days).
check_ambient_conditionsA

Check if the printer's chamber temperature is safe for a material.

Reads the current chamber temperature from the connected printer
and checks it against material-specific thermal limits.  Warns
about conditions like:
- Chamber too hot for PLA (softening risk)
- Chamber too cold for ABS/ASA (warping risk)
- Thermal runaway (exceeds printer safety profile max)
- Cool-down advisory after a high-temp print

All checks are local — no data leaves the machine.

Args:
    material: Filament material type (e.g. "PLA", "ABS", "PETG").
              If not provided, only checks against printer max.
decorate_surfaceA

Put any image, text, or pattern onto a 3D model surface.

For repeating patterns (wood grain, camo, honeycomb) that tile across
the entire surface, use ``apply_geometric_texture`` or
``apply_procedural_texture`` instead.  This tool is for one-off
content placement (logos, text, images).

Takes a model and content (image file, text string, SVG) and returns
a new STL with the content embossed or debossed onto the surface.
Automatically detects the best face for placement and scales content
to fit.  Single-color coin-relief style — no multi-material needed.

**Content types** (auto-detected from *content* string):

- **Image file** (PNG/JPG/SVG): ``"/path/to/photo.jpg"``
- **Text**: ``"text:KILN"`` or ``"text:Hello World"``

**Image styles** for raster images:

- ``"auto"`` — detects the image kind: a logo/wordmark/line-art
  image routes to ``"stencil"`` (crisp traced strokes); a
  continuous-tone photo routes to ``"coin"``
- ``"coin"`` — histogram-equalized posterize, best for FDM coin-relief
- ``"portrait"`` — edge-detected line art
- ``"composite"`` — posterize base + edge overlay hybrid
- ``"medallion"`` — coin + raised border ring (premium look)
- ``"photo"`` — simple 3-level posterize
- ``"stencil"`` (alias ``"logo"``) — the mark's ink is traced into
  vector strokes and carved directly: crisp edges, no background
  tile, correct orientation.  The right choice for brand logos.
- ``"lithophane"`` — full gradient for backlit prints

**Examples**::

    decorate_surface(model_path="coaster.stl", content="photo.jpg",
                     mode="deboss", depth_mm=1.5, image_style="coin")

    decorate_surface(model_path="keychain.stl", content="text:KILN",
                     face="top", depth_mm=0.5)

Requires OpenSCAD installed locally for compilation.

:param model_path: Path to the base model (STL or OBJ).
:param content: What to put on the surface — file path (PNG/JPG/SVG)
    or ``"text:..."`` for text.
:param face: Which face to decorate.  ``"auto"`` picks the largest
    flat face.  Also accepts ``"top"``, ``"bottom"``, ``"front"``,
    ``"back"``, ``"left"``, ``"right"``.  A deboss now carves into
    the body on every cardinal face, and ``offset_x/y_mm`` place
    face-locally (see below).  ``top``/``bottom``/``front`` are the
    battle-tested three; ``back`` carves and offsets correctly but
    content may still land rotated 180° (content orientation is
    unaddressed by the placement fix); on ``left``/``right`` the
    carve lands but the offset axis scaling is less verified.  Prefer
    the front-facing three when exact placement matters.
    ``"wall"`` wraps content around the upright round wall of a cup,
    jar, vase or bowl (STL, deboss only).  TEXT wraps letter by
    letter; an SVG logo or a bi-level raster mark (line art, a
    wordmark, a traced logo) wraps as a radial carve — equal arc
    length along the wall, uniform depth, placed on the plain band of
    the wall clear of any thread band, rim bead or rib.
    Continuous-tone photo relief is not wrapped (use a flat face such
    as a lid).  Content reads correctly from outside; size and carve
    depth may be adjusted to keep it readable and the wall sound, and
    the response reports what was actually used.  On the wall,
    *scale* sets letter height as a share of the wall (text) or the
    mark's width as a share of the readable 120° arc (marks), and
    *absolute_size_mm* pins the letter height / mark width exactly;
    *offset_x/y_mm* and *placement* do not apply (content sits
    centred on the front at mid-band).  The wrap engines ship with
    kiln-pro and are included on the hosted service (api.kiln3d.com)
    on every tier; without them locally, use a flat face.
:param depth_mm: Emboss/deboss depth in mm.  ``0`` = auto based on
    *material* (e.g. 0.6 mm for PLA, 1.2 mm for TPU).
:param mode: ``"deboss"`` (cut into surface) or ``"emboss"`` (raised).
:param scale: Fraction of the face to cover (0.1-1.0, default 0.7).
:param material: Material for depth auto-tuning (default ``"PLA"``).
:param content_type: Override auto-detection: ``"svg"``, ``"image"``,
    ``"text"``.  Default ``"auto"`` detects from *content*.
:param offset_x_mm: Placement offset from the face centre along the
    face's own WIDTH axis, in mm — positive slides the content
    toward the content's right.  Offsets are FACE-LOCAL: they are
    applied inside the face-aligning rotation, so they always move
    the art in the face plane, never along its normal.
:param offset_y_mm: Same, along the face's HEIGHT axis — positive
    slides the content toward the content's top.  Measured
    world-axis mapping per face: top +y, bottom −y, front +z,
    back −z.
:param image_style: Image preprocessing style.  ``"auto"`` uses
    ``"coin"`` for photos.  See docstring for all options.
:param placement: Named position preset for content placement.
    ``"center"`` (default), ``"top"``, ``"bottom"``, ``"top-rim"``,
    ``"bottom-rim"``.  Use ``"bottom"`` for text below a centered
    portrait on a coaster.  Manual ``offset_x/y_mm`` is added on
    top of the preset for fine-tuning.
:param svg_id: Target a specific SVG group by ``id`` attribute when using
    SVG ``import()`` fallback on OpenSCAD 2024+.  E.g. ``"icon"`` targets
    ``<g id="icon">``.  No effect on the native polygon path.
:param svg_layer: Target a specific SVG layer by ``layer`` attribute when
    using SVG ``import()`` fallback on OpenSCAD 2024+.  E.g.
    ``"foreground"`` targets a layer named ``foreground``.
:param template_id: Optional template ID (e.g. ``"nameplate"``), used
    for provenance tracking only.  To auto-fill ``face``, ``depth_mm``,
    ``mode``, ``scale``, and ``image_style`` from a template's curated
    decoration profile, call ``resolve_template_decoration()`` first
    (kiln-pro) and pass its results explicitly.
:returns: Dict with output STL path, preview info, and metadata.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

analyze_model_geometryA

Detect geometric regions in a 3D model that affect slicing.

Analyzes model geometry to identify overhangs, bridges, thin walls,
top/bottom surfaces, fine details, and curved surfaces.  Each region
gets optimized slicing parameters in the adaptive plan.

Args:
    model_path: Path to an STL or 3MF file for analysis.
    model_stats: Pre-computed geometry statistics dict (from slicer
        preview or external tool).  Keys include ``height_mm``,
        ``overhangs``, ``bridges``, ``thin_walls``, etc.

Provide either ``model_path`` or ``model_stats`` (or both —
``model_stats`` takes precedence).
get_material_slicing_profileA

Get material-specific slicing constraints for adaptive slicing.

Returns layer height limits, bridge/overhang parameters, fan speeds,
and other material-tuned values used by the adaptive slicer.

Args:
    material: Material name — PLA, PETG, ABS, TPU, ASA, Nylon, PC,
        PVA, or HIPS.
    nozzle_diameter_mm: Nozzle diameter in mm (affects layer height
        limits).  Leave unset for the only printer Kiln knows of,
        else 0.4; the reply's ``nozzle`` says which.
generate_adaptive_slicing_planA

Generate a per-layer adaptive slicing plan.

Creates a layer-by-layer plan with variable heights, speeds, and
cooling based on detected geometry regions and material constraints.

Args:
    regions: List of region dicts from ``analyze_model_geometry``.
        Each dict needs ``region_type``, ``z_start_mm``,
        ``z_end_mm``, and ``area_pct``.
    material: Material name (PLA, PETG, ABS, etc.).
    model_height_mm: Total model height in mm.
    model_name: Optional model name for record keeping.
    printer: Optional printer identifier.
    nozzle_diameter_mm: Nozzle diameter in mm.  Leave unset for the
        nozzle Kiln has for ``printer`` (or the only printer it knows
        of), else 0.4; the reply's ``nozzle`` says which.
    mode: Adaptive strategy — "balanced" (default), "quality_first",
        "speed_first", or "material_optimized".
export_adaptive_slicer_configA

Export an adaptive slicing plan as slicer-compatible configuration.

Converts a plan to the target slicer's format — PrusaSlicer and
OrcaSlicer use variable layer height data, Cura uses adaptive
layers plugin format.

Args:
    plan_data: Plan dict from ``generate_adaptive_slicing_plan``.
    slicer: Target slicer — "prusaslicer", "orcaslicer", "cura",
        or "generic".
estimate_adaptive_time_savingsA

Compare adaptive plan time savings vs uniform layer height.

Shows layer count reduction, estimated time savings, and percentage
improvement.

Args:
    plan_data: Plan dict from ``generate_adaptive_slicing_plan``.
    uniform_height_mm: Reference uniform layer height for comparison
        (default 0.2mm).
quick_adaptive_planA

All-in-one adaptive slicing: analyze geometry + generate plan.

Convenience tool that combines geometry analysis and plan generation
in a single call.  Ideal when you have basic model info and want a
quick adaptive plan without multiple tool calls.

Args:
    material: Material name (PLA, PETG, ABS, etc.).
    model_height_mm: Total model height in mm.
    model_name: Optional model name.
    nozzle_diameter_mm: Nozzle diameter in mm.  Leave unset for the
        nozzle Kiln has for ``printer`` (or the only printer it knows
        of), else 0.4; the reply's ``nozzle`` says which.
    mode: Adaptive strategy — "balanced", "quality_first",
        "speed_first", or "material_optimized".
    printer: Optional printer identifier.
    regions: Optional list of region dicts.  If omitted, a default
        STANDARD region spanning the full height is used.
list_supported_materialsA

List all materials with adaptive slicing profiles.

Returns material names with their key slicing constraints (layer height limits, bridge parameters, overhang angles).

get_adaptive_plan_summaryA

Generate a human-readable summary of an adaptive slicing plan.

Args:
    plan_data: Plan dict from ``generate_adaptive_slicing_plan``
        or ``quick_adaptive_plan``.

Returns a structured summary with key metrics and region breakdown.
ams_filament_dryingA

Start or stop an AMS 2 Pro / AMS HT active dry cycle.

Bambu printers with an AMS 2 Pro or AMS HT dry filament in place.
This controls that dryer.

To START (``mode=1``): set ``temp_c`` (drying temperature),
``duration_min`` (> 0), and ``cooling_temp_c`` -- which must be
>= 45, or the printer silently ignores the command.  A start is
checked against the unit's own ceiling (AMS 2 Pro 65 C, AMS HT 85 C)
before it is sent; when Kiln cannot run that check, nothing is sent and
the answer says why.  To STOP (``mode=0``): only ``ams_id`` is needed,
and a stop is always sent.

Only Bambu printers with an AMS 2 Pro / AMS HT support this; other
printers and plain AMS / AMS Lite units return an error.

:param ams_id: AMS unit index (0-based).
:param mode: 1 to start drying, 0 to stop.
:param duration_min: Dry-cycle length in minutes (> 0 to start).
:param temp_c: Drying temperature in C (required to start; capped
    at the unit's max -- AMS 2 Pro 65 C, AMS HT 85 C).
:param cooling_temp_c: Cooldown temperature in C (>= 45 to start).
:param humidity: Optional target humidity.
:param rotate_tray: Optional tray-rotation flag.
:param printer_name: Target printer.  Omit for the default printer.
:returns: Dict with the dispatched command and a status message.
create_assemblyB

Create a new empty assembly.

        Returns the assembly state as a JSON-serialisable dict that
        must be passed back to subsequent assembly tools.

        Args:
            name: Human-readable name for the assembly.
        
add_assembly_partB

Add a part to an existing assembly.

        Parses the assembly from its JSON representation, appends
        the new part, and returns the updated assembly state.

        Args:
            assembly_json: JSON string of the current assembly state
                (as returned by create_assembly or a previous tool call).
            part_id: Unique identifier for this part within the assembly.
            file_path: Path to the STL/OBJ mesh file for the part.
            position_x: X position offset in mm (default 0.0).
            position_y: Y position offset in mm (default 0.0).
            position_z: Z position offset in mm (default 0.0).
            material: Filament material for the part (default ``"PLA"``).
            role: Structural role of the part (default ``"structural"``).
        
add_assembly_interfaceA

Add a mating interface between two parts in an assembly.

        Defines how two parts connect (joint type and clearance),
        which is used during validation and clearance checking.  For
        screw/anchor-based joints, ``fastener`` may provide an
        explicit hardware spec so downstream manuals and BOM tools do
        not have to guess from clearance alone.

        Args:
            assembly_json: JSON string of the current assembly state.
            part_a_id: ID of the first part in the interface.
            part_b_id: ID of the second part in the interface.
            joint_type: Type of joint (default ``"clearance_fit"``).
            clearance_mm: Clearance gap in mm (default 0.2).  For
                ``"interference_fit"`` pass a NEGATIVE value (the
                part is intentionally larger than its socket);
                interference geometry is the entire point.
            magnet_polarity_aligned: Only meaningful when
                ``joint_type == "magnetic"``.  ``True`` declares
                the designer has confirmed which poles face each
                other in each magnet pocket; ``None`` means
                unknown.  Downstream tooling refuses to ship a
                hand-wavy "make sure they pull together"
                instruction when polarity is unknown.
            fastener: Optional FastenerSpec as a dict or JSON object
                string.  Supported keys include ``size``, ``family``,
                ``length_mm``, ``length_range_mm``, ``head_type``,
                ``drive_type``, ``surface_type``,
                ``quantity_per_interface``, and ``notes``.
        
validate_assemblyA

Validate an assembly for correctness and printability.

        Runs clearance checks and joint validations on the assembly,
        returning the validated assembly state with results populated.

        Args:
            assembly_json: JSON string of the current assembly state.
            printer_id: Optional printer identifier (e.g.
                ``"bambu_a1"``).  When supplied AND kiln-pro is
                installed, each joint that drives a screw into a
                printed part gains a ``screw_hole`` block with the
                compensated hole diameter, thread engagement,
                install-torque ceiling, and lead-in chamfer
                (Bambu-calibrated on Bambu X1/P1/A1 + PLA/PETG; a
                generic starting point otherwise).  Omit it to keep
                the historic behaviour.
        
check_assembly_clearancesB

Check clearances between all mating parts in an assembly.

        Returns a list of clearance check results indicating whether
        each interface meets its clearance requirements.

        Args:
            assembly_json: JSON string of the current assembly state.
            default_clearance_mm: Default clearance gap in mm to use
                when an interface does not specify one (default 0.2).
        
compose_assembly_partsA

Compose all assembly parts into a single output STL file.

        Merges the individual part meshes according to their
        positions and writes the combined model to ``output_path``.

        Args:
            assembly_json: JSON string of the current assembly state.
            output_path: File path where the composed STL will be written.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

get_joint_recommendationA

Get recommended clearance settings for a joint type and material pairing.

        Returns clearance recommendations based on the joint type
        and the materials of the two mating parts.  When
        ``printer_id`` is supplied AND kiln-pro is installed, the
        response narrows the clearance range by the user's
        calibration tier (HIGH halves it, MEDIUM shaves ~10%, LOW
        and UNKNOWN leave it unchanged) and attaches a
        ``calibration_used`` block documenting the source.

        Args:
            joint_type: Type of joint (e.g. ``"clearance_fit"``,
                ``"press_fit"``, ``"snap_fit"``).
            material_a: Material of the first part (default ``"PLA"``).
            material_b: Material of the second part (default ``"PLA"``).
            printer_id: Optional printer identifier (e.g.
                ``"bambu_a1"``).  For a joint whose parts MOVE, omitting
                it resolves the user's active printer rather than
                answering generically — pass it only to ask about a
                machine that is not the one they are set up on.  For
                every other joint type, omitting it keeps the historic
                flat-range behaviour.
            mating: Optional shape hint for joints whose parts MOVE
                against each other (``"clearance_fit"``, ``"loose"``):
                ``"pin_in_bore"`` for a shaft or pin turning in a hole,
                ``"slot"`` for a tongue sliding in a groove,
                ``"planar_face"`` for two flat faces sliding, or
                ``"gear_flank"`` for meshing teeth.  Omit it and the
                round-joint case is assumed, which is the erring-loose
                reading — a bore is closed on from both sides and needs
                about twice the allowance a flat gap does, so assuming
                it can only give a joint too much room, never too
                little.  Ignored for joints that do not move.
        
kiln_signinA

Start a Kiln sign-in via OAuth.

        Returns a URL the user can open in their browser to sign in
        with Google / Apple / GitHub.  Relay the ``verification_uri``
        to the user and then call ``kiln_signin_poll(device_code)``
        every few seconds until the status is no longer ``"pending"``.

        Response fields (all strings unless noted):

        * ``verification_uri`` — URL to open in the browser; the
          ``user_code`` is already embedded as a query param so the
          user typically doesn't have to type anything.
        * ``user_code`` — the short human-readable code
          (``KLN-ABCD-EFGH``); show it only as a fallback in case
          the verification URL didn't pre-fill it.
        * ``device_code`` — secret; pass to ``kiln_signin_poll``,
          never show to the user.
        * ``interval`` (int) — seconds to wait between polls
          (default 2).
        * ``expires_in`` (int) — seconds the code is valid for
          (900 = 15 minutes).

        A free Kiln account adds a cloud design library with share
        links plus the free monthly allowance of Kiln's hosted
        tools.  Free tier — no license key required; this is the
        very first call an unauthenticated user makes.
        
kiln_signin_pollA

Check whether a sign-in started by kiln_signin is done.

        Call this repeatedly (every ``interval`` seconds) with the
        ``device_code`` that ``kiln_signin`` returned.  Each call is a
        single HTTP round-trip (it does NOT block), so the agent stays
        responsive and the user sees progress.

        Returns ``{"status": "pending" | "success" | "denied" |
        "expired", ...}``.

        * ``pending`` — user hasn't finished in the browser yet;
          wait ``interval`` seconds and call again.
        * ``success`` — tokens have been written to
          ``~/.kiln/auth_tokens.json`` (mode 0600); the response
          also echoes ``email`` and ``tier``.  Every other Kiln tool
          picks up the new session automatically.
        * ``denied`` — user cancelled in the browser.
        * ``expired`` — the device_code timed out (15 min window);
          call ``kiln_signin`` again for a fresh code.

        Free tier — no license key required.
        
cache_modelA

Add a 3D model file to the local cache for reuse across jobs.

        Copies the file into ``~/.kiln/model_cache/`` and stores metadata
        (source, prompt, tags, dimensions) in the database.  Duplicate files
        are detected automatically by SHA-256 hash.

        Args:
            file_path: Path to the model file on disk.
            source: Origin — ``"thingiverse"``, ``"myminifactory"``, ``"meshy"``,
                ``"openscad"``, ``"upload"``, etc.
            source_id: Marketplace thing ID or generation job ID.
            prompt: For generated models, the text prompt used.
            tags: Comma-separated tags (e.g. ``"benchy,calibration,test"``).
            dimensions: JSON object with bounding box in mm, e.g.
                ``'{"x": 60, "y": 31, "z": 48}'``.
            metadata: Optional JSON object with extra data.
        
search_cached_modelsA

Search the local model cache by name, source, tags, or prompt text.

        Args:
            query: Free-text search against file name, prompt, and tags.
            source: Filter by source (e.g. ``"thingiverse"``).
            tags: Comma-separated tags to filter by.
            limit: Maximum results (default 20).

        The response declares its ``scope``: this cache is local to
        this machine, so the count is what THIS install has cached,
        not everything the user has ever downloaded or generated.
        
get_cached_modelC

Return details for a specific cached model.

        Args:
            cache_id: The unique cache ID of the model.
        
list_cached_modelsB

List all models in the local cache, newest first.

        Args:
            limit: Maximum results (default 50).
            offset: Number of entries to skip for pagination.

        The response declares its ``scope``: this cache is local to
        this machine, so the count is what THIS install has cached,
        not everything the user has ever downloaded or generated.
        It is also a page — ``limit``/``offset`` bound it further.
        
delete_cached_modelA

Remove a model from the local cache (file and metadata).

        Args:
            cache_id: The unique cache ID of the model to delete.
        
cache_designC

Cache a 3D design file for faster access and version tracking.

        Args:
            file_path: Path to the design file to cache.
            label: Human-readable label for the cached design.
            material: Intended material for this design.
        
list_cached_designsA

List cached designs, optionally filtered by material.

        Args:
            material: Filter by material (e.g. "PLA", "PETG").
            limit: Maximum number of results.

        Most recently used designs come first.

        The response declares its ``scope``: which store was read.
        The cache is local-only at every tier (regenerable files,
        no cloud copy), so a complete local read is the whole
        cache.
        
get_cached_designC

Retrieve a cached design by ID.

        Args:
            design_id: The cached design's identifier.
        
cloud_sync_statusA

Get the current cloud sync status.

cloud_sync_nowA

Trigger an immediate cloud sync cycle.

cloud_sync_configureC

Configure and start cloud sync.

        Args:
            cloud_url: Base URL of the cloud sync endpoint.
            api_key: API key for authentication.
            interval: Sync interval in seconds (default 60).
        
auto_color_by_heightA

Split a 3D model into horizontal color zones by Z-height.

        Divides the model's height into N equal bands.  Faces that
        cross a band edge are cut exactly at it, so the line where two
        colors meet is the straight horizontal line the bands name —
        never a sawtooth of whole faces, on any tessellation.  The
        cut faces are capped at the band planes, so each zone of a
        closed model is itself a closed solid ready to slice.
        Produces separate STL files per zone and (if available) a
        multicolor 3MF ready for AMS/MMU printers.

        Zero cloud dependencies — pure geometry.

        Says whether its colours are on the printer, as
        ``colour_availability`` (absent when Kiln cannot see what is
        loaded).  Relay its ``say`` as written and add nothing about
        filament: never suggest buying filament unless the person asks
        for one or says yes to the offer in ``say``.  On a yes, call
        ``find_closest_filaments`` with these colours and the print's
        material.

        :param input_path: Path to a binary STL file.
        :param num_colors: Number of color zones (default 4).
        :param color_palette: List of hex colors (e.g.
            ``["#FF0000", "#00FF00"]``).  Defaults to white/red/black/grey.
        :param material: Optional material the part will be printed in
            (e.g. ``"PETG"``).  A spool on record in a clearly
            different material is then not named as one to load.
        :param printer_id: Optional supported printer model id.  Names
            the bed the composed 3MF is placed on, so a model sitting
            off the plate is centred on the machine's real bed rather
            than an assumed 256mm one.
        :returns: Dict with zone STL paths, hex colors, face counts
            (boundary faces are cut and capped, so counts can exceed
            the input's), per-zone ``watertight`` verdicts, AMS slot
            mapping, weight estimates, and optional 3MF path.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

auto_color_by_regionA

Split a 3D model into color zones by geometric region.

        Supports multiple assignment methods:
          - ``"z_height"``: horizontal bands by Z-height (default) —
            faces crossing a band edge are cut exactly at it and the
            cuts are capped, so the color boundary is a straight line
            on any tessellation and each zone of a closed model is
            itself a closed solid ready to slice
          - ``"normal"``: group by face normal direction
            (top / bottom / sides)
          - ``"random"``: random face assignment for artistic prints

        The 3MF takes whichever form actually prints: z_height bands
        become one closed solid per color; normal/random colorings
        follow the surface, so the mesh stays ONE watertight object
        with the colors painted per triangle — slicers that support
        color import (BambuStudio, OrcaSlicer) offer to map each
        color to a filament on open.

        Zero cloud dependencies — pure geometry.

        Says whether its colours are on the printer, as
        ``colour_availability`` (absent when Kiln cannot see what is
        loaded).  Relay its ``say`` as written and add nothing about
        filament: never suggest buying filament unless the person asks
        for one or says yes to the offer in ``say``.  On a yes, call
        ``find_closest_filaments`` with these colours and the print's
        material.

        :param input_path: Path to a binary STL file.
        :param num_colors: Number of color zones (default 4).
        :param method: Assignment method — ``"z_height"``,
            ``"normal"``, or ``"random"``.
        :param color_palette: List of hex colors.  Defaults to
            white/red/black/grey.
        :param material: Optional material the part will be printed in
            (e.g. ``"PETG"``).  A spool on record in a clearly
            different material is then not named as one to load.
        :param printer_id: Optional supported printer model id.  Names
            the bed the composed 3MF is placed on, so a model sitting
            off the plate is centred on the machine's real bed rather
            than an assumed 256mm one.
        :returns: Dict with zone STL paths, hex colors, face counts,
            AMS slot mapping, weight estimates, and optional 3MF path.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

paint_decoration_facesA

Paint exactly the faces a decoration carve created (Pro-free).

        A deboss/emboss records which output triangles it created —
        recess floors and side-walls — in a face-provenance sidecar
        beside the decorated mesh.  This tool paints THOSE faces and
        nothing else, so a debossed logo with a closed outline (any
        mark with enclosed regions) colors only its carved strokes:
        the untouched surface island inside the outline stays the
        body color, where crease-angle segmentation would have
        "filled the logo in".

        Use after any decoration door (``decorate_surface``,
        ``apply_decoration``, ``apply_decoration_preset``,
        ``smart_decorate``, ``batch_decorate``…) — they all record
        the sidecar.  For meshes with no sidecar (older files,
        hand-made carves), fall back to ``segment_mesh_regions`` +
        ``paint_mesh_regions``.

        Writes a painted 3MF (one watertight object, per-triangle
        colors) via the same composer ``paint_mesh_regions`` uses,
        so the output slices identically.  A successful paint is
        also written back into the carve's face record (color,
        target, output file) so the design's provenance says
        "carved, then painted" — ``paint_recorded`` in the result
        reports whether that write-back landed.

        Says whether its colours are on the printer, as
        ``colour_availability`` (absent when Kiln cannot see what is
        loaded).  Relay its ``say`` as written and add nothing about
        filament: never suggest buying filament unless the person asks
        for one or says yes to the offer in ``say``.  On a yes, call
        ``find_closest_filaments`` with these colours and the print's
        material.

        :param model_path: The decorated mesh (STL/OBJ/3MF) whose
            ``<mesh>.decoration_faces.json`` sidecar to consume.
        :param color: Hex color for the carved faces (default red).
        :param base_color: Optional hex color for every other face.
            Empty = uncolored (renders neutral; slicer maps it to
            the base filament).
        :param target: ``"all"`` carved faces (default), or
            ``"floors"`` / ``"walls"`` when the record carries the
            split — floors are the recess bottoms (the visible mark),
            walls the carved sides.
        :param step_colors: Per-decoration colors for a chained
            carve, e.g. ``{"0": "#F72323", "1": "#FFFFFF"}`` — keys
            are step indices from the record's ``decorations`` list
            (every result of this tool lists them).  When given it
            is the COMPLETE paint spec: only the named steps are
            painted, the rest stay base — so "name red, title left
            plain" is one call.  Incompatible with a floors/walls
            ``target``; ``color`` is ignored.
        :param output_path: Where to write the painted 3MF.  Default:
            beside the model as ``<name>_painted.3mf``.
        :param material: Optional material the part will be printed in
            (e.g. ``"PETG"``).  A spool on record in a clearly
            different material is then not named as one to load.
        :param printer_id: Optional supported printer model id for
            bed placement of the composed 3MF.
        :returns: Dict with ``output_path``, ``painted_triangles``,
            ``total_triangles``, and the composer's color summary.
            Refuses loudly — no painting — when the sidecar is
            missing, malformed, or STALE (mesh content changed since
            the decoration was recorded).
        
tax_estimateA

Preview the complete price breakdown — including tax — before placing an order.

        Terms §7 contract: "Preview the tax for any order with the
        ``tax_estimate`` tool before placing it.  We display the full
        fee + tax breakdown before charging.  No hidden fees."

        This tool fulfills that contract by returning the same line
        items the order will commit to at charge time.  Per Terms §7
        tax is computed on the orchestration fee ONLY — never on
        the manufacturer's quoted total.  The manufacturer is
        responsible for any taxes on their own charges.

        Two calling shapes are supported:

        1. **Canonical preview** (recommended): pass
           ``manufacturer_quote_usd`` and the tool returns the
           full breakdown — ``manufacturer_quote``,
           ``orchestration_fee``, ``tax_on_fee``, ``total`` — so
           the agent can show the user the exact line items that
           match the eventual charge.  This is the shape Terms §7
           commits to.
        2. **Tax-only legacy** (compatibility): pass ``fee_amount``
           with no ``manufacturer_quote_usd`` and the tool returns
           the older ``{tax: {...}}`` shape, useful for callers
           that already know the fee and only want the tax line.

        Args:
            fee_amount: Legacy — the platform fee amount (from the
                quote's ``kiln_fee``).  Used only when
                ``manufacturer_quote_usd`` is omitted.
            jurisdiction: Where the buyer is located (e.g.
                ``"US-CA"``, ``"DE"``, ``"AU"``).  Use
                ``tax_jurisdictions`` to see all supported codes.
                When empty in canonical-preview mode, no tax is
                applied (preview shows manuf + fee only).
            business_tax_id: If the buyer is a business, their tax
                ID (e.g. EU VAT number).  In the EU, UK, Australia,
                and Japan, businesses are exempt — the tax line
                shows $0.00 with a note that reverse charge
                applies.
            manufacturer_quote_usd: Provider's quoted price (e.g.
                from ``fulfillment_quote``).  When non-zero,
                triggers canonical-preview mode.
            currency: Currency of the manufacturer quote (default
                USD).  Tax rates are applied at the standard
                jurisdiction rate regardless.
            user_email: Buyer's email — affects the free-tier
                waiver (first 3 fulfillment orders/month per user
                are fee-free).  Available in canonical mode only.

        Returns:
            Canonical mode (``manufacturer_quote_usd > 0``):
                ``{success, manufacturer_quote, orchestration_fee,
                tax_on_fee, total, currency, fee_waived,
                fee_waiver_reason, tax_jurisdiction,
                tax_rate_percent, tax_reverse_charge, note}``.
            Legacy mode (``manufacturer_quote_usd == 0``):
                ``{success, tax: {...}}``.

        Read-only — charges no card, contacts no provider.
        
tax_jurisdictionsA

List all 22 supported regions so the agent can match the user's location.

        Returns jurisdiction codes, tax types, and rates for the US (8 states),
        EU (7 countries), UK, Canada (4 provinces), Australia, and Japan.
        Pass the matching code to ``fulfillment_order`` or ``tax_estimate``
        to include tax in the price breakdown.
        
tax_jurisdiction_lookupA

Look up tax details for a specific region (rate, type, B2B exemptions).

        Args:
            code: Jurisdiction code (e.g. "US-CA", "DE", "GB", "AU").
                Use ``tax_jurisdictions`` to browse all codes.
        
donate_infoA

Get crypto wallet addresses to tip/donate to the Kiln project.

Kiln is free, open-source software. This tool returns wallet addresses (with ENS/SNS domains) where users can send tips in SOL, ETH, USDC, or other tokens to support development.

No payment is required -- Kiln is fully functional without donating.

consumer_onboardingA

Get the guided onboarding workflow for users without a 3D printer.

Returns a step-by-step guide covering model discovery/generation, material recommendations, pricing, ordering, and delivery tracking. Perfect for first-time users who want to manufacture a custom part.

validate_shipping_addressA

Validate and normalize a shipping address for fulfillment orders.

        Args:
            street: Street address (e.g. "123 Main St").
            city: City name.
            country: ISO 3166-1 alpha-2 country code (e.g. "US", "GB", "DE").
            state: State/province (recommended for US addresses).
            postal_code: ZIP/postal code (validated per country format).

        Checks required fields, validates postal codes per country (US ZIP,
        Canadian postal, UK postcode), and returns warnings for missing optional
        fields.  Use the ``normalized`` address in the response when placing
        fulfillment orders.
        
suggest_material_for_orderA

Suggest a material when ordering a print from a fulfillment provider.

        Use this when routing a print job to a fulfillment provider
        and need to pick the right material + technology for the order.

        **Which material tool to use:**

        - Ordering a print from a service? → ``suggest_material_for_order`` (this tool)
        - Designing a part and need engineering specs? → ``recommend_design_material``
        - Quick intent-based pick for your own printer? → ``recommend_material``

        Args:
            use_case: What the part is for. Options: decorative, functional,
                mechanical, prototype, miniature, jewelry, enclosure, wearable,
                outdoor, food_safe.
            budget: Price preference: "budget", "mid", or "premium". Empty = any.
            need_weather_resistant: Only recommend weather-resistant materials.
            need_food_safe: Only recommend food-safe materials.
            need_high_detail: Prefer high-detail materials (SLA/MJF).
            need_high_strength: Prefer high-strength materials (SLS/MJF).

        Returns ranked material recommendations with technology, reasoning,
        price tier, and which fulfillment provider to use.
        
estimate_priceA

Get an instant price estimate before requesting a full quote.

        Args:
            technology: Manufacturing technology: FDM, SLA, SLS, MJF, or DMLS.
            volume_cm3: Part volume in cubic centimeters (if known).
            dimensions_x_mm: Bounding box X dimension in mm (alternative to volume).
            dimensions_y_mm: Bounding box Y dimension in mm.
            dimensions_z_mm: Bounding box Z dimension in mm.
            quantity: Number of copies (default 1).

        Returns a low/high price range based on typical per-cm3 pricing for
        the technology.  For exact pricing, use ``fulfillment_quote`` with a
        real model file.

        Either ``volume_cm3`` or all three dimension parameters must be provided.
        
estimate_timelineA

Estimate order-to-delivery timeline with per-stage breakdown.

        Args:
            technology: Manufacturing technology (FDM, SLA, SLS, MJF, DMLS).
            shipping_days: Known shipping days from a quote (optional).
            quantity: Number of copies (larger quantities add production time).
            country: Destination country code for shipping estimate fallback.

        Returns a stage-by-stage timeline (order confirmation, production,
        quality check, packaging, shipping) with estimated days per stage
        and a total delivery date.
        
supported_shipping_countriesA

List all countries supported for fulfillment shipping.

Returns ISO country codes and full names for all 23+ countries where Kiln fulfillment providers can ship manufactured parts.

store_credentialA

Encrypt and store a credential (API key, webhook secret, etc.).

        The value is encrypted at rest using PBKDF2 + XOR stream encryption.
        Only metadata is returned — the plaintext is never exposed.

        Args:
            credential_type: Type of credential (api_key, webhook_secret,
                stripe_key, marketplace_token, printer_password).
            value: The plaintext secret to store.
            label: Human-readable description.
        
list_credentialsA

List all stored credentials (metadata only, no plaintext).

retrieve_credentialB

Decrypt and return a stored credential.

        Args:
            credential_id: The credential's unique identifier.
        
save_decorationA

Save a proven decoration to the library for reuse on future models.

        Captures the content file (heightmap, SVG, image), settings
        (depth, mode, material), and processing pipeline from the
        ``.kiln_recipe.json`` sidecar so the exact same decoration can
        be applied to new models with ``apply_decoration``.

        :param name: Human-readable name (e.g. "Ash Portrait").
        :param model_path: Path to the model that was just decorated.
        :param content_type: Content type — ``photo``, ``svg``, ``qr``,
            ``text``, or ``auto`` (detect from file extension).
        :param source_path: Path to the original input file (photo, SVG).
        :param content_data: For QR: the data string. For text: the text.
        :param depth_mm: Decoration depth in mm (0 = auto from recipe).
        :param mode: ``emboss`` or ``deboss``.
        :param image_style: Image processing style (coin, portrait, etc.).
        :param material: Material used (e.g. PLA, PETG).
        :param tags: Comma-separated tags for filtering.
        :returns: Dict with saved decoration details and library path.
        
list_decorationsA

List all saved decorations in the library.

        Browse the decoration library to find reusable decorations.
        Filter by content type, category, or tag.

        :param content_type: Filter by type — ``photo``, ``svg``, ``qr``,
            ``text``, ``procedural_texture``, ``ai_texture``
            (empty = show all).
        :param category: Filter by category — ``surface`` (photo/svg/qr/text)
            or ``texture`` (procedural/AI textures).  Empty = show all.
        :param tag: Filter by tag (empty = show all).
        :returns: Dict with decoration count and list.

        This is the decoration LIBRARY: keyed by name, and it ADAPTS —
        each recorded success stores proven settings for THAT material,
        so applying picks the depth and mode your prints proved for
        whatever you are printing in now.  It keeps no version history.

        Kiln's other kind of saved decoration is a decoration PRESET
        (kiln-pro; what the web's /decorations pages show): keyed by an
        id because it has versions, branches and signed releases, and
        applied at the exact settings its version recorded rather than
        adapting to the material.  Listed by ``list_decoration_presets``,
        applied by ``apply_decoration_preset``.  The library adapts, the
        preset remembers — if what you want isn't here, look there.

        The response declares its own SCOPE.  The library is
        local-only at every tier — the web's /decorations pages are
        the decoration PRESET store above, not a cloud copy of this
        one — so a complete local read here is the whole library,
        and ``scope`` says exactly that.
        
apply_decorationA

Apply a saved decoration to a new model — proven settings, one call.

        Loads a previously saved decoration and applies it to the target
        model using the exact settings that worked before.  Automatically
        resolves depth, mode, and image style from the proven recipe.

        This is the magic tool — decorations that took many iterations
        to perfect can be replayed on any model in one call.

        :param name: Decoration name or slug.
        :param model_path: Path to the target model (STL or OBJ).
        :param material: Override material (empty = use proven or detect
            from printer).
        :param face: Which face to decorate (auto, top, bottom, etc.).
        :param printer_id: Optional printer ID for material detection.
        :returns: Dict with decorated model path and settings used.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

decoration_infoA

Get full details about a saved decoration.

        Shows the decoration's proven settings, content paths, tags,
        processing pipeline, and library location.

        :param name: Decoration name or slug.
        :returns: Dict with full decoration details and file paths.
        
decoration_quota_statusA

Check your decoration quota — how many decorations you've used this month.

Free-tier users get 3 decorations per calendar month. Every paid tier has unlimited decorations.

Returns used count, limit, remaining, tier, and current month.

record_decoration_successA

Record a successful print with a saved decoration (Kiln Pro).

        After a decoration prints well, call this with the settings that
        worked.  ``apply_decoration`` then replays them on that material.

        :param name: Decoration name or slug.
        :param material: Material used (e.g. ``"PLA"``, ``"PETG"``).
        :param depth_mm: Depth in mm that printed well.
        :param mode: ``"emboss"`` or ``"deboss"``.
        :param image_style: Image style that worked (e.g. ``"coin"``).
        :param source_job_id: The print's job id when known: the same
            print reported twice (here and through
            ``record_print_outcome``) counts once.
        :returns: Dict with the updated decoration.
        
iterate_decorationA

Create a new version of a saved decoration, archiving the current one (Kiln Pro).

        Use this when tuning a decoration -- a new depth, mode, style or
        content file -- and the previous version stays available for
        ``rollback_decoration``.

        :param name: Decoration name or slug.
        :param content_path: New content file (empty = keep current).
        :param depth_mm: New depth in mm (0 = keep current).
        :param mode: New mode (empty = keep current).
        :param image_style: New image style (empty = keep current).
        :param notes: Free-text notes for this iteration.
        :returns: Dict with the new version and what changed.
        
decoration_historyA

Get every version of a saved decoration (Kiln Pro).

        Each version with when it was made, what changed, the materials
        it has printed well on and its print count.

        :param name: Decoration name or slug.
        :returns: Dict with the version history and the current version.
        
rollback_decorationA

Restore an earlier version of a saved decoration (Kiln Pro).

        The current version is archived and the earlier one comes back
        as a NEW version number, so history is never rewritten.

        :param name: Decoration name or slug.
        :param version: Version number to restore.
        :returns: Dict with the restored decoration.
        
analyze_structural_risksA

Analyze an STL mesh for structural weak points.

        Goes beyond printability to find **structural** risks:
        - **thin_neck**: narrow cross-sections that will snap under load
        - **stress_concentration**: abrupt section changes that focus stress
        - **cantilever**: unsupported overhanging geometry
        - **sharp_corner**: concave edges that initiate cracks
        - **insufficient_base**: topple risk from height-to-base ratio
        - **weak_layer_adhesion**: overhangs in structurally critical areas

        Returns risk locations as (x, y, z) coordinates in mm so agents
        can reason about *where* problems are, not just *that* they exist.

        :param file_path: Path to the STL file.
        :param min_cross_section_mm2: Minimum safe cross-section area (default 4).
        :param sharp_angle_threshold_deg: Angle for sharp edge detection (default 60).
        :returns: Dict with ``risks`` list, each containing location, severity, and description.
        
recommend_design_reinforcementsB

Recommend specific reinforcements for an STL mesh.

        Analyzes geometry to find structural risks, then generates actionable
        recommendations with **specific locations** and what each one does for the part:
        - **gusset**: triangular support at cantilever bases
        - **fillet**: smooth transitions at stress concentrations
        - **thicken_wall**: add material at thin necks
        - **add_base**: widen the base for stability
        - **reorient**: change print orientation for layer strength

        Each recommendation includes the coordinates where the reinforcement
        should be applied and which Kiln tool to use (e.g., ``add_mesh_fillet()``).

        :param file_path: Path to the STL file.
        :param min_cross_section_mm2: Minimum safe cross-section area.
        :returns: Dict with ``reinforcements`` list.
        
assess_load_bearingA

Analyze load-bearing characteristics of a mesh from its geometry.

        Infers structural behavior by analyzing surface normals, shape type,
        and cross-section distribution:
        - **primary_load_axis**: which direction the part resists force
        - **load_surfaces**: which surfaces bear load (with area fractions)
        - **weak_axis**: the most vulnerable direction for failure
        - **recommended_print_orientation**: how to orient for maximum strength
        - **layer_direction_concern**: how FDM layers affect structural integrity

        This is the difference between "PLA is good for prototypes" (lookup)
        and "this bracket should be printed on its side because the load path
        crosses layer boundaries" (geometric reasoning).

        :param file_path: Path to the STL file.
        :returns: Dict with load analysis.
        
design_improvement_planA

Generate a complete structural improvement plan for a design.

        The **full design reasoning pipeline** — combines risk analysis,
        reinforcement recommendations, and load analysis into one actionable
        report with an overall structural score (0-100, A-F grade).

        This is the tool that makes Kiln a **design advisor**, not just a
        geometry validator. It answers: "This bracket needs a gusset at the
        load point" — not just "the part has thin walls."

        The plan includes:
        1. **Risks**: all structural weak points with locations and severity
        2. **Reinforcements**: specific fixes and what each does for the part
        3. **Load analysis**: how the part handles forces, best print orientation
        4. **Score**: overall structural grade with summary

        :param file_path: Path to the STL file.
        :param min_cross_section_mm2: Minimum safe cross-section area.
        :param sharp_angle_threshold_deg: Angle for sharp edge detection.
        :returns: Complete improvement plan as dict.
        
apply_design_reinforcementsA

Analyze a part for structural risks, then auto-apply fixes.

        This is the **one-step design hardening tool** — it runs the full
        structural analysis pipeline, then applies every applicable fix:

        - **Thin necks** → thickened walls (+material at narrow sections)
        - **Sharp corners** → rounded edges (stress concentration reduced at inside corners)
        - **Insufficient base** → wider base plate (stabilizing geometry added)
        - **Cantilevers** → triangular gusset ribs

        Thickening and edge rounding are done on the part's CAD file, so
        pass its STEP file when there is one (or a mesh Kiln converted
        from one that still sits beside it).  When every fix applied was
        a CAD one the result carries ``step_path``, the reinforced part as
        CAD.  On a mesh with no CAD file, edge rounding is skipped with
        the reason.

        Edge rounding is sized for the printer: name it (or the nozzle,
        layer height and material) and each rounded edge keeps one nozzle
        width of flat beside it.  Each rounded entry's ``edges`` lists
        what was finished, what stayed sharp and why, and ``cautions``
        for edges that will print badly; ``print_aware`` sums it up.
        Choosing the finish edge by edge for the printer and material is
        a Kiln Pro feature (https://kiln3d.com/pricing).

        Returns a before/after structural score so agents can see the
        improvement.  Reinforcements that can't be auto-applied (like
        ``reorient``) are listed in ``skipped`` with guidance.

        Requires OpenSCAD for base plate and gusset operations.

        AGENT DISPLAY CONTRACT: a result carries a before|after self-check
        of the part.  Look at it and write what changed before calling
        the job done.

        :param file_path: The part: an STL, or its STEP file.
        :param output_path: Output path (defaults to ``<name>_reinforced.stl``).
        :param fillet_radius_mm: Fillet radius for sharp corners (default 1.5).
        :param wall_thicken_mm: Amount to add to thin walls (default 0.6).
        :param base_height_mm: Height of stabilizing base plate (default 2.0).
        :param printer_id: The printer the part is for.
        :param nozzle_mm: The nozzle size, when it differs from the one
            Kiln has for the printer.
        :param layer_height_mm: The layer height it will print at.
        :param material: The material it will print in.
        :param fastener: The fastener the part's holes take, e.g.
            ``"M3"`` — pass only if the user actually named one.  Kiln
            does not read the part looking for screw holes.
        :returns: Dict with before/after scores, applied/skipped reinforcements.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

infer_print_settingsA

Infer optimal slicer settings from structural analysis.

        Bridges the gap between **design analysis** and **print success**.
        Analyzes the mesh for structural risks, then recommends concrete
        slicer parameters (perimeters, infill, supports, brim, layer height)
        tuned to compensate for the design's weaknesses.

        **Examples of what it catches:**

        - Thin neck detected → increase perimeters to 4+
        - Cantilever overhangs → enable tree supports
        - High center of gravity → add brim for bed adhesion
        - Stress concentrations → switch to gyroid infill at 50%+
        - Sharp corners → fine layer height for detail

        Material-specific: defaults vary by PLA/PETG/ABS/Nylon/TPU/ASA/PC.

        :param file_path: Path to the STL file.
        :param material: Filament type (PLA, PETG, ABS, Nylon, TPU, ASA, PC).
        :returns: Dict with perimeters, infill, supports, brim, layer height,
                  orientation, special notes, and confidence level.
        
design_advisorA

Ask which generation method to use for a design idea (triage tool — call FIRST).

        Analyzes the design prompt and recommends:
        - Which generation approach to use (template, OpenSCAD, or AI)
        - Which template matches (if any)
        - Material recommendations
        - Key constraints to consider
        - Estimated complexity

        :param prompt: Text description of the desired object.
        :param printer_model: Optional printer model for constraints.
        :param material: Optional material the user has already named
            ("for ABS") — tunes the constraint analysis to it.
        :returns: Dict with recommendations.
        
arrange_parts_on_plateA

Pack multiple STL files onto a virtual build plate.

        Uses greedy bottom-left bin-packing (largest parts first) to
        efficiently arrange parts with configurable spacing. Reports
        which parts fit, which overflow, and plate utilization.

        Supports printing multiple copies of parts via the copies parameter.

        :param file_paths: JSON array of file paths, e.g. ``["/tmp/a.stl", "/tmp/b.stl"]``.
        :param plate_width_mm: Build plate width in mm (default 256).
        :param plate_depth_mm: Build plate depth in mm (default 256).
        :param spacing_mm: Minimum gap between parts in mm (default 5).
        :param copies: Optional JSON dict of filename->count, e.g. ``{"part.stl": 3}``.
        :param printer_id: Optional supported printer model id, or the
            name of a printer set up in Kiln.  When provided, printer
            intelligence supplies the plate size.
            Keep passing it downstream — a later
            ``compose_multicolor_3mf`` without it judges the layout
            against a 256mm default plate.
        :returns: Dict with arranged_parts, overflow_parts, plate_utilization, summary.
        
auto_arrange_parts_on_plateA

Calculate non-overlapping XY positions for multiple parts on a print plate.

        Use this **before** :func:`compose_multicolor_3mf` when you have multiple
        separate objects (e.g., two coasters) to print in one job.  Parts that
        share the same ``group`` index are treated as a multi-color unit and
        placed at the *same* XY position (they overlap intentionally).

        Returns a list of positioned part specs ready to pass directly to
        ``compose_multicolor_3mf`` — pass the SAME ``printer_id`` to that
        call: the composer re-centres a group it judges off ITS plate
        (256mm by default), so composing a layout packed for a different
        bed without the printer undoes this placement.

        Arrangement strategy (free tier): simple left-to-right row layout.  For
        maximum plate density (2D bin-packing), use kiln-pro.

        Example -- two coasters, each with a body + QR layer::

            positioned = auto_arrange_parts_on_plate(part_specs=[
                {"stl_path": "/tmp/c1_body.stl", "extruder": 1, "group": 0, "material": "PLA Grey"},
                {"stl_path": "/tmp/c1_qr.stl",   "extruder": 2, "group": 0, "material": "PLA Black"},
                {"stl_path": "/tmp/c2_body.stl",  "extruder": 1, "group": 1, "material": "PLA Grey"},
                {"stl_path": "/tmp/c2_qr.stl",    "extruder": 2, "group": 1, "material": "PLA Black"},
            ], plate_width=256, plate_depth=256, gap_mm=5)
            # -> each part now has "x", "y" set; pass to compose_multicolor_3mf

        Args:
            part_specs: List of dicts, each with:

                * ``stl_path`` (str) -- absolute path to the STL
                * ``extruder`` (int) -- 1-indexed AMS slot
                * ``group`` (int, optional) -- parts sharing a group get the same
                  XY position (multi-color unit).  Default: each part is its own group.
                * ``name`` (str, optional) -- label in slicer
                * ``color`` (str, optional) -- hex preview color
                * ``material`` (str, optional) -- filament label (also triggers
                  compatibility checks when passed to compose_multicolor_3mf)

            plate_width: Print plate X dimension in mm (default 256 for
                legacy callers without a printer id).
            plate_depth: Print plate Y dimension in mm (default 256 for
                legacy callers without a printer id).
            gap_mm: Minimum spacing between groups in mm.
            printer_id: Optional supported printer model id.  When
                provided, printer intelligence supplies the plate size.

        Returns:
            Dict with ``success``, ``parts`` list (each part has ``x``, ``y`` set),
            ``group_count``, ``fits_bed`` (``False`` when the rows run past
            the bed: the message then gives the layout's size, the bed's, and
            what to do, instead of the next step), ``bed_fit``, and
            ``message``.
        
optimize_template_paramsA

Find the structurally strongest version of a parametric template.

        Sweeps each template parameter across its [min, max] range at
        evenly spaced sample points, generates every combination via
        OpenSCAD, runs structural analysis on each variant, and returns
        the configuration with the highest structural score.

        Use this when you want to **automatically** find optimal dimensions
        for a functional part -- e.g. "what wall thickness and bracket
        height give the strongest shelf bracket?"

        :param template_id: Template ID from the design template library.
        :param samples_per_param: Sample points per parameter (default 3).
        :param max_variants: Maximum total variants to test (default 27).
        :param constraints: JSON string of constraints, e.g.
               ``{"max_width_mm": 100, "max_height_mm": 50}``.
        :param output_dir: Directory for generated STLs (temp dir if empty).
        :returns: Dict with best_params, best_score, best_grade, best_stl_path,
                  variants_tested, all_scores, and summary.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

MAKE DOORS: design_session, Kiln's front door for making an object, is not installed here (signed in to Kiln it runs on Kiln's servers). On this install compile_scad IS the make → preview → iterate loop: make it, show the preview, iterate.

solve_template_constraintsA

Solve parametric constraints to find valid template parameters.

        Given a template and constraints (min/max/equals/ratio), iteratively
        adjusts parameters to satisfy all constraints while staying within
        the template's declared parameter ranges.

        :param template_id: Template identifier (e.g., "shelf_bracket").
        :param constraints: JSON object mapping param names to constraint dicts.
            Example: ``{"width": {"min": 20, "max": 50}, "height": {"equals": 30}}``
            Supported keys: min, max, equals, ratio (e.g. ``{"ratio": ["width", 0.5]}``).
        :returns: Dict with solved_params, satisfied/violated constraints,
            plus ``dof`` (how many parameters no constraint pinned),
            ``free`` (one sentence per unpinned parameter and the value it
            was left at) and ``defaults_applied``.  Tell the person what
            was left free rather than silently accepting a default:
            ``min``/``max`` bound a parameter without choosing it.
        
iterate_designA

Automated design iteration: generate -> validate -> improve -> regenerate.

        Runs a closed loop that generates a model, validates it for
        printability issues, and if issues are found, improves the prompt
        and regenerates.  Stops when the model passes validation or
        max_iterations is reached.  Returns the best result.

        :param prompt: Text description or OpenSCAD code.
        :param provider: Generation provider (default ``"openscad"``).
        :param max_iterations: Maximum improvement attempts (1-5).
        :param material: Optional material for design intelligence.
        :param printer_model: Optional printer model for constraints.
        :param brief_id: Optional saved-goal id from ``design_session``.
            When supplied AND the best iteration produced a mesh, a
            ``design_brief:<id>`` intent sidecar is written next to
            the produced file so the audit's "matches what you
            asked for" gate, the brief failure_history wiring, and
            the ``compare_design_versions`` intent diff all light
            up against the saved goal — without the user having to
            re-attach the brief after every iteration round.  The
            result is also compared with any picture kept on the goal
            (``reference_check``); where this install cannot read the
            goal, ``reference_check`` says the result was not compared.
        :returns: Dict with the best result and iteration history.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

MAKE DOORS: design_session, Kiln's front door for making an object, is not installed here (signed in to Kiln it runs on Kiln's servers). On this install compile_scad IS the make → preview → iterate loop: make it, show the preview, iterate.

optimize_print_orientationA

Auto-rotate a mesh to minimize overhangs and maximize bed contact.

        Tests multiple candidate orientations and picks the one with the
        fewest overhangs and the most bed contact.  Re-orients the mesh
        and places it flat on the build plate (z_min = 0).

        ``printability_score`` / ``printability_grade`` are the chosen
        orientation's score from ``analyze_printability`` itself, judged
        for ``material`` and ``printer_id`` — pass the same ones you
        gave ``analyze_printability`` and the two numbers match.

        :param file_path: Path to the STL file.
        :param output_path: Output path.  Defaults to overwriting the input.
        :param material: Material the score is judged for (default ``"pla"``).
        :param printer_id: Optional printer the score is judged for.
        :returns: Dict with rotation angles, overhang stats, the
            printability score and grade, and new dimensions.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

check_print_readinessA

Single-call print readiness check with optional auto-repair.

        Runs the full validation battery: parseable, manifold, no floating
        regions, supports (``analyze_printability``'s own verdict, which
        knows a short ceiling bridges), fits build plate, no degenerate
        triangles.

        With ``auto_fix=True``, automatically repairs degenerate triangles,
        closes holes, and removes floating regions.

        :param file_path: Path to mesh file.
        :param auto_fix: Attempt automatic repairs (default False).
        :param output_path: Where to write the fixed file.
        :param bed_x_mm: Build plate X dimension (default 256).
        :param bed_y_mm: Build plate Y dimension (default 256).
        :param bed_z_mm: Build plate Z dimension (default 256).
        :param printer_id: Optional supported printer model id, or the
            name of a printer set up in Kiln.  When provided, printer
            intelligence supplies the build volume.
        :param material: Material the supports verdict and the
            ``printability_score`` are judged for (default ``"pla"``) —
            ``analyze_printability``'s own, so the two agree.
        :returns: Dict with can_print verdict, issues, and actions taken.
        
estimate_support_materialB

Estimate support material needed for a mesh.

        Analyzes overhang triangles and projects them to the build plate
        to estimate the volume and weight of support material required.

        :param file_path: Path to a .stl, .obj, .glb, or .3mf file.
        :returns: Dict with support volume (mm³), weight (g), and overhang stats.
        
rebuild_designA

Re-execute the full build pipeline from a saved design recipe.

        Two modes, chosen by what the recipe carries — the result names
        which one ran:

        - **Parametric** (the recipe has OpenSCAD source): the geometry
          is RE-DERIVED.  The recipe's numeric parameters are applied to
          the source and recompiled, so wall thicknesses and fastener
          holes come out exactly as designed.  To resize a parametric
          design, change the parameter — with ``update_scad_parameter``
          on the source, or on the recipe's parameters — and rebuild.
          Never scale the mesh instead: it scales every feature with
          the body, so a 3mm wall becomes 3.6mm and a 3.4mm M3
          clearance hole becomes 4.08mm — no longer the fit it was
          dimensioned for.
        - **Mesh** (no source): the recorded part meshes are re-sliced
          exactly as they are.  A geometry change needs a mesh edit first
          (``rescale_model``, ``thicken_mesh_walls``, ...), then a rebuild.

        Every parameter is itemized as applied, absent from the source,
        or skipped with a reason — an edit this tool cannot honor is
        reported, never silently dropped.

        The artifact is a print-ready 3MF where a Bambu printer is
        registered and the merged G-code otherwise (send that with
        ``upload_file``); ``wrapped`` says which one you got.

        When the render pipeline is available this also returns an
        inline preview of the rebuilt design; display that image to the
        user rather than summarizing it. The rebuild itself never
        depends on it.

        Example: rebuild_design("prints/bracket/")

        :param recipe_path: The design directory, or the recipe file.
        :param brief_id: Optional saved-goal id. When supplied it is
            recorded on the recipe before the rebuild, so the output
            carries the goal in its provenance; when omitted the
            recipe's existing goal is kept, so iterating a
            goal-attached design keeps it automatically.
        :returns: Dict with the print artifact, the mode used, and
            per-part or per-parameter results.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

MAKE DOORS: design_session, Kiln's front door for making an object, is not installed here (signed in to Kiln it runs on Kiln's servers). On this install compile_scad IS the make → preview → iterate loop: make it, show the preview, iterate.

analyze_design_requirementsA

Analyze a functional requirement and return technical recommendations.

        This is the internal-lookup tool that resolves a natural-language
        requirement into material recommendations, applicable design
        patterns, dimensional constraints, print orientation rules, and
        expert guidance notes.

        For the user-facing flow — capturing what a user is making at the
        duty / environment / materials / safety layer and producing a
        saved goal that drives generation, the audit, and the post-print
        review — call ``design_session(verb="start", idea="...")`` first.
        That tool internally calls this one for technical lookups; agents
        calling ``analyze_design_requirements`` directly should treat it
        as a pre-design analysis pass, not the user-facing entry point.

        Examples:
            "shelf bracket that holds 10 lbs of books"
            "outdoor planter that holds water"
            "phone mount for car dashboard, survives summer heat"
            "snap-fit enclosure for a Raspberry Pi"
            "flexible phone case that absorbs drops"
            "cookie cutter, food safe"
            "decorative vase, looks premium"

        Args:
            requirements: Natural language description of what the object
                needs to do — functional needs, environment, loads, etc.
            material: Optional material override (e.g. "petg"). If not
                provided, the system recommends the best material.
        
build_generation_promptA

Build a design-aware generation prompt for original 3D creation.

        This is the best pre-generation tool for original designs. It takes
        a natural-language idea and appends manufacturing constraints,
        printer-fit limits, and material guidance so text-to-3D backends
        receive a prompt grounded in real printability constraints.

        When provider is specified, the prompt length is optimized for that
        backend. Use provider="openscad" for maximum constraint injection
        (100K chars), "meshy" for lean prompts (600 chars), or omit for
        the default limit.

        Args:
            requirements: Natural language description of the desired part.
            material: Optional material override (e.g. "petg").
            printer_model: Optional printer model ID (e.g. "bambu_a1").
            provider: Optional generation provider (e.g. "openscad", "meshy",
                "gemini"). Controls prompt length budget.
        
audit_original_designA

Run a ruthless audit of an original design before printing.

        Combines design briefing, prompt enhancement, mesh validation,
        printability scoring, orientation analysis, advanced diagnostics,
        and regeneration feedback into a single report.

        Use this after generating or modeling a new part to answer:
        "Is this genuinely ready to print, and if not, what exact changes
        should the agent make next?"

        Args:
            file_path: Path to STL or OBJ file.
            requirements: Functional requirements the design must satisfy.
            material: Optional material constraint (e.g. "petg").
            printer_model: Optional printer model ID (e.g. "bambu_a1").
            build_volume_x: Optional build volume X override in mm.
            build_volume_y: Optional build volume Y override in mm.
            build_volume_z: Optional build volume Z override in mm.
            nozzle_diameter: Printer nozzle diameter in mm.
            layer_height: Layer height in mm.
            max_overhang_angle: Supportless overhang threshold in degrees.
        
get_material_design_profileA

Compatibility lookup for a material's public design floor.

        Returns the same public safety and process fields as
        ``get_material_properties``. For deeper engineering guidance,
        ask one specific question with ``answer_material_question``.

        Args:
            material: Material ID (for example ``"pla"`` or ``"petg"``).
        
list_design_materialsB

List public material identifiers and safety/process summaries.

The list is sourced only from public Kiln data and does not include optional engineering enrichment.

recommend_design_materialA

Recommend material for engineering/functional parts (strength, heat, environment).

        Analyzes functional requirements and recommends the optimal
        material considering mechanical needs, environmental exposure,
        printer capabilities, and ease of printing.  Returns the top
        recommendation with reasoning, warnings, and alternatives.

        **Which material tool to use:**

        - Designing a part and need engineering specs? → ``recommend_design_material`` (this tool)
        - Quick intent-based pick for your own printer? → ``recommend_material``
        - Ordering a print from a service? → ``suggest_material_for_order``

        Args:
            requirements: What the object needs to do (e.g. "hold 5 kg
                of books on an outdoor shelf").
            printer_has_enclosure: Whether the printer has an enclosed
                build chamber (needed for ABS, ASA, Nylon, PC).
            printer_has_direct_drive: Whether the printer has a direct
                drive extruder (needed for TPU).
            max_hotend_temp_c: Maximum hotend temperature in Celsius.
        
estimate_structural_loadA

Estimate safe structural load for a cantilevered section.

        The figure is Kiln Pro's (https://kiln3d.com/pricing), worked
        out for this one part -- strength, sag and the arm's own weight,
        for any length of arm and size of section; below Pro the answer
        says the load was not checked.  A part whose arm cannot hold its
        own weight gets no figure: ``load_checked`` is false and
        ``message`` says why.  When the figure cannot be had (offline,
        signed out, no answer) the answer says why and that the part is
        unchecked.

        Args:
            material: Material ID (e.g. "petg", "nylon", "polycarbonate").
            cross_section_mm2: Effective load-bearing cross section in mm^2.
            cantilever_length_mm: Cantilever length in mm.
            load_across_layers: True when the load pulls the layer
                interfaces apart (load along the build/Z direction —
                the WEAK direction for FDM, so the figure is lower).
                False when the load acts within the layer planes
                (e.g. a bracket printed lying flat — the strong
                direction). If unsure, leave True: it is the
                conservative default.
        
check_material_environmentA

Check whether a material is compatible with an environment, and optionally whether it meets the rules the part must meet.

        Args:
            material: Material ID from the design knowledge base.
            environment: Natural language environment description.
            requirements: Optional rules to check the material against
                before printing: any of ``food_safe``, ``reach``,
                ``rohs``, ``flame_retardant``, ``uv``.  The answer comes
                back under ``rule_checks``: the material's warnings at
                every tier, and from Kiln Business a meets / does-not-meet
                verdict with the reason for each requirement
                (https://kiln3d.com/pricing).  When the check cannot be
                made, ``rule_checks.checked`` is false and no
                requirement is called met.
        
get_design_template_infoA

Look up one design template by id — parametric part or pattern.

        Resolves an id from EITHER library and says which it came
        from, so a caller never has to know in advance:

        * a PARAMETRIC PART (``generatable: true``) comes back with
          its full parameter list — names, defaults, and units — which
          is what you need to fill in the user's own dimensions and
          call ``generate_from_template``.
        * a DESIGN PATTERN (``generatable: false``) comes back with
          its use cases, material compatibility, and print
          orientation.  Patterns are guidance for OpenSCAD you write
          yourself; ``generate_from_template`` does not accept them.

        Args:
            template: Template identifier, from either library —
                e.g. "shelf_bracket" (part) or "snap_fit_cantilever"
                (pattern).  Use ``find_design_templates`` to search.
        
list_design_templates_catalogA

Browse the whole design-template library, both kinds.

        Returns every PARAMETRIC PART Kiln can render on its own —
        brackets, bins, stands, cases, hooks, jigs, clamps, plumbing
        and garden parts — followed by the DESIGN PATTERNS that are
        guidance rather than geometry.  Every entry carries a
        ``generatable`` flag and the call to make next.

        The parametric parts are FREE and need no AI provider: they
        compile locally through OpenSCAD.  Reach for one whenever a
        user wants a functional part to their own dimensions, and
        offer it before writing OpenSCAD from scratch — it is
        faster and every part in the library is print-verified.

        Use ``find_design_templates(use_case)`` to search rather than
        reading the whole catalog.
        
find_design_templatesA

Find a ready-made parametric part for what the user is making.

        CALL THIS FIRST whenever a user asks for a FUNCTIONAL PART to
        their own dimensions — a bracket that holds a shelf, a bin
        that fits a drawer, a clip for an 8 mm cable, a case for a
        board, an adapter between two hose sizes.  Kiln ships a
        library of print-verified parametric parts; offering one is
        faster and more reliable than writing OpenSCAD from scratch,
        it is FREE, and it needs no AI provider or API key.  Do not
        wait to be asked whether a template exists — search, and if
        something fits, offer it.

        Ranked best match first, across both libraries:

        * ``generatable: true`` — a PARAMETRIC PART.  The result
          carries its parameters, so you can fill in the user's
          dimensions and call ``generate_from_template(template_id, {...})``
          to render a printable STL.
        * ``generatable: false`` — a DESIGN PATTERN (snap fit, living
          hinge, press fit).  Guidance for OpenSCAD you write
          yourself; ``generate_from_template`` does not accept it.

        No match is a normal answer, not a failure — fall back to
        writing OpenSCAD and compiling with ``compile_scad``.

        Args:
            use_case: What the user is making, in their words —
                e.g. "shelf bracket", "storage bin", "cable clip",
                "enclosure", "gear train", "hose adapter".
        
match_design_requirementsA

Identify which functional requirements apply to a design task.

        Scans natural language for requirement triggers (load bearing,
        watertight, outdoor, food safe, heat resistant, flexible, impact
        resistant, precision, aesthetic) and returns matched constraint
        sets with rules and guidance.

        Use this to understand WHAT constraints apply before getting
        the full design brief.

        Args:
            description: What the object needs to do (e.g. "outdoor
                hook that holds a heavy hanging planter").
        
validate_design_for_requirementsA

Validate a 3D model against functional design requirements.

        Checks that a generated STL/OBJ model meets the structural,
        dimensional, and manufacturability constraints implied by the
        requirements.  Returns pass/fail per check with specific fix
        suggestions for any failures.

        Call this AFTER generating a model and BEFORE printing it.
        If validation fails, use the fix suggestions to improve the
        generation prompt and regenerate.

        Args:
            file_path: Path to STL or OBJ file.
            requirements: Same requirements text used for analyze_design_requirements.
            material: Optional material (e.g. "petg").
        
troubleshoot_print_issueA

Diagnose a 3D printing problem by material and symptom.

        Searches the troubleshooting knowledge base for matching issues
        and returns root causes, prioritised fixes, prevention tips, and
        storage/drying requirements for that specific symptom.

        Use this when a user reports a print failure, quality issue, or
        asks "why is my print doing X?"

        Examples:
            material="pla", symptom="stringing"
            material="petg", symptom="poor layer adhesion"
            material="abs", symptom="warping"
        Args:
            material: Material ID (e.g. "pla", "petg", "abs", "tpu",
                "nylon", "polycarbonate", "asa", "cf_nylon").
            symptom: Symptom keywords to search for (e.g.
                "stringing", "warping", "clog", "brittle").
        
check_printer_material_compatibilityA

Check if a specific printer can handle a material.

        Returns compatibility status (compatible / needs_upgrade /
        not_compatible), any required hardware upgrades (enclosure,
        hardened nozzle, dry box), and practical notes.

        Use this when a user asks "can my Ender 3 print nylon?" or
        another specific printer/material question.

        Args:
            printer: Printer model ID (e.g. "ender3", "bambu_x1c",
                "prusa_mk4", "voron_2"). Use underscores, lowercase.
            material: Material to check (e.g. "nylon", "abs").
        
get_post_processing_guideA

Get bounded public post-processing help for one goal.

        Pass ``surface_finish``, ``paint``, ``strengthen``, or the name of
        one listed technique. Omitting ``goal`` returns a compact
        compatibility overview rather than the complete guide.

        Args:
            material: Material ID (e.g. "pla", "abs", "petg", "nylon").
            goal: Optional finishing goal or technique name.
        
check_multi_material_pairingA

Check if two materials can be co-printed in dual extrusion.

        Returns compatibility (yes/no), interface adhesion quality,
        notes on temperature management, and soluble support dissolution
        instructions when applicable.

        Use this when a user asks "can I print PLA with TPU?" or
        "what support material works with ABS?" or planning any
        multi-material / dual-extrusion print.

        Args:
            material_a: First material (e.g. "pla", "abs").
            material_b: Second material (e.g. "tpu", "hips", "pva").
        
get_print_diagnosticA

Get a comprehensive print diagnostic combining multiple knowledge sources.

        This is the PRIMARY tool for debugging print problems.  Combines
        troubleshooting data (symptom matching, root causes, fixes),
        printer compatibility (upgrade requirements, known issues),
        storage requirements (drying temps, humidity limits), and
        post-processing tips (strengthening options) into a single
        actionable response.

        Call this FIRST when a user reports any print quality problem.
        It cross-references all knowledge sources so the agent doesn't
        need to make multiple tool calls.

        Examples:
            material="petg", symptom="stringing", printer="ender3"
            material="abs", symptom="warping", printer="bambu_a1"
            material="nylon", symptom="brittle"

        Args:
            material: Material being printed (e.g. "pla", "petg").
            symptom: What's going wrong (e.g. "stringing", "warping",
                "poor adhesion", "clog", "brittle").
            printer: Optional printer model for compatibility context
                (e.g. "ender3", "bambu_x1c").
        
estimate_print_cost_from_meshA

Estimate total print cost from a 3D model file.

        Calculates material, support, adhesion, and electricity costs directly
        from mesh geometry — no G-code or slicing required. Includes a detailed
        cost breakdown and actionable recommendations to reduce cost.

        Supported materials: pla, pla+, petg, abs, tpu, asa, nylon, pc,
        cf-pla, silk-pla, hips, pva, pp, peek.

        Args:
            file_path: Path to mesh file (.stl, .obj, or .3mf).
            material: Material type (default "pla").
            infill_percent: Interior fill percentage 0-100 (default 20).
            wall_layers: Number of perimeter shells (default 3).
            layer_height_mm: Layer height in mm (default 0.2).
            nozzle_mm: Nozzle diameter in mm.  Leave unset for the only
                printer Kiln knows of, else 0.4; ``nozzle`` in the reply
                says which.
            include_supports: Estimate support material cost (default False).
            support_density: Support infill percentage (default 15).
            adhesion_type: Bed adhesion type: "none", "brim", or "raft".
            electricity_rate: Electricity cost in $/kWh (default 0.12).
            printer_wattage: Printer power consumption in watts (default 200).
        
build_parametric_promptA

Build a prompt optimized for parametric OpenSCAD code generation.

        Returns an enhanced prompt with OpenSCAD-specific instructions that
        guide AI to produce well-structured parametric code with named
        variables, descriptive comments, and material-aware design limits.

        Use this instead of build_generation_prompt when you want the AI to
        generate editable OpenSCAD code rather than a mesh file.

        Args:
            requirements: Natural language description of the desired part.
            material: Optional material override (e.g. "petg").
            printer_model: Optional printer model ID (e.g. "bambu_a1").
        
parse_scad_parametersA

Parse parameter variables from OpenSCAD code.

        Extracts named dimension variables from the top of an OpenSCAD
        file, including their values, units, descriptions, and valid
        ranges (if annotated in comments).

        Use this after generating OpenSCAD code to discover which
        parameters can be adjusted. A parameter computed from others
        (``inner = outer - 2*wall;``) is returned with ``derived: true``,
        its ``expression`` and ``depends_on``; it moves when those
        change and cannot be set directly.

        Args:
            scad_code: OpenSCAD source code string.
        
update_scad_parameterA

Update a parameter value in OpenSCAD code.

        Finds the named variable declaration and replaces its value,
        preserving comments and formatting. Use this to tweak dimensions
        without regenerating the entire model. A derived parameter is
        refused with a message naming its formula and the parameters to
        change instead.

        Args:
            scad_code: OpenSCAD source code string.
            parameter_name: Name of the variable to update.
            new_value: New numeric value for the parameter.
        
validate_scad_parametersA

Validate OpenSCAD parameters against material design limits.

        Checks if parameter values (wall thickness, hole diameter, etc.)
        violate the design limits for the specified material. Catches
        issues before compilation and printing.

        Args:
            scad_code: OpenSCAD source code string.
            material: Optional material ID (e.g. "pla", "petg") to check
                against material-specific limits.
        
list_design_componentsA

List available pre-built OpenSCAD components from bundled libraries.

        Kiln bundles BOSL2 OpenSCAD libraries with pre-built
        components for gears, threads, screws, bearings, hinges, and more.
        These components produce proven geometry — much better than
        generating complex mechanical parts from scratch.

        Categories: mechanical, fasteners, electronics

        Args:
            category: Optional filter by category. If not provided, lists
                all available components.
        
match_design_componentsA

Find pre-built library components matching a design description.

        Given a natural language description of what you want to build,
        identifies which bundled OpenSCAD library components can be used.
        Returns import lines, example usage, parameters, and guidance
        for each matching component.

        Examples:
            "hand crank with a gear" → finds spur_gear
            "box with a hinge" → finds knuckle_hinge
            "mounting bracket with screw holes" → finds screw_hole

        Args:
            description: Natural language description of the design.
        
compile_scadA

Compile OpenSCAD code into an STL file.

        Takes OpenSCAD source code OR a path to a .scad file, compiles
        it using the local OpenSCAD binary, and returns the path to the
        generated STL. Supports Kiln's bundled BOSL2 library.

        For surface() heightmap operations (photo emboss, lithophane),
        increase timeout to 600+ seconds.

        Kiln checks the compiled part is joined up.  A piece that floats
        with nothing under it is joined to nothing and prints as a loose
        part on supports, or not at all, so the make is REFUSED
        (``code: "FLOATING_PIECES"``; ``error`` names the pieces, how
        far they are from the nearest surface, and the fix): correct
        the geometry and compile again.  Separate parts that all sit on
        the bed are a plate and pass; a piece held inside the part (a
        ball in a cage, a pin in its knuckles) passes with a warning; a
        piece that touches the rest without overlapping it is named in
        ``warnings``.

        Colour: pass ``color`` (a name such as ``"teal"`` or a hex) when
        the user asked for one, and the preview and the 3D stage show
        the part in it.  Left out, a single ``color("...")`` in the
        source is used.  It is how the part is SHOWN; it prints in
        whatever filament is loaded, and the result's ``color`` block
        says so.

        Round shapes: leave ``$fn`` out and Kiln cuts each curve by its
        size, writing that rule into the file it compiles.  Set ``$fn``
        only for a deliberate polygon (``$fn = 6`` for a hexagon).  A
        file that sets ``$fn``, ``$fa`` or ``$fs`` at the top compiles
        exactly as written, and the result's ``curve_resolution`` note
        says so.

        When you pass ``fastener``, the result carries a
        ``fastener_advice`` block saying the code compiled as written
        and nothing resized the hole for that fastener.  Kiln raises
        it once per session across every tool that can raise it.  Read
        its ``agent_instruction`` before repeating any of it.

        Args:
            brief_id: The saved goal's id from ``design_session``; pass it so
                this make joins the goal (recorded against it; Kiln Pro checks the
                result against it). Empty when there is no goal.
            scad_code: Valid OpenSCAD source code (provide this OR scad_path).
            scad_path: Path to a .scad file (provide this OR scad_code).
            timeout: Maximum compilation time in seconds (default 300).
            fastener: The fastener the user named, e.g. ``"M4"`` — pass
                only if they actually said one.  Kiln does NOT read your
                OpenSCAD looking for screw holes; guessing intent out of
                geometry would be wrong often. No argument, no advisory.
            color: The colour the user asked for, shown on the preview and
                the stage (a name or ``#rrggbb``).  Not a print setting.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

MAKE DOORS: design_session, Kiln's front door for making an object, is not installed here (signed in to Kiln it runs on Kiln's servers). On this install compile_scad IS the make → preview → iterate loop: make it, show the preview, iterate.

tweak_and_compile_scadA

Update a parameter in OpenSCAD code and recompile to STL.

        The complete parametric tweaking workflow: changes a dimension
        variable, validates against material limits, and compiles a new
        STL — all in one step. Perfect for "make it 5mm wider" requests.

        A tweak that leaves a piece floating with nothing under it is
        refused like a compile is (``code: "FLOATING_PIECES"``, the fix
        in ``error``).  ``color`` shows the part in the colour the user
        asked for, as on ``compile_scad``.

        Args:
            brief_id: The saved goal's id from ``design_session``; pass it so
                this make joins the goal (recorded against it; Kiln Pro checks the
                result against it). Empty when there is no goal.
            scad_code: OpenSCAD source code.
            parameter_name: Variable name to update (e.g. "wall_thickness").
            new_value: New numeric value.
            material: Optional material for limit validation (e.g. "pla").
            color: The colour the user asked for, shown on the preview and
                the stage (a name or ``#rrggbb``).  Not a print setting.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

MAKE DOORS: design_session, Kiln's front door for making an object, is not installed here (signed in to Kiln it runs on Kiln's servers). On this install compile_scad IS the make → preview → iterate loop: make it, show the preview, iterate.

analyze_scad_codeA

Analyze the structure of OpenSCAD code.

        Parses parameters, modules, and library imports to understand
        the code's architecture. Use this before modifying code to know
        what modules exist and what each one does.

        Args:
            scad_code: OpenSCAD source code.
        
modify_scad_moduleA

Replace a module in OpenSCAD code with new implementation.

        Finds the named module and replaces its body entirely. Use for
        major modifications like redesigning a component.

        Args:
            scad_code: OpenSCAD source code.
            module_name: Module to replace (e.g. "top_panel").
            new_module_code: Complete new module code including the
                module declaration and braces.
        
insert_into_scadA

Insert code into an OpenSCAD module without replacing it.

        Adds geometry or operations inside a module. Use for targeted
        additions like "add ventilation holes to the top panel" or
        "add screw holes to the base."

        Args:
            scad_code: OpenSCAD source code.
            module_name: Module to modify (e.g. "base_plate").
            code_to_insert: OpenSCAD code to insert.
            position: "end" (before closing brace) or "start" (after
                opening brace). Default: "end".
        
cache_design_with_sourceA

Cache a design file alongside its parametric source code.

        Stores the STL/3MF file in the design cache and attaches the
        OpenSCAD source code and generation prompt so the design can
        be re-generated or tweaked later.

        Args:
            file_path: Path to the design file (STL, 3MF, etc.).
            scad_source: OpenSCAD source code that produced this file.
            generation_prompt: The prompt used to generate the design.
            provider: Generation provider name (e.g. "openscad", "gemini").
            tags: Optional tags for search.
            filament_type: Material type (e.g. "PLA", "PETG").
        
get_design_sourceA

Retrieve the parametric source code for a cached design.

        Returns the OpenSCAD source, generation prompt, and provider
        so the design can be re-generated, tweaked, or inspected.

        Args:
            design_id: ID of the cached design.
        
analyze_warping_riskA

Analyze warping risk for a 3D model based on geometry and material.

        Examines the mesh for warping risk factors: large flat surfaces that
        tend to curl at corners, tall/narrow geometry prone to thermal
        contraction pulling, and sharp base corners that lift. Cross-references
        with the material's known warping tendency (from thermal properties).

        Returns a risk assessment with:
        - risk_level: "low", "moderate", "high", or "critical"
        - score_deduction: impact on overall printability score
        - large_flat_surfaces: detected flat areas prone to warping
        - height_to_base_ratio: geometry aspect ratio risk factor
        - material_warping_tendency: material's inherent warp behavior
        - recommendations: actionable mitigation advice, led by the brim
          or raft to use when the part calls for one
        - adhesion: the brim / raft decision for this part (width, raft,
          reason, slicer overrides) — the same one analyze_printability
          reports

        Args:
            file_path: Path to STL, OBJ, GLB, or 3MF file to analyze.
            material: Material ID (e.g. "pla", "abs", "petg"). Defaults to PLA.
                Used to look up thermal warping tendency.
            printer_id: Optional registered printer whose real geometry
                and calibration should inform the analysis.

        Examples:
            analyze_warping_risk("/path/to/model.stl", material="abs")
            analyze_warping_risk("/path/to/plate.stl")  # defaults to PLA
        
resolve_filament_profileA

Resolve a material name or brand ID to a unified filament profile.

        Accepts EITHER a generic material (``"PLA"``, ``"TPU"``) OR a
        specific brand profile ID (``"bambu_pla_basic"``,
        ``"prusament_tpu_95a"``).  Brand profiles return manufacturer-exact
        specs (density, temps, drying, nozzle/enclosure requirements).
        Generic materials return conservative defaults.

        When ``printer_id`` is provided, also checks compatibility and
        returns warnings (e.g. "needs hardened nozzle", "needs enclosure",
        "not AMS compatible").

        Use this BEFORE slicing or printing to get exact filament specs.
        Pass the result to ``estimate_before_design`` for brand-accurate
        cost/time estimates.

        :param material_or_brand: Material name (``"PLA"``) or brand
            profile ID (``"bambu_petg_cf"``).
        :param printer_id: Optional printer model for compatibility checks.
        
export_audit_trailA

Export the safety audit trail as JSON or CSV.

        Enterprise feature. Returns the full audit log with optional filters
        for date range, tool name, action type, and session ID.

        Args:
            start_time: Unix timestamp lower bound (0 = no filter).
            end_time: Unix timestamp upper bound (0 = no filter).
            format: Output format, ``"json"`` or ``"csv"``.
            tool_name: Filter by MCP tool name.
            action: Filter by action (executed, blocked, etc.).
            session_id: Filter by agent session ID.
        
lock_safety_profileA

Lock a safety profile so agents cannot modify its limits.

        Enterprise feature. When locked, community profile updates for this
        printer model are rejected. Only an admin can unlock.

        Args:
            printer_model: Profile identifier to lock (e.g. "ender3").
        
unlock_safety_profileB

Unlock a previously locked safety profile.

        Enterprise feature. Allows community profile modifications for
        this printer model again.

        Args:
            printer_model: Profile identifier to unlock.
        
manage_team_memberB

Add, remove, or update a team member.

        Enterprise feature. Manages team seats and role assignments.
        Business includes 3 seats and meters to a cap of 10; Enterprise is
        unlimited.

        Args:
            action: One of ``"add"``, ``"remove"``, ``"set_role"``, ``"list"``.
            email: Member email address (ignored for ``"list"``).
            role: Role for add/set_role: ``"admin"``, ``"engineer"``, ``"operator"``.
        
printer_usage_summaryB

How many printers are registered with this Kiln, and what they add to your bill on your plan, at the prices on kiln3d.com/pricing. Free on every plan.

Counts the machines registered here, so ask it on the computer your printers are attached to.

uptime_reportA

Get rolling uptime statistics and SLA status.

Enterprise feature. Shows uptime percentages for 1h, 24h, 7d, and 30d windows, average response times, and whether the 99.9% SLA target is being met.

encryption_statusA

Check G-code encryption status and configuration.

        Enterprise feature. Reports whether encryption is active on
        this computer, whether the local encryption key is configured,
        and whether the cryptography library is installed.  On a
        machine where encryption at rest is not installed, it answers
        that encryption is not active here, in the same shape, and
        says what enables it.  ``account_files`` says, on every
        install, what is true of the print files kept in the person's
        Kiln account: Kiln's servers encrypt those with a key held
        there.  Local files on this computer are encrypted only when
        the local key is set and encryption is installed here.
        
rotate_encryption_keyA

Rotate the G-code encryption key by re-encrypting all files.

        Scans *directory* recursively for encrypted G-code files, decrypts
        with the old passphrase, and re-encrypts with the new one.

        **Run with ``dry_run=True`` first** to preview which files would be
        affected.  Then call again with ``dry_run=False`` to execute.

        After rotation, update the ``KILN_ENCRYPTION_KEY`` environment
        variable to the new passphrase and restart the server.

        Args:
            old_passphrase: The current KILN_ENCRYPTION_KEY value.
            new_passphrase: The new passphrase to encrypt with.
            directory: Root directory to scan for encrypted G-code files.
            pattern: Glob pattern for files to process (default ``"*.gcode"``).
            dry_run: Preview only — don't modify files (default ``True``).

        Requires Enterprise license and admin scope.
        
database_statusA

Check database backend status and configuration.

Reports whether Kiln is using SQLite or PostgreSQL, the connection status, and key metrics. Useful for verifying a PostgreSQL migration or diagnosing connectivity issues.

Requires Enterprise license.

configure_ssoA

Configure SSO (OIDC or SAML) for Enterprise authentication.

        Enterprise feature. Sets up single sign-on with your identity provider
        (Okta, Google Workspace, Azure AD, Auth0, etc.).

        Args:
            issuer_url: IdP issuer URL (e.g. ``https://accounts.google.com``).
            client_id: OIDC client ID or SAML entity ID.
            protocol: ``"oidc"`` or ``"saml"``.
            client_secret: OIDC client secret (optional for public clients).
            redirect_uri: Callback URL after auth. Default: ``http://localhost:8741/sso/callback``.
            allowed_domains: Comma-separated email domains (e.g. ``"acme.com,partner.org"``).
            role_mapping: JSON string mapping IdP groups to Kiln roles
                (e.g. ``'{"admins":"admin","devs":"engineer"}'``).
        
sso_login_urlA

Get the SSO login URL to redirect users to the identity provider.

        Enterprise feature. Returns the IdP authorization URL for OIDC or
        the SAML AuthnRequest redirect URL.

        Args:
            state: Optional opaque state parameter for CSRF protection.
        
sso_exchange_codeA

Exchange an SSO authorization code for user identity and role.

        Enterprise feature. After the user completes IdP login, exchange
        the auth code to get their identity, email, groups, and mapped
        Kiln role.

        Args:
            code: The authorization code from the IdP callback.
        
sso_statusA

Check current SSO configuration status.

Enterprise feature. Returns whether SSO is configured, the protocol, issuer, allowed domains, and role mapping.

slice_and_estimateA

Primary estimation tool — slice a 3D model and return time, filament, cost, and printability analysis.

        For G-code files (already sliced), use ``estimate_cost`` instead.
        For quick volume-based estimates without slicing, use ``estimate_material_cost``.

        Slices the model using PrusaSlicer or OrcaSlicer, parses the
        output G-code for time and filament metadata, runs printability
        analysis on the file as it was sliced (a STEP file as Kiln's
        mesh of it), and returns adhesion recommendations — all without
        uploading or starting a print.  When the analysis could not be
        made, ``printability`` is null and ``printability_note`` says
        why.

        Use this tool to answer "how long will this take?" or "how much
        filament will I use?" before committing to a print job.

        Args:
            input_path: Path to the input file (STL, OBJ, 3MF, STEP, AMF).
            printer_id: Optional printer model ID for bundled profile
                auto-selection (e.g. ``"bambu_a1"``, ``"prusa_mini"``).
            profile: Path to a slicer profile/config file (.ini or .json).
                Takes precedence over ``printer_id`` auto-selection.
            material: Filament material (e.g. ``"PLA"``, ``"PETG"``,
                ``"TPU"``).  The slice is set for it -- temperatures,
                melt rate and cooling -- so the time is the time THIS
                material takes (a TPU part is far slower than the same
                part in PLA), and its density gives the weight.
                Default is ``"PLA"``.
            printer_name: Registered printer this estimate is FOR.  Omit
                for the default printer.  An estimate is only as true as
                the profile behind it, so naming a second machine costs
                the job on that machine rather than on the default.
            placement: Where the part goes when the plate still holds the
                last print: ``[x, y]`` in mm (the part's footprint
                origin), a named region (``"front-left"``, ``"centre"``,
                ``"back-right"``, …), or ``"keep"``.  An estimate never
                refuses because of the plate: when the plate still holds
                the last print and no safe spot is named, the estimate is
                for the part on an empty plate and ``plate_note`` says
                so.  Where a named spot is safe, the estimate is of the
                part there, with the clearance verdict in ``placement``.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

estimate_costA

Estimate the cost of a print job from a G-code file (already-sliced only).

        For STL/OBJ files, use ``slice_and_estimate`` instead — it slices
        and estimates in one step.

        The slicer's own ``filament used`` totals are the filament
        figures when the file carries them; otherwise Kiln counts the
        extruding moves itself.  ``estimate.filament_source`` says which,
        and a ``warnings`` entry names both numbers when Kiln's count
        sits more than 5% from the slicer's total.

        Each filament is priced as the material the file was sliced
        for; ``estimate.filaments`` lists them and
        ``estimate.material_source`` says where the material came from.
        When kiln-pro (https://kiln3d.com) answers, the estimate also
        carries a ``cost_intelligence`` field; what it holds depends on
        the tier (https://kiln3d.com/pricing).

        Args:
            file_path: Path to the G-code file.
            material: Filament material (PLA, PETG, ABS, TPU, ASA, NYLON,
                PC, …).  Leave empty to use what the file was sliced
                for, PLA when it names nothing; a named material prices
                every filament.
            electricity_rate: Cost per kWh in USD (default 0.12).
            printer_wattage: Printer power consumption in watts (default 200).
            printer_id: Optional registered printer the print is for;
                passed on with the file when kiln-pro is asked.
        
estimate_print_timeA

Estimate print time and filament usage for a model.

        Slices the model and parses the G-code for print time, filament
        length/weight, and layer count.

        For **already-sliced** G-code files, pass the ``.gcode`` path
        directly — it will be parsed without re-slicing.

        Weight needs a filament density, which lives on a filament
        profile; Kiln's bundled profiles describe a PRINTER and name no
        filament, so pass ``material`` to get a weight.  Without it the
        weight is reported as absent rather than guessed — a key missing
        from the result means the slicer could not answer it, never that
        the answer is zero.

        **See also:** ``estimate_material_cost`` for weight and cost from
        a mesh with your own price per kg, and ``slice_and_estimate`` for
        a fuller analysis with printability scoring.

        :param file_path: Path to STL/3MF/OBJ or .gcode file.
        :param profile: Optional slicer profile path.
        :param printer_id: Optional printer model ID for bundled profile
            (e.g. ``"bambu_a1"``).  Used when no explicit profile is given.
        :param slicer_path: Optional explicit slicer binary path.
        :param material: Optional filament family (``"PLA"``, ``"PETG"``,
            …) used only as a density source for the weight.
        :returns: Dict with time, filament, and layer estimates.
        
estimate_material_costA

Estimate material usage and cost for printing a mesh.

        Computes filament weight, length, and cost based on mesh volume,
        infill percentage, wall shell count, and material density.  The
        walls are as wide as the nozzle, and the reply's ``nozzle`` says
        which size was used and where it came from.

        **See also:** ``estimate_print_cost_from_mesh`` for a richer
        estimate that includes support material, adhesion, and electricity.

        Supported materials: pla, petg, abs, tpu, asa, nylon, pc, pla+,
        carbon_fiber_pla.

        :param file_path: Path to mesh file (.stl, .obj, or .glb).
        :param material: Material type (default "pla").
        :param infill_pct: Interior fill percentage 0-100 (default 20).
        :param wall_layers: Number of perimeter shells (default 3).
        :param cost_per_kg: Override material cost in $/kg (0 = use default).
        :param nozzle_mm: Nozzle size in mm.  Left out, Kiln uses the
            nozzle of the only printer it knows of, else its default.
        :returns: Dict with weight, filament length, cost, and ``nozzle``.
        
estimate_print_progressA

Estimate print progress with phase-aware time prediction.

        Breaks a print into phases -- preparing, printing, cooling, and
        post-processing -- and uses historical data from the print outcomes
        database to estimate time remaining.  Typically more accurate than
        raw firmware estimates for predicting true completion time.

        Supply ``elapsed_seconds``, ``total_layers``, and ``current_layer``
        when available; any omitted values will be read from the printer's
        live status.

        :param printer_name: Printer running the job.
        :param elapsed_seconds: Seconds elapsed since print start.  Omit to
            read from printer status.
        :param total_layers: Total layer count for the job.  Omit to read
            from printer/G-code metadata.
        :param current_layer: Current layer being printed.  Omit to read
            from printer status.

        See also: ``printer_status()``, ``get_print_outcomes()``.
        
estimate_before_designA

Estimate print time, cost, and filament usage BEFORE generating a model.

        Works from dimensions alone — no file, no slicing, no generation
        needed.  Use this to answer "how long will it take?", "how much
        will it cost?", and "how much filament?" before committing to a
        design.

        **Two ways to specify dimensions:**

        1. **Direct dimensions** — provide ``width_mm``, ``depth_mm``,
           ``height_mm`` explicitly.
        2. **Template** — provide ``template_id`` (e.g. ``"phone_stand"``,
           ``"box_with_lid"``) and optional ``template_overrides`` to use
           the template's default dimensions.

        **Multi-material prints:** Pass comma-separated materials
        (e.g. ``"PLA,PLA"`` for two-color) with optional fractions
        (e.g. ``"0.85,0.15"`` for body + accent).  The tool estimates
        per-filament usage and tool change overhead automatically.

        Returns time estimate, per-filament weight/length/cost breakdown,
        electricity cost, total cost, and tool swap count.

        :param width_mm: Part width (X) in mm.  Required if no template.
        :param depth_mm: Part depth (Y) in mm.  Required if no template.
        :param height_mm: Part height (Z) in mm.  Required if no template.
        :param template_id: Design template ID (e.g. ``"phone_stand"``).
            Resolves dimensions from template defaults.  Overrides
            width/depth/height if provided.
        :param template_overrides: JSON string of template parameter
            overrides (e.g. ``'{"phone_width": 85}'``).
        :param materials: Comma-separated material names
            (e.g. ``"PLA"`` or ``"PLA,PLA"`` for two-color).
        :param material_fractions: Comma-separated volume fractions
            (e.g. ``"0.85,0.15"``).  Must match materials count and sum
            to 1.0.  Default: body gets 85%, accents split the rest.
        :param material_roles: Comma-separated role labels
            (e.g. ``"body,accent"``).  Default: auto-generated.
        :param infill_percent: Infill density override (0-100).
            Default: from printer profile or 20%.  Pass ``-1`` for auto.
        :param layer_height_mm: Layer height override.  ``0`` = auto.
        :param nozzle_mm: Nozzle diameter in mm.  Leave unset for the
            nozzle Kiln has for ``printer_id`` (or the only printer it
            knows of), else 0.4.
        :param wall_layers: Number of perimeter shells (default 3).
        :param printer_id: Printer model for speed/setting lookup
            (e.g. ``"bambu_a1"``, ``"prusa_mk4"``).
        :param tool_changer_addon: Optional multi-material add-on ID.
            Overrides the printer's built-in tool change timing.
            Examples: ``"creality_cfs"`` (K1 series),
            ``"mosaic_palette3"`` (universal), ``"coprint_kcm"``
            (Klipper printers), ``"chameleon_mk4"`` (universal),
            ``"elegoo_canvas"`` (Centauri Carbon 2).
            Use ``list_multi_material_addons`` to see all options.
        :param electricity_rate: Cost per kWh in USD (default 0.12).
        :param printer_wattage: Printer power in watts (default 200).
        
list_multi_material_addonsA

List available multi-material add-on systems for 3D printers.

        Returns a catalog of optional multi-material add-ons (Creality CFS,
        Mosaic Palette, Co Print KCM, 3D Chameleon, Elegoo CANVAS) with
        their tool change times, color capacity, and compatibility info.

        When a ``printer_id`` is provided, only add-ons compatible with
        that printer are returned.  Universal add-ons (Palette, Chameleon)
        appear for all printers.  Klipper-only add-ons (KCM) appear only
        for Klipper-based printers.

        Use the returned ``id`` values as the ``tool_changer_addon``
        parameter in ``estimate_before_design`` to model multi-material
        prints on printers that don't have a built-in tool changer.

        :param printer_id: Optional printer model to filter by compatibility
            (e.g. ``"k1"``, ``"ender3"``, ``"voron_2"``).
        
load_filamentA

Feed filament to the nozzle — an AMS tray on Bambu, a manual feed elsewhere.

On Bambu Lab the firmware's own change-filament routine runs (retract,
feed, purge) and the answer is read from the AMS: ``extrusion_verified``
is ``True`` once ``tray_now`` reports the tray feeding the nozzle,
``False`` with the fault code in plain language if the routine raised
one (the same HMS codes the touchscreen shows), ``None`` if neither
arrived in ``wait_seconds``.  On Klipper a ``LOAD_FILAMENT`` / ``M701``
macro from the printer's own config is used when it exists; otherwise,
and on OctoPrint / Duet / serial, the hotend is heated and
``length_mm`` is fed at 3 mm/s — push the filament into the extruder
first.

Temperature is checked against the printer's safety profile, the
spool's own ``nozzle_temp_min/max`` (AMS) or Kiln's material table,
and the 170 °C cold-extrusion floor; refused outside any of them.
Refused while a print is running (paused is fine).

Branch on ``outcome`` — one field, three values, the same shape
``set_temperature`` and ``start_print`` use:

- ``"confirmed"``: the printer showed the effect (the AMS reports the
  tray feeding the nozzle).
- ``"accepted"``: the command was sent and not refused, and the printer
  has not shown the effect yet.  A Bambu load takes a minute or two
  and a tool call cannot wait that long, so this is the normal answer
  when the watch runs out: the routine is still running.  Do NOT send
  the load again — read ``next_read`` (``ams_status`` for ``tray_now``,
  ``printer_status`` for ``print_error``) to finish the answer.
- ``"failed"``: the gate or the printer refused, or a fault was raised
  (``error_code`` / ``error_hint``).

On Bambu Lab that check binds what Kiln sends, not what the routine
does: the firmware heats to its own flush temperature for a filament
change (250 °C observed on an A1 asked for 215, the ``M109 S250`` its
own start sequence sets) and drops to the requested target only when
the routine finishes.  The answer reports the temperature the firmware
actually used (``firmware_hotend_target_c``) beside the one Kiln
validated; the gate is not widened to match it.

Where the declared model's own purge position is served one plan at a time through Kiln's hosted service for a printer paired to your Kiln sign-in, free, and kept on your machine so it works offline, the head is parked over the purge chute
before the routine runs, so its purge falls into the chute instead of
hanging off the nozzle at home; the answer says where the head was
either way.

Args:
    slot: The printer's own tray id, as ``ams_status`` lists it in
        ``tray_id`` (0–3 on unit A, 4–7 on unit B, 128 for the AMS HT
        named HT-A).  Omit for the external / single spool.
    material: e.g. ``"PLA"`` — picks a temperature when none is given
        and no spool report supplies one.
    temperature: Hotend target in °C.  Omit to use the middle of the
        spool's or material's window.
    length_mm: Feed distance for the generic G-code path (default 60;
        bowden machines need more).  Ignored where the firmware's own
        routine decides.
    wait_seconds: How long to watch for the AMS to confirm.  Bounded to
        what a tool call can wait inside the client's request window
        (40 s unless ``KILN_FILAMENT_WAIT_BUDGET_S`` says otherwise); a
        longer ask is applied at the bound and the response says so.
    keep_hot: Leave the heater ON afterwards, for a caller about to do
        something else hot.  Off by default: every op ends with the
        heater off and says so; where the machine's own cool-down is
        served, the part fan goes on and Kiln turns it off on its own
        once the nozzle reads the hand-off temperature -- the answer
        does not wait for that, and ``printer_status`` shows it.
    printer_name: Which printer.  Omit for the default one.
unload_filamentA

Pull filament out of the hotend — back into the AMS on Bambu, a heated retract elsewhere.

Same temperature gate, verification, ``outcome`` vocabulary and wait
bound as ``load_filament``: on Bambu ``extrusion_verified`` is ``True``
once the AMS reports no tray feeding the nozzle (``tray_now`` 255); on
Klipper an ``UNLOAD_FILAMENT`` / ``M702`` macro is used when the config
has one; otherwise the hotend is heated and ``length_mm`` is retracted
(default 80).

Args:
    material / temperature / length_mm / wait_seconds / keep_hot /
        printer_name: as ``load_filament``.  Unload never retracts at
        the end (the filament is already out) but still turns the
        heater off unless ``keep_hot`` asks otherwise.
purge_filamentA

Heat the nozzle and extrude a short length — the clog test.

Reports what the printer could honestly say, not that a command was
sent: ``extrusion_verified`` is ``False`` with ``error_hint`` when the
firmware refused the move (cold-extrusion guard, Klipper
``can_extrude=false``) or raised an extrusion fault during or right
after the purge (Bambu HMS codes, decoded to plain language);
``None`` when the move was accepted and the machine reports no flow
signal — every backend without a flow sensor — in which case look at
the nozzle for a clean stream.  It is never ``True`` on a purge alone.

Refused while printing (paused is fine), below 170 °C, above the
printer's safety ceiling, outside the loaded spool's own temperature
window, and beyond 150 mm.

The answer always says where the purge went.  Where the declared
model's own purge position is served one plan at a time through Kiln's hosted service for a printer paired to your Kiln sign-in, free, and kept on your machine so it works offline — the head is parked over the purge chute before the
heater is touched, the machine's own tail snap and shake follow the
extrude, and ``purge_station.status`` is ``"parked"``.  Otherwise it is
``"in_place"`` with the reason (a paused print, or no served position
for the model) and the head's coordinates where the printer reports
any; no coordinate is ever inferred, and no model borrows a sibling's.
A pad wipe is a separate door: ``wipe_nozzle``.

Args:
    length_mm: Extrusion length, 1–150 mm (default 30).
    material: e.g. ``"PLA"`` — picks a temperature when none is given.
    temperature: Hotend target in °C.  Omit to use the middle of the
        spool's (AMS) or material's window.
    slot: AMS tray whose temperature window applies (Bambu).  Omit to
        use the tray currently feeding the nozzle.
    wait_seconds: How long after the purge to watch for a fault code
        on Bambu (default 10).  Bounded the same way as
        ``load_filament``'s.
    keep_hot: Leave the heater ON afterwards, for a caller about to do
        something else hot.  Off by default: every op ends with the
        heater off and says so; where the machine's own cool-down is
        served, the part fan goes on and Kiln turns it off on its own
        once the nozzle reads the hand-off temperature -- the answer
        does not wait for that, and ``printer_status`` shows it.
    printer_name: Which printer.  Omit for the default one.
wipe_nozzleA

Clean the nozzle tip on the printer's own wipe pad.

Heats to the loaded material's window (or the temperature given), parks
over the purge chute while heating, snaps the tail with the vendor's
own retract, then runs the wipe-pad pass the machine's start sequence
runs and reports where the head ended up.  Only where the declared
model's pad pass is served one plan at a time through Kiln's hosted service for a printer paired to your Kiln sign-in, free, and kept on your machine so it works offline
(``printer_model`` in config.yaml names the model).  Any other model is
refused with the reason rather than moved to a guessed coordinate: use
the printer's own screen, or start a print — its start sequence wipes
on the pad.  No model ever borrows a sibling's position.

Same gate as ``purge_filament``: refused while printing, below 170 °C,
above the safety ceiling, outside the loaded spool's own window.  Also
refused while paused — the head is parked over the part and Kiln does
not travel mid-print.  The pad is touched the machine's own way, on the
way down in temperature.  ``extrusion_verified`` stays ``None``: Bambu
acknowledges no G-code, so "no fault raised" is the strongest thing the
printer can say — look at the tip.

Args:
    material: e.g. ``"PLA"`` — picks a temperature when none is given.
    temperature: Hotend target in °C.  Omit to use the middle of the
        spool's (AMS) or material's window.
    slot: AMS tray whose temperature window applies (Bambu).  Omit to
        use the tray currently feeding the nozzle.
    wait_seconds: How long after the wipe to watch for a fault code
        (default 45).
    keep_hot: Leave the heater ON afterwards, for a caller about to do
        something else hot.  Off by default: every op ends with the
        heater off and says so; where the machine's own cool-down is
        served, the part fan goes on and Kiln turns it off on its own
        once the nozzle reads the hand-off temperature -- the answer
        does not wait for that, and ``printer_status`` shows it.
    plate_clear: A PERSON's statement that the plate is empty, given on
        THIS call.  Read on every call by a wipe whose plan presses the
        plate (its Z datum is taken on the plate, or the head has to
        cross the plate to reach the pad), whatever the plate record
        says -- the record cannot see a print started from the printer's
        own screen; without it the tool refuses with
        ``PLATE_CLEAR_REQUIRED`` and, where the printer has a camera,
        ``snapshot_path`` -- look, then call again with it set.  Never
        set it on a person's behalf.
    step: Send only this step of the wipe's plan (1-based); the answer
        describes the next one, and the finish (heater off, the
        cool-down) runs after the last step.  Step mode is how a wipe
        no one has yet run on a real machine is benched -- one motion,
        one report, one go -- and the only way such a wipe runs.
    plan_only: Describe the steps; send nothing.
    printer_name: Which printer.  Omit for the default one.
firmware_statusA

Check firmware updates on the default/connected printer (adapter-level, no name needed).

        For fleet setups where you need to check a specific printer by name,
        use ``check_firmware_status`` instead.  Returns a list of firmware
        components (e.g. Klipper, Moonraker, OctoPrint) with current and
        available versions, plus whether
        an update is available.

        Not all printer backends support firmware updates.  Bambu and
        Prusa Link printers will return an ``UNSUPPORTED`` error.
        
check_firmware_statusA

Check firmware version for a specific printer by name (fleet-level, firmware manager).

        Use this in multi-printer setups. For single-printer setups where you
        don't need to specify a name, use ``firmware_status`` instead.

        Args:
            printer_name: Printer to check.
        
update_printer_firmwareA

Start a firmware update on a specific printer by name (fleet-level, supports version pinning).

        Use this in multi-printer setups. For single-printer setups, use ``update_firmware`` instead.

        Args:
            printer_name: Printer to update.
            target_version: Specific version to update to (latest if None).
        
rollback_printer_firmwareA

Rollback firmware on a specific printer by name (fleet-level, supports version pinning).

        Use this in multi-printer setups. For single-printer setups, use ``rollback_firmware`` instead.

        Args:
            printer_name: Printer to rollback.
            target_version: Specific version to rollback to.
        
fleet_analyticsA

Get fleet historical analytics: per-printer success rates, utilization, job throughput.

        For live printer status (current state/temps), use ``fleet_status``.
        Returns statistics for every registered printer including total prints,
        success rate, average print duration, and total print hours.  Also
        includes fleet-wide aggregate metrics.

        Requires Business license.
        
list_fleet_sitesA

List all fleet sites/locations with printer counts.

Returns the distinct sites defined across registered printers. Useful for multi-site fleet dashboards.

Requires Enterprise license.

fleet_status_by_siteA

Get fleet status grouped by physical site/location.

        Returns printer statuses organized by site, making it easy to see
        which printers are idle, busy, or offline at each location.
        Printers without a site are grouped under ``"unassigned"``.

        Requires Enterprise license.
        
update_printer_siteB

Assign a printer to a physical site/location with optional tags.

        Args:
            name: Registered printer name.
            site: Physical site or location label (e.g. ``"nyc-lab"``,
                ``"chicago-floor-2"``).
            tags: Comma-separated key=value pairs for metadata
                (e.g. ``"building=A,floor=3,owner=team-alpha"``).

        Requires Enterprise license.
        
route_print_jobA

Route a print job to the best available printer in the fleet.

        Scores each registered printer on material match, availability,
        queue depth, and historical success rate, then recommends the
        best assignment with scored alternatives.  Every candidate also
        carries a ``plate`` block -- whether the plate as it stands has
        room for this part and how a print there would start.  A machine
        with no room, or a plate Kiln has no record of, is never
        recommended; when none has room the answer is a refusal
        (``NO_ROOM``) with each machine's own sentence.  A print that
        would start the quiet way beside a part still on the plate is
        scored lower unless ``priority`` is high.

        Args:
            file_path: Path to the file to print.
            material: Required filament material (e.g. "PLA", "PETG").
            quality: Quality preference — "draft", "standard", or "fine".
            priority: Job urgency — "low", "normal", or "high".
        
fleet_submit_jobA

Submit a print job to the fleet orchestrator.

        If no printer is specified, the orchestrator auto-assigns to the best
        available printer. Tracks the job through completion.

        Before anything is queued, every candidate plate is surveyed as it
        stands (the named printer's, or the whole fleet's): a job no plate
        has room for is refused here, with each machine's own sentence
        (``NO_ROOM``), never queued to be refused at the printer later.

        Args:
            file_path: Path to the file to print.
            printer_name: Specific printer to assign to (auto-routes if None).
            material: Required filament material.
            priority: Job priority (low, normal, high).
            idempotency_key: Optional opaque key (e.g. a UUID you
                generate) naming this one submission.  If the call
                fails in a way where you cannot tell whether the job
                was queued, retry with the SAME key to get the
                original job back (``submission: "replayed"``)
                instead of queuing a duplicate print.  Use a new key
                for each job you genuinely want printed.
        
fleet_job_statusC

Get the status of a fleet-managed print job.

        Args:
            job_id: The orchestrated job's identifier.
        
fleet_utilizationA

Get fleet utilization metrics — busy/idle/offline counts and utilization %.

        Lightweight overview of fleet capacity. For full printer details, use
        ``fleet_status``. For historical analytics, use ``fleet_analytics``.
        
fulfillment_materialsA

List available materials from external manufacturing services.

        Returns materials with technology (FDM, SLA, SLS, etc.), color,
        finish, and pricing.  Use the material ``id`` when requesting a quote
        with ``fulfillment_quote``.

        The full catalog contains 2000+ materials.  Use the optional filter
        parameters to narrow results so agents can find the right material
        without overwhelming context windows.

        Args:
            search: Filter materials whose name contains this term
                (word-boundary match, case-insensitive).  E.g. ``"nylon"``
                matches "Nylon 12" and "Glass-filled Nylon" but not
                "Carbonylon".
            technology: Filter by manufacturing technology (word-boundary
                match, case-insensitive).  Common values: ``"SLS"``,
                ``"FDM"``, ``"SLA"``, ``"MJF"``, ``"DMLS"``.  Matches
                against both the technology field and the material name.
            limit: Maximum number of materials to return (default 50).
        
fulfillment_quoteA

Get a manufacturing quote for a 3D model from Craftcloud.

        Args:
            file_path: Absolute path to the model file (STL, 3MF, OBJ).
            material_id: Material ID from ``fulfillment_materials``.
            quantity: Number of copies to print (default 1).
            shipping_country: ISO country code for shipping (default "US").

        Uploads the model, returns pricing from Craftcloud's network of 150+
        print services, including unit price, total, lead time, and shipping
        options. A Kiln orchestration fee is shown separately so
        the user sees the full cost before committing.

        If a payment method is linked, a hold is placed on the fee amount
        at quote time (Stripe auth-and-capture).  The hold is captured
        when the order is placed via ``fulfillment_order``, or released
        if the user doesn't proceed.

        The reply opens with ``tell_the_person``: the price and what it
        is made of, timing, what more copies would cost, and the print
        service's order terms with a link to them, already worded for
        the person. Pass every line on to them word for word, in order,
        before they decide; do not summarise, shorten or drop any.
        ``quote.price_sheet`` holds the same numbers as data.

        Use the returned ``quote_id`` with ``fulfillment_order`` to place the
        order.
        
save_shipping_profileA

Save a local shipping profile after explicit user consent.

        Args:
            name: Profile name, e.g. ``"home"`` or ``"office"``.
            shipping_address: Full shipping contact/address dict. Keys:
                ``first_name``, ``last_name``, ``email``, ``phone``,
                ``street``, ``city``, ``postal_code``, ``country``;
                include ``state`` for US addresses.
            overwrite: Replace an existing profile with the same name.
            set_default: Make this the default shipping profile.
            consent_to_store: Must be ``True``. This is the explicit
                consent gate for storing personal contact/address data.
        
list_shipping_profilesA

List saved local shipping profiles.

        Args:
            include_addresses: Include full contact/address fields. Defaults
                to ``False`` so listing profiles does not expose personal
                details unless the user is actively reviewing them.
        
delete_shipping_profileC

Delete a saved local shipping profile.

        Args:
            name: Profile name to delete.
        
issue_shipping_confirmation_tokenA

Issue a single-use token after the user confirms shipping details.

        Call this only after showing the normalized contact/shipping address
        and selected shipping option to the user, asking whether Kiln should
        save the address as a profile, and receiving approval.
        ``fulfillment_order`` refuses to place an order without this token.

        Args:
            quote_id: Quote ID from ``fulfillment_quote``.
            shipping_option_id: Shipping option ID selected from the quote.
            shipping_address: Explicit full shipping address.
            shipping_profile_name: Saved profile name to use instead of
                passing ``shipping_address``.
            save_profile_decision: Required when ``shipping_address`` is
                provided directly. Pass ``"save"`` only after the user says
                yes; pass ``"do_not_save"`` after the user says no.
            save_profile_name: Profile name to save when
                ``save_profile_decision`` is ``"save"``.
            overwrite_saved_profile: Replace an existing profile with the
                same name when saving.
            set_default_profile: Make the saved profile the default.
            ttl_seconds: Token lifetime, default 10 minutes.
        
fulfillment_orderA

Place a manufacturing order based on a previous quote.

        Charges the orchestration fee BEFORE placing the order to prevent
        unpaid orders.  If order placement fails after payment, the
        charge is automatically refunded.

        Args:
            quote_id: Quote ID from ``fulfillment_quote``.
            shipping_option_id: Shipping option ID from the quote's
                ``shipping_options`` list.
            shipping_address: Optional shipping contact/address dict for
                provider checkout. Keys: ``first_name``, ``last_name``,
                ``email``, ``phone``, ``street``, ``city``,
                ``postal_code``, ``country``; include ``state`` for US.
            shipping_profile_name: Saved shipping profile name to use
                instead of passing ``shipping_address``.
            preview_token: Token from ``issue_preview_token`` after the
                rendered model preview was shown to and approved by the user.
            preview_file_path: Exact model file path that was previewed.
                The preview token is validated against this file's bytes.
            shipping_confirmation_token: Token from
                ``issue_shipping_confirmation_token`` after the contact and
                shipping address were shown to and approved by the user.
            payment_hold_id: PaymentIntent ID from the quote's
                ``payment_hold`` field.  If provided, the previously
                authorized hold is captured before placing the order.
                This is the preferred payment flow.
            quoted_price: Total price returned by ``fulfillment_quote``
                (used to calculate the fee when no ``payment_hold_id``
                is provided).  Required when ``payment_hold_id`` is
                empty and a payment rail is configured.
            quoted_currency: Currency of ``quoted_price`` (default USD).
            jurisdiction: Buyer's region (e.g. ``"US-CA"``, ``"DE"``, ``"AU"``).
                When provided, the response includes an accurate total with
                tax so the user sees exactly what they'll pay — no hidden
                fees.  Use ``tax_jurisdictions`` to see all supported codes.
            business_tax_id: If the buyer is a registered business, their
                tax ID (EU VAT number, AU ABN, etc.).  Businesses in the
                EU, UK, Australia, and Japan are tax-exempt via reverse
                charge — the tax line shows $0.00.

        Use ``fulfillment_order_status`` to track progress after placing.

        Nothing is made until the person pays on the print service's
        checkout, so the reply opens with ``tell_the_person``: the link to
        pay first, then the checkout total with any tax, the print
        service's order terms and a link to them. Pass every line on to
        the person word for word.

        If the person asks whether they can pay with a particular method,
        answer from ``provider_pay_methods`` in the reply: yes for one it
        lists; for any other, say Kiln doesn't know and that the checkout
        page shows every option for their country. Never claim a method
        that isn't listed.
        
fulfillment_order_statusA

Check the status of a fulfillment order.

        Args:
            order_id: Order ID from ``fulfillment_order``.

        Returns current order state, tracking info, and estimated delivery.

        The reply opens with ``tell_the_person``: where the order is and,
        while it is unpaid, the link to pay for it. Pass every line on to
        the person word for word.

        Nothing is made until an order is paid on the print service's
        checkout, and Kiln cannot pay it for them. When the person wants to
        pay, asks how to pay, or asks about an order that is not paid yet,
        call this right away for that order and give them the link to pay
        first, before anything else, without waiting to be asked for it.

        If the person asks whether they can pay with a particular method,
        answer from ``provider_pay_methods`` in the reply: yes for one it
        lists; for any other, say Kiln doesn't know and that the checkout
        page shows every option for their country. Never claim a method
        that isn't listed.
        
fulfillment_cancelA

Cancel a fulfillment order (if still cancellable).

        Args:
            order_id: Order ID to cancel.

        Only orders that have not yet shipped can be cancelled. When the
        print service has nothing to cancel (an unpaid order is never
        made) or cancels only on a written request, the error message
        says which and how; pass it on to the person as it is.
        
fulfillment_alertsA

Check for fulfillment order alerts (stalled, failed, cancelled orders).

Returns any active alerts from the background fulfillment monitor. Alerts are generated when orders are cancelled/failed by the provider or have been stuck in processing longer than the expected lead time.

validate_gcodeA

Validate G-code syntax and basic safety (generic, no printer-specific limits).

        For printer-specific safety validation (PTFE temp caps, speed limits),
        use ``validate_gcode_safe`` with a ``printer_id`` instead.

        Args:
            commands: One or more G-code commands separated by newlines.

        Returns a JSON object with:
        - ``valid``: whether all commands passed safety checks
        - ``commands``: the parsed command list
        - ``errors``: blocking issues (temperature limits, firmware commands)
        - ``warnings``: non-blocking advisories (Z below bed, high feedrate)
        - ``blocked_commands``: specific commands that were blocked

        Use this to preview what ``send_gcode`` would accept or reject.
        
validate_gcode_safeA

Validate G-code with printer-specific safety limits (PTFE temp caps, speed limits).

        Preferred over ``validate_gcode`` when you know the target printer — uses
        that printer's safety profile for accurate limits.  Without a printer_id,
        falls back to conservative generic defaults.

        Args:
            commands: G-code commands separated by newlines.
            printer_id: Optional printer model ID for profile-aware validation.
        
validate_print_qualityA

Validate print quality after a completed print job.

        Captures a webcam snapshot (if available), examines the job record and
        events, and produces a quality assessment with recommendations.

        Args:
            job_id: The completed job's ID.  If omitted, uses the most recent
                completed job.
            printer_name: Target printer name (omit for default printer).
            save_snapshot: Optional file path to save the post-print snapshot.

        Returns a quality report with snapshot data, job metrics, and any
        detected issues.
        
list_generation_providersA

List available text-to-3D generation providers.

        Returns details about each provider: name, description,
        available styles, and whether it requires an API key.
        Use this to discover providers before calling ``generate_model``.
        
generate_modelA

Generate a 3D model from a text prompt via external AI API (Meshy/etc).

        Pass ``material`` when the user has named one ("print this in
        TPU") — it steers the design-intelligence prompt enrichment
        toward that material's constraints.  It is a design hint, not a
        slicing setting; leave it empty when the material is undecided.

        Start here if user has no template/image — just a text description.
        For image-based generation, use ``generate_model_from_image``.
        For parametric templates (local, no AI API needed), use ``generate_from_template``.
        To also slice + upload in one step, use ``generate_and_print``.

        **EXPERIMENTAL:** AI-generated 3D models are experimental and may not
        be suitable for printing without manual review.  Generated geometry
        can have thin walls, non-manifold faces, floating islands, or
        dimensions that exceed printer build volume.  3D printers are delicate
        hardware — always validate the generated mesh before printing.

        **When possible, prefer downloading proven community models from
        marketplaces** (Thingiverse, MyMiniFactory) over generating new ones.
        Use generation for custom/unique objects only.

        Submits a generation job to the specified provider and returns a
        job ID for status tracking.  Use ``generation_status`` to poll for
        completion, then ``download_generated_model`` to retrieve the file.

        **Prompt tips for Meshy (text-to-3D AI):**
        - Describe the physical object clearly: shape, size, purpose.
        - Include material cues: "wooden", "metallic", "smooth plastic".
        - Specify printability: "solid base", "no overhangs", "flat bottom".
        - Keep prompts under 200 words for best results (max 600 chars).
        - Good example: "A phone stand with a curved cradle, flat rectangular
          base, and angled back support. Smooth plastic surface."
        - Bad example: "make me something cool" (too vague).

        **For OpenSCAD**, the prompt must be valid OpenSCAD code.  The job
        completes synchronously and the result is immediately available.

        Args:
            prompt: Text description (or OpenSCAD code for ``openscad``).
            provider: Generation backend — ``"meshy"`` (cloud AI) or
                ``"openscad"`` (local parametric).  Default: ``"meshy"``.
            format: Desired output format (``"stl"``).  Default: ``"stl"``.
            style: Optional style hint (``"realistic"`` or ``"sculpture"``
                for Meshy).  Ignored by OpenSCAD.

MAKE DOORS: design_session, Kiln's front door for making an object, is not installed here (signed in to Kiln it runs on Kiln's servers). On this install compile_scad IS the make → preview → iterate loop: make it, show the preview, iterate.

generate_model_from_imageA

Make a 3D model from a reference image.

        DEFAULT (keyless): you (the agent) can SEE the image — study it,
        give it to ``design_session`` as ``reference_images`` (every later
        make is checked against it), and write the OpenSCAD yourself for
        ``design_session(verb="generate", scad_code=...)`` — or
        ``compile_scad`` on an install without ``design_session``. You do
        NOT need an image-to-3D provider, and with no key configured this
        tool hands the job back to your vision instead of erroring.

        OPT-IN cloud path: when the user has set their OWN
        KILN_MESHY_API_KEY, this submits the image to Meshy for an AI mesh
        reconstruction. The image should show the object clearly against a
        clean background for best results.

        **EXPERIMENTAL:** AI-generated models are experimental.  Always
        validate the mesh before printing.

        ``reference_picture`` says what becomes of the picture: compared
        with the model when it arrives and with every make on the goal it
        is given to, or, where this install cannot compare, that you must.

        **Image tips:**
        - Use a clear, well-lit photo of the object.
        - Plain/solid backgrounds produce better results.
        - Show the full object — avoid cropped or partial views.
        - Multiple angles are not supported; use the best single view.

        Args:
            image_url: URL to the reference image (PNG, JPG).  Must be
                publicly accessible.
            provider: Generation provider.  Currently only ``"meshy"``
                supports image-to-3D.
            style: Optional style hint (``"realistic"`` or ``"sculpture"``).

MAKE DOORS: design_session, Kiln's front door for making an object, is not installed here (signed in to Kiln it runs on Kiln's servers). On this install compile_scad IS the make → preview → iterate loop: make it, show the preview, iterate.

generation_statusB

Check the status of a model generation job.

        Args:
            job_id: Job ID returned by ``generate_model``.
            provider: Provider that owns the job (``"meshy"`` or ``"openscad"``).
        
download_generated_modelA

Download a completed generated model, check it, and open it on the stage.

        The result says where the model came from (``came_from``: the
        provider and the prompt) and, when the provider was asked for a
        shape and not a size, that its numbers are not millimetres
        (``size_check``).  A note beside the file keeps where it came
        from, so the stage and design history can say so later.

        Args:
            brief_id: The saved goal's id from ``design_session``; pass it so
                this make joins the goal (recorded against it; Kiln Pro checks the
                result against it). Empty when there is no goal.
            job_id: Job ID of a completed generation job.
            provider: Provider that owns the job (``"meshy"`` or ``"openscad"``).
            output_path: Directory to save the file.  Defaults to
                the system temp directory.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

MAKE DOORS: design_session, Kiln's front door for making an object, is not installed here (signed in to Kiln it runs on Kiln's servers). On this install compile_scad IS the make → preview → iterate loop: make it, show the preview, iterate.

await_generationA

Wait for a generation job to complete and return the final status.

        Polls the provider until the job reaches a terminal state or the
        timeout is exceeded.  Useful for agents that want to block until
        a model is ready.

        Args:
            job_id: Job ID from ``generate_model``.
            provider: Provider that owns the job.
            timeout: Max seconds to wait for generation (default 600 = 10 min).
            poll_interval: Seconds between polls (default 10).
        
generate_and_printA

Full pipeline: generate a model, validate, slice, and upload (preview).

        **EXPERIMENTAL:** This generates a 3D model, validates it, slices it,
        and uploads it to the printer — but does NOT start printing.  3D
        printers are delicate hardware and AI-generated models are not
        guaranteed to be safe or printable.  You MUST call ``start_print``
        separately after reviewing the preview results.

        When possible, prefer downloading proven models from marketplaces
        (Thingiverse, MyMiniFactory) instead of generating new ones.

        Args:
            brief_id: The saved goal's id from ``design_session``; pass it so
                this make joins the goal (recorded against it; Kiln Pro checks the
                result against it). Empty when there is no goal.
            prompt: Text description of the 3D model to generate.
            provider: Generation provider (``"meshy"`` or ``"openscad"``).
            style: Optional style hint for cloud providers.
            printer_name: Target printer.  Omit for the default printer.
            profile: Slicer profile path.
            printer_id: Optional printer model ID for bundled profile
                auto-selection (e.g. ``"prusa_mini"``).
            timeout: Max seconds to wait for generation (default 600).
            material: Filament material for the slice (``"PLA"``,
                ``"PETG"``, …).  It sets the temperatures, melt rate and
                cooling, and its density weighs the print.  Omitted, the
                spool the printer reports loaded answers, then PLA —
                ``slice.filament`` says which.
            placement: Where the part goes when the plate still holds
                the last print: ``[x, y]`` in mm, a named region
                (``"front-left"``, ``"centre"``, …), or ``"keep"``.
                Omitted, an occupied plate refuses before slicing and
                lists the spots that would work.  The clearance verdict
                is free; placing and starting a second print on an
                occupied plate is a kiln-pro feature
                (https://kiln3d.com/pricing).

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

MAKE DOORS: design_session, Kiln's front door for making an object, is not installed here (signed in to Kiln it runs on Kiln's servers). On this install compile_scad IS the make → preview → iterate loop: make it, show the preview, iterate.

smart_generate_from_templateA

Generate from template + structural analysis + print settings (recommended for functional parts).

        Higher-level than ``generate_from_template`` — adds structural risk analysis
        and auto-reinforcement. This is the **one-step design-to-print-ready** pipeline:

        1. Generates STL from a parametric template (like ``generate_from_template``)
        2. Runs structural risk analysis (thin necks, cantilevers, sharp corners)
        3. Optionally auto-applies reinforcements (fillets, wall thickening, etc.)
        4. Infers optimal slicer settings tuned to the design's structural profile
        5. Returns the STL path + recommended settings ready for slicing

        The agent can take the output and directly call ``reslice_with_overrides``
        or ``run_reslice_and_print`` with the recommended settings.

        :param brief_id: The saved goal's id from ``design_session``; pass it so
            this make joins the goal (recorded against it; Kiln Pro checks the
            result against it). Empty when there is no goal.
        :param template_id: Template ID from ``list_design_templates``.
        :param parameters: Parameter overrides (e.g., ``{"phone_width": 80}``).
        :param material: Filament type for settings inference and for the
            reinforcements (PLA, PETG, ABS, etc.).
        :param auto_reinforce: If True, auto-apply structural reinforcements.
        :param printer_id: The printer the part is for, so the reinforcements
            are sized for its nozzle and layer height.
        :returns: Dict with STL path, structural grade, reinforcements, and print settings.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

MAKE DOORS: design_session, Kiln's front door for making an object, is not installed here (signed in to Kiln it runs on Kiln's servers). On this install compile_scad IS the make → preview → iterate loop: make it, show the preview, iterate.

generate_template_variationsB

Generate multiple variations of a parametric template.

        Creates N variations by sampling parameter values across their
        valid ranges.  Useful for exploring design space or offering
        choices to the user.

        :param template_id: Template ID (e.g. ``"phone_stand"``).
        :param variation_count: Number of variations (1-10, default 3).
        :param parameter_ranges: Optional overrides ``{param: [min, max]}``.
        :returns: Dict with list of generated variations and their files.

MAKE DOORS: design_session, Kiln's front door for making an object, is not installed here (signed in to Kiln it runs on Kiln's servers). On this install compile_scad IS the make → preview → iterate loop: make it, show the preview, iterate.

generate_model_with_providerA

Generate a printable design via an external AI provider.

        The cloud, provider-backed creation path: hands a natural-language
        description to an external idea-to-3D service, audits the candidate
        for printability and design correctness, and can perform one or
        more corrective retries using feedback from failed attempts.

        This is NOT the default. It needs a configured provider (the user
        supplies their own API key). For most custom objects the free,
        keyless path is to author the OpenSCAD yourself and make it with
        ``design_session(verb="generate", goal_id=..., scad_code=...)`` —
        or ``compile_scad`` on an install without ``design_session`` — no
        provider required. Reach for this tool when the shape is organic
        or photo-derived and hard to express in OpenSCAD AND a provider is
        configured.

        For the user-facing saved-goal flow (capturing duty / environment /
        materials / safety so the audit and post-print review can verify
        the result against the user's intent), call this through
        ``design_session(verb="generate", goal_id=...)`` rather than
        calling ``generate_model_with_provider`` directly.

        Provider notes:
        - ``auto`` prefers Gemini for idea-to-CAD when available.
        - ``openscad`` is intentionally rejected here because it compiles
          code; it does not turn a natural-language idea into geometry.

        No-provider fallback:
        - If no cloud provider is configured this raises NO_PROVIDER. Do
          NOT ask the user to set an API key — fall back to writing the
          OpenSCAD yourself and making it through design_session (or
          compile_scad where design_session is not installed). That free,
          local path is the default for custom objects; cloud providers are
          an opt-in the user supplies their own key for (best for organic
          or photo-based shapes OpenSCAD can't easily reach).

        Args:
            brief_id: The saved goal's id from ``design_session``; pass it so
                this make joins the goal (recorded against it; Kiln Pro checks the
                result against it). Empty when there is no goal.
            requirements: Natural-language description of the part to create.
            provider: ``auto``, ``gemini``, ``meshy``, ``tripo3d``, or ``stability``.
            material: Optional material target (e.g. ``"petg"``).
            printer_model: Optional printer model ID (e.g. ``"bambu_a1"``).
            style: Optional style hint for providers that support it.
            output_dir: Optional directory for generated files.
            build_volume_x: Optional build volume X override in mm.
            build_volume_y: Optional build volume Y override in mm.
            build_volume_z: Optional build volume Z override in mm.
            nozzle_diameter: Printer nozzle diameter in mm.
            layer_height: Printer layer height in mm.
            max_overhang_angle: Supportless overhang threshold in degrees.
            timeout: Max seconds to wait per generation attempt.
            max_attempts: Max corrective generation attempts.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

MAKE DOORS: design_session, Kiln's front door for making an object, is not installed here (signed in to Kiln it runs on Kiln's servers). On this install compile_scad IS the make → preview → iterate loop: make it, show the preview, iterate.

preview_generated_modelA

Specialized post-generation verification renderer. For general-purpose model viewing, use visualize_model instead. This tool adds generation-specific checks (floating geometry, thin walls) on top of the standard multi-angle renders.

        Render a 3D model to multi-angle PNG previews for visual inspection.

        **REQUIRED** before printing any generated model.  You MUST call this
        tool after generating a model and BEFORE printing.  View ALL rendered
        angles to check for:
        - Missing or simplified features (e.g., plain box instead of pattern)
        - Incorrect proportions or dimensions
        - Floating/disconnected geometry
        - Thin walls that won't print
        - Overhangs that need supports
        - Non-manifold artifacts
        - Bottom surface not flat (check bottom view for bed adhesion)
        - Elephant's foot risk on first layer

        **Required workflow:**
        1. Call ``generate_model`` or ``generate_model_from_image``
        2. **MUST** call ``preview_generated_model`` — view ALL angles
        3. If the model doesn't match the request, regenerate with refined prompt
        4. Call ``validate_generated_mesh`` for structural checks
        5. Only then proceed to print

        Args:
            file_path: Path to an STL or 3MF file to render.  Colored 3MF
                files are rendered with per-face colors via the PIL-based
                colored renderer; STL and colorless 3MF use OpenSCAD.
        
validate_and_prepare_meshA

Full validation pipeline: validate, repair, analyze, and prepare a mesh for printing.

        **See also:** ``validate_and_prepare`` for a more comprehensive
        10-step pipeline (format, mesh, scale, repair, printability,
        structural, bed-fit, material, and cost estimation).

        Runs every AI-generated mesh through Kiln's engineering review before
        it reaches the slicer or printer.  Chains validation → auto-repair →
        printability analysis → build volume check into a single quality gate.

        **Use this instead of ``validate_generated_mesh`` when you want the
        full pipeline** — repair, printability scoring, build volume checks,
        and actionable recommendations.

        The mesh file may be modified in place if ``auto_repair`` or
        ``auto_scale`` is enabled.  The response includes the final file
        path (which may differ from the input if repairs created a new file).

        Args:
            file_path: Path to an STL, OBJ, GLB, or STEP/STP file.
                STEP is converted to a mesh on the way in; if no
                converter is installed the call returns ``NO_BACKEND``
                with a ``remedy`` — read it rather than guessing whether
                the user can fix this (``kiln install-step-backend``) or
                is on a hosted server with nothing to install.
            material: Filament material for printability analysis (default PLA).
            nozzle_diameter: Printer nozzle diameter in mm.  Leave unset to
                check for the nozzle Kiln has for ``printer_id``.
            layer_height: Print layer height in mm (default 0.2).
            build_volume_x: Optional X build dimension (mm).
            build_volume_y: Optional Y build dimension (mm).
            build_volume_z: Optional Z build dimension (mm).
            printer_id: Optional supported printer model id.  When
                provided, printer intelligence supplies the build volume.
            auto_repair: Auto-repair non-manifold meshes (default True).
            auto_scale: Auto-scale if mesh exceeds build volume (default False).
            min_printability_score: Minimum score (0-100) to pass (default 40).
        
generate_textureA

Cloud AI texture generation (requires Meshy API key + internet).

        For instant offline textures without any API, use
        ``apply_procedural_texture`` (multicolor) or
        ``apply_geometric_texture`` (relief) from kiln-pro.

        Takes any untextured mesh (STL, OBJ, GLB) and generates a
        UV-mapped texture based on the text description.  The textured
        model can then be processed with ``auto_multicolor_from_texture``
        (Kiln Pro) for multi-material printing.

        Requires a Meshy API key (``KILN_MESHY_API_KEY``).

        Args:
            mesh_path: Absolute path to the mesh file (STL, OBJ, GLB, FBX).
            prompt: Text description of the desired texture (max 600 chars).
                E.g. "smooth matte wood grain with dark walnut finish".
            style: Art style — ``"realistic"`` (default) or ``"2.5d-cartoon"``.
            provider: Generation provider.  Currently only ``"meshy"`` supports
                retexturing.
        
home_axesA

Home the print head — what the Home button on the printer's screen does.

Refused while a print is running, and while one is paused (the head is
over the part and homing travels).

Where the connected model's own start-sequence homing is served one plan at a time through Kiln's hosted service for a printer paired to your Kiln sign-in, free, and kept on your machine so it works offline — raise first, home X, Z found the way
the maker finds it, park off the plate — it runs that, one described
motion at a time.  A bare ``G28`` from an unknown height is exactly the
move that family's own sequences avoid, so a Bambu model whose sequence
is not served here is refused rather than guessed.  Other backends send
the firmware's own ``G28`` and say so (``sequence_source:
"firmware_home_routine"``) -- but only after the catalogue's motion
record for the declared ``printer_model`` has answered how that routine
finds Z: on a machine whose Z home presses a probe or the nozzle onto
the plate (most of them) the tool asks for ``plate_clear`` first, on
the few whose Z home cannot touch the plate it runs unasked, and with
no ``printer_model`` declared, or one the catalogue does not know, it
refuses and says which key to set (code ``PRINTER_MODEL_REQUIRED``).
Homing X and Y alone never needs the record.  The plan's first step
says what the person will see -- what descends and where, in the
vendor's words -- and whether the routine travels sideways before Z is
known; on a Klipper or USB Marlin machine the unit's own config or
reports settle the cells the maker left blank, and the plan says so.

Branch on ``outcome``: ``confirmed`` (the printer was seen at home),
``accepted`` (sent, not refused, not read back — the honest answer on
every backend Kiln cannot read a homed flag from), ``failed``.
``homed_axes`` names the axes the sequence's own homing commands
addressed; ``resting_position`` says where the head was left.

**Run it in steps the first time on any machine with a person beside
it.**  ``plan_only=True`` returns the sequence as steps -- what the
person will see and how each motion knows where to stop -- and sends
nothing.  ``step=N`` sends only step N, reports what it left armed
(heater, soft endstops), and describes step N+1 for the next call.  A
single script cannot be paused between motions, however well it was
announced; step mode can.

Args:
    axes: Any of ``X``, ``Y``, ``Z``.  Default all three.
    wait_seconds: How long to watch for a fault code afterwards on
        backends that raise one (default 10).
    step: Send only this step of the sequence (1-based).
    plan_only: Describe the steps; send nothing.
    plate_clear: A PERSON's statement that the plate is empty.  Required
        on every call that homes Z on a model whose Z home presses the
        nozzle onto the plate (the A1 mini), whatever the plate record
        says; without it the tool refuses with
        ``PLATE_CLEAR_REQUIRED`` and, where the printer has a camera,
        ``snapshot_path`` -- look, then call again with it set.  Never
        set it on a person's behalf.
    printer_name: Which printer.  Omit for the default one.
park_headA

Move the print head somewhere safe, away from the plate, and leave it there.

The retreat, as distinct from ``home_axes`` (the measurement).  A park
NEVER homes Z and never heats: it raises the head the vendor's way,
homes X (an endstop -- nothing is touched), and travels to the model's
own off-plate spot -- on a Bambu, the position the machine itself
flushes at, served one plan at a time through Kiln's hosted service for a printer paired to your Kiln sign-in, free, and kept on your machine so it works offline.  On
Marlin, Klipper and RepRapFirmware the firmware's own home position IS
the park, chosen by whoever configured the machine -- and the catalogue's
motion record for the declared ``printer_model`` decides how much of it
is sent: on a machine whose Z home presses a probe or the nozzle onto
the plate (most of them), park homes X and Y only and leaves Z alone;
on the few whose Z home cannot touch the plate, the full home.  With no
``printer_model`` declared, or one the catalogue does not know, park
refuses and says which key to set (code PRINTER_MODEL_REQUIRED).  A
Bambu model whose spot is not served here refuses by name rather than
guessing a coordinate, and says to use the screen's jog controls, Z up
first -- never its Home button over a part.

Use this first on any machine you are nervous about: it is the safer
of the two verbs by construction, because nothing descends.  Same
``plan_only`` / ``step`` options as ``home_axes`` -- run it in steps
the first time with a person beside the machine.

Args:
    wait_seconds: How long to watch for a fault code afterwards on
        backends that raise one (default 10).
    step: Send only this step of the sequence (1-based).
    plan_only: Describe the steps; send nothing.
    plate_clear: A PERSON's statement that the plate is empty.  Lets a
        park proceed over a plate the record says holds a part, and lets
        the full home (Z included) stand in for the park on a machine
        whose Z home touches the plate.  Written to the plate record,
        as on ``home_axes``: the plate reads ``clear`` until the next
        print starts.  Never set it on a person's behalf.
    printer_name: Which printer.  Omit for the default one.
plate_statusA

What Kiln knows is on the build plate -- read-only, no printer round trip.

Kiln records the plate at the moments it can be sure of: a print Kiln
started puts a part there (``occupied``, with the file and, where Kiln
could read it, the part's height); a print seen ending leaves it there;
a PERSON says it is empty (``plate_clear=true`` on ``home_axes`` or
``park_head``, or ``kiln plate clear`` at the command line); and a LOOK
through the machine's camera settles it either way (``look_at_plate``).  Anything
else -- no record, a torn record, a print started at the printer's own
screen -- reads as ``unknown``, and the answer then says whether a
camera could settle it.

Why it matters: ``home_axes`` and ``park_head`` start with the vendor's
raise and then cross the head's row a few millimetres up -- and a
collision there raises no fault.  When the record names a part taller
than that raise, both refuse and say so; a ``clear`` record is what
lets them stop asking about the row.  A Z home that presses the nozzle
onto the plate (the A1 mini) asks on every call regardless -- the
record cannot see a print started from the printer's own screen, and
that press is the one motion a stale record must never answer for.

An ``occupied`` record says a part WAS there.  ``recorded_ago`` says
how long ago, and every refusal that rests on it carries a look at the
plate where the machine has a camera -- so look (``look_at_plate``)
rather than take an old record's word that the part is still there.

There is deliberately no tool that marks the plate clear from nothing:
that is a statement someone has to make, at the machine, at the command
line, by looking through the camera and saying what they see, or -- a
person in a chat -- in their own words, which ``look_at_plate`` records
as theirs (``person_says``) and labels as passed on when it could not
ask them itself.

Args:
    printer_name: Which printer.  Omit for the default one.

Returns ``plate`` with ``status`` (``unknown`` / ``occupied`` /
``clear``), ``source``, ``since``, ``job`` (``file``, ``footprint_mm``,
``max_z_mm``, ``printer_id``), ``from_camera`` and ``looked_by`` when a
look wrote it, ``recorded_ago`` (how old the record is, in words), and a
one-line ``description``; plus ``camera``, whether this machine has one
that could settle an unknown plate.
look_at_plateA

Look at the build plate through the machine's camera, and record what is there.

Two steps, one tool.  Called WITHOUT ``seen`` it fetches a frame and
hands it to you as a picture, after a short text record that names
``snapshot_path``, the same picture saved on this computer -- and
records nothing.  Look at it, then call again with ``seen="clear"``
(nothing on the plate) or ``seen="occupied"`` (something is), and that
answer becomes the plate record with you named as the one who looked.

The picture shows whatever the camera sees, the room around the
printer included.  This tool saves it only on this computer and hands
it only to you; it is never written to a log.

A refusal over a recorded part (a slice with no spot named, a print
start, a park or home that would cross it) already carries that frame
as ``snapshot_path`` and says how old the record is: look at it and
come straight here with ``seen``.  A record days old most likely
describes a part someone took off -- look before you ask a person.

A print held with ``ALWAYS_ALLOW_LOOK_FIRST`` carries a frame the same
way: always allow is on for that printer, nobody is being asked, so
the bed is looked at first.  Judge that frame here with ``seen`` and
start the print again; the picture is kept with the print's record.
If you cannot tell, say ``occupied`` -- the person is then the one who
says the bed is clear.

When the PERSON tells you the bed is clear -- typed to you in a chat,
after a refusal that says a part is on it -- pass their words exactly
as ``person_says``.  They have to say it flatly ("bed clear", "the
plate is empty"); a hedge or a question is not that.  Where this app
can show a dialog, Kiln asks the person itself and records their
answer; otherwise the words are recorded as passed on by you, kept on
the record.  Never write these words yourself: if they have not said
it, ask them.  It settles a plate the record says is occupied; a plate
with no such record is settled by looking.

Kiln ships no vision model and judges nothing here.  The eyes are
yours; this tool is the camera and the pen.  Say what you actually see:
a plate you are not sure about is ``occupied``, because the cost of a
wrong "clear" is a print driven into a part and the cost of a wrong
"occupied" is one question.

Works on any printer with a camera Kiln can read -- the machine's own,
or one registered against it with ``camera_snapshot_url``, which works
on every printer type including those with no camera of their own.
A machine with neither says so and stays ``unknown``.

Args:
    printer_name: Which printer.  Omit for the default one.
    seen: Omit to fetch the picture.  ``"clear"`` or ``"occupied"`` to
        record what you saw in the picture you were just given.
    person_says: The person's own words that the bed is clear, exactly
        as they typed them.  Not with ``seen``.

Returns the ``plate`` record and a ``look`` block saying whether a
frame was available and which camera it came from -- followed, when a
picture was taken, by the picture itself as image content.
fingerprint_modelA

Compute a geometric fingerprint for a 3D model file.

        Reads the STL file and produces a fingerprint containing: SHA-256
        file hash, triangle/vertex counts, bounding box, surface area,
        volume, overhang ratio, complexity score, and TWO geometric
        signatures for similarity matching.

        ``geometric_signature_v2`` is the one to carry into
        ``record_print_dna`` / ``predict_print_settings`` /
        ``find_similar_prints`` / ``contribute_community_print``: it
        tells this design apart from a different one that happens to
        share the older ``geometric_signature``.  Pass both — the
        older key is what joins this print to history recorded before
        v2 existed.

        Args:
            file_path: Path to the STL file to fingerprint.
        
record_print_dnaA

Record a print outcome with full model DNA.

        Saves the model fingerprint alongside print settings and outcome
        for cross-user learning.  Use ``fingerprint_model`` first to
        compute the fingerprint fields.

        Args:
            file_hash: SHA-256 hash of the model file.
            geometric_signature: Geometric signature from fingerprinting.
            triangle_count: Number of triangles in the model.
            surface_area_mm2: Total surface area in mm^2.
            volume_mm3: Model volume in mm^3.
            overhang_ratio: Ratio of overhanging triangles (0.0-1.0).
            complexity_score: Model complexity (0.0-1.0).
            printer_model: Printer model name.
            material: Material used (e.g. ``"PLA"``).
            settings: Print settings dict.
            outcome: ``"success"``, ``"failed"``, or ``"partial"``.
            quality_grade: Grade from ``"A"`` to ``"F"`` (default ``"B"``).
            failure_mode: Optional failure description.
            print_time_seconds: Print duration in seconds.
            geometric_signature_v2: ``fingerprint_model``'s
                ``geometric_signature_v2``.  Pass it: it is what lets
                this print be told apart from a different design that
                happens to share the older signature.  Omitted, the row
                is stored with the older key only and can never be
                separated from that design later.
        
predict_print_settingsA

Predict optimal print settings from historical DNA data.

        Searches for exact file hash matches first, then falls back to
        geometrically similar models, and finally to material defaults.

        Args:
            file_hash: SHA-256 hash of the model file.
            geometric_signature: Geometric signature from fingerprinting.
            surface_area_mm2: Surface area in mm^2.
            volume_mm3: Model volume in mm^3.
            complexity_score: Model complexity (0.0-1.0).
            printer_model: Target printer model.
            material: Target material.
            geometric_signature_v2: ``fingerprint_model``'s
                ``geometric_signature_v2``.  Pass it: without it the
                prediction can be averaged over prints of a DIFFERENT
                design that shares the older signature.
        
find_similar_printsA

Find similar models in the print DNA knowledge base.

        Uses geometric signature matching and surface area / volume
        similarity to locate models with similar geometry.

        Args:
            file_hash: SHA-256 hash of the model file.
            geometric_signature: Geometric signature from fingerprinting.
            surface_area_mm2: Surface area in mm^2 (for fuzzy matching).
            volume_mm3: Volume in mm^3 (for fuzzy matching).
            complexity_score: Complexity (for fuzzy matching).
            limit: Maximum results (default 10).
            threshold: Similarity threshold 0.0-1.0 (default 0.8).
            geometric_signature_v2: ``fingerprint_model``'s
                ``geometric_signature_v2``.  Pass it: without it,
                models that merely share the older signature are
                reported as the same geometry.
        
get_model_print_historyA

Get all print attempts for a model.

        Returns the complete history of print outcomes, settings, and
        quality grades.  The success-rate metrics cover every material
        by default; pass ``material`` to scope them to one filament
        ("how does this do in PETG?").

        PASS ``model_path`` WHENEVER YOU HAVE THE FILE.  History is a
        question about the SHAPE, and ``model_path`` lets Kiln identify
        it directly.  A file hash alone identifies BYTES: re-export an
        unchanged part from CAD and the hash changes, so a hash-only
        lookup reports a part with real history as never printed.

        ``identified_by`` in the response says which it used —
        ``"shape"`` is the precise answer, ``"file"`` means the history
        may be incomplete.

        Args:
            file_hash: SHA-256 hash of the model file, when known.
            material: Optional material filter for the success-rate
                metrics.  Empty = all materials.
            model_path: Path to the model file — the best input.  Kiln
                fingerprints it and identifies the design itself.
            geometric_signature: v1 shape signature, if you already have
                one from ``fingerprint_model``.
            geometric_signature_v2: v2 shape signature, likewise.
        
contribute_community_printA

Contribute a print outcome to the community registry.

        Adds an anonymous print record for community aggregation.
        Only geometric signatures and settings are stored — never
        file contents, user IDs, or file paths.

        Args:
            geometric_signature: Geometric signature from fingerprinting.
            printer_model: Printer model name.
            material: Material used.
            settings: Print settings dict.
            outcome: ``"success"``, ``"failed"``, or ``"partial"``.
            quality_grade: Grade from ``"A"`` to ``"F"`` (default ``"B"``).
            failure_mode: Optional failure description.
            print_time_seconds: Print duration in seconds.
            job_id: The print's job id when known — it anchors the
                federation dedupe key, so a print that was also
                watched (or recorded via ``record_print_outcome``)
                ships to the community pool once, not twice.
            geometric_signature_v2: ``fingerprint_model``'s
                ``geometric_signature_v2``.  Pass it: it is what keeps
                this contribution from being averaged into a different
                design that shares the older signature.
        
get_community_insightA

Get aggregated print data for a model geometry.

        Two layers, and the tool always returns whatever it can get:

        * ``insight`` — what THIS install has printed of this
          geometry: success rate, printers, materials, settings,
          failure modes.  Always available, no account needed.
        * ``community`` — the same picture across everyone who has
          printed this shape, so you can start from what already
          worked.  Community insights come with Kiln Pro
          (https://kiln3d.com/pricing); without them ``community``
          reports that it isn't available and the local layer is
          unaffected.

        Never fails because of the network or the plan: no
        connection, no account, or a plan without community
        insights all still return the local answer.

        Args:
            geometric_signature: Geometric signature to look up
                (``fingerprint_model``'s ``geometric_signature``).
            geometric_signature_v2: The same mesh's
                ``geometric_signature_v2``, when known.  Supplying it
                narrows the answer to THIS design: without it, prints
                of a different design that happens to share the older
                signature can be counted into the result.
        
community_statsA

Get overall print-registry statistics.

        ``stats`` covers this install: total records, unique models,
        printers, materials, and overall success rate.  ``community``
        adds the size of the shared pool everyone contributes to —
        counts only, available to anyone signed in.

        Works offline: the local numbers are always returned.
        
recommend_materialA

Recommend material from intent + printer capabilities (considers enclosure, bed, budget).

        Uses printer DNA + historical data to translate natural language
        intent (e.g. ``"make it strong"``, ``"make it pretty"``,
        ``"make it cheap"``) into an optimal material recommendation
        with settings.

        Pass ``printer_id`` to answer for a SPECIFIC machine — essential
        on a mixed fleet, where "what should I run this in" depends on
        which printer will run it.  The recommendation is then computed
        against that machine's nozzle state (abrasive materials on a
        brass nozzle get an explicit wear warning) and the response
        names the machine it answered for.

        Pass ``on_hand_only=True`` to recommend only from materials you
        physically have — recorded spools (``add_spool``) plus what's
        loaded on your machines (AMS/CFS sync).  Scoped to one printer
        this works on every tier; sweeping a multi-machine fleet in one
        call is a Kiln Business feature (https://kiln3d.com/pricing).  The recommendation's
        ``availability`` block then says WHERE the material is: which
        machine has it loaded, or that it's on the shelf and needs a
        spool swap first.  With ``printer_id`` the loaded half is
        scoped to that one machine (shelf spools always count — they
        can be swapped in); without it, every machine's load counts.
        When nothing on hand suits the request, the response returns
        the best catalog pick clearly labeled needs-purchase — it
        never silently widens to the catalog.  And when what you have
        works but a material you DON'T own fits the job materially
        better, the answer names that too, so "best of what you have"
        is never mistaken for "right for the job".

        **Which material tool to use:**

        - Quick intent-based pick for your own printer? → ``recommend_material`` (this tool)
        - Only from spools I actually own? → ``recommend_material(on_hand_only=True)``
        - Designing a part and need engineering specs? → ``recommend_design_material``
        - Ordering a print from a service? → ``suggest_material_for_order``
        - Which of MY printers has a material loaded? → ``find_printers_with_material``
        - What's loaded across the fleet right now? → ``get_fleet_material_summary``

        Args:
            intent: User intent text (e.g. ``"strong"``, ``"pretty"``).
            has_enclosure: Whether the printer has an enclosure.
            has_heated_bed: Whether the printer has a heated bed.
            budget_usd: Optional maximum budget per kg in USD.
            printer_id: Optional registered printer to answer for.
                Empty = printer-agnostic recommendation.
            on_hand_only: Restrict candidates to recorded inventory
                (loaded materials + shelf spools).  Default False =
                full catalog.
        
list_available_materialsB

List all available 3D printing materials with properties.

Returns details for every material in the database including strength, flexibility, heat resistance, surface quality, ease of print, cost, and temperature requirements.

start_gcode_interceptionA

Start a real-time G-code interception session for a printer.

Automatically loads safety-profile-based rules (temperature limits,
feedrate caps, blocked commands) for the printer.  Use
``add_interception_rule`` to add custom rules after starting.

Args:
    printer_name: Target printer name (e.g. "ender3", "voron-350").

Returns a session ID and initial rule set.

AGENT CONTRACT: when ``coverage_warnings`` is non-empty this session
is running with reduced protection (generic temperature limits, or no
bed-fit rules because the build volume is unknown).  Relay those
warnings to the user verbatim -- do not present the session as fully
protected.  Passing the printer's model key (e.g. "bambu_a1") instead
of a nickname resolves the gap.
stop_gcode_interceptionB

Stop a G-code interception session.

Args:
    session_id: The session ID returned by ``start_gcode_interception``.

Returns the final session stats.
add_interception_ruleB

Add a custom interception rule to an active session.

Args:
    session_id: Target session ID.
    name: Human-readable rule name.
    trigger: Trigger type -- one of: temp_exceeds, temp_below,
        temp_delta, feedrate_exceeds, flow_anomaly, position_limit,
        command_blocked, pattern_match, always, layer_change.
    action: Action to take -- one of: allow, block, modify, pause, alert.
    priority: Rule priority -- one of: critical, high, medium, low.
    threshold: Numeric threshold for trigger evaluation.
    threshold_max: Upper bound for range-based triggers.
    blocked_commands: List of G/M codes for command_blocked trigger.
    pattern: Regex pattern for pattern_match trigger.
    modify_params: Parameter overrides for modify action (e.g. {"F": 3000}).
    message: Human-readable explanation shown when rule fires.
remove_interception_ruleB

Remove an interception rule from an active session.

Args:
    session_id: Target session ID.
    rule_id: The rule ID to remove.
intercept_gcode_commandA

Check one line of G-code for danger before you send it to a printer.

G-code is the language printers take orders in -- "heat the nozzle to
250C", "move to X=100".  One bad line can cook a hotend or drive the
nozzle into the bed.  This checks a single line against the safety
rules for this session (temperature ceilings, speed caps, the
printer's build volume) and says whether it looks safe to send.

It is a smoke detector, not a sprinkler.  It reports; it does not
intervene.  Kiln does not quietly pipe outgoing G-code through it, so
a line gets checked only when you call this on it, and gets stopped
only if you act on the answer.  A line you never checked, or one you
checked and sent anyway, reaches the printer untouched.

So call it on each line before sending that line, and do what the
answer says:

- ``allow``  -- looks safe; send as-is.
- ``block``  -- dangerous; do not send.
- ``modify`` -- send ``modified_command`` instead, never the original.
- ``pause``  -- hold, and ask the user before sending.
- ``alert``  -- may be sent, but show the user ``reasons`` first.

A session can also come back with ``coverage_warnings`` (see
``start_gcode_interception``), meaning some checks could not be set up
at all -- usually because Kiln does not know which printer model it is
guarding.  An ``allow`` from a session like that means "nothing I was
able to check objected", not "this is safe".  Tell the user that
rather than reporting a clean pass.

Args:
    session_id: Active interception session ID.
    command: Raw G-code command string (e.g. "M104 S280", "G1 X10 F6000").

Returns the interception result including action, modified command
(if applicable), triggered rules, and human-readable reasons.
update_interception_telemetryA

Push a telemetry snapshot to an active interception session.

Telemetry is used by rules that evaluate live device state
(temperature thresholds, thermal runaway detection, flow anomalies).
Call this periodically during printing (e.g. every few seconds).

Args:
    session_id: Active session ID.
    hotend_temp: Current hotend temperature (C).
    hotend_target: Target hotend temperature (C).
    bed_temp: Current bed temperature (C).
    bed_target: Target bed temperature (C).
    position_x: Current X position (mm).
    position_y: Current Y position (mm).
    position_z: Current Z position (mm).
    feedrate: Current feedrate (mm/min).
    flow_rate_pct: Flow rate percentage (100 = normal).
    fan_speed_pct: Fan speed percentage.
    current_layer: Current layer number.
    elapsed_seconds: Elapsed print time (seconds).
    filament_used_mm: Filament consumed (mm).
get_interception_statusB

Get status and statistics for an interception session.

Args:
    session_id: Target session ID.

Returns session metadata, command counts, and current telemetry.
list_interception_sessionsA

List all active G-code interception sessions.

Returns summary information for each active session including printer name, command counts, and rule counts.

load_safety_interception_rulesA

Load safety-profile rules for a printer into an active session.

Generates rules from the printer's safety profile (temperature
limits, feedrate caps, blocked commands) and adds them to the
session.  Use this to reset or refresh safety rules.

Args:
    session_id: Target session ID.
    printer_name: Printer model for safety profile lookup.

AGENT CONTRACT: relay any ``coverage_warnings`` to the user verbatim
-- they mean the loaded rule set protects less than a full one.
get_interception_historyA

Get recent interception results for a session.

Args:
    session_id: Target session ID.
    limit: Maximum results to return (default 50, max 500).

Returns interception results from newest to oldest, including
actions taken, triggered rules, and reasons.
record_print_outcomeA

Record the outcome of a print for cross-printer learning.

The learning database helps agents make better decisions about which
printer to use for a given job and material.  Outcomes are agent-curated
quality data — separate from the auto-populated print history.

**Safety**: Settings are validated against hard safety limits.  Outcomes
with temperatures exceeding safe maximums are rejected to prevent
poisoning the learning database with dangerous data.

**Decoration feedback**: When ``decoration_slug`` is provided, the
corresponding decoration's proven-settings counter is auto-updated
(``success_count`` or ``failure_count``) so the library's tracked
reliability reflects real field outcomes without manual curation.

**Auto-classification** (opt-in): When ``auto_classify=True`` and the
outcome is ``"failed"`` with no explicit ``failure_mode``, the failure
classifier runs (:func:`kiln.failure_recovery.analyze_failure`) and
its result is mapped into the canonical DB vocabulary.  The
classification is always echoed back in the ``auto_classification``
key of the response; it is only STORED as ``failure_mode`` when the
classifier's confidence meets or exceeds
``_AUTO_CLASSIFY_MIN_CONFIDENCE`` (0.75).  Lower-confidence guesses
are surfaced to the caller without poisoning the learning database.

Args:
    job_id: The job ID from the print queue.
    outcome: One of ``"success"``, ``"failed"``, ``"partial"``, or
        ``"cancelled"``.
    quality_grade: Optional — ``"excellent"``, ``"good"``, ``"acceptable"``, ``"poor"``.
    failure_mode: Optional — e.g. ``"spaghetti"``, ``"layer_shift"``, ``"warping"``.
    settings: Optional dict of print settings used (temp_tool, temp_bed, speed, etc.).
    environment: Optional dict of environment conditions (ambient_temp, humidity).
    notes: Optional free-text notes about the print.
    printer_name: Printer used.  Auto-resolved from job if omitted.
    file_name: File printed.  Auto-resolved from job if omitted.
    file_hash: Optional hash of the file for cross-printer comparison.
    material_type: Material used (e.g. ``"PLA"``, ``"PETG"``).  Omit and
        Kiln backfills it from what the job declared (print history, then
        the queue job) or — for an outcome watched live — from the
        filament the printer currently holds.  Stays unset when no honest
        source knows it; per-material learning skips unset rows rather
        than learning from a guess.
    decoration_slug: Optional decoration slug that was applied to this
        print.  When set, the matching decoration's success/failure
        counters are auto-updated.
    decoration_settings: Optional dict of decoration settings used
        (``depth_mm``, ``mode``, ``image_style``).  Falls back to the
        decoration's current defaults when omitted.
    auto_classify: When True and this outcome is a failure with no
        explicit ``failure_mode``, run the failure classifier and
        store its best-guess mode if confidence >= 0.75.  Default
        False — callers opt in.
    auto_recorded: When True, tags the outcome as auto-fired by
        the terminal-state hook (see
        :mod:`kiln.auto_record_hook`).  Agents can later refine
        the outcome by calling record_print_outcome again with the
        same ``job_id`` — the most recent call wins at the
        ``proven_settings`` level.  Default False.
    determined_by: Who settled this outcome — ``"observed"`` (a
        live process watched the print end), ``"inferred"``
        (reconstructed from printer state after the fact), or
        ``"user_reported"`` (the human said so).  Defaults to
        ``"observed"`` for auto-recorded outcomes and
        ``"user_reported"`` otherwise — a manual record normally
        relays what the user reported about the part in hand.
        Recording an outcome for a print that started while Kiln
        wasn't watching RESOLVES its pending row in place rather
        than duplicating it.
    print_error: Optional raw firmware error code the print tripped
        (Bambu HMS, e.g. ``50348044``).  Stored as EVIDENCE and kept
        deliberately separate from ``failure_mode``, which is a
        VERDICT: a print the user CANCELLED carries whatever code the
        abort tripped and no failure_mode at all, because a deliberate
        stop is not a machine failure but the firmware's complaint
        still happened and is worth keeping.  A single machine cannot
        characterise a fault from codes like these — what predicts one
        sticking is a question for many printers — so the code is
        captured now against the day there are enough of them to ask.
        ``0`` and unset both store NULL; a backend with no such code
        simply omits it.
recommend_settingsA

Recommend print settings based on historical successful outcomes.

Queries the learning database for settings that produced successful
prints, filtered by printer, material, and/or file hash.  Returns
aggregated recommendations (most common temps, speeds, slicer profiles)
plus the raw successful settings for agent review.

When kiln-pro is installed AND the user has a calibrated slicer
profile for ``(printer_name, material_type)``, the calibration coach
overlays personally-tuned values (flow rate, max volumetric speed,
pressure advance, retraction distance) on top of the historical
medians.  The response gains a ``calibration_used`` block and an
extra ``rationale`` line per overridden value naming the slicer +
staleness — so the user sees "Using your calibrated flow rate of
0.95 from OrcaSlicer (updated 12 days ago)" instead of the generic
aggregate.  Behavior is unchanged when kiln-pro is not installed
or no calibration is available.

**Note**: Recommendations are advisory.  They do NOT override safety
limits or preflight checks.  Always validate settings against printer
safety profiles before use.

Args:
    printer_name: Filter by printer (e.g. ``"voron-350"``).
    material_type: Filter by material (e.g. ``"PLA"``, ``"PETG"``).
    file_hash: Filter by file hash for exact file matching.
save_agent_noteA

Save a persistent note or preference that survives across sessions.

Use this to remember printer quirks, calibration findings, material
preferences, or any operational knowledge worth preserving.

Args:
    key: Name for this memory (e.g., ``"z_offset_adjustment"``, ``"pla_temp_notes"``).
    value: The information to store.
    scope: Namespace — ``"global"``, ``"fleet"``, or use *printer_name* for printer-specific.
    printer_name: If provided, scope is automatically set to ``"printer:<name>"``.
    ttl_seconds: Optional time-to-live in seconds.  The note will be
        automatically excluded from queries after this duration.  Pass
        ``None`` (default) for notes that should never expire.
get_agent_contextA

Retrieve all stored agent memory for context.

Call this at the start of a session to recall what you've learned
about printers, materials, and past print outcomes.  Expired entries
are automatically filtered out.  Each entry includes a ``version``
field showing how many times it has been updated.

Args:
    printer_name: If provided, retrieves printer-specific memory.
    scope: Filter by scope (e.g., ``"global"``, ``"fleet"``).
clean_agent_memoryA

Remove all expired agent memory entries.

Entries with a TTL that has elapsed are permanently deleted. Returns the count of entries removed.

get_printer_insightsA

Query cross-printer learning insights for a specific printer.

        Returns success rates, failure mode breakdown, and per-material
        statistics based on previously recorded outcomes — plus any
        UNRESOLVED prints: jobs that started (or ended) while no Kiln
        process was watching, whose outcome nobody has settled yet.

        **Agent contract for ``unresolved_prints``**: these entries are
        waiting on the one witness the machine can't replace — the
        user, who has the part.  When the moment is natural (not
        mid-task), ask casually ("Your ashtray finished while Kiln
        wasn't watching — did it come out OK?") and settle the answer
        via ``record_print_outcome(job_id=..., outcome=...,
        determined_by="user_reported")``.  Never guess an outcome on
        the user's behalf; an unresolved print stays out of all
        success-rate math until someone who knows answers.

        **Note**: Insights are advisory.  They do NOT override safety limits
        or preflight checks.

        Args:
            printer_name: The printer to get insights for.
            limit: Maximum recent outcomes to include (default 20).
        
suggest_printer_for_jobA

Suggest the best printer for a job based on historical outcomes.

        Rankings are based on success rates from previously recorded outcomes,
        optionally filtered by file hash or material type.  Cross-references
        the printer registry for current availability.

        **Note**: Suggestions are advisory.  They do NOT override safety limits
        or preflight checks.  Always run preflight validation before starting
        a print regardless of learning data.

        Each suggestion also says ``has_room``: whether that printer's plate,
        as Kiln's record has it, can take a print right now (a clear plate;
        a part still on it, or no record, is ``false``), with the plate
        block beside it.  Advisory, like the rest: the slice and start doors
        judge the real part against the real plate.  The plate reading is a
        fleet feature; below its tier ``has_room`` is ``null`` and
        ``plate_note`` says so.

        Args:
            file_hash: Optional hash of the file to match previous prints.
            material_type: Optional material type to filter by (e.g. ``"PLA"``).
            file_name: Optional file name (informational, not used for matching).
        
delete_agent_noteB

Remove a stored note or preference.

        Args:
            key: The key of the note to delete.
            scope: The scope namespace (default ``"global"``).
            printer_name: If provided, targets ``"printer:<name>"`` scope.
        
search_all_modelsA

Search across all connected 3D model marketplaces simultaneously.

        Searches Thingiverse, MyMiniFactory, Cults3D, and MakerWorld in
        parallel and returns interleaved results from all sources.  Note
        that MakerWorld returns a search URL (no direct API access) while
        other sources return actual model results.

        Args:
            query: Search keywords (e.g. "raspberry pi case", "benchy").
            page: Page number (1-based, default 1).
            per_page: Results per source (default 10).
            sort: Sort order — "relevant", "popular", or "newest".
            sources: Optional list to restrict search (e.g. ["thingiverse",
                "myminifactory"]).  Omit to search all connected sources.

        Each result includes a ``source`` field identifying the marketplace.
        Results also include ``is_free``, ``has_printable_files`` (has G-code),
        and ``has_sliceable_files`` (has STL/3MF) hints.

        Use ``model_details`` with the ``id`` to inspect, ``model_files``
        to see downloadable files, and ``download_model`` to save locally.
        
search_modelsA

Search Thingiverse for 3D-printable models.

        Args:
            query: Search keywords (e.g. "raspberry pi case", "benchy").
            page: Page number for pagination (1-based, default 1).
            per_page: Results per page (default 10, max 100).
            sort: Sort order — "relevant", "popular", "newest", or "makes".

        Returns a list of model summaries including name, creator, thumbnail,
        and download/like counts.  Use ``model_details`` with the ``id`` to
        get full information, and ``model_files`` to see downloadable files.
        
model_detailsA

Get full details for a Thingiverse model.

        Args:
            thing_id: Numeric thing ID (from ``search_models`` results).

        Returns comprehensive metadata including description, instructions,
        license, tags, and file count.
        
model_filesA

List downloadable files for a Thingiverse model.

        Args:
            thing_id: Numeric thing ID.

        Returns a list of files with name, size, and download URL.
        Use ``download_model`` with the ``file_id`` to save a file locally.
        
download_modelA

Download model file(s) from a marketplace to local storage.

        **Community models are unverified.** Always preview dimensions and
        validate the mesh (``validate_generated_mesh``) before printing.
        Models with high download counts and positive ratings are generally
        safer.  AI-generated or untested designs can damage delicate printer
        hardware — prefer proven blueprints when possible.

        Args:
            brief_id: The saved goal's id from ``design_session``; pass it so
                this make joins the goal (recorded against it; Kiln Pro checks the
                result against it). Empty when there is no goal.
            file_id: Numeric file ID (from ``model_files`` results).  If
                omitted and ``model_id`` is provided, downloads all files
                for the model.
            dest_dir: Local directory to save the file in (default:
                the system temp directory).
            file_name: Override the saved file name (single-file mode only).
                Defaults to the original name from the marketplace.
            model_id: Model/thing ID.  When ``file_id`` is omitted,
                all files for this model are downloaded.
            source: Marketplace source — ``"thingiverse"`` (default),
                ``"myminifactory"``, etc.
            download_all: When True, downloads all files for the model
                regardless of whether ``file_id`` is provided.

        A downloaded GLB is handed on as an STL beside it, because the
        stage, the slicer and printers cannot open a GLB: its
        ``local_path`` is the STL, and ``conversion`` names the
        original, which stays on disk (``conversion_failed`` says so
        when a GLB cannot be read).  The stage opens on the first
        downloaded file it can draw, and
        the result measures that file (``validation``, ``dimensions``;
        ``size_check`` when its size reads like a units mix-up) and says
        where the files came from (``came_from``: the marketplace and,
        when its listing could be read, the designer, license and page).
        A note beside each file keeps where it came from, so the stage
        and design history can say so later; ``show_on_stage(path)``
        opens any of the other files.  Then upload to a printer with
        ``upload_file`` and print with ``start_print``.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

MAKE DOORS: design_session, Kiln's front door for making an object, is not installed here (signed in to Kiln it runs on Kiln's servers). On this install compile_scad IS the make → preview → iterate loop: make it, show the preview, iterate.

browse_modelsA

Browse Thingiverse models by popularity, recency, or category.

        Args:
            browse_type: One of "popular", "newest", or "featured".
            page: Page number (1-based, default 1).
            per_page: Results per page (default 10, max 100).
            category: Optional category slug to filter by (e.g. "3d-printing",
                "art").  Use ``list_categories`` to see available slugs.

        Returns model summaries similar to ``search_models``.
        
list_model_categoriesA

List available Thingiverse content categories.

        Returns category names and slugs.  Pass a slug to
        ``browse_models(category=...)`` to browse models in that category.
        
marketplace_statusA

Check which 3D model marketplaces are connected and available.

Returns the list of configured marketplace sources, their connection status, and whether credentials are present. Use this to verify marketplace access before searching or downloading models.

marketplace_diagnosticsA

Run connectivity checks against all configured marketplaces.

Performs a lightweight probe (empty search) against each connected marketplace and reports which ones are reachable. Useful for debugging download failures.

get_fleet_material_summaryA

Aggregate material inventory across all printers and spools.

Returns a per-material-type summary of total stock in grams, spool counts, which printers have it loaded, and available colours.

get_material_consumption_historyA

Get material consumption history from completed prints.

        Aggregates filament usage per material type over the given
        window, converting filament length to grams using standard
        material densities.

        Args:
            days: Number of days to look back (default 30).
        
forecast_material_consumptionA

Forecast when a material type will run out.

        Combines current stock with historical consumption rate to
        estimate remaining days and urgency level (ok/low/critical).

        Args:
            material_type: Material type to forecast (e.g. ``"PLA"``).
            days_ahead: Days of history for rate estimation (default 30).
        
check_material_sufficiencyA

Check if a printer has enough material for a print job.

        When material is insufficient, says what the person can do with
        what they have: a spool on the shelf, a pause-and-swap.  Only
        when nothing they have will do does it end with one offer of
        help finding a filament.  Relay that offer as written and never
        suggest buying filament unless the person asks or says yes;
        then use ``find_closest_filaments``.  Suggestions that point at
        OTHER machines are a fleet-wide answer and need Kiln Business;
        the check itself — does THIS printer have enough — works on
        every tier.

        Args:
            printer_name: Name of the printer to check.
            required_grams: Amount of material needed in grams.
            material_type: Optional material type filter.
        
get_restock_suggestionsA

Find materials running low and generate purchase links.

Examines all material types in inventory and returns restock suggestions for any projected to run out within 30 days, sorted by urgency (critical first).

find_printers_with_materialA

Find printers that have a specific material loaded.

        Returns printers with the matching material, sorted by
        remaining stock (most first).  Optionally filter by colour
        and minimum remaining grams.

        Args:
            material_type: Material type to find (e.g. ``"PLA"``).
            color: Optional colour filter.
            min_grams: Minimum remaining grams (default 0).
        
optimize_fleet_assignmentA

Assign print jobs to printers by material availability.

        Each job dict should contain ``file_name``, ``material_type``,
        ``required_grams``, and optionally ``color``.  On one machine it
        says which jobs its loaded spool can take, in order; across
        several machines it picks a printer for each job, preferring
        colour matches and fewer spool swaps (Kiln Business,
        https://kiln3d.com/pricing).

        Args:
            jobs: List of job dicts to assign.
        
suggest_spool_swapsA

Suggest minimal spool swaps to run all queued jobs.

        Compares what the jobs need with what is loaded and says which
        shelf spools to load, and where.  On one machine it answers for
        that machine; across several machines it plans the fewest
        physical spool changes between them (Kiln Business,
        https://kiln3d.com/pricing).

        Args:
            jobs: List of job dicts with ``material_type`` and ``required_grams``.
        
get_active_materialA

Get the filament physically active in the AMS hardware right now (Bambu Lab).

        Reads live tray data from the AMS hardware. For the software-tracked
        material (what was told to Kiln via ``set_material``), use
        ``get_material`` instead.

        For Bambu Lab printers with an AMS, reads the active tray and
        returns its type, colour, remaining percentage, and temperature
        range.  For non-Bambu printers (or printers without AMS), the
        material is reported as ``"unknown"``.

        ``tray_now`` is the printer's own tray id (``unit * 4 + slot``
        on a chained unit, the unit id itself on an AMS HT); ``254``
        is the external spool and ``255`` no tray.  An A1 / AMS Lite
        can report ``255`` with trays loaded; then Kiln falls back to
        the selected/target tray fields or returns the loaded
        candidates instead of claiming the external spool.

        Args:
            printer_name: Named printer to query.  Omit to use the
                default printer.
        
check_print_healthA

Perform a single-shot health assessment of the current print.

        Unlike ``watch_print`` (which starts a background monitoring
        thread), this tool runs one check cycle and returns immediately.
        It is designed for quick "is the print OK right now?" queries
        from an agent without starting persistent background tasks.

        Checks performed:

        * **Printer connectivity** — is the printer online?
        * **Temperature** — are hot-end and bed within 15 °C of target?
        * **Print progress** — current completion, layer count, ETA.
        * **Error state** — any active firmware error codes.

        If *model_path* is supplied, adhesion risk is also evaluated via
        ``analyze_printability``.

        Args:
            printer_name: Named printer to query.  Omit for the default.
            model_path: Optional path to the model being printed.
                Enables geometry-based adhesion risk analysis.
            material: Filament material (e.g. ``"PLA"``, ``"ABS"``).
                Passed to adhesion analysis when *model_path* is provided.
            printer_id: Printer model ID (e.g. ``"bambu_a1"``).
                Used for printer-intelligence lookups.
        
diagnose_meshA

Deep mesh defect analysis — self-intersections, holes, normals, fragments (defect-focused).

        Goes deeper than ``analyze_mesh_geometry`` (which focuses on printability
        scoring and overhang detection). Use this when you suspect mesh defects
        or when ``repair_mesh`` didn't fix the issue.

        Analyzes: self-intersections, inverted/inconsistent normals, degenerate
        (zero-area) faces, floating fragments, detailed hole reporting (count,
        size, location), and polygon count assessment for FDM printing.

        Returns a structured report with severity level, defect list, and
        actionable fix recommendations (specific MeshLab/Blender steps).

        Requires the optional ``trimesh`` package (``pip install trimesh``).
        Supports STL, 3MF, OBJ, PLY, OFF, GLB, and GLTF formats.  A 3MF
        holding several objects is read as one body — the report describes
        the whole plate.

        Use this BEFORE slicing to catch problems that would cause print
        failures or slicer errors.  Complements ``validate_generated_mesh``
        (basic checks) and ``analyze_printability`` (print-readiness scoring).

        Args:
            file_path: Path to a mesh file (STL, 3MF, OBJ, PLY, OFF, GLB,
                GLTF).
        
validate_generated_meshB

Validate a 3D mesh file for printing readiness.

        Checks that the file is a valid STL, OBJ, GLB, or 3MF, has reasonable
        dimensions, an acceptable polygon count, and is manifold
        (watertight).

        Args:
            file_path: Path to an STL, OBJ, GLB, or 3MF file.
        
rescale_modelA

Rescale an STL model to meet dimensional targets.

        Useful when a generated model is the wrong size for the printer's
        build volume or doesn't match the desired dimensions.

        **Uniform scaling** -- provide exactly ONE of:

        - ``target_height_mm``: Scale so Z-axis equals this value.
        - ``scale_factor``: Uniform multiplier (2.0 = double size).
        - ``max_dimension_mm``: Scale down so largest axis fits this limit.

        **Per-axis scaling** -- provide ``scale_x``, ``scale_y``, and/or
        ``scale_z``.  Omitted axes default to 1.0 (no change).

        Cannot combine uniform and per-axis options.

        Args:
            file_path: Path to the STL file to rescale (modified in-place).
            target_height_mm: Desired Z-axis height in mm.
            scale_factor: Uniform scale multiplier.
            max_dimension_mm: Maximum dimension on any axis.
            scale_x: Per-axis X scale factor.
            scale_y: Per-axis Y scale factor.
            scale_z: Per-axis Z scale factor.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

analyze_mesh_geometryA

Deep geometric and printability analysis of a 3D mesh.

        Goes beyond basic validation to compute volume, surface area,
        center of mass, overhang detection, connected components (floating
        parts), degenerate triangles, and ``mesh_check_score`` (0-100), a
        quick mesh check.  It is not the printability score: call
        ``analyze_printability`` for that grade.

        Use this after generating a model to understand its geometry and
        identify printability issues before sending to the slicer.

        For a STEP/STP CAD file this converts it first and every metric
        below is measured on Kiln's mesh copy — except an added ``exact``
        block, which carries the volume, surface area and envelope read
        from the CAD file's own surfaces.  Those two disagree slightly
        and the exact ones are the part's: quote ``exact`` when telling
        a user how big their CAD part is.  ``mesh_quality_scorecard``
        gives the same file a fuller intake report.

        :param file_path: Path to a mesh (.stl, .obj, .glb, .3mf) or a CAD
            file (.step, .stp), which is converted automatically.
        :returns: Dict with full mesh analysis metrics, plus ``exact``
            for CAD input.
        
detect_mesh_pocketsA

Detect pockets and cavities in a mesh before multi-part composition.

        Analyzes a base model to find recessed regions (circular or rectangular
        pockets) on top and bottom faces. Call this before compose_models or
        multi_material_print to know pocket dimensions for overlay geometry.

        :param file_path: Path to the STL file to analyze.
        :param min_depth_mm: Minimum pocket depth to report (default 0.3mm).
        :returns: Dict with pocket list, dimensions, and positions.
        
analyze_non_manifold_edgesA

Count and classify non-manifold edges in a mesh.

        Reports boundary edges (shared by 1 triangle), T-junction edges
        (shared by 3+ triangles), and manifold edges (shared by exactly 2).

        This is the diagnostic version of the manifold check -- use it
        to understand exactly how many edges are problematic before
        deciding whether to repair.

        A STEP/STP CAD file is converted first and the count is taken on
        the converted mesh, because a non-manifold edge is a defect of
        the triangles, not of the shape -- a STEP solid has none to be
        defective.  So on CAD input this measures KILN'S TESSELLATION,
        which is worth knowing (it says whether the conversion came out
        clean) and is not a finding about the user's file.  ``subject``
        says which artifact was measured and ``message`` says it in
        words.  AGENT CONTRACT: when ``subject`` is
        ``"kiln_tessellation"``, carry that attribution through to the
        user -- never report the count as a verdict on their CAD.

        :param file_path: Path to a mesh (.stl, .obj, .glb) or a
            STEP/STP CAD file.
        :returns: Dict with edge count breakdown, watertight status,
            ``subject``, ``message``, and (CAD only) ``converted_from``.
        
cross_section_viewA

Compute a 2D cross-section of a mesh at a cutting plane.

        Slices the mesh perpendicular to the chosen axis and returns
        contour polygons and cross-sectional area.  Useful for inspecting
        internal geometry (e.g., wall thickness, hole placement).

        :param file_path: Path to STL file.
        :param plane: Axis perpendicular to the cut -- "x", "y", or "z".
        :param offset_ratio: Fractional position 0.0-1.0 (default 0.5 = midpoint).
        :param offset_mm: If set, absolute position in mm (overrides offset_ratio).
        :returns: Dict with contour_count, contour_points, cross_section_area_mm2.
        
mesh_quality_scorecardA

Assess a model — a graded scorecard for a mesh, an intake report for a CAD file.

        **For a mesh** (.stl, .obj, .glb) it evaluates four dimensions:
        - **Printability** (35%): ``analyze_printability``'s own score and
          grade for ``material`` / ``printer_id`` — pass the ones you gave
          ``analyze_printability`` and the two match
        - **Structural** (25%): aspect ratio, base stability, component count
        - **Efficiency** (20%): fill ratio, support waste
        - **Quality** (20%): triangle density, degenerate count

        and returns per-factor scores, an overall 0-100 score, and a
        letter grade (A-F).  ``subject`` is ``"mesh"``.

        **For a CAD file** (.step, .stp) it returns an INTAKE REPORT and
        deliberately no letter grade.  ``subject`` is ``"cad_file"``,
        ``grade`` is null, and ``grade_withheld`` says why: 20% of that
        score measures Kiln's own tessellation, so the identical part
        would grade differently depending on which converter is installed
        on the machine that read it.  Instead you get three bands:

        - ``exact`` — read from the user's file by the CAD kernel:
          volume, surface area, envelope, validity, solid/shell/face
          counts, in mm.  These match their CAD package to the decimal
          and are the numbers to quote back to them.
        - ``measured`` — what genuinely needs triangles (overhangs,
          stability, floating parts), with the conversion named and this
          part's own conversion difference stated.
        - ``about_our_copy`` — triangle and degenerate counts for Kiln's
          generated mesh, as counts, never scored.

        When quoting a CAD part's size to a user, quote ``exact`` —
        ``about_our_copy`` describes Kiln's mesh, not their design.

        :param file_path: Path to a mesh (.stl, .obj, .glb) or a CAD file
            (.step, .stp).
        :param material: Material the printability factor is judged for
            (default ``"pla"``).
        :param printer_id: Optional printer the printability factor is
            judged for.
        :returns: Dict with scores and a grade for a mesh; the three-band
            intake report with ``grade: null`` for a CAD file.
        
compare_mesh_versionsA

Compare two mesh files and report geometric differences.

        Computes volume change, surface area change, dimension deltas,
        center-of-mass shift, the mesh-check delta, and an approximate
        Hausdorff distance showing how far the meshes differ spatially.

        Useful for verifying that a repair, rescale, or regeneration
        actually improved the model.

        :param file_a: Path to the reference (original) mesh.
        :param file_b: Path to the modified mesh.
        :returns: Dict with comparison metrics and ``meshes_identical`` flag.
        
repair_meshA

Repair mesh defects: rounding-noise seams, degenerates, holes.

        Every pass first welds vertices that are coincident up to a tiny
        radius (0.1 µm by default) — scanned and AI-generated meshes
        routinely carry float rounding jitter that reads as thousands of
        phantom open edges, and welding is the honest fix for those.  The
        default pass then removes zero-area triangles and recomputes face
        normals.  Pass ``close_holes=True`` for the deep pass, which
        additionally finds boundary edges (edges shared by only one
        triangle) and closes small holes via fan triangulation — use it
        when the mesh is not watertight.

        Hole closing refuses rather than ruins: sewing triangles that
        merely re-stamp existing surface are discarded, and a closure
        that collapses the enclosed volume is rolled back with the
        reason in ``unrepaired``.

        The result states the output's actual condition: ``is_watertight``
        (which also refuses to certify a sheet-cancelling zero-volume
        surface), remaining boundary/pinch edge counts,
        ``enclosed_volume_mm3`` when the surface closes up, and — when
        defects survive the pass — an ``unrepaired`` list saying which
        defect classes this tool has no repair for (pinched edges, where
        3+ triangles meet along one line, are not holes and cannot be
        sewn; they must be fixed where the geometry was made).  Read
        ``unrepaired`` before telling the user the mesh is fixed.

        :param file_path: Path to the STL file to repair.
        :param output_path: Output path.  Defaults to overwriting the input.
        :param close_holes: Also close open holes and fix boundary edges
            (slower; default False).
        :param weld_tolerance: Weld radius in mm.  Empty = auto (0.1 µm or
            a millionth of the part diagonal); "0" disables welding.
        :returns: Dict with repair statistics and residual-defect report.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

repair_mesh_advancedA

Deprecated alias for repair_mesh(close_holes=True).

        Kept for one release so existing callers keep working; new callers
        should use ``repair_mesh`` with ``close_holes=True``.  Behavior is
        identical to the original tool.

        :param file_path: Path to the STL file.
        :param output_path: Output path.  Defaults to overwriting the input.
        :param close_holes: Whether to attempt closing holes (default True).
        :param weld_tolerance: Weld radius in mm.  Empty = auto; "0"
            disables welding.
        :returns: Dict with repair statistics.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

splice_mesh_at_zA

Splice two meshes at a z-plane: top from one STL, bottom from another.

        Takes geometry ABOVE *z_plane* from *top_path* and geometry BELOW
        *z_plane* from *bottom_path*.  Triangles crossing the boundary are
        clipped cleanly.  No boolean ops -- works on non-manifold meshes.

        **Use case:** Combine a body with the correct top (e.g. logo from
        v5.3) with a body that has the correct bottom (e.g. larger pocket
        from v5.4) to create the next design iteration.

        :param top_path: STL providing geometry above z_plane.
        :param bottom_path: STL providing geometry below z_plane.
        :param z_plane: Z height (mm) where the splice happens.
        :param output_path: Output STL path. Auto-generated if empty.
        :returns: Dict with splice stats and output path.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

mirror_mesh_modelA

Mirror (reflect) a mesh along an axis.

        Creates a mirror image by negating coordinates on the chosen axis
        and reversing triangle winding order to preserve correct normals.

        :param file_path: Path to the STL file.
        :param axis: Axis to mirror ("x", "y", or "z", default "x").
        :param output_path: Output path (defaults to overwriting input).
        :returns: Dict with mirror info.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

hollow_mesh_modelA

Create a hollow version of a mesh to save material.

        Generates an inner offset shell and combines it with the outer
        surface.  Reports estimated material savings.

        :param file_path: Path to the STL file.
        :param wall_thickness_mm: Wall thickness in mm (default 2.0).
        :param output_path: Output path (defaults to ``<name>_hollow.stl``).
        :returns: Dict with hollowing stats and material savings.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

thicken_mesh_wallsA

Thicken a part's walls by moving every surface out amount_mm.

        Two routes, and the reply says which ran:

        * **The CAD file** -- pass the part's STEP file (``.step`` /
          ``.stp``), or a mesh Kiln converted from one that still sits
          beside it.  The CAD kernel moves every face exactly, and round
          holes keep their size so screws still fit.  Walls gain twice the
          amount; the outside grows twice the amount on every axis.
        * **A mesh** with no CAD file -- vertices are moved and the result
          is MEASURED against the input: the thinnest wall must gain at
          least the amount, the surface must stay closed, and every hole
          must survive.  A result that fails is refused with the
          measurements and your file is left as it was (on a part with
          holes and thin features this is the usual outcome -- use the
          CAD route).

        Openings that are not round holes (slots, vents, cutouts) narrow by
        twice the amount on either route.

        Use after ``analyze_printability`` or ``predict_print_failures``
        flags thin walls.

        AGENT DISPLAY CONTRACT: the reply carries a before|after
        self-check of the part.  Look at it and write what changed before
        calling the job done.

        :param file_path: The part: a STEP file, or a mesh (STL/OBJ/3MF).
        :param amount_mm: How far every surface moves out, in mm (0-5).
        :param output_path: Output path (defaults to ``<name>_thickened.stl``).
        :param keep_hole_size: Keep round holes at their diameter
            (default).  False lets them close in with everything else.
        :returns: ``path``, ``method`` (``cad`` or ``mesh``), the
            measurements before and after, and a ``note``; or a refusal
            saying why the result was worse than the part.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

add_mesh_filletA

Round a part's edges, exactly, on its CAD file.

        Pass the part's STEP file (or a mesh Kiln converted from one that
        still sits beside it).  The CAD kernel rebuilds each face, so the
        result is a closed solid of the size geometry gives; it comes back
        as a mesh (``path``) and as CAD beside it (``step_path``), so the
        next edit starts from CAD again.

        Literal: it rounds the edges you select at the radius you give.
        Two things can change that, and the reply says so each time:

        * an edge on a narrow face gets a smaller radius (the face keeps
          one nozzle width of flat), or stays sharp when what is left
          would not show in a print;
        * a hole's rim stays sharp unless you select it.

        ``edges.left_sharp`` lists every selected edge left sharp, with
        its reason.  ``edges.cautions`` says what will print badly as
        asked: a finish on the bed or facing down whose surface overhangs
        past what the printer bridges, and by how much.

        A mesh with no CAD file behind it is refused: rounding on a mesh
        left an open surface and a bigger part on every part measured.  A
        part made from an OpenSCAD script is rounded in its script; the
        refusal names it.

        AGENT DISPLAY CONTRACT: a result carries a before|after self-check
        of the part.  Look at it and write what changed before calling
        the job done.

        :param file_path: The part: a STEP file, or a mesh converted from one.
        :param radius_mm: Fillet radius in mm (default 1.0).
        :param angle_threshold_deg: An edge is sharp when the surface
            turns at least this much across it (default 60).
        :param output_path: Output ``.stl`` path (defaults to
            ``<name>_filleted.stl``); the CAD is written beside it.
        :param edges: Which edges.  Empty or ``all``: every sharp edge.
            Words narrow it -- where the edge sits as the part prints
            (``vertical``, ``top``, ``bottom``, ``under``, ``sloped``) and
            which way the corner goes (``outside``, ``inside``);
            ``holes`` selects hole rims.  Combine with commas:
            ``top,outside``.  Or name edges by id: ``e12,e15`` (ids come
            from ``plan_only``).
        :param printer_id: The printer the part is for; sizes are limited
            by its nozzle and layer height.
        :param nozzle_mm: The nozzle size, when it differs from the one
            Kiln has for the printer.
        :param layer_height_mm: The layer height it will print at.
        :param material: The material it will print in.
        :param plan_only: Return the plan and every edge's id without
            building anything.
        :returns: ``path``, ``step_path``, ``edges`` (finished, left
            sharp, cautions), ``sized_for``, ``volume_mm3`` and the
            measurements before and after; or a refusal saying why.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

add_mesh_chamferA

Bevel a part's edges, exactly, on its CAD file.

        The flat-faced twin of ``add_mesh_fillet``: same CAD route, same
        edge selection, same reply.

        Literal: it bevels the edges you select at the distance you give
        (measured along each face from the edge).  An edge on a narrow
        face gets a smaller bevel or stays sharp, a hole's rim stays sharp
        unless selected, and ``edges.left_sharp`` gives every reason.

        A mesh with no CAD file behind it is refused, and a part made
        from an OpenSCAD script is bevelled in its script; each refusal
        says which.

        AGENT DISPLAY CONTRACT: a result carries a before|after self-check
        of the part.  Look at it and write what changed before calling
        the job done.

        :param file_path: The part: a STEP file, or a mesh converted from one.
        :param distance_mm: Bevel distance from the edge in mm (default 0.5).
        :param angle_threshold_deg: An edge is sharp when the surface
            turns at least this much across it (default 60).
        :param output_path: Output ``.stl`` path (defaults to
            ``<name>_chamfered.stl``); the CAD is written beside it.
        :param edges: Which edges; see ``add_mesh_fillet``.
        :param printer_id: The printer the part is for.
        :param nozzle_mm: The nozzle size, when it differs from the one
            Kiln has for the printer.
        :param layer_height_mm: The layer height it will print at.
        :param material: The material it will print in.
        :param plan_only: Return the plan and every edge's id without
            building anything.
        :returns: ``path``, ``step_path``, ``edges`` (finished, left
            sharp, cautions), ``sized_for``, ``volume_mm3`` and the
            measurements before and after; or a refusal saying why.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

scale_mesh_to_fitA

Auto-scale a mesh to fit within a build volume while maintaining aspect ratio.

        Useful when a model is too large for your printer -- this uniformly
        shrinks it to the largest size that fits.

        :param file_path: Path to mesh file (.stl).
        :param max_x_mm: Maximum X dimension of build volume.
        :param max_y_mm: Maximum Y dimension of build volume.
        :param max_z_mm: Maximum Z dimension of build volume.
        :param printer_id: Optional supported printer model id.  When
            provided, printer intelligence supplies the build volume.
        :param output_path: Output path. Defaults to overwriting input.
        :returns: Dict with original/new dimensions and scale factor.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

center_model_on_bedA

Center a mesh on the build plate and place at z=0.

        Translates the model so it sits centered on the bed with its
        lowest point touching the build plate.

        :param file_path: Path to the STL file.
        :param bed_x_mm: Build plate X dimension (default 256).
        :param bed_y_mm: Build plate Y dimension (default 256).
        :param printer_id: Optional supported printer model id.  When
            provided, printer intelligence supplies the bed size.
        :param output_path: Output path (defaults to overwriting input).
        :returns: Dict with translation applied.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

compose_modelsA

Merge multiple mesh files into a single combined model.

        Concatenates all triangle geometry from the input files into one
        output STL.  No boolean operations — bodies are simply combined.
        Useful for multi-part assemblies or adding components to a design.

        **See also:** ``merge_mesh_files`` for the same operation with
        a different parameter style, or ``merge_stl`` for positional
        offset support.

        :param file_paths: List of .stl/.obj/.glb file paths to merge.
        :param output_path: Path for the combined output STL.
        :returns: Dict with merge statistics.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

merge_mesh_filesA

Combine multiple STL files into a single mesh file (simple concatenation).

        For positioning parts with x/y/z offsets, use ``merge_stl`` instead.
        Useful for composing multi-part designs into one printable file.

        :param file_paths: List of STL file paths to merge.
        :param output_path: Destination path for the merged file.
        :returns: Dict with merge statistics.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

boolean_mesh_opA

Perform a CSG boolean operation on two or more STL meshes.

        Uses OpenSCAD's boolean engine to compute:
        - **union**: combine multiple bodies into one
        - **difference**: subtract subsequent bodies from the first
        - **intersection**: keep only the overlapping region

        Requires OpenSCAD installed on the system.

        **Use cases:**
        - Subtract a cylinder from a block to create a hole
        - Combine multiple parts into a single printable body
        - Create complex shapes from simple primitives

        :param operation: ``"union"``, ``"difference"``, or ``"intersection"``.
        :param file_paths: List of STL file paths (minimum 2).
        :param output_path: Output path (defaults to a temp file).
        :returns: Dict with result path, operation, and triangle count.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

compose_part_from_primitivesA

Build a functional part by composing geometric primitives with booleans.

        The **CAD-aware generation path** -- instead of asking text-to-mesh AI
        to guess at geometry, describe parts as a tree of primitives combined
        with boolean operations. Produces exact, deterministic, functional parts.

        **SAFETY DEFAULT (changed 2026-04-15):** ``center_on_bed=True`` is the
        default.  OpenSCAD primitives are natively centered on the model origin
        (``cylinder(h,r)`` produces geometry centered on X/Y = (0,0), which
        means half the geometry lives at NEGATIVE X/Y).  Sending such an STL
        to most FDM printers (Bambu, Prusa, Ender, Creality) — whose bed
        origin is the front-left corner — causes the nozzle to drive off-bed
        into the purge/wipe assembly on layer 1.  This happened once on a
        Bambu A1 (incident #0, 2026-04-15, nearly damaged the printer).

        With ``center_on_bed=True`` the output STL is translated so it sits
        centered on the build plate and its lowest point touches z=0.  Set
        ``center_on_bed=False`` only if your downstream flow expects
        origin-centered geometry (e.g. further CAD composition).

        **Operation format** -- each item is either a primitive or boolean:

        Primitive: ``{"type": "primitive", "shape": "<shape>",
        "params": {...}, "translate": [x,y,z], "rotate": [rx,ry,rz]}``

        Boolean: ``{"type": "boolean", "operation": "union|difference|intersection",
        "children": [op1, op2, ...]}``

        **Primitive shapes and params:**
        - cube: ``{"size": [x,y,z]}`` or ``{"size": scalar}``
        - cylinder: ``{"h": height, "r": radius}`` or ``{"h", "r1", "r2"}``
        - sphere: ``{"r": radius}``
        - cone: ``{"h": height, "r1": bottom_r, "r2": top_r}``
        - torus: ``{"major_r": ring_radius, "minor_r": tube_radius}``
        - wedge: ``{"width": w, "depth": d, "height": h}``
        - hex_prism: ``{"r": radius, "h": height}``  -- hexagonal (for nuts)
        - text: ``{"text": "string", "size": 10, "depth": 2}``
        - rounded_cube: ``{"size": [x,y,z], "radius": 1}``
        - pipe: ``{"h": height, "outer_r": 10, "inner_r": 8}``

        Requires OpenSCAD installed on the system.

        :param brief_id: The saved goal's id from ``design_session``; pass it so
            this make joins the goal (recorded against it; Kiln Pro checks the
            result against it). Empty when there is no goal.
        :param operations: List of operation dicts (primitive/boolean tree).
        :param output_path: Output path (defaults to temp file).
        :param center_on_bed: Translate output to bed-center (default True).
        :param bed_x_mm: Build plate X dimension for centering (default 256).
        :param bed_y_mm: Build plate Y dimension for centering (default 256).
        :param printer_id: Optional supported printer model id.  When
            provided, printer intelligence supplies the bed size.
        :returns: Dict with result path, SCAD code, triangle count, and
            (if centered) ``bed_centered=True`` + applied translation.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

MAKE DOORS: design_session, Kiln's front door for making an object, is not installed here (signed in to Kiln it runs on Kiln's servers). On this install compile_scad IS the make → preview → iterate loop: make it, show the preview, iterate.

split_mesh_by_componentA

Split a multi-component mesh into separate STL files.

        Identifies disconnected bodies (components) using shared-edge
        analysis and writes each as a separate file.

        :param file_path: Path to mesh file (.stl).
        :param output_dir: Directory for output files. Defaults to input directory.
        :returns: Dict with component count and file paths.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

remove_mesh_floating_regionsA

Remove small disconnected components (floating geometry).

        Downloads and marketplace models often contain support pillars,
        internal fragments, or other floating geometry.  This tool
        identifies connected components and removes the small ones.

        :param file_path: Path to the STL file.
        :param output_path: Output path (defaults to overwriting input).
        :param keep_largest: Keep only the largest component (default True).
        :param min_triangle_pct: Min triangle % to keep (when keep_largest=False).
        :returns: Dict with removal statistics.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

simplify_mesh_modelA

Reduce mesh triangle count for faster preview or smaller files.

        Uses vertex-clustering decimation to merge nearby vertices.
        The result is a lower-resolution version of the same shape.

        :param file_path: Path to the STL file.
        :param target_ratio: Target fraction of original triangles (0.01-1.0).
        :param output_path: Output path (defaults to ``<name>_simplified.stl``).
        :returns: Dict with original/simplified triangle counts and reduction percentage.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

export_model_3mfA

Export a mesh to 3MF format (preferred by modern slicers).

        Converts STL/OBJ/GLB to 3MF, a ZIP-based XML format used by
        PrusaSlicer, OrcaSlicer, and Bambu Studio.  3MF is more compact
        and supports metadata better than STL.

        :param file_path: Path to the input mesh file.
        :param output_path: Output 3MF path.  Auto-generated if empty.
        :returns: Dict with the output file path.
        
extract_model_from_3mfA

Extract the embedded 3D model from a .3mf or .gcode.3mf file to STL.

        3MF files are ZIP archives containing XML mesh geometry.  This tool
        parses the embedded model, extracts all mesh objects, and writes a
        binary STL file ready for slicing, multi-copy printing, or further
        mesh operations.

        .. note::
            For extracting a single object's **G-code** from a multi-object
            Bambu .gcode.3mf file, use ``extract_plate_object`` instead.
            Use ``list_plate_objects`` to discover available objects.

        Works with both standard 3MF files and Bambu Studio .gcode.3mf files
        (which bundle both G-code and the source model).  When multiple
        objects exist they are merged into a single STL.

        :param file_path: Path to the .3mf or .gcode.3mf file.
        :param output_path: Output STL path (auto-generated if empty).
        :returns: Dict with output path, triangle/vertex counts, and dimensions.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

show_on_stageA

Open Kiln's interactive 3D stage on a file that already exists.

        The door for "let me see it" when nothing needs making: a mesh
        from an earlier session, a download, or the sliced print file
        about to go to the printer.  Nothing is re-made, re-sliced,
        imported or written.  Free on every install, like the stage.

        What the stage draws (``shows`` says which, in words):

        - An STL, OBJ or 3MF is drawn as itself; a STEP file is drawn
          from Kiln's mesh of it.
        - A sliced ``.gcode.3mf`` is drawn as the model it carries — the
          file going to the printer, in its paint — with the slicer's
          skirt, brim, prime tower and supports under EXTRAS while this
          machine still holds that slice's G-code.
        - A print file with no model of its own (raw G-code, or an
          archive holding only Kiln's 1 mm placeholder) is drawn as the
          mesh this machine sliced it from, and refused, with the
          reason, when there is no record of that mesh.

        Before a print: open the print file here, let the person turn it
        over, then call ``issue_preview_token(file_path, door="stage")``
        for that same file — the panel's own fetch is the evidence the
        gate reads.  On a host that draws no panel, or until a panel has
        fetched since the server started, the result also carries
        ``viewer_url``: hand it over, and use ``door="url"``.  ``shown``
        says which door this result took.

        ``visualize_model`` is the still-picture door: renders to check
        yourself, and the sign-off only when neither this panel nor a
        link is possible.

        A slice result that opened the stage has already drawn its print,
        from the mesh the slicer was handed, and the print gate counts
        that panel's fetch for the print file the slice wrote.  Called on
        that print file right after, this draws the same slice again,
        from the model the file carries.  ``shown.repeat`` says when the
        panel just above already shows what this one draws.

        :param file_path: Path to an STL, OBJ, 3MF, STEP, ``.gcode.3mf``
            or G-code file on this machine.
        :returns: ``stage_mesh_path`` (the file the stage draws),
            ``shows`` and ``message``, plus ``came_from`` for a file a
            generator or a marketplace download brought in; the stage
            adds ``artifact``, ``shown`` and, when the link is the
            stage, ``viewer_url``.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

estimate_mesh_weightA

Estimate the printed weight of a model file (a STEP file is converted first).

        Uses the divergence theorem to compute mesh volume, then applies
        material density, infill ratio, and shell fraction for a realistic
        weight estimate.

        :param file_path: Path to an STL file.
        :param material: Material name (pla, abs, petg, tpu, nylon, etc.).
        :param infill_percent: Infill percentage 0-100 (default 20).
        :param wall_thickness_mm: Perimeter wall thickness in mm (default 1.2).
        :returns: Dict with volume, weight estimates, bounding box.
        
estimate_mesh_print_timeA

Rough print time estimate from mesh geometry (STL/OBJ/GLB; a STEP file is converted first).

        Divides the plastic the part needs by the rate a print head lays
        it down, plus per-layer overhead.  It is a planning figure for a
        printer it is not told about: ``range_seconds`` is how far a real
        slice has sat from it, and the printer is most of that spread.

        Unlike estimate_print_time (which slices the part with the
        printer's profile, and is the real answer when a slicer is
        installed), this works directly on mesh files before slicing.

        :param file_path: Path to mesh file.
        :param layer_height_mm: Layer height for slicing.
        :param print_speed_mm_s: Average print speed in mm/s.
        :param material: Material hint (affects per-layer overhead).
        :returns: Dict with estimated time, its range, layer count,
            deposited plastic, assumptions, and note.
        
publish_print_twinA

Upload the current print's sliced file so the web Monitor can show the object and scrub its layers.

        The web Monitor at kiln3d.com calls this through the Kiln bridge
        while a print is running; there is normally no reason to call it
        by hand.  It reads the engine's own retained copy of the file it
        last sent to the printer (kept per printer under
        ``~/.kiln/monitor_twin``), uploads it — gzipped — to YOUR Kiln
        account, and returns a short-lived artifact token the browser
        uses to fetch the mesh and toolpath.  Nothing is uploaded except
        by this explicit call, and nothing crosses tenants: the token is
        IDOR-checked against your own account on every fetch.

        Honest refusals: prints Kiln did not slice on this machine (a
        pre-sliced upload, a job started at the printer's screen) have
        no retained file, and the response says so rather than guessing.

        Args:
            printer_name: Which printer's active print to publish.  Omit
                for the machine's single/default printer.

        Returns:
            ``{"success": True, "artifact_token", "stl_url"|null,
            "gcode_url"|null, "file_name", "expires_in"}`` on success;
            ``{"success": False, "code", "message"}`` otherwise.
        
monitor_print_visionA

Snapshot + structured data for AI visual inspection of an in-progress print.

        Use when analyzing camera images for print failures. Returns webcam image
        (base64 or saved file) alongside structured metadata (temps, progress,
        phase, cost estimate, failure hints). Can auto-pause on detected issues.
        For a quick text status report, use ``monitor_print`` instead.
        For persistent background monitoring, use ``watch_print``.

        Args:
            printer_name: Target printer.  Omit for the default printer.
            include_snapshot: Whether to capture a webcam snapshot (default True).
            save_snapshot: Optional path to save the snapshot image.
            failure_type: Optional detected failure type (e.g. "spaghetti",
                "layer_shift", "warping").  Reported by the agent after visual
                inspection of a previous snapshot.
            failure_confidence: Confidence score (0.0-1.0) of the failure detection.
            auto_pause: If True, automatically pause the print when a failure is
                detected with confidence >= 0.8.  Defaults to the value of the
                ``KILN_VISION_AUTO_PAUSE`` environment variable (default False).
            show_panel: Open the inline live monitor panel again even though
                one opened by an earlier call is still live above.  Pass only
                when the person asks to see the panel again.  Read by the
                inline monitor's result hook (``kiln.local_monitor``), not here.

INLINE LIVE MONITOR: in apps that draw MCP Apps panels, this tool's result also carries Kiln's inline print monitor — a live panel with progress, temperatures, and the camera while a print runs. The result's own 'Live monitor:' line says whether that panel is open here, attached but unconfirmed, or not available in this app (then it names the web monitor instead); repeat what that line says and never tell the person a panel is open on the strength of this description. The panel polls the printer itself once open, so do not call this tool again to refresh it: later checks go through printer_status or first_layer_status, and a repeat while the panel is live returns the text report with a one-line card, not a second panel. Pass show_panel=True only when the person asks to see the panel again. Free with a Kiln sign-in; the text report below is always complete on its own.

watch_printA

Start background monitoring of an in-progress print.

        Launches a background thread that polls the printer state every
        *poll_interval* seconds and captures webcam snapshots every
        *snapshot_interval* seconds.  Returns immediately with a
        ``watch_id`` that can be used with ``watch_print_status`` and
        ``stop_watch_print``.

        The watcher finishes automatically when:

        1. **Print terminal state** -- completed, failed, cancelled, or offline.
        2. **Snapshot batch ready** -- *max_snapshots* images collected.
        3. **Timeout** -- the print has not finished within *timeout* seconds.
        4. **cancel_at_percent** -- if set (> 0), auto-cancels when completion
           reaches or exceeds this percentage.  Use this for test prints,
           calibration runs, or any case where you want to stop at a specific
           progress point without writing a polling script.
        5. **Hardware stop** -- the print carries a hardware plan (pauses
           written in for nuts, magnets or bearings) and a stop is a few
           minutes away, the printer has stopped for the parts, or it went
           past a stop without stopping: ``outcome: "hardware_stop"`` with a
           ``hardware`` block saying what goes in.  Tell the person; at the
           stop itself, resume only on their word that every piece is in
           (``resume_print(hardware_confirmed=true)``).  Then watch again.

        **Camera ground-truth**: each captured snapshot is hashed and compared to
        the previous frame.  If the camera shows the print bed changing but
        telemetry reports zero progress, the snapshot is flagged with
        ``telemetry_mismatch: true`` so agents can detect broken monitoring
        scripts and fall back to visual inspection.

        Args:
            printer_name: Target printer.  Omit for the default printer.
            snapshot_interval: Seconds between snapshot captures (default 60).
            max_snapshots: Return after this many snapshots (default 5).
            timeout: Maximum seconds to monitor (default 7200 = 2 hours).
            poll_interval: Seconds between state polls (default 15).
            stall_timeout: Seconds of zero progress before declaring stall
                (default 600 = 10 min).  Set to 0 to disable stall detection.
            save_to_disk: Save snapshots as JPEG files to
                ``~/.kiln/timelapses/<watch_id>/`` and persist metadata to the
                database.  Use ``list_snapshots`` to query saved frames after
                the print completes (default False).
            cancel_at_percent: Auto-cancel when completion >= this value.
                Set to 0 (default) to disable.  Example: ``cancel_at_percent=50``
                cancels the print as soon as it reaches 50%.
        
watch_print_statusA

Check the current status of a background print watcher.

        Returns progress, collected snapshots, and whether the watcher
        has finished.

        By default returns immediately with the current state.  Set
        ``block_until_event=True`` to wait server-side until a new
        event fires on the bus matching this watcher's printer (or
        ``timeout`` seconds elapse).  Loop a single blocking call
        instead of polling every N seconds — roughly 50× fewer tool
        invocations on a multi-hour print.

        Args:
            watch_id: The watcher ID returned by ``watch_print``.
            block_until_event: If True, block until a matching event
                arrives on the event bus or ``timeout`` is reached.
                Default False (return immediately, current behaviour).
            timeout: Maximum seconds to block when
                ``block_until_event=True``.  Default 60.  MCP clients
                should set their tool-call timeout comfortably above
                this (e.g. 120s) so the call returns cleanly instead
                of being killed mid-wait.
            event_types: Optional list of event-type strings to wait
                on.  Defaults to
                ``["vision.alert", "print.terminal", "recovery.completed"]``
                — failure alerts, print completion, and recovery
                terminal state (so a recovered-and-resumed print
                doesn't leave the watcher hanging if no
                ``print.terminal`` fires for the failed attempt).
                Pass a custom list to wait on different events
                (e.g. ``["vision.frame_captured"]`` to wake on
                every snapshot).

        When ``block_until_event=True`` and an event arrives, the
        return payload includes ``events_received`` (list of events)
        alongside the watcher's current status.  On timeout the
        payload includes ``timed_out: True``.  If the watcher has
        already finished before subscription, the call returns
        immediately with ``watcher_already_finished: True``.
        
stop_watch_printA

Stop a background print watcher and return its final state.

        Signals the watcher thread to exit and removes it from the
        active watchers registry.

        Args:
            watch_id: The watcher ID returned by ``watch_print``.
        
start_monitored_printA

Start a print and automatically monitor the first layer.

        This is the recommended way to start prints autonomously. It combines
        start_print with first-layer monitoring in a single operation:

        1. Starts the print
        2. Waits for the configured delay (default 2 minutes)
        3. Captures snapshots during first layers
        4. Returns snapshots for you to visually inspect
        5. Optionally auto-pauses if you report a failure

        Use this instead of start_print when operating autonomously (Level 1/2)
        to satisfy the first-layer monitoring safety requirement.

        Args:
            file_name: Name of the file to print (must exist on printer).
            printer_name: Target printer. Omit for default.
            first_layer_delay: Seconds to wait before first snapshot (default 120).
            first_layer_checks: Number of first-layer snapshots to capture (default 3).
            first_layer_interval: Seconds between snapshots (default 60).
            auto_pause: Auto-pause if snapshot analysis detects failure (default True).
        
first_layer_statusA

Check the status of a first-layer monitor.

        Returns the current monitoring state, including any captured snapshots
        once monitoring is complete.  A fault the printer has stopped for
        rides this result as ``printer_fault`` (as it rides every tool
        result while Kiln's watchdog sees it standing); the monitor's own
        fields describe the first layer, not the machine's fault state.

        Args:
            monitor_id: The monitor ID returned by ``start_monitored_print``.
        
list_print_pipelinesA

List all available pre-validated print pipelines.

        Pipelines are named command sequences that chain multiple operations
        into reliable one-shot workflows (e.g. quick_print, calibrate, benchmark).
        
pipeline_statusA

Get the current state of a pipeline execution.

        Returns the execution state (running/paused/completed/failed/aborted),
        completed steps, and the name of the next step to run.

        Args:
            execution_id: The pipeline execution ID returned when starting a pipeline.
        
pipeline_pauseA

Pause a running pipeline at the next step boundary.

        The pipeline will finish the current step and then pause before
        starting the next one.  Use ``pipeline_resume`` to continue.

        Args:
            execution_id: The pipeline execution ID.
        
pipeline_resumeA

Resume a paused pipeline from where it stopped.

        Continues executing from the next unfinished step.

        Args:
            execution_id: The pipeline execution ID.
        
pipeline_abortA

Abort a running or paused pipeline.

        Immediately marks the pipeline as aborted. Any completed steps
        are preserved in the result.

        Args:
            execution_id: The pipeline execution ID.
        
pipeline_retry_stepA

Retry a specific failed step in a pipeline, then continue from there.

        Re-runs the step at the given index and, if it succeeds, continues
        executing the remaining steps.

        Args:
            execution_id: The pipeline execution ID.
            step_index: Zero-based index of the step to retry.
        
analyze_printabilityA

Analyze a 3D model for FDM printing readiness.

        Performs deep analysis of an STL or OBJ mesh including overhang
        detection, thin wall analysis, bridging assessment, bed adhesion
        surface estimation, and support volume estimation.  Returns a
        printability score (0-100), letter grade (A-F), and actionable
        recommendations.

        Pass ``material`` (and ``printer_id`` when a printer is
        registered) so the warping, thermal-stress, and adhesion checks
        run against the actual filament instead of generic PLA defaults.
        On the free tier those checks use conservative safe-floor
        thresholds; with Kiln Pro they are tuned to the specific
        material and printer (kiln3d.com/pricing).

        When the mesh turns out to have holes in it, the result also
        carries a ``fastener_advice`` block saying they were measured
        but not checked against the hardware meant to go in.  Kiln
        raises that once per session across every tool that can raise
        it, so a later analysis may omit the block even though the
        part has holes.  Read its ``agent_instruction`` before
        repeating any of it to the user.

        Args:
            file_path: Path to an STL or OBJ mesh file.
            nozzle_diameter: Printer nozzle diameter in mm.  Leave unset
                and name the printer: Kiln then checks for the nozzle on
                record for it, else the printer's own setting, else the
                model's stock size, and ``report.nozzle`` says which.
                With no printer named, the only printer Kiln knows of
                stands in; with none, the check assumes 0.4 and says so.
            layer_height: Print layer height in mm (default 0.2).
            max_overhang_angle: Maximum overhang angle in degrees before
                supports are needed.  Leave unset for the material's own
                limit (45 when none is known) — the value every other
                tool that reports this score uses, so the numbers agree.
            build_volume_x: Optional build volume X dimension in mm.
            build_volume_y: Optional build volume Y dimension in mm.
            build_volume_z: Optional build volume Z dimension in mm.
            material: Material ID for warping / thermal-stress / adhesion
                analysis (default ``"pla"``).
            printer_id: Optional registered printer whose real geometry
                and calibration should inform the analysis.
        
auto_orient_modelA

Find the optimal print orientation for a 3D model.

        Evaluates multiple rotations of the model, ranks them, and
        reports each candidate's bed contact, support volume, print
        height and overhang share.  On a plain install, and for a
        caller below Kiln Pro on Kiln's hosted service, the ranking is
        by bed contact, the lower part first between equals; a Kiln Pro
        caller on the hosted service gets Kiln's own scorer
        (https://kiln3d.com/pricing).  A caller the scorer was withheld
        from is told so once, in ``upgrade_hint``.  Optionally applies
        the best orientation and writes a reoriented STL file.

        Args:
            file_path: Path to an STL or OBJ mesh file.
            candidates: Number of candidate orientations to evaluate
                (default 24).
            nozzle_diameter: Printer nozzle diameter in mm (default 0.4).
            apply: If True, apply the best orientation and write the
                reoriented STL to disk.
            output_path: Output path for the reoriented STL.  Only used
                when ``apply`` is True.  Defaults to
                ``<input>_oriented.stl``.
        
estimate_supportsA

Estimate support volume for a 3D model.

        Analyzes the mesh for overhangs and estimates the volume of
        support material needed to print the model in its current
        orientation.

        Args:
            file_path: Path to an STL or OBJ mesh file.
            max_overhang_angle: Maximum overhang angle in degrees
                before supports are needed (default 45).
        
recommend_adhesion_settingsA

Recommend brim/raft settings for a 3D model based on geometry + material.

        Analyzes the model's bed contact area, material warp tendency, and
        printer type to produce a concrete brim width and optional raft
        recommendation.  Returns ``slicer_overrides`` ready to pass to
        ``slice_model`` or ``slice_and_print``.

        Args:
            model_path: Path to an STL or OBJ mesh file.
            material: Filament material (e.g. ``"PLA"``, ``"ABS"``,
                ``"PETG"``).  Affects warp risk calculation.
            printer_id: Optional printer model ID (e.g. ``"bambu_a1"``).
                Used to detect bed-slinger printers that need wider brims.
        
diagnose_print_failure_liveA

Diagnose a print failure using live printer state + model geometry.

        Unlike ``analyze_print_failure`` (which requires a job_id and
        analyzes historical data), this tool works in real-time by
        reading the current printer state and optionally analyzing
        the model that was being printed.

        Combines printer temperature deltas, bed adhesion analysis,
        overhang geometry, material properties, and printer intelligence
        to produce a ranked diagnosis with actionable fixes.

        Args:
            printer_name: Printer to diagnose.  Omit for the default printer.
            model_path: Path to the model file that was being printed.
                Enables geometry-based diagnosis (adhesion, overhangs).
            material: Filament material (e.g. ``"ABS"``, ``"PLA"``).
            printer_id: Printer model ID (e.g. ``"bambu_a1"``).
                Enables printer-specific intelligence lookup.
        
printer_benchA

Help Kiln get to know your printer in a few minutes: a guided session, one ask at a time.

Kiln judges where a second part can go on an occupied plate from a
record of how each printer moves its head on its own.  Where that
record has a blank -- a pause, cancel or end nobody has described, a
head nobody has measured -- Kiln assumes the worst.  This session
fills the blanks for THIS printer: it prints a coin-sized square,
pauses, resumes, cancels and ends it, and watches where the head goes.
A Klipper or Marlin printer says where its head is, so nothing about
the moves is asked; a closed-firmware printer is asked which numbered
zone the head stopped in (a picture is included) and about how high it
lifted.  Numbers only ever leave the machine, and only while telemetry
is on.  Runout is never tested.

Call it with no ``answer`` to start or resume.  Every reply carries
``ask`` (one sentence -- relay it word for word), ``images`` (what each
picture is; the pictures themselves follow the reply as images, in the
same order -- show them), ``options`` when the answer is a choice, and ``waiting`` with
``check_again_in_seconds`` when Kiln is watching the print and there is
nothing to ask yet.  Hand the person's answer back as ``answer``.  The
test print is a real print: when the reply says so, show the file with
``visualize_model``, get a token with ``issue_preview_token`` and start
it with ``run_quick_print`` -- the normal approval dialog shows, once.
``restart=True`` throws the session away and begins again.

Args:
    printer_name: Which printer.  Omit for the default one.
    answer: The person's answer to the previous ask, verbatim.
    restart: Begin again from the first ask.

Returns the next ask, or ``done`` with what Kiln learned, the payoff
line, and what it still does not know.
discover_printersA

Scan the local network for 3D printers.

        Uses mDNS/Bonjour and HTTP subnet probing to find OctoPrint,
        Moonraker/Creality, Bambu Lab, Elegoo, and Prusa printers on
        the local network.

        Args:
            timeout: Maximum scan duration in seconds (default 5).

        Returns a list of discovered printers with host, port, type, and
        whether the API is reachable.  Each one also carries
        ``address`` -- pass it as ``register_printer``'s ``host``; it
        keeps the port the printer answered on -- and ``to_connect``:
        what the person still has to supply and where they find it
        (``still_needed``), and anything to switch on in the printer
        first (``first``).  Ask for exactly those, in plain words, then
        add the printer with ``register_printer``.
        
list_trusted_printersA

Return the list of trusted printer hostnames/IPs.

Trusted printers are used to flag discovered printers that have been explicitly approved by the user, preventing spoofed-printer attacks.

trust_printerB

Add a printer hostname/IP to the trusted whitelist.

        Trusted printers are flagged during network discovery.  Connecting
        to an untrusted printer should raise a warning.

        Args:
            host: The hostname or IP address to trust.
        
untrust_printerA

Remove a printer hostname/IP from the trusted whitelist.

        Args:
            host: The hostname or IP address to untrust.
        
acquire_printer_lockA

Acquire an exclusive lock on a printer for safe concurrent access.

        Prevents multiple agents from controlling the same printer simultaneously.

        Args:
            printer_name: Printer to lock.
            holder: Identifier of the lock holder.
            timeout_seconds: Maximum time to wait for the lock.
        
hand_back_printerA

Tell Kiln you are taking a printer from here, so it can move on.

        Below the fleet tier Kiln works with one printer at a time: the
        machine it started a print on, or one it is watching for you.
        This hands that machine back — you keep the print, Kiln stops
        being the one driving it, and its attention is free for another
        printer.

        Nothing is cancelled and nothing is paused.  The print carries on
        exactly as it was; this only changes which machine Kiln considers
        itself responsible for.

        Called with no arguments it reports which printer Kiln is working
        with, without changing anything, so you can always find out where
        its attention is before moving it.

        One thing worth knowing before you do it: Kiln will come back to
        this print once if you need it to, and after that it stays with
        whatever machine it moved to until this print finishes.  Going
        back and forth between two running printers is what the fleet
        tier is for.

        Args:
            printer_name: Printer to hand back.  Omit to report only.
        
release_printer_lockB

Release an exclusive lock on a printer.

        Args:
            printer_name: Printer to unlock.
            holder: Identifier of the lock holder (must match acquire).
        
submit_jobA

Submit a print job to the queue.

Free tier allows up to 10 queued jobs for single-printer use.
Pro tier unlocks unlimited queue depth with multi-printer scheduling.

Args:
    file_name: G-code file name (must already exist on the printer).
    printer_name: Target printer name, or omit to let the scheduler
        pick any idle printer.
    priority: Higher values are scheduled first (default 0).
    idempotency_key: Optional opaque key (e.g. a UUID you generate)
        naming this one submission.  If your call fails in a way
        where you cannot tell whether the job was queued — a timeout,
        a dropped connection — retry with the SAME key: you will get
        the original job back (``submission: "replayed"``) instead of
        queuing a duplicate print.  Use a NEW key for each job you
        genuinely want printed; reusing a key with different
        parameters is refused.
    preview_token: Token from ``issue_preview_token`` after the user
        has seen the file.  Required: a queued job is a print the
        scheduler will start unattended, so the gate is here, at the
        door, and the sign-off rides the job.

Jobs are executed in priority order, with FIFO tie-breaking.
Use ``job_status`` to check progress and ``queue_summary`` for an overview.
job_statusA

Get the status of a queued or completed print job.

Args:
    job_id: The job ID returned by ``submit_job``.

Returns the full job record including status, timing, and metadata,
plus ``watch`` when the scheduler is watching it: ``state`` is
``moving`` / ``stalled`` / ``no_contact`` / ``watching`` and ``note``
is the sentence to show a person when it is not moving.
queue_summaryB

Get an overview of the print job queue.

Returns counts by status, next job to execute, recent jobs, and
``watch_alerts``: watched prints that have stalled or stopped answering
and need a person (they stay active until the printer ends them or
someone cancels).
cancel_queued_jobA

Remove one job from the print queue while it is still WAITING.

Queue bookkeeping only: this marks the row cancelled and never sends
anything to a printer.  To STOP a job the machine has already
started, use ``cancel_print`` — that is the tool that talks to the
hardware.

Args:
    job_id: The job ID to cancel.

Only a job still in the QUEUED state can be cancelled here.  A job
that has reached the machine (starting, printing, or paused) is
refused with ``code="PRINT_IN_PROGRESS"`` rather than cancelled,
because marking the row cancelled would leave the queue claiming a
print had stopped while the printer carried on running it.
cancel_queued_jobsA

Cancel ALL queued print jobs at once.

The bulk companion to ``cancel_queued_job`` (which cancels one job by id).
Cancels every job currently in the QUEUED state — clear a backed-up
queue in one call instead of cancelling one job at a time.

- ``printer_name``: limit the sweep to one printer's queued jobs; omit
  to clear every queued job.
- ``dry_run=True``: preview exactly which jobs WOULD be cancelled and
  change nothing.  Run this first when clearing a large queue.

Safety: this never cancels a running print.  Only jobs still in the
QUEUED state are cancelled; each job's status is re-checked immediately
before cancelling, so a job that has already started printing (or
finished, or was cancelled elsewhere) is skipped rather than
interrupted.  Use ``cancel_print`` to stop the job that is actually
running.  Each cancel emits the same ``JOB_CANCELLED`` event as
``cancel_queued_job``.

Returns ``{success, dry_run, count, cancelled, skipped, message}`` —
``count`` always equals ``len(cancelled)``; ``skipped`` is a list of
``{job_id, reason}`` for jobs that were not cancelled.
job_historyA

Get history of completed, failed, and cancelled print jobs.

        Args:
            limit: Maximum number of jobs to return (default 20, max 100).
            status: Optional filter by status -- "completed", "failed", or
                "cancelled".  Omit to show all finished jobs.

        Returns recent job records from newest to oldest, read from
        the durable job store on THIS machine (``~/.kiln/queue.db``)
        — a server restart does not shorten it.  The response
        declares its own SCOPE: ``scope.local.total_records`` gives
        the store's full matching count when ``limit`` truncated the
        page, other machines running Kiln keep their own histories,
        and the response marks itself ``incomplete`` if the durable
        store could not be read.
        
analyze_print_failure_smartB

Classify a print failure and suggest recovery steps.

        Uses heuristics based on error messages, print progress, and
        failure history to classify the failure type and generate an
        actionable recovery plan.

        With kiln-pro installed the answer can also carry
        ``nozzle_wear_hypothesis``: whether the printer's nozzle wear
        likely contributed.  That check is Kiln Pro
        (https://kiln3d.com/pricing); below it, a failure wear could
        explain carries ``nozzle_wear_hypothesis_gated`` saying so once.

        Args:
            progress: Print progress at failure (0.0 - 1.0).
            error_message: Error message from the printer or system.
            printer_name: Name of the printer that failed.
            job_id: Job ID of the failed print.
        
get_recovery_planB

Get a recovery plan for a specific failure type.

        Args:
            failure_type: One of: spaghetti, layer_shift, adhesion_loss,
                nozzle_clog, stringing, thermal_runaway, power_loss,
                filament_runout, warping, unknown.
            printer_name: Name of the affected printer.
            has_power_loss_recovery: Whether the printer supports
                power-loss recovery.
            has_filament_sensor: Whether the printer has a filament
                runout sensor.
        
failure_historyA

View failure history for a printer or failure type.

        Args:
            printer_name: Filter by printer name.
            failure_type: Filter by failure type.
            limit: Maximum records to return (default 20).

        The response declares its own SCOPE: these are the failures
        THIS machine recorded, and ``scope.local.total_records``
        gives the store's full matching count when ``limit``
        truncated the page.
        
plan_multi_copy_splitB

Plan parallel printing of multiple copies across printers.

        Distributes N copies of a file across available printers in the
        fleet for maximum parallelism.

        Args:
            file_path: Path to the G-code or model file.
            copies: Number of copies to print.
            material: Material type (default ``"pla"``).
        
plan_assembly_splitB

Split a multi-file assembly across printers.

        Assigns each file in a multi-part assembly to a different
        printer for parallel printing.

        Args:
            file_paths: List of file paths in the assembly.
            material: Material type (default ``"pla"``).
        
split_plan_statusB

Check the progress of a split plan.

        Args:
            plan_id: The plan ID returned by submitting a split plan.
        
cancel_split_planB

Cancel all pending/in-progress parts of a split plan.

        Args:
            plan_id: The plan ID to cancel.
        
analyze_generation_feedbackA

Analyze a generated model and get feedback for improvement.

        Returns feedback with specific constraints to add to the
        generation prompt to fix identified issues.

        Args:
            file_path: Path to the generated model file.
            original_prompt: The original generation prompt.
            failure_mode: Optional failure mode if the model was printed
                and failed (e.g. ``"adhesion"``, ``"spaghetti"``).
            max_overhang_angle: Maximum overhang angle in degrees.
            min_wall_thickness: Minimum wall thickness in mm.
            has_bridges: Whether the model has bridge features.
            has_floating_parts: Whether the model has disconnected parts.
            non_manifold: Whether the mesh is non-manifold.
        
improve_generation_promptA

Generate an improved prompt from feedback.

        Adds physical constraints to the original prompt to address
        printability and structural issues, without modifying the
        creative intent.

        The improved prompt is run through a three-check sanity gate
        (no contradictions, fits the provider budget, ≥70% original-token overlap so intent
        is preserved).  When ``enforce_sanity=True`` (default) and
        the gate fails, this tool refuses with
        ``code="SANITY_GATE_FAILED"`` and returns the failure list
        instead of a contradictory prompt.  Callers that genuinely
        want the failed prompt — for inspection, repair, or model
        self-correction — set ``enforce_sanity=False`` and read
        ``improved_prompt.sanity`` from the response.

        Args:
            original_prompt: The original generation prompt.
            failure_mode: Optional failure mode string.
            max_overhang_angle: Maximum overhang angle detected.
            min_wall_thickness: Minimum wall thickness detected.
            has_bridges: Whether bridges were detected.
            iteration: Which retry iteration this is.
            file_path: Optional path to the STL file for structural
                analysis.  When provided, the tool also analyzes
                structural risks and folds them into the improved
                prompt.
            enforce_sanity: When True (default), refuse the
                response if the prompt sanity gate fails.  Pass
                False to receive a contradictory prompt anyway —
                useful when the agent intends to repair it before
                sending to the generator.
        
generation_feedback_loop_statusC

Check the status of a generation feedback loop.

        Args:
            model_id: The model ID of the feedback loop.
        
detect_print_failureB

Analyze printer telemetry to detect and classify a print failure.

        Examines current telemetry data and optional historical snapshots
        to identify failure conditions such as thermal runaway, layer shift,
        filament runout, adhesion loss, nozzle clogs, and more.

        Args:
            printer_name: Identifier of the printer to analyze.
            telemetry: Current telemetry snapshot with keys like
                ``hotend_temp``, ``bed_temp``, ``connected``,
                ``filament_detected``, etc.
            telemetry_history: Optional list of recent telemetry snapshots
                for trend analysis (newest last).
            job_info: Optional current job metadata with keys like
                ``file_name``, ``layer``, ``total_layers``, ``z_mm``.

        Returns a failure report dict if a failure is detected, or a
        success dict with ``failure_detected: False`` if no failure found.
        
plan_failure_recoveryA

Generate a recovery plan for a previously detected failure.

        Uses the failure ID from a prior ``detect_print_failure`` call
        to look up the failure report and generate an appropriate recovery
        strategy with preparation steps, parameter adjustments, and risk
        assessment.

        **Which recovery tool to use:**

        - Have a printer_name + job_id from a failed print? → ``plan_print_recovery``
        - Have a failure_id from ``detect_print_failure``? → ``plan_failure_recovery`` (this tool)

        With kiln-pro installed the answer can also carry
        ``nozzle_wear_hypothesis`` (Kiln Pro), or below Pro
        ``nozzle_wear_hypothesis_gated``, as for
        ``analyze_print_failure_smart``.

        Args:
            failure_id: The failure_id from a detect_print_failure result.
            printer_capabilities: Optional printer capabilities dict.
            safety_profile: Optional safety profile dict.
        
start_print_recoveryA

Begin executing a recovery plan.

        Creates a recovery session that tracks the recovery lifecycle.

        Args:
            plan_id: The plan_id from a plan_failure_recovery result.
            failure_id: The failure_id this recovery addresses.
        
confirm_print_recoveryA

Confirm that a recovery plan should proceed.

        For plans requiring human confirmation, transitions from
        ``awaiting_confirmation`` to ``executing``.

        Args:
            session_id: The session_id to confirm.
        
cancel_print_recoveryC

Cancel an active recovery session.

        Args:
            session_id: The session_id to cancel.
            reason: Optional reason for the cancellation.
        
get_recovery_session_statusC

Get the current status of a recovery session.

        Args:
            session_id: The session_id to query.
        
get_recovery_gcode_stepsC

Get the G-code/commands for executing a recovery.

        Args:
            session_id: The session_id to get steps for.
        
record_recovery_checkB

Record a post-recovery monitoring check result.

        After recovery execution, monitoring checks verify the print
        is proceeding correctly.

        Args:
            session_id: The session_id being monitored.
            passed: Whether this monitoring check passed.
            notes: Optional notes about the check result.
        
complete_print_recoveryA

Mark a recovery session as completed.

        On failure (success=False) with ``alternative_printers`` and
        kiln-pro installed, the answer can carry a
        ``reroute_recommendation``: whether the failed job should
        move to one of those printers, and which.  Choosing between
        printers is Kiln Business (https://kiln3d.com/pricing); below
        it the answer says so once in ``reroute_recommendation_gated``.
        A failure that needs hands-on inspection of the printer is
        held where it is, in ``reroute_recommendation``, at every
        tier.  Recommendation only; the agent runs any move itself
        via ``submit_job`` / ``start_print``.

        Args:
            session_id: The session_id to complete.
            success: Whether the recovery was ultimately successful.
            notes: Final notes about the recovery outcome.
            alternative_printers: Optional other printers the job
                could move to (each with ``printer_id`` plus optional
                ``is_idle``, ``supported_materials``,
                ``build_volume_mm``, ``success_rate``).  Read only
                when ``success=False``.  Single-printer setups can
                omit this.
            completion_pct_at_failure: How far the failed print got
                (0.0–1.0); the recommendation weighs it.  Defaults
                to 0.
        
get_recovery_statisticsA

Get historical recovery success rates and failure distribution.

Returns aggregate statistics about all recovery attempts including success rates per strategy, failure type distribution, and active session counts.

repair_guideA

Walk through the printer maker's own repair guide, one step per call.

The guide is the maker's published page for THIS model, reproduced in the
maker's order: their power-off warning first, their numbered steps in
their words, their picture for each step (as a URL, served from their
site with attribution -- Kiln never copies it), and their own check at
the end where the page has one.  Kiln adds words only where the picture
cannot say it.  Where the maker states them, the header carries the
tools, the interval ("every 10-15 spools") and the parts.

**Run it in steps, with the person at the machine.**  ``plan_only=True``
returns the header (maker, page title and URL, the maker's own "also
applies to" sentence, tools, interval, parts) plus step 0 and the step
titles.  ``step=0`` is ALWAYS the maker's power-off warning, verbatim.
``step=N`` returns only step N and names step N+1.  Every step from 1 on
requires ``power_off_confirmed=True`` -- a PERSON's statement that the
printer is off and unplugged; without it the call is refused with
``POWER_OFF_REQUIRED`` and the warning itself.  Never set it on a
person's behalf.  A person who is already partway in (the screw is out)
skips ahead with ``step``; Kiln never assumes where they are.

Where Kiln has no guide for the topic it says so: the maker's own
maintenance index for this model where Kiln knows it (``maker_index_url``),
otherwise "your maker publishes no guide Kiln can step through".  No
generic procedure is ever presented as the maker's.

Args:
    printer_id: Printer model identifier (e.g. ``bambu_a1_mini``).  Omit
        to use the declared ``printer_model`` of ``printer_name`` (or the
        default printer).
    topic: What to repair -- ``cutter``, ``nozzle``, ``hotend``,
        ``ptfe_tube``, ``extruder_gears``, ``belts``, ``bed_level``,
        ``lubrication``, ``firmware_recovery``, ``filament_sensor``.  A
        fault code written here is read as one.
    hms_code: The code on the printer's screen (``"1200-8001"``, any
        separators); where it maps to a guide, that guide is chosen and
        the answer says which step to start at.
    step: Which step to serve (0 = the power-off warning).  Ignored with
        ``plan_only``.
    plan_only: Return the header and step titles; serve no step.
    power_off_confirmed: A PERSON has powered the printer off and
        unplugged it.  Required for every ``step >= 1``.
    printer_name: Which registered printer's declared model to use when
        ``printer_id`` is omitted.
    guide: A guide's slug, from a ``choices`` answer.  When a topic
        matches more than one of the maker's guides for this model (one
        Kiln printer id can cover two machines; a maker often has two
        pages for one job) the answer lists them and nothing is picked
        for the person -- ask, then pass the chosen slug here.
safety_auditA

Query the safety audit log.

        Returns a record of all safety-relevant operations: tool executions,
        blocked attempts, rate-limit violations, and preflight failures.

        Args:
            action: Filter by action type.  Options: ``"executed"``,
                ``"blocked"``, ``"rate_limited"``, ``"auth_denied"``,
                ``"preflight_failed"``, ``"dry_run"``.  Omit for all.
            tool_name: Filter by MCP tool name (e.g. ``"send_gcode"``).
            limit: Maximum number of records to return (default 25, max 100).
        
safety_statusA

Get a comprehensive snapshot of all active safety measures.

        Returns a single summary showing: the active safety profile, temperature
        limits, rate-limit configuration, recent blocked actions, authentication
        status, and confirmation-mode status.  Use this to answer "is my printer
        safe right now?" in a single call.
        
safety_settingsA

Show current safety and auto-print settings.

Displays whether auto-print is enabled for marketplace downloads and AI-generated models, and which printers have always allow on, along with guidance on how to change them. Call this early in a session to understand what safety protections are active.

list_safety_profilesA

List the printers Kiln has a safety profile for, by id and name.

        The list names printers; it carries no limits.  Kiln reads a
        printer's limits one printer at a time: call
        ``get_safety_profile`` with one of these ids for its temperature,
        feedrate and flow limits, its build volume, and where those
        numbers came from.  ``validate_gcode_safe`` checks commands
        against one printer's limits.  A printer set up on this machine
        with limits its owner entered is listed too, marked
        ``set_up_on_this_machine``.
        
get_safety_profileA

Get the full safety profile for a specific printer model.

        Returns temperature limits, feedrate limits, volumetric flow,
        build volume, and safety notes.  Falls back to the default
        profile if the printer_id is not found.

        The profile also says where its numbers came from:
        ``owner_supplied`` lists any limit fields whose values were
        typed by this machine's owner rather than verified by Kiln,
        and ``limits_provenance`` is a ready-made sentence stating
        it.  Repeat that sentence when quoting a limit, so a
        verified number and a typed one are never presented with
        the same authority.

        Args:
            printer_id: Printer model identifier (e.g. ``"ender3"``,
                ``"bambu_x1c"``, ``"prusa_mk4"``).
        
add_safety_profileA

Add a local safety-profile override for a printer model. Free at every tier.

        Validates the profile and saves it to this machine's override file
        (``~/.kiln/local_printer_overrides.json``; the older name
        ``community_profiles.json`` is still read).  Nothing saved here is
        uploaded, pooled or shared.

        An override may only TIGHTEN a curated limit.  A higher number is
        discarded in favour of Kiln's curated value, so this is the right
        tool for a printer Kiln has never heard of, or for holding your own
        machine BELOW the curated limits.

        It is the WRONG tool for "my hotend is upgraded".  Use
        ``select_printer_variant`` for that: it resolves to a ceiling Kiln
        has verified against the manufacturer, instead of one you typed.

        Values saved here are labelled owner-supplied in every profile
        readout — Kiln never presents them as its own verified numbers.

        For a printer Kiln has no number for, a limit above its generic
        floor needs two things.  A signed-in install (a free account:
        ``kiln_signin``), because Kiln vouches for ceilings it enforces
        and a ceiling nobody set is held to the floor.  And a PERSON's
        confirmation: Kiln shows a code on the screen of the machine it
        runs on, the person types it in the chat, you pass it to
        ``give_print_code``, then call this again with the same numbers.  Find the numbers on the maker's own spec
        page (maximum hotend and bed temperature, bed size) and say where
        they came from in ``notes``; never guess them, and never ask the
        person to type numbers they do not know.  The code is the
        confirmation; nothing you can call stands in for it.

        A Klipper printer that is set up here can state them itself.
        Leave ``profile`` out and Kiln reads the heater ceilings, travel
        and velocity limit off the printer's own configuration (through
        Moonraker), puts them in front of the person as ``proposal`` with
        the configuration lines they came from, and takes the same code.
        The saved limits are labelled as read from that printer.  The
        hotend and bed numbers are the board's shutdown points, and a
        hotend proposal above Kiln's generic floor carries a
        ``caution`` about PTFE-lined hotends: say it to the person
        before they confirm.  A printer that cannot state them (any
        other backend) says so and asks for ``profile``; a
        configuration that states only some of them hands those back
        in ``proposal`` for you to complete.

        Args:
            printer_model: Short identifier for the printer (e.g.
                ``"my_custom_corexy"``).
            profile: Dict containing at least ``max_hotend_temp``,
                ``max_bed_temp``, ``max_feedrate``, and ``build_volume``
                (a list of 3 positive numbers ``[X, Y, Z]``).  Optional
                fields: ``display_name``, ``max_chamber_temp``, ``min_safe_z``,
                ``max_volumetric_flow``, ``notes``.  Omit it to read the
                limits off the printer.
            printer_name: Which registered printer to read the limits
                off when ``profile`` is omitted; the default printer
                when empty.  Ignored when ``profile`` is given.
        
list_printer_variantsA

Show the curated hardware variants available for a printer.

        A curated profile describes a printer AS SHIPPED.  When Kiln has
        verified a documented hardware change — an Ender 3 whose PTFE-lined
        hotend has been replaced with an E3D Revo CR, say — that
        configuration is curated as a VARIANT, with its own limits, its
        manufacturer source, and the preconditions that make it true.

        Returns the as-shipped limits alongside each variant's, so you can
        see what selecting one would change before selecting it.  An empty
        ``variants`` map is the honest answer for a machine Kiln has not
        verified a modified configuration for.

        Args:
            printer_model: Printer identifier (e.g. ``"ender3"``).
        
select_printer_variantA

Declare which curated hardware variant your machine actually is.

        This is how an operator with a modified printer gets an accurate
        ceiling WITHOUT typing one.  You say which hardware you have; Kiln
        supplies the limit from curated, manufacturer-sourced data.  There
        is no argument here that accepts a temperature, which is the point:
        a limit Kiln enforces is always a limit Kiln verified.

        Check ``requires`` on the variant first — a ceiling is only true if
        its preconditions are met.  Several variants need a firmware change
        as well as the part, and selecting the variant is your statement
        that you have done both.  Kiln cannot check your hardware remotely.

        The declaration stays on this machine.  It is never uploaded or
        pooled, and it is ignored entirely on hosted multi-tenant
        deployments, where "this machine" has no single owner.

        Args:
            printer_model: Printer identifier (e.g. ``"ender3"``).
            variant_id: Variant to declare, from ``list_printer_variants``.
                Pass ``""`` to go back to the as-shipped profile.
        
give_print_codeA

Relay the code the person typed after Kiln showed one on their screen.

        When a print is refused with "a code was just shown in a notification",
        ask the person to type it here, then pass their exact words: the code
        alone approves that one print; the code followed by ``2h`` or ``today``
        also keeps printing on that printer without asking for a while. Then
        call the start tool again. Nothing you can call reveals the code; a
        wrong guess counts, and three wrong guesses void every code for a minute.
        When the reply carries ``phone_next_time``, pass that one line on once
        the print has started.

        Args:
            words: Exactly what the person typed, e.g. ``4821`` or ``4821 2h``.
        
consent_window_statusA

Which standing consent windows are open, for what, until when.

        A standing window is the person's "yes, for a while": inside it,
        prints start on the named printer without asking each time (each
        one still previewed first).  Only the person opens one — by
        picking "yes, and for the next…" in the approval dialog, or with
        ``kiln consent window`` at a terminal.  Nothing an agent can call
        opens or extends one.  Closing one is always allowed: see
        ``revoke_consent_window``.

        An entry with ``always: true`` is always allow: the person turned
        it on for one printer — at a terminal, or on their Kiln account
        page (``opened_via`` says which) — it has no end (``until`` is
        null), and prints there start without asking until it is turned
        off.  ``turned_off`` lists any that Kiln turned off itself in the
        last day because a different printer was set up under the name.

        Args:
            printer_name: Show only the window covering this printer.
                Omit for every open window.
        
revoke_consent_windowA

Close a standing consent window now. Prints ask the person again.

        The person opened the window — in the approval dialog or at a
        terminal — and can close it here, through you, without touching
        a terminal: when they say to close it, call this.  Closing is
        the safe direction, so it needs no confirmation and no window
        can refuse it.  Jobs queued under the window will not start.

        This is also how always allow is turned off: when the person
        says "ask me first", call this with the printer's name (or the
        id on the print result) and show them the ``note`` as written.

        Args:
            window_id: The window to close (from ``consent_window_status``
                or the ``standing_window`` block on a print result).
            printer_name: Close every open window covering this printer.
            all_windows: Close every open window.
        
publish_modelA

Publish a 3D model to one or more marketplaces.

        Validates the model, optionally generates a print "birth
        certificate" from print history, and uploads to the specified
        marketplaces.

        Args:
            file_path: Path to the 3D model file (STL, 3MF, OBJ).
            title: Listing title for the model.
            description: Listing description (Markdown supported).
            tags: List of tags for discoverability.
            category: Model category (e.g. "tools", "art", "gadgets").
            license: License type — ``"cc-by"``, ``"cc-by-sa"``,
                ``"cc-by-nc"``, ``"gpl"``, or ``"public_domain"``.
            target_marketplaces: Marketplaces to publish to.
                Defaults to ``["thingiverse"]``.
            include_certificate: Attach print certificate if available.
            include_print_settings: Include recommended print settings.
        
generate_print_certificateA

Generate a print "birth certificate" for a 3D model.

        Queries print history for the file and builds a certificate
        containing tested printers, materials, success rate, and
        recommended settings.

        Args:
            file_path: Path to the 3D model file.
        
list_published_modelsC

List models that have been published to marketplaces.

        Args:
            marketplace: Filter by marketplace name (optional).
            limit: Maximum number of results (default 50).
        
record_revenueB

Record a revenue event (sale, royalty, tip, or refund).

        Args:
            model_id: File hash or listing ID of the model.
            marketplace: Marketplace name (e.g. ``"thingiverse"``).
            amount_usd: Amount in USD.
            transaction_type: Type — ``"sale"``, ``"royalty"``,
                ``"tip"``, or ``"refund"``.
            currency: Currency code (default ``"USD"``).
            description: Optional description of the transaction.
        
revenue_dashboardB

Get aggregate revenue analytics dashboard.

        Returns total revenue, sales count, top models, monthly
        trends, and marketplace breakdown.

        Args:
            days: Number of days to include (default 30).
        
model_revenueB

Get revenue summary for a specific model.

        Args:
            model_id: File hash or listing ID of the model.
        
create_print_service_orderA

Create a Print-as-a-Service order and get a quote.

        Provide ONE of ``model_path``, ``model_url``, or ``prompt``.
        Returns a quote with local and fulfillment options. Call
        ``print_service_quote`` with the order ID to confirm.

        Args:
            model_path: Local path to a 3D model file.
            model_url: URL to download a 3D model.
            prompt: Text prompt for AI model generation.
            material: Material type (default ``"pla"``).
            intent: Print intent — ``"strong"``, ``"pretty"``, or ``"cheap"``.
            quantity: Number of copies (default 1).
            color: Desired color (optional).
            prefer_local: Prefer local printing (default True).
            printer_name: Specific local printer name (optional).
            max_budget_usd: Maximum budget in USD (optional).
        
print_service_quoteB

Confirm a print service order and start processing.

        Args:
            order_id: The order ID from ``create_print_service_order``.
            option: ``"local"``, ``"fulfillment"``, or ``"recommended"``.
        
print_service_statusC

Check the status of a print service order.

        Args:
            order_id: The order ID to check.
        
cancel_print_service_orderB

Cancel a print service order.

        Only orders that have not started printing can be cancelled.

        Args:
            order_id: The order ID to cancel.
        
slice_modelA

Slice a 3D model (STL/3MF/STEP) to G-code using PrusaSlicer or OrcaSlicer.

        Args:
            input_path: Path to the input file (STL, 3MF, STEP, OBJ, AMF).
            output_dir: Directory for the output G-code.  Defaults to
                the system temp directory.
            profile: Path to a slicer profile/config file (.ini or .json).
            printer_id: Optional printer model ID for bundled profile
                auto-selection (e.g. ``"prusa_mini"``).
            slicer_path: Explicit path to the slicer binary.  Auto-detected
                if omitted.
            material: Filament material for this slice (``"PLA"``,
                ``"PETG"``, ``"TPU"``, …, or a product such as
                ``"bambu_tpu_95a"``).  It sets the slice's temperatures,
                melt rate and cooling -- Kiln's settings for it on this
                printer, see ``build_material_overrides`` -- and its
                density weighs the print.  Omitted, the spool the printer
                reports loaded answers, then PLA; the response's
                ``filament`` block says which, and ``filament.settings``
                what the slice was set to and why.
            auto_center: When True (default), off-bed STLs are translated
                to a bed-centered copy before slicing.  This prevents the
                class of crash where origin-centered meshes (common from
                compose_part_from_primitives / OpenSCAD output) produce
                sliced gcode with negative X/Y moves that drive the
                nozzle into the printer frame.  Set False only if you've
                verified the input is already correctly positioned.
                A part too big for the bed as modelled is also turned a
                quarter turn when that makes it fit — an STL directly,
                a STEP file as Kiln's mesh of it — and the response's
                ``bed_fit`` block says so.
            printer_name: Registered printer this slice is FOR.  Omit for
                the default printer.  Naming a second machine resolves
                its profile, its bed and its safety limits — without it,
                a multi-printer install slices everything for whichever
                printer is the default.
            placement: Where the part goes when the plate still holds the
                last print.  ``[x, y]`` in mm (where the part's footprint
                origin lands), a named region (``"front-left"``,
                ``"centre"``, ``"back-right"``, …), or ``"keep"`` to leave
                it where the file puts it.  Omitted, an occupied plate
                refuses and lists the spots that would work; a clear
                plate slices as before.  The response's ``placement``
                block is the clearance verdict, and the sliced file is
                checked against the plate once more before it is handed
                on.  The clearance verdict is free; placing and starting
                a second print on an occupied plate is a kiln-pro feature
                (https://kiln3d.com/pricing).

        A bundled profile is sliced for the nozzle fitted to the machine --
        the nozzle on record for it, else the printer's own setting --
        rather than the model's stock size.  The response's ``nozzle``
        block names the size, where it came from and what was changed to
        suit it; tell the user when it is not the stock size.

        Returns a JSON object with the output G-code path.  The output file
        can then be uploaded to a printer with ``upload_file`` and printed
        with ``start_print``.  A skirt that would print past the edge of
        the bed is dropped and the part sliced again (``bed_fit``'s
        ``skirt_dropped`` says so); a brim that would is refused
        (``BRIM_PAST_BED``) with the width that fits.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

reslice_with_overridesA

Reslice a 3D model with custom slicer parameter overrides.

        Accepts a base printer profile and a JSON dict of overrides to customize
        the slice. Common override keys (PrusaSlicer INI format):

          Adhesion: brim_width (mm), skirts (count), skirt_distance (mm)
          Temperature: temperature, first_layer_temperature, bed_temperature
          Speed: perimeter_speed, infill_speed, external_perimeter_speed, first_layer_speed, travel_speed (mm/s)
          Structure: fill_density (e.g. "25%"), fill_pattern (gyroid/grid/honeycomb), layer_height
          Support: support_material (0/1), support_material_buildplate_only (0/1)
          Retraction: retract_length, retract_speed

        Example overrides JSON: {"brim_width": "8", "perimeter_speed": "30", "fill_density": "25%"}

        Use this tool when a print failed due to adhesion, wobble, or quality issues
        and you need to reslice with adjusted settings. Pair with rotate_model to
        also change part orientation before reslicing.  A brim too wide for the
        room beside the part is refused (``BRIM_PAST_BED``) with the width that
        fits; a skirt past the edge of the bed is dropped and said in ``bed_fit``.

        Requires PrusaSlicer or OrcaSlicer installed locally.
        Use kiln find-slicer or the find_slicer MCP tool to verify.

        Args:
            input_path: Path to the input file (STL, 3MF, STEP, OBJ, AMF).
            printer_id: Printer model ID for bundled profile selection
                (e.g. ``"prusa_mini"``, ``"bambu_a1"``).
            overrides: Slicer keys to override, as a JSON object or its
                string form (e.g. ``{"brim_width": "8", "fill_density": "25%"}``).
            output_dir: Directory for the output G-code.  Defaults to the
                system temp directory.
            slicer_path: Explicit path to the slicer binary.  Auto-detected
                if omitted.
            printer_name: Registered printer this reslice is FOR.  Omit
                for the default printer.  Naming a second machine
                resolves its profile, its bed and its temperature
                ceilings instead of the default printer's.
            material: Filament material for this slice (``"PLA"``,
                ``"PETG"``, …).  It sets the temperatures, melt rate and
                cooling (``build_material_overrides`` shows them) and its
                density weighs the print; any of them you also pass in
                ``overrides`` stays yours.  Omitted, the loaded spool
                answers, then PLA — the response's ``filament`` block
                says which.
            placement: Where the part goes when the plate still holds the
                last print: ``[x, y]`` in mm (the part's footprint
                origin), a named region (``"front-left"``, ``"centre"``,
                ``"back-right"``, …), or ``"keep"``.  Omitted, an
                occupied plate refuses and lists the spots that would
                work; a clear plate reslices as before.  The response's
                ``placement`` block is the clearance verdict, checked
                again on the sliced file.  The clearance verdict is free;
                placing and starting a second print on an occupied plate
                is a kiln-pro feature (https://kiln3d.com/pricing).

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

find_slicerA

Check if a slicer (PrusaSlicer/OrcaSlicer) is available on the system.

Returns the slicer path, name, and version if found.

slice_and_printA

Slice a 3D model (STL/3MF) + upload + print in one step (basic pipeline).

        Colour is a promise kept here.  A part made in a colour (the
        ``color`` the make was asked for, or the one its source named)
        prints from a loaded spool of that colour: on a printer with an
        AMS the slot is chosen and named in the result; with none of that
        colour loaded the print is HELD (``code: "COLOR_NOT_LOADED"``),
        naming the nearest loaded spool, so the person decides before
        anything prints -- call again with ``color="<that colour>"`` to
        print in it, or load the asked colour and call again; on a
        printer with no unit Kiln can read it prints in whatever is
        loaded and the result says so.  ``color`` here overrides the
        make's: a colour word or hex to print in instead, or ``"any"``
        to print in whatever is loaded.

        For a more comprehensive pipeline with validation and profile auto-detection,
        use ``run_quick_print``. For custom slicer overrides, use ``run_reslice_and_print``.
        Automatically analyzes bed adhesion and adds brim/raft when needed
        based on model geometry, material warp tendency, and printer type.
        This adhesion intelligence only activates when no custom profile is
        supplied; when it could not read the model, ``printability_note``
        says why.  A skirt that would print past the edge of the bed is
        dropped and the part sliced again; a brim that would is refused
        with the width that fits.

        Pre-print validation gate: mesh inputs (.stl/.obj/.3mf/.step/.glb)
        run through Kiln's full validation pipeline before slicing —
        format check, watertight check, auto-repair, printability scoring
        (0-100), bed-fit, and material checks.  Designs that fail the gate
        are blocked before reaching the printer; auto-repaired meshes are
        sliced from the repaired path.  Pass ``skip_validation=True`` to
        bypass (e.g. for already-validated meshes or pre-sliced 3MFs).

        Args:
            input_path: Path to the 3D model file (STL, 3MF, STEP, etc.).
            printer_name: Target printer name.  Omit for the default printer.
            profile: Path to a slicer profile/config file.
            printer_id: Optional printer model ID for bundled profile
                auto-selection (e.g. ``"prusa_mini"``).
            material: Filament material (e.g. ``"PLA"``, ``"ABS"``).  It
                sets the slice's temperatures, melt rate and cooling
                (``build_material_overrides`` shows them), its density
                weighs the print, and it steers the automatic brim/raft
                decision.  Omitted, the spool the printer reports loaded
                answers, then PLA — the response's ``slice.filament``
                says which.
            metadata: Optional dict of pass-through fields.  When
                kiln-pro (https://kiln3d.com) is installed it
                consumes keys here to generate a printable
                assembly manual alongside the print, surfacing it
                under ``response["assembly_manual"]``.  Without
                kiln-pro the metadata is silently ignored.
                Recognised keys (all optional):
                ``assembly_json``, ``manual_output_dir``,
                ``manual_design_name``, ``manual_branding``,
                ``manual_co_brand_name``, ``manual_languages``,
                ``manual_cover_language``.  Multi-language and
                co-brand are kiln-pro Business+ features
                (https://kiln3d.com/pricing).
            skip_validation: Bypass the pre-print validation gate.
                Defaults to False — designs are pre-tested for
                printability before they reach the printer.  Set to
                True only when the caller has already validated the
                mesh (e.g. ``validate_and_prepare`` was just called)
                or when the input is a pre-sliced 3MF the validator
                can't introspect.
            placement: Where the part goes when the plate still holds the
                last print: ``[x, y]`` in mm (the part's footprint
                origin), a named region (``"front-left"``, ``"centre"``,
                ``"back-right"``, …), or ``"keep"``.  Omitted, an
                occupied plate refuses before anything is sliced and
                lists the spots that would work; a clear plate prints as
                before.  The response's ``placement`` block is the
                clearance verdict, checked again on the sliced file
                before upload.  The clearance verdict is free; placing
                and starting a second print on an occupied plate is a
                kiln-pro feature (https://kiln3d.com/pricing).
            hardware: Bought parts that go into the part while it
                prints, as short phrases such as ``["4x 6x3 magnet",
                "2x M3 nut"]``.  The file that prints carries the pause
                Kiln's servers wrote into it, and the response's
                ``hardware`` block says what goes in and when; a part
                that needs a pause that cannot be written is refused
                before anything is sent to the printer.  Left out, a
                part with a pocket that would be sealed inside the
                print is refused with ``HARDWARE_UNNAMED`` and the
                planner's question for each pocket ("this hex pocket
                takes an M3 nut -- right?"): ask the person, then call
                again with what they said, or ``["none"]`` to print
                every pocket empty on their word.  ``["none"]`` with a
                pause already in the sliced file over a sealed pocket
                is refused as a contradiction (``HARDWARE_NONE_BUT_PAUSED``).
                Writing the pause is a kiln-pro feature
                (https://kiln3d.com/pricing).

        Combines ``slice_model``, ``upload_file``, and ``start_print`` into
        a single action.

        Branch on ``print_start`` — one field, three values, and the
        nested ``print`` block carries the identical pair so the two
        halves cannot disagree:

        - ``"started"``: the printer, asked after the command, is printing.
        - ``"accepted"``: the command was sent and not refused, and the
          machine has not confirmed it is running.  Normal during the
          start-up transient (homing, AMS load, calibration).  Call
          ``printer_status()`` to watch it start.
        - ``"failed"``: the printer, asked after the command, is idle or
          errored — it did not take the job.

        ``success`` is ``False`` only for ``"failed"``.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

list_slicer_profilesA

List all bundled slicer profiles for supported printers.

        Returns profile IDs, display names, recommended slicer, and the
        minimum license tier required for each.  Free-tier profiles can be
        used by everyone; PRO profiles require a Kiln Pro license.

        Use with ``get_slicer_profile`` to see full settings, or
        ``slice_model`` with printer_id for auto-profile selection.
        
get_slicer_profileA

Get the full tuned slicer profile for a printer model.

        Returns all INI settings (layer height, speeds, temps, retraction, etc.)
        and the recommended slicer.  A catalogued printer's profile is
        served one printer per call and kept on this computer; a printer
        whose record this install does not hold answers with the generic
        ``default`` profile (``profile.id == "default"``).  Free-tier
        profiles (default, ender3, prusa_mk3s, klipper_generic) are
        available to all users.  Premium profiles require a Kiln Pro license.

        Args:
            printer_id: Printer model identifier (e.g. ``"ender3"``,
                ``"bambu_x1c"``, ``"creality_k1_max"``).
        
retry_print_with_fixA

Diagnose the last print failure and re-slice + print with fixes.

        When a print fails, call this tool instead of manually chaining
        ``diagnose_print_failure_live`` → ``slice_and_print``.  It:

        1. Reads live printer state and analyses the model geometry to
           diagnose the failure (unless ``skip_diagnosis`` is True).
        2. Auto-detects the loaded material from the AMS when
           ``material`` is omitted and the printer supports it.
        3. Merges diagnosis-recommended slicer overrides with any
           ``custom_overrides`` you supply (your overrides win on
           conflict).
        4. Re-validates the mesh's printability before re-slicing.  A
           retry path that re-sends a broken mesh is the highest-
           value place to validate — the previous attempt already
           failed, and slicer overrides can't fix mesh-level issues.
           Bypass with ``skip_validation=True`` if the caller already
           validated.
        5. Re-slices the (possibly auto-repaired) mesh with the merged
           overrides, uploads the result, and starts the print.

        Args:
            model_path: Path to the model that failed (STL, OBJ, 3MF,
                STEP, ...).  One the diagnosis cannot read is said in
                ``printability_note``.
            printer_name: Target printer name.  Omit for the default
                printer.
            material: Filament material (e.g. ``"PLA"``, ``"ABS"``); the
                reslice is set for it (temperatures, melt rate,
                cooling).  Auto-detected from AMS when omitted.
            printer_id: Printer model ID for intelligence lookup
                (e.g. ``"bambu_a1"``).
            custom_overrides: JSON object of additional slicer overrides
                to merge on top of the diagnosis recommendations
                (e.g. ``'{"brim_width": "8"}'``).  Your values win on
                conflict.
            skip_diagnosis: If True, skip the failure diagnosis step and
                re-slice using only ``custom_overrides``.
            skip_validation: If True, bypass the pre-print mesh
                validation gate.  Defaults to False — designs are
                pre-tested for printability before the retry reaches
                the printer.
            placement: Where the part goes when the plate still holds
                the last print: ``[x, y]`` in mm, a named region
                (``"front-left"``, ``"centre"``, …), or ``"keep"``.
                Omitted, an occupied plate refuses before slicing and
                lists the spots that would work.  The clearance verdict
                is free; placing and starting a second print on an
                occupied plate is a kiln-pro feature
                (https://kiln3d.com/pricing).
        
kiln_spend_caps_showA

Show your current Kiln spend caps and whether chat may change them.

        Returns the per-order and monthly caps, the defaults, and
        ``agent_flow_enabled``.  When that is off the answer carries a
        ``next_step`` with the web page where the account owner turns it
        on; give the person that link as written, because turning it on
        cannot be done from chat.

        Needs a signed-in session: call ``kiln_signin`` first.
        
kiln_spend_caps_request_changeA

Ask to raise the per-order and/or monthly spend cap (step 1 of 2).

        The servers hold the requested change for a few minutes and
        return a ``challenge_id``.  Show the person ``current_caps`` and
        ``requested_caps`` so they can review the change, then ask them
        for the six-digit code from their authenticator app and pass it
        to ``kiln_spend_caps_confirm_change``.

        Args:
            per_order_dollars: New per-order cap; leave unset to keep it.
            monthly_dollars: New monthly cap; leave unset to keep it.
            reason: Optional note kept with the change.

        A refusal says which case it is (chat changes turned off, with
        ``enable_url``; too many attempts, with ``retry_after_seconds``;
        a cap below the minimum).  Relay it as written.
        
kiln_spend_caps_confirm_changeA

Confirm a cap change with the person's six-digit code (step 2 of 2).

        Args:
            challenge_id: From ``kiln_spend_caps_request_change``.
            totp_code: The six-digit code the PERSON reads from their own
                authenticator app.  Never produce or guess it.

        Returns the new caps on success.  A refusal names its case: a
        wrong code (they may try again within the daily limit), a
        challenge that expired or was already used (ask again from step
        1), no authenticator set up on the account, or too many attempts.
        
kiln_spend_caps_request_order_approvalA

Ask to approve ONE order over the cap (step 1 of 2).

        For an order Kiln refused as over the person's spend cap, when
        they want this order to go ahead without raising the cap for
        good.  Returns a ``challenge_id``; step 2 is
        ``kiln_spend_caps_confirm_order_approval`` with their code.

        Args:
            order_id: The order Kiln refused.
            max_dollars: The order total being approved, in dollars.
        
kiln_spend_caps_confirm_order_approvalA

Confirm a one-order approval with the person's code (step 2 of 2).

        On success returns an ``approval_token``: pass it to the order
        tool when placing that order again.  It works once, for that
        order and amount, and expires within minutes.

        Args:
            challenge_id: From ``kiln_spend_caps_request_order_approval``.
            totp_code: The six-digit code the PERSON reads from their own
                authenticator app.  Never produce or guess it.
        
import_step_fileA

Import a STEP (.step/.stp) CAD file and convert it for Kiln's mesh pipeline.

        Converts STEP files using whichever backend is available (the
        OCCT kernel that ``kiln install-step-backend`` sets up, or an
        existing FreeCAD / Gmsh / CadQuery install).

        **The output format follows what the file carries.**  A plain
        single-solid STEP becomes an STL.  A STEP with part colours or
        multiple bodies becomes ONE 3MF that keeps each part's colour,
        name, and position — so a coloured CAD assembly arrives ready
        for a multi-material print instead of flattened grey.  Pass
        ``output_format="stl"`` or ``"3mf"`` to force either.

        Use ``check_step_support`` first to verify that a conversion
        backend is installed.  After conversion, use ``diagnose_mesh``
        or ``analyze_mesh_geometry`` to validate the output.

        If this returns ``code="NO_BACKEND"``, read the ``remedy`` field
        rather than guessing: when ``remedy.actionable_by_caller`` is
        True, tell the user to run ``remedy.command`` (``kiln
        install-step-backend``) — one command and it works.  When it is
        False the caller is on a hosted server and has nothing to
        install; say so plainly and suggest ``report_issue``.  Never
        hand a hosted user an install instruction.

        Args:
            brief_id: The saved goal's id from ``design_session``; pass it so
                this make joins the goal (recorded against it; Kiln Pro checks the
                result against it). Empty when there is no goal.
            file_path: Path to the STEP/STP file.
            output_format: ``"auto"`` (default — 3MF when colour or
                multiple bodies are present, else STL), ``"stl"``, or
                ``"3mf"``.
            merge_bodies: STL output only: if True, merge all bodies
                into one STL; if False, export each body separately.
                (3MF keeps bodies as separate named objects either way.)
            output_dir: Directory for output files.  Defaults to
                the STEP file's parent directory.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

MAKE DOORS: design_session, Kiln's front door for making an object, is not installed here (signed in to Kiln it runs on Kiln's servers). On this install compile_scad IS the make → preview → iterate loop: make it, show the preview, iterate.

check_step_supportA

Check which STEP import backends are available on this system.

        Returns a dict listing each backend (FreeCAD, Gmsh, the OCCT
        kernel, CadQuery) with its availability status and priority.
        If none is found,
        includes ``install_help`` (prose) and ``remedy`` (structured) —
        prefer ``remedy``: its ``actionable_by_caller`` flag tells you
        whether the user can fix this (``kiln install-step-backend``) or
        whether they're on a hosted server where they cannot.

        Call this before ``import_step_file`` to verify the system is
        ready for STEP conversion.
        
step_file_infoA

Extract metadata from a STEP file without converting it.

        Parses the STEP ASCII header to extract product names, estimated
        body count, file schema, and other metadata.  This is fast and
        requires no external backend.

        Use this to inspect a STEP file before deciding whether to
        import it.

        Args:
            file_path: Path to the STEP/STP file.
        
check_my_tierA

Check the user's current Kiln subscription tier (Free / Pro / Business / Enterprise) and explain WHY they're on it.

        Use this whenever the user asks any tier / plan / subscription /
        paywall / access question — for example: "what tier am I on",
        "why does it say I need Pro", "do I have to pay for this",
        "what's my plan", "why isn't this Pro feature working", "did
        my subscription not activate", "what's the difference between
        Free and Pro", "I just paid but I'm still seeing free tier",
        "can I use the texture engine", "do I have access to fleet
        management", "what unlocks at Business", "how do I upgrade".

        Walks the live tier-resolution chain on the user's machine
        (KILN_LICENSE_KEY env var → ~/.kiln/license file → OAuth
        session at ~/.kiln/auth_tokens.json → cached entitlement →
        free-tier fallback) and reports:

          - effective_tier: one of 'free', 'pro', 'business', 'enterprise'
          - resolution_chain: list of every step with which matched
          - matched_source: which step actually determined the tier
          - agent_summary: a plain-English one-liner you can show
            the user verbatim
          - pricing_url: link to send the user if they want to upgrade

        No arguments.  Free-tier safe — does NOT require a license
        to call.  Available to every user.

        JUST PAIRED, AND THE TIER LOOKS STALE?  Try this order, and do
        it yourself rather than handing the user a checklist:

          1. Call ``restart_server``.  This server caches what it
             resolved at startup, so a pairing that happened after it
             launched may simply not be visible to it yet.  A restart
             re-execs in place and is invisible to the user.
          2. Call this tool again.
          3. Only if the tier is STILL stale, ask the user to fully
             quit and reopen their AI app.  That is the one step they
             have to do by hand, so it is the last resort, not the
             first suggestion — and MCP clients differ (some reconnect
             to a restarted server on their own, some do not).

        Report the tier plainly whatever it turns out to be, Free
        included: pairing is not a purchase, and a free account that
        paired successfully must not be told it failed.

        Common interpretation:
          - effective_tier="free", matched_source="kiln_pro_install":
            kiln-pro not installed on this machine.  User can still
            use Pro features via api.kiln3d.com if signed in.
          - effective_tier="free", matched_source="default":
            kiln-pro installed but no auth — needs `kiln signin` or
            KILN_LICENSE_KEY.
          - effective_tier="pro" (or higher) with matched_source=
            "license_manager_resolve" and "oauth_session" matched=True
            in the chain: user is signed in via OAuth and the
            entitlement on file gives them this tier.

        Returns:
            dict with success/effective_tier/resolution_chain/
            matched_source/agent_summary/tier_rank/pricing_url.
        
get_session_logA

Return the full audit log for an agent session.

        Every tool call made by an agent is recorded with a session ID — a UUID
        generated when the MCP server starts.  Use this tool to replay exactly
        what an agent issued during a session: every command, every safety check
        that fired, every blocked attempt.

        Args:
            session_id: Session UUID to query.  Omit to use the current session.
            limit: Maximum records to return (default 100, max 500).
        
upgrade_kilnA

Update the Kiln package to the latest version — for the user.

        The Apple-grade upgrade path. When a newer Kiln is available (or a
        hosted call returns an upgrade-required signal), OFFER to handle it:
        ask "want me to update Kiln for you now?" and call this with
        confirm=True once they agree. Don't make the user run a pip command.

        AGENT CONTRACT (important):
          * NEVER call this while a print is active — wait until it finishes.
            Swapping Kiln mid-print is unsafe.
          * Confirm with the user first; this changes their installed
            software. Pass confirm=True only after they say yes.
          * On success the new version is on disk but the running Kiln still
            has the old code loaded — relay the restart instruction from the
            result so the user applies it at a safe moment (not mid-print).

        Args:
            confirm: Set True to actually perform the update. Called without
                it, this returns the offer to show the user and changes
                nothing.
            force: Override the mid-print safety defer — only when the user
                explicitly insists.
        
trim_serve_processesA

Close leftover Kiln servers left behind by closed sessions.

        Every agent session spawns its own background Kiln server;
        client apps don't reliably close them when a session ends, so
        they accumulate and quietly hold memory. This is the cleanup
        the pile-up warning (health_check / kiln_health / get_started)
        offers.

        WHY THIS IS SAFE: closing a server never stops a physical
        print — the printer keeps going regardless. What a close can
        end is MONITORING (a running watch loop). So this refuses to
        act while any printer has a job in flight, and otherwise the
        worst case is that a still-open session reconnects. This
        session's own server is never closed.

        AGENT CONTRACT (important):
          * ASK THE USER how many agent sessions they actually have
            open right now and pass it as open_sessions — they are
            the one source of truth for that, and it beats guessing
            from process age. Never ask them for a PID.
          * Confirm before acting. Called without confirm, this
            returns the plan (how many would close, how many stay)
            to show the user; pass confirm=True once they agree.
          * If it comes back blocked because something is printing,
            tell the user what's printing and leave it alone — offer
            to clean up after the print finishes rather than
            reaching for force.

        Args:
            confirm: Set True to actually close the leftovers.
            open_sessions: The user's own count of agent sessions
                currently open. Keeps that many most-recently-started
                servers and proposes the rest.
            force: Proceed even though a printer has a job in flight.
                Only when the user explicitly insists, knowing that
                monitoring for that job may stop.
        
health_checkA

Return system health information for monitoring.

        No authentication required.  Useful for container healthchecks,
        dashboards, and verifying the server is responsive.

        **See also:** ``kiln_health`` for version info, module
        availability, scheduler status, and webhook configuration.
        
kiln_healthA

Get a health check for the Kiln system.

Returns versions, uptime, module availability, scheduler status, webhook status, and overall system health. Use this to verify the system is running correctly.

get_startedA

Quick-start guide for AI agents using Kiln.

        Returns an onboarding summary: what Kiln is, how to discover
        its tools, core workflows, and the most useful tools to call
        first.  Call this at the start of a session if you're
        unfamiliar with the available capabilities.

        Args:
            chat_app: The chat app the person is writing to you from,
                when there is one (``telegram``, ``discord``,
                ``whatsapp``, ``imessage``, ``signal``, ``slack``,
                ``wechat``, etc.).  Say it once per session; leave it
                out when they are typing in this app itself.  Kiln
                uses it to lead with the way of approving a print
                that suits someone on a phone.
        
get_skill_manifestA

Get the Kiln skill manifest for agent self-discovery.

Returns a machine-readable description of Kiln's capabilities, configuration requirements, available interfaces, and setup instructions. Use this when first connecting to understand what Kiln can do and what configuration is needed.

verify_audit_integrityA

Verify HMAC signatures on all safety audit log entries.

Checks each audit log row against its stored HMAC signature to detect tampering. Returns counts of valid, invalid, and total entries along with an overall integrity status.

backup_databaseA

Back up the Kiln database with optional credential redaction.

        Creates a copy of the SQLite database.  By default, sensitive fields
        (API keys, access codes, payment refs) are replaced with "REDACTED"
        in the backup.

        Args:
            output_path: Destination file path.  Defaults to
                ``~/.kiln/backups/kiln-YYYYMMDD-HHMMSS.db``.
            redact: If ``True`` (default), redact credentials in the backup.
        
plugin_infoC

Get detailed information about a specific plugin.

        Args:
            name: Plugin name.
        
validate_and_prepareA

Comprehensive validation pipeline for any 3D model before printing.

        Runs format check, mesh analysis, watertight check, auto-repair,
        printability analysis, structural assessment, bed-fit check, and
        (optionally) material-specific checks.
        Returns a detailed pass/fail report with actionable recommendations
        plus a numeric printability score (0-100).

        Works with any model — AI-generated, downloaded from marketplaces,
        or created in CAD.  Every model passes Kiln's engineering review
        before it touches your printer.

        Each step is resilient — if a step's underlying module is unavailable
        the step is skipped and the pipeline continues.

        :param input_path: Path to a 3D model file (.stl, .3mf, .obj, .step, .glb).
        :param printer_id: Optional printer model ID (e.g. "bambu_a1") for
            bed-fit checking.  If empty, bed-fit check is skipped.
        :param material: Optional material name (e.g. "pla", "petg", "abs",
            "asa", "tpu").  When provided, adds a material-specific check
            for known print-quality risks.  If empty, material check is skipped.
        :returns: Dict with pass/fail status, per-check details, recommendations,
            ``printability_score`` and ``printability_grade``
            (analyze_printability's, for ``material`` and ``printer_id``;
            ``None`` when the analysis could not run), and
            ``readiness_score`` (0-100, the tally of the checks) with its
            ``score_breakdown``.
        
prepare_ai_model_for_printA

Prepare any AI-generated model for printing — fixes the unit mix-up.

        AI model generators (Meshy, Tripo, Stability, Gemini) routinely
        export models in meters instead of millimeters, so a 60mm figurine
        reads as 0.06mm.  This tool corrects that by the real unit
        conversion when exactly one explains the size — never by scaling
        to an invented "reasonable" target — then runs the full validation
        pipeline and provides smart recommendations for simplification
        and hollowing.

        Pipeline:
            1. Run validate_and_prepare for baseline analysis
            2. Size — scale to target_height_mm when given; otherwise
               apply a unit correction only when exactly one real
               conversion (meters, centimeters, inches, microns) lands
               the model at a printable size.  A size several units
               could explain, or none can, is reported, never guessed at.
            3. Mesh simplification recommendation (if > 100K triangles)
            4. Smart hollow recommendation (only when appropriate)
            5. Re-validate the scaled model
            6. Return combined before/after comparison

        Works with STL, OBJ, and 3MF files.

        :param input_path: Path to the AI-generated model file.
        :param target_height_mm: Desired height in mm — an instruction,
            honored at any starting size.  If 0, only a unit mistake is
            ever fixed; the model's designed size is otherwise kept.
        :param printer_id: Optional printer model ID for bed-fit checking.
        :param material: Material name (default "PLA") for material checks.
        :returns: Dict with original/prepared comparison, actions taken,
            recommendations, and next_action for slicing.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

save_design_versionA

Save a new version of a parametric design.

        Automatically computes a unified diff from the previous version,
        increments the version number, and persists a versioned recipe
        sidecar (``~/.kiln/designs/<design_id>/.kiln_recipe.vN.json``).

        **Upgrade to Kiln Pro** for automatic mesh fingerprinting,
        regression detection (warns when features are lost between
        versions), and ``.kiln.json`` sidecar provenance files that
        travel with your STLs.

        Args:
            design_id: Identifier grouping versions of the same design.
            scad_source: Full OpenSCAD source code for this version.
            prompt: The natural-language prompt that produced this version.
            parameters: Parametric values used for generation.
            notes: Free-text notes for this version.
            provenance: Context on how this version was created.
                Recommended keys: ``tools_used``, ``change_summary``,
                ``source_files``.  (Pro: auto-enriched with mesh
                fingerprinting and regression detection.)
            stl_path: Path to the output STL file.  (Pro: auto-computes
                a geometric fingerprint and warns if features were
                lost from the parent version.)
            parent_version_id: Unused in this implementation; kept for
                backward compatibility.  The parent is always the most
                recent existing version.
            brief_id: Optional saved-goal id from ``design_session``.
                When supplied, the new version's recipe records the
                link so the audit's "matches what you asked for" gate,
                the brief failure_history wiring, and the
                ``compare_design_versions`` intent diff all join back
                to the goal.  When omitted, an earlier version's
                ``brief_id`` (read from the parent recipe) is
                inherited automatically.
            intent_hash: Optional content hash of the brief's derived
                intent payload, paired with ``brief_id``.  Same
                inheritance fall-back as ``brief_id``.

        Returns:
            The saved version record including version number, diff, and
            parent information.  Pro users also get provenance,
            mesh_fingerprint, and mesh_diff with regression warnings.
        
list_design_versionsA

List version history for a design, newest first.

        Args:
            design_id: The design whose versions to list.
            limit: Maximum number of versions to return (default 20).

        Returns:
            A list of version records ordered by version number
            descending, plus a ``scope`` block saying which store
            was read and whether the user's cloud-side versions are
            included.  Read ``scope`` before treating ``count`` as
            the design's whole history.
        
diff_design_versionsA

Compute a unified diff between two design versions.

        Version IDs are interpreted as ``<design_id>:<version_number>``
        (e.g. ``my-coaster:2``).  If no colon is present the string is
        treated as a plain version number and the tool will attempt to
        locate a design that contains that version.

        Args:
            version_id_a: The "from" version in ``design_id:N`` format.
            version_id_b: The "to" version in ``design_id:N`` format.

        Returns:
            A unified diff string showing changes from version A to B.
        
rollback_design_versionA

Rollback a design to a previous version.

        Creates a *new* version whose source matches the target version,
        preserving full history.  The new version's notes record the
        rollback origin.

        Args:
            design_id: The design to rollback.
            to_version_id: The version number (integer) or
                ``design_id:N`` ref to restore.

        Returns:
            The newly created rollback version record.

INLINE 3D STAGE: on success this tool opens Kiln's interactive 3D stage — an inline viewer panel the user can orbit, zoom, and turn over — in hosts that render MCP Apps panels (Kiln's hosted connection attaches a browser stage link for hosts that don't). Oversized meshes are decimated automatically for the stage; the PNG preview is the floor, not the whole experience.

get_design_versionA

Retrieve a single design version by its ID.

        Use this to inspect the full source code, parameters, and notes
        for a specific version when you already know the version reference.

        Args:
            version_id: ``design_id:N`` reference (e.g. ``my-coaster:3``)
                or a plain integer version number if the design_id is
                unambiguous.

        Returns:
            The version record including source_scad, prompt,
            parameters, notes, and parent_version.
            Returns an error if the version does not exist.
        
search_design_versionsA

Search design versions by prompt, notes, or design name.

        Scans all design directories under ``~/.kiln/designs/`` for
        versioned recipe files whose prompt, notes, or name fields
        contain the query string (case-insensitive).

        Args:
            query: The search term (literal substring, not regex).
            limit: Maximum number of results to return (default 10).

        Returns:
            A list of matching version records, newest first, plus a
            ``scope`` block saying which store was searched and
            whether the user's cloud-side versions were included.  A
            miss here is only a miss in the stores ``scope`` names.
        
lock_designA

Keep a design on this computer only: never saved to the person's Kiln account.

        A locked design is never saved to the Kiln account, by any door:
        a cloud push, an automatic save after each version, a push of one
        of its signed releases, or a pull request.  Each is refused and
        says the design is locked.  Branching, merging and the history
        views keep working; when Kiln's servers run one of those, the
        design passes through them for that call only and is not kept
        there.  Locking removes nothing already in the account.  Free on
        every plan.

        Args:
            design_id: The design to lock or unlock.
            locked: ``True`` (the default) to lock it, ``False`` to unlock it.

        Returns:
            ``locked`` (the state it is now in) and ``said``: a sentence
            to show the person, saying what the lock does and does not do.
        
auto_generate_manual_for_printC

Fire the automatic manual trigger for a multi-part print (Business+).

Business adds team review, approval gates, and 3 printers (grow to 50). Requires Kiln Business. Upgrade: https://kiln3d.com/pricing?src=agent&tool=auto_generate_manual_for_print

derive_assembly_planC

Derive an assembly plan from part GEOMETRY — no hand declaration needed.

Business adds team review, approval gates, and 3 printers (grow to 50). Requires Kiln Business. Upgrade: https://kiln3d.com/pricing?src=agent&tool=derive_assembly_plan

diff_assembly_manualsC

Compute a "what changed" PDF between two manual revisions (Business+).

Business adds team review, approval gates, and 3 printers (grow to 50). Requires Kiln Business. Upgrade: https://kiln3d.com/pricing?src=agent&tool=diff_assembly_manuals

embed_manual_in_3mfC

Augment a 3MF with the assembly manual + signed manifest (Business+).

Business adds team review, approval gates, and 3 printers (grow to 50). Requires Kiln Business. Upgrade: https://kiln3d.com/pricing?src=agent&tool=embed_manual_in_3mf

find_manual_siblingsC

List sibling revisions of a parametric design (Business+).

Business adds team review, approval gates, and 3 printers (grow to 50). Requires Kiln Business. Upgrade: https://kiln3d.com/pricing?src=agent&tool=find_manual_siblings

generate_assembly_manualC

Generate a flat-pack-style assembly manual for a multi-part print (Business+).

Business adds team review, approval gates, and 3 printers (grow to 50). Requires Kiln Business. Upgrade: https://kiln3d.com/pricing?src=agent&tool=generate_assembly_manual

get_manual_revisionC

Fetch a single manual revision by id.

list_manual_historyC

List the chronological revision history of a design's manuals.

retire_manual_revisionC

Soft-delete a manual revision (Business+, owner-only).

Business adds team review, approval gates, and 3 printers (grow to 50). Requires Kiln Business. Upgrade: https://kiln3d.com/pricing?src=agent&tool=retire_manual_revision

license_status_liveB

Return live tier / status / expiry for the current Kiln caller by hitting the server (revocation-aware).

open_billing_portalA

Get a Stripe Billing Portal URL so a paying customer can update their card, see invoices, or cancel. Plan switches are not in the portal and never made by an agent: explain the plans, then send the person to Billing in the Kiln web app (https://app.kiln3d.com/settings/billing) to choose and confirm.

preview_overage_chargeB

What a number of printers would cost in extra-printer charges on your plan. Free on every plan.

start_subscription_checkoutC

Get a URL the user can visit to subscribe to a Kiln paid tier.

usage_summaryB

Return the current billing cycle's usage snapshot.

export_stepC

Export a design as a STEP file — real analytic B-rep, always.

cloud_backup_configureC

Turn automatic cloud backup of your designs on or off.

Kiln Pro would push your design branches to a cloud remote and pull them back on any signed-in machine, with automatic backup available. Requires Kiln Pro. Upgrade: https://kiln3d.com/pricing?src=agent&tool=cloud_backup_configure

cloud_clone_designC

Bootstrap local storage for a remote-only design.

Kiln Pro would push your design branches to a cloud remote and pull them back on any signed-in machine, with automatic backup available. Requires Kiln Pro. Upgrade: https://kiln3d.com/pricing?src=agent&tool=cloud_clone_design

Prompts

Interactive templates invoked by user choice

NameDescription
print_workflowStep-by-step guide for printing a file on a 3D printer.
fleet_workflowGuide for managing multiple printers in a fleet.
troubleshootingCommon troubleshooting steps for 3D printing issues.

Resources

Contextual data attached and managed by the client

NameDescription
resource_statusLive snapshot of the entire Kiln system: printers, queue, and recent events.
resource_printersFleet status for all registered printers.
resource_queueCurrent job queue summary and recent jobs.
resource_eventsRecent events from the Kiln event bus (last 50).
kiln_mesh_viewerInteractive inline 3D stage for Kiln mesh results — orbit, zoom, and turntable on Kiln's dark stage.
kiln_print_monitorLive inline monitor for a running print — camera, progress, temperatures, and connection state on Kiln's dark surface.

TDQS

C2.6/5.0

Scored across 851 tools

Disambiguation1/5

Dozens of tools have near-identical purposes: slice_and_estimate, estimate_print_time, estimate_material_cost, estimate_print_cost_from_mesh, estimate_cost, estimate_mesh_weight and estimate_mesh_print_time all answer 'time/filament/cost'; validate_and_prepare, validate_and_prepare_mesh, validate_generated_mesh, check_print_readiness and audit_original_design all gate the same mesh; merge_stl, merge_mesh_files and compose_models concatenate meshes; visualize_model, render_model_preview, preview_generated_model, inspect_mesh_view and show_on_stage all render images. Several deprecated aliases (print_status_lite, repair_mesh_advanced, render_model_preview, recover_texture_detail) sit beside their replacements with no removal. An agent cannot reliably pick among these without reading long prose.

Naming Consistency3/5

The dominant pattern is snake_case verb_noun (list_designs, create_design_branch, retire_feature_release), which is readable and mostly predictable. But conventions are mixed: namespace prefixes that invert the order (fleet_status, cloud_remote_list, kiln_health), noun-first names (may_i_print, axis_report style), and product generators all named generate_<object> alongside generate_model, generate_from_template, generate_model_with_provider, generate_and_print. Deprecated duplicates with no naming distinction compound the inconsistency.

Tool Count1/5

851 tools is an extreme mismatch for any single MCP surface; the descriptions alone exceed a context window, so an agent cannot survey the set before choosing. Large blocks are tier-gated stubs (Business/Enterprise) that cannot even run on the installing tier, and many are verbatim duplicates or deprecated aliases rather than earned capabilities.

Completeness4/5

The domain — an end-to-end 3D printing workspace (design, version, cloud sync, slice, print, monitor, repair, marketplace, fulfillment, fleet, org/teams) — is covered to an unusual depth, with CRUD, lifecycle, branching, releases and audit all present. Gaps are minor and mostly integration-specific (e.g. Klipper power-loss recovery noted as unsupported), not surface-level.

Maintenance

ActivityActive
ResponsivenessSlow