diff --git a/PLCSharp.Mcp/PLCSharp.Mcp.csproj b/PLCSharp.Mcp/PLCSharp.Mcp.csproj
new file mode 100644
index 0000000..92cbbe1
--- /dev/null
+++ b/PLCSharp.Mcp/PLCSharp.Mcp.csproj
@@ -0,0 +1,14 @@
+
+
+ Exe
+ net8.0-windows7.0
+ x64
+ enable
+ ..\packages
+
+
+
+
+
+
+
diff --git a/PLCSharp.Mcp/Program.cs b/PLCSharp.Mcp/Program.cs
new file mode 100644
index 0000000..6e207b3
--- /dev/null
+++ b/PLCSharp.Mcp/Program.cs
@@ -0,0 +1,17 @@
+using Microsoft.Extensions.DependencyInjection;
+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")))
+{
+ Console.Error.WriteLine("Usage: PLCSharp.Mcp --project ");
+ 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.AddMcpServer().WithStdioServerTransport().WithTools();
+await builder.Build().RunAsync();
+return 0;
diff --git a/PLCSharp.Mcp/ProjectGateway.cs b/PLCSharp.Mcp/ProjectGateway.cs
new file mode 100644
index 0000000..6ab5edd
--- /dev/null
+++ b/PLCSharp.Mcp/ProjectGateway.cs
@@ -0,0 +1,13 @@
+using PLCSharp.Models;
+using System.Text.Json.Nodes;
+
+namespace PLCSharp.Mcp;
+
+internal sealed class ProjectGateway(string root)
+{
+ public string Call(string operation, JsonObject arguments)
+ {
+ using var project = ProjectDirectory.Open(root);
+ return ProjectInspection.Query(project, operation, arguments).ToJsonString();
+ }
+}
diff --git a/PLCSharp.Mcp/ProjectTools.cs b/PLCSharp.Mcp/ProjectTools.cs
new file mode 100644
index 0000000..7bc0cb3
--- /dev/null
+++ b/PLCSharp.Mcp/ProjectTools.cs
@@ -0,0 +1,19 @@
+using System.ComponentModel;
+using ModelContextProtocol.Server;
+using System.Text.Json.Nodes;
+
+namespace PLCSharp.Mcp;
+
+[McpServerToolType]
+internal sealed class ProjectTools(ProjectGateway gateway)
+{
+ [McpServerTool(Name = "get_project_summary", ReadOnly = true), Description("Read the bound PLCSharp project, default recipe and available object kinds.")]
+ public string Summary() => gateway.Call("summary", new());
+
+ [McpServerTool(Name = "list_objects", ReadOnly = true), Description("List one object kind from the summary, optionally scoped to a recipe. Pages start at offset zero.")]
+ public string ListObjects(string kind, string recipeId = null, int offset = 0, int limit = 50) =>
+ gateway.Call("list", new() { ["kind"] = kind, ["recipeId"] = recipeId, ["offset"] = offset, ["limit"] = limit });
+
+ [McpServerTool(Name = "get_object", ReadOnly = true), Description("Read one project object by kind and stable ID, including source for workflows.")]
+ public string GetObject(string kind, string id) => gateway.Call("get", new() { ["kind"] = kind, ["id"] = id });
+}
diff --git a/PLCSharp.sln b/PLCSharp.sln
index db745f0..b8aea1d 100644
--- a/PLCSharp.sln
+++ b/PLCSharp.sln
@@ -16,6 +16,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PLCSharp.Tests", "Tests\PLC
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "PLCSharpWpf", "PLCSharpWpf", "{E591F1A8-23FF-EC95-040F-C75762A9CC6E}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PLCSharp.Mcp", "PLCSharp.Mcp\PLCSharp.Mcp.csproj", "{FEF3E7EC-5AC1-4A08-AE01-7740FD6B25CB}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -50,6 +52,18 @@ Global
{F151D949-979B-4193-BFB1-6A8B93A1946D}.Release|x64.Build.0 = Release|Any CPU
{F151D949-979B-4193-BFB1-6A8B93A1946D}.Release|x86.ActiveCfg = Release|Any CPU
{F151D949-979B-4193-BFB1-6A8B93A1946D}.Release|x86.Build.0 = Release|Any CPU
+ {FEF3E7EC-5AC1-4A08-AE01-7740FD6B25CB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {FEF3E7EC-5AC1-4A08-AE01-7740FD6B25CB}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {FEF3E7EC-5AC1-4A08-AE01-7740FD6B25CB}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {FEF3E7EC-5AC1-4A08-AE01-7740FD6B25CB}.Debug|x64.Build.0 = Debug|Any CPU
+ {FEF3E7EC-5AC1-4A08-AE01-7740FD6B25CB}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {FEF3E7EC-5AC1-4A08-AE01-7740FD6B25CB}.Debug|x86.Build.0 = Debug|Any CPU
+ {FEF3E7EC-5AC1-4A08-AE01-7740FD6B25CB}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {FEF3E7EC-5AC1-4A08-AE01-7740FD6B25CB}.Release|Any CPU.Build.0 = Release|Any CPU
+ {FEF3E7EC-5AC1-4A08-AE01-7740FD6B25CB}.Release|x64.ActiveCfg = Release|Any CPU
+ {FEF3E7EC-5AC1-4A08-AE01-7740FD6B25CB}.Release|x64.Build.0 = Release|Any CPU
+ {FEF3E7EC-5AC1-4A08-AE01-7740FD6B25CB}.Release|x86.ActiveCfg = Release|Any CPU
+ {FEF3E7EC-5AC1-4A08-AE01-7740FD6B25CB}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/PLCSharpWpf/Models/ProjectInspection.cs b/PLCSharpWpf/Models/ProjectInspection.cs
new file mode 100644
index 0000000..ad71bff
--- /dev/null
+++ b/PLCSharpWpf/Models/ProjectInspection.cs
@@ -0,0 +1,52 @@
+using System.Text.Json;
+using System.Text.Json.Nodes;
+
+namespace PLCSharp.Models;
+
+public static class ProjectInspection
+{
+ private static readonly string[] Kinds = ["Recipes", "Workflows", .. ProjectConfiguration.Groups.Values.SelectMany(t => t)];
+
+ public static JsonNode Query(ProjectDirectory project, string operation, JsonObject args)
+ {
+ if (operation == "summary")
+ return JsonSerializer.SerializeToNode(new { project.Id, project.DefaultRecipeId, project.Root,
+ 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.");
+ var rows = Rows(project, kind);
+ if (operation == "get")
+ {
+ var id = Guid.Parse((string)args["id"]);
+ return rows.SingleOrDefault(row => Guid.Parse((string)row["ID"]) == id)
+ ?? throw new ArgumentException("Object not found.");
+ }
+ if (operation != "list") throw new ArgumentException("Unknown operation.");
+ if ((string)args["recipeId"] is string filter)
+ {
+ var recipe = Guid.Parse(filter);
+ rows = rows.Where(row => Guid.TryParse((string)row[kind == "Recipes" ? "ID" : "RecipeID"], out var owner) && owner == recipe);
+ }
+ int offset = (int?)args["offset"] ?? 0, limit = (int?)args["limit"] ?? 50;
+ if (offset < 0 || limit is < 1 or > 200) throw new ArgumentException("Invalid page bounds.");
+ var items = rows.Select(r => new { id = (string)r["ID"], name = (string)r["Name"], recipeId = (string)r["RecipeID"] }).ToArray();
+ return JsonSerializer.SerializeToNode(new { total = items.Length, items = items.Skip(offset).Take(limit) });
+ }
+
+ private static IEnumerable Rows(ProjectDirectory p, string kind)
+ {
+ if (kind == "Recipes")
+ return p.Recipes.Select(r => JsonSerializer.SerializeToNode(new { r.ID, r.Name, r.Comment }).AsObject());
+ if (kind == "Workflows")
+ return p.Recipes.SelectMany(r => p.Flows(r.ID).Select(w => JsonSerializer.SerializeToNode(new
+ { w.ID, RecipeID = r.ID, w.Name, w.Comment, w.Code, w.AutomaticExecution, w.CycleDelayTime }).AsObject()));
+ if (kind == "Variables")
+ return p.Data.Variables.ToList().Select(v => JsonSerializer.SerializeToNode(new { v.ID, v.RecipeID, v.Name,
+ v.Comment, v.Type, v.DefaultValueStr, v.ValueStr, v.RetainPersistent }).AsObject());
+ 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();
+ return table.Select(n => n.AsObject());
+ }
+}
diff --git a/Tests/mcp_smoke.py b/Tests/mcp_smoke.py
new file mode 100644
index 0000000..a507365
--- /dev/null
+++ b/Tests/mcp_smoke.py
@@ -0,0 +1,68 @@
+"""Run the stdio acceptance check against a copy of the portable QA project."""
+import json
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import tempfile
+
+
+class Client:
+ def __init__(self, exe, project, *options):
+ self.process = subprocess.Popen(
+ [exe, "--project", project, *options], stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE, text=True, encoding="utf-8")
+ self.sequence = 0
+ self.request("initialize", {"protocolVersion": "2025-11-25", "capabilities": {},
+ "clientInfo": {"name": "PLCSharp-QA", "version": "1"}})
+ self.send({"method": "notifications/initialized"})
+
+ def send(self, message):
+ message["jsonrpc"] = "2.0"
+ self.process.stdin.write(json.dumps(message) + "\n")
+ self.process.stdin.flush()
+
+ def request(self, method, params):
+ self.sequence += 1
+ self.send({"id": self.sequence, "method": method, "params": params})
+ while line := self.process.stdout.readline():
+ result = json.loads(line)
+ if result.get("id") == self.sequence:
+ assert "error" not in result, result
+ return result["result"]
+ raise RuntimeError("MCP server closed stdout")
+
+ def call(self, tool, **args):
+ result = self.request("tools/call", {"name": tool, "arguments": args})
+ assert not result.get("isError"), result
+ return json.loads(result["content"][0]["text"])
+
+ def close(self):
+ self.process.stdin.close()
+ self.process.wait(timeout=15)
+ assert self.process.returncode == 0
+
+
+def verify(exe, source):
+ with tempfile.TemporaryDirectory() as folder:
+ project = Path(folder) / "工程副本"
+ shutil.copytree(source, project)
+ client = Client(exe, project)
+ try:
+ names = {tool["name"] for tool in client.request("tools/list", {})["tools"]}
+ assert {"get_project_summary", "list_objects", "get_object"} <= names
+ summary = client.call("get_project_summary")
+ recipe = summary["DefaultRecipeId"]
+ workflow, = client.call("list_objects", kind="Workflows", recipeId=recipe)["items"]
+ variable, = client.call("list_objects", kind="Variables", recipeId=recipe)["items"]
+ assert variable["name"] == "计数"
+ source_object = client.call("get_object", kind="Workflows", id=workflow["id"])
+ assert source_object["Code"] == "// portability fixture"
+ print(f'{summary["Id"]}: {len(summary["recipes"])} recipes, {workflow["name"]}, {variable["name"]}')
+ finally:
+ client.close()
+
+
+if __name__ == "__main__":
+ verify(*sys.argv[1:])
+