Preview and apply scoped MCP edits with editor approval and conflict checks
This commit is contained in:
parent
46dc6282fc
commit
444953d81a
@ -3,15 +3,17 @@ using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PLCSharp.Mcp;
|
||||
|
||||
if (args.Length != 2 || args[0] != "--project" || !File.Exists(Path.Combine(args[1], "project.json")))
|
||||
bool allowWrite = args.Length == 3 && args[2] == "--allow-write";
|
||||
if ((args.Length != 2 && !allowWrite) || args[0] != "--project" || !File.Exists(Path.Combine(args[1], "project.json")))
|
||||
{
|
||||
Console.Error.WriteLine("Usage: PLCSharp.Mcp --project <project directory>");
|
||||
Console.Error.WriteLine("Usage: PLCSharp.Mcp --project <project directory> [--allow-write]");
|
||||
return 2;
|
||||
}
|
||||
var builder = Host.CreateApplicationBuilder();
|
||||
builder.Logging.ClearProviders();
|
||||
builder.Logging.AddConsole(options => options.LogToStandardErrorThreshold = LogLevel.Trace);
|
||||
builder.Services.AddSingleton(new ProjectGateway(Path.GetFullPath(args[1])));
|
||||
builder.Services.AddSingleton(new ProjectGateway(Path.GetFullPath(args[1]), allowWrite));
|
||||
builder.Logging.SetMinimumLevel(LogLevel.Warning);
|
||||
builder.Services.AddMcpServer().WithStdioServerTransport().WithTools<ProjectTools>();
|
||||
await builder.Build().RunAsync();
|
||||
return 0;
|
||||
|
||||
@ -3,11 +3,30 @@ using System.Text.Json.Nodes;
|
||||
|
||||
namespace PLCSharp.Mcp;
|
||||
|
||||
internal sealed class ProjectGateway(string root)
|
||||
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)
|
||||
{
|
||||
using var project = ProjectDirectory.Open(root);
|
||||
return ProjectInspection.Query(project, operation, arguments).ToJsonString();
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@ -7,6 +7,16 @@ namespace PLCSharp.Mcp;
|
||||
[McpServerToolType]
|
||||
internal sealed class ProjectTools(ProjectGateway gateway)
|
||||
{
|
||||
[McpServerTool(Name = "preview_changes"), Description("Preview a comment change to one recipe, variable or workflow. Returns a draft ID and before/after values. No file is written.")]
|
||||
public string PreviewChanges(string kind, string id, string comment) =>
|
||||
gateway.Call("preview", new() { ["kind"] = kind, ["id"] = id, ["comment"] = comment });
|
||||
|
||||
[McpServerTool(Name = "apply_changes"), Description("Save an existing preview using its draft ID. Requires write-enabled launch. An open editor requests user confirmation.")]
|
||||
public string ApplyChanges(string draftId) => gateway.Call("apply", new() { ["draftId"] = draftId });
|
||||
|
||||
[McpServerTool(Name = "get_change_status", ReadOnly = true), Description("Inspect a pending, rejected or saved draft.")]
|
||||
public string GetChangeStatus(string draftId) => gateway.Call("status", new() { ["draftId"] = draftId });
|
||||
|
||||
[McpServerTool(Name = "find_references", ReadOnly = true), Description("Find C# references to a Variables, SystemVariables or Workflows ID within its recipe. Dynamic hits require human review.")]
|
||||
public string FindReferences(string kind, string id) => gateway.Call("references", new() { ["kind"] = kind, ["id"] = id });
|
||||
|
||||
|
||||
@ -24,6 +24,19 @@ namespace PLCSharp
|
||||
{
|
||||
internal bool SwitchingProject { get; set; }
|
||||
private Mutex mutex;
|
||||
private ProjectPipe projectPipe;
|
||||
|
||||
internal void AttachProjectPipe(string root)
|
||||
{
|
||||
projectPipe ??= new ProjectPipe(root, request =>
|
||||
Dispatcher.Invoke(() => Container.Resolve<GlobalModel>().HandleAiRequest(request)));
|
||||
}
|
||||
|
||||
protected override void OnExit(ExitEventArgs e)
|
||||
{
|
||||
projectPipe?.Dispose();
|
||||
base.OnExit(e);
|
||||
}
|
||||
|
||||
//第1执行
|
||||
/// <summary>
|
||||
@ -51,11 +64,17 @@ namespace PLCSharp
|
||||
ProjectDirectory project;
|
||||
try
|
||||
{
|
||||
project = args.Length == 2 && (switching || args[0] == "--project")
|
||||
? ProjectDirectory.Open(args[1]) : ProjectDirectory.New();
|
||||
if (args.Length == 2 && (switching || args[0] == "--project"))
|
||||
{
|
||||
AttachProjectPipe(args[1]);
|
||||
project = ProjectDirectory.Open(args[1]);
|
||||
}
|
||||
else project = ProjectDirectory.New();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
projectPipe?.Dispose();
|
||||
projectPipe = null;
|
||||
MessageBox.Show($"无法打开工程:{ex.Message}", "PLCSharp");
|
||||
project = ProjectDirectory.New();
|
||||
}
|
||||
|
||||
@ -8,6 +8,46 @@ public partial class GlobalModel
|
||||
{
|
||||
internal ProjectDirectory Project { get; }
|
||||
public string ProjectLocation => Project.Root ?? "未保存工程";
|
||||
public bool AllowAiAccess { get; set; }
|
||||
private DelegateCommand copyMcpConfig;
|
||||
public DelegateCommand CopyMcpConfig => copyMcpConfig ??= new DelegateCommand(() =>
|
||||
{
|
||||
if (Project.Root == null) { SendInfoDialog("请先保存工程。"); return; }
|
||||
var exe = System.IO.Path.Combine(AppContext.BaseDirectory, "PLCSharp.Mcp.exe");
|
||||
if (!System.IO.File.Exists(exe))
|
||||
{
|
||||
var picker = new OpenFileDialog { Title = "选择 MCP 服务程序", Filter = "PLCSharp.Mcp.exe|PLCSharp.Mcp.exe" };
|
||||
if (picker.ShowDialog() != true) return;
|
||||
exe = picker.FileName;
|
||||
}
|
||||
var config = new { mcpServers = new { plcsharp = new { command = exe,
|
||||
args = new[] { "--project", Project.Root, "--allow-write" } } } };
|
||||
Clipboard.SetText(System.Text.Json.JsonSerializer.Serialize(config, new System.Text.Json.JsonSerializerOptions { WriteIndented = true }));
|
||||
SendInfoDialog("已复制当前工程的 MCP 配置。仅需读取时可移除 --allow-write。");
|
||||
});
|
||||
private readonly ProjectChanges aiChanges = new();
|
||||
|
||||
internal System.Text.Json.Nodes.JsonNode HandleAiRequest(System.Text.Json.Nodes.JsonObject request)
|
||||
{
|
||||
if (!AllowAiAccess) throw new InvalidOperationException("请在机种配方页面启用 AI 访问。");
|
||||
string operation = (string)request["operation"];
|
||||
var args = request["arguments"].AsObject();
|
||||
if (operation is "preview" or "apply" or "status")
|
||||
{
|
||||
if (operation == "apply" && (ModeState.State.Execute || WorkflowsModel.IsBusy))
|
||||
throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。");
|
||||
return aiChanges.Execute(Project, operation, args, true, change =>
|
||||
MessageBox.Show($"{change.Path}\n{change.Kind} / {change.Name}\n\n原备注:{change.Before}\n新备注:{change.After}",
|
||||
"应用 AI 修改", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes);
|
||||
}
|
||||
var result = ProjectInspection.Query(Project, operation, args);
|
||||
if (operation == "summary")
|
||||
{
|
||||
result["source"] = "editor";
|
||||
result["currentRecipeId"] = CurrentRecipe.ID.ToString();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
private AsyncDelegateCommand<string> projectManage;
|
||||
public AsyncDelegateCommand<string> ProjectManage => projectManage ??= new AsyncDelegateCommand<string>(ManageProjectAsync);
|
||||
|
||||
@ -24,6 +64,7 @@ public partial class GlobalModel
|
||||
var root = Project.Root ?? ChooseFolder("选择空文件夹以保存工程");
|
||||
if (root == null) return false;
|
||||
Project.Save(root);
|
||||
((App)Application.Current).AttachProjectPipe(root);
|
||||
RaisePropertyChanged(nameof(ProjectLocation));
|
||||
foreach (var recipe in Recipes)
|
||||
{
|
||||
|
||||
117
PLCSharpWpf/Models/ProjectChanges.cs
Normal file
117
PLCSharpWpf/Models/ProjectChanges.cs
Normal file
@ -0,0 +1,117 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace PLCSharp.Models;
|
||||
|
||||
public sealed record ProjectChange(Guid DraftId, Guid ProjectId, string Kind, Guid ObjectId, Guid RecipeId,
|
||||
string Name, string Path, string Before, string After, string Revision, string Status);
|
||||
|
||||
public sealed class ProjectChanges
|
||||
{
|
||||
private readonly Dictionary<Guid, ProjectChange> drafts = new();
|
||||
|
||||
public JsonNode Execute(ProjectDirectory project, string operation, JsonObject args, bool allowWrite,
|
||||
Func<ProjectChange, bool> confirm = null)
|
||||
{
|
||||
if (operation == "preview")
|
||||
{
|
||||
string kind = (string)args["kind"], after = (string)args["comment"];
|
||||
if (after == null || after.Length > 8192) throw new ArgumentException("Expected a comment of at most 8192 characters.");
|
||||
if (kind is not ("Recipes" or "Variables" or "SystemVariables" or "Workflows"))
|
||||
throw new ArgumentException("Unsupported comment target.");
|
||||
var id = Guid.Parse((string)args["id"]);
|
||||
lock (project.Data.Sync)
|
||||
{
|
||||
var target = ProjectInspection.Query(project, "get", args);
|
||||
var recipeId = kind == "Recipes" ? id : Guid.Parse((string)target["RecipeID"]);
|
||||
string path = kind is "Variables" or "SystemVariables" ? "configuration/variables.json" : $"recipes/{recipeId:D}/recipe.json";
|
||||
string before = (string)target["Comment"];
|
||||
var change = new ProjectChange(Guid.NewGuid(), project.Id, kind, id, recipeId, (string)target["Name"],
|
||||
path, before, after, project.Revision(path), "pending");
|
||||
if (drafts.Count >= 256) drafts.Remove(drafts.Keys.First());
|
||||
drafts.Add(change.DraftId, change);
|
||||
return JsonSerializer.SerializeToNode(change);
|
||||
}
|
||||
}
|
||||
if (!drafts.TryGetValue(Guid.Parse((string)args["draftId"]), out var draft) || draft.ProjectId != project.Id)
|
||||
throw new ArgumentException("Unknown or expired draft.");
|
||||
if (operation == "apply" && draft.Status == "pending")
|
||||
{
|
||||
if (!allowWrite) throw new InvalidOperationException("Start the MCP server with --allow-write to apply a preview.");
|
||||
if (confirm != null && !confirm(draft)) draft = draft with { Status = "rejected" };
|
||||
else
|
||||
{
|
||||
try { project.ApplyComment(draft); }
|
||||
catch (ProjectConflictException)
|
||||
{
|
||||
drafts[draft.DraftId] = draft with { Status = "conflict" };
|
||||
throw;
|
||||
}
|
||||
draft = draft with { Status = "saved" };
|
||||
}
|
||||
drafts[draft.DraftId] = draft;
|
||||
}
|
||||
return JsonSerializer.SerializeToNode(draft);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class ProjectConflictException(string message) : System.IO.IOException(message);
|
||||
|
||||
public sealed partial class ProjectDirectory
|
||||
{
|
||||
internal string Revision(string path) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(baseline[path])));
|
||||
|
||||
internal void ApplyComment(ProjectChange change)
|
||||
{
|
||||
lock (Data.Sync)
|
||||
{
|
||||
var id = change.ObjectId;
|
||||
var current = ProjectInspection.Query(this, "get", new() { ["kind"] = change.Kind, ["id"] = id.ToString() });
|
||||
if (Revision(change.Path) != change.Revision || (string)current["Comment"] != change.Before)
|
||||
throw new ProjectConflictException("The target changed after preview. Create a new preview.");
|
||||
var document = JsonNode.Parse(baseline[change.Path]);
|
||||
var isVariable = change.Kind is "Variables" or "SystemVariables";
|
||||
JsonNode target = change.Kind switch
|
||||
{
|
||||
"Recipes" => document,
|
||||
"Workflows" => document["workflows"].AsArray().Single(w => Guid.Parse((string)w["id"]) == id),
|
||||
_ => document[change.Kind].AsArray().Single(v => Guid.Parse((string)v["ID"]) == id)
|
||||
};
|
||||
var field = isVariable ? "Comment" : "comment";
|
||||
if ((string)target[field] != change.Before)
|
||||
throw new ProjectConflictException("Save the pending editor change to this comment first.");
|
||||
target[field] = change.After;
|
||||
var json = Serialize(document);
|
||||
var files = new Dictionary<string, string>(baseline) { [change.Path] = json };
|
||||
// Change only the approved column in the private working database. Other tracked drafts stay pending.
|
||||
using var transaction = isVariable ? Data.Database.BeginTransaction() : null;
|
||||
if (change.Kind == "Variables")
|
||||
Data.Variables.Where(v => v.ID == id).ExecuteUpdate(s => s.SetProperty(v => v.Comment, change.After));
|
||||
if (change.Kind == "SystemVariables")
|
||||
Data.SystemVariables.Where(v => v.ID == id).ExecuteUpdate(s => s.SetProperty(v => v.Comment, change.After));
|
||||
try { WriteFiles(Root, files, [change.Path]); }
|
||||
catch (System.IO.IOException) when (!System.IO.File.Exists(ProjectFile(Root, change.Path)) ||
|
||||
System.IO.File.ReadAllText(ProjectFile(Root, change.Path)) != baseline[change.Path])
|
||||
{
|
||||
throw new ProjectConflictException("The file changed outside the editor. Reopen the project and preview again.");
|
||||
}
|
||||
transaction?.Commit();
|
||||
if (isVariable)
|
||||
{
|
||||
configuration[change.Path] = json;
|
||||
object entity = change.Kind == "Variables" ? Data.Variables.Local.First(v => v.ID == id)
|
||||
: Data.SystemVariables.Local.First(v => v.ID == id);
|
||||
var property = Data.Entry(entity).Property(field);
|
||||
if (entity is PLCSharp.VVMs.GlobalVariables.Variable variable) variable.Comment = change.After;
|
||||
else ((PLCSharp.VVMs.GlobalVariables.SystemVariable)entity).Comment = change.After;
|
||||
property.OriginalValue = change.After;
|
||||
}
|
||||
else if (change.Kind == "Recipes") Recipes.Single(r => r.ID == id).Comment = change.After;
|
||||
else Flows(change.RecipeId).Single(w => w.ID == id).Comment = change.After;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -26,7 +26,7 @@ internal static class ProjectConfiguration
|
||||
|
||||
private static string Quote(string identifier) => "\"" + identifier.Replace("\"", "\"\"") + "\"";
|
||||
|
||||
internal static JsonObject Capture(DatasContext db, string[] tables)
|
||||
internal static JsonObject Capture(DatasContext db, string[] tables, bool embedInputs = true)
|
||||
{
|
||||
var document = new JsonObject();
|
||||
foreach (var table in tables)
|
||||
@ -49,7 +49,7 @@ internal static class ProjectConfiguration
|
||||
{
|
||||
var raw = reader.GetValue(i);
|
||||
value = IsJson(p) ? (JsonNode.Parse((string)raw) ?? JsonValue.Create("null")) : JsonSerializer.SerializeToNode(raw);
|
||||
if (table == "VisionFunctions" && p.GetColumnName() == "VisionFlows")
|
||||
if (embedInputs && table == "VisionFunctions" && p.GetColumnName() == "VisionFlows")
|
||||
EmbedImageInputs(value);
|
||||
}
|
||||
row.Add(p.GetColumnName(), value);
|
||||
|
||||
@ -7,7 +7,7 @@ using System.Text.Json;
|
||||
|
||||
namespace PLCSharp.Models;
|
||||
|
||||
public sealed class ProjectDirectory : IDisposable
|
||||
public sealed partial class ProjectDirectory : IDisposable
|
||||
{
|
||||
private sealed record Manifest(int FormatVersion, Guid ProjectId, Guid DefaultRecipeId, Guid[] Recipes);
|
||||
private sealed record RecipeFile(Guid Id, string Name, string Comment, FlowFile[] Workflows);
|
||||
@ -95,11 +95,26 @@ public sealed class ProjectDirectory : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
private static string ProjectFile(string root, string relative)
|
||||
{
|
||||
var path = root;
|
||||
foreach (var part in relative.Split('/'))
|
||||
{
|
||||
path = Path.Combine(path, part);
|
||||
if (File.Exists(path) || Directory.Exists(path))
|
||||
{
|
||||
if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0)
|
||||
throw new InvalidDataException($"Project files must be inside the directory: {relative}");
|
||||
}
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
private void ReadDirectory()
|
||||
{
|
||||
string Read(string path)
|
||||
{
|
||||
string value = File.ReadAllText(Path.Combine(Root, path));
|
||||
string value = File.ReadAllText(ProjectFile(Root, path));
|
||||
baseline.Add(path, value);
|
||||
return value;
|
||||
}
|
||||
@ -207,7 +222,7 @@ public sealed class ProjectDirectory : IDisposable
|
||||
var paths = scope ?? files.Keys.Union(previous.Keys).ToArray();
|
||||
foreach (var path in paths)
|
||||
{
|
||||
var full = Path.Combine(root, path);
|
||||
var full = ProjectFile(root, path);
|
||||
var disk = File.Exists(full) ? File.ReadAllText(full) : null;
|
||||
previous.TryGetValue(path, out var original);
|
||||
if (disk != original)
|
||||
@ -233,7 +248,7 @@ public sealed class ProjectDirectory : IDisposable
|
||||
{
|
||||
var temp = Path.Combine(stage, path);
|
||||
if (files.ContainsKey(path) && !File.Exists(temp)) continue;
|
||||
var target = Path.Combine(root, path);
|
||||
var target = ProjectFile(root, path);
|
||||
if (previous.ContainsKey(path))
|
||||
{
|
||||
var backup = Path.Combine(stage, Guid.NewGuid().ToString());
|
||||
|
||||
@ -11,7 +11,7 @@ public static class ProjectInspection
|
||||
{
|
||||
if (operation == "references") return WorkflowReferences.Find(project, (string)args["kind"], (string)args["id"]);
|
||||
if (operation == "summary")
|
||||
return JsonSerializer.SerializeToNode(new { project.Id, project.DefaultRecipeId, project.Root,
|
||||
return JsonSerializer.SerializeToNode(new { project.Id, project.DefaultRecipeId, project.Root, source = "directory",
|
||||
kinds = Kinds, recipes = project.Recipes.Select(r => new { r.ID, r.Name }) });
|
||||
string kind = (string)args["kind"];
|
||||
if (!Kinds.Contains(kind)) throw new ArgumentException("Unknown object kind.");
|
||||
@ -47,7 +47,13 @@ public static class ProjectInspection
|
||||
if (kind == "SystemVariables")
|
||||
return p.Data.SystemVariables.ToList().Select(v => JsonSerializer.SerializeToNode(new { v.ID, v.RecipeID, v.Name,
|
||||
v.Comment, v.Type, v.DefaultValueStr, v.ValueStr, v.RetainPersistent }).AsObject());
|
||||
var table = ProjectConfiguration.Capture(p.Data, [kind])[kind].AsArray();
|
||||
var table = ProjectConfiguration.Capture(p.Data, [kind], embedInputs: false)[kind].AsArray();
|
||||
if (kind == "LocalImageDatas")
|
||||
{
|
||||
var owners = p.Data.VisionFunctions.Select(f => new { f.ID, f.RecipeID }).ToDictionary(f => f.ID, f => f.RecipeID);
|
||||
foreach (var row in table)
|
||||
if (owners.TryGetValue(Guid.Parse((string)row["FuncID"]), out var owner)) row["RecipeID"] = owner.ToString();
|
||||
}
|
||||
return table.Select(n => n.AsObject());
|
||||
}
|
||||
}
|
||||
|
||||
111
PLCSharpWpf/Models/ProjectPipe.cs
Normal file
111
PLCSharpWpf/Models/ProjectPipe.cs
Normal file
@ -0,0 +1,111 @@
|
||||
using System.IO;
|
||||
using System.IO.Pipes;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Principal;
|
||||
using System.Text;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Threading;
|
||||
|
||||
namespace PLCSharp.Models;
|
||||
|
||||
public sealed class ProjectPipe : IDisposable
|
||||
{
|
||||
private readonly CancellationTokenSource stopping = new();
|
||||
private readonly Mutex marker;
|
||||
private readonly string name;
|
||||
private readonly Func<JsonObject, JsonNode> handle;
|
||||
private static readonly UTF8Encoding Utf8 = new(false);
|
||||
|
||||
private static string Name(string root)
|
||||
{
|
||||
var path = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)).ToUpperInvariant();
|
||||
using var user = WindowsIdentity.GetCurrent();
|
||||
var identity = user.User.Value;
|
||||
return "PLCSharp-" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(identity + "|" + path)));
|
||||
}
|
||||
|
||||
internal static T Synchronized<T>(string root, Func<T> action)
|
||||
{
|
||||
using var mutex = new Mutex(false, Name(root) + "-access");
|
||||
bool acquired;
|
||||
try { acquired = mutex.WaitOne(TimeSpan.FromSeconds(15)); }
|
||||
catch (AbandonedMutexException) { acquired = true; }
|
||||
if (!acquired) throw new IOException("Project is busy. Retry the request.");
|
||||
try { return action(); }
|
||||
finally { mutex.ReleaseMutex(); }
|
||||
}
|
||||
|
||||
public static JsonNode Call(string root, JsonObject request, Func<JsonNode> offline)
|
||||
{
|
||||
var result = Synchronized(root, () =>
|
||||
{
|
||||
if (!Mutex.TryOpenExisting(Name(root) + "-editor", out var active)) return offline();
|
||||
active.Dispose();
|
||||
return null;
|
||||
});
|
||||
return result ?? TryCall(root, request) ?? throw new IOException("Editor closed. Retry the request.");
|
||||
}
|
||||
|
||||
public ProjectPipe(string root, Func<JsonObject, JsonNode> handle)
|
||||
{
|
||||
name = Name(root);
|
||||
this.handle = handle;
|
||||
marker = Synchronized(root, () =>
|
||||
{
|
||||
var registration = new Mutex(false, name + "-editor", out var created);
|
||||
if (created) return registration;
|
||||
registration.Dispose();
|
||||
throw new IOException("工程已在另一个编辑器中打开。");
|
||||
});
|
||||
_ = ServeAsync(stopping.Token);
|
||||
}
|
||||
|
||||
private async Task ServeAsync(CancellationToken token)
|
||||
{
|
||||
while (!token.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var pipe = new NamedPipeServerStream(name, PipeDirection.InOut, 1, PipeTransmissionMode.Byte,
|
||||
PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
|
||||
await pipe.WaitForConnectionAsync(token).ConfigureAwait(false);
|
||||
using var input = new StreamReader(pipe, Utf8, leaveOpen: true);
|
||||
using var output = new StreamWriter(pipe, Utf8, leaveOpen: true) { AutoFlush = true };
|
||||
JsonObject response;
|
||||
try
|
||||
{
|
||||
var line = await input.ReadLineAsync(token).ConfigureAwait(false);
|
||||
response = new() { ["result"] = handle(JsonNode.Parse(line).AsObject()) };
|
||||
}
|
||||
catch (Exception ex) { response = new() { ["error"] = ex.GetBaseException().Message }; }
|
||||
await output.WriteLineAsync(response.ToJsonString()).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested) { return; }
|
||||
catch (IOException) { if (!token.IsCancellationRequested) await Task.Delay(50).ConfigureAwait(false); }
|
||||
}
|
||||
}
|
||||
|
||||
public static JsonNode TryCall(string root, JsonObject request)
|
||||
{
|
||||
string name = Name(root);
|
||||
if (!Mutex.TryOpenExisting(name + "-editor", out var active)) return null;
|
||||
using (active)
|
||||
using (var pipe = new NamedPipeClientStream(".", name, PipeDirection.InOut, PipeOptions.CurrentUserOnly))
|
||||
{
|
||||
pipe.Connect(5000);
|
||||
using var input = new StreamReader(pipe, Utf8, leaveOpen: true);
|
||||
using var output = new StreamWriter(pipe, Utf8, leaveOpen: true) { AutoFlush = true };
|
||||
output.WriteLine(request.ToJsonString());
|
||||
var response = JsonNode.Parse(input.ReadLine() ?? throw new IOException("Editor disconnected."));
|
||||
if (response["error"] != null) throw new InvalidOperationException((string)response["error"]);
|
||||
return response["result"];
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
stopping.Cancel();
|
||||
marker.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@ -35,7 +35,8 @@ namespace PLCSharp.VVMs.GlobalVariables
|
||||
/// <summary>
|
||||
/// 备注
|
||||
/// </summary>
|
||||
public string Comment { get; set; }
|
||||
public string Comment { get => _comment; set => SetProperty(ref _comment, value); }
|
||||
private string _comment;
|
||||
|
||||
private dynamic _Value;
|
||||
|
||||
@ -212,7 +213,8 @@ namespace PLCSharp.VVMs.GlobalVariables
|
||||
/// <summary>
|
||||
/// 备注
|
||||
/// </summary>
|
||||
public string Comment { get; set; }
|
||||
public string Comment { get => _comment; set => SetProperty(ref _comment, value); }
|
||||
private string _comment;
|
||||
|
||||
private dynamic _Value;
|
||||
|
||||
|
||||
@ -70,7 +70,9 @@
|
||||
<Button Command="{Binding Model.ProjectManage}" CommandParameter="New" Content="新建工程…" Margin="3,0" />
|
||||
<Button Command="{Binding Model.ProjectManage}" CommandParameter="Open" Content="打开工程…" Margin="3,0" />
|
||||
<Button Command="{Binding Model.ProjectManage}" CommandParameter="Save" Content="保存工程" Margin="3,0" />
|
||||
<CheckBox Content="允许 AI 访问" IsChecked="{Binding Model.AllowAiAccess}" VerticalAlignment="Center" Margin="6,0" />
|
||||
<Button Content="复制 MCP 配置" Command="{Binding Model.CopyMcpConfig}" Margin="3,0" />
|
||||
<TextBlock Text="{Binding Model.ProjectLocation}" VerticalAlignment="Center" Margin="8,0" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
</UserControl>
|
||||
|
||||
10
README.md
10
README.md
@ -31,6 +31,14 @@
|
||||
|
||||
|
||||
```
|
||||
## 用 AI 读取和修改工程
|
||||
|
||||
在 Windows 上运行 `dotnet build PLCSharp.sln -c Release`。MCP 服务程序位于 `PLCSharp.Mcp/bin/Release/net8.0-windows7.0/PLCSharp.Mcp.exe`。在 PLCSharp 的「机种配方」页面保存工程,点击「复制 MCP 配置」,选择该程序,然后将配置添加到支持 stdio 的 MCP 客户端。每个服务实例通过 `--project` 绑定一个工程目录。移除 `--allow-write` 后仍可查询和预览。
|
||||
|
||||
工程已在 PLCSharp 中打开时,勾选「允许 AI 访问」。工具通过当前 Windows 用户的命名管道查询编辑器,显示当前配方和工作流草稿。硬件等模块返回已提交到工程工作区的配置。保存前,编辑器会显示旧备注和新备注供确认。工程关闭时,服务直接读取目录;以 `--allow-write` 启动的客户端可以应用预览。
|
||||
|
||||
例如,向 AI 提问:“找出默认配方中引用‘计数’的工作流,列出文件和行号,再预览将变量备注改为‘累计完成数量’。” 服务按对象 ID 和配方定位,使用 Roslyn 分析 `GetVariable`、`GetTask` 和对象名称相等比较。动态名称会标为待核对。首版支持修改配方、工作流、用户变量和系统变量的备注。应用草案时会核对预览版本。
|
||||
|
||||
## 界面展示
|
||||
|
||||

|
||||
@ -47,4 +55,4 @@
|
||||
|
||||
## 免责声明
|
||||
|
||||
本项目仅用于学习交流,未经严格测试及安全认证,请勿用于实际生产环境,本人不对使用或无法使用该软件所造成的所有直接和间接后果包括并不限于人身伤害、财产损坏、数据丢失、错误输出、经济损失负责。
|
||||
本项目仅用于学习交流,未经严格测试及安全认证,请勿用于实际生产环境,本人不对使用或无法使用该软件所造成的所有直接和间接后果包括并不限于人身伤害、财产损坏、数据丢失、错误输出、经济损失负责。
|
||||
|
||||
50
Tests/PLCSharp.Tests/ProjectMcpTests.cs
Normal file
50
Tests/PLCSharp.Tests/ProjectMcpTests.cs
Normal file
@ -0,0 +1,50 @@
|
||||
using PLCSharp.Models;
|
||||
using PLCSharp.VVMs.GlobalVariables;
|
||||
using System.IO;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace PLCSharp.Tests;
|
||||
|
||||
public class ProjectMcpTests
|
||||
{
|
||||
[Fact]
|
||||
public void EditorPipeUsesLiveObjectsAndOnlyPersistsTheApprovedField()
|
||||
{
|
||||
var folder = Directory.CreateTempSubdirectory();
|
||||
try
|
||||
{
|
||||
using var project = ProjectDirectory.New();
|
||||
var recipe = project.Recipes.Single();
|
||||
var variable = new Variable { RecipeID = recipe.ID, Name = "Counter", Comment = "old" };
|
||||
project.Data.Add(variable);
|
||||
project.Save(folder.FullName);
|
||||
recipe.Name = "unsaved";
|
||||
var changes = new ProjectChanges();
|
||||
bool approve = false;
|
||||
using var pipe = new ProjectPipe(folder.FullName, request =>
|
||||
{
|
||||
var op = (string)request["operation"]!;
|
||||
var args = request["arguments"]!.AsObject();
|
||||
return op == "get" ? ProjectInspection.Query(project, op, args)
|
||||
: changes.Execute(project, op, args, true, _ => approve);
|
||||
});
|
||||
JsonNode Call(string operation, JsonObject args) => ProjectPipe.Call(folder.FullName,
|
||||
new() { ["operation"] = operation, ["arguments"] = args }, () => throw new Exception("Unexpected offline access"));
|
||||
var live = Call("get", new() { ["kind"] = "Recipes", ["id"] = recipe.ID.ToString() });
|
||||
Assert.Equal("unsaved", (string?)live["Name"]);
|
||||
JsonNode Preview() => Call("preview", new() { ["kind"] = "Variables", ["id"] = variable.ID.ToString(), ["comment"] = "new" });
|
||||
JsonNode Apply(JsonNode draft) => Call("apply", new() { ["draftId"] = (string?)draft["DraftId"] });
|
||||
Assert.Equal("rejected", (string?)Apply(Preview())["Status"]);
|
||||
Assert.Equal("old", variable.Comment);
|
||||
approve = true;
|
||||
Assert.Equal("saved", (string?)Apply(Preview())["Status"]);
|
||||
Assert.Equal("new", variable.Comment);
|
||||
Assert.Equal("unsaved", recipe.Name);
|
||||
using var disk = ProjectDirectory.Open(folder.FullName);
|
||||
Assert.Equal("First", disk.Recipes.Single().Name);
|
||||
Assert.Equal("new", disk.Data.Variables.Single().Comment);
|
||||
}
|
||||
finally { folder.Delete(true); }
|
||||
}
|
||||
}
|
||||
|
||||
@ -73,7 +73,35 @@ class Sample {
|
||||
assert [(h["line"], h["confidence"]) for h in hits] == [(5, "confirmed"), (6, "dynamic")], hits
|
||||
flow_hit, = client.call("find_references", kind="Workflows", id=workflow["id"])["hits"]
|
||||
assert flow_hit["line"] == 7 and flow_hit["confidence"] == "confirmed", flow_hit
|
||||
print(f'{summary["Id"]}: {len(summary["recipes"])} recipes, {workflow["name"]}, {variable["name"]}')
|
||||
script.write_text(source_object["Code"], encoding="utf-8")
|
||||
args = {"kind": "Variables", "id": variable["id"], "comment": "已核对计数变量"}
|
||||
draft = client.call("preview_changes", **args)
|
||||
denied = client.request("tools/call", {"name": "apply_changes", "arguments": {"draftId": draft["DraftId"]}})
|
||||
assert denied["isError"]
|
||||
client.close()
|
||||
client = Client(exe, project, "--allow-write")
|
||||
snapshot = {p: p.read_bytes() for p in project.rglob("*") if p.is_file()}
|
||||
draft = client.call("preview_changes", **args)
|
||||
assert draft["Before"] == "A" and draft["After"] == args["comment"]
|
||||
assert all(p.read_bytes() == old for p, old in snapshot.items())
|
||||
key = {"draftId": draft["DraftId"]}
|
||||
assert client.call("apply_changes", **key)["Status"] == "saved"
|
||||
assert client.call("apply_changes", **key)["Status"] == "saved"
|
||||
assert client.call("get_change_status", **key)["Status"] == "saved"
|
||||
changed = [p.relative_to(project).as_posix() for p, old in snapshot.items() if p.read_bytes() != old]
|
||||
assert changed == ["configuration/variables.json"], changed
|
||||
client.close()
|
||||
client = Client(exe, project, "--allow-write")
|
||||
assert client.call("get_object", kind="Variables", id=variable["id"])["Comment"] == args["comment"]
|
||||
pending = client.call("preview_changes", **(args | {"comment": "stale draft"}))
|
||||
file = project / changed[0]
|
||||
external = file.read_bytes() + b"\n"
|
||||
file.write_bytes(external)
|
||||
conflict = client.request("tools/call", {"name": "apply_changes", "arguments": {"draftId": pending["DraftId"]}})
|
||||
assert conflict["isError"] and file.read_bytes() == external
|
||||
assert client.call("get_change_status", draftId=pending["DraftId"])["Status"] == "conflict"
|
||||
print(f'{summary["Id"]}: {len(summary["recipes"])} recipes, {workflow["name"]}, {variable["name"]}; '
|
||||
f'confirmed variable line 5 / workflow line 7; saved {changed[0]} and reopened')
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user