Update .gitignore and README.md for CODESYS MCP project. Added entries to .gitignore for VSIX files and VS Code settings. Expanded README to include architecture, components, deployment instructions, and details about the Cursor extension.

This commit is contained in:
2026-05-24 15:47:21 +03:00
parent acdd740d01
commit bedc5d0628
55 changed files with 11120 additions and 3 deletions

4
.gitignore vendored
View File

@@ -8,3 +8,7 @@ dist/
build/
.venv/
venv/
*.vsix
.vscode/settings.json
vscode_codesys_companion/node_modules/
vscode_codesys_companion/out/

5
.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,5 @@
{
"recommendations": [
"nearxos.codesys-mcp-companion"
]
}

9
.vscode/settings.json.example vendored Normal file
View File

@@ -0,0 +1,9 @@
{
"codesys.pythonPath": "/Users/nearxos/Project/Codesys MCP/.venv/bin/python",
"codesys.bridgeScriptPath": "/Users/nearxos/Project/Codesys MCP/python_scripting/mcp_codesys_bridge/server.py",
"codesys.agentUrl": "http://10.211.55.3:8787",
"codesys.agentToken": "REPLACE_WITH_TOKEN",
"codesys.requestTimeoutSec": 60,
"codesys.defaultDryRunMutations": true,
"codesys.allowDownloadCommand": false
}

View File

@@ -1,7 +1,92 @@
# Codesys MCP
MCP server for CODESYS integration.
MCP bridge for working on CODESYS projects from Cursor, backed by a Windows agent in Parallels.
## Status
## Architecture
Initial project setup.
```
Cursor (Mac) → MCP bridge (FastMCP) → Windows agent (FastAPI :8787) → CODESYS ScriptEngine
```
## Components
| Path | Role |
|------|------|
| `python_scripting/mcp_codesys_bridge/` | MCP server for Cursor |
| `python_scripting/windows_codesys_agent/` | Windows job API + ScriptEngine scripts |
| `vscode_codesys_companion/` | Cursor/VS Code extension (UI, ST syntax, commands) |
| `deploy/windows/start-agent.bat.example` | Windows agent startup template |
| `deploy/cursor/mcp.json.example` | Cursor MCP config template |
## Deployment (Parallels)
### Windows VM
1. Copy `python_scripting/windows_codesys_agent/` to `C:\codesys-agent\`
2. Install Python 3.12 ARM64 and create venv: `python -m venv C:\codesys-agent\.venv`
3. `pip install -r requirements.txt`
4. Copy `deploy/windows/start-agent.bat.example``C:\codesys-agent\start-agent.bat` and set `CODESYS_AGENT_TOKEN`
5. Run `C:\codesys-agent\start-agent.bat` (listens on `0.0.0.0:8787`)
Current VM: **Windows 11** at `10.211.55.3` (Parallels shared network).
### Mac (Cursor)
1. `python3 -m venv .venv && .venv/bin/pip install -r python_scripting/mcp_codesys_bridge/requirements.txt`
2. Add MCP server config to `~/.cursor/mcp.json` (see `deploy/cursor/mcp.json.example`)
3. Restart Cursor / reload MCP servers
## Cursor extension (CODESYS MCP Companion)
The companion extension adds a **CODESYS sidebar**, command palette actions, ST syntax highlighting, and job polling UI — alongside the MCP tools used by the AI in chat.
### Install
```bash
cd vscode_codesys_companion
npm install && npm run compile && npm run package
cursor --install-extension codesys-mcp-companion-0.1.0.vsix
```
Or from Cursor: **Extensions → … → Install from VSIX** and select the `.vsix` file.
### Configure
Copy `.vscode/settings.json.example` to `.vscode/settings.json` (or set **Settings → CODESYS MCP Companion**):
- `codesys.agentUrl``http://10.211.55.3:8787`
- `codesys.agentToken` → same token as the Windows agent
- `codesys.pythonPath` → project `.venv/bin/python`
- `codesys.bridgeScriptPath` → path to `mcp_codesys_bridge/server.py`
Reload Cursor, then run **CODESYS: Connect MCP Bridge** and **CODESYS: Health Check**.
### Extension vs MCP server
| Feature | Cursor MCP (`~/.cursor/mcp.json`) | Companion extension |
|---------|-----------------------------------|---------------------|
| AI chat tools | Yes | No |
| Sidebar (Projects/Jobs/Actions) | No | Yes |
| ST syntax + snippets | No | Yes |
| Command palette workflows | No | Yes |
| Sync current `.st` file | No | Yes |
Both can run together; the extension spawns its own bridge process when you connect.
## Smoke tests
```bash
curl http://10.211.55.3:8787/health
```
Use MCP tools `codesys_health`, `create_project` (dry_run), `read_project_inventory`.
**Note:** Project paths on Parallels shared folders (`C:\Mac\Home\...` / OneDrive) may fail when the agent runs as SYSTEM. Use native Windows paths like `C:\Temp\codesys-tests\` for reliable ScriptEngine access.
## Docs
See `python_scripting/how-to-use-codesys-mcp.md` and `python_scripting/codesys-mcp-bridge-operations.md`.
## Origin
Ported from [codesys-mcp-agent](https://git.paraskeva.net/nearxos/codesys-mcp-agent).

View File

@@ -0,0 +1,15 @@
{
"mcpServers": {
"codesys-bridge": {
"command": "/Users/nearxos/Project/Codesys MCP/.venv/bin/python",
"args": [
"/Users/nearxos/Project/Codesys MCP/python_scripting/mcp_codesys_bridge/server.py"
],
"env": {
"CODESYS_AGENT_URL": "http://10.211.55.3:8787",
"CODESYS_AGENT_TOKEN": "REPLACE_WITH_TOKEN",
"CODESYS_AGENT_REQUEST_TIMEOUT_SEC": "60"
}
}
}
}

View File

@@ -0,0 +1,17 @@
@echo off
setlocal
cd /d C:\codesys-agent
rem Copy to start-agent.bat and set your token locally (do not commit).
set CODESYS_AGENT_TOKEN=REPLACE_WITH_TOKEN
set CODESYS_AGENT_SCRIPTS_DIR=C:\codesys-agent\scripts
set CODESYS_AGENT_RUNTIME_DIR=C:\codesys-agent\runtime
set CODESYS_AGENT_PYTHON_BIN=C:\Program Files\Python312-arm64\python.exe
set CODESYS_AGENT_ALLOW_DOWNLOAD=false
set CODESYS_EXE_PATH=C:\Program Files\CODESYS 3.5.22.10\CODESYS\Common\CODESYS.exe
set CODESYS_PROFILE=CODESYS V3.5 SP22 Patch 1
set CODESYS_NO_UI=true
if not exist C:\codesys-agent\runtime mkdir C:\codesys-agent\runtime
C:\codesys-agent\.venv\Scripts\uvicorn.exe agent:app --host 0.0.0.0 --port 8787

11
package.json Normal file
View File

@@ -0,0 +1,11 @@
{
"name": "codesys-mcp-workspace",
"private": true,
"description": "CODESYS MCP workspace root",
"scripts": {
"compile:extension": "npm run compile --prefix vscode_codesys_companion",
"watch:extension": "npm run watch --prefix vscode_codesys_companion",
"package:extension": "npm run package --prefix vscode_codesys_companion",
"check:extension": "npm run check --prefix vscode_codesys_companion"
}
}

View File

@@ -0,0 +1,19 @@
# Python Scripting in CODESYS
This folder contains practical documentation for using Python scripting with the CODESYS IDE.
## Files
- `setup-in-codesys-ide.md` - step-by-step setup and verification in the IDE
- `what-you-can-do.md` - real use cases, limits, and automation ideas
- `mcp_codesys_bridge/` - Linux MCP server for Cursor
- `windows_codesys_agent/` - Windows VM service that executes CODESYS actions
- `codesys-mcp-bridge-operations.md` - deployment, security, and smoke-test guide
- `how-to-use-codesys-mcp.md` - day-to-day usage, workflow, and FAQ
## Quick Start
1. Open `setup-in-codesys-ide.md` and complete the environment setup.
2. Run the small validation script from the guide.
3. Use `what-you-can-do.md` to choose your first automation workflow.
4. Follow `codesys-mcp-bridge-operations.md` to deploy MCP + VM agent bridge.

View File

@@ -0,0 +1,115 @@
# CODESYS MCP Bridge Operations Guide
This guide covers deployment, security, and smoke tests for the recommended architecture.
## 1) Components
- Linux: `mcp_codesys_bridge/server.py` (MCP server for Cursor)
- Windows VM: `windows_codesys_agent/agent.py` (job API)
- Windows VM scripts: `windows_codesys_agent/scripts/*.py`
ScriptEngine actions (`create_project`, `read_project_inventory`, `build_project`, `download_to_device`) are executed by launching `CODESYS.exe --runscript --noUI` from the agent.
## 2) Deployment Steps
1. Copy `windows_codesys_agent` to the Windows VM.
2. Install dependencies and start the agent on port `8787`.
3. Open firewall only to trusted Linux host IP.
4. Configure Linux MCP server with `CODESYS_AGENT_URL` and `CODESYS_AGENT_TOKEN`.
5. Register MCP server in Cursor settings and restart Cursor.
## 3) Security Checklist
- Use a long random `CODESYS_AGENT_TOKEN`.
- Restrict inbound access by firewall rules.
- Keep `CODESYS_AGENT_ALLOW_DOWNLOAD=false` until testing completes.
- Use dry-run for all mutating calls first.
- Rotate token after initial setup validation.
## 4) Smoke Tests
## 4.1 Health check
Call MCP tool:
- `codesys_health`
Expected:
- `ok: true`
- correct `scripts_dir`
## 4.2 Submit dry-run create project
Call MCP tool:
- `create_project`
- `project_name`: `SmokeTest`
- `output_dir`: `C:\\Temp\\codesys-tests`
- `dry_run`: `true`
Expected:
- returns `job_id`
- job transitions `queued -> running -> succeeded`
## 4.3 Poll job result
Call MCP tool:
- `codesys_get_job` with returned `job_id`
Expected:
- final `status: succeeded`
- `result.dry_run: true`
## 4.4 Run one safe write artifact action
Call MCP tool:
- `write_pou` with test content and `dry_run=false`
Expected:
- `artifact_file` created under `_mcp_generated` near project path.
## 4.5 Read existing project
If your existing project is scattered in an old location, stage it first:
Call MCP tool:
- `stage_existing_project`
- `source_path`: `C:\\Users\\nearxos\\OneDrive - individual\\Codesys_Home_Automation`
- `projects_root_dir`: `C:\\Users\\nearxos\\OneDrive - individual\\Codesys_Projects`
- `project_folder_name`: `Home_Automation` (optional)
- `move`: `false` (copy by default)
- `overwrite`: `false`
Expected:
- returns `job_id`
- result contains `project_folder` and resolved staged `project_path`
Then read inventory:
Call MCP tool:
- `read_project_inventory`
- `project_path`: `C:\\path\\to\\project.project` (or `.projectarchive`, or a folder with one project file)
- `max_depth`: `3`
Expected:
- `node_count > 0`
- tree entries in `nodes[]`
## 5) Enabling download to device
Only after successful smoke tests:
1. Set `CODESYS_AGENT_ALLOW_DOWNLOAD=true` on VM.
2. Restart agent service.
3. Run download tool in dry-run first, then actual run.
4. Verify target routing, credentials, and safety state before start.

View File

@@ -0,0 +1,142 @@
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import base64
import pathlib
import sys
from typing import Iterable
import winrm
def run_ps(session: winrm.Session, script: str) -> str:
result = session.run_ps(script)
stdout = result.std_out.decode("utf-8", errors="ignore").strip()
stderr = result.std_err.decode("utf-8", errors="ignore").strip()
if result.status_code != 0:
raise RuntimeError(f"PowerShell failed ({result.status_code}): {stderr or stdout}")
return stdout
def upload_file(session: winrm.Session, local_path: pathlib.Path, remote_path: str) -> None:
data_b64 = base64.b64encode(local_path.read_bytes()).decode("ascii")
temp_b64_path = remote_path + ".b64tmp"
# WinRM command payloads can be short; use conservative chunking.
chunk_size = 500
run_ps(
session,
(
f"$p='{remote_path}';"
"$d=Split-Path -Parent $p;"
"New-Item -ItemType Directory -Force -Path $d | Out-Null;"
f"[System.IO.File]::WriteAllText('{temp_b64_path}','');"
"Write-Output 'ready'"
),
)
for i in range(0, len(data_b64), chunk_size):
chunk = data_b64[i : i + chunk_size]
run_ps(
session,
f"Add-Content -Path '{temp_b64_path}' -Value '{chunk}' -NoNewline",
)
ps_finalize = (
f"$b64=[System.IO.File]::ReadAllText('{temp_b64_path}');"
f"[System.IO.File]::WriteAllBytes('{remote_path}',[Convert]::FromBase64String($b64));"
f"Remove-Item -Path '{temp_b64_path}' -Force;"
f"Write-Output ('uploaded:' + '{remote_path}')"
)
print(run_ps(session, ps_finalize))
def iter_agent_files(root: pathlib.Path) -> Iterable[pathlib.Path]:
for p in sorted(root.rglob("*")):
if p.is_file():
yield p
def main() -> int:
parser = argparse.ArgumentParser(description="Deploy Windows CODESYS agent via WinRM.")
parser.add_argument("--host", required=True)
parser.add_argument("--username", required=True)
parser.add_argument("--password", required=True)
parser.add_argument("--token", required=True)
parser.add_argument("--install-path", default=r"C:\codesys-agent")
parser.add_argument("--codesys-exe-path", required=True)
parser.add_argument("--codesys-profile", required=True)
args = parser.parse_args()
session = winrm.Session(
target=f"http://{args.host}:5985/wsman",
auth=(args.username, args.password),
transport="ntlm",
server_cert_validation="ignore",
)
print("Connected, checking identity...")
whoami = run_ps(session, "whoami")
print(f"Remote identity: {whoami}")
local_root = pathlib.Path(__file__).resolve().parent / "windows_codesys_agent"
if not local_root.is_dir():
raise RuntimeError(f"Local folder not found: {local_root}")
remote_root = args.install_path.rstrip("\\") + r"\windows_codesys_agent"
for f in iter_agent_files(local_root):
rel = f.relative_to(local_root).as_posix().replace("/", "\\")
remote_path = remote_root + "\\" + rel
upload_file(session, f, remote_path)
scripts_dir = remote_root + r"\scripts"
runtime_dir = args.install_path.rstrip("\\") + r"\runtime"
run_script_path = remote_root + r"\run-agent.ps1"
run_script = (
f"$env:CODESYS_AGENT_TOKEN = '{args.token}'\n"
f"$env:CODESYS_AGENT_SCRIPTS_DIR = '{scripts_dir}'\n"
f"$env:CODESYS_AGENT_RUNTIME_DIR = '{runtime_dir}'\n"
"$env:CODESYS_AGENT_ALLOW_DOWNLOAD = 'false'\n"
"$env:CODESYS_AGENT_TIMEOUT_SEC = '180'\n"
f"$env:CODESYS_EXE_PATH = '{args.codesys_exe_path}'\n"
f"$env:CODESYS_PROFILE = '{args.codesys_profile}'\n"
"$env:CODESYS_NO_UI = 'true'\n"
"$env:CODESYS_SCRIPT_TIMEOUT_SEC = '600'\n"
"Set-Location -Path $PSScriptRoot\n"
".\\.venv\\Scripts\\python.exe -m uvicorn agent:app --host 0.0.0.0 --port 8787\n"
)
run_b64 = base64.b64encode(run_script.encode("utf-8")).decode("ascii")
run_ps(
session,
(
f"$p='{run_script_path}';"
f"[System.IO.File]::WriteAllBytes($p,[Convert]::FromBase64String('{run_b64}'));"
"Write-Output ('uploaded:' + $p)"
),
)
setup_ps = (
f"Set-Location -Path '{remote_root}';"
"if (Get-Command py -ErrorAction SilentlyContinue) { py -3 -m venv .venv } "
"elseif (Get-Command python -ErrorAction SilentlyContinue) { python -m venv .venv } "
"else { throw 'Python is not installed on the Windows VM.' };"
".\\.venv\\Scripts\\python.exe -m pip install -r requirements.txt;"
"Get-Process -Name python -ErrorAction SilentlyContinue | "
"Where-Object { $_.Path -like '*windows_codesys_agent*' } | Stop-Process -Force -ErrorAction SilentlyContinue;"
"Start-Process -FilePath powershell.exe "
f"-ArgumentList '-ExecutionPolicy Bypass -File \"{run_script_path}\"' "
"-WindowStyle Hidden;"
"Write-Output 'agent-started'"
)
print(run_ps(session, setup_ps))
print(f"Deployment complete. Agent expected at: http://{args.host}:8787/health")
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except Exception as exc:
print(f"ERROR: {exc}", file=sys.stderr)
raise

View File

@@ -0,0 +1,156 @@
# How To Use CODESYS MCP Bridge
This guide explains day-to-day usage of your CODESYS MCP bridge from Cursor.
## 1) Confirm prerequisites
- Windows VM agent is running on port `8787`
- Linux host can reach VM IP
- Same token is configured on both sides:
- VM: `CODESYS_AGENT_TOKEN`
- Cursor MCP config: `CODESYS_AGENT_TOKEN`
- **CODESYS IDE must be closed** for write operations (read operations work even with IDE open)
Quick connectivity check from Linux:
```bash
curl http://10.77.30.50:8787/health
```
## 2) Cursor MCP config (working example)
Update `~/.cursor/mcp.json`:
```json
{
"mcpServers": {
"codesys-bridge": {
"command": "/home/nearxos/Projects/.venvs/winrm/bin/python",
"args": [
"/home/nearxos/Projects/gitea/codesys-mcp-agent/python_scripting/mcp_codesys_bridge/server.py"
],
"env": {
"CODESYS_AGENT_URL": "http://10.77.30.50:8787",
"CODESYS_AGENT_TOKEN": "<your-token>",
"CODESYS_AGENT_REQUEST_TIMEOUT_SEC": "30"
}
}
}
}
```
Reload MCP servers or restart Cursor after editing.
## 3) Available MCP tools
### Reading (works even with IDE open)
| Tool | Purpose |
|------|---------|
| `codesys_health` | Check VM agent status |
| `codesys_get_job` | Poll job status/result by ID |
| `read_project_inventory` | Read project tree + textual sources (POUs, GVLs, NVLs, structs) |
| `read_device_io` | Read device tree, I/O channels, variable mappings |
### Writing (requires CODESYS IDE to be closed)
| Tool | Purpose |
|------|---------|
| `write_pou` | Update single or batch textual objects (declaration + implementation) |
| `write_io_mapping` | Map IEC variables to device I/O channels |
| `manage_device` | Add, remove, update, rename devices; set device parameters |
| `sync_project` | **Batch push** -- apply textual updates, IO mappings, and device params in one save |
### Build & Deploy
| Tool | Purpose |
|------|---------|
| `create_project` | Create new empty CODESYS project on VM |
| `build_project` | Compile a project |
| `download_to_device` | Deploy to PLC (requires `CODESYS_AGENT_ALLOW_DOWNLOAD=true`) |
### Low-level
| Tool | Purpose |
|------|---------|
| `codesys_submit_job` | Submit any action directly to the job queue |
| `stage_existing_project` | Copy/move project into standardized folder |
## 4) Typical round-trip workflow
### Import existing project into Cursor
```
1. read_project_inventory → get tree + textual sources → populate codesys_tree/
2. read_device_io → get devices, I/O channels, variable mappings → populate codesys_tree/
```
### Edit locally
Edit `.st`, `.gvl`, `.nvl`, `.type.st` files under `codesys_tree/` in Cursor.
### Push changes back to VM project
```
3. sync_project (dry_run=true) → preview what will change
4. sync_project (dry_run=false) → apply all textual + IO mapping changes in one save
5. build_project → compile
6. download_to_device → deploy to PLC
```
For individual changes, use `write_pou` or `write_io_mapping` directly.
## 5) Safety-first usage
- Start with `dry_run=true` for all mutating operations.
- Keep `CODESYS_AGENT_ALLOW_DOWNLOAD=false` while validating.
- Enable download only when target routing and credentials are verified.
- Close the CODESYS IDE on the VM before any write/push operations.
## 6) Local project layout
Every project in `Codesys_Projects/projects/<name>/` uses this structure:
```
<project>/
├── config/project.json # VM paths, profile, target device
├── codesys_tree/ # 1:1 mirror of CODESYS IDE tree
│ └── Device/
│ ├── Plc Logic/Application/
│ │ ├── POUs/PLC_PRG/PLC_PRG.program.st
│ │ ├── GVL/GVL.gvl
│ │ └── 3.Function Blocks/fb_boiler/fb_boiler.fb.st
│ └── EtherCAT_Master/EK1100/
│ ├── K1/K1.io_mapping.txt
│ └── K2/K2.io_mapping.txt
└── docs/
```
`codesys_tree/` is the canonical source layout. It mirrors the hierarchical
structure inside the CODESYS IDE so every folder and file maps 1:1 to a
CODESYS tree node.
## FAQ
### Do we need to keep CODESYS IDE open?
- **No.** The agent launches `CODESYS.exe` with `--noUI --runscript` for all operations.
- **Read operations** (inventory, device I/O) work even if the IDE has the project open (uses readonly mode).
- **Write operations** (write_pou, sync_project, manage_device) require the IDE to have the project **closed**, because CODESYS project files are exclusively locked.
- A CODESYS installation and valid profile are still required on the VM.
### Can we read existing CODESYS projects?
- Yes. Use `read_project_inventory` for sources and `read_device_io` for device/IO info.
- Sources are written into `codesys_tree/` mirroring the exact CODESYS IDE hierarchy.
### Can we modify device I/O mappings?
- Yes. Use `write_io_mapping` with device_path + param_id + variable.
- Or use `sync_project` with `io_mappings` for batch updates.
- Or import/export CSV via `read_device_io(export_csv_path=...)` and `write_io_mapping(import_csv_path=...)`.
### Can we add/remove devices?
- Yes. Use `manage_device` with operations like `add`, `remove`, `update`, `rename`, `enable`/`disable`, `set_param`.
- Device type/id/version values come from `read_device_io` output or the CODESYS device catalog.

View File

@@ -0,0 +1,51 @@
# CODESYS MCP Bridge (Linux)
This MCP server runs on Linux (where Cursor runs) and forwards tool calls to a Windows VM agent that has access to CODESYS.
## Tools
- `codesys_health`
- `codesys_submit_job`
- `codesys_get_job`
- `create_project`
- `read_project_inventory`
- `stage_existing_project`
- `write_pou`
- `build_project`
- `download_to_device`
## Environment variables
- `CODESYS_AGENT_URL` (default: `http://127.0.0.1:8787`)
- `CODESYS_AGENT_TOKEN` (required)
- `CODESYS_AGENT_REQUEST_TIMEOUT_SEC` (default: `30`)
## Run locally
```bash
cd mcp_codesys_bridge
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
export CODESYS_AGENT_URL="http://<windows-vm-ip>:8787"
export CODESYS_AGENT_TOKEN="<shared-secret-token>"
python server.py
```
## Cursor MCP config example
```json
{
"mcpServers": {
"codesys-bridge": {
"command": "python",
"args": ["/absolute/path/to/mcp_codesys_bridge/server.py"],
"env": {
"CODESYS_AGENT_URL": "http://<windows-vm-ip>:8787",
"CODESYS_AGENT_TOKEN": "<shared-secret-token>",
"CODESYS_AGENT_REQUEST_TIMEOUT_SEC": "30"
}
}
}
}
```

View File

@@ -0,0 +1,2 @@
mcp>=1.10.0
httpx>=0.27.0

View File

@@ -0,0 +1,293 @@
#!/usr/bin/env python3
"""Cursor MCP bridge for a remote Windows CODESYS agent."""
from __future__ import annotations
import json
import os
from typing import Any, Dict
import httpx
from mcp.server.fastmcp import FastMCP
AGENT_URL = os.environ.get("CODESYS_AGENT_URL", "http://127.0.0.1:8787").rstrip("/")
AGENT_TOKEN = os.environ.get("CODESYS_AGENT_TOKEN", "")
REQUEST_TIMEOUT_SEC = float(os.environ.get("CODESYS_AGENT_REQUEST_TIMEOUT_SEC", "30"))
if not AGENT_TOKEN:
raise RuntimeError("CODESYS_AGENT_TOKEN is required.")
mcp = FastMCP("codesys-bridge")
def _headers() -> Dict[str, str]:
return {"x-api-token": AGENT_TOKEN, "content-type": "application/json"}
def _client() -> httpx.Client:
return httpx.Client(timeout=REQUEST_TIMEOUT_SEC)
def _post(path: str, payload: Dict[str, Any]) -> Dict[str, Any]:
with _client() as client:
response = client.post(
f"{AGENT_URL}{path}",
headers=_headers(),
content=json.dumps(payload),
)
response.raise_for_status()
return response.json()
def _get(path: str) -> Dict[str, Any]:
with _client() as client:
response = client.get(f"{AGENT_URL}{path}", headers=_headers())
response.raise_for_status()
return response.json()
@mcp.tool()
def codesys_health() -> Dict[str, Any]:
"""Check Windows VM CODESYS agent health."""
with _client() as client:
response = client.get(f"{AGENT_URL}/health")
response.raise_for_status()
return response.json()
@mcp.tool()
def codesys_submit_job(action: str, payload: Dict[str, Any], dry_run: bool = False) -> Dict[str, Any]:
"""Submit an asynchronous CODESYS action."""
return _post(
"/jobs",
{
"action": action,
"payload": payload,
"dry_run": dry_run,
},
)
@mcp.tool()
def codesys_get_job(job_id: str) -> Dict[str, Any]:
"""Get CODESYS job status/result by ID."""
return _get(f"/jobs/{job_id}")
@mcp.tool()
def create_project(project_name: str, output_dir: str, template: str = "standard", dry_run: bool = False) -> Dict[str, Any]:
"""Create a new CODESYS project in the Windows VM."""
return codesys_submit_job(
action="create_project",
payload={
"project_name": project_name,
"output_dir": output_dir,
"template": template,
},
dry_run=dry_run,
)
@mcp.tool()
def read_project_inventory(project_path: str, max_depth: int = 3, dry_run: bool = False) -> Dict[str, Any]:
"""Read an existing project tree/inventory."""
return codesys_submit_job(
action="read_project_inventory",
payload={"project_path": project_path, "max_depth": max_depth},
dry_run=dry_run,
)
@mcp.tool()
def stage_existing_project(
source_path: str,
projects_root_dir: str,
project_folder_name: str = "",
move: bool = False,
overwrite: bool = False,
dry_run: bool = False,
) -> Dict[str, Any]:
"""Copy/move an existing project into a standardized projects root folder."""
return codesys_submit_job(
action="stage_existing_project",
payload={
"source_path": source_path,
"projects_root_dir": projects_root_dir,
"project_folder_name": project_folder_name,
"move": move,
"overwrite": overwrite,
},
dry_run=dry_run,
)
@mcp.tool()
def write_pou(
project_path: str,
object_path: str = "",
object_name: str = "",
declaration: str = "",
implementation: str = "",
updates: list = [],
dry_run: bool = False,
) -> Dict[str, Any]:
"""Write/update textual objects (POUs, FBs, GVLs, NVLs, structs, programs).
For a single object: provide object_path (e.g. "Device/Plc Logic/Application/3.Function Blocks/fb_boiler")
or object_name (unique name), plus declaration and/or implementation text.
For batch: provide updates list of dicts with object_path/object_name + declaration/implementation.
"""
payload: Dict[str, Any] = {"project_path": project_path, "dry_run": dry_run}
if updates:
payload["updates"] = updates
else:
if object_path:
payload["object_path"] = object_path
if object_name:
payload["object_name"] = object_name
if declaration:
payload["declaration"] = declaration
if implementation:
payload["implementation"] = implementation
return codesys_submit_job(action="write_pou", payload=payload, dry_run=dry_run)
@mcp.tool()
def read_device_io(
project_path: str,
channels_only: bool = True,
max_depth: int = 10,
export_csv_path: str = "",
dry_run: bool = False,
) -> Dict[str, Any]:
"""Read device tree with I/O channels, parameters, and variable mappings.
Returns device identification (type/model), I/O channel details (input/output,
bit size, IEC type), and current variable mappings for each device in the project.
Set channels_only=False to include non-IO parameters too.
Optionally export all IO mappings as CSV on the VM.
"""
payload: Dict[str, Any] = {
"project_path": project_path,
"channels_only": channels_only,
"max_depth": max_depth,
}
if export_csv_path:
payload["export_csv_path"] = export_csv_path
return codesys_submit_job(action="read_device_io", payload=payload, dry_run=dry_run)
@mcp.tool()
def write_io_mapping(
project_path: str,
mappings: list = [],
import_csv_path: str = "",
dry_run: bool = True,
) -> Dict[str, Any]:
"""Map IEC variables to device I/O channels.
Each mapping dict needs: device_path (slash-separated, e.g. "Device/EtherCAT_Master/EK1100/K1"),
param_id or param_name (from read_device_io output), and variable (IEC variable expression).
Alternatively provide import_csv_path to bulk-import mappings from a CSV file on the VM.
dry_run=True by default for safety -- set False to actually write.
"""
payload: Dict[str, Any] = {
"project_path": project_path,
"dry_run": dry_run,
}
if mappings:
payload["mappings"] = mappings
if import_csv_path:
payload["import_csv_path"] = import_csv_path
return codesys_submit_job(action="write_io_mapping", payload=payload, dry_run=dry_run)
@mcp.tool()
def manage_device(
project_path: str,
operations: list = [],
dry_run: bool = True,
) -> Dict[str, Any]:
"""Add, remove, update, rename, enable/disable devices, or set device parameters.
Each operation dict needs action_type plus action-specific fields:
- add: parent_path, name, device_type, device_id, device_version [, method="add"|"plug"|"insert"]
- remove: device_path
- update: device_path, device_type, device_id, device_version
- rename: device_path, new_name
- enable/disable: device_path, enabled (bool)
- set_param: device_path, param_id or param_name, value
Use device_type/device_id/device_version values from read_device_io output.
dry_run=True by default for safety.
"""
return codesys_submit_job(
action="manage_device",
payload={
"project_path": project_path,
"operations": operations,
"dry_run": dry_run,
},
dry_run=dry_run,
)
@mcp.tool()
def sync_project(
project_path: str,
textual_updates: list = [],
io_mappings: list = [],
device_params: list = [],
dry_run: bool = True,
) -> Dict[str, Any]:
"""Batch-push local changes into a CODESYS project in a single open/save cycle.
textual_updates: list of {object_path, declaration?, implementation?}
io_mappings: list of {device_path, param_id, variable}
device_params: list of {device_path, param_id or param_name, value}
This is the primary "push" tool -- reads all changes from Cursor and applies them at once.
dry_run=True by default for safety.
"""
return codesys_submit_job(
action="sync_project",
payload={
"project_path": project_path,
"textual_updates": textual_updates,
"io_mappings": io_mappings,
"device_params": device_params,
"dry_run": dry_run,
},
dry_run=dry_run,
)
@mcp.tool()
def build_project(project_path: str, dry_run: bool = False) -> Dict[str, Any]:
"""Build/compile a CODESYS project."""
return codesys_submit_job(
action="build_project",
payload={"project_path": project_path},
dry_run=dry_run,
)
@mcp.tool()
def download_to_device(project_path: str, target_name: str, start_application: bool = False, dry_run: bool = False) -> Dict[str, Any]:
"""Download project to configured target device."""
return codesys_submit_job(
action="download_to_device",
payload={
"project_path": project_path,
"target_name": target_name,
"start_application": start_application,
},
dry_run=dry_run,
)
if __name__ == "__main__":
mcp.run()

View File

@@ -0,0 +1,61 @@
# Configure Python Scripting in CODESYS IDE
This guide helps you enable and validate Python scripting in the CODESYS Development System.
## 1) Prerequisites
- CODESYS Development System installed
- A local Python installation (recommended: 64-bit)
- Permissions to install CODESYS packages/add-ons
> Note: Python version compatibility can vary by CODESYS release. Check your CODESYS release notes if the scripting package requests a specific Python version.
## 2) Enable scripting support in CODESYS
1. Start CODESYS IDE.
2. Open the CODESYS package/add-on manager.
3. Verify that scripting support is installed (usually shown as `Scripting`, `Script Engine`, or similar CODESYS scripting component).
4. If missing, install the scripting package from CODESYS Store/Installer and restart CODESYS.
## 3) Verify Python environment in IDE
1. Open the scripting window/console in CODESYS (menu name depends on version/profile).
2. Confirm that the script console starts without errors.
3. If CODESYS asks for a Python path/interpreter, set your local Python executable.
4. Save settings and restart IDE once.
## 4) Run a first test script
Use this minimal script in the CODESYS script console/editor:
```python
import sys
print("Python OK")
print(sys.version)
```
Expected result: no import/runtime errors and printed Python version output.
## 5) Connect script to an existing project
1. Open your CODESYS project.
2. From scripting console/editor, access the active project object (CODESYS scripting API).
3. Start with read-only actions first:
- list devices
- list POUs
- print project metadata
4. Then move to controlled write actions (for example, auto-creating folders/objects).
## 6) Common setup issues
- **Scripting menu missing**: scripting package not installed or wrong CODESYS profile.
- **Interpreter errors**: incompatible Python version or wrong executable path.
- **Permission errors**: run IDE with appropriate permissions for package/plugin install.
- **API object errors**: script written for another CODESYS version/API revision.
## 7) Recommended workflow
- Keep scripts in version control near your CODESYS project.
- Start with non-destructive scripts (reporting/checks) before auto-edit scripts.
- Add log output for every script action.
- Test scripts on a copy of the project before applying to production projects.

View File

@@ -0,0 +1,46 @@
# What You Can Do with Python in CODESYS
Python in CODESYS is mainly for **engineering automation** (IDE/project automation), not for PLC runtime logic execution.
## Typical use cases
- **Project scaffolding**
- Create project structures, folders, and naming templates automatically.
- **Bulk edits**
- Create or modify many POUs/objects consistently.
- **Consistency checks**
- Enforce naming conventions, library versions, and structure rules.
- **Build/export automation**
- Trigger exports and produce repeatable build artifacts.
- **Documentation generation**
- Extract project metadata and generate docs/reports.
- **Pre-release validation**
- Run scripted checks before handing over a project.
## Practical examples
- Generate standard folder trees and placeholder POUs for new machines.
- Scan all variables and report naming/style violations.
- Export project data for review and commit audit trails.
- Produce release notes from project metadata.
## What Python in CODESYS is NOT
- Not a replacement for IEC 61131-3 application logic running on the PLC.
- Not typically used for hard real-time control loops on the target runtime.
## Good practices
- Keep scripts idempotent where possible (safe to run multiple times).
- Add a `dry-run` mode for scripts that change project data.
- Write action logs (what changed, where, and when).
- Use one script per purpose (small, focused scripts are easier to maintain).
- Test against project copies before production use.
## Suggested first automation tasks
1. A read-only project inventory script (devices, POUs, libraries).
2. A naming-convention checker script.
3. A release/export helper script.
These three give immediate value while keeping risk low.

View File

@@ -0,0 +1,57 @@
# Windows CODESYS Agent
This service runs inside the Windows VM that has CODESYS installed.
It receives authenticated job requests from the Linux MCP bridge and executes action scripts locally.
## Supported actions
- `create_project`
- `read_project_inventory`
- `stage_existing_project`
- `write_pou`
- `build_project`
- `download_to_device`
## Endpoints
- `GET /health`
- `POST /jobs`
- `GET /jobs/{job_id}`
## Environment variables
- `CODESYS_AGENT_TOKEN` (required shared secret)
- `CODESYS_AGENT_SCRIPTS_DIR` (default: `C:\\codesys-agent\\scripts`)
- `CODESYS_AGENT_RUNTIME_DIR` (default: `C:\\codesys-agent\\runtime`)
- `CODESYS_AGENT_PYTHON_BIN` (default: `python`)
- `CODESYS_AGENT_TIMEOUT_SEC` (default: `180`)
- `CODESYS_AGENT_ALLOW_DOWNLOAD` (`true` or `false`, default `false`)
- `CODESYS_EXE_PATH` (required for ScriptEngine actions, e.g. `C:\\Program Files\\CODESYS 3.5.xx\\CODESYS\\Common\\CODESYS.exe`)
- `CODESYS_PROFILE` (required for ScriptEngine actions, e.g. `CODESYS V3.5 SP21`)
- `CODESYS_NO_UI` (`true`/`false`, default `true`, runs actions without opening visible IDE UI)
- `CODESYS_SCRIPT_TIMEOUT_SEC` (default `600`)
## Run on Windows VM
```powershell
cd windows_codesys_agent
py -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt
$env:CODESYS_AGENT_TOKEN = "<shared-secret-token>"
$env:CODESYS_AGENT_SCRIPTS_DIR = "C:\codesys-agent\windows_codesys_agent\scripts"
$env:CODESYS_AGENT_RUNTIME_DIR = "C:\codesys-agent\runtime"
$env:CODESYS_AGENT_ALLOW_DOWNLOAD = "false"
$env:CODESYS_EXE_PATH = "C:\Program Files\CODESYS 3.5.21.0\CODESYS\Common\CODESYS.exe"
$env:CODESYS_PROFILE = "CODESYS V3.5 SP21"
$env:CODESYS_NO_UI = "true"
uvicorn agent:app --host 0.0.0.0 --port 8787
```
## Security notes
- Keep VM firewall limited to trusted source IPs.
- Use a long random token, rotate periodically.
- Keep `CODESYS_AGENT_ALLOW_DOWNLOAD=false` until you finish dry-run validation.
- For full automation, verify `CODESYS_EXE_PATH` and `CODESYS_PROFILE` are correct for your VM installation.

View File

@@ -0,0 +1,301 @@
#!/usr/bin/env python3
"""Windows-side CODESYS agent with async job processing."""
from __future__ import annotations
import json
import os
import queue
import subprocess
import tempfile
import threading
import time
import uuid
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any, Dict, Optional
from fastapi import FastAPI, Header, HTTPException
from pydantic import BaseModel, Field
API_TOKEN = os.environ.get("CODESYS_AGENT_TOKEN", "")
SCRIPTS_DIR = Path(
os.environ.get("CODESYS_AGENT_SCRIPTS_DIR", r"C:\codesys-agent\scripts")
).resolve()
RUNTIME_DIR = Path(
os.environ.get("CODESYS_AGENT_RUNTIME_DIR", r"C:\codesys-agent\runtime")
).resolve()
PYTHON_BIN = os.environ.get("CODESYS_AGENT_PYTHON_BIN", "python")
DEFAULT_TIMEOUT_SEC = int(os.environ.get("CODESYS_AGENT_TIMEOUT_SEC", "180"))
ALLOW_DOWNLOAD = os.environ.get("CODESYS_AGENT_ALLOW_DOWNLOAD", "false").lower() == "true"
CODESYS_EXE_PATH = os.environ.get("CODESYS_EXE_PATH", "")
CODESYS_PROFILE = os.environ.get("CODESYS_PROFILE", "")
CODESYS_NO_UI = os.environ.get("CODESYS_NO_UI", "true").lower() == "true"
CODESYS_SCRIPT_TIMEOUT_SEC = int(os.environ.get("CODESYS_SCRIPT_TIMEOUT_SEC", "600"))
@dataclass
class Job:
id: str
action: str
payload: Dict[str, Any]
dry_run: bool = False
status: str = "queued"
created_at: float = field(default_factory=time.time)
started_at: Optional[float] = None
finished_at: Optional[float] = None
result: Optional[Dict[str, Any]] = None
error: Optional[str] = None
class SubmitJobRequest(BaseModel):
action: str = Field(..., description="Action name")
payload: Dict[str, Any] = Field(default_factory=dict)
dry_run: bool = False
class JobStore:
def __init__(self) -> None:
self._jobs: Dict[str, Job] = {}
self._lock = threading.Lock()
def create(self, action: str, payload: Dict[str, Any], dry_run: bool) -> Job:
job = Job(
id=str(uuid.uuid4()),
action=action,
payload=payload,
dry_run=dry_run,
)
with self._lock:
self._jobs[job.id] = job
return job
def get(self, job_id: str) -> Job:
with self._lock:
job = self._jobs.get(job_id)
if not job:
raise KeyError(job_id)
return job
def update(self, job: Job) -> None:
with self._lock:
self._jobs[job.id] = job
app = FastAPI(title="CODESYS VM Agent", version="0.2.0")
store = JobStore()
job_queue: "queue.Queue[str]" = queue.Queue()
def _check_auth(token: Optional[str]) -> None:
if not API_TOKEN:
raise HTTPException(
status_code=500,
detail="CODESYS_AGENT_TOKEN is not configured.",
)
if token != API_TOKEN:
raise HTTPException(status_code=401, detail="Unauthorized")
def _action_to_script(action: str) -> str:
mapping = {
"create_project": "create_project.py",
"read_project_inventory": "read_project_inventory.py",
"read_device_io": "read_device_io.py",
"write_pou": "write_pou.py",
"write_io_mapping": "write_io_mapping.py",
"manage_device": "manage_device.py",
"sync_project": "sync_project.py",
"stage_existing_project": "stage_existing_project.py",
"build_project": "build_project.py",
"download_to_device": "download_to_device.py",
}
script = mapping.get(action)
if not script:
raise RuntimeError(f"Unsupported action: {action}")
if action == "download_to_device" and not ALLOW_DOWNLOAD:
raise RuntimeError("download_to_device is disabled by policy.")
return script
def _run_script_python(script_name: str, payload: Dict[str, Any]) -> Dict[str, Any]:
script_path = (SCRIPTS_DIR / script_name).resolve()
if not script_path.is_file():
raise RuntimeError(f"Script not found: {script_path}")
cmd = [PYTHON_BIN, str(script_path), json.dumps(payload)]
proc = subprocess.run(
cmd,
text=True,
capture_output=True,
timeout=DEFAULT_TIMEOUT_SEC,
check=False,
)
return {
"command": cmd,
"exit_code": proc.returncode,
"stdout": proc.stdout,
"stderr": proc.stderr,
}
def _run_script_codesys(script_name: str, payload: Dict[str, Any]) -> Dict[str, Any]:
if not CODESYS_EXE_PATH or not CODESYS_PROFILE:
raise RuntimeError(
"CODESYS_EXE_PATH and CODESYS_PROFILE must be configured for ScriptEngine actions."
)
script_path = (SCRIPTS_DIR / script_name).resolve()
if not script_path.is_file():
raise RuntimeError(f"Script not found: {script_path}")
RUNTIME_DIR.mkdir(parents=True, exist_ok=True)
payload_fd, payload_name = tempfile.mkstemp(
prefix="codesys_payload_",
suffix=".json",
dir=str(RUNTIME_DIR),
)
result_fd, result_name = tempfile.mkstemp(
prefix="codesys_result_",
suffix=".json",
dir=str(RUNTIME_DIR),
)
os.close(payload_fd)
os.close(result_fd)
payload_file = Path(payload_name)
result_file = Path(result_name)
payload_file.write_text(json.dumps(payload), encoding="utf-8")
script_args = f'--scriptargs:"{payload_file}"'
cmd = (
f'"{CODESYS_EXE_PATH}" '
f'--profile="{CODESYS_PROFILE}" '
f'--runscript="{script_path}" '
f"{script_args}"
)
if CODESYS_NO_UI:
cmd += " --noUI"
proc_env = os.environ.copy()
proc_env["CODESYS_SCRIPT_RESULT_PATH"] = str(result_file)
proc = subprocess.run(
cmd,
shell=True,
env=proc_env,
text=True,
capture_output=True,
timeout=CODESYS_SCRIPT_TIMEOUT_SEC,
check=False,
)
parsed_result: Dict[str, Any] | None = None
if result_file.exists():
try:
parsed_result = json.loads(result_file.read_text(encoding="utf-8"))
except json.JSONDecodeError:
parsed_result = {"raw_result_text": result_file.read_text(encoding="utf-8", errors="ignore")}
return {
"command": cmd,
"exit_code": proc.returncode,
"stdout": proc.stdout,
"stderr": proc.stderr,
"script_result": parsed_result,
"payload_file": str(payload_file),
"result_file": str(result_file),
}
def _execute(job: Job) -> Dict[str, Any]:
if job.dry_run:
return {
"dry_run": True,
"action": job.action,
"payload": job.payload,
"message": "Dry-run accepted. No changes made.",
}
script_name = _action_to_script(job.action)
# Project operations use CODESYS ScriptEngine (no manual IDE opening required).
codesys_actions = {
"create_project",
"read_project_inventory",
"read_device_io",
"write_pou",
"write_io_mapping",
"manage_device",
"sync_project",
"build_project",
"download_to_device",
}
if job.action in codesys_actions:
result = _run_script_codesys(script_name, job.payload)
else:
result = _run_script_python(script_name, job.payload)
if result["exit_code"] != 0:
raise RuntimeError(
f"{job.action} failed with exit_code={result['exit_code']} stderr={result['stderr']}"
)
if result.get("script_result"):
return result["script_result"]
return result
def _worker() -> None:
while True:
job_id = job_queue.get()
try:
job = store.get(job_id)
job.status = "running"
job.started_at = time.time()
store.update(job)
result = _execute(job)
job.status = "succeeded"
job.result = result
job.finished_at = time.time()
store.update(job)
except Exception as exc: # pylint: disable=broad-except
job = store.get(job_id)
job.status = "failed"
job.error = str(exc)
job.finished_at = time.time()
store.update(job)
finally:
job_queue.task_done()
threading.Thread(target=_worker, daemon=True).start()
@app.get("/health")
def health() -> Dict[str, Any]:
return {
"ok": True,
"service": "codesys-vm-agent",
"version": "0.2.0",
"scripts_dir": str(SCRIPTS_DIR),
"runtime_dir": str(RUNTIME_DIR),
"download_enabled": ALLOW_DOWNLOAD,
"codesys_exe_configured": bool(CODESYS_EXE_PATH),
"codesys_profile_configured": bool(CODESYS_PROFILE),
"codesys_no_ui": CODESYS_NO_UI,
}
@app.post("/jobs")
def submit_job(req: SubmitJobRequest, x_api_token: Optional[str] = Header(None)) -> Dict[str, Any]:
_check_auth(x_api_token)
job = store.create(req.action, req.payload, req.dry_run)
job_queue.put(job.id)
return {"job_id": job.id, "status": job.status}
@app.get("/jobs/{job_id}")
def get_job(job_id: str, x_api_token: Optional[str] = Header(None)) -> Dict[str, Any]:
_check_auth(x_api_token)
try:
job = store.get(job_id)
except KeyError as exc:
raise HTTPException(status_code=404, detail="Job not found") from exc
return asdict(job)

View File

@@ -0,0 +1,2 @@
fastapi>=0.115.0
uvicorn>=0.30.0

View File

@@ -0,0 +1,78 @@
#!/usr/bin/env python
"""Shared helpers for Windows CODESYS action scripts."""
from __future__ import print_function
import json
import os
import sys
try:
text_type = unicode # type: ignore[name-defined]
binary_type = str
PY2 = True
except NameError:
text_type = str
binary_type = bytes
PY2 = False
def _argv(index):
if len(sys.argv) > index:
return sys.argv[index]
return None
def load_payload():
"""Load payload from argv[1] (json string or json file path)."""
raw = _argv(1)
if not raw:
raise ValueError("Missing payload argument.")
if os.path.exists(raw):
with open(raw, "r") as f:
return json.loads(f.read())
try:
return json.loads(raw)
except ValueError as exc:
raise ValueError("Invalid JSON payload: {0}".format(exc))
def _normalize_text(value):
if isinstance(value, dict):
normalized = {}
for key, item in value.items():
normalized[_normalize_text(key)] = _normalize_text(item)
return normalized
if isinstance(value, list):
return [_normalize_text(item) for item in value]
if isinstance(value, tuple):
return [_normalize_text(item) for item in value]
if isinstance(value, binary_type):
if PY2:
for encoding in ("utf-8", "cp1252", "latin-1"):
try:
return value.decode(encoding).encode("ascii", "replace")
except Exception:
pass
return value.decode("latin-1", "replace").encode("ascii", "replace")
for encoding in ("utf-8", "cp1252", "latin-1"):
try:
return value.decode(encoding).encode("ascii", "replace").decode("ascii")
except Exception:
pass
return value.decode("latin-1", "replace").encode("ascii", "replace").decode("ascii")
if isinstance(value, text_type):
if PY2:
return value.encode("ascii", "replace")
return value.encode("ascii", "replace").decode("ascii")
return value
def emit(data):
"""Print JSON to stdout and optionally write to argv[2] path."""
text = json.dumps(_normalize_text(data), indent=2, ensure_ascii=True)
print(text)
result_path = _argv(2) or os.environ.get("CODESYS_SCRIPT_RESULT_PATH")
if result_path:
with open(result_path, "w") as f:
f.write(text)

View File

@@ -0,0 +1,46 @@
#!/usr/bin/env python
"""Build/compile a CODESYS project via ScriptEngine."""
from __future__ import print_function
import os
from _common import emit, load_payload
def main():
payload = load_payload()
project_path = payload.get("project_path")
save_after_build = bool(payload.get("save_after_build", True))
if not project_path:
raise ValueError("project_path is required.")
pp = os.path.abspath(os.path.expanduser(project_path))
if not os.path.exists(pp):
raise RuntimeError("Project path does not exist: {0}".format(pp))
if "projects" not in globals():
raise RuntimeError("Run through CODESYS ScriptEngine (--runscript).")
if projects.primary:
projects.primary.close()
proj = projects.open(pp, primary=True, allow_readonly=False)
app = proj.active_application
if app is None:
raise RuntimeError("No active application found in project.")
app.build()
if save_after_build:
proj.save()
proj.close()
emit(
{
"ok": True,
"action": "build_project",
"project_path": pp,
"save_after_build": save_after_build,
}
)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,55 @@
#!/usr/bin/env python
"""Create a new CODESYS project via ScriptEngine."""
from __future__ import print_function
import os
from _common import emit, load_payload
def main():
payload = load_payload()
project_name = payload.get("project_name")
output_dir = payload.get("output_dir")
template = payload.get("template", "standard")
overwrite = bool(payload.get("overwrite", False))
if not project_name or not output_dir:
raise ValueError("project_name and output_dir are required.")
project_path = os.path.join(output_dir, "{0}.project".format(project_name))
if os.path.exists(project_path) and not overwrite:
raise RuntimeError("Project already exists: {0}".format(project_path))
if not os.path.exists(output_dir):
os.makedirs(output_dir)
if "projects" not in globals():
raise RuntimeError(
"CODESYS ScriptEngine globals not found. "
"Run this script through CODESYS.exe --runscript."
)
if projects.primary:
projects.primary.close()
if os.path.exists(project_path) and overwrite:
os.remove(project_path)
proj = projects.create(project_path, primary=True)
proj.save()
proj.close()
emit(
{
"ok": True,
"action": "create_project",
"project_name": project_name,
"template": template,
"project_path": project_path,
}
)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,59 @@
#!/usr/bin/env python
"""Login/download/start the active application using ScriptEngine online API."""
from __future__ import print_function
import os
from _common import emit, load_payload
def main():
payload = load_payload()
project_path = payload.get("project_path")
target_name = payload.get("target_name", "")
start_application = bool(payload.get("start_application", False))
force_download = bool(payload.get("force_download", True))
if not project_path:
raise ValueError("project_path is required.")
pp = os.path.abspath(os.path.expanduser(project_path))
if not os.path.exists(pp):
raise RuntimeError("Project path does not exist: {0}".format(pp))
if "projects" not in globals() or "online" not in globals():
raise RuntimeError("Run through CODESYS ScriptEngine (--runscript).")
if projects.primary:
projects.primary.close()
proj = projects.open(pp, primary=True, allow_readonly=False)
app = proj.active_application
if app is None:
raise RuntimeError("No active application found in project.")
online_app = online.create_online_application(app)
# Try online change first; CODESYS handles download when needed.
login_mode = OnlineChangeOption.Try if force_download else OnlineChangeOption.Never
online_app.login(login_mode, True)
started = False
if start_application and online_app.application_state != ApplicationState.run:
online_app.start()
started = True
online_app.logout()
proj.close()
emit(
{
"ok": True,
"action": "download_to_device",
"project_path": pp,
"target_name": target_name,
"start_application": start_application,
"started": started,
}
)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,318 @@
#!/usr/bin/env python
"""Add, remove, or update devices in a CODESYS project via ScriptEngine."""
from __future__ import print_function
import os
from _common import emit, load_payload
def _discover_project_file(path_value):
if os.path.isfile(path_value):
lower_path = path_value.lower()
if lower_path.endswith(".project") or lower_path.endswith(".projectarchive"):
return path_value
raise RuntimeError("project_path must be .project or .projectarchive: {0}".format(path_value))
if os.path.isdir(path_value):
candidates = []
for entry in os.listdir(path_value):
full_path = os.path.join(path_value, entry)
if os.path.isfile(full_path):
lower_name = entry.lower()
if lower_name.endswith(".project") or lower_name.endswith(".projectarchive"):
candidates.append(full_path)
if len(candidates) == 1:
return candidates[0]
if not candidates:
raise RuntimeError("No .project/.projectarchive in: {0}".format(path_value))
raise RuntimeError("Multiple project files: {0}".format(", ".join(candidates)))
raise RuntimeError("Path does not exist: {0}".format(path_value))
def _safe_str(val):
try:
return "{0}".format(val)
except Exception:
return "?"
def _name_of(obj):
try:
return obj.get_name(False)
except Exception:
try:
return obj.get_name()
except Exception:
return _safe_str(obj)
def _children_of(obj):
try:
return list(obj.get_children(False))
except Exception:
try:
return list(obj.get_children())
except Exception:
return []
def _find_by_path(root, path_str):
parts = [p.strip() for p in path_str.split("/") if p.strip()]
current = root
for i, part in enumerate(parts):
found = None
for child in _children_of(current):
if _name_of(child) == part:
found = child
break
if found is None:
raise RuntimeError("Not found: '{0}' at segment {1} of '{2}'".format(part, i, path_str))
current = found
return current
def _get_device_id(obj):
try:
did = obj.get_device_identification()
return {"type": int(did.type), "id": _safe_str(did.id), "version": _safe_str(did.version)}
except Exception:
return None
def _action_add(proj, op, warnings):
parent_path = op.get("parent_path", "")
name = op.get("name", "")
dev_type = op.get("device_type")
dev_id = op.get("device_id", "")
dev_version = op.get("device_version", "")
module_id = op.get("module_id")
if not parent_path or not name or dev_type is None or not dev_id or not dev_version:
raise ValueError("add requires: parent_path, name, device_type, device_id, device_version")
parent = _find_by_path(proj, parent_path)
args = [name, int(dev_type), dev_id, dev_version]
if module_id is not None:
args.append(module_id)
method = op.get("method", "add")
if method == "plug":
parent.plug(*args)
elif method == "insert":
index = int(op.get("index", -1))
parent.insert(name, index, int(dev_type), dev_id, dev_version)
else:
parent.add(*args)
return {
"action": "add",
"parent_path": parent_path,
"name": name,
"device_type": dev_type,
"device_id": dev_id,
"device_version": dev_version,
"status": "added",
}
def _action_remove(proj, op, warnings):
device_path = op.get("device_path", "")
if not device_path:
raise ValueError("remove requires: device_path")
obj = _find_by_path(proj, device_path)
name = _name_of(obj)
dev_id = _get_device_id(obj)
obj.remove()
return {
"action": "remove",
"device_path": device_path,
"name": name,
"device_id": dev_id,
"status": "removed",
}
def _action_update(proj, op, warnings):
device_path = op.get("device_path", "")
dev_type = op.get("device_type")
dev_id = op.get("device_id", "")
dev_version = op.get("device_version", "")
module_id = op.get("module_id")
if not device_path or dev_type is None or not dev_id or not dev_version:
raise ValueError("update requires: device_path, device_type, device_id, device_version")
obj = _find_by_path(proj, device_path)
old_id = _get_device_id(obj)
args = [int(dev_type), dev_id, dev_version]
if module_id is not None:
args.append(module_id)
obj.update(*args)
return {
"action": "update",
"device_path": device_path,
"old_device_id": old_id,
"new_device_id": {"type": dev_type, "id": dev_id, "version": dev_version},
"status": "updated",
}
def _action_rename(proj, op, warnings):
device_path = op.get("device_path", "")
new_name = op.get("new_name", "")
if not device_path or not new_name:
raise ValueError("rename requires: device_path, new_name")
obj = _find_by_path(proj, device_path)
old_name = _name_of(obj)
obj.rename(new_name)
return {
"action": "rename",
"device_path": device_path,
"old_name": old_name,
"new_name": new_name,
"status": "renamed",
}
def _action_enable(proj, op, warnings):
device_path = op.get("device_path", "")
enabled = op.get("enabled", True)
if not device_path:
raise ValueError("enable/disable requires: device_path")
obj = _find_by_path(proj, device_path)
if enabled:
obj.enable()
else:
obj.disable()
return {
"action": "enable" if enabled else "disable",
"device_path": device_path,
"status": "enabled" if enabled else "disabled",
}
def _action_set_param(proj, op, warnings):
"""Set a device parameter value by id or name."""
device_path = op.get("device_path", "")
param_id = op.get("param_id")
param_name = op.get("param_name", "")
value = op.get("value")
if not device_path:
raise ValueError("set_param requires: device_path")
if value is None:
raise ValueError("set_param requires: value")
obj = _find_by_path(proj, device_path)
params = obj.device_parameters
target = None
for p in list(params):
if param_id is not None and int(p.id) == int(param_id):
target = p
break
if param_name and (_safe_str(getattr(p, "visible_name", "")) == param_name or _safe_str(getattr(p, "name", "")) == param_name):
target = p
break
if target is None:
raise RuntimeError("Parameter not found: id={0} name={1} on {2}".format(param_id, param_name, device_path))
old_value = _safe_str(target.value) if hasattr(target, "value") else "?"
target.value = _safe_str(value)
return {
"action": "set_param",
"device_path": device_path,
"param_id": int(target.id),
"param_name": _safe_str(getattr(target, "visible_name", "")),
"old_value": old_value,
"new_value": _safe_str(value),
"status": "set",
}
ACTIONS = {
"add": _action_add,
"remove": _action_remove,
"update": _action_update,
"rename": _action_rename,
"enable": _action_enable,
"disable": _action_enable,
"set_param": _action_set_param,
}
def main():
payload = load_payload()
project_path = payload.get("project_path")
if not project_path:
raise ValueError("project_path is required.")
operations = payload.get("operations", [])
if not operations:
single_action = payload.get("action_type", "")
if single_action:
operations = [payload]
else:
raise ValueError("Provide 'operations' list or a single operation with 'action_type'.")
dry_run = bool(payload.get("dry_run", False))
pp = os.path.abspath(os.path.expanduser(project_path))
pp = _discover_project_file(pp)
if "projects" not in globals():
raise RuntimeError("Run through CODESYS ScriptEngine (--runscript).")
if projects.primary:
projects.primary.close()
proj = projects.open(pp, primary=True)
results = []
warnings = []
for op in operations:
action_type = op.get("action_type", "")
handler = ACTIONS.get(action_type)
if not handler:
warnings.append("unknown action_type: {0}".format(action_type))
continue
try:
if dry_run:
results.append({
"action": action_type,
"dry_run": True,
"status": "would_execute",
"details": op,
})
else:
result = handler(proj, op, warnings)
results.append(result)
except Exception as exc:
warnings.append("{0}_failed: {1}".format(action_type, exc))
if not dry_run:
try:
proj.save()
except Exception as exc:
warnings.append("project_save_failed: {0}".format(exc))
proj.close()
emit({
"ok": True,
"action": "manage_device",
"project_path": pp,
"dry_run": dry_run,
"results": results,
"result_count": len(results),
"warnings": warnings,
})
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,303 @@
#!/usr/bin/env python
"""Read device I/O channels, parameters, and variable mappings from a CODESYS project."""
from __future__ import print_function
import os
from _common import emit, load_payload
def _discover_project_file(path_value):
if os.path.isfile(path_value):
lower_path = path_value.lower()
if lower_path.endswith(".project") or lower_path.endswith(".projectarchive"):
return path_value
raise RuntimeError(
"project_path must point to a .project or .projectarchive file. Got: {0}".format(path_value)
)
if os.path.isdir(path_value):
candidates = []
for entry in os.listdir(path_value):
full_path = os.path.join(path_value, entry)
if os.path.isfile(full_path):
lower_name = entry.lower()
if lower_name.endswith(".project") or lower_name.endswith(".projectarchive"):
candidates.append(full_path)
if len(candidates) == 1:
return candidates[0]
if not candidates:
raise RuntimeError("No .project/.projectarchive in directory: {0}".format(path_value))
raise RuntimeError("Multiple project files found: {0}".format(", ".join(candidates)))
raise RuntimeError("Project path does not exist: {0}".format(path_value))
def _safe_str(val):
try:
return "{0}".format(val)
except Exception:
return "?"
def _name_of(obj):
try:
return obj.get_name(False)
except Exception:
try:
return obj.get_name()
except Exception:
return _safe_str(obj)
def _children_of(obj):
try:
return list(obj.get_children(False))
except Exception:
try:
return list(obj.get_children())
except Exception:
return []
def _get_device_id(obj):
try:
did = obj.get_device_identification()
return {
"type": int(did.type),
"id": _safe_str(did.id),
"version": _safe_str(did.version),
}
except Exception:
return None
def _channel_type_str(ct):
mapping = {0: "none", 1: "input", 2: "output", 3: "output_readonly"}
try:
return mapping.get(int(ct), _safe_str(ct))
except Exception:
return _safe_str(ct)
def _read_io_mapping(param):
"""Extract IO mapping info from a device parameter."""
try:
iom = param.io_mapping
if iom is None:
return None
result = {}
try:
result["variable"] = _safe_str(iom.variable) if iom.variable else ""
except Exception:
result["variable"] = ""
try:
result["default_variable"] = _safe_str(iom.default_variable) if iom.default_variable else ""
except Exception:
result["default_variable"] = ""
try:
result["creates_variable"] = bool(iom.mapping_creates_variable)
except Exception:
pass
try:
result["maps_to_existing"] = bool(iom.maps_to_existing_variable)
except Exception:
pass
try:
result["auto_iec_address"] = bool(iom.automatic_iec_address)
except Exception:
pass
try:
addr = iom.manual_iec_address
result["iec_address"] = _safe_str(addr) if addr else ""
except Exception:
result["iec_address"] = ""
return result
except Exception:
return None
def _read_params(param_set, channels_only):
"""Read device parameters, optionally filtering to I/O channels only."""
params = []
try:
param_list = list(param_set)
except Exception:
return params
for param in param_list:
try:
ct = param.channel_type
ct_str = _channel_type_str(ct)
if channels_only and ct_str == "none":
continue
entry = {
"name": _safe_str(getattr(param, "visible_name", "") or getattr(param, "name", "")),
"id": int(param.id) if hasattr(param, "id") else -1,
"channel_type": ct_str,
"bit_size": int(param.bit_size) if hasattr(param, "bit_size") else 0,
}
try:
entry["iec_type"] = _safe_str(param.iec_type) if param.iec_type else ""
except Exception:
entry["iec_type"] = ""
try:
entry["type_string"] = _safe_str(param.type_string)
except Exception:
entry["type_string"] = ""
try:
entry["section"] = _safe_str(param.section) if param.section else ""
except Exception:
entry["section"] = ""
mapping = _read_io_mapping(param)
if mapping is not None:
entry["io_mapping"] = mapping
if getattr(param, "has_sub_elements", False):
sub_entries = []
try:
for sub in list(param):
sub_entry = {
"name": _safe_str(getattr(sub, "visible_name", "") or getattr(sub, "identifier", "")),
"bit_size": int(sub.bit_size) if hasattr(sub, "bit_size") else 0,
}
try:
sub_entry["iec_type"] = _safe_str(sub.iec_type) if hasattr(sub, "iec_type") and sub.iec_type else ""
except Exception:
pass
sub_mapping = _read_io_mapping(sub)
if sub_mapping is not None:
sub_entry["io_mapping"] = sub_mapping
sub_entries.append(sub_entry)
except Exception:
pass
if sub_entries:
entry["sub_elements"] = sub_entries
params.append(entry)
except Exception:
continue
return params
def _walk_devices(node, path_parts, results, warnings, channels_only, max_depth, depth):
if depth > max_depth:
return
name = _name_of(node)
is_dev = getattr(node, "is_device", False)
if is_dev:
device_info = {
"name": name,
"path": "/".join(path_parts + [name]),
}
dev_id = _get_device_id(node)
if dev_id:
device_info["device_id"] = dev_id
try:
params = node.device_parameters
device_info["parameters"] = _read_params(params, channels_only)
device_info["parameter_count"] = len(device_info["parameters"])
except Exception as exc:
device_info["parameters"] = []
device_info["parameter_count"] = 0
warnings.append("params_failed({0}): {1}".format(name, exc))
connectors_info = []
try:
conn_set = node.connectors
for conn in list(conn_set):
ci = {
"connector_id": int(conn.connector_id),
"interface": _safe_str(conn.interface),
"role": "parent" if int(conn.connector_role) == 0 else "child",
}
try:
hp = conn.host_parameters
ci["host_parameters"] = _read_params(hp, channels_only)
except Exception:
pass
connectors_info.append(ci)
except Exception as exc:
warnings.append("connectors_failed({0}): {1}".format(name, exc))
if connectors_info:
device_info["connectors"] = connectors_info
results.append(device_info)
for child in _children_of(node):
try:
_walk_devices(child, path_parts + [name], results, warnings, channels_only, max_depth, depth + 1)
except Exception as exc:
warnings.append("walk_child_failed({0}): {1}".format(name, exc))
def main():
payload = load_payload()
project_path = payload.get("project_path")
if not project_path:
raise ValueError("project_path is required.")
channels_only = bool(payload.get("channels_only", True))
max_depth = int(payload.get("max_depth", 10))
export_csv_path = payload.get("export_csv_path", "")
pp = os.path.abspath(os.path.expanduser(project_path))
pp = _discover_project_file(pp)
if "projects" not in globals():
raise RuntimeError("Run through CODESYS ScriptEngine (--runscript).")
if projects.primary:
projects.primary.close()
if pp.lower().endswith(".projectarchive"):
project_dir = os.path.dirname(pp)
proj = projects.open_archive(pp, project_dir, overwrite=False)
else:
proj = projects.open(pp, primary=True, allow_readonly=True)
devices = []
warnings = []
try:
top_nodes = _children_of(proj)
except Exception as exc:
top_nodes = []
warnings.append("top_level_enumeration_failed: {0}".format(exc))
for top in top_nodes:
try:
_walk_devices(top, [], devices, warnings, channels_only, max_depth, 0)
except Exception as exc:
warnings.append("walk_failed: {0}".format(exc))
if export_csv_path:
try:
for top in top_nodes:
if getattr(top, "is_device", False):
top.export_io_mappings_as_csv(export_csv_path)
break
except Exception as exc:
warnings.append("csv_export_failed: {0}".format(exc))
proj.close()
emit({
"ok": True,
"action": "read_device_io",
"project_path": pp,
"devices": devices,
"device_count": len(devices),
"channels_only": channels_only,
"warnings": warnings,
})
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,188 @@
#!/usr/bin/env python
"""Read existing CODESYS project inventory via ScriptEngine."""
from __future__ import print_function
import os
from _common import emit, load_payload
def _discover_project_file(path_value):
if os.path.isfile(path_value):
lower_path = path_value.lower()
if lower_path.endswith(".project") or lower_path.endswith(".projectarchive"):
return path_value
raise RuntimeError(
"project_path must point to a .project or .projectarchive file. Got: {0}".format(path_value)
)
if os.path.isdir(path_value):
candidates = []
for entry in os.listdir(path_value):
full_path = os.path.join(path_value, entry)
if os.path.isfile(full_path):
lower_name = entry.lower()
if lower_name.endswith(".project") or lower_name.endswith(".projectarchive"):
candidates.append(full_path)
if len(candidates) == 1:
return candidates[0]
if not candidates:
raise RuntimeError(
"No .project or .projectarchive file found in directory: {0}".format(path_value)
)
raise RuntimeError(
"Multiple project files found in directory. Specify project_path explicitly: {0}".format(
", ".join(candidates)
)
)
raise RuntimeError("Project path does not exist: {0}".format(path_value))
def _name_of(obj):
try:
return obj.get_name(False)
except Exception:
try:
return obj.get_name()
except Exception:
return "{0}".format(obj)
def _children_of(obj):
try:
return list(obj.get_children(False))
except Exception:
try:
return list(obj.get_children())
except Exception:
return []
def _walk(node, depth, max_depth, rows):
if depth > max_depth:
return
kind = "node"
for attr in ("is_device", "is_application", "is_folder"):
if getattr(node, attr, False):
kind = attr.replace("is_", "")
break
rows.append({"name": _name_of(node), "kind": kind, "depth": depth})
for child in _children_of(node):
_walk(child, depth + 1, max_depth, rows)
def _text_from_doc(doc):
try:
return doc.text
except Exception:
try:
return doc.get_text(0, doc.length)
except Exception:
return None
def _collect_textual(node, path_names, collected):
name = _name_of(node)
decl = None
impl = None
try:
if getattr(node, "has_textual_declaration", False):
decl = _text_from_doc(node.textual_declaration)
except Exception:
pass
try:
if getattr(node, "has_textual_implementation", False):
impl = _text_from_doc(node.textual_implementation)
except Exception:
pass
if decl is not None or impl is not None:
collected.append(
{
"name": name,
"path": " / ".join(path_names + [name]),
"has_declaration": decl is not None,
"has_implementation": impl is not None,
"declaration": decl or "",
"implementation": impl or "",
}
)
for child in _children_of(node):
_collect_textual(child, path_names + [name], collected)
def main():
payload = load_payload()
project_path = payload.get("project_path")
max_depth = int(payload.get("max_depth", 3))
include_textual_sources = bool(payload.get("include_textual_sources", True))
if not project_path:
raise ValueError("project_path is required.")
pp = os.path.abspath(os.path.expanduser(project_path))
pp = _discover_project_file(pp)
if "projects" not in globals():
raise RuntimeError("Run through CODESYS ScriptEngine (--runscript).")
if projects.primary:
projects.primary.close()
if pp.lower().endswith(".projectarchive"):
project_dir = os.path.dirname(pp)
proj = projects.open_archive(pp, project_dir, overwrite=False)
else:
proj = projects.open(pp, primary=True, allow_readonly=True)
rows = []
warnings = []
try:
top_nodes = _children_of(proj)
except Exception as exc:
top_nodes = []
warnings.append("top_level_enumeration_failed: {0}".format(exc))
for top in top_nodes:
try:
_walk(top, depth=0, max_depth=max_depth, rows=rows)
except Exception as exc:
warnings.append("walk_failed_for_node: {0}".format(exc))
textual_sources = []
if include_textual_sources:
for top in top_nodes:
try:
_collect_textual(top, [], textual_sources)
except Exception as exc:
warnings.append("textual_collect_failed: {0}".format(exc))
active_app_name = None
try:
active_app = getattr(proj, "active_application", None)
except Exception as exc:
active_app = None
warnings.append("active_application_unavailable: {0}".format(exc))
if active_app is not None:
try:
active_app_name = _name_of(active_app)
except Exception as exc:
warnings.append("active_application_name_failed: {0}".format(exc))
proj.close()
emit(
{
"ok": True,
"action": "read_project_inventory",
"project_path": pp,
"active_application": active_app_name,
"nodes": rows,
"node_count": len(rows),
"textual_sources": textual_sources,
"textual_source_count": len(textual_sources),
"warnings": warnings,
}
)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,116 @@
#!/usr/bin/env python
"""Stage an existing CODESYS project into a standardized projects root folder."""
from __future__ import print_function
import os
import re
import shutil
from _common import emit, load_payload
def _is_project_file(name):
lower_name = name.lower()
return lower_name.endswith(".project") or lower_name.endswith(".projectarchive")
def _sanitize_folder_name(name):
cleaned = re.sub(r'[<>:"/\\|?*]+', "_", name or "")
cleaned = cleaned.strip().strip(".")
return cleaned or "codesys_project"
def _discover_project_file(source_path):
if os.path.isfile(source_path):
if _is_project_file(source_path):
return source_path
raise RuntimeError(
"source_path file must be .project or .projectarchive. Got: {0}".format(source_path)
)
if not os.path.isdir(source_path):
raise RuntimeError("source_path does not exist: {0}".format(source_path))
candidates = []
for root, _, files in os.walk(source_path):
for file_name in files:
if _is_project_file(file_name):
candidates.append(os.path.join(root, file_name))
if len(candidates) == 1:
return candidates[0]
if not candidates:
raise RuntimeError("No .project or .projectarchive found under: {0}".format(source_path))
raise RuntimeError(
"Multiple project files found under source_path. Use source_path as a specific file: {0}".format(
", ".join(candidates)
)
)
def _copy_or_move(source_dir, target_dir, move_mode):
if move_mode:
shutil.move(source_dir, target_dir)
else:
shutil.copytree(source_dir, target_dir)
def main():
payload = load_payload()
source_path = payload.get("source_path")
projects_root_dir = payload.get("projects_root_dir")
project_folder_name = payload.get("project_folder_name")
move_mode = bool(payload.get("move", False))
overwrite = bool(payload.get("overwrite", False))
if not source_path or not projects_root_dir:
raise ValueError("source_path and projects_root_dir are required.")
source_abs = os.path.abspath(os.path.expanduser(source_path))
root_abs = os.path.abspath(os.path.expanduser(projects_root_dir))
if not os.path.exists(source_abs):
raise RuntimeError("source_path does not exist: {0}".format(source_abs))
project_file_abs = _discover_project_file(source_abs)
source_dir_abs = os.path.dirname(project_file_abs)
inferred_folder_name = os.path.basename(source_dir_abs)
folder_name = _sanitize_folder_name(project_folder_name or inferred_folder_name)
if not os.path.exists(root_abs):
os.makedirs(root_abs)
target_dir_abs = os.path.join(root_abs, folder_name)
if os.path.exists(target_dir_abs):
if not overwrite:
raise RuntimeError("Target project folder already exists: {0}".format(target_dir_abs))
if os.path.isdir(target_dir_abs):
shutil.rmtree(target_dir_abs)
else:
os.remove(target_dir_abs)
_copy_or_move(source_dir_abs, target_dir_abs, move_mode)
relative_project_path = os.path.relpath(project_file_abs, source_dir_abs)
staged_project_path = os.path.join(target_dir_abs, relative_project_path)
if not os.path.exists(staged_project_path):
raise RuntimeError(
"Staged project file not found after transfer: {0}".format(staged_project_path)
)
emit(
{
"ok": True,
"action": "stage_existing_project",
"source_path": source_abs,
"projects_root_dir": root_abs,
"project_folder": target_dir_abs,
"project_path": staged_project_path,
"moved": move_mode,
"overwritten": overwrite,
}
)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,314 @@
#!/usr/bin/env python
"""Batch-push local source changes into a CODESYS project.
Receives a list of textual updates and IO mapping changes in a single payload,
applies them all in one project open/save cycle.
"""
from __future__ import print_function
import os
from _common import emit, load_payload
def _discover_project_file(path_value):
if os.path.isfile(path_value):
lower_path = path_value.lower()
if lower_path.endswith(".project") or lower_path.endswith(".projectarchive"):
return path_value
raise RuntimeError("project_path must be .project or .projectarchive: {0}".format(path_value))
if os.path.isdir(path_value):
candidates = []
for entry in os.listdir(path_value):
full_path = os.path.join(path_value, entry)
if os.path.isfile(full_path):
lower_name = entry.lower()
if lower_name.endswith(".project") or lower_name.endswith(".projectarchive"):
candidates.append(full_path)
if len(candidates) == 1:
return candidates[0]
if not candidates:
raise RuntimeError("No .project/.projectarchive in: {0}".format(path_value))
raise RuntimeError("Multiple project files: {0}".format(", ".join(candidates)))
raise RuntimeError("Path does not exist: {0}".format(path_value))
def _safe_str(val):
try:
return "{0}".format(val)
except Exception:
return "?"
def _name_of(obj):
try:
return obj.get_name(False)
except Exception:
try:
return obj.get_name()
except Exception:
return _safe_str(obj)
def _children_of(obj):
try:
return list(obj.get_children(False))
except Exception:
try:
return list(obj.get_children())
except Exception:
return []
def _find_by_path(root, path_str):
parts = [p.strip() for p in path_str.split("/") if p.strip()]
current = root
for i, part in enumerate(parts):
found = None
for child in _children_of(current):
if _name_of(child) == part:
found = child
break
if found is None:
return None
current = found
return current
def _set_text(doc, new_text):
try:
doc.replace(new_text=new_text)
except TypeError:
length = doc.length
if length > 0:
doc.remove(offset=0, length=length)
if new_text:
doc.append(new_text)
def _apply_textual_updates(proj, updates, results, warnings):
for upd in updates:
obj_path = upd.get("object_path", "")
obj_name = upd.get("object_name", "")
decl = upd.get("declaration")
impl = upd.get("implementation")
target_label = obj_path or obj_name
if not target_label:
warnings.append("skipped update: no object_path or object_name")
continue
try:
obj = None
if obj_path:
obj = _find_by_path(proj, obj_path)
if obj is None and obj_name:
found = proj.find(obj_name, True)
if found:
obj = found[0]
if obj is None:
warnings.append("not_found: {0}".format(target_label))
continue
name = _name_of(obj)
entry = {"name": name, "path": target_label, "declaration_updated": False, "implementation_updated": False}
if decl is not None and getattr(obj, "has_textual_declaration", False):
_set_text(obj.textual_declaration, decl)
entry["declaration_updated"] = True
if impl is not None and getattr(obj, "has_textual_implementation", False):
_set_text(obj.textual_implementation, impl)
entry["implementation_updated"] = True
results.append(entry)
except Exception as exc:
warnings.append("textual_update_failed({0}): {1}".format(target_label, exc))
def _apply_io_mappings(proj, mappings, results, warnings):
for m in mappings:
device_path = m.get("device_path", "")
param_id = m.get("param_id")
param_name = m.get("param_name")
variable = m.get("variable", "")
if not device_path or not variable:
warnings.append("io_mapping skipped: missing device_path or variable")
continue
try:
device = _find_by_path(proj, device_path)
if device is None:
warnings.append("device not found: {0}".format(device_path))
continue
target_param = None
try:
params = device.device_parameters
for p in list(params):
if param_id is not None and int(p.id) == int(param_id):
target_param = p
break
if param_name and _safe_str(getattr(p, "visible_name", "")) == param_name:
target_param = p
break
except Exception:
pass
if target_param is None:
for conn in list(device.connectors):
try:
hp = conn.host_parameters
for p in list(hp):
if param_id is not None and int(p.id) == int(param_id):
target_param = p
break
if param_name and _safe_str(getattr(p, "visible_name", "")) == param_name:
target_param = p
break
except Exception:
pass
if target_param:
break
if target_param is None:
warnings.append("param not found: id={0} name={1} on {2}".format(param_id, param_name, device_path))
continue
iom = target_param.io_mapping
if iom is None:
warnings.append("no io_mapping for param on {0}".format(device_path))
continue
old_var = _safe_str(iom.variable) if iom.variable else ""
iom.variable = variable
results.append({
"type": "io_mapping",
"device_path": device_path,
"param_id": int(target_param.id),
"old_variable": old_var,
"new_variable": variable,
"status": "mapped",
})
except Exception as exc:
warnings.append("io_mapping_failed({0}): {1}".format(device_path, exc))
def _apply_device_params(proj, params, results, warnings):
for dp in params:
device_path = dp.get("device_path", "")
param_id = dp.get("param_id")
param_name = dp.get("param_name", "")
value = dp.get("value")
if not device_path or value is None:
warnings.append("device_param skipped: missing device_path or value")
continue
try:
device = _find_by_path(proj, device_path)
if device is None:
warnings.append("device not found: {0}".format(device_path))
continue
target = None
for p in list(device.device_parameters):
if param_id is not None and int(p.id) == int(param_id):
target = p
break
if param_name and _safe_str(getattr(p, "visible_name", "")) == param_name:
target = p
break
if target is None:
warnings.append("param not found on {0}".format(device_path))
continue
old_val = _safe_str(target.value) if hasattr(target, "value") else "?"
target.value = _safe_str(value)
results.append({
"type": "device_param",
"device_path": device_path,
"param_id": int(target.id),
"old_value": old_val,
"new_value": _safe_str(value),
"status": "set",
})
except Exception as exc:
warnings.append("device_param_failed({0}): {1}".format(device_path, exc))
def main():
payload = load_payload()
project_path = payload.get("project_path")
if not project_path:
raise ValueError("project_path is required.")
dry_run = bool(payload.get("dry_run", False))
textual_updates = payload.get("textual_updates", [])
io_mappings = payload.get("io_mappings", [])
device_params = payload.get("device_params", [])
if not textual_updates and not io_mappings and not device_params:
raise ValueError("Nothing to sync. Provide textual_updates, io_mappings, or device_params.")
pp = os.path.abspath(os.path.expanduser(project_path))
pp = _discover_project_file(pp)
if "projects" not in globals():
raise RuntimeError("Run through CODESYS ScriptEngine (--runscript).")
if projects.primary:
projects.primary.close()
proj = projects.open(pp, primary=True)
results = []
warnings = []
if dry_run:
emit({
"ok": True,
"action": "sync_project",
"project_path": pp,
"dry_run": True,
"textual_update_count": len(textual_updates),
"io_mapping_count": len(io_mappings),
"device_param_count": len(device_params),
"message": "Dry-run: would apply {0} textual updates, {1} IO mappings, {2} device params.".format(
len(textual_updates), len(io_mappings), len(device_params)),
"warnings": [],
})
proj.close()
return
if textual_updates:
_apply_textual_updates(proj, textual_updates, results, warnings)
if io_mappings:
_apply_io_mappings(proj, io_mappings, results, warnings)
if device_params:
_apply_device_params(proj, device_params, results, warnings)
try:
proj.save()
except Exception as exc:
warnings.append("project_save_failed: {0}".format(exc))
proj.close()
emit({
"ok": True,
"action": "sync_project",
"project_path": pp,
"dry_run": False,
"results": results,
"result_count": len(results),
"warnings": warnings,
})
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,222 @@
#!/usr/bin/env python
"""Write I/O variable mappings in a CODESYS project via ScriptEngine."""
from __future__ import print_function
import os
from _common import emit, load_payload
def _discover_project_file(path_value):
if os.path.isfile(path_value):
lower_path = path_value.lower()
if lower_path.endswith(".project") or lower_path.endswith(".projectarchive"):
return path_value
raise RuntimeError(
"project_path must point to a .project or .projectarchive file. Got: {0}".format(path_value)
)
if os.path.isdir(path_value):
candidates = []
for entry in os.listdir(path_value):
full_path = os.path.join(path_value, entry)
if os.path.isfile(full_path):
lower_name = entry.lower()
if lower_name.endswith(".project") or lower_name.endswith(".projectarchive"):
candidates.append(full_path)
if len(candidates) == 1:
return candidates[0]
if not candidates:
raise RuntimeError("No .project/.projectarchive in directory: {0}".format(path_value))
raise RuntimeError("Multiple project files found: {0}".format(", ".join(candidates)))
raise RuntimeError("Project path does not exist: {0}".format(path_value))
def _safe_str(val):
try:
return "{0}".format(val)
except Exception:
return "?"
def _name_of(obj):
try:
return obj.get_name(False)
except Exception:
try:
return obj.get_name()
except Exception:
return _safe_str(obj)
def _children_of(obj):
try:
return list(obj.get_children(False))
except Exception:
try:
return list(obj.get_children())
except Exception:
return []
def _find_device_by_path(proj, device_path):
"""Walk the tree to find a device node matching the given slash-separated path."""
parts = [p.strip() for p in device_path.split("/") if p.strip()]
current_nodes = _children_of(proj)
target = None
for i, part in enumerate(parts):
found = None
for node in current_nodes:
if _name_of(node) == part:
found = node
break
if found is None:
raise RuntimeError(
"Device path segment '{0}' not found at depth {1}. Path: {2}".format(part, i, device_path)
)
if i == len(parts) - 1:
target = found
else:
current_nodes = _children_of(found)
return target
def _find_param(param_set, param_id=None, param_name=None):
"""Find a parameter by numeric id or name."""
for param in list(param_set):
if param_id is not None:
try:
if int(param.id) == int(param_id):
return param
except Exception:
pass
if param_name is not None:
try:
pname = _safe_str(getattr(param, "visible_name", "") or getattr(param, "name", ""))
if pname == param_name:
return param
except Exception:
pass
return None
def main():
payload = load_payload()
project_path = payload.get("project_path")
if not project_path:
raise ValueError("project_path is required.")
mappings = payload.get("mappings", [])
import_csv_path = payload.get("import_csv_path", "")
dry_run = bool(payload.get("dry_run", False))
if not mappings and not import_csv_path:
raise ValueError("Provide 'mappings' list or 'import_csv_path'.")
pp = os.path.abspath(os.path.expanduser(project_path))
pp = _discover_project_file(pp)
if "projects" not in globals():
raise RuntimeError("Run through CODESYS ScriptEngine (--runscript).")
if projects.primary:
projects.primary.close()
proj = projects.open(pp, primary=True)
results = []
warnings = []
if import_csv_path:
try:
for top in _children_of(proj):
if getattr(top, "is_device", False):
if dry_run:
results.append({
"action": "import_csv",
"csv_path": import_csv_path,
"dry_run": True,
"status": "would_import",
})
else:
top.import_io_mappings_from_csv(import_csv_path)
results.append({
"action": "import_csv",
"csv_path": import_csv_path,
"status": "imported",
})
break
except Exception as exc:
warnings.append("csv_import_failed: {0}".format(exc))
for m in mappings:
device_path = m.get("device_path", "")
param_id = m.get("param_id")
param_name = m.get("param_name")
variable = m.get("variable", "")
if not device_path:
warnings.append("mapping skipped: missing device_path")
continue
if not variable:
warnings.append("mapping skipped: missing variable for {0}".format(device_path))
continue
try:
device = _find_device_by_path(proj, device_path)
if device is None:
warnings.append("device not found: {0}".format(device_path))
continue
param = _find_param(device.device_parameters, param_id=param_id, param_name=param_name)
if param is None:
warnings.append("param not found: id={0} name={1} on {2}".format(param_id, param_name, device_path))
continue
iom = param.io_mapping
if iom is None:
warnings.append("no io_mapping on param {0} of {1}".format(param_id or param_name, device_path))
continue
old_var = _safe_str(iom.variable) if iom.variable else ""
entry = {
"device_path": device_path,
"param_id": int(param.id) if hasattr(param, "id") else -1,
"param_name": _safe_str(getattr(param, "visible_name", "")),
"old_variable": old_var,
"new_variable": variable,
}
if dry_run:
entry["status"] = "would_map"
else:
iom.variable = variable
entry["status"] = "mapped"
results.append(entry)
except Exception as exc:
warnings.append("mapping_failed({0}): {1}".format(device_path, exc))
if not dry_run:
try:
proj.save()
except Exception as exc:
warnings.append("project_save_failed: {0}".format(exc))
proj.close()
emit({
"ok": True,
"action": "write_io_mapping",
"project_path": pp,
"dry_run": dry_run,
"results": results,
"result_count": len(results),
"warnings": warnings,
})
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,208 @@
#!/usr/bin/env python
"""Write/update textual objects (POU, FB, GVL, NVL, struct, program) in a CODESYS project."""
from __future__ import print_function
import os
from _common import emit, load_payload
def _discover_project_file(path_value):
if os.path.isfile(path_value):
lower_path = path_value.lower()
if lower_path.endswith(".project") or lower_path.endswith(".projectarchive"):
return path_value
raise RuntimeError("project_path must be .project or .projectarchive: {0}".format(path_value))
if os.path.isdir(path_value):
candidates = []
for entry in os.listdir(path_value):
full_path = os.path.join(path_value, entry)
if os.path.isfile(full_path):
lower_name = entry.lower()
if lower_name.endswith(".project") or lower_name.endswith(".projectarchive"):
candidates.append(full_path)
if len(candidates) == 1:
return candidates[0]
if not candidates:
raise RuntimeError("No .project/.projectarchive in: {0}".format(path_value))
raise RuntimeError("Multiple project files: {0}".format(", ".join(candidates)))
raise RuntimeError("Path does not exist: {0}".format(path_value))
def _safe_str(val):
try:
return "{0}".format(val)
except Exception:
return "?"
def _name_of(obj):
try:
return obj.get_name(False)
except Exception:
try:
return obj.get_name()
except Exception:
return _safe_str(obj)
def _children_of(obj):
try:
return list(obj.get_children(False))
except Exception:
try:
return list(obj.get_children())
except Exception:
return []
def _find_by_path(root, path_str):
"""Walk slash-separated path from project root to find the target object."""
parts = [p.strip() for p in path_str.split("/") if p.strip()]
current = root
for i, part in enumerate(parts):
found = None
for child in _children_of(current):
if _name_of(child) == part:
found = child
break
if found is None:
raise RuntimeError("Object not found at '{0}' (segment {1} of '{2}')".format(
part, i, path_str))
current = found
return current
def _find_by_name(root, name):
"""Use project.find() with recursive search."""
results = root.find(name, True)
if not results:
raise RuntimeError("Object '{0}' not found in project.".format(name))
if len(results) > 1:
paths = []
for r in results:
try:
paths.append(_name_of(r))
except Exception:
paths.append("?")
raise RuntimeError("Multiple objects named '{0}': {1}. Use object_path instead.".format(
name, ", ".join(paths)))
return results[0]
def _set_text(doc, new_text):
"""Replace full text of a ScriptTextDocument."""
try:
doc.replace(new_text=new_text)
except TypeError:
length = doc.length
if length > 0:
doc.remove(offset=0, length=length)
if new_text:
doc.append(new_text)
def main():
payload = load_payload()
project_path = payload.get("project_path")
if not project_path:
raise ValueError("project_path is required.")
updates = payload.get("updates", [])
if not updates:
single = {}
for key in ("object_path", "object_name", "declaration", "implementation"):
if key in payload:
single[key] = payload[key]
if single:
updates = [single]
if not updates:
raise ValueError("Provide 'updates' list or single object_path/object_name + declaration/implementation.")
dry_run = bool(payload.get("dry_run", False))
pp = os.path.abspath(os.path.expanduser(project_path))
pp = _discover_project_file(pp)
if "projects" not in globals():
raise RuntimeError("Run through CODESYS ScriptEngine (--runscript).")
if projects.primary:
projects.primary.close()
proj = projects.open(pp, primary=True)
results = []
warnings = []
for upd in updates:
obj_path = upd.get("object_path", "")
obj_name = upd.get("object_name", "")
decl_text = upd.get("declaration")
impl_text = upd.get("implementation")
if not obj_path and not obj_name:
warnings.append("update skipped: no object_path or object_name")
continue
try:
if obj_path:
obj = _find_by_path(proj, obj_path)
else:
obj = _find_by_name(proj, obj_name)
name = _name_of(obj)
entry = {
"name": name,
"object_path": obj_path or obj_name,
"has_declaration": getattr(obj, "has_textual_declaration", False),
"has_implementation": getattr(obj, "has_textual_implementation", False),
"declaration_updated": False,
"implementation_updated": False,
}
if decl_text is not None:
if not getattr(obj, "has_textual_declaration", False):
warnings.append("{0}: object has no textual declaration".format(name))
elif dry_run:
entry["declaration_updated"] = "would_update"
else:
_set_text(obj.textual_declaration, decl_text)
entry["declaration_updated"] = True
if impl_text is not None:
if not getattr(obj, "has_textual_implementation", False):
warnings.append("{0}: object has no textual implementation".format(name))
elif dry_run:
entry["implementation_updated"] = "would_update"
else:
_set_text(obj.textual_implementation, impl_text)
entry["implementation_updated"] = True
results.append(entry)
except Exception as exc:
warnings.append("update_failed({0}): {1}".format(obj_path or obj_name, exc))
if not dry_run:
try:
proj.save()
except Exception as exc:
warnings.append("project_save_failed: {0}".format(exc))
proj.close()
emit({
"ok": True,
"action": "write_pou",
"project_path": pp,
"dry_run": dry_run,
"results": results,
"result_count": len(results),
"warnings": warnings,
})
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,23 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"env": {
"node": true,
"es2022": true
},
"ignorePatterns": [
"out",
"node_modules"
],
"rules": {
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/explicit-module-boundary-types": "off"
}
}

View File

@@ -0,0 +1,6 @@
src/**
tsconfig.json
.eslintrc.json
**/*.map
**/*.ts
.vscode-test/**

View File

@@ -0,0 +1,84 @@
# CODESYS MCP Companion Extension
VS Code/Cursor companion extension for the CODESYS MCP bridge.
This extension provides command workflows, project/actions/jobs views, status bar state, and diagnostics for the existing Python MCP bridge located at:
- `python_scripting/mcp_codesys_bridge/server.py`
## Features
- MCP bridge lifecycle and health check
- Project-level commands:
- create project
- stage existing project
- read project inventory
- read device I/O
- write POU
- write I/O mapping
- manage device
- sync project
- build project
- download to device
- Job polling UX through Jobs view
- Error diagnostics surfaced in Problems panel
- ST language support:
- syntax grammar
- snippets
- context menu action for current ST file sync
## Settings
All settings are under the `codesys.*` namespace:
- `codesys.pythonPath`
- `codesys.bridgeScriptPath`
- `codesys.agentUrl`
- `codesys.agentToken`
- `codesys.requestTimeoutSec`
- `codesys.pollIntervalMs`
- `codesys.defaultProjectPath`
- `codesys.defaultDryRunMutations`
- `codesys.allowDownloadCommand`
## Local Development
Prerequisites:
- Node.js 20+
- npm 10+
- Python 3 available for bridge startup
Install and build:
```bash
cd vscode_codesys_companion
npm install
npm run check
```
Run extension in Extension Development Host:
1. Open `vscode_codesys_companion` in VS Code/Cursor.
2. Press `F5`.
3. Use command palette commands with prefix `CODESYS:`.
## Packaging
Build VSIX package:
```bash
cd vscode_codesys_companion
npm install
npm run compile
npm run package
```
## Operational Notes
- Keep mutating operations in dry-run mode first.
- `download_to_device` command is gated by `codesys.allowDownloadCommand`.
- Bridge auth requires `codesys.agentToken` to match VM agent token.
- Align operations with:
- `python_scripting/how-to-use-codesys-mcp.md`
- `python_scripting/codesys-mcp-bridge-operations.md`

View File

@@ -0,0 +1,56 @@
# Companion Extension Smoke Test
This validates extension + MCP bridge + VM agent integration.
## 1. Preconditions
- Windows VM agent is reachable.
- `codesys.agentUrl` and `codesys.agentToken` are configured in extension settings.
- CODESYS bridge script path resolves correctly.
Reference operational guide:
- `../python_scripting/codesys-mcp-bridge-operations.md`
## 2. Connect + Health
1. Run `CODESYS: Connect MCP Bridge`.
2. Run `CODESYS: Health Check`.
3. Confirm status bar shows connected and output logs health response.
## 3. Project Selection
1. Run `CODESYS: Select Project`.
2. Provide a valid project path.
3. Confirm Projects view shows active project.
## 4. Read Workflows
1. Run `CODESYS: Read Project Inventory`.
2. Run `CODESYS: Read Device I/O`.
3. Confirm Jobs view shows `succeeded` for both jobs.
## 5. Safe Mutation (Dry Run)
1. Run `CODESYS: Sync Project`.
2. Keep dry-run enabled.
3. Confirm job success and no errors in Problems view.
## 6. Build
1. Run `CODESYS: Build Project`.
2. Confirm job success.
## 7. Optional Deploy
1. Set `codesys.allowDownloadCommand=true`.
2. Run `CODESYS: Download To Device`.
3. Validate target confirmation and completion.
## 8. Failure Signal Check
1. Intentionally provide bad input (for example invalid project path) to `Read Project Inventory`.
2. Confirm failure:
- appears in output
- appears in Jobs view
- appears in Problems panel diagnostics

View File

@@ -0,0 +1,47 @@
{
"comments": {
"lineComment": "//",
"blockComment": [
"(*",
"*)"
]
},
"brackets": [
[
"(",
")"
],
[
"[",
"]"
]
],
"autoClosingPairs": [
{
"open": "(",
"close": ")"
},
{
"open": "[",
"close": "]"
},
{
"open": "\"",
"close": "\""
}
],
"surroundingPairs": [
[
"(",
")"
],
[
"[",
"]"
],
[
"\"",
"\""
]
]
}

View File

@@ -0,0 +1,4 @@
<svg width="128" height="128" viewBox="0 0 128 128" xmlns="http://www.w3.org/2000/svg">
<rect x="8" y="8" width="112" height="112" rx="14" fill="#2b2b2b"/>
<path d="M30 88V40h18l11 20 11-20h18v48H74V66l-15 22-15-22v22H30z" fill="#f2f2f2"/>
</svg>

After

Width:  |  Height:  |  Size: 251 B

6192
vscode_codesys_companion/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,240 @@
{
"name": "codesys-mcp-companion",
"displayName": "CODESYS MCP Companion",
"description": "VS Code/Cursor companion extension for CODESYS MCP bridge workflows.",
"version": "0.1.0",
"publisher": "nearxos",
"private": true,
"engines": {
"vscode": "^1.90.0"
},
"categories": [
"Other",
"Programming Languages"
],
"activationEvents": [
"onStartupFinished",
"onCommand:codesys.connect",
"onCommand:codesys.health",
"onCommand:codesys.createProject",
"onCommand:codesys.syncProject",
"onCommand:codesys.buildProject",
"onCommand:codesys.downloadToDevice"
],
"main": "./out/extension.js",
"contributes": {
"commands": [
{
"command": "codesys.connect",
"title": "CODESYS: Connect MCP Bridge"
},
{
"command": "codesys.health",
"title": "CODESYS: Health Check"
},
{
"command": "codesys.createProject",
"title": "CODESYS: Create Project"
},
{
"command": "codesys.selectProject",
"title": "CODESYS: Select Project"
},
{
"command": "codesys.stageExistingProject",
"title": "CODESYS: Stage Existing Project"
},
{
"command": "codesys.readProjectInventory",
"title": "CODESYS: Read Project Inventory"
},
{
"command": "codesys.readDeviceIo",
"title": "CODESYS: Read Device I/O"
},
{
"command": "codesys.writePou",
"title": "CODESYS: Write POU"
},
{
"command": "codesys.writeIoMapping",
"title": "CODESYS: Write IO Mapping"
},
{
"command": "codesys.manageDevice",
"title": "CODESYS: Manage Device"
},
{
"command": "codesys.syncProject",
"title": "CODESYS: Sync Project"
},
{
"command": "codesys.buildProject",
"title": "CODESYS: Build Project"
},
{
"command": "codesys.downloadToDevice",
"title": "CODESYS: Download To Device"
},
{
"command": "codesys.refreshJobs",
"title": "CODESYS: Refresh Jobs"
},
{
"command": "codesys.openOutput",
"title": "CODESYS: Open Output"
},
{
"command": "codesys.syncCurrentFile",
"title": "CODESYS: Sync Current ST File"
}
],
"configuration": {
"title": "CODESYS MCP Companion",
"properties": {
"codesys.pythonPath": {
"type": "string",
"default": "python",
"description": "Python executable used to launch the CODESYS MCP bridge server."
},
"codesys.bridgeScriptPath": {
"type": "string",
"default": "",
"description": "Absolute path to python_scripting/mcp_codesys_bridge/server.py. If empty, default repo-relative path is used."
},
"codesys.agentUrl": {
"type": "string",
"default": "http://127.0.0.1:8787",
"description": "Windows CODESYS agent URL passed to MCP bridge."
},
"codesys.agentToken": {
"type": "string",
"default": "",
"description": "Windows CODESYS agent shared token."
},
"codesys.requestTimeoutSec": {
"type": "number",
"default": 30,
"minimum": 5,
"description": "CODESYS MCP bridge request timeout in seconds."
},
"codesys.pollIntervalMs": {
"type": "number",
"default": 1500,
"minimum": 500,
"description": "Polling interval for asynchronous job progress."
},
"codesys.defaultProjectPath": {
"type": "string",
"default": "",
"description": "Default CODESYS project path used by commands."
},
"codesys.defaultDryRunMutations": {
"type": "boolean",
"default": true,
"description": "Run mutating operations in dry-run mode unless explicitly disabled in command input."
},
"codesys.allowDownloadCommand": {
"type": "boolean",
"default": false,
"description": "Enable UI command for download_to_device."
},
"codesys.mockMode": {
"type": "boolean",
"default": false,
"description": "Use local mocked MCP responses for extension integration testing."
}
}
},
"viewsContainers": {
"activitybar": [
{
"id": "codesys",
"title": "CODESYS",
"icon": "media/codesys.svg"
}
]
},
"views": {
"codesys": [
{
"id": "codesysProjectsView",
"name": "Projects"
},
{
"id": "codesysJobsView",
"name": "Jobs"
},
{
"id": "codesysActionsView",
"name": "Actions"
}
]
},
"menus": {
"editor/context": [
{
"command": "codesys.syncCurrentFile",
"when": "resourceExtname =~ /\\.st$/ || resourceExtname =~ /\\.gvl$/ || resourceExtname =~ /\\.nvl$/ || resourceExtname =~ /\\.txt$/",
"group": "navigation@90"
}
],
"view/title": [
{
"command": "codesys.refreshJobs",
"when": "view == codesysJobsView",
"group": "navigation"
}
]
},
"languages": [
{
"id": "codesys-st",
"aliases": [
"CODESYS Structured Text",
"ST"
],
"extensions": [
".st",
".gvl",
".nvl",
".type.st"
],
"configuration": "./language-configuration.json"
}
],
"grammars": [
{
"language": "codesys-st",
"scopeName": "source.codesys.st",
"path": "./syntaxes/codesys-st.tmLanguage.json"
}
],
"snippets": [
{
"language": "codesys-st",
"path": "./snippets/codesys-st.json"
}
]
},
"scripts": {
"compile": "tsc -p ./",
"watch": "tsc -watch -p ./",
"lint": "eslint src --ext ts",
"test": "npm run compile && node ./out/test/runTest.js",
"package": "vsce package --no-dependencies",
"check": "npm run compile && npm run lint"
},
"devDependencies": {
"@types/mocha": "^10.0.8",
"@types/node": "^20.16.5",
"@types/vscode": "^1.90.0",
"@typescript-eslint/eslint-plugin": "^8.13.0",
"@typescript-eslint/parser": "^8.13.0",
"@vscode/test-electron": "^2.4.1",
"@vscode/vsce": "^3.2.2",
"eslint": "^8.57.1",
"mocha": "^10.7.3",
"typescript": "^5.6.2"
}
}

View File

@@ -0,0 +1,46 @@
{
"Function Block": {
"prefix": "fb",
"body": [
"FUNCTION_BLOCK ${1:FB_Name}",
"VAR_INPUT",
" ${2:inputVar} : ${3:BOOL};",
"END_VAR",
"",
"VAR_OUTPUT",
" ${4:outputVar} : ${5:BOOL};",
"END_VAR",
"",
"VAR",
" ${6:internalVar} : ${7:BOOL};",
"END_VAR",
"",
"${0}",
"END_FUNCTION_BLOCK"
],
"description": "CODESYS function block template"
},
"Program": {
"prefix": "prg",
"body": [
"PROGRAM ${1:PLC_PRG}",
"VAR",
" ${2:xStart} : BOOL;",
"END_VAR",
"",
"${0}",
"END_PROGRAM"
],
"description": "CODESYS program template"
},
"Timer TON": {
"prefix": "ton",
"body": [
"${1:tonTimer}(IN := ${2:xEnable}, PT := T#${3:1s});",
"IF ${1:tonTimer}.Q THEN",
" ${0}",
"END_IF;"
],
"description": "Insert TON call template"
}
}

View File

@@ -0,0 +1,10 @@
import { JsonObject } from "../types";
export function buildDefaultSyncPayload(projectPath: string): JsonObject {
return {
project_path: projectPath,
textual_updates: [],
io_mappings: [],
device_params: []
};
}

View File

@@ -0,0 +1,243 @@
import * as vscode from "vscode";
import { CompanionSettings, resolveBridgeScriptPath } from "../config";
import { Logger } from "../logging";
import { McpClient } from "../mcp/client";
import { JsonObject, McpCallResult } from "../types";
export interface CodesysCallOptions {
dryRun?: boolean;
poll?: boolean;
}
export interface JobRecord {
id: string;
action: string;
status: string;
detail?: string;
}
export class CodesysService {
private client?: McpClient;
private connected = false;
private readonly jobs = new Map<string, JobRecord>();
constructor(
private readonly logger: Logger,
private readonly settings: CompanionSettings,
private readonly diagnostics: vscode.DiagnosticCollection
) {}
public getJobs(): JobRecord[] {
return Array.from(this.jobs.values()).sort((a, b) => b.id.localeCompare(a.id));
}
public isConnected(): boolean {
return this.connected;
}
public async connect(): Promise<void> {
if (this.settings.mockMode) {
this.connected = true;
this.logger.info("Mock mode enabled. MCP process is not started.");
return;
}
if (this.connected && this.client) {
return;
}
const bridgeScriptPath = resolveBridgeScriptPath(this.settings);
const client = new McpClient({
pythonPath: this.settings.pythonPath,
bridgeScriptPath,
environment: {
CODESYS_AGENT_URL: this.settings.agentUrl,
CODESYS_AGENT_TOKEN: this.settings.agentToken,
CODESYS_AGENT_REQUEST_TIMEOUT_SEC: String(this.settings.requestTimeoutSec)
},
logger: this.logger
});
await client.connect();
await client.listTools();
this.client = client;
this.connected = true;
}
public async disconnect(): Promise<void> {
await this.client?.disconnect();
this.client = undefined;
this.connected = false;
}
public async call(action: string, payload: JsonObject, options: CodesysCallOptions = {}): Promise<JsonObject> {
if (this.settings.mockMode) {
return this.mockCall(action, payload, options);
}
await this.connect();
const mergedPayload: JsonObject = { ...payload };
if (options.dryRun !== undefined) {
mergedPayload.dry_run = options.dryRun;
}
const result = await this.executeTool(action, mergedPayload);
const jobId = extractJobId(result);
if (!jobId || !options.poll) {
return result;
}
this.jobs.set(jobId, { id: jobId, action, status: "queued", detail: "submitted" });
return this.pollJob(action, jobId);
}
private async mockCall(action: string, payload: JsonObject, options: CodesysCallOptions): Promise<JsonObject> {
if (action === "codesys_health") {
return { ok: true, service: "codesys-vm-agent", mocked: true };
}
if (action === "codesys_get_job") {
return {
id: String(payload.job_id ?? "mock-job"),
action: "mock_action",
status: "succeeded",
result: { mocked: true }
};
}
const dryRun = typeof options.dryRun === "boolean" ? options.dryRun : this.settings.defaultDryRunMutations;
return {
mocked: true,
action,
payload,
dry_run: dryRun,
job_id: `mock-${Date.now()}`
};
}
public async codesysHealth(): Promise<JsonObject> {
return this.call("codesys_health", {}, { poll: false });
}
public async codesysSubmitJob(payload: JsonObject): Promise<JsonObject> {
return this.call("codesys_submit_job", payload, { poll: false });
}
public async codesysGetJob(payload: JsonObject): Promise<JsonObject> {
return this.call("codesys_get_job", payload, { poll: false });
}
public async createProject(payload: JsonObject, options: CodesysCallOptions): Promise<JsonObject> {
return this.call("create_project", payload, { ...options, poll: true });
}
public async stageExistingProject(payload: JsonObject, options: CodesysCallOptions): Promise<JsonObject> {
return this.call("stage_existing_project", payload, options);
}
public async readProjectInventory(payload: JsonObject): Promise<JsonObject> {
return this.call("read_project_inventory", payload, { poll: true });
}
public async readDeviceIo(payload: JsonObject): Promise<JsonObject> {
return this.call("read_device_io", payload, { poll: true });
}
public async writePou(payload: JsonObject, options: CodesysCallOptions): Promise<JsonObject> {
return this.call("write_pou", payload, { ...options, poll: true });
}
public async writeIoMapping(payload: JsonObject, options: CodesysCallOptions): Promise<JsonObject> {
return this.call("write_io_mapping", payload, { ...options, poll: true });
}
public async manageDevice(payload: JsonObject, options: CodesysCallOptions): Promise<JsonObject> {
return this.call("manage_device", payload, { ...options, poll: true });
}
public async syncProject(payload: JsonObject, options: CodesysCallOptions): Promise<JsonObject> {
return this.call("sync_project", payload, { ...options, poll: true });
}
public async buildProject(payload: JsonObject): Promise<JsonObject> {
return this.call("build_project", payload, { poll: true });
}
public async downloadToDevice(payload: JsonObject): Promise<JsonObject> {
return this.call("download_to_device", payload, { poll: true });
}
public async pollJob(action: string, jobId: string): Promise<JsonObject> {
const pollInterval = Math.max(500, this.settings.pollIntervalMs);
while (true) {
const result = await this.executeTool("codesys_get_job", { job_id: jobId });
const status = String(result.status ?? "unknown");
this.jobs.set(jobId, {
id: jobId,
action,
status,
detail: status === "failed" ? String(result.error ?? "Unknown error") : undefined
});
if (status === "succeeded" || status === "failed") {
if (status === "failed") {
this.raiseDiagnostic(String(result.error ?? `Job ${jobId} failed.`));
} else {
this.clearDiagnostics();
}
return result;
}
await sleep(pollInterval);
}
}
private async executeTool(tool: string, payload: JsonObject): Promise<JsonObject> {
const response = await this.client?.callTool(tool, payload);
if (!response) {
throw new Error(`No response from MCP tool ${tool}`);
}
const parsed = this.parseToolResult(response);
return parsed;
}
private parseToolResult(response: McpCallResult): JsonObject {
if (response.structuredContent) {
return response.structuredContent;
}
const text = response.content?.find((item) => item.type === "text")?.text;
if (!text) {
return {};
}
try {
return JSON.parse(text) as JsonObject;
} catch {
return { text };
}
}
private raiseDiagnostic(message: string): void {
const wsFolder = vscode.workspace.workspaceFolders?.[0]?.uri;
if (!wsFolder) {
return;
}
const uri = vscode.Uri.joinPath(wsFolder, ".codesys-mcp-errors");
const diagnostic = new vscode.Diagnostic(
new vscode.Range(new vscode.Position(0, 0), new vscode.Position(0, 1)),
message,
vscode.DiagnosticSeverity.Error
);
diagnostic.source = "codesys-mcp";
this.diagnostics.set(uri, [diagnostic]);
}
private clearDiagnostics(): void {
this.diagnostics.clear();
}
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function extractJobId(result: JsonObject): string | undefined {
const id = result.job_id;
return typeof id === "string" && id.length > 0 ? id : undefined;
}

View File

@@ -0,0 +1,296 @@
import * as path from "path";
import * as vscode from "vscode";
import { CompanionSettings } from "./config";
import { buildDefaultSyncPayload } from "./codesys/payloads";
import { CodesysService } from "./codesys/service";
import { Logger } from "./logging";
import { ExtensionState } from "./state";
import { JsonObject } from "./types";
import { ActionsViewProvider, JobsViewProvider, ProjectsViewProvider } from "./views";
interface CommandDeps {
service: CodesysService;
logger: Logger;
state: ExtensionState;
settings: CompanionSettings;
status: vscode.StatusBarItem;
projectsView: ProjectsViewProvider;
jobsView: JobsViewProvider;
actionsView: ActionsViewProvider;
}
export function registerCommands(context: vscode.ExtensionContext, deps: CommandDeps): void {
const register = (name: string, callback: () => Promise<void>) =>
context.subscriptions.push(
vscode.commands.registerCommand(name, async () => {
try {
await callback();
deps.jobsView.refresh();
deps.projectsView.refresh();
deps.actionsView.refresh();
updateStatus(deps);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
deps.logger.error(message);
vscode.window.showErrorMessage(`CODESYS: ${message}`);
}
})
);
register("codesys.connect", async () => {
await deps.service.connect();
deps.logger.info("Connected to MCP bridge.");
vscode.window.showInformationMessage("Connected to CODESYS MCP bridge.");
});
register("codesys.health", async () => {
const result = await deps.service.codesysHealth();
deps.logger.info(`health: ${JSON.stringify(result)}`);
vscode.window.showInformationMessage(`CODESYS health ok=${String(result.ok ?? "unknown")}`);
});
register("codesys.createProject", async () => {
const projectName = await ask("Project name", "NewProject");
const outputDir = await ask("Output directory", "C:\\\\Temp\\\\codesys-projects");
if (!projectName || !outputDir) {
return;
}
const template = (await ask("Template", "standard")) ?? "standard";
const dryRun = await askDryRun(deps.settings.defaultDryRunMutations);
const result = await deps.service.createProject(
{ project_name: projectName, output_dir: outputDir, template },
{ dryRun }
);
deps.logger.info(`create_project: ${JSON.stringify(result)}`);
});
register("codesys.selectProject", async () => {
const value = await vscode.window.showInputBox({
prompt: "Project path (.project/.projectarchive or folder)",
value: deps.state.activeProjectPath || deps.settings.defaultProjectPath
});
if (!value) {
return;
}
await deps.state.setActiveProjectPath(value);
});
register("codesys.stageExistingProject", async () => {
const sourcePath = await ask("Source path", "");
const projectsRootDir = await ask("Projects root dir", "");
if (!sourcePath || !projectsRootDir) {
return;
}
const projectFolderName = (await ask("Project folder name (optional)", "")) ?? "";
const move = await askQuickPickBoolean("Move source instead of copy?", false);
const overwrite = await askQuickPickBoolean("Overwrite existing destination?", false);
const dryRun = await askDryRun(deps.settings.defaultDryRunMutations);
const result = await deps.service.stageExistingProject(
{ source_path: sourcePath, projects_root_dir: projectsRootDir, project_folder_name: projectFolderName, move, overwrite },
{ dryRun, poll: true }
);
deps.logger.info(`stage_existing_project: ${JSON.stringify(result)}`);
});
register("codesys.readProjectInventory", async () => {
const projectPath = await requireProjectPath(deps);
if (!projectPath) {
return;
}
const maxDepth = Number.parseInt((await ask("max_depth", "3")) ?? "3", 10);
const result = await deps.service.readProjectInventory({ project_path: projectPath, max_depth: Number.isFinite(maxDepth) ? maxDepth : 3 });
deps.logger.info(`read_project_inventory: ${JSON.stringify(result)}`);
});
register("codesys.readDeviceIo", async () => {
const projectPath = await requireProjectPath(deps);
if (!projectPath) {
return;
}
const channelsOnly = await askQuickPickBoolean("Read channels only?", true);
const maxDepth = Number.parseInt((await ask("max_depth", "10")) ?? "10", 10);
const result = await deps.service.readDeviceIo({
project_path: projectPath,
channels_only: channelsOnly,
max_depth: Number.isFinite(maxDepth) ? maxDepth : 10
});
deps.logger.info(`read_device_io: ${JSON.stringify(result)}`);
});
register("codesys.writePou", async () => {
const projectPath = await requireProjectPath(deps);
if (!projectPath) {
return;
}
const objectPath = await ask("Object path", "");
const declaration = await ask("Declaration text (optional)", "");
const implementation = await ask("Implementation text (optional)", "");
if (!objectPath) {
return;
}
const dryRun = await askDryRun(deps.settings.defaultDryRunMutations);
const result = await deps.service.writePou(
{ project_path: projectPath, object_path: objectPath, declaration: declaration ?? "", implementation: implementation ?? "" },
{ dryRun }
);
deps.logger.info(`write_pou: ${JSON.stringify(result)}`);
});
register("codesys.writeIoMapping", async () => {
const projectPath = await requireProjectPath(deps);
if (!projectPath) {
return;
}
const devicePath = await ask("Device path", "");
const paramId = await ask("Param id", "");
const variable = await ask("IEC variable", "");
if (!devicePath || !paramId || !variable) {
return;
}
const dryRun = await askDryRun(deps.settings.defaultDryRunMutations);
const mappings = [{ device_path: devicePath, param_id: paramId, variable }];
const result = await deps.service.writeIoMapping(
{ project_path: projectPath, mappings },
{ dryRun }
);
deps.logger.info(`write_io_mapping: ${JSON.stringify(result)}`);
});
register("codesys.manageDevice", async () => {
const projectPath = await requireProjectPath(deps);
if (!projectPath) {
return;
}
const operationText = await ask("Operation JSON (single operation object)", '{"action_type":"rename","device_path":"Device/X","new_name":"X"}');
if (!operationText) {
return;
}
const operation = JSON.parse(operationText) as JsonObject;
const dryRun = await askDryRun(deps.settings.defaultDryRunMutations);
const result = await deps.service.manageDevice({ project_path: projectPath, operations: [operation] }, { dryRun });
deps.logger.info(`manage_device: ${JSON.stringify(result)}`);
});
register("codesys.syncProject", async () => {
const projectPath = await requireProjectPath(deps);
if (!projectPath) {
return;
}
const dryRun = await askDryRun(deps.settings.defaultDryRunMutations);
const result = await deps.service.syncProject(buildDefaultSyncPayload(projectPath), { dryRun });
deps.logger.info(`sync_project: ${JSON.stringify(result)}`);
});
register("codesys.buildProject", async () => {
const projectPath = await requireProjectPath(deps);
if (!projectPath) {
return;
}
const result = await deps.service.buildProject({ project_path: projectPath });
deps.logger.info(`build_project: ${JSON.stringify(result)}`);
});
register("codesys.downloadToDevice", async () => {
if (!deps.settings.allowDownloadCommand) {
vscode.window.showWarningMessage("Download command disabled by setting codesys.allowDownloadCommand.");
return;
}
const projectPath = await requireProjectPath(deps);
if (!projectPath) {
return;
}
const targetName = await ask("Target name", "");
if (!targetName) {
return;
}
const startApplication = await askQuickPickBoolean("Start application after download?", false);
const result = await deps.service.downloadToDevice(
{ project_path: projectPath, target_name: targetName, start_application: startApplication },
);
deps.logger.info(`download_to_device: ${JSON.stringify(result)}`);
});
register("codesys.refreshJobs", async () => {
deps.jobsView.refresh();
deps.logger.info("Jobs view refreshed.");
});
register("codesys.openOutput", async () => {
deps.logger.show();
});
register("codesys.syncCurrentFile", async () => {
const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
const projectPath = await requireProjectPath(deps);
if (!projectPath) {
return;
}
const absFilePath = editor.document.uri.fsPath;
const objectPath = inferCodesysObjectPath(absFilePath);
const declaration = editor.document.getText();
const dryRun = await askDryRun(deps.settings.defaultDryRunMutations);
const result = await deps.service.writePou(
{ project_path: projectPath, object_path: objectPath, declaration, implementation: "" },
{ dryRun }
);
deps.logger.info(`syncCurrentFile write_pou: ${JSON.stringify(result)}`);
});
updateStatus(deps);
}
function updateStatus(deps: CommandDeps): void {
deps.status.text = deps.service.isConnected() ? "CODESYS: Connected" : "CODESYS: Disconnected";
deps.status.tooltip = deps.state.activeProjectPath || "No active project selected";
}
async function requireProjectPath(deps: CommandDeps): Promise<string | undefined> {
if (deps.state.activeProjectPath) {
return deps.state.activeProjectPath;
}
const fallback = deps.settings.defaultProjectPath;
const chosen = await vscode.window.showInputBox({
prompt: "Project path",
value: fallback
});
if (!chosen) {
return undefined;
}
await deps.state.setActiveProjectPath(chosen);
return chosen;
}
async function ask(prompt: string, value: string): Promise<string | undefined> {
return vscode.window.showInputBox({ prompt, value });
}
async function askQuickPickBoolean(prompt: string, defaultValue: boolean): Promise<boolean> {
const defaultLabel = defaultValue ? "yes" : "no";
const selected = await vscode.window.showQuickPick(["yes", "no"], { placeHolder: `${prompt} (default: ${defaultLabel})` });
return (selected ?? defaultLabel) === "yes";
}
async function askDryRun(defaultValue: boolean): Promise<boolean> {
return askQuickPickBoolean("Run in dry-run mode?", defaultValue);
}
function inferCodesysObjectPath(absFilePath: string): string {
const marker = `${path.sep}codesys_tree${path.sep}`;
const index = absFilePath.indexOf(marker);
if (index < 0) {
return path.basename(absFilePath);
}
const relative = absFilePath.slice(index + marker.length).replaceAll(path.sep, "/");
const withoutExt = relative
.replace(/\.program\.st$/i, "")
.replace(/\.fb\.st$/i, "")
.replace(/\.type\.st$/i, "")
.replace(/\.gvl$/i, "")
.replace(/\.nvl$/i, "")
.replace(/\.st$/i, "");
return withoutExt;
}

View File

@@ -0,0 +1,44 @@
import * as path from "path";
import * as vscode from "vscode";
export interface CompanionSettings {
pythonPath: string;
bridgeScriptPath: string;
agentUrl: string;
agentToken: string;
requestTimeoutSec: number;
pollIntervalMs: number;
defaultProjectPath: string;
defaultDryRunMutations: boolean;
allowDownloadCommand: boolean;
mockMode: boolean;
}
export function readSettings(): CompanionSettings {
const cfg = vscode.workspace.getConfiguration("codesys");
return {
pythonPath: cfg.get<string>("pythonPath", "python"),
bridgeScriptPath: cfg.get<string>("bridgeScriptPath", ""),
agentUrl: cfg.get<string>("agentUrl", "http://127.0.0.1:8787"),
agentToken: cfg.get<string>("agentToken", ""),
requestTimeoutSec: cfg.get<number>("requestTimeoutSec", 30),
pollIntervalMs: cfg.get<number>("pollIntervalMs", 1500),
defaultProjectPath: cfg.get<string>("defaultProjectPath", ""),
defaultDryRunMutations: cfg.get<boolean>("defaultDryRunMutations", true),
allowDownloadCommand: cfg.get<boolean>("allowDownloadCommand", false),
mockMode: cfg.get<boolean>("mockMode", false)
};
}
export function resolveBridgeScriptPath(settings: CompanionSettings): string {
if (settings.bridgeScriptPath.trim()) {
return settings.bridgeScriptPath.trim();
}
const root = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
if (root) {
return path.resolve(root, "python_scripting", "mcp_codesys_bridge", "server.py");
}
throw new Error("No workspace open and codesys.bridgeScriptPath is empty.");
}

View File

@@ -0,0 +1,51 @@
import * as vscode from "vscode";
import { registerCommands } from "./commands";
import { readSettings } from "./config";
import { CodesysService } from "./codesys/service";
import { Logger } from "./logging";
import { ExtensionState } from "./state";
import { ActionsViewProvider, JobsViewProvider, ProjectsViewProvider } from "./views";
export async function activate(context: vscode.ExtensionContext): Promise<void> {
const logger = new Logger();
const settings = readSettings();
const diagnostics = vscode.languages.createDiagnosticCollection("codesys-mcp");
const service = new CodesysService(logger, settings, diagnostics);
const state = new ExtensionState(context);
const status = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 20);
status.command = "codesys.openOutput";
status.text = "CODESYS: Disconnected";
status.show();
const projectsView = new ProjectsViewProvider(state);
const jobsView = new JobsViewProvider(service);
const actionsView = new ActionsViewProvider();
context.subscriptions.push(
logger,
diagnostics,
status,
vscode.window.registerTreeDataProvider("codesysProjectsView", projectsView),
vscode.window.registerTreeDataProvider("codesysJobsView", jobsView),
vscode.window.registerTreeDataProvider("codesysActionsView", actionsView),
{
dispose: () => {
void service.disconnect();
}
}
);
registerCommands(context, {
service,
logger,
state,
settings,
status,
projectsView,
jobsView,
actionsView
});
}
export function deactivate(): void {}

View File

@@ -0,0 +1,29 @@
import * as vscode from "vscode";
export class Logger {
private readonly output: vscode.OutputChannel;
constructor() {
this.output = vscode.window.createOutputChannel("CODESYS MCP Companion");
}
public info(message: string): void {
this.output.appendLine(`[INFO] ${new Date().toISOString()} ${message}`);
}
public warn(message: string): void {
this.output.appendLine(`[WARN] ${new Date().toISOString()} ${message}`);
}
public error(message: string): void {
this.output.appendLine(`[ERROR] ${new Date().toISOString()} ${message}`);
}
public show(): void {
this.output.show(true);
}
public dispose(): void {
this.output.dispose();
}
}

View File

@@ -0,0 +1,190 @@
import { ChildProcessWithoutNullStreams, spawn } from "child_process";
import * as fs from "fs";
import { Logger } from "../logging";
import { JsonObject, JsonValue, McpCallResult, McpTool } from "../types";
interface PendingRequest {
resolve: (value: JsonValue) => void;
reject: (reason?: unknown) => void;
}
interface McpClientOptions {
pythonPath: string;
bridgeScriptPath: string;
environment: Record<string, string>;
logger: Logger;
}
export class McpClient {
private process?: ChildProcessWithoutNullStreams;
private readonly pending = new Map<number, PendingRequest>();
private readonly logger: Logger;
private nextRequestId = 1;
private readBuffer = Buffer.alloc(0);
private initialized = false;
constructor(private readonly options: McpClientOptions) {
this.logger = options.logger;
}
public async connect(): Promise<void> {
if (this.initialized) {
return;
}
if (!fs.existsSync(this.options.bridgeScriptPath)) {
throw new Error(`Bridge script not found: ${this.options.bridgeScriptPath}`);
}
this.process = spawn(this.options.pythonPath, [this.options.bridgeScriptPath], {
env: {
...process.env,
...this.options.environment
},
stdio: "pipe"
});
this.process.stderr.on("data", (chunk: Buffer) => {
this.logger.warn(`MCP stderr: ${chunk.toString("utf8").trim()}`);
});
this.process.on("exit", (code) => {
this.logger.warn(`MCP process exited: ${code ?? -1}`);
this.initialized = false;
});
this.process.stdout.on("data", (chunk: Buffer) => this.handleStdout(chunk));
await this.request("initialize", {
protocolVersion: "2024-11-05",
capabilities: {},
clientInfo: {
name: "codesys-mcp-companion",
version: "0.1.0"
}
});
await this.notify("notifications/initialized", {});
this.initialized = true;
this.logger.info("MCP connection initialized.");
}
public async disconnect(): Promise<void> {
if (!this.process) {
return;
}
this.process.kill();
this.process = undefined;
this.pending.clear();
this.initialized = false;
}
public async listTools(): Promise<McpTool[]> {
const response = (await this.request("tools/list", {})) as JsonObject;
const tools = response.tools as JsonValue[] | undefined;
if (!Array.isArray(tools)) {
return [];
}
return tools as unknown as McpTool[];
}
public async callTool(name: string, argumentsPayload: JsonObject): Promise<McpCallResult> {
const response = (await this.request("tools/call", {
name,
arguments: argumentsPayload
})) as JsonObject;
return response as unknown as McpCallResult;
}
private async notify(method: string, params: JsonObject): Promise<void> {
this.ensureConnected();
this.writeMessage({ jsonrpc: "2.0", method, params });
}
private async request(method: string, params: JsonObject): Promise<JsonValue> {
this.ensureConnected();
const id = this.nextRequestId++;
const payload = {
jsonrpc: "2.0",
id,
method,
params
};
const responsePromise = new Promise<JsonValue>((resolve, reject) => {
this.pending.set(id, { resolve, reject });
setTimeout(() => {
if (this.pending.has(id)) {
this.pending.delete(id);
reject(new Error(`MCP request timeout (${method})`));
}
}, 60_000);
});
this.writeMessage(payload);
return responsePromise;
}
private ensureConnected(): void {
if (!this.process || !this.process.stdin.writable) {
throw new Error("MCP process is not connected.");
}
}
private writeMessage(message: JsonObject): void {
const raw = JSON.stringify(message);
const framed = `Content-Length: ${Buffer.byteLength(raw, "utf8")}\r\n\r\n${raw}`;
this.process?.stdin.write(framed, "utf8");
}
private handleStdout(chunk: Buffer): void {
this.readBuffer = Buffer.concat([this.readBuffer, chunk]);
while (true) {
const splitMarker = this.readBuffer.indexOf("\r\n\r\n");
if (splitMarker === -1) {
return;
}
const header = this.readBuffer.subarray(0, splitMarker).toString("utf8");
const contentLengthLine = header
.split("\r\n")
.find((line) => line.toLowerCase().startsWith("content-length:"));
if (!contentLengthLine) {
this.logger.warn("Dropping MCP frame with no Content-Length.");
this.readBuffer = this.readBuffer.subarray(splitMarker + 4);
continue;
}
const lengthText = contentLengthLine.split(":")[1]?.trim() ?? "0";
const length = Number.parseInt(lengthText, 10);
const bodyStart = splitMarker + 4;
const bodyEnd = bodyStart + length;
if (this.readBuffer.length < bodyEnd) {
return;
}
const bodyRaw = this.readBuffer.subarray(bodyStart, bodyEnd).toString("utf8");
this.readBuffer = this.readBuffer.subarray(bodyEnd);
this.handleMessage(bodyRaw);
}
}
private handleMessage(raw: string): void {
try {
const message = JSON.parse(raw) as {
id?: number;
result?: JsonValue;
error?: { message?: string };
};
if (typeof message.id === "number") {
const pending = this.pending.get(message.id);
if (!pending) {
return;
}
this.pending.delete(message.id);
if (message.error) {
pending.reject(new Error(message.error.message ?? "Unknown MCP error"));
return;
}
pending.resolve(message.result ?? null);
}
} catch (error) {
this.logger.error(`Failed to parse MCP message: ${String(error)}`);
}
}
}

View File

@@ -0,0 +1,15 @@
import * as vscode from "vscode";
const ACTIVE_PROJECT_KEY = "codesys.activeProjectPath";
export class ExtensionState {
constructor(private readonly context: vscode.ExtensionContext) {}
public get activeProjectPath(): string {
return this.context.globalState.get<string>(ACTIVE_PROJECT_KEY, "");
}
public async setActiveProjectPath(path: string): Promise<void> {
await this.context.globalState.update(ACTIVE_PROJECT_KEY, path);
}
}

View File

@@ -0,0 +1,19 @@
import * as path from "path";
import { runTests } from "@vscode/test-electron";
async function main(): Promise<void> {
try {
const extensionDevelopmentPath = path.resolve(__dirname, "..", "..");
const extensionTestsPath = path.resolve(__dirname, "./suite/index");
await runTests({
extensionDevelopmentPath,
extensionTestsPath
});
} catch (error) {
console.error("Failed to run tests", error);
process.exit(1);
}
}
void main();

View File

@@ -0,0 +1,7 @@
import * as assert from "assert";
suite("Extension Smoke", () => {
test("sanity", () => {
assert.strictEqual(1 + 1, 2);
});
});

View File

@@ -0,0 +1,22 @@
import Mocha from "mocha";
import * as path from "path";
export function run(): Promise<void> {
const mocha = new Mocha({
ui: "tdd",
color: true
});
const testsRoot = path.resolve(__dirname, "..", "suite");
return new Promise((resolve, reject) => {
mocha.addFile(path.resolve(testsRoot, "extension.test.js"));
mocha.addFile(path.resolve(testsRoot, "payloads.test.js"));
mocha.run((failures: number) => {
if (failures > 0) {
reject(new Error(`${failures} tests failed.`));
return;
}
resolve();
});
});
}

View File

@@ -0,0 +1,12 @@
import * as assert from "assert";
import { buildDefaultSyncPayload } from "../../codesys/payloads";
suite("Payloads", () => {
test("buildDefaultSyncPayload creates empty arrays", () => {
const payload = buildDefaultSyncPayload("C:\\project.project");
assert.strictEqual(payload.project_path, "C:\\project.project");
assert.deepStrictEqual(payload.textual_updates, []);
assert.deepStrictEqual(payload.io_mappings, []);
assert.deepStrictEqual(payload.device_params, []);
});
});

View File

@@ -0,0 +1,27 @@
export type JsonValue = string | number | boolean | null | JsonObject | JsonValue[];
export interface JsonObject {
[key: string]: JsonValue;
}
export interface McpTool {
name: string;
description?: string;
inputSchema?: JsonObject;
}
export interface McpCallResult {
content?: Array<{ type: string; text?: string }>;
structuredContent?: JsonObject;
isError?: boolean;
}
export interface JobSummary {
id: string;
action: string;
status: string;
created_at: number;
started_at?: number;
finished_at?: number;
error?: string | null;
}

View File

@@ -0,0 +1,91 @@
import * as vscode from "vscode";
import { CodesysService, JobRecord } from "./codesys/service";
import { ExtensionState } from "./state";
export class SimpleItem extends vscode.TreeItem {
constructor(label: string, description?: string, command?: vscode.Command) {
super(label, vscode.TreeItemCollapsibleState.None);
this.description = description;
this.command = command;
}
}
export class ProjectsViewProvider implements vscode.TreeDataProvider<SimpleItem> {
private emitter = new vscode.EventEmitter<SimpleItem | undefined>();
public readonly onDidChangeTreeData = this.emitter.event;
constructor(private readonly state: ExtensionState) {}
public refresh(): void {
this.emitter.fire(undefined);
}
public getTreeItem(element: SimpleItem): vscode.TreeItem {
return element;
}
public getChildren(): Thenable<SimpleItem[]> {
const active = this.state.activeProjectPath || "(none)";
return Promise.resolve([
new SimpleItem("Active Project", active),
new SimpleItem("Select Project", "Pick a project path", {
title: "Select Project",
command: "codesys.selectProject"
})
]);
}
}
export class JobsViewProvider implements vscode.TreeDataProvider<SimpleItem> {
private emitter = new vscode.EventEmitter<SimpleItem | undefined>();
public readonly onDidChangeTreeData = this.emitter.event;
constructor(private readonly service: CodesysService) {}
public refresh(): void {
this.emitter.fire(undefined);
}
public getTreeItem(element: SimpleItem): vscode.TreeItem {
return element;
}
public getChildren(): Thenable<SimpleItem[]> {
const jobs = this.service.getJobs();
if (jobs.length === 0) {
return Promise.resolve([new SimpleItem("No jobs yet")]);
}
return Promise.resolve(jobs.slice(0, 20).map(toJobItem));
}
}
export class ActionsViewProvider implements vscode.TreeDataProvider<SimpleItem> {
private emitter = new vscode.EventEmitter<SimpleItem | undefined>();
public readonly onDidChangeTreeData = this.emitter.event;
public refresh(): void {
this.emitter.fire(undefined);
}
public getTreeItem(element: SimpleItem): vscode.TreeItem {
return element;
}
public getChildren(): Thenable<SimpleItem[]> {
const make = (label: string, command: string) =>
new SimpleItem(label, undefined, { title: label, command });
return Promise.resolve([
make("Health Check", "codesys.health"),
make("Create Project", "codesys.createProject"),
make("Read Project Inventory", "codesys.readProjectInventory"),
make("Read Device I/O", "codesys.readDeviceIo"),
make("Sync Project", "codesys.syncProject"),
make("Build Project", "codesys.buildProject"),
make("Download To Device", "codesys.downloadToDevice")
]);
}
}
function toJobItem(job: JobRecord): SimpleItem {
return new SimpleItem(`${job.action}`, `${job.status} ${job.id.slice(0, 8)}`);
}

View File

@@ -0,0 +1,36 @@
{
"scopeName": "source.codesys.st",
"name": "CODESYS ST",
"patterns": [
{
"name": "comment.block.codesys",
"begin": "\\(\\*",
"end": "\\*\\)"
},
{
"name": "comment.line.double-slash.codesys",
"match": "//.*$"
},
{
"name": "keyword.control.codesys",
"match": "\\b(IF|THEN|ELSE|ELSIF|CASE|OF|FOR|TO|BY|DO|WHILE|REPEAT|UNTIL|RETURN|EXIT)\\b"
},
{
"name": "keyword.declaration.codesys",
"match": "\\b(PROGRAM|FUNCTION|FUNCTION_BLOCK|TYPE|STRUCT|END_STRUCT|VAR|VAR_INPUT|VAR_OUTPUT|VAR_IN_OUT|VAR_GLOBAL|VAR_TEMP|END_VAR|END_FUNCTION|END_FUNCTION_BLOCK|END_PROGRAM|END_TYPE)\\b"
},
{
"name": "constant.language.bool.codesys",
"match": "\\b(TRUE|FALSE)\\b"
},
{
"name": "constant.numeric.codesys",
"match": "\\b\\d+(?:\\.\\d+)?\\b"
},
{
"name": "string.quoted.double.codesys",
"begin": "\"",
"end": "\""
}
]
}

View File

@@ -0,0 +1,29 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "ES2022",
"outDir": "out",
"lib": [
"ES2022"
],
"sourceMap": true,
"rootDir": "src",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"moduleResolution": "node",
"types": [
"node",
"vscode"
],
"esModuleInterop": true,
"skipLibCheck": true
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules",
".vscode-test"
]
}