@codesys/mcp-toolkit 1.1.9 → 1.1.10

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,13 @@ 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.1.10] - 2025-05-06
9
+
10
+ ### Fixed
11
+ - Improved handling of Windows paths in `get_project_structure` and `ensure_project_open` functions
12
+ - Enhanced error handling and debugging for project structure tool
13
+ - Added more detailed logging to help diagnose connection issues with CODESYS
14
+
8
15
  ## [1.1.9] - 2025-05-06
9
16
 
10
17
  ### Added
@@ -8,10 +8,31 @@ import traceback
8
8
  MAX_RETRIES = 3
9
9
  RETRY_DELAY = 2.0 # seconds (use float for time.sleep)
10
10
 
11
+ # Special handling for Windows paths
12
+ def sanitize_windows_path(path_str):
13
+ """Properly sanitize Windows paths for CODESYS scripting"""
14
+ # If it's already a Python raw string literal, return it as is
15
+ if path_str.startswith('r"') or path_str.startswith("r'"):
16
+ return path_str
17
+
18
+ # Make Windows paths with backslashes work correctly when passed to CODESYS
19
+ # We use actual backslashes (which will be doubled by Python raw string)
20
+ sanitized = path_str.replace('\\', '\\\\')
21
+
22
+ # Clean up any extraneous quotes
23
+ sanitized = sanitized.strip('"\'')
24
+
25
+ print(f"DEBUG: Sanitized path from '{path_str}' to '{sanitized}'")
26
+ return sanitized
27
+
11
28
  def ensure_project_open(target_project_path):
12
29
  print("DEBUG: Ensuring project is open: %s" % target_project_path)
30
+
31
+ # First sanitize the path for proper Windows path handling
32
+ sanitized_path = sanitize_windows_path(target_project_path)
33
+
13
34
  # Normalize target path once
14
- normalized_target_path = os.path.normcase(os.path.abspath(target_project_path))
35
+ normalized_target_path = os.path.normcase(os.path.abspath(sanitized_path))
15
36
 
16
37
  for attempt in range(MAX_RETRIES):
17
38
  print("DEBUG: Ensure project attempt %d/%d for %s" % (attempt + 1, MAX_RETRIES, normalized_target_path))
@@ -100,8 +121,12 @@ def ensure_project_open(target_project_path):
100
121
  time.sleep(RETRY_DELAY) # Give CODESYS time
101
122
  # Re-verify: Is the project now primary and accessible?
102
123
  recheck_primary = None
103
- try: recheck_primary = script_engine.projects.primary
104
- except Exception as recheck_primary_err: print("WARN: Error getting primary project after reopen: %s" % recheck_primary_err)
124
+ try:
125
+ recheck_primary = script_engine.projects.primary
126
+ print(f"DEBUG: Recheck primary project type: {type(recheck_primary).__name__}")
127
+ except Exception as recheck_primary_err:
128
+ print("WARN: Error getting primary project after reopen: %s" % recheck_primary_err)
129
+ traceback.print_exc() # Print full trace for primary project access issue
105
130
 
106
131
  if recheck_primary:
107
132
  recheck_path = ""
@@ -8,9 +8,14 @@ def ensure_project_open(target_project_path):
8
8
 
9
9
  def get_object_structure(obj, indent=0, max_depth=10): # Add max_depth
10
10
  lines = []; indent_str = " " * indent
11
+ if obj is None:
12
+ lines.append("%s- ERROR: Null object received" % indent_str)
13
+ return lines
14
+
11
15
  if indent > max_depth:
12
16
  lines.append("%s- Max recursion depth reached." % indent_str)
13
17
  return lines
18
+
14
19
  try:
15
20
  name = "Unnamed"; obj_type = type(obj).__name__
16
21
  guid_str = ""
@@ -37,10 +42,10 @@ def get_object_structure(obj, indent=0, max_depth=10): # Add max_depth
37
42
  if can_have_children:
38
43
  try:
39
44
  children = obj.get_children(False)
40
- # print("DEBUG: %s has %d children" % (name, len(children))) # Verbose
45
+ print("DEBUG: '%s' has %d children" % (name, len(children)))
41
46
  except Exception as get_child_err:
42
47
  lines.append("%s ERROR getting children: %s" % (indent_str, get_child_err))
43
- # traceback.print_exc() # Optional
48
+ traceback.print_exc() # Now print detailed error
44
49
 
45
50
  for child in children:
46
51
  lines.extend(get_object_structure(child, indent + 1, max_depth)) # Recurse
@@ -49,15 +54,63 @@ def get_object_structure(obj, indent=0, max_depth=10): # Add max_depth
49
54
  lines.append("%s- Error processing node: %s" % (indent_str, e))
50
55
  traceback.print_exc() # Print detailed error for this node
51
56
  return lines
57
+
58
+ # Normalize Windows paths for CODESYS scripting
59
+ def normalize_path(path_str):
60
+ # Replace backslashes with double backslashes for Python string in CODESYS
61
+ normalized = path_str.replace('\\', '\\\\')
62
+ # Remove any quotes that might be present
63
+ normalized = normalized.strip('"\'')
64
+ print(f"DEBUG: Normalized path from '{path_str}' to '{normalized}'")
65
+ return normalized
52
66
 
53
67
  try:
54
- print("DEBUG: Getting structure for: %s" % PROJECT_FILE_PATH)
55
- primary_project = ensure_project_open(PROJECT_FILE_PATH)
56
- project_name = os.path.basename(PROJECT_FILE_PATH)
57
- print("DEBUG: Getting structure for project: %s" % project_name)
68
+ # Normalize the project path for CODESYS
69
+ normalized_path = normalize_path(PROJECT_FILE_PATH)
70
+ print("DEBUG: Getting structure for project path: '%s'" % normalized_path)
71
+
72
+ # First confirm that CODESYS is running properly
73
+ print("DEBUG: CODESYS version info:")
74
+ try:
75
+ version_info = script_engine.get_version_info()
76
+ print(f"DEBUG: CODESYS Version: {version_info}")
77
+ except Exception as v_err:
78
+ print(f"DEBUG: Error getting CODESYS version: {v_err}")
79
+
80
+ print("DEBUG: Opening project...")
81
+ primary_project = ensure_project_open(normalized_path)
82
+
83
+ if primary_project is None:
84
+ print("DEBUG: ERROR - Project object is None after ensure_project_open")
85
+ raise ValueError(f"Failed to open project: {normalized_path} - project object is None")
86
+
87
+ print("DEBUG: Project object type: %s" % type(primary_project).__name__)
88
+ project_name = os.path.basename(normalized_path)
89
+
90
+ if hasattr(primary_project, 'get_name'):
91
+ print("DEBUG: Project name from object: %s" % primary_project.get_name())
92
+ else:
93
+ print("DEBUG: Project object does not have get_name() method")
94
+
95
+ # Check if project has useful methods
96
+ if hasattr(primary_project, 'get_children'):
97
+ print("DEBUG: Project has get_children method")
98
+ else:
99
+ print("DEBUG: WARNING - Project does not have get_children method")
100
+
101
+ if hasattr(primary_project, 'active_application'):
102
+ print("DEBUG: Project has active_application property")
103
+ app = primary_project.active_application
104
+ if app:
105
+ print("DEBUG: Active application name: %s" % getattr(app, 'get_name', lambda: "Unknown")())
106
+ else:
107
+ print("DEBUG: WARNING - Project does not have active_application property")
108
+
58
109
  # Use the project object obtained from ensure_project_open
59
- structure_list = get_object_structure(primary_project, max_depth=15) # Set a reasonable depth
110
+ print("DEBUG: Starting recursion for project structure with max_depth=15")
111
+ structure_list = get_object_structure(primary_project, max_depth=15)
60
112
  structure_output = "\\n".join(structure_list)
113
+
61
114
  # Ensure markers are printed distinctly
62
115
  print("\\n--- PROJECT STRUCTURE START ---")
63
116
  print(structure_output)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codesys/mcp-toolkit",
3
- "version": "1.1.9",
3
+ "version": "1.1.10",
4
4
  "description": "Model Context Protocol (MCP) server for CODESYS automation platform",
5
5
  "main": "dist/server.js",
6
6
  "bin": {
@@ -8,10 +8,31 @@ import traceback
8
8
  MAX_RETRIES = 3
9
9
  RETRY_DELAY = 2.0 # seconds (use float for time.sleep)
10
10
 
11
+ # Special handling for Windows paths
12
+ def sanitize_windows_path(path_str):
13
+ """Properly sanitize Windows paths for CODESYS scripting"""
14
+ # If it's already a Python raw string literal, return it as is
15
+ if path_str.startswith('r"') or path_str.startswith("r'"):
16
+ return path_str
17
+
18
+ # Make Windows paths with backslashes work correctly when passed to CODESYS
19
+ # We use actual backslashes (which will be doubled by Python raw string)
20
+ sanitized = path_str.replace('\\', '\\\\')
21
+
22
+ # Clean up any extraneous quotes
23
+ sanitized = sanitized.strip('"\'')
24
+
25
+ print(f"DEBUG: Sanitized path from '{path_str}' to '{sanitized}'")
26
+ return sanitized
27
+
11
28
  def ensure_project_open(target_project_path):
12
29
  print("DEBUG: Ensuring project is open: %s" % target_project_path)
30
+
31
+ # First sanitize the path for proper Windows path handling
32
+ sanitized_path = sanitize_windows_path(target_project_path)
33
+
13
34
  # Normalize target path once
14
- normalized_target_path = os.path.normcase(os.path.abspath(target_project_path))
35
+ normalized_target_path = os.path.normcase(os.path.abspath(sanitized_path))
15
36
 
16
37
  for attempt in range(MAX_RETRIES):
17
38
  print("DEBUG: Ensure project attempt %d/%d for %s" % (attempt + 1, MAX_RETRIES, normalized_target_path))
@@ -100,8 +121,12 @@ def ensure_project_open(target_project_path):
100
121
  time.sleep(RETRY_DELAY) # Give CODESYS time
101
122
  # Re-verify: Is the project now primary and accessible?
102
123
  recheck_primary = None
103
- try: recheck_primary = script_engine.projects.primary
104
- except Exception as recheck_primary_err: print("WARN: Error getting primary project after reopen: %s" % recheck_primary_err)
124
+ try:
125
+ recheck_primary = script_engine.projects.primary
126
+ print(f"DEBUG: Recheck primary project type: {type(recheck_primary).__name__}")
127
+ except Exception as recheck_primary_err:
128
+ print("WARN: Error getting primary project after reopen: %s" % recheck_primary_err)
129
+ traceback.print_exc() # Print full trace for primary project access issue
105
130
 
106
131
  if recheck_primary:
107
132
  recheck_path = ""
@@ -8,9 +8,14 @@ def ensure_project_open(target_project_path):
8
8
 
9
9
  def get_object_structure(obj, indent=0, max_depth=10): # Add max_depth
10
10
  lines = []; indent_str = " " * indent
11
+ if obj is None:
12
+ lines.append("%s- ERROR: Null object received" % indent_str)
13
+ return lines
14
+
11
15
  if indent > max_depth:
12
16
  lines.append("%s- Max recursion depth reached." % indent_str)
13
17
  return lines
18
+
14
19
  try:
15
20
  name = "Unnamed"; obj_type = type(obj).__name__
16
21
  guid_str = ""
@@ -37,10 +42,10 @@ def get_object_structure(obj, indent=0, max_depth=10): # Add max_depth
37
42
  if can_have_children:
38
43
  try:
39
44
  children = obj.get_children(False)
40
- # print("DEBUG: %s has %d children" % (name, len(children))) # Verbose
45
+ print("DEBUG: '%s' has %d children" % (name, len(children)))
41
46
  except Exception as get_child_err:
42
47
  lines.append("%s ERROR getting children: %s" % (indent_str, get_child_err))
43
- # traceback.print_exc() # Optional
48
+ traceback.print_exc() # Now print detailed error
44
49
 
45
50
  for child in children:
46
51
  lines.extend(get_object_structure(child, indent + 1, max_depth)) # Recurse
@@ -49,15 +54,63 @@ def get_object_structure(obj, indent=0, max_depth=10): # Add max_depth
49
54
  lines.append("%s- Error processing node: %s" % (indent_str, e))
50
55
  traceback.print_exc() # Print detailed error for this node
51
56
  return lines
57
+
58
+ # Normalize Windows paths for CODESYS scripting
59
+ def normalize_path(path_str):
60
+ # Replace backslashes with double backslashes for Python string in CODESYS
61
+ normalized = path_str.replace('\\', '\\\\')
62
+ # Remove any quotes that might be present
63
+ normalized = normalized.strip('"\'')
64
+ print(f"DEBUG: Normalized path from '{path_str}' to '{normalized}'")
65
+ return normalized
52
66
 
53
67
  try:
54
- print("DEBUG: Getting structure for: %s" % PROJECT_FILE_PATH)
55
- primary_project = ensure_project_open(PROJECT_FILE_PATH)
56
- project_name = os.path.basename(PROJECT_FILE_PATH)
57
- print("DEBUG: Getting structure for project: %s" % project_name)
68
+ # Normalize the project path for CODESYS
69
+ normalized_path = normalize_path(PROJECT_FILE_PATH)
70
+ print("DEBUG: Getting structure for project path: '%s'" % normalized_path)
71
+
72
+ # First confirm that CODESYS is running properly
73
+ print("DEBUG: CODESYS version info:")
74
+ try:
75
+ version_info = script_engine.get_version_info()
76
+ print(f"DEBUG: CODESYS Version: {version_info}")
77
+ except Exception as v_err:
78
+ print(f"DEBUG: Error getting CODESYS version: {v_err}")
79
+
80
+ print("DEBUG: Opening project...")
81
+ primary_project = ensure_project_open(normalized_path)
82
+
83
+ if primary_project is None:
84
+ print("DEBUG: ERROR - Project object is None after ensure_project_open")
85
+ raise ValueError(f"Failed to open project: {normalized_path} - project object is None")
86
+
87
+ print("DEBUG: Project object type: %s" % type(primary_project).__name__)
88
+ project_name = os.path.basename(normalized_path)
89
+
90
+ if hasattr(primary_project, 'get_name'):
91
+ print("DEBUG: Project name from object: %s" % primary_project.get_name())
92
+ else:
93
+ print("DEBUG: Project object does not have get_name() method")
94
+
95
+ # Check if project has useful methods
96
+ if hasattr(primary_project, 'get_children'):
97
+ print("DEBUG: Project has get_children method")
98
+ else:
99
+ print("DEBUG: WARNING - Project does not have get_children method")
100
+
101
+ if hasattr(primary_project, 'active_application'):
102
+ print("DEBUG: Project has active_application property")
103
+ app = primary_project.active_application
104
+ if app:
105
+ print("DEBUG: Active application name: %s" % getattr(app, 'get_name', lambda: "Unknown")())
106
+ else:
107
+ print("DEBUG: WARNING - Project does not have active_application property")
108
+
58
109
  # Use the project object obtained from ensure_project_open
59
- structure_list = get_object_structure(primary_project, max_depth=15) # Set a reasonable depth
110
+ print("DEBUG: Starting recursion for project structure with max_depth=15")
111
+ structure_list = get_object_structure(primary_project, max_depth=15)
60
112
  structure_output = "\\n".join(structure_list)
113
+
61
114
  # Ensure markers are printed distinctly
62
115
  print("\\n--- PROJECT STRUCTURE START ---")
63
116
  print(structure_output)