node-opcua-modeler-mcp-server 1.6.1 → 1.7.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.
@@ -0,0 +1,134 @@
1
+ /**
2
+ * ==========================================================================
3
+ * OPC UA Modeler — generate: NodeId stability and files on disk
4
+ *
5
+ * Work items 8 and 11. Every regeneration must replay the symbols of the
6
+ * previous one, or the NodeIds change and every server and client bound to
7
+ * them breaks. A tool description alone does not make agents do that, so a
8
+ * generate call has to SAY what it is: an update (symbols passed back), a
9
+ * first generation (`mode: "new"`), or a deliberate renumbering. A call that
10
+ * says nothing is refused before it reaches the backend, with the reason.
11
+ *
12
+ * Each call is judged on its own arguments: nothing is remembered between
13
+ * calls, so the rule holds over stdio and hosted HTTP, and across restarts.
14
+ *
15
+ * The file helpers serve the stdio server only, which runs as the user next
16
+ * to their files: the agent passes a path and never carries the NodeSet2.
17
+ *
18
+ * IMPORTANT: Never use console.log() — stdout is reserved for JSON-RPC.
19
+ * ==========================================================================
20
+ */
21
+ export type SymbolsMode = "new" | "update" | "renumber";
22
+ export interface Hint {
23
+ code: string;
24
+ level: "info" | "warning";
25
+ message: string;
26
+ }
27
+ export interface Diagnostic {
28
+ severity: string;
29
+ code?: string;
30
+ message: string;
31
+ line?: number | null;
32
+ }
33
+ /** A previous generate returned the CSV base64-encoded; accept it as is, or as text. */
34
+ export declare function decodeSymbolsArg(value: string): string;
35
+ /** `name,id,nodeClass` lines, as `toCSV` writes them, to a name → id map. */
36
+ export declare function parseSymbols(csv: string): Map<string, number>;
37
+ /**
38
+ * A self-contained `.opcua.yaml` stream. Restated from
39
+ * `@sterfive/opcua-modeler-ex` (self_contained/stream.ts) rather than
40
+ * imported: this package depends on the MCP SDK and zod only.
41
+ */
42
+ export declare function isSelfContainedStream(text: string): boolean;
43
+ /** The stream carries its own symbol table, which the engine replays. */
44
+ export declare function hasEmbeddedSymbolTable(text: string): boolean;
45
+ /**
46
+ * The symbols CSV paired with a model file: `<name>.model.symbols.csv` next
47
+ * to `<name>.model.yaml`. Restated from `pairedSymbolsFile` in
48
+ * `@sterfive/opcua-modeler-ex` (self_contained/pack.ts); a test on each side
49
+ * pins the same names. Reading also accepts the older `<name>.symbols.csv`.
50
+ */
51
+ export declare function pairedSymbolsFile(modelFile: string, forWriting?: boolean): string;
52
+ /** The files `opcua-modeler generate <model>` writes, in `outputDir` or beside the model. */
53
+ export declare function outputFiles(modelFile: string, outputDir?: string): {
54
+ nodeset: string;
55
+ markdown: string;
56
+ symbols: string;
57
+ };
58
+ export type SymbolsSource = "argument" | "paired-file" | "stream" | "none";
59
+ export type SymbolsDecision = {
60
+ ok: true;
61
+ /** CSV text to replay, if any. */
62
+ send?: string;
63
+ /** What the new symbols are compared with: what was replayed, or replaced. */
64
+ previous?: string;
65
+ source: SymbolsSource;
66
+ } | {
67
+ ok: false;
68
+ code: string;
69
+ message: string;
70
+ };
71
+ export interface SymbolsInput {
72
+ mode?: SymbolsMode;
73
+ /** From the `symbols_csv` argument, decoded. */
74
+ symbolsCsv?: string;
75
+ /** The paired CSV found next to a model passed by path. */
76
+ pairedCsv?: {
77
+ path: string;
78
+ text: string;
79
+ };
80
+ /** Where the paired CSV would be, for the messages (path mode). */
81
+ expectedPairedPath?: string;
82
+ embeddedTable: boolean;
83
+ }
84
+ /** Decide what to replay, or refuse a call that does not say what it is. */
85
+ export declare function decideSymbols(input: SymbolsInput): SymbolsDecision;
86
+ export interface SymbolsReport {
87
+ /** Same name, same id. */
88
+ reused: number;
89
+ /** Not in the previous symbols. */
90
+ new: number;
91
+ /** In the previous symbols, gone from the model: those ids are retired. */
92
+ dropped: number;
93
+ /** Same name, another id: only on a renumbering, or a wrong CSV. */
94
+ renumbered: number;
95
+ /** Share of the previous names the model still has. */
96
+ match: number;
97
+ new_names: string[];
98
+ dropped_names: string[];
99
+ }
100
+ export declare function compareSymbols(previousCsv: string, nextCsv: string): SymbolsReport;
101
+ export interface FileWritten {
102
+ role: "nodeset" | "symbols" | "documentation";
103
+ path: string;
104
+ bytes: number;
105
+ status: "written" | "unchanged";
106
+ }
107
+ export interface HintContext {
108
+ valid: boolean;
109
+ mode?: SymbolsMode;
110
+ source: SymbolsSource;
111
+ report?: SymbolsReport;
112
+ diagnostics: Diagnostic[];
113
+ /** Path mode: what was written. Absent in text mode. */
114
+ files?: FileWritten[];
115
+ /** Show PREFER_STREAM (once per session). */
116
+ suggestStream: boolean;
117
+ }
118
+ /**
119
+ * Hints are generated by code from fixed conditions, with stable codes: they
120
+ * can be tested and never invent advice. Ranked, and few — a long list is
121
+ * skipped like a long tool description.
122
+ */
123
+ export declare function buildHints(ctx: HintContext): {
124
+ hints: Hint[];
125
+ next_steps: string[];
126
+ };
127
+ /**
128
+ * Write `content` unless the file already holds exactly it. Unchanged files
129
+ * are not touched, so git, file watchers and the VS Code extension see
130
+ * nothing when a regeneration changes nothing. The write is atomic: a temp
131
+ * file in the same folder, then a rename, so a crash never leaves half a
132
+ * NodeSet.
133
+ */
134
+ export declare function writeIfChanged(file: string, content: Buffer): Promise<"written" | "unchanged">;
@@ -0,0 +1,289 @@
1
+ /**
2
+ * ==========================================================================
3
+ * OPC UA Modeler — generate: NodeId stability and files on disk
4
+ *
5
+ * Work items 8 and 11. Every regeneration must replay the symbols of the
6
+ * previous one, or the NodeIds change and every server and client bound to
7
+ * them breaks. A tool description alone does not make agents do that, so a
8
+ * generate call has to SAY what it is: an update (symbols passed back), a
9
+ * first generation (`mode: "new"`), or a deliberate renumbering. A call that
10
+ * says nothing is refused before it reaches the backend, with the reason.
11
+ *
12
+ * Each call is judged on its own arguments: nothing is remembered between
13
+ * calls, so the rule holds over stdio and hosted HTTP, and across restarts.
14
+ *
15
+ * The file helpers serve the stdio server only, which runs as the user next
16
+ * to their files: the agent passes a path and never carries the NodeSet2.
17
+ *
18
+ * IMPORTANT: Never use console.log() — stdout is reserved for JSON-RPC.
19
+ * ==========================================================================
20
+ */
21
+ import fs from "node:fs";
22
+ import path from "node:path";
23
+ // ── Symbols input ─────────────────────────────────────────────────────────
24
+ /** A previous generate returned the CSV base64-encoded; accept it as is, or as text. */
25
+ export function decodeSymbolsArg(value) {
26
+ // every CSV line holds two commas; base64 never holds one
27
+ return value.includes(",") ? value : Buffer.from(value, "base64").toString("utf-8");
28
+ }
29
+ /** `name,id,nodeClass` lines, as `toCSV` writes them, to a name → id map. */
30
+ export function parseSymbols(csv) {
31
+ const out = new Map();
32
+ for (const line of csv.trim().split(/\r?\n/)) {
33
+ const [name, id] = line.split(",");
34
+ if (name && id !== undefined)
35
+ out.set(name, Number.parseInt(id, 10));
36
+ }
37
+ return out;
38
+ }
39
+ /**
40
+ * A self-contained `.opcua.yaml` stream. Restated from
41
+ * `@sterfive/opcua-modeler-ex` (self_contained/stream.ts) rather than
42
+ * imported: this package depends on the MCP SDK and zod only.
43
+ */
44
+ export function isSelfContainedStream(text) {
45
+ return /^kind:\s*(symbols|declarations|model)\s*$/m.test(text);
46
+ }
47
+ /** The stream carries its own symbol table, which the engine replays. */
48
+ export function hasEmbeddedSymbolTable(text) {
49
+ return /^kind:\s*symbols\s*$/m.test(text);
50
+ }
51
+ /**
52
+ * The symbols CSV paired with a model file: `<name>.model.symbols.csv` next
53
+ * to `<name>.model.yaml`. Restated from `pairedSymbolsFile` in
54
+ * `@sterfive/opcua-modeler-ex` (self_contained/pack.ts); a test on each side
55
+ * pins the same names. Reading also accepts the older `<name>.symbols.csv`.
56
+ */
57
+ export function pairedSymbolsFile(modelFile, forWriting = false) {
58
+ const parsed = path.parse(modelFile);
59
+ const generateForm = path.join(parsed.dir, `${parsed.name.replace(/\.opcua$/, ".model")}.symbols.csv`);
60
+ if (forWriting)
61
+ return generateForm;
62
+ const shortForm = path.join(parsed.dir, `${parsed.name.replace(/\.model$/, "").replace(/\.opcua$/, "")}.symbols.csv`);
63
+ return fs.existsSync(generateForm) || !fs.existsSync(shortForm) ? generateForm : shortForm;
64
+ }
65
+ /** The files `opcua-modeler generate <model>` writes, in `outputDir` or beside the model. */
66
+ export function outputFiles(modelFile, outputDir) {
67
+ const parsed = path.parse(modelFile);
68
+ const dir = outputDir ?? parsed.dir;
69
+ return {
70
+ nodeset: path.join(dir, `${parsed.name}.Nodeset2.xml`),
71
+ markdown: path.join(dir, `${parsed.name}.md`),
72
+ symbols: path.join(dir, path.basename(pairedSymbolsFile(modelFile, true)))
73
+ };
74
+ }
75
+ /** Decide what to replay, or refuse a call that does not say what it is. */
76
+ export function decideSymbols(input) {
77
+ const { mode, symbolsCsv, pairedCsv, embeddedTable } = input;
78
+ const previous = symbolsCsv ?? pairedCsv?.text;
79
+ const source = symbolsCsv !== undefined ? "argument" : pairedCsv ? "paired-file" : "none";
80
+ const csvName = input.expectedPairedPath ? path.basename(input.expectedPairedPath) : "<name>.model.symbols.csv";
81
+ if (mode === "renumber") {
82
+ return { ok: true, previous, source: embeddedTable ? "stream" : source };
83
+ }
84
+ if (mode === "new") {
85
+ if (symbolsCsv !== undefined) {
86
+ return {
87
+ ok: false,
88
+ code: "MODE_CONFLICT",
89
+ message: 'mode "new" is for a model generated for the first time, but symbols_csv was passed. Drop mode to replay them, or pass mode "renumber" to allocate new ids on purpose.'
90
+ };
91
+ }
92
+ if (pairedCsv) {
93
+ return {
94
+ ok: false,
95
+ code: "SYMBOLS_FILE_EXISTS",
96
+ message: `${pairedCsv.path} exists: this model was generated before. Drop mode to keep its NodeIds (the file is read automatically), or pass mode "renumber" to allocate new ids on purpose.`
97
+ };
98
+ }
99
+ if (embeddedTable) {
100
+ return {
101
+ ok: false,
102
+ code: "MODE_CONFLICT",
103
+ message: 'This self-contained stream carries a symbol table: the model was generated before. Drop mode to keep its NodeIds, or pass mode "renumber".'
104
+ };
105
+ }
106
+ return { ok: true, source: "none" };
107
+ }
108
+ if (previous !== undefined)
109
+ return { ok: true, send: previous, previous, source };
110
+ if (embeddedTable)
111
+ return { ok: true, source: "stream" };
112
+ if (mode === "update") {
113
+ return {
114
+ ok: false,
115
+ code: "SYMBOLS_REQUIRED",
116
+ message: `mode "update" needs the symbols of the previous generation: pass them as symbols_csv (the content of ${csvName}).`
117
+ };
118
+ }
119
+ return {
120
+ ok: false,
121
+ code: "SYMBOLS_DECISION_REQUIRED",
122
+ message: [
123
+ "NodeIds only stay stable if you pass back the symbols CSV from the previous generation. Retry with one of:",
124
+ `- generated before: symbols_csv (the content of ${csvName});`,
125
+ '- first generation: mode: "new";',
126
+ '- renumbering on purpose: mode: "renumber".'
127
+ ].join("\n")
128
+ };
129
+ }
130
+ // ── What changed ──────────────────────────────────────────────────────────
131
+ const NAMES_SHOWN = 10;
132
+ export function compareSymbols(previousCsv, nextCsv) {
133
+ const before = parseSymbols(previousCsv);
134
+ const after = parseSymbols(nextCsv);
135
+ let reused = 0;
136
+ let renumbered = 0;
137
+ const newNames = [];
138
+ for (const [name, id] of after) {
139
+ const old = before.get(name);
140
+ if (old === undefined)
141
+ newNames.push(name);
142
+ else if (old === id)
143
+ reused++;
144
+ else
145
+ renumbered++;
146
+ }
147
+ const droppedNames = [...before.keys()].filter((name) => !after.has(name));
148
+ return {
149
+ reused,
150
+ new: newNames.length,
151
+ dropped: droppedNames.length,
152
+ renumbered,
153
+ match: before.size === 0 ? 1 : Math.round(((reused + renumbered) / before.size) * 100) / 100,
154
+ new_names: newNames.slice(0, NAMES_SHOWN),
155
+ dropped_names: droppedNames.slice(0, NAMES_SHOWN)
156
+ };
157
+ }
158
+ // ── Hints and next steps ──────────────────────────────────────────────────
159
+ const MAX_HINTS = 5;
160
+ /** Below this share of known names, the CSV most likely belongs to another model. */
161
+ const LOW_MATCH = 0.5;
162
+ const list = (names, total) => names.join(", ") + (total > names.length ? `, … (${total} in all)` : "");
163
+ /**
164
+ * Hints are generated by code from fixed conditions, with stable codes: they
165
+ * can be tested and never invent advice. Ranked, and few — a long list is
166
+ * skipped like a long tool description.
167
+ */
168
+ export function buildHints(ctx) {
169
+ const ranked = [];
170
+ const { report, files } = ctx;
171
+ const symbolsFile = files?.find((f) => f.role === "symbols");
172
+ if (!ctx.valid) {
173
+ const errors = ctx.diagnostics.filter((d) => d.severity === "error").length;
174
+ ranked.push({
175
+ code: "INVALID",
176
+ level: "warning",
177
+ message: `The model has ${errors} error(s): no artefact was ${files ? "written" : "produced"}. Fix them (opcua_model_validate gives line numbers), then generate again.`
178
+ });
179
+ return { hints: ranked, next_steps: ["Fix the errors listed in diagnostics, then call opcua_model_generate again."] };
180
+ }
181
+ if (report && report.renumbered > 0) {
182
+ ranked.push({
183
+ code: "IDS_RENUMBERED",
184
+ level: "warning",
185
+ message: ctx.mode === "renumber"
186
+ ? `${report.renumbered} existing node(s) got a new NodeId, as requested: servers and clients bound to the old ids will break.`
187
+ : `${report.renumbered} node(s) changed NodeId although their symbols were passed: the CSV probably belongs to another model.`
188
+ });
189
+ }
190
+ if (report && report.dropped > 0) {
191
+ ranked.push({
192
+ code: "IDS_DROPPED",
193
+ level: "warning",
194
+ message: `${report.dropped} NodeId(s) retired, their nodes are gone from the model: ${list(report.dropped_names, report.dropped)}. Clients bound to them will break.`
195
+ });
196
+ }
197
+ if (report && ctx.mode !== "renumber" && report.match < LOW_MATCH) {
198
+ ranked.push({
199
+ code: "SYMBOLS_LOW_MATCH",
200
+ level: "warning",
201
+ message: `Only ${Math.round(report.match * 100)}% of the names in the symbols passed exist in this model: they probably belong to another model.`
202
+ });
203
+ }
204
+ if (ctx.source === "none" || ctx.mode === "renumber") {
205
+ ranked.push({
206
+ code: "SAVE_SYMBOLS",
207
+ level: "info",
208
+ message: symbolsFile
209
+ ? `Wrote ${symbolsFile.path}: commit it with the model. Later generates read it from there and keep these NodeIds.`
210
+ : "Save symbols_csv (base64-decoded) as <name>.model.symbols.csv next to the model and commit it. Pass it back as symbols_csv on every later generate, or the NodeIds change."
211
+ });
212
+ }
213
+ else if (report && (report.new > 0 || report.dropped > 0)) {
214
+ ranked.push({
215
+ code: "SYMBOLS_UPDATED",
216
+ level: "info",
217
+ message: symbolsFile
218
+ ? `${symbolsFile.path} updated: ${report.new} new id(s)${report.new ? ` (${list(report.new_names, report.new)})` : ""}.`
219
+ : `The symbols changed: ${report.new} new id(s)${report.new ? ` (${list(report.new_names, report.new)})` : ""}. Write symbols_csv back to the file it came from.`
220
+ });
221
+ }
222
+ if (ctx.source === "stream") {
223
+ ranked.push({
224
+ code: "STREAM_TABLE_NOT_UPDATED",
225
+ level: "info",
226
+ message: "This tool does not rewrite the symbol table embedded in the stream. If the model gained nodes, run `opcua-modeler generate <file>` once to record their ids in it."
227
+ });
228
+ }
229
+ const warnings = ctx.diagnostics.filter((d) => d.severity === "warning");
230
+ if (warnings.length > 0) {
231
+ const top = warnings
232
+ .slice(0, 3)
233
+ .map((d) => `${d.code ?? "warning"}${d.line ? ` line ${d.line}` : ""}`)
234
+ .join(", ");
235
+ ranked.push({
236
+ code: "WARNINGS_PRESENT",
237
+ level: "warning",
238
+ message: `${warnings.length} warning(s) (${top}). Fix them before publishing the NodeSet.`
239
+ });
240
+ }
241
+ if (ctx.suggestStream && ctx.source === "argument") {
242
+ ranked.push({
243
+ code: "PREFER_STREAM",
244
+ level: "info",
245
+ message: "Passing the model by path (model_path) or as a self-contained .opcua.yaml stream removes the need to carry symbols_csv between calls."
246
+ });
247
+ }
248
+ const next_steps = [];
249
+ if (files) {
250
+ const written = files.filter((f) => f.status === "written");
251
+ next_steps.push(written.length > 0
252
+ ? `Commit ${written.map((f) => path.basename(f.path)).join(", ")} with the model.`
253
+ : "Nothing changed on disk: the generated files were already up to date.");
254
+ }
255
+ else {
256
+ next_steps.push("Save nodeset2_xml (base64-decoded) as <name>.Nodeset2.xml.", "Save symbols_csv (base64-decoded) as <name>.model.symbols.csv, replacing the previous one.", "Commit both with the model: the CSV is what keeps NodeIds stable.");
257
+ }
258
+ return { hints: ranked.slice(0, MAX_HINTS), next_steps };
259
+ }
260
+ // ── Files ─────────────────────────────────────────────────────────────────
261
+ /**
262
+ * Write `content` unless the file already holds exactly it. Unchanged files
263
+ * are not touched, so git, file watchers and the VS Code extension see
264
+ * nothing when a regeneration changes nothing. The write is atomic: a temp
265
+ * file in the same folder, then a rename, so a crash never leaves half a
266
+ * NodeSet.
267
+ */
268
+ export async function writeIfChanged(file, content) {
269
+ try {
270
+ const existing = await fs.promises.readFile(file);
271
+ if (existing.equals(content))
272
+ return "unchanged";
273
+ }
274
+ catch {
275
+ // absent: write it
276
+ }
277
+ await fs.promises.mkdir(path.dirname(file), { recursive: true });
278
+ const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
279
+ try {
280
+ await fs.promises.writeFile(temp, content);
281
+ await fs.promises.rename(temp, file);
282
+ }
283
+ catch (err) {
284
+ await fs.promises.rm(temp, { force: true });
285
+ throw err;
286
+ }
287
+ return "written";
288
+ }
289
+ //# sourceMappingURL=generate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate.js","sourceRoot":"","sources":["../src/generate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAiB7B,6EAA6E;AAE7E,wFAAwF;AACxF,MAAM,UAAU,gBAAgB,CAAC,KAAa;IAC5C,0DAA0D;IAC1D,OAAO,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AACtF,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAAU,YAAY,CAAC,GAAW;IACtC,MAAM,GAAG,GAAG,IAAI,GAAG,EAAkB,CAAC;IACtC,KAAK,MAAM,IAAI,IAAI,GAAG,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;QAC7C,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACnC,IAAI,IAAI,IAAI,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CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IACjE,MAAM,IAAI,GAAG,GAAG,IAAI,IAAI,OAAO,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,EAAE,MAAM,CAAC;IACxD,IAAI,CAAC;QACH,MAAM,EAAE,CAAC,QAAQ,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC3C,MAAM,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACvC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QAC5C,MAAM,GAAG,CAAC;IACZ,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC"}
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ==========================================================================
4
+ * OPC UA Modeler — MCP Server (HTTP CLI Entry Point)
5
+ *
6
+ * `node-opcua-modeler-mcp-http`, or `node-opcua-modeler-mcp --http`.
7
+ * Serves the same tools as the stdio entry point over streamable HTTP; see
8
+ * http-server.ts for the env vars.
9
+ * ==========================================================================
10
+ */
11
+ export {};
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ==========================================================================
4
+ * OPC UA Modeler — MCP Server (HTTP CLI Entry Point)
5
+ *
6
+ * `node-opcua-modeler-mcp-http`, or `node-opcua-modeler-mcp --http`.
7
+ * Serves the same tools as the stdio entry point over streamable HTTP; see
8
+ * http-server.ts for the env vars.
9
+ * ==========================================================================
10
+ */
11
+ import { startMcpHttpServer } from "./http-server.js";
12
+ startMcpHttpServer();
13
+ //# sourceMappingURL=http-cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-cli.js","sourceRoot":"","sources":["../src/http-cli.ts"],"names":[],"mappings":";AACA;;;;;;;;GAQG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAEtD,kBAAkB,EAAE,CAAC"}
@@ -0,0 +1,36 @@
1
+ /**
2
+ * ==========================================================================
3
+ * OPC UA Modeler — MCP Server (standalone HTTP host)
4
+ *
5
+ * A plain `node:http` server around `handleMcpHttpRequest`, so the server can
6
+ * be self-hosted and registered as a remote streamable-HTTP connector (Mistral
7
+ * connectors, claude.ai custom connectors...) without a framework.
8
+ *
9
+ * POST /mcp MCP JSON-RPC (stateless, JSON responses)
10
+ * GET /health {"ok":true}, never gated
11
+ *
12
+ * Env:
13
+ * PORT listen port (default 8807), bound on 0.0.0.0
14
+ * MCP_HTTP_AUTH_TOKEN if set, /mcp requires `Authorization: Bearer <token>`
15
+ * MCP_HTTP_CORS=1 add permissive CORS headers (off: the reverse proxy
16
+ * is expected to own them)
17
+ *
18
+ * File access stays off: a path sent over HTTP would name a file on THIS
19
+ * host. `handleMcpHttpRequest` already builds the server that way.
20
+ * ==========================================================================
21
+ */
22
+ import { type Server } from "node:http";
23
+ export declare const DEFAULT_PORT = 8807;
24
+ export interface HttpServerOptions {
25
+ /** Bearer token required on /mcp; undefined allows anonymous access. */
26
+ authToken?: string;
27
+ /** Add permissive CORS headers and answer preflight on /mcp. */
28
+ cors?: boolean;
29
+ }
30
+ /** Build (not start) the HTTP server. */
31
+ export declare function createMcpHttpServer(options?: HttpServerOptions): Server;
32
+ /**
33
+ * Start listening and install SIGTERM/SIGINT handlers that stop accepting
34
+ * connections, close the open ones, and exit.
35
+ */
36
+ export declare function startMcpHttpServer(env?: NodeJS.ProcessEnv): Server;
@@ -0,0 +1,150 @@
1
+ /**
2
+ * ==========================================================================
3
+ * OPC UA Modeler — MCP Server (standalone HTTP host)
4
+ *
5
+ * A plain `node:http` server around `handleMcpHttpRequest`, so the server can
6
+ * be self-hosted and registered as a remote streamable-HTTP connector (Mistral
7
+ * connectors, claude.ai custom connectors...) without a framework.
8
+ *
9
+ * POST /mcp MCP JSON-RPC (stateless, JSON responses)
10
+ * GET /health {"ok":true}, never gated
11
+ *
12
+ * Env:
13
+ * PORT listen port (default 8807), bound on 0.0.0.0
14
+ * MCP_HTTP_AUTH_TOKEN if set, /mcp requires `Authorization: Bearer <token>`
15
+ * MCP_HTTP_CORS=1 add permissive CORS headers (off: the reverse proxy
16
+ * is expected to own them)
17
+ *
18
+ * File access stays off: a path sent over HTTP would name a file on THIS
19
+ * host. `handleMcpHttpRequest` already builds the server that way.
20
+ * ==========================================================================
21
+ */
22
+ import { timingSafeEqual } from "node:crypto";
23
+ import { createServer as createHttpServer } from "node:http";
24
+ import { Readable } from "node:stream";
25
+ import { handleMcpHttpRequest } from "./http.js";
26
+ export const DEFAULT_PORT = 8807;
27
+ const CORS_HEADERS = {
28
+ "Access-Control-Allow-Origin": "*",
29
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
30
+ "Access-Control-Allow-Headers": "Content-Type, Authorization, MCP-Protocol-Version, Mcp-Session-Id",
31
+ "Access-Control-Expose-Headers": "Mcp-Session-Id"
32
+ };
33
+ function sendJson(res, status, body, headers = {}) {
34
+ res.writeHead(status, { "Content-Type": "application/json", ...headers });
35
+ res.end(JSON.stringify(body));
36
+ }
37
+ /** Constant-time compare, so the token cannot be guessed byte by byte. */
38
+ function isAuthorized(header, token) {
39
+ const match = /^Bearer\s+(.+)$/i.exec(header ?? "");
40
+ if (!match)
41
+ return false;
42
+ const given = Buffer.from(match[1].trim());
43
+ const expected = Buffer.from(token);
44
+ return given.length === expected.length && timingSafeEqual(given, expected);
45
+ }
46
+ /** The first hop of X-Forwarded-For (set by the reverse proxy), else the socket peer. */
47
+ function clientIp(req) {
48
+ const forwarded = req.headers["x-forwarded-for"];
49
+ const first = (Array.isArray(forwarded) ? forwarded[0] : forwarded)?.split(",")[0]?.trim();
50
+ return first || req.socket.remoteAddress || undefined;
51
+ }
52
+ /** Node `IncomingMessage` → Web `Request`. */
53
+ function toWebRequest(req) {
54
+ const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
55
+ const headers = new Headers();
56
+ for (const [key, value] of Object.entries(req.headers)) {
57
+ if (value === undefined)
58
+ continue;
59
+ for (const v of Array.isArray(value) ? value : [value])
60
+ headers.append(key, v);
61
+ }
62
+ const hasBody = req.method !== "GET" && req.method !== "HEAD";
63
+ return new Request(url, {
64
+ method: req.method,
65
+ headers,
66
+ body: hasBody ? Readable.toWeb(req) : undefined,
67
+ // required by undici whenever the body is a stream
68
+ ...(hasBody ? { duplex: "half" } : {})
69
+ });
70
+ }
71
+ /** Web `Response` → Node `ServerResponse`; streams, so SSE bodies pass through too. */
72
+ async function sendWebResponse(res, response, extra) {
73
+ const headers = {};
74
+ response.headers.forEach((value, key) => {
75
+ headers[key] = value;
76
+ });
77
+ res.writeHead(response.status, { ...headers, ...extra });
78
+ if (!response.body) {
79
+ res.end();
80
+ return;
81
+ }
82
+ for await (const chunk of response.body) {
83
+ res.write(chunk);
84
+ }
85
+ res.end();
86
+ }
87
+ /** Build (not start) the HTTP server. */
88
+ export function createMcpHttpServer(options = {}) {
89
+ const cors = options.cors ? CORS_HEADERS : {};
90
+ return createHttpServer(async (req, res) => {
91
+ const path = new URL(req.url ?? "/", "http://localhost").pathname;
92
+ try {
93
+ if (path === "/health") {
94
+ sendJson(res, req.method === "GET" || req.method === "HEAD" ? 200 : 405, { ok: true });
95
+ return;
96
+ }
97
+ if (path !== "/mcp") {
98
+ sendJson(res, 404, { error: "Not Found" });
99
+ return;
100
+ }
101
+ if (req.method === "OPTIONS" && options.cors) {
102
+ res.writeHead(204, cors);
103
+ res.end();
104
+ return;
105
+ }
106
+ if (options.authToken && !isAuthorized(req.headers.authorization, options.authToken)) {
107
+ sendJson(res, 401, { jsonrpc: "2.0", error: { code: -32001, message: "Unauthorized" }, id: null }, { "WWW-Authenticate": 'Bearer realm="mcp"', ...cors });
108
+ return;
109
+ }
110
+ // Forward the caller's IP so the hosted API rate-limits per user,
111
+ // not per container.
112
+ const ip = clientIp(req);
113
+ const response = await handleMcpHttpRequest(toWebRequest(req), ip ? { forwardHeaders: { "x-forwarded-for": ip } } : undefined);
114
+ await sendWebResponse(res, response, cors);
115
+ }
116
+ catch (err) {
117
+ console.error("MCP HTTP request failed:", err);
118
+ if (!res.headersSent) {
119
+ sendJson(res, 500, { jsonrpc: "2.0", error: { code: -32603, message: "Internal error" }, id: null }, cors);
120
+ }
121
+ else {
122
+ res.end();
123
+ }
124
+ }
125
+ });
126
+ }
127
+ /**
128
+ * Start listening and install SIGTERM/SIGINT handlers that stop accepting
129
+ * connections, close the open ones, and exit.
130
+ */
131
+ export function startMcpHttpServer(env = process.env) {
132
+ const port = Number(env.PORT) || DEFAULT_PORT;
133
+ const authToken = env.MCP_HTTP_AUTH_TOKEN || undefined;
134
+ const server = createMcpHttpServer({ authToken, cors: env.MCP_HTTP_CORS === "1" });
135
+ server.listen(port, "0.0.0.0", () => {
136
+ // never log the token itself
137
+ console.error(`opcua-modeler MCP server listening on http://0.0.0.0:${port}/mcp (auth: ${authToken ? "bearer token" : "anonymous"})`);
138
+ });
139
+ const shutdown = (signal) => {
140
+ console.error(`${signal} received, shutting down`);
141
+ server.close(() => process.exit(0));
142
+ server.closeAllConnections();
143
+ // safety net if a socket refuses to close
144
+ setTimeout(() => process.exit(0), 5000).unref();
145
+ };
146
+ process.once("SIGTERM", () => shutdown("SIGTERM"));
147
+ process.once("SIGINT", () => shutdown("SIGINT"));
148
+ return server;
149
+ }
150
+ //# sourceMappingURL=http-server.js.map