Export
exportUse this when you need to export geometry to a file. One exporter, selected by target:
target:'model' — export the script geometry to one file. Pass { file | code }, a required { output_path }, and { format }. Supported formats: stl (binary STL mesh), step (BREP CAD interchange), dxf (2D cut file for laser / waterjet / CNC: a flat part — plate, panel, extruded profile, in any orientation — exports its outline and holes in its own plane with exact arcs and circles; a sheet-metal part or a returned Region exports its flat pattern; a flat or sheet-metal part also returns sheet { thickness_mm, bend_count }, which a shop needs and the DXF does not carry; options.section { axis: "x"|"y"|"z", at } exports the cross-section of any part in world coordinates (plans, profiles); a multi-part model (cut list) writes all parts side by side on output_path, one layer per part, plus parts/.dxf per part (reported in part_files; options.layout 'sheet' writes the combined sheet only); a 3D part that is not a flat plate or panel fails with export.dxf.non-planar), 3mf (slicer-friendly mesh: one named object per part, colours as core-spec basematerials named by the part's engineering material; options.arrange 'plate' packs parts on the bed at Z=0 without overlap (options.orient puts each part's largest flat face down), 'assembled' keeps them together as one multi-part object for multi-colour prints; options.slicer 'bambu' | 'orca' | 'prusa' adds that slicer's per-object name + filament-slot sidecar — slot N is the Nth distinct colour/material), options.infill { fromFea: '' | true, bands?, pattern? } = stress-graded FDM infill (requires the local CalculiX + gmsh toolchain; without it the export fails with fea.solver.unavailable): solves the feaStudy and writes modifier volumes, each with its own infill density (Orca/Bambu format by default; options.slicer 'prusa' writes PrusaSlicer's format instead, since the two are not interchangeable); the result carries infill { bands, saving, images }), gcode (installed OrcaSlicer output; preserves G-code and returns optional gcode_stats with header generator identity and slicer-predicted time/material), glb (web-viewer / AR with PBR materials), asset-pack (deterministic zip of the script when the licence allows it, a default-parameter GLB, params JSON, README, SPDX licence, three.js viewer and sha256 manifest), obj (Wavefront indexed triangle mesh), ply (Stanford PLY triangle mesh, mm, Z-up, binary little-endian by default, with per-vertex normals and the part colour from .finish()/.material()/.color(); an assembly is one file with every part in world space), usd (ASCII USDA triangle mesh in millimeter, Z-up coordinates, with face-varying normals split at edges sharper than 30°; multi-part scenes emit one named mesh per part), svg-drawing (third-angle engineering-drawing sheet: front/top/left + isometric views, hidden edges dashed, tangent edges thin, overall bounding-box dimensions, title block; assemblies are drawn with inter-part occlusion; pass options.annotations to dimension specific features instead of the bounding box; pass options.exploded { factor, mode } to explode the isometric cell, options.balloons to number parts from the BOM, and options.partsList for an item/name/qty/material table above the title block). overall bounding-box dimensions, title block; assemblies are drawn with inter-part occlusion; pass options.annotations to dimension specific features instead of the bounding box, options.autoAnnotate to derive datums A/B/C, grouped hole callouts with position tolerances, hole positions, overall size, radius and chamfer callouts, flatness and an ISO 2768 note from the geometry (the result carries drawing_report with placed / overlapped counts), and options.sections for real section views on any cutting plane). pdf-drawing (the same sheet — views, dashed hidden lines, dimensions, hole callouts, GD&T, sections, parts list — as a printable vector PDF on a standard sheet, one call: ISO a4|a3|a2|a1|a0 or ANSI ansi-a…ansi-e landscape, default a3, or sheet "auto" / "auto-ansi" for the smallest sheet that holds the views at 1:1; the drawing scale is picked to fit; projection "third" (default) or "first" arranges the views and draws the matching symbol; a full title block carries title, part name, material, scale, units, sheet size, date and revision, settable through options.title / partName / material / revision / date; overall dimensions are the default; request inferred callouts and tolerances explicitly with options.autoAnnotate). Robot descriptions: urdf (tree-topology robot description), srdf (motion-planning semantics layered over the URDF), sdf-gazebo (SDFormat 1.10 with native ball joints, closed loops, and solved per-link poses), usd-isaac (ASCII USD physics stage: PhysicsArticulationRootAPI root, one rigid body per link at its solved pose with mass / centre of mass / principal inertia, PhysicsFixedJoint/PhysicsRevoluteJoint/PhysicsPrismaticJoint per mate with token axis, two-sided joint frames and limits, UsdPreviewSurface materials from the part appearance, and joint drives only when declared in options.drives { : { stiffness, damping, maxForce?, targetPosition? } }; options.collisionApproximation is convexHull | convexDecomposition; planar/cylindrical/pin_slot/ball mates fail closed with export.usd.joint-unsupported). bom-csv / bom-json (bill of materials over assembly.model()/solvedModel(): one row per distinct part — grouped by geometry/catalog identity, not name — with real instance quantity, kind, material, density, mass, bbox, fabrication process (
process+processSource), declared stock when present, and catalog provenance for purchased parts; same numbers as inspect({ of: 'bom' })). order-pack (a zip: one single-body file per fabricated part — STEP always, plus STL for 3d-print and DXF for sheet-cut rows, per-part drawing PDFs where available — with bom.csv/bom.json, vendor paste handoff texts for purchased rows and a machine-readable manifest; options processes / items narrow which rows are packed; nothing is uploaded). bend-table (tube bender tables over tube() records: one .csv per tube with the LRA bend table, XYZ points, cut length and last straight; output_path is a DIRECTORY and the written files are reported in table_files; a script with no tube() fails with export.bend-table.no-tubes, and a script whose tube gates report errors writes nothing). urdf and sdf-gazebo also write one meshes/.stl per link, and usd-isaac one meshes/.usda mesh layer per link, next to output_path (reported in mesh_files) — ship the whole directory to the consumer. STL exports run a watertight verify by default; failures return ok: false with export.mesh.not-watertight (open-edge count + up to 5 crack-cluster locations) but the file is still written so the broken mesh can be inspected. STEP exports check B-rep validity and mesh watertightness by default; failures return ok: false with export.brep.invalid or export.mesh.not-watertight, while keeping the STEP file for inspection. Set options.verify: false or pass { no_verify: true } to skip STEP checks. Optional { feature_id } selects which feature to export (default: last). Optional { options } carries per-format options bag (see the kernelcad-mcp skill for the per-format keys: step unit/verify, stl tolerance/angularToleranceDeg/verify, dxf layers/tolerance/unit/section/layout, 3mf tolerance/angularToleranceDeg/printUnit/embedSource/arrange/orient/slicer/printer/infill, obj tolerance/angularToleranceDeg, glb axis/draco, ply encoding/normals/colors). A requested mesh tolerance is checked against capped samples on the exact B-rep surfaces and the exported triangles; mesh_deviation reports that sampled maximum and p95, not a certified global bound.target:'part' — export solved-assembly parts as individual binary STL files in their modeled (world-frame) positions. Pass { file | code }, plus { part, output_path } for one part or { output_dir } for all parts (files land at <output_dir>/.stl). A watertight verify runs on every exported mesh by default and fails the call with export.mesh.not-watertight; unknown part names fail with export.part.not-found listing the valid names. Pass { no_verify: true } to skip the watertight gate. target:"part" options: { tolerance?: mm (finite, >= 0.001), angularToleranceDeg?: degrees }; each written STL reports mesh_deviation alongside watertight. Geometry-quality gate (both targets; formats stl, step, 3mf, obj, ply, gcode): every solid body (each assembly part) is screened for BREP faces below tiny_face_area_mm2 (default 0.01 mm²) and edges below short_edge_length_mm (default 0.1 mm), the same thresholds as verify({ check: 'geometry-quality' }) without its symmetry sampling. quality_gate 'warn' (default) exports and returns geometryQuality { ok, tinyFaces, shortEdges, worst: up to 5 { part, kind, id, location, size, unit }, thresholds, parts } plus warn diagnostics export.geometry-quality.tiny-faces / export.geometry-quality.short-edges; 'block' makes them errors and writes no file (ok: false); 'off' skips the screen. Shells, mesh bodies and bodies past the face budget are skipped with info export.geometry-quality.skipped. All params except
targetare forwarded verbatim; each target fails closed on its own missing required params. Hosted server: the file is written on the kernelCAD server, NOT on the caller's machine. The result carriesdownloads[]— an HTTPSurlper file (expires after 24 h; give it to the user) — Small text files an agent can read (SVG, DXF, URDF, JSON, CSV; up to 32 KB) also come inline as an embedded resource; STEP, STL, 3MF and GLB are link-only — do not fetch them into your context, give the user the link.output_pathonly names the file; the returnedoutput_pathis a server-side path, usable only asfilein later calls to this server. HEAVY FORMATS (step/stl/3mf/glb): if OCCT serialization outlives the client tool-call limit, this tool returns { ok:true, status:"running", code:"export.deferred", job_id } while the export continues on the server — poll by calling export({ job_id }) until status is done/failed. CRITICAL: open_in_studio / paint does NOT need STEP. On export.deferred or any STEP stall, call open_in_studio immediately for the shaded widget; do not block paint on export.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| code | No | Inline kernelCAD script source. | |
| file | No | Path to a .kcad.ts script file. Hosted: `code`, `project:<slug>` (head), or a Studio `/p/<slug>?version=N` link (pinned); no local files. | |
| part | No | target:'part' — part name for single-part export, or 'all'. | |
| format | No | target:'model' — output file format (required for that target). | |
| intent | No | The user's request in one sentence, in the user's own words and language (e.g. 'M4 bracket for a 25 mm tube, print on Bambu A1'). Helps kernelCAD improve; leave out personal data. | |
| job_id | No | Poll an existing hosted export job using the job_id returned by export.deferred. Pass only job_id to retrieve its status or completed downloads. | |
| target | No | Which exporter to run: 'model' (whole-script geometry to one file) or 'part' (per-part STLs from a solved assembly). | |
| options | No | target:'model' — optional per-format options bag. The top-level format selects these options. If supplied, options.format must match it. step: { unit?: "mm"|"cm"|"in", verify?: boolean } (verify defaults to true and checks B-rep validity plus mesh watertightness; false skips both). stl: { verify?: boolean, tolerance?: mm (finite, >= 0.001; absolute sampled chord-deviation target), angularToleranceDeg?: degrees }. dxf: { layers?, unit?: "mm"|"cm"|"in", tolerance?, section?: { axis: "x"|"y"|"z", at: mm }, sectionLayers?: { axis: "x"|"y"|"z", layers: [{ name, at: mm, omitSharedWith?: earlier layer name }] }, layout?: "per-part"|"sheet" }. Use sectionLayers on one selected solid to write explicit section planes into named layers. omitSharedWith removes congruent closed contours from the named earlier layer and fails if any are missing. Section planes and layer names are supplied by the caller. 3mf: { tolerance?: mm (finite, >= 0.001), angularToleranceDeg?: degrees, printUnit?: "mm"|"cm"|"in", embedSource?, arrange?: "none"|"plate"|"assembled", orient?: boolean, slicer?: "generic"|"bambu"|"orca"|"prusa", printer?: printer profile id, one of "generic-fdm"|"bambu-a1-mini"|"bambu-a1"|"bambu-p1s"|"bambu-p1p"|"bambu-x1c"|"bambu-x1e"|"bambu-h2d"|"bambu-h2s"|"prusa-mini-plus"|"prusa-mk4s"|"prusa-core-one"|"prusa-xl"|"creality-ender-3-v3"|"creality-k1"|"creality-k1-max"|"creality-k2-plus"|"elegoo-neptune-4-pro"|"anycubic-kobra-3"|"voron-2.4-250"|"voron-2.4-300"|"voron-2.4-350"|"ultimaker-s5" (default "generic-fdm"; sets the bed for arrange and the slicer default; an unknown id is refused with the valid list; CLI: kernelcad print printers) }; parts that do not fit the bed are still written and reported as warn diagnostics export.3mf.plate-overflow / export.3mf.exceeds-bed, whose hint names the smallest profiles the layout fits on. gcode: { printer?: printer profile id, layerHeight?: mm, infill?: percent, supports?: boolean, material?: string }; requires a locally installed OrcaSlicer. Returns slicer predictions as gcode_stats; does not start a printer. glb: { axis?: "y-up"|"z-up", draco?: false, style?: "pbr"|"lowpoly", lowpoly?: { angularDeg?: 5..60 (default 30, about 12 segments per circle), maxTriangles?: number }, units?: "mm"|"m" (default "m", the glTF length unit) }. Both GLB styles default to metres and scale kernelCAD millimetre geometry at the scene root, so standard glTF viewers show the authored physical size. units:"mm" keeps raw millimetre coordinates and records that choice in asset.extras.kernelcad.units for consumers that read kernelCAD metadata; standard viewers still interpret raw coordinates as metres. style "lowpoly" writes a faceted, flat-shaded game asset with every opaque part coloured through COLOR_0 on one shared material "kernelcad-palette" (merges to one draw call); asset.extras.kernelcad carries stats { triangles, sizeM, minUpM, materials, drawCalls, parts, hasRig, hasIk } and palette zones; exceeding maxTriangles fails with export.glb.triangle-budget. asset-pack takes no extra keys: it zips the default-parameter GLB (named materials and mesh stats) with the script when the licence allows it, params JSON, a knob README, an SPDX licence, a three.js viewer and a sha256 manifest. obj: { tolerance?: mm (finite, >= 0.001), angularToleranceDeg?: degrees }; usd writes ASCII USDA (millimeter, Z-up). ply: { encoding?: "binary"|"ascii" (default "binary" = binary_little_endian), normals?: boolean (default true; vertices split at creases over 30°), colors?: "vertex"|"face"|"none" (default "vertex": uchar red/green/blue per vertex; "face" puts them on the face element) }; any other key or value fails with export.ply.invalid-options. svg-drawing: { views?: ["front"], sheet?: "a4"|"a3" (or any pdf-drawing sheet), layoutRepair?: boolean, projection?, titleBlock?: { title?, partName?, material?, revision? }, modelName?, date?, annotations?, exploded?: { factor, mode? }, balloons?, partsList?, sections?, autoAnnotate? }. Pass views:["front"], ["top"], or ["left"] for one centred orthographic view in SVG or PDF; omit views for four views. Single-view sheets require annotations on the selected view and reject isometric balloons and exploded overlays. svg-drawing annotations is an array of authored dimensions/notes, each { kind: "linear"|"radius"|"diameter"|"angular"|"note", view?: "front"|"top"|"left"|"iso", text?, offset? } plus kind-specific geometry: linear { from, to }, radius/diameter { edge: EdgeQuery }, angular { from: EdgeQuery, to: EdgeQuery }, note { at, text }. from/to/at anchors are an [x,y,z] model point, { edge: EdgeQuery } or { face: FaceQuery }. Supplying any annotation REPLACES the automatic bounding-box dimensions; an annotation whose query resolves to zero or multiple matches fails the export rather than being dropped. svg-drawing sections is an array of { plane: "xy"|"xz"|"yz"|{ origin, normal }, label } (any non-zero normal). svg-drawing autoAnnotate is true or { tolerance?: "ISO2768-f"|"ISO2768-m"|"ISO2768-c", datums?: "auto"|[{ label, face: FaceQuery }], include?: ["datums"|"flatness"|"holes"|"hole-positions"|"overall"|"fillets"|"chamfers"|"general-tolerance"], dimensioningStyle?: "baseline"|"chain"|"symmetry" }; datums and tolerances declared in the script with shape.datum() / shape.tolerance() override the automatic ones. pdf-drawing: { sheet?: "a4"|"a3"|"a2"|"a1"|"a0"|"ansi-a"|"ansi-b"|"ansi-c"|"ansi-d"|"ansi-e"|"auto"|"auto-ansi" (default "a3"), projection?: "third"|"first", title?, partName?, material?, revision?, date? (default today), modelName?, views?: ["front"], annotations?, sections?, exploded?, balloons?, partsList?, autoAnnotate?, layoutRepair?: boolean (legacy sheet-only repair) } — the svg-drawing keys mean the same. Mechanical SVG/PDF also accept visualQa?: { autoRepair?: boolean, maxAttempts?: 1|2|3 }, the preferred end-to-end QA path. The drawing_report.visualQa covers actual SVG/PDF layout, critical requirements, verified PDF text and accepted/rejected repair attempts. A clean PDF drawing does not certify physical fit or tolerances. layoutRepair is retained for compatibility but must not be combined with visualQa. Mechanical SVG/PDF also accept draftingProfile?: "general"|"machining"|"sheet-metal" or { id, name, sheet, projection, dimensioningStyle, tolerance?, notes? }, with explicit options overriding profile defaults. Functional drawing review: shape.drawingReview(plan) source declarations merge with reviewPlans?: additional plans; decisionResolutions?: { [encodeURIComponent(planId)+":"+encodeURIComponent(decisionId)]: { note, provenance } }. drawing_report.review reports declared geometric-callout coverage and unresolved engineering decisions. requireCompleteReview?: true rejects incomplete/not-declared mechanical reviews before export; architectural style rejects review contracts. Coverage is not engineering certification. annotationOverrides?: { [drawing_report.annotations[i].id]: { suppress?, text?, view?, offset? } }; offset is extra nonnegative sheet mm. Text edits primary labels while preserving attached FCFs; datum/standalone FCF text is changed in its declaration instead. Suppressed rows remain in the report but not visible counts. Missing IDs warn after geometry edits. Authored annotations can set id for stable review identity. svg-drawing and pdf-drawing also take style?: "mechanical" (default, the part sheet) | "architectural" (a floor plan for a building or room model: section about 1 m above the floor with filled cut walls, wall / opening chain dimensions and overall sizes, room labels with net area, scale bar, north arrow; millimetres, or feet-inches when the model is in whole feet / inches) and plan?: { units?: "metric"|"imperial", cutHeight?: mm above the floor, rooms?: [{ name, at: [x, y] }], northDeg?: degrees clockwise from sheet up }. A building-sized model drawn in the default style gets a drawing.style.architectural-suggested warning. | |
| no_verify | No | Skip the default STL/STEP validity and watertightness gates. | |
| feature_id | No | target:'model' — optional FeatureId to export; defaults to last. | |
| output_dir | No | target:'part' — destination directory (all-parts mode); files are <dir>/<part>.stl. Hosted server: only the file name is used; the file is written to a server-owned directory and returned as a download link. | |
| output_path | No | Destination path (a directory for format 'bend-table'). target:'model' — the export file (required). target:'part' — single-part .stl path. Hosted server: only the file name is used; the file is written to a server-owned directory and returned as a download link. | |
| quality_gate | No | Geometry-quality gate for stl/step/3mf/obj/ply/gcode (both targets): 'warn' exports and reports geometryQuality + warn diagnostics, 'block' fails the export (nothing written) when tiny faces or short edges are found, 'off' skips it. | warn |
| tiny_face_area_mm2 | No | Quality gate threshold: faces with BREP area below this (mm²) are tiny. Default 0.01; 0 disables. | |
| short_edge_length_mm | No | Quality gate threshold: edges shorter than this (mm) are short. Default 0.1; 0 disables. |
Output Schema
| Name | Required | Description | Default |
|---|---|---|---|
No arguments | |||