OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Validate the Root and Required Fields of a Saved XML Agent Workflow

Python

Read a local XML workflow and validate that its root has an exact CLI-selected tag and that every element with an exact CLI-selected call tag has nonempty `name` and `arguments` attributes, without executing or modifying the workflow.

Python code excerpt: Validate the Root and Required Fields of a Saved XML Agent Workflow. Version 0.1.0. Read the full recipe for code, sources and recorded test scope.

Before handing a saved agent workflow to another tool, catch a wrong document root and incomplete call declarations with a small offline check. This validates only the requested XML structure; it does not establish that the workflow is executable, safe, or accepted by any particular agent framework.

Before you start

  • Intended runner: Python 3.12; no minimum version claim is made.
  • Uses only Python standard-library `argparse`, `sys`, `pathlib`, and `xml.etree.ElementTree`, whose documented interfaces support CLI parsing and XML parsing/iteration.
  • Input must be a local UTF-8 XML file or XML supplied on stdin. No credentials, network access, remote changes, or output files are used.
  • ElementTree documentation warns it is not secure against maliciously constructed XML. Use only appropriate trusted local fixtures; this validator is not a security boundary.

Build and check

  1. Save the code in a local file named `validate_workflow.py`.
  2. Create the synthetic XML fixture shown above as `workflow.xml`.
  3. Run the command in `usage` and confirm it prints the expected success line.
  4. Change one call to omit `name` or provide only whitespace in `arguments`; confirm it prints an `INVALID` diagnostic and exits unsuccessfully.
  5. Change the root tag or use a different `--root-tag`; confirm the root mismatch is reported.
  6. Try an empty file and malformed XML; confirm parsing errors are reported. Try a nonexistent path and invalid UTF-8 bytes; confirm each is reported as an input error.
  7. Pipe the valid fixture through stdin using the documented `-` form and confirm it produces the same validation result.

Limits to understand

  • Checks exact XML tag names and attribute presence/nonblankness only; namespace-qualified tags must be supplied in their exact parsed form and are not specially normalized.
  • Does not parse or validate the contents of `arguments`, resolve workflow references, infer framework-specific schemas, execute calls, or prove a workflow safe or operational.
  • ElementTree parses the full document into memory, so this is for modest local workflow files rather than streaming very large XML.
  • The example is proposed code displayed as data and requires independent testing before publication; no execution or testing is claimed.

What this example adds

The supplied documentation establishes XML parsing with `xml.etree.ElementTree`, recursive element iteration, and CLI argument handling with `argparse`. This proposal combines those documented interfaces into a distinct workflow preflight check: instead of merely listing element attributes or checking references, it checks a caller-selected root and required nonblank call attributes, accepts either a path or stdin, and reports actionable failures without exposing attribute values.

Run it

Save as `validate_workflow.py`, then run `python3.12 validate_workflow.py workflow.xml --root-tag workflow --call-tag tool_call`. Use `-` as the file argument to read stdin, for example `python3.12 validate_workflow.py - --root-tag workflow --call-tag tool_call < workflow.xml`.

Example input

<workflow>
  <tool_call name="lookup" arguments="{"key":"sample"}" />
  <tool_call name="summarize" arguments="{}" />
</workflow>

Expected output

OK: root=workflow; 2 call element(s) validated
INSPECT THE SCRIPT

Inspect, copy and run the documented checks.

This browser preview builds code locally. It does not contact an API or run the code.

Default example ready.

Python example
# SPDX-License-Identifier: MIT
# Copyright (c) 2026 OpenViST contributors
import argparse
import sys
import xml.etree.ElementTree as ET
from pathlib import Path


def main():
    parser = argparse.ArgumentParser(
        description="Validate a local XML workflow root and call attributes."
    )
    parser.add_argument("file", help="XML path, or - to read standard input")
    parser.add_argument("--root-tag", required=True, help="Exact required root tag")
    parser.add_argument("--call-tag", required=True, help="Exact tag identifying calls")
    args = parser.parse_args()

    if not args.root_tag or not args.call_tag:
        parser.error("--root-tag and --call-tag must not be empty")

    try:
        if args.file == "-":
            source = sys.stdin.read()
        else:
            source = Path(args.file).read_text(encoding="utf-8")
        root = ET.fromstring(source)
    except FileNotFoundError:
        print("ERROR: input file not found", file=sys.stderr)
        return 2
    except UnicodeDecodeError:
        print("ERROR: input is not valid UTF-8", file=sys.stderr)
        return 2
    except ET.ParseError as exc:
        print(f"ERROR: malformed XML: {exc}", file=sys.stderr)
        return 2
    except OSError as exc:
        print(f"ERROR: cannot read input: {exc}", file=sys.stderr)
        return 2

    problems = []
    if root.tag != args.root_tag:
        problems.append(f"root tag is {root.tag!r}; expected {args.root_tag!r}")

    calls = list(root.iter(args.call_tag))
    for index, call in enumerate(calls, start=1):
        for attribute in ("name", "arguments"):
            if not call.get(attribute, "").strip():
                problems.append(f"{args.call_tag} #{index} has missing or empty {attribute}")

    if problems:
        for problem in problems:
            print(f"INVALID: {problem}")
        return 1

    print(f"OK: root={root.tag}; {len(calls)} call element(s) validated")
    return 0


if __name__ == "__main__":
    sys.exit(main())
What to verify after running
  • Run the valid synthetic fixture and compare stdout exactly with `OK: root=workflow; 2 call element(s) validated`.
  • Use a syntactically valid XML fixture with a wrong root and verify the expected-versus-actual root diagnostic.
  • Use a call element with a missing or whitespace-only required attribute and verify its one-based call number and attribute name are reported, without printing attribute values.
  • Test empty and malformed XML separately; verify each yields a clear error on stderr and a nonzero exit status.
  • Test a missing file and invalid UTF-8 input; verify both fail without a traceback.
  • Run the same valid XML through stdin and a path; verify equivalent success output. Independently test all behavior before publication.

Request or format preview

Illustrative preview. No provider response, price or balance is fetched.

Change a setting to inspect the preview.

Official sources and related profiles

    Code license: MIT. Keep the license notice with your copy.

    Example version 0.1.0 · Documentation reviewed 2026-10-12.

    Executed 6 synthetic local fixture cases in isolated CPython 3.12.15 on GitHub Actions, without network access. Declared exit codes, output assertions and input integrity checks passed. Live services, installed third-party packages and production behavior remain outside scope. Editorial approval is still required.

    Related browser tools

    Inspect related data locally in your browser. These tools have their own input rules and limits; they do not execute this recipe.