@codesys/mcp-toolkit 1.0.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/dist/server.js ADDED
@@ -0,0 +1,1444 @@
1
+ "use strict";
2
+ /**
3
+ * server.ts
4
+ * MCP Server for interacting with CODESYS via Python scripting.
5
+ * Version: 1.6.9 (Fix disconnect error on shutdown)
6
+ * - Removed invalid server.disconnect() calls in SIGINT/SIGTERM handlers.
7
+ * - Includes property/method creation tools (v1.6.8).
8
+ */
9
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ var desc = Object.getOwnPropertyDescriptor(m, k);
12
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13
+ desc = { enumerable: true, get: function() { return m[k]; } };
14
+ }
15
+ Object.defineProperty(o, k2, desc);
16
+ }) : (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ o[k2] = m[k];
19
+ }));
20
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
21
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
22
+ }) : function(o, v) {
23
+ o["default"] = v;
24
+ });
25
+ var __importStar = (this && this.__importStar) || (function () {
26
+ var ownKeys = function(o) {
27
+ ownKeys = Object.getOwnPropertyNames || function (o) {
28
+ var ar = [];
29
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
30
+ return ar;
31
+ };
32
+ return ownKeys(o);
33
+ };
34
+ return function (mod) {
35
+ if (mod && mod.__esModule) return mod;
36
+ var result = {};
37
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
38
+ __setModuleDefault(result, mod);
39
+ return result;
40
+ };
41
+ })();
42
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
43
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
44
+ return new (P || (P = Promise))(function (resolve, reject) {
45
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
46
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
47
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
48
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
49
+ });
50
+ };
51
+ Object.defineProperty(exports, "__esModule", { value: true });
52
+ console.error(">>> SERVER.TS TOP LEVEL EXECUTION <<<");
53
+ const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
54
+ const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
55
+ const zod_1 = require("zod");
56
+ const codesys_interop_1 = require("./codesys_interop"); // Assumes this utility exists and works
57
+ const os = __importStar(require("os"));
58
+ const path = __importStar(require("path"));
59
+ const promises_1 = require("fs/promises"); // For file existence check
60
+ // --- Configuration ---
61
+ const WORKSPACE_DIR = process.cwd(); // Use current working directory as default workspace
62
+ console.error(`Using Workspace Directory: ${WORKSPACE_DIR}`);
63
+ // --- CODESYS Configuration ---
64
+ let codesysExePath = process.argv[2];
65
+ let codesysProfileName = process.argv[3];
66
+ console.error('Command line arguments:', process.argv);
67
+ if (!codesysExePath) {
68
+ codesysExePath = "C:\\Program Files\\CODESYS 3.5.21.0\\CODESYS\\Common\\CODESYS.exe"; // Default Example - ADJUST IF NEEDED
69
+ console.error(`WARNING: Using default CODESYS path: ${codesysExePath}`);
70
+ }
71
+ if (!codesysProfileName) {
72
+ codesysProfileName = "CODESYS V3.5 SP21"; // Default Example - ADJUST IF NEEDED
73
+ console.error(`WARNING: Using default CODESYS profile: ${codesysProfileName}`);
74
+ }
75
+ console.error('INFO: Using command-line arguments is recommended for production.');
76
+ console.error(`Using CODESYS Path: ${codesysExePath}`);
77
+ console.error(`Using CODESYS Profile: ${codesysProfileName}`);
78
+ console.error(`OS: ${os.platform()} ${os.release()}, Node: ${process.version}, CWD: ${process.cwd()}`);
79
+ // --- End CODESYS Configuration ---
80
+ // --- Helper Function ---
81
+ function fileExists(filePath) {
82
+ return __awaiter(this, void 0, void 0, function* () {
83
+ try {
84
+ yield (0, promises_1.stat)(filePath);
85
+ return true;
86
+ }
87
+ catch (error) {
88
+ if (error.code === 'ENOENT') {
89
+ return false;
90
+ }
91
+ throw error;
92
+ }
93
+ });
94
+ }
95
+ // --- MCP Server Initialization ---
96
+ const server = new mcp_js_1.McpServer({
97
+ name: "CODESYS Control MCP Server",
98
+ version: "1.6.9", // Incremented version
99
+ capabilities: { resources: {}, tools: {} }
100
+ });
101
+ // --- Python Script Templates ---
102
+ // (ENSURE_PROJECT_OPEN_PYTHON_SNIPPET remains the same as before)
103
+ const ENSURE_PROJECT_OPEN_PYTHON_SNIPPET = `
104
+ import sys
105
+ import scriptengine as script_engine
106
+ import os
107
+ import time
108
+ import traceback
109
+
110
+ # --- Function to ensure the correct project is open ---
111
+ MAX_RETRIES = 3
112
+ RETRY_DELAY = 2.0 # seconds (use float for time.sleep)
113
+
114
+ def ensure_project_open(target_project_path):
115
+ print("DEBUG: Ensuring project is open: %s" % target_project_path)
116
+ # Normalize target path once
117
+ normalized_target_path = os.path.normcase(os.path.abspath(target_project_path))
118
+
119
+ for attempt in range(MAX_RETRIES):
120
+ print("DEBUG: Ensure project attempt %d/%d for %s" % (attempt + 1, MAX_RETRIES, normalized_target_path))
121
+ primary_project = None
122
+ try:
123
+ # Getting primary project might fail if CODESYS instance is unstable
124
+ primary_project = script_engine.projects.primary
125
+ except Exception as primary_err:
126
+ print("WARN: Error getting primary project: %s. Assuming none." % primary_err)
127
+ # traceback.print_exc() # Optional: Print stack trace for this error
128
+ primary_project = None
129
+
130
+ current_project_path = ""
131
+ project_ok = False # Flag to check if target is confirmed primary and accessible
132
+
133
+ if primary_project:
134
+ try:
135
+ # Getting path should be relatively safe if primary_project object exists
136
+ current_project_path = os.path.normcase(os.path.abspath(primary_project.path))
137
+ print("DEBUG: Current primary project path: %s" % current_project_path)
138
+ if current_project_path == normalized_target_path:
139
+ # Found the right project as primary, now check if it's usable
140
+ print("DEBUG: Target project path matches primary. Checking access...")
141
+ try:
142
+ # Try a relatively safe operation to confirm object usability
143
+ # Getting children count is a reasonable check
144
+ _ = len(primary_project.get_children(False))
145
+ print("DEBUG: Target project '%s' is primary and accessible." % target_project_path)
146
+ project_ok = True
147
+ return primary_project # SUCCESS CASE 1: Already open and accessible
148
+ except Exception as access_err:
149
+ # Project found, but accessing it failed. Might be unstable.
150
+ print("WARN: Primary project access check failed for '%s': %s. Will attempt reopen." % (current_project_path, access_err))
151
+ # traceback.print_exc() # Optional: Print stack trace
152
+ primary_project = None # Force reopen by falling through
153
+ else:
154
+ # A *different* project is primary
155
+ print("DEBUG: Primary project is '%s', not the target '%s'." % (current_project_path, normalized_target_path))
156
+ # Consider closing the wrong project if causing issues, but for now, just open target
157
+ # try:
158
+ # print("DEBUG: Closing incorrect primary project '%s'..." % current_project_path)
159
+ # primary_project.close() # Be careful with unsaved changes
160
+ # except Exception as close_err:
161
+ # print("WARN: Failed to close incorrect primary project: %s" % close_err)
162
+ primary_project = None # Force open target project
163
+
164
+ except Exception as path_err:
165
+ # Failed even to get the path of the supposed primary project
166
+ print("WARN: Could not get path of current primary project: %s. Assuming not the target." % path_err)
167
+ # traceback.print_exc() # Optional: Print stack trace
168
+ primary_project = None # Force open target project
169
+
170
+ # If target project not confirmed as primary and accessible, attempt to open/reopen
171
+ if not project_ok:
172
+ # Log clearly whether we are opening initially or reopening
173
+ if primary_project is None and current_project_path == "":
174
+ print("DEBUG: No primary project detected. Attempting to open target: %s" % target_project_path)
175
+ elif primary_project is None and current_project_path != "":
176
+ print("DEBUG: Primary project was '%s' but failed access check or needed close. Attempting to open target: %s" % (current_project_path, target_project_path))
177
+ else: # Includes cases where wrong project was open
178
+ print("DEBUG: Target project not primary or initial check failed. Attempting to open/reopen: %s" % target_project_path)
179
+
180
+ try:
181
+ # Set flags for silent opening, handle potential attribute errors
182
+ update_mode = script_engine.VersionUpdateFlags.NoUpdates | script_engine.VersionUpdateFlags.SilentMode
183
+ # try:
184
+ # update_mode = script_engine.VersionUpdateFlags.NoUpdates | script_engine.VersionUpdateFlags.SilentMode
185
+ # except AttributeError:
186
+ # print("WARN: VersionUpdateFlags not found, using integer flags for open (1 | 2 = 3).")
187
+ # update_mode = 3 # 1=NoUpdates, 2=SilentMode
188
+
189
+ opened_project = None
190
+ try:
191
+ # The actual open call
192
+ print("DEBUG: Calling script_engine.projects.open('%s', update_flags=%s)..." % (target_project_path, update_mode))
193
+ opened_project = script_engine.projects.open(target_project_path, update_flags=update_mode)
194
+
195
+ if not opened_project:
196
+ # This is a critical failure if open returns None without exception
197
+ print("ERROR: projects.open returned None for %s on attempt %d" % (target_project_path, attempt + 1))
198
+ # Allow retry loop to continue
199
+ else:
200
+ # Open call returned *something*, let's verify
201
+ print("DEBUG: projects.open call returned an object for: %s" % target_project_path)
202
+ print("DEBUG: Pausing for stabilization after open...")
203
+ time.sleep(RETRY_DELAY) # Give CODESYS time
204
+ # Re-verify: Is the project now primary and accessible?
205
+ recheck_primary = None
206
+ try: recheck_primary = script_engine.projects.primary
207
+ except Exception as recheck_primary_err: print("WARN: Error getting primary project after reopen: %s" % recheck_primary_err)
208
+
209
+ if recheck_primary:
210
+ recheck_path = ""
211
+ try: # Getting path might fail
212
+ recheck_path = os.path.normcase(os.path.abspath(recheck_primary.path))
213
+ except Exception as recheck_path_err:
214
+ print("WARN: Failed to get path after reopen: %s" % recheck_path_err)
215
+
216
+ if recheck_path == normalized_target_path:
217
+ print("DEBUG: Target project confirmed as primary after reopening.")
218
+ try: # Final sanity check
219
+ _ = len(recheck_primary.get_children(False))
220
+ print("DEBUG: Reopened project basic access confirmed.")
221
+ return recheck_primary # SUCCESS CASE 2: Successfully opened/reopened
222
+ except Exception as access_err_reopen:
223
+ print("WARN: Reopened project (%s) basic access check failed: %s." % (normalized_target_path, access_err_reopen))
224
+ # traceback.print_exc() # Optional
225
+ # Allow retry loop to continue
226
+ else:
227
+ print("WARN: Different project is primary after reopening! Expected '%s', got '%s'." % (normalized_target_path, recheck_path))
228
+ # Allow retry loop to continue, maybe it fixes itself
229
+ else:
230
+ print("WARN: No primary project found after reopening attempt %d!" % (attempt+1))
231
+ # Allow retry loop to continue
232
+
233
+ except Exception as open_err:
234
+ # Catch errors during the open call itself
235
+ print("ERROR: Exception during projects.open call on attempt %d: %s" % (attempt + 1, open_err))
236
+ traceback.print_exc() # Crucial for diagnosing open failures
237
+ # Allow retry loop to continue
238
+
239
+ except Exception as outer_open_err:
240
+ # Catch errors in the flag setup etc.
241
+ print("ERROR: Unexpected error during open setup/logic attempt %d: %s" % (attempt + 1, outer_open_err))
242
+ traceback.print_exc()
243
+
244
+ # If we didn't return successfully in this attempt, wait before retrying
245
+ if attempt < MAX_RETRIES - 1:
246
+ print("DEBUG: Ensure project attempt %d did not succeed. Waiting %f seconds..." % (attempt + 1, RETRY_DELAY))
247
+ time.sleep(RETRY_DELAY)
248
+ else: # Last attempt failed
249
+ print("ERROR: Failed all ensure_project_open attempts for %s." % normalized_target_path)
250
+
251
+
252
+ # If all retries fail after the loop
253
+ raise RuntimeError("Failed to ensure project '%s' is open and accessible after %d attempts." % (target_project_path, MAX_RETRIES))
254
+ # --- End of function ---
255
+
256
+ # Placeholder for the project file path (must be set in scripts using this snippet)
257
+ PROJECT_FILE_PATH = r"{PROJECT_FILE_PATH}"
258
+ `;
259
+ // (CHECK_STATUS_SCRIPT remains the same)
260
+ const CHECK_STATUS_SCRIPT = `
261
+ import sys, scriptengine as script_engine, os, traceback
262
+ project_open = False; project_name = "No project open"; project_path = "N/A"; scripting_ok = False
263
+ try:
264
+ scripting_ok = True; primary_project = script_engine.projects.primary
265
+ if primary_project:
266
+ project_open = True
267
+ try:
268
+ project_path = os.path.normcase(os.path.abspath(primary_project.path))
269
+ try:
270
+ project_name = primary_project.get_name() # Might fail
271
+ if not project_name: project_name = "Unnamed (path: %s)" % os.path.basename(project_path)
272
+ except: project_name = "Unnamed (path: %s)" % os.path.basename(project_path)
273
+ except Exception as e_path: project_path = "N/A (Error: %s)" % e_path; project_name = "Unnamed (Path Error)"
274
+ print("Project Open: %s" % project_open); print("Project Name: %s" % project_name)
275
+ print("Project Path: %s" % project_path); print("Scripting OK: %s" % scripting_ok)
276
+ print("SCRIPT_SUCCESS: Status check complete."); sys.exit(0)
277
+ except Exception as e:
278
+ error_message = "Error during status check: %s" % e
279
+ print(error_message); print("Scripting OK: False")
280
+ # traceback.print_exc() # Optional traceback
281
+ print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
282
+ `;
283
+ // (OPEN_PROJECT_SCRIPT_TEMPLATE remains the same)
284
+ const OPEN_PROJECT_SCRIPT_TEMPLATE = `
285
+ import sys, scriptengine as script_engine, os, traceback
286
+ ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
287
+ try:
288
+ project = ensure_project_open(PROJECT_FILE_PATH)
289
+ # Get name from object if possible, otherwise use path basename
290
+ proj_name = "Unknown"
291
+ try:
292
+ if project: proj_name = project.get_name() or os.path.basename(PROJECT_FILE_PATH)
293
+ else: proj_name = os.path.basename(PROJECT_FILE_PATH) + " (ensure_project_open returned None?)"
294
+ except Exception:
295
+ proj_name = os.path.basename(PROJECT_FILE_PATH) + " (name retrieval failed)"
296
+ print("Project Opened: %s" % proj_name)
297
+ print("SCRIPT_SUCCESS: Project opened successfully.")
298
+ sys.exit(0)
299
+ except Exception as e:
300
+ error_message = "Error opening project %s: %s" % (PROJECT_FILE_PATH, e)
301
+ print(error_message)
302
+ traceback.print_exc()
303
+ print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
304
+ `;
305
+ // (CREATE_PROJECT_SCRIPT_TEMPLATE remains the same)
306
+ const CREATE_PROJECT_SCRIPT_TEMPLATE = `
307
+ import sys, scriptengine as script_engine, os, shutil, time, traceback
308
+ # Placeholders
309
+ TEMPLATE_PROJECT_PATH = r'{TEMPLATE_PROJECT_PATH}' # Path to Standard.project
310
+ PROJECT_FILE_PATH = r'{PROJECT_FILE_PATH}' # Path for the new project (Target Path)
311
+ try:
312
+ print("DEBUG: Python script create_project (copy from template):")
313
+ print("DEBUG: Template Source = %s" % TEMPLATE_PROJECT_PATH)
314
+ print("DEBUG: Target Path = %s" % PROJECT_FILE_PATH)
315
+ if not PROJECT_FILE_PATH: raise ValueError("Target project file path empty.")
316
+ if not TEMPLATE_PROJECT_PATH: raise ValueError("Template project file path empty.")
317
+ if not os.path.exists(TEMPLATE_PROJECT_PATH): raise IOError("Template project file not found: %s" % TEMPLATE_PROJECT_PATH)
318
+
319
+ # 1. Copy the template project file to the new location
320
+ target_dir = os.path.dirname(PROJECT_FILE_PATH)
321
+ if not os.path.exists(target_dir): print("DEBUG: Creating target directory: %s" % target_dir); os.makedirs(target_dir)
322
+ # Check if target file already exists
323
+ if os.path.exists(PROJECT_FILE_PATH): print("WARN: Target project file already exists, overwriting: %s" % PROJECT_FILE_PATH)
324
+
325
+ print("DEBUG: Copying '%s' to '%s'..." % (TEMPLATE_PROJECT_PATH, PROJECT_FILE_PATH))
326
+ shutil.copy2(TEMPLATE_PROJECT_PATH, PROJECT_FILE_PATH) # copy2 preserves metadata
327
+ print("DEBUG: File copy complete.")
328
+
329
+ # 2. Open the newly copied project file
330
+ print("DEBUG: Opening the copied project: %s" % PROJECT_FILE_PATH)
331
+ # Set flags for silent opening
332
+ update_mode = script_engine.VersionUpdateFlags.NoUpdates | script_engine.VersionUpdateFlags.SilentMode
333
+ # try:
334
+ # update_mode = script_engine.VersionUpdateFlags.NoUpdates | script_engine.VersionUpdateFlags.SilentMode
335
+ # except AttributeError:
336
+ # print("WARN: VersionUpdateFlags not found, using integer flags for open (1 | 2 = 3).")
337
+ # update_mode = 3
338
+
339
+ project = script_engine.projects.open(PROJECT_FILE_PATH, update_flags=update_mode)
340
+ print("DEBUG: script_engine.projects.open returned: %s" % project)
341
+ if project:
342
+ print("DEBUG: Pausing briefly after open...")
343
+ time.sleep(1.0) # Allow CODESYS to potentially initialize things
344
+ try:
345
+ print("DEBUG: Explicitly saving project after opening copy...")
346
+ project.save();
347
+ print("DEBUG: Project save after opening copy succeeded.")
348
+ except Exception as save_err:
349
+ print("WARN: Explicit save after opening copy failed: %s" % save_err)
350
+ # Decide if this is critical - maybe not, but good to know.
351
+ print("Project Created from Template Copy at: %s" % PROJECT_FILE_PATH)
352
+ print("SCRIPT_SUCCESS: Project copied from template and opened successfully.")
353
+ sys.exit(0)
354
+ else:
355
+ error_message = "Failed to open project copy %s after copying template %s. projects.open returned None." % (PROJECT_FILE_PATH, TEMPLATE_PROJECT_PATH)
356
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
357
+ except Exception as e:
358
+ detailed_error = traceback.format_exc()
359
+ error_message = "Error creating project '%s' from template '%s': %s\\n%s" % (PROJECT_FILE_PATH, TEMPLATE_PROJECT_PATH, e, detailed_error)
360
+ print(error_message); print("SCRIPT_ERROR: Error copying/opening template: %s" % e); sys.exit(1)
361
+ `;
362
+ // (SAVE_PROJECT_SCRIPT_TEMPLATE remains the same)
363
+ const SAVE_PROJECT_SCRIPT_TEMPLATE = `
364
+ import sys, scriptengine as script_engine, os, traceback
365
+ ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
366
+ try:
367
+ primary_project = ensure_project_open(PROJECT_FILE_PATH)
368
+ # Get name from object if possible, otherwise use path basename
369
+ project_name = "Unknown"
370
+ try:
371
+ if primary_project: project_name = primary_project.get_name() or os.path.basename(PROJECT_FILE_PATH)
372
+ else: project_name = os.path.basename(PROJECT_FILE_PATH) + " (ensure_project_open returned None?)"
373
+ except Exception:
374
+ project_name = os.path.basename(PROJECT_FILE_PATH) + " (name retrieval failed)"
375
+
376
+ print("DEBUG: Saving project: %s (%s)" % (project_name, PROJECT_FILE_PATH))
377
+ primary_project.save()
378
+ print("DEBUG: project.save() executed.")
379
+ print("Project Saved: %s" % project_name)
380
+ print("SCRIPT_SUCCESS: Project saved successfully.")
381
+ sys.exit(0)
382
+ except Exception as e:
383
+ error_message = "Error saving project %s: %s" % (PROJECT_FILE_PATH, e)
384
+ print(error_message)
385
+ traceback.print_exc()
386
+ print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
387
+ `;
388
+ const PouTypeEnum = zod_1.z.enum(["Program", "FunctionBlock", "Function"]);
389
+ const ImplementationLanguageEnum = zod_1.z.enum(["ST", "LD", "FBD", "SFC", "IL", "CFC", "StructuredText", "LadderDiagram", "FunctionBlockDiagram", "SequentialFunctionChart", "InstructionList", "ContinuousFunctionChart"]);
390
+ // --- Path finding function (used by multiple templates) ---
391
+ const FIND_OBJECT_BY_PATH_PYTHON_SNIPPET = `
392
+ import traceback
393
+ # --- Find object by path function ---
394
+ def find_object_by_path_robust(start_node, full_path, target_type_name="object"):
395
+ print("DEBUG: Finding %s by path: '%s'" % (target_type_name, full_path))
396
+ normalized_path = full_path.replace('\\\\', '/').strip('/')
397
+ path_parts = normalized_path.split('/')
398
+ if not path_parts:
399
+ print("ERROR: Path is empty.")
400
+ return None
401
+
402
+ # Determine the actual starting node (project or application)
403
+ project = start_node # Assume start_node is project initially
404
+ if not hasattr(start_node, 'active_application') and hasattr(start_node, 'project'):
405
+ # If start_node is not project but has project ref (e.g., an application), get the project
406
+ try: project = start_node.project
407
+ except Exception as proj_ref_err:
408
+ print("WARN: Could not get project reference from start_node: %s" % proj_ref_err)
409
+ # Proceed assuming start_node might be the project anyway or search fails
410
+
411
+ # Try to get the application object robustly if we think we have the project
412
+ app = None
413
+ if hasattr(project, 'active_application'):
414
+ try: app = project.active_application
415
+ except Exception: pass # Ignore errors getting active app
416
+ if not app:
417
+ try:
418
+ apps = project.find("Application", True) # Search recursively
419
+ if apps: app = apps[0]
420
+ except Exception: pass
421
+
422
+ # Check if the first path part matches the application name
423
+ app_name_lower = ""
424
+ if app:
425
+ try: app_name_lower = (app.get_name() or "application").lower()
426
+ except Exception: app_name_lower = "application" # Fallback
427
+
428
+ # Decide where to start the traversal
429
+ current_obj = start_node # Default to the node passed in
430
+ if hasattr(project, 'active_application'): # Only adjust if start_node was likely the project
431
+ if app and path_parts[0].lower() == app_name_lower:
432
+ print("DEBUG: Path starts with Application name '%s'. Beginning search there." % path_parts[0])
433
+ current_obj = app
434
+ path_parts = path_parts[1:] # Consume the app name part
435
+ # If path was *only* the application name
436
+ if not path_parts:
437
+ print("DEBUG: Target path is the Application object itself.")
438
+ return current_obj
439
+ else:
440
+ print("DEBUG: Path does not start with Application name. Starting search from project root.")
441
+ current_obj = project # Start search from the project root
442
+ else:
443
+ print("DEBUG: Starting search from originally provided node.")
444
+
445
+
446
+ # Traverse the remaining path parts
447
+ parent_path_str = getattr(current_obj, 'get_name', lambda: str(current_obj))() # Safer name getting
448
+
449
+ for i, part_name in enumerate(path_parts):
450
+ is_last_part = (i == len(path_parts) - 1)
451
+ print("DEBUG: Searching for part [%d/%d]: '%s' under '%s'" % (i+1, len(path_parts), part_name, parent_path_str))
452
+ found_in_parent = None
453
+ try:
454
+ # Prioritize non-recursive find for direct children
455
+ children_of_current = current_obj.get_children(False)
456
+ print("DEBUG: Found %d direct children under '%s'." % (len(children_of_current), parent_path_str))
457
+ for child in children_of_current:
458
+ child_name = getattr(child, 'get_name', lambda: None)() # Safer name getting
459
+ # print("DEBUG: Checking child: '%s'" % child_name) # Verbose
460
+ if child_name == part_name:
461
+ found_in_parent = child
462
+ print("DEBUG: Found direct child matching '%s'." % part_name)
463
+ break # Found direct child, stop searching children
464
+
465
+ # If not found directly, AND it's the last part, try recursive find from current parent
466
+ if not found_in_parent and is_last_part:
467
+ print("DEBUG: Direct find failed for last part '%s'. Trying recursive find under '%s'." % (part_name, parent_path_str))
468
+ found_recursive_list = current_obj.find(part_name, True) # Recursive find
469
+ if found_recursive_list:
470
+ # Maybe add a check here if multiple are found?
471
+ found_in_parent = found_recursive_list[0] # Take the first match
472
+ print("DEBUG: Found last part '%s' recursively." % part_name)
473
+ else:
474
+ print("DEBUG: Recursive find also failed for last part '%s'." % part_name)
475
+
476
+ # Update current object if found
477
+ if found_in_parent:
478
+ current_obj = found_in_parent
479
+ parent_path_str = getattr(current_obj, 'get_name', lambda: part_name)() # Safer name getting
480
+ print("DEBUG: Stepped into '%s'." % parent_path_str)
481
+ else:
482
+ # If not found at any point, the path is invalid from this parent
483
+ print("ERROR: Path part '%s' not found under '%s'." % (part_name, parent_path_str))
484
+ return None # Path broken
485
+
486
+ except Exception as find_err:
487
+ print("ERROR: Exception while searching for '%s' under '%s': %s" % (part_name, parent_path_str, find_err))
488
+ traceback.print_exc()
489
+ return None # Error during search
490
+
491
+ # Final verification (optional but recommended): Check if the found object's name matches the last part
492
+ final_expected_name = full_path.split('/')[-1]
493
+ found_final_name = getattr(current_obj, 'get_name', lambda: None)() # Safer name getting
494
+
495
+ if found_final_name == final_expected_name:
496
+ print("DEBUG: Final %s found and name verified for path '%s': %s" % (target_type_name, full_path, found_final_name))
497
+ return current_obj
498
+ else:
499
+ print("ERROR: Traversal ended on object '%s' but expected final name was '%s'." % (found_final_name, final_expected_name))
500
+ return None # Name mismatch implies target not found as expected
501
+
502
+ # --- End of find object function ---
503
+ `;
504
+ // (CREATE_POU_SCRIPT_TEMPLATE uses FIND_OBJECT_BY_PATH_PYTHON_SNIPPET)
505
+ const CREATE_POU_SCRIPT_TEMPLATE = `
506
+ import sys, scriptengine as script_engine, os, traceback
507
+ ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
508
+ ${FIND_OBJECT_BY_PATH_PYTHON_SNIPPET}
509
+ POU_NAME = "{POU_NAME}"; POU_TYPE_STR = "{POU_TYPE_STR}"; IMPL_LANGUAGE_STR = "{IMPL_LANGUAGE_STR}"; PARENT_PATH_REL = "{PARENT_PATH}"
510
+ pou_type_map = { "Program": script_engine.PouType.Program, "FunctionBlock": script_engine.PouType.FunctionBlock, "Function": script_engine.PouType.Function }
511
+ # Map common language names to ImplementationLanguages attributes if needed (optional, None usually works)
512
+ # lang_map = { "ST": script_engine.ImplementationLanguage.st, ... }
513
+
514
+ try:
515
+ print("DEBUG: create_pou script: Name='%s', Type='%s', Lang='%s', ParentPath='%s', Project='%s'" % (POU_NAME, POU_TYPE_STR, IMPL_LANGUAGE_STR, PARENT_PATH_REL, PROJECT_FILE_PATH))
516
+ primary_project = ensure_project_open(PROJECT_FILE_PATH)
517
+ if not POU_NAME: raise ValueError("POU name empty.")
518
+ if not PARENT_PATH_REL: raise ValueError("Parent path empty.")
519
+
520
+ # Resolve POU Type Enum
521
+ pou_type_enum = pou_type_map.get(POU_TYPE_STR)
522
+ if not pou_type_enum: raise ValueError("Invalid POU type string: %s. Use Program, FunctionBlock, or Function." % POU_TYPE_STR)
523
+
524
+ # Find parent object using the robust function
525
+ parent_object = find_object_by_path_robust(primary_project, PARENT_PATH_REL, "parent container")
526
+ if not parent_object: raise ValueError("Parent object not found for path: %s" % PARENT_PATH_REL)
527
+
528
+ parent_name = getattr(parent_object, 'get_name', lambda: str(parent_object))()
529
+ print("DEBUG: Using parent object: %s (Type: %s)" % (parent_name, type(parent_object).__name__))
530
+
531
+ # Check if parent object supports creating POUs (should implement ScriptIecLanguageObjectContainer)
532
+ if not hasattr(parent_object, 'create_pou'):
533
+ raise TypeError("Parent object '%s' of type %s does not support create_pou." % (parent_name, type(parent_object).__name__))
534
+
535
+ # Set language GUID to None (let CODESYS default based on parent/settings)
536
+ lang_guid = None
537
+ print("DEBUG: Setting language to None (will use default).")
538
+ # Example if mapping language string: lang_guid = lang_map.get(IMPL_LANGUAGE_STR, None)
539
+
540
+ print("DEBUG: Calling parent_object.create_pou: Name='%s', Type=%s, Lang=%s" % (POU_NAME, pou_type_enum, lang_guid))
541
+
542
+ # Call create_pou using keyword arguments
543
+ new_pou = parent_object.create_pou(
544
+ name=POU_NAME,
545
+ type=pou_type_enum,
546
+ language=lang_guid # Pass None
547
+ )
548
+
549
+ print("DEBUG: parent_object.create_pou returned: %s" % new_pou)
550
+ if new_pou:
551
+ new_pou_name = getattr(new_pou, 'get_name', lambda: POU_NAME)()
552
+ print("DEBUG: POU object created: %s" % new_pou_name)
553
+
554
+ # --- SAVE THE PROJECT TO PERSIST THE NEW POU ---
555
+ try:
556
+ print("DEBUG: Saving Project...")
557
+ primary_project.save() # Save the overall project file
558
+ print("DEBUG: Project saved successfully after POU creation.")
559
+ except Exception as save_err:
560
+ print("ERROR: Failed to save Project after POU creation: %s" % save_err)
561
+ detailed_error = traceback.format_exc()
562
+ error_message = "Error saving Project after creating POU '%s': %s\\n%s" % (new_pou_name, save_err, detailed_error)
563
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
564
+ # --- END SAVING ---
565
+
566
+ print("POU Created: %s" % new_pou_name); print("Type: %s" % POU_TYPE_STR); print("Language: %s (Defaulted)" % IMPL_LANGUAGE_STR); print("Parent Path: %s" % PARENT_PATH_REL)
567
+ print("SCRIPT_SUCCESS: POU created successfully."); sys.exit(0)
568
+ else:
569
+ error_message = "Failed to create POU '%s'. create_pou returned None." % POU_NAME; print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
570
+ except Exception as e:
571
+ detailed_error = traceback.format_exc()
572
+ error_message = "Error creating POU '%s' in project '%s': %s\\n%s" % (POU_NAME, PROJECT_FILE_PATH, e, detailed_error)
573
+ print(error_message); print("SCRIPT_ERROR: Error creating POU '%s': %s" % (POU_NAME, e)); sys.exit(1)
574
+ `;
575
+ // (SET_POU_CODE_SCRIPT_TEMPLATE uses FIND_OBJECT_BY_PATH_PYTHON_SNIPPET)
576
+ const SET_POU_CODE_SCRIPT_TEMPLATE = `
577
+ import sys, scriptengine as script_engine, os, traceback
578
+ ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
579
+ ${FIND_OBJECT_BY_PATH_PYTHON_SNIPPET}
580
+ POU_FULL_PATH = "{POU_FULL_PATH}" # Expecting format like "Application/MyPOU" or "Folder/SubFolder/MyPOU"
581
+ DECLARATION_CONTENT = """{DECLARATION_CONTENT}"""
582
+ IMPLEMENTATION_CONTENT = """{IMPLEMENTATION_CONTENT}"""
583
+
584
+ try:
585
+ print("DEBUG: set_pou_code script: POU_FULL_PATH='%s', Project='%s'" % (POU_FULL_PATH, PROJECT_FILE_PATH))
586
+ primary_project = ensure_project_open(PROJECT_FILE_PATH)
587
+ if not POU_FULL_PATH: raise ValueError("POU full path empty.")
588
+
589
+ # Find the target POU/Method/Property object
590
+ target_object = find_object_by_path_robust(primary_project, POU_FULL_PATH, "target object")
591
+ if not target_object: raise ValueError("Target object not found using path: %s" % POU_FULL_PATH)
592
+
593
+ target_name = getattr(target_object, 'get_name', lambda: POU_FULL_PATH)()
594
+ print("DEBUG: Found target object: %s" % target_name)
595
+
596
+ # --- Set Declaration Part ---
597
+ declaration_updated = False
598
+ # Check if the content is actually provided (might be None/empty if only impl is set)
599
+ has_declaration_content = 'DECLARATION_CONTENT' in locals() or 'DECLARATION_CONTENT' in globals()
600
+ if has_declaration_content and DECLARATION_CONTENT is not None: # Check not None
601
+ if hasattr(target_object, 'textual_declaration'):
602
+ decl_obj = target_object.textual_declaration
603
+ if decl_obj and hasattr(decl_obj, 'replace'):
604
+ try:
605
+ print("DEBUG: Accessing textual_declaration...")
606
+ decl_obj.replace(DECLARATION_CONTENT)
607
+ print("DEBUG: Set declaration text using replace().")
608
+ declaration_updated = True
609
+ except Exception as decl_err:
610
+ print("ERROR: Failed to set declaration text: %s" % decl_err)
611
+ traceback.print_exc() # Print stack trace for detailed error
612
+ else:
613
+ print("WARN: Target '%s' textual_declaration attribute is None or does not have replace(). Skipping declaration update." % target_name)
614
+ else:
615
+ print("WARN: Target '%s' does not have textual_declaration attribute. Skipping declaration update." % target_name)
616
+ else:
617
+ print("DEBUG: Declaration content not provided or is None. Skipping declaration update.")
618
+
619
+
620
+ # --- Set Implementation Part ---
621
+ implementation_updated = False
622
+ has_implementation_content = 'IMPLEMENTATION_CONTENT' in locals() or 'IMPLEMENTATION_CONTENT' in globals()
623
+ if has_implementation_content and IMPLEMENTATION_CONTENT is not None: # Check not None
624
+ if hasattr(target_object, 'textual_implementation'):
625
+ impl_obj = target_object.textual_implementation
626
+ if impl_obj and hasattr(impl_obj, 'replace'):
627
+ try:
628
+ print("DEBUG: Accessing textual_implementation...")
629
+ impl_obj.replace(IMPLEMENTATION_CONTENT)
630
+ print("DEBUG: Set implementation text using replace().")
631
+ implementation_updated = True
632
+ except Exception as impl_err:
633
+ print("ERROR: Failed to set implementation text: %s" % impl_err)
634
+ traceback.print_exc() # Print stack trace for detailed error
635
+ else:
636
+ print("WARN: Target '%s' textual_implementation attribute is None or does not have replace(). Skipping implementation update." % target_name)
637
+ else:
638
+ print("WARN: Target '%s' does not have textual_implementation attribute. Skipping implementation update." % target_name)
639
+ else:
640
+ print("DEBUG: Implementation content not provided or is None. Skipping implementation update.")
641
+
642
+
643
+ # --- SAVE THE PROJECT TO PERSIST THE CODE CHANGE ---
644
+ # Only save if something was actually updated to avoid unnecessary saves
645
+ if declaration_updated or implementation_updated:
646
+ try:
647
+ print("DEBUG: Saving Project (after code change)...")
648
+ primary_project.save() # Save the overall project file
649
+ print("DEBUG: Project saved successfully after code change.")
650
+ except Exception as save_err:
651
+ print("ERROR: Failed to save Project after setting code: %s" % save_err)
652
+ detailed_error = traceback.format_exc()
653
+ error_message = "Error saving Project after code change for '%s': %s\\n%s" % (target_name, save_err, detailed_error)
654
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
655
+ else:
656
+ print("DEBUG: No code parts were updated, skipping project save.")
657
+ # --- END SAVING ---
658
+
659
+ print("Code Set For: %s" % target_name)
660
+ print("Path: %s" % POU_FULL_PATH)
661
+ print("SCRIPT_SUCCESS: Declaration and/or implementation set successfully."); sys.exit(0)
662
+
663
+ except Exception as e:
664
+ detailed_error = traceback.format_exc()
665
+ error_message = "Error setting code for object '%s' in project '%s': %s\\n%s" % (POU_FULL_PATH, PROJECT_FILE_PATH, e, detailed_error)
666
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
667
+ `;
668
+ // --- CREATE_PROPERTY_SCRIPT_TEMPLATE uses FIND_OBJECT_BY_PATH_PYTHON_SNIPPET ---
669
+ const CREATE_PROPERTY_SCRIPT_TEMPLATE = `
670
+ import sys, scriptengine as script_engine, os, traceback
671
+ ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
672
+ ${FIND_OBJECT_BY_PATH_PYTHON_SNIPPET}
673
+ PARENT_POU_FULL_PATH = "{PARENT_POU_FULL_PATH}" # e.g., "Application/MyFB"
674
+ PROPERTY_NAME = "{PROPERTY_NAME}"
675
+ PROPERTY_TYPE = "{PROPERTY_TYPE}"
676
+ # Optional: Language for Getter/Setter (usually defaults to ST)
677
+ # LANG_GUID_STR = "{LANG_GUID_STR}" # Example if needed
678
+
679
+ try:
680
+ print("DEBUG: create_property script: ParentPOU='%s', Name='%s', Type='%s', Project='%s'" % (PARENT_POU_FULL_PATH, PROPERTY_NAME, PROPERTY_TYPE, PROJECT_FILE_PATH))
681
+ primary_project = ensure_project_open(PROJECT_FILE_PATH)
682
+ if not PARENT_POU_FULL_PATH: raise ValueError("Parent POU full path empty.")
683
+ if not PROPERTY_NAME: raise ValueError("Property name empty.")
684
+ if not PROPERTY_TYPE: raise ValueError("Property type empty.")
685
+
686
+ # Find the parent POU object
687
+ parent_pou_object = find_object_by_path_robust(primary_project, PARENT_POU_FULL_PATH, "parent POU")
688
+ if not parent_pou_object: raise ValueError("Parent POU object not found: %s" % PARENT_POU_FULL_PATH)
689
+
690
+ parent_pou_name = getattr(parent_pou_object, 'get_name', lambda: PARENT_POU_FULL_PATH)()
691
+ print("DEBUG: Found Parent POU object: %s" % parent_pou_name)
692
+
693
+ # Check if parent object supports creating properties (should implement ScriptIecLanguageMemberContainer)
694
+ if not hasattr(parent_pou_object, 'create_property'):
695
+ raise TypeError("Parent object '%s' of type %s does not support create_property." % (parent_pou_name, type(parent_pou_object).__name__))
696
+
697
+ # Default language to None (usually ST)
698
+ lang_guid = None
699
+ print("DEBUG: Calling create_property: Name='%s', Type='%s', Lang=%s" % (PROPERTY_NAME, PROPERTY_TYPE, lang_guid))
700
+
701
+ # Call the create_property method ON THE PARENT POU
702
+ new_property_object = parent_pou_object.create_property(
703
+ name=PROPERTY_NAME,
704
+ return_type=PROPERTY_TYPE,
705
+ language=lang_guid # Pass None to use default
706
+ )
707
+
708
+ if new_property_object:
709
+ new_prop_name = getattr(new_property_object, 'get_name', lambda: PROPERTY_NAME)()
710
+ print("DEBUG: Property object created: %s" % new_prop_name)
711
+
712
+ # --- SAVE THE PROJECT TO PERSIST THE NEW PROPERTY OBJECT ---
713
+ try:
714
+ print("DEBUG: Saving Project (after property creation)...")
715
+ primary_project.save()
716
+ print("DEBUG: Project saved successfully after property creation.")
717
+ except Exception as save_err:
718
+ print("ERROR: Failed to save Project after creating property: %s" % save_err)
719
+ detailed_error = traceback.format_exc()
720
+ error_message = "Error saving Project after creating property '%s': %s\\n%s" % (PROPERTY_NAME, save_err, detailed_error)
721
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
722
+ # --- END SAVING ---
723
+
724
+ print("Property Created: %s" % new_prop_name)
725
+ print("Parent POU: %s" % PARENT_POU_FULL_PATH)
726
+ print("Type: %s" % PROPERTY_TYPE)
727
+ print("SCRIPT_SUCCESS: Property created successfully."); sys.exit(0)
728
+ else:
729
+ error_message = "Failed to create property '%s' under '%s'. create_property returned None." % (PROPERTY_NAME, parent_pou_name)
730
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
731
+
732
+ except Exception as e:
733
+ detailed_error = traceback.format_exc()
734
+ error_message = "Error creating property '%s' under POU '%s' in project '%s': %s\\n%s" % (PROPERTY_NAME, PARENT_POU_FULL_PATH, PROJECT_FILE_PATH, e, detailed_error)
735
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
736
+ `;
737
+ // --- CREATE_METHOD_SCRIPT_TEMPLATE uses FIND_OBJECT_BY_PATH_PYTHON_SNIPPET ---
738
+ const CREATE_METHOD_SCRIPT_TEMPLATE = `
739
+ import sys, scriptengine as script_engine, os, traceback
740
+ ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
741
+ ${FIND_OBJECT_BY_PATH_PYTHON_SNIPPET}
742
+ PARENT_POU_FULL_PATH = "{PARENT_POU_FULL_PATH}" # e.g., "Application/MyFB"
743
+ METHOD_NAME = "{METHOD_NAME}"
744
+ RETURN_TYPE = "{RETURN_TYPE}" # Can be empty string for no return type
745
+ # Optional: Language
746
+ # LANG_GUID_STR = "{LANG_GUID_STR}" # Example if needed
747
+
748
+ try:
749
+ print("DEBUG: create_method script: ParentPOU='%s', Name='%s', ReturnType='%s', Project='%s'" % (PARENT_POU_FULL_PATH, METHOD_NAME, RETURN_TYPE, PROJECT_FILE_PATH))
750
+ primary_project = ensure_project_open(PROJECT_FILE_PATH)
751
+ if not PARENT_POU_FULL_PATH: raise ValueError("Parent POU full path empty.")
752
+ if not METHOD_NAME: raise ValueError("Method name empty.")
753
+ # RETURN_TYPE can be empty
754
+
755
+ # Find the parent POU object
756
+ parent_pou_object = find_object_by_path_robust(primary_project, PARENT_POU_FULL_PATH, "parent POU")
757
+ if not parent_pou_object: raise ValueError("Parent POU object not found: %s" % PARENT_POU_FULL_PATH)
758
+
759
+ parent_pou_name = getattr(parent_pou_object, 'get_name', lambda: PARENT_POU_FULL_PATH)()
760
+ print("DEBUG: Found Parent POU object: %s" % parent_pou_name)
761
+
762
+ # Check if parent object supports creating methods (should implement ScriptIecLanguageMemberContainer)
763
+ if not hasattr(parent_pou_object, 'create_method'):
764
+ raise TypeError("Parent object '%s' of type %s does not support create_method." % (parent_pou_name, type(parent_pou_object).__name__))
765
+
766
+ # Default language to None (usually ST)
767
+ lang_guid = None
768
+ # Use None if RETURN_TYPE is empty string, otherwise use the string
769
+ actual_return_type = RETURN_TYPE if RETURN_TYPE else None
770
+ print("DEBUG: Calling create_method: Name='%s', ReturnType=%s, Lang=%s" % (METHOD_NAME, actual_return_type, lang_guid))
771
+
772
+ # Call the create_method method ON THE PARENT POU
773
+ new_method_object = parent_pou_object.create_method(
774
+ name=METHOD_NAME,
775
+ return_type=actual_return_type,
776
+ language=lang_guid # Pass None to use default
777
+ )
778
+
779
+ if new_method_object:
780
+ new_meth_name = getattr(new_method_object, 'get_name', lambda: METHOD_NAME)()
781
+ print("DEBUG: Method object created: %s" % new_meth_name)
782
+
783
+ # --- SAVE THE PROJECT TO PERSIST THE NEW METHOD OBJECT ---
784
+ try:
785
+ print("DEBUG: Saving Project (after method creation)...")
786
+ primary_project.save()
787
+ print("DEBUG: Project saved successfully after method creation.")
788
+ except Exception as save_err:
789
+ print("ERROR: Failed to save Project after creating method: %s" % save_err)
790
+ detailed_error = traceback.format_exc()
791
+ error_message = "Error saving Project after creating method '%s': %s\\n%s" % (METHOD_NAME, save_err, detailed_error)
792
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
793
+ # --- END SAVING ---
794
+
795
+ print("Method Created: %s" % new_meth_name)
796
+ print("Parent POU: %s" % PARENT_POU_FULL_PATH)
797
+ print("Return Type: %s" % (RETURN_TYPE if RETURN_TYPE else "(None)"))
798
+ print("SCRIPT_SUCCESS: Method created successfully."); sys.exit(0)
799
+ else:
800
+ error_message = "Failed to create method '%s' under '%s'. create_method returned None." % (METHOD_NAME, parent_pou_name)
801
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
802
+
803
+ except Exception as e:
804
+ detailed_error = traceback.format_exc()
805
+ error_message = "Error creating method '%s' under POU '%s' in project '%s': %s\\n%s" % (METHOD_NAME, PARENT_POU_FULL_PATH, PROJECT_FILE_PATH, e, detailed_error)
806
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
807
+ `;
808
+ // (COMPILE_PROJECT_SCRIPT_TEMPLATE remains the same)
809
+ const COMPILE_PROJECT_SCRIPT_TEMPLATE = `
810
+ import sys, scriptengine as script_engine, os, traceback
811
+ ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
812
+ try:
813
+ print("DEBUG: compile_project script: Project='%s'" % PROJECT_FILE_PATH)
814
+ primary_project = ensure_project_open(PROJECT_FILE_PATH)
815
+ project_name = os.path.basename(PROJECT_FILE_PATH)
816
+ target_app = None
817
+ app_name = "N/A"
818
+
819
+ # Try getting active application first
820
+ try:
821
+ target_app = primary_project.active_application
822
+ if target_app:
823
+ app_name = getattr(target_app, 'get_name', lambda: "Unnamed App (Active)")()
824
+ print("DEBUG: Found active application: %s" % app_name)
825
+ except Exception as active_err:
826
+ print("WARN: Could not get active application: %s. Searching..." % active_err)
827
+
828
+ # If no active app, search for the first one
829
+ if not target_app:
830
+ print("DEBUG: Searching for first compilable application...")
831
+ apps = []
832
+ try:
833
+ # Search recursively through all project objects
834
+ all_children = primary_project.get_children(True)
835
+ for child in all_children:
836
+ # Check using the marker property and if build method exists
837
+ if hasattr(child, 'is_application') and child.is_application and hasattr(child, 'build'):
838
+ app_name_found = getattr(child, 'get_name', lambda: "Unnamed App")()
839
+ print("DEBUG: Found potential application object: %s" % app_name_found)
840
+ apps.append(child)
841
+ break # Take the first one found
842
+ except Exception as find_err: print("WARN: Error finding application object: %s" % find_err)
843
+
844
+ if not apps: raise RuntimeError("No compilable application found in project '%s'" % project_name)
845
+ target_app = apps[0]
846
+ app_name = getattr(target_app, 'get_name', lambda: "Unnamed App (First Found)")()
847
+ print("WARN: Compiling first found application: %s" % app_name)
848
+
849
+ print("DEBUG: Calling build() on app '%s'..." % app_name)
850
+ if not hasattr(target_app, 'build'):
851
+ raise TypeError("Selected object '%s' is not an application or doesn't support build()." % app_name)
852
+
853
+ # Execute the build
854
+ target_app.build();
855
+ print("DEBUG: Build command executed for application '%s'." % app_name)
856
+
857
+ # Check messages is harder without direct access to message store from script.
858
+ # Rely on CODESYS UI or log output for now.
859
+ print("Compile Initiated For Application: %s" % app_name); print("In Project: %s" % project_name)
860
+ print("SCRIPT_SUCCESS: Application compilation initiated."); sys.exit(0)
861
+ except Exception as e:
862
+ detailed_error = traceback.format_exc()
863
+ error_message = "Error initiating compilation for project %s: %s\\n%s" % (PROJECT_FILE_PATH, e, detailed_error)
864
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
865
+ `;
866
+ // (GET_PROJECT_STRUCTURE_SCRIPT_TEMPLATE remains the same)
867
+ const GET_PROJECT_STRUCTURE_SCRIPT_TEMPLATE = `
868
+ import sys, scriptengine as script_engine, os, traceback
869
+ ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
870
+ # FIND_OBJECT_BY_PATH_PYTHON_SNIPPET is NOT needed here, we start from project root.
871
+
872
+ def get_object_structure(obj, indent=0, max_depth=10): # Add max_depth
873
+ lines = []; indent_str = " " * indent
874
+ if indent > max_depth:
875
+ lines.append("%s- Max recursion depth reached." % indent_str)
876
+ return lines
877
+ try:
878
+ name = "Unnamed"; obj_type = type(obj).__name__
879
+ guid_str = ""
880
+ folder_str = ""
881
+ try:
882
+ name = getattr(obj, 'get_name', lambda: "Unnamed")() or "Unnamed" # Safer get_name
883
+ if hasattr(obj, 'guid'): guid_str = " {%s}" % obj.guid
884
+ if hasattr(obj, 'is_folder') and obj.is_folder: folder_str = " [Folder]"
885
+ except Exception as name_err:
886
+ print("WARN: Error getting name/guid/folder status for an object: %s" % name_err)
887
+ name = "!!! Error Getting Name !!!"
888
+
889
+ lines.append("%s- %s (%s)%s%s" % (indent_str, name, obj_type, folder_str, guid_str))
890
+
891
+ # Get children only if the object potentially has them
892
+ children = []
893
+ can_have_children = hasattr(obj, 'get_children') and (
894
+ not hasattr(obj, 'is_folder') or # If it's not clear if it's a folder (e.g., project root)
895
+ (hasattr(obj, 'is_folder') and obj.is_folder) or # If it is a folder
896
+ # Add known container types explicitly, check marker interfaces too
897
+ hasattr(obj, 'is_project') or hasattr(obj, 'is_application') or hasattr(obj, 'is_device') or hasattr(obj,'is_pou')
898
+ )
899
+
900
+ if can_have_children:
901
+ try:
902
+ children = obj.get_children(False)
903
+ # print("DEBUG: %s has %d children" % (name, len(children))) # Verbose
904
+ except Exception as get_child_err:
905
+ lines.append("%s ERROR getting children: %s" % (indent_str, get_child_err))
906
+ # traceback.print_exc() # Optional
907
+
908
+ for child in children:
909
+ lines.extend(get_object_structure(child, indent + 1, max_depth)) # Recurse
910
+
911
+ except Exception as e:
912
+ lines.append("%s- Error processing node: %s" % (indent_str, e))
913
+ traceback.print_exc() # Print detailed error for this node
914
+ return lines
915
+ try:
916
+ print("DEBUG: Getting structure for: %s" % PROJECT_FILE_PATH)
917
+ primary_project = ensure_project_open(PROJECT_FILE_PATH)
918
+ project_name = os.path.basename(PROJECT_FILE_PATH)
919
+ print("DEBUG: Getting structure for project: %s" % project_name)
920
+ # Use the project object obtained from ensure_project_open
921
+ structure_list = get_object_structure(primary_project, max_depth=15) # Set a reasonable depth
922
+ structure_output = "\\n".join(structure_list)
923
+ # Ensure markers are printed distinctly
924
+ print("\\n--- PROJECT STRUCTURE START ---")
925
+ print(structure_output)
926
+ print("--- PROJECT STRUCTURE END ---\\n")
927
+ print("SCRIPT_SUCCESS: Project structure retrieved."); sys.exit(0)
928
+ except Exception as e:
929
+ detailed_error = traceback.format_exc()
930
+ error_message = "Error getting structure for %s: %s\\n%s" % (PROJECT_FILE_PATH, e, detailed_error)
931
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
932
+ `;
933
+ // (GET_POU_CODE_SCRIPT_TEMPLATE uses FIND_OBJECT_BY_PATH_PYTHON_SNIPPET)
934
+ const GET_POU_CODE_SCRIPT_TEMPLATE = `
935
+ import sys, scriptengine as script_engine, os, traceback
936
+ ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
937
+ ${FIND_OBJECT_BY_PATH_PYTHON_SNIPPET}
938
+ POU_FULL_PATH = "{POU_FULL_PATH}"; CODE_START_MARKER = "### POU CODE START ###"; CODE_END_MARKER = "### POU CODE END ###"
939
+ DECL_START_MARKER = "### POU DECLARATION START ###"; DECL_END_MARKER = "### POU DECLARATION END ###"
940
+ IMPL_START_MARKER = "### POU IMPLEMENTATION START ###"; IMPL_END_MARKER = "### POU IMPLEMENTATION END ###"
941
+
942
+ try:
943
+ print("DEBUG: Getting code: POU_FULL_PATH='%s', Project='%s'" % (POU_FULL_PATH, PROJECT_FILE_PATH))
944
+ primary_project = ensure_project_open(PROJECT_FILE_PATH)
945
+ if not POU_FULL_PATH: raise ValueError("POU full path empty.")
946
+
947
+ # Find the target POU/Method/Property object
948
+ target_object = find_object_by_path_robust(primary_project, POU_FULL_PATH, "target object")
949
+ if not target_object: raise ValueError("Target object not found using path: %s" % POU_FULL_PATH)
950
+
951
+ target_name = getattr(target_object, 'get_name', lambda: POU_FULL_PATH)()
952
+ print("DEBUG: Found target object: %s" % target_name)
953
+
954
+ declaration_code = ""; implementation_code = ""
955
+
956
+ # --- Get Declaration Part ---
957
+ if hasattr(target_object, 'textual_declaration'):
958
+ decl_obj = target_object.textual_declaration
959
+ if decl_obj and hasattr(decl_obj, 'text'):
960
+ try:
961
+ declaration_code = decl_obj.text
962
+ print("DEBUG: Got declaration text.")
963
+ except Exception as decl_read_err:
964
+ print("ERROR: Failed to read declaration text: %s" % decl_read_err)
965
+ declaration_code = "/* ERROR reading declaration: %s */" % decl_read_err
966
+ else:
967
+ print("WARN: textual_declaration exists but is None or has no 'text' attribute.")
968
+ else:
969
+ print("WARN: No textual_declaration attribute.")
970
+
971
+ # --- Get Implementation Part ---
972
+ if hasattr(target_object, 'textual_implementation'):
973
+ impl_obj = target_object.textual_implementation
974
+ if impl_obj and hasattr(impl_obj, 'text'):
975
+ try:
976
+ implementation_code = impl_obj.text
977
+ print("DEBUG: Got implementation text.")
978
+ except Exception as impl_read_err:
979
+ print("ERROR: Failed to read implementation text: %s" % impl_read_err)
980
+ implementation_code = "/* ERROR reading implementation: %s */" % impl_read_err
981
+ else:
982
+ print("WARN: textual_implementation exists but is None or has no 'text' attribute.")
983
+ else:
984
+ print("WARN: No textual_implementation attribute.")
985
+
986
+
987
+ print("Code retrieved for: %s" % target_name)
988
+ # Print declaration between markers, ensuring markers are on separate lines
989
+ print("\\n" + DECL_START_MARKER)
990
+ print(declaration_code)
991
+ print(DECL_END_MARKER + "\\n")
992
+ # Print implementation between markers
993
+ print(IMPL_START_MARKER)
994
+ print(implementation_code)
995
+ print(IMPL_END_MARKER + "\\n")
996
+
997
+ # --- LEGACY MARKERS for backward compatibility if needed ---
998
+ # Combine both for old marker format, adding a separator line
999
+ # legacy_combined_code = declaration_code + "\\n\\n// Implementation\\n" + implementation_code
1000
+ # print(CODE_START_MARKER); print(legacy_combined_code); print(CODE_END_MARKER)
1001
+ # --- END LEGACY ---
1002
+
1003
+ print("SCRIPT_SUCCESS: Code retrieved."); sys.exit(0)
1004
+ except Exception as e:
1005
+ detailed_error = traceback.format_exc()
1006
+ error_message = "Error getting code for object '%s' in project '%s': %s\\n%s" % (POU_FULL_PATH, PROJECT_FILE_PATH, e, detailed_error)
1007
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
1008
+ `;
1009
+ // --- MCP Resources ---
1010
+ // (Resource definitions remain the same)
1011
+ server.resource("project-status", "codesys://project/status", (uri) => __awaiter(void 0, void 0, void 0, function* () {
1012
+ var _a, _b, _c, _d, _e;
1013
+ console.error(`Resource request: ${uri.href}`);
1014
+ try {
1015
+ const result = yield (0, codesys_interop_1.executeCodesysScript)(CHECK_STATUS_SCRIPT, codesysExePath, codesysProfileName);
1016
+ const outputLines = result.output.split(/[\r\n]+/).filter(line => line.trim());
1017
+ const statusData = {};
1018
+ outputLines.forEach(line => { const match = line.match(/^([^:]+):\s*(.*)$/); if (match) {
1019
+ statusData[match[1].trim()] = match[2].trim();
1020
+ } });
1021
+ const statusText = `CODESYS Status:\n - Scripting OK: ${(_a = statusData['Scripting OK']) !== null && _a !== void 0 ? _a : 'Unknown'}\n - Project Open: ${(_b = statusData['Project Open']) !== null && _b !== void 0 ? _b : 'Unknown'}\n - Project Name: ${(_c = statusData['Project Name']) !== null && _c !== void 0 ? _c : 'Unknown'}\n - Project Path: ${(_d = statusData['Project Path']) !== null && _d !== void 0 ? _d : 'N/A'}`;
1022
+ // Determine error status based on script success AND scripting OK status
1023
+ const isError = !result.success || ((_e = statusData['Scripting OK']) === null || _e === void 0 ? void 0 : _e.toLowerCase()) !== 'true';
1024
+ return { contents: [{ uri: uri.href, text: statusText, contentType: "text/plain" }], isError: isError };
1025
+ }
1026
+ catch (error) {
1027
+ console.error(`Error resource ${uri.href}:`, error);
1028
+ return { contents: [{ uri: uri.href, text: `Failed status script: ${error.message}`, contentType: "text/plain" }], isError: true };
1029
+ }
1030
+ }));
1031
+ const projectStructureTemplate = new mcp_js_1.ResourceTemplate("codesys://project/{+project_path}/structure", { list: undefined });
1032
+ server.resource("project-structure", projectStructureTemplate, (uri, params) => __awaiter(void 0, void 0, void 0, function* () {
1033
+ const projectPathParam = params.project_path;
1034
+ if (typeof projectPathParam !== 'string') {
1035
+ return { contents: [{ uri: uri.href, text: `Error: Invalid project path type (${typeof projectPathParam}).`, contentType: "text/plain" }], isError: true };
1036
+ }
1037
+ const projectPath = projectPathParam;
1038
+ if (!projectPath) {
1039
+ return { contents: [{ uri: uri.href, text: "Error: Project path missing.", contentType: "text/plain" }], isError: true };
1040
+ }
1041
+ console.error(`Resource request: project structure for ${projectPath}`);
1042
+ try {
1043
+ const absoluteProjPath = path.normalize(path.isAbsolute(projectPath) ? projectPath : path.join(WORKSPACE_DIR, projectPath));
1044
+ // No need to check file existence here, ensure_project_open will handle it
1045
+ // if (!(await fileExists(absoluteProjPath))) { return { contents: [{ uri: uri.href, text: `Error: Project file not found: ${absoluteProjPath}`, contentType: "text/plain" }], isError: true }; }
1046
+ const escapedPathForPython = absoluteProjPath.replace(/\\/g, '\\\\');
1047
+ const scriptContent = GET_PROJECT_STRUCTURE_SCRIPT_TEMPLATE.replace("{PROJECT_FILE_PATH}", escapedPathForPython);
1048
+ const result = yield (0, codesys_interop_1.executeCodesysScript)(scriptContent, codesysExePath, codesysProfileName);
1049
+ let structureText = `Error retrieving structure for ${absoluteProjPath}.\n\n${result.output}`;
1050
+ let isError = !result.success;
1051
+ if (result.success && result.output.includes("SCRIPT_SUCCESS")) {
1052
+ const startMarker = "--- PROJECT STRUCTURE START ---";
1053
+ const endMarker = "--- PROJECT STRUCTURE END ---";
1054
+ const startIndex = result.output.indexOf(startMarker);
1055
+ const endIndex = result.output.indexOf(endMarker);
1056
+ if (startIndex !== -1 && endIndex !== -1 && startIndex < endIndex) {
1057
+ // Extract text between markers, replace escaped newlines, trim whitespace
1058
+ structureText = result.output.substring(startIndex + startMarker.length, endIndex).replace(/\\n/g, '\n').trim();
1059
+ }
1060
+ else {
1061
+ console.error("Error: Could not find structure markers in script output.");
1062
+ structureText = `Could not parse structure markers in output for ${absoluteProjPath}.\n\nOutput:\n${result.output}`;
1063
+ isError = true;
1064
+ }
1065
+ }
1066
+ else {
1067
+ isError = true;
1068
+ } // Explicitly set error if script failed
1069
+ return { contents: [{ uri: uri.href, text: structureText, contentType: "text/plain" }], isError: isError };
1070
+ }
1071
+ catch (error) {
1072
+ console.error(`Error getting structure ${uri.href}:`, error);
1073
+ return { contents: [{ uri: uri.href, text: `Failed structure script for '${projectPath}': ${error.message}`, contentType: "text/plain" }], isError: true };
1074
+ }
1075
+ }));
1076
+ const pouCodeTemplate = new mcp_js_1.ResourceTemplate("codesys://project/{+project_path}/pou/{+pou_path}/code", { list: undefined });
1077
+ server.resource("pou-code", pouCodeTemplate, (uri, params) => __awaiter(void 0, void 0, void 0, function* () {
1078
+ const projectPathParam = params.project_path;
1079
+ const pouPathParam = params.pou_path;
1080
+ if (typeof projectPathParam !== 'string' || typeof pouPathParam !== 'string') {
1081
+ return { contents: [{ uri: uri.href, text: "Error: Invalid project or POU path type.", contentType: "text/plain" }], isError: true };
1082
+ }
1083
+ const projectPath = projectPathParam;
1084
+ const pouPath = pouPathParam;
1085
+ if (!projectPath || !pouPath) {
1086
+ return { contents: [{ uri: uri.href, text: "Error: Project or POU path missing.", contentType: "text/plain" }], isError: true };
1087
+ }
1088
+ console.error(`Resource request: POU code: Project='${projectPath}', POU='${pouPath}'`);
1089
+ try {
1090
+ const absoluteProjPath = path.normalize(path.isAbsolute(projectPath) ? projectPath : path.join(WORKSPACE_DIR, projectPath));
1091
+ const sanitizedPouPath = String(pouPath).replace(/\\/g, '/').replace(/^\/+|\/+$/g, ''); // Normalize slashes, remove leading/trailing
1092
+ // No need to check file existence here, ensure_project_open handles it
1093
+ // if (!(await fileExists(absoluteProjPath))) { return { contents: [{ uri: uri.href, text: `Error: Project file not found: ${absoluteProjPath}`, contentType: "text/plain" }], isError: true }; }
1094
+ const escapedProjPath = absoluteProjPath.replace(/\\/g, '\\\\');
1095
+ let scriptContent = GET_POU_CODE_SCRIPT_TEMPLATE.replace("{PROJECT_FILE_PATH}", escapedProjPath);
1096
+ scriptContent = scriptContent.replace("{POU_FULL_PATH}", sanitizedPouPath); // Use normalized POU path
1097
+ const result = yield (0, codesys_interop_1.executeCodesysScript)(scriptContent, codesysExePath, codesysProfileName);
1098
+ let codeText = `Error retrieving code for object '${sanitizedPouPath}' in project '${absoluteProjPath}'.\n\n${result.output}`;
1099
+ let isError = !result.success;
1100
+ if (result.success && result.output.includes("SCRIPT_SUCCESS")) {
1101
+ const declStartMarker = "### POU DECLARATION START ###";
1102
+ const declEndMarker = "### POU DECLARATION END ###";
1103
+ const implStartMarker = "### POU IMPLEMENTATION START ###";
1104
+ const implEndMarker = "### POU IMPLEMENTATION END ###";
1105
+ const declStartIdx = result.output.indexOf(declStartMarker);
1106
+ const declEndIdx = result.output.indexOf(declEndMarker);
1107
+ const implStartIdx = result.output.indexOf(implStartMarker);
1108
+ const implEndIdx = result.output.indexOf(implEndMarker);
1109
+ let declaration = "/* Declaration not found in output */";
1110
+ let implementation = "/* Implementation not found in output */";
1111
+ if (declStartIdx !== -1 && declEndIdx !== -1 && declStartIdx < declEndIdx) {
1112
+ declaration = result.output.substring(declStartIdx + declStartMarker.length, declEndIdx).replace(/\\n/g, '\n').trim();
1113
+ }
1114
+ else {
1115
+ console.error(`WARN: Declaration markers not found correctly for ${sanitizedPouPath}`);
1116
+ }
1117
+ if (implStartIdx !== -1 && implEndIdx !== -1 && implStartIdx < implEndIdx) {
1118
+ implementation = result.output.substring(implStartIdx + implStartMarker.length, implEndIdx).replace(/\\n/g, '\n').trim();
1119
+ }
1120
+ else {
1121
+ console.error(`WARN: Implementation markers not found correctly for ${sanitizedPouPath}`);
1122
+ }
1123
+ // Combine them for the output (adjust format as needed)
1124
+ codeText = `// ----- Declaration -----\n${declaration}\n\n// ----- Implementation -----\n${implementation}`;
1125
+ }
1126
+ else {
1127
+ isError = true;
1128
+ }
1129
+ return { contents: [{ uri: uri.href, text: codeText, contentType: "text/plain" }], isError: isError };
1130
+ }
1131
+ catch (error) {
1132
+ console.error(`Error getting POU code ${uri.href}:`, error);
1133
+ return { contents: [{ uri: uri.href, text: `Failed POU code script for '${pouPath}' in '${projectPath}': ${error.message}`, contentType: "text/plain" }], isError: true };
1134
+ }
1135
+ }));
1136
+ // --- MCP Tools ---
1137
+ server.tool("open_project", { filePath: zod_1.z.string().describe("Path to the project file.") }, (args) => __awaiter(void 0, void 0, void 0, function* () {
1138
+ const { filePath } = args;
1139
+ let absPath = path.normalize(path.isAbsolute(filePath) ? filePath : path.join(WORKSPACE_DIR, filePath));
1140
+ console.error(`Tool call: open_project: ${absPath}`);
1141
+ // File existence check is now handled by ensure_project_open within the script
1142
+ // if (!(await fileExists(absPath))) { return { content: [{ type: "text", text: `Error: File not found: ${absPath}` }], isError: true }; }
1143
+ try {
1144
+ const escapedPath = absPath.replace(/\\/g, '\\\\');
1145
+ const script = OPEN_PROJECT_SCRIPT_TEMPLATE.replace("{PROJECT_FILE_PATH}", escapedPath);
1146
+ const result = yield (0, codesys_interop_1.executeCodesysScript)(script, codesysExePath, codesysProfileName);
1147
+ const success = result.success && result.output.includes("SCRIPT_SUCCESS");
1148
+ return { content: [{ type: "text", text: success ? `Project opened: ${absPath}` : `Failed open project ${absPath}. Output:\n${result.output}` }], isError: !success };
1149
+ }
1150
+ catch (e) {
1151
+ console.error(`Error open_project ${absPath}: ${e}`);
1152
+ return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1153
+ }
1154
+ }));
1155
+ server.tool("create_project", { filePath: zod_1.z.string().describe("Path for new project.") }, (args) => __awaiter(void 0, void 0, void 0, function* () {
1156
+ const { filePath } = args;
1157
+ let absPath = path.normalize(path.isAbsolute(filePath) ? filePath : path.join(WORKSPACE_DIR, filePath));
1158
+ console.error(`Tool call: create_project (copy template): ${absPath}`);
1159
+ let templatePath = "";
1160
+ try {
1161
+ // Prioritize relative path first, as it's more common with portable installs
1162
+ const baseDir = path.dirname(path.dirname(codesysExePath)); // Go up two levels from CODESYS.exe
1163
+ templatePath = path.normalize(path.join(baseDir, 'Templates', 'Standard.project'));
1164
+ if (yield fileExists(templatePath)) {
1165
+ console.error(`DEBUG: Found template relative to exe: ${templatePath}`);
1166
+ }
1167
+ else {
1168
+ // Fallback to ProgramData
1169
+ console.error(`WARN: Template not found relative to exe: ${templatePath}. Trying ProgramData...`);
1170
+ const programData = process.env.ALLUSERSPROFILE || process.env.ProgramData || 'C:\\ProgramData';
1171
+ // Construct path carefully, might vary slightly between versions/installers
1172
+ const possibleTemplateDir = path.join(programData, 'CODESYS', 'CODESYS', codesysProfileName, 'Templates'); // Common pattern
1173
+ let potentialTemplatePath = path.normalize(path.join(possibleTemplateDir, 'Standard.project'));
1174
+ if (yield fileExists(potentialTemplatePath)) {
1175
+ templatePath = potentialTemplatePath;
1176
+ console.error(`DEBUG: Found template in ProgramData: ${templatePath}`);
1177
+ }
1178
+ else {
1179
+ // Try another common pattern without the profile name subdir under the second CODESYS
1180
+ const alternativeTemplateDir = path.join(programData, 'CODESYS', 'Templates');
1181
+ potentialTemplatePath = path.normalize(path.join(alternativeTemplateDir, 'Standard.project'));
1182
+ if (yield fileExists(potentialTemplatePath)) {
1183
+ templatePath = potentialTemplatePath;
1184
+ console.error(`DEBUG: Found template in ProgramData (alternative): ${templatePath}`);
1185
+ }
1186
+ else {
1187
+ throw new Error(`Standard template project file not found at relative path or ProgramData locations.`);
1188
+ }
1189
+ }
1190
+ }
1191
+ }
1192
+ catch (e) {
1193
+ console.error(`Template Error: ${e.message}`);
1194
+ return { content: [{ type: "text", text: `Template Error: ${e.message}` }], isError: true };
1195
+ }
1196
+ try {
1197
+ const escProjPath = absPath.replace(/\\/g, '\\\\');
1198
+ const escTmplPath = templatePath.replace(/\\/g, '\\\\');
1199
+ const script = CREATE_PROJECT_SCRIPT_TEMPLATE
1200
+ .replace("{PROJECT_FILE_PATH}", escProjPath)
1201
+ .replace("{TEMPLATE_PROJECT_PATH}", escTmplPath);
1202
+ console.error(">>> create_project (copy-then-open): PREPARED SCRIPT:", script.substring(0, 500) + "..."); // Log start of script
1203
+ const result = yield (0, codesys_interop_1.executeCodesysScript)(script, codesysExePath, codesysProfileName);
1204
+ console.error(">>> create_project (copy-then-open): EXECUTION RESULT:", JSON.stringify(result));
1205
+ const success = result.success && result.output.includes("SCRIPT_SUCCESS");
1206
+ return { content: [{ type: "text", text: success ? `Project created from template: ${absPath}` : `Failed create project ${absPath} from template. Output:\n${result.output}` }], isError: !success };
1207
+ }
1208
+ catch (e) {
1209
+ console.error(`Error create_project ${absPath}: ${e}`);
1210
+ return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1211
+ }
1212
+ }));
1213
+ server.tool("save_project", { projectFilePath: zod_1.z.string().describe("Path to project.") }, (args) => __awaiter(void 0, void 0, void 0, function* () {
1214
+ const { projectFilePath } = args;
1215
+ let absPath = path.normalize(path.isAbsolute(projectFilePath) ? projectFilePath : path.join(WORKSPACE_DIR, projectFilePath));
1216
+ console.error(`Tool call: save_project: ${absPath}`);
1217
+ // No need to check file existence here, ensure_project_open handles it
1218
+ // if (!(await fileExists(absPath))) { return { content: [{ type: "text", text: `Error: File not found: ${absPath}` }], isError: true }; }
1219
+ try {
1220
+ const escapedPath = absPath.replace(/\\/g, '\\\\');
1221
+ const script = SAVE_PROJECT_SCRIPT_TEMPLATE.replace("{PROJECT_FILE_PATH}", escapedPath);
1222
+ const result = yield (0, codesys_interop_1.executeCodesysScript)(script, codesysExePath, codesysProfileName);
1223
+ const success = result.success && result.output.includes("SCRIPT_SUCCESS");
1224
+ return { content: [{ type: "text", text: success ? `Project saved: ${absPath}` : `Failed save project ${absPath}. Output:\n${result.output}` }], isError: !success };
1225
+ }
1226
+ catch (e) {
1227
+ console.error(`Error save_project ${absPath}: ${e}`);
1228
+ return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1229
+ }
1230
+ }));
1231
+ server.tool("create_pou", {
1232
+ projectFilePath: zod_1.z.string().describe("Path to project."),
1233
+ name: zod_1.z.string().describe("Name for the new POU."),
1234
+ type: PouTypeEnum.describe("Type of POU (Program, FunctionBlock, Function)."),
1235
+ language: ImplementationLanguageEnum.describe("Implementation language (ST, LD, FBD, etc.). Will use default if not directly supported/mapped by script."),
1236
+ parentPath: zod_1.z.string().describe("Relative path under project/application (e.g., 'Application' or 'MyFolder/SubFolder').")
1237
+ }, (args) => __awaiter(void 0, void 0, void 0, function* () {
1238
+ const { projectFilePath, name, type, language, parentPath } = args;
1239
+ let absPath = path.normalize(path.isAbsolute(projectFilePath) ? projectFilePath : path.join(WORKSPACE_DIR, projectFilePath));
1240
+ const sanParentPath = parentPath.replace(/\\/g, '/').replace(/^\/+|\/+$/g, ''); // Normalize parent path slashes
1241
+ const sanName = name.trim(); // Trim whitespace from name
1242
+ console.error(`Tool call: create_pou: Name='${sanName}', Type='${type}', Lang='${language}', Parent='${sanParentPath}', Project='${absPath}'`);
1243
+ // No need for file exists check here
1244
+ // if (!(await fileExists(absPath))) { return { content: [{ type: "text", text: `Error: File not found: ${absPath}` }], isError: true }; }
1245
+ try {
1246
+ const escProjPath = absPath.replace(/\\/g, '\\\\');
1247
+ // Use the fixed CREATE_POU_SCRIPT_TEMPLATE
1248
+ let script = CREATE_POU_SCRIPT_TEMPLATE.replace("{PROJECT_FILE_PATH}", escProjPath);
1249
+ script = script.replace("{POU_NAME}", sanName);
1250
+ script = script.replace("{POU_TYPE_STR}", type); // Pass the enum string directly
1251
+ script = script.replace("{IMPL_LANGUAGE_STR}", language); // Pass language string
1252
+ script = script.replace("{PARENT_PATH}", sanParentPath); // Use normalized path
1253
+ console.error(">>> create_pou: PREPARED SCRIPT:", script.substring(0, 500) + "...");
1254
+ const result = yield (0, codesys_interop_1.executeCodesysScript)(script, codesysExePath, codesysProfileName);
1255
+ console.error(">>> create_pou: EXECUTION RESULT:", JSON.stringify(result));
1256
+ const success = result.success && result.output.includes("SCRIPT_SUCCESS");
1257
+ return { content: [{ type: "text", text: success ? `POU '${sanName}' created in '${sanParentPath}' of ${absPath}. Project saved.` : `Failed create POU '${sanName}'. Output:\n${result.output}` }], isError: !success };
1258
+ }
1259
+ catch (e) {
1260
+ console.error(`Error create_pou ${sanName} in ${absPath}: ${e}`);
1261
+ return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1262
+ }
1263
+ }));
1264
+ // **TOOL: set_pou_code**
1265
+ server.tool("set_pou_code", {
1266
+ projectFilePath: zod_1.z.string().describe("Path to project."),
1267
+ pouPath: zod_1.z.string().describe("Relative POU/Method/Property path (e.g., 'Application/MyPOU' or 'MyFolder/MyFB/MyMethod')."),
1268
+ declarationCode: zod_1.z.string().describe("Code for the declaration part (VAR...END_VAR).").optional(),
1269
+ implementationCode: zod_1.z.string().describe("Code for the implementation logic part.").optional()
1270
+ }, (args) => __awaiter(void 0, void 0, void 0, function* () {
1271
+ const { projectFilePath, pouPath, declarationCode, implementationCode } = args;
1272
+ // Basic validation: ensure at least one code part is provided
1273
+ if (declarationCode === undefined && implementationCode === undefined) {
1274
+ return { content: [{ type: "text", text: "Error: At least one of declarationCode or implementationCode must be provided." }], isError: true };
1275
+ }
1276
+ let absPath = path.normalize(path.isAbsolute(projectFilePath) ? projectFilePath : path.join(WORKSPACE_DIR, projectFilePath));
1277
+ const sanPouPath = pouPath.replace(/\\/g, '/').replace(/^\/+|\/+$/g, ''); // Normalize POU path slashes
1278
+ console.error(`Tool call: set_pou_code: Target='${sanPouPath}', Project='${absPath}'`);
1279
+ // No need for file exists check here
1280
+ // if (!(await fileExists(absPath))) { return { content: [{ type: "text", text: `Error: File not found: ${absPath}` }], isError: true }; }
1281
+ try {
1282
+ const escProjPath = absPath.replace(/\\/g, '\\\\');
1283
+ // Escape content for Python triple-quoted strings
1284
+ // Provide empty string if undefined, then escape
1285
+ const sanDeclCode = (declarationCode !== null && declarationCode !== void 0 ? declarationCode : "").replace(/\\/g, '\\\\').replace(/"""/g, '\\"\\"\\"');
1286
+ const sanImplCode = (implementationCode !== null && implementationCode !== void 0 ? implementationCode : "").replace(/\\/g, '\\\\').replace(/"""/g, '\\"\\"\\"');
1287
+ // Use the SET_POU_CODE_SCRIPT_TEMPLATE
1288
+ let script = SET_POU_CODE_SCRIPT_TEMPLATE.replace("{PROJECT_FILE_PATH}", escProjPath);
1289
+ script = script.replace("{POU_FULL_PATH}", sanPouPath);
1290
+ script = script.replace("{DECLARATION_CONTENT}", sanDeclCode);
1291
+ script = script.replace("{IMPLEMENTATION_CONTENT}", sanImplCode);
1292
+ console.error(">>> set_pou_code: PREPARED SCRIPT:", script.substring(0, 500) + "...");
1293
+ const result = yield (0, codesys_interop_1.executeCodesysScript)(script, codesysExePath, codesysProfileName);
1294
+ console.error(">>> set_pou_code: EXECUTION RESULT:", JSON.stringify(result));
1295
+ const success = result.success && result.output.includes("SCRIPT_SUCCESS");
1296
+ return { content: [{ type: "text", text: success ? `Code set for '${sanPouPath}' in ${absPath}. Project saved.` : `Failed set code for '${sanPouPath}'. Output:\n${result.output}` }], isError: !success };
1297
+ }
1298
+ catch (e) {
1299
+ console.error(`Error set_pou_code ${sanPouPath} in ${absPath}: ${e}`);
1300
+ return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1301
+ }
1302
+ }));
1303
+ // **NEW TOOL: create_property**
1304
+ server.tool("create_property", {
1305
+ projectFilePath: zod_1.z.string().describe("Path to the project file."),
1306
+ parentPouPath: zod_1.z.string().describe("Relative path to the parent POU (e.g., 'Application/MyFB')."),
1307
+ propertyName: zod_1.z.string().describe("Name of the new property."),
1308
+ propertyType: zod_1.z.string().describe("Data type of the property (e.g., 'BOOL', 'INT', 'MyDUT').")
1309
+ // language: z.string().optional().describe("Implementation language for Getter/Setter (e.g., 'ST'). Defaults to project default.") // Optional
1310
+ }, (args) => __awaiter(void 0, void 0, void 0, function* () {
1311
+ const { projectFilePath, parentPouPath, propertyName, propertyType } = args;
1312
+ let absPath = path.normalize(path.isAbsolute(projectFilePath) ? projectFilePath : path.join(WORKSPACE_DIR, projectFilePath));
1313
+ const sanParentPath = parentPouPath.replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');
1314
+ const sanPropName = propertyName.trim();
1315
+ const sanPropType = propertyType.trim();
1316
+ console.error(`Tool call: create_property: Name='${sanPropName}', Type='${sanPropType}', ParentPOU='${sanParentPath}', Project='${absPath}'`);
1317
+ // No file exists check needed here
1318
+ if (!sanPropName || !sanPropType) {
1319
+ return { content: [{ type: "text", text: `Error: Property name and type cannot be empty.` }], isError: true };
1320
+ }
1321
+ try {
1322
+ const escProjPath = absPath.replace(/\\/g, '\\\\');
1323
+ let script = CREATE_PROPERTY_SCRIPT_TEMPLATE.replace("{PROJECT_FILE_PATH}", escProjPath);
1324
+ script = script.replace("{PARENT_POU_FULL_PATH}", sanParentPath);
1325
+ script = script.replace("{PROPERTY_NAME}", sanPropName);
1326
+ script = script.replace("{PROPERTY_TYPE}", sanPropType);
1327
+ // Add language replacement here if you implement the optional language argument
1328
+ console.error(">>> create_property: PREPARED SCRIPT:", script.substring(0, 500) + "...");
1329
+ const result = yield (0, codesys_interop_1.executeCodesysScript)(script, codesysExePath, codesysProfileName);
1330
+ console.error(">>> create_property: EXECUTION RESULT:", JSON.stringify(result));
1331
+ const success = result.success && result.output.includes("SCRIPT_SUCCESS");
1332
+ return {
1333
+ content: [{ type: "text", text: success ? `Property '${sanPropName}' created under '${sanParentPath}' in ${absPath}. Project saved.` : `Failed to create property '${sanPropName}'. Output:\n${result.output}` }],
1334
+ isError: !success
1335
+ };
1336
+ }
1337
+ catch (e) {
1338
+ console.error(`Error create_property ${sanPropName} in ${absPath}: ${e}`);
1339
+ return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1340
+ }
1341
+ }));
1342
+ // **NEW TOOL: create_method**
1343
+ server.tool("create_method", {
1344
+ projectFilePath: zod_1.z.string().describe("Path to the project file."),
1345
+ parentPouPath: zod_1.z.string().describe("Relative path to the parent POU (e.g., 'Application/MyFB')."),
1346
+ methodName: zod_1.z.string().describe("Name of the new method."),
1347
+ returnType: zod_1.z.string().optional().describe("Return type (e.g., 'BOOL', 'INT'). Leave empty or omit for no return value."),
1348
+ // language: z.string().optional().describe("Implementation language (e.g., 'ST'). Defaults to project default.") // Optional
1349
+ }, (args) => __awaiter(void 0, void 0, void 0, function* () {
1350
+ const { projectFilePath, parentPouPath, methodName, returnType } = args;
1351
+ let absPath = path.normalize(path.isAbsolute(projectFilePath) ? projectFilePath : path.join(WORKSPACE_DIR, projectFilePath));
1352
+ const sanParentPath = parentPouPath.replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');
1353
+ const sanMethName = methodName.trim();
1354
+ const sanReturnType = (returnType !== null && returnType !== void 0 ? returnType : "").trim(); // Use empty string if undefined/null
1355
+ console.error(`Tool call: create_method: Name='${sanMethName}', Return='${sanReturnType}', ParentPOU='${sanParentPath}', Project='${absPath}'`);
1356
+ // No file exists check needed here
1357
+ if (!sanMethName) {
1358
+ return { content: [{ type: "text", text: `Error: Method name cannot be empty.` }], isError: true };
1359
+ }
1360
+ try {
1361
+ const escProjPath = absPath.replace(/\\/g, '\\\\');
1362
+ let script = CREATE_METHOD_SCRIPT_TEMPLATE.replace("{PROJECT_FILE_PATH}", escProjPath);
1363
+ script = script.replace("{PARENT_POU_FULL_PATH}", sanParentPath);
1364
+ script = script.replace("{METHOD_NAME}", sanMethName);
1365
+ script = script.replace("{RETURN_TYPE}", sanReturnType); // Pass empty string if no return type
1366
+ // Add language replacement here if needed
1367
+ console.error(">>> create_method: PREPARED SCRIPT:", script.substring(0, 500) + "...");
1368
+ const result = yield (0, codesys_interop_1.executeCodesysScript)(script, codesysExePath, codesysProfileName);
1369
+ console.error(">>> create_method: EXECUTION RESULT:", JSON.stringify(result));
1370
+ const success = result.success && result.output.includes("SCRIPT_SUCCESS");
1371
+ return {
1372
+ content: [{ type: "text", text: success ? `Method '${sanMethName}' created under '${sanParentPath}' in ${absPath}. Project saved.` : `Failed to create method '${sanMethName}'. Output:\n${result.output}` }],
1373
+ isError: !success
1374
+ };
1375
+ }
1376
+ catch (e) {
1377
+ console.error(`Error create_method ${sanMethName} in ${absPath}: ${e}`);
1378
+ return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1379
+ }
1380
+ }));
1381
+ // (compile_project tool remains the same)
1382
+ server.tool("compile_project", { projectFilePath: zod_1.z.string().describe("Path to project.") }, (args) => __awaiter(void 0, void 0, void 0, function* () {
1383
+ const { projectFilePath } = args;
1384
+ let absPath = path.normalize(path.isAbsolute(projectFilePath) ? projectFilePath : path.join(WORKSPACE_DIR, projectFilePath));
1385
+ console.error(`Tool call: compile_project: ${absPath}`);
1386
+ // No file exists check needed here
1387
+ // if (!(await fileExists(absPath))) { return { content: [{ type: "text", text: `Error: File not found: ${absPath}` }], isError: true }; }
1388
+ try {
1389
+ const escapedPath = absPath.replace(/\\/g, '\\\\');
1390
+ const script = COMPILE_PROJECT_SCRIPT_TEMPLATE.replace("{PROJECT_FILE_PATH}", escapedPath);
1391
+ const result = yield (0, codesys_interop_1.executeCodesysScript)(script, codesysExePath, codesysProfileName);
1392
+ const success = result.success && result.output.includes("SCRIPT_SUCCESS");
1393
+ // Add check for compile errors in output if possible/needed
1394
+ // Regex might be more robust if format is consistent
1395
+ const hasCompileErrors = result.output.includes("Compile complete --") && !/ 0 error\(s\),/.test(result.output);
1396
+ let message = success ? `Compilation initiated for application in ${absPath}. Check CODESYS messages for results.` : `Failed initiating compilation for ${absPath}. Output:\n${result.output}`;
1397
+ if (success && hasCompileErrors) {
1398
+ message += " WARNING: Build command reported errors in the output log.";
1399
+ console.warn("Compile project reported build errors in the output.");
1400
+ // Optionally set isError = true here if compile errors should fail the tool call
1401
+ // return { content: [{ type: "text", text: message }], isError: true };
1402
+ }
1403
+ return { content: [{ type: "text", text: message }], isError: !success };
1404
+ }
1405
+ catch (e) {
1406
+ console.error(`Error compile_project ${absPath}: ${e}`);
1407
+ return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
1408
+ }
1409
+ }));
1410
+ // --- Server Connection & Start ---
1411
+ function startServer() {
1412
+ return __awaiter(this, void 0, void 0, function* () {
1413
+ try {
1414
+ const transport = new stdio_js_1.StdioServerTransport();
1415
+ console.error("Connecting MCP server via stdio...");
1416
+ yield server.connect(transport);
1417
+ console.error("MCP Server connected and listening.");
1418
+ }
1419
+ catch (error) {
1420
+ console.error("FATAL: Failed to start MCP server:", error);
1421
+ process.exit(1);
1422
+ }
1423
+ });
1424
+ }
1425
+ // Ensure startup happens only once if run directly
1426
+ if (require.main === module) {
1427
+ startServer();
1428
+ }
1429
+ // --- Graceful Shutdown ---
1430
+ process.on('SIGINT', () => {
1431
+ console.error('\nSIGINT received, shutting down...');
1432
+ // No server.disconnect() needed for stdio
1433
+ process.exit(0); // Exit the process, closing stdio streams
1434
+ });
1435
+ process.on('SIGTERM', () => {
1436
+ console.error('\nSIGTERM received, shutting down...');
1437
+ // No server.disconnect() needed for stdio
1438
+ process.exit(0); // Exit the process, closing stdio streams
1439
+ });
1440
+ // Optional: Handle unhandled rejections
1441
+ process.on('unhandledRejection', (reason, promise) => {
1442
+ console.error('Unhandled Rejection at:', promise, 'reason:', reason);
1443
+ // Application specific logging, throwing an error, or other logic here
1444
+ });