Python API reference

The standalone server’s importable Python surface (used by the runnable examples and any agent that wraps the FastMCP instance directly).

pain001-mcp: a Model Context Protocol server for the pain001 library.

Tool, resource and prompt modules

Each tool family has its own module; pain001_mcp.server builds the server, registers every tool and re-exports them.

Server and registrations

Model Context Protocol (MCP) server for pain001.

This server exposes the pain001 library’s ISO 20022 pain.001 and companion-message capabilities as MCP tools so any MCP-compatible client (Claude Desktop, IDEs, agents) can discover supported message versions, inspect input schemas, validate payment records and financial identifiers, generate validated XML, and parse the bank-reply messages (camt.053 statements and pain.002 status reports).

Every tool is a thin, typed wrapper over the pain001 public API (the schema loader, the IBAN/BIC validators, generate_xml_string, and the camt.053 / pain.002 parsers) so all interfaces behave identically to the CLI and REST API. Tools return JSON-serializable data (dicts, lists, or strings); on a ValueError (or a pain001.exceptions subclass thereof) they return an {"error": ...} dictionary rather than raising.

The tools live in one module per family (_catalogue, _records, _generate, _replies, _schemes, _corpus, _faces, _staging, _clearing), sharing _common and the result shapes in _shapes. This module builds the server, registers every tool in listing order (ADR 0003) and re-exports them, so server.<tool> keeps working for callers.

Launching the server:
  • As a console script:

    pain001-mcp
    
  • Programmatically:

    from pain001_mcp.server import main
    main()
    
  • In an MCP client config (e.g. Claude Desktop claude_desktop_config.json):

    {
      "mcpServers": {
        "pain001": {
          "command": "pain001-mcp"
        }
      }
    }
    

The server communicates over stdio (MCPServer’s default transport).

pain001_mcp.server.build_payment_batch(message_type='pain.001.001.09')[source]

Guided prompt for assembling a compliant payment batch.

The MCP client sends this to the model to teach it the recommended tool order: discover columns, build rows, validate, then generate.

Parameters:

message_type (str) – The target ISO 20022 pain message type.

Return type:

str

Returns:

A prompt string instructing the model how to proceed.

pain001_mcp.server.check_payment_file(xml_content, scheme=None, schematron=None)[source]

Check an existing pain.001 or pain.008 file, as pain001 check does.

Use this on a payment file that already exists (one a bank returned, another system wrote, or an earlier run produced) to learn whether it is valid and why not. validate_records checks rows before generation; this checks the XML itself: its message type’s XSD, the cross-element rules of the message definition, and the scheme profiles and Schematron preset asked for. Every rung runs, so all problems come back at once.

Delegates to pain001.check.check_document().

Parameters:
  • xml_content (str) – The document as XML text.

  • scheme (str | None) – Scheme profiles, comma-separated, or None.

  • schematron (str | None) – A Schematron preset, or None.

Return type:

CheckResult

Returns:

{"message_type", "passed", "errors", "warnings", "rungs", "findings": [{"rung", "rule", "severity", "message", "location"}, ...]}, or {"error": ...} when the document cannot be checked (not a bundled pain.001 or pain.008, a DTD, too large, an unknown scheme or preset) or the installed pain001 has no checker.

pain001_mcp.server.commit_payment_batch(stage_id, confirmation_token, output_file_path=None)[source]

Commit a staged payment batch with its confirmation token.

Verifies the stage ID and validates the secondary confirmation token using constant-time cryptographic comparison (preventing timing attacks). Transitions the order status from ‘staged’ to ‘committed’. Optionally writes a new .xml file inside the output directory (see _output.py). The token guards against an accidental commit only.

Parameters:
  • stage_id (str) – Staging identifier from stage_payment_batch.

  • confirmation_token (str) – Secondary secret confirmation token.

  • output_file_path (str | None) – Optional new XML file in the output directory.

Return type:

CommitPaymentBatchResult

Returns:

CommitPaymentBatchResult with commit timestamp and fingerprint, or {“error”: …}.

pain001_mcp.server.convert_mt101(mt101_text)[source]

Convert a legacy SWIFT MT101 message into pain.001-ready records.

Use this to bridge the Nov-2025+ SWIFT MT→MX migration: parse an MT101 (Request for Transfer) into the flat records the other tools consume — feed the result straight to validate_records / validate_payment_scheme and then generate_message to emit pain.001.001.09 XML. An MT101 can request many transfers (repeating sequence B), so this returns one record per transaction. Operates on the supplied text only; no file is read or written.

Wraps pain001_loader_mt101.loader.parse_mt101(). Sequence-A ordering-customer / account-servicing fields apply to every transaction unless a sequence-B block overrides them; fields the MT101 does not carry are synthesised to schema defaults (payment_method "TRF", service_level_code "SEPA", etc.).

Parameters:

mt101_text (str) – The MT101 payload as a string.

Return type:

list[dict] | dict

Returns:

A list of flat pain.001 records (one per transaction), or an {"error": ...} dict if the MT101 is missing a mandatory field (:20:, :30:, or per transaction :21: / :32B: / a named beneficiary) or is otherwise malformed.

pain001_mcp.server.generate_message(message_type, records, identifier_checks=True)[source]

Generate a validated ISO 20022 pain XML message from in-memory records.

This is the primary generation tool: pass records you already hold in memory. Use generate_message_from_file when the data lives in a CSV on disk, and generate_message_async for very large batches you want to run off the event loop. The result is XSD-validated before return; no file is written.

Records are normalized before rendering: ‘amount’/’currency’ aliases, JSON booleans, and bare ‘YYYY-MM-DD’ dates are accepted, and nb_of_txs/ctrl_sum are computed from the records. On failure the {"error": ...} payload lists every missing or invalid field at once. The records are validated first exactly as validate_records and the pain001 CLI validate them (row contract, every IBAN and BIC unless identifier_checks is false, one payment information block, the JSON Schema); values are never coerced.

Returns the validated XML document as a string, or a JSON-encoded {"error": ..., "issues": [...]} payload if generation fails; issues (present when the validation refused the rows) lists each finding’s line, column, P001-E... code and message.

Parameters:
  • message_type (str) – A supported ISO 20022 pain message type.

  • records (list[dict]) – One or more flat payment records.

  • identifier_checks (bool) – If false, skip the IBAN and BIC checks.

Return type:

str

async pain001_mcp.server.generate_message_async(message_type, records, identifier_checks=True)[source]

Generate validated pain XML off the event loop, for large batches.

Behaves exactly like generate_message but runs the synchronous renderer in a worker thread so an agent can interleave a long generation with other tool calls. Use generate_message for small or interactive batches; use this only when the record count is large enough that blocking would matter.

Validates in a worker thread, then delegates to pain001.async_adapter.generate_xml_string_async(). Returns the validated XML, or the same JSON-encoded {"error", "issues"?} payload as generate_message.

Parameters:
  • message_type (str) – A supported ISO 20022 pain message type.

  • records (list[dict]) – One or more flat payment records.

  • identifier_checks (bool) – If false, skip the IBAN and BIC checks.

Return type:

str

pain001_mcp.server.generate_message_from_file(message_type, data_file_path)[source]

Generate validated pain XML from a payment data file on the local disk.

Use this when the records live in a file rather than in memory; if you already have them as dicts, call generate_message. The file is read and validated by the core’s own loader and validation ladder, exactly as pain001 generate reads it, so the same path-safety guards apply and the same files are refused; an issue’s line is the file’s line (a CSV header is line 1).

Parameters:
  • message_type (str) – A supported ISO 20022 pain message type.

  • data_file_path (str) – Path to the payment data file.

Return type:

str

Returns:

The validated XML, or a JSON-encoded {"error", "issues"?} payload as generate_message returns it.

pain001_mcp.server.get_corpus_coverage(version)[source]

Return the schema coverage verdict of one message type’s coverage set.

Use this to check that the shipped coverage files reach every element path and choice branch of an edition’s XSD before relying on them to smoke a parser or a mapping.

Delegates to pain001.corpus.coverage_report().

Parameters:

version (str) – The message type.

Return type:

CorpusCoverageResult

Returns:

The coverage.json content (path and branch counts and percentages, completeness, missing and exempt lists), or {"error": ...} when the edition has no set or there is no corpus.

pain001_mcp.server.get_corpus_file(scenario_id, version, variant=None)[source]

Return the XML of one validated example file from the market corpus.

Use this to show a model, a tester or a mapping exercise what a correct file for a given country and rail looks like in a given edition. The text is exactly what pain001 ships; it passed the XSD, the ISO MDR rules, the rail profile and the overlay when it was built.

Delegates to pain001.corpus.get_file().

Parameters:
  • scenario_id (str) – The scenario.

  • version (str) – The message type.

  • variant (str | None) – The overlay id of a bank variant, else None.

Return type:

CorpusFileResult

Returns:

{"scenario_id", "version", "variant", "xml"}, or {"error": ...} when there is no such file or no corpus.

pain001_mcp.server.get_corpus_provenance(scenario_id, version, variant=None)[source]

Return the provenance sidecar of one example file.

Use this to know how far to trust a file: the sources it was derived from, the confidence of the evidence (verified, derived or assumed), the validation ladder result per rung, what the builder renamed or dropped to fit the edition, and the file’s SHA-256.

Delegates to pain001.corpus.provenance().

Parameters:
  • scenario_id (str) – The scenario.

  • version (str) – The message type.

  • variant (str | None) – The overlay id of a bank variant, else None.

Return type:

CorpusProvenanceResult

Returns:

The parsed sidecar as a dict, or {"error": ...} when there is no such file or no corpus.

pain001_mcp.server.get_input_schema(message_type)[source]

Return the full JSON Schema for a message type’s flat input record.

Use this to learn every field, its type, and its constraints before assembling records, or to drive a form/UI. For just the required-field names use get_required_fields; to actually check records against this schema use validate_records.

Parameters:

message_type (str) – A supported ISO 20022 pain message type.

Return type:

SchemaResult

pain001_mcp.server.get_required_fields(message_type)[source]

List only the required input field names for a pain message type.

Use this for a quick checklist of the mandatory columns before building records. When you need full type/format constraints (not just which fields are required), call get_input_schema instead.

Parameters:

message_type (str) – A supported ISO 20022 pain message type.

Return type:

list[str]

pain001_mcp.server.inspect_template(message_type)[source]

Return the CSV column headers the message type’s bundled template uses.

Use this to see the exact column order for hand-building a CSV before generate_message_from_file. This returns column names from the bundled sample; for the typed JSON contract (types, required flags) use get_input_schema.

Mirrors the in-tree pain001.mcp.server.inspect_template tool so an agent can introspect the column layout before assembling rows.

Parameters:

message_type (str) – A supported ISO 20022 pain message type.

Return type:

TemplateResult

Returns:

{"message_type": str, "columns": list[str]} or {"error": ...} if the type is unsupported or no template ships.

pain001_mcp.server.list_corpus_files(kind=None, country=None, version=None)[source]

List the example files pain001 ships: market scenarios and coverage sets.

Use this to discover the scenario_id, version, and variant identifiers of the ready-made, validated ISO 20022 files pain001 ships; get_corpus_file and get_corpus_provenance accept those identifiers. Market files are realistic payments per country and rail (scenario_id like gb.chaps.property-purchase); a variant names the bank overlay a file was built with. Coverage files exercise every element and choice branch of one message type and carry no scenario.

Delegates to pain001.corpus.list_files().

Parameters:
  • kind (str | None) – market, coverage or None for both.

  • country (str | None) – Optional two-letter country filter for market files.

  • version (str | None) – Optional message-type filter.

Returns:

[{“kind”, “scenario_id”, “version”, “country”, “family”, “variant”, “file”}, …]}``, or {"error": ...} when the installed pain001 has no corpus.

Return type:

CorpusListResult

pain001_mcp.server.list_faces()[source]

List the faces: the standards a pain.001 document can be projected into.

Use this before project_face to pick a target and to learn which bindings it accepts. A binding is a value the payment message does not carry, such as the UK Open Banking ConsentId agreed with the bank; any key a face does not list is refused.

Delegates to pain001.faces.list_supported_faces().

Return type:

FaceListResult

Returns:

{"count", "faces": [{"name", "description", "bindings"}, ...]}, or {"error": ...} when the installed pain001 has no faces.

pain001_mcp.server.list_message_types()[source]

List every supported ISO 20022 pain message type and its human name.

Use this first, before any generation or validation call, to discover the exact message_type strings this server accepts. Returns message-type codes and display names only; use get_required_fields or get_input_schema to inspect fields or schemas.

Returns a list of {"message_type": ..., "name": ...} dictionaries, one per supported message type (e.g. pain.001.001.09).

Return type:

list[dict]

pain001_mcp.server.list_scheme_profiles()[source]

List every payment-scheme rulebook profile the core ships.

Use this to choose the profile for validate_payment_scheme (or the scheme of simulate_payment_batch and stage_payment_batch) before calling it. Each entry gives the profile name, a one-line description, the prefix of the rule ids a rail profile reports (null for the SEPA, cross-border, duplicate and purpose-mandate profiles), and the public documents it was built from. Everything comes from the installed pain001; nothing is restated here.

Returns:

int, “profiles”: [{“name”, “description”, “rule_prefix”, “sources”}, …]}`` in name order.

Return type:

SchemeProfilesResult

pain001_mcp.server.list_supported_formats()[source]

List the on-disk data formats the pain001 loader can read.

Use this to tell a user which file types they may supply to generate_message_from_file. This lists data-source formats (CSV, SQLite, …); for the list of ISO 20022 message types call list_message_types instead.

Returns a list of {"id", "name", "extension"} dictionaries covering CSV, SQLite, JSON, JSONL, and Parquet (the last requires the pain001[parquet] extra).

Return type:

list[dict]

pain001_mcp.server.main(argv=None)[source]

Run the pain001 MCP server (the pain001-mcp entry point).

stdio by default; --transport streamable-http or --transport sse listens on --host/--port instead. See pain001_mcp._cli.

Parameters:

argv (list[str] | None) – Command-line arguments; None reads sys.argv[1:].

Return type:

None

pain001_mcp.server.migrate_records(records, from_version, to_version)[source]

Migrate flat payment records between two pain.001 schema versions.

Use this to upgrade/downgrade records when your bank requires a different pain.001 version than your source data uses (e.g. move .03 rows to .09); it reports which fields were renamed, derived, or dropped. This transforms records only — run validate_records afterwards, then generate_message to emit XML.

Wraps pain001.migration.VersionMapper. Returns the migrated rows plus a summary of which fields were renamed, derived, or dropped; {"error": ...} if either version is unsupported.

Parameters:
  • records (list[dict]) – Records in the from_version shape.

  • from_version (str) – Source pain.001 version (e.g. "pain.001.001.03").

  • to_version (str) – Target pain.001 version (e.g. "pain.001.001.09").

Return type:

MigrateResult

Returns:

{"records": [...], "migrated": int, "from": str, "to": str} or {"error": ...}.

pain001_mcp.server.parse_camt053(xml_file_path, xsd_file_path=None)[source]

Parse a camt.053 bank-statement XML file on disk into structured data.

Use this to read a bank’s account statement (the reply that confirms settlement) into a header + entry list. Reads xml_file_path from the local filesystem. For the payment-status reply (accepted/rejected per transaction) use parse_pain002 instead; to validate a camt.053 string you already hold, this is not it — this tool needs a file path.

Wraps pain001.parse_camt053_statement(). When xsd_file_path is provided, the document is first validated against that XSD; on a schema or parse error the tool returns {"error": ...} rather than raising.

Parameters:
  • xml_file_path (str) – Filesystem path to the camt.053 XML statement.

  • xsd_file_path (str | None) – Optional path to a camt.053 XSD for upfront validation.

Return type:

Camt053Result

Returns:

The first statement’s header and entries, every statement under statements, or an {"error": ...} payload on failure.

pain001_mcp.server.parse_pain002(xml_file_path, xsd_file_path=None)[source]

Parse a pain.002 payment-status report file on disk into structured data.

Use this to read the bank’s acknowledgement of a submitted pain.001 — the per-transaction accepted/rejected status and reason codes. Reads xml_file_path from the local filesystem. For the account statement that later confirms booked entries, use parse_camt053 instead.

Wraps pain001.parse_pain002_report(). When xsd_file_path is provided, the document is first validated against that XSD; on a schema or parse error the tool returns {"error": ...} rather than raising.

Parameters:
  • xml_file_path (str) – Filesystem path to the pain.002 XML report.

  • xsd_file_path (str | None) – Optional path to a pain.002 XSD for upfront validation.

Return type:

Pain002Result

Returns:

A dict with the group header and transaction statuses, or an {"error": ...} payload on failure.

pain001_mcp.server.project_face(xml_content, face, version=None, bindings=None)[source]

Project a pain.001 document into another standard’s JSON shape.

Use this to turn a payment file into the request body a UK Open Banking or Berlin Group API expects, or into ISO 20022 element names, and to see exactly what the target cannot carry: the loss report lists every source element left out, by indexed path. A face never invents a value: when the target requires an element the document lacks, the answer is an {"error": ...} naming it. To check the document itself first, use validate_xml_against_schema.

Delegates to pain001.faces.project_face_text().

Parameters:
  • xml_content (str) – The pain.001 document as XML text.

  • face (str) – The target face.

  • version (str | None) – The edition, or None to detect it.

  • bindings (dict[str, Any] | None) – Side inputs the face accepts, or None.

Return type:

FaceProjectionResult

Returns:

{"face", "version", "payload", "loss_report"}, or {"error": ...} when the face refuses the document or a binding, or the installed pain001 has no faces.

pain001_mcp.server.sanitize_to_iso20022_charset(value, charset='SWIFT_X')[source]

Sanitise one free-text field to a SWIFT / ISO 20022 character set.

Use this on a single free-text value (name, remittance info) to transliterate accents and drop unsupported symbols before placing it in a record, and to see whether the value changed. Operates on one string; to check a whole batch’s rulebook compliance use validate_payment_scheme.

Two character sets are supported via charset:

  • "SWIFT_X" (default, backward-compatible) - the basic set used in most ISO 20022 / pain.001 fields. Delegates to pain001.sanitize_to_charset().

  • "SWIFT_Z" - the SWIFT extended set, a strict superset of X that also permits = ! " % & * < > ; { @ # _ (used in narrative / envelope fields). It does not permit | or }.

In both cases accents are transliterated (é -> e) and any remaining out-of-set character is replaced with a space. The result includes flags for whether the original was already valid and whether it changed - useful for surfacing the change to the user before writing it back to a record.

Parameters:
  • value (str) – The text to sanitise.

  • charset (Literal['SWIFT_X', 'SWIFT_Z']) – "SWIFT_X" (default) or "SWIFT_Z".

Return type:

SanitiseResult

Returns:

{"value": str, "sanitised": str, "was_valid": bool, "changed": bool}.

pain001_mcp.server.schema_resource(message_type)[source]

Expose the official XSD schema text for a message type as a resource.

MCP clients can subscribe to or fetch pain001://schema/{type} to pull the canonical XSD without having to install pain001 themselves.

Parameters:

message_type (str) – A supported ISO 20022 pain message type.

Return type:

str

Returns:

The XSD schema text. Raises ValueError for an unsupported type.

pain001_mcp.server.simulate_clearing(stage_id, clearing_system='EPC-SEPA')[source]

Simulate settlement and clearing network execution for a staged batch.

Evaluates network-specific rulebooks and clearing constraints: - EPC-SEPA: EUR currency mandate, SEPA-zone IBAN prefixes, SLEV charge bearer. - FedNow: USD instant gross settlement eligibility. - US-ACH: USD next-day clearing cycle routing. - SWIFT-MX: Cross-border correspondent banking BIC routing. - CHAPS: Same-day RTGS high-value GBP clearing. - BACS: Three-day GBP direct credit clearing.

Parameters:
  • stage_id (str) – Staging identifier from stage_payment_batch.

  • clearing_system (Literal['EPC-SEPA', 'FedNow', 'US-ACH', 'SWIFT-MX', 'CHAPS', 'BACS']) – Clearing rail profile to simulate.

Return type:

SimulateClearingResult

Returns:

SimulateClearingResult with verdict (ACCEPTED / REJECTED), detailed checks, and estimated settlement window, or {“error”: …}.

pain001_mcp.server.simulate_payment_batch(message_type, records, scheme=None)[source]

Simulate and pre-flight a payment batch before XML generation.

Performs comprehensive pre-flight verification without generating XML or staging files:

  1. Validates records against the message type’s JSON Schema.

  2. Validates records against an optional payment-scheme rulebook.

  3. Computes control sums grouped by currency.

  4. Calculates unique debtor and creditor account counts.

  5. Detects intra-batch duplicate transactions (same debtor, creditor, amount, currency, and execution date).

Returns a structured verdict with totals, sums by currency, duplicate findings, and schema/scheme errors.

Parameters:
  • message_type (str) – A supported ISO 20022 pain message type.

  • records (list[dict]) – One or more flat payment records to simulate.

  • scheme (str | None) – Optional payment scheme profile to validate against.

Return type:

SimulatePaymentBatchResult

pain001_mcp.server.stage_payment_batch(message_type, records, scheme=None)[source]

Stage a payment batch for simulation and a confirmed commit.

Creates an in-memory staged payment order with zero fund movement and a 1-hour expiration window. Computes:

  1. Schema validation against the message type’s JSON Schema.

  2. Optional scheme compliance verification (SEPA, BACS, etc.).

  3. Multi-currency control sums and fee estimation.

  4. Multi-factor risk scoring (detecting duplicates, high transaction amounts, and generic remittance narratives).

  5. In-memory XML compilation and SHA-256 fingerprinting.

  6. A confirmation token that commit_payment_batch requires.

Parameters:
  • message_type (str) – A supported ISO 20022 pain message type.

  • records (list[dict]) – One or more flat payment records to stage.

  • scheme (str | None) – Optional payment scheme profile to validate against.

Return type:

StagedBatchResult

Returns:

StagedBatchResult with staging metadata, risk assessment, fingerprint, and confirmation token, or {“error”: …}.

pain001_mcp.server.suggest_record_fix(record, validation_error, message_type='pain.001.001.03')[source]

Suggest deterministic, review-only fixes to non-financial fields.

Returns patches or a cannot_autofix reason. Never changes IBANs, BICs, accounts, amounts or currencies, even for whitespace. Review every candidate and validate the full record before generating a payment.

Parameters:
  • record (dict[str, Any]) – A flat payment record, left unchanged.

  • validation_error (dict[str, Any]) – Finding with field (or path) and rule keys.

  • message_type (str) – Supported schema supplying trusted field bounds.

Return type:

dict[str, Any]

pain001_mcp.server.validate_identifier(kind, value)[source]

Validate a single financial identifier (IBAN or BIC).

Use this for a one-off identifier check with a clear pass/fail and reason. To validate identifiers embedded across a whole batch, prefer validate_records / validate_payment_scheme instead of calling this per field.

Returns {"kind": str, "value": str, "valid": bool, "error": str} (the error key is present only when valid is False).

Parameters:
  • kind (str) – One of "iban" or "bic" (case-insensitive).

  • value (str) – The identifier value to check.

Return type:

ValidateIdentifierResult

pain001_mcp.server.validate_payment_scheme(records, profile='sepa-sct')[source]

Validate records against a payment-scheme rulebook (e.g. SEPA).

Use this after validate_records to enforce scheme-specific business rules (SEPA field lengths, allowed characters, currency/BIC constraints) that JSON-Schema validation alone does not cover. validate_records checks structural shape; this checks rulebook compliance for one profile.

Delegates to pain001.validate_scheme(). The profile parameter lists every profile the installed pain001 ships.

Parameters:
  • records (list[dict]) – Payment records as a list of flat dicts.

  • profile (str) – The scheme profile name.

Return type:

SchemeResult

Returns:

{"profile", "is_valid", "violations": [...]} with structured violations (each with rule, severity, field, message, remediation keys), or {"error": ...} for an unknown profile.

pain001_mcp.server.validate_records(message_type, records, identifier_checks=True)[source]

Validate flat records the way the pain001 CLI and REST API do.

Use this before generate_message: it runs the core’s validation ladder (pain001.validate), so a batch it accepts is one the CLI, the REST API and generate_message accept, and a batch it refuses is refused there too. The ladder checks the row contract (required fields, amounts, booleans, dates), every IBAN and BIC (unless identifier_checks is false), that the rows form one payment information block, then the message type’s JSON Schema (for example an ISO 4217 currency). For payment-scheme rulebook checks (SEPA field lengths, charset, etc.) also run validate_payment_scheme.

The row contract and identifier checks refuse the batch as a whole (valid_count 0) and name the first problems; the schema check then reports every row. Each error carries row (from 0), line (from 1), path (the field), code (the core’s stable P001-E... issue code) and message, which never repeats the value.

Returns a report {"valid": bool, "total": int, "valid_count": int, "errors": [...]}, or {"error": ...} for rows that do not form one batch, an empty list or an unknown message type.

Parameters:
  • message_type (str) – A supported ISO 20022 pain message type.

  • records (list[dict]) – One or more flat payment records to validate.

  • identifier_checks (bool) – If false, skip the IBAN and BIC checks.

Return type:

ValidateRecordsResult

pain001_mcp.server.validate_xml_against_schema(xml_content, message_type)[source]

Validate a raw pain.001 / pain.008 XML string against its official XSD.

Use this to check XML you already have as a string (e.g. received from another system) without touching the filesystem. To validate records before they become XML, use validate_records; to parse a statement or status-report file, use parse_camt053 / parse_pain002.

Wraps pain001.xml.validate_via_xsd.validate_xml_string_via_xsd().

Parameters:
  • xml_content (str) – The XML document as a string.

  • message_type (str) – A supported ISO 20022 pain message type.

Return type:

XsdResult

Returns:

{"valid": bool, "message_type": str, "error": str?} - error is present only when valid is False.

Discovery tools, resource and prompt

Discovery tools: message types, fields, schemas, templates, formats.

Also the pain001://schema/{message_type} resource and the build_payment_batch prompt, which point an agent at these tools.

pain001_mcp._catalogue.build_payment_batch(message_type='pain.001.001.09')[source]

Guided prompt for assembling a compliant payment batch.

The MCP client sends this to the model to teach it the recommended tool order: discover columns, build rows, validate, then generate.

Parameters:

message_type (str) – The target ISO 20022 pain message type.

Return type:

str

Returns:

A prompt string instructing the model how to proceed.

pain001_mcp._catalogue.get_input_schema(message_type)[source]

Return the full JSON Schema for a message type’s flat input record.

Use this to learn every field, its type, and its constraints before assembling records, or to drive a form/UI. For just the required-field names use get_required_fields; to actually check records against this schema use validate_records.

Parameters:

message_type (str) – A supported ISO 20022 pain message type.

Return type:

SchemaResult

pain001_mcp._catalogue.get_required_fields(message_type)[source]

List only the required input field names for a pain message type.

Use this for a quick checklist of the mandatory columns before building records. When you need full type/format constraints (not just which fields are required), call get_input_schema instead.

Parameters:

message_type (str) – A supported ISO 20022 pain message type.

Return type:

list[str]

pain001_mcp._catalogue.inspect_template(message_type)[source]

Return the CSV column headers the message type’s bundled template uses.

Use this to see the exact column order for hand-building a CSV before generate_message_from_file. This returns column names from the bundled sample; for the typed JSON contract (types, required flags) use get_input_schema.

Mirrors the in-tree pain001.mcp.server.inspect_template tool so an agent can introspect the column layout before assembling rows.

Parameters:

message_type (str) – A supported ISO 20022 pain message type.

Return type:

TemplateResult

Returns:

{"message_type": str, "columns": list[str]} or {"error": ...} if the type is unsupported or no template ships.

pain001_mcp._catalogue.list_message_types()[source]

List every supported ISO 20022 pain message type and its human name.

Use this first, before any generation or validation call, to discover the exact message_type strings this server accepts. Returns message-type codes and display names only; use get_required_fields or get_input_schema to inspect fields or schemas.

Returns a list of {"message_type": ..., "name": ...} dictionaries, one per supported message type (e.g. pain.001.001.09).

Return type:

list[dict]

pain001_mcp._catalogue.list_supported_formats()[source]

List the on-disk data formats the pain001 loader can read.

Use this to tell a user which file types they may supply to generate_message_from_file. This lists data-source formats (CSV, SQLite, …); for the list of ISO 20022 message types call list_message_types instead.

Returns a list of {"id", "name", "extension"} dictionaries covering CSV, SQLite, JSON, JSONL, and Parquet (the last requires the pain001[parquet] extra).

Return type:

list[dict]

pain001_mcp._catalogue.schema_resource(message_type)[source]

Expose the official XSD schema text for a message type as a resource.

MCP clients can subscribe to or fetch pain001://schema/{type} to pull the canonical XSD without having to install pain001 themselves.

Parameters:

message_type (str) – A supported ISO 20022 pain message type.

Return type:

str

Returns:

The XSD schema text. Raises ValueError for an unsupported type.

Record tools

Record tools: schema checks, identifiers, fixes, migration, charset, MT101.

Each tool works on the records or text it is given; none reads or writes a file.

pain001_mcp._records.convert_mt101(mt101_text)[source]

Convert a legacy SWIFT MT101 message into pain.001-ready records.

Use this to bridge the Nov-2025+ SWIFT MT→MX migration: parse an MT101 (Request for Transfer) into the flat records the other tools consume — feed the result straight to validate_records / validate_payment_scheme and then generate_message to emit pain.001.001.09 XML. An MT101 can request many transfers (repeating sequence B), so this returns one record per transaction. Operates on the supplied text only; no file is read or written.

Wraps pain001_loader_mt101.loader.parse_mt101(). Sequence-A ordering-customer / account-servicing fields apply to every transaction unless a sequence-B block overrides them; fields the MT101 does not carry are synthesised to schema defaults (payment_method "TRF", service_level_code "SEPA", etc.).

Parameters:

mt101_text (str) – The MT101 payload as a string.

Return type:

list[dict] | dict

Returns:

A list of flat pain.001 records (one per transaction), or an {"error": ...} dict if the MT101 is missing a mandatory field (:20:, :30:, or per transaction :21: / :32B: / a named beneficiary) or is otherwise malformed.

pain001_mcp._records.migrate_records(records, from_version, to_version)[source]

Migrate flat payment records between two pain.001 schema versions.

Use this to upgrade/downgrade records when your bank requires a different pain.001 version than your source data uses (e.g. move .03 rows to .09); it reports which fields were renamed, derived, or dropped. This transforms records only — run validate_records afterwards, then generate_message to emit XML.

Wraps pain001.migration.VersionMapper. Returns the migrated rows plus a summary of which fields were renamed, derived, or dropped; {"error": ...} if either version is unsupported.

Parameters:
  • records (list[dict]) – Records in the from_version shape.

  • from_version (str) – Source pain.001 version (e.g. "pain.001.001.03").

  • to_version (str) – Target pain.001 version (e.g. "pain.001.001.09").

Return type:

MigrateResult

Returns:

{"records": [...], "migrated": int, "from": str, "to": str} or {"error": ...}.

pain001_mcp._records.sanitize_to_iso20022_charset(value, charset='SWIFT_X')[source]

Sanitise one free-text field to a SWIFT / ISO 20022 character set.

Use this on a single free-text value (name, remittance info) to transliterate accents and drop unsupported symbols before placing it in a record, and to see whether the value changed. Operates on one string; to check a whole batch’s rulebook compliance use validate_payment_scheme.

Two character sets are supported via charset:

  • "SWIFT_X" (default, backward-compatible) - the basic set used in most ISO 20022 / pain.001 fields. Delegates to pain001.sanitize_to_charset().

  • "SWIFT_Z" - the SWIFT extended set, a strict superset of X that also permits = ! " % & * < > ; { @ # _ (used in narrative / envelope fields). It does not permit | or }.

In both cases accents are transliterated (é -> e) and any remaining out-of-set character is replaced with a space. The result includes flags for whether the original was already valid and whether it changed - useful for surfacing the change to the user before writing it back to a record.

Parameters:
  • value (str) – The text to sanitise.

  • charset (Literal['SWIFT_X', 'SWIFT_Z']) – "SWIFT_X" (default) or "SWIFT_Z".

Return type:

SanitiseResult

Returns:

{"value": str, "sanitised": str, "was_valid": bool, "changed": bool}.

pain001_mcp._records.suggest_record_fix(record, validation_error, message_type='pain.001.001.03')[source]

Suggest deterministic, review-only fixes to non-financial fields.

Returns patches or a cannot_autofix reason. Never changes IBANs, BICs, accounts, amounts or currencies, even for whitespace. Review every candidate and validate the full record before generating a payment.

Parameters:
  • record (dict[str, Any]) – A flat payment record, left unchanged.

  • validation_error (dict[str, Any]) – Finding with field (or path) and rule keys.

  • message_type (str) – Supported schema supplying trusted field bounds.

Return type:

dict[str, Any]

pain001_mcp._records.validate_identifier(kind, value)[source]

Validate a single financial identifier (IBAN or BIC).

Use this for a one-off identifier check with a clear pass/fail and reason. To validate identifiers embedded across a whole batch, prefer validate_records / validate_payment_scheme instead of calling this per field.

Returns {"kind": str, "value": str, "valid": bool, "error": str} (the error key is present only when valid is False).

Parameters:
  • kind (str) – One of "iban" or "bic" (case-insensitive).

  • value (str) – The identifier value to check.

Return type:

ValidateIdentifierResult

pain001_mcp._records.validate_records(message_type, records, identifier_checks=True)[source]

Validate flat records the way the pain001 CLI and REST API do.

Use this before generate_message: it runs the core’s validation ladder (pain001.validate), so a batch it accepts is one the CLI, the REST API and generate_message accept, and a batch it refuses is refused there too. The ladder checks the row contract (required fields, amounts, booleans, dates), every IBAN and BIC (unless identifier_checks is false), that the rows form one payment information block, then the message type’s JSON Schema (for example an ISO 4217 currency). For payment-scheme rulebook checks (SEPA field lengths, charset, etc.) also run validate_payment_scheme.

The row contract and identifier checks refuse the batch as a whole (valid_count 0) and name the first problems; the schema check then reports every row. Each error carries row (from 0), line (from 1), path (the field), code (the core’s stable P001-E... issue code) and message, which never repeats the value.

Returns a report {"valid": bool, "total": int, "valid_count": int, "errors": [...]}, or {"error": ...} for rows that do not form one batch, an empty list or an unknown message type.

Parameters:
  • message_type (str) – A supported ISO 20022 pain message type.

  • records (list[dict]) – One or more flat payment records to validate.

  • identifier_checks (bool) – If false, skip the IBAN and BIC checks.

Return type:

ValidateRecordsResult

Generation tools

Generation tools: pain XML from records in memory or from a data file.

The rows climb the core’s validation ladder first, as pain001 generate and the REST API’s generate route make them, so nothing is generated that those refuse; the XML is then XSD-validated by the core before it is returned. No tool here writes a file. validate_xml_against_schema runs the same XSD check on an XML string the caller already holds.

pain001_mcp._generate.generate_message(message_type, records, identifier_checks=True)[source]

Generate a validated ISO 20022 pain XML message from in-memory records.

This is the primary generation tool: pass records you already hold in memory. Use generate_message_from_file when the data lives in a CSV on disk, and generate_message_async for very large batches you want to run off the event loop. The result is XSD-validated before return; no file is written.

Records are normalized before rendering: ‘amount’/’currency’ aliases, JSON booleans, and bare ‘YYYY-MM-DD’ dates are accepted, and nb_of_txs/ctrl_sum are computed from the records. On failure the {"error": ...} payload lists every missing or invalid field at once. The records are validated first exactly as validate_records and the pain001 CLI validate them (row contract, every IBAN and BIC unless identifier_checks is false, one payment information block, the JSON Schema); values are never coerced.

Returns the validated XML document as a string, or a JSON-encoded {"error": ..., "issues": [...]} payload if generation fails; issues (present when the validation refused the rows) lists each finding’s line, column, P001-E... code and message.

Parameters:
  • message_type (str) – A supported ISO 20022 pain message type.

  • records (list[dict]) – One or more flat payment records.

  • identifier_checks (bool) – If false, skip the IBAN and BIC checks.

Return type:

str

async pain001_mcp._generate.generate_message_async(message_type, records, identifier_checks=True)[source]

Generate validated pain XML off the event loop, for large batches.

Behaves exactly like generate_message but runs the synchronous renderer in a worker thread so an agent can interleave a long generation with other tool calls. Use generate_message for small or interactive batches; use this only when the record count is large enough that blocking would matter.

Validates in a worker thread, then delegates to pain001.async_adapter.generate_xml_string_async(). Returns the validated XML, or the same JSON-encoded {"error", "issues"?} payload as generate_message.

Parameters:
  • message_type (str) – A supported ISO 20022 pain message type.

  • records (list[dict]) – One or more flat payment records.

  • identifier_checks (bool) – If false, skip the IBAN and BIC checks.

Return type:

str

pain001_mcp._generate.generate_message_from_file(message_type, data_file_path)[source]

Generate validated pain XML from a payment data file on the local disk.

Use this when the records live in a file rather than in memory; if you already have them as dicts, call generate_message. The file is read and validated by the core’s own loader and validation ladder, exactly as pain001 generate reads it, so the same path-safety guards apply and the same files are refused; an issue’s line is the file’s line (a CSV header is line 1).

Parameters:
  • message_type (str) – A supported ISO 20022 pain message type.

  • data_file_path (str) – Path to the payment data file.

Return type:

str

Returns:

The validated XML, or a JSON-encoded {"error", "issues"?} payload as generate_message returns it.

pain001_mcp._generate.validate_xml_against_schema(xml_content, message_type)[source]

Validate a raw pain.001 / pain.008 XML string against its official XSD.

Use this to check XML you already have as a string (e.g. received from another system) without touching the filesystem. To validate records before they become XML, use validate_records; to parse a statement or status-report file, use parse_camt053 / parse_pain002.

Wraps pain001.xml.validate_via_xsd.validate_xml_string_via_xsd().

Parameters:
  • xml_content (str) – The XML document as a string.

  • message_type (str) – A supported ISO 20022 pain message type.

Return type:

XsdResult

Returns:

{"valid": bool, "message_type": str, "error": str?} - error is present only when valid is False.

Payment file check tool

Check an existing payment file (pain001 >= 0.0.82).

check_payment_file runs pain001.check.check_document(), the engine behind pain001 check and POST /api/v1/check (ADR-0010 in the core repository): the XSD of the message type the document’s namespace names, the message definition’s cross-element rules, and the scheme profiles and Schematron preset asked for. The document arrives as XML text, never a server path, and a Schematron rulebook is named by preset only, so a call cannot make the server read a file.

class pain001_mcp._check.CheckFindingResult[source]

Bases: TypedDict

One problem one rung found.

location: str | None
message: str
rule: str
rung: str
severity: str
class pain001_mcp._check.CheckResult[source]

Bases: TypedDict

The verdict, the rungs that ran and every finding, or a refusal.

error: NotRequired[str]
errors: NotRequired[int]
findings: NotRequired[list[CheckFindingResult]]
message_type: NotRequired[str]
passed: NotRequired[bool]
rungs: NotRequired[list[str]]
warnings: NotRequired[int]
pain001_mcp._check.check_payment_file(xml_content, scheme=None, schematron=None)[source]

Check an existing pain.001 or pain.008 file, as pain001 check does.

Use this on a payment file that already exists (one a bank returned, another system wrote, or an earlier run produced) to learn whether it is valid and why not. validate_records checks rows before generation; this checks the XML itself: its message type’s XSD, the cross-element rules of the message definition, and the scheme profiles and Schematron preset asked for. Every rung runs, so all problems come back at once.

Delegates to pain001.check.check_document().

Parameters:
  • xml_content (str) – The document as XML text.

  • scheme (str | None) – Scheme profiles, comma-separated, or None.

  • schematron (str | None) – A Schematron preset, or None.

Return type:

CheckResult

Returns:

{"message_type", "passed", "errors", "warnings", "rungs", "findings": [{"rung", "rule", "severity", "message", "location"}, ...]}, or {"error": ...} when the document cannot be checked (not a bundled pain.001 or pain.008, a DTD, too large, an unknown scheme or preset) or the installed pain001 has no checker.

Bank-reply tools

Bank-reply tools: camt.053 statements and pain.002 status reports.

Both read a file the caller names, through the core parsers and their path guards, and return the parsed content or an {"error": ...} payload.

pain001_mcp._replies.parse_camt053(xml_file_path, xsd_file_path=None)[source]

Parse a camt.053 bank-statement XML file on disk into structured data.

Use this to read a bank’s account statement (the reply that confirms settlement) into a header + entry list. Reads xml_file_path from the local filesystem. For the payment-status reply (accepted/rejected per transaction) use parse_pain002 instead; to validate a camt.053 string you already hold, this is not it — this tool needs a file path.

Wraps pain001.parse_camt053_statement(). When xsd_file_path is provided, the document is first validated against that XSD; on a schema or parse error the tool returns {"error": ...} rather than raising.

Parameters:
  • xml_file_path (str) – Filesystem path to the camt.053 XML statement.

  • xsd_file_path (str | None) – Optional path to a camt.053 XSD for upfront validation.

Return type:

Camt053Result

Returns:

The first statement’s header and entries, every statement under statements, or an {"error": ...} payload on failure.

pain001_mcp._replies.parse_pain002(xml_file_path, xsd_file_path=None)[source]

Parse a pain.002 payment-status report file on disk into structured data.

Use this to read the bank’s acknowledgement of a submitted pain.001 — the per-transaction accepted/rejected status and reason codes. Reads xml_file_path from the local filesystem. For the account statement that later confirms booked entries, use parse_camt053 instead.

Wraps pain001.parse_pain002_report(). When xsd_file_path is provided, the document is first validated against that XSD; on a schema or parse error the tool returns {"error": ...} rather than raising.

Parameters:
  • xml_file_path (str) – Filesystem path to the pain.002 XML report.

  • xsd_file_path (str | None) – Optional path to a pain.002 XSD for upfront validation.

Return type:

Pain002Result

Returns:

A dict with the group header and transaction statuses, or an {"error": ...} payload on failure.

Scheme tools

Scheme tools: rulebook validation and the batch pre-flight simulation.

pain001_mcp._schemes.list_scheme_profiles()[source]

List every payment-scheme rulebook profile the core ships.

Use this to choose the profile for validate_payment_scheme (or the scheme of simulate_payment_batch and stage_payment_batch) before calling it. Each entry gives the profile name, a one-line description, the prefix of the rule ids a rail profile reports (null for the SEPA, cross-border, duplicate and purpose-mandate profiles), and the public documents it was built from. Everything comes from the installed pain001; nothing is restated here.

Returns:

int, “profiles”: [{“name”, “description”, “rule_prefix”, “sources”}, …]}`` in name order.

Return type:

SchemeProfilesResult

pain001_mcp._schemes.simulate_payment_batch(message_type, records, scheme=None)[source]

Simulate and pre-flight a payment batch before XML generation.

Performs comprehensive pre-flight verification without generating XML or staging files:

  1. Validates records against the message type’s JSON Schema.

  2. Validates records against an optional payment-scheme rulebook.

  3. Computes control sums grouped by currency.

  4. Calculates unique debtor and creditor account counts.

  5. Detects intra-batch duplicate transactions (same debtor, creditor, amount, currency, and execution date).

Returns a structured verdict with totals, sums by currency, duplicate findings, and schema/scheme errors.

Parameters:
  • message_type (str) – A supported ISO 20022 pain message type.

  • records (list[dict]) – One or more flat payment records to simulate.

  • scheme (str | None) – Optional payment scheme profile to validate against.

Return type:

SimulatePaymentBatchResult

pain001_mcp._schemes.validate_payment_scheme(records, profile='sepa-sct')[source]

Validate records against a payment-scheme rulebook (e.g. SEPA).

Use this after validate_records to enforce scheme-specific business rules (SEPA field lengths, allowed characters, currency/BIC constraints) that JSON-Schema validation alone does not cover. validate_records checks structural shape; this checks rulebook compliance for one profile.

Delegates to pain001.validate_scheme(). The profile parameter lists every profile the installed pain001 ships.

Parameters:
  • records (list[dict]) – Payment records as a list of flat dicts.

  • profile (str) – The scheme profile name.

Return type:

SchemeResult

Returns:

{"profile", "is_valid", "violations": [...]} with structured violations (each with rule, severity, field, message, remediation keys), or {"error": ...} for an unknown profile.

Example corpus tools

Example corpus tools (pain001 >= 0.0.67).

Four read-only tools over pain001.corpus: the index, one file, a file’s provenance sidecar, and an edition’s schema coverage. An older core without the corpus gets a clear error payload, never an import failure.

pain001_mcp._corpus.get_corpus_coverage(version)[source]

Return the schema coverage verdict of one message type’s coverage set.

Use this to check that the shipped coverage files reach every element path and choice branch of an edition’s XSD before relying on them to smoke a parser or a mapping.

Delegates to pain001.corpus.coverage_report().

Parameters:

version (str) – The message type.

Return type:

CorpusCoverageResult

Returns:

The coverage.json content (path and branch counts and percentages, completeness, missing and exempt lists), or {"error": ...} when the edition has no set or there is no corpus.

pain001_mcp._corpus.get_corpus_file(scenario_id, version, variant=None)[source]

Return the XML of one validated example file from the market corpus.

Use this to show a model, a tester or a mapping exercise what a correct file for a given country and rail looks like in a given edition. The text is exactly what pain001 ships; it passed the XSD, the ISO MDR rules, the rail profile and the overlay when it was built.

Delegates to pain001.corpus.get_file().

Parameters:
  • scenario_id (str) – The scenario.

  • version (str) – The message type.

  • variant (str | None) – The overlay id of a bank variant, else None.

Return type:

CorpusFileResult

Returns:

{"scenario_id", "version", "variant", "xml"}, or {"error": ...} when there is no such file or no corpus.

pain001_mcp._corpus.get_corpus_provenance(scenario_id, version, variant=None)[source]

Return the provenance sidecar of one example file.

Use this to know how far to trust a file: the sources it was derived from, the confidence of the evidence (verified, derived or assumed), the validation ladder result per rung, what the builder renamed or dropped to fit the edition, and the file’s SHA-256.

Delegates to pain001.corpus.provenance().

Parameters:
  • scenario_id (str) – The scenario.

  • version (str) – The message type.

  • variant (str | None) – The overlay id of a bank variant, else None.

Return type:

CorpusProvenanceResult

Returns:

The parsed sidecar as a dict, or {"error": ...} when there is no such file or no corpus.

pain001_mcp._corpus.list_corpus_files(kind=None, country=None, version=None)[source]

List the example files pain001 ships: market scenarios and coverage sets.

Use this to discover the scenario_id, version, and variant identifiers of the ready-made, validated ISO 20022 files pain001 ships; get_corpus_file and get_corpus_provenance accept those identifiers. Market files are realistic payments per country and rail (scenario_id like gb.chaps.property-purchase); a variant names the bank overlay a file was built with. Coverage files exercise every element and choice branch of one message type and carry no scenario.

Delegates to pain001.corpus.list_files().

Parameters:
  • kind (str | None) – market, coverage or None for both.

  • country (str | None) – Optional two-letter country filter for market files.

  • version (str | None) – Optional message-type filter.

Returns:

[{“kind”, “scenario_id”, “version”, “country”, “family”, “variant”, “file”}, …]}``, or {"error": ...} when the installed pain001 has no corpus.

Return type:

CorpusListResult

Faces tools

Faces: a pain.001 document projected into another standard (pain001 >= 0.0.78).

Two tools over pain001.faces (ADR-0005 in the core repository): list_faces names each face, its target and the bindings it accepts; project_face returns the target payload and a loss report of every source element the target could not carry. The document arrives as XML text and goes through pain001.faces.project_face_text(), which never reads a server path and refuses entity declarations. The tools are registered in pain001_mcp.server with the others.

class pain001_mcp._faces.FaceEntry[source]

Bases: TypedDict

One face: its name, its target and the binding keys it accepts.

bindings: list[str]
description: str
name: str
class pain001_mcp._faces.FaceListResult[source]

Bases: TypedDict

Every face, or an error when the library has none.

count: NotRequired[int]
error: NotRequired[str]
faces: NotRequired[list[FaceEntry]]
class pain001_mcp._faces.FaceProjectionResult[source]

Bases: TypedDict

The target payload and its loss report, or the face’s refusal.

error: NotRequired[str]
face: NotRequired[str]
loss_report: NotRequired[LossReportResult]
payload: NotRequired[dict[str, Any]]
version: NotRequired[str]
class pain001_mcp._faces.LossReportResult[source]

Bases: TypedDict

Source leaves carried and not carried, by indexed path.

face: str
is_lossless: bool
loss_ratio: float
mapped_count: int
mapped_paths: list[str]
total_source_elements: int
unmapped_count: int
unmapped_paths: list[str]
pain001_mcp._faces.list_faces()[source]

List the faces: the standards a pain.001 document can be projected into.

Use this before project_face to pick a target and to learn which bindings it accepts. A binding is a value the payment message does not carry, such as the UK Open Banking ConsentId agreed with the bank; any key a face does not list is refused.

Delegates to pain001.faces.list_supported_faces().

Return type:

FaceListResult

Returns:

{"count", "faces": [{"name", "description", "bindings"}, ...]}, or {"error": ...} when the installed pain001 has no faces.

pain001_mcp._faces.project_face(xml_content, face, version=None, bindings=None)[source]

Project a pain.001 document into another standard’s JSON shape.

Use this to turn a payment file into the request body a UK Open Banking or Berlin Group API expects, or into ISO 20022 element names, and to see exactly what the target cannot carry: the loss report lists every source element left out, by indexed path. A face never invents a value: when the target requires an element the document lacks, the answer is an {"error": ...} naming it. To check the document itself first, use validate_xml_against_schema.

Delegates to pain001.faces.project_face_text().

Parameters:
  • xml_content (str) – The pain.001 document as XML text.

  • face (str) – The target face.

  • version (str | None) – The edition, or None to detect it.

  • bindings (dict[str, Any] | None) – Side inputs the face accepts, or None.

Return type:

FaceProjectionResult

Returns:

{"face", "version", "payload", "loss_report"}, or {"error": ...} when the face refuses the document or a binding, or the installed pain001 has no faces.

Staging tools

Staging tools: stage a batch, then commit it with its token.

A staged batch lives in memory for an hour with zero fund movement. simulate_clearing (in pain001_mcp._clearing) reads it, and commit_payment_batch marks it committed and may write its XML inside the output directory (pain001_mcp._output). The confirmation token guards against an accidental commit only.

pain001_mcp._staging.commit_payment_batch(stage_id, confirmation_token, output_file_path=None)[source]

Commit a staged payment batch with its confirmation token.

Verifies the stage ID and validates the secondary confirmation token using constant-time cryptographic comparison (preventing timing attacks). Transitions the order status from ‘staged’ to ‘committed’. Optionally writes a new .xml file inside the output directory (see _output.py). The token guards against an accidental commit only.

Parameters:
  • stage_id (str) – Staging identifier from stage_payment_batch.

  • confirmation_token (str) – Secondary secret confirmation token.

  • output_file_path (str | None) – Optional new XML file in the output directory.

Return type:

CommitPaymentBatchResult

Returns:

CommitPaymentBatchResult with commit timestamp and fingerprint, or {“error”: …}.

pain001_mcp._staging.stage_payment_batch(message_type, records, scheme=None)[source]

Stage a payment batch for simulation and a confirmed commit.

Creates an in-memory staged payment order with zero fund movement and a 1-hour expiration window. Computes:

  1. Schema validation against the message type’s JSON Schema.

  2. Optional scheme compliance verification (SEPA, BACS, etc.).

  3. Multi-currency control sums and fee estimation.

  4. Multi-factor risk scoring (detecting duplicates, high transaction amounts, and generic remittance narratives).

  5. In-memory XML compilation and SHA-256 fingerprinting.

  6. A confirmation token that commit_payment_batch requires.

Parameters:
  • message_type (str) – A supported ISO 20022 pain message type.

  • records (list[dict]) – One or more flat payment records to stage.

  • scheme (str | None) – Optional payment scheme profile to validate against.

Return type:

StagedBatchResult

Returns:

StagedBatchResult with staging metadata, risk assessment, fingerprint, and confirmation token, or {“error”: …}.

Clearing simulation

The clearing simulation over a staged batch.

Each clearing system is one row of _CLEARING: its settlement window and the function that returns its checks. A check passes or fails; the batch is accepted only when every check passes.

pain001_mcp._clearing.simulate_clearing(stage_id, clearing_system='EPC-SEPA')[source]

Simulate settlement and clearing network execution for a staged batch.

Evaluates network-specific rulebooks and clearing constraints: - EPC-SEPA: EUR currency mandate, SEPA-zone IBAN prefixes, SLEV charge bearer. - FedNow: USD instant gross settlement eligibility. - US-ACH: USD next-day clearing cycle routing. - SWIFT-MX: Cross-border correspondent banking BIC routing. - CHAPS: Same-day RTGS high-value GBP clearing. - BACS: Three-day GBP direct credit clearing.

Parameters:
  • stage_id (str) – Staging identifier from stage_payment_batch.

  • clearing_system (Literal['EPC-SEPA', 'FedNow', 'US-ACH', 'SWIFT-MX', 'CHAPS', 'BACS']) – Clearing rail profile to simulate.

Return type:

SimulateClearingResult

Returns:

SimulateClearingResult with verdict (ACCEPTED / REJECTED), detailed checks, and estimated settlement window, or {“error”: …}.

Result shapes

Result shapes: the TypedDicts every tool’s output schema comes from.

Every tool returns a JSON object, and any tool can answer with {"error": "..."} instead of its payload (ADR 0001: errors as data), so each shape lists the payload keys plus error and marks all of them optional. The MCP SDK derives the tool’s outputSchema from these, which is what an agent reads to know the keys before it calls; the exact keys and wording are pinned by tests/test_tool_result_shapes.py.

class pain001_mcp._shapes.Camt053Result[source]

Bases: TypedDict

A parsed camt.053: the first statement’s fields, and every one.

currency: NotRequired[str]
electronic_sequence_number: NotRequired[str]
entries: NotRequired[list[dict[str, Any]]]
error: NotRequired[str]
iban: NotRequired[str]
statement_id: NotRequired[str]
statements: NotRequired[list[dict[str, Any]]]
class pain001_mcp._shapes.ClearingCheck[source]

Bases: TypedDict

An individual rule check during clearing simulation.

check: str
detail: str
status: str
class pain001_mcp._shapes.CommitPaymentBatchResult[source]

Bases: TypedDict

Confirmation of authorized payment batch commit.

committed_at: NotRequired[str]
error: NotRequired[str]
output_file_path: NotRequired[str | None]
sha256_fingerprint: NotRequired[str]
stage_id: NotRequired[str]
status: NotRequired[str]
total_transactions: NotRequired[int]
class pain001_mcp._shapes.CorpusCoverageResult[source]

Bases: TypedDict

Schema-path coverage of the corpus for one message edition.

branches: NotRequired[CoverageCount]
complete: NotRequired[bool]
error: NotRequired[str]
exempt: NotRequired[list[str]]
files: NotRequired[list[dict[str, Any]]]
message_type: NotRequired[str]
missing_branches: NotRequired[list[str]]
missing_paths: NotRequired[list[str]]
paths: NotRequired[CoverageCount]
sources: NotRequired[list[Any]]
unknown: NotRequired[list[str]]
class pain001_mcp._shapes.CorpusFileEntry[source]

Bases: TypedDict

One file of the example corpus, as the index lists it.

Market files name a scenario, a country and a rail family; coverage files carry the edition only, so those three are null for them.

country: NotRequired[str | None]
family: NotRequired[str | None]
file: NotRequired[str]
kind: NotRequired[str]
scenario_id: NotRequired[str | None]
variant: NotRequired[str | None]
version: NotRequired[str]
class pain001_mcp._shapes.CorpusFileResult[source]

Bases: TypedDict

One corpus XML file with the request echoed beside it.

error: NotRequired[str]
scenario_id: NotRequired[str]
variant: NotRequired[str | None]
version: NotRequired[str]
xml: NotRequired[str]
class pain001_mcp._shapes.CorpusListResult[source]

Bases: TypedDict

The example corpus index.

count: NotRequired[int]
error: NotRequired[str]
files: NotRequired[list[CorpusFileEntry]]
class pain001_mcp._shapes.CorpusProvenanceResult[source]

Bases: TypedDict

A scenario’s provenance record, as the corpus ships it.

build: NotRequired[dict[str, Any]]
constraints: NotRequired[list[Any]]
country: NotRequired[str]
description: NotRequired[str]
error: NotRequired[str]
family: NotRequired[str]
message_type: NotRequired[str]
provenance: NotRequired[dict[str, Any]]
scenario: NotRequired[str]
sha256: NotRequired[str]
twins: NotRequired[dict[str, Any]]
validation: NotRequired[dict[str, Any]]
variant: NotRequired[str | None]
class pain001_mcp._shapes.CoverageCount[source]

Bases: TypedDict

Declared schema elements, how many the corpus hits, as a percentage.

declared: int
hit: int
percent: float
class pain001_mcp._shapes.DuplicateTransaction[source]

Bases: TypedDict

An intra-batch duplicate payment transaction.

amount: str
creditor_account_IBAN: str
currency: str
debtor_account_IBAN: str
matching_row: int
requested_execution_date: str
row: int
class pain001_mcp._shapes.ErrorResult[source]

Bases: TypedDict

The failure payload every tool may return instead of its result.

error: NotRequired[str]
class pain001_mcp._shapes.MigrateResult

Bases: TypedDict

Records rewritten from one message edition to another.

error: NotRequired[str]
from: NotRequired[str]
migrated: NotRequired[int]
records: NotRequired[list[dict[str, Any]]]
to: NotRequired[str]
class pain001_mcp._shapes.Pain002Result[source]

Bases: TypedDict

A parsed pain.002 status report, as the core library reports it.

creation_datetime: NotRequired[str]
error: NotRequired[str]
group_status: NotRequired[str]
message_id: NotRequired[str]
original_message_id: NotRequired[str]
original_message_name_id: NotRequired[str]
payment_statuses: NotRequired[list[dict[str, Any]]]
class pain001_mcp._shapes.RecordError[source]

Bases: TypedDict

One finding: the record’s row and line, the field, the code, why.

row counts records from 0 and line from 1, as the core’s issues do; code is the core’s stable P001-E... issue code.

code: str
line: int
message: str
path: str
row: int
class pain001_mcp._shapes.SanitiseResult[source]

Bases: TypedDict

A value and its ISO 20022 charset-clean rendering.

changed: NotRequired[bool]
sanitised: NotRequired[str]
value: NotRequired[str]
was_valid: NotRequired[bool]
class pain001_mcp._shapes.SchemaResult[source]

Bases: TypedDict

A JSON Schema (draft 7) for one message type’s flat records.

additionalProperties: NotRequired[bool]
description: NotRequired[str]
error: NotRequired[str]
properties: NotRequired[dict[str, Any]]
required: NotRequired[list[str]]
title: NotRequired[str]
type: NotRequired[str]
version: NotRequired[str]
class pain001_mcp._shapes.SchemeProfileEntry[source]

Bases: TypedDict

One scheme profile: its name, what it checks, and where from.

rule_prefix begins every rule id a rail profile reports (UK-FPS for UK-FPS-AMT); it is null for the other profiles, whose rule ids the core does not group under one prefix. sources are the public documents a rail or purpose mandate was built from, empty otherwise.

description: str
name: str
rule_prefix: str | None
sources: list[str]
class pain001_mcp._shapes.SchemeProfilesResult[source]

Bases: TypedDict

Every scheme profile the core ships, in name order.

count: NotRequired[int]
error: NotRequired[str]
profiles: NotRequired[list[SchemeProfileEntry]]
class pain001_mcp._shapes.SchemeResult[source]

Bases: TypedDict

Verdict against a scheme rulebook profile.

error: NotRequired[str]
is_valid: NotRequired[bool]
profile: NotRequired[str]
violations: NotRequired[list[SchemeViolation]]
class pain001_mcp._shapes.SchemeViolation[source]

Bases: TypedDict

One rulebook violation, with the remediation the library suggests.

field: str
index: int
message: str
remediation: str
rule: str
severity: str
class pain001_mcp._shapes.SimulateClearingResult[source]

Bases: TypedDict

Clearing network simulation verdict and settlement estimation.

checks: NotRequired[list[ClearingCheck]]
clearing_status: NotRequired[str]
clearing_system: NotRequired[str]
error: NotRequired[str]
settlement_window: NotRequired[str]
stage_id: NotRequired[str]
class pain001_mcp._shapes.SimulatePaymentBatchResult[source]

Bases: TypedDict

Simulation and pre-flight verdict over a payment batch.

control_sum_by_currency: NotRequired[dict[str, str]]
duplicates: NotRequired[list[DuplicateTransaction]]
error: NotRequired[str]
schema_errors: NotRequired[list[RecordError]]
scheme_violations: NotRequired[list[SchemeViolation]]
total: NotRequired[int]
unique_creditors: NotRequired[int]
unique_debtors: NotRequired[int]
valid: NotRequired[bool]
valid_count: NotRequired[int]
class pain001_mcp._shapes.StagedBatchResult[source]

Bases: TypedDict

Result of staging a payment batch for simulation and approval.

confirmation_token: NotRequired[str]
control_sum_by_currency: NotRequired[dict[str, str]]
error: NotRequired[str]
estimated_fees: NotRequired[dict[str, str]]
expires_at: NotRequired[str]
risk_factors: NotRequired[list[str]]
risk_level: NotRequired[str]
risk_score: NotRequired[int]
sha256_fingerprint: NotRequired[str]
stage_id: NotRequired[str]
status: NotRequired[str]
total_transactions: NotRequired[int]
class pain001_mcp._shapes.TemplateResult[source]

Bases: TypedDict

The bundled CSV template’s column names for one message type.

columns: NotRequired[list[str]]
error: NotRequired[str]
message_type: NotRequired[str]
class pain001_mcp._shapes.ValidateIdentifierResult[source]

Bases: TypedDict

An IBAN or BIC verdict, with the library’s message when invalid.

error: NotRequired[str]
kind: NotRequired[str]
valid: NotRequired[bool]
value: NotRequired[str]
class pain001_mcp._shapes.ValidateRecordsResult[source]

Bases: TypedDict

Verdict over a batch: one entry per violation, plus the counts.

error: NotRequired[str]
errors: NotRequired[list[RecordError]]
total: NotRequired[int]
valid: NotRequired[bool]
valid_count: NotRequired[int]
class pain001_mcp._shapes.XsdResult[source]

Bases: TypedDict

Verdict of an XML document against the official XSD.

error: NotRequired[str]
message_type: NotRequired[str]
valid: NotRequired[bool]

Transports and command line

The transport dispatch and its flags, shared verbatim by every server in the suite.

One command line for the three MCP transports.

Every server in the suite is started the same way:

<server>                                   # stdio, for a client that spawns it
<server> --transport streamable-http       # HTTP on 127.0.0.1:8000, path /mcp
<server> --transport sse --port 8001       # the older HTTP+SSE transport

Over streamable HTTP the SDK speaks both current protocol revisions on one endpoint: 2026-07-28 (stateless, server/discover, per-request _meta) and 2025-11-25 (initialize handshake, Mcp-Session-Id). Responses stream as server-sent events; a GET on the same path opens the server-to-client event stream. --transport sse serves the 2024-11-05 HTTP+SSE transport for clients that still expect it.

The listener binds the loopback interface unless told otherwise. There is no authentication here: put the server behind a gateway you trust before binding a routable address.

This module holds the transport dispatch; the flags that drive it live in _cli. Both files are copied verbatim into every server of the suite and work on mcp 1.x and 2.x.

pain001_mcp._transports.run(server, transport='stdio', host='127.0.0.1', port=8000)[source]

Serve server over transport; returns when the server stops.

Raises:

ValueError – If transport is not one of TRANSPORTS, or port is outside 1-65535.

Return type:

None

Parameters:

The command line every server in the suite shares.

serve is the body of each main(): it parses --transport, --host, --port and --version and hands the result to _transports.run(). Flag names, defaults and help text live here and nowhere else, so the suite is started and documented the same way.

Copied verbatim into every server of the suite.

pain001_mcp._cli.add_arguments(parser)[source]

Add --transport, --host and --port to parser.

Return type:

None

Parameters:

parser (ArgumentParser)

pain001_mcp._cli.serve(server, argv, prog, version)[source]

Parse argv and run server: the body of every main().

Return type:

None

Parameters: