node-opcua-modeler-mcp-server 1.3.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -21
- package/NOTICE +21 -0
- package/README.md +68 -6
- package/catalog/catalog.json +6706 -1432
- package/dist/catalog.d.ts +6 -0
- package/dist/catalog.js +6 -0
- package/dist/catalog.js.map +1 -1
- package/dist/cloud.d.ts +21 -6
- package/dist/cloud.js +173 -49
- package/dist/cloud.js.map +1 -1
- package/dist/local.d.ts +74 -0
- package/dist/local.js +149 -0
- package/dist/local.js.map +1 -0
- package/dist/server.d.ts +13 -17
- package/dist/server.js +185 -166
- package/dist/server.js.map +1 -1
- package/package.json +5 -3
- package/server.json +2 -2
package/dist/local.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ==========================================================================
|
|
3
|
+
* OPC UA Modeler — On-premise backend transport
|
|
4
|
+
*
|
|
5
|
+
* Talks to `opcua-modeler serve` running as the same OS user, over a named
|
|
6
|
+
* pipe (Windows) or Unix socket. Selected with OPCUA_MODELER_BACKEND=local.
|
|
7
|
+
*
|
|
8
|
+
* Why a pipe rather than a localhost port:
|
|
9
|
+
*
|
|
10
|
+
* - Both processes are on one machine by definition, so a network socket
|
|
11
|
+
* buys nothing and adds a surface. There is no address to bind wrongly
|
|
12
|
+
* and no port to expose beyond the host.
|
|
13
|
+
* - Access control is the operating system's, not ours: pipe and socket
|
|
14
|
+
* permissions already scope the endpoint to the user who started it,
|
|
15
|
+
* with no port-level authorisation layer to design or get wrong.
|
|
16
|
+
* - No port to allocate, publish, or collide with another service — the
|
|
17
|
+
* endpoint is named per process and advertised in a discovery file.
|
|
18
|
+
*
|
|
19
|
+
* Why node:http rather than fetch: native fetch cannot address a pipe without
|
|
20
|
+
* a custom dispatcher, and pulling undici into a package whose only runtime
|
|
21
|
+
* deps are the MCP SDK and zod is a poor trade for one option. `socketPath`
|
|
22
|
+
* has been in node:http forever and costs nothing.
|
|
23
|
+
*
|
|
24
|
+
* IMPORTANT: Never use console.log() — stdout is reserved for JSON-RPC.
|
|
25
|
+
* ==========================================================================
|
|
26
|
+
*/
|
|
27
|
+
import fs from "node:fs";
|
|
28
|
+
import http from "node:http";
|
|
29
|
+
import os from "node:os";
|
|
30
|
+
import path from "node:path";
|
|
31
|
+
/**
|
|
32
|
+
* Where `opcua-modeler serve` advertises itself.
|
|
33
|
+
*
|
|
34
|
+
* This is a wire contract between two independently-distributed packages, so
|
|
35
|
+
* the path is restated here rather than imported — this package stays
|
|
36
|
+
* installable on its own, with no build-time coupling to the CLI. Both sides
|
|
37
|
+
* carry a test asserting the same path; change one, change the other.
|
|
38
|
+
*
|
|
39
|
+
* The location follows each platform's convention for per-user runtime state
|
|
40
|
+
* (XDG_RUNTIME_DIR, LOCALAPPDATA), so the endpoint is scoped to the account
|
|
41
|
+
* that started the server.
|
|
42
|
+
*/
|
|
43
|
+
export function discoveryFilePath(env = process.env) {
|
|
44
|
+
if (process.platform === "win32") {
|
|
45
|
+
return path.join(env.LOCALAPPDATA || os.homedir(), "opcua-modeler", "serve.json");
|
|
46
|
+
}
|
|
47
|
+
if (env.XDG_RUNTIME_DIR) {
|
|
48
|
+
return path.join(env.XDG_RUNTIME_DIR, "opcua-modeler", "serve.json");
|
|
49
|
+
}
|
|
50
|
+
let user = "user";
|
|
51
|
+
try {
|
|
52
|
+
user = os.userInfo().username;
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
// Containers without a passwd entry.
|
|
56
|
+
}
|
|
57
|
+
return path.join(os.tmpdir(), `opcua-modeler-${user}`, "serve.json");
|
|
58
|
+
}
|
|
59
|
+
/** True when the operator asked for the on-premise backend. */
|
|
60
|
+
export function isLocalBackend(env = process.env) {
|
|
61
|
+
return (env.OPCUA_MODELER_BACKEND || "").toLowerCase() === "local";
|
|
62
|
+
}
|
|
63
|
+
const START_HINT = "Start it with `opcua-modeler serve` on this machine (it needs a licence " +
|
|
64
|
+
"carrying the 'serve' entitlement), or set OPCUA_MODELER_BACKEND=cloud to " +
|
|
65
|
+
"use the hosted API.";
|
|
66
|
+
/**
|
|
67
|
+
* Locate a running server.
|
|
68
|
+
*
|
|
69
|
+
* Deliberately does NOT fall back to the cloud when the file is missing.
|
|
70
|
+
* On-premise is chosen so that models never leave the network; silently
|
|
71
|
+
* shipping a model to the hosted API because a local daemon was down is a
|
|
72
|
+
* data-egress bug, not a convenience.
|
|
73
|
+
*/
|
|
74
|
+
export function readLocalEndpoint(env = process.env) {
|
|
75
|
+
const file = discoveryFilePath(env);
|
|
76
|
+
let raw;
|
|
77
|
+
try {
|
|
78
|
+
raw = fs.readFileSync(file, "utf-8");
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return {
|
|
82
|
+
ok: false,
|
|
83
|
+
error: { error: `No on-premise OPC UA Modeler server found (expected ${file}).`, hint: START_HINT }
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
let parsed;
|
|
87
|
+
try {
|
|
88
|
+
parsed = JSON.parse(raw);
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return {
|
|
92
|
+
ok: false,
|
|
93
|
+
error: { error: `The server discovery file at ${file} is not valid JSON.`, hint: START_HINT }
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
if (!parsed.pipe || !parsed.token) {
|
|
97
|
+
return {
|
|
98
|
+
ok: false,
|
|
99
|
+
error: { error: `The server discovery file at ${file} is incomplete.`, hint: START_HINT }
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
ok: true,
|
|
104
|
+
endpoint: {
|
|
105
|
+
pipe: parsed.pipe,
|
|
106
|
+
token: parsed.token,
|
|
107
|
+
pid: parsed.pid ?? 0,
|
|
108
|
+
version: parsed.version ?? "unknown",
|
|
109
|
+
capabilities: parsed.capabilities ?? []
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* One request over the pipe, adapted to a `Response`.
|
|
115
|
+
*
|
|
116
|
+
* Returning a real Response means the caller's status handling — 401, 429,
|
|
117
|
+
* 422, the JSON/text error parsing — is the SAME code for both backends. Two
|
|
118
|
+
* copies of that logic is exactly the drift this whole design avoids.
|
|
119
|
+
*/
|
|
120
|
+
export function localFetch(endpoint, apiPath, body, contentType, method, timeoutMs) {
|
|
121
|
+
return new Promise((resolve, reject) => {
|
|
122
|
+
const headers = {
|
|
123
|
+
Accept: "application/json",
|
|
124
|
+
Authorization: `Bearer ${endpoint.token}`
|
|
125
|
+
};
|
|
126
|
+
if (method !== "GET") {
|
|
127
|
+
headers["Content-Type"] = contentType;
|
|
128
|
+
headers["Content-Length"] = String(Buffer.byteLength(body));
|
|
129
|
+
}
|
|
130
|
+
const request = http.request({ socketPath: endpoint.pipe, path: apiPath, method, headers }, (response) => {
|
|
131
|
+
const chunks = [];
|
|
132
|
+
response.on("data", (chunk) => chunks.push(chunk));
|
|
133
|
+
response.on("end", () => {
|
|
134
|
+
resolve(new Response(Buffer.concat(chunks).toString("utf-8"), {
|
|
135
|
+
status: response.statusCode ?? 502,
|
|
136
|
+
headers: { "Content-Type": response.headers["content-type"] ?? "application/json" }
|
|
137
|
+
}));
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
request.setTimeout(timeoutMs, () => {
|
|
141
|
+
request.destroy(new Error(`Request timed out after ${timeoutMs / 1000}s.`));
|
|
142
|
+
});
|
|
143
|
+
request.on("error", reject);
|
|
144
|
+
if (method !== "GET")
|
|
145
|
+
request.write(body);
|
|
146
|
+
request.end();
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
//# sourceMappingURL=local.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"local.js","sourceRoot":"","sources":["../src/local.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,EAAE,MAAM,SAAS,CAAC;A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OAAO,EAAE,MAAM,CAAC,CAAC;QAE5B,IAAI,MAAM,KAAK,KAAK;YAAE,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC1C,OAAO,CAAC,GAAG,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC"}
|
package/dist/server.d.ts
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
* ==========================================================================
|
|
3
3
|
* OPC UA Modeler — MCP Server Factory (IP-Safe Version)
|
|
4
4
|
*
|
|
5
|
-
* Creates and configures the MCP server with
|
|
6
|
-
* -
|
|
7
|
-
* -
|
|
5
|
+
* Creates and configures the MCP server with 12 OPC UA tools:
|
|
6
|
+
* - 7 LOCAL tools: query the static type catalog (free, offline)
|
|
7
|
+
* - 5 CLOUD tools: proxy to api.opcua-modeler.sterfive.io
|
|
8
8
|
*
|
|
9
9
|
* Architecture: "Thin Local Shell" per Project Prometheus §1.1
|
|
10
10
|
* ZERO dependencies on proprietary @sterfive/* packages.
|
|
@@ -16,24 +16,20 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
|
16
16
|
import { findEngineeringUnit, findReusableBlock, getTypeDetails, listNamespaces, listTypes, resolveDependencies, searchTypes } from "./catalog.js";
|
|
17
17
|
export { findEngineeringUnit, findReusableBlock, getTypeDetails, listNamespaces, listTypes, resolveDependencies, searchTypes };
|
|
18
18
|
/** Tool name type */
|
|
19
|
-
export type ToolName = "resolve_dependencies" | "list_namespaces" | "list_types" | "get_type_details" | "search_types" | "find_reusable_block" | "find_engineering_unit" | "opcua_model_validate" | "opcua_model_generate" | "opcua_model_reverse" | "opcua_model_create";
|
|
20
|
-
|
|
21
|
-
* Direct tool call handler for testing (bypasses MCP protocol).
|
|
22
|
-
* Returns the same shape as MCP tool responses.
|
|
23
|
-
*/
|
|
24
|
-
export declare function handleToolCall(name: ToolName, args: Record<string, unknown>): Promise<{
|
|
25
|
-
content: {
|
|
26
|
-
type: "text";
|
|
27
|
-
text: string;
|
|
28
|
-
}[];
|
|
29
|
-
isError?: undefined;
|
|
30
|
-
} | {
|
|
19
|
+
export type ToolName = "resolve_dependencies" | "list_namespaces" | "list_types" | "get_type_details" | "search_types" | "find_reusable_block" | "find_engineering_unit" | "opcua_model_validate" | "opcua_model_generate" | "opcua_model_reverse" | "opcua_model_create" | "get_dsl_reference";
|
|
20
|
+
type ToolResult = {
|
|
31
21
|
content: {
|
|
32
22
|
type: "text";
|
|
33
23
|
text: string;
|
|
34
24
|
}[];
|
|
35
|
-
isError
|
|
36
|
-
}
|
|
25
|
+
isError?: boolean;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Direct tool call handler for testing (bypasses the MCP protocol). Runs the
|
|
29
|
+
* SAME validated `invoke` path the MCP server uses. Cloud tools are not handled
|
|
30
|
+
* here (they require the network) → treated as unknown.
|
|
31
|
+
*/
|
|
32
|
+
export declare function handleToolCall(name: ToolName, args: Record<string, unknown>): Promise<ToolResult>;
|
|
37
33
|
/**
|
|
38
34
|
* Create and configure the MCP server with all OPC UA tools registered.
|
|
39
35
|
* The server is NOT connected to any transport — the caller is responsible
|
package/dist/server.js
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
* ==========================================================================
|
|
3
3
|
* OPC UA Modeler — MCP Server Factory (IP-Safe Version)
|
|
4
4
|
*
|
|
5
|
-
* Creates and configures the MCP server with
|
|
6
|
-
* -
|
|
7
|
-
* -
|
|
5
|
+
* Creates and configures the MCP server with 12 OPC UA tools:
|
|
6
|
+
* - 7 LOCAL tools: query the static type catalog (free, offline)
|
|
7
|
+
* - 5 CLOUD tools: proxy to api.opcua-modeler.sterfive.io
|
|
8
8
|
*
|
|
9
9
|
* Architecture: "Thin Local Shell" per Project Prometheus §1.1
|
|
10
10
|
* ZERO dependencies on proprietary @sterfive/* packages.
|
|
@@ -16,58 +16,118 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
|
16
16
|
import { z } from "zod";
|
|
17
17
|
import { findEngineeringUnit, findReusableBlock, getTypeDetails, listNamespaces, listTypes, resolveDependencies, searchTypes } from "./catalog.js";
|
|
18
18
|
import { cloudFetch, formatCloudError } from "./cloud.js";
|
|
19
|
+
import { isLocalBackend } from "./local.js";
|
|
19
20
|
// Re-export for testing
|
|
20
21
|
export { findEngineeringUnit, findReusableBlock, getTypeDetails, listNamespaces, listTypes, resolveDependencies, searchTypes };
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
dependencies: s.deps
|
|
38
|
-
}));
|
|
39
|
-
return { content: [{ type: "text", text: JSON.stringify(specs) }] };
|
|
22
|
+
const jsonResult = (data) => ({ content: [{ type: "text", text: JSON.stringify(data) }] });
|
|
23
|
+
const jsonError = (message) => ({
|
|
24
|
+
content: [{ type: "text", text: JSON.stringify({ error: message }) }],
|
|
25
|
+
isError: true
|
|
26
|
+
});
|
|
27
|
+
function defineLocalTool(spec) {
|
|
28
|
+
const validator = z.object(spec.schema);
|
|
29
|
+
return {
|
|
30
|
+
name: spec.name,
|
|
31
|
+
description: spec.description,
|
|
32
|
+
schema: spec.schema,
|
|
33
|
+
invoke: (rawArgs) => {
|
|
34
|
+
const parsed = validator.safeParse(rawArgs);
|
|
35
|
+
if (!parsed.success) {
|
|
36
|
+
const detail = parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
|
|
37
|
+
return jsonError(`Invalid arguments: ${detail}`);
|
|
40
38
|
}
|
|
41
|
-
|
|
42
|
-
return
|
|
39
|
+
try {
|
|
40
|
+
return spec.run(parsed.data);
|
|
43
41
|
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
if (!details) {
|
|
47
|
-
return { content: [{ type: "text", text: JSON.stringify({ error: `Type not found` }) }], isError: true };
|
|
48
|
-
}
|
|
49
|
-
return { content: [{ type: "text", text: JSON.stringify(details) }] };
|
|
42
|
+
catch (e) {
|
|
43
|
+
return jsonError(String(e));
|
|
50
44
|
}
|
|
51
|
-
case "search_types": {
|
|
52
|
-
return { content: [{ type: "text", text: JSON.stringify(searchTypes(args.query)) }] };
|
|
53
|
-
}
|
|
54
|
-
case "find_reusable_block": {
|
|
55
|
-
return { content: [{ type: "text", text: JSON.stringify(findReusableBlock(args.query)) }] };
|
|
56
|
-
}
|
|
57
|
-
case "find_engineering_unit": {
|
|
58
|
-
const result = findEngineeringUnit(String(args.query ?? ""));
|
|
59
|
-
if (!result) {
|
|
60
|
-
return { content: [{ type: "text", text: JSON.stringify({ error: `No unit found` }) }], isError: true };
|
|
61
|
-
}
|
|
62
|
-
return { content: [{ type: "text", text: JSON.stringify(result) }] };
|
|
63
|
-
}
|
|
64
|
-
default:
|
|
65
|
-
return { content: [{ type: "text", text: JSON.stringify({ error: `Unknown tool: ${name}` }) }], isError: true };
|
|
66
45
|
}
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
const LOCAL_TOOLS = [
|
|
49
|
+
defineLocalTool({
|
|
50
|
+
name: "resolve_dependencies",
|
|
51
|
+
description: "Given one or more companion spec namespace aliases, returns the full " +
|
|
52
|
+
"resolved dependency list that MUST go in the YAML `namespaces:` section. " +
|
|
53
|
+
"Always call this before generating the namespaces block.",
|
|
54
|
+
schema: { aliases: z.array(z.string()).describe('Companion spec aliases to resolve (e.g. ["machineTool", "robotics"])') },
|
|
55
|
+
run: ({ aliases }) => jsonResult(resolveDependencies(aliases))
|
|
56
|
+
}),
|
|
57
|
+
defineLocalTool({
|
|
58
|
+
name: "list_namespaces",
|
|
59
|
+
description: "List all well-known OPC UA companion spec namespace aliases with their " +
|
|
60
|
+
"full names, URIs, and dependencies. Use this to discover what namespaces are available.",
|
|
61
|
+
schema: {},
|
|
62
|
+
run: () => jsonResult(listNamespaces().map((s) => ({ alias: s.alias, name: s.name, uri: s.uri, dependencies: s.deps })))
|
|
63
|
+
}),
|
|
64
|
+
defineLocalTool({
|
|
65
|
+
name: "list_types",
|
|
66
|
+
description: "List ALL ObjectTypes, VariableTypes, and InterfaceTypes defined in a " +
|
|
67
|
+
"specific companion spec namespace. " +
|
|
68
|
+
"ALWAYS call this before using any type from a namespace — NEVER guess type names.",
|
|
69
|
+
schema: { alias: z.string().describe('Companion spec alias (e.g. "machinery", "di", "robotics")') },
|
|
70
|
+
run: ({ alias }) => jsonResult(listTypes(alias))
|
|
71
|
+
}),
|
|
72
|
+
defineLocalTool({
|
|
73
|
+
name: "get_type_details",
|
|
74
|
+
description: "Get detailed information about a specific type: its components, properties, " +
|
|
75
|
+
"methods, interfaces, and optional members. Use this to understand a type's " +
|
|
76
|
+
"structure before creating instances or subtypes.",
|
|
77
|
+
schema: {
|
|
78
|
+
alias: z.string().describe('Companion spec alias where the type is defined (e.g. "machinery")'),
|
|
79
|
+
browseName: z.string().describe('The type browse name (e.g. "MachineryItemIdentificationType")')
|
|
80
|
+
},
|
|
81
|
+
run: ({ alias, browseName }) => {
|
|
82
|
+
const details = getTypeDetails(alias, browseName);
|
|
83
|
+
return details ? jsonResult(details) : jsonError(`Type "${browseName}" not found in "${alias}"`);
|
|
84
|
+
}
|
|
85
|
+
}),
|
|
86
|
+
defineLocalTool({
|
|
87
|
+
name: "search_types",
|
|
88
|
+
description: "Search for types across ALL companion specs by keyword. " +
|
|
89
|
+
"Use this when you don't know which namespace defines a type. " +
|
|
90
|
+
"Returns matching types with their namespace alias.",
|
|
91
|
+
schema: { query: z.string().describe('Search keyword (e.g. "identification", "temperature", "motion")') },
|
|
92
|
+
run: ({ query }) => jsonResult(searchTypes(query))
|
|
93
|
+
}),
|
|
94
|
+
defineLocalTool({
|
|
95
|
+
name: "find_reusable_block",
|
|
96
|
+
description: "Find reusable Interfaces / AddIns by capability — pass a member name or keyword " +
|
|
97
|
+
'(e.g. "SerialNumber", "DeviceHealth", "Location") and get the standard blocks that ' +
|
|
98
|
+
"already expose it. PREFER applying/composing an existing block over redefining its " +
|
|
99
|
+
"members inline. Interfaces are applied with `interfaces:`; addins (types with a " +
|
|
100
|
+
"DefaultInstanceBrowseName) are composed with `addIns:`. A single property → use the " +
|
|
101
|
+
"Interface; a whole named sub-object → use the AddIn.",
|
|
102
|
+
schema: { query: z.string().describe('Member name or capability keyword (e.g. "SerialNumber", "health", "calibration")') },
|
|
103
|
+
run: ({ query }) => jsonResult(findReusableBlock(query))
|
|
104
|
+
}),
|
|
105
|
+
defineLocalTool({
|
|
106
|
+
name: "find_engineering_unit",
|
|
107
|
+
description: "Find the official UNECE Rec. 20 engineering unit symbol for a given description. " +
|
|
108
|
+
"ALWAYS call this before using any engineering unit — NEVER guess unit symbols.",
|
|
109
|
+
schema: {
|
|
110
|
+
query: z
|
|
111
|
+
.string()
|
|
112
|
+
.describe('Description or common name of the unit (e.g. "revolutions per minute", "celsius", "pressure bar")')
|
|
113
|
+
},
|
|
114
|
+
run: ({ query }) => {
|
|
115
|
+
const result = findEngineeringUnit(query);
|
|
116
|
+
return result ? jsonResult(result) : jsonError(`No unit found for "${query}"`);
|
|
117
|
+
}
|
|
118
|
+
})
|
|
119
|
+
];
|
|
120
|
+
const LOCAL_TOOLS_BY_NAME = new Map(LOCAL_TOOLS.map((t) => [t.name, t]));
|
|
121
|
+
/**
|
|
122
|
+
* Direct tool call handler for testing (bypasses the MCP protocol). Runs the
|
|
123
|
+
* SAME validated `invoke` path the MCP server uses. Cloud tools are not handled
|
|
124
|
+
* here (they require the network) → treated as unknown.
|
|
125
|
+
*/
|
|
126
|
+
export async function handleToolCall(name, args) {
|
|
127
|
+
const tool = LOCAL_TOOLS_BY_NAME.get(name);
|
|
128
|
+
if (!tool)
|
|
129
|
+
return jsonError(`Unknown tool: ${name}`);
|
|
130
|
+
return tool.invoke(args);
|
|
71
131
|
}
|
|
72
132
|
/**
|
|
73
133
|
* Create and configure the MCP server with all OPC UA tools registered.
|
|
@@ -79,113 +139,46 @@ export function createServer() {
|
|
|
79
139
|
name: "opcua-modeler",
|
|
80
140
|
version: "1.2.0"
|
|
81
141
|
});
|
|
82
|
-
// ──
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
name: s.name,
|
|
105
|
-
uri: s.uri,
|
|
106
|
-
dependencies: s.deps
|
|
107
|
-
}));
|
|
108
|
-
return {
|
|
109
|
-
content: [{ type: "text", text: JSON.stringify(specs) }]
|
|
110
|
-
};
|
|
111
|
-
});
|
|
112
|
-
// ── 3. list_types ────────────────────────────────────────────────────
|
|
113
|
-
server.tool("list_types", "List ALL ObjectTypes, VariableTypes, and InterfaceTypes defined in a " +
|
|
114
|
-
"specific companion spec namespace. " +
|
|
115
|
-
"ALWAYS call this before using any type from a namespace — NEVER guess type names.", { alias: z.string().describe('Companion spec alias (e.g. "machinery", "di", "robotics")') }, async ({ alias }) => {
|
|
116
|
-
const types = listTypes(alias);
|
|
117
|
-
return {
|
|
118
|
-
content: [{ type: "text", text: JSON.stringify(types) }]
|
|
119
|
-
};
|
|
120
|
-
});
|
|
121
|
-
// ── 4. get_type_details ──────────────────────────────────────────────
|
|
122
|
-
server.tool("get_type_details", "Get detailed information about a specific type: its components, properties, " +
|
|
123
|
-
"methods, interfaces, and optional members. Use this to understand a type's " +
|
|
124
|
-
"structure before creating instances or subtypes.", {
|
|
125
|
-
alias: z.string().describe('Companion spec alias where the type is defined (e.g. "machinery")'),
|
|
126
|
-
browseName: z.string().describe('The type browse name (e.g. "MachineryItemIdentificationType")')
|
|
127
|
-
}, async ({ alias, browseName }) => {
|
|
128
|
-
const details = getTypeDetails(alias, browseName);
|
|
129
|
-
if (!details) {
|
|
130
|
-
return {
|
|
131
|
-
content: [{ type: "text", text: JSON.stringify({ error: `Type "${browseName}" not found in "${alias}"` }) }],
|
|
132
|
-
isError: true
|
|
133
|
-
};
|
|
134
|
-
}
|
|
135
|
-
return {
|
|
136
|
-
content: [{ type: "text", text: JSON.stringify(details) }]
|
|
137
|
-
};
|
|
138
|
-
});
|
|
139
|
-
// ── 5. search_types ──────────────────────────────────────────────────
|
|
140
|
-
server.tool("search_types", "Search for types across ALL companion specs by keyword. " +
|
|
141
|
-
"Use this when you don't know which namespace defines a type. " +
|
|
142
|
-
"Returns matching types with their namespace alias.", { query: z.string().describe('Search keyword (e.g. "identification", "temperature", "motion")') }, async ({ query }) => {
|
|
143
|
-
const results = searchTypes(query);
|
|
144
|
-
return {
|
|
145
|
-
content: [{ type: "text", text: JSON.stringify(results) }]
|
|
146
|
-
};
|
|
147
|
-
});
|
|
148
|
-
// ── 5b. find_reusable_block ───────────────────────────────────────────
|
|
149
|
-
server.tool("find_reusable_block", "Find reusable Interfaces / AddIns by capability — pass a member name or keyword " +
|
|
150
|
-
'(e.g. "SerialNumber", "DeviceHealth", "Location") and get the standard blocks that ' +
|
|
151
|
-
"already expose it. PREFER applying/composing an existing block over redefining its " +
|
|
152
|
-
"members inline. Interfaces are applied with `interfaces:`; addins (types with a " +
|
|
153
|
-
"DefaultInstanceBrowseName) are composed with `addIns:`. A single property → use the " +
|
|
154
|
-
"Interface; a whole named sub-object → use the AddIn.", { query: z.string().describe('Member name or capability keyword (e.g. "SerialNumber", "health", "calibration")') }, async ({ query }) => {
|
|
155
|
-
const results = findReusableBlock(query);
|
|
156
|
-
return {
|
|
157
|
-
content: [{ type: "text", text: JSON.stringify(results) }]
|
|
158
|
-
};
|
|
159
|
-
});
|
|
160
|
-
// ── 6. find_engineering_unit ──────────────────────────────────────────
|
|
161
|
-
server.tool("find_engineering_unit", "Find the official UNECE Rec. 20 engineering unit symbol for a given description. " +
|
|
162
|
-
"ALWAYS call this before using any engineering unit — NEVER guess unit symbols.", {
|
|
163
|
-
query: z
|
|
164
|
-
.string()
|
|
165
|
-
.describe('Description or common name of the unit (e.g. "revolutions per minute", "celsius", "pressure bar")')
|
|
166
|
-
}, async ({ query }) => {
|
|
167
|
-
const result = findEngineeringUnit(query);
|
|
168
|
-
if (!result) {
|
|
142
|
+
// ── LOCAL TOOLS — registered from the single-source descriptors ───────
|
|
143
|
+
// Same list `handleToolCall` uses, so protocol and test paths never diverge.
|
|
144
|
+
for (const tool of LOCAL_TOOLS) {
|
|
145
|
+
server.registerTool(tool.name, { description: tool.description, inputSchema: tool.schema }, async (args) => tool.invoke(args));
|
|
146
|
+
}
|
|
147
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
148
|
+
// CLOUD TOOLS — proxy to api.opcua-modeler.sterfive.io (Phase 1b)
|
|
149
|
+
// These require the SaaS API to be running. Set OPCUA_MODELER_API_KEY
|
|
150
|
+
// in env for authenticated access (generate/reverse require a key).
|
|
151
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
152
|
+
// ── get_dsl_reference ─────────────────────────────────────────────────
|
|
153
|
+
// Served from the cloud (not bundled here) so the reference always matches
|
|
154
|
+
// the validator it precedes, and the open-source package stays content-free.
|
|
155
|
+
server.registerTool("get_dsl_reference", {
|
|
156
|
+
description: "Get the grammar reference for the OPC UA modeler YAML DSL: file " +
|
|
157
|
+
"header, top-level sections, name-prefix conventions, minimal " +
|
|
158
|
+
"examples, and common mistakes. Call this FIRST before writing any " +
|
|
159
|
+
"YAML model by hand. Works without an API key.",
|
|
160
|
+
inputSchema: {}
|
|
161
|
+
}, async () => {
|
|
162
|
+
const result = await cloudFetch("/api/v1/dsl-reference", "", "", "GET");
|
|
163
|
+
if (!result.ok) {
|
|
169
164
|
return {
|
|
170
|
-
content: [{ type: "text", text:
|
|
165
|
+
content: [{ type: "text", text: formatCloudError(result.error) }],
|
|
171
166
|
isError: true
|
|
172
167
|
};
|
|
173
168
|
}
|
|
174
169
|
return {
|
|
175
|
-
content: [{ type: "text", text:
|
|
170
|
+
content: [{ type: "text", text: result.data.reference }]
|
|
176
171
|
};
|
|
177
172
|
});
|
|
178
|
-
// ═══════════════════════════════════════════════════════════════════════
|
|
179
|
-
// CLOUD TOOLS — proxy to api.opcua-modeler.sterfive.io (Phase 1b)
|
|
180
|
-
// These require the SaaS API to be running. Set OPCUA_MODELER_API_KEY
|
|
181
|
-
// in env for authenticated access (generate/reverse require a key).
|
|
182
|
-
// ═══════════════════════════════════════════════════════════════════════
|
|
183
173
|
// ── 7. opcua_model_validate ───────────────────────────────────────────
|
|
184
|
-
server.
|
|
185
|
-
"
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
174
|
+
server.registerTool("opcua_model_validate", {
|
|
175
|
+
description: "Validate an OPC UA YAML model for correctness. Returns diagnostics " +
|
|
176
|
+
"with severity (error/warning/info), codes, messages, and line numbers. " +
|
|
177
|
+
"Works without an API key (limited to 50 calls/day). " +
|
|
178
|
+
"ALWAYS validate before generating.",
|
|
179
|
+
inputSchema: {
|
|
180
|
+
yaml: z.string().describe("The full YAML model source to validate")
|
|
181
|
+
}
|
|
189
182
|
}, async ({ yaml }) => {
|
|
190
183
|
const result = await cloudFetch("/api/v1/validate", yaml, "text/yaml");
|
|
191
184
|
if (!result.ok) {
|
|
@@ -199,13 +192,16 @@ export function createServer() {
|
|
|
199
192
|
};
|
|
200
193
|
});
|
|
201
194
|
// ── 8. opcua_model_generate ───────────────────────────────────────────
|
|
202
|
-
server.
|
|
203
|
-
"
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
195
|
+
server.registerTool("opcua_model_generate", {
|
|
196
|
+
description: "Generate OPC UA NodeSet2.xml and Symbols.CSV from a YAML model. " +
|
|
197
|
+
"Requires an API key (set OPCUA_MODELER_API_KEY env var). " +
|
|
198
|
+
"Returns base64-encoded artifacts if the model is valid, " +
|
|
199
|
+
"or diagnostics if validation fails. " +
|
|
200
|
+
"Optionally set include_docs=true to also generate markdown documentation.",
|
|
201
|
+
inputSchema: {
|
|
202
|
+
yaml: z.string().describe("The full YAML model source to generate from"),
|
|
203
|
+
include_docs: z.boolean().optional().describe("Set to true to include markdown documentation (slower)")
|
|
204
|
+
}
|
|
209
205
|
}, async ({ yaml, include_docs }) => {
|
|
210
206
|
const path = include_docs ? "/api/v1/generate?include=docs" : "/api/v1/generate";
|
|
211
207
|
const result = await cloudFetch(path, yaml, "text/yaml");
|
|
@@ -220,11 +216,14 @@ export function createServer() {
|
|
|
220
216
|
};
|
|
221
217
|
});
|
|
222
218
|
// ── 9. opcua_model_reverse ────────────────────────────────────────────
|
|
223
|
-
server.
|
|
224
|
-
"
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
219
|
+
server.registerTool("opcua_model_reverse", {
|
|
220
|
+
description: "Reverse-engineer a NodeSet2.xml file back into the YAML DSL format. " +
|
|
221
|
+
"Requires an API key (set OPCUA_MODELER_API_KEY env var). " +
|
|
222
|
+
"Optionally specify the target namespace URI to extract.",
|
|
223
|
+
inputSchema: {
|
|
224
|
+
xml: z.string().describe("The NodeSet2.xml content to reverse-engineer"),
|
|
225
|
+
namespace_uri: z.string().optional().describe("Target namespace URI to extract (auto-detected if omitted)")
|
|
226
|
+
}
|
|
228
227
|
}, async ({ xml, namespace_uri }) => {
|
|
229
228
|
const path = namespace_uri ? `/api/v1/reverse?ns=${encodeURIComponent(namespace_uri)}` : "/api/v1/reverse";
|
|
230
229
|
const result = await cloudFetch(path, xml, "application/xml");
|
|
@@ -239,13 +238,33 @@ export function createServer() {
|
|
|
239
238
|
};
|
|
240
239
|
});
|
|
241
240
|
// ── 10. opcua_model_create ─────────────────────────────────────────────
|
|
242
|
-
server.
|
|
243
|
-
"
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
241
|
+
server.registerTool("opcua_model_create", {
|
|
242
|
+
description: "Generate an OPC UA YAML model from a natural language description " +
|
|
243
|
+
"using AI. Requires an API key (set OPCUA_MODELER_API_KEY env var). " +
|
|
244
|
+
"The AI will auto-detect relevant companion specs, generate a " +
|
|
245
|
+
"validated model with documentation, and auto-correct validation errors.",
|
|
246
|
+
inputSchema: {
|
|
247
|
+
prompt: z.string().describe("Natural language description of the OPC UA model to generate"),
|
|
248
|
+
forceSpecs: z.array(z.string()).optional().describe('Companion spec aliases to force (e.g. ["di", "ia"])')
|
|
249
|
+
}
|
|
248
250
|
}, async ({ prompt, forceSpecs }) => {
|
|
251
|
+
// The on-premise backend does not implement AI generation. It would
|
|
252
|
+
// answer 501, but saying so here avoids a pointless round trip and a
|
|
253
|
+
// confusing error for an agent that cannot change the backend anyway.
|
|
254
|
+
if (isLocalBackend()) {
|
|
255
|
+
return {
|
|
256
|
+
content: [
|
|
257
|
+
{
|
|
258
|
+
type: "text",
|
|
259
|
+
text: formatCloudError({
|
|
260
|
+
error: "AI model generation is not available on the on-premise backend.",
|
|
261
|
+
hint: "Set OPCUA_MODELER_BACKEND=cloud to use the hosted API for this tool. The other tools work on either backend."
|
|
262
|
+
})
|
|
263
|
+
}
|
|
264
|
+
],
|
|
265
|
+
isError: true
|
|
266
|
+
};
|
|
267
|
+
}
|
|
249
268
|
const result = await cloudFetch("/api/v1/ai/generate", JSON.stringify({ prompt, forceSpecs, stream: false }), "application/json");
|
|
250
269
|
if (!result.ok) {
|
|
251
270
|
return {
|