@codesys/mcp-toolkit 1.0.9 → 1.1.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/README.md CHANGED
@@ -1,254 +1,151 @@
1
+
1
2
  # @codesys/mcp-toolkit
2
3
 
3
4
  ![npm](https://img.shields.io/npm/v/@codesys/mcp-toolkit)
4
5
  ![License](https://img.shields.io/github/license/johannesPettersson80/codesys-mcp-toolkit)
6
+ ![Node Version](https://img.shields.io/node/v/@codesys/mcp-toolkit)
5
7
 
6
- A Model Context Protocol (MCP) server for CODESYS V3 programming environments. This toolkit enables seamless interaction between MCP clients (like Claude Desktop) and CODESYS, allowing automation of project management, POU creation, code editing, and compilation tasks.
8
+ A Model Context Protocol (MCP) server for CODESYS V3 programming environments. This toolkit enables seamless interaction between MCP clients (like Claude Desktop) and CODESYS, allowing automation of project management, POU creation, code editing, and compilation tasks via the CODESYS Scripting Engine.
7
9
 
8
10
  ## 🌟 Features
9
11
 
10
12
  - **Project Management**
11
- - Open existing CODESYS projects
12
- - Create new projects from templates
13
- - Save project changes
13
+ - Open existing CODESYS projects (`open_project`)
14
+ - Create new projects from standard templates (`create_project`)
15
+ - Save project changes (`save_project`)
14
16
 
15
17
  - **POU Management**
16
- - Create Programs, Function Blocks, and Functions
17
- - Set declaration and implementation code
18
- - Create properties and methods for Function Blocks
19
- - Compile projects
18
+ - Create Programs, Function Blocks, and Functions (`create_pou`)
19
+ - Set declaration and implementation code (`set_pou_code`)
20
+ - Create properties for Function Blocks (`create_property`)
21
+ - Create methods for Function Blocks (`create_method`)
22
+ - Compile projects (`compile_project`)
20
23
 
21
24
  - **MCP Resources**
22
- - `codesys://project/status`: Check scripting status and project state
23
- - `codesys://project/{+project_path}/structure`: Retrieve project structure
24
- - `codesys://project/{+project_path}/pou/{+pou_path}/code`: Read POU code
25
-
26
- - **MCP Tools**
27
- - `open_project`: Open specified CODESYS project
28
- - `create_project`: Create new CODESYS project
29
- - `save_project`: Save currently open project
30
- - `create_pou`: Create new Program, Function Block, or Function
31
- - `set_pou_code`: Update code for a specified POU
32
- - `create_property`: Create property in a Function Block
33
- - `create_method`: Create method in a Function Block
34
- - `compile_project`: Compile the open project
25
+ - `codesys://project/status`: Check scripting status and currently open project state.
26
+ - `codesys://project/{+project_path}/structure`: Retrieve the object structure of a specified project.
27
+ - `codesys://project/{+project_path}/pou/{+pou_path}/code`: Read the declaration and implementation code for a specified POU, Method, or Property accessor.
35
28
 
36
29
  ## 📋 Prerequisites
37
30
 
38
- - **CODESYS V3**: A working CODESYS V3 installation (tested with 3.5 SP21) with **Scripting Engine** component enabled
39
- - **Node.js**: Version 18 or later required
40
- - **MCP Client**: An MCP-enabled application (e.g., Claude Desktop)
31
+ - **CODESYS V3**: A working CODESYS V3 installation (tested with 3.5 SP21) with the **Scripting Engine** component enabled during installation.
32
+ - **Node.js**: Version 18.0.0 or later is recommended.
33
+ - **MCP Client**: An MCP-enabled application (e.g., Claude Desktop).
34
+
35
+ *(Note: CODESYS uses Python 2.7 internally for its scripting engine, but this toolkit handles the interaction; you do not need to manage Python separately.)*
41
36
 
42
37
  ## 🚀 Installation
43
38
 
44
- ### Option 1: Install from npm (Recommended)
39
+ The recommended way to install is globally using npm:
45
40
 
46
41
  ```bash
47
42
  npm install -g @codesys/mcp-toolkit
48
43
  ```
49
44
 
50
- This installs the package globally, making the `codesys-mcp-toolkit` command available in your terminal.
51
-
52
- ### Option 2: Install from Source
53
-
54
- ```bash
55
- # Clone the repository
56
- git clone https://github.com/johannesPettersson80/codesys-mcp-toolkit.git
57
- cd codesys-mcp-toolkit
58
-
59
- # Install dependencies
60
- npm install
45
+ This installs the package globally, making the `codesys-mcp-tool` command available in your system's terminal PATH.
61
46
 
62
- # Build the project
63
- npm run build
47
+ *(Advanced users can also install from source for development - see CONTRIBUTING.md if available).*
64
48
 
65
- # Install globally
66
- npm install -g .
67
- ```
49
+ ## 🔧 Configuration (IMPORTANT!)
68
50
 
69
- ## 🔧 Configuration
51
+ This toolkit needs to know where your CODESYS installation is and which profile to use. Configuration is typically done within your MCP Client application (like Claude Desktop).
70
52
 
71
- ### Claude Desktop Configuration
53
+ ### Recommended Configuration Method (Direct Command)
72
54
 
73
- 1. Locate your Claude Desktop configuration file:
74
- - Windows: `C:\Users\<YourUsername>\AppData\Roaming\Claude\claude_desktop_config.json`
55
+ Due to potential environment variable issues (especially with `PATH`) when launching Node.js tools via wrappers like `npx` within certain host applications (e.g., Claude Desktop), it is **strongly recommended** to configure your MCP client to run the installed command `codesys-mcp-tool` **directly**.
75
56
 
76
- 2. Add the CODESYS MCP server entry:
57
+ **Example for Claude Desktop (`settings.json` -> `mcpServers`):**
77
58
 
78
59
  ```json
79
60
  {
80
61
  "mcpServers": {
62
+ // ... other servers ...
81
63
  "codesys_local": {
82
- "command": "npx",
64
+ "command": "codesys-mcp-tool", // <<< Use the direct command name
83
65
  "args": [
84
- "-y",
85
- "@codesys/mcp-toolkit",
86
- "--codesys-path", "C:\\Program Files\\CODESYS 3.5.21.0\\CODESYS\\Common\\CODESYS.exe",
87
- "--codesys-profile", "CODESYS V3.5 SP21"
66
+ // Pass arguments directly to the tool using flags
67
+ "--codesys-path", "C:\\Program Files\\Path\\To\\Your\\CODESYS\\Common\\CODESYS.exe",
68
+ "--codesys-profile", "Your CODESYS Profile Name"
69
+ // Optional: Add --workspace "/path/to/your/projects" if needed
88
70
  ]
89
71
  }
72
+ // ... other servers ...
90
73
  }
91
74
  }
92
75
  ```
93
76
 
94
- 3. Customize the paths to match your CODESYS installation:
95
- - `--codesys-path`: Path to your CODESYS.exe
96
- - `--codesys-profile`: Your CODESYS profile name
97
-
98
- 4. Restart Claude Desktop to apply the changes
77
+ **Key Steps:**
78
+ 1. Replace `"C:\\Program Files\\Path\\To\\Your\\CODESYS\\Common\\CODESYS.exe"` with the **full, correct path** to your specific `CODESYS.exe` file.
79
+ 2. Replace `"Your CODESYS Profile Name"` with the **exact name** of the CODESYS profile you want to use (visible in the CODESYS UI).
80
+ 3. Ensure the `codesys-mcp-tool` command is accessible in the system PATH where the MCP Client application runs. Global installation via `npm install -g` usually handles this.
81
+ 4. Restart your MCP Client application (e.g., Claude Desktop) to apply the settings changes.
99
82
 
100
- ## 🛠️ Usage Examples
83
+ ### Alternative Configuration (Using `npx` - Not Recommended)
101
84
 
102
- ### Creating a Function Block with Properties
85
+ Launching with `npx` has been observed to cause immediate errors (`'C:\Program' is not recognized...`) in some environments, likely due to how `npx` handles the execution environment. **Use the Direct Command method above if possible.** If you must use `npx`:
103
86
 
87
+ ```json
88
+ // Example using npx (POTENTIALLY PROBLEMATIC - USE WITH CAUTION):
89
+ {
90
+ "mcpServers": {
91
+ "codesys_local": {
92
+ "command": "npx",
93
+ "args": [
94
+ "-y", // Tells npx to install temporarily if not found globally
95
+ "@codesys/mcp-toolkit",
96
+ // Arguments for the tool MUST come AFTER the package name
97
+ "--codesys-path", "C:\\Program Files\\Path\\To\\Your\\CODESYS\\Common\\CODESYS.exe",
98
+ "--codesys-profile", "Your CODESYS Profile Name"
99
+ ]
100
+ }
101
+ }
102
+ }
104
103
  ```
105
- Ask Claude: "Using the CODESYS Local server, please create a Motor Controller function block with Start and Stop methods, plus CurrentSpeed property."
106
- ```
104
+ *(Note: The `--` separator after the package name might sometimes help `npx` but is not guaranteed to fix the environment issue.)*
107
105
 
108
- Claude will execute these MCP tool calls:
109
- 1. `create_pou` to create the MotorController Function Block
110
- 2. `create_property` to add the CurrentSpeed property
111
- 3. `create_method` to add Start and Stop methods
112
- 4. `set_pou_code` to implement each method and property
106
+ ## 🛠️ Command-Line Arguments
113
107
 
114
- ### Opening and Compiling a Project
108
+ When running `codesys-mcp-tool` directly or configuring it, you can use these arguments:
115
109
 
116
- ```
117
- Ask Claude: "Can you open the project at C:/MyProjects/TestProject.project using CODESYS Local and compile it?"
118
- ```
119
-
120
- Claude will:
121
- 1. Use `open_project` to open the specified file
122
- 2. Use `compile_project` to build the application
110
+ * `-p, --codesys-path <path>`: Full path to `CODESYS.exe`. (Required, overrides `CODESYS_PATH` env var, has a default but relying on it is not recommended).
111
+ * `-f, --codesys-profile <profile>`: Name of the CODESYS profile. (Required, overrides `CODESYS_PROFILE` env var, has a default but relying on it is not recommended).
112
+ * `-w, --workspace <dir>`: Workspace directory for resolving relative project paths passed to tools. Defaults to the directory where the command was launched (which might be unpredictable when run by another application). Setting this explicitly might be needed if using relative paths.
113
+ * `-h, --help`: Show help message.
114
+ * `--version`: Show package version.
123
115
 
124
116
  ## 🔍 Troubleshooting
125
117
 
126
- ### Common Issues
118
+ * **`'C:\Program' is not recognized...` error immediately after connection:**
119
+ * **Cause:** This typically happens when the tool is launched via `npx` within an environment like Claude Desktop. The execution environment (`PATH` variable) provided to the process likely causes an internal CODESYS command (like running Python) to fail.
120
+ * **Solution:** Configure your MCP Client to run the command **directly** (`"command": "codesys-mcp-tool"`) instead of using `"command": "npx"`. See the **Recommended Configuration Method** section above.
127
121
 
128
- - **Connection Failures**: Check Claude Desktop logs for error messages
129
- - **Path Issues**: Ensure CODESYS executable path is correct
130
- - **Profile Mismatch**: Verify profile name matches exactly
131
- - **Permission Problems**: Ensure Claude has appropriate permissions
132
- - **CODESYS Already Running**: Close other CODESYS instances
122
+ * **Tool Fails / Errors in Output:**
123
+ * Check the logs from your MCP Client application (e.g., Claude Desktop logs). Look for `INTEROP:` messages or Python `DEBUG:` / `ERROR:` messages printed to stderr from the CODESYS script execution.
124
+ * Ensure the `--codesys-path` and `--codesys-profile` arguments passed to the command are correct and point to a valid CODESYS installation with scripting enabled.
125
+ * Verify the project paths and object paths you are passing to tools are correct (use forward slashes `/`).
126
+ * Make sure no other CODESYS instances are running in conflicting ways (e.g., holding a lock on the profile).
133
127
 
134
- ### Debug Logs
128
+ * **`command not found: codesys-mcp-tool`:**
129
+ * Ensure the package was installed globally (`npm install -g @codesys/mcp-toolkit`).
130
+ * Ensure the npm global bin directory is in your system's `PATH` environment variable. Find it with `npm config get prefix` and add the `bin` subdirectory (or the main directory itself on Windows) to your PATH.
135
131
 
136
- Check logs at:
137
- - Windows: `C:\Users\<YourUsername>\AppData\Roaming\Claude\logs\`
132
+ * **Check Logs:**
133
+ * Claude Desktop logs: `C:\Users\<YourUsername>\AppData\Roaming\Claude\logs\` (Windows)
138
134
 
139
135
  ## 📖 Detailed OOP Workflow Guide
140
-
141
- When creating object-oriented structures with this toolkit, follow this step-by-step workflow for best results:
142
-
143
- ### Creating Function Blocks with Properties and Methods
144
-
145
- 1. **Create the Function Block**
146
- ```
147
- create_pou(
148
- projectFilePath: "path/to/project.project",
149
- name: "PumpController",
150
- type: "FunctionBlock",
151
- language: "ST",
152
- parentPath: "Application"
153
- )
154
- ```
155
-
156
- 2. **Create Properties**
157
- ```
158
- create_property(
159
- projectFilePath: "path/to/project.project",
160
- parentPouPath: "Application/PumpController",
161
- propertyName: "SpeedSetpoint",
162
- propertyType: "INT"
163
- )
164
- ```
165
-
166
- 3. **Create Methods**
167
- ```
168
- create_method(
169
- projectFilePath: "path/to/project.project",
170
- parentPouPath: "Application/PumpController",
171
- methodName: "Start",
172
- returnType: "" // Empty for no return value
173
- )
174
- ```
175
-
176
- 4. **Implement Methods**
177
- ```
178
- set_pou_code(
179
- projectFilePath: "path/to/project.project",
180
- pouPath: "Application/PumpController/Start",
181
- implementationCode: "isRunning := TRUE;"
182
- )
183
- ```
184
-
185
- 5. **Declare Backing Variables**
186
- ```
187
- set_pou_code(
188
- projectFilePath: "path/to/project.project",
189
- pouPath: "Application/PumpController",
190
- declarationCode: "VAR PRIVATE\n _speedSetpoint : INT;\n _isRunning : BOOL;\nEND_VAR"
191
- )
192
- ```
193
-
194
- 6. **Implement Property Accessors**
195
- - For GET accessor:
196
- ```
197
- set_pou_code(
198
- projectFilePath: "path/to/project.project",
199
- pouPath: "Application/PumpController/SpeedSetpoint/Get",
200
- implementationCode: "SpeedSetpoint := _speedSetpoint;"
201
- )
202
- ```
203
- - For SET accessor:
204
- ```
205
- set_pou_code(
206
- projectFilePath: "path/to/project.project",
207
- pouPath: "Application/PumpController/SpeedSetpoint/Set",
208
- implementationCode: "_speedSetpoint := SpeedSetpoint;"
209
- )
210
- ```
211
-
212
- 7. **Save Project**
213
- ```
214
- save_project(
215
- projectFilePath: "path/to/project.project"
216
- )
217
- ```
218
-
219
- ### Important Path Usage Notes
220
-
221
- - Use forward slashes (`/`) in all object paths
222
- - Ensure paths are precise and target the specific object
223
- - For property accessors, always specify the full path including `/Get` or `/Set`
224
-
225
- ### CODESYS Naming Conventions
226
-
227
- - **POUs** (Programs, FBs, Functions): PascalCase (e.g., `MotorControl`)
228
- - **Interfaces**: PascalCase with I_ prefix (e.g., `I_AxisCommands`)
229
- - **DUTs** (Structs, Enums): PascalCase (e.g., `MachineState`, `E_OperationMode`)
230
- - **Variables**: camelCase (e.g., `motorSpeed`)
231
- - **Backing variables**: camelCase with _ prefix (e.g., `_speedSetpoint`)
232
- - **Constants**: UPPER_SNAKE_CASE (e.g., `MAX_RPM`)
233
- - **Properties & Methods**: PascalCase with descriptive names
234
-
235
- ### Recommended Property Naming
236
-
237
- - Control values: Add `Setpoint` suffix (e.g., `SpeedSetpoint`)
238
- - Measured values: Add `Actual` suffix (e.g., `TemperatureActual`)
239
- - Status indicators: Use `Is` or `Has` prefix (e.g., `IsRunning`, `HasError`)
240
- - Configuration: Use descriptive prefixes (e.g., `MaxSpeed`, `MinPressure`)
136
+ *(This section seems good, keep as is)*
137
+ ... (Paste your existing OOP Workflow Guide here) ...
241
138
 
242
139
  ## 🤝 Contributing
243
-
140
+ *(Keep as is or add details)*
244
141
  Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for details.
245
142
 
246
143
  ## 📝 License
247
-
144
+ *(Keep as is)*
248
145
  This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
249
146
 
250
147
  ## 🙏 Acknowledgements
251
-
148
+ *(Keep as is)*
252
149
  - The [CODESYS](https://www.codesys.com/) team for their scripting engine
253
150
  - [Model Context Protocol](https://github.com/m-ld/model-context-protocol) project
254
151
  - All contributors who have helped improve this toolkit
package/dist/bin.js CHANGED
@@ -4,36 +4,68 @@
4
4
  * CODESYS MCP Server CLI
5
5
  * Command-line interface for starting the CODESYS MCP server
6
6
  * with configurable CODESYS executable paths and profile names.
7
+ *
8
+ * This is the entry point for the MCP toolkit when invoked as a command-line tool.
9
+ * It handles argument parsing and passes configuration to server.ts via function parameters.
7
10
  */
8
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
+ // Use Commander for initial parsing
9
13
  const commander_1 = require("commander");
14
+ // Import the server setup function
15
+ const server_js_1 = require("./server.js"); // Adjust path if needed
16
+ console.error(">>> BIN.TS Starting <<<");
10
17
  // Define version from package.json
11
- const packageJson = require('../package.json');
12
- const version = packageJson.version;
18
+ // Use import assertion for JSON in ES modules if possible, otherwise require is okay for CommonJS
19
+ let version = 'unknown';
20
+ try {
21
+ // Assuming CommonJS based on package.json type="commonjs"
22
+ const packageJson = require('../package.json');
23
+ version = packageJson.version;
24
+ }
25
+ catch (e) {
26
+ console.error("BIN.TS: Warning - Could not read package.json for version.", e);
27
+ }
13
28
  commander_1.program
14
- .name('codesys-mcp-toolkit')
29
+ .name('codesys-mcp-tool') // Set the command name users will see
15
30
  .description('Model Context Protocol (MCP) server for CODESYS automation platform')
16
31
  .version(version)
17
- .option('-e, --codesys-path <path>', 'Path to CODESYS executable', 'C:\\Program Files\\CODESYS 3.5.21.0\\CODESYS\\Common\\CODESYS.exe')
18
- .option('-p, --codesys-profile <profile>', 'CODESYS profile name', 'CODESYS V3.5 SP21')
19
- .parse(process.argv);
32
+ .option(// Use options consistently
33
+ '-p, --codesys-path <path>', 'Path to CODESYS executable (can contain spaces, use quotes if needed)', process.env.CODESYS_PATH || 'C:\\Program Files\\CODESYS 3.5.21.0\\CODESYS\\Common\\CODESYS.exe' // Default AFTER reading env var
34
+ )
35
+ .option('-f, --codesys-profile <profile>', // Changed alias to 'f' to avoid conflict if you add other '-p' options
36
+ 'CODESYS profile name (overrides CODESYS_PROFILE env var)', process.env.CODESYS_PROFILE || 'CODESYS V3.5 SP21' // Default AFTER reading env var
37
+ )
38
+ // Add workspace option if needed, defaults to cwd
39
+ .option('-w, --workspace <dir>', 'Workspace directory for relative project paths', process.cwd() // Default to current working directory
40
+ )
41
+ .parse(process.argv); // Parse the arguments
20
42
  const options = commander_1.program.opts();
21
- // Enhanced logging for debugging purposes
43
+ // --- Log the options Commander parsed ---
22
44
  console.error(`========================================`);
23
45
  console.error(`Starting CODESYS MCP Server v${version}`);
24
- console.error(`CODESYS path: ${options.codesysPath}`);
25
- console.error(`CODESYS profile: ${options.codesysProfile}`);
26
- console.error(`Using Node.js ${process.version}`);
27
- console.error(`Current directory: ${process.cwd()}`);
46
+ console.error(`BIN.TS Options: ${JSON.stringify(options)}`);
47
+ console.error(` CODESYS Path Used: ${options.codesysPath}`);
48
+ console.error(` CODESYS Profile Used: ${options.codesysProfile}`);
49
+ console.error(` Workspace Used: ${options.workspace}`);
50
+ console.error(` Node.js: ${process.version}`);
28
51
  console.error(`========================================`);
29
- // Pass properly sanitized command line arguments
30
- const codesysPath = options.codesysPath.trim();
31
- const codesysProfile = options.codesysProfile.trim();
32
- // The server.js file expects these as positional parameters
33
- process.argv[2] = codesysPath;
34
- process.argv[3] = codesysProfile;
35
- // Also set them as environment variables as a backup mechanism
36
- process.env.CODESYS_PATH = codesysPath;
37
- process.env.CODESYS_PROFILE = codesysProfile;
38
- // Import and start the server
39
- import('./server.js');
52
+ // --- End Logging ---
53
+ // --- Prepare Config for Server ---
54
+ const serverConfig = {
55
+ codesysPath: options.codesysPath.trim(),
56
+ profileName: options.codesysProfile.trim(),
57
+ workspaceDir: options.workspace.trim() // Pass workspace dir
58
+ };
59
+ // --- End Prepare Config ---
60
+ // --- Call the server setup function ---
61
+ console.error("BIN.TS: Calling startMcpServer...");
62
+ (0, server_js_1.startMcpServer)(serverConfig)
63
+ .then(() => {
64
+ console.error("BIN.TS: startMcpServer finished (likely connected and listening).");
65
+ // Keep process alive (server handles shutdown)
66
+ })
67
+ .catch(error => {
68
+ console.error("BIN.TS: FATAL error during server startup:", error);
69
+ process.exit(1);
70
+ });
71
+ console.error(">>> BIN.TS End of synchronous execution <<<");