JDesignCAD / API 1.4 / 2026-10-16

Save and export API / MCP

1. Saving versus exporting

Use the application, worker, MCP server and SDK from the same distribution. Restart CAD and the MCP connection after updating.

Save and export are available through ICadFileApi and their MCP tools. Request acceptance is separate from successful file completion.

PurposeCallOn completion
Save the working drawingSaveDocumentAsync / cad_save_documentUpdates filename and clears dirty state
Write an exchange copyExportDocumentAsync / cad_export_documentPreserves filename, dirty state and Undo
1. Requestpath / format / revision2. runningsnapshot + conversion3. completedfilePath / bytes / sha256failed / cancelled → error.code + error.message
running is pending work. Only completed confirms a committed file.

No file dialog opens. The host captures a snapshot, converts it in a worker, then rechecks the drawing, target and license before committing. Changes or conversion failures prevent destination replacement. Geometry Undo does not undo file output.

ICadFileApi supplies five file methods. The MCP server exposes 36 tools, alongside 93 structured operations and interactive commands. Use is/TryCast to detect ICadFileApi; existing interface declarations are unchanged.

2. Formats and Free edition

formatExtensionUsePlanScope
jdc.jdcSave / copyFreeNative editing information
jdc.json.jdc.json / .jsonSave / copyFreeNative JSON
dwg / dxf.dwg / .dxfSave / copySTD / ProExchange; retain a JDC original
jww.jwwSave / copySTD / ProExisting 2D converter rules
p21 / sfc.p21 / .sfcSave / copySTD / ProSXF rejects objects outside XY
step.step / .stpCopy onlySTD / ProActive-model geometry
stl.stl / .stla / .stlbCopy onlyFreeTriangulated surfaces
obj.objCopy onlySTD / ProMesh plus MTL material file
svg.svgCopy onlySTD / ProSupported 2D objects, XY projection
ifc.ifcCopy onlySTD / ProSolids form one IFC component

There are 12 formats. Choose one format value; stp and json alias step and jdc.json. Extensions are not appended automatically. Free permits MCP, native JDC/JSON save or copy and STL export. Only the bundled DLL sample is allowed in Free. Custom DLL, exchange-format, sheet-metal and analysis restrictions remain.

Check Available in GetFileFormatsAsync / cad_get_file_formats. A refusal returns license_required and LicenseRestriction, including currentPlan and requiredPlans. Permission is checked at start and commit. The AI should explain the required plan, not bypass the restriction.

STL/OBJ omit lines, text and exact surface definitions; no exported surface means failure. Transfer the OBJ together with its additionalFiles MTL beside it. Overwriting an OBJ retains the old MTL. IFC accepts ifc4Advanced (default), ifc4Faceted or ifc2x3Faceted; multiple solids form one component.

Whole-document STEP/mesh/SVG/IFC export uses the active model. Exchange formats cannot guarantee round-tripping native data such as sheet-metal history. Keep an editable JDC and read Warnings. Available indicates license permission, not guaranteed conversion of arbitrary geometry.

3. Public method reference

Namespace: JDesignCAD.Api. Extension interface: ICadFileApi : ICadInteractionApi. LocalCadClient implements it as well.

GetFileFormatsAsync

Task<FileFormatInfo[]> GetFileFormatsAsync(
    CancellationToken cancellationToken = default);

Lists formats, extensions, CanSave/CanExport, Available, UnavailableCode and LicenseRestriction. Read-only; the host checks permission again when writing.

SaveDocumentAsync

Task<FileOperationInfo> SaveDocumentAsync(
    SaveDocumentRequest request,
    CancellationToken cancellationToken = default);

Saves the complete drawing. The initial running result acknowledges the request. Only completed updates the current filename and clears the dirty state.

ExportDocumentAsync

Task<FileOperationInfo> ExportDocumentAsync(
    ExportDocumentRequest request,
    CancellationToken cancellationToken = default);

Writes a copy of the complete drawing or explicit entities. Preserves current filename, dirty state and Undo history. Cannot target the current drawing file.

GetFileOperationAsync

Task<FileOperationInfo> GetFileOperationAsync(
    string operationId,
    CancellationToken cancellationToken = default);

Polls the original operationId. Repeat at a reasonable interval while running. Does not modify the drawing.

CancelFileOperationAsync

Task<FileOperationInfo> CancelFileOperationAsync(
    string operationId,
    CancellationToken cancellationToken = default);

Cancels before destination commit. Inspect the returned state. An already completed write cannot be undone by this method.

CancellationToken cancels waiting before a call starts or an individual call. Disconnecting or stopping polling does not cancel accepted work. Explicitly call CancelFileOperationAsync and inspect its result.

4. Request types and arguments

Argument (.NET / JSON)Meaning
DocumentId / documentIdFresh document ID; prevents writing the wrong drawing
ExpectedRevision / expectedRevisionFresh revision; changes during conversion are also checked
OperationId / operationIdNew UUID, D format. Same ID and payload only for transport retries
FilePath / filePathAbsolute path; parent folder must exist; extension must match format
Format / formatOne listed format; check CanSave/CanExport
Overwrite / overwriteDefault false. Set true explicitly to replace an existing file
TimeoutSeconds / timeoutSecondsDefault 300; 1..1800 seconds, including queued time after snapshot
EntityIds / entityIdsExport only. null=whole project; 1..1000 top-level IDs=selection
BasePoint / basePointExport with explicit selection only. WCS mm; semantics below
Ifc / ifcIFC export only. Output (default ifc4Advanced), optional Name (max 512 characters)

BasePoint is the JDC/JSON/DWG/DXF insertion base, SVG origin, or IFC component origin. It does not translate DWG/DXF geometry. Omitted selection insertion base is (0,0,0); whole-project output retains the existing base. BasePoint is rejected for STEP/STL/OBJ/JWW/SXF.

Exact record declarations are shipped in SDK/Api/Contracts/FileContracts.cs. SaveDocumentRequest and ExportDocumentRequest each require the first five arguments; subsequent parameters are optional.

5. C# examples

Examples assume D:\CAD_Output already exists. Replace it with your target folder. The first saves JDC; the second exports selected objects to DXF, requiring STD/Pro.

using JDesignCAD.Api;
// api: ICadApi supplied by the DLL host, or a LocalCadClient.
if (api is not ICadFileApi files)
    throw new NotSupportedException("Requires API 1.4");
var formats = await files.GetFileFormatsAsync(ct);
if (!formats.Any(x => x.Format == "jdc" && x.Available))
    throw new InvalidOperationException("Format unavailable");
var doc = await api.GetDocumentAsync(ct);
var request = new SaveDocumentRequest(
    doc.Id, doc.Revision, Guid.NewGuid().ToString("D"),
    @"D:\CAD_Output\part.jdc", "jdc", Overwrite: false);
var result = await files.SaveDocumentAsync(request, ct);
while (result.State == "running")
{
    await Task.Delay(500, ct);
    result = await files.GetFileOperationAsync(
        request.OperationId, ct);
}
if (result.State != "completed")
    throw new InvalidOperationException(
        $"{result.Error?.Code}: {result.Error?.Message}");
// result.FilePath / Bytes / Sha256 / Warnings
// File output is NOT reverted by geometry Undo.
var selection = await api.GetSelectionAsync(0, 1000, ct);
if (selection.Total == 0 || selection.Total > 1000)
    throw new InvalidOperationException("Select 1..1000 objects");
var request = new ExportDocumentRequest(
    selection.Document.Id, selection.Document.Revision,
    Guid.NewGuid().ToString("D"),
    @"D:\CAD_Output\part.dxf", "dxf",
    EntityIds: selection.Entities.Select(x => x.Id).ToArray(),
    BasePoint: new Point3(100, 200, 0));
var result = await files.ExportDocumentAsync(request, ct);
// Poll GetFileOperationAsync as in the save example.
// DXF/DWG basePoint sets INSBASE; it does not move WCS geometry.

On failure/cancellation, report Error.Code, Message and LicenseRestriction. After a transport interruption, resend the retained request unchanged. After fixing a failed request, refresh document information and use a new OperationId.

6. MCP and AI completion checks

ToolPurpose
cad_get_file_formatsDiscover formats and permissions
cad_save_documentStart a complete drawing save
cad_export_documentStart whole-project or selected export
cad_get_file_operationPoll state and result
cad_cancel_file_operationCancel before commit

1. Select a session with cad_list_sessions and read cad_get_document. 2. Check cad_get_file_formats. 3. Send the first JSON to cad_save_document. 4. Poll cad_get_file_operation with the second JSON every 0.5-1 seconds while running. Replace placeholder IDs and revision 42 with actual values.

{
  "sessionId": "<current-session-id>",
  "request": {
    "documentId": "<current-document-id>",
    "expectedRevision": 42,
    "operationId": "<new-UUID-in-D-format>",
    "filePath": "D:/CAD_Output/part.jdc",
    "format": "jdc",
    "overwrite": false,
    "timeoutSeconds": 300
  }
}
{
  "sessionId": "<same-session-id>",
  "operationId": "<same-operation-id>"
}

Report success only for completed, with filePath, bytes, sha256 and warnings. Include additionalFiles for OBJ. For failed/cancelled, report error.code/message and required plans when licenseRestriction is present. A successful status-query call with state=failed still means output failed. Immediate refusals use MCP isError=true; post-acceptance failures appear in the status result error. Do not call cad_commit_job.

7. Results, errors and recovery

FileOperationInfoMeaning
OperationId / DocumentId / SourceRevisionRequest ID, document ID, source revision
Kind / FilePath / Formatsave/export, absolute path, normalized format
Staterunning / completed / failed / cancelled
DocumentSavedtrue only for a completed Save
Bytes / Sha256Committed main-file size and SHA256
Warnings / AdditionalFilesConversion warnings; OBJ MTL path, size and SHA256
ErrorFileOutputError: Code / Message / Retryable / LicenseRestriction
CodeAction
license_requiredExplain required plan; do not blindly retry
unsupported_format / format_extension_mismatchCorrect format, use or extension
invalid_argument / directory_not_foundCheck arguments and parent folder
file_exists / active_document_targetConfirm overwrite intent; use Save for the current drawing
file_locked / access_denied / io_errorCheck locks, read-only state, permissions and storage
destination_changed / file_busyInspect concurrent writes or a changed target
revision_conflict / document_changed / cad_busyRefresh document information and inspect editing state
operation_conflict / file_operation_not_foundCheck reused IDs and originating session
file_operation_limit128-operation history limit; finish pending work then restart CAD
worker_unavailable / worker_failedCheck matching host and worker installation
export_failed / unsupported_geometryInspect geometry and format limitations
operation_timeout / cancelledIncomplete; review conditions before a new request

History lasts only for the CAD window session. A completed retry result is historical; it does not recreate a subsequently deleted file. If status is unavailable after restart, inspect the actual file before deciding what to do. Blindly retrying with a new ID can duplicate or overwrite output.