using PLCSharp.Models; using System.Text.Json.Nodes; namespace PLCSharp.Mcp; internal sealed class ProjectGateway(string root, bool allowWrite) { private readonly ProjectChanges changes = new(); private readonly object gate = new(); public string Call(string operation, JsonObject arguments) { try { lock (gate) return Dispatch(operation, arguments); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException or TimeoutException or System.Text.Json.JsonException) { throw new ModelContextProtocol.McpException(ex.Message, ex); } } private string Dispatch(string operation, JsonObject arguments) { if (operation == "apply" && !allowWrite) throw new InvalidOperationException("Start MCP with --allow-write to save."); return ProjectPipe.Call(root, new() { ["operation"] = operation == "apply" ? "applyAgentConfirmed" : operation, ["arguments"] = arguments }, () => { using var project = ProjectDirectory.Open(root); if (operation is "previewBatch" or "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewVisionAssetRename" or "previewObjectEdit" or "previewObjectRename" or "previewDeviceRename" or "previewUndo" or "apply" or "status") return changes.Execute(project, operation, arguments, allowWrite, _ => ProjectChanges.AgentApproval(arguments)); return ProjectInspection.Query(project, operation, arguments); }).ToJsonString(); } }