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.
- pain001_mcp.server.check_payment_file(xml_content, scheme=None, schematron=None)[source]¶
Check an existing pain.001 or pain.008 file, as
pain001 checkdoes.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_recordschecks 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:
- Return type:
- 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
.xmlfile inside the output directory (see_output.py). The token guards against an accidental commit only.- Parameters:
- Return type:
- 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_schemeand thengenerate_messageto 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:
- 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_filewhen the data lives in a CSV on disk, andgenerate_message_asyncfor 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 asvalidate_recordsand the pain001 CLI validate them (row contract, every IBAN and BIC unlessidentifier_checksis 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’sline,column,P001-E...codeandmessage.
- 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_messagebut runs the synchronous renderer in a worker thread so an agent can interleave a long generation with other tool calls. Usegenerate_messagefor 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 asgenerate_message.
- 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 aspain001 generatereads it, so the same path-safety guards apply and the same files are refused; an issue’slineis the file’s line (a CSV header is line 1).
- 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:
- Returns:
The
coverage.jsoncontent (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:
- Return type:
- 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,derivedorassumed), 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:
- Return type:
- 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 usevalidate_records.- Parameters:
message_type (
str) – A supported ISO 20022 pain message type.- Return type:
- 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_schemainstead.
- 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) useget_input_schema.Mirrors the in-tree
pain001.mcp.server.inspect_templatetool so an agent can introspect the column layout before assembling rows.- Parameters:
message_type (
str) – A supported ISO 20022 pain message type.- Return type:
- 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, andvariantidentifiers of the ready-made, validated ISO 20022 filespain001ships;get_corpus_fileandget_corpus_provenanceaccept those identifiers. Market files are realistic payments per country and rail (scenario_idlikegb.chaps.property-purchase); avariantnames 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:
- Returns:
[{“kind”, “scenario_id”, “version”, “country”, “family”, “variant”, “file”}, …]}``, or
{"error": ...}when the installed pain001 has no corpus.- Return type:
- pain001_mcp.server.list_faces()[source]¶
List the faces: the standards a pain.001 document can be projected into.
Use this before
project_faceto 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 BankingConsentIdagreed with the bank; any key a face does not list is refused.Delegates to
pain001.faces.list_supported_faces().- Return type:
- 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_typestrings this server accepts. Returns message-type codes and display names only; useget_required_fieldsorget_input_schemato inspect fields or schemas.Returns a list of
{"message_type": ..., "name": ...}dictionaries, one per supported message type (e.g.pain.001.001.09).
- pain001_mcp.server.list_scheme_profiles()[source]¶
List every payment-scheme rulebook profile the core ships.
Use this to choose the
profileforvalidate_payment_scheme(or theschemeofsimulate_payment_batchandstage_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:
- 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 calllist_message_typesinstead.Returns a list of
{"id", "name", "extension"}dictionaries covering CSV, SQLite, JSON, JSONL, and Parquet (the last requires thepain001[parquet]extra).
- pain001_mcp.server.main(argv=None)[source]¶
Run the pain001 MCP server (the
pain001-mcpentry point).stdio by default;
--transport streamable-httpor--transport sselistens on--host/--portinstead. Seepain001_mcp._cli.
- 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
.03rows to.09); it reports which fields were renamed, derived, or dropped. This transforms records only — runvalidate_recordsafterwards, thengenerate_messageto 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:
- Return type:
- 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_pathfrom the local filesystem. For the payment-status reply (accepted/rejected per transaction) useparse_pain002instead; to validate a camt.053 string you already hold, this is not it — this tool needs a file path.Wraps
pain001.parse_camt053_statement(). Whenxsd_file_pathis provided, the document is first validated against that XSD; on a schema or parse error the tool returns{"error": ...}rather than raising.- Parameters:
- Return type:
- 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_pathfrom the local filesystem. For the account statement that later confirms booked entries, useparse_camt053instead.Wraps
pain001.parse_pain002_report(). Whenxsd_file_pathis provided, the document is first validated against that XSD; on a schema or parse error the tool returns{"error": ...}rather than raising.- Parameters:
- Return type:
- 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, usevalidate_xml_against_schema.Delegates to
pain001.faces.project_face_text().- Parameters:
- Return type:
- 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 topain001.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:
- Return type:
- 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.
- 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:
- Return type:
- 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:
Validates records against the message type’s JSON Schema.
Validates records against an optional payment-scheme rulebook.
Computes control sums grouped by currency.
Calculates unique debtor and creditor account counts.
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.
- 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:
Schema validation against the message type’s JSON Schema.
Optional scheme compliance verification (SEPA, BACS, etc.).
Multi-currency control sums and fee estimation.
Multi-factor risk scoring (detecting duplicates, high transaction amounts, and generic remittance narratives).
In-memory XML compilation and SHA-256 fingerprinting.
A confirmation token that commit_payment_batch requires.
- Parameters:
- Return type:
- 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.
- 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_schemeinstead of calling this per field.Returns
{"kind": str, "value": str, "valid": bool, "error": str}(theerrorkey is present only whenvalidisFalse).- Parameters:
- Return type:
- 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_recordsto enforce scheme-specific business rules (SEPA field lengths, allowed characters, currency/BIC constraints) that JSON-Schema validation alone does not cover.validate_recordschecks structural shape; this checks rulebook compliance for one profile.Delegates to
pain001.validate_scheme(). Theprofileparameter lists every profile the installed pain001 ships.- Parameters:
- Return type:
- Returns:
{"profile", "is_valid", "violations": [...]}with structuredviolations(each withrule,severity,field,message,remediationkeys), 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 andgenerate_messageaccept, and a batch it refuses is refused there too. The ladder checks the row contract (required fields, amounts, booleans, dates), every IBAN and BIC (unlessidentifier_checksis 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 runvalidate_payment_scheme.The row contract and identifier checks refuse the batch as a whole (
valid_count0) and name the first problems; the schema check then reports every row. Each error carriesrow(from 0),line(from 1),path(the field),code(the core’s stableP001-E...issue code) andmessage, 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:
- Return type:
- 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, useparse_camt053/parse_pain002.Wraps
pain001.xml.validate_via_xsd.validate_xml_string_via_xsd().
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.
- 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 usevalidate_records.- Parameters:
message_type (
str) – A supported ISO 20022 pain message type.- Return type:
- 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_schemainstead.
- 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) useget_input_schema.Mirrors the in-tree
pain001.mcp.server.inspect_templatetool so an agent can introspect the column layout before assembling rows.- Parameters:
message_type (
str) – A supported ISO 20022 pain message type.- Return type:
- 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_typestrings this server accepts. Returns message-type codes and display names only; useget_required_fieldsorget_input_schemato inspect fields or schemas.Returns a list of
{"message_type": ..., "name": ...}dictionaries, one per supported message type (e.g.pain.001.001.09).
- 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 calllist_message_typesinstead.Returns a list of
{"id", "name", "extension"}dictionaries covering CSV, SQLite, JSON, JSONL, and Parquet (the last requires thepain001[parquet]extra).
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_schemeand thengenerate_messageto 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:
- 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
.03rows to.09); it reports which fields were renamed, derived, or dropped. This transforms records only — runvalidate_recordsafterwards, thengenerate_messageto 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:
- Return type:
- 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 topain001.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:
- Return type:
- 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.
- 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_schemeinstead of calling this per field.Returns
{"kind": str, "value": str, "valid": bool, "error": str}(theerrorkey is present only whenvalidisFalse).- Parameters:
- Return type:
- 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 andgenerate_messageaccept, and a batch it refuses is refused there too. The ladder checks the row contract (required fields, amounts, booleans, dates), every IBAN and BIC (unlessidentifier_checksis 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 runvalidate_payment_scheme.The row contract and identifier checks refuse the batch as a whole (
valid_count0) and name the first problems; the schema check then reports every row. Each error carriesrow(from 0),line(from 1),path(the field),code(the core’s stableP001-E...issue code) andmessage, 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:
- Return type:
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_filewhen the data lives in a CSV on disk, andgenerate_message_asyncfor 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 asvalidate_recordsand the pain001 CLI validate them (row contract, every IBAN and BIC unlessidentifier_checksis 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’sline,column,P001-E...codeandmessage.
- 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_messagebut runs the synchronous renderer in a worker thread so an agent can interleave a long generation with other tool calls. Usegenerate_messagefor 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 asgenerate_message.
- 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 aspain001 generatereads it, so the same path-safety guards apply and the same files are refused; an issue’slineis the file’s line (a CSV header is line 1).
- 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, useparse_camt053/parse_pain002.Wraps
pain001.xml.validate_via_xsd.validate_xml_string_via_xsd().
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.CheckResult[source]¶
Bases:
TypedDictThe 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 checkdoes.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_recordschecks 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:
- Return type:
- 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_pathfrom the local filesystem. For the payment-status reply (accepted/rejected per transaction) useparse_pain002instead; to validate a camt.053 string you already hold, this is not it — this tool needs a file path.Wraps
pain001.parse_camt053_statement(). Whenxsd_file_pathis provided, the document is first validated against that XSD; on a schema or parse error the tool returns{"error": ...}rather than raising.- Parameters:
- Return type:
- 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_pathfrom the local filesystem. For the account statement that later confirms booked entries, useparse_camt053instead.Wraps
pain001.parse_pain002_report(). Whenxsd_file_pathis provided, the document is first validated against that XSD; on a schema or parse error the tool returns{"error": ...}rather than raising.- Parameters:
- Return type:
- 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
profileforvalidate_payment_scheme(or theschemeofsimulate_payment_batchandstage_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:
- 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:
Validates records against the message type’s JSON Schema.
Validates records against an optional payment-scheme rulebook.
Computes control sums grouped by currency.
Calculates unique debtor and creditor account counts.
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.
- 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_recordsto enforce scheme-specific business rules (SEPA field lengths, allowed characters, currency/BIC constraints) that JSON-Schema validation alone does not cover.validate_recordschecks structural shape; this checks rulebook compliance for one profile.Delegates to
pain001.validate_scheme(). Theprofileparameter lists every profile the installed pain001 ships.- Parameters:
- Return type:
- Returns:
{"profile", "is_valid", "violations": [...]}with structuredviolations(each withrule,severity,field,message,remediationkeys), 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:
- Returns:
The
coverage.jsoncontent (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:
- Return type:
- 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,derivedorassumed), 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:
- Return type:
- 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, andvariantidentifiers of the ready-made, validated ISO 20022 filespain001ships;get_corpus_fileandget_corpus_provenanceaccept those identifiers. Market files are realistic payments per country and rail (scenario_idlikegb.chaps.property-purchase); avariantnames 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:
- Returns:
[{“kind”, “scenario_id”, “version”, “country”, “family”, “variant”, “file”}, …]}``, or
{"error": ...}when the installed pain001 has no corpus.- Return type:
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:
TypedDictOne face: its name, its target and the binding keys it accepts.
- class pain001_mcp._faces.FaceListResult[source]¶
Bases:
TypedDictEvery 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:
TypedDictThe 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:
TypedDictSource leaves carried and not carried, by indexed path.
- pain001_mcp._faces.list_faces()[source]¶
List the faces: the standards a pain.001 document can be projected into.
Use this before
project_faceto 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 BankingConsentIdagreed with the bank; any key a face does not list is refused.Delegates to
pain001.faces.list_supported_faces().- Return type:
- 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, usevalidate_xml_against_schema.Delegates to
pain001.faces.project_face_text().- Parameters:
- Return type:
- 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
.xmlfile inside the output directory (see_output.py). The token guards against an accidental commit only.- Parameters:
- Return type:
- 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:
Schema validation against the message type’s JSON Schema.
Optional scheme compliance verification (SEPA, BACS, etc.).
Multi-currency control sums and fee estimation.
Multi-factor risk scoring (detecting duplicates, high transaction amounts, and generic remittance narratives).
In-memory XML compilation and SHA-256 fingerprinting.
A confirmation token that commit_payment_batch requires.
- Parameters:
- Return type:
- 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:
- Return type:
- 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:
TypedDictA parsed camt.053: the first statement’s fields, and every one.
- currency: NotRequired[str]¶
- electronic_sequence_number: NotRequired[str]¶
- error: NotRequired[str]¶
- iban: NotRequired[str]¶
- statement_id: NotRequired[str]¶
- class pain001_mcp._shapes.ClearingCheck[source]¶
Bases:
TypedDictAn individual rule check during clearing simulation.
- class pain001_mcp._shapes.CommitPaymentBatchResult[source]¶
Bases:
TypedDictConfirmation 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:
TypedDictSchema-path coverage of the corpus for one message edition.
- branches: NotRequired[CoverageCount]¶
- complete: NotRequired[bool]¶
- error: NotRequired[str]¶
- exempt: NotRequired[list[str]]¶
- 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:
TypedDictOne 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:
TypedDictOne 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:
TypedDictThe example corpus index.
- count: NotRequired[int]¶
- error: NotRequired[str]¶
- files: NotRequired[list[CorpusFileEntry]]¶
- class pain001_mcp._shapes.CorpusProvenanceResult[source]¶
Bases:
TypedDictA 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:
TypedDictDeclared schema elements, how many the corpus hits, as a percentage.
- class pain001_mcp._shapes.DuplicateTransaction[source]¶
Bases:
TypedDictAn intra-batch duplicate payment transaction.
- class pain001_mcp._shapes.ErrorResult[source]¶
Bases:
TypedDictThe failure payload every tool may return instead of its result.
- error: NotRequired[str]¶
- class pain001_mcp._shapes.MigrateResult¶
Bases:
TypedDictRecords rewritten from one message edition to another.
- error: NotRequired[str]¶
- from: NotRequired[str]¶
- migrated: NotRequired[int]¶
- to: NotRequired[str]¶
- class pain001_mcp._shapes.Pain002Result[source]¶
Bases:
TypedDictA 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]¶
- class pain001_mcp._shapes.RecordError[source]¶
Bases:
TypedDictOne finding: the record’s row and line, the field, the code, why.
rowcounts records from 0 andlinefrom 1, as the core’s issues do;codeis the core’s stableP001-E...issue code.
- class pain001_mcp._shapes.SanitiseResult[source]¶
Bases:
TypedDictA 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:
TypedDictA 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:
TypedDictOne scheme profile: its name, what it checks, and where from.
rule_prefixbegins every rule id a rail profile reports (UK-FPSforUK-FPS-AMT); it is null for the other profiles, whose rule ids the core does not group under one prefix.sourcesare the public documents a rail or purpose mandate was built from, empty otherwise.
- class pain001_mcp._shapes.SchemeProfilesResult[source]¶
Bases:
TypedDictEvery 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:
TypedDictVerdict 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:
TypedDictOne rulebook violation, with the remediation the library suggests.
- class pain001_mcp._shapes.SimulateClearingResult[source]¶
Bases:
TypedDictClearing 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:
TypedDictSimulation 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:
TypedDictResult 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:
TypedDictThe 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:
TypedDictAn 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:
TypedDictVerdict 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:
TypedDictVerdict 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
serverovertransport; returns when the server stops.
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,--hostand--porttoparser.- Return type:
- Parameters:
parser (ArgumentParser)