Skip to content
Back to search

Kiln

Describe it or draw it — Kiln makes it real. The open-source MCP server for 3D printing: AI agents (Claude, Codex, Cursor, or any MCP client) design, generate, slice & print on Bambu Lab, Creality, Prusa, Elegoo, Klipper/Moonraker, OctoPrint, Duet/RepRapFirmware & any Marlin printer.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/codeofaxel/Kiln with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/codeofaxel/Kiln'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/codeofaxel--kiln/badge.svg)](/listings/codeofaxel--kiln)

HTML

<a href="/listings/codeofaxel--kiln"><img src="/api/listings/codeofaxel--kiln/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

**Using Claude Desktop? Install Kiln in one click.** [Download `kiln.mcpb`](https://github.com/codeofaxel/Kiln/releases/latest/download/kiln.mcpb) and double-click it — Claude Desktop installs Kiln and wires it in (just Claude Desktop: steps 1 and 2 below are how Codex and every other AI app connect), so those steps aren't yours. Two things still are: OpenSCAD, and Kiln's terms — the command shows them and asks you to type your acceptance, which is why it's yours and not your AI's: `uvx --from kiln3d kiln accept-terms`. The bundle and that command both run on [`uv`](https://docs.astral.sh/uv/getting-started/installation/) — free, with a one-line install for each platform at that link. If Claude Desktop says the server failed to start, that's uv missing: install it and restart. Updates arrive with the extension, not via `kiln self-update`.

Everyone else — three steps. Then ask your AI to make something.

**1. Install**

pip install kiln3d

**2. Connect your AI** — Kiln sets itself up inside Claude Desktop, Claude Code, and Codex:

kiln signin        # create your free account
kiln install-mcp   # connects Kiln to your AI apps

Restart your AI app and it can run your printer. (Claude Code and Codex can even run this whole setup for you — the one-prompt version lives at [kiln3d.com/install](https://kiln3d.com/install?utm_source=github&utm_medium=readme).) Using a different MCP client? `kiln install-mcp --print` prints the config — or paste it yourself:

<details> <summary><strong>Manual MCP config (any client, no sign-in needed)</strong></summary>

{
  "mcpServers": {
    "kiln": {
      "command": "python3",
      "args": ["-m", "kiln", "serve"]
    }
  }
}

**No install needed?** Swap the command for a zero-install runner — `"command": "uvx"`, `"args": ["kiln3d", "serve"]` (Python), or `"command": "npx"`, `"args": ["kiln3d"]` (Node). Same server, nothing to `pip install`.

Drop this into Claude Desktop, Claude Code, Codex, Cursor, or any MCP-capable agent. Runs on the free tier until you sign in. </details>

**3. Ask** — paste a sentence like this into your agent. Kiln does the rest:

> Make me a coaster with my dog's photo on it

That's the whole happy path. Your AI does the designing, slicing, and printing — you never touch a CLI. OS-specific walkthrough (Windows, WSL 2, Linux) at **[kiln3d.com/install](https://kiln3d.com/install?utm_source=github&utm_medium=readme)**.

> [!TIP] > `kiln doctor` checks your whole setup and tells you exactly what to fix. `kiln self-update` upgrades in place when a new release lands.

<details> <summary><strong>Prefer to drive it yourself? (CLI tour)</strong></summary>

# Discover printers on your network (mDNS + HTTP probe)
kiln discover

# Add your printer (see the printer table under "Supported Printers")
kiln auth --name my-printer --host http://octopi.local --type octoprint --api-key YOUR_KEY
# Other types:
# kiln auth --name prusa  --host http://192.168.1.100      --type prusalink --api-key YOUR_KEY
# kiln auth --name klipper --host http://192.168.1.100:7125 --type moonraker
# kiln auth --name bambu  --host 192.168.1.100             --type bambu --access-code LAN_CODE --serial SERIAL

kiln status                       # Printer state + job progress
kiln upload model.gcode           # Upload a file
kiln print model.gcode            # Start printing
kiln slice model.stl --print-after  # Slice an STL and print in one step
kiln print *.gcode --queue        # Batch print
kiln wait                         # Monitor a running print
kiln snapshot --save photo.jpg    # Webcam snapshot
kiln history --status completed   # Print history
kiln park --plan                  # Describe the safe park, send nothing; then --step 1, 2, 3
kiln home --plan                  # Same for the Home button; --plate-clear where Z homes onto the plate
kiln filament wipe --plan         # Same for the wipe-pad pass; --plate-clear where its plan presses the plate

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 28 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. {
  2. "name": "kiln",
  3. "owner": {
  4. "name": "Hadron Labs Inc.",
  5. "url": "https://kiln3d.com"
  6. },
  7. "metadata": {
  8. "description": "Kiln — AI agent infrastructure for 3D printing. Design, slice, print, monitor, and recover across Bambu Lab, Creality, Prusa, Elegoo, OctoPrint, Moonraker/Klipper and more.",
  9. "pluginRoot": "./plugins"
  10. },
  11. "plugins": [
  12. {
  13. "name": "kiln",
  14. "source": "./kiln",
  15. "description": "Wire the full Kiln MCP server into Claude Code in one command — design, slice, print, monitor, and recover on real 3D printers on your own network. Requires uv (astral.sh/uv).",
  16. "author": {
  17. "name": "Hadron Labs Inc.",
  18. "url": "https://kiln3d.com"
  19. },
  20. "homepage": "https://kiln3d.com",
  21. "license": "AGPL-3.0-or-later",
  22. "keywords": [
  23. "3d-printing", "3d-printer", "bambu-lab", "prusa", "creality",
  24. "elegoo", "octoprint", "moonraker", "klipper", "slicer", "fabrication"
  25. ]
  26. }
  27. ]
  28. }
README.md · README · 673 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <!-- mcp-name: io.github.codeofaxel/kiln -->
  2. <p align="center">
  3. <img src="docs/assets/kiln-banner-1280x640.svg" alt="Kiln" width="640">
  4. </p>
  5. <p align="center">
  6. <a href="https://pypi.org/project/kiln3d/"><img src="https://img.shields.io/pypi/v/kiln3d" alt="PyPI"></a>
  7. <a href="https://pepy.tech/projects/kiln3d"><img src="https://img.shields.io/pepy/dt/kiln3d" alt="PyPI Downloads"></a>
  8. <a href="https://pypi.org/project/kiln3d/"><img src="https://img.shields.io/pypi/pyversions/kiln3d" alt="Python"></a>
  9. <a href="https://github.com/codeofaxel/Kiln/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-AGPL--3.0-blue" alt="License"></a>
  10. <a href="https://github.com/codeofaxel/Kiln/blob/main/policies/SIGNING.md"><img src="https://img.shields.io/badge/verified%20by-sigstore%20%2B%20SLSA-0f6fdc?logo=sigstore&logoColor=white" alt="Verified by Sigstore + SLSA"></a>
  11. <a href="https://glama.ai/mcp/servers/codeofaxel/kiln"><img src="https://glama.ai/mcp/servers/codeofaxel/kiln/badge?v=2" alt="Kiln MCP server" width="120"></a>
  12. <a href="https://mcptoplist.com/server/io.github.codeofaxel%2Fkiln"><img src="https://mcptoplist.com/badge/io.github.codeofaxel%2Fkiln.svg" alt="MCP Toplist"></a>
  13. </p>
  14. ---
  15. **Spawn an object into existence.**
  16. Kiln is how AI agents make real things, safely. Describe what you want to exist, and your agent designs it, checks it will print, and prints it on your own 3D printer, or has it printed and shipped to you. Every version is kept, Git-style, so you can try the risky idea and keep the one that worked.
  17. **The open-source MCP server for 3D printing.**
  18. Kiln lets AI agents (ChatGPT, Claude Desktop, Claude Code, Gemini, GitHub Copilot, Grok, Codex, Cursor, OpenCode, Devin Desktop, Amp, Claude Duet, Hermes Agent, OpenClaw, or any custom MCP client) drive real 3D printers end to end — Bambu Lab, Creality, Prusa, Elegoo, Voron, Sovol, AnkerMake, Artillery, FlashForge, QIDI, RatRig, and SparkX. It is compatible with OctoPrint, Moonraker/Klipper, PrusaLink, and Direct USB.
  19. In a single conversation, an agent can design a part, slice it, queue it on the right printer, monitor the camera, recover from failures, and ship the result. You approve every print, or let one printer run on its own for as long as you choose.
  20. > **Reading this as an AI agent?** [**kiln3d.com/agents**](https://kiln3d.com/agents?utm_source=github&utm_medium=readme) is written for you rather than for the person running you: install, MCP config, the design-to-print loop, and exactly what Kiln will refuse to do and why.
  21. ```bash
  22. pip install kiln3d
  23. ```
  24. <p align="center">
  25. <img src="docs/assets/kiln-demo-loop.svg" alt="A Kiln agent session: the user asks for a coaster with their dog's photo; Kiln designs it, checks it will print, slices, and prints it on a Bambu A1 — done in 41 minutes." width="640">
  26. </p>
  27. <p align="center">
  28. <img src="docs/assets/ash-coaster.jpg" alt="A 3D-printed coaster with a relief portrait of a French bulldog and the name ASH along the bottom edge, held in a hand" width="640">
  29. </p>
  30. <p align="center">
  31. <em>"a coaster with a photo of my dog Ash" — start to finish, from one sentence.</em><br>
  32. <a href="https://kiln3d.com/?utm_source=github&utm_medium=readme#demo">Watch the demo →</a>
  33. </p>
  34. **Version control for 3D printing.** Branch a design to try the risky idea, compare any two versions with the numbers, merge the one that printed, and undo anything. [See how it works →](https://kiln3d.com/version-control?utm_source=github&utm_medium=readme)
  35. <p align="center">
  36. <img src="docs/assets/git-for-3d-gear.jpg" alt="Two versions of a spur gear side by side: version 1 solid, version 2 with five spokes, a recessed web and a keyed bore, 39.7% less material" width="640">
  37. </p>
  38. <p align="center">
  39. <sub>Kiln's built in the open. If it made your printing more fun, or just saved you a headache, a ⭐ on the repo helps the next maker find it.</sub>
  40. </p>
  41. ## Quick Start
  42. **Using Claude Desktop? Install Kiln in one click.** [Download `kiln.mcpb`](https://github.com/codeofaxel/Kiln/releases/latest/download/kiln.mcpb) and double-click it — Claude Desktop installs Kiln and wires it in (just Claude Desktop: steps 1 and 2 below are how Codex and every other AI app connect), so those steps aren't yours. Two things still are: OpenSCAD, and Kiln's terms — the command shows them and asks you to type your acceptance, which is why it's yours and not your AI's: `uvx --from kiln3d kiln accept-terms`. The bundle and that command both run on [`uv`](https://docs.astral.sh/uv/getting-started/installation/) — free, with a one-line install for each platform at that link. If Claude Desktop says the server failed to start, that's uv missing: install it and restart. Updates arrive with the extension, not via `kiln self-update`.
  43. **Using ChatGPT, Claude, Gemini, Grok, Cursor, Amp, Claude Duet or Hermes Agent? Nothing to install.** Add Kiln inside the app by its address, `https://api.kiln3d.com/mcp`, and sign in (Claude Duet uses the one you add in Claude; Hermes Agent takes one terminal command, on its page): it designs the part, checks it will print, and shows it in 3D, right in the chat where the app can show it. Each app's page says exactly what was seen there: [ChatGPT](https://kiln3d.com/chatgpt?utm_source=github&utm_medium=readme), [Claude](https://kiln3d.com/claude?utm_source=github&utm_medium=readme), [Gemini](https://kiln3d.com/gemini?utm_source=github&utm_medium=readme), [GitHub Copilot](https://kiln3d.com/copilot?utm_source=github&utm_medium=readme), [Grok](https://kiln3d.com/grok?utm_source=github&utm_medium=readme), [Codex](https://kiln3d.com/codex?utm_source=github&utm_medium=readme), [Cursor](https://kiln3d.com/cursor?utm_source=github&utm_medium=readme), [OpenCode](https://kiln3d.com/opencode?utm_source=github&utm_medium=readme), [Devin Desktop](https://kiln3d.com/devin?utm_source=github&utm_medium=readme), [Amp](https://kiln3d.com/amp?utm_source=github&utm_medium=readme), [Claude Duet](https://kiln3d.com/claude-duet?utm_source=github&utm_medium=readme), [Hermes Agent](https://kiln3d.com/hermes?utm_source=github&utm_medium=readme). To run your own printer, do the three steps below on the computer next to it.
  44. Using OpenClaw? Tell it to install Kiln from ClawHub and it sets Kiln up on the computer it runs on: [see how](https://kiln3d.com/openclaw?utm_source=github&utm_medium=readme).
  45. Everyone else — three steps. Then ask your AI to make something.
  46. **1. Install**
  47. ```bash
  48. pip install kiln3d
  49. ```
  50. **2. Connect your AI** — Kiln sets itself up inside Claude Desktop, Claude Code, and Codex:
  51. ```bash
  52. kiln signin # create your free account
  53. kiln install-mcp # connects Kiln to your AI apps
  54. ```
  55. Restart your AI app and it can run your printer. (Claude Code and Codex can even run this whole setup for you — the one-prompt version lives at [kiln3d.com/install](https://kiln3d.com/install?utm_source=github&utm_medium=readme).) Using a different MCP client? `kiln install-mcp --print` prints the config — or paste it yourself:
  56. <details>
  57. <summary><strong>Manual MCP config (any client, no sign-in needed)</strong></summary>
  58. ```json
  59. {
  60. "mcpServers": {
  61. "kiln": {
  62. "command": "python3",
  63. "args": ["-m", "kiln", "serve"]
  64. }
  65. }
  66. }
  67. ```
  68. **No install needed?** Swap the command for a zero-install runner — `"command": "uvx"`, `"args": ["kiln3d", "serve"]` (Python), or `"command": "npx"`, `"args": ["kiln3d"]` (Node). Same server, nothing to `pip install`.
  69. Drop this into Claude Desktop, Claude Code, Codex, Cursor, or any MCP-capable agent. Runs on the free tier until you sign in.
  70. </details>
  71. **3. Ask** — paste a sentence like this into your agent. Kiln does the rest:
  72. > Make me a coaster with my dog's photo on it
  73. That's the whole happy path. Your AI does the designing, slicing, and printing — you never touch a CLI. OS-specific walkthrough (Windows, WSL 2, Linux) at **[kiln3d.com/install](https://kiln3d.com/install?utm_source=github&utm_medium=readme)**.
  74. > [!TIP]
  75. > `kiln doctor` checks your whole setup and tells you exactly what to fix. `kiln self-update` upgrades in place when a new release lands.
  76. <details>
  77. <summary><strong>Prefer to drive it yourself? (CLI tour)</strong></summary>
  78. ```bash
  79. # Discover printers on your network (mDNS + HTTP probe)
  80. kiln discover
  81. # Add your printer, saying which printer it is (see "Supported Printers")
  82. kiln auth --name my-printer --host http://octopi.local --type octoprint --api-key YOUR_KEY --printer-model "Ender 3"
  83. # Other types:
  84. # kiln auth --name prusa --host http://192.168.1.100 --type prusalink --api-key YOUR_KEY --printer-model MK4
  85. # kiln auth --name klipper --host http://192.168.1.100:7125 --type moonraker --printer-model "Voron 2.4"
  86. # kiln auth --name bambu --host 192.168.1.100 --type bambu --access-code LAN_CODE --serial SERIAL --printer-model P1S
  87. # A printer Kiln doesn't list yet: add who makes it, e.g. --printer-make Anycubic --printer-model "Kobra X"
  88. kiln status # Printer state + job progress
  89. kiln upload model.gcode # Upload a file
  90. kiln print model.gcode # Start printing
  91. kiln slice model.stl --print-after # Slice an STL and print in one step
  92. kiln print *.gcode --queue # Batch print
  93. kiln wait # Monitor a running print
  94. kiln snapshot --output photo.jpg # Webcam snapshot
  95. kiln history --status completed # Print history
  96. kiln park --plan # Describe the safe park, send nothing; then --step 1, 2, 3
  97. kiln home --plan # Same for the Home button; --plate-clear where Z homes onto the plate
  98. kiln filament wipe --plan # Same for the wipe-pad pass; --plate-clear where its plan presses the plate
  99. # Every command supports --json for agent consumption
  100. kiln status --json
  101. ```
  102. Global option: `--printer <name>` targets a specific printer per command. The full command reference is in [Project Docs](https://www.kiln3d.com/docs?utm_source=github&utm_medium=readme).
  103. </details>
  104. <details>
  105. <summary><strong>Connect a specific agent (Claude Code, Claude Desktop, env vars)</strong></summary>
  106. **Claude Code** — install the plugin (one-time: install [uv](https://astral.sh/uv) first if you don't have it — it's free and takes one line):
  107. ```bash
  108. claude plugin marketplace add codeofaxel/Kiln
  109. claude plugin install kiln@kiln
  110. ```
  111. Or wire it by hand — add to `.claude/settings.json` (project) or `~/.claude/settings.json` (global):
  112. ```json
  113. {
  114. "mcpServers": {
  115. "kiln": { "command": "kiln", "args": ["serve"] }
  116. }
  117. }
  118. ```
  119. Claude Code uses your `~/.kiln/config.yaml` for printer credentials (set via `kiln setup` or `kiln auth`). No env vars needed if a printer is already configured.
  120. **Claude Desktop** — add to `~/.config/Claude/claude_desktop_config.json`:
  121. ```json
  122. {
  123. "mcpServers": {
  124. "kiln": {
  125. "command": "python3",
  126. "args": ["-m", "kiln", "serve"],
  127. "env": {
  128. "KILN_PRINTER_HOST": "http://192.168.1.100",
  129. "KILN_PRINTER_API_KEY": "your_key",
  130. "KILN_PRINTER_TYPE": "prusalink"
  131. }
  132. }
  133. }
  134. }
  135. ```
  136. Set `KILN_PRINTER_TYPE` to your backend: `octoprint`, `moonraker`, `bambu`, `prusalink`, `elegoo`, `duet`, or `usb` — or skip env vars entirely if you've run `kiln setup`.
  137. **Any other LLM (OpenRouter)** — Kiln works with any model that supports OpenAI-compatible function calling, not just Claude:
  138. ```bash
  139. export KILN_OPENROUTER_KEY=sk-or-...
  140. kiln agent --model openai/gpt-4o
  141. kiln agent --model meta-llama/llama-3.1-70b-instruct --tier essential
  142. ```
  143. Tool tiers auto-match model capability: **essential** (15 tools) for smaller models, **standard** (60 tools) for mid-range, **full** (135 tools) for stronger models. All <!-- KILN_MCP_TOOL_COUNT:OLD --> 880 tools are available over MCP via `kiln serve`.
  144. </details>
  145. <details>
  146. <summary><strong>Platform &amp; printer setup notes (Linux/WSL 2, Ethernet-only, Bambu)</strong></summary>
  147. ### Prerequisites by printer type
  148. | Printer | `--type` | What you need |
  149. |---------|----------|---------------|
  150. | **Prusa MK4/XL/Mini+** | `prusalink` | IP + API key (Settings › Network › PrusaLink on the LCD) |
  151. | **OctoPrint** (any printer) | `octoprint` | OctoPrint URL + API key (User Settings › Application Keys) |
  152. | **Klipper/Moonraker** | `moonraker` | Moonraker URL (usually `http://<ip>:7125`) |
  153. | **Creality K1/K2/Hi/Ender V4/V3 KE** | `creality` | IP + `printer_model` (e.g. `creality_k1_max`); probes local Moonraker ports |
  154. | **Bambu Lab** | `bambu` | IP + serial number + LAN access code, all on the printer's screen; LAN Only Mode and Developer Mode on to start and control prints |
  155. | **Elegoo** (SDCP) | `elegoo` | IP only — no auth. Neptune 4 / OrangeStorm Giga use `moonraker`. |
  156. | **Duet / RepRapFirmware** | `duet` | IP only, plus the machine password if one is set (`M551` in `config.g`). |
  157. | **Direct USB** (Marlin) | `usb` | USB cable only — no network. Ender 3, Prusa MK3, CR-10, any Marlin/RepRap printer. |
  158. Kiln only needs IP reachability on your LAN. Ethernet-only printers are fully supported.
  159. **Optional tools:** [PrusaSlicer](https://www.prusa3d.com/prusaslicer/) OrcaSlicer, or BambuStudio for slicing STL → G-code (`brew install --cask prusaslicer`); [OpenSCAD](https://openscad.org/downloads#snapshots) for local text-to-3D generation — install the current build (`brew install --cask openscad@snapshot`); set `KILN_GEMINI_API_KEY` to enable Gemini-generated geometry.
  160. ### Linux / WSL 2
  161. `pipx` installs Kiln into its own isolated environment and puts `kiln` on your PATH. (The pip package is `kiln3d`; the CLI command is `kiln`.)
  162. ```bash
  163. sudo apt install pipx && pipx ensurepath
  164. git clone https://github.com/codeofaxel/Kiln.git && cd Kiln
  165. pipx install ./kiln
  166. sudo apt install prusa-slicer # optional: slicing for printing
  167. sudo snap install openscad --edge # optional: the design engine (current build)
  168. kiln verify
  169. # Update / uninstall
  170. git pull && pipx install --force ./kiln
  171. pipx uninstall kiln3d
  172. ```
  173. **WSL 2 networking:** WSL 2 uses NAT, so mDNS discovery (`kiln discover`) won't see printers on your home network. Connect directly by IP instead (same as Ethernet-only setups).
  174. ### Ethernet-only printers (no Wi-Fi)
  175. Kiln works the same over Ethernet and Wi-Fi — it talks to printer APIs over LAN IP. Verify the printer endpoint responds, then register by IP:
  176. ```bash
  177. curl http://<ip>/api/version # OctoPrint
  178. curl http://<ip>:7125/server/info # Moonraker / Creality (local Moonraker)
  179. curl -H "X-Api-Key: YOUR_KEY" http://<ip>/api/v1/status # Prusa Link
  180. # Bambu uses MQTT — ensure port 8883 is reachable: nc -zv <ip> 8883
  181. kiln auth --name my-printer --host http://<ip> --type prusalink --api-key YOUR_KEY --printer-model MK4
  182. ```
  183. If PrusaSlicer isn't on your PATH: `export KILN_SLICER_PATH=/path/to/prusa-slicer`.
  184. ### Bambu TLS &amp; webcam
  185. Kiln pins the printer certificate (TOFU) on first connection in `~/.kiln/bambu_tls_pins.json`. Overrides:
  186. ```bash
  187. export KILN_BAMBU_TLS_MODE=ca # strict CA/hostname (usually fails on stock self-signed printers)
  188. export KILN_BAMBU_TLS_MODE=insecure # legacy, no validation — trusted LANs only
  189. export KILN_BAMBU_TLS_FINGERPRINT=0123abcd... # explicit SHA-256 pin
  190. ```
  191. **Camera.** Kiln can take a picture of your print on every Bambu Lab printer, and on the A1, A1 mini, A2L, P1P and P1S it can also show the camera live in the print monitor. The X1, X2, P2 and H series need a free camera add-on; Kiln tells you when yours does and can add it for you. To include it when you install Kiln: `pip install 'kiln3d[camera]'`.
  192. </details>
  193. Paid tiers ([kiln3d.com/pricing](https://kiln3d.com/pricing?utm_source=github&utm_medium=readme)) add version control on every design, product templates, assembly manuals, fleet workflows, SSO + SCIM, ERP webhooks, and long-term audit logs.
  194. ## Why Kiln?
  195. - **One control plane, any printer** — compatible with OctoPrint, Moonraker, Creality, Bambu Lab, Prusa Link, Elegoo, Serial. Manage a mixed fleet from one place.
  196. - **No printer? No problem** — Outsource jobs to Craftcloud's 150+ manufacturing services, quoted and ordered through Kiln.
  197. - **AI-native** — <!-- KILN_MCP_CAPABILITY_COUNT:OLD --> 887 MCP capabilities and <!-- KILN_CLI_COUNT:OLD --> 253 CLI commands built for AI agents. Not a web UI with an API bolted on.
  198. - **Describe it, print it** — Natural-language to physical object pipeline: text or sketch → AI generation → validation → slice → print.
  199. - **Decorate anything** — QR codes, photos, logos, text, SVGs, and procedural textures (tiger stripe, marble, camo, wood grain, honeycomb) embossed or debossed onto any model with one command.
  200. - **Manuals included** — Multi-part prints can generate printable PDF assembly manuals with Bill of Materials, isometric step renders, mating arrows, and pause-and-check verification gates. (Business)
  201. - **Resume, don't restart** — Cancelled or failed print? Resume from the exact layer it stopped on any supported FDM printer. No filament wasted. (Pro)
  202. - **Modify mid-print** — Add decorations, append features, or swap materials on a live print with atomic revert if anything goes wrong. (Pro)
  203. - **Smart material routing** — 38 materials and brand filament profiles for 69 brands and lines (the per-brand tune is part of Kiln Pro). Intent-based recommendations with printer capability awareness.
  204. - **Prints don't fail silently** — Cross-printer learning, automatic failure recovery, closed-loop AI generation feedback (failed prints auto-improve future generations), preflight safety checks on every job.
  205. - **Doomed prints stopped early** — Too big for the build plate, or a material your hotend can't melt? Caught before filament is wasted, rotated to fit when possible, one-command override. Pro shows the fix: true usable area, cleanest split, or the material to switch to.
  206. - **Search → Slice → Print** — Search and download 3D models from MyMiniFactory and Cults3D (search only), auto-slice with PrusaSlicer, OrcaSlicer, or BambuStudio, print — all from one agent conversation.
  207. - **Safety at scale** — a named safety profile for every supported printer, G-code validation, heater watchdog, tamper-proof audit logs. Enterprise adds encrypted G-code at rest with key rotation, lockable profiles, RBAC, SSO, fleet site grouping, per-project cost tracking, and PostgreSQL HA.
  208. ## Supported Printers
  209. | Backend | Status | Printers |
  210. |---------|--------|----------|
  211. | **OctoPrint** | Stable | Compatible with any OctoPrint-connected printer (Prusa, Ender, custom) |
  212. | **Moonraker** | Stable | Klipper-based printers (Voron, Ratrig, etc.) |
  213. | **Creality** | Stable when Moonraker is reachable | SPARKX i7, K1/K1 Max/K1C/K1 SE, K2/K2 Pro/K2 Plus/K2 SE, Creality Hi, Ender-3 V4/V3 KE, Ender-5 Max, CR-10 SE via local Moonraker. Older Marlin Creality printers use `serial` or `octoprint`. |
  214. | **Bambu** | Stable | Bambu Lab X1C, X1E, P1S, P1P, P2S, A1, A1 Mini, A2L, H2S, H2D, H2D Pro, H2C, H3C, X2D (via LAN MQTT) |
  215. | **Prusa Link** | Stable | Prusa MK4, XL, Mini+ (local REST API — type: `prusalink`) |
  216. | **Elegoo** | Stable | Centauri Carbon (via LAN WebSocket/SDCP). Neptune 4 / OrangeStorm Giga use Moonraker. |
  217. | **Duet / RepRapFirmware** | Beta — not yet verified against physical hardware | Duet 2 and Duet 3 controller boards, over the same HTTP interface Duet Web Control uses. Both RepRapFirmware 2 and 3 are supported. Vision Miner 22 IDEX v4 is the first catalogued machine. Type: `duet`. |
  218. | **Direct USB** | Stable | Any Marlin-based printer over USB (Ender 3, Prusa MK3, CR-10, etc.). No OctoPrint or Klipper needed — just a USB cable. Type: `serial`. |
  219. <!-- BEGIN SUPPORTED PRINTERS (auto-generated by scripts/generate_supported_printers.py) -->
  220. Kiln ships **tuned profiles for 76 models across 17 brands** — Creality, Bambu Lab, QIDI, Prusa Research, Elegoo, Sovol, Voron, AON3D, Anycubic, Artillery, AnkerMake, FlashForge, INTAMSYS, RatRig, Snapmaker, SparkX, Vision Miner. [See the full searchable list →](https://kiln3d.com/printers?utm_source=github&utm_medium=readme)
  221. <!-- END SUPPORTED PRINTERS -->
  222. ## Architecture
  223. ```mermaid
  224. graph TD
  225. A["🤖 AI Agent<br/><sub>Claude · GPT · Custom</sub>"]
  226. A -->|"CLI or MCP"| B["⚙️ Kiln<br/><sub>CLI + MCP Server</sub>"]
  227. B --> C["🖨️ Your Printers"]
  228. B --> F["🏭 Fulfillment"]
  229. B --> D["🛒 Marketplaces"]
  230. B --> V["📐 Designs (versioned)<br/><sub>Pro+</sub>"]
  231. C --> E1["OctoPrint"]
  232. C --> E2["Moonraker"]
  233. C --> E3["Creality"]
  234. C --> E4["Bambu"]
  235. C --> E5["Prusa Link"]
  236. C --> E6["Elegoo"]
  237. F --> F1["Craftcloud"]
  238. D --> I["MyMiniFactory"]
  239. D --> J["Cults3D"]
  240. V --> V1["Branches"]
  241. V --> V2["Signed Releases"]
  242. V --> V3["Cloud Sync"]
  243. style A fill:#1a1a2e,stroke:#e94560,color:#fff
  244. style B fill:#16213e,stroke:#0f3460,color:#fff
  245. style C fill:#0f3460,stroke:#e94560,color:#fff
  246. style F fill:#0f3460,stroke:#27ae60,color:#fff
  247. style D fill:#0f3460,stroke:#533483,color:#fff
  248. style V fill:#0f3460,stroke:#f59e42,color:#fff
  249. style E1 fill:#2d2d44,stroke:#e94560,color:#fff
  250. style E2 fill:#2d2d44,stroke:#e94560,color:#fff
  251. style E3 fill:#2d2d44,stroke:#e94560,color:#fff
  252. style E4 fill:#2d2d44,stroke:#e94560,color:#fff
  253. style E5 fill:#2d2d44,stroke:#e94560,color:#fff
  254. style F1 fill:#2d2d44,stroke:#27ae60,color:#fff
  255. style I fill:#2d2d44,stroke:#533483,color:#fff
  256. style J fill:#2d2d44,stroke:#533483,color:#fff
  257. style V1 fill:#2d2d44,stroke:#f59e42,color:#fff
  258. style V2 fill:#2d2d44,stroke:#f59e42,color:#fff
  259. style V3 fill:#2d2d44,stroke:#f59e42,color:#fff
  260. ```
  261. Agents can also outsource jobs through **Craftcloud** fulfillment and search models on **MyMiniFactory** and **Cults3D** (search only). The design store itself is versioned — branches and cross-machine cloud sync on the designs a free Kiln account keeps, and on every design with signed releases on Pro and up — first-class outputs of the system, not a side database.
  262. ## Version control for 3D printing
  263. A printed part goes through versions the way code does, and usually ends up as `bracket_final_v2_REAL.stl`. Kiln keeps every version for you, so you can try the risky idea and keep the one that printed. Your agent does it in plain words: *"try 4 mm walls on a branch, and keep the 3 mm one."*
  264. - **Branch and undo.** Try the risky idea on a branch. The working version stays untouched, and any step can be undone.
  265. - **See what changed.** Compare two versions side by side or drag between them, with how much material each change added or removed.
  266. - **Prints on the record.** Every print is filed under the version that made it, so you can look up how each one went.
  267. - **Merge.** Bring the change that printed best back into your main design. Kiln merges what it can and asks you about the rest.
  268. - **Signed releases.** Sign the version you ship, and prove later that it hasn't changed.
  269. <p align="center">
  270. <img src="docs/assets/git-for-3d-gear-sweep.gif" alt="A line sweeps across a spur gear: on one side the solid first version, on the other the second version with five spokes, a recessed web and a keyed bore" width="640">
  271. </p>
  272. <p align="center">
  273. <em>Drag across a part to see two versions at once, on every plan.</em>
  274. </p>
  275. | Plan | What you get |
  276. |---|---|
  277. | Free | Every version saved on your computer, with diff and rollback. With a free Kiln account: branch, merge, cherry-pick, undo and pull requests on the designs you keep, synced to the account |
  278. | **Pro** | All of that on every design, plus the change drawn on the part, pinned comments, signed releases, versioned decorations and features, and design provenance |
  279. | **Business** | Approval gates, team review, organizations and teams |
  280. | **Enterprise** | Named-approver sign-off, step-up sign-in before production releases, audit log export, SSO, access reviews |
  281. [See how version control works →](https://kiln3d.com/version-control?utm_source=github&utm_medium=readme)
  282. ## Tools
  283. The Kiln MCP server (`kiln serve`) exposes **<!-- KILN_MCP_TOOL_COUNT:OLD --> 880 tools** to agents, plus prompts and resources for **<!-- KILN_MCP_CAPABILITY_COUNT:OLD --> 887 total MCP capabilities**. Rather than list them all here, agents browse the live catalog with `get_skill_manifest` and ToolSearch-style discovery. A representative slice, in the order a print actually happens:
  284. - **design_session**
  285. - Talk to Kiln about what you're making and get back a design that matches what you asked for
  286. - The front door for making anything: goal, geometry, preview, iterate. Free, unlimited, every tier
  287. - **compile_scad**
  288. - Compile OpenSCAD code into a printable STL — the keyless path underneath a design session
  289. - No API key and no external service: the agent writes the geometry, Kiln compiles it locally
  290. - **generate_model**
  291. - Generate a 3D model from a text prompt through an external AI provider
  292. - Optional, and off unless you bring your own key (Meshy, Tripo3D, Stability, Gemini)
  293. - **search_all_models**
  294. - Search connected 3D model marketplaces in one call
  295. - Covers MyMiniFactory and Cults3D; downloads where the marketplace supports it
  296. - **import_step_file**
  297. - Import a STEP (.step/.stp) CAD file and convert it for Kiln's mesh pipeline
  298. - **analyze_printability**
  299. - Run a full printability analysis on a mesh: overhangs, thin walls, warping risk, bed fit
  300. - **auto_orient_model**
  301. - Find the print orientation that needs the least support and prints strongest
  302. - **repair_mesh**
  303. - Repair mesh defects — holes, degenerate faces, rounding-noise seams
  304. - The usual fix for a model an AI generator or a rough scan produced
  305. - **split_mesh_to_fit**
  306. - Cut one solid too big for your build plate into printable pieces that reassemble
  307. - **recommend_material**
  308. - Recommend materials for a use case, with the reasons and the trade-offs
  309. - **decorate_surface**
  310. - Put any image, text, QR code, or pattern onto a model surface as an emboss or deboss
  311. - **slice_model**
  312. - Slice a model (STL/3MF/STEP) to G-code using PrusaSlicer, OrcaSlicer, or BambuStudio
  313. - **show_on_stage**
  314. - Turn over a file you already have — a model, or the sliced file about to print — on Kiln's interactive 3D stage, without re-making or re-slicing it
  315. - **estimate_print_cost_from_mesh**
  316. - Estimate material cost, weight, and print time before committing the printer
  317. - **preflight_check**
  318. - Run pre-print safety checks: printer state, temperatures, file validity, bed clearance
  319. - **start_print**
  320. - Start a print on a connected machine
  321. - **monitor_print**
  322. - One-shot print status: progress, temperatures, time remaining, cost, and a camera snapshot where the printer has one
  323. - **emergency_stop**
  324. - Stop a running print immediately
  325. - **purge_filament**
  326. - Heat the nozzle and push a short length through — the clog test, with `load_filament` and `unload_filament` beside it for a spool change
  327. - Reports what the printer could actually tell: where a machine reports no flow signal it says so rather than claiming success
  328. - Always says where the purge went: over the machine's own purge chute where Kiln knows it for your model (served through Kiln's hosted service for a printer paired to your Kiln sign-in, free, and kept on your machine so it keeps working offline), or in place with the reason — never a guessed coordinate
  329. - **wipe_nozzle**
  330. - Clean the nozzle tip on the printer's own wipe pad (served through Kiln's hosted service for a printer paired to your Kiln sign-in, free, and kept on your machine so it keeps working offline); refuses, and says what to use instead, on any model whose pad Kiln does not know
  331. - Run it in steps where the pass is new to a machine: `plan_only` describes every motion and sends nothing; `step=N` sends one motion, says what it left armed, and holds the cool-down until the last step. A wipe that presses or crosses the plate asks for `plate_clear` on every call: a person's word, never inferred. Where a model's wipe has not yet been run on a real machine, Kiln says so and runs it in steps only
  332. - **home_axes**
  333. - The Home button, from Kiln: your model's own homing routine where Kiln has it (served through Kiln's hosted service for a printer paired to your Kiln sign-in, free, and kept on your machine so it keeps working offline), the firmware's own routine elsewhere, a refusal that names the screen's jog controls where neither is safe
  334. - Run it in steps the first time: `plan_only` describes every motion before anything moves; `step=N` sends one motion and says what it left armed
  335. - **park_head**
  336. - Move the head to the model's own spot off the plate and leave it there; never a Z touch, never heat
  337. - **plate_status**
  338. - What Kiln knows is on the build plate: the print that left a part there and how long ago, or that it is clear — a person's word (`kiln plate clear`, or `plate_clear` on home and park) or a look through the printer's camera (`look_at_plate`); nothing marks it clear on its own
  339. - Home, park, slicing and starting a print refuse to cross a recorded part, and the refusal shows the plate through the camera where the printer has one, so an old record is checked rather than trusted
  340. - **diagnose_print_failure_live**
  341. - Diagnose a failing print from live printer state plus the model's own geometry
  342. - **retry_print_with_fix**
  343. - Diagnose what went wrong on the last print, then re-slice and print with the fix applied
  344. - **resume_interrupted_print** *(Pro)*
  345. - Resume an interrupted print with one call on any supported FDM printer
  346. - **save_design_version**
  347. - Save a new version of a parametric design, so you can go back to the one that worked
  348. - Linear history is free; branching and merges are free on the designs you keep in a free Kiln account and on every design with Pro; signed releases are Pro
  349. - **export_step**
  350. - Export a finished design as a real STEP CAD file — analytic B-rep a machine shop can open and measure
  351. - **printer_status**
  352. - What a printer is doing right now, and the list of printers you have set up; several printers' live status in one answer (state, temperatures, connection) is part of Kiln Business
  353. - **fulfillment_quote**
  354. - Get a manufacturing quote from Craftcloud's network — printing without owning a printer
  355. Beyond this slice, the catalog covers fleet orchestration, print-failure prediction, design version control, assembly manuals, and per-machine calibration; the deeper tiers are described at [kiln3d.com/pricing](https://kiln3d.com/pricing?utm_source=github&utm_medium=readme). The complete tool catalog, grouped by subsystem, lives in **[Project Docs](https://www.kiln3d.com/docs?utm_source=github&utm_medium=readme)**. If you *are* the agent, [**kiln3d.com/agents**](https://kiln3d.com/agents?utm_source=github&utm_medium=readme) covers the same ground written in the second person, including the refusals worth knowing before you hit them.
  356. <details>
  357. <summary>MCP resources (read-only context for agents)</summary>
  358. | Resource URI | Description |
  359. |---|---|
  360. | `kiln://status` | System-wide snapshot (printers, queue, events) |
  361. | `kiln://printers` | Fleet listing with idle printers |
  362. | `kiln://printers/{name}` | Detailed status for a specific printer |
  363. | `kiln://queue` | Job queue summary and recent jobs |
  364. | `kiln://queue/{job_id}` | Detail for a specific job |
  365. | `kiln://events` | Recent events (last 50) |
  366. </details>
  367. ## Capabilities
  368. **Search → download → print.** Kiln searches MyMiniFactory and Cults3D (search only) in one call via `search_all_models`, downloads where supported, and uploads straight to a printer — a full design-to-print loop with no human in the middle. *(Thingiverse is supported but deprecated since its Feb 2026 acquisition by MyMiniFactory; prefer MMF.)* Marketplace access uses free API keys (`KILN_MMF_API_KEY`, `KILN_CULTS3D_USERNAME` + `KILN_CULTS3D_API_KEY`).
  369. **AI model generation.** Set any provider key and it's available instantly — `KILN_MESHY_API_KEY`, `KILN_TRIPO3D_API_KEY`, `KILN_STABILITY_API_KEY`, `KILN_GEMINI_API_KEY` — or use local OpenSCAD with no key. Generated meshes are auto-validated for printability (manifold, triangle count, bounding box) before printing. `kiln generate` renders a 3-view preview by default.
  370. **Slicing.** Wraps PrusaSlicer, OrcaSlicer, and BambuStudio for headless slicing; auto-detects installed slicers on PATH, macOS app bundles, or via `KILN_SLICER_PATH`. Supports STL, 3MF, STEP, OBJ, AMF with material-aware temps and smart supports.
  371. **Fulfillment (no printer required).** Print through Craftcloud's network — quote, validate address, confirm, order, track — or run alongside your own printers for overflow and specialty materials. Orders go through Kiln's hosted service, which keeps provider credentials server-side and enforces your spend limits.
  372. **Decoration &amp; textures.** Emboss or deboss QR codes, photos, logos, text, and SVGs onto any model face, or apply procedural textures (tiger stripe, marble, camo, wood grain, honeycomb) with a single tool call.
  373. ## Pricing
  374. All local printing is **free forever** — status, file management, slicing, fleet control, and printing to your own printers cost nothing. Kiln charges a **5% orchestration fee** on orders placed through external manufacturing services ($0.25 min / $200 max per order; a Pro account's first 3 orders each calendar month free; no fee on Business and Enterprise), shown transparently in every quote. Outsourced order volume is not capped on any tier.
  375. | Tier | Price | Headline |
  376. |------|-------|----------|
  377. | **Free** | $0 | Unlimited local printing, slicing, marketplace search, safety profiles, one printer, design intelligence, linear design history, and branching on the designs you keep in a free account. |
  378. | **Pro** | $49/mo | Branching on every design, signed releases, product templates, procedural textures, mid-print modification, print resume, failure recovery, nozzle-wear tracking, solo cloud sync, selling prints of your own designs. |
  379. | **Business** | $199/mo | Client and custom-order work, 3 printers + 3 seats, fleet management, cross-printer learning, QR generation, assembly manuals, team pull requests, approval gates, webhooks. |
  380. | **Enterprise** | Contact us | Large fleets, SSO/SCIM, RBAC, audit trail, encrypted G-code at rest, white-label manuals, 99.9% SLA, on-prem/VPC. |
  381. **Founding offer:** half off for life while founding spots last — Pro $24.50/mo or $234/yr, Business $99.50/mo or $954/yr. Students get half off for 12 months. Details and how to claim the student price: **[kiln3d.com/pricing](https://kiln3d.com/pricing?utm_source=github&utm_medium=readme)**.
  382. Full comparison at **[kiln3d.com/pricing](https://kiln3d.com/pricing?utm_source=github&utm_medium=readme)**. Already subscribed? Run `kiln signin` to put this machine on your plan. For provider-routed orders, the provider remains merchant of record; Kiln acts as orchestration infrastructure.
  383. ## Safety
  384. Kiln is safety-first infrastructure for controlling physical machines:
  385. - **Pre-flight checks** validate printer state, temperatures, and files before every print
  386. - **G-code validation** blocks dangerous commands (firmware reset, unsafe temperatures)
  387. - **Temperature limits** hold each printer to its own maximums, and a printer whose model Kiln has not been told to 240 °C hotend and 80 °C bed, whether the request is a temperature setting or raw G-code
  388. - **A person says go** before every print — in your AI app's approval dialog, by typing a code Kiln shows on your screen, or at the terminal — unless you chose not to be asked: for a while (a day at most), always on a printer you named yourself (at your own terminal, or on your Kiln account page with two-factor), or by switching on auto-print yourself; stopping, pausing and watching a print never need that yes
  389. - **Confirmation required** for destructive operations (cancel, raw G-code)
  390. - **Optional authentication** with scope-based API keys for multi-user setups
  391. - **Structured errors** ensure agents always know when something fails
  392. ## Packages
  393. This monorepo contains two packages:
  394. | Package | Description | Entry point |
  395. |---------|-------------|-------------|
  396. | **kiln** | CLI + MCP server for multi-printer control (OctoPrint, Moonraker, Creality, Bambu, Prusa Link, Elegoo, Direct USB) | `kiln` or `python -m kiln` |
  397. | **octoprint-cli** | Lightweight standalone CLI for OctoPrint-only setups | `octoprint-cli` |
  398. ## Development
  399. ```bash
  400. # Create a virtualenv first (required on modern Ubuntu/Debian/WSL)
  401. python3 -m venv .venv && source .venv/bin/activate
  402. pip install -e "./kiln[dev]"
  403. pip install -e "./octoprint-cli[dev]"
  404. cd kiln && python3 -m pytest tests/ -v
  405. cd ../octoprint-cli && python3 -m pytest tests/ -v
  406. ```
  407. ### Run in Docker
  408. `docker compose up` self-hosts the Kiln MCP server against your own printer — set `KILN_PRINTER_TYPE`/`KILN_PRINTER_HOST`/`KILN_PRINTER_API_KEY` first. This is a personal self-host quickstart, unrelated to the infrastructure behind the hosted api.kiln3d.com service. Prefer zero setup? [kiln3d.com](https://kiln3d.com/?utm_source=github&utm_medium=readme) runs the hosted version for you.
  409. <details>
  410. <summary><strong>Configuration reference (auth, webhooks, discovery, plugins)</strong></summary>
  411. ### Authentication (optional)
  412. Optional API-key auth for MCP tools, disabled by default. Scopes: `read`, `write`, `admin`. Read-only tools never require auth.
  413. ```bash
  414. export KILN_AUTH_ENABLED=1
  415. export KILN_AUTH_KEY=your_secret_key
  416. export KILN_MCP_AUTH_TOKEN=your_secret_key # clients provide their key here
  417. ```
  418. ### Webhooks
  419. Register HTTP endpoints for real-time event notifications:
  420. ```
  421. register_webhook(url="https://example.com/hook", events=["job.completed", "print.failed"])
  422. ```
  423. Payloads are signed with HMAC-SHA256 when a secret is provided. Redirects are blocked by default (`KILN_WEBHOOK_ALLOW_REDIRECTS=0`); when enabled, each hop is SSRF-validated and HTTPS→HTTP downgrade is blocked.
  424. ### Printer discovery
  425. ```bash
  426. kiln discover # mDNS/Bonjour + HTTP subnet probing
  427. ```
  428. Finds OctoPrint, Moonraker/Creality, Bambu, Elegoo, and Prusa Link printers. If discovery returns nothing, register directly by IP with `kiln auth`.
  429. ### Third-party plugins
  430. Entry-point plugins are **default-deny** in production (`KILN_PLUGIN_POLICY=strict`). Allow specific plugins with `KILN_ALLOWED_PLUGINS=my_plugin,other_plugin`, or set `KILN_PLUGIN_POLICY=permissive` for temporary migration compatibility.
  431. </details>
  432. <details>
  433. <summary><strong>Modules (for contributors)</strong></summary>
  434. | Module | Description |
  435. |---|---|
  436. | `server.py` | MCP server with tools, resources, and subsystem wiring |
  437. | `printers/` | Printer adapter abstraction (OctoPrint, Moonraker, Creality, Bambu, Prusa Link, Elegoo) |
  438. | `marketplaces/` | Model marketplace adapters (MyMiniFactory, Cults3D, Thingiverse, metadata-only sources) |
  439. | `slicer.py` | Slicer integration (PrusaSlicer, OrcaSlicer, BambuStudio) with auto-detection |
  440. | `registry.py` | Fleet registry for multi-printer management |
  441. | `queue.py` | Priority job queue with status tracking |
  442. | `scheduler.py` | Background job dispatcher with history-based smart routing |
  443. | `events.py` | Pub/sub event bus with history |
  444. | `persistence.py` | SQLite storage for jobs, events, and settings |
  445. | `webhooks.py` | Event-driven webhook delivery with HMAC signing |
  446. | `auth.py` | Optional API key authentication with scope-based access |
  447. | `discovery.py` | Network printer discovery (mDNS + HTTP probe) |
  448. | `generation/` | Text-to-model generation providers (Meshy, Tripo3D, Stability AI, Gemini Deep Think, OpenSCAD) with auto-discovery, mesh validation, and printability analysis |
  449. | `consumer.py` | Consumer workflow for non-printer users (address validation, material recommendations, timeline/price estimation, onboarding) |
  450. | `cost_estimator.py` | Print cost estimation from G-code analysis |
  451. | `materials.py` | Multi-material and spool tracking |
  452. | `material_inventory.py` | Fleet material inventory and assignment tracking |
  453. | `bed_leveling.py` | Automated bed leveling trigger system |
  454. | `streaming.py` | MJPEG webcam streaming proxy |
  455. | `cloud_sync.py` | Cloud sync for printer configs and job history |
  456. | `plugin_loader.py` | Internal tool-plugin discovery and registration |
  457. | `plugins/` | Focused MCP tool modules loaded by the plugin loader |
  458. | `gcode.py` | G-code safety validator with per-printer limits |
  459. | `gcode_interceptor.py` | Rule-based G-code interception and safety rewriting |
  460. | `safety_profiles.py` | Per-printer safety limits (temps, feedrates, flow) for every supported model, served per printer from Kiln's catalogue, over a bundled generic floor for any other machine |
  461. | `slicer_profiles.py` | Bundled slicer profiles (auto-generates .ini files per printer) |
  462. | `printer_intelligence.py` | Printer roster and spec sheets: each machine's limits, per-material temperatures and motion facts, with the spec sheet served per printer from Kiln's catalogue (curated quirks, calibration recipes and failure modes are in Kiln Pro) |
  463. | `pipelines.py` | Pre-validated print pipelines (quick_print, calibrate, benchmark) |
  464. | `assembly.py` | Multi-part assembly validation and manual planning support |
  465. | `design_versions.py` | Local design history, version records, diffs, and rollback primitives |
  466. | `mesh_validation_pipeline.py` | Multi-gate printability validation pipeline |
  467. | `model_visualizer.py` | Local model preview rendering |
  468. | `tool_schema.py` | OpenAI function-calling schema converter (MCP → OpenAI format) |
  469. | `tool_tiers.py` | Tool tier definitions (essential/standard/full) for model capability matching |
  470. | `agent_loop.py` | Generic agent loop for any OpenAI-compatible API (OpenRouter, direct, etc.) |
  471. | `openrouter.py` | OpenRouter integration with model catalog and auto-tier detection |
  472. | `data/` | Bundled JSON databases (safety profiles, slicer profiles, printer intelligence) |
  473. | `heater_watchdog.py` | Auto-cooldown watchdog for idle heaters |
  474. | `wallets.py` | Crypto wallet configuration (Solana/Ethereum for donations and fees) |
  475. | `pro_tool_manifest.json` | Public manifest for kiln-pro tool discovery and REST proxy stubs |
  476. | `decoration_quota.py` | Free-tier decoration quota tracking and tier resolution hooks |
  477. | `cli/` | Click CLI with <!-- KILN_CLI_COUNT:OLD --> 253 commands and JSON output |
  478. kiln-pro ([kiln3d.com](https://kiln3d.com/?utm_source=github&utm_medium=readme)) extends public Kiln with paid-tier REST serving, billing, licensing, SSO, RBAC, G-code encryption, uptime reporting, team administration, and project-cost workflows. Public Kiln exposes only the interface/proxy surface for those capabilities; the private implementation stays in kiln-pro.
  479. </details>
  480. ## Documentation
  481. | Document | Description |
  482. |----------|-------------|
  483. | [Project Docs](https://www.kiln3d.com/docs?utm_source=github&utm_medium=readme) | Complete reference (CLI, MCP tools, adapters, config) |
  484. <details>
  485. <summary>Brand assets</summary>
  486. Logo files live in [`docs/assets/`](docs/assets/) — all vector SVG, scale to any size.
  487. | File | Use |
  488. |------|-----|
  489. | `kiln-banner-1280x640.svg` / `kiln-banner-1280x640-light.svg` | GitHub / social media banner (dark / light scheme) |
  490. | `kiln-logo-dark.svg` / `kiln-logo-light.svg` | Primary mark + wordmark (dark / light bg) |
  491. | `kiln-horizontal-dark.svg` / `kiln-horizontal-light.svg` | Horizontal lockup (dark / light bg) |
  492. | `kiln-logo-dark-notext.svg` | Mark only (dark bg) |
  493. | `kiln-favicon-256.svg` | Favicon / app icon |
  494. | `kiln-logo-transparent.svg` / `kiln-logo-transparent-dark.svg` | Transparent bg (for dark / light UIs) |
  495. | `kiln-mark-1024.svg` | Square mark tile — profile picture, app tile (1024×1024) |
  496. | `kiln-x-header-1500x500.svg` | Social header (1500×500) |
  497. | `wallpapers/kiln-wallpaper-iphone-*.svg` | iPhone wallpapers |
  498. | `wallpapers/kiln-wallpaper-macbook-*.svg` | MacBook wallpapers |
  499. Every file above is generated from one geometry, so the mark is identical across
  500. all of them. Please don't redraw it — scale the vector instead.
  501. </details>
  502. ## Support Development
  503. Kiln is free, open-source software. If you find it useful, consider sending a tip:
  504. - **Solana:** `kiln3d.sol`
  505. - **Ethereum:** `kiln3d.eth`
  506. ## Positioning
  507. > **Messaging clarification (February 24, 2026):** We clarified wording to remove ambiguity and align with existing intent; no strategy change. Kiln is orchestration and agent infrastructure for fabrication workflows. Kiln does **not** operate a first-party decentralized manufacturing marketplace/network. Kiln integrates with third-party providers and external provider/network adapters as integrations are available.
  508. **Non-goals:** operating a first-party decentralized manufacturing marketplace/network; replacing partner supply-side networks; owning provider marketplaces instead of integrating with them; acting as merchant of record for provider-routed manufacturing orders.
  509. ## License
  510. Kiln is a project of **Hadron Labs Inc.**
  511. [AGPL-3.0 License](LICENSE) — open source with copyleft. [Commercial licensing](policies/COMMERCIAL_LICENSE.md) available for companies that need proprietary use.
  512. By contributing, you agree to the [Contributor License Agreement](policies/CONTRIBUTOR_LICENSE_AGREEMENT.md).
  513. ---
  514. Also listed on [Smithery](https://smithery.ai/servers/codeofaxel/kiln) and LobeHub: [![MCP Badge](https://lobehub.com/badge/mcp/codeofaxel-kiln)](https://lobehub.com/mcp/codeofaxel-kiln)
  515. ## Trademarks
  516. [OctoPrint is a registered trademark](https://octoprint.org). Other product and company names are trademarks of their respective owners; Kiln is not affiliated with or endorsed by them.
kiln/src/kiln/cli/auth_commands.py · Bundled script · 1,368 lines · 1 finding marked
  1. """``kiln signin`` / ``kiln signout`` / ``kiln whoami`` / ``kiln pair`` /
  2. ``kiln link`` — the CLI's device-code OAuth flow + bidirectional pairing
  3. against the Kiln REST API.
  4. How the login flow works end-to-end:
  5. 1. ``kiln signin`` POSTs ``/api/auth/device/start``. Gets back a
  6. ``device_code`` (secret), a ``user_code`` (human-typeable), and a
  7. ``verification_uri`` (URL to open in the browser).
  8. 2. CLI prints the ``user_code`` + URL, opens the URL in the user's
  9. default browser (unless ``--no-browser``), and starts polling
  10. ``/api/auth/device/poll`` every ``interval`` seconds.
  11. 3. User picks a provider on the browser page (Google / Apple / GitHub),
  12. completes the OAuth flow with Supabase. The Supabase redirect
  13. lands on our ``/auth/device/callback`` page, which JS-side fetches
  14. the user and POSTs ``/api/auth/device/claim`` so the server can
  15. mark the row as ``status=success`` + stash the tokens.
  16. 4. The next poll from the CLI returns ``{status: success,
  17. access_token, refresh_token, tier, email}``.
  18. 5. CLI writes the tokens to ``~/.kiln/auth_tokens.json`` (mode 0600)
  19. and prints ``Signed in as {email} ({tier})``.
  20. ``kiln signout`` removes this computer from the account (for a machine
  21. credential) and deletes the token file.
  22. ``kiln whoami`` renews the sign-in if it needs it, hits ``GET
  23. /api/auth/whoami``, and prints the resolved email + tier (and, for a
  24. machine credential, which computer this is on the account).
  25. What a sign-in door asks for is a machine credential of this computer's
  26. own (``kiln.auth_session.machine_signin_request``): a sign-in Kiln issues
  27. to the computer, which nothing done in a browser can end. A server that
  28. predates them answers with a session, stored exactly as before.
  29. ``kiln pair <code>`` is the web-initiated mirror of ``kiln signin`` —
  30. the user has already signed in on app.kiln3d.com; this command claims
  31. a short-lived pairing code and writes the tokens locally without a
  32. second browser round-trip.
  33. All four commands talk ONLY to the public Kiln REST API at
  34. ``https://api.kiln3d.com`` (override with ``KILN_API_URL`` for local
  35. dev). No proprietary logic lives here — they ship in the public
  36. ``kiln`` package so ``pip install kiln3d && kiln pair <code>`` works
  37. out-of-the-box on a clean machine without requiring kiln-pro.
  38. The file is JSON not YAML so that ops can eyeball it without a parser
  39. dependency and so third-party tooling can read tier without depending
  40. on any Kiln package at all.
  41. """
  42. from __future__ import annotations
  43. import contextlib
  44. import json
  45. import os
  46. import stat
  47. import sys
  48. import time
  49. from pathlib import Path
  50. from typing import Any
  51. import click
  52. from kiln import run_program
  53. # Default API base — override with ``KILN_API_URL`` for local dev.
  54. def _api_base() -> str:
  55. return (os.environ.get("KILN_API_URL") or "https://api.kiln3d.com").rstrip("/")
  56. # How the sign-in poll rides out a stretch when Kiln's servers cannot be
  57. # reached (see the loop in ``auth_login``). Each failed tick waits twice as
  58. # long as the last, up to this cap, so an outage is not hammered yet a
  59. # recovered connection is noticed within half a minute.
  60. _POLL_OUTAGE_MAX_WAIT_S = 30.0
  61. # The notice on stderr waits for this many failed ticks in a row: one lost
  62. # request is a blip the person never needs to hear about.
  63. _POLL_OUTAGE_NOTICE_AFTER = 3
  64. # Give up once the servers have been out of reach for this long without a
  65. # single answered tick. Long enough to cover a router reboot or a change
  66. # of Wi-Fi, short enough that nobody stares at a dead terminal for the rest
  67. # of the device code's lifetime.
  68. _POLL_OUTAGE_GIVE_UP_S = 120.0
  69. def _tokens_path() -> Path:
  70. """Where we persist the access + refresh token. Per-user, tight
  71. permissions. ``$KILN_AUTH_HOME`` lets tests redirect the path
  72. without monkeypatching ``Path.home``."""
  73. home = os.environ.get("KILN_AUTH_HOME") or str(Path.home())
  74. return Path(home) / ".kiln" / "auth_tokens.json"
  75. def _write_tokens(data: dict[str, Any]) -> None:
  76. """Atomic + 0600. Create the directory with 0700 perms first so
  77. we never leave an intermediate mode-wide-open file on disk."""
  78. path = _tokens_path()
  79. path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
  80. tmp = path.with_suffix(".tmp")
  81. tmp.write_text(json.dumps(data, indent=2, sort_keys=True), encoding="utf-8")
  82. with contextlib.suppress(OSError):
  83. os.chmod(tmp, stat.S_IRUSR | stat.S_IWUSR) # 0600
  84. tmp.replace(path)
  85. def _record_signin_stage(stage: str) -> None:
  86. """Count a sign-in funnel stage (``daily_stats.record_account_nudge``).
  87. Never raises: a sign-in must not fail over its own counter.
  88. """
  89. try:
  90. from kiln.daily_stats import record_account_nudge
  91. record_account_nudge(stage)
  92. except Exception: # noqa: BLE001
  93. pass
  94. def _complete_signin(data: dict[str, Any], *, door: str = "other") -> None:
  95. """Store a new sign-in, then hand the account this install's agreement to
  96. the Terms.
  97. Every door that signs a person in on this machine ends here — ``kiln
  98. signin``, ``kiln pair`` and the in-chat ``kiln_signin_poll`` — so an
  99. agreement made on the machine before it was signed in reaches the account
  100. the moment one exists, not on the first hosted call that gets refused
  101. without it. The hand-off is best-effort: a sign-in never fails over it,
  102. and a refused hosted call still makes it (``server._pro_api_call``).
  103. ``door`` names which way in it was (``chat`` / ``cli`` / ``pair``), counted
  104. here because this is the one function every door ends in: a fourth door
  105. still counts, as ``completed_other``, instead of going unseen. A machine
  106. that still held a session is also counted ``completed_returning``, so a
  107. lapsed owner signing back in is never read as a new account; one that
  108. was shown a limits nudge at a printer's setup within the day is also
  109. counted ``completed_limits``.
  110. """
  111. try:
  112. held = _read_tokens()
  113. returning = bool(held.get("access_token") or held.get("refresh_token"))
  114. except Exception: # noqa: BLE001
  115. returning = False
  116. _write_tokens(data)
  117. _record_signin_stage(
  118. f"completed_{door}" if door in ("chat", "cli", "pair") else "completed_other"
  119. )
  120. if returning:
  121. _record_signin_stage("completed_returning")
  122. # A limits nudge shown at a printer's setup (``safety_profiles.warm_profile``)
  123. # waits for this moment in a marker on disk, because it was minted in the
  124. # MCP server process and this sign-in may be finishing in another: counted
  125. # ``completed_limits`` when the nudge was within a day, nothing otherwise.
  126. try:
  127. from kiln.daily_stats import record_limits_nudge_conversion
  128. record_limits_nudge_conversion()
  129. except Exception: # noqa: BLE001 -- a sign-in never fails over its counter
  130. pass
  131. # And in THIS process the catalogue bridge forgets the signed-out misses,
  132. # so the next ask for a printer's record goes to the servers at once
  133. # rather than after its retry wait -- the in-chat door (kiln_signin_poll)
  134. # ends here in the same process that will now answer for the printers.
  135. try:
  136. from kiln._pro_catalogue_bridge import forget
  137. forget()
  138. except Exception: # noqa: BLE001
  139. pass
  140. # The printer question likewise forgets what it was told while signed
  141. # out, so the next ending asks the servers for the account now signed in.
  142. try:
  143. from kiln._pro_printer_checkin_bridge import forget as forget_checkins
  144. forget_checkins()
  145. except Exception: # noqa: BLE001
  146. pass
  147. from kiln import terms
  148. # A sign-in never fails over either terms hand-off below.
  149. with contextlib.suppress(Exception):
  150. terms.sync_to_account(bearer=str(data.get("access_token") or ""))
  151. # And the other direction: an agreement the account already holds, made
  152. # on another device, is brought onto this machine now, so the very next
  153. # command runs instead of asking the person to agree a second time. The
  154. # sign-in that just landed is the bearer ``is_current`` resolves from the
  155. # file; forcing the server past the recheck throttle matters because a
  156. # stale local record may have been checked minutes ago with a dead token.
  157. with contextlib.suppress(Exception):
  158. terms.is_current(force_server=True)
  159. def _read_tokens() -> dict[str, Any]:
  160. path = _tokens_path()
  161. if not path.exists():
  162. return {}
  163. try:
  164. return json.loads(path.read_text(encoding="utf-8"))
  165. except Exception:
  166. return {}
  167. def _delete_tokens() -> bool:
  168. path = _tokens_path()
  169. if not path.exists():
  170. return False
  171. path.unlink()
  172. # Served motion plans are kept for the signed-in account; they leave
  173. # with it, so the next account on this machine starts with none.
  174. try:
  175. from kiln.printers.motion_plan_cache import forget_all
  176. forget_all()
  177. except Exception: # noqa: BLE001 -- a sign-out never fails over a cache
  178. pass
  179. return True
  180. class _ApiUnavailable(click.ClickException):
  181. """Kiln's servers could not be reached, or answered that they are
  182. unwell (5xx) -- the one kind of failure worth asking again about a
  183. moment later.
  184. Still a ``ClickException``, so a caller that does not care gets the
  185. same one-line exit as before; a caller that can afford to wait out a
  186. blip (the sign-in poll loop) catches this one and lets everything
  187. else -- a bad request, a non-JSON answer, a refused bearer -- end the
  188. command as it always has.
  189. """
  190. def _http_post(
  191. path: str,
  192. body: dict[str, Any],
  193. *,
  194. bearer: str | None = None,
  195. timeout: float = 15.0,
  196. ) -> dict[str, Any]:
  197. """Thin requests.post wrapper that returns a dict or raises
  198. click.ClickException with a human message. Keeping the HTTP
  199. surface tiny (no retry, no session reuse) because these endpoints
  200. are called at most a few dozen times across the whole flow; the one
  201. caller that has to outlive a network blip (the sign-in poll) retries
  202. on its own by catching ``_ApiUnavailable``.
  203. ``bearer`` is keyword-only so every existing call site (all
  204. unauthenticated pairing/login endpoints) keeps working unchanged;
  205. only authed callers like ``kiln link`` opt in."""
  206. try:
  207. import requests # type: ignore[import-untyped]
  208. except ImportError as exc: # pragma: no cover — requests is a hard dep
  209. raise click.ClickException(
  210. "The `requests` package is required for `kiln signin`. "
  211. "Install with `pip install requests`."
  212. ) from exc
  213. headers = {"User-Agent": f"kiln-cli/{_cli_version()}"}
  214. if bearer:
  215. headers["Authorization"] = f"Bearer {bearer}"
  216. try:
  217. resp = requests.post(
  218. f"{_api_base()}{path}",
  219. json=body,
  220. timeout=timeout,
  221. headers=headers,
  222. )
  223. except requests.exceptions.ConnectionError as exc:
  224. raise _ApiUnavailable(
  225. f"Could not reach Kiln API at {_api_base()} — is the server up?"
  226. ) from exc
  227. except requests.exceptions.Timeout as exc:
  228. raise _ApiUnavailable(
  229. f"Timed out reaching {_api_base()}{path}."
  230. ) from exc
  231. except requests.exceptions.RequestException as exc:
  232. # Everything else requests can raise on the wire -- a connection
  233. # reset partway through the body (ChunkedEncodingError, seen on
  234. # Windows), a protocol hiccup -- is the same kind of passing
  235. # trouble, and must never surface as a raw traceback mid-poll.
  236. raise _ApiUnavailable(
  237. f"Connection to {_api_base()} dropped mid-request "
  238. f"({exc.__class__.__name__})."
  239. ) from exc
  240. if bearer and resp.status_code == 401:
  241. # Only surface 401 as a terminal error when an Authorization
  242. # header was actually sent. Unauthenticated callers (the
  243. # device-flow / pairing-claim endpoints) never expect 401 and
  244. # continue to signal success/failure via the JSON body — hiding
  245. # that under a blanket 401 branch would break the login flow.
  246. raise click.ClickException(
  247. "Your session is not accepted by the Kiln API (HTTP 401). "
  248. "Run `kiln signin` to refresh, then retry."
  249. )
  250. if resp.status_code >= 500:
  251. raise _ApiUnavailable(
  252. f"Kiln API returned {resp.status_code} for {path}. "
  253. "Try again in a moment; if it persists, email adam@kiln3d.com."
  254. )
  255. try:
  256. return resp.json()
  257. except ValueError as exc:
  258. raise click.ClickException(
  259. f"Kiln API returned non-JSON for {path}: {resp.text[:200]}"
  260. ) from exc
  261. def _http_get(path: str, *, bearer: str | None = None, timeout: float = 10.0) -> tuple[int, dict[str, Any]]:
  262. try:
  263. import requests # type: ignore[import-untyped]
  264. except ImportError as exc: # pragma: no cover
  265. raise click.ClickException("The `requests` package is required.") from exc
  266. headers = {"User-Agent": f"kiln-cli/{_cli_version()}"}
  267. if bearer:
  268. headers["Authorization"] = f"Bearer {bearer}"
  269. try:
  270. resp = requests.get(f"{_api_base()}{path}", headers=headers, timeout=timeout)
  271. except requests.exceptions.ConnectionError as exc:
  272. raise click.ClickException(f"Could not reach {_api_base()}.") from exc
  273. try:
  274. return resp.status_code, resp.json()
  275. except ValueError:
  276. return resp.status_code, {}
  277. def _cli_version() -> str:
  278. try:
  279. from kiln import __version__
  280. return __version__
  281. except Exception:
  282. return "dev"
  283. # ═════════════════════════════════════════════════════════════════════
  284. # `kiln signin` (also aliased as `kiln signin` for backwards compat)
  285. # ═════════════════════════════════════════════════════════════════════
  286. @click.command("signin")
  287. @click.option(
  288. "--no-browser", is_flag=True, default=False,
  289. help="Don't open the browser automatically. Print the URL and wait.",
  290. )
  291. @click.option(
  292. "--timeout", type=int, default=900, show_default=True,
  293. help="Max seconds to wait for the user to complete the browser step.",
  294. )
  295. @click.option(
  296. # Hidden on purpose: `--provider` is NOT a real flag here. It's the
  297. # natural wrong guess (account sign-in vs. linking a GitHub identity
  298. # for signing are different things), so instead of Click's bare
  299. # "No such option: --provider" we catch it and redirect to the right
  300. # command. Hidden so it never appears in --help and the canonical
  301. # flag set stays {--no-browser, --timeout}.
  302. "--provider", "provider", default=None, hidden=True,
  303. )
  304. def auth_login(no_browser: bool, timeout: int, provider: str | None) -> None:
  305. """Sign in to your Kiln account via OAuth (Google / Apple / GitHub).
  306. This is KILN ACCOUNT AUTHENTICATION — use this to log in to the
  307. Kiln REST API + workshop as yourself. If you want to "log in to
  308. Kiln", this is the command. Connecting a GitHub identity for
  309. signing design releases is a different thing, and is not this.
  310. Launches the device-code flow: opens your browser to a small
  311. provider-picker page, polls until you finish signing in, then
  312. writes your session token to ``~/.kiln/auth_tokens.json``.
  313. The rest of the CLI will pick up your session automatically — no
  314. license key needed for OAuth-linked Pro+ accounts. Backwards-compat
  315. alias: ``kiln login`` (same command, same flow).
  316. """
  317. # `--provider` isn't an option for account sign-in (this command picks
  318. # the provider for you on the browser page). Say so and bail WITHOUT
  319. # signing in, so we never half-start a device flow the user didn't mean
  320. # to run. No other command is named: none on a plain install links an
  321. # identity today, and a pointer to a command the person lacks is worse
  322. # than none (tests/test_auth_commands.py pins it).
  323. if provider is not None:
  324. click.echo(
  325. "`--provider` isn't an option for `kiln login` (that's account "
  326. "sign-in, which picks the provider for you in the browser). "
  327. "Run `kiln signin` to sign in.",
  328. err=True,
  329. )
  330. sys.exit(2)
  331. # 1) Start the device flow, asking for this computer's own machine
  332. # credential under the name /settings/agent will list it by.
  333. from kiln.auth_session import machine_signin_request
  334. try:
  335. start = _http_post(
  336. "/api/auth/device/start",
  337. machine_signin_request(_detect_client_name() or "Kiln CLI", label=_hostname_label()),
  338. )
  339. except Exception:
  340. _record_signin_stage("start_failed")
  341. raise
  342. if not start.get("success"):
  343. _record_signin_stage("start_failed")
  344. raise click.ClickException(
  345. start.get("error") or "Could not start the sign-in flow."
  346. )
  347. _record_signin_stage("started_cli")
  348. device_code = start["device_code"]
  349. user_code = start["user_code"]
  350. verification_uri = start["verification_uri"]
  351. interval = max(1, int(start.get("interval") or 2))
  352. expires_in = int(start.get("expires_in") or 900)
  353. deadline = time.monotonic() + min(timeout, expires_in)
  354. # 2) Try to open the browser FIRST. The verification URL carries
  355. # the user_code as a query param, so when the browser opens the
  356. # human lands on the provider picker with nothing to type. We
  357. # only fall back to showing the raw URL / code when auto-open
  358. # fails — most users (normies, agents, devs alike) never see
  359. # the code. Hiding device-flow implementation details is the
  360. # biggest single UX win over the classic "paste this code"
  361. # pattern.
  362. browser_opened = False
  363. if not no_browser:
  364. try:
  365. browser_opened = run_program.open_url(verification_uri, new=1, autoraise=True)
  366. except Exception:
  367. browser_opened = False
  368. click.echo("", err=True)
  369. if browser_opened:
  370. click.echo(" Opening your browser to sign in\u2026", err=True)
  371. else:
  372. # Fallback path — no browser auto-open (--no-browser, headless
  373. # machine, sandboxed CLI). URL is primary; code is the
  374. # last-resort affordance shown in a muted secondary line.
  375. click.echo(" Open this URL to sign in:", err=True)
  376. click.echo("", err=True)
  377. click.echo(f" {verification_uri}", err=True)
  378. click.echo("", err=True)
  379. click.echo(
  380. f" If the page asks you to confirm a code, it\u2019s {user_code}",
  381. err=True,
  382. )
  383. click.echo("", err=True)
  384. # 3) Poll with a subtle braille spinner so the terminal feels
  385. # alive during the 5–30s most users take in the browser.
  386. # TTY-gated so piping to a log file (or CI) produces static,
  387. # greppable output instead of a carriage-return salad.
  388. result: dict[str, Any] = {}
  389. spinner_frames = "\u2807\u2811\u2813\u2817\u2837\u2836\u2834\u2830\u2820\u2800"
  390. is_tty = bool(getattr(sys.stderr, "isatty", lambda: False)())
  391. tick = 0
  392. if is_tty:
  393. click.echo(
  394. f" {spinner_frames[0]} Waiting for you to finish in the browser\u2026",
  395. nl=False, err=True,
  396. )
  397. else:
  398. click.echo(" Waiting for you to finish in the browser\u2026", err=True)
  399. # A poll tick that cannot reach Kiln is not the end of the sign-in. The
  400. # person is in a browser tab that is about to claim this device code, and
  401. # one dropped connection on this side -- a laptop changing Wi-Fi, a home
  402. # router hiccup, a proxy restart -- must not end the command with "is the
  403. # server up?" and throw the code away while the server never missed a
  404. # request. So a tick that fails is simply tried again, waiting a little
  405. # longer each time, and the command only gives up when the browser flow's
  406. # own deadline passes or the servers have been out of reach for minutes
  407. # on end. The start request is different: a server that is down is
  408. # better said at once than discovered after a wait.
  409. wait = interval
  410. failures = 0
  411. outage_began: float | None = None
  412. notice_shown = False
  413. while time.monotonic() < deadline:
  414. time.sleep(min(wait, max(0.0, deadline - time.monotonic())))
  415. try:
  416. poll = _http_post("/api/auth/device/poll", {"device_code": device_code})
  417. except _ApiUnavailable as exc:
  418. now = time.monotonic()
  419. failures += 1
  420. if outage_began is None:
  421. outage_began = now
  422. if now - outage_began >= _POLL_OUTAGE_GIVE_UP_S:
  423. if is_tty:
  424. click.echo("\r" + " " * 60 + "\r", nl=False, err=True)
  425. _record_signin_stage("poll_unreachable")
  426. raise click.ClickException(
  427. "Could not reach Kiln's servers for about two minutes, so this "
  428. "sign-in was abandoned. Check your connection and run "
  429. "`kiln signin` again."
  430. ) from exc
  431. # Say something only once a blip has outlasted a couple of ticks:
  432. # a single dropped request is not worth a line of alarm.
  433. if failures == _POLL_OUTAGE_NOTICE_AFTER and not notice_shown:
  434. notice_shown = True
  435. if is_tty:
  436. click.echo("\r" + " " * 60 + "\r", nl=False, err=True)
  437. click.echo(
  438. " Lost contact with Kiln\u2019s servers, still trying\u2026",
  439. err=True,
  440. )
  441. if is_tty:
  442. click.echo(
  443. f" {spinner_frames[tick % len(spinner_frames)]} "
  444. "Waiting for you to finish in the browser\u2026",
  445. nl=False, err=True,
  446. )
  447. wait = min(wait * 2, _POLL_OUTAGE_MAX_WAIT_S)
  448. continue
  449. if failures:
  450. # Back in touch: poll at the browser flow's own pace again, and
  451. # close the notice so the person knows nothing was lost.
  452. failures = 0
  453. outage_began = None
  454. wait = interval
  455. if notice_shown:
  456. notice_shown = False
  457. if is_tty:
  458. click.echo("\r" + " " * 60 + "\r", nl=False, err=True)
  459. click.echo(" Back in touch with Kiln\u2019s servers.", err=True)
  460. if is_tty:
  461. click.echo(
  462. f" {spinner_frames[tick % len(spinner_frames)]} "
  463. "Waiting for you to finish in the browser\u2026",
  464. nl=False, err=True,
  465. )
  466. status = str(poll.get("status") or "pending").lower()
  467. if status == "pending":
  468. if is_tty:
  469. tick += 1
  470. frame = spinner_frames[tick % len(spinner_frames)]
  471. click.echo(
  472. f"\r {frame} Waiting for you to finish in the browser\u2026",
  473. nl=False, err=True,
  474. )
  475. continue
  476. result = poll
  477. break
  478. else:
  479. if is_tty:
  480. click.echo("\r" + " " * 60 + "\r", nl=False, err=True)
  481. _record_signin_stage("timed_out")
  482. if failures:
  483. # The wait ran out while Kiln's servers were out of reach, so the
  484. # browser may well have finished; say which it was.
  485. raise click.ClickException(
  486. "Sign-in timed out while Kiln's servers were out of reach, so "
  487. "this terminal could not see whether you finished in the "
  488. "browser. Check your connection and run `kiln signin` again."
  489. )
  490. raise click.ClickException(
  491. "Sign-in timed out before the browser flow completed. "
  492. "Run `kiln signin` again."
  493. )
  494. # Clear the spinner line cleanly before printing the final verdict.
  495. if is_tty:
  496. click.echo("\r" + " " * 60 + "\r", nl=False, err=True)
  497. status = str(result.get("status") or "").lower()
  498. if status == "success":
  499. from kiln.auth_session import credential_fields
  500. email = str(result.get("email") or "")
  501. tier = str(result.get("tier") or "free").lower()
  502. _complete_signin({
  503. "access_token": result.get("access_token") or "",
  504. "refresh_token": result.get("refresh_token") or "",
  505. "email": email,
  506. "auth_uid": result.get("auth_uid") or "",
  507. "tier": tier,
  508. "has_entitlement": bool(result.get("has_entitlement")),
  509. "signed_in_at": int(time.time()),
  510. **credential_fields(result),
  511. }, door="cli")
  512. # Final confirmation on stdout (not stderr) so ``kiln login
  513. # | tail -1`` captures it. Ember-coloured checkmark +
  514. # lowercase "you're in" matches the workshop's signin copy
  515. # and the /auth/device page's h1 — three surfaces, one voice.
  516. click.echo(f"\u2713 You\u2019re in \u2014 {email} ({tier}).")
  517. return
  518. if status == "denied":
  519. # User cancelled in the browser (e.g. picked a provider, got
  520. # to the consent screen, hit back). Quiet exit, no scolding.
  521. _record_signin_stage("denied")
  522. raise click.ClickException(
  523. result.get("message") or "Sign-in was cancelled in the browser."
  524. )
  525. if status == "expired":
  526. _record_signin_stage("expired")
  527. raise click.ClickException(
  528. result.get("message") or "Sign-in code expired. Run `kiln signin` again."
  529. )
  530. raise click.ClickException(f"Unexpected sign-in status: {status!r}")
  531. # ═════════════════════════════════════════════════════════════════════
  532. # `kiln signout` (also aliased as `kiln logout` for backwards compat)
  533. # ═════════════════════════════════════════════════════════════════════
  534. @click.command("signout")
  535. def auth_logout() -> None:
  536. """Sign this computer out of Kiln.
  537. A computer on its own machine sign-in is also removed from your account
  538. (app.kiln3d.com/settings/agent), so nothing is left behind that nobody
  539. holds. Your other computers and your browser stay signed in.
  540. """
  541. from kiln.auth_session import holds_machine_credential, revoke_machine_credential
  542. tokens = _read_tokens()
  543. removed = False
  544. if holds_machine_credential(tokens):
  545. removed = revoke_machine_credential()
  546. if _delete_tokens():
  547. if removed:
  548. click.echo("Signed out. This computer was removed from your Kiln account.")
  549. elif holds_machine_credential(tokens):
  550. click.echo(
  551. "Signed out on this computer. Kiln couldn't be reached to remove it from "
  552. "your account, so it may still be listed at app.kiln3d.com/settings/agent; "
  553. "removing it there finishes the job."
  554. )
  555. else:
  556. click.echo("Signed out. Token file removed.")
  557. else:
  558. click.echo("You weren't signed in.")
  559. # ═════════════════════════════════════════════════════════════════════
  560. # `kiln whoami`
  561. # ═════════════════════════════════════════════════════════════════════
  562. @click.command("whoami")
  563. @click.option(
  564. "--json", "as_json", is_flag=True, default=False,
  565. help="Emit the full whoami response as JSON instead of a human summary.",
  566. )
  567. def auth_whoami(as_json: bool) -> None:
  568. """Show who you're signed in as + your current tier.
  569. Hits ``GET /api/auth/whoami`` with your saved access_token and
  570. prints the tier + email the server resolves. Useful when the
  571. local cache might be out of date (e.g. right after an upgrade in
  572. the Stripe portal).
  573. """
  574. from kiln.auth_session import resolve_session_bearer
  575. # Renewed first when it needs it: a machine credential's access token
  576. # lives about fifteen minutes, and "session expired" for a sign-in that
  577. # renews itself would be untrue.
  578. session = resolve_session_bearer()
  579. if not session.token:
  580. if session.state == "needs_signin" and session.detail:
  581. # Ended, and the detail says how (removed, found in use in two
  582. # places, an org seat that ended) — not merely "not signed in".
  583. raise click.ClickException(f"{session.detail} Run `kiln signin` to sign in again.")
  584. raise click.ClickException("Not signed in. Run `kiln signin` to sign in.")
  585. code, body = _http_get("/api/auth/whoami", bearer=session.token)
  586. if str(body.get("reason") or "") == "auth_upstream_unavailable":
  587. # The API could not check the sign-in (a 401 for a session, a 503 for
  588. # a machine credential): its servers did not answer, and the sign-in
  589. # itself is fine. "Sign in again" would send the person after the
  590. # wrong fix.
  591. raise click.ClickException(
  592. "Kiln's servers didn't answer just now, so your sign-in couldn't be "
  593. "checked. You're still signed in; try again in a minute."
  594. )
  595. if code == 401:
  596. raise click.ClickException(
  597. str(body.get("message") or "Session expired.") + " Run `kiln signin` to sign in again."
  598. )
  599. if code >= 400 or not body.get("success"):
  600. raise click.ClickException(
  601. body.get("error") or f"whoami failed (HTTP {code})"
  602. )
  603. email = str(body.get("email") or "")
  604. tier = str(body.get("tier") or "free").lower()
  605. status = str(body.get("status") or "").lower()
  606. expires = str(body.get("expires_at") or "")
  607. # Write the fresh server-resolved tier back to the token cache so
  608. # any LicenseManager (which reads this file) picks up tier changes
  609. # immediately after ``kiln whoami`` instead of waiting for its own
  610. # 24h auto-refresh. Useful right after a Stripe upgrade: run
  611. # ``kiln whoami``, then every local tool sees the new tier.
  612. # Read only now: another Kiln process may have renewed the sign-in while
  613. # the server answered, and writing back a copy read before the call would
  614. # put the superseded secret on disk. The next renewal would present it,
  615. # which the server reads as this computer's sign-in in use in two places.
  616. tokens = _read_tokens()
  617. if str(tokens.get("tier") or "").lower() != tier or not tokens.get("signed_in_at"):
  618. tokens["tier"] = tier
  619. tokens["signed_in_at"] = int(time.time())
  620. if email:
  621. tokens["email"] = email
  622. _write_tokens(tokens)
  623. if as_json:
  624. click.echo(json.dumps(body, indent=2, sort_keys=True))
  625. return
  626. click.echo(f"Email: {email}")
  627. click.echo(f"Tier: {tier}")
  628. if status and status not in ("none", "active"):
  629. click.echo(f"Status: {status}")
  630. if expires:
  631. click.echo(f"Expires: {expires}")
  632. if body.get("credential") == "machine":
  633. label = str(body.get("machine_label") or "") or "this computer"
  634. click.echo(f"Machine: {label} ({body.get('machine_id') or '?'}) — app.kiln3d.com/settings/agent")
  635. # ═════════════════════════════════════════════════════════════════════
  636. # `kiln pair <code>` — web-initiated pairing
  637. # ═════════════════════════════════════════════════════════════════════
  638. #
  639. # The mirror image of ``kiln signin``: instead of this machine bootstrapping
  640. # an OAuth session from cold, the user has already signed in on the web
  641. # (usually right after upgrading their tier at app.kiln3d.com/checkout/
  642. # success → /connect). The workshop minted a short-lived code tied to
  643. # their session; ``kiln pair <code>`` hands the tokens to this machine
  644. # without any browser round-trip here.
  645. #
  646. # Why this is the preferred post-upgrade path (even though ``kiln signin``
  647. # still works): after paying, the user is already in a browser, already
  648. # signed in. Asking them to run ``kiln signin`` which opens ANOTHER
  649. # browser to sign in AGAIN is a jarring re-authentication. Pairing
  650. # reuses the session they already have in one command.
  651. def _hostname_label() -> str:
  652. """Best-effort human label for this machine, used on the workshop's
  653. paired-machines list. Never fatal — fall back to a generic string
  654. if hostname resolution fails (rare, but it happens in some container
  655. runtimes)."""
  656. try:
  657. import socket as _socket
  658. h = _socket.gethostname()
  659. # Strip ``.local`` and other zeroconf suffixes — users recognize
  660. # ``Adams-MacBook-Pro`` faster than ``Adams-MacBook-Pro.local``.
  661. for suf in (".local", ".lan", ".home"):
  662. if h.endswith(suf):
  663. h = h[: -len(suf)]
  664. return h or "this machine"
  665. except Exception:
  666. return "this machine"
  667. # ---------------------------------------------------------------------
  668. # AI-client identity detection
  669. # ---------------------------------------------------------------------
  670. #
  671. # Two rows that both read "Adams-MBP" on /settings/agent is the exact
  672. # ambiguity this helper exists to resolve. A user running Claude
  673. # Desktop + Claude Code + Cursor on one laptop needs to know which row
  674. # is which before they can meaningfully revoke. ``client_name``
  675. # captures the AI client; ``machine_label`` captures the host.
  676. #
  677. # Priority ladder (highest → lowest):
  678. #
  679. # 1. Explicit ``--client`` flag on the command — user knows best,
  680. # so shortcut the ladder.
  681. # 2. Environment-variable sniff. Most LLM surfaces export a
  682. # distinguishing env var when they spawn an MCP subprocess.
  683. # Order matters: CLAUDE_DESKTOP_SESSION beats CLAUDE_CODE_* because
  684. # a Claude Desktop session that happens to set both is still
  685. # semantically "Claude Desktop."
  686. # 3. Parent-process name (best-effort, Unix only). If env sniff
  687. # missed (older client versions that don't export a session var)
  688. # we try to read the parent's executable name. Only surface a
  689. # well-known set — anything else stays empty rather than leaking
  690. # a meaningless name like ``zsh``.
  691. # 4. Headless detection. If stdin isn't a TTY AND every sniff
  692. # returned nothing, assume this is an MCP-launched subprocess
  693. # with no distinguishing identity. "Unspecified (MCP)" beats
  694. # an empty string for giving the user a handle to reason about.
  695. # 5. Interactive prompt — the caller handles this when appropriate;
  696. # the helper itself only returns "" so the caller can decide
  697. # whether to prompt.
  698. #
  699. # None of this is security-bearing; it's identification only. A
  700. # malicious client that sets CLAUDE_DESKTOP_SESSION to impersonate a
  701. # Claude Desktop row is defeated by /settings/agent's Revoke button —
  702. # the user sees their OWN list and kicks off anything they don't
  703. # recognise. We just need the labels to be *usually correct* so the
  704. # list is useful in the common case.
  705. # Public map for testing — so test_auth_commands.py can assert the
  706. # priority order without duplicating the env-var names.
  707. _CLIENT_NAME_ENV_SIGNALS: tuple[tuple[str, str], ...] = (
  708. ("CLAUDE_DESKTOP_SESSION", "Claude Desktop"),
  709. ("CLAUDE_CODE_SESSION_ID", "Claude Code"),
  710. ("CURSOR_SESSION", "Cursor"),
  711. ("CURSOR_EDITOR", "Cursor"),
  712. ("CONTINUE_SESSION_ID", "Continue"),
  713. ("CODEX_SESSION_ID", "Codex"),
  714. )
  715. # Parent-process name → canonical client label. Lowercase match on
  716. # the basename so we don't care about ``.app`` suffixes, capitalisation
  717. # variants, or Electron helper names that embed the parent.
  718. _CLIENT_NAME_PROC_SIGNALS: tuple[tuple[str, str], ...] = (
  719. ("claude.app", "Claude Desktop"),
  720. ("claude", "Claude Desktop"),
  721. ("cursor.app", "Cursor"),
  722. ("cursor", "Cursor"),
  723. ("codex", "Codex"),
  724. ("continue", "Continue"),
  725. )
  726. def _sniff_client_from_env() -> str:
  727. """Walk the env-var priority ladder and return the first match.
  728. Kept pure so tests can patch ``os.environ`` without worrying about
  729. process-name side effects.
  730. """
  731. for var, label in _CLIENT_NAME_ENV_SIGNALS:
  732. if os.environ.get(var):
  733. return label
  734. # Generic CLAUDE_CODE_* fallback — new session-variable names ship
  735. # faster than this ladder can track them, so any CLAUDE_CODE_ prefix
  736. # with a non-empty value counts as Claude Code. Isolated to its own
  737. # branch (not a tuple entry) because we need the prefix-match, not
  738. # an equality-match.
  739. for key, value in os.environ.items():
    • Dismissed after review: Copies every environment variable, where API keys and tokens live, in a file that sends data
    • Line 835 on GitHub
  740. if key.startswith("CLAUDE_CODE_") and value:
  741. return "Claude Code"
  742. # VS Code without Cursor indicates the VS Code MCP host, which is
  743. # worth distinguishing from Cursor (they set similar pids but
  744. # different identity env). Placed last so explicit Cursor/Claude
  745. # signals always win.
  746. if os.environ.get("VSCODE_PID") and not os.environ.get("CURSOR_EDITOR"):
  747. return "VS Code"
  748. return ""
  749. def _sniff_client_from_parent_process() -> str:
  750. """Best-effort parent-process name lookup on Unix.
  751. Uses ``ps`` — present on every macOS and Linux install we care
  752. about, including minimal container images. Never raises;
  753. returns empty string on any failure (Windows, locked-down
  754. sandbox, truncated stat, unknown parent name).
  755. """
  756. try:
  757. ppid = os.getppid()
  758. if ppid <= 0:
  759. return ""
  760. # -p: filter by pid; -o comm=: just the executable name, no header.
  761. result = run_program.run(
  762. ["ps", "-p", str(ppid), "-o", "comm="],
  763. capture_output=True, text=True, timeout=2.0,
  764. )
  765. name = (result.stdout or "").strip().lower()
  766. if not name:
  767. return ""
  768. # ps returns the full path on some systems — take the basename.
  769. base = name.rsplit("/", 1)[-1]
  770. for match, label in _CLIENT_NAME_PROC_SIGNALS:
  771. if match in base:
  772. return label
  773. return ""
  774. except Exception:
  775. return ""
  776. def _is_stdin_tty() -> bool:
  777. """Wrapper so tests can patch the TTY check without touching
  778. ``sys.stdin`` (which click's CliRunner rewires anyway)."""
  779. try:
  780. return bool(sys.stdin.isatty())
  781. except Exception:
  782. return False
  783. def _detect_client_name() -> str:
  784. """Return a best-guess AI client name for this pairing.
  785. Priority: env-var signal > parent-process name > "Unspecified (MCP)"
  786. (headless fallback) > "" (caller decides whether to prompt).
  787. Explicit ``--client`` handling is the caller's responsibility; it
  788. takes precedence over this helper.
  789. """
  790. env_hit = _sniff_client_from_env()
  791. if env_hit:
  792. return env_hit
  793. proc_hit = _sniff_client_from_parent_process()
  794. if proc_hit:
  795. return proc_hit
  796. # Headless: no TTY and no env/proc signals → almost certainly an
  797. # MCP subprocess launched by a client we don't have a signature
  798. # for. Better to label it "Unspecified (MCP)" than leave it
  799. # blank, which shows as "Unspecified client" on /settings/agent
  800. # and is indistinguishable from a legit-but-unknown pairing.
  801. if not _is_stdin_tty():
  802. return "Unspecified (MCP)"
  803. return ""
  804. def _prompt_for_client_name() -> str:
  805. """Interactive TTY fallback — ask the user which agent this is for.
  806. Only called when env/proc sniffs came up empty AND stdin is a TTY.
  807. A headless caller never gets here (``_detect_client_name`` returns
  808. "Unspecified (MCP)" first). The default on Enter is ``[1] Claude
  809. Desktop`` — the most common answer, and the safest miss (the user
  810. can always edit the label from /settings/agent later).
  811. """
  812. options = [
  813. ("Claude Desktop", "Claude Desktop"),
  814. ("Claude Code", "Claude Code"),
  815. ("Cursor", "Cursor"),
  816. ("Codex", "Codex"),
  817. ("Other", None),
  818. ]
  819. click.echo(" Which agent is this pairing for?", err=True)
  820. for i, (label, _value) in enumerate(options, start=1):
  821. click.echo(f" [{i}] {label}", err=True)
  822. try:
  823. raw = click.prompt(
  824. " Choice", default="1", show_default=True,
  825. prompt_suffix=" ", err=True,
  826. )
  827. except (click.Abort, EOFError, KeyboardInterrupt):
  828. return ""
  829. try:
  830. idx = int(str(raw).strip())
  831. except (TypeError, ValueError):
  832. idx = 1
  833. if idx < 1 or idx > len(options):
  834. idx = 1
  835. label, value = options[idx - 1]
  836. if value is not None:
  837. return value
  838. # "Other" — free-text label, cap at 40 chars, strip non-printable
  839. # + surrounding whitespace. The server also caps at 40 (same as
  840. # machine_label); we trim here so the user sees their final label
  841. # without a server round-trip.
  842. try:
  843. free = click.prompt(
  844. " Label", default="", show_default=False,
  845. prompt_suffix=" ", err=True,
  846. )
  847. except (click.Abort, EOFError, KeyboardInterrupt):
  848. return ""
  849. cleaned = "".join(c for c in str(free or "")[:40] if c.isprintable()).strip()
  850. return cleaned
  851. def _resolve_client_name(explicit: str | None) -> str:
  852. """One entry point for both ``pair`` and ``invite`` so there's a
  853. single source of truth for the priority order.
  854. ``explicit`` is whatever ``--client`` captured, including the
  855. absent-flag sentinel ``None``. An explicit empty string ("" via
  856. ``--client ""``) is treated as "user wants no label" and short-
  857. circuits both the detection and the TTY prompt.
  858. """
  859. if explicit is not None:
  860. # User said what they wanted; honour it verbatim, just tidy
  861. # the visible characters + cap length. No prompt, no sniff.
  862. cleaned = "".join(c for c in str(explicit)[:40] if c.isprintable()).strip()
  863. return cleaned
  864. detected = _detect_client_name()
  865. if detected:
  866. return detected
  867. # Env + proc sniffs came up empty AND we're interactive — ask.
  868. # _detect_client_name already returned "Unspecified (MCP)" for
  869. # the non-TTY case, so reaching this branch means TTY is True.
  870. if _is_stdin_tty():
  871. return _prompt_for_client_name()
  872. return ""
  873. @click.command("pair")
  874. @click.argument("code", required=True)
  875. @click.option(
  876. "--client", "client",
  877. type=str, default=None,
  878. metavar="NAME",
  879. help=(
  880. "Label this pairing by the AI client running it — e.g. "
  881. "\"Claude Desktop\", \"Cursor\", \"Codex\". If omitted, Kiln "
  882. "auto-detects from your environment. On /settings/agent this "
  883. "shows alongside the hostname so you can tell two paired "
  884. "machines apart."
  885. ),
  886. )
  887. def auth_pair(code: str, client: str | None) -> None:
  888. """Pair this machine with your signed-in Kiln workshop session.
  889. After you upgrade on app.kiln3d.com, the workshop shows a pairing
  890. code. Run this command here to sync your tier to this machine —
  891. your MCP server picks it up immediately, no Claude Desktop restart
  892. required.
  893. The code is single-use and expires in 10 minutes. Generate a new
  894. one any time at app.kiln3d.com/connect.
  895. Accepts either the full ``KLN-ABCD-EFGH`` shape or just
  896. ``ABCD-EFGH`` (the prefix is added for you).
  897. """
  898. raw = (code or "").strip().upper()
  899. if not raw:
  900. raise click.ClickException("Missing pairing code. Usage: kiln pair <code>")
  901. # Strip any leading ``kiln pair`` the user may have accidentally
  902. # double-pasted from the copy button. Small courtesy, saves a
  903. # "why isn't this working" moment.
  904. for prefix in ("KILN PAIR ", "KILN PAIR\u00A0"):
  905. if raw.startswith(prefix):
  906. raw = raw[len(prefix):].strip()
  907. break
  908. # Tidy typos: some users drop the ``KLN-`` prefix. The server
  909. # accepts both shapes, but normalizing here means the terminal
  910. # banner we print on success shows the user what the server saw.
  911. if not raw.startswith("KLN-"):
  912. raw = f"KLN-{raw}"
  913. # Resolve the AI-client identity BEFORE printing the pairing banner
  914. # so the interactive prompt (if any) comes first — the user
  915. # shouldn't see "Pairing..." then get stopped with a question.
  916. client_name = _resolve_client_name(client)
  917. click.echo("")
  918. click.echo(f" Pairing {_hostname_label()} with your Kiln workshop\u2026", err=True)
  919. from kiln.auth_session import credential_fields, machine_signin_request
  920. resp = _http_post(
  921. "/api/auth/pairing/claim",
  922. {
  923. "code": raw,
  924. # This computer's own machine credential, named the way
  925. # /settings/agent will list it.
  926. **machine_signin_request(client_name, label=_hostname_label()),
  927. "client_name": client_name,
  928. },
  929. )
  930. if not resp.get("success"):
  931. # Server sends a machine-readable ``code`` field alongside the
  932. # human ``error`` so we can print tailored next-step guidance
  933. # without string-sniffing the error message.
  934. reason = str(resp.get("code") or "").lower()
  935. msg = resp.get("error") or "Pairing failed."
  936. if reason in ("not_found", "expired"):
  937. raise click.ClickException(
  938. f"{msg}\n\n Get a fresh code at app.kiln3d.com/connect."
  939. )
  940. if reason == "already_claimed":
  941. raise click.ClickException(
  942. f"{msg}\n\n If you paired on another machine, that's fine — "
  943. f"this machine just needs its own code."
  944. )
  945. if reason == "rate_limited":
  946. raise click.ClickException(
  947. f"{msg} Wait a minute and retry."
  948. )
  949. raise click.ClickException(msg)
  950. # Defensive response validation — the CLI MUST NOT write a partial
  951. # token file that silently degrades to free-tier on every tool call.
  952. # If the server says ``success`` but omits ``access_token`` (a failure
  953. # that surfaces as stale empty tokens in ~/.kiln/auth_tokens.json),
  954. # fail loudly instead of writing a lie.
  955. access_token = str(resp.get("access_token") or "")
  956. refresh_token = str(resp.get("refresh_token") or "")
  957. auth_uid = str(resp.get("auth_uid") or "")
  958. if not access_token:
  959. raise click.ClickException(
  960. "Pairing claim succeeded but the server response carried no "
  961. "access_token. Nothing was written locally. This is a "
  962. "server-side bug — please retry with a fresh code from "
  963. "app.kiln3d.com/connect, and if it persists: adam@kiln3d.com."
  964. )
  965. email = str(resp.get("email") or "")
  966. tier = str(resp.get("tier") or "free").lower()
  967. _complete_signin({
  968. "access_token": access_token,
  969. "refresh_token": refresh_token,
  970. "email": email,
  971. "auth_uid": auth_uid,
  972. "tier": tier,
  973. "has_entitlement": bool(resp.get("has_entitlement")),
  974. "signed_in_at": int(time.time()),
  975. **credential_fields(resp),
  976. }, door="pair")
  977. # Post-write smoke test — confirm the token the server just gave us
  978. # is accepted by /api/auth/whoami. The token IS written regardless
  979. # of smoke result: rolling back on a single-endpoint 401 would
  980. # incorrectly block pairing when only whoami has an upstream issue
  981. # (a server-side issuer misconfiguration can make whoami return 401 on
  982. # a JWT that is valid). Instead: write tokens, then WARN loudly if
  983. # whoami rejects them, so the operator has visibility without losing
  984. # the pair.
  985. try:
  986. smoke_status, _ = _http_get("/api/auth/whoami", bearer=access_token, timeout=5.0)
  987. except Exception:
  988. smoke_status = 0 # network / unexpected — skip the warning
  989. if smoke_status == 401:
  990. click.echo(
  991. " ⚠ Tokens written, but /api/auth/whoami rejected them "
  992. "(HTTP 401). Tools may still work if the gate accepts this "
  993. "token shape — verify with a real call. If every tool "
  994. "fails: adam@kiln3d.com (server-side issuer/validator "
  995. "mismatch).",
  996. err=True,
  997. )
  998. elif smoke_status and smoke_status >= 400:
  999. click.echo(
  1000. f" ⚠ Tokens written, but /api/auth/whoami returned HTTP "
  1001. f"{smoke_status}. This is non-fatal; tools will still be "
  1002. "attempted.",
  1003. err=True,
  1004. )
  1005. # Final one-line confirmation on stdout (so `kiln pair ... | tail
  1006. # -1` captures it). Matches the `kiln signin` voice for source
  1007. # consistency.
  1008. click.echo(f"\u2713 Paired \u2014 {email} ({tier}).")
  1009. # ═════════════════════════════════════════════════════════════════════
  1010. # `kiln link` — CLI-initiated pairing (the reverse of `kiln pair`)
  1011. # ═════════════════════════════════════════════════════════════════════
  1012. #
  1013. # The mirror image of ``kiln pair``: the user is already signed in on
  1014. # THIS terminal (``kiln signin`` or ``kiln pair``) and wants to open a
  1015. # fresh browser tab at app.kiln3d.com while carrying the same session.
  1016. # ``kiln link`` mints a one-shot code that the browser's
  1017. # /settings/agent page can claim.
  1018. #
  1019. # Why this matters: pairing is symmetric. No matter which surface you
  1020. # sign in on first — web or terminal — you can pair the other in one
  1021. # code, so nobody signs in twice.
  1022. #
  1023. # ``kiln invite`` is a hidden deprecation alias for this command that
  1024. # prints a stderr warning and forwards. It is not the name: ``invite``
  1025. # reads as "invite another USER to Kiln" (referral / team-invite
  1026. # semantics) rather than "link my own browser tab to my own CLI
  1027. # session", and the ``invite`` namespace is kept for a referral system.
  1028. @click.command("link")
  1029. @click.option(
  1030. "--json", "as_json", is_flag=True, default=False,
  1031. help="Emit the link response as JSON (for piping into scripts).",
  1032. )
  1033. @click.option(
  1034. "--client", "client",
  1035. type=str, default=None,
  1036. metavar="NAME",
  1037. help=(
  1038. "Label this pairing by the AI client running it — e.g. "
  1039. "\"Claude Desktop\", \"Cursor\". The browser's /settings/agent "
  1040. "list shows it alongside the hostname so two paired machines "
  1041. "on the same host are distinguishable. Auto-detected if omitted."
  1042. ),
  1043. )
  1044. def auth_link(as_json: bool, client: str | None) -> None:
  1045. """Generate a one-shot code to sign in on another device.
  1046. Use this when you're signed in on THIS terminal (``kiln signin`` or
  1047. ``kiln pair``) and want to open a fresh browser tab at
  1048. app.kiln3d.com carrying the same session — no re-signin.
  1049. How it works:
  1050. 1. Run ``kiln link`` here.
  1051. 2. The terminal prints a short code + the URL to visit.
  1052. 3. Open app.kiln3d.com/settings/agent in a browser, sign in if
  1053. you haven't already (SAME account), and paste the code into
  1054. the "Link from another device" box.
  1055. 4. The browser tab is now paired with this terminal's session.
  1056. The code is single-use and expires in 10 minutes.
  1057. """
  1058. from kiln.auth_session import holds_machine_credential
  1059. tokens = _read_tokens()
  1060. access_token = str(tokens.get("access_token") or "")
  1061. if not access_token:
  1062. raise click.ClickException(
  1063. "Not signed in on this terminal. Run `kiln signin` first, "
  1064. "then `kiln link` to pair a browser tab."
  1065. )
  1066. if holds_machine_credential(tokens):
  1067. # A computer's own sign-in is never handed to a browser: it would turn
  1068. # a credential only this computer holds into a person's session.
  1069. raise click.ClickException(
  1070. "This computer has its own Kiln sign-in, which only it can use, so it "
  1071. "can't sign a browser in. Open app.kiln3d.com and sign in there; this "
  1072. "computer is already listed at app.kiln3d.com/settings/agent."
  1073. )
  1074. refresh_token = str(tokens.get("refresh_token") or "")
  1075. # Resolve AI-client identity BEFORE minting — if we need to prompt
  1076. # the user, we do it before the "Minting..." spinner so the flow
  1077. # reads: prompt → mint → print code.
  1078. client_name = _resolve_client_name(client)
  1079. click.echo("")
  1080. click.echo(" Minting a one-shot code for your browser\u2026", err=True)
  1081. # POST /api/auth/pairing/invite — authed with our access_token via
  1082. # the shared _http_post helper. 401 is surfaced as a ClickException
  1083. # by the helper itself when a bearer is supplied.
  1084. #
  1085. # NOTE: the SERVER endpoint is still /api/auth/pairing/invite — this
  1086. # is internal CLI/web wiring that users never see. Renaming it
  1087. # would force every test + the web client to migrate in lockstep
  1088. # for zero user-visible benefit, so we leave it. The user-facing
  1089. # name (this command) is what changed.
  1090. body = _http_post(
  1091. "/api/auth/pairing/invite",
  1092. {
  1093. "refresh_token": refresh_token,
  1094. "client_name": client_name,
  1095. },
  1096. bearer=access_token,
  1097. )
  1098. if not body.get("success"):
  1099. raise click.ClickException(body.get("error") or "Could not mint a link code.")
  1100. code = str(body.get("code") or "")
  1101. expires_at = str(body.get("expires_at") or "")
  1102. verify_url = str(body.get("verify_url") or "https://app.kiln3d.com/settings/agent")
  1103. if as_json:
  1104. click.echo(json.dumps(body, indent=2, sort_keys=True))
  1105. return
  1106. # Human output — match the `kiln signin` / `kiln pair` voice.
  1107. # The code is the hero; render it letter-spaced so it's easy to
  1108. # read off the terminal and type into a browser. A single blank
  1109. # line of breathing room above and below.
  1110. click.echo("")
  1111. click.echo(f" {code}")
  1112. click.echo("")
  1113. click.echo(f" Enter this code at: {verify_url}", err=True)
  1114. # Countdown — same 10-min window as the forward flow. Best-effort
  1115. # parse; if the ISO timestamp doesn't round-trip (timezone weirdness
  1116. # on some platforms) we just skip the countdown. Users have the
  1117. # absolute timestamp from the API if they need it.
  1118. try:
  1119. from datetime import datetime as _dt
  1120. from datetime import timezone as _tz
  1121. exp_dt = _dt.fromisoformat(expires_at.replace("Z", "+00:00"))
  1122. now = _dt.now(tz=_tz.utc)
  1123. mins = max(0, int((exp_dt - now).total_seconds() // 60))
  1124. if mins:
  1125. click.echo(f" Expires in ~{mins} minute{'s' if mins != 1 else ''}.", err=True)
  1126. except Exception:
  1127. pass
  1128. click.echo("")
  1129. click.echo(
  1130. " After you enter the code in the browser, that tab will be "
  1131. "signed in with the same account as this terminal.",
  1132. err=True,
  1133. )
  1134. # ═════════════════════════════════════════════════════════════════════
  1135. # `kiln invite` — deprecated alias for `kiln link` (one-release grace)
  1136. # ═════════════════════════════════════════════════════════════════════
  1137. @click.command(
  1138. "invite",
  1139. hidden=True,
  1140. context_settings={"ignore_unknown_options": True, "allow_extra_args": True},
  1141. )
  1142. @click.pass_context
  1143. def _auth_invite_deprecated(ctx: click.Context) -> None:
  1144. """[deprecated] alias for ``kiln link``.
  1145. Forwards every flag through unchanged so existing scripts keep
  1146. working. Will be removed one PyPI release after the rename ships.
  1147. """
  1148. click.echo(
  1149. "warning: `kiln invite` has been renamed to `kiln link` "
  1150. "(this alias will be removed in the next release).",
  1151. err=True,
  1152. )
  1153. ctx.invoke(auth_link, **{k: v for k, v in _parse_link_args(ctx.args).items()})
  1154. def _parse_link_args(args: list[str]) -> dict[str, Any]:
  1155. """Tiny re-parser for the deprecation alias.
  1156. Click's ``ctx.forward`` doesn't compose well with ``allow_extra_args``
  1157. when the source and target commands have the same option set, so we
  1158. reconstruct the kwargs by hand. Keep this dumb on purpose — only
  1159. the two flags ``auth_link`` actually accepts (``--json``,
  1160. ``--client``). Anything else is silently dropped (with a stderr
  1161. warning above flagging the deprecation, the user already knows
  1162. they're on a legacy code path).
  1163. """
  1164. out: dict[str, Any] = {"as_json": False, "client": None}
  1165. i = 0
  1166. while i < len(args):
  1167. a = args[i]
  1168. if a == "--json":
  1169. out["as_json"] = True
  1170. i += 1
  1171. elif a == "--client" and i + 1 < len(args):
  1172. out["client"] = args[i + 1]
  1173. i += 2
  1174. elif a.startswith("--client="):
  1175. out["client"] = a.split("=", 1)[1]
  1176. i += 1
  1177. else:
  1178. i += 1
  1179. return out
  1180. # ═════════════════════════════════════════════════════════════════════
  1181. # registration
  1182. # ═════════════════════════════════════════════════════════════════════
  1183. def register_auth_cli(cli_group: click.Group) -> None:
  1184. """Attach ``kiln signin`` / ``kiln signout`` / ``kiln whoami`` /
  1185. ``kiln pair`` / ``kiln link``.
  1186. If the group already has a command named ``login`` (the legacy
  1187. identity-linking flow in kiln-pro's ``vcs_commands.cli_login``), we
  1188. move it under ``kiln identity login`` so the top-level ``login``
  1189. name is free for the OAuth device flow — which is the command the
  1190. vast majority of users type first.
  1191. Called from ``kiln.cli.main`` unconditionally so every install
  1192. (free tier + Pro) gets ``kiln pair`` / ``kiln signin`` out of the
  1193. box.
  1194. """
  1195. # Canonical names: signin / signout (match the web workshop + MCP tools).
  1196. cli_group.add_command(auth_login)
  1197. cli_group.add_command(auth_logout)
  1198. cli_group.add_command(auth_whoami)
  1199. cli_group.add_command(auth_pair)
  1200. cli_group.add_command(auth_link)
  1201. # Legacy aliases: `kiln signin` / `kiln logout` keep working for existing
  1202. # scripts + muscle memory. Docs point at signin/signout.
  1203. cli_group.add_command(auth_login, name="login")
  1204. cli_group.add_command(auth_logout, name="logout")
  1205. # Deprecation alias: `kiln invite` is an earlier name for this
  1206. # command. Hidden from --help so docs point at `kiln link`, but
  1207. # still callable so a script or muscle memory written against it
  1208. # keeps working for ONE release.
  1209. cli_group.add_command(_auth_invite_deprecated, name="invite")

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.