Publish runtime workflow script contracts and compilable examples through MCP
This commit is contained in:
parent
8f54d7901b
commit
ff2288bd5d
@ -54,6 +54,10 @@ internal sealed class ProjectTools(ProjectGateway gateway)
|
|||||||
public string FindReferences(string kind, string id, string memberName = null, string segmentName = null) =>
|
public string FindReferences(string kind, string id, string memberName = null, string segmentName = null) =>
|
||||||
gateway.Call("references", new() { ["kind"] = kind, ["id"] = id, ["memberName"] = memberName, ["segmentName"] = segmentName });
|
gateway.Call("references", new() { ["kind"] = kind, ["id"] = id, ["memberName"] = memberName, ["segmentName"] = segmentName });
|
||||||
|
|
||||||
|
[McpServerTool(Name = "get_workflow_script_api", ReadOnly = true), Description("Consult before authoring workflow C#. Returns this project runtime build's script entry contract, API signatures, call conditions, wait/completion and failure semantics, and compilable examples. Omit topic for all, or pass vision, workflow, flow, lookup, a method name, or Type.Method. For edits pass workflowId to substitute its actual class name in examples.")]
|
||||||
|
public string WorkflowScriptApi(string topic = null, string workflowId = null) =>
|
||||||
|
gateway.Call("scriptApi", new() { ["topic"] = topic, ["workflowId"] = workflowId });
|
||||||
|
|
||||||
[McpServerTool(Name = "get_project_summary", ReadOnly = true), Description("Read the bound PLCSharp project, default recipe and available object kinds.")]
|
[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());
|
public string Summary() => gateway.Call("summary", new());
|
||||||
|
|
||||||
|
|||||||
@ -9,6 +9,8 @@ public static class ProjectInspection
|
|||||||
|
|
||||||
public static JsonNode Query(ProjectDirectory project, string operation, JsonObject args)
|
public static JsonNode Query(ProjectDirectory project, string operation, JsonObject args)
|
||||||
{
|
{
|
||||||
|
if (operation == "scriptApi")
|
||||||
|
return WorkflowScriptApi.Read((string)args["topic"], args["workflowId"] == null ? null : Guid.Parse((string)args["workflowId"]));
|
||||||
if (operation == "references")
|
if (operation == "references")
|
||||||
{
|
{
|
||||||
string type = (string)args["kind"], target = (string)args["id"];
|
string type = (string)args["kind"], target = (string)args["id"];
|
||||||
|
|||||||
128
PLCSharpWpf/Models/WorkflowScriptApi.cs
Normal file
128
PLCSharpWpf/Models/WorkflowScriptApi.cs
Normal file
@ -0,0 +1,128 @@
|
|||||||
|
using PLCSharp.Core.Common;
|
||||||
|
using PLCSharp.VVMs.Vision;
|
||||||
|
using PLCSharp.VVMs.Workflows;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Nodes;
|
||||||
|
|
||||||
|
namespace PLCSharp.Models;
|
||||||
|
|
||||||
|
internal static class WorkflowScriptApi
|
||||||
|
{
|
||||||
|
private sealed record Member(Type Owner, string Name, string Conditions, string Completion, string Failure)
|
||||||
|
{
|
||||||
|
public string Signature
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
var method = Owner.GetMethods().Single(m => m.Name == Name);
|
||||||
|
var args = method.GetParameters().Select(p => $"{TypeName(p.ParameterType)} {p.Name}");
|
||||||
|
return $"{TypeName(method.ReturnType)} {Owner.Name}.{Name}({string.Join(", ", args)})";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string TypeName(Type t) =>
|
||||||
|
t == typeof(void) ? "void" : t == typeof(string) ? "string" : t == typeof(bool) ? "bool" :
|
||||||
|
t == typeof(double) ? "double" : t.IsGenericType ?
|
||||||
|
$"{t.Name.Split('`')[0]}<{string.Join(", ", t.GetGenericArguments().Select(TypeName))}>" : t.Name;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Member Lookup(string method, string failure) =>
|
||||||
|
new(typeof(GlobalModel), method, "使用工程中已配置的对象名称;配方对象取当前配方。", "同步返回对象。", failure);
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, Member[]> Topics = new(StringComparer.OrdinalIgnoreCase)
|
||||||
|
{
|
||||||
|
["workflow"] = [
|
||||||
|
Lookup(nameof(GlobalModel.GetTask), "找不到工作流时返回 null。"),
|
||||||
|
new(typeof(Workflow), nameof(Workflow.Run),
|
||||||
|
"调用已在运行时编译的工作流。停止中、已有运行、无入口、未编译、异常状态或编译后不足 3 秒时会直接返回。避免递归调度。",
|
||||||
|
"同步执行一次 Run 入口。返回 void,没有表示本次是否实际执行的返回值。多步脚本须自行约定 Flow.Completed/Success。",
|
||||||
|
"工作流捕获入口异常,设置 Exception 并写 DebugLog。调用方检查 Exception;仅凭 Run 返回不能判定业务成功。")],
|
||||||
|
["vision"] = [
|
||||||
|
Lookup(nameof(GlobalModel.GetVisionFunction), "找不到视觉功能时抛出异常。"),
|
||||||
|
new(typeof(VisionFunction), nameof(VisionFunction.RunAllAsync),
|
||||||
|
"功能必须属于已加载的当前配方。一次独立检查前调用其 Flow.Reset();同一视觉实例共享步骤、图像和结果,避免并发或重入。",
|
||||||
|
"等待整个 Task 后读取功能自身的 Flow.Success。同步脚本由 WPF 界面线程调用时不能直接阻塞尚未完成的 Task;见本主题示例。后台线程可 GetAwaiter().GetResult()。",
|
||||||
|
"返回的 bool 即使在步骤失败或超时时也可能为 true。步骤失败详情在对应 VisionFlows 步骤的 Flow.FailMessage 中。等待时也可能抛异常。超时步骤可能仍在后台结束。")],
|
||||||
|
["flow"] = [
|
||||||
|
new(typeof(FlowModel), nameof(FlowModel.Reset), "仅在开始独立操作时调用。", "同步重置 Step、Completed、Success、FailMessage 及计时起点。", "不会等待或取消正在执行的任务。"),
|
||||||
|
new(typeof(FlowModel), nameof(FlowModel.CheckStepTime), "second 单位为秒。", "同步返回当前步骤是否超过时限。", "返回 true 表示超时;不自动中止流程。"),
|
||||||
|
new(typeof(FlowModel), nameof(FlowModel.CheckFlowTime), "second 单位为秒。", "同步返回整个流程是否超过时限。", "返回 true 表示超时;不自动中止流程。")],
|
||||||
|
["lookup"] = [
|
||||||
|
Lookup(nameof(GlobalModel.GetVariable), "找不到变量时抛异常。"), Lookup(nameof(GlobalModel.GetImageData), "找不到图像或 Mat 为 null 时抛异常。"),
|
||||||
|
Lookup(nameof(GlobalModel.GetCustomControl), "名称为空或找不到控件时返回 null。"), Lookup(nameof(GlobalModel.GetImageControl), "名称为空、未找到或控件类型不匹配时返回 null。"),
|
||||||
|
Lookup(nameof(GlobalModel.GetRobot), "未配置时抛异常。"), Lookup(nameof(GlobalModel.GetConnect), "未配置时抛异常。")]
|
||||||
|
};
|
||||||
|
|
||||||
|
private const string VisionExample = """
|
||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Windows;
|
||||||
|
using System.Windows.Threading;
|
||||||
|
using PLCSharp.Models;
|
||||||
|
using PLCSharp.Core.Common;
|
||||||
|
|
||||||
|
public class Extension___WORKFLOW_ID__
|
||||||
|
{
|
||||||
|
public void Run(GlobalModel model, FlowModel flow)
|
||||||
|
{
|
||||||
|
var check = model.GetVisionFunction("检查");
|
||||||
|
check.Flow.Reset();
|
||||||
|
var run = check.RunAllAsync();
|
||||||
|
if (!run.IsCompleted && Application.Current.Dispatcher.CheckAccess())
|
||||||
|
{
|
||||||
|
var frame = new DispatcherFrame();
|
||||||
|
run.GetAwaiter().OnCompleted(() => frame.Continue = false);
|
||||||
|
Dispatcher.PushFrame(frame);
|
||||||
|
}
|
||||||
|
run.GetAwaiter().GetResult();
|
||||||
|
if (!check.Flow.Success)
|
||||||
|
{
|
||||||
|
var failed = check.VisionFlows.FirstOrDefault(step => !string.IsNullOrEmpty(step.Flow.FailMessage));
|
||||||
|
throw new InvalidOperationException(failed?.Flow.FailMessage ?? "视觉检查失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
|
||||||
|
private const string CallerExample = """
|
||||||
|
using System;
|
||||||
|
using PLCSharp.Models;
|
||||||
|
using PLCSharp.Core.Common;
|
||||||
|
|
||||||
|
public class Extension___WORKFLOW_ID__
|
||||||
|
{
|
||||||
|
public void Run(GlobalModel model, FlowModel flow)
|
||||||
|
{
|
||||||
|
var target = model.GetTask("执行视觉检查") ?? throw new InvalidOperationException("找不到执行视觉检查");
|
||||||
|
if (!target.IsCompiled || target.Exception || target.IsRuning || target.CompiledTime.AddSeconds(3) > DateTime.Now)
|
||||||
|
throw new InvalidOperationException("执行视觉检查尚未就绪");
|
||||||
|
target.Run(model);
|
||||||
|
if (target.Exception)
|
||||||
|
throw new InvalidOperationException("执行视觉检查异常:" + target.DebugLog);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
|
||||||
|
internal static JsonNode Read(string topic, Guid? workflowId)
|
||||||
|
{
|
||||||
|
var assembly = typeof(GlobalModel).Assembly;
|
||||||
|
var name = assembly.GetName();
|
||||||
|
var selected = string.IsNullOrWhiteSpace(topic) ? Topics : Topics.Where(kv =>
|
||||||
|
kv.Key.Equals(topic, StringComparison.OrdinalIgnoreCase) || kv.Value.Any(m =>
|
||||||
|
m.Name.Equals(topic, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
$"{m.Owner.Name}.{m.Name}".Equals(topic, StringComparison.OrdinalIgnoreCase))).ToDictionary();
|
||||||
|
if (selected.Count == 0) throw new ArgumentException("未知主题或方法。省略 topic 可列出全部主题。");
|
||||||
|
string Example(string template) => workflowId is Guid id ? template.Replace("__WORKFLOW_ID__", id.ToString("N")) : template;
|
||||||
|
return JsonSerializer.SerializeToNode(new {
|
||||||
|
assembly = name.Name, version = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? name.Version?.ToString(),
|
||||||
|
buildId = assembly.ManifestModule.ModuleVersionId,
|
||||||
|
entry = "public void Run(GlobalModel model, FlowModel flow);公开可无参构造的 Extension_<工作流ID的32位十六进制> 类。入口必须同步完成,不能使用 async void 或启动未等待的任务。",
|
||||||
|
examples = "新建工作流时直接使用模板,preview_batch 在分配 ID 后替换 __WORKFLOW_ID__。修改已有脚本可传 workflowId 获取真实类名,只合并所需语句。预览编译不执行代码;保存后仍须在运行时编译才能执行。",
|
||||||
|
topics = selected.Select(kv => new { topic = kv.Key,
|
||||||
|
members = kv.Value.Select(m => new { signature = m.Signature, conditions = m.Conditions, completion = m.Completion, failure = m.Failure }),
|
||||||
|
example = kv.Key switch { "vision" => Example(VisionExample), "workflow" => Example(CallerExample), _ => null } })
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@ -39,6 +39,12 @@
|
|||||||
|
|
||||||
例如,向 AI 提问:“找出默认配方中引用‘计数’的工作流,列出文件和行号,再预览将变量备注改为‘累计完成数量’。” 服务按对象 ID 和配方定位,使用 Roslyn 分析 `GetVariable`、`GetTask` 和对象名称相等比较。动态名称会标为待核对。首版支持修改配方、工作流、用户变量和系统变量的备注。应用草案时会核对预览版本。
|
例如,向 AI 提问:“找出默认配方中引用‘计数’的工作流,列出文件和行号,再预览将变量备注改为‘累计完成数量’。” 服务按对象 ID 和配方定位,使用 Roslyn 分析 `GetVariable`、`GetTask` 和对象名称相等比较。动态名称会标为待核对。首版支持修改配方、工作流、用户变量和系统变量的备注。应用草案时会核对预览版本。
|
||||||
|
|
||||||
|
### 查询当前版本的流程脚本 API
|
||||||
|
|
||||||
|
编写脚本前调用只读工具 `get_workflow_script_api`。省略参数可取得入口约定、全部主题和两个完整示例;传 `topic="vision"` 或 `topic="Workflow.Run"` 可缩小范围。返回值带有 PLCSharp 程序集版本和构建 ID。已打开的工程从编辑器进程返回说明,离线工程使用本地 MCP 随附的运行时。
|
||||||
|
|
||||||
|
每个方法列出 C# 签名、调用条件、等待方式和失败行为。例如 `GetTask` 未命中时返回 `null`,`GetVisionFunction` 未命中时抛出异常。视觉检查等待 `RunAllAsync()` 完成后读取视觉功能的 `Flow.Success`。新建工作流可使用示例中的 `__WORKFLOW_ID__` 模板;传入已有的 `workflowId` 会返回对应类名。示例通过工程预览使用的同一个编译器测试。
|
||||||
|
|
||||||
### 修改工作流脚本
|
### 修改工作流脚本
|
||||||
|
|
||||||
让 AI 先调用 `get_object` 读取工作流,再把该工作流的 ID 和完整 C# 源码传给 `preview_workflow_script`。返回值包含逐行差异、编译诊断和草案 ID。Roslyn 在内存中编译并校验 `Extension_<工作流ID的32位十六进制>` 的同步入口 `public void Run(GlobalModel, FlowModel)`。有编译错误的草案不能保存。
|
让 AI 先调用 `get_object` 读取工作流,再把该工作流的 ID 和完整 C# 源码传给 `preview_workflow_script`。返回值包含逐行差异、编译诊断和草案 ID。Roslyn 在内存中编译并校验 `Extension_<工作流ID的32位十六进制>` 的同步入口 `public void Run(GlobalModel, FlowModel)`。有编译错误的草案不能保存。
|
||||||
|
|||||||
24
Tests/PLCSharp.Tests/WorkflowScriptApiTests.cs
Normal file
24
Tests/PLCSharp.Tests/WorkflowScriptApiTests.cs
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
using System.Text.Json.Nodes;
|
||||||
|
using PLCSharp.Models;
|
||||||
|
|
||||||
|
namespace PLCSharp.Tests;
|
||||||
|
|
||||||
|
public class WorkflowScriptApiTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData("VisionFunction.RunAllAsync", "vision", "Task<bool> VisionFunction.RunAllAsync()")]
|
||||||
|
[InlineData("Run", "workflow", "void Workflow.Run(GlobalModel globalModel)")]
|
||||||
|
public void PublishedExamplesCompileAgainstTheirRuntime(string method, string topic, string signature)
|
||||||
|
{
|
||||||
|
using var p = ProjectDirectory.New();
|
||||||
|
var id = Guid.NewGuid();
|
||||||
|
var api = ProjectInspection.Query(p, "scriptApi", new() { ["topic"] = method, ["workflowId"] = id.ToString() });
|
||||||
|
var part = Assert.Single(api["topics"]!.AsArray())!;
|
||||||
|
Assert.Equal(typeof(ProjectDirectory).Assembly.ManifestModule.ModuleVersionId, Guid.Parse((string)api["buildId"]!));
|
||||||
|
Assert.Equal(topic, (string)part["topic"]!);
|
||||||
|
Assert.Contains(part["members"]!.AsArray(), m => (string)m!["signature"]! == signature);
|
||||||
|
var review = WorkflowScriptReview.Create(id, "", (string)part["example"]!);
|
||||||
|
Assert.True(review.Compiled, string.Join("\n", review.Diagnostics));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Loading…
Reference in New Issue
Block a user