node-opcua-modeler-mcp-server 1.2.3 → 1.4.2

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/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;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,iBAAiB,CAAC,MAAyB,OAAO,CAAC,GAAG;IACpE,IAAI,OAAO,CAAC,QAAQ,KAA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
2
  * ==========================================================================
3
3
  * OPC UA Modeler — MCP Server Factory (IP-Safe Version)
4
4
  *
5
- * Creates and configures the MCP server with 10 OPC UA tools:
6
- * - 6 LOCAL tools: query the static type catalog (free, offline)
7
- * - 4 CLOUD tools: proxy to api.opcua-modeler.sterfive.io
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.
@@ -13,27 +13,23 @@
13
13
  * ==========================================================================
14
14
  */
15
15
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
16
- import { findEngineeringUnit, getTypeDetails, listNamespaces, listTypes, resolveDependencies, searchTypes } from "./catalog.js";
17
- export { findEngineeringUnit, getTypeDetails, listNamespaces, listTypes, resolveDependencies, searchTypes };
16
+ import { findEngineeringUnit, findReusableBlock, getTypeDetails, listNamespaces, listTypes, resolveDependencies, searchTypes } from "./catalog.js";
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_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: boolean;
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 10 OPC UA tools:
6
- * - 6 LOCAL tools: query the static type catalog (free, offline)
7
- * - 4 CLOUD tools: proxy to api.opcua-modeler.sterfive.io
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.
@@ -14,57 +14,120 @@
14
14
  */
15
15
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
16
16
  import { z } from "zod";
17
- import { findEngineeringUnit, getTypeDetails, listNamespaces, listTypes, resolveDependencies, searchTypes } from "./catalog.js";
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
- export { findEngineeringUnit, getTypeDetails, listNamespaces, listTypes, resolveDependencies, searchTypes };
21
- /**
22
- * Direct tool call handler for testing (bypasses MCP protocol).
23
- * Returns the same shape as MCP tool responses.
24
- */
25
- export async function handleToolCall(name, args) {
26
- try {
27
- switch (name) {
28
- case "resolve_dependencies": {
29
- const aliases = args.aliases;
30
- return { content: [{ type: "text", text: JSON.stringify(resolveDependencies(aliases)) }] };
31
- }
32
- case "list_namespaces": {
33
- const specs = listNamespaces().map((s) => ({
34
- alias: s.alias,
35
- name: s.name,
36
- uri: s.uri,
37
- dependencies: s.deps
38
- }));
39
- return { content: [{ type: "text", text: JSON.stringify(specs) }] };
21
+ export { findEngineeringUnit, findReusableBlock, getTypeDetails, listNamespaces, listTypes, resolveDependencies, searchTypes };
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
- case "list_types": {
42
- return { content: [{ type: "text", text: JSON.stringify(listTypes(args.alias)) }] };
39
+ try {
40
+ return spec.run(parsed.data);
43
41
  }
44
- case "get_type_details": {
45
- const details = getTypeDetails(args.alias, args.browseName);
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_engineering_unit": {
55
- const result = findEngineeringUnit(String(args.query ?? ""));
56
- if (!result) {
57
- return { content: [{ type: "text", text: JSON.stringify({ error: `No unit found` }) }], isError: true };
58
- }
59
- return { content: [{ type: "text", text: JSON.stringify(result) }] };
60
- }
61
- default:
62
- return { content: [{ type: "text", text: JSON.stringify({ error: `Unknown tool: ${name}` }) }], isError: true };
63
45
  }
64
- }
65
- catch (e) {
66
- return { content: [{ type: "text", text: JSON.stringify({ error: String(e) }) }], isError: true };
67
- }
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);
68
131
  }
69
132
  /**
70
133
  * Create and configure the MCP server with all OPC UA tools registered.
@@ -76,101 +139,46 @@ export function createServer() {
76
139
  name: "opcua-modeler",
77
140
  version: "1.2.0"
78
141
  });
79
- // ── 1. resolve_dependencies ──────────────────────────────────────────
80
- server.tool("resolve_dependencies", "Given one or more companion spec namespace aliases, returns the full " +
81
- "resolved dependency list that MUST go in the YAML `namespaces:` section. " +
82
- "Always call this before generating the namespaces block.", { aliases: z.array(z.string()).describe('Companion spec aliases to resolve (e.g. ["machineTool", "robotics"])') }, async ({ aliases }) => {
83
- try {
84
- const resolved = resolveDependencies(aliases);
85
- return {
86
- content: [{ type: "text", text: JSON.stringify(resolved) }]
87
- };
88
- }
89
- catch (e) {
90
- return {
91
- content: [{ type: "text", text: JSON.stringify({ error: String(e) }) }],
92
- isError: true
93
- };
94
- }
95
- });
96
- // ── 2. list_namespaces ───────────────────────────────────────────────
97
- server.tool("list_namespaces", "List all well-known OPC UA companion spec namespace aliases with their " +
98
- "full names, URIs, and dependencies. Use this to discover what namespaces are available.", {}, async () => {
99
- const specs = listNamespaces().map((s) => ({
100
- alias: s.alias,
101
- name: s.name,
102
- uri: s.uri,
103
- dependencies: s.deps
104
- }));
105
- return {
106
- content: [{ type: "text", text: JSON.stringify(specs) }]
107
- };
108
- });
109
- // ── 3. list_types ────────────────────────────────────────────────────
110
- server.tool("list_types", "List ALL ObjectTypes, VariableTypes, and InterfaceTypes defined in a " +
111
- "specific companion spec namespace. " +
112
- "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 }) => {
113
- const types = listTypes(alias);
114
- return {
115
- content: [{ type: "text", text: JSON.stringify(types) }]
116
- };
117
- });
118
- // ── 4. get_type_details ──────────────────────────────────────────────
119
- server.tool("get_type_details", "Get detailed information about a specific type: its components, properties, " +
120
- "methods, interfaces, and optional members. Use this to understand a type's " +
121
- "structure before creating instances or subtypes.", {
122
- alias: z.string().describe('Companion spec alias where the type is defined (e.g. "machinery")'),
123
- browseName: z.string().describe('The type browse name (e.g. "MachineryItemIdentificationType")')
124
- }, async ({ alias, browseName }) => {
125
- const details = getTypeDetails(alias, browseName);
126
- if (!details) {
127
- return {
128
- content: [{ type: "text", text: JSON.stringify({ error: `Type "${browseName}" not found in "${alias}"` }) }],
129
- isError: true
130
- };
131
- }
132
- return {
133
- content: [{ type: "text", text: JSON.stringify(details) }]
134
- };
135
- });
136
- // ── 5. search_types ──────────────────────────────────────────────────
137
- server.tool("search_types", "Search for types across ALL companion specs by keyword. " +
138
- "Use this when you don't know which namespace defines a type. " +
139
- "Returns matching types with their namespace alias.", { query: z.string().describe('Search keyword (e.g. "identification", "temperature", "motion")') }, async ({ query }) => {
140
- const results = searchTypes(query);
141
- return {
142
- content: [{ type: "text", text: JSON.stringify(results) }]
143
- };
144
- });
145
- // ── 6. find_engineering_unit ──────────────────────────────────────────
146
- server.tool("find_engineering_unit", "Find the official UNECE Rec. 20 engineering unit symbol for a given description. " +
147
- "ALWAYS call this before using any engineering unit — NEVER guess unit symbols.", {
148
- query: z
149
- .string()
150
- .describe('Description or common name of the unit (e.g. "revolutions per minute", "celsius", "pressure bar")')
151
- }, async ({ query }) => {
152
- const result = findEngineeringUnit(query);
153
- 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) {
154
164
  return {
155
- content: [{ type: "text", text: JSON.stringify({ error: `No unit found for "${query}"` }) }],
165
+ content: [{ type: "text", text: formatCloudError(result.error) }],
156
166
  isError: true
157
167
  };
158
168
  }
159
169
  return {
160
- content: [{ type: "text", text: JSON.stringify(result) }]
170
+ content: [{ type: "text", text: result.data.reference }]
161
171
  };
162
172
  });
163
- // ═══════════════════════════════════════════════════════════════════════
164
- // CLOUD TOOLS — proxy to api.opcua-modeler.sterfive.io (Phase 1b)
165
- // These require the SaaS API to be running. Set OPCUA_MODELER_API_KEY
166
- // in env for authenticated access (generate/reverse require a key).
167
- // ═══════════════════════════════════════════════════════════════════════
168
173
  // ── 7. opcua_model_validate ───────────────────────────────────────────
169
- server.tool("opcua_model_validate", "Validate an OPC UA YAML model for correctness. Returns diagnostics " +
170
- "with severity (error/warning/info), codes, messages, and line numbers. " +
171
- "Works without an API key (limited to 50 calls/day). " +
172
- "ALWAYS validate before generating.", {
173
- yaml: z.string().describe("The full YAML model source to validate")
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
+ }
174
182
  }, async ({ yaml }) => {
175
183
  const result = await cloudFetch("/api/v1/validate", yaml, "text/yaml");
176
184
  if (!result.ok) {
@@ -184,13 +192,16 @@ export function createServer() {
184
192
  };
185
193
  });
186
194
  // ── 8. opcua_model_generate ───────────────────────────────────────────
187
- server.tool("opcua_model_generate", "Generate OPC UA NodeSet2.xml and Symbols.CSV from a YAML model. " +
188
- "Requires an API key (set OPCUA_MODELER_API_KEY env var). " +
189
- "Returns base64-encoded artifacts if the model is valid, " +
190
- "or diagnostics if validation fails. " +
191
- "Optionally set include_docs=true to also generate markdown documentation.", {
192
- yaml: z.string().describe("The full YAML model source to generate from"),
193
- include_docs: z.boolean().optional().describe("Set to true to include markdown documentation (slower)")
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
+ }
194
205
  }, async ({ yaml, include_docs }) => {
195
206
  const path = include_docs ? "/api/v1/generate?include=docs" : "/api/v1/generate";
196
207
  const result = await cloudFetch(path, yaml, "text/yaml");
@@ -205,11 +216,14 @@ export function createServer() {
205
216
  };
206
217
  });
207
218
  // ── 9. opcua_model_reverse ────────────────────────────────────────────
208
- server.tool("opcua_model_reverse", "Reverse-engineer a NodeSet2.xml file back into the YAML DSL format. " +
209
- "Requires an API key (set OPCUA_MODELER_API_KEY env var). " +
210
- "Optionally specify the target namespace URI to extract.", {
211
- xml: z.string().describe("The NodeSet2.xml content to reverse-engineer"),
212
- namespace_uri: z.string().optional().describe("Target namespace URI to extract (auto-detected if omitted)")
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
+ }
213
227
  }, async ({ xml, namespace_uri }) => {
214
228
  const path = namespace_uri ? `/api/v1/reverse?ns=${encodeURIComponent(namespace_uri)}` : "/api/v1/reverse";
215
229
  const result = await cloudFetch(path, xml, "application/xml");
@@ -224,13 +238,33 @@ export function createServer() {
224
238
  };
225
239
  });
226
240
  // ── 10. opcua_model_create ─────────────────────────────────────────────
227
- server.tool("opcua_model_create", "Generate an OPC UA YAML model from a natural language description " +
228
- "using AI. Requires an API key (set OPCUA_MODELER_API_KEY env var). " +
229
- "The AI will auto-detect relevant companion specs, generate a " +
230
- "validated model with documentation, and auto-correct validation errors.", {
231
- prompt: z.string().describe("Natural language description of the OPC UA model to generate"),
232
- forceSpecs: z.array(z.string()).optional().describe('Companion spec aliases to force (e.g. ["di", "ia"])')
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
+ }
233
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
+ }
234
268
  const result = await cloudFetch("/api/v1/ai/generate", JSON.stringify({ prompt, forceSpecs, stream: false }), "application/json");
235
269
  if (!result.ok) {
236
270
  return {