TwinCAT Validator MCP Server
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@TwinCAT Validator MCP Server validate MotorControl.TcPOU and suggest safe fixes"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
TwinCAT Validator MCP Server
An MCP server that validates, auto-fixes, and scaffolds TwinCAT 3 XML files (.TcPOU, .TcIO, .TcDUT, .TcGVL). Connect it to any LLM client to give your AI assistant reliable, deterministic TwinCAT code quality tooling — structural checks, 21 IEC 61131-3 OOP checks, auto-fix pipelines, and canonical skeleton generation.
Supported File Types
Extension | Description |
| Program Organization Units — Function Blocks, Programs, Functions |
| I/O configurations — Interfaces |
| Data Unit Types — Structures, Enums, Type Aliases |
| Global Variable Lists |
Related MCP server: tiacommander-mcp
Installation
pip install twincat-validator-mcpFrom Source
git clone https://github.com/agenticcontrolio/twincat-validator-mcp.git
cd twincat-validator-mcp
pip install -e .Claude Desktop Extension
The easiest way to use this server with Claude Desktop is via the one-click .dxt extension:
pip install twincat-validator-mcpDownload the
.dxtfile from the latest releaseOpen Claude Desktop → Settings → Extensions → Install Extension
See dxt/README.md for full instructions and troubleshooting.
Connecting to an LLM Client
For other clients (Cursor, VS Code, Windsurf, Cline), the server uses stdio transport. Add the following to your client's MCP config file:
Cursor — .cursor/mcp.json
{
"mcpServers": {
"twincat-validator": {
"command": "twincat-validator-mcp",
"args": []
}
}
}VS Code (Copilot / Continue) — .vscode/mcp.json
{
"servers": {
"twincat-validator": {
"type": "stdio",
"command": "twincat-validator-mcp",
"args": []
}
}
}Windsurf — ~/.codeium/windsurf/mcp_config.json
{
"mcpServers": {
"twincat-validator": {
"command": "twincat-validator-mcp",
"args": []
}
}
}Cline (VS Code Extension)
{
"mcpServers": {
"twincat-validator": {
"command": "twincat-validator-mcp",
"args": [],
"disabled": false
}
}
}Replace "command": "twincat-validator-mcp" with:
"command": "python",
"args": ["-m", "twincat_validator"],
"cwd": "/path/to/twincat-validator-mcp"MCP Tools
Validation
Tool | Description |
| Full validation of a single file — returns all issues with severity, location, code snippet, and explanation |
| Validate multiple files matching glob patterns (e.g. |
| Quick critical-only check to confirm a file is safe to import into TwinCAT |
| Run a named subset of validation checks on a file |
| Return a 0–100 health score with issue counts by severity |
| Generate prioritized fix recommendations from a validation result |
Auto-fix
Tool | Description |
| Apply all safe auto-fixes to a single file in deterministic order |
| Apply auto-fixes to multiple files matching glob patterns |
| Generate a canonical, deterministic XML skeleton for a given file type and subtype |
| Promote inline |
Orchestration
Tool | Description |
| Full enforced pipeline for one file: validate → autofix → validate → suggest fixes if still unsafe |
| Full enforced pipeline across multiple files with summary or full response modes |
| Run the strict pipeline twice and report per-file idempotence stability |
| Resolve the active OOP validation policy for a file or directory (walks ancestor dirs for |
| Validate the nearest |
| Return curated knowledge-base entries and OOP policy scoped to a workflow stage ( |
Validation Checks
Structure & Format (critical — blocks import)
XML structure validity
GUID format (
{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx})GUID uniqueness across elements
Property getter VAR blocks (missing
VAR/END_VAR)LineIds count consistency
File ending format
Style (warning — advisory)
Tab characters (TwinCAT requires spaces)
2-space indentation
Element ordering
Naming conventions (
FB_,PRG_,FUNC_,E_,ST_,I_,GVL_)Excessive blank lines
CDATA formatting
OOP — IEC 61131-3 (21 checks)
Runs automatically when EXTENDS or IMPLEMENTS is detected. Skipped for procedural code.
Category | Checks |
Inheritance safety | Extends visibility, extends cycle detection, diamond inheritance warning |
Override correctness | Override marker, override signature match, override super call |
Interface compliance | Interface contract, inheritance property contract, interface segregation |
FB lifecycle |
|
Memory safety | Dynamic creation attribute, pointer/delete pairing |
Design quality |
|
Property/method | Property accessor pairing, method visibility consistency, method count |
Auto-fix Capabilities
Fixes are applied in a deterministic, dependency-aware order:
Tabs → 2 spaces (runs before indentation)
File ending — fixes truncated
]]>after</TcPlcObject>Property newlines — normalizes declaration line breaks
CDATA formatting — corrects CDATA section structure
Property VAR blocks — inserts missing
VAR/END_VARin gettersExcessive blank lines — reduces to max 2 consecutive
Indentation — normalizes to 2-space multiples
GUID case — uppercases hex to canonical lowercase
LineIds — experimental generation (marked unsafe, opt-in only)
Running autofix twice on the same file produces byte-identical output (idempotency guaranteed).
Intent-Aware OOP Enforcement
All tools accept an intent_profile parameter:
Value | Behavior |
| Detects OOP patterns ( |
| Skips all 21 OOP checks regardless of file content |
| Always runs OOP checks |
Batch tools scan all .TcPOU files to resolve "auto" once at the batch level.
Health Score
Files are scored 0–100 based on issue counts:
Deduction | Severity |
−25 pts | Critical / error |
−5 pts | Warning |
−1 pt | Info |
Score | Rating |
90–100 | Excellent — production ready |
70–89 | Good — minor issues |
50–69 | Needs work |
0–49 | Critical issues present |
Target ≥ 90 for all production files.
MCP Resources
URI | Description |
| All 34 check definitions |
| All 9 fix definitions with complexity and risk level |
| TwinCAT naming patterns by file type |
| Server metadata and capability summary |
| Full LLM-friendly knowledge base |
| Explanation, examples, and common mistakes for one check |
| Algorithm and examples for one fix |
| Deterministic generation contracts for all file types |
| Contract for |
| Default OOP policy values |
| Resolved OOP policy for a path |
MCP Prompts
8 reusable prompt templates for canonical LLM workflows — covering single-file generation, batch validation, OOP scaffolding, determinism verification, and troubleshooting flows. Accessible via your MCP client's prompt interface.
Agent Guide
AGENT.md is an example guide prompt that tells your LLM agent exactly how to use this server — which tools to call, in what order, how to route intent (procedural vs OOP), stop conditions, and the reporting contract. Copy it into your system prompt or agent instructions and customise it to match your workflow.
Recommended Workflow
The pattern for any TwinCAT generation task — no code is written until the user has approved the plan.
flowchart LR
A([User Prompt]) --> B[📋 Plan\nLLM produces plan file\nand stops]
B --> C{User reviews\nand approves?}
C -- No --> B
C -- Yes --> D[⚙️ Implement\nLLM generates\nTwinCAT artifacts]
D --> E[✅ Validate\nMCP server validates,\nauto-fixes, confirms safety]
E --> F([Done])
style A fill:#4a90d9,color:#fff,stroke:none
style F fill:#27ae60,color:#fff,stroke:none
style C fill:#f39c12,color:#fff,stroke:noneAfter approval, the LLM follows this MCP tool sequence:
flowchart TD
START([Plan approved by user]) --> CTX
CTX["get_context_pack\n(stage=pre_generation)"]
CTX --> POLICY["get_effective_oop_policy\n(if OOP task)"]
POLICY --> SKE
CTX --> SKE
SKE["generate_skeleton\nfor each artifact"]
SKE --> WRITE["LLM writes\nST content into files"]
WRITE --> ORCH
subgraph ORCH_LOOP ["Orchestration loop (max 3 iterations)"]
ORCH["process_twincat_single\nor process_twincat_batch"]
ORCH --> SAFE{safe_to_import\n&& safe_to_compile?}
SAFE -- Yes --> DET
SAFE -- No --> BLOCKED{no_progress\nor iter >= 3?}
BLOCKED -- No --> KB["get_context_pack\n(stage=troubleshooting,\ncheck_ids=blockers)"]
KB --> FIX["LLM applies\none focused correction"]
FIX --> ORCH
BLOCKED -- Yes --> FAIL([Report blocked —\nstop])
end
DET["verify_determinism_batch\n(second pass — no changes expected)"]
DET --> STABLE{stable?}
STABLE -- No --> ORCH
STABLE -- Yes --> DONE([Report done ✅\nsafe_to_import, safe_to_compile,\nblocking_count=0, content_changed=false])
style START fill:#4a90d9,color:#fff,stroke:none
style DONE fill:#27ae60,color:#fff,stroke:none
style FAIL fill:#e74c3c,color:#fff,stroke:none
style BLOCKED fill:#f39c12,color:#fff,stroke:none
style SAFE fill:#f39c12,color:#fff,stroke:none
style STABLE fill:#f39c12,color:#fff,stroke:noneSee EXAMPLE_PROMPT.md for a complete worked prompt using this pattern.
Configuration
Config files live in twincat_validator/config/ inside the installed package. To locate them:
import twincat_validator, os
print(os.path.join(os.path.dirname(twincat_validator.__file__), "config"))File | Purpose |
| Check definitions — severity, category, auto_fixable flag |
| Fix definitions — complexity, risk level, deterministic order |
| Naming patterns by file type and subtype |
| LLM-friendly explanations and examples for all checks and fixes |
| Canonical XML generation rules and forbidden patterns |
Restart the server after editing config files to reload.
Development
pip install -e ".[dev]"
# Run tests
pytest tests/
# Format
black --line-length=100 .
# Lint
ruff check .
# Type check
mypy twincat_validator/server.py --ignore-missing-imports
# Full CI suite (py311 + py312, lint, type check)
toxLicense
MIT — see LICENSE for details.
Authors
Agentic Control - Jaime Calvente Mieres: design, architecture, and domain expertise
Built with the assistance of Claude (Anthropic) and Codex (OpenAI).
Available Tools
16 toolsautofix_batchB
Automatically fix multiple TwinCAT files matching glob patterns.
Args: file_patterns: Glob patterns (e.g., ["*.TcPOU"]) directory_path: Base directory create_backup: Create backup files before fixing profile: Response profile passed to per-file autofix (default: llm_strict) format_profile: Formatting profile for per-file autofix strict_contract: Enforce generation contract fail-closed in per-file autofix create_implicit_files: Auto-create missing interface/DUT dependencies orchestration_hints: Include loop-guard hints in per-file responses intent_profile: Programming paradigm intent — "auto" (default), "procedural", or "oop". With "auto", each file's content is inspected individually for EXTENDS/IMPLEMENTS, so OOP files receive full OOP checks even in mixed batches. ctx: FastMCP context for per-file progress notifications (injected automatically)
Inputs: file_patterns (required), directory_path, create_backup, profile, +7 more. Returns: result
autofix_fileB
Automatically fix common TwinCAT XML issues.
Args: file_path: Path to TwinCAT file create_backup: Create backup before fixing fixes_to_apply: List of fix IDs, or None for all profile: "full" (default) verbose response, "llm_strict" minimal response format_profile: "default" or "twincat_canonical" formatting pass strict_contract: If True, fail closed on generation-contract violations create_implicit_files: If True, auto-create missing implicit dependency files (currently interface .TcIO files for IMPLEMENTS I_* clauses) orchestration_hints: If True, include next_action/terminal/no_change hints and content fingerprints for loop prevention in weak agents. intent_profile: Programming paradigm intent — "auto" (default), "procedural", or "oop". Controls which check families are used in post-fix validation.
Inputs: file_path (required), create_backup, fixes_to_apply, profile, +6 more. Returns: result
check_specificC
Run specific validation checks on a TwinCAT file.
Args: file_path: Path to TwinCAT file check_names: List of check IDs to run
Inputs: file_path (required), check_names (required), enforcement_mode. Returns: result
extract_methods_to_xmlB
Promote inline METHOD blocks from main ST to XML elements.
Args: file_path: Path to .TcPOU file create_backup: Create .bak backup when content changes
Inputs: file_path (required), create_backup. Returns: result
generate_skeletonB
Generate canonical deterministic TwinCAT XML skeleton for a file type.
Args: file_type: .TcPOU, .TcDUT, .TcGVL, or .TcIO (with or without leading dot) subtype: For .TcPOU only: function_block, function, or program
Inputs: file_type (required), subtype, enforcement_mode. Returns: result
get_context_packA
Get curated knowledge base entries and OOP policy scoped by workflow stage.
Stages:
pre_generation: Returns high-priority non-fixable checks the LLM must get right when generating TwinCAT XML from scratch.
troubleshooting: Returns KB entries for specific check_ids (typically extracted from blocker lists after orchestration).
Args: stage: Workflow stage ("pre_generation" or "troubleshooting"). check_ids: Explicit check IDs (required for troubleshooting, ignored for pre_generation). target_path: Optional file/dir path for OOP policy resolution. max_entries: Maximum KB entries to return (default 10). include_examples: Include correct_examples and common_mistakes arrays (default True). Set False to save tokens. enforcement_mode: Policy enforcement mode ("strict" or "compat"). intent_profile: Programming paradigm intent — "oop", "procedural", or "auto". In pre_generation stage: - omitted: defaults to "oop" (backward compatible behavior). - "oop": Core + OOP check guidance is returned. - "procedural": Only core (non-OOP) check guidance is returned. - "auto": No file content is available at pre-generation time, so resolves to "procedural". Use "oop" or "procedural" explicitly for predictability. In troubleshooting stage: - explicit value is required (workflow guardrail). - value has no routing effect (check_ids drive selection).
Returns: JSON with effective_oop_policy, curated entries[], missing_check_ids[], intent metadata, truncation info, and meta envelope.
Inputs: stage, check_ids, target_path, max_entries, +3 more. Returns: result
get_effective_oop_policyA
Get effective OOP validation policy for a file or directory target.
Args: target_path: Optional path to a file or directory. If omitted, uses current working directory defaults.
Inputs: target_path. Returns: result
get_validation_summaryB
Get high-level file quality summary with health score.
Args: file_path: Path to TwinCAT file
Inputs: file_path (required). Returns: result
lint_oop_policyB
Lint nearest .twincat-validator.json policy keys/types and return normalized policy.
Inputs: target_path, strict. Returns: result
process_twincat_batchA
Run enforced deterministic batch TwinCAT workflow.
Steps:
validate_batch (pre-check)
autofix_batch (strict pipeline)
validate_batch (post-check)
Args: file_patterns: Glob patterns (e.g., ["*.TcPOU"]) directory_path: Base directory create_backup: Create backup files before fixing validation_level: "all", "critical", or "style" enforcement_mode: Policy enforcement mode ("strict" or "compat") response_mode: "summary" (minimal, default), "compact" (no pre/post blobs), or "full" (all detail sections included). include_sections: In summary mode only — optional list of heavy sections to add. Supported: "blockers", "issues", "pre_validation", "autofix", "post_validation", "effective_oop_policy", "meta_detailed". Unknown names are ignored with a warning in the response. Has no effect in compact or full mode. include_knowledge_hints: Include recommended_check_ids from blockers (when not done). intent_profile: Programming paradigm intent — "auto" (default), "procedural", or "oop". Controls which check families run: - "procedural": OOP checks are skipped. - "oop": Full OOP check family is enforced. - "auto": Scans matched .TcPOU declarations for EXTENDS/IMPLEMENTS; resolves to "oop" if any are found, otherwise "procedural".
Inputs: file_patterns (required), directory_path, create_backup, validation_level, +5 more. Returns: result
process_twincat_singleA
Run enforced deterministic single-file TwinCAT workflow.
Steps:
validate_file (pre-check)
autofix_file (strict pipeline)
validate_file (post-check)
suggest_fixes (only if still unsafe)
Args: file_path: Path to the TwinCAT file to process. create_backup: Create a backup before applying fixes. validation_level: "all", "critical", or "style". enforcement_mode: Policy enforcement mode ("strict" or "compat"). include_knowledge_hints: Include recommended_check_ids from blockers. intent_profile: Programming paradigm intent — "auto" (default), "procedural", or "oop". Controls which check families run: - "procedural": OOP checks are skipped (safe for plain FUNCTION_BLOCK/PROGRAM). - "oop": Full OOP check family is enforced. - "auto": Resolved from file content (EXTENDS/IMPLEMENTS → oop, else procedural).
Inputs: file_path (required), create_backup, validation_level, enforcement_mode, +2 more. Returns: result
suggest_fixesA
Generate prioritized fix recommendations from validation results.
Args: validation_result: JSON string from validate_file()
Inputs: validation_result (required). Returns: result
validate_batchA
Validate multiple TwinCAT files matching glob patterns.
Args: file_patterns: Glob patterns (e.g., ["*.TcPOU"]) directory_path: Base directory validation_level: "all", "critical", or "style" intent_profile: Programming paradigm intent — "auto" (default), "procedural", or "oop". With "auto", the matched .TcPOU files are scanned for EXTENDS/ IMPLEMENTS; if any are found the batch resolves to "oop", otherwise "procedural". ctx: FastMCP context for per-file progress notifications (injected automatically)
Inputs: file_patterns (required), directory_path, validation_level, enforcement_mode, +2 more. Returns: result
validate_fileA
Validate a single TwinCAT file.
Args: file_path: Path to TwinCAT file validation_level: "all", "critical", or "style" profile: Output profile - "full" (verbose, default) or "llm_strict" (minimal) intent_profile: Programming paradigm intent — "auto" (default), "procedural", or "oop". Controls which check families run: - "procedural": OOP checks are skipped. - "oop": Full OOP check family is enforced. - "auto": Resolved from file content (EXTENDS/IMPLEMENTS → oop, else procedural).
Returns: JSON string with validation results.
Full profile includes: validation_status, checks array, issues with Phase 3
enrichment, metrics, timing.
LLM strict profile includes only: file_path, safe_to_import, safe_to_compile,
blocking_count, blockers (unfixable errors).
Inputs: file_path (required), validation_level, profile, enforcement_mode, +1 more. Returns: result
validate_for_importC
Quick validation check for TwinCAT import readiness.
Args: file_path: Path to TwinCAT file
Inputs: file_path (required), enforcement_mode. Returns: result
verify_determinism_batchA
Run strict batch orchestration twice and report per-file idempotence stability.
Args: file_patterns: Glob patterns (e.g., ["*.TcPOU"]) directory_path: Base directory create_backup: Create backup files before fixing validation_level: "all", "critical", or "style" enforcement_mode: Policy enforcement mode ("strict" or "compat") response_mode: "summary" (minimal, default), "compact", or "full". include_sections: In summary mode only — optional heavy sections to include. Supported: "blockers", "pre_validation", "autofix", "post_validation", "effective_oop_policy", "meta_detailed". Unknown names ignored with a warning in the response. Has no effect in compact or full mode.
Inputs: file_patterns (required), directory_path, create_backup, validation_level, +3 more. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 16 tools
There is significant overlap between tools, particularly between autofix_batch/autofix_file, validate_batch/validate_file, and process_twincat_batch/process_twincat_single which appear to be batch vs single-file versions of the same core operations. However, the descriptions help clarify the scope differences, and tools like extract_methods_to_xml, generate_skeleton, and get_context_pack have distinct purposes.
Most tools follow a consistent snake_case pattern with clear verb_noun structure (e.g., validate_file, generate_skeleton, get_context_pack). The main deviation is check_specific which uses an adjective_verb pattern rather than verb_noun, but overall the naming is predictable and readable.
16 tools is borderline high for a TwinCAT validation server, especially given the redundancy between batch and single-file versions. The server could likely consolidate some overlapping tools without losing functionality, making the count feel somewhat heavy for the domain scope.
The toolset provides comprehensive coverage for TwinCAT validation workflows including validation (single/batch), fixing (single/batch), policy management, knowledge retrieval, skeleton generation, and specialized operations like method extraction. There are no obvious gaps - it supports the full lifecycle from creation to troubleshooting to verification.
Maintenance
Related MCP Connectors
The OpenZeppelin Solidity Contracts MCP server integrates OpenZeppelin's security and style rules into AI-driven development workflows, enabling AI assistants to generate safe, correct, and production-ready smart contracts. It automatically validates generated code against OpenZeppelin standards (including imports, modifiers, naming conventions, and security checks) and supports various contract types including ERC-20, ERC-721, ERC-1155, Stablecoins, RWA, Governor, and Account contracts through prompt-driven workflows.
MCP Server for Slima - AI Writing IDE for Novel Authors with AI Beta Reader.
Generate TIA Portal importable SimaticML (V19) from LadDoc IR, with strict validation, over MCP.
The OpenZeppelin Cairo Contracts MCP server generates secure smart contracts in the Cairo language for Starknet environments based on OpenZeppelin templates. It brings OpenZeppelin's proven security and style rules directly into AI-driven development workflows to create safe, production-ready contracts. Key capabilities include providing templates for ERC-20, ERC-721, ERC-1155, Multisig, Governor, and Vesting contracts.
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceA Model Context Protocol server that enables seamless interaction between MCP clients (like Claude Desktop) and CODESYS V3 programming environments, allowing automation of project management, POU creation, code editing, and compilation tasks.3,146 npm142MIT
- FlicenseNot gradedqualityCmaintenanceMCP server that connects AI assistants to Siemens TIA Portal via the Openness API. AI-assisted PLC programming, project management, hardware configuration, cross-reference analysis, and deployment. 19 tools, 230 actions.67-
- AlicenseBqualityCmaintenanceMCP server for Beckhoff TwinCAT XAE / TE1000 Automation Interface, enabling control of XAE Shell, TwinCAT tree manipulation, PLC operations, and build actions via natural language.2525MIT
- AlicenseNot gradedqualityCmaintenanceAn MCP server that extends AI coding assistants with deterministic, algorithmic capabilities such as code analysis, fault localization, and formal verification, enabling an autonomous engineering team within the IDE.MIT