From 1fb7464a088cf069fc0201a7298bd031f57bc6b2 Mon Sep 17 00:00:00 2001 From: wanglei Date: Sat, 5 Dec 2026 23:53:12 +0800 Subject: [PATCH] Protect hardware, recipe and point names in MCP operations and workflow previews --- PLCSharp.Mcp/ProjectTools.cs | 20 +-------- PLCSharpWpf/Models/AiNamePolicy.cs | 47 ++++++++++++++++++++++ PLCSharpWpf/Models/ObjectEdit.cs | 2 + PLCSharpWpf/Models/ProjectChanges.cs | 8 ++++ PLCSharpWpf/Models/WorkflowReferences.cs | 8 ++-- PLCSharpWpf/Models/WorkflowScriptReview.cs | 8 ++++ Tests/PLCSharp.Tests/ProjectBatchTests.cs | 34 ++++++++++++++++ Tests/mcp_all_names_smoke.py | 8 ++++ 8 files changed, 114 insertions(+), 21 deletions(-) create mode 100644 PLCSharpWpf/Models/AiNamePolicy.cs diff --git a/PLCSharp.Mcp/ProjectTools.cs b/PLCSharp.Mcp/ProjectTools.cs index 7cddff4..dc7c0af 100644 --- a/PLCSharp.Mcp/ProjectTools.cs +++ b/PLCSharp.Mcp/ProjectTools.cs @@ -7,7 +7,7 @@ namespace PLCSharp.Mcp; [McpServerToolType] internal sealed class ProjectTools(ProjectGateway gateway) { - [McpServerTool(Name = "preview_batch", ReadOnly = true), Description("Use one batch for all edits requested together, even across files. Preview only; no editor dialog or project writes. Pass ordered operations with action create/update/delete/rename, kind, id, properties or newName (and optional memberName/segmentName). To edit script source update Workflows with properties.Code. For dependencies give a create an alias, then use $alias as id or RecipeID/RobotID/FuncID. Returns references, diagnostics and one draft ID. Review once with apply_changes; preview_undo reverses the whole saved batch. For analysis only use read/preview tools and stop before apply_changes.")] + [McpServerTool(Name = "preview_batch", ReadOnly = true), Description("Use one batch for all edits requested together, even across files. Preview only; no editor dialog or project writes. Pass ordered operations with action create/update/delete/rename, kind, id, properties or newName (and optional memberName/segmentName). To edit script source update Workflows with properties.Code. Hardware, recipe and point names are protected. For dependencies give a create an alias, then use $alias as id or RecipeID/RobotID/FuncID. Returns references, diagnostics and one draft ID. Review once with apply_changes; preview_undo reverses the whole saved batch. For analysis only use read/preview tools and stop before apply_changes.")] public string PreviewBatch(JsonArray operations) => gateway.Call("previewBatch", new() { ["operations"] = operations.DeepClone() }); @@ -23,26 +23,10 @@ internal sealed class ProjectTools(ProjectGateway gateway) public string PreviewVisionAssetRename(string kind, string id, string newName) => gateway.Call("previewVisionAssetRename", new() { ["kind"] = kind, ["id"] = id, ["newName"] = newName }); - [McpServerTool(Name = "preview_object_rename"), Description("Preview a rename of any named project object. Use the kind and ID from list_objects. For VisionLocalVariables, ControlMeasurements, InterpolationSegments or InterpolationPoints pass the parent object ID and memberName, plus segmentName for a point. Review configuration, compiled scripts and manual references before applying.")] + [McpServerTool(Name = "preview_object_rename"), Description("Rename a workflow, vision function, image, variable or homepage control. Existing hardware, recipe and point names are protected. Use the kind and ID from list_objects. For VisionLocalVariables, ControlMeasurements, InterpolationSegments or InterpolationPoints pass the parent object ID and memberName, plus segmentName for a point. Review configuration, compiled scripts and manual references before applying.")] public string PreviewObjectRename(string kind, string id, string newName, string memberName = null, string segmentName = null) => gateway.Call("previewObjectRename", new() { ["kind"] = kind, ["id"] = id, ["newName"] = newName, ["memberName"] = memberName, ["segmentName"] = segmentName }); - [McpServerTool(Name = "preview_device_rename"), Description("Preview renaming a Cylinders, Robots or Connects ID. Updates the hardware definition and bound lookups across recipes, compiles affected scripts and lists manual references.")] - public string PreviewDeviceRename(string kind, string id, string newName) => - gateway.Call("previewDeviceRename", new() { ["kind"] = kind, ["id"] = id, ["newName"] = newName }); - - [McpServerTool(Name = "preview_io_rename"), Description("Preview renaming a DI or DQ channel across the project, including cylinder bindings and compiled workflow references.")] - public string PreviewIoRename(string kind, string id, string newName) => - gateway.Call("previewIoRename", new() { ["kind"] = kind, ["id"] = id, ["newName"] = newName }); - - [McpServerTool(Name = "preview_axis_rename"), Description("Preview a project-wide motion axis rename by ID, including point and interpolation configuration, compiled workflow edits and dynamic references.")] - public string PreviewAxisRename(string id, string newName) => - gateway.Call("previewAxisRename", new() { ["id"] = id, ["newName"] = newName }); - - [McpServerTool(Name = "preview_point_rename"), Description("Preview renaming an AxisPoints or RobotPoints ID, including bound workflow and matrix references. Review uncertain and dynamic hits before applying.")] - public string PreviewPointRename(string kind, string id, string newName) => - gateway.Call("previewPointRename", new() { ["kind"] = kind, ["id"] = id, ["newName"] = newName }); - [McpServerTool(Name = "preview_workflow_rename"), Description("Preview renaming a workflow by ID in its recipe. Compile rewritten callers and list dynamic or uncertain references for review.")] public string PreviewWorkflowRename(string id, string newName) => gateway.Call("previewWorkflowRename", new() { ["id"] = id, ["newName"] = newName }); diff --git a/PLCSharpWpf/Models/AiNamePolicy.cs b/PLCSharpWpf/Models/AiNamePolicy.cs new file mode 100644 index 0000000..4aa9548 --- /dev/null +++ b/PLCSharpWpf/Models/AiNamePolicy.cs @@ -0,0 +1,47 @@ +using Microsoft.CodeAnalysis; +using System.Text.Json.Nodes; + +namespace PLCSharp.Models; + +internal static class AiNamePolicy +{ + private static readonly HashSet Protected = new( + ProjectConfiguration.Groups["hardware"].Concat(ProjectConfiguration.Groups["points"]) + .Concat(["Recipes", "InterpolationSegments", "InterpolationPoints"])); + private static readonly HashSet Types = Protected.Select(kind => WorkflowReferences.TargetType(kind).FullName).ToHashSet(); + + internal static void CheckRename(string kind) + { + if (kind != null && Protected.Contains(kind)) + throw new ArgumentException("AI 可以引用硬件、配方和点位,但不能修改这些对象的名称。"); + } + + internal static bool IsProtectedType(INamedTypeSymbol type) + { + for (; type != null; type = type.BaseType) + if (Types.Contains(type.ToDisplayString())) return true; + return false; + } + + internal static void CheckInterpolationNames(JsonArray before, JsonArray after) + { + // Embedded segments and points have no stable ID. A simultaneous removal and addition + // cannot be distinguished from a rename when the parent array is replaced. + static void CheckNames(JsonArray oldItems, JsonArray newItems) + { + var oldNames = oldItems.Select(i => (string)i["Name"]).ToHashSet(); + var newNames = newItems.Select(i => (string)i["Name"]).ToHashSet(); + if (oldNames.Except(newNames).Any() && newNames.Except(oldNames).Any()) + CheckRename("InterpolationPoints"); + } + CheckNames(before, after); + foreach (var segment in before) + { + var next = after.FirstOrDefault(s => (string)s["Name"] == (string)segment["Name"]); + if (next != null) + CheckNames(JsonNode.Parse((string)segment["SerializedInterpolations"] ?? "[]").AsArray(), + JsonNode.Parse((string)next["SerializedInterpolations"] ?? "[]").AsArray()); + } + } +} + diff --git a/PLCSharpWpf/Models/ObjectEdit.cs b/PLCSharpWpf/Models/ObjectEdit.cs index e1d0d21..a8dc5d8 100644 --- a/PLCSharpWpf/Models/ObjectEdit.cs +++ b/PLCSharpWpf/Models/ObjectEdit.cs @@ -157,6 +157,8 @@ public sealed partial class ProjectDirectory private void ValidateObject(string kind, JsonArray rows, Guid id, JsonObject before, JsonObject after) { bool Changed(string key) => before == null || !JsonNode.DeepEquals(before[key], after[key]); + if (kind == "InterpolationGroups" && before != null && Changed("Interpolations")) + AiNamePolicy.CheckInterpolationNames(before["Interpolations"].AsArray(), after["Interpolations"].AsArray()); bool Other(JsonNode r) => Guid.Parse((string)r["ID"]) != id; if (after.ContainsKey("RecipeID") && !Recipes.Any(r => r.ID == Guid.Parse((string)after["RecipeID"]))) throw new ArgumentException("所属配方不存在。"); diff --git a/PLCSharpWpf/Models/ProjectChanges.cs b/PLCSharpWpf/Models/ProjectChanges.cs index e6090d8..cabcd8d 100644 --- a/PLCSharpWpf/Models/ProjectChanges.cs +++ b/PLCSharpWpf/Models/ProjectChanges.cs @@ -28,6 +28,13 @@ public sealed class ProjectChanges public JsonNode Execute(ProjectDirectory project, string operation, JsonObject args, bool allowWrite, Func confirm = null) { + var renameKind = operation switch + { + "previewAxisRename" => "Axes", + "previewPointRename" or "previewObjectRename" or "previewDeviceRename" or "previewIoRename" or "previewVisionAssetRename" => (string)args["kind"], + _ => null + }; + AiNamePolicy.CheckRename(renameKind); ProjectBatch batch = null; if (operation == "previewBatch") batch = project.PlanBatch(args["operations"]?.AsArray()); if (operation == "previewUndo" && drafts.TryGetValue(Guid.Parse((string)args["draftId"]), out var originalBatch) && originalBatch.Batch != null) @@ -83,6 +90,7 @@ public sealed class ProjectChanges if (!drafts.TryGetValue(Guid.Parse((string)args["draftId"]), out var saved) || saved.ProjectId != project.Id || saved.Status != "saved" || saved.Rename == null || saved.Rename.UndoOf.HasValue) throw new ArgumentException("需要当前会话中已保存且尚未撤销的重命名 ID。"); + AiNamePolicy.CheckRename(saved.Rename.Kind); plan = project.PlanUndo(saved.DraftId, saved.Rename); } return Remember(new(Guid.NewGuid(), project.Id, plan.Kind, plan.ObjectId, plan.RecipeId, plan.OldName, diff --git a/PLCSharpWpf/Models/WorkflowReferences.cs b/PLCSharpWpf/Models/WorkflowReferences.cs index 87f42b5..fb30b2c 100644 --- a/PLCSharpWpf/Models/WorkflowReferences.cs +++ b/PLCSharpWpf/Models/WorkflowReferences.cs @@ -28,9 +28,7 @@ internal static class WorkflowReferences .Select(p => MetadataReference.CreateFromFile(p)).ToArray(); }); - internal static JsonNode Find(ProjectDirectory project, string kind, string id, bool forRename = false, NestedName nested = null, string memberName = null, JsonNode candidate = null) - { - var targetType = kind switch { "Variables" => typeof(Variable), "SystemVariables" => typeof(SystemVariable), + internal static Type TargetType(string kind) => kind switch { "Variables" => typeof(Variable), "SystemVariables" => typeof(SystemVariable), "VisionFunctions" => typeof(VisionFunction), "DI" => typeof(DI), "DQ" => typeof(DQ), "Axes" => typeof(Axis), "AxisPoints" => typeof(AxisPoint), "RobotPoints" => typeof(RobotPoint), "CanvasConfigs" => typeof(PLCSharp.VVMs.Homepage.CanvasConfig), "Controllers" => typeof(Controller), "Cylinders" => typeof(Cylinder), "Robots" => typeof(Robot), "Connects" => typeof(Connect), "Cameras" => typeof(PLCSharp.VVMs.Vision.Camera.CameraBase), "ImageDatas" => typeof(ImageData), "LocalImageDatas" => typeof(LocalImageData), @@ -39,6 +37,10 @@ internal static class WorkflowReferences "Recipes" => typeof(PLCSharp.VVMs.Recipe.Recipe), "CustomControls" => typeof(PLCSharp.VVMs.Homepage.CustomControl), "Matrices" => typeof(Matrix), "RobotMatrices" => typeof(RobotMatrix), "InterpolationGroups" => typeof(InterpolationGroup), "Workflows" => typeof(Workflow), _ => throw new ArgumentException("Unsupported reference target.") }; + + internal static JsonNode Find(ProjectDirectory project, string kind, string id, bool forRename = false, NestedName nested = null, string memberName = null, JsonNode candidate = null) + { + var targetType = TargetType(kind); var target = candidate ?? ProjectInspection.Query(project, "get", new() { ["kind"] = nested?.Table ?? kind, ["id"] = id }); bool projectWide = kind is "Controllers" or "Axes" or "DI" or "DQ" or "Cylinders" or "Robots" or "Connects" or "Cameras" or "Recipes"; var recipeId = projectWide ? Guid.Empty : Guid.Parse((string)target["RecipeID"]); diff --git a/PLCSharpWpf/Models/WorkflowScriptReview.cs b/PLCSharpWpf/Models/WorkflowScriptReview.cs index 5cdd2ce..5ccbec4 100644 --- a/PLCSharpWpf/Models/WorkflowScriptReview.cs +++ b/PLCSharpWpf/Models/WorkflowScriptReview.cs @@ -45,6 +45,14 @@ public sealed record WorkflowScriptReview(string Diff, bool Compiled, List()) + { + if (model.GetSymbolInfo(assignment.Left).Symbol is not IPropertySymbol { Name: "Name" } property || + !AiNamePolicy.IsProtectedType(property.ContainingType)) continue; + var position = assignment.Left.GetLocation().GetLineSpan().StartLinePosition; + diagnostics.Add(new("Error", "PLC002", position.Line + 1, position.Character + 1, + "流程可以读取硬件、配方和点位名称,不能给这些名称赋值。")); + } var types = tree.GetRoot().DescendantNodes().OfType() .Where(t => t.Identifier.ValueText == expected).Select(t => model.GetDeclaredSymbol(t)) .Distinct(SymbolEqualityComparer.Default).ToArray(); diff --git a/Tests/PLCSharp.Tests/ProjectBatchTests.cs b/Tests/PLCSharp.Tests/ProjectBatchTests.cs index e37b97e..fad36db 100644 --- a/Tests/PLCSharp.Tests/ProjectBatchTests.cs +++ b/Tests/PLCSharp.Tests/ProjectBatchTests.cs @@ -7,6 +7,40 @@ namespace PLCSharp.Tests; public class ProjectBatchTests { + [Theory] + [InlineData("Recipes")] + [InlineData("Axes")] + [InlineData("RobotPoints")] + [InlineData("Cameras")] + [InlineData("InterpolationPoints")] + public void ProtectedNamesCannotBeRenamedThroughSingleOrBatchTools(string kind) + { + var dir = Directory.CreateTempSubdirectory(); + try + { + using var p = ProjectDirectory.New(); + p.Save(dir.FullName); + var changes = new ProjectChanges(); + var args = new JsonObject { ["action"] = "rename", ["kind"] = kind, ["id"] = p.DefaultRecipeId.ToString(), ["newName"] = "改名" }; + Assert.Contains("不能修改", Assert.Throws(() => changes.Execute(p, "previewObjectRename", args, false)).Message); + Assert.Contains("不能修改", Assert.Throws(() => changes.Execute(p, "previewBatch", + new() { ["operations"] = new JsonArray(args.DeepClone()) }, false)).Message); + Assert.Equal("First", p.Recipes.Single().Name); + } + finally { dir.Delete(true); } + } + + [Fact] + public void ScriptMayReadButCannotAssignExistingRecipeName() + { + var id = Guid.NewGuid(); + string Source(string statement) => $"using PLCSharp.Models; using PLCSharp.Core.Common; public class Extension_{id:N} {{ public void Run(GlobalModel model, FlowModel flow) {{ {statement} }} }}"; + Assert.True(WorkflowScriptReview.Create(id, "", Source("_ = model.CurrentRecipe.Name;")).Compiled); + var review = WorkflowScriptReview.Create(id, "", Source("model.CurrentRecipe.Name = \"其他\";")); + Assert.Contains(review.Diagnostics, d => d.Code == "PLC002"); + Assert.False(review.Compiled); + } + [Fact] public void BatchIsReviewedOnceAndRestoresOriginalBytes() { diff --git a/Tests/mcp_all_names_smoke.py b/Tests/mcp_all_names_smoke.py index 59fd005..982e2de 100644 --- a/Tests/mcp_all_names_smoke.py +++ b/Tests/mcp_all_names_smoke.py @@ -60,11 +60,18 @@ def run(exe, source): try: summary = client.call("get_project_summary") ids = {} + protected = {"Recipes", "Axes", "AxisPoints", "RobotPoints", "Matrices", "RobotMatrices", "InterpolationGroups", + "InterpolationSegments", "InterpolationPoints", "DI", "DQ", "Connects", "Cylinders", "Robots", "Cameras"} for kind in summary["kinds"]: if kind in {"Controllers", "CanvasConfigs"}: continue row = client.call("list_objects", kind=kind)["items"][0] ids[kind] = row["id"] + if kind in protected: + denied = client.request("tools/call", {"name": "preview_object_rename", + "arguments": {"kind": kind, "id": row["id"], "newName": "QA_" + kind}}) + assert denied["isError"] and snapshot() == baseline + continue draft = client.call("preview_object_rename", kind=kind, id=row["id"], newName="QA_" + kind) assert draft["Rename"]["Compiled"], draft assert len(ids) == 20 and snapshot() == baseline @@ -75,6 +82,7 @@ def run(exe, source): ("InterpolationPoints", "InterpolationGroups")] members = dict(VisionLocalVariables="读数", ControlMeasurements="测量", InterpolationSegments="线段", InterpolationPoints="终点") history = [] + order = [(kind, parent) for kind, parent in order if kind not in protected] for kind, parent in order: options = {"memberName": members[kind]} if kind in members else {} if kind == "InterpolationPoints":