@codesys/mcp-toolkit 1.1.7 → 1.1.9
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 +15 -0
- package/dist/scripts/create_pou.py +46 -3
- package/dist/server.js +147 -0
- package/package.json +1 -1
- package/src/scripts/create_pou.py +46 -3
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,21 @@ 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.9] - 2025-05-06
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
- Added three new MCP tools that were previously only available as resources:
|
|
12
|
+
- `check_status`: Tool to check CODESYS environment and open project status
|
|
13
|
+
- `get_project_structure`: Tool to retrieve the structure of a CODESYS project
|
|
14
|
+
- `get_pou_code`: Tool to retrieve code from a specific POU
|
|
15
|
+
- These tools allow Claude and other AI assistants to directly access project inspection functionality
|
|
16
|
+
|
|
17
|
+
## [1.1.8] - 2025-05-06
|
|
18
|
+
|
|
19
|
+
### Fixed
|
|
20
|
+
- Enhanced create_pou script to automatically find the Application object when only "Application" is specified as the parent path
|
|
21
|
+
- Added better error messages with suggestions when Application isn't found
|
|
22
|
+
|
|
8
23
|
## [1.1.7] - 2025-05-06
|
|
9
24
|
|
|
10
25
|
### Fixed
|
|
@@ -35,9 +35,52 @@ try:
|
|
|
35
35
|
pou_type_enum = pou_type_map.get(POU_TYPE_STR)
|
|
36
36
|
if not pou_type_enum: raise ValueError("Invalid POU type string: %s. Use Program, FunctionBlock, or Function." % POU_TYPE_STR)
|
|
37
37
|
|
|
38
|
-
#
|
|
39
|
-
|
|
40
|
-
|
|
38
|
+
# For common case where user just specified "Application", automatically try to find it
|
|
39
|
+
if PARENT_PATH_REL == "Application":
|
|
40
|
+
# Get project name from file path to build the likely full path
|
|
41
|
+
project_name = os.path.splitext(os.path.basename(PROJECT_FILE_PATH))[0]
|
|
42
|
+
potential_paths = [
|
|
43
|
+
PARENT_PATH_REL, # Original "Application"
|
|
44
|
+
f"{project_name}.{PARENT_PATH_REL}", # "projectName.Application"
|
|
45
|
+
f"{project_name}/{PARENT_PATH_REL}", # "projectName/Application"
|
|
46
|
+
f"{project_name}" # Just the project name itself might work
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
print(f"DEBUG: Parent path is simply 'Application', trying several variants to find it")
|
|
50
|
+
|
|
51
|
+
# Try each potential path until one works
|
|
52
|
+
parent_object = None
|
|
53
|
+
for path in potential_paths:
|
|
54
|
+
print(f"DEBUG: Attempting to find parent with path: '{path}'")
|
|
55
|
+
parent_candidate = find_object_by_path_robust(primary_project, path, "parent container")
|
|
56
|
+
if parent_candidate:
|
|
57
|
+
parent_object = parent_candidate
|
|
58
|
+
print(f"DEBUG: Successfully found parent using path: '{path}'")
|
|
59
|
+
break
|
|
60
|
+
|
|
61
|
+
if not parent_object:
|
|
62
|
+
# For diagnostics, try to get the application object directly as a fallback
|
|
63
|
+
print("DEBUG: All path attempts failed. Trying to access application directly...")
|
|
64
|
+
try:
|
|
65
|
+
if hasattr(primary_project, 'active_application'):
|
|
66
|
+
app = primary_project.active_application
|
|
67
|
+
if app:
|
|
68
|
+
parent_object = app
|
|
69
|
+
print(f"DEBUG: Found application object directly: {app.get_name()}")
|
|
70
|
+
if not parent_object and hasattr(primary_project, 'find'):
|
|
71
|
+
apps = primary_project.find("Application", True)
|
|
72
|
+
if apps:
|
|
73
|
+
parent_object = apps[0]
|
|
74
|
+
print(f"DEBUG: Found application via search: {parent_object.get_name()}")
|
|
75
|
+
except Exception as e:
|
|
76
|
+
print(f"ERROR: Direct application access also failed: {e}")
|
|
77
|
+
else:
|
|
78
|
+
# Use the provided path normally
|
|
79
|
+
parent_object = find_object_by_path_robust(primary_project, PARENT_PATH_REL, "parent container")
|
|
80
|
+
|
|
81
|
+
# Final check if parent was found
|
|
82
|
+
if not parent_object:
|
|
83
|
+
raise ValueError("Parent object not found for path: %s. Try using the full path like 'ProjectName.Application' or run get_project_structure first to see the correct structure." % PARENT_PATH_REL)
|
|
41
84
|
|
|
42
85
|
parent_name = getattr(parent_object, 'get_name', lambda: str(parent_object))()
|
|
43
86
|
print("DEBUG: Using parent object: %s (Type: %s)" % (parent_name, type(parent_object).__name__))
|
package/dist/server.js
CHANGED
|
@@ -619,6 +619,153 @@ function startMcpServer(config) {
|
|
|
619
619
|
};
|
|
620
620
|
}
|
|
621
621
|
}));
|
|
622
|
+
server.tool("check_status", "Checks the status of the CODESYS environment and any open project", {}, () => __awaiter(this, void 0, void 0, function* () {
|
|
623
|
+
var _a, _b, _c, _d;
|
|
624
|
+
console.error(`Tool call: check_status`);
|
|
625
|
+
try {
|
|
626
|
+
const scriptContent = yield (0, scriptLoader_1.loadScriptTemplate)('check_status');
|
|
627
|
+
const result = yield (0, codesys_interop_1.executeCodesysScript)(scriptContent, codesysExePath, codesysProfileName);
|
|
628
|
+
if (!result.success) {
|
|
629
|
+
return {
|
|
630
|
+
content: [{ type: "text", text: `Failed to check CODESYS status: ${result.output}` }],
|
|
631
|
+
isError: true
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
const outputLines = result.output.split(/[\r\n]+/).filter(line => line.trim());
|
|
635
|
+
const statusData = {};
|
|
636
|
+
outputLines.forEach(line => {
|
|
637
|
+
const match = line.match(/^([^:]+):\s*(.*)$/);
|
|
638
|
+
if (match) {
|
|
639
|
+
statusData[match[1].trim()] = match[2].trim();
|
|
640
|
+
}
|
|
641
|
+
});
|
|
642
|
+
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'}`;
|
|
643
|
+
return {
|
|
644
|
+
content: [{ type: "text", text: statusText }],
|
|
645
|
+
isError: false
|
|
646
|
+
};
|
|
647
|
+
}
|
|
648
|
+
catch (error) {
|
|
649
|
+
console.error(`Error checking status:`, error);
|
|
650
|
+
return {
|
|
651
|
+
content: [{ type: "text", text: `Failed to check CODESYS status: ${error.message}` }],
|
|
652
|
+
isError: true
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
}));
|
|
656
|
+
server.tool("get_pou_code", "Retrieves the code (declaration and implementation) of a POU from a CODESYS project", {
|
|
657
|
+
projectFilePath: zod_1.z.string().describe("Path to the CODESYS project file."),
|
|
658
|
+
pouPath: zod_1.z.string().describe("Path to the POU within the project (e.g., 'Application/MyFB').")
|
|
659
|
+
}, (args) => __awaiter(this, void 0, void 0, function* () {
|
|
660
|
+
const { projectFilePath, pouPath } = args;
|
|
661
|
+
let absPath = path.normalize(path.isAbsolute(projectFilePath) ? projectFilePath : path.join(WORKSPACE_DIR, projectFilePath));
|
|
662
|
+
const sanitizedPouPath = String(pouPath).replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');
|
|
663
|
+
console.error(`Tool call: get_pou_code: Project='${absPath}', POU='${sanitizedPouPath}'`);
|
|
664
|
+
try {
|
|
665
|
+
// Load script template and prepare parameters
|
|
666
|
+
const scriptTemplate = yield (0, scriptLoader_1.loadScriptTemplate)('get_pou_code');
|
|
667
|
+
const ensureProjectOpenTemplate = yield (0, scriptLoader_1.loadScriptTemplate)('ensure_project_open');
|
|
668
|
+
const findObjectByPathTemplate = yield (0, scriptLoader_1.loadScriptTemplate)('find_object_by_path');
|
|
669
|
+
const combinedScript = ensureProjectOpenTemplate + '\n\n' + findObjectByPathTemplate + '\n\n' + scriptTemplate;
|
|
670
|
+
const scriptContent = (0, scriptLoader_1.interpolateScript)(combinedScript, {
|
|
671
|
+
'PROJECT_FILE_PATH': absPath.replace(/\\/g, '\\\\'),
|
|
672
|
+
'POU_FULL_PATH': sanitizedPouPath
|
|
673
|
+
});
|
|
674
|
+
const result = yield (0, codesys_interop_1.executeCodesysScript)(scriptContent, codesysExePath, codesysProfileName);
|
|
675
|
+
if (!result.success) {
|
|
676
|
+
return {
|
|
677
|
+
content: [{ type: "text", text: `Failed to get POU code: ${result.output}` }],
|
|
678
|
+
isError: true
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
const declStartMarker = "### POU DECLARATION START ###";
|
|
682
|
+
const declEndMarker = "### POU DECLARATION END ###";
|
|
683
|
+
const implStartMarker = "### POU IMPLEMENTATION START ###";
|
|
684
|
+
const implEndMarker = "### POU IMPLEMENTATION END ###";
|
|
685
|
+
const declStartIdx = result.output.indexOf(declStartMarker);
|
|
686
|
+
const declEndIdx = result.output.indexOf(declEndMarker);
|
|
687
|
+
const implStartIdx = result.output.indexOf(implStartMarker);
|
|
688
|
+
const implEndIdx = result.output.indexOf(implEndMarker);
|
|
689
|
+
let declaration = "/* Declaration not found in output */";
|
|
690
|
+
let implementation = "/* Implementation not found in output */";
|
|
691
|
+
let isError = false;
|
|
692
|
+
if (declStartIdx !== -1 && declEndIdx !== -1 && declStartIdx < declEndIdx) {
|
|
693
|
+
declaration = result.output.substring(declStartIdx + declStartMarker.length, declEndIdx).replace(/\\n/g, '\n').trim();
|
|
694
|
+
}
|
|
695
|
+
else {
|
|
696
|
+
console.error(`WARN: Declaration markers not found correctly for ${sanitizedPouPath}`);
|
|
697
|
+
isError = true;
|
|
698
|
+
}
|
|
699
|
+
if (implStartIdx !== -1 && implEndIdx !== -1 && implStartIdx < implEndIdx) {
|
|
700
|
+
implementation = result.output.substring(implStartIdx + implStartMarker.length, implEndIdx).replace(/\\n/g, '\n').trim();
|
|
701
|
+
}
|
|
702
|
+
else {
|
|
703
|
+
console.error(`WARN: Implementation markers not found correctly for ${sanitizedPouPath}`);
|
|
704
|
+
isError = true;
|
|
705
|
+
}
|
|
706
|
+
const codeText = `// ----- Declaration -----\n${declaration}\n\n// ----- Implementation -----\n${implementation}`;
|
|
707
|
+
return {
|
|
708
|
+
content: [{ type: "text", text: codeText }],
|
|
709
|
+
isError: isError
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
catch (error) {
|
|
713
|
+
console.error(`Error getting POU code:`, error);
|
|
714
|
+
return {
|
|
715
|
+
content: [{ type: "text", text: `Failed to get POU code for '${pouPath}' in '${projectFilePath}': ${error.message}` }],
|
|
716
|
+
isError: true
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
}));
|
|
720
|
+
server.tool("get_project_structure", "Retrieves the structure of a CODESYS project including its POUs, methods, properties, etc.", {
|
|
721
|
+
projectFilePath: zod_1.z.string().describe("Path to the CODESYS project file to examine.")
|
|
722
|
+
}, (args) => __awaiter(this, void 0, void 0, function* () {
|
|
723
|
+
const { projectFilePath } = args;
|
|
724
|
+
let absPath = path.normalize(path.isAbsolute(projectFilePath) ? projectFilePath : path.join(WORKSPACE_DIR, projectFilePath));
|
|
725
|
+
console.error(`Tool call: get_project_structure: ${absPath}`);
|
|
726
|
+
try {
|
|
727
|
+
// Load the script templates and prepare with parameters
|
|
728
|
+
const scriptTemplate = yield (0, scriptLoader_1.loadScriptTemplate)('get_project_structure');
|
|
729
|
+
const ensureProjectOpenTemplate = yield (0, scriptLoader_1.loadScriptTemplate)('ensure_project_open');
|
|
730
|
+
const combinedScript = ensureProjectOpenTemplate + '\n\n' + scriptTemplate;
|
|
731
|
+
const scriptContent = (0, scriptLoader_1.interpolateScript)(combinedScript, {
|
|
732
|
+
'PROJECT_FILE_PATH': absPath.replace(/\\/g, '\\\\')
|
|
733
|
+
});
|
|
734
|
+
const result = yield (0, codesys_interop_1.executeCodesysScript)(scriptContent, codesysExePath, codesysProfileName);
|
|
735
|
+
if (!result.success) {
|
|
736
|
+
return {
|
|
737
|
+
content: [{ type: "text", text: `Failed to get project structure: ${result.output}` }],
|
|
738
|
+
isError: true
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
// Extract the structure from the output
|
|
742
|
+
let structureText = '';
|
|
743
|
+
const startMarker = "--- PROJECT STRUCTURE START ---";
|
|
744
|
+
const endMarker = "--- PROJECT STRUCTURE END ---";
|
|
745
|
+
const startIndex = result.output.indexOf(startMarker);
|
|
746
|
+
const endIndex = result.output.indexOf(endMarker);
|
|
747
|
+
if (startIndex !== -1 && endIndex !== -1 && startIndex < endIndex) {
|
|
748
|
+
structureText = result.output.substring(startIndex + startMarker.length, endIndex).replace(/\\n/g, '\n').trim();
|
|
749
|
+
return {
|
|
750
|
+
content: [{ type: "text", text: structureText }],
|
|
751
|
+
isError: false
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
else {
|
|
755
|
+
return {
|
|
756
|
+
content: [{ type: "text", text: `Could not parse structure markers in output for ${absPath}.\n\nOutput:\n${result.output}` }],
|
|
757
|
+
isError: true
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
catch (error) {
|
|
762
|
+
console.error(`Error tool get_project_structure:`, error);
|
|
763
|
+
return {
|
|
764
|
+
content: [{ type: "text", text: `Failed to get project structure for '${projectFilePath}': ${error.message}` }],
|
|
765
|
+
isError: true
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
}));
|
|
622
769
|
server.tool("compile_project", "Compiles (Builds) the primary application within a CODESYS project.", {
|
|
623
770
|
projectFilePath: zod_1.z.string().describe("Path to the project file containing the application to compile (e.g., 'C:/Projects/MyPLC.project').")
|
|
624
771
|
}, (args) => __awaiter(this, void 0, void 0, function* () {
|
package/package.json
CHANGED
|
@@ -35,9 +35,52 @@ try:
|
|
|
35
35
|
pou_type_enum = pou_type_map.get(POU_TYPE_STR)
|
|
36
36
|
if not pou_type_enum: raise ValueError("Invalid POU type string: %s. Use Program, FunctionBlock, or Function." % POU_TYPE_STR)
|
|
37
37
|
|
|
38
|
-
#
|
|
39
|
-
|
|
40
|
-
|
|
38
|
+
# For common case where user just specified "Application", automatically try to find it
|
|
39
|
+
if PARENT_PATH_REL == "Application":
|
|
40
|
+
# Get project name from file path to build the likely full path
|
|
41
|
+
project_name = os.path.splitext(os.path.basename(PROJECT_FILE_PATH))[0]
|
|
42
|
+
potential_paths = [
|
|
43
|
+
PARENT_PATH_REL, # Original "Application"
|
|
44
|
+
f"{project_name}.{PARENT_PATH_REL}", # "projectName.Application"
|
|
45
|
+
f"{project_name}/{PARENT_PATH_REL}", # "projectName/Application"
|
|
46
|
+
f"{project_name}" # Just the project name itself might work
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
print(f"DEBUG: Parent path is simply 'Application', trying several variants to find it")
|
|
50
|
+
|
|
51
|
+
# Try each potential path until one works
|
|
52
|
+
parent_object = None
|
|
53
|
+
for path in potential_paths:
|
|
54
|
+
print(f"DEBUG: Attempting to find parent with path: '{path}'")
|
|
55
|
+
parent_candidate = find_object_by_path_robust(primary_project, path, "parent container")
|
|
56
|
+
if parent_candidate:
|
|
57
|
+
parent_object = parent_candidate
|
|
58
|
+
print(f"DEBUG: Successfully found parent using path: '{path}'")
|
|
59
|
+
break
|
|
60
|
+
|
|
61
|
+
if not parent_object:
|
|
62
|
+
# For diagnostics, try to get the application object directly as a fallback
|
|
63
|
+
print("DEBUG: All path attempts failed. Trying to access application directly...")
|
|
64
|
+
try:
|
|
65
|
+
if hasattr(primary_project, 'active_application'):
|
|
66
|
+
app = primary_project.active_application
|
|
67
|
+
if app:
|
|
68
|
+
parent_object = app
|
|
69
|
+
print(f"DEBUG: Found application object directly: {app.get_name()}")
|
|
70
|
+
if not parent_object and hasattr(primary_project, 'find'):
|
|
71
|
+
apps = primary_project.find("Application", True)
|
|
72
|
+
if apps:
|
|
73
|
+
parent_object = apps[0]
|
|
74
|
+
print(f"DEBUG: Found application via search: {parent_object.get_name()}")
|
|
75
|
+
except Exception as e:
|
|
76
|
+
print(f"ERROR: Direct application access also failed: {e}")
|
|
77
|
+
else:
|
|
78
|
+
# Use the provided path normally
|
|
79
|
+
parent_object = find_object_by_path_robust(primary_project, PARENT_PATH_REL, "parent container")
|
|
80
|
+
|
|
81
|
+
# Final check if parent was found
|
|
82
|
+
if not parent_object:
|
|
83
|
+
raise ValueError("Parent object not found for path: %s. Try using the full path like 'ProjectName.Application' or run get_project_structure first to see the correct structure." % PARENT_PATH_REL)
|
|
41
84
|
|
|
42
85
|
parent_name = getattr(parent_object, 'get_name', lambda: str(parent_object))()
|
|
43
86
|
print("DEBUG: Using parent object: %s (Type: %s)" % (parent_name, type(parent_object).__name__))
|