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, ["arguments"] = arguments }, () => { using var project = ProjectDirectory.Open(root); if (operation is "preview" or "apply" or "status") return changes.Execute(project, operation, arguments, allowWrite); return ProjectInspection.Query(project, operation, arguments); }).ToJsonString(); } }