@codesys/mcp-toolkit 1.0.9 → 1.1.2

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,145 @@
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.
45
+ This installs the package globally, making the `codesys-mcp-tool` command available in your system's terminal PATH.
51
46
 
52
- ### Option 2: Install from Source
47
+ *(Advanced users can also install from source for development - see CONTRIBUTING.md if available).*
53
48
 
54
- ```bash
55
- # Clone the repository
56
- git clone https://github.com/johannesPettersson80/codesys-mcp-toolkit.git
57
- cd codesys-mcp-toolkit
49
+ ## 🔧 Configuration (IMPORTANT!)
58
50
 
59
- # Install dependencies
60
- npm install
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).
61
52
 
62
- # Build the project
63
- npm run build
53
+ ### Recommended Configuration Method (Direct Command)
64
54
 
65
- # Install globally
66
- npm install -g .
67
- ```
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**.
68
56
 
69
- ## 🔧 Configuration
57
+ **Example for Claude Desktop (`settings.json` -> `mcpServers`):**
58
+
59
+ ```json
60
+ {
61
+ "mcpServers": {
62
+ // ... other servers ...
63
+ "codesys_local": {
64
+ "command": "codesys-mcp-tool", // <<< Use the direct command name
65
+ "args": [
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
70
+ ]
71
+ }
72
+ // ... other servers ...
73
+ }
74
+ }
75
+ ```
70
76
 
71
- ### Claude Desktop Configuration
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.
72
82
 
73
- 1. Locate your Claude Desktop configuration file:
74
- - Windows: `C:\Users\<YourUsername>\AppData\Roaming\Claude\claude_desktop_config.json`
83
+ ### Alternative Configuration (Using `npx` - Not Recommended)
75
84
 
76
- 2. Add the CODESYS MCP server entry:
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`:
77
86
 
78
87
  ```json
88
+ // Example using npx (POTENTIALLY PROBLEMATIC - USE WITH CAUTION):
79
89
  {
80
90
  "mcpServers": {
81
91
  "codesys_local": {
82
92
  "command": "npx",
83
93
  "args": [
84
- "-y",
94
+ "-y", // Tells npx to install temporarily if not found globally
85
95
  "@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"
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"
88
99
  ]
89
100
  }
90
101
  }
91
102
  }
92
103
  ```
104
+ *(Note: The `--` separator after the package name might sometimes help `npx` but is not guaranteed to fix the environment issue.)*
93
105
 
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
99
-
100
- ## 🛠️ Usage Examples
106
+ ## 🛠️ Command-Line Arguments
101
107
 
102
- ### Creating a Function Block with Properties
103
-
104
- ```
105
- Ask Claude: "Using the CODESYS Local server, please create a Motor Controller function block with Start and Stop methods, plus CurrentSpeed property."
106
- ```
108
+ When running `codesys-mcp-tool` directly or configuring it, you can use these arguments:
107
109
 
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
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.
113
115
 
114
- ### Opening and Compiling a Project
116
+ ## 🔍 Troubleshooting
115
117
 
116
- ```
117
- Ask Claude: "Can you open the project at C:/MyProjects/TestProject.project using CODESYS Local and compile it?"
118
- ```
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.
119
121
 
120
- Claude will:
121
- 1. Use `open_project` to open the specified file
122
- 2. Use `compile_project` to build the application
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).
123
127
 
124
- ## 🔍 Troubleshooting
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.
125
131
 
126
- ### Common Issues
127
-
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
133
-
134
- ### Debug Logs
135
-
136
- Check logs at:
137
- - Windows: `C:\Users\<YourUsername>\AppData\Roaming\Claude\logs\`
138
-
139
- ## 📖 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`)
132
+ * **Check Logs:**
133
+ * Claude Desktop logs: `C:\Users\<YourUsername>\AppData\Roaming\Claude\logs\` (Windows)
241
134
 
242
135
  ## 🤝 Contributing
243
-
244
- Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for details.
136
+ Contributions, issues, and feature requests are welcome! Feel free to check the issues page. (Optionally add a CONTRIBUTING.md file with more details).
245
137
 
246
138
  ## 📝 License
247
-
248
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
139
+ This project is licensed under the MIT License - see the LICENSE file for details.
249
140
 
250
141
  ## 🙏 Acknowledgements
142
+ - The CODESYS GmbH team for the powerful CODESYS platform and its scripting engine.
143
+ - The Model Context Protocol project for defining the interaction standard.
144
+ - All contributors and users who help improve this toolkit.
251
145
 
252
- - The [CODESYS](https://www.codesys.com/) team for their scripting engine
253
- - [Model Context Protocol](https://github.com/m-ld/model-context-protocol) project
254
- - 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 <<<");