camt-exceptions 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,189 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work.
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean any work of authorship, including
48
+ the original version of the Work and any modifications or additions
49
+ to that Work or Derivative Works thereof, that is intentionally
50
+ submitted to the Licensor for inclusion in the Work by the copyright owner
51
+ or by an individual or Legal Entity authorized to submit on behalf of
52
+ the copyright owner. For the purposes of this definition, "submitted"
53
+ means any form of electronic, verbal, or written communication sent
54
+ to the Licensor or its representatives, including but not limited to
55
+ communication on electronic mailing lists, source code control systems,
56
+ and issue tracking systems that are managed by, or on behalf of, the
57
+ Licensor for the purpose of discussing and improving the Work, but
58
+ excluding communication that is conspicuously marked or otherwise
59
+ designated in writing by the copyright owner as "Not a Contribution."
60
+
61
+ "Contributor" shall mean Licensor and any individual or Legal Entity
62
+ on behalf of whom a Contribution has been received by the Licensor and
63
+ subsequently incorporated within the Work.
64
+
65
+ 2. Grant of Copyright License. Subject to the terms and conditions of
66
+ this License, each Contributor hereby grants to You a perpetual,
67
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
68
+ copyright license to reproduce, prepare Derivative Works of,
69
+ publicly display, publicly perform, sublicense, and distribute the
70
+ Work and such Derivative Works in Source or Object form.
71
+
72
+ 3. Grant of Patent License. Subject to the terms and conditions of
73
+ this License, each Contributor hereby grants to You a perpetual,
74
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
75
+ (except as stated in this section) patent license to make, have made,
76
+ use, offer to sell, sell, import, and otherwise transfer the Work,
77
+ where such license applies only to those patent claims licensable
78
+ by such Contributor that are necessarily infringed by their
79
+ Contribution(s) alone or by combination of their Contribution(s)
80
+ with the Work to which such Contribution(s) was submitted. If You
81
+ institute patent litigation against any entity (including a
82
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
83
+ or a Contribution incorporated within the Work constitutes direct
84
+ or contributory patent infringement, then any patent licenses
85
+ granted to You under this License for that Work shall terminate
86
+ as of the date such litigation is filed.
87
+
88
+ 4. Redistribution. You may reproduce and distribute copies of the
89
+ Work or Derivative Works thereof in any medium, with or without
90
+ modifications, and in Source or Object form, provided that You
91
+ meet the following conditions:
92
+
93
+ (a) You must give any other recipients of the Work or
94
+ Derivative Works a copy of this License; and
95
+
96
+ (b) You must cause any modified files to carry prominent notices
97
+ stating that You changed the files; and
98
+
99
+ (c) You must retain, in the Source form of any Derivative Works
100
+ that You distribute, all copyright, patent, trademark, and
101
+ attribution notices from the Source form of the Work,
102
+ excluding those notices that do not pertain to any part of
103
+ the Derivative Works; and
104
+
105
+ (d) If the Work includes a "NOTICE" text file as part of its
106
+ distribution, then any Derivative Works that You distribute must
107
+ include a readable copy of the attribution notices contained
108
+ within such NOTICE file, excluding any notices that do not
109
+ pertain to any part of the Derivative Works, in at least one
110
+ of the following places: within a NOTICE text file distributed
111
+ as part of the Derivative Works; within the Source form or
112
+ documentation, if provided along with the Derivative Works; or,
113
+ within a display generated by the Derivative Works, if and
114
+ wherever such third-party notices normally appear. The contents
115
+ of the NOTICE file are for informational purposes only and
116
+ do not modify the License. You may add Your own attribution
117
+ notices within Derivative Works that You distribute, alongside
118
+ or as an addendum to the NOTICE text from the Work, provided
119
+ that such additional attribution notices cannot be construed
120
+ as modifying the License.
121
+
122
+ You may add Your own copyright statement to Your modifications and
123
+ may provide additional or different license terms and conditions
124
+ for use, reproduction, or distribution of Your modifications, or
125
+ for any such Derivative Works as a whole, provided Your use,
126
+ reproduction, and distribution of the Work otherwise complies with
127
+ the conditions stated in this License.
128
+
129
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
130
+ any Contribution intentionally submitted for inclusion in the Work
131
+ by You to the Licensor shall be under the terms and conditions of
132
+ this License, without any additional terms or conditions.
133
+ Notwithstanding the above, nothing herein shall supersede or modify
134
+ the terms of any separate license agreement you may have executed
135
+ with Licensor regarding such Contributions.
136
+
137
+ 6. Trademarks. This License does not grant permission to use the trade
138
+ names, trademarks, service marks, or product names of the Licensor,
139
+ except as required for reasonable and customary use in describing the
140
+ origin of the Work and reproducing the content of the NOTICE file.
141
+
142
+ 7. Disclaimer of Warranty. Unless required by applicable law or
143
+ agreed to in writing, Licensor provides the Work (and each
144
+ Contributor provides its Contributions) on an "AS IS" BASIS,
145
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
146
+ implied, including, without limitation, any warranties or conditions
147
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
148
+ PARTICULAR PURPOSE. You are solely responsible for determining the
149
+ appropriateness of using or redistributing the Work and assume any
150
+ risks associated with Your exercise of permissions under this License.
151
+
152
+ 8. Limitation of Liability. In no event and under no legal theory,
153
+ whether in tort (including negligence), contract, or otherwise,
154
+ unless required by applicable law (such as deliberate and grossly
155
+ negligent acts) or agreed to in writing, shall any Contributor be
156
+ liable to You for damages, including any direct, indirect, special,
157
+ incidental, or consequential damages of any character arising as a
158
+ result of this License or out of the use or inability to use the
159
+ Work (including but not limited to damages for loss of goodwill,
160
+ work stoppage, computer failure or malfunction, or any and all
161
+ other commercial damages or losses), even if such Contributor
162
+ has been advised of the possibility of such damages.
163
+
164
+ 9. Accepting Warranty or Additional Liability. While redistributing
165
+ the Work or Derivative Works thereof, You may choose to offer,
166
+ and charge a fee for, acceptance of support, warranty, indemnity,
167
+ or other liability obligations and/or rights consistent with this
168
+ License. However, in accepting such obligations, You may act only
169
+ on Your own behalf and on Your sole responsibility, not on behalf
170
+ of any other Contributor, and only if You agree to indemnify,
171
+ defend, and hold each Contributor harmless for any liability
172
+ incurred by, or claims asserted against, such Contributor by reason
173
+ of your accepting any such warranty or additional liability.
174
+
175
+ END OF TERMS AND CONDITIONS
176
+
177
+ Copyright 2023-2026 Sebastien Rousseau
178
+
179
+ Licensed under the Apache License, Version 2.0 (the "License");
180
+ you may not use this file except in compliance with the License.
181
+ You may obtain a copy of the License at
182
+
183
+ http://www.apache.org/licenses/LICENSE-2.0
184
+
185
+ Unless required by applicable law or agreed to in writing, software
186
+ distributed under the License is distributed on an "AS IS" BASIS,
187
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
188
+ See the License for the specific language governing permissions and
189
+ limitations under the License.
@@ -0,0 +1,154 @@
1
+ Metadata-Version: 2.4
2
+ Name: camt-exceptions
3
+ Version: 0.0.1
4
+ Summary: Generate and validate ISO 20022 Exceptions & Investigations (E&I) camt messages -- starting with camt.056 FI-to-FI Payment Cancellation Request -- with an MCP server.
5
+ License: Apache-2.0
6
+ License-File: LICENSE
7
+ Keywords: iso-20022,camt056,exceptions,investigations,payment-cancellation,mcp,payments,fintech
8
+ Author: Sebastien Rousseau
9
+ Author-email: sebastian.rousseau@gmail.com
10
+ Requires-Python: >=3.10,<4.0
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Requires-Dist: jinja2 (>=3.0)
19
+ Requires-Dist: mcp (>=1.2)
20
+ Requires-Dist: xmlschema (>=2.0)
21
+ Project-URL: Homepage, https://camt-exceptions.com
22
+ Project-URL: Repository, https://github.com/sebastienrousseau/camt-exceptions
23
+ Description-Content-Type: text/markdown
24
+
25
+ # camt-exceptions: ISO 20022 Exceptions & Investigations, generated + XSD-valid
26
+
27
+ **Generate and validate ISO 20022 Exceptions & Investigations (E&I) `camt`
28
+ messages — with an [MCP][mcp] server.** Starts with **`camt.056`** (FI-to-FI
29
+ Payment Cancellation Request): the message a bank sends to *recall or cancel* a
30
+ payment it already dispatched — a duplicate, an erroneous amount, a fraud
31
+ recall. Output is validated against the **official bundled XSD** before it's
32
+ returned.
33
+
34
+ > **Latest release: v0.0.1** — `camt.056.001.12` generation + validation, 4 MCP
35
+ > tools over stdio, 100% branch coverage, for Python 3.10+. Part of the
36
+ > [ISO 20022 MCP suite](#the-suite). Additional E&I messages (camt.029, camt.026,
37
+ > camt.027, camt.087) plug into the same engine.
38
+
39
+ ## Why E&I
40
+
41
+ When a payment goes wrong, the fix is an Exceptions & Investigations message —
42
+ and these are the *least* tooled corner of ISO 20022. `camt.056` alone covers
43
+ the single most common need: **"I need to cancel/recall that payment."** This
44
+ library makes it a one-call, schema-valid operation for an agent, with the same
45
+ depth as the credit-transfer generators elsewhere in the suite.
46
+
47
+ ## Install
48
+
49
+ ```sh
50
+ pip install camt-exceptions
51
+ # or run the MCP server without installing:
52
+ uvx camt-exceptions
53
+ ```
54
+
55
+ MCP client config (e.g. Claude Desktop):
56
+
57
+ ```json
58
+ {
59
+ "mcpServers": {
60
+ "camt-exceptions": {
61
+ "command": "camt-exceptions-mcp"
62
+ }
63
+ }
64
+ }
65
+ ```
66
+
67
+ ## Quick start — cancel a payment
68
+
69
+ ```python
70
+ from camt_exceptions import generator as g
71
+
72
+ xml = g.generate_message("camt.056.001.12", {
73
+ "assignment_id": "CXL-001",
74
+ "assigner_agent_bic": "DEUTDEFF",
75
+ "assignee_agent_bic": "COBADEFF",
76
+ "creation_date_time": "2026-03-02T10:00:00",
77
+ "original_msg_id": "MSG-ORIG-001",
78
+ "original_msg_nm_id": "pacs.008.001.08",
79
+ "transactions": [{
80
+ "original_end_to_end_id": "E2E-001",
81
+ "original_interbank_settlement_amount": "1000.00",
82
+ "original_interbank_settlement_currency": "EUR",
83
+ "cancellation_reason_cd": "DUPL", # duplicate payment
84
+ }],
85
+ })
86
+ assert g.validate_xml("camt.056.001.12", xml)["is_valid"] # True
87
+ ```
88
+
89
+ ## Tools
90
+
91
+ | Tool | What it does |
92
+ | --- | --- |
93
+ | `list_message_types` | List supported E&I message types and names. |
94
+ | `get_required_fields` | Required top-level fields for a message type. |
95
+ | `generate_message` | Generate a validated E&I XML message from a record (validated against the bundled XSD before return). |
96
+ | `validate_xml` | Validate raw XML against a message type's bundled XSD. |
97
+
98
+ ## Supported messages
99
+
100
+ | Message | Name | Status |
101
+ | --- | --- | --- |
102
+ | `camt.056.001.12` | FI to FI Payment Cancellation Request | ✅ |
103
+ | `camt.029` | Resolution of Investigation | planned |
104
+ | `camt.026` | Unable to Apply | planned |
105
+ | `camt.027` | Claim Non-Receipt | planned |
106
+ | `camt.087` | Request to Modify Payment | planned |
107
+
108
+ Each new message plugs into the same engine: bundle its official XSD +
109
+ `template.xml` and register it in `MESSAGE_TYPES`. Generated output is always
110
+ XSD-validated before return, so correctness is machine-checked, not asserted.
111
+
112
+ > Note: the payment-status and return messages of the E&I family —
113
+ > **`pacs.002`** (Payment Status Report) and **`pacs.004`** (Payment Return) —
114
+ > are already generated, XSD-valid, by [`pacs008-mcp`][pacs008-mcp].
115
+
116
+ ## The suite
117
+
118
+ Part of a family of vendor-neutral, Python-native ISO 20022 MCP servers:
119
+
120
+ - [`iso20022-mcp`][iso20022-mcp] — unified gateway across the families.
121
+ - [`pain001-mcp`][pain001-mcp] · [`pacs008-mcp`][pacs008-mcp] ·
122
+ [`camt053-mcp`][camt053-mcp] · [`acmt001-mcp`][acmt001-mcp] — per-family servers.
123
+ - [`reconcile-mcp`][reconcile-mcp] — statement/payment reconciliation.
124
+
125
+ ## Development
126
+
127
+ ```sh
128
+ git clone https://github.com/sebastienrousseau/camt-exceptions
129
+ cd camt-exceptions
130
+ python -m venv .venv && . .venv/bin/activate
131
+ pip install -e . && pip install pytest pytest-cov ruff black mypy
132
+ pytest # 100% branch coverage gate; output is XSD-validated
133
+ ruff check camt_exceptions tests && black --check camt_exceptions tests && mypy camt_exceptions
134
+ ```
135
+
136
+ ## Licence
137
+
138
+ Code licensed under the [Apache License, Version 2.0](LICENSE). Bundled ISO
139
+ 20022 message schemas (`*.xsd`) are © ISO 20022 and redistributed under the
140
+ ISO 20022 terms; they are the same schemas published at
141
+ [iso20022.org](https://www.iso20022.org).
142
+
143
+ ---
144
+
145
+ `mcp-name: io.github.sebastienrousseau/camt-exceptions`
146
+
147
+ [mcp]: https://modelcontextprotocol.io
148
+ [iso20022-mcp]: https://github.com/sebastienrousseau/iso20022-mcp
149
+ [pain001-mcp]: https://github.com/sebastienrousseau/pain001-mcp
150
+ [pacs008-mcp]: https://github.com/sebastienrousseau/pacs008-mcp
151
+ [camt053-mcp]: https://github.com/sebastienrousseau/camt053-mcp
152
+ [acmt001-mcp]: https://github.com/sebastienrousseau/acmt001-mcp
153
+ [reconcile-mcp]: https://github.com/sebastienrousseau/reconcile-mcp
154
+
@@ -0,0 +1,129 @@
1
+ # camt-exceptions: ISO 20022 Exceptions & Investigations, generated + XSD-valid
2
+
3
+ **Generate and validate ISO 20022 Exceptions & Investigations (E&I) `camt`
4
+ messages — with an [MCP][mcp] server.** Starts with **`camt.056`** (FI-to-FI
5
+ Payment Cancellation Request): the message a bank sends to *recall or cancel* a
6
+ payment it already dispatched — a duplicate, an erroneous amount, a fraud
7
+ recall. Output is validated against the **official bundled XSD** before it's
8
+ returned.
9
+
10
+ > **Latest release: v0.0.1** — `camt.056.001.12` generation + validation, 4 MCP
11
+ > tools over stdio, 100% branch coverage, for Python 3.10+. Part of the
12
+ > [ISO 20022 MCP suite](#the-suite). Additional E&I messages (camt.029, camt.026,
13
+ > camt.027, camt.087) plug into the same engine.
14
+
15
+ ## Why E&I
16
+
17
+ When a payment goes wrong, the fix is an Exceptions & Investigations message —
18
+ and these are the *least* tooled corner of ISO 20022. `camt.056` alone covers
19
+ the single most common need: **"I need to cancel/recall that payment."** This
20
+ library makes it a one-call, schema-valid operation for an agent, with the same
21
+ depth as the credit-transfer generators elsewhere in the suite.
22
+
23
+ ## Install
24
+
25
+ ```sh
26
+ pip install camt-exceptions
27
+ # or run the MCP server without installing:
28
+ uvx camt-exceptions
29
+ ```
30
+
31
+ MCP client config (e.g. Claude Desktop):
32
+
33
+ ```json
34
+ {
35
+ "mcpServers": {
36
+ "camt-exceptions": {
37
+ "command": "camt-exceptions-mcp"
38
+ }
39
+ }
40
+ }
41
+ ```
42
+
43
+ ## Quick start — cancel a payment
44
+
45
+ ```python
46
+ from camt_exceptions import generator as g
47
+
48
+ xml = g.generate_message("camt.056.001.12", {
49
+ "assignment_id": "CXL-001",
50
+ "assigner_agent_bic": "DEUTDEFF",
51
+ "assignee_agent_bic": "COBADEFF",
52
+ "creation_date_time": "2026-03-02T10:00:00",
53
+ "original_msg_id": "MSG-ORIG-001",
54
+ "original_msg_nm_id": "pacs.008.001.08",
55
+ "transactions": [{
56
+ "original_end_to_end_id": "E2E-001",
57
+ "original_interbank_settlement_amount": "1000.00",
58
+ "original_interbank_settlement_currency": "EUR",
59
+ "cancellation_reason_cd": "DUPL", # duplicate payment
60
+ }],
61
+ })
62
+ assert g.validate_xml("camt.056.001.12", xml)["is_valid"] # True
63
+ ```
64
+
65
+ ## Tools
66
+
67
+ | Tool | What it does |
68
+ | --- | --- |
69
+ | `list_message_types` | List supported E&I message types and names. |
70
+ | `get_required_fields` | Required top-level fields for a message type. |
71
+ | `generate_message` | Generate a validated E&I XML message from a record (validated against the bundled XSD before return). |
72
+ | `validate_xml` | Validate raw XML against a message type's bundled XSD. |
73
+
74
+ ## Supported messages
75
+
76
+ | Message | Name | Status |
77
+ | --- | --- | --- |
78
+ | `camt.056.001.12` | FI to FI Payment Cancellation Request | ✅ |
79
+ | `camt.029` | Resolution of Investigation | planned |
80
+ | `camt.026` | Unable to Apply | planned |
81
+ | `camt.027` | Claim Non-Receipt | planned |
82
+ | `camt.087` | Request to Modify Payment | planned |
83
+
84
+ Each new message plugs into the same engine: bundle its official XSD +
85
+ `template.xml` and register it in `MESSAGE_TYPES`. Generated output is always
86
+ XSD-validated before return, so correctness is machine-checked, not asserted.
87
+
88
+ > Note: the payment-status and return messages of the E&I family —
89
+ > **`pacs.002`** (Payment Status Report) and **`pacs.004`** (Payment Return) —
90
+ > are already generated, XSD-valid, by [`pacs008-mcp`][pacs008-mcp].
91
+
92
+ ## The suite
93
+
94
+ Part of a family of vendor-neutral, Python-native ISO 20022 MCP servers:
95
+
96
+ - [`iso20022-mcp`][iso20022-mcp] — unified gateway across the families.
97
+ - [`pain001-mcp`][pain001-mcp] · [`pacs008-mcp`][pacs008-mcp] ·
98
+ [`camt053-mcp`][camt053-mcp] · [`acmt001-mcp`][acmt001-mcp] — per-family servers.
99
+ - [`reconcile-mcp`][reconcile-mcp] — statement/payment reconciliation.
100
+
101
+ ## Development
102
+
103
+ ```sh
104
+ git clone https://github.com/sebastienrousseau/camt-exceptions
105
+ cd camt-exceptions
106
+ python -m venv .venv && . .venv/bin/activate
107
+ pip install -e . && pip install pytest pytest-cov ruff black mypy
108
+ pytest # 100% branch coverage gate; output is XSD-validated
109
+ ruff check camt_exceptions tests && black --check camt_exceptions tests && mypy camt_exceptions
110
+ ```
111
+
112
+ ## Licence
113
+
114
+ Code licensed under the [Apache License, Version 2.0](LICENSE). Bundled ISO
115
+ 20022 message schemas (`*.xsd`) are © ISO 20022 and redistributed under the
116
+ ISO 20022 terms; they are the same schemas published at
117
+ [iso20022.org](https://www.iso20022.org).
118
+
119
+ ---
120
+
121
+ `mcp-name: io.github.sebastienrousseau/camt-exceptions`
122
+
123
+ [mcp]: https://modelcontextprotocol.io
124
+ [iso20022-mcp]: https://github.com/sebastienrousseau/iso20022-mcp
125
+ [pain001-mcp]: https://github.com/sebastienrousseau/pain001-mcp
126
+ [pacs008-mcp]: https://github.com/sebastienrousseau/pacs008-mcp
127
+ [camt053-mcp]: https://github.com/sebastienrousseau/camt053-mcp
128
+ [acmt001-mcp]: https://github.com/sebastienrousseau/acmt001-mcp
129
+ [reconcile-mcp]: https://github.com/sebastienrousseau/reconcile-mcp
@@ -0,0 +1,18 @@
1
+ # Copyright (C) 2023-2026 Sebastien Rousseau.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12
+ # implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """camt-exceptions: ISO 20022 Exceptions & Investigations message generation."""
17
+
18
+ __version__ = "0.0.1"
@@ -0,0 +1,171 @@
1
+ # Copyright (C) 2023-2026 Sebastien Rousseau.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12
+ # implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """Generate and validate ISO 20022 Exceptions & Investigations (E&I) messages.
17
+
18
+ This is the ``camt`` counterpart to the generation engines elsewhere in the
19
+ suite: each supported message type bundles its official XSD plus a Jinja2
20
+ ``template.xml``; :func:`generate_message` renders a record into XML and
21
+ :func:`validate_xml` checks any XML against the bundled schema.
22
+
23
+ Currently supported:
24
+
25
+ * ``camt.056.001.12`` -- FI to FI Payment Cancellation Request (recall or
26
+ cancel a previously sent payment, e.g. a duplicate or erroneous transfer).
27
+
28
+ Additional E&I messages (camt.029 resolution of investigation, camt.026 unable
29
+ to apply, camt.027 claim non-receipt, camt.087 request to modify) plug in by
30
+ dropping their XSD + ``template.xml`` alongside and registering them in
31
+ :data:`MESSAGE_TYPES`.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import functools
37
+ from importlib.resources import files
38
+ from typing import Any
39
+
40
+ import jinja2
41
+ import xmlschema
42
+
43
+
44
+ class MessageSpec:
45
+ """Static description of one supported E&I message type."""
46
+
47
+ def __init__(
48
+ self,
49
+ message_type: str,
50
+ name: str,
51
+ required: tuple[str, ...],
52
+ ) -> None:
53
+ self.message_type = message_type
54
+ self.name = name
55
+ self.required = required
56
+
57
+
58
+ # Registry of supported message types. Adding a message = bundle its
59
+ # templates/<mt>/<mt>.xsd + template.xml and add a MessageSpec here.
60
+ MESSAGE_TYPES: dict[str, MessageSpec] = {
61
+ "camt.056.001.12": MessageSpec(
62
+ message_type="camt.056.001.12",
63
+ name="FI to FI Payment Cancellation Request",
64
+ required=(
65
+ "assignment_id",
66
+ "assigner_agent_bic",
67
+ "assignee_agent_bic",
68
+ "creation_date_time",
69
+ ),
70
+ ),
71
+ }
72
+
73
+
74
+ def list_message_types() -> list[dict[str, str]]:
75
+ """Return every supported E&I message type and its human name."""
76
+ return [
77
+ {"message_type": s.message_type, "name": s.name}
78
+ for s in MESSAGE_TYPES.values()
79
+ ]
80
+
81
+
82
+ def _spec(message_type: str) -> MessageSpec:
83
+ """Return the spec for a message type or raise a helpful ValueError."""
84
+ spec = MESSAGE_TYPES.get(message_type)
85
+ if spec is None:
86
+ known = ", ".join(sorted(MESSAGE_TYPES))
87
+ raise ValueError(
88
+ f"unsupported message type {message_type!r}; supported: {known}"
89
+ )
90
+ return spec
91
+
92
+
93
+ def get_required_fields(message_type: str) -> list[str]:
94
+ """Return the required top-level fields for a message type."""
95
+ return list(_spec(message_type).required)
96
+
97
+
98
+ def _template_text(message_type: str) -> str:
99
+ """Read the bundled Jinja template for a message type."""
100
+ base = files("camt_exceptions") / "templates" / message_type
101
+ return (base / "template.xml").read_text(encoding="utf-8")
102
+
103
+
104
+ @functools.cache
105
+ def _schema(message_type: str) -> xmlschema.XMLSchema:
106
+ """Load (and cache) the bundled XSD for a message type."""
107
+ base = files("camt_exceptions") / "templates" / message_type
108
+ xsd = base / f"{message_type}.xsd"
109
+ return xmlschema.XMLSchema(str(xsd))
110
+
111
+
112
+ @functools.cache
113
+ def _template(message_type: str) -> jinja2.Template:
114
+ """Compile (and cache) the Jinja template for a message type."""
115
+ env = jinja2.Environment(
116
+ trim_blocks=True,
117
+ lstrip_blocks=True,
118
+ keep_trailing_newline=True,
119
+ autoescape=True,
120
+ )
121
+ return env.from_string(_template_text(message_type))
122
+
123
+
124
+ def generate_message(message_type: str, record: dict[str, Any]) -> str:
125
+ """Render a validated E&I message to XML.
126
+
127
+ Args:
128
+ message_type: e.g. ``"camt.056.001.12"``.
129
+ record: the message fields (see :func:`get_required_fields` for the
130
+ required keys; ``transactions`` is a list of per-transaction dicts).
131
+
132
+ Returns:
133
+ The rendered ISO 20022 XML as a string.
134
+
135
+ Raises:
136
+ ValueError: unknown message type, a missing required field, or output
137
+ that fails XSD validation.
138
+ """
139
+ spec = _spec(message_type)
140
+ missing = [f for f in spec.required if not record.get(f)]
141
+ if missing:
142
+ raise ValueError(
143
+ f"{message_type} is missing required field(s): "
144
+ f"{', '.join(missing)}"
145
+ )
146
+ xml = _template(message_type).render(**record)
147
+ errors = list(_schema(message_type).iter_errors(xml))
148
+ if errors:
149
+ first = str(errors[0]).splitlines()[0]
150
+ raise ValueError(
151
+ f"generated {message_type} failed XSD validation: {first}"
152
+ )
153
+ return xml
154
+
155
+
156
+ def validate_xml(message_type: str, xml: str) -> dict[str, Any]:
157
+ """Validate raw XML against a message type's bundled XSD.
158
+
159
+ Returns:
160
+ ``{"message_type": ..., "is_valid": bool, "errors": [...]}`` -- never
161
+ raises on a validation failure (only on an unknown message type).
162
+ """
163
+ _spec(message_type)
164
+ errors = [
165
+ str(e).splitlines()[0] for e in _schema(message_type).iter_errors(xml)
166
+ ]
167
+ return {
168
+ "message_type": message_type,
169
+ "is_valid": not errors,
170
+ "errors": errors,
171
+ }