mirror of
https://github.com/ajisaacs/OpenNest.git
synced 2026-12-05 12:59:27 -05:00
Agents could bring drawings in but only save .nest files, and could not describe an irregular sheet. New tools: export_plate and export_drawing (DXF/SVG/placement text, as File > Export), list_posts and post_nest (behind the same pre-post verification gate as desktop and console, with consent per call), and set_plate_outline (as the console's --outline). The shipped posts now copy to Posts/ beside the server on build and publish. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
308 lines
14 KiB
C#
308 lines
14 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.ComponentModel;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading;
|
|
using ModelContextProtocol.Server;
|
|
using OpenNest.Desktop;
|
|
using OpenNest.Diagnostics;
|
|
using OpenNest.IO;
|
|
|
|
namespace OpenNest.Mcp.Tools
|
|
{
|
|
/// <summary>
|
|
/// What leaves the session besides a .nest file: a plate or drawing as DXF or SVG, and CNC
|
|
/// output through a post processor, behind the same pre-post verification the desktop and
|
|
/// console run. Also the irregular sheet outline, which only a file can describe.
|
|
/// </summary>
|
|
[McpServerToolType]
|
|
public class OutputTools
|
|
{
|
|
private readonly NestSession _session;
|
|
|
|
public OutputTools(NestSession session)
|
|
{
|
|
_session = session;
|
|
}
|
|
|
|
/// <summary>Where post DLLs are looked for when a call names no directory.</summary>
|
|
internal static string DefaultPostsDirectory => Path.Combine(AppContext.BaseDirectory, "Posts");
|
|
|
|
[McpServerTool(Name = "set_plate_outline")]
|
|
[Description(
|
|
"Make an empty plate an irregular sheet (a remnant, a drop or a damaged sheet) from a DXF, DWG or SVG "
|
|
+ "file: its largest closed contour is the sheet and closed contours inside it are areas to keep "
|
|
+ "empty. The plate's size becomes the outline's bounding box. Only autonest_plate and autonest_job "
|
|
+ "with engine Irregular nest on an outlined sheet. Omit path to make the plate rectangular again "
|
|
+ "(it keeps the outline's bounding box as its size)."
|
|
)]
|
|
public string SetPlateOutline(
|
|
[Description("Index of the empty plate")] int plateIndex,
|
|
[Description("Absolute path to the DXF, DWG or SVG outline; omit to remove the plate's outline")]
|
|
string path = null,
|
|
[Description("How many of an SVG's units make an inch; required only when the file does not state its real-world size")]
|
|
double? svgUnitsPerInch = null
|
|
)
|
|
{
|
|
var plate = _session.GetPlate(plateIndex);
|
|
if (plate == null)
|
|
return $"Error: plate {plateIndex} not found";
|
|
if (plate.Parts.Count != 0)
|
|
return $"Error: plate {plateIndex} has parts; clear it first. Nothing changed.";
|
|
if (plate.CutOffs.Count != 0)
|
|
return $"Error: plate {plateIndex} has cutoff definitions. Nothing changed.";
|
|
|
|
if (string.IsNullOrWhiteSpace(path))
|
|
{
|
|
if (plate.Outline == null)
|
|
return $"Plate {plateIndex} is already rectangular: {plate.Size.Width:F2} x {plate.Size.Length:F2}";
|
|
plate.Outline = null;
|
|
return $"Removed the outline of plate {plateIndex}; it is a {plate.Size.Width:F2} x {plate.Size.Length:F2} rectangle.";
|
|
}
|
|
|
|
if (!File.Exists(path))
|
|
return $"Error: file not found: {path}";
|
|
|
|
SheetOutline outline;
|
|
try
|
|
{
|
|
var import = CadImporter.Import(
|
|
path,
|
|
new CadImportOptions
|
|
{
|
|
DrawingUnits = _session.Nest?.Units ?? default,
|
|
SvgUserUnitsPerInch = svgUnitsPerInch,
|
|
}
|
|
);
|
|
outline = SheetOutline.FromGeometry(import.Entities);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return $"Error: no sheet outline from '{path}': {ex.Message} Nothing changed.";
|
|
}
|
|
|
|
plate.Outline = outline;
|
|
var work = plate.WorkArea();
|
|
var sb = new StringBuilder();
|
|
sb.AppendLine($"Plate {plateIndex} is now an irregular sheet: {outline}");
|
|
sb.AppendLine($" Size (bounding box): {plate.Size.Width:F2} x {plate.Size.Length:F2}");
|
|
sb.AppendLine($" Material area: {outline.Area:F2}");
|
|
sb.AppendLine($" Areas to keep empty: {outline.Obstacles.Count}");
|
|
sb.AppendLine($" Work area (bounding box): {work.Width:F2} x {work.Length:F2}");
|
|
sb.AppendLine("Nest it with autonest_plate or autonest_job using engine Irregular.");
|
|
return sb.ToString();
|
|
}
|
|
|
|
[McpServerTool(Name = "export_plate")]
|
|
[Description(
|
|
"Write one plate to a file in the format its extension names: .dxf (the plate and its parts' "
|
|
+ "geometry), .svg (in the nest's units) or .txt (one line per part: drawing path | X,Y | rotation). "
|
|
+ "The plate is only read."
|
|
)]
|
|
public string ExportPlate(
|
|
[Description("Index of the plate to export")] int plateIndex,
|
|
[Description("Absolute path of the .dxf, .svg or .txt file to write")] string path,
|
|
[Description("For .svg only: write what laser software such as LightBurn needs (only cut and marked "
|
|
+ "geometry, each kind in its own layer color)")]
|
|
bool forLaserSoftware = false,
|
|
[Description("Replace the file if it already exists")] bool overwrite = false
|
|
)
|
|
{
|
|
var plate = _session.GetPlate(plateIndex);
|
|
if (plate == null)
|
|
return $"Error: plate {plateIndex} not found";
|
|
|
|
var format = PlateExport.FromPath(path);
|
|
if (format is null or PlateExportFormat.Image)
|
|
return "Error: the path must end in .dxf, .svg or .txt";
|
|
if (forLaserSoftware)
|
|
{
|
|
if (format != PlateExportFormat.Svg)
|
|
return "Error: forLaserSoftware applies only to .svg";
|
|
format = PlateExportFormat.SvgForLaser;
|
|
}
|
|
|
|
if (PrepareDestination(path, overwrite) is { } refusal)
|
|
return refusal;
|
|
|
|
try
|
|
{
|
|
PlateExport.Write(plate, _session.Nest?.Units ?? default, path, format.Value, writeImage: null);
|
|
}
|
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or NotSupportedException)
|
|
{
|
|
return $"Error: failed to write '{path}': {ex.Message}";
|
|
}
|
|
|
|
return $"Exported plate {plateIndex} ({plate.Parts.Count} parts) to {path}";
|
|
}
|
|
|
|
[McpServerTool(Name = "export_drawing")]
|
|
[Description(
|
|
"Write one drawing's cut program to a .dxf or .svg file (SVG in the nest's units). The drawing is only read."
|
|
)]
|
|
public string ExportDrawing(
|
|
[Description("Name of the drawing")] string drawing,
|
|
[Description("Absolute path of the .dxf or .svg file to write")] string path,
|
|
[Description("Replace the file if it already exists")] bool overwrite = false
|
|
)
|
|
{
|
|
var found = _session.GetDrawing(drawing);
|
|
if (found == null)
|
|
return $"Error: drawing '{drawing}' not found";
|
|
|
|
var extension = Path.GetExtension(path ?? "").ToLowerInvariant();
|
|
if (extension is not (".dxf" or ".svg"))
|
|
return "Error: the path must end in .dxf or .svg";
|
|
|
|
if (PrepareDestination(path, overwrite) is { } refusal)
|
|
return refusal;
|
|
|
|
try
|
|
{
|
|
if (extension == ".svg")
|
|
Svg.ExportProgram(found.Program, path, _session.Nest?.Units ?? default);
|
|
else
|
|
Dxf.ExportProgram(found.Program, path);
|
|
}
|
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or NotSupportedException)
|
|
{
|
|
return $"Error: failed to write '{path}': {ex.Message}";
|
|
}
|
|
|
|
return $"Exported drawing '{found.Name}' to {path}";
|
|
}
|
|
|
|
[McpServerTool(Name = "list_posts")]
|
|
[Description("List the post processors post_nest can use, from the Posts folder beside this server or postsDir.")]
|
|
public string ListPosts(
|
|
[Description("Folder holding post processor DLLs (default: Posts beside this server)")] string postsDir = null
|
|
)
|
|
{
|
|
var directory = postsDir ?? DefaultPostsDirectory;
|
|
var loaded = PostProcessorLoader.Load(directory);
|
|
|
|
var sb = new StringBuilder();
|
|
if (loaded.PostProcessors.Count == 0)
|
|
sb.AppendLine($"No post processors found in: {directory}");
|
|
else
|
|
{
|
|
sb.AppendLine($"Post processors ({directory}):");
|
|
foreach (var post in loaded.PostProcessors)
|
|
sb.AppendLine($" {post.Name}: {post.Description}");
|
|
}
|
|
foreach (var failure in loaded.Failures)
|
|
sb.AppendLine($" Failed to load {failure}");
|
|
return sb.ToString();
|
|
}
|
|
|
|
[McpServerTool(Name = "post_nest")]
|
|
[Description(
|
|
"Write CNC output (G-code) for every plate in the session through a post processor. Pre-post "
|
|
+ "verification runs first, as on the desktop: with any warning nothing is written unless "
|
|
+ "acknowledgeRisks is true for this call. Plan cutting (plan_cutting, apply_cutting_plan) first so "
|
|
+ "parts have lead-ins and a cut order. The post uses its saved settings on this PC."
|
|
)]
|
|
public string PostNest(
|
|
[Description("Post processor name, as list_posts shows it")] string post,
|
|
[Description("Absolute path of the CNC file to write; a multi-file post derives its files from it")]
|
|
string outputPath,
|
|
[Description("Explicitly accept the verification warnings this call reports, including possible head "
|
|
+ "crashes and machine or material damage, and post anyway. Applies to this call only.")]
|
|
bool acknowledgeRisks = false,
|
|
[Description("Replace output files that already exist")] bool overwrite = false,
|
|
[Description("Folder holding post processor DLLs (default: Posts beside this server)")] string postsDir = null,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(outputPath) || !Path.IsPathFullyQualified(outputPath))
|
|
return "Error: outputPath must be an absolute path";
|
|
|
|
var directory = postsDir ?? DefaultPostsDirectory;
|
|
var loaded = PostProcessorLoader.Load(directory);
|
|
var processor = loaded.PostProcessors.FirstOrDefault(p =>
|
|
string.Equals(p.Name, post, StringComparison.OrdinalIgnoreCase));
|
|
if (processor == null)
|
|
{
|
|
var available = loaded.PostProcessors.Count == 0
|
|
? $"No post processors found in: {directory}"
|
|
: $"Available: {string.Join(", ", loaded.PostProcessors.Select(p => p.Name))}";
|
|
return $"Error: post processor '{post}' not found. {available}";
|
|
}
|
|
|
|
var nest = PostedNest();
|
|
if (!nest.Plates.Any(p => p.Parts.Count != 0))
|
|
return "Error: no plate has parts; nothing to post";
|
|
|
|
if (processor is IPostProcessorNestAware nestAware)
|
|
nestAware.PrepareForNest(nest);
|
|
|
|
// A common line cut once needs a post that writes it; none falls back to cutting it twice.
|
|
try
|
|
{
|
|
CNC.CommonLineCuts.EnsurePostable(nest, processor);
|
|
}
|
|
catch (InvalidOperationException ex)
|
|
{
|
|
return $"Error: {ex.Message} No output was written.";
|
|
}
|
|
|
|
// Verification runs fresh on every call; its consent never outlives this call.
|
|
var verification = PostVerificationAnalyzer.AnalyzeForPost(nest, processor, cancellationToken);
|
|
var sb = new StringBuilder();
|
|
sb.AppendLine(verification.ToDisplayText());
|
|
if (!verification.CanPost(acknowledgeRisks))
|
|
{
|
|
sb.AppendLine("Posting blocked: review these warnings. No output was written. To accept the risks, "
|
|
+ "including possible head crashes and machine or material damage, call post_nest again with "
|
|
+ "acknowledgeRisks=true.");
|
|
return sb.ToString();
|
|
}
|
|
|
|
var outputs = processor is IMultiFilePostProcessor multiFile
|
|
? multiFile.GetOutputFiles(nest, outputPath).ToList()
|
|
: new List<string> { outputPath };
|
|
if (!overwrite && outputs.FirstOrDefault(File.Exists) is { } existing)
|
|
return sb + $"Error: {existing} already exists. Pass overwrite=true to replace it. No output was written.";
|
|
|
|
var dir = Path.GetDirectoryName(outputPath);
|
|
if (!string.IsNullOrEmpty(dir))
|
|
Directory.CreateDirectory(dir);
|
|
|
|
try
|
|
{
|
|
processor.Post(nest, outputPath);
|
|
}
|
|
catch (Exception ex) when (ex is InvalidOperationException or IOException or UnauthorizedAccessException)
|
|
{
|
|
return sb + $"Error: {processor.Name} failed: {ex.Message}";
|
|
}
|
|
|
|
foreach (var file in outputs)
|
|
sb.AppendLine($"Post: {processor.Name} -> {file}");
|
|
return sb.ToString();
|
|
}
|
|
|
|
/// <summary>The loaded nest when it is the whole session; otherwise a nest of everything in it.</summary>
|
|
private Nest PostedNest() =>
|
|
_session.Nest != null && _session.Plates.Count == 0 && _session.Drawings.Count == 0
|
|
? _session.Nest
|
|
: _session.Snapshot(null);
|
|
|
|
private static string PrepareDestination(string path, bool overwrite)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(path) || !Path.IsPathFullyQualified(path))
|
|
return "Error: path must be an absolute path";
|
|
if (!overwrite && File.Exists(path))
|
|
return $"Error: {path} already exists. Pass overwrite=true to replace it.";
|
|
|
|
var dir = Path.GetDirectoryName(path);
|
|
if (!string.IsNullOrEmpty(dir))
|
|
Directory.CreateDirectory(dir);
|
|
return null;
|
|
}
|
|
}
|
|
}
|