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
}
experimental
{}

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``.

: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.
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: Slot mapping per extruder (Bambu only).  Defaults to
        ``[0]`` when AMS feeding is on and ``[]`` (external spool) when
        it is off.  Use ``-1`` for unused positions.  Check
        ``ams_status()`` to see which slots have filament.
    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).
    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 M112 (emergency stop), turns off heaters, and disables steppers.
Unlike ``cancel_print``, this does **not** allow a graceful cooldown —
all motion ceases instantly.

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.

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.

Pausing lifts the nozzle and parks the head.

Heater behaviour during pause varies by firmware:

  - 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.
  - Bambu X1/P1 series: typically holds both targets, but a long
    idle can still trigger cooldown.
  - OctoPrint / Moonraker / Klipper: depends on firmware config;
    most hold targets across pause.

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.

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.

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."

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.
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 unknown-printer limit rather than
        to the default printer's, which may be the more permissive of
        the two.

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.
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.

The ``tray_now`` field usually shows which tray is currently active
(``"255"`` means none / external spool on X1/P1-style reports).  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()``.
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 printer speed profile (Bambu Lab printers only).

Args:
    profile: Speed profile name — one of ``"silent"`` (50% speed,
        quiet), ``"standard"`` (100%, default), ``"sport"`` (124%,
        faster), or ``"ludicrous"`` (166%, maximum speed).

Sport and Ludicrous modes automatically increase nozzle temperature
to prevent under-extrusion at higher flow rates.

Use ``printer_status()`` to see the current speed profile in the
response's ``printer.speed_profile`` field.
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"``.
        Defaults to ``"on"``.

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

Set the speed of a printer fan.

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
(https://github.com/prusa3d/Prusa-Link/issues/832). Elegoo's resin/MSLA
printers (Saturn, Mars) have no part-cooling fan and are 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. Defaults to ``100``.

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.
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 (default 220 for PLA).
    bed_temp: Bed temperature in °C (default 65 for PLA).
    filament_type: Filament type string — ``"PLA"``, ``"PETG"``,
        ``"ABS"``, etc.
    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).

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.
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

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.
issue_preview_tokenA

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

Call this AFTER rendering a preview (``visualize_model`` /
``preview_generated_model``) and showing it to the user.  The user
approves → you call this tool → you pass the returned token as
``preview_token`` to ``start_print`` or ``fulfillment_order``.

Without a valid token, ``start_print`` refuses to execute (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.
    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`` and ``expires_at`` (unix timestamp).
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: API key (required for OctoPrint and Bambu, optional for
        Moonraker/Creality, unused for USB).  For Bambu printers
        this is the LAN Access Code.
    serial: Printer serial number (required for Bambu printers).
    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.

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.
create_projectA

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 MCP client (Claude Code, etc.) should detect
the connection drop and automatically reconnect.

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 connection will drop within ~0.5 seconds.
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) for the model.

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 also 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.

: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.
    tool_index: Extruder index for multi-tool printers (default 0).
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.

add_spoolB

Add a new filament spool to inventory.

Args:
    material: Material type (PLA, PETG, ABS, etc.).
    color: Filament color.
    brand: Manufacturer brand.
    weight_grams: Total spool weight in grams (default 1000).
    cost_usd: Cost of the spool in USD.
remove_spoolC

Remove a filament spool from inventory.

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_levelA

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_policyA

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_streamB

Control the MJPEG webcam streaming proxy.

Args:
    printer_name: Target printer.  Omit for the default printer.
    action: One of ``"start"``, ``"stop"``, or ``"status"``.
    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.
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 local estimate (PLA, PETG, etc.).
    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.
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.

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

Primary 3D preview tool — renders high-quality PNGs from multiple camera angles via OpenSCAD.

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 BEFORE printing to verify the model looks correct from all
sides.  Both agents and humans should review the output.

**When to use this vs other preview tools:**
- ``visualize_model`` — any file, 6 angles, universal (USE THIS ONE)
- ``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_templatesB

List available parametric design templates for common objects.

Templates provide ready-to-use OpenSCAD code with customizable
parameters.  Use ``generate_from_template`` to render one into
a printable STL.

Each template includes:
- Customizable parameters with defaults, ranges, and descriptions
- Pre-validated OpenSCAD code (prints without supports)
- Category and description
generate_from_templateA

Generate a 3D model from a parametric template with explicit parameters (local, no AI API).

Use when you know which template and parameter values to use. For AI-assisted
parameter inference + structural analysis, use ``smart_generate_from_template``.
Renders the template's OpenSCAD code with custom parameter values
into a printable STL.  Use ``list_design_templates`` to see
available templates and their parameters.

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.

Args:
    template_id: Template ID from ``list_design_templates``.
    parameters: Optional dict of parameter overrides
        (e.g., ``{"phone_width": 80, "angle": 70}``).

INLINE 3D STAGE: on success this tool also 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_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: AMS slot mapping (e.g. ``[0]`` for slot 1).
: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 .3mf or .gcode.3mf file was downloaded from.

Reads embedded metadata to determine the original marketplace source.
Supports 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 code: OpenSCAD source code to validate.
: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.

:param file_path: Path to mesh file (.stl, .obj, or .glb).
:param min_wall_mm: Minimum printable wall thickness (default 0.8).
:param max_bridge_mm: Maximum unsupported bridge length (default 15).
:param max_overhang_deg: Maximum overhang angle before failure (default 55).
:returns: Dict with verdict, risk score, and failure list.
search_design_templatesA

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 description: Natural-language design description.
:param output_dir: Directory for output files (uses tempdir if empty).
:param material: Material for weight estimation and slicing.
: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.
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 also 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 print-ready .3mf** containing all parts with per-part
AMS/extruder slot assignments.  This is the correct way to send a
multi-color design to any FDM printer — the printer receives one file,
not multiple.

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. Upload and print:
    upload_file(result["output_path"])
    start_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.

Returns:
    Dict with ``success``, ``output_path``, ``parts``, ``total_triangles``,
    ``total_vertices``, ``extruder_map``, and ``message``.

INLINE 3D STAGE: on success this tool also 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).
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.

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 hint (e.g. ``"PLA"``).  When set, 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.

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 hint (e.g. ``"PLA"``).  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.
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.

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

Auto-generate slicer override dict for a specific material.

Combines material thermal data (from the material database) with
printer-specific tuning (from printer intelligence) to produce a
ready-to-use JSON override dict for ``reslice_with_overrides`` or
``run_reslice_and_print``.

This is the key tool for material switching — call it to get the
correct temperatures, speeds, and retraction settings when changing
from one material to another.

Example workflow::

    # 1. Get overrides for PETG on your printer
    overrides = build_material_overrides("petg", "bambu_a1")
    # 2. Reslice and print with those overrides
    run_reslice_and_print(model_path, overrides=json.dumps(overrides["overrides"]))

Args:
    material_id: Target material (e.g. ``"petg"``, ``"tpu"``).
    printer_id: Optional printer model for printer-specific tuning.
        If omitted, uses material database defaults.
reprint_with_materialA

Reprint a model with a different material — auto-adjusts temperatures, speeds, and retraction for the new material.

One-shot convenience tool: looks up the target material's optimal slicer
settings, merges any extra overrides you provide, reslices the model,
runs a safety check, uploads to the printer, and starts the print.

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 AMS slot 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.

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. Generates merged slicer overrides (uses the highest-temp material)
    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.

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: Explicit AMS slot indices (0-based) per copy.
    E.g. ``[0, 1, 2, 3]`` for all 4 AMS Lite trays.
: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.

.. 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_cachedA

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 TEXT around the upright round wall of a cup,
    vase or bowl (STL, text + deboss only).  Letters stay legible and
    read correctly from outside; size and carve depth may be adjusted
    to keep them 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 and *absolute_size_mm* pins it
    exactly; *offset_x/y_mm* and *placement* do not apply (the line
    sits centred on the front at mid-height).  The wrap engine ships
    with kiln-pro and is included on the hosted service
    (api.kiln3d.com) on every tier; without it 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 also 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).  Default 0.4mm.
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.
    mode: Adaptive strategy — "balanced" (default), "quality_first",
        "speed_first", or "material_optimized".
export_adaptive_slicer_configC

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 (default 0.4mm).
    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.
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_partA

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_clearancesA

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 also 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_modelsB

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).
        
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.
        
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_designsC

List cached designs, optionally filtered by material.

        Args:
            material: Filter by material (e.g. "PLA", "PETG").
            limit: Maximum number of results.
        
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.

        :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.
        :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 also 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.

        :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.
        :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 also 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.

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.
        
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 also 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.

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_reinforcementsA

Recommend specific reinforcements for an STL mesh.

        Analyzes geometry to find structural risks, then generates actionable
        recommendations with **specific locations** and **estimated strength gains**:
        - **gusset**: triangular support at cantilever bases (3-10x stronger)
        - **fillet**: smooth transitions at stress concentrations (30-60% gain)
        - **thicken_wall**: add material at thin necks (2-5x gain)
        - **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 with estimated strength gains
        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 mesh 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** → filleted edges (stress concentration eliminated)
        - **Insufficient base** → wider base plate (stabilizing geometry added)
        - **Cantilevers** → triangular gusset ribs (deflection reduced 3-10x)

        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.

        :param file_path: Path to the STL file to reinforce.
        :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).
        :returns: Dict with before/after scores, applied/skipped reinforcements.

INLINE 3D STAGE: on success this tool also 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.  When
            provided, printer intelligence supplies the plate size.
        :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``.

        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``, 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 also 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.

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.
        
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.
            Best-effort: kiln-pro not installed silently skips.
        :returns: Dict with the best result and iteration history.

INLINE 3D STAGE: on success this tool also 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.

optimize_print_orientationA

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

        Tests multiple candidate orientations and picks the one with the
        best printability score.  Re-orients the mesh and places it flat
        on the build plate (z_min = 0).

        :param file_path: Path to the STL file.
        :param output_path: Output path.  Defaults to overwriting the input.
        :returns: Dict with rotation angles, overhang stats, and new dimensions.

INLINE 3D STAGE: on success this tool also 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, overhangs within limits, 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.  When
            provided, printer intelligence supplies the build volume.
        :returns: Dict with can_print verdict, issues, and actions taken.
        
estimate_support_materialA

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 .stl, .obj, or .glb 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 also 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_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.

        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; capacity is derated).
                False when the load acts within the layer planes
                (e.g. a bracket printed lying flat — the strong
                direction; full table value). If unsure, leave True:
                it is the conservative default.
        
check_material_environmentA

Check whether a material is compatible with an environment.

        Args:
            material: Material ID from the design knowledge base.
            environment: Natural language environment description.
        
get_design_template_infoB

Get one template's public discovery and safety-floor fields.

        Args:
            template: Template identifier.
        
list_design_templates_catalogB

List public design-template discovery summaries.

find_design_templatesA

Find public design-template summaries for a use case.

        Args:
            use_case: What you're designing (e.g. "enclosure",
                "gear train", "battery cover", "vase").
        
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 (default 0.4).
            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.

        Args:
            scad_code: OpenSCAD source code string.
        
update_scad_parameterB

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.

        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_parametersB

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.

        Args:
            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).

INLINE 3D STAGE: on success this tool also 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.

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.

        Args:
            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").

INLINE 3D STAGE: on success this tool also 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_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_sourceB

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

        Args:
            file_path: Path to STL or OBJ 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_trailB

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_memberA

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_summaryA

Show printer count, included allowance, and overage charges.

Enterprise feature. Enterprise base includes 50 printers. Additional printers are $15/month each.

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, whether the encryption key is configured, and whether the cryptography library is installed.

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.

report_printer_overageA

Report metered printer usage to Stripe for Enterprise billing.

        Enterprise feature. The first 50 printers are included in the base
        Enterprise price. This tool **automatically subtracts** the
        50 included printers and reports only the overage count to Stripe's
        ``active_printers`` meter at $15/printer/month.

        If *active_printer_count* is omitted, the fleet registry is queried
        automatically — no manual counting needed.

        Args:
            subscription_item_id: The Stripe SubscriptionItem ID (``si_...``) for
                the metered printer overage line item on the customer's subscription.
            active_printer_count: Total number of active printers.  Leave empty
                to auto-detect from the fleet registry.

        Example:
            With 55 registered printers, this reports **5** to Stripe
            (55 − 50 included = 5 overage × $15 = $75/mo).
        
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 (for STL/OBJ/3MF inputs), and returns adhesion
        recommendations — all without uploading or starting a print.

        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 for weight and adhesion estimates
                (e.g. ``"PLA"``, ``"PETG"``, ``"ABS"``).  Default is
                ``"PLA"``.
        
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.

        Analyses G-code extrusion commands to calculate filament usage,
        material weight, filament cost, electricity cost, and total.

        Args:
            file_path: Path to the G-code file.
            material: Filament material (PLA, PETG, ABS, TPU, ASA, NYLON, PC).
            electricity_rate: Cost per kWh in USD (default 0.12).
            printer_wattage: Printer power consumption in watts (default 200).
        
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.

        **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).
        :returns: Dict with weight, filament length, and cost.
        
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 (default 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"``).
        
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 Kiln Pro or 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_siteA

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_jobB

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.

        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.

        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).

        Direct Craftcloud mode requires the operator's own
        ``KILN_CRAFTCLOUD_API_KEY``. Normal users should use the hosted
        kiln-pro proxy so Craftcloud access stays server-side and quota
        enforcement applies.
        
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.

        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.
        
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.
        
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.
        
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.
        
generate_model_from_imageA

Make a 3D model from a reference image.

        DEFAULT (keyless): you (the agent) can SEE the image — study it
        and write the OpenSCAD yourself, then compile_scad. 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.

        **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"``).
        
generation_statusC

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 and optionally validate it.

        Args:
            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 also 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.

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:
            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).
        
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 template_id: Template ID from ``list_design_templates``.
        :param parameters: Parameter overrides (e.g., ``{"phone_width": 80}``).
        :param material: Filament type for settings inference (PLA, PETG, ABS, etc.).
        :param auto_reinforce: If True, auto-apply structural reinforcements.
        :returns: Dict with STL path, structural grade, reinforcements, and print settings.

INLINE 3D STAGE: on success this tool also 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.

generate_template_variationsA

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.
        
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 compile it with
        ``compile_scad`` — 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", session_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 compiling it with compile_scad. 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:
            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 also 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.

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 (default 0.4).
            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.
        
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_ruleA

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.

        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:
            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.

        After downloading, validate with ``validate_generated_mesh``, then
        upload to a printer with ``upload_file`` and print with ``start_print``.
        
browse_modelsB

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.

search_material_catalogA

Search the material catalog by brand, type, or keyword.

        Performs a case-insensitive multi-token search across vendor
        names, material types, and notes.  All tokens must match for
        an entry to be returned.

        Args:
            query: Search text (e.g. ``"Hatchbox PLA"``, ``"PETG"``).
        
get_material_infoA

Get detailed information for a specific material by ID.

        Returns the full catalog entry including vendor, type, family,
        variants, price range, weight options, and purchase sources.

        Args:
            material_id: Catalog ID (e.g. ``"hatchbox_pla"``, ``"esun_petg"``).
        
list_material_catalogA

List all material IDs in the catalog.

Returns a sorted list of every material identifier available in the built-in catalog database.

get_compatible_materialsB

Find all materials in a given family (e.g. PLA, PETG, resin).

        Returns every catalog entry sharing the same material family,
        useful for finding compatible substitutes.

        Args:
            material_family: Family name (e.g. ``"pla"``, ``"petg"``, ``"resin"``).
        
get_material_purchase_urlsA

Get purchase URLs for a material.

        Returns Amazon search links and manufacturer URLs.  If a colour
        is specified, it is substituted into the Amazon search template.

        Args:
            material_id: Catalog ID (e.g. ``"hatchbox_pla"``).
            color: Optional colour for URL personalisation.
        
find_material_matchB

Fuzzy-match a catalog entry from spool metadata.

        Matches against vendor and material type (case-insensitive
        substring).  If multiple entries match and a colour is provided,
        prefers entries whose variants include that colour.

        Args:
            vendor: Brand name (e.g. ``"Hatchbox"``).
            material_type: Product name (e.g. ``"PLA"``, ``"PLA+"``).
            color: Optional colour preference for tie-breaking.
        
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, generates actionable suggestions
        including shelf spool availability, pause-and-swap hints, and
        purchase links.  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``.  Returns optimal
        printer assignments that minimise spool swaps and prefer
        colour matches.

        Args:
            jobs: List of job dicts to assign.
        
suggest_spool_swapsA

Suggest minimal spool swaps to run all queued jobs.

        Analyses which jobs need which materials, compares against
        what is currently loaded on each printer, and suggests the
        fewest physical spool changes needed.

        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 == "255"`` normally means external spool.  On some
        A1/AMS Lite reports it can also mean the active slot was not
        reported even though AMS trays are present; in that case Kiln
        falls back to selected/target tray metadata or returns the
        loaded AMS candidates instead of claiming 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, OBJ, PLY, OFF, GLB, and GLTF formats.

        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, 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, or GLB, has reasonable
        dimensions, an acceptable polygon count, and is manifold
        (watertight).

        Args:
            file_path: Path to an STL, OBJ, or GLB 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 also 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 a composite printability score
        (0-100).

        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) 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%): overhangs, manifold, support needs
        - **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).
        :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, printability 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 also 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 also 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 also 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 also 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 also 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 thin walls in a mesh by offsetting vertices outward.

        Detects thin-wall regions and pushes vertices outward along their
        averaged normals.  This is a **geometry-level fix** -- the mesh is
        surgically modified instead of regenerating from scratch.

        Use after ``predict_print_failures()`` detects ``thin_walls`` or
        after ``design_scorecard()`` flags wall thickness issues.

        :param file_path: Path to the STL file.
        :param amount_mm: Offset distance in mm (default 0.5).
        :param output_path: Output path (defaults to ``<name>_thickened.stl``).
        :returns: Dict with number of vertices modified, amounts, and output path.

INLINE 3D STAGE: on success this tool also 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

Add fillets (rounded transitions) at sharp edges.

        Detects edges where adjacent faces meet at a sharp angle and
        inserts intermediate triangles to approximate a smooth fillet.
        Reduces stress concentration at corners and improves printability.

        Use after ``design_scorecard()`` flags sharp corners or
        ``predict_print_failures()`` detects stress risers.

        :param file_path: Path to the STL file.
        :param radius_mm: Fillet radius in mm (default 1.0).
        :param angle_threshold_deg: Edges sharper than this get filleted (default 60).
        :param output_path: Output path (defaults to ``<name>_filleted.stl``).
        :returns: Dict with sharp edge count, triangles added, and output path.

INLINE 3D STAGE: on success this tool also 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

Add chamfers (flat bevels) at sharp edges.

        Detects edges where adjacent faces meet at a sharp angle and
        bevels them with a flat transition face.  Chamfers are faster
        to print than fillets and reduce stress concentration.

        :param file_path: Path to the STL file.
        :param distance_mm: Chamfer distance from edge in mm (default 0.5).
        :param angle_threshold_deg: Edges sharper than this get chamfered (default 60).
        :param output_path: Output path (defaults to ``<name>_chamfered.stl``).
        :returns: Dict with sharp edge count, triangles added, and output path.

INLINE 3D STAGE: on success this tool also 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 also 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 also 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 also 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 also 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 also 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 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 also 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.

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 also 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 also 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 also 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 also 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 an STL file.

        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).

        Uses model height, surface area, and layer count to approximate
        print duration. This is a ballpark estimate -- actual time depends
        on slicer settings, infill density, supports, and acceleration.

        Unlike estimate_print_time (which uses slicer profiles), 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, layer count, 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).
        
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.

        **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.

        Args:
            monitor_id: The monitor ID returned by ``start_monitored_print``.
        
connect_provider_accountA

Connect a local printer to a provider account (integration path).

        Args:
            name: Human-readable printer name (e.g. "Prusa MK4 #2").
            location: Geographic location (e.g. "Austin, TX").
            capabilities: Optional dict of printer capabilities (build volume,
                supported materials, etc.).
            price_per_gram: Price per gram of filament in USD (optional).

        Registers this printer with the configured partner provider
        integration (currently 3DOS).
        
sync_provider_capacityB

Sync local printer capacity/availability to the provider integration.

        Args:
            printer_id: Optional ID of a registered provider printer.
            available: Optional availability update for ``printer_id``.

        If ``printer_id`` and ``available`` are provided, updates that
        listing first, then returns the current provider-side capacity view.
        
list_provider_capacityB

List printers registered with connected provider integrations.

Returns all provider-side listings associated with this integration account.

find_provider_capacityA

Find available provider capacity by material/location.

        Args:
            material: Material type to filter by (e.g. "PLA", "PETG", "ABS").
            location: Optional geographic filter (e.g. "Austin, TX").

        Returns provider-side capacity listings that match the request.
        
submit_provider_jobA

Submit a print job through a connected provider integration.

        Args:
            file_url: Public URL of the model file to print.
            material: Material to print with (e.g. "PLA", "PETG").
            printer_id: Optional target printer ID.  If omitted, provider
                auto-assigns the best available printer.

        Returns a provider-managed job reference. Use
        ``provider_job_status`` to track progress.
        
provider_job_statusB

Check status of a provider-managed remote job.

        Args:
            job_id: Job ID from ``submit_provider_job``.
        
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).

        Args:
            file_path: Path to an STL or OBJ mesh file.
            nozzle_diameter: Printer nozzle diameter in mm (default 0.4).
            layer_height: Print layer height in mm (default 0.2).
            max_overhang_angle: Maximum overhang angle in degrees before
                supports are needed (default 45).
            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 and scores each based
        on bed adhesion, support requirements, print height, and
        overhang coverage.  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.
        
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.  Use ``register_printer`` to add
        discovered printers to the fleet.
        
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_lockA

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.

Jobs are executed in priority order, with FIFO tie-breaking.
Use ``job_status`` to check progress and ``queue_summary`` for an overview.
job_statusB

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.
queue_summaryB

Get an overview of the print job queue.

Returns counts by status, next job to execute, and recent jobs.

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.
        
analyze_print_failure_smartA

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.

        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_planC

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_historyB

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).
        
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_splitA

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.

        Patent KILN-010 claim 51 — 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_failureA

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)

        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_recoveryB

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_checkA

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) AND when ``alternative_printers``
        is supplied AND kiln-pro is installed, the response carries
        a ``reroute_recommendation`` block — the rerouter's seven-rule
        verdict on whether the failed job should move to one of the
        alternatives.  Recommendation only; the agent must run the
        actual reroute 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 fleet of alternative
                printer dicts (each with ``printer_id`` plus optional
                ``is_idle``, ``supported_materials``,
                ``build_volume_mm``, ``success_rate``).  When
                supplied alongside ``success=False``, the response
                will include a ``reroute_recommendation`` from the
                pro rerouter (patent KILN-003 claim 5).  Single-printer
                setups can omit this.
            completion_pct_at_failure: How far the failed print got
                (0.0–1.0).  Below 10% the rerouter prefers
                same-device restart over reroute.  Defaults to 0
                (treated as low progress).
        
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.

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, 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 all available printer safety profiles.

        Returns a list of profile IDs and display names from the bundled
        safety database.  Use with ``get_safety_profile`` to inspect limits
        for a specific printer, or ``validate_gcode_safe`` to validate
        commands against a printer's limits.
        
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.

        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.

        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``.
        
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.
        
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_modelsA

List models that have been published to marketplaces.

        Args:
            marketplace: Filter by marketplace name (optional).
            limit: Maximum number of results (default 50).
        
record_revenueA

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.
            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.

        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``.
        
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.

        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: JSON string of key-value pairs to override in the slicer
                profile (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.
        
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).

        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.

        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"``).  Affects
                automatic brim/raft decisions.
            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.

        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"``.
        
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_profileB

Get the full bundled slicer profile for a printer model.

        Returns all INI settings (layer height, speeds, temps, retraction, etc.)
        and the recommended slicer.  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 STL/OBJ/3MF that failed.
            printer_name: Target printer name.  Omit for the default
                printer.
            material: Filament material (e.g. ``"PLA"``, ``"ABS"``).
                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.
        
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:
            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 also 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_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.

        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_logB

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.
        
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`` (0-100), and ``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 also 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.
        
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 also 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.
        

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.

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/codeofaxel/kiln'

If you have feedback or need assistance with the MCP directory API, please join our Discord server