@codesys/mcp-toolkit 1.2.1 → 1.3.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/CHANGELOG.md CHANGED
@@ -5,6 +5,22 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.2.4] - 2025-05-02
9
+ ### Fixed
10
+ - Fully disabled session management to prevent operations appearing to succeed but not actually running
11
+ - Made it clearer that the persistent session feature is not yet implemented
12
+
13
+ ## [1.2.3] - 2025-05-02
14
+ ### Fixed
15
+ - Improved Windows path handling in Python scripts
16
+ - Added better error detection and reporting for file operations
17
+ - Enhanced debugging for file creation operations
18
+
19
+ ## [1.2.2] - 2025-05-02
20
+ ### Fixed
21
+ - Fixed issue where session management appeared to work but didn't create files
22
+ - Temporarily disabled incomplete session manager implementation
23
+
8
24
  ## [1.2.1] - 2025-05-02
9
25
  ### Fixed
10
26
  - Fixed Python script templates not being included in the npm package
@@ -56,12 +56,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
56
56
  };
57
57
  Object.defineProperty(exports, "__esModule", { value: true });
58
58
  exports.executeCodesysScript = executeCodesysScript;
59
+ exports.checkSessionStatus = checkSessionStatus;
60
+ exports.startSession = startSession;
61
+ exports.stopSession = stopSession;
59
62
  const child_process_1 = require("child_process");
60
63
  const promises_1 = require("fs/promises");
61
64
  const path = __importStar(require("path"));
62
65
  const os = __importStar(require("os"));
63
66
  const fs = __importStar(require("fs")); // Import fs for existsSync check
64
- // Optional import for session manager
67
+ // Session manager import
65
68
  const sessionManager_1 = require("./sessionManager");
66
69
  // Define expected success/error markers from the Python scripts
67
70
  const SCRIPT_SUCCESS_MARKER = 'SCRIPT_SUCCESS';
@@ -88,12 +91,16 @@ function executeCodesysScript(scriptContent, codesysExePath, codesysProfileName,
88
91
  if (!fs.existsSync(codesysExePath))
89
92
  throw new Error(`CODESYS executable not found at provided path: ${codesysExePath}`);
90
93
  // --- End Pre-checks ---
94
+ // Enable or disable session management
95
+ const SESSION_FEATURE_DISABLED = false;
91
96
  // --- Check if we should use the persistent session ---
92
- if (sessionManager) {
97
+ if (!SESSION_FEATURE_DISABLED && sessionManager) {
93
98
  const sessionState = sessionManager.getState();
99
+ // Check if the session is active
94
100
  if (sessionState === sessionManager_1.SessionState.RUNNING || sessionState === sessionManager_1.SessionState.BUSY) {
95
101
  process.stderr.write(`INTEROP: Using persistent session for script execution\n`);
96
102
  try {
103
+ // Execute the script in the session
97
104
  const result = yield sessionManager.executeScript(scriptContent);
98
105
  return {
99
106
  success: result.success,
@@ -106,10 +113,40 @@ function executeCodesysScript(scriptContent, codesysExePath, codesysProfileName,
106
113
  // Continue with the non-persistent approach as fallback
107
114
  }
108
115
  }
116
+ else if (sessionState === sessionManager_1.SessionState.STOPPED || sessionState === sessionManager_1.SessionState.ERROR) {
117
+ // Try to start the session if it's stopped or in error state
118
+ process.stderr.write(`INTEROP: Session is in ${sessionState} state. Attempting to start it.\n`);
119
+ try {
120
+ yield sessionManager.startSession();
121
+ const newState = sessionManager.getState();
122
+ if (newState === sessionManager_1.SessionState.RUNNING) {
123
+ process.stderr.write(`INTEROP: Session started successfully. Using it for script execution.\n`);
124
+ // Now that the session is running, execute the script
125
+ const result = yield sessionManager.executeScript(scriptContent);
126
+ return {
127
+ success: result.success,
128
+ output: result.output
129
+ };
130
+ }
131
+ else {
132
+ process.stderr.write(`INTEROP: Failed to start session (state: ${newState}). Using one-time execution.\n`);
133
+ }
134
+ }
135
+ catch (error) {
136
+ process.stderr.write(`INTEROP: Error starting session: ${error.message}\n`);
137
+ process.stderr.write(`INTEROP: Using one-time execution as fallback.\n`);
138
+ }
139
+ }
109
140
  else {
110
141
  process.stderr.write(`INTEROP: Session not in RUNNING/BUSY state (current: ${sessionState}). Using one-time execution.\n`);
111
142
  }
112
143
  }
144
+ else if (SESSION_FEATURE_DISABLED) {
145
+ process.stderr.write(`INTEROP: Session feature is disabled. Using one-time execution mode.\n`);
146
+ }
147
+ else {
148
+ process.stderr.write(`INTEROP: No session manager provided. Using one-time execution mode.\n`);
149
+ }
113
150
  // --- Standard one-time script execution ---
114
151
  const tempDir = os.tmpdir();
115
152
  const tempFileName = `codesys_script_${Date.now()}_${Math.random().toString(36).substring(2, 9)}.py`;
@@ -295,3 +332,107 @@ function executeCodesysScript(scriptContent, codesysExePath, codesysProfileName,
295
332
  return { success, output: finalOutput };
296
333
  });
297
334
  }
335
+ /**
336
+ * Checks if a session is currently active
337
+ *
338
+ * @param codesysExePath The full path to the CODESYS.exe executable
339
+ * @param codesysProfileName The name of the CODESYS profile to use for scripting
340
+ * @param sessionManager The session manager instance
341
+ * @returns Promise resolving to an object with session status
342
+ */
343
+ function checkSessionStatus(codesysExePath, codesysProfileName, sessionManager) {
344
+ return __awaiter(this, void 0, void 0, function* () {
345
+ if (!sessionManager) {
346
+ return { active: false, info: null };
347
+ }
348
+ try {
349
+ // Check if session is active
350
+ const isActive = yield sessionManager.isSessionActive();
351
+ if (!isActive) {
352
+ return { active: false, info: null };
353
+ }
354
+ // Get session information
355
+ const sessionInfo = yield sessionManager.getSessionInfo();
356
+ return {
357
+ active: true,
358
+ info: sessionInfo
359
+ };
360
+ }
361
+ catch (error) {
362
+ process.stderr.write(`INTEROP: Error checking session status: ${error.message}\n`);
363
+ return { active: false, info: null };
364
+ }
365
+ });
366
+ }
367
+ /**
368
+ * Starts a new persistent CODESYS session
369
+ *
370
+ * @param codesysExePath The full path to the CODESYS.exe executable
371
+ * @param codesysProfileName The name of the CODESYS profile to use for scripting
372
+ * @param sessionManager The session manager instance
373
+ * @returns Promise resolving when the session has started
374
+ */
375
+ function startSession(codesysExePath, codesysProfileName, sessionManager) {
376
+ return __awaiter(this, void 0, void 0, function* () {
377
+ if (!sessionManager) {
378
+ return { success: false, message: "No session manager provided" };
379
+ }
380
+ try {
381
+ // Check if session is already active
382
+ const isActive = yield sessionManager.isSessionActive();
383
+ if (isActive) {
384
+ return { success: true, message: "Session is already active" };
385
+ }
386
+ // Start a new session
387
+ yield sessionManager.startSession();
388
+ // Check if session started successfully
389
+ const statusAfterStart = yield sessionManager.isSessionActive();
390
+ if (statusAfterStart) {
391
+ return { success: true, message: "Session started successfully" };
392
+ }
393
+ else {
394
+ return { success: false, message: "Failed to start session" };
395
+ }
396
+ }
397
+ catch (error) {
398
+ process.stderr.write(`INTEROP: Error starting session: ${error.message}\n`);
399
+ return { success: false, message: `Error starting session: ${error.message}` };
400
+ }
401
+ });
402
+ }
403
+ /**
404
+ * Stops an active CODESYS session
405
+ *
406
+ * @param codesysExePath The full path to the CODESYS.exe executable
407
+ * @param codesysProfileName The name of the CODESYS profile to use for scripting
408
+ * @param sessionManager The session manager instance
409
+ * @returns Promise resolving when the session has stopped
410
+ */
411
+ function stopSession(codesysExePath, codesysProfileName, sessionManager) {
412
+ return __awaiter(this, void 0, void 0, function* () {
413
+ if (!sessionManager) {
414
+ return { success: false, message: "No session manager provided" };
415
+ }
416
+ try {
417
+ // Check if session is active
418
+ const isActive = yield sessionManager.isSessionActive();
419
+ if (!isActive) {
420
+ return { success: true, message: "No active session to stop" };
421
+ }
422
+ // Stop the session
423
+ yield sessionManager.stopSession();
424
+ // Verify session stopped
425
+ const statusAfterStop = yield sessionManager.isSessionActive();
426
+ if (!statusAfterStop) {
427
+ return { success: true, message: "Session stopped successfully" };
428
+ }
429
+ else {
430
+ return { success: false, message: "Failed to stop session" };
431
+ }
432
+ }
433
+ catch (error) {
434
+ process.stderr.write(`INTEROP: Error stopping session: ${error.message}\n`);
435
+ return { success: false, message: `Error stopping session: ${error.message}` };
436
+ }
437
+ });
438
+ }
@@ -121,8 +121,20 @@ function interpolateScript(template, params) {
121
121
  let result = template;
122
122
  // Replace each parameter in the template
123
123
  for (const [key, value] of Object.entries(params)) {
124
- // Convert value to string and escape backslashes for Python
125
- const escapedValue = String(value).replace(/\\/g, '\\\\');
124
+ // Handle Windows paths specially
125
+ let escapedValue;
126
+ // Check if this looks like a Windows path
127
+ if (typeof value === 'string' && (value.includes(':\\') || value.includes('\\'))) {
128
+ // For Windows paths, use a different approach with raw strings
129
+ console.error(`SCRIPT_LOADER: Detected Windows path: ${value}`);
130
+ // Use Python raw string format to avoid backslash interpretation issues
131
+ escapedValue = `r'${value.replace(/'/g, "\\'")}'`;
132
+ console.error(`SCRIPT_LOADER: Converted to Python raw string: ${escapedValue}`);
133
+ }
134
+ else {
135
+ // For non-path values, just escape backslashes normally
136
+ escapedValue = String(value).replace(/\\/g, '\\\\');
137
+ }
126
138
  // Replace {PARAM_NAME} with the escaped value
127
139
  const paramPattern = new RegExp(`\\{${key}\\}`, 'g');
128
140
  result = result.replace(paramPattern, escapedValue);
@@ -1,7 +1,21 @@
1
1
  import sys, scriptengine as script_engine, os, shutil, time, traceback
2
- # Placeholders
3
- TEMPLATE_PROJECT_PATH = r'{TEMPLATE_PROJECT_PATH}' # Path to Standard.project
4
- PROJECT_FILE_PATH = r'{PROJECT_FILE_PATH}' # Path for the new project (Target Path)
2
+ # Placeholders - These might be Python raw strings (r'path') from the Node.js side
3
+ # So we need to handle them specially
4
+ TEMPLATE_PROJECT_PATH_RAW = '{TEMPLATE_PROJECT_PATH}' # Path to Standard.project
5
+ PROJECT_FILE_PATH_RAW = '{PROJECT_FILE_PATH}' # Path for the new project (Target Path)
6
+
7
+ # Process the paths - if they start with r' and end with ', extract the content
8
+ def extract_path(path_str):
9
+ if path_str.startswith("r'") and path_str.endswith("'"):
10
+ # This is a raw string from Node.js - extract the content
11
+ return path_str[2:-1]
12
+ return path_str
13
+
14
+ TEMPLATE_PROJECT_PATH = extract_path(TEMPLATE_PROJECT_PATH_RAW)
15
+ PROJECT_FILE_PATH = extract_path(PROJECT_FILE_PATH_RAW)
16
+
17
+ print("DEBUG: Processed TEMPLATE_PROJECT_PATH: %s" % TEMPLATE_PROJECT_PATH)
18
+ print("DEBUG: Processed PROJECT_FILE_PATH: %s" % PROJECT_FILE_PATH)
5
19
  try:
6
20
  print("DEBUG: Python script create_project (copy from template):")
7
21
  print("DEBUG: Template Source = %s" % TEMPLATE_PROJECT_PATH)
@@ -12,12 +26,44 @@ try:
12
26
 
13
27
  # 1. Copy the template project file to the new location
14
28
  target_dir = os.path.dirname(PROJECT_FILE_PATH)
15
- if not os.path.exists(target_dir): print("DEBUG: Creating target directory: %s" % target_dir); os.makedirs(target_dir)
29
+ print("DEBUG: Target directory path: %s" % target_dir)
30
+
31
+ # More robust directory creation
32
+ if not os.path.exists(target_dir):
33
+ try:
34
+ print("DEBUG: Creating target directory: %s" % target_dir)
35
+ os.makedirs(target_dir, exist_ok=True)
36
+ print("DEBUG: Directory creation result - exists after creation: %s" % os.path.exists(target_dir))
37
+ except Exception as dir_err:
38
+ print("ERROR: Failed to create directory %s: %s" % (target_dir, dir_err))
39
+ raise
40
+
16
41
  # Check if target file already exists
17
42
  if os.path.exists(PROJECT_FILE_PATH): print("WARN: Target project file already exists, overwriting: %s" % PROJECT_FILE_PATH)
18
43
 
19
44
  print("DEBUG: Copying '%s' to '%s'..." % (TEMPLATE_PROJECT_PATH, PROJECT_FILE_PATH))
20
- shutil.copy2(TEMPLATE_PROJECT_PATH, PROJECT_FILE_PATH) # copy2 preserves metadata
45
+ try:
46
+ # Complete path diagnosis
47
+ print("DEBUG: Template path absolute: %s" % os.path.abspath(TEMPLATE_PROJECT_PATH))
48
+ print("DEBUG: Target path absolute: %s" % os.path.abspath(PROJECT_FILE_PATH))
49
+ print("DEBUG: Template exists: %s" % os.path.exists(TEMPLATE_PROJECT_PATH))
50
+ print("DEBUG: Target dir exists: %s" % os.path.exists(target_dir))
51
+ print("DEBUG: Target dir is writable: %s" % os.access(target_dir, os.W_OK))
52
+
53
+ # Perform the copy
54
+ shutil.copy2(TEMPLATE_PROJECT_PATH, PROJECT_FILE_PATH) # copy2 preserves metadata
55
+
56
+ # Verify copy succeeded
57
+ if os.path.exists(PROJECT_FILE_PATH):
58
+ print("DEBUG: File copy VERIFIED - file exists at destination")
59
+ print("DEBUG: File size at destination: %s bytes" % os.path.getsize(PROJECT_FILE_PATH))
60
+ else:
61
+ print("ERROR: Copy seemed to succeed but file does not exist at destination!")
62
+ raise IOError("File not found at destination after copy: %s" % PROJECT_FILE_PATH)
63
+ except Exception as copy_err:
64
+ print("ERROR: Failed to copy file: %s" % copy_err)
65
+ raise
66
+
21
67
  print("DEBUG: File copy complete.")
22
68
 
23
69
  # 2. Open the newly copied project file
@@ -0,0 +1,132 @@
1
+ import sys, os, json, time
2
+ import tempfile
3
+
4
+ # Define markers for script results
5
+ SCRIPT_SUCCESS_MARKER = "SCRIPT_SUCCESS"
6
+ SCRIPT_ERROR_MARKER = "SCRIPT_ERROR"
7
+
8
+ # Session state and command files
9
+ SESSION_DIR = os.path.join(tempfile.gettempdir(), "codesys_session")
10
+ SESSION_STATE_FILE = os.path.join(SESSION_DIR, "session_state.json")
11
+ COMMAND_FILE = os.path.join(SESSION_DIR, "command.json")
12
+ RESULT_FILE = os.path.join(SESSION_DIR, "result.json")
13
+ SESSION_LOCK_FILE = os.path.join(SESSION_DIR, "session.lock")
14
+
15
+ def check_session_status():
16
+ """Check the status of a CODESYS session"""
17
+ try:
18
+ # Check if session directory exists
19
+ if not os.path.exists(SESSION_DIR):
20
+ print(f"{SCRIPT_SUCCESS_MARKER}: No session active. Session directory not found.")
21
+ return False
22
+
23
+ # Check if session state file exists
24
+ if not os.path.exists(SESSION_STATE_FILE):
25
+ print(f"{SCRIPT_SUCCESS_MARKER}: No session active. Session state file not found.")
26
+ return False
27
+
28
+ # Read session state
29
+ with open(SESSION_STATE_FILE, 'r') as f:
30
+ try:
31
+ session_state = json.load(f)
32
+ except json.JSONDecodeError:
33
+ print(f"{SCRIPT_ERROR_MARKER}: Invalid session state file")
34
+ return False
35
+
36
+ # Check if session is active
37
+ active = session_state.get('active', False)
38
+ status = session_state.get('status', 'unknown')
39
+
40
+ # Check session lock file to see if it's been updated recently
41
+ if os.path.exists(SESSION_LOCK_FILE):
42
+ try:
43
+ with open(SESSION_LOCK_FILE, 'r') as f:
44
+ lock_time = float(f.read().strip())
45
+ current_time = time.time()
46
+ time_diff = current_time - lock_time
47
+
48
+ # If lock file hasn't been updated in 30 seconds, session might be dead
49
+ if time_diff > 30:
50
+ print(f"{SCRIPT_SUCCESS_MARKER}: Session appears to be inactive (lock file stale by {time_diff:.1f} seconds)")
51
+ # But we'll leave the active flag as is, since it might just be busy
52
+ except Exception as e:
53
+ print(f"Error reading lock file: {e}")
54
+
55
+ # Execute a ping test by sending a simple command
56
+ if active and status in ["running", "busy"]:
57
+ # Try to ping the session
58
+ try:
59
+ # Check if command file exists
60
+ if os.path.exists(COMMAND_FILE):
61
+ # Create ping command
62
+ ping_command = {
63
+ "id": f"ping_{int(time.time())}",
64
+ "type": "execute_script",
65
+ "script": "print('SCRIPT_SUCCESS: Ping successful')",
66
+ "timestamp": time.time()
67
+ }
68
+
69
+ # Write command to file
70
+ command_data = {
71
+ "status": "pending",
72
+ "command": ping_command,
73
+ "timestamp": time.time()
74
+ }
75
+
76
+ with open(COMMAND_FILE, 'w') as f:
77
+ json.dump(command_data, f)
78
+
79
+ # Wait for result (with short timeout)
80
+ timeout = 5 # seconds
81
+ start_time = time.time()
82
+ ping_success = False
83
+
84
+ while not ping_success and (time.time() - start_time) < timeout:
85
+ # Check if result file exists
86
+ if not os.path.exists(RESULT_FILE):
87
+ time.sleep(0.5)
88
+ continue
89
+
90
+ try:
91
+ with open(RESULT_FILE, 'r') as f:
92
+ result_data = json.load(f)
93
+
94
+ if result_data.get("status") == "complete" and result_data.get("result"):
95
+ result = result_data.get("result")
96
+ if result.get('id') == ping_command['id'] and result.get('success', False):
97
+ ping_success = True
98
+ break
99
+ except Exception as e:
100
+ print(f"Error reading result: {e}")
101
+ time.sleep(0.5)
102
+
103
+ if not ping_success:
104
+ print(f"{SCRIPT_SUCCESS_MARKER}: Session appears to be unresponsive to ping")
105
+ return False
106
+ except Exception as e:
107
+ print(f"Error during ping test: {e}")
108
+
109
+ # Build status message
110
+ project_info = ""
111
+ if session_state.get('project_open', False):
112
+ project_name = session_state.get('project_name', 'Unknown')
113
+ project_path = session_state.get('project_path', 'Unknown')
114
+ project_info = f", Project: {project_name} ({project_path})"
115
+
116
+ if active and status in ["running", "busy"]:
117
+ print(f"{SCRIPT_SUCCESS_MARKER}: Session is active (Status: {status}{project_info})")
118
+ return True
119
+ else:
120
+ print(f"{SCRIPT_SUCCESS_MARKER}: Session is not active (Status: {status})")
121
+ return False
122
+
123
+ except Exception as e:
124
+ print(f"{SCRIPT_ERROR_MARKER}: Error checking session status - {str(e)}")
125
+ return False
126
+
127
+ # Main script
128
+ if __name__ == "__main__":
129
+ if check_session_status():
130
+ sys.exit(0)
131
+ else:
132
+ sys.exit(1)