Skip to content
Back to search

Codesys-MCP

An MCP server for Codesys that enables AI systems to stand up a live UI where they can edit/push code and view variables live on device.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/luke-harriman--codesys-mcp/badge.svg)](/listings/luke-harriman--codesys-mcp)

HTML

<a href="/listings/luke-harriman--codesys-mcp"><img src="/api/listings/luke-harriman--codesys-mcp/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

git clone <repository-url>
cd Codesys-MCP
npm install
npm run build
npm link

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 235 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # codesys-mcp-persistent
  2. MCP server that exposes the CODESYS V3.5 IDE scripting API as 41 tools and 3 resources, with the CODESYS UI kept open across calls via a file-based IPC watcher.
  3. Unlike headless-only wrappers that spawn a new `--noUI` CODESYS process per command, this server launches CODESYS with its UI visible and routes every tool call through a watcher script running inside that same instance. Changes appear in the IDE in real time and the user can interact with CODESYS alongside AI-driven automation.
  4. ## Requirements
  5. - Windows
  6. - Node.js 18+
  7. - CODESYS V3.5 **SP19 or SP20** for persistent mode. **SP21+ runs only in headless mode** — see [Known limitations](#known-limitations).
  8. ## Install
  9. ```bash
  10. git clone <repository-url>
  11. cd Codesys-MCP
  12. npm install
  13. npm run build
  14. npm link
  15. ```
  16. ## Configure
  17. `.mcp.json` (Claude Code):
  18. ```json
  19. {
  20. "mcpServers": {
  21. "codesys": {
  22. "command": "codesys-mcp-persistent",
  23. "args": [
  24. "--codesys-path", "C:\\Program Files\\CODESYS 3.5.20.0\\CODESYS\\Common\\CODESYS.exe",
  25. "--codesys-profile", "CODESYS V3.5 SP20",
  26. "--mode", "persistent"
  27. ]
  28. }
  29. }
  30. }
  31. ```
  32. For SP21+, set `--mode headless` (each tool call spawns a `--noUI` CODESYS process).
  33. ## CLI
  34. | Flag | Description | Default |
  35. |---|---|---|
  36. | `-p, --codesys-path <path>` | Path to `CODESYS.exe` | `$CODESYS_PATH` or `C:\Program Files\CODESYS 3.5.21.0\CODESYS\Common\CODESYS.exe` |
  37. | `-f, --codesys-profile <name>` | CODESYS profile name | `$CODESYS_PROFILE` or `CODESYS V3.5 SP21` |
  38. | `-w, --workspace <dir>` | Workspace for relative paths | cwd |
  39. | `-m, --mode <mode>` | `persistent` or `headless` | `persistent` |
  40. | `--no-auto-launch` | Don't launch CODESYS on startup | auto-launch on |
  41. | `--fallback-headless` | Fall back to headless if persistent launch fails | `true` |
  42. | `--keep-alive` | Keep CODESYS running after server stops | `false` |
  43. | `--kill-existing-codesys` | Kill any running `CODESYS.exe` before launching | `false` |
  44. | `--timeout <ms>` | Default command timeout | `60000` |
  45. | `--detect` | List installed CODESYS versions and exit | - |
  46. | `--verbose` / `--debug` | Logging | - |
  47. Environment variables:
  48. - `CODESYS_PATH`, `CODESYS_PROFILE` — defaults for the corresponding flags
  49. - `CODESYS_MCP_READY_TIMEOUT_MS` — watcher-ready deadline (default `180000`)
  50. ## Tools
  51. ### Management
  52. | Tool | Description |
  53. |---|---|
  54. | `launch_codesys` | Manually launch CODESYS (use with `--no-auto-launch`). Adopts a live session if one exists |
  55. | `shutdown_codesys` | Shut down the persistent CODESYS instance |
  56. | `get_codesys_status` | Report state, PID, execution mode |
  57. | `eval_python` | **[DEV]** Execute arbitrary IronPython 2.7 against the live `scriptengine`. Code must `print("SCRIPT_SUCCESS")` before exit |
  58. ### Project
  59. | Tool | Description |
  60. |---|---|
  61. | `open_project` | Open an existing `.project` file |
  62. | `create_project` | Create a new project. Defaults to copying CODESYS's installed `Standard.project`; pass `templatePath` to copy a specific `.project`, or `templateName` to instantiate a template registered with CODESYS's Template Manager |
  63. | `list_project_templates` | Enumerate templates from CODESYS's Template Manager and `%ProgramData%/CODESYS` |
  64. | `save_project` | Save the currently open project |
  65. | `compile_project` | Build with structured error output (120s timeout) |
  66. | `get_compile_messages` | Retrieve last compiler messages without rebuilding |
  67. ### POU / code authoring
  68. | Tool | Description |
  69. |---|---|
  70. | `create_pou` | Create a Program, Function Block, or Function |
  71. | `set_pou_code` | Set declaration and/or implementation. Accepts Method/Property paths (`Application/MyFB/Method1`). Auto-saves to disk |
  72. | `create_property` / `create_method` | Add a Property / Method to a Function Block |
  73. | `create_dut` | Create a Data Unit Type (Structure, Enumeration, Union, Alias) |
  74. | `create_gvl` | Create a Global Variable List, optionally with initial declaration |
  75. | `create_folder` | Create an organisational folder |
  76. | `delete_object` | Delete a user-created object. Refuses system nodes (`Application`, `Device`, `Library Manager`, etc.) and top-level paths |
  77. | `rename_object` | Rename any project object |
  78. | `get_all_pou_code` | Bulk read every declaration + implementation in the project (120s timeout) |
  79. | `search_code` | Regex or literal substring search across every textual POU/Method/Property/DUT/GVL body |
  80. | `find_references` | Word-boundary search for a symbol; wraps `search_code` |
  81. | `rename_symbol` | Textual rename across all POU bodies. Two-phase plan + apply; `dryRun=true` by default |
  82. ### Online / runtime
  83. | Tool | Description |
  84. |---|---|
  85. | `connect_to_device` | Login to the PLC runtime. Optionally pass `ipAddress` (and `gatewayName`, default `Gateway-1`); the device address is set then re-resolved from IP form to the gateway-scan node form before login |
  86. | `disconnect_from_device` | Logout. No-op if not connected |
  87. | `set_credentials` | Set default username/password for subsequent logins. Username must be non-empty |
  88. | `set_simulation_mode` | Toggle device-level simulation mode |
  89. | `get_application_state` | Report run / stop / exception plus login status |
  90. | `read_variable` | Read a live variable. Path: `GVL.var` / `PRG.var` / `GVL.s.aRoi[0].field` (no `Application.` prefix) |
  91. | `write_variable` | Write via `set_prepared_value` + `force_prepared_values`. The variable is FORCED until unforced or runtime restart |
  92. | `download_to_device` | Download compiled application. `mode`: `auto` (default), `online_change`, or `full`. Boot application created after login. 120s timeout |
  93. | `start_stop_application` | Start or stop the PLC application |
  94. | `monitor_variables` | Sample one or more variables at a fixed interval. Duration capped at 60s, `intervalMs` floor 10ms |
  95. Online tools route every `scriptengine.online` call through an `ExecuteSource` frame via the `with_executor` helper in `ensure_online_connection.py`. Without it, `create_online_application` raises `InvalidOperationException: Stack empty` from IPC-driven scripts on real PLCs.
  96. ### Library management
  97. | Tool | Description |
  98. |---|---|
  99. | `list_project_libraries` | List referenced libraries with version info |
  100. | `add_library` | Add a library reference. Pass the fully-qualified placeholder string from the Library Manager UI (e.g. `Standard, * (System)`) — bare names like `Util` won't resolve |
  101. ### Device tree
  102. | Tool | Description |
  103. |---|---|
  104. | `list_device_repository` | Enumerate device descriptors in the local CODESYS Device Repository. Optional `vendor`, `nameContains`, `maxResults` filters |
  105. | `inspect_device_node` | Read-only introspection of a device node: descriptor metadata, parameters with values, child sub-devices |
  106. | `add_device` | Wrap `parent.add_device(name, type, id, version)`. Pair with `list_device_repository` to source canonical ids |
  107. | `set_device_parameter` | EXPERIMENTAL. Many fieldbus parameters are GUI-only and return a clear error |
  108. | `map_io_channel` | Bind (or clear) a fieldbus I/O channel to a global variable. Channel resolved by name path (`Inputs/Byte 0/Bit 3`) or numeric indices (`0/3`) |
  109. ### Archiving
  110. | Tool | Description |
  111. |---|---|
  112. | `create_project_archive` | Save the open project as a `.projectarchive`. Saves unsaved edits first |
  113. ## Resources
  114. | URI | Description |
  115. |---|---|
  116. | `codesys://project/status` | Scripting status and open-project info |
  117. | `codesys://project/{path}/structure` | Project tree |
  118. | `codesys://project/{path}/pou/{pou}/code` | POU / Method / Property declaration + implementation |
  119. `{path}` and `{pou}` use [RFC 6570 reserved expansion](https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.3) — pass values with raw `:` and `/`, **not** percent-encoded. On Windows, use forward slashes:
  120. ```
  121. codesys://project/C:/Users/me/Documents/MyPLC.project/structure
  122. codesys://project/C:/Users/me/Documents/MyPLC.project/pou/Application/MyFB/Method1/code
  123. ```
  124. > The two templated resources don't appear in `ListMcpResourcesTool` (only `project-status` is static).
  125. >
  126. > ⚠️ If the requested project path differs from the currently-open project, the resource handler refuses to switch — it raises rather than silently swapping context.
  127. ## Execution modes
  128. **Persistent (default).** On launch, the server scans `%TEMP%/codesys-mcp-persistent/` for a live session left by a previous MCP server (matching profile, PID alive, `ready.signal` present) and adopts it. Otherwise it spawns `CODESYS.exe --runscript=watcher.py` (no `--noUI`). The watcher writes `ready.signal`, then runs a background thread that polls a `commands/` directory and marshals each script onto the CODESYS UI thread via `system.execute_on_primary_thread()`. Results land in `results/`; Node polls with exponential backoff (100ms → 1s). The UI stays interactive between commands and pauses briefly during synchronous API calls (compile, open).
  129. **Headless.** Each tool call spawns a new `--noUI` CODESYS process, runs the script, and exits. No UI. Used when `--mode headless` is set, when `--no-auto-launch` is used and `launch_codesys` hasn't been called, or when persistent launch fails and `--fallback-headless` is on.
  130. ## Detect installations
  131. ```bash
  132. codesys-mcp-persistent --detect
  133. ```
  134. Scans `Program Files` and `Program Files (x86)` for CODESYS installations.
  135. ## Known limitations
  136. - **Persistent mode is broken on CODESYS V3.5 SP21+.** CODESYS removed `se.system.execute_on_primary_thread()` from the scripting API somewhere in the SP21 line. Persistent launch completes (`ready.signal` fires) and then every tool call returns `Marshal error: The functionality 'system.execute_on_primary_thread(...)' is no longer supported`. `--fallback-headless` is launch-time only and does not catch this. Workarounds: (a) run with `--mode headless`; (b) use the forward-port at [phobicdotno/Codesys-MCP-SP21-plus](https://github.com/phobicdotno/Codesys-MCP-SP21-plus). SP19/SP20 are unaffected.
  137. - **`set_pou_code` auto-saves to disk** every successful call. UI Ctrl+Z does NOT recover prior content.
  138. - **`set_pou_code` empty string is a no-op.** Passing `declarationCode: ""` or `implementationCode: ""` leaves the section unchanged. To clear a section, pass a single-line placeholder (e.g. `// cleared`).
  139. - **`delete_object` refuses system nodes and any top-level object** (no `/`). System-reserved exact paths: `Application`, `Device`, `Project Settings`, `Device/Plc Logic`, `Application/Library Manager`, `Application/Task Configuration`, `Application/Task Configuration/MainTask`, `Device/Communication`, `Device/Communication/Ethernet`, `Device/SoftMotion General Axis Pool` (and the `Device/Plc Logic/...` variants).
  140. - **`set_credentials` rejects empty usernames.** For no-auth runtimes, do not call this tool at all.
  141. - **`add_library` requires a fully-qualified placeholder** matching the Library Manager UI string (e.g. `Standard, * (System)`). Bare names fail with `placeholder library X could not be resolved`.
  142. - **DUT names containing `.` are rejected by CODESYS** (`The name 'X.Y' is not valid for this object`).
  143. - **Identifier length isn't enforced at create time.** CODESYS only complains at compile/save. Stick to ≤32-char IEC identifiers.
  144. - **`find_object_by_path` refuses ambiguous matches** and returns `None`. Pass a more specific path.
  145. - **`is_simulation_mode` getter returns `None`** on some device descriptors. The setter works; verify via compile + login.
  146. ## Troubleshooting
  147. **CODESYS not found** — verify with `--detect`. Executable is typically at `C:\Program Files\CODESYS 3.5.XX.X\CODESYS\Common\CODESYS.exe`.
  148. **Every tool call returns `Marshal error: ... is no longer supported`** — you're on SP21+. Restart with `--mode headless`.
  149. **Watcher timeout** — default is 180s. Cold first launches of older SPs can exceed the older 60s budget. Bump further on slow hardware: `CODESYS_MCP_READY_TIMEOUT_MS=300000`. If CODESYS is still coming up, just call `launch_codesys` again — the launcher will re-attach to the live PID rather than spawning a second instance.
  150. **Command timeout** — default 60s; `compile_project`, `get_all_pou_code`, and `download_to_device` use 120s. Increase with `--timeout <ms>`.
  151. **Project file locked across MCP restarts** — the launcher adopts a live session from the prior server on startup. If you still hit `StandardError: The selected project is currently in use`, kill the orphan `CODESYS.exe` via Task Manager, or pass `--kill-existing-codesys` on next launch (off by default to protect external IDE sessions).
  152. **Online tools fail** — they require a device/gateway configured (or `connect_to_device(ipAddress=...)`, or `set_simulation_mode(enable=true)`), a successful compile, and a reachable PLC.
  153. **`Network error: No route to host` from `connect_to_device`** even though `ping` works — V3 login routes by the gateway-scan node address (e.g. `0301.B0F7`), not by the IP-encoded form (`0192.0168.0083.0247`) that `set_gateway_and_address` stores from a raw IP. `connect_to_device` re-scans and re-sets the address before login; if it still fails, the gateway-to-runtime port (TCP 11740 by default) is probably blocked.
  154. ## Development
  155. ```bash
  156. npm install
  157. npm run build # tsc + copy src/scripts/ -> dist/scripts/
  158. npm test
  159. npm run typecheck
  160. pwsh dev/check-scripts.ps1 # ASCII + template-reference static checks
  161. ```
  162. Project layout:
  163. ```
  164. src/
  165. bin.ts CLI entry point
  166. server.ts MCP tool / resource registration
  167. launcher.ts CODESYS process management + session adoption
  168. ipc.ts File-based IPC transport
  169. headless.ts Headless fallback executor
  170. script-manager.ts Python template loading + interpolation
  171. executor-proxy.ts Race-free executor swap during background auto-launch
  172. result-parser.ts RESULT_JSON marker extraction
  173. scripts/ IronPython 2.7 watcher + helpers + tool scripts
  174. tests/
  175. unit/ IPC, script manager, launcher
  176. integration/ Script pipeline + manual CODESYS tests
  177. ```
  178. ## License
  179. MIT

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.