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.
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
Markdown
[](/listings/codeofaxel--kiln)HTML
<a href="/listings/codeofaxel--kiln"><img src="/api/listings/codeofaxel--kiln/badge.svg" alt="findsafeskills safety rating" /></a>Install
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.
- {
- "name": "kiln",
- "owner": {
- "name": "Hadron Labs Inc.",
- "url": "https://kiln3d.com"
- },
- "metadata": {
- "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.",
- "pluginRoot": "./plugins"
- },
- "plugins": [
- {
- "name": "kiln",
- "source": "./kiln",
- "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).",
- "author": {
- "name": "Hadron Labs Inc.",
- "url": "https://kiln3d.com"
- },
- "homepage": "https://kiln3d.com",
- "license": "AGPL-3.0-or-later",
- "keywords": [
- "3d-printing", "3d-printer", "bambu-lab", "prusa", "creality",
- "elegoo", "octoprint", "moonraker", "klipper", "slicer", "fabrication"
- ]
- }
- ]
- }
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.
- <!-- mcp-name: io.github.codeofaxel/kiln -->
- <p align="center">
- <img src="docs/assets/kiln-banner-1280x640.svg" alt="Kiln" width="640">
- </p>
- <p align="center">
- <a href="https://pypi.org/project/kiln3d/"><img src="https://img.shields.io/pypi/v/kiln3d" alt="PyPI"></a>
- <a href="https://pepy.tech/projects/kiln3d"><img src="https://img.shields.io/pepy/dt/kiln3d" alt="PyPI Downloads"></a>
- <a href="https://pypi.org/project/kiln3d/"><img src="https://img.shields.io/pypi/pyversions/kiln3d" alt="Python"></a>
- <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>
- <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>
- <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>
- <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>
- </p>
- ---
- **Spawn an object into existence.**
- 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.
- **The open-source MCP server for 3D printing.**
- 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.
- 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.
- > **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.
- ```bash
- pip install kiln3d
- ```
- <p align="center">
- <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">
- </p>
- <p align="center">
- <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">
- </p>
- <p align="center">
- <em>"a coaster with a photo of my dog Ash" — start to finish, from one sentence.</em><br>
- <a href="https://kiln3d.com/?utm_source=github&utm_medium=readme#demo">Watch the demo →</a>
- </p>
- **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)
- <p align="center">
- <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">
- </p>
- <p align="center">
- <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>
- </p>
- ## Quick Start
- **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`.
- **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.
- 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).
- Everyone else — three steps. Then ask your AI to make something.
- **1. Install**
- ```bash
- pip install kiln3d
- ```
- **2. Connect your AI** — Kiln sets itself up inside Claude Desktop, Claude Code, and Codex:
- ```bash
- 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>
- ```json
- {
- "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>
- ```bash
- # Discover printers on your network (mDNS + HTTP probe)
- kiln discover
- # Add your printer, saying which printer it is (see "Supported Printers")
- kiln auth --name my-printer --host http://octopi.local --type octoprint --api-key YOUR_KEY --printer-model "Ender 3"
- # Other types:
- # kiln auth --name prusa --host http://192.168.1.100 --type prusalink --api-key YOUR_KEY --printer-model MK4
- # kiln auth --name klipper --host http://192.168.1.100:7125 --type moonraker --printer-model "Voron 2.4"
- # kiln auth --name bambu --host 192.168.1.100 --type bambu --access-code LAN_CODE --serial SERIAL --printer-model P1S
- # A printer Kiln doesn't list yet: add who makes it, e.g. --printer-make Anycubic --printer-model "Kobra X"
- 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 --output 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
- # Every command supports --json for agent consumption
- kiln status --json
- ```
- 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).
- </details>
- <details>
- <summary><strong>Connect a specific agent (Claude Code, Claude Desktop, env vars)</strong></summary>
- **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):
- ```bash
- claude plugin marketplace add codeofaxel/Kiln
- claude plugin install kiln@kiln
- ```
- Or wire it by hand — add to `.claude/settings.json` (project) or `~/.claude/settings.json` (global):
- ```json
- {
- "mcpServers": {
- "kiln": { "command": "kiln", "args": ["serve"] }
- }
- }
- ```
- 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.
- **Claude Desktop** — add to `~/.config/Claude/claude_desktop_config.json`:
- ```json
- {
- "mcpServers": {
- "kiln": {
- "command": "python3",
- "args": ["-m", "kiln", "serve"],
- "env": {
- "KILN_PRINTER_HOST": "http://192.168.1.100",
- "KILN_PRINTER_API_KEY": "your_key",
- "KILN_PRINTER_TYPE": "prusalink"
- }
- }
- }
- }
- ```
- 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`.
- **Any other LLM (OpenRouter)** — Kiln works with any model that supports OpenAI-compatible function calling, not just Claude:
- ```bash
- export KILN_OPENROUTER_KEY=sk-or-...
- kiln agent --model openai/gpt-4o
- kiln agent --model meta-llama/llama-3.1-70b-instruct --tier essential
- ```
- 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`.
- </details>
- <details>
- <summary><strong>Platform & printer setup notes (Linux/WSL 2, Ethernet-only, Bambu)</strong></summary>
- ### Prerequisites by printer type
- | Printer | `--type` | What you need |
- |---------|----------|---------------|
- | **Prusa MK4/XL/Mini+** | `prusalink` | IP + API key (Settings › Network › PrusaLink on the LCD) |
- | **OctoPrint** (any printer) | `octoprint` | OctoPrint URL + API key (User Settings › Application Keys) |
- | **Klipper/Moonraker** | `moonraker` | Moonraker URL (usually `http://<ip>:7125`) |
- | **Creality K1/K2/Hi/Ender V4/V3 KE** | `creality` | IP + `printer_model` (e.g. `creality_k1_max`); probes local Moonraker ports |
- | **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 |
- | **Elegoo** (SDCP) | `elegoo` | IP only — no auth. Neptune 4 / OrangeStorm Giga use `moonraker`. |
- | **Duet / RepRapFirmware** | `duet` | IP only, plus the machine password if one is set (`M551` in `config.g`). |
- | **Direct USB** (Marlin) | `usb` | USB cable only — no network. Ender 3, Prusa MK3, CR-10, any Marlin/RepRap printer. |
- Kiln only needs IP reachability on your LAN. Ethernet-only printers are fully supported.
- **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.
- ### Linux / WSL 2
- `pipx` installs Kiln into its own isolated environment and puts `kiln` on your PATH. (The pip package is `kiln3d`; the CLI command is `kiln`.)
- ```bash
- sudo apt install pipx && pipx ensurepath
- git clone https://github.com/codeofaxel/Kiln.git && cd Kiln
- pipx install ./kiln
- sudo apt install prusa-slicer # optional: slicing for printing
- sudo snap install openscad --edge # optional: the design engine (current build)
- kiln verify
- # Update / uninstall
- git pull && pipx install --force ./kiln
- pipx uninstall kiln3d
- ```
- **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).
- ### Ethernet-only printers (no Wi-Fi)
- 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:
- ```bash
- curl http://<ip>/api/version # OctoPrint
- curl http://<ip>:7125/server/info # Moonraker / Creality (local Moonraker)
- curl -H "X-Api-Key: YOUR_KEY" http://<ip>/api/v1/status # Prusa Link
- # Bambu uses MQTT — ensure port 8883 is reachable: nc -zv <ip> 8883
- kiln auth --name my-printer --host http://<ip> --type prusalink --api-key YOUR_KEY --printer-model MK4
- ```
- If PrusaSlicer isn't on your PATH: `export KILN_SLICER_PATH=/path/to/prusa-slicer`.
- ### Bambu TLS & webcam
- Kiln pins the printer certificate (TOFU) on first connection in `~/.kiln/bambu_tls_pins.json`. Overrides:
- ```bash
- export KILN_BAMBU_TLS_MODE=ca # strict CA/hostname (usually fails on stock self-signed printers)
- export KILN_BAMBU_TLS_MODE=insecure # legacy, no validation — trusted LANs only
- export KILN_BAMBU_TLS_FINGERPRINT=0123abcd... # explicit SHA-256 pin
- ```
- **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]'`.
- </details>
- 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.
- ## Why Kiln?
- - **One control plane, any printer** — compatible with OctoPrint, Moonraker, Creality, Bambu Lab, Prusa Link, Elegoo, Serial. Manage a mixed fleet from one place.
- - **No printer? No problem** — Outsource jobs to Craftcloud's 150+ manufacturing services, quoted and ordered through Kiln.
- - **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.
- - **Describe it, print it** — Natural-language to physical object pipeline: text or sketch → AI generation → validation → slice → print.
- - **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.
- - **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)
- - **Resume, don't restart** — Cancelled or failed print? Resume from the exact layer it stopped on any supported FDM printer. No filament wasted. (Pro)
- - **Modify mid-print** — Add decorations, append features, or swap materials on a live print with atomic revert if anything goes wrong. (Pro)
- - **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.
- - **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.
- - **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.
- - **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.
- - **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.
- ## Supported Printers
- | Backend | Status | Printers |
- |---------|--------|----------|
- | **OctoPrint** | Stable | Compatible with any OctoPrint-connected printer (Prusa, Ender, custom) |
- | **Moonraker** | Stable | Klipper-based printers (Voron, Ratrig, etc.) |
- | **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`. |
- | **Bambu** | Stable | Bambu Lab X1C, X1E, P1S, P1P, P2S, A1, A1 Mini, A2L, H2S, H2D, H2D Pro, H2C, H3C, X2D (via LAN MQTT) |
- | **Prusa Link** | Stable | Prusa MK4, XL, Mini+ (local REST API — type: `prusalink`) |
- | **Elegoo** | Stable | Centauri Carbon (via LAN WebSocket/SDCP). Neptune 4 / OrangeStorm Giga use Moonraker. |
- | **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`. |
- | **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`. |
- <!-- BEGIN SUPPORTED PRINTERS (auto-generated by scripts/generate_supported_printers.py) -->
- 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)
- <!-- END SUPPORTED PRINTERS -->
- ## Architecture
- ```mermaid
- graph TD
- A["🤖 AI Agent<br/><sub>Claude · GPT · Custom</sub>"]
- A -->|"CLI or MCP"| B["⚙️ Kiln<br/><sub>CLI + MCP Server</sub>"]
- B --> C["🖨️ Your Printers"]
- B --> F["🏭 Fulfillment"]
- B --> D["🛒 Marketplaces"]
- B --> V["📐 Designs (versioned)<br/><sub>Pro+</sub>"]
- C --> E1["OctoPrint"]
- C --> E2["Moonraker"]
- C --> E3["Creality"]
- C --> E4["Bambu"]
- C --> E5["Prusa Link"]
- C --> E6["Elegoo"]
- F --> F1["Craftcloud"]
- D --> I["MyMiniFactory"]
- D --> J["Cults3D"]
- V --> V1["Branches"]
- V --> V2["Signed Releases"]
- V --> V3["Cloud Sync"]
- style A fill:#1a1a2e,stroke:#e94560,color:#fff
- style B fill:#16213e,stroke:#0f3460,color:#fff
- style C fill:#0f3460,stroke:#e94560,color:#fff
- style F fill:#0f3460,stroke:#27ae60,color:#fff
- style D fill:#0f3460,stroke:#533483,color:#fff
- style V fill:#0f3460,stroke:#f59e42,color:#fff
- style E1 fill:#2d2d44,stroke:#e94560,color:#fff
- style E2 fill:#2d2d44,stroke:#e94560,color:#fff
- style E3 fill:#2d2d44,stroke:#e94560,color:#fff
- style E4 fill:#2d2d44,stroke:#e94560,color:#fff
- style E5 fill:#2d2d44,stroke:#e94560,color:#fff
- style F1 fill:#2d2d44,stroke:#27ae60,color:#fff
- style I fill:#2d2d44,stroke:#533483,color:#fff
- style J fill:#2d2d44,stroke:#533483,color:#fff
- style V1 fill:#2d2d44,stroke:#f59e42,color:#fff
- style V2 fill:#2d2d44,stroke:#f59e42,color:#fff
- style V3 fill:#2d2d44,stroke:#f59e42,color:#fff
- ```
- 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.
- ## Version control for 3D printing
- 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."*
- - **Branch and undo.** Try the risky idea on a branch. The working version stays untouched, and any step can be undone.
- - **See what changed.** Compare two versions side by side or drag between them, with how much material each change added or removed.
- - **Prints on the record.** Every print is filed under the version that made it, so you can look up how each one went.
- - **Merge.** Bring the change that printed best back into your main design. Kiln merges what it can and asks you about the rest.
- - **Signed releases.** Sign the version you ship, and prove later that it hasn't changed.
- <p align="center">
- <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">
- </p>
- <p align="center">
- <em>Drag across a part to see two versions at once, on every plan.</em>
- </p>
- | Plan | What you get |
- |---|---|
- | 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 |
- | **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 |
- | **Business** | Approval gates, team review, organizations and teams |
- | **Enterprise** | Named-approver sign-off, step-up sign-in before production releases, audit log export, SSO, access reviews |
- [See how version control works →](https://kiln3d.com/version-control?utm_source=github&utm_medium=readme)
- ## Tools
- 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:
- - **design_session**
- - Talk to Kiln about what you're making and get back a design that matches what you asked for
- - The front door for making anything: goal, geometry, preview, iterate. Free, unlimited, every tier
- - **compile_scad**
- - Compile OpenSCAD code into a printable STL — the keyless path underneath a design session
- - No API key and no external service: the agent writes the geometry, Kiln compiles it locally
- - **generate_model**
- - Generate a 3D model from a text prompt through an external AI provider
- - Optional, and off unless you bring your own key (Meshy, Tripo3D, Stability, Gemini)
- - **search_all_models**
- - Search connected 3D model marketplaces in one call
- - Covers MyMiniFactory and Cults3D; downloads where the marketplace supports it
- - **import_step_file**
- - Import a STEP (.step/.stp) CAD file and convert it for Kiln's mesh pipeline
- - **analyze_printability**
- - Run a full printability analysis on a mesh: overhangs, thin walls, warping risk, bed fit
- - **auto_orient_model**
- - Find the print orientation that needs the least support and prints strongest
- - **repair_mesh**
- - Repair mesh defects — holes, degenerate faces, rounding-noise seams
- - The usual fix for a model an AI generator or a rough scan produced
- - **split_mesh_to_fit**
- - Cut one solid too big for your build plate into printable pieces that reassemble
- - **recommend_material**
- - Recommend materials for a use case, with the reasons and the trade-offs
- - **decorate_surface**
- - Put any image, text, QR code, or pattern onto a model surface as an emboss or deboss
- - **slice_model**
- - Slice a model (STL/3MF/STEP) to G-code using PrusaSlicer, OrcaSlicer, or BambuStudio
- - **show_on_stage**
- - 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
- - **estimate_print_cost_from_mesh**
- - Estimate material cost, weight, and print time before committing the printer
- - **preflight_check**
- - Run pre-print safety checks: printer state, temperatures, file validity, bed clearance
- - **start_print**
- - Start a print on a connected machine
- - **monitor_print**
- - One-shot print status: progress, temperatures, time remaining, cost, and a camera snapshot where the printer has one
- - **emergency_stop**
- - Stop a running print immediately
- - **purge_filament**
- - Heat the nozzle and push a short length through — the clog test, with `load_filament` and `unload_filament` beside it for a spool change
- - Reports what the printer could actually tell: where a machine reports no flow signal it says so rather than claiming success
- - 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
- - **wipe_nozzle**
- - 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
- - 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
- - **home_axes**
- - 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
- - 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
- - **park_head**
- - Move the head to the model's own spot off the plate and leave it there; never a Z touch, never heat
- - **plate_status**
- - 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
- - 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
- - **diagnose_print_failure_live**
- - Diagnose a failing print from live printer state plus the model's own geometry
- - **retry_print_with_fix**
- - Diagnose what went wrong on the last print, then re-slice and print with the fix applied
- - **resume_interrupted_print** *(Pro)*
- - Resume an interrupted print with one call on any supported FDM printer
- - **save_design_version**
- - Save a new version of a parametric design, so you can go back to the one that worked
- - 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
- - **export_step**
- - Export a finished design as a real STEP CAD file — analytic B-rep a machine shop can open and measure
- - **printer_status**
- - 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
- - **fulfillment_quote**
- - Get a manufacturing quote from Craftcloud's network — printing without owning a printer
- 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.
- <details>
- <summary>MCP resources (read-only context for agents)</summary>
- | Resource URI | Description |
- |---|---|
- | `kiln://status` | System-wide snapshot (printers, queue, events) |
- | `kiln://printers` | Fleet listing with idle printers |
- | `kiln://printers/{name}` | Detailed status for a specific printer |
- | `kiln://queue` | Job queue summary and recent jobs |
- | `kiln://queue/{job_id}` | Detail for a specific job |
- | `kiln://events` | Recent events (last 50) |
- </details>
- ## Capabilities
- **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`).
- **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.
- **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.
- **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.
- **Decoration & 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.
- ## Pricing
- 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.
- | Tier | Price | Headline |
- |------|-------|----------|
- | **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. |
- | **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. |
- | **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. |
- | **Enterprise** | Contact us | Large fleets, SSO/SCIM, RBAC, audit trail, encrypted G-code at rest, white-label manuals, 99.9% SLA, on-prem/VPC. |
- **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)**.
- 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.
- ## Safety
- Kiln is safety-first infrastructure for controlling physical machines:
- - **Pre-flight checks** validate printer state, temperatures, and files before every print
- - **G-code validation** blocks dangerous commands (firmware reset, unsafe temperatures)
- - **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
- - **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
- - **Confirmation required** for destructive operations (cancel, raw G-code)
- - **Optional authentication** with scope-based API keys for multi-user setups
- - **Structured errors** ensure agents always know when something fails
- ## Packages
- This monorepo contains two packages:
- | Package | Description | Entry point |
- |---------|-------------|-------------|
- | **kiln** | CLI + MCP server for multi-printer control (OctoPrint, Moonraker, Creality, Bambu, Prusa Link, Elegoo, Direct USB) | `kiln` or `python -m kiln` |
- | **octoprint-cli** | Lightweight standalone CLI for OctoPrint-only setups | `octoprint-cli` |
- ## Development
- ```bash
- # Create a virtualenv first (required on modern Ubuntu/Debian/WSL)
- python3 -m venv .venv && source .venv/bin/activate
- pip install -e "./kiln[dev]"
- pip install -e "./octoprint-cli[dev]"
- cd kiln && python3 -m pytest tests/ -v
- cd ../octoprint-cli && python3 -m pytest tests/ -v
- ```
- ### Run in Docker
- `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.
- <details>
- <summary><strong>Configuration reference (auth, webhooks, discovery, plugins)</strong></summary>
- ### Authentication (optional)
- Optional API-key auth for MCP tools, disabled by default. Scopes: `read`, `write`, `admin`. Read-only tools never require auth.
- ```bash
- export KILN_AUTH_ENABLED=1
- export KILN_AUTH_KEY=your_secret_key
- export KILN_MCP_AUTH_TOKEN=your_secret_key # clients provide their key here
- ```
- ### Webhooks
- Register HTTP endpoints for real-time event notifications:
- ```
- register_webhook(url="https://example.com/hook", events=["job.completed", "print.failed"])
- ```
- 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.
- ### Printer discovery
- ```bash
- kiln discover # mDNS/Bonjour + HTTP subnet probing
- ```
- Finds OctoPrint, Moonraker/Creality, Bambu, Elegoo, and Prusa Link printers. If discovery returns nothing, register directly by IP with `kiln auth`.
- ### Third-party plugins
- 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.
- </details>
- <details>
- <summary><strong>Modules (for contributors)</strong></summary>
- | Module | Description |
- |---|---|
- | `server.py` | MCP server with tools, resources, and subsystem wiring |
- | `printers/` | Printer adapter abstraction (OctoPrint, Moonraker, Creality, Bambu, Prusa Link, Elegoo) |
- | `marketplaces/` | Model marketplace adapters (MyMiniFactory, Cults3D, Thingiverse, metadata-only sources) |
- | `slicer.py` | Slicer integration (PrusaSlicer, OrcaSlicer, BambuStudio) with auto-detection |
- | `registry.py` | Fleet registry for multi-printer management |
- | `queue.py` | Priority job queue with status tracking |
- | `scheduler.py` | Background job dispatcher with history-based smart routing |
- | `events.py` | Pub/sub event bus with history |
- | `persistence.py` | SQLite storage for jobs, events, and settings |
- | `webhooks.py` | Event-driven webhook delivery with HMAC signing |
- | `auth.py` | Optional API key authentication with scope-based access |
- | `discovery.py` | Network printer discovery (mDNS + HTTP probe) |
- | `generation/` | Text-to-model generation providers (Meshy, Tripo3D, Stability AI, Gemini Deep Think, OpenSCAD) with auto-discovery, mesh validation, and printability analysis |
- | `consumer.py` | Consumer workflow for non-printer users (address validation, material recommendations, timeline/price estimation, onboarding) |
- | `cost_estimator.py` | Print cost estimation from G-code analysis |
- | `materials.py` | Multi-material and spool tracking |
- | `material_inventory.py` | Fleet material inventory and assignment tracking |
- | `bed_leveling.py` | Automated bed leveling trigger system |
- | `streaming.py` | MJPEG webcam streaming proxy |
- | `cloud_sync.py` | Cloud sync for printer configs and job history |
- | `plugin_loader.py` | Internal tool-plugin discovery and registration |
- | `plugins/` | Focused MCP tool modules loaded by the plugin loader |
- | `gcode.py` | G-code safety validator with per-printer limits |
- | `gcode_interceptor.py` | Rule-based G-code interception and safety rewriting |
- | `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 |
- | `slicer_profiles.py` | Bundled slicer profiles (auto-generates .ini files per printer) |
- | `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) |
- | `pipelines.py` | Pre-validated print pipelines (quick_print, calibrate, benchmark) |
- | `assembly.py` | Multi-part assembly validation and manual planning support |
- | `design_versions.py` | Local design history, version records, diffs, and rollback primitives |
- | `mesh_validation_pipeline.py` | Multi-gate printability validation pipeline |
- | `model_visualizer.py` | Local model preview rendering |
- | `tool_schema.py` | OpenAI function-calling schema converter (MCP → OpenAI format) |
- | `tool_tiers.py` | Tool tier definitions (essential/standard/full) for model capability matching |
- | `agent_loop.py` | Generic agent loop for any OpenAI-compatible API (OpenRouter, direct, etc.) |
- | `openrouter.py` | OpenRouter integration with model catalog and auto-tier detection |
- | `data/` | Bundled JSON databases (safety profiles, slicer profiles, printer intelligence) |
- | `heater_watchdog.py` | Auto-cooldown watchdog for idle heaters |
- | `wallets.py` | Crypto wallet configuration (Solana/Ethereum for donations and fees) |
- | `pro_tool_manifest.json` | Public manifest for kiln-pro tool discovery and REST proxy stubs |
- | `decoration_quota.py` | Free-tier decoration quota tracking and tier resolution hooks |
- | `cli/` | Click CLI with <!-- KILN_CLI_COUNT:OLD --> 253 commands and JSON output |
- 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.
- </details>
- ## Documentation
- | Document | Description |
- |----------|-------------|
- | [Project Docs](https://www.kiln3d.com/docs?utm_source=github&utm_medium=readme) | Complete reference (CLI, MCP tools, adapters, config) |
- <details>
- <summary>Brand assets</summary>
- Logo files live in [`docs/assets/`](docs/assets/) — all vector SVG, scale to any size.
- | File | Use |
- |------|-----|
- | `kiln-banner-1280x640.svg` / `kiln-banner-1280x640-light.svg` | GitHub / social media banner (dark / light scheme) |
- | `kiln-logo-dark.svg` / `kiln-logo-light.svg` | Primary mark + wordmark (dark / light bg) |
- | `kiln-horizontal-dark.svg` / `kiln-horizontal-light.svg` | Horizontal lockup (dark / light bg) |
- | `kiln-logo-dark-notext.svg` | Mark only (dark bg) |
- | `kiln-favicon-256.svg` | Favicon / app icon |
- | `kiln-logo-transparent.svg` / `kiln-logo-transparent-dark.svg` | Transparent bg (for dark / light UIs) |
- | `kiln-mark-1024.svg` | Square mark tile — profile picture, app tile (1024×1024) |
- | `kiln-x-header-1500x500.svg` | Social header (1500×500) |
- | `wallpapers/kiln-wallpaper-iphone-*.svg` | iPhone wallpapers |
- | `wallpapers/kiln-wallpaper-macbook-*.svg` | MacBook wallpapers |
- Every file above is generated from one geometry, so the mark is identical across
- all of them. Please don't redraw it — scale the vector instead.
- </details>
- ## Support Development
- Kiln is free, open-source software. If you find it useful, consider sending a tip:
- - **Solana:** `kiln3d.sol`
- - **Ethereum:** `kiln3d.eth`
- ## Positioning
- > **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.
- **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.
- ## License
- Kiln is a project of **Hadron Labs Inc.**
- [AGPL-3.0 License](LICENSE) — open source with copyleft. [Commercial licensing](policies/COMMERCIAL_LICENSE.md) available for companies that need proprietary use.
- By contributing, you agree to the [Contributor License Agreement](policies/CONTRIBUTOR_LICENSE_AGREEMENT.md).
- ---
- Also listed on [Smithery](https://smithery.ai/servers/codeofaxel/kiln) and LobeHub: [](https://lobehub.com/mcp/codeofaxel-kiln)
- ## Trademarks
- [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
- """``kiln signin`` / ``kiln signout`` / ``kiln whoami`` / ``kiln pair`` /
- ``kiln link`` — the CLI's device-code OAuth flow + bidirectional pairing
- against the Kiln REST API.
- How the login flow works end-to-end:
- 1. ``kiln signin`` POSTs ``/api/auth/device/start``. Gets back a
- ``device_code`` (secret), a ``user_code`` (human-typeable), and a
- ``verification_uri`` (URL to open in the browser).
- 2. CLI prints the ``user_code`` + URL, opens the URL in the user's
- default browser (unless ``--no-browser``), and starts polling
- ``/api/auth/device/poll`` every ``interval`` seconds.
- 3. User picks a provider on the browser page (Google / Apple / GitHub),
- completes the OAuth flow with Supabase. The Supabase redirect
- lands on our ``/auth/device/callback`` page, which JS-side fetches
- the user and POSTs ``/api/auth/device/claim`` so the server can
- mark the row as ``status=success`` + stash the tokens.
- 4. The next poll from the CLI returns ``{status: success,
- access_token, refresh_token, tier, email}``.
- 5. CLI writes the tokens to ``~/.kiln/auth_tokens.json`` (mode 0600)
- and prints ``Signed in as {email} ({tier})``.
- ``kiln signout`` removes this computer from the account (for a machine
- credential) and deletes the token file.
- ``kiln whoami`` renews the sign-in if it needs it, hits ``GET
- /api/auth/whoami``, and prints the resolved email + tier (and, for a
- machine credential, which computer this is on the account).
- What a sign-in door asks for is a machine credential of this computer's
- own (``kiln.auth_session.machine_signin_request``): a sign-in Kiln issues
- to the computer, which nothing done in a browser can end. A server that
- predates them answers with a session, stored exactly as before.
- ``kiln pair <code>`` is the web-initiated mirror of ``kiln signin`` —
- the user has already signed in on app.kiln3d.com; this command claims
- a short-lived pairing code and writes the tokens locally without a
- second browser round-trip.
- All four commands talk ONLY to the public Kiln REST API at
- ``https://api.kiln3d.com`` (override with ``KILN_API_URL`` for local
- dev). No proprietary logic lives here — they ship in the public
- ``kiln`` package so ``pip install kiln3d && kiln pair <code>`` works
- out-of-the-box on a clean machine without requiring kiln-pro.
- The file is JSON not YAML so that ops can eyeball it without a parser
- dependency and so third-party tooling can read tier without depending
- on any Kiln package at all.
- """
- from __future__ import annotations
- import contextlib
- import json
- import os
- import stat
- import sys
- import time
- from pathlib import Path
- from typing import Any
- import click
- from kiln import run_program
- # Default API base — override with ``KILN_API_URL`` for local dev.
- def _api_base() -> str:
- return (os.environ.get("KILN_API_URL") or "https://api.kiln3d.com").rstrip("/")
- # How the sign-in poll rides out a stretch when Kiln's servers cannot be
- # reached (see the loop in ``auth_login``). Each failed tick waits twice as
- # long as the last, up to this cap, so an outage is not hammered yet a
- # recovered connection is noticed within half a minute.
- _POLL_OUTAGE_MAX_WAIT_S = 30.0
- # The notice on stderr waits for this many failed ticks in a row: one lost
- # request is a blip the person never needs to hear about.
- _POLL_OUTAGE_NOTICE_AFTER = 3
- # Give up once the servers have been out of reach for this long without a
- # single answered tick. Long enough to cover a router reboot or a change
- # of Wi-Fi, short enough that nobody stares at a dead terminal for the rest
- # of the device code's lifetime.
- _POLL_OUTAGE_GIVE_UP_S = 120.0
- def _tokens_path() -> Path:
- """Where we persist the access + refresh token. Per-user, tight
- permissions. ``$KILN_AUTH_HOME`` lets tests redirect the path
- without monkeypatching ``Path.home``."""
- home = os.environ.get("KILN_AUTH_HOME") or str(Path.home())
- return Path(home) / ".kiln" / "auth_tokens.json"
- def _write_tokens(data: dict[str, Any]) -> None:
- """Atomic + 0600. Create the directory with 0700 perms first so
- we never leave an intermediate mode-wide-open file on disk."""
- path = _tokens_path()
- path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
- tmp = path.with_suffix(".tmp")
- tmp.write_text(json.dumps(data, indent=2, sort_keys=True), encoding="utf-8")
- with contextlib.suppress(OSError):
- os.chmod(tmp, stat.S_IRUSR | stat.S_IWUSR) # 0600
- tmp.replace(path)
- def _record_signin_stage(stage: str) -> None:
- """Count a sign-in funnel stage (``daily_stats.record_account_nudge``).
- Never raises: a sign-in must not fail over its own counter.
- """
- try:
- from kiln.daily_stats import record_account_nudge
- record_account_nudge(stage)
- except Exception: # noqa: BLE001
- pass
- def _complete_signin(data: dict[str, Any], *, door: str = "other") -> None:
- """Store a new sign-in, then hand the account this install's agreement to
- the Terms.
- Every door that signs a person in on this machine ends here — ``kiln
- signin``, ``kiln pair`` and the in-chat ``kiln_signin_poll`` — so an
- agreement made on the machine before it was signed in reaches the account
- the moment one exists, not on the first hosted call that gets refused
- without it. The hand-off is best-effort: a sign-in never fails over it,
- and a refused hosted call still makes it (``server._pro_api_call``).
- ``door`` names which way in it was (``chat`` / ``cli`` / ``pair``), counted
- here because this is the one function every door ends in: a fourth door
- still counts, as ``completed_other``, instead of going unseen. A machine
- that still held a session is also counted ``completed_returning``, so a
- lapsed owner signing back in is never read as a new account; one that
- was shown a limits nudge at a printer's setup within the day is also
- counted ``completed_limits``.
- """
- try:
- held = _read_tokens()
- returning = bool(held.get("access_token") or held.get("refresh_token"))
- except Exception: # noqa: BLE001
- returning = False
- _write_tokens(data)
- _record_signin_stage(
- f"completed_{door}" if door in ("chat", "cli", "pair") else "completed_other"
- )
- if returning:
- _record_signin_stage("completed_returning")
- # A limits nudge shown at a printer's setup (``safety_profiles.warm_profile``)
- # waits for this moment in a marker on disk, because it was minted in the
- # MCP server process and this sign-in may be finishing in another: counted
- # ``completed_limits`` when the nudge was within a day, nothing otherwise.
- try:
- from kiln.daily_stats import record_limits_nudge_conversion
- record_limits_nudge_conversion()
- except Exception: # noqa: BLE001 -- a sign-in never fails over its counter
- pass
- # And in THIS process the catalogue bridge forgets the signed-out misses,
- # so the next ask for a printer's record goes to the servers at once
- # rather than after its retry wait -- the in-chat door (kiln_signin_poll)
- # ends here in the same process that will now answer for the printers.
- try:
- from kiln._pro_catalogue_bridge import forget
- forget()
- except Exception: # noqa: BLE001
- pass
- # The printer question likewise forgets what it was told while signed
- # out, so the next ending asks the servers for the account now signed in.
- try:
- from kiln._pro_printer_checkin_bridge import forget as forget_checkins
- forget_checkins()
- except Exception: # noqa: BLE001
- pass
- from kiln import terms
- # A sign-in never fails over either terms hand-off below.
- with contextlib.suppress(Exception):
- terms.sync_to_account(bearer=str(data.get("access_token") or ""))
- # And the other direction: an agreement the account already holds, made
- # on another device, is brought onto this machine now, so the very next
- # command runs instead of asking the person to agree a second time. The
- # sign-in that just landed is the bearer ``is_current`` resolves from the
- # file; forcing the server past the recheck throttle matters because a
- # stale local record may have been checked minutes ago with a dead token.
- with contextlib.suppress(Exception):
- terms.is_current(force_server=True)
- def _read_tokens() -> dict[str, Any]:
- path = _tokens_path()
- if not path.exists():
- return {}
- try:
- return json.loads(path.read_text(encoding="utf-8"))
- except Exception:
- return {}
- def _delete_tokens() -> bool:
- path = _tokens_path()
- if not path.exists():
- return False
- path.unlink()
- # Served motion plans are kept for the signed-in account; they leave
- # with it, so the next account on this machine starts with none.
- try:
- from kiln.printers.motion_plan_cache import forget_all
- forget_all()
- except Exception: # noqa: BLE001 -- a sign-out never fails over a cache
- pass
- return True
- class _ApiUnavailable(click.ClickException):
- """Kiln's servers could not be reached, or answered that they are
- unwell (5xx) -- the one kind of failure worth asking again about a
- moment later.
- Still a ``ClickException``, so a caller that does not care gets the
- same one-line exit as before; a caller that can afford to wait out a
- blip (the sign-in poll loop) catches this one and lets everything
- else -- a bad request, a non-JSON answer, a refused bearer -- end the
- command as it always has.
- """
- def _http_post(
- path: str,
- body: dict[str, Any],
- *,
- bearer: str | None = None,
- timeout: float = 15.0,
- ) -> dict[str, Any]:
- """Thin requests.post wrapper that returns a dict or raises
- click.ClickException with a human message. Keeping the HTTP
- surface tiny (no retry, no session reuse) because these endpoints
- are called at most a few dozen times across the whole flow; the one
- caller that has to outlive a network blip (the sign-in poll) retries
- on its own by catching ``_ApiUnavailable``.
- ``bearer`` is keyword-only so every existing call site (all
- unauthenticated pairing/login endpoints) keeps working unchanged;
- only authed callers like ``kiln link`` opt in."""
- try:
- import requests # type: ignore[import-untyped]
- except ImportError as exc: # pragma: no cover — requests is a hard dep
- raise click.ClickException(
- "The `requests` package is required for `kiln signin`. "
- "Install with `pip install requests`."
- ) from exc
- headers = {"User-Agent": f"kiln-cli/{_cli_version()}"}
- if bearer:
- headers["Authorization"] = f"Bearer {bearer}"
- try:
- resp = requests.post(
- f"{_api_base()}{path}",
- json=body,
- timeout=timeout,
- headers=headers,
- )
- except requests.exceptions.ConnectionError as exc:
- raise _ApiUnavailable(
- f"Could not reach Kiln API at {_api_base()} — is the server up?"
- ) from exc
- except requests.exceptions.Timeout as exc:
- raise _ApiUnavailable(
- f"Timed out reaching {_api_base()}{path}."
- ) from exc
- except requests.exceptions.RequestException as exc:
- # Everything else requests can raise on the wire -- a connection
- # reset partway through the body (ChunkedEncodingError, seen on
- # Windows), a protocol hiccup -- is the same kind of passing
- # trouble, and must never surface as a raw traceback mid-poll.
- raise _ApiUnavailable(
- f"Connection to {_api_base()} dropped mid-request "
- f"({exc.__class__.__name__})."
- ) from exc
- if bearer and resp.status_code == 401:
- # Only surface 401 as a terminal error when an Authorization
- # header was actually sent. Unauthenticated callers (the
- # device-flow / pairing-claim endpoints) never expect 401 and
- # continue to signal success/failure via the JSON body — hiding
- # that under a blanket 401 branch would break the login flow.
- raise click.ClickException(
- "Your session is not accepted by the Kiln API (HTTP 401). "
- "Run `kiln signin` to refresh, then retry."
- )
- if resp.status_code >= 500:
- raise _ApiUnavailable(
- f"Kiln API returned {resp.status_code} for {path}. "
- "Try again in a moment; if it persists, email adam@kiln3d.com."
- )
- try:
- return resp.json()
- except ValueError as exc:
- raise click.ClickException(
- f"Kiln API returned non-JSON for {path}: {resp.text[:200]}"
- ) from exc
- def _http_get(path: str, *, bearer: str | None = None, timeout: float = 10.0) -> tuple[int, dict[str, Any]]:
- try:
- import requests # type: ignore[import-untyped]
- except ImportError as exc: # pragma: no cover
- raise click.ClickException("The `requests` package is required.") from exc
- headers = {"User-Agent": f"kiln-cli/{_cli_version()}"}
- if bearer:
- headers["Authorization"] = f"Bearer {bearer}"
- try:
- resp = requests.get(f"{_api_base()}{path}", headers=headers, timeout=timeout)
- except requests.exceptions.ConnectionError as exc:
- raise click.ClickException(f"Could not reach {_api_base()}.") from exc
- try:
- return resp.status_code, resp.json()
- except ValueError:
- return resp.status_code, {}
- def _cli_version() -> str:
- try:
- from kiln import __version__
- return __version__
- except Exception:
- return "dev"
- # ═════════════════════════════════════════════════════════════════════
- # `kiln signin` (also aliased as `kiln signin` for backwards compat)
- # ═════════════════════════════════════════════════════════════════════
- @click.command("signin")
- @click.option(
- "--no-browser", is_flag=True, default=False,
- help="Don't open the browser automatically. Print the URL and wait.",
- )
- @click.option(
- "--timeout", type=int, default=900, show_default=True,
- help="Max seconds to wait for the user to complete the browser step.",
- )
- @click.option(
- # Hidden on purpose: `--provider` is NOT a real flag here. It's the
- # natural wrong guess (account sign-in vs. linking a GitHub identity
- # for signing are different things), so instead of Click's bare
- # "No such option: --provider" we catch it and redirect to the right
- # command. Hidden so it never appears in --help and the canonical
- # flag set stays {--no-browser, --timeout}.
- "--provider", "provider", default=None, hidden=True,
- )
- def auth_login(no_browser: bool, timeout: int, provider: str | None) -> None:
- """Sign in to your Kiln account via OAuth (Google / Apple / GitHub).
- This is KILN ACCOUNT AUTHENTICATION — use this to log in to the
- Kiln REST API + workshop as yourself. If you want to "log in to
- Kiln", this is the command. Connecting a GitHub identity for
- signing design releases is a different thing, and is not this.
- Launches the device-code flow: opens your browser to a small
- provider-picker page, polls until you finish signing in, then
- writes your session token to ``~/.kiln/auth_tokens.json``.
- The rest of the CLI will pick up your session automatically — no
- license key needed for OAuth-linked Pro+ accounts. Backwards-compat
- alias: ``kiln login`` (same command, same flow).
- """
- # `--provider` isn't an option for account sign-in (this command picks
- # the provider for you on the browser page). Say so and bail WITHOUT
- # signing in, so we never half-start a device flow the user didn't mean
- # to run. No other command is named: none on a plain install links an
- # identity today, and a pointer to a command the person lacks is worse
- # than none (tests/test_auth_commands.py pins it).
- if provider is not None:
- click.echo(
- "`--provider` isn't an option for `kiln login` (that's account "
- "sign-in, which picks the provider for you in the browser). "
- "Run `kiln signin` to sign in.",
- err=True,
- )
- sys.exit(2)
- # 1) Start the device flow, asking for this computer's own machine
- # credential under the name /settings/agent will list it by.
- from kiln.auth_session import machine_signin_request
- try:
- start = _http_post(
- "/api/auth/device/start",
- machine_signin_request(_detect_client_name() or "Kiln CLI", label=_hostname_label()),
- )
- except Exception:
- _record_signin_stage("start_failed")
- raise
- if not start.get("success"):
- _record_signin_stage("start_failed")
- raise click.ClickException(
- start.get("error") or "Could not start the sign-in flow."
- )
- _record_signin_stage("started_cli")
- device_code = start["device_code"]
- user_code = start["user_code"]
- verification_uri = start["verification_uri"]
- interval = max(1, int(start.get("interval") or 2))
- expires_in = int(start.get("expires_in") or 900)
- deadline = time.monotonic() + min(timeout, expires_in)
- # 2) Try to open the browser FIRST. The verification URL carries
- # the user_code as a query param, so when the browser opens the
- # human lands on the provider picker with nothing to type. We
- # only fall back to showing the raw URL / code when auto-open
- # fails — most users (normies, agents, devs alike) never see
- # the code. Hiding device-flow implementation details is the
- # biggest single UX win over the classic "paste this code"
- # pattern.
- browser_opened = False
- if not no_browser:
- try:
- browser_opened = run_program.open_url(verification_uri, new=1, autoraise=True)
- except Exception:
- browser_opened = False
- click.echo("", err=True)
- if browser_opened:
- click.echo(" Opening your browser to sign in\u2026", err=True)
- else:
- # Fallback path — no browser auto-open (--no-browser, headless
- # machine, sandboxed CLI). URL is primary; code is the
- # last-resort affordance shown in a muted secondary line.
- click.echo(" Open this URL to sign in:", err=True)
- click.echo("", err=True)
- click.echo(f" {verification_uri}", err=True)
- click.echo("", err=True)
- click.echo(
- f" If the page asks you to confirm a code, it\u2019s {user_code}",
- err=True,
- )
- click.echo("", err=True)
- # 3) Poll with a subtle braille spinner so the terminal feels
- # alive during the 5–30s most users take in the browser.
- # TTY-gated so piping to a log file (or CI) produces static,
- # greppable output instead of a carriage-return salad.
- result: dict[str, Any] = {}
- spinner_frames = "\u2807\u2811\u2813\u2817\u2837\u2836\u2834\u2830\u2820\u2800"
- is_tty = bool(getattr(sys.stderr, "isatty", lambda: False)())
- tick = 0
- if is_tty:
- click.echo(
- f" {spinner_frames[0]} Waiting for you to finish in the browser\u2026",
- nl=False, err=True,
- )
- else:
- click.echo(" Waiting for you to finish in the browser\u2026", err=True)
- # A poll tick that cannot reach Kiln is not the end of the sign-in. The
- # person is in a browser tab that is about to claim this device code, and
- # one dropped connection on this side -- a laptop changing Wi-Fi, a home
- # router hiccup, a proxy restart -- must not end the command with "is the
- # server up?" and throw the code away while the server never missed a
- # request. So a tick that fails is simply tried again, waiting a little
- # longer each time, and the command only gives up when the browser flow's
- # own deadline passes or the servers have been out of reach for minutes
- # on end. The start request is different: a server that is down is
- # better said at once than discovered after a wait.
- wait = interval
- failures = 0
- outage_began: float | None = None
- notice_shown = False
- while time.monotonic() < deadline:
- time.sleep(min(wait, max(0.0, deadline - time.monotonic())))
- try:
- poll = _http_post("/api/auth/device/poll", {"device_code": device_code})
- except _ApiUnavailable as exc:
- now = time.monotonic()
- failures += 1
- if outage_began is None:
- outage_began = now
- if now - outage_began >= _POLL_OUTAGE_GIVE_UP_S:
- if is_tty:
- click.echo("\r" + " " * 60 + "\r", nl=False, err=True)
- _record_signin_stage("poll_unreachable")
- raise click.ClickException(
- "Could not reach Kiln's servers for about two minutes, so this "
- "sign-in was abandoned. Check your connection and run "
- "`kiln signin` again."
- ) from exc
- # Say something only once a blip has outlasted a couple of ticks:
- # a single dropped request is not worth a line of alarm.
- if failures == _POLL_OUTAGE_NOTICE_AFTER and not notice_shown:
- notice_shown = True
- if is_tty:
- click.echo("\r" + " " * 60 + "\r", nl=False, err=True)
- click.echo(
- " Lost contact with Kiln\u2019s servers, still trying\u2026",
- err=True,
- )
- if is_tty:
- click.echo(
- f" {spinner_frames[tick % len(spinner_frames)]} "
- "Waiting for you to finish in the browser\u2026",
- nl=False, err=True,
- )
- wait = min(wait * 2, _POLL_OUTAGE_MAX_WAIT_S)
- continue
- if failures:
- # Back in touch: poll at the browser flow's own pace again, and
- # close the notice so the person knows nothing was lost.
- failures = 0
- outage_began = None
- wait = interval
- if notice_shown:
- notice_shown = False
- if is_tty:
- click.echo("\r" + " " * 60 + "\r", nl=False, err=True)
- click.echo(" Back in touch with Kiln\u2019s servers.", err=True)
- if is_tty:
- click.echo(
- f" {spinner_frames[tick % len(spinner_frames)]} "
- "Waiting for you to finish in the browser\u2026",
- nl=False, err=True,
- )
- status = str(poll.get("status") or "pending").lower()
- if status == "pending":
- if is_tty:
- tick += 1
- frame = spinner_frames[tick % len(spinner_frames)]
- click.echo(
- f"\r {frame} Waiting for you to finish in the browser\u2026",
- nl=False, err=True,
- )
- continue
- result = poll
- break
- else:
- if is_tty:
- click.echo("\r" + " " * 60 + "\r", nl=False, err=True)
- _record_signin_stage("timed_out")
- if failures:
- # The wait ran out while Kiln's servers were out of reach, so the
- # browser may well have finished; say which it was.
- raise click.ClickException(
- "Sign-in timed out while Kiln's servers were out of reach, so "
- "this terminal could not see whether you finished in the "
- "browser. Check your connection and run `kiln signin` again."
- )
- raise click.ClickException(
- "Sign-in timed out before the browser flow completed. "
- "Run `kiln signin` again."
- )
- # Clear the spinner line cleanly before printing the final verdict.
- if is_tty:
- click.echo("\r" + " " * 60 + "\r", nl=False, err=True)
- status = str(result.get("status") or "").lower()
- if status == "success":
- from kiln.auth_session import credential_fields
- email = str(result.get("email") or "")
- tier = str(result.get("tier") or "free").lower()
- _complete_signin({
- "access_token": result.get("access_token") or "",
- "refresh_token": result.get("refresh_token") or "",
- "email": email,
- "auth_uid": result.get("auth_uid") or "",
- "tier": tier,
- "has_entitlement": bool(result.get("has_entitlement")),
- "signed_in_at": int(time.time()),
- **credential_fields(result),
- }, door="cli")
- # Final confirmation on stdout (not stderr) so ``kiln login
- # | tail -1`` captures it. Ember-coloured checkmark +
- # lowercase "you're in" matches the workshop's signin copy
- # and the /auth/device page's h1 — three surfaces, one voice.
- click.echo(f"\u2713 You\u2019re in \u2014 {email} ({tier}).")
- return
- if status == "denied":
- # User cancelled in the browser (e.g. picked a provider, got
- # to the consent screen, hit back). Quiet exit, no scolding.
- _record_signin_stage("denied")
- raise click.ClickException(
- result.get("message") or "Sign-in was cancelled in the browser."
- )
- if status == "expired":
- _record_signin_stage("expired")
- raise click.ClickException(
- result.get("message") or "Sign-in code expired. Run `kiln signin` again."
- )
- raise click.ClickException(f"Unexpected sign-in status: {status!r}")
- # ═════════════════════════════════════════════════════════════════════
- # `kiln signout` (also aliased as `kiln logout` for backwards compat)
- # ═════════════════════════════════════════════════════════════════════
- @click.command("signout")
- def auth_logout() -> None:
- """Sign this computer out of Kiln.
- A computer on its own machine sign-in is also removed from your account
- (app.kiln3d.com/settings/agent), so nothing is left behind that nobody
- holds. Your other computers and your browser stay signed in.
- """
- from kiln.auth_session import holds_machine_credential, revoke_machine_credential
- tokens = _read_tokens()
- removed = False
- if holds_machine_credential(tokens):
- removed = revoke_machine_credential()
- if _delete_tokens():
- if removed:
- click.echo("Signed out. This computer was removed from your Kiln account.")
- elif holds_machine_credential(tokens):
- click.echo(
- "Signed out on this computer. Kiln couldn't be reached to remove it from "
- "your account, so it may still be listed at app.kiln3d.com/settings/agent; "
- "removing it there finishes the job."
- )
- else:
- click.echo("Signed out. Token file removed.")
- else:
- click.echo("You weren't signed in.")
- # ═════════════════════════════════════════════════════════════════════
- # `kiln whoami`
- # ═════════════════════════════════════════════════════════════════════
- @click.command("whoami")
- @click.option(
- "--json", "as_json", is_flag=True, default=False,
- help="Emit the full whoami response as JSON instead of a human summary.",
- )
- def auth_whoami(as_json: bool) -> None:
- """Show who you're signed in as + your current tier.
- Hits ``GET /api/auth/whoami`` with your saved access_token and
- prints the tier + email the server resolves. Useful when the
- local cache might be out of date (e.g. right after an upgrade in
- the Stripe portal).
- """
- from kiln.auth_session import resolve_session_bearer
- # Renewed first when it needs it: a machine credential's access token
- # lives about fifteen minutes, and "session expired" for a sign-in that
- # renews itself would be untrue.
- session = resolve_session_bearer()
- if not session.token:
- if session.state == "needs_signin" and session.detail:
- # Ended, and the detail says how (removed, found in use in two
- # places, an org seat that ended) — not merely "not signed in".
- raise click.ClickException(f"{session.detail} Run `kiln signin` to sign in again.")
- raise click.ClickException("Not signed in. Run `kiln signin` to sign in.")
- code, body = _http_get("/api/auth/whoami", bearer=session.token)
- if str(body.get("reason") or "") == "auth_upstream_unavailable":
- # The API could not check the sign-in (a 401 for a session, a 503 for
- # a machine credential): its servers did not answer, and the sign-in
- # itself is fine. "Sign in again" would send the person after the
- # wrong fix.
- raise click.ClickException(
- "Kiln's servers didn't answer just now, so your sign-in couldn't be "
- "checked. You're still signed in; try again in a minute."
- )
- if code == 401:
- raise click.ClickException(
- str(body.get("message") or "Session expired.") + " Run `kiln signin` to sign in again."
- )
- if code >= 400 or not body.get("success"):
- raise click.ClickException(
- body.get("error") or f"whoami failed (HTTP {code})"
- )
- email = str(body.get("email") or "")
- tier = str(body.get("tier") or "free").lower()
- status = str(body.get("status") or "").lower()
- expires = str(body.get("expires_at") or "")
- # Write the fresh server-resolved tier back to the token cache so
- # any LicenseManager (which reads this file) picks up tier changes
- # immediately after ``kiln whoami`` instead of waiting for its own
- # 24h auto-refresh. Useful right after a Stripe upgrade: run
- # ``kiln whoami``, then every local tool sees the new tier.
- # Read only now: another Kiln process may have renewed the sign-in while
- # the server answered, and writing back a copy read before the call would
- # put the superseded secret on disk. The next renewal would present it,
- # which the server reads as this computer's sign-in in use in two places.
- tokens = _read_tokens()
- if str(tokens.get("tier") or "").lower() != tier or not tokens.get("signed_in_at"):
- tokens["tier"] = tier
- tokens["signed_in_at"] = int(time.time())
- if email:
- tokens["email"] = email
- _write_tokens(tokens)
- if as_json:
- click.echo(json.dumps(body, indent=2, sort_keys=True))
- return
- click.echo(f"Email: {email}")
- click.echo(f"Tier: {tier}")
- if status and status not in ("none", "active"):
- click.echo(f"Status: {status}")
- if expires:
- click.echo(f"Expires: {expires}")
- if body.get("credential") == "machine":
- label = str(body.get("machine_label") or "") or "this computer"
- click.echo(f"Machine: {label} ({body.get('machine_id') or '?'}) — app.kiln3d.com/settings/agent")
- # ═════════════════════════════════════════════════════════════════════
- # `kiln pair <code>` — web-initiated pairing
- # ═════════════════════════════════════════════════════════════════════
- #
- # The mirror image of ``kiln signin``: instead of this machine bootstrapping
- # an OAuth session from cold, the user has already signed in on the web
- # (usually right after upgrading their tier at app.kiln3d.com/checkout/
- # success → /connect). The workshop minted a short-lived code tied to
- # their session; ``kiln pair <code>`` hands the tokens to this machine
- # without any browser round-trip here.
- #
- # Why this is the preferred post-upgrade path (even though ``kiln signin``
- # still works): after paying, the user is already in a browser, already
- # signed in. Asking them to run ``kiln signin`` which opens ANOTHER
- # browser to sign in AGAIN is a jarring re-authentication. Pairing
- # reuses the session they already have in one command.
- def _hostname_label() -> str:
- """Best-effort human label for this machine, used on the workshop's
- paired-machines list. Never fatal — fall back to a generic string
- if hostname resolution fails (rare, but it happens in some container
- runtimes)."""
- try:
- import socket as _socket
- h = _socket.gethostname()
- # Strip ``.local`` and other zeroconf suffixes — users recognize
- # ``Adams-MacBook-Pro`` faster than ``Adams-MacBook-Pro.local``.
- for suf in (".local", ".lan", ".home"):
- if h.endswith(suf):
- h = h[: -len(suf)]
- return h or "this machine"
- except Exception:
- return "this machine"
- # ---------------------------------------------------------------------
- # AI-client identity detection
- # ---------------------------------------------------------------------
- #
- # Two rows that both read "Adams-MBP" on /settings/agent is the exact
- # ambiguity this helper exists to resolve. A user running Claude
- # Desktop + Claude Code + Cursor on one laptop needs to know which row
- # is which before they can meaningfully revoke. ``client_name``
- # captures the AI client; ``machine_label`` captures the host.
- #
- # Priority ladder (highest → lowest):
- #
- # 1. Explicit ``--client`` flag on the command — user knows best,
- # so shortcut the ladder.
- # 2. Environment-variable sniff. Most LLM surfaces export a
- # distinguishing env var when they spawn an MCP subprocess.
- # Order matters: CLAUDE_DESKTOP_SESSION beats CLAUDE_CODE_* because
- # a Claude Desktop session that happens to set both is still
- # semantically "Claude Desktop."
- # 3. Parent-process name (best-effort, Unix only). If env sniff
- # missed (older client versions that don't export a session var)
- # we try to read the parent's executable name. Only surface a
- # well-known set — anything else stays empty rather than leaking
- # a meaningless name like ``zsh``.
- # 4. Headless detection. If stdin isn't a TTY AND every sniff
- # returned nothing, assume this is an MCP-launched subprocess
- # with no distinguishing identity. "Unspecified (MCP)" beats
- # an empty string for giving the user a handle to reason about.
- # 5. Interactive prompt — the caller handles this when appropriate;
- # the helper itself only returns "" so the caller can decide
- # whether to prompt.
- #
- # None of this is security-bearing; it's identification only. A
- # malicious client that sets CLAUDE_DESKTOP_SESSION to impersonate a
- # Claude Desktop row is defeated by /settings/agent's Revoke button —
- # the user sees their OWN list and kicks off anything they don't
- # recognise. We just need the labels to be *usually correct* so the
- # list is useful in the common case.
- # Public map for testing — so test_auth_commands.py can assert the
- # priority order without duplicating the env-var names.
- _CLIENT_NAME_ENV_SIGNALS: tuple[tuple[str, str], ...] = (
- ("CLAUDE_DESKTOP_SESSION", "Claude Desktop"),
- ("CLAUDE_CODE_SESSION_ID", "Claude Code"),
- ("CURSOR_SESSION", "Cursor"),
- ("CURSOR_EDITOR", "Cursor"),
- ("CONTINUE_SESSION_ID", "Continue"),
- ("CODEX_SESSION_ID", "Codex"),
- )
- # Parent-process name → canonical client label. Lowercase match on
- # the basename so we don't care about ``.app`` suffixes, capitalisation
- # variants, or Electron helper names that embed the parent.
- _CLIENT_NAME_PROC_SIGNALS: tuple[tuple[str, str], ...] = (
- ("claude.app", "Claude Desktop"),
- ("claude", "Claude Desktop"),
- ("cursor.app", "Cursor"),
- ("cursor", "Cursor"),
- ("codex", "Codex"),
- ("continue", "Continue"),
- )
- def _sniff_client_from_env() -> str:
- """Walk the env-var priority ladder and return the first match.
- Kept pure so tests can patch ``os.environ`` without worrying about
- process-name side effects.
- """
- for var, label in _CLIENT_NAME_ENV_SIGNALS:
- if os.environ.get(var):
- return label
- # Generic CLAUDE_CODE_* fallback — new session-variable names ship
- # faster than this ladder can track them, so any CLAUDE_CODE_ prefix
- # with a non-empty value counts as Claude Code. Isolated to its own
- # branch (not a tuple entry) because we need the prefix-match, not
- # an equality-match.
- 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
- if key.startswith("CLAUDE_CODE_") and value:
- return "Claude Code"
- # VS Code without Cursor indicates the VS Code MCP host, which is
- # worth distinguishing from Cursor (they set similar pids but
- # different identity env). Placed last so explicit Cursor/Claude
- # signals always win.
- if os.environ.get("VSCODE_PID") and not os.environ.get("CURSOR_EDITOR"):
- return "VS Code"
- return ""
- def _sniff_client_from_parent_process() -> str:
- """Best-effort parent-process name lookup on Unix.
- Uses ``ps`` — present on every macOS and Linux install we care
- about, including minimal container images. Never raises;
- returns empty string on any failure (Windows, locked-down
- sandbox, truncated stat, unknown parent name).
- """
- try:
- ppid = os.getppid()
- if ppid <= 0:
- return ""
- # -p: filter by pid; -o comm=: just the executable name, no header.
- result = run_program.run(
- ["ps", "-p", str(ppid), "-o", "comm="],
- capture_output=True, text=True, timeout=2.0,
- )
- name = (result.stdout or "").strip().lower()
- if not name:
- return ""
- # ps returns the full path on some systems — take the basename.
- base = name.rsplit("/", 1)[-1]
- for match, label in _CLIENT_NAME_PROC_SIGNALS:
- if match in base:
- return label
- return ""
- except Exception:
- return ""
- def _is_stdin_tty() -> bool:
- """Wrapper so tests can patch the TTY check without touching
- ``sys.stdin`` (which click's CliRunner rewires anyway)."""
- try:
- return bool(sys.stdin.isatty())
- except Exception:
- return False
- def _detect_client_name() -> str:
- """Return a best-guess AI client name for this pairing.
- Priority: env-var signal > parent-process name > "Unspecified (MCP)"
- (headless fallback) > "" (caller decides whether to prompt).
- Explicit ``--client`` handling is the caller's responsibility; it
- takes precedence over this helper.
- """
- env_hit = _sniff_client_from_env()
- if env_hit:
- return env_hit
- proc_hit = _sniff_client_from_parent_process()
- if proc_hit:
- return proc_hit
- # Headless: no TTY and no env/proc signals → almost certainly an
- # MCP subprocess launched by a client we don't have a signature
- # for. Better to label it "Unspecified (MCP)" than leave it
- # blank, which shows as "Unspecified client" on /settings/agent
- # and is indistinguishable from a legit-but-unknown pairing.
- if not _is_stdin_tty():
- return "Unspecified (MCP)"
- return ""
- def _prompt_for_client_name() -> str:
- """Interactive TTY fallback — ask the user which agent this is for.
- Only called when env/proc sniffs came up empty AND stdin is a TTY.
- A headless caller never gets here (``_detect_client_name`` returns
- "Unspecified (MCP)" first). The default on Enter is ``[1] Claude
- Desktop`` — the most common answer, and the safest miss (the user
- can always edit the label from /settings/agent later).
- """
- options = [
- ("Claude Desktop", "Claude Desktop"),
- ("Claude Code", "Claude Code"),
- ("Cursor", "Cursor"),
- ("Codex", "Codex"),
- ("Other", None),
- ]
- click.echo(" Which agent is this pairing for?", err=True)
- for i, (label, _value) in enumerate(options, start=1):
- click.echo(f" [{i}] {label}", err=True)
- try:
- raw = click.prompt(
- " Choice", default="1", show_default=True,
- prompt_suffix=" ", err=True,
- )
- except (click.Abort, EOFError, KeyboardInterrupt):
- return ""
- try:
- idx = int(str(raw).strip())
- except (TypeError, ValueError):
- idx = 1
- if idx < 1 or idx > len(options):
- idx = 1
- label, value = options[idx - 1]
- if value is not None:
- return value
- # "Other" — free-text label, cap at 40 chars, strip non-printable
- # + surrounding whitespace. The server also caps at 40 (same as
- # machine_label); we trim here so the user sees their final label
- # without a server round-trip.
- try:
- free = click.prompt(
- " Label", default="", show_default=False,
- prompt_suffix=" ", err=True,
- )
- except (click.Abort, EOFError, KeyboardInterrupt):
- return ""
- cleaned = "".join(c for c in str(free or "")[:40] if c.isprintable()).strip()
- return cleaned
- def _resolve_client_name(explicit: str | None) -> str:
- """One entry point for both ``pair`` and ``invite`` so there's a
- single source of truth for the priority order.
- ``explicit`` is whatever ``--client`` captured, including the
- absent-flag sentinel ``None``. An explicit empty string ("" via
- ``--client ""``) is treated as "user wants no label" and short-
- circuits both the detection and the TTY prompt.
- """
- if explicit is not None:
- # User said what they wanted; honour it verbatim, just tidy
- # the visible characters + cap length. No prompt, no sniff.
- cleaned = "".join(c for c in str(explicit)[:40] if c.isprintable()).strip()
- return cleaned
- detected = _detect_client_name()
- if detected:
- return detected
- # Env + proc sniffs came up empty AND we're interactive — ask.
- # _detect_client_name already returned "Unspecified (MCP)" for
- # the non-TTY case, so reaching this branch means TTY is True.
- if _is_stdin_tty():
- return _prompt_for_client_name()
- return ""
- @click.command("pair")
- @click.argument("code", required=True)
- @click.option(
- "--client", "client",
- type=str, default=None,
- metavar="NAME",
- help=(
- "Label this pairing by the AI client running it — e.g. "
- "\"Claude Desktop\", \"Cursor\", \"Codex\". If omitted, Kiln "
- "auto-detects from your environment. On /settings/agent this "
- "shows alongside the hostname so you can tell two paired "
- "machines apart."
- ),
- )
- def auth_pair(code: str, client: str | None) -> None:
- """Pair this machine with your signed-in Kiln workshop session.
- After you upgrade on app.kiln3d.com, the workshop shows a pairing
- code. Run this command here to sync your tier to this machine —
- your MCP server picks it up immediately, no Claude Desktop restart
- required.
- The code is single-use and expires in 10 minutes. Generate a new
- one any time at app.kiln3d.com/connect.
- Accepts either the full ``KLN-ABCD-EFGH`` shape or just
- ``ABCD-EFGH`` (the prefix is added for you).
- """
- raw = (code or "").strip().upper()
- if not raw:
- raise click.ClickException("Missing pairing code. Usage: kiln pair <code>")
- # Strip any leading ``kiln pair`` the user may have accidentally
- # double-pasted from the copy button. Small courtesy, saves a
- # "why isn't this working" moment.
- for prefix in ("KILN PAIR ", "KILN PAIR\u00A0"):
- if raw.startswith(prefix):
- raw = raw[len(prefix):].strip()
- break
- # Tidy typos: some users drop the ``KLN-`` prefix. The server
- # accepts both shapes, but normalizing here means the terminal
- # banner we print on success shows the user what the server saw.
- if not raw.startswith("KLN-"):
- raw = f"KLN-{raw}"
- # Resolve the AI-client identity BEFORE printing the pairing banner
- # so the interactive prompt (if any) comes first — the user
- # shouldn't see "Pairing..." then get stopped with a question.
- client_name = _resolve_client_name(client)
- click.echo("")
- click.echo(f" Pairing {_hostname_label()} with your Kiln workshop\u2026", err=True)
- from kiln.auth_session import credential_fields, machine_signin_request
- resp = _http_post(
- "/api/auth/pairing/claim",
- {
- "code": raw,
- # This computer's own machine credential, named the way
- # /settings/agent will list it.
- **machine_signin_request(client_name, label=_hostname_label()),
- "client_name": client_name,
- },
- )
- if not resp.get("success"):
- # Server sends a machine-readable ``code`` field alongside the
- # human ``error`` so we can print tailored next-step guidance
- # without string-sniffing the error message.
- reason = str(resp.get("code") or "").lower()
- msg = resp.get("error") or "Pairing failed."
- if reason in ("not_found", "expired"):
- raise click.ClickException(
- f"{msg}\n\n Get a fresh code at app.kiln3d.com/connect."
- )
- if reason == "already_claimed":
- raise click.ClickException(
- f"{msg}\n\n If you paired on another machine, that's fine — "
- f"this machine just needs its own code."
- )
- if reason == "rate_limited":
- raise click.ClickException(
- f"{msg} Wait a minute and retry."
- )
- raise click.ClickException(msg)
- # Defensive response validation — the CLI MUST NOT write a partial
- # token file that silently degrades to free-tier on every tool call.
- # If the server says ``success`` but omits ``access_token`` (a failure
- # that surfaces as stale empty tokens in ~/.kiln/auth_tokens.json),
- # fail loudly instead of writing a lie.
- access_token = str(resp.get("access_token") or "")
- refresh_token = str(resp.get("refresh_token") or "")
- auth_uid = str(resp.get("auth_uid") or "")
- if not access_token:
- raise click.ClickException(
- "Pairing claim succeeded but the server response carried no "
- "access_token. Nothing was written locally. This is a "
- "server-side bug — please retry with a fresh code from "
- "app.kiln3d.com/connect, and if it persists: adam@kiln3d.com."
- )
- email = str(resp.get("email") or "")
- tier = str(resp.get("tier") or "free").lower()
- _complete_signin({
- "access_token": access_token,
- "refresh_token": refresh_token,
- "email": email,
- "auth_uid": auth_uid,
- "tier": tier,
- "has_entitlement": bool(resp.get("has_entitlement")),
- "signed_in_at": int(time.time()),
- **credential_fields(resp),
- }, door="pair")
- # Post-write smoke test — confirm the token the server just gave us
- # is accepted by /api/auth/whoami. The token IS written regardless
- # of smoke result: rolling back on a single-endpoint 401 would
- # incorrectly block pairing when only whoami has an upstream issue
- # (a server-side issuer misconfiguration can make whoami return 401 on
- # a JWT that is valid). Instead: write tokens, then WARN loudly if
- # whoami rejects them, so the operator has visibility without losing
- # the pair.
- try:
- smoke_status, _ = _http_get("/api/auth/whoami", bearer=access_token, timeout=5.0)
- except Exception:
- smoke_status = 0 # network / unexpected — skip the warning
- if smoke_status == 401:
- click.echo(
- " ⚠ Tokens written, but /api/auth/whoami rejected them "
- "(HTTP 401). Tools may still work if the gate accepts this "
- "token shape — verify with a real call. If every tool "
- "fails: adam@kiln3d.com (server-side issuer/validator "
- "mismatch).",
- err=True,
- )
- elif smoke_status and smoke_status >= 400:
- click.echo(
- f" ⚠ Tokens written, but /api/auth/whoami returned HTTP "
- f"{smoke_status}. This is non-fatal; tools will still be "
- "attempted.",
- err=True,
- )
- # Final one-line confirmation on stdout (so `kiln pair ... | tail
- # -1` captures it). Matches the `kiln signin` voice for source
- # consistency.
- click.echo(f"\u2713 Paired \u2014 {email} ({tier}).")
- # ═════════════════════════════════════════════════════════════════════
- # `kiln link` — CLI-initiated pairing (the reverse of `kiln pair`)
- # ═════════════════════════════════════════════════════════════════════
- #
- # The mirror image of ``kiln pair``: the user is already signed in on
- # THIS terminal (``kiln signin`` or ``kiln pair``) and wants to open a
- # fresh browser tab at app.kiln3d.com while carrying the same session.
- # ``kiln link`` mints a one-shot code that the browser's
- # /settings/agent page can claim.
- #
- # Why this matters: pairing is symmetric. No matter which surface you
- # sign in on first — web or terminal — you can pair the other in one
- # code, so nobody signs in twice.
- #
- # ``kiln invite`` is a hidden deprecation alias for this command that
- # prints a stderr warning and forwards. It is not the name: ``invite``
- # reads as "invite another USER to Kiln" (referral / team-invite
- # semantics) rather than "link my own browser tab to my own CLI
- # session", and the ``invite`` namespace is kept for a referral system.
- @click.command("link")
- @click.option(
- "--json", "as_json", is_flag=True, default=False,
- help="Emit the link response as JSON (for piping into scripts).",
- )
- @click.option(
- "--client", "client",
- type=str, default=None,
- metavar="NAME",
- help=(
- "Label this pairing by the AI client running it — e.g. "
- "\"Claude Desktop\", \"Cursor\". The browser's /settings/agent "
- "list shows it alongside the hostname so two paired machines "
- "on the same host are distinguishable. Auto-detected if omitted."
- ),
- )
- def auth_link(as_json: bool, client: str | None) -> None:
- """Generate a one-shot code to sign in on another device.
- Use this when you're signed in on THIS terminal (``kiln signin`` or
- ``kiln pair``) and want to open a fresh browser tab at
- app.kiln3d.com carrying the same session — no re-signin.
- How it works:
- 1. Run ``kiln link`` here.
- 2. The terminal prints a short code + the URL to visit.
- 3. Open app.kiln3d.com/settings/agent in a browser, sign in if
- you haven't already (SAME account), and paste the code into
- the "Link from another device" box.
- 4. The browser tab is now paired with this terminal's session.
- The code is single-use and expires in 10 minutes.
- """
- from kiln.auth_session import holds_machine_credential
- tokens = _read_tokens()
- access_token = str(tokens.get("access_token") or "")
- if not access_token:
- raise click.ClickException(
- "Not signed in on this terminal. Run `kiln signin` first, "
- "then `kiln link` to pair a browser tab."
- )
- if holds_machine_credential(tokens):
- # A computer's own sign-in is never handed to a browser: it would turn
- # a credential only this computer holds into a person's session.
- raise click.ClickException(
- "This computer has its own Kiln sign-in, which only it can use, so it "
- "can't sign a browser in. Open app.kiln3d.com and sign in there; this "
- "computer is already listed at app.kiln3d.com/settings/agent."
- )
- refresh_token = str(tokens.get("refresh_token") or "")
- # Resolve AI-client identity BEFORE minting — if we need to prompt
- # the user, we do it before the "Minting..." spinner so the flow
- # reads: prompt → mint → print code.
- client_name = _resolve_client_name(client)
- click.echo("")
- click.echo(" Minting a one-shot code for your browser\u2026", err=True)
- # POST /api/auth/pairing/invite — authed with our access_token via
- # the shared _http_post helper. 401 is surfaced as a ClickException
- # by the helper itself when a bearer is supplied.
- #
- # NOTE: the SERVER endpoint is still /api/auth/pairing/invite — this
- # is internal CLI/web wiring that users never see. Renaming it
- # would force every test + the web client to migrate in lockstep
- # for zero user-visible benefit, so we leave it. The user-facing
- # name (this command) is what changed.
- body = _http_post(
- "/api/auth/pairing/invite",
- {
- "refresh_token": refresh_token,
- "client_name": client_name,
- },
- bearer=access_token,
- )
- if not body.get("success"):
- raise click.ClickException(body.get("error") or "Could not mint a link code.")
- code = str(body.get("code") or "")
- expires_at = str(body.get("expires_at") or "")
- verify_url = str(body.get("verify_url") or "https://app.kiln3d.com/settings/agent")
- if as_json:
- click.echo(json.dumps(body, indent=2, sort_keys=True))
- return
- # Human output — match the `kiln signin` / `kiln pair` voice.
- # The code is the hero; render it letter-spaced so it's easy to
- # read off the terminal and type into a browser. A single blank
- # line of breathing room above and below.
- click.echo("")
- click.echo(f" {code}")
- click.echo("")
- click.echo(f" Enter this code at: {verify_url}", err=True)
- # Countdown — same 10-min window as the forward flow. Best-effort
- # parse; if the ISO timestamp doesn't round-trip (timezone weirdness
- # on some platforms) we just skip the countdown. Users have the
- # absolute timestamp from the API if they need it.
- try:
- from datetime import datetime as _dt
- from datetime import timezone as _tz
- exp_dt = _dt.fromisoformat(expires_at.replace("Z", "+00:00"))
- now = _dt.now(tz=_tz.utc)
- mins = max(0, int((exp_dt - now).total_seconds() // 60))
- if mins:
- click.echo(f" Expires in ~{mins} minute{'s' if mins != 1 else ''}.", err=True)
- except Exception:
- pass
- click.echo("")
- click.echo(
- " After you enter the code in the browser, that tab will be "
- "signed in with the same account as this terminal.",
- err=True,
- )
- # ═════════════════════════════════════════════════════════════════════
- # `kiln invite` — deprecated alias for `kiln link` (one-release grace)
- # ═════════════════════════════════════════════════════════════════════
- @click.command(
- "invite",
- hidden=True,
- context_settings={"ignore_unknown_options": True, "allow_extra_args": True},
- )
- @click.pass_context
- def _auth_invite_deprecated(ctx: click.Context) -> None:
- """[deprecated] alias for ``kiln link``.
- Forwards every flag through unchanged so existing scripts keep
- working. Will be removed one PyPI release after the rename ships.
- """
- click.echo(
- "warning: `kiln invite` has been renamed to `kiln link` "
- "(this alias will be removed in the next release).",
- err=True,
- )
- ctx.invoke(auth_link, **{k: v for k, v in _parse_link_args(ctx.args).items()})
- def _parse_link_args(args: list[str]) -> dict[str, Any]:
- """Tiny re-parser for the deprecation alias.
- Click's ``ctx.forward`` doesn't compose well with ``allow_extra_args``
- when the source and target commands have the same option set, so we
- reconstruct the kwargs by hand. Keep this dumb on purpose — only
- the two flags ``auth_link`` actually accepts (``--json``,
- ``--client``). Anything else is silently dropped (with a stderr
- warning above flagging the deprecation, the user already knows
- they're on a legacy code path).
- """
- out: dict[str, Any] = {"as_json": False, "client": None}
- i = 0
- while i < len(args):
- a = args[i]
- if a == "--json":
- out["as_json"] = True
- i += 1
- elif a == "--client" and i + 1 < len(args):
- out["client"] = args[i + 1]
- i += 2
- elif a.startswith("--client="):
- out["client"] = a.split("=", 1)[1]
- i += 1
- else:
- i += 1
- return out
- # ═════════════════════════════════════════════════════════════════════
- # registration
- # ═════════════════════════════════════════════════════════════════════
- def register_auth_cli(cli_group: click.Group) -> None:
- """Attach ``kiln signin`` / ``kiln signout`` / ``kiln whoami`` /
- ``kiln pair`` / ``kiln link``.
- If the group already has a command named ``login`` (the legacy
- identity-linking flow in kiln-pro's ``vcs_commands.cli_login``), we
- move it under ``kiln identity login`` so the top-level ``login``
- name is free for the OAuth device flow — which is the command the
- vast majority of users type first.
- Called from ``kiln.cli.main`` unconditionally so every install
- (free tier + Pro) gets ``kiln pair`` / ``kiln signin`` out of the
- box.
- """
- # Canonical names: signin / signout (match the web workshop + MCP tools).
- cli_group.add_command(auth_login)
- cli_group.add_command(auth_logout)
- cli_group.add_command(auth_whoami)
- cli_group.add_command(auth_pair)
- cli_group.add_command(auth_link)
- # Legacy aliases: `kiln signin` / `kiln logout` keep working for existing
- # scripts + muscle memory. Docs point at signin/signout.
- cli_group.add_command(auth_login, name="login")
- cli_group.add_command(auth_logout, name="logout")
- # Deprecation alias: `kiln invite` is an earlier name for this
- # command. Hidden from --help so docs point at `kiln link`, but
- # still callable so a script or muscle memory written against it
- # keeps working for ONE release.
- cli_group.add_command(_auth_invite_deprecated, name="invite")
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.