Skip to main content
Glama
cmendezs

mcp-facturacion-electronica-es

es__validate_ticketbai_schema

Validate a TicketBAI XML document against the province-specific XSD schema for Araba, Gipuzkoa, or Bizkaia.

Instructions

Valida un documento XML TicketBAI contra el XSD correcto para la provincia indicada. Los esquemas NO son intercambiables entre provincias.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
xmlYesXML TicketBAI a validar.
provinceYes

Implementation Reference

  • Async handler that validates TicketBAI XML against a provincial XSD schema. It first parses the XML, checks structural required elements (Emisor, NumFactura, FechaExpedicionFactura, ImporteTotalFactura, HuellaTBAI), then optionally validates against an XSD file found in specs/ticketbai/{province}/. Returns validation results with errors and warnings.
    async def handle_es_validate_ticketbai_schema(
        arguments: dict[str, Any],
    ) -> list[types.TextContent]:
        try:
            import pathlib  # noqa: PLC0415
    
            xml_str = arguments.get("xml", "")
            province_str = arguments.get("province", "")
    
            if not xml_str:
                return err("xml is required", "MISSING_PARAM")
            if not province_str:
                return err("province is required", "MISSING_PARAM")
    
            try:
                province = TicketBAIProvince(province_str)
            except ValueError:
                return err(f"Invalid province: {province_str!r}")
    
            xml_bytes = xml_str.encode() if isinstance(xml_str, str) else xml_str
            try:
                root = etree.fromstring(xml_bytes)
            except etree.XMLSyntaxError as exc:
                return ok({
                    "valid": False,
                    "errors": [f"XML malformado: {exc}"],
                    "warnings": [],
                    "province": province.value,
                    "validation_mode": "structural",
                })
    
            errors: list[str] = []
            warnings: list[str] = []
    
            def _req(tag: str) -> None:
                if root.find(f".//*[local-name()='{tag}']") is None:
                    errors.append(f"Elemento obligatorio ausente: <{tag}>")
    
            for tag in [
                "Emisor", "NumFactura", "FechaExpedicionFactura",
                "ImporteTotalFactura", "HuellaTBAI",
            ]:
                _req(tag)
    
            # Check XSDs per province
            xsd_dir = (
                pathlib.Path(__file__).parent.parent.parent
                / "specs" / "ticketbai" / province.value
            )
            xsd_files = list(xsd_dir.glob("*.xsd")) if xsd_dir.exists() else []
            validation_mode = "structural"
    
            if xsd_files:
                try:
                    schema = etree.XMLSchema(etree.parse(str(xsd_files[0])))
                    schema.validate(root)
                    for e in schema.error_log:
                        errors.append(f"[XSD-{province.value}] {e.message} (línea {e.line})")
                    validation_mode = f"xsd-{province.value}"
                except Exception as exc:
                    warnings.append(f"XSD validation failed to run: {exc}")
            else:
                warnings.append(
                    f"XSD provincial de {province.value} no disponible — "
                    f"descárguelo a specs/ticketbai/{province.value}/ para validación completa."
                )
    
            return ok({
                "valid": len(errors) == 0,
                "errors": errors,
                "warnings": warnings,
                "province": province.value,
                "validation_mode": validation_mode,
            })
    
        except Exception as exc:
            logger.exception("es__validate_ticketbai_schema failed")
            return err(str(exc))
  • Tool definition with inputSchema for es__validate_ticketbai_schema. Accepts 'xml' (string) and 'province' (enum: araba/gipuzkoa/bizkaia). Both are required.
    TOOL_ES_VALIDATE_TICKETBAI_SCHEMA = types.Tool(
        name="es__validate_ticketbai_schema",
        description=(
            "Valida un documento XML TicketBAI contra el XSD correcto para la provincia indicada. "
            "Los esquemas NO son intercambiables entre provincias."
        ),
        inputSchema={
            "type": "object",
            "properties": {
                "xml": {"type": "string", "description": "XML TicketBAI a validar."},
                "province": {
                    "type": "string",
                    "enum": ["araba", "gipuzkoa", "bizkaia"],
                },
            },
            "required": ["xml", "province"],
        },
    )
  • The tool constant TOOL_ES_VALIDATE_TICKETBAI_SCHEMA is included in the _ALL_TOOLS list (line 98) which is returned by the list_tools() handler.
    _ALL_TOOLS: list[types.Tool] = [
        # VERI*FACTU
        TOOL_ES_GENERATE_VERIFACTU_RECORD,
        TOOL_ES_VALIDATE_VERIFACTU_RECORD,
        TOOL_ES_SUBMIT_VERIFACTU_TO_AEAT,
        TOOL_ES_GENERATE_QR_VERIFACTU,
        TOOL_ES_CANCEL_VERIFACTU_RECORD,
        # Facturae / FACe
        TOOL_ES_GENERATE_FACTURAE_XML,
        TOOL_ES_SIGN_FACTURAE_XADES,
        TOOL_ES_SUBMIT_TO_FACE,
        TOOL_ES_GET_FACE_INVOICE_STATUS,
        TOOL_ES_VALIDATE_FACTURAE_SCHEMA,
        # SII
        TOOL_ES_BUILD_SII_INVOICE_RECORD,
        TOOL_ES_SUBMIT_SII_BATCH,
        TOOL_ES_QUERY_SII_STATUS,
        TOOL_ES_GENERATE_SII_CORRECTION,
        # TicketBAI
        TOOL_ES_GENERATE_TICKETBAI_XML,
        TOOL_ES_SUBMIT_TICKETBAI,
        TOOL_ES_VALIDATE_TICKETBAI_SCHEMA,
        # Crea y Crece / B2B
        TOOL_ES_GENERATE_B2B_EINVOICE_ES,
        TOOL_ES_CHECK_B2B_MANDATE_APPLICABILITY,
        # Utilities
        TOOL_ES_DETECT_REGIONAL_REGIME,
        TOOL_ES_GET_COMPLIANCE_STATUS,
        TOOL_ES_PARSE_AEAT_RESPONSE,
    ]
  • The handler handle_es_validate_ticketbai_schema is registered in _TOOL_HANDLERS dict under the key 'es__validate_ticketbai_schema'. The call_tool() dispatcher looks up handlers here.
    _TOOL_HANDLERS: dict[str, Any] = {
        # VERI*FACTU
        "es__generate_verifactu_record":      handle_es_generate_verifactu_record,
        "es__validate_verifactu_record":      handle_es_validate_verifactu_record,
        "es__submit_verifactu_to_aeat":       handle_es_submit_verifactu_to_aeat,
        "es__generate_qr_verifactu":          handle_es_generate_qr_verifactu,
        "es__cancel_verifactu_record":        handle_es_cancel_verifactu_record,
        # Facturae / FACe
        "es__generate_facturae_xml":          handle_es_generate_facturae_xml,
        "es__sign_facturae_xades":            handle_es_sign_facturae_xades,
        "es__submit_to_face":                 handle_es_submit_to_face,
        "es__get_face_invoice_status":        handle_es_get_face_invoice_status,
        "es__validate_facturae_schema":       handle_es_validate_facturae_schema,
        # SII
        "es__build_sii_invoice_record":       handle_es_build_sii_invoice_record,
        "es__submit_sii_batch":               handle_es_submit_sii_batch,
        "es__query_sii_status":               handle_es_query_sii_status,
        "es__generate_sii_correction":        handle_es_generate_sii_correction,
        # TicketBAI
        "es__generate_ticketbai_xml":         handle_es_generate_ticketbai_xml,
        "es__submit_ticketbai":               handle_es_submit_ticketbai,
        "es__validate_ticketbai_schema":      handle_es_validate_ticketbai_schema,
  • Import of TOOL_ES_VALIDATE_TICKETBAI_SCHEMA and handle_es_validate_ticketbai_schema from the ticketbai module.
    from mcp_facturacion_electronica_es.tools.ticketbai import (
        TOOL_ES_GENERATE_TICKETBAI_XML,
        TOOL_ES_SUBMIT_TICKETBAI,
        TOOL_ES_VALIDATE_TICKETBAI_SCHEMA,
        handle_es_generate_ticketbai_xml,
        handle_es_submit_ticketbai,
        handle_es_validate_ticketbai_schema,
    )
Behavior2/5

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

No annotations are provided, so the description must fully disclose behavioral traits. It only states the validation action without describing output format, error handling, or whether it is read-only.

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

Conciseness5/5

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

The description consists of two clear, concise sentences with no redundant information.

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

Completeness2/5

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

The tool has no output schema, so the description should explain what the response looks like. It omits return values or validation result structure, leaving the agent without sufficient context for invocation handling.

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

Parameters3/5

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

The schema documents the xml parameter and enum values for province. The description adds context that province selects the correct XSD, partially compensating for the missing province description in schema.

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 clearly states the tool validates a TicketBAI XML document against the correct XSD for the specified province, distinguishing it from sibling validation tools for other formats.

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 provides context for when to use the tool (validation with correct province) but does not explicitly mention when not to use it or compare with sibling validation tools.

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/cmendezs/mcp-facturacion-electronica-es'

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