Skip to main content
Glama
agenticcontrolio

TwinCAT Validator MCP Server

validate_batch

Validate multiple TwinCAT automation project files simultaneously using glob patterns to check code quality, structure, and compliance with IEC 61131-3 standards at specified validation levels.

Instructions

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)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_patternsYes
directory_pathNo.
validation_levelNoall
enforcement_modeNostrict
intent_profileNoauto
ctxNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The validate_batch tool handler implementation using FastMCP @mcp.tool().
    @mcp.tool()
    async def validate_batch(
        file_patterns: list[str],
        directory_path: str = ".",
        validation_level: str = "all",
        enforcement_mode: str = DEFAULT_ENFORCEMENT_MODE,
        intent_profile: str = "auto",
        ctx: Optional[Any] = None,
    ) -> str:
        """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)
        """
        _t0 = time.monotonic()
        ctx_policy = None
        try:
            mode_error = _validate_enforcement_mode(enforcement_mode, start_time=_t0)
            if mode_error:
                return mode_error
            ctx_policy = _resolve_execution_context(
                directory_path, enforcement_mode=enforcement_mode
            )
            if intent_profile not in _VALID_INTENT_PROFILES:
                return _tool_error(
                    f"Invalid intent_profile: {intent_profile}",
                    start_time=_t0,
                    execution_context=ctx_policy,
                    valid_intent_profiles=list(_VALID_INTENT_PROFILES),
                )
            from glob import glob
    
            start_time = time.time()
            base_path = Path(directory_path)
    
            if not base_path.exists():
                return _tool_error(
                    f"Directory not found: {directory_path}",
                    start_time=_t0,
                    execution_context=ctx_policy,
                    error_type="DirectoryNotFoundError",
                )
    
            all_files: set[Path] = set()
            for pattern in file_patterns:
                pattern_path = base_path / pattern
                matches = glob(str(pattern_path), recursive=True)
                all_files.update(Path(f) for f in matches)
    
            tc_files = [f for f in all_files if f.suffix in config.supported_extensions]
    
            # Resolve intent after file discovery so "auto" can scan .TcPOU declarations.
            _intent_resolved = _batch_auto_resolve_intent(tc_files, intent_profile)
            _exclude_cats = frozenset({"oop"}) if _intent_resolved == "procedural" else None
    
            if not tc_files:
                return _tool_error(
                    "No TwinCAT files found matching patterns",
                    start_time=_t0,
                    execution_context=ctx_policy,
                    patterns=file_patterns,
                    directory=str(base_path),
                )
    
            total = len(tc_files)
            results = []
            failed_files = []
            passed = 0
            failed = 0
            warnings = 0
    
            for idx, file_path in enumerate(tc_files):
                await _emit_progress(
                    ctx,
                    current=idx,
                    total=total,
                    message=f"validate {idx + 1}/{total}: {file_path.name}",
                )
                try:
                    file = TwinCATFile.from_path(file_path)
                    validation_time_start = time.time()
                    engine_result = validation_engine.validate(
                        file, validation_level, exclude_categories=_exclude_cats
                    )
                    validation_time = time.time() - validation_time_start
    
                    file_result = _convert_engine_result_to_mcp_format(
                        engine_result, file, validation_time, validation_level
                    )
    
                    status = file_result["validation_status"]
                    if status == "passed":
                        passed += 1
                    elif status == "failed":
                        failed += 1
                    elif status == "warnings":
                        warnings += 1
    
                    # Derive per-file contract state canonically (RC-1).
                    per_file_cs = derive_contract_state(file_result.get("issues", []))
                    results.append(
                        {
                            "file_path": str(file_path),
                            "status": status,
                            # error_count from canonical contract (issues with severity error/critical),
                            # not summary["failed"] which counts failed checks, not error issues.
                            "error_count": per_file_cs.error_count,
                            "warning_count": per_file_cs.warning_count,
                            # Flat per-file safety schema for consistency with process_twincat_batch
                            "safe_to_import": per_file_cs.safe_to_import,
                            "safe_to_compile": per_file_cs.safe_to_compile,
                            "blocking_count": per_file_cs.blocking_count,
                            "blockers": per_file_cs.blockers,
                            "validation_result": file_result,
                        }
                    )
    
                except Exception as e:
                    failed_files.append(
                        {
                            "file_path": str(file_path),
                            "error": str(e),
                            "error_type": type(e).__name__,
                        }
                    )
                    failed += 1
    
            await _emit_progress(ctx, current=total, total=total, message="validate complete")
    
            batch_id = f"batch_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
            safe_to_import = (
                all(bool(item.get("safe_to_import", False)) for item in results)
                if results
                else False
            )
            safe_to_compile = (
                all(bool(item.get("safe_to_compile", False)) for item in results)
                if results
                else False
            )
            done = failed == 0 and safe_to_import and safe_to_compile
            blockers = _aggregate_batch_blockers(results)
            result = {
                "success": True,
                "batch_id": batch_id,
                "processed_files": len(results),
                "total_files": total,
                "processing_time": round(time.time() - start_time, 3),
                "batch_summary": {"passed": passed, "failed": failed, "warnings": warnings},
                "files": results,
                "failed_files": failed_files,
                "safe_to_import": safe_to_import,
                "safe_to_compile": safe_to_compile,
                "done": done,
                "status": "done" if done else "blocked",
                "blocking_count": len(blockers),
                "blockers": blockers,
                "next_action": (
                    "done_no_further_validation" if done else "manual_intervention_or_targeted_fix"
                ),
            }
            _assert_validate_batch_contract(result)
    
            return _with_meta(result, _t0, execution_context=ctx_policy)
    
        except Exception as e:
            error_kwargs = {"execution_context": ctx_policy}
            if ctx_policy is None:
                error_kwargs.update(unresolved_policy_fields(enforcement_mode))
            return _tool_error(str(e), start_time=_t0, **error_kwargs)
  • Function that registers batch tools, including validate_batch.
    def register_batch_tools() -> None:
        """Register all batch tool handlers with the mcp instance."""
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden. It successfully discloses behavioral details like 'per-file progress notifications' for the ctx parameter and the OOP detection logic ('scanned for EXTENDS/IMPLEMENTS'). However, it fails to state whether the operation is read-only or destructive—a critical omission given the presence of 'autofix_batch' as a sibling—and doesn't mention performance characteristics or side effects.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with a clear one-line purpose followed by an Args section. Every sentence adds value, explaining either the tool's purpose or parameter semantics. The format is scannable and front-loaded, though the Args block could be slightly more concise.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (6 parameters with validation logic and output schema), the description is adequate but incomplete. The missing 'enforcement_mode' documentation and lack of sibling comparison context prevent a higher score, though the presence of an output schema reduces the description's burden for return value documentation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Despite 0% schema description coverage, the Args section provides rich semantic detail for 5 of 6 parameters: file_patterns includes an example ('*.TcPOU'), validation_level enumerates options, and intent_profile explains the auto-detection algorithm. However, it completely omits the 'enforcement_mode' parameter present in the schema, creating a documentation gap.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description opens with a clear, specific statement: 'Validate multiple TwinCAT files matching glob patterns.' It specifies the verb (validate), resource (TwinCAT files), and mechanism (glob patterns), effectively distinguishing it from the sibling tool 'validate_file' through the 'multiple' and 'glob patterns' qualifiers.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies batch usage through the 'glob patterns' and 'multiple' qualifiers, but provides no explicit guidance on when to use this tool versus 'validate_file' or other siblings. It also lacks guidance on selecting between validation_level options ('all', 'critical', 'style') or when to override the 'auto' intent_profile.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/agenticcontrolio/twincat-validator-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server