diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 90e2c85..7d2e9a7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -104,13 +104,13 @@ The host serves one MCP server at `/mcp` (Streamable HTTP, stateless, [ADR 0021] - **Adding tools:** a context's `.Mcp` adapter (its folder of `RimBank.Mcp`, [ADR 0025](docs/adr/0025-one-api-project.md)) exposes one `IMcpServerBuilder` extension, for example `AddPartyReferenceDataDirectoryTools()`, which calls `WithTools<…>()`. The context's module calls only that extension in `AddMcpTools`. Never call `AddMcpServer`, `WithHttpTransport` or `MapMcp` from a context. A tool name registered twice stops the host. - **Names:** one tool per BIAN operation, `_[_]` in snake_case, set explicitly with `[McpServerTool(Name = …)]`. The description is the BIAN operation's description. - **Authorisation:** every context tool carries `[ToolOperation(OperationId)]` from `RimBank.Mcp`, with the same BIAN operation id as its endpoint's `RequireOperation`, so it needs the same policy and scope ([ADR 0038](docs/adr/0038-per-operation-authorisation-policies.md), [ADR 0039](docs/adr/0039-party-mcp-tools.md)). A caller without the scope does not see the tool in `tools/list`, and a call gets `isError` with the `shared.forbidden` (403) Problem Details. Do not use `[Authorize]` on tools: the SDK would refuse the call with a JSON-RPC error instead. -- **Arguments and results:** arguments are the tool method's camelCase parameters. A command tool takes a required `idempotencyKey` and builds the same core command as its endpoint. A tool's result is its own record in its `.Mcp` folder that mirrors the endpoint's response (same BIAN property names) plus `version`, the entry's stream version that HTTP sends as `ETag`. Answer with `ToolResults.Structured(...)`. `.Mcp` never references `.Api`, so a parity test in `RimBank.Mcp.Tests` proves both channels give the same JSON and the same Problem Details. +- **Arguments and results:** arguments are the tool method's camelCase parameters. Ids are named after the BIAN path parameter (`partyReferenceDataDirectoryEntryId`, `referenceId`, …). A command tool takes a required `idempotencyKey`, a required `expectedVersion` when it changes a record (the `version` of the last Retrieve or command, HTTP's `If-Match`), and its BIAN request body as one `request` object that mirrors the endpoint's request record, so the partial-update and refusal rules are the same ([ADR 0040](docs/adr/0040-party-mcp-command-tools.md)). It builds the same core command as its endpoint. A tool's result is its own record in its `.Mcp` folder that mirrors the endpoint's response (same BIAN property names) plus `version`, the entry's stream version that HTTP sends as `ETag`. Answer with `ToolResults.Structured(...)`. `.Mcp` never references `.Api`, so a parity test in `RimBank.Mcp.Tests` proves both channels give the same JSON and the same Problem Details. - **Annotations:** set `ReadOnly`, `Destructive`, `Idempotent` and `OpenWorld` on every tool, following the table in ADR 0021. `Retrieve` tools are read-only queries. Every other tool is a command with an idempotency key. - **Errors:** a tool dispatches through `IMessageBus` and answers with `result.ToToolResult(...)` from `RimBank.Mcp`. A failed `Result` becomes `isError` with the same Problem Details as HTTP. Never throw for a business failure. The host's tool error filter adds `instance` and `traceId`, turns arguments the SDK cannot bind into `shared.tool-arguments-invalid` (400), and turns any exception into `shared.unexpected` (500) with no exception text. - **Caller:** a tool call carries the token's subject to the message bus like an HTTP call. Do not read the token in a tool. - **Connecting a local client:** start the AppHost, then point MCP Inspector (`npx @modelcontextprotocol/inspector`) or Claude Code at the host's `/mcp` URL from the Aspire dashboard. Use client ID `rimbank-mcp-client` (public, PKCE, loopback redirects `http://127.0.0.1:` and `http://localhost:6274`). Sign in as `rimbank-developer` / `rimbank-developer-local-only`. Both are dev-only and published on purpose. -- **Calling the Party tools:** once signed in, call `party_reference_data_directory_register` with `{ "partyType": "Person", "idempotencyKey": "demo-1" }`, then `party_reference_data_directory_retrieve` with the returned `PartyReferenceDataDirectoryEntryId` as `partyReferenceDataDirectoryEntryId`. An unknown id answers `isError` with the 404 Problem Details. -- **Tests** connect the SDK's `McpClient` in-process over `HttpClientTransport`, using the test server's `HttpClient` with a `TestTokens` bearer token (`McpTestHost` in `tests/RimBank.Host.Tests/Mcp`). A context's tools are tested in `tests/RimBank.Mcp.Tests///` against the real host and PostgreSQL (`PartyMcpHost`), including a tool-catalog test (each implemented operation has its tool, named after it, with its policy and annotations) and HTTP parity tests. +- **Calling the Party tools:** once signed in, call `party_reference_data_directory_register` with `{ "partyType": "Person", "idempotencyKey": "demo-1" }`, then `party_reference_data_directory_retrieve` with the returned `PartyReferenceDataDirectoryEntryId` as `partyReferenceDataDirectoryEntryId`. An unknown id answers `isError` with the 404 Problem Details. To change the entry, call for example `party_reference_data_directory_update_reference` with the entry id, the `ReferenceId`, `"request": { "ResidentialAddress": { "TownName": "Paris", "Country": { "Code": "FR" } } }`, the `version` you last read as `expectedVersion` and a new `idempotencyKey`. The answer carries the new `version`, and sending the old one again is `isError` with the 409 `party.version-conflict` Problem Details. +- **Tests** connect the SDK's `McpClient` in-process over `HttpClientTransport`, using the test server's `HttpClient` with a `TestTokens` bearer token (`McpTestHost` in `tests/RimBank.Host.Tests/Mcp`). A context's tools are tested in `tests/RimBank.Mcp.Tests///` against the real host and PostgreSQL (`PartyMcpHost`), including a tool-catalog test (the tools are exactly the implemented operations, each named after it, with its policy, annotations and the arguments of its kind) and HTTP parity tests for every tool. ### Errors diff --git a/docs/adr/0039-party-mcp-tools.md b/docs/adr/0039-party-mcp-tools.md index ebc4857..dc4636b 100644 --- a/docs/adr/0039-party-mcp-tools.md +++ b/docs/adr/0039-party-mcp-tools.md @@ -63,7 +63,7 @@ Mission principle 6 says an AI agent reaches every service domain through MCP to - If a later SDK lets a filter see its authorization denial, or answers it as a tool error, this decision can be revisited. The attribute would then become `[Authorize]`, and the tests stay. - RimBank's tool list filter replaces the SDK's for these tools. Resources and prompts are not used. - Follow-ups: - - **1.17:** Update and BQ tools with `expectedVersion`, and an empty catalog list. + - **1.17:** Update and BQ tools with `expectedVersion`, and an empty catalog list. Done: a command's body is one `request` argument, and Update and Exchange tools require `expectedVersion` ([ADR 0040](0040-party-mcp-command-tools.md)). - **4.14:** money-moving tools behind their own scope, off by default. - **7.9:** rate limiting and the tool-call audit query. - Proven by: diff --git a/docs/adr/0040-party-mcp-command-tools.md b/docs/adr/0040-party-mcp-command-tools.md new file mode 100644 index 0000000..8d4bd9c --- /dev/null +++ b/docs/adr/0040-party-mcp-command-tools.md @@ -0,0 +1,77 @@ +# 0040. Party MCP command tools: a BIAN body object and expected versions + +- Status: Accepted +- Date: 2026-11-09 +- Roadmap phase: 1.17 + +## Context + +Roadmap 1.17 adds an MCP tool for each Party Reference Data Directory operation that 1.16 left out: +- the Control Record's Update; +- Demographics Update, Exchange and Retrieve; +- Reference Update and Retrieve; +- Associations Register, Update and Retrieve; +- BankRelations Update and Retrieve. + +[ADR 0024](0024-party-reference-data-directory-mapping.md) maps these operations. [ADR 0039](0039-party-mcp-tools.md) fixed the conventions of the first two tools. Their results mirror the HTTP responses plus `version`, a command takes an `idempotencyKey`, and `[ToolOperation]` carries the policy. ADR 0039 also chose flat camelCase parameters for arguments, so that agents do not nest them. + +That choice works for Register, whose body has one field. It does not fit the bodies of 1.17: +- **Size.** The Reference body has about 25 BIAN fields ([ADR 0029](0029-reference-fields-in-stages.md), [ADR 0032](0032-reference-legal-standing-and-documents.md), [ADR 0034](0034-reference-corporate-and-officer-references.md)). Several of them are objects: three ISO 20022 postal addresses, a government document with a validity period, and the corporate and officer references. +- **Partial updates.** The Update operations are partial updates with three states per field: left out keeps the value, empty clears it, and a value sets it. An object such as an address replaces the whole of it. +- **Refusals.** BIAN parts RimBank does not record are refused by path, for example `party.reference-field-not-supported`, through `[JsonExtensionData]` on each model. + +The Update and Exchange tools also need MCP's form of HTTP's `If-Match` ([ADR 0027](0027-optimistic-concurrency-for-commands.md)), which ADR 0039 left to this phase. + +## Options considered + +**Arguments of a command with a body** +1. **Flat parameters**, one per BIAN field, with objects flattened (for example `residentialAddressTownName`). The schema is simplest, but Reference would take more than 60 parameters. Their names would no longer be BIAN's. The "left out, empty or set" rules and the refusal by BIAN path would have to be written again for MCP, outside the core inputs that HTTP shares. +2. **One parameter per top-level BIAN field, with BIAN objects as nested records.** This is ADR 0039's style at the top level, with BIAN names below it. It is still about 25 parameters with mixed naming, and the refusal of unknown top-level fields has no `[JsonExtensionData]` to hang on. +3. **One `request` object shaped like the BIAN request body**, next to the flat ids, `expectedVersion` and `idempotencyKey`. The JSON is the HTTP body, so the same mirror model, the same core input and the same refusals apply, and the parity tests compare like with like. Agents nest the body once, under a name that points to the BIAN schema. + +**Expected version** +1. **Optional**, with the current version used when it is left out. This drops the lost-update protection that ADR 0027 requires of every command that changes a record. +2. **Required `long` parameter `expectedVersion`.** It is MCP's `If-Match`, taken from a Retrieve's or a previous command's `version`. + +## Decision + +**Option 3 for arguments, and a required `expectedVersion`.** + +- **Shape.** A command tool whose operation has a BIAN request body takes it as one required `request` argument. `request` has the body's BIAN property names and mirrors the `.Api` request record in its own `.Mcp` folder, with the same nested models and `[JsonExtensionData]`. +- **Flat parameters.** The ids, `expectedVersion` and `idempotencyKey` stay flat camelCase parameters (ADR 0039). An id is named after its BIAN path parameter: `partyReferenceDataDirectoryEntryId`, `demographicsId`, `referenceId`, `associationsId` and `bankRelationsId`. +- **Register.** The Control Record's Register keeps its flat `partyType`, since its body has a single field (ADR 0039). +- **Translation.** The mirror translates the JSON into the existing core inputs (`DemographicsChanges`, `PartyReferenceInput`, `PartyAssociationInput`, `BankRelationsInput`), so every rule and error stays in `RimBank.Core`. +- **The partial-update rules carry over unchanged:** + - a field left out keeps its value; + - an empty value clears it; + - a given address or document replaces the whole of it; + - an unrecorded BIAN part is refused by its BIAN path, with the HTTP code; + - a property that is not BIAN's is ignored. +- **`expectedVersion`.** Every Update and Exchange tool requires it, a `long`, and passes it to the command as HTTP passes `If-Match`. + - A stale version is the same `party.version-conflict` (409) as on HTTP. + - A missing one is `shared.tool-arguments-invalid` (400), because the SDK refuses a missing required argument before the tool runs (ADR 0022). HTTP answers `shared.if-match-required` (428) instead. A missing value is the one case where MCP and HTTP differ. + - Register tools take no `expectedVersion`: they create a record. +- **Version per aggregate.** The `version` of a result is the version of the stream the operation wrote: + - the entry's for the Control Record, Demographics, Reference and BankRelations; + - the association's own stream for the three Associations tools, because an association is its own aggregate ([ADR 0033](0033-party-associations.md)). + + It is the same value HTTP sends as `ETag`. +- **Schema.** With SDK 2.3.1, the generated input schema of `request` is a nested object with the BIAN property names. A `request` that is missing or not an object is `shared.tool-arguments-invalid`. The tests pin both. +- **Descriptions.** Each tool's description is its endpoint's, written for `request` and `expectedVersion` instead of a body and `If-Match`. +- **Guard.** The tool-list guard of ADR 0039 no longer has an allow-list. The tools are exactly the 13 implemented operations: 8 commands and 5 queries. + +## Consequences + +- Tech-stack §6 (Naming) and CONTRIBUTING "MCP" describe `request` and `expectedVersion`. ADR 0039's 1.17 follow-up points here. +- Agents nest a command's body once, under `request`, and can use the BIAN schema of the operation to fill it. +- Each new body-carrying tool adds a mirror of its `.Api` request, response and nested models. This doubles the model code, as ADR 0039 already accepted. The per-operation parity tests catch drift. In particular, they cover a full Reference with every recorded field, the refused parts, and the validation, not-found, stale-version and wrong-type-reference errors. +- Money-moving tools (4.14) follow the same shape. Their `destructive` and scope rules are added then. +- Proven by `tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/`: + - `PartyToolCatalogTests`: + - the tool list equals the implemented operations; + - each tool has its policy and the annotations of its kind; + - the required arguments of each kind; + - the nested `request` schema; + - a read-scope caller sees only the 5 Retrieve tools and gets `shared.forbidden` on a command; + - `VersionRoundTripTests`: Retrieve, then Update, then a stale version is 409, a replay gives the same answer, and a missing `expectedVersion` is refused; + - the tool and parity tests of each BQ: `Update/`, `Demographics/`, `BankRelations/`, `Associations/` and `Reference/`. diff --git a/specs/2026-11-09-party-mcp-remaining-tools/plan.md b/specs/2026-11-09-party-mcp-remaining-tools/plan.md new file mode 100644 index 0000000..e6369ac --- /dev/null +++ b/specs/2026-11-09-party-mcp-remaining-tools/plan.md @@ -0,0 +1,104 @@ +# Plan: MCP adapter: remaining operations + +All tools live in `src/RimBank.Mcp/Party/PartyReferenceDataDirectory//`, namespace `RimBank.Party.PartyReferenceDataDirectory.Mcp`. Each tool: +- is a `[McpServerToolType]` class with `Name` and `OperationId` constants, `[ToolOperation(OperationId)]` and explicit annotations; +- has a description taken from the BIAN operation (and the HTTP endpoint's description); +- builds the core command or query from its arguments and `request` mirror; +- dispatches through `IMessageBus`, and answers with `ToToolResult(… ToolResults.Structured(…))`. + +Tests live in `tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory//`, namespace `RimBank.Party.PartyReferenceDataDirectory.Mcp.Tests`. The build, `dotnet format --verify-no-changes` and the tests are green after each group. + +## 1. CR Update and the command-tool conventions +- [x] Spike: a `request` record parameter with `[JsonPropertyName]` and `[JsonExtensionData]`. Check the SDK 2.3.1 input schema (nested properties, `required`, `additionalProperties`), and how a missing or unbindable `request` is reported (`shared.tool-arguments-invalid`). Record the result for ADR 0040. +- [x] `Update/UpdatePartyReferenceDataDirectoryEntryRequest.cs`: mirror of the `.Api` request (`PartyType` plus the ignored BIAN fields). +- [x] `Update/UpdatePartyReferenceDataDirectoryEntryResult.cs`: reuse the Retrieve result if the shapes match, otherwise a mirror of the `.Api` response plus `version`. +- [x] `Update/UpdatePartyReferenceDataDirectoryEntryTool.cs`, `party_reference_data_directory_update`: + - parameters: `partyReferenceDataDirectoryEntryId`, `request`, `expectedVersion` (long), `idempotencyKey`; + - dispatches `UpdatePartyReferenceDataDirectoryEntry`. +- [x] Register it in `PartyReferenceDataDirectoryTools`, and remove its entry from `_toolsIn117`. +- [x] Test helpers in `PartyMcpHost` or a shared `PartyTools` test class: + - `RegisterAsync` → id plus `version`; + - `CallCommandAsync(name, args)`; + - a parity helper that compares the tool's `structuredContent` (without `version`) to an HTTP body, and `version` to the `ETag`. +- [x] Tests in `Update/UpdatePartyReferenceDataDirectoryEntryToolTests.cs`: + - success returns version + 1; + - a stale version is 409; + - a missing `expectedVersion` is `shared.tool-arguments-invalid`; + - an invalid `PartyType` is 400; + - an unknown id is 404; + - the same key and request give the same answer. +- [x] Parity: success body and `version`, a stale version gives the same Problem Details as HTTP's 409, and an invalid `PartyType` the same 400. + +## 2. Demographics (Update, Exchange, Retrieve) +- [x] `Demographics/`: mirrors of `UpdateDemographicsRequest`, `ExchangeDemographicsRequest`, `DemographicsEmployment` and `DemographicsResponse` (as the result, plus `version`). +- [x] `UpdateDemographicsTool`, `ExchangeDemographicsTool` (commands), and `RetrieveDemographicsTool` (query, `readOnly`, reads the entry view through `RetrievePartyReferenceDataDirectoryEntry` as the endpoint does). +- [x] Registration, and remove their 3 entries from the allow-list. +- [x] Tool tests: + - Update and Retrieve round-trip; + - an invalid `ExchangeActionType`; + - an unknown `demographicsId` is 404; + - a stale version is 409. +- [x] Parity for all three tools: the success body, plus one error each (validation 400, unknown BQ 404). + +## 3. BankRelations (Update, Retrieve) +- [x] `BankRelations/`: mirrors of `UpdateBankRelationsRequest`, `BankRelationReferenceModel` and `BankRelationsResponse`. +- [x] `UpdateBankRelationsTool` (command), and `RetrieveBankRelationsTool` (query). +- [x] Registration, and remove their 2 entries from the allow-list. +- [x] Tool tests: + - an employee (a person) and a unit (an organisation) recorded and retrieved; + - an unregistered or wrong-type party is refused with the HTTP error code; + - a stale version is 409. +- [x] Parity: the success body for both tools, and a wrong-type reference gives the same Problem Details. + +## 4. Associations (Register, Update, Retrieve) +- [x] `Associations/`: mirrors of `PartyAssociationRequest` (with `[JsonExtensionData]`), `InvolvedPartyModel`, `AssociationValidityPeriodModel` and `PartyAssociationResponse`. +- [x] Tools: + - `RegisterPartyAssociationTool` (command, no `expectedVersion`); + - `UpdatePartyAssociationTool` (command, with the association's `expectedVersion`); + - `RetrievePartyAssociationTool` (query). +- [x] Registration, and remove their 3 entries from the allow-list. +- [x] Tool tests: + - register, then retrieve, then update with the association's version; + - an unknown associate is refused; + - a BIAN field that is not recorded is refused with the HTTP code; + - an unknown `associationsId` is 404. +- [x] Parity: the success body for all three, plus a refused field and a stale association version. + +## 5. Reference (Retrieve, Update) +- [x] `Reference/`: mirrors of `UpdatePartyReferenceRequest` and its nested models: + - `CountryModel`, `ResidencyStatusModel`, `PostalAddressModel`; + - `EmailAddressModel`, `MobileNumberModel`, `SocialNetworkContactModel`; + - `PartyLegalEntityModel`, `GovernmentIssuedIdentityModel`; + - `PartyDocumentModel`, `DocumentDirectoryEntryModel`; + - `InvolvedPartyModel`, shared with Associations; + - and the `JsonElement` `CompanyOfficerRole`. +- [x] The same `UnsupportedFields()` as HTTP, using the core's `PartyReferenceFields`. Only the JSON is translated into `PartyReferenceInput`, and validation stays in `PartyReferenceChanges.Create` in core. +- [x] Mirror of `PartyReferenceResponse` as the result, plus `version`. +- [x] `RetrievePartyReferenceTool` (query), and `UpdatePartyReferenceTool` (command). +- [x] Registration, and remove the last 2 entries from the allow-list. +- [x] Tool tests: + - a partial update keeps the fields left out and clears the empty ones; + - an address replaces the whole address; + - an invalid LEI, e-mail and country give the HTTP codes; + - corporate and officer references only on an organisation; + - an unsupported part is `party.reference-field-not-supported`. +- [x] Parity: + - a full Reference (every field, including addresses, a document and officer references) gives the same body; + - one validation error and one refused part give the same Problem Details. + +## 6. Guard, ADR and docs +- [x] `PartyToolCatalogTests`: + - delete `_toolsIn117`; the tool list now equals the catalog's operations exactly; + - rename the test to `The_tool_list_is_the_implemented_operations`. +- [x] Catalog test: every command tool requires `idempotencyKey`, every Update or Exchange tool requires `expectedVersion`, and query tools take neither. This replaces the two single-tool tests from 1.16. +- [x] Authorisation test: a read-scope-only caller lists only the 5 Retrieve tools, and gets `shared.forbidden` when it calls one Update tool. Nothing is stored. +- [x] Version round-trip integration test: + - Retrieve → Update with its version → version + 1; + - the old version again is 409; + - the new version works. +- [x] `docs/adr/0040-party-mcp-command-tools.md` (Decisions and Open questions resolved). +- [x] Update the ADR 0039 "Consequences" line on 1.17 to point to ADR 0040. +- [x] tech-stack §6, Naming bullet: a command's body is one `request` object with BIAN names, and Update and Exchange tools take `expectedVersion`. +- [x] CONTRIBUTING "MCP": an Update call example with `request` and `expectedVersion`. +- [x] `PartyReferenceDataDirectoryTools` comment ("every implemented BIAN operation"). +- [x] `specs/roadmap.md`: tick 1.17. diff --git a/specs/2026-11-09-party-mcp-remaining-tools/requirements.md b/specs/2026-11-09-party-mcp-remaining-tools/requirements.md new file mode 100644 index 0000000..82d0b5f --- /dev/null +++ b/specs/2026-11-09-party-mcp-remaining-tools/requirements.md @@ -0,0 +1,96 @@ +# MCP adapter: remaining operations + +Roadmap phase: 1.17 +Branch: plan/1.17-party-mcp-remaining-tools + +## Context +Mission principle 6 says every operation a context offers over HTTP is also an MCP tool over the same core. Principle 8 says an MCP error is the same Problem Details as on HTTP. Phase 1.16 shipped the first two Party tools (Register, Retrieve) and the conventions they follow ([ADR 0039](../../docs/adr/0039-party-mcp-tools.md)): +- mirrored `.Mcp` models proven equal to HTTP by parity tests; +- `version` on every result; +- a required `idempotencyKey` on commands; +- `[ToolOperation]` with RimBank's call and list authorisation filters; +- a tool-list guard with an allow-list of the 11 operations still missing a tool. + +This phase adds those 11 tools to the folder `Party/PartyReferenceDataDirectory/` of **`RimBank.Mcp`** (namespace `RimBank.Party.PartyReferenceDataDirectory.Mcp`, [ADR 0025](../../docs/adr/0025-one-api-project.md), [ADR 0026](../../docs/adr/0026-flat-context-namespaces.md)) and empties the allow-list. It closes Stage 1: every Party operation in [PartyReferenceDataDirectory.yaml](../../doc-0/release14.0.0/apis-iso20022_ext-ddd/oas3/yamls/PartyReferenceDataDirectory.yaml) that RimBank implements ([ADR 0024](../../docs/adr/0024-party-reference-data-directory-mapping.md)) is reachable over HTTP and MCP. + +It depends on 1.8–1.12 (the operations), 1.15 (policies) and 1.16 (tool conventions, test host, guard), all merged. It unblocks Stage 2's MCP work, 4.14 (money-moving tools) and 7.9 (MCP hardening). + +**CQRS split** (tech-stack §8): +- **Commands (write side), 7 tools.** Each dispatches the existing command through `IMessageBus.InvokeAsync>` and answers from the acknowledgement, never from a read model. The commands are `UpdatePartyReferenceDataDirectoryEntry`, `UpdateDemographics`, `ExchangeDemographics`, `UpdatePartyReference`, `RegisterPartyAssociation`, `UpdatePartyAssociation` and `UpdateBankRelations`. Idempotency comes from `CommandIdempotencyPolicy` ([ADR 0018](../../docs/adr/0018-idempotency-keys-for-commands.md)). Every Update and Exchange tool takes an `expectedVersion` ([ADR 0027](../../docs/adr/0027-optimistic-concurrency-for-commands.md)). +- **Queries (read side), 4 tools.** Demographics, Reference and BankRelations Retrieve read the existing **inline** `PartyReferenceDataDirectoryEntryView`. Associations Retrieve reads the existing **inline** `PartyAssociationView`. **No read model is added or changed**, so there is no new projection, projection test or rebuild step. + +## Scope +### In scope +- **11 tools**, named by the existing `ToolName` rule (ADR 0021): + + | Operation | Tool | Kind | Arguments | + |---|---|---|---| + | `PartyReferenceDataDirectoryEntry/Update` | `party_reference_data_directory_update` | command | entry id, `request`, `expectedVersion`, `idempotencyKey` | + | `Demographics/Update` | `party_reference_data_directory_update_demographics` | command | entry id, `demographicsId`, `request`, `expectedVersion`, `idempotencyKey` | + | `Demographics/Exchange` | `party_reference_data_directory_exchange_demographics` | command | entry id, `demographicsId`, `request`, `expectedVersion`, `idempotencyKey` | + | `Demographics/Retrieve` | `party_reference_data_directory_retrieve_demographics` | query | entry id, `demographicsId` | + | `Reference/Update` | `party_reference_data_directory_update_reference` | command | entry id, `referenceId`, `request`, `expectedVersion`, `idempotencyKey` | + | `Reference/Retrieve` | `party_reference_data_directory_retrieve_reference` | query | entry id, `referenceId` | + | `Associations/Register` | `party_reference_data_directory_register_associations` | command | entry id, `request`, `idempotencyKey` | + | `Associations/Update` | `party_reference_data_directory_update_associations` | command | entry id, `associationsId`, `request`, `expectedVersion`, `idempotencyKey` | + | `Associations/Retrieve` | `party_reference_data_directory_retrieve_associations` | query | entry id, `associationsId` | + | `BankRelations/Update` | `party_reference_data_directory_update_bank_relations` | command | entry id, `bankRelationsId`, `request`, `expectedVersion`, `idempotencyKey` | + | `BankRelations/Retrieve` | `party_reference_data_directory_retrieve_bank_relations` | query | entry id, `bankRelationsId` | + +- **One body object per command tool (user's choice).** + - Each command tool takes one object argument, `request`, shaped exactly like the operation's BIAN request body, with BIAN property names (for example `GovernmentIssuedIdentityReference`, `ResidentialAddress.TownName`). + - The ids, `expectedVersion` and `idempotencyKey` stay flat camelCase parameters, as in ADR 0039. + - The partial-update rules are those of HTTP, because the JSON is the same: + - a field left out keeps its value; + - an empty value clears it; + - an address or document replaces the whole of it; + - BIAN parts RimBank does not record are refused with the same error codes (for example `party.reference-field-not-supported`); + - properties that are not BIAN's are ignored. +- **Mirrored models.** The `.Mcp` folder gets its own request mirrors of the 7 `.Api` request records and their nested models (postal address, document, country, residency status, e-mail, mobile, social network, legal entity, government identity, involved party, validity period, employment, bank relation reference). It also gets result mirrors of the 6 response records (Update, Demographics, Reference, Associations, BankRelations; the CR Update reuses the Retrieve shape if it is the same). `mcp-dependencies` (`.Mcp` never references `.Api`) is unchanged. Parsing and validation stay in `RimBank.Core` (the existing `…Input`/`…Changes`/`…Terms` factories). The mirrors only translate JSON into those inputs. +- **Results.** Each result is `structuredContent` with the BIAN response fields plus `version`, and the same JSON as text. The version is the entry's version, or the association's for the Associations tools (its own stream, ADR 0033). +- **Annotations** (ADR 0021 table): queries `ReadOnly=true`; commands `ReadOnly=false`. All tools are `Destructive=false`, `Idempotent=true` and `OpenWorld=false`. Nothing in Party moves money. +- **Authorisation:** `[ToolOperation(OperationId)]` on each tool. A caller with the read scope only does not see the 8 command tools (the 7 new ones and 1.16's Register) in `tools/list`, and a call to one gets `shared.forbidden` (403) Problem Details (ADR 0038, ADR 0039). +- **Errors:** every failure goes through `ToToolResult` and `ToolProblem`, with the same codes as HTTP. That covers invalid ids (400), an unknown entry, BQ or association (404), a stale `expectedVersion` (409), a reused key (409) and validation errors (400). A missing `expectedVersion`, a missing `request` or a body that cannot be bound is `shared.tool-arguments-invalid`. +- **Wiring:** `AddPartyReferenceDataDirectoryTools()` registers the 11 new tool types. +- **Guard:** `_toolsIn117` is deleted from `PartyToolCatalogTests`. The tool list equals the catalog's operations exactly. The catalog test also checks that every command tool requires `idempotencyKey`, every Update or Exchange tool also requires `expectedVersion`, and no query tool takes either. +- **Docs:** + - ADR 0040; + - tech-stack §6 (arguments: flat for ids and keys, one `request` object for a command's body); + - CONTRIBUTING "MCP" (calling an Update tool with `expectedVersion`); + - the comment of `PartyReferenceDataDirectoryTools`; + - the roadmap tick. + +### Out of scope +- Money-moving scope, default-off switch and `destructive` tools (**4.14**). +- Per-client rate limiting and the tool-call audit query (**7.9**). +- The deferred BIAN operations (CR Control, Request, Execute, Exchange and the eight BQ channels, ADR 0024). They have no HTTP endpoint, so they get no tool. +- Changing Register and CR Retrieve from 1.16. Register keeps its flat `partyType` because it has a single field and no body to mirror. +- An MCP equivalent of `If-None-Match` / 304. MCP has no conditional requests (ADR 0039). +- A manual MCP Inspector demo as a merge gate. The user did not choose it. CONTRIBUTING still explains how to run one. +- New architecture rules for tools. The catalog tests cover names, policies, annotations and required arguments. + +## Decisions +| Decision | Choice | Rationale | +|---|---|---| +| Tool set | All 11 remaining operations, with the allow-list emptied | User's choice and the roadmap row. It closes Stage 1's principle 6 parity. | +| Command arguments | One `request` object shaped like the BIAN request body, plus flat ids, `expectedVersion` and `idempotencyKey` | User's choice. The body is the same JSON as HTTP, so the partial-update rules (left out, empty, replaced, refused) carry over unchanged and the parity tests compare like with like. Reference has about 25 fields, some nested, which do not fit flat parameters. This changes ADR 0039's flat-only rule for body-carrying commands, so it needs ADR 0040. | +| Name of the object argument | `request` on every command tool | One name across Update, Exchange and Register. It is the BIAN request body, so agents and docs can point at the BIAN schema. | +| Request and result models | Mirrors in `.Mcp`, proven equal by parity tests | ADR 0039. `mcp-dependencies` stays, and each adapter can move alone (tech-stack §2). | +| Unrecorded BIAN parts | The mirrors keep `[JsonExtensionData]`, so they are refused exactly as on HTTP | Same error codes on both channels (principle 8). The parity tests include a refused field. | +| `expectedVersion` | A required `long` parameter on every Update and Exchange tool, taken from a Retrieve or a previous command's `version` | MCP's form of `If-Match` (ADR 0027, ADR 0039). A missing one is `shared.tool-arguments-invalid`, where HTTP answers 428. ADR 0040 records this difference. | +| Associations version | The association's own stream version | Associations is its own aggregate (ADR 0033), as its HTTP `ETag` already is. | +| Annotations | Commands are not destructive and are idempotent with their key; queries are `readOnly` | ADR 0021 table. Party moves no money. | +| Order of work | Smallest first: CR Update → Demographics → BankRelations → Associations → Reference → guard and docs | User's choice. Each group repeats the pattern on a larger body, and the build is green after each one. | +| Test home | `RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory//`, reusing `PartyMcpHost` and the 1.16 parity helpers | Tech-stack §3.3 and §9. | + +## ADRs to write +- **0040 Party MCP command tools: a BIAN body object and expected versions.** It covers: + - the `request` object argument for body-carrying commands, which amends ADR 0039 and tech-stack §6; + - the required `expectedVersion`, and its missing case as `shared.tool-arguments-invalid` instead of HTTP's 428; + - how mirrored nested models and `[JsonExtensionData]` keep the refusal rules identical; + - the Associations version; + - the empty tool-list allow-list. + +## Open questions +- **Input schema for `request`.** Does SDK 2.3.1 generate a usable nested JSON schema from a record with `[JsonPropertyName]` and `[JsonExtensionData]`, including `additionalProperties`? Check this in group 1 with the CR Update. If the schema is wrong or unreadable, describe the BIAN fields in the parameter's `[Description]` and record the workaround in ADR 0040. +- **CR Update result shape.** If `UpdatePartyReferenceDataDirectoryEntryResponse` is the same as the Retrieve response, reuse the 1.16 result mirror. Otherwise add its own. Decide in group 1 from the `.Api` model. diff --git a/specs/2026-11-09-party-mcp-remaining-tools/validation.md b/specs/2026-11-09-party-mcp-remaining-tools/validation.md new file mode 100644 index 0000000..a7bbbd1 --- /dev/null +++ b/specs/2026-11-09-party-mcp-remaining-tools/validation.md @@ -0,0 +1,48 @@ +# Validation: MCP adapter: remaining operations + +## Done when (from roadmap) +> **1.17 MCP adapter: remaining operations:** Update and BQ tools; a test that the tool list matches the implemented BIAN operations. +> + Definition of done (roadmap.md) + +The phase adds no read model and changes none, so the projection-test and rebuild items of the Definition of done do not apply. The read side reuses the existing inline views. + +## Automated checks +- [ ] **Tool-list guard** (`PartyToolCatalogTests`, user's choice): + - `_toolsIn117` is gone; + - the registered tools are exactly the `ToolName` of every operation in `OperationPolicyCatalog` (13 tools); + - every tool has one `[ToolOperation]` whose policy exists, a description, and the annotations of its kind (`readOnly` for queries only, never `destructive`, `idempotent`, never `openWorld`). +- [ ] **Required arguments:** + - every command tool requires `idempotencyKey`; + - every Update and Exchange tool also requires `expectedVersion`, and every command tool except Register requires `request`; + - query tools take neither key nor version. +- [ ] **Parity per operation** (`PartyMcpParityTests` and the per-BQ parity tests, user's choice). For each of the 11 operations: + - the tool's `structuredContent` without `version` equals the HTTP body, and `version` equals the `ETag`; + - at least one error gives the same Problem Details members (`type`, `title`, `status`, `detail`, `errorCode`, `errors`). The error is a validation 400, an unknown id 404, a stale version 409 or a refused BIAN part. +- [ ] **Version round-trip** (user's choice): + - Retrieve gives `version` n, and Update with n succeeds with n + 1; + - Update with n again is 409 Problem Details with the HTTP code; + - a missing `expectedVersion` is `shared.tool-arguments-invalid`; + - the same `idempotencyKey` and `request` return the first answer without a second event. +- [ ] **Authorisation:** + - a read-scope-only token lists only the 5 Retrieve tools; + - its call to a command tool is `isError` with `shared.forbidden` (403), and nothing is appended; + - a call without a token is rejected, as tested in 0.16. +- [ ] **Tool tests per BQ** (`RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/{Update,Demographics,BankRelations,Associations,Reference}/`), with the cases listed in plan.md groups 1–5, against a Testcontainers PostgreSQL through `PartyMcpHost`. +- [ ] **Unchanged suites stay green:** + - `RimBank.Architecture.Tests`, including `mcp-dependencies` (`.Mcp` does not reference `.Api`) and `shared-mcp-dependencies` (the `RimBank.Mcp` root does not reference core or Wolverine); + - `RimBank.Core.Tests` and `RimBank.Api.Tests`, including the BIAN conformance tests. +- [ ] `dotnet build -warnaserror`, `dotnet test` and `dotnet format --verify-no-changes` pass locally. +- [ ] GitHub Actions CI green: build, test, format, CodeQL. + +## Manual / demo checks +- [ ] Read through the `tools/list` output (from a test log or a local run): the input schema of `party_reference_data_directory_update_reference` shows a nested `request` object with BIAN property names, and its description says how left-out and empty fields behave. +- [ ] Optional (not a merge gate, per the user's choice): MCP Inspector against the AppHost's `/mcp` with a Keycloak token, following CONTRIBUTING "MCP". Register, then Retrieve (take `version`), then `party_reference_data_directory_update_reference` with a `ResidentialAddress` and that `expectedVersion`. Then `party_reference_data_directory_retrieve_reference` shows the address, and a second Update with the old version gives an `isError` 409 Problem Details. + +## Merge criteria +- [ ] All checks above pass in CI +- [ ] Roadmap checkbox 1.17 ticked in the same PR +- [ ] ADR 0040 written; ADR 0039 consequences and tech-stack §6 updated to match +- [ ] CONTRIBUTING "MCP" explains `request` and `expectedVersion` +- [ ] No business rule or validation added to `RimBank.Mcp`: the mirrors only translate JSON into the existing core inputs (business logic in core) +- [ ] No PII in logs or tool error details: Problem Details only, with no request echo or stack trace +- [ ] PR opened with the `open-phase-pr` skill (labels, milestone, board, `Closes #<1.17 issue>`) diff --git a/specs/roadmap.md b/specs/roadmap.md index a75c9ed..0680308 100644 --- a/specs/roadmap.md +++ b/specs/roadmap.md @@ -63,7 +63,7 @@ - [x] **1.14 Conformance:** OpenAPI and AsyncAPI conformance tests green for the implemented subset. - [x] **1.15 Authorisation policies:** per-operation policies (separate scopes for command and query operations), with tests. - [x] **1.16 MCP adapter: Register & Retrieve:** `RimBank.Party.PartyReferenceDataDirectory.Mcp` tools for Register (command) and Retrieve (query, `readOnly`), with a parity test against the HTTP endpoints. -- [ ] **1.17 MCP adapter: remaining operations:** Update and BQ tools; a test that the tool list matches the implemented BIAN operations. +- [x] **1.17 MCP adapter: remaining operations:** Update and BQ tools; a test that the tool list matches the implemented BIAN operations. ## Stage 2: Product Directory diff --git a/specs/tech-stack.md b/specs/tech-stack.md index c585708..1a1e3e2 100644 --- a/specs/tech-stack.md +++ b/specs/tech-stack.md @@ -271,7 +271,7 @@ The architecture tests tell these roles apart by SharedKernel markers ([ADR 0012 - **MCP is a driving adapter alongside `.Api`.** A context's `.Mcp` adapter (its folder of `RimBank.Mcp`, [ADR 0025](../docs/adr/0025-one-api-project.md)) sends the same core commands and queries through `IMessageBus`. It never calls the HTTP API and never contains business logic, so the HTTP and MCP channels cannot drift apart. - **Hosting:** all contexts' MCP tools are registered in `RimBank.Host` and exposed at a single `/mcp` endpoint over Streamable HTTP in stateless mode. Each context hands its tools to the host through its module's `AddMcpTools(IMcpServerBuilder)`, which calls the one extension its `.Mcp` adapter exposes; contexts never configure the transport or map the route, and a tool name registered twice stops the host ([ADR 0021](../docs/adr/0021-mcp-wiring-and-tool-conventions.md)). When a context is extracted, its `.Mcp` adapter moves with it. -- **Naming:** each tool maps 1:1 to a BIAN operation, named `_[_]` in snake_case (for example `party_reference_data_directory_register` and `current_account_retrieve_payment`). Descriptions come from the BIAN operation description. Arguments are the tool's camelCase parameters (a command tool adds a required `idempotencyKey`), and a result mirrors the `.Api` response model with BIAN's property names plus `version`, the stream version HTTP sends as `ETag`. `.Mcp` never references `.Api`: parity tests prove both channels give the same JSON and Problem Details ([ADR 0039](../docs/adr/0039-party-mcp-tools.md)). +- **Naming:** each tool maps 1:1 to a BIAN operation, named `_[_]` in snake_case (for example `party_reference_data_directory_register` and `current_account_retrieve_payment`). Descriptions come from the BIAN operation description. Arguments are the tool's camelCase parameters: the ids, and for a command a required `idempotencyKey`, a required `expectedVersion` when it changes a record (HTTP's `If-Match`), and its BIAN request body as one `request` object with BIAN's property names ([ADR 0040](../docs/adr/0040-party-mcp-command-tools.md)). A result mirrors the `.Api` response model with BIAN's property names plus `version`, the stream version HTTP sends as `ETag`. `.Mcp` never references `.Api`: parity tests prove both channels give the same JSON and Problem Details ([ADR 0039](../docs/adr/0039-party-mcp-tools.md)). - **Tool annotations:** every tool sets `readOnly`, `destructive`, `idempotent` and `openWorld` explicitly (table in ADR 0021). Retrieve tools dispatch queries and are marked `readOnly`; every other tool dispatches a command. Operations that move money or close facilities are marked `destructive` and are not `idempotent` unless an idempotency key is supplied. - **Security:** the MCP endpoint follows the MCP authorization spec (OAuth 2.1, with Keycloak as the authorization server): a 401 on `/mcp` points to the RFC 9728 protected-resource metadata, which names the realm, and tokens carry the same `rimbank-api` audience as HTTP ([ADR 0022](../docs/adr/0022-mcp-authorization-and-tool-errors.md)). Tool calls go through the same per-BIAN-operation authorisation policies as HTTP: a tool carries the policy named by its operation id (`[ToolOperation(OperationId)]`), a caller without its scope does not see it in `tools/list` and gets the `shared.forbidden` Problem Details on a call, and the metadata lists every policy scope in `scopes_supported` ([ADR 0038](../docs/adr/0038-per-operation-authorisation-policies.md), [ADR 0039](../docs/adr/0039-party-mcp-tools.md)). Money-moving tools need a dedicated scope and are disabled by default, so each deployment must turn them on explicitly. - **Errors:** a business or validation failure returns a tool result with `isError: true` whose content (and `structuredContent`) is the Problem Details JSON (same `type`, `errorCode` and `traceId` as HTTP, ADR 0021). Adapters return failures with `ToToolResult` from `RimBank.Mcp`, whose call-tool filter turns unbindable arguments into `shared.tool-arguments-invalid` and any exception into `shared.unexpected` ([ADR 0022](../docs/adr/0022-mcp-authorization-and-tool-errors.md)). Stack traces and internal details are never exposed. diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceEndpoint.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceEndpoint.cs index 7d1e0ab..7e945e5 100644 --- a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceEndpoint.cs +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceEndpoint.cs @@ -49,10 +49,11 @@ public static RouteHandlerBuilder MapUpdatePartyReference(this IEndpointRouteBui + "GovernmentIssuedDocumentDetails records PartyDocumentType and, in DocumentReference, " + "DocumentIdentification.IdentifierValue (both required), DocumentName and DocumentValidityPeriod " + "(FromDateTime and ToDateTime DateTimeContent dates); DocumentDirectoryEntryInstanceReference records " - + "DocumentDirectoryEntryIdentification. A value left out keeps its value, an empty one clears it, and a given " - + "address or document replaces the whole of it. CorporateCustomerReference, " - + "CorporateCustomerLegalEntityReference, CompanyOfficerReference and CompanyOfficerRole are refused with " - + "party.reference-field-not-supported until roadmap phase 1.21, as are the other parts of the objects above. " + + "DocumentDirectoryEntryIdentification. On an organisation only, CorporateCustomerReference and " + + "CorporateCustomerLegalEntityReference name registered organisations and CompanyOfficerReference a " + + "registered person, each in its PartyReference, with CompanyOfficerRole as text. A value left out keeps its " + + "value, an empty one clears it, and a given address or document replaces the whole of it. Other parts of " + + "the objects above are refused with party.reference-field-not-supported. " + "Send the entry's ETag in If-Match: a missing one is 428, and one that is no longer current is 409. The ETag " + "of the answer is the new version.") .Produces(StatusCodes.Status200OK) diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/AssociationIds.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/AssociationIds.cs new file mode 100644 index 0000000..e3ee803 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/AssociationIds.cs @@ -0,0 +1,31 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// Reads the owner and association ids of an Associations tool, with the errors HTTP gives for its route values. +internal static class AssociationIds +{ + /// The owner's id, or the error of an invalid one. + /// The owner's entry id, as sent. + /// The typed id, or the validation error. + public static Result ReadOwner(string partyReferenceDataDirectoryEntryId) => + PartyReferenceDataDirectoryEntryId.TryCreate(partyReferenceDataDirectoryEntryId) switch + { + { IsFailure: true } => PartyReferenceDataDirectoryEntryErrors.EntryIdInvalid, + var ownerId => ownerId.Value, + }; + + /// The two ids, or the error of the first invalid one. + /// The owner's entry id, as sent. + /// The association's id, as sent. + /// The typed ids, or the validation error. + public static Result<(PartyReferenceDataDirectoryEntryId OwnerId, PartyAssociationId AssociationId)> Read( + string partyReferenceDataDirectoryEntryId, + string associationsId) => + (PartyReferenceDataDirectoryEntryId.TryCreate(partyReferenceDataDirectoryEntryId), PartyAssociationId.TryCreate(associationsId)) switch + { + ({ IsFailure: true }, _) => PartyReferenceDataDirectoryEntryErrors.EntryIdInvalid, + (_, { IsFailure: true }) => PartyAssociationErrors.AssociationIdInvalid, + var (ownerId, associationId) => (ownerId.Value, associationId.Value), + }; +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/AssociationValidityPeriodModel.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/AssociationValidityPeriodModel.cs new file mode 100644 index 0000000..8b6f7ac --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/AssociationValidityPeriodModel.cs @@ -0,0 +1,44 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// BIAN's DateTimePeriod as the Associations AssociationValidFromToDate, in requests and responses (roadmap +/// 1.11, ADR 0033). Unlike the document period of a Reference, its bounds are plain ISO 8601 strings. RimBank records +/// FromDateTime and ToDateTime; a request that sends any other part of it is refused. +/// +public sealed record AssociationValidityPeriodModel +{ + /// BIAN FromDateTime: when the association starts, an ISO 8601 date-time or date. + [JsonPropertyName("FromDateTime")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? FromDateTime { get; init; } + + /// BIAN ToDateTime: when the association ends, an ISO 8601 date-time or date. + [JsonPropertyName("ToDateTime")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? ToDateTime { get; init; } + + /// The other parts a request sent (for example NumberOfDays), which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } + + /// The period as a response shows it: each known bound in UTC, for example 2024-01-01T00:00:00Z. + /// The recorded period, if any. + /// The model, or null when no period is recorded. + public static AssociationValidityPeriodModel? From(AssociationValidityPeriod? period) => + period switch + { + null => null, + _ => new AssociationValidityPeriodModel { FromDateTime = Format(period.From), ToDateTime = Format(period.To) }, + }; + + /// The raw bounds, for the core to read. + /// The input. + public AssociationValidityPeriodInput ToInput() => new(FromDateTime, ToDateTime); + + private static string? Format(DateTimeOffset? bound) => + bound?.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.FFFFFFF'Z'", CultureInfo.InvariantCulture); +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/InvolvedPartyModel.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/InvolvedPartyModel.cs new file mode 100644 index 0000000..9f7ff26 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/InvolvedPartyModel.cs @@ -0,0 +1,22 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// BIAN's Involvedparty, in requests and responses: the Associations AssociateReference (roadmap 1.11, +/// ADR 0033) and the Reference CorporateCustomerReference, CorporateCustomerLegalEntityReference and +/// CompanyOfficerReference (roadmap 1.21, ADR 0034). RimBank records its PartyReference, the id of a +/// directory entry; a request that sends any other part of it (such as InvolvementReference) is refused. +/// +public sealed record InvolvedPartyModel +{ + /// BIAN PartyReference: the associate's PartyReferenceDataDirectoryEntryId. + [JsonPropertyName("PartyReference")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? PartyReference { get; init; } + + /// The other parts a request sent, which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/PartyAssociationRequest.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/PartyAssociationRequest.cs new file mode 100644 index 0000000..762613a --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/PartyAssociationRequest.cs @@ -0,0 +1,87 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// The request argument of party_reference_data_directory_register_associations and +/// party_reference_data_directory_update_associations: BIAN's RegisterAssociations and +/// UpdateAssociations, which have the same properties (roadmap 1.11, ADR 0033), mirroring the HTTP request +/// (ADR 0039, ADR 0040). Register needs the associate and the type; Update is a partial +/// update in which a value left out keeps its value and an empty validity period clears it. The other BIAN Associations +/// fields are refused; properties that are not BIAN's are ignored. +/// +public sealed record PartyAssociationRequest +{ + /// BIAN AssociateReference: the associate's directory entry id in its PartyReference. + [JsonPropertyName("AssociateReference")] + public InvolvedPartyModel? AssociateReference { get; init; } + + /// + /// BIAN AssociateType, as a plain string (BIAN's enum wrapper flattened, ADR 0024), for example + /// PartyIsParentOfParty. + /// + [JsonPropertyName("AssociateType")] + public string? AssociateType { get; init; } + + /// BIAN AssociationValidFromToDate: when the association holds. + [JsonPropertyName("AssociationValidFromToDate")] + public AssociationValidityPeriodModel? AssociationValidFromToDate { get; init; } + + /// Every other property sent: the BIAN Associations fields RimBank does not record are found here. + [JsonExtensionData] + public Dictionary? Other { get; init; } + + /// + /// The BIAN paths of the Associations fields this request sends with a value that RimBank does not record: the + /// top-level fields of (matched without regard to case) and every + /// other part of the objects it reads. A field sent as null is not sent. + /// + /// The paths, in the order sent. + public IReadOnlyList UnsupportedFields() => + [ + .. Present(Other) + .Select(name => PartyAssociationFields.NotRecorded.FirstOrDefault(field => string.Equals(field, name, StringComparison.OrdinalIgnoreCase))) + .OfType(), + .. Present(AssociateReference?.Other).Select(part => $"{PartyAssociationFields.AssociateReference}.{part}"), + .. Present(AssociationValidFromToDate?.Other).Select(part => $"{PartyAssociationFields.AssociationValidFromToDate}.{part}"), + ]; + + /// + /// The Register command this request asks for, party.association-field-not-supported or + /// party.association-invalid. + /// + /// The entry the route names. + /// The request's Idempotency-Key (ADR 0018). + /// The command, or the validation error. + public Result ToRegisterCommand(PartyReferenceDataDirectoryEntryId ownerId, IdempotencyKey idempotencyKey) => + PartyAssociationTerms.Create(ToInput(), UnsupportedFields()) + .Map(terms => new RegisterPartyAssociation(ownerId, terms, idempotencyKey)); + + /// + /// The Update command this request asks for, party.association-field-not-supported or + /// party.association-invalid. + /// + /// The entry the route names. + /// The association the route names. + /// The version from If-Match (ADR 0027). + /// The request's Idempotency-Key (ADR 0018). + /// The command, or the validation error. + public Result ToUpdateCommand( + PartyReferenceDataDirectoryEntryId ownerId, + PartyAssociationId associationId, + long expectedVersion, + IdempotencyKey idempotencyKey) => + PartyAssociationChanges.Create(ToInput(), UnsupportedFields()) + .Map(changes => new UpdatePartyAssociation(ownerId, associationId, expectedVersion, changes, idempotencyKey)); + + private PartyAssociationInput ToInput() => + new( + AssociateReference is { } associate ? associate.PartyReference ?? string.Empty : null, + AssociateType, + AssociationValidFromToDate?.ToInput()); + + private static IEnumerable Present(Dictionary? properties) => + (properties ?? []).Where(property => property.Value.ValueKind != JsonValueKind.Null).Select(property => property.Key); +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/PartyAssociationResult.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/PartyAssociationResult.cs new file mode 100644 index 0000000..11a588e --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/PartyAssociationResult.cs @@ -0,0 +1,64 @@ +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// The result of the Associations tools (roadmap 1.11, ADR 0033): the fields of the HTTP Associations response with +/// BIAN's names, which it mirrors (a parity test proves the JSON is equal, ADR 0039), and the association's +/// , which HTTP sends as the ETag header. An association is its own aggregate, so this is the +/// version of its own stream, not of the owner's entry (ADR 0024, ADR 0040). +/// +/// The association. +/// The entry that owns it. +/// BIAN AssociateReference: the associate's entry. +/// BIAN AssociateType. +/// BIAN AssociationValidFromToDate, when recorded. +/// The association's version: the expectedVersion of its next Update (ADR 0027). +public sealed record PartyAssociationResult( + [property: JsonPropertyName("AssociationsId")] Guid AssociationsId, + [property: JsonPropertyName("PartyReferenceDataDirectoryEntryId")] Guid PartyReferenceDataDirectoryEntryId, + [property: JsonPropertyName("AssociateReference")] InvolvedPartyModel AssociateReference, + [property: JsonPropertyName("AssociateType")] string AssociateType, + [property: JsonPropertyName("AssociationValidFromToDate"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + AssociationValidityPeriodModel? AssociationValidFromToDate, + [property: JsonPropertyName("version")] long Version) +{ + /// The result of a Register or an Update, built from its acknowledgement, never from a read model. + /// The outcome of or . + /// The tool's result. + public static PartyAssociationResult From(PartyAssociationAcknowledged acknowledged) + { + ArgumentNullException.ThrowIfNull(acknowledged); + return From( + acknowledged.AssociationId, + acknowledged.OwnerId, + acknowledged.AssociateId, + acknowledged.AssociateType, + acknowledged.ValidityPeriod, + acknowledged.Version); + } + + /// The result of a Retrieve, built from the association's view. + /// The association's read model. + /// The tool's result. + public static PartyAssociationResult From(PartyAssociationView view) + { + ArgumentNullException.ThrowIfNull(view); + return From(view.AssociationId, view.OwnerId, view.AssociateId, view.AssociateType, view.ValidityPeriod, view.Version); + } + + private static PartyAssociationResult From( + PartyAssociationId associationId, + PartyReferenceDataDirectoryEntryId ownerId, + PartyReferenceDataDirectoryEntryId associateId, + PartyRelationshipType type, + AssociationValidityPeriod? period, + long version) => + new( + associationId.Value, + ownerId.Value, + new InvolvedPartyModel { PartyReference = associateId.ToString() }, + type.ToBianName(), + AssociationValidityPeriodModel.From(period), + version); +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationTool.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationTool.cs new file mode 100644 index 0000000..c8368e3 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationTool.cs @@ -0,0 +1,66 @@ +using System.ComponentModel; +using ModelContextProtocol.Protocol; +using ModelContextProtocol.Server; +using RimBank.Mcp; +using RimBank.SharedKernel; +using Wolverine; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// party_reference_data_directory_register_associations: BIAN Associations/Register, a command that starts +/// a new association, its own aggregate (ADR 0024, ADR 0033). It dispatches , as +/// POST …/Associations/Register does, and answers from its acknowledgement (ADR 0039, ADR 0040). It changes no +/// existing record, so it takes no expectedVersion. +/// +[McpServerToolType] +public sealed class RegisterPartyAssociationTool +{ + /// The tool's name (ADR 0021). + public const string Name = "party_reference_data_directory_register_associations"; + + /// The BIAN operation id, which names the tool's authorisation policy (ADR 0038). + public const string OperationId = "Associations/Register"; + + /// Associates the party with another party, as the HTTP endpoint does: the same command, idempotency and errors. + /// The id of the entry that owns the association. + /// The BIAN Register body. + /// The command's idempotency key (ADR 0018). + /// The host's message bus. + /// The call's cancellation. + /// The new association with its version, or the Problem Details of the error. + [McpServerTool(Name = Name, Title = "Associate a party with another party", ReadOnly = false, Destructive = false, Idempotent = true, OpenWorld = false)] + [ToolOperation(OperationId)] + [Description( + "BIAN Party Reference Data Directory: register a new association of the customer with another party of the " + + "directory. In request, AssociateReference.PartyReference (the associate's PartyReferenceDataDirectoryEntryId) " + + "and AssociateType are required. AssociateType is one of PartyIsParentOfParty, PartyIsSubsidiaryOfParty, " + + "PartyIsCertifiedByParty, PartyIsMarriedToParty, PartyActsOnBehalfOfParty, PartyIsContactPointForParty, " + + "PartyIsTrustedByParty, PartyIsThePowerOfAttorneyForParty or PartyReceivesBenefitsFromAParty, read as \"this " + + "party the associate\". AssociationValidFromToDate (FromDateTime and ToDateTime, ISO 8601, from not after " + + "to) is optional. The associate must be registered and must not be the party itself. The other BIAN Associations " + + "fields are refused with party.association-field-not-supported. Returns the AssociationsId and the " + + "association's version (send it as expectedVersion to update the association). Calling again with the same " + + "idempotencyKey and arguments returns the same association.")] + public static async Task RegisterAsync( + [Description("The PartyReferenceDataDirectoryEntryId of the party that owns the association.")] string partyReferenceDataDirectoryEntryId, + [Description("The BIAN RegisterAssociations body, with BIAN's property names.")] PartyAssociationRequest request, + [Description("A key of 1 to 255 visible ASCII characters, unique per registration. Reusing it with other arguments is a conflict.")] string idempotencyKey, + IMessageBus bus, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(bus); + + var command = AssociationIds.ReadOwner(partyReferenceDataDirectoryEntryId) + .Bind(ownerId => IdempotencyKey.TryCreate(idempotencyKey) + .Bind(key => request.ToRegisterCommand(ownerId, key))); + if (command.IsFailure) + { + return ToolProblem.Create(command.Error); + } + + var outcome = await bus.InvokeAsync>(command.Value, cancellationToken); + return outcome.ToToolResult(acknowledged => ToolResults.Structured(PartyAssociationResult.From(acknowledged))); + } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationTool.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationTool.cs new file mode 100644 index 0000000..8c1feb9 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationTool.cs @@ -0,0 +1,56 @@ +using System.ComponentModel; +using ModelContextProtocol.Protocol; +using ModelContextProtocol.Server; +using RimBank.Mcp; +using RimBank.SharedKernel; +using Wolverine; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// party_reference_data_directory_retrieve_associations: BIAN Associations/Retrieve, a query (ADR 0024). +/// It dispatches , as GET …/Associations/{associationsid}/Retrieve does, +/// and answers only from the association's inline view (tech-stack §6, §8, ADR 0039). +/// +[McpServerToolType] +public sealed class RetrievePartyAssociationTool +{ + /// The tool's name (ADR 0021). + public const string Name = "party_reference_data_directory_retrieve_associations"; + + /// The BIAN operation id, which names the tool's authorisation policy (ADR 0038). + public const string OperationId = "Associations/Retrieve"; + + /// Retrieves an association, as the HTTP endpoint does: the same query and errors. + /// The id of the entry that owns the association. + /// The association's id. + /// The host's message bus. + /// The call's cancellation. + /// The association with its version, or the Problem Details of the error. + [McpServerTool(Name = Name, Title = "Retrieve a party association", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false)] + [ToolOperation(OperationId)] + [Description( + "BIAN Party Reference Data Directory: retrieve details about an association of the customer. Returns " + + "AssociateReference.PartyReference (the associate's entry id), AssociateType and, when recorded, " + + "AssociationValidFromToDate in UTC, with the association's version (send it as expectedVersion to update the " + + "association). Only the entry that owns the association finds it.")] + public static async Task RetrieveAsync( + [Description("The PartyReferenceDataDirectoryEntryId of the party that owns the association.")] string partyReferenceDataDirectoryEntryId, + [Description("The AssociationsId that Register returned.")] string associationsId, + IMessageBus bus, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(bus); + + var ids = AssociationIds.Read(partyReferenceDataDirectoryEntryId, associationsId); + if (ids.IsFailure) + { + return ToolProblem.Create(ids.Error); + } + + var view = await bus.InvokeAsync>( + new RetrievePartyAssociation(ids.Value.OwnerId, ids.Value.AssociationId), + cancellationToken); + return view.ToToolResult(found => ToolResults.Structured(PartyAssociationResult.From(found))); + } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationTool.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationTool.cs new file mode 100644 index 0000000..ae07776 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationTool.cs @@ -0,0 +1,67 @@ +using System.ComponentModel; +using ModelContextProtocol.Protocol; +using ModelContextProtocol.Server; +using RimBank.Mcp; +using RimBank.SharedKernel; +using Wolverine; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// party_reference_data_directory_update_associations: BIAN Associations/Update, a command (ADR 0024, +/// ADR 0033). It dispatches , as PUT …/Associations/{associationsid}/Update +/// does, with the association's expectedVersion in place of If-Match, and answers from its acknowledgement +/// (ADR 0039, ADR 0040). +/// +[McpServerToolType] +public sealed class UpdatePartyAssociationTool +{ + /// The tool's name (ADR 0021). + public const string Name = "party_reference_data_directory_update_associations"; + + /// The BIAN operation id, which names the tool's authorisation policy (ADR 0038). + public const string OperationId = "Associations/Update"; + + /// Updates an association, as the HTTP endpoint does: the same command, idempotency and errors. + /// The id of the entry that owns the association. + /// The association's id. + /// The BIAN Update body. + /// The association's version the caller last read (ADR 0027). + /// The command's idempotency key (ADR 0018). + /// The host's message bus. + /// The call's cancellation. + /// The association with its new version, or the Problem Details of the error. + [McpServerTool(Name = Name, Title = "Update a party association", ReadOnly = false, Destructive = false, Idempotent = true, OpenWorld = false)] + [ToolOperation(OperationId)] + [Description( + "BIAN Party Reference Data Directory: update details about an association of the customer. request is the BIAN " + + "UpdateAssociations body, a partial update of AssociateType and AssociationValidFromToDate (FromDateTime and " + + "ToDateTime, ISO 8601, from not after to). A value left out keeps its value, and an empty validity period clears " + + "it; the type cannot be cleared. The owner and the associate never change: an AssociateReference.PartyReference " + + "other than the registered associate is refused with party.associate-cannot-change. Send the association's " + + "version you last read as expectedVersion (it is the association's own version, not the entry's): one that is no " + + "longer current is a conflict. The answer's version is the new one.")] + public static async Task UpdateAsync( + [Description("The PartyReferenceDataDirectoryEntryId of the party that owns the association.")] string partyReferenceDataDirectoryEntryId, + [Description("The AssociationsId that Register returned.")] string associationsId, + [Description("The BIAN UpdateAssociations body, with BIAN's property names.")] PartyAssociationRequest request, + [Description("The association's version from its last Retrieve or command (the ETag on HTTP).")] long expectedVersion, + [Description("A key of 1 to 255 visible ASCII characters, unique per update. Reusing it with other arguments is a conflict.")] string idempotencyKey, + IMessageBus bus, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(bus); + + var command = AssociationIds.Read(partyReferenceDataDirectoryEntryId, associationsId) + .Bind(ids => IdempotencyKey.TryCreate(idempotencyKey) + .Bind(key => request.ToUpdateCommand(ids.OwnerId, ids.AssociationId, expectedVersion, key))); + if (command.IsFailure) + { + return ToolProblem.Create(command.Error); + } + + var outcome = await bus.InvokeAsync>(command.Value, cancellationToken); + return outcome.ToToolResult(acknowledged => ToolResults.Structured(PartyAssociationResult.From(acknowledged))); + } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/BankRelations/BankRelationReferenceModel.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/BankRelations/BankRelationReferenceModel.cs new file mode 100644 index 0000000..fe564bc --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/BankRelations/BankRelationReferenceModel.cs @@ -0,0 +1,90 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// BIAN's BankRelations BankRelationReference (a PartyRelationship), in requests and responses (roadmap 1.12, +/// ADR 0035). RimBank records the DateTimeContent of RelationshipStartDate and RelationshipEndDate, and +/// the StatusDescription of RelationshipLifecycleStatus; a request that sends any other part (such as +/// RelationshipIdentification) is refused. +/// +public sealed record BankRelationReferenceModel +{ + /// BIAN RelationshipStartDate: when the relationship started. + [JsonPropertyName("RelationshipStartDate")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public DateTimeModel? RelationshipStartDate { get; init; } + + /// BIAN RelationshipEndDate: when the relationship ended or ends. + [JsonPropertyName("RelationshipEndDate")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public DateTimeModel? RelationshipEndDate { get; init; } + + /// BIAN RelationshipLifecycleStatus: where the relationship stands. + [JsonPropertyName("RelationshipLifecycleStatus")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public RelationshipLifecycleStatusModel? RelationshipLifecycleStatus { get; init; } + + /// The other parts a request sent, which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } + + /// The recorded parts as raw text: an object sent without its recorded part is sent blank, which clears it. + /// The input the core reads. + public BankRelationReferenceInput ToInput() => + new( + RelationshipStartDate is { } start ? start.DateTimeContent ?? string.Empty : null, + RelationshipEndDate is { } end ? end.DateTimeContent ?? string.Empty : null, + RelationshipLifecycleStatus is { } status ? status.StatusDescription ?? string.Empty : null); + + /// The BIAN paths of the parts sent with a value that RimBank does not record. + /// The paths, in the order sent. + public IEnumerable UnsupportedParts() => + [ + .. ReferenceModelParts.Present(BankRelationsFields.BankRelationReference, Other), + .. ReferenceModelParts.Present(BankRelationsFields.RelationshipStartDate, RelationshipStartDate?.Other), + .. ReferenceModelParts.Present(BankRelationsFields.RelationshipEndDate, RelationshipEndDate?.Other), + .. ReferenceModelParts.Present(BankRelationsFields.RelationshipLifecycleStatus, RelationshipLifecycleStatus?.Other), + ]; + + /// The recorded relationship parts of some BankRelations, or null when none is known. + /// The BankRelations. + /// The model, with each unknown part left out. + public static BankRelationReferenceModel? From(BankRelationsDetails details) + { + ArgumentNullException.ThrowIfNull(details); + return details is { StartDate: null, EndDate: null, LifecycleStatus: null } + ? null + : new BankRelationReferenceModel + { + RelationshipStartDate = DateOf(details.StartDate), + RelationshipEndDate = DateOf(details.EndDate), + RelationshipLifecycleStatus = details.LifecycleStatus is { } status + ? new RelationshipLifecycleStatusModel { StatusDescription = status.ToBianName() } + : null, + }; + } + + private static DateTimeModel? DateOf(DateTimeOffset? value) => + value is { } instant + ? new DateTimeModel { DateTimeContent = instant.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.FFFFFFF'Z'", CultureInfo.InvariantCulture) } + : null; +} + +/// +/// BIAN's RelationshipLifecycleStatus (ISO 20022 Status) inside +/// (roadmap 1.12). RimBank records StatusDescription; a request that sends any other part of it is refused. +/// +public sealed record RelationshipLifecycleStatusModel +{ + /// BIAN StatusDescription: Active, Suspended or Ended. + [JsonPropertyName("StatusDescription")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? StatusDescription { get; init; } + + /// The other parts a request sent (for example StatusReason), which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsIds.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsIds.cs new file mode 100644 index 0000000..1254c69 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsIds.cs @@ -0,0 +1,21 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// Reads the entry and BankRelations ids of a BankRelations tool, with the errors HTTP gives for its route values. +internal static class BankRelationsIds +{ + /// The two ids, or the error of the first invalid one. + /// The entry's id, as sent. + /// The BankRelations id, as sent. + /// The typed ids, or the validation error. + public static Result<(PartyReferenceDataDirectoryEntryId EntryId, BankRelationsId BankRelationsId)> Read( + string partyReferenceDataDirectoryEntryId, + string bankRelationsId) => + (PartyReferenceDataDirectoryEntryId.TryCreate(partyReferenceDataDirectoryEntryId), BankRelationsId.TryCreate(bankRelationsId)) switch + { + ({ IsFailure: true }, _) => PartyReferenceDataDirectoryEntryErrors.EntryIdInvalid, + (_, { IsFailure: true }) => BankRelationsErrors.BankRelationsIdInvalid, + var (entryId, bankRelations) => (entryId.Value, bankRelations.Value), + }; +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsResult.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsResult.cs new file mode 100644 index 0000000..cdade91 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsResult.cs @@ -0,0 +1,57 @@ +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// The result of the BankRelations tools (roadmap 1.12, ADR 0035): the fields of the HTTP BankRelations response with +/// BIAN's names, which it mirrors (a parity test proves the JSON is equal, ADR 0039), with every unknown value left out, +/// and the entry's , which HTTP sends as the ETag header. +/// +/// The entry's BankRelations. +/// The entry. +/// BIAN BankRelationType. +/// BIAN BusinessUnitEmployeeReference: the employee's or unit's entry. +/// BIAN BankRelationReference: the relationship's dates and lifecycle status. +/// The entry's version: the expectedVersion of a later command (ADR 0027). +public sealed record BankRelationsResult( + [property: JsonPropertyName("BankRelationsId")] Guid BankRelationsId, + [property: JsonPropertyName("PartyReferenceDataDirectoryEntryId")] Guid PartyReferenceDataDirectoryEntryId, + [property: JsonPropertyName("BankRelationType"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + string? BankRelationType, + [property: JsonPropertyName("BusinessUnitEmployeeReference"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + InvolvedPartyModel? BusinessUnitEmployeeReference, + [property: JsonPropertyName("BankRelationReference"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + BankRelationReferenceModel? BankRelationReference, + [property: JsonPropertyName("version")] long Version) +{ + /// The result of an Update, built from its acknowledgement, never from a read model (tech-stack §5). + /// The outcome of . + /// The tool's result. + public static BankRelationsResult From(UpdateBankRelationsAcknowledged acknowledged) + { + ArgumentNullException.ThrowIfNull(acknowledged); + return From(acknowledged.BankRelationsId, acknowledged.EntryId, acknowledged.BankRelations, acknowledged.Version); + } + + /// The result of a Retrieve, built from the entry's view. + /// The entry's read model. + /// The tool's result. + public static BankRelationsResult From(PartyReferenceDataDirectoryEntryView view) + { + ArgumentNullException.ThrowIfNull(view); + return From(view.BankRelationsId, view.EntryId, view.CurrentBankRelations, view.Version); + } + + private static BankRelationsResult From( + BankRelationsId bankRelationsId, + PartyReferenceDataDirectoryEntryId entryId, + BankRelationsDetails details, + long version) => + new( + bankRelationsId.Value, + entryId.Value, + details.Type?.ToBianName(), + details.BusinessUnitEmployee is { } employee ? new InvolvedPartyModel { PartyReference = employee.ToString() } : null, + BankRelationReferenceModel.From(details), + version); +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelationsTool.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelationsTool.cs new file mode 100644 index 0000000..93ff7f2 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelationsTool.cs @@ -0,0 +1,57 @@ +using System.ComponentModel; +using ModelContextProtocol.Protocol; +using ModelContextProtocol.Server; +using RimBank.Mcp; +using RimBank.SharedKernel; +using Wolverine; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// party_reference_data_directory_retrieve_bank_relations: BIAN BankRelations/Retrieve, a query +/// (ADR 0024). It dispatches , as GET …/BankRelations/{bankrelationsid}/Retrieve +/// does, and answers only from the entry's inline view (tech-stack §6, §8, ADR 0039). +/// +[McpServerToolType] +public sealed class RetrieveBankRelationsTool +{ + /// The tool's name (ADR 0021). + public const string Name = "party_reference_data_directory_retrieve_bank_relations"; + + /// The BIAN operation id, which names the tool's authorisation policy (ADR 0038). + public const string OperationId = "BankRelations/Retrieve"; + + /// Retrieves the party's BankRelations, as the HTTP endpoint does: the same query and errors. + /// The entry's id. + /// The entry's BankRelationsId. + /// The host's message bus. + /// The call's cancellation. + /// The BankRelations with the entry's version, or the Problem Details of the error. + [McpServerTool(Name = Name, Title = "Retrieve a party's bank relations", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false)] + [ToolOperation(OperationId)] + [Description( + "BIAN Party Reference Data Directory: retrieve details about the customer's relationship with the bank. Returns " + + "BankRelationType, the employee or unit in BusinessUnitEmployeeReference.PartyReference, and in " + + "BankRelationReference the RelationshipStartDate and RelationshipEndDate (UTC date-times) and the " + + "RelationshipLifecycleStatus, with the entry's version (send it as expectedVersion to change the entry). Unknown " + + "values are left out.")] + public static async Task RetrieveAsync( + [Description("The PartyReferenceDataDirectoryEntryId that Register returned.")] string partyReferenceDataDirectoryEntryId, + [Description("The entry's BankRelationsId, from Register or Retrieve.")] string bankRelationsId, + IMessageBus bus, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(bus); + + var ids = BankRelationsIds.Read(partyReferenceDataDirectoryEntryId, bankRelationsId); + if (ids.IsFailure) + { + return ToolProblem.Create(ids.Error); + } + + var view = await bus.InvokeAsync>( + new RetrieveBankRelations(ids.Value.EntryId, ids.Value.BankRelationsId), + cancellationToken); + return view.ToToolResult(found => ToolResults.Structured(BankRelationsResult.From(found))); + } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsRequest.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsRequest.cs new file mode 100644 index 0000000..86f7122 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsRequest.cs @@ -0,0 +1,61 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// The request argument of party_reference_data_directory_update_bank_relations: BIAN's +/// UpdateBankRelations body (roadmap 1.12, ADR 0035), mirroring the HTTP request (ADR 0039, ADR 0040). It is a +/// partial update in which a value left out keeps its value and an empty one clears it. The parts of the BIAN objects +/// RimBank does not record are refused; properties that are not BIAN's are ignored. +/// +public sealed record UpdateBankRelationsRequest +{ + /// BIAN BankRelationType, for example RelationshipManager. + [JsonPropertyName("BankRelationType")] + public string? BankRelationType { get; init; } + + /// BIAN BusinessUnitEmployeeReference: the employee's or unit's directory entry id in its PartyReference. + [JsonPropertyName("BusinessUnitEmployeeReference")] + public InvolvedPartyModel? BusinessUnitEmployeeReference { get; init; } + + /// BIAN BankRelationReference: the relationship's dates and lifecycle status. + [JsonPropertyName("BankRelationReference")] + public BankRelationReferenceModel? BankRelationReference { get; init; } + + /// Every other property sent, which is not a BIAN BankRelations field and is ignored. + [JsonExtensionData] + public Dictionary? Other { get; init; } + + /// The BIAN paths of the parts this request sends with a value that RimBank does not record. + /// The paths, in the order sent. + public IReadOnlyList UnsupportedFields() => + [ + .. ReferenceModelParts.Present(BankRelationsFields.BusinessUnitEmployeeReference, BusinessUnitEmployeeReference?.Other), + .. BankRelationReference?.UnsupportedParts() ?? [], + ]; + + /// + /// The Update command this request asks for, party.bank-relations-field-not-supported or + /// party.bank-relations-invalid. + /// + /// The entry the route names. + /// The BankRelations the route names. + /// The version from If-Match (ADR 0027). + /// The request's Idempotency-Key (ADR 0018). + /// The command, or the validation error. + public Result ToCommand( + PartyReferenceDataDirectoryEntryId entryId, + BankRelationsId bankRelationsId, + long expectedVersion, + IdempotencyKey idempotencyKey) => + BankRelationsChanges.Create(ToInput(), UnsupportedFields()) + .Map(changes => new UpdateBankRelations(entryId, bankRelationsId, expectedVersion, changes, idempotencyKey)); + + private BankRelationsInput ToInput() => + new( + BankRelationType, + BusinessUnitEmployeeReference is { } employee ? employee.PartyReference ?? string.Empty : null, + BankRelationReference?.ToInput()); +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsTool.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsTool.cs new file mode 100644 index 0000000..bf37d10 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsTool.cs @@ -0,0 +1,70 @@ +using System.ComponentModel; +using ModelContextProtocol.Protocol; +using ModelContextProtocol.Server; +using RimBank.Mcp; +using RimBank.SharedKernel; +using Wolverine; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// party_reference_data_directory_update_bank_relations: BIAN BankRelations/Update, a command (ADR 0024, +/// ADR 0035). It dispatches , as PUT …/BankRelations/{bankrelationsid}/Update +/// does, with expectedVersion in place of If-Match, and answers from its acknowledgement (ADR 0039, +/// ADR 0040). +/// +[McpServerToolType] +public sealed class UpdateBankRelationsTool +{ + /// The tool's name (ADR 0021). + public const string Name = "party_reference_data_directory_update_bank_relations"; + + /// The BIAN operation id, which names the tool's authorisation policy (ADR 0038). + public const string OperationId = "BankRelations/Update"; + + /// Updates the party's BankRelations, as the HTTP endpoint does: the same command, idempotency and errors. + /// The entry's id. + /// The entry's BankRelationsId. + /// The BIAN Update body. + /// The entry's version the caller last read (ADR 0027). + /// The command's idempotency key (ADR 0018). + /// The host's message bus. + /// The call's cancellation. + /// The BankRelations with the entry's new version, or the Problem Details of the error. + [McpServerTool(Name = Name, Title = "Update a party's bank relations", ReadOnly = false, Destructive = false, Idempotent = true, OpenWorld = false)] + [ToolOperation(OperationId)] + [Description( + "BIAN Party Reference Data Directory: update details about the customer's relationship with the bank. request is " + + "the BIAN UpdateBankRelations body, a partial update. BankRelationType is RelationshipManager or AccountOfficer " + + "(BusinessUnitEmployeeReference.PartyReference then names a registered person) or ServicingBranch or " + + "ServicingBusinessUnit (it then names a registered organisation); the reference must be another entry of the " + + "directory and needs a type. BankRelationReference records RelationshipStartDate and RelationshipEndDate " + + "(DateTimeContent, an ISO 8601 date or date-time, the end not before the start) and " + + "RelationshipLifecycleStatus.StatusDescription (Active, Suspended or Ended). A value left out keeps its value, an " + + "empty one clears it, and an empty BankRelationReference clears the dates and the status. Every other BIAN part " + + "is refused with party.bank-relations-field-not-supported. Send the version you last read as expectedVersion: one " + + "that is no longer current is a conflict. The answer's version is the new one.")] + public static async Task UpdateAsync( + [Description("The PartyReferenceDataDirectoryEntryId that Register returned.")] string partyReferenceDataDirectoryEntryId, + [Description("The entry's BankRelationsId, from Register or Retrieve.")] string bankRelationsId, + [Description("The BIAN UpdateBankRelations body, with BIAN's property names.")] UpdateBankRelationsRequest request, + [Description("The entry's version from the last Retrieve or command (the ETag on HTTP).")] long expectedVersion, + [Description("A key of 1 to 255 visible ASCII characters, unique per update. Reusing it with other arguments is a conflict.")] string idempotencyKey, + IMessageBus bus, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(bus); + + var command = BankRelationsIds.Read(partyReferenceDataDirectoryEntryId, bankRelationsId) + .Bind(ids => IdempotencyKey.TryCreate(idempotencyKey) + .Bind(key => request.ToCommand(ids.EntryId, ids.BankRelationsId, expectedVersion, key))); + if (command.IsFailure) + { + return ToolProblem.Create(command.Error); + } + + var outcome = await bus.InvokeAsync>(command.Value, cancellationToken); + return outcome.ToToolResult(acknowledged => ToolResults.Structured(BankRelationsResult.From(acknowledged))); + } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/DemographicsEmployment.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/DemographicsEmployment.cs new file mode 100644 index 0000000..85615e0 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/DemographicsEmployment.cs @@ -0,0 +1,25 @@ +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// BIAN Employment of the Demographics, mirroring the HTTP model (ADR 0039). +/// The employer. +/// The employment's reference. +public sealed record DemographicsEmployment( + [property: JsonPropertyName("PartyReference"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? PartyReference, + [property: JsonPropertyName("InvolvementReference"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? InvolvementReference) +{ + /// The core's employment. + /// The employment this model describes. + public Employment ToEmployment() => new(PartyReference, InvolvementReference); + + /// The model of , or null when none is recorded. + /// The recorded employment. + /// The model. + public static DemographicsEmployment? From(Employment? employment) => + employment switch + { + null => null, + _ => new DemographicsEmployment(employment.PartyReference, employment.InvolvementReference), + }; +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/DemographicsIds.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/DemographicsIds.cs new file mode 100644 index 0000000..5b58376 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/DemographicsIds.cs @@ -0,0 +1,21 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// Reads the entry and Demographics ids of a Demographics tool, with the errors HTTP gives for its route values. +internal static class DemographicsIds +{ + /// The two ids, or the error of the first invalid one. + /// The entry's id, as sent. + /// The Demographics id, as sent. + /// The typed ids, or the validation error. + public static Result<(PartyReferenceDataDirectoryEntryId EntryId, DemographicsId DemographicsId)> Read( + string partyReferenceDataDirectoryEntryId, + string demographicsId) => + (PartyReferenceDataDirectoryEntryId.TryCreate(partyReferenceDataDirectoryEntryId), DemographicsId.TryCreate(demographicsId)) switch + { + ({ IsFailure: true }, _) => PartyReferenceDataDirectoryEntryErrors.EntryIdInvalid, + (_, { IsFailure: true }) => DemographicsErrors.DemographicsIdInvalid, + var (entryId, demographics) => (entryId.Value, demographics.Value), + }; +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/DemographicsResult.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/DemographicsResult.cs new file mode 100644 index 0000000..4d74152 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/DemographicsResult.cs @@ -0,0 +1,75 @@ +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// The result of the Demographics tools: the fields of the HTTP Demographics response with BIAN's names, which it +/// mirrors (a parity test proves the JSON is equal, ADR 0039), and the entry's , which HTTP sends as +/// the ETag header. Commands build it from their acknowledgement, Retrieve from the entry's view. +/// +/// The entry. +/// The entry's Demographics. +/// BIAN Socio-EconomicClassification, when known. +/// BIAN Employment, when known. +/// BIAN EmploymentHistory, when known. +/// BIAN EducationHistory, when known. +/// BIAN ServicingConstraints, when known. +/// Whether the bank verified the details (ADR 0028). +/// When the bank verified or rejected them. +/// The entry's version: the expectedVersion of a later command (ADR 0027). +public sealed record DemographicsResult( + [property: JsonPropertyName("PartyReferenceDataDirectoryEntryId")] Guid PartyReferenceDataDirectoryEntryId, + [property: JsonPropertyName("DemographicsId")] Guid DemographicsId, + [property: JsonPropertyName("Socio-EconomicClassification"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? SocioEconomicClassification, + [property: JsonPropertyName("Employment"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] DemographicsEmployment? Employment, + [property: JsonPropertyName("EmploymentHistory"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? EmploymentHistory, + [property: JsonPropertyName("EducationHistory"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? EducationHistory, + [property: JsonPropertyName("ServicingConstraints"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? ServicingConstraints, + [property: JsonPropertyName("VerificationStatus")] string VerificationStatus, + [property: JsonPropertyName("VerificationDate"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] DateTimeOffset? VerificationDate, + [property: JsonPropertyName("version")] long Version) +{ + /// The result of an Update. + /// The outcome of . + /// The tool's result. + public static DemographicsResult From(UpdateDemographicsAcknowledged acknowledged) + { + ArgumentNullException.ThrowIfNull(acknowledged); + return From(acknowledged.EntryId, acknowledged.DemographicsId, acknowledged.Demographics, acknowledged.Version); + } + + /// The result of an Exchange. + /// The outcome of . + /// The tool's result. + public static DemographicsResult From(ExchangeDemographicsAcknowledged acknowledged) + { + ArgumentNullException.ThrowIfNull(acknowledged); + return From(acknowledged.EntryId, acknowledged.DemographicsId, acknowledged.Demographics, acknowledged.Version); + } + + /// The result of a Retrieve. + /// The entry's read model. + /// The tool's result. + public static DemographicsResult From(PartyReferenceDataDirectoryEntryView view) + { + ArgumentNullException.ThrowIfNull(view); + return From(view.EntryId, view.DemographicsId, view.CurrentDemographics, view.Version); + } + + private static DemographicsResult From( + PartyReferenceDataDirectoryEntryId entryId, + DemographicsId demographicsId, + DemographicsRecord demographics, + long version) => + new( + entryId.Value, + demographicsId.Value, + demographics.Details.SocioEconomicClassification, + DemographicsEmployment.From(demographics.Details.Employment), + demographics.Details.EmploymentHistory, + demographics.Details.EducationHistory, + demographics.Details.ServicingConstraints, + demographics.VerificationStatus.ToString(), + demographics.VerificationDate, + version); +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/ExchangeDemographicsRequest.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/ExchangeDemographicsRequest.cs new file mode 100644 index 0000000..a468d33 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/ExchangeDemographicsRequest.cs @@ -0,0 +1,56 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// The request argument of party_reference_data_directory_exchange_demographics: BIAN's +/// ExchangeDemographics body, mirroring the HTTP request (ADR 0039, ADR 0040). ExchangeActionType is +/// RimBank's extension field (ADR 0028); the BIAN detail fields are accepted and ignored. +/// +public sealed record ExchangeDemographicsRequest +{ + /// RimBank's ExchangeActionType: Verify or Reject. + [JsonPropertyName("ExchangeActionType")] + public string? ExchangeActionType { get; init; } + + /// BIAN Socio-EconomicClassification: accepted and ignored. + [JsonPropertyName("Socio-EconomicClassification")] + public JsonElement? SocioEconomicClassification { get; init; } + + /// BIAN EthnicityReligion: accepted and ignored. + [JsonPropertyName("EthnicityReligion")] + public JsonElement? EthnicityReligion { get; init; } + + /// BIAN Employment: accepted and ignored. + [JsonPropertyName("Employment")] + public JsonElement? Employment { get; init; } + + /// BIAN EmploymentHistory: accepted and ignored. + [JsonPropertyName("EmploymentHistory")] + public JsonElement? EmploymentHistory { get; init; } + + /// BIAN EducationHistory: accepted and ignored. + [JsonPropertyName("EducationHistory")] + public JsonElement? EducationHistory { get; init; } + + /// BIAN ServicingConstraints: accepted and ignored. + [JsonPropertyName("ServicingConstraints")] + public JsonElement? ServicingConstraints { get; init; } + + /// The command this request asks for, or the error of a missing or unknown action. + /// The entry. + /// The entry's Demographics. + /// The entry's version the caller last read (ADR 0027). + /// The command's idempotency key (ADR 0018). + /// The command, or the validation error. + public Result ToCommand( + PartyReferenceDataDirectoryEntryId entryId, + DemographicsId demographicsId, + long expectedVersion, + IdempotencyKey idempotencyKey) => + ExchangeActionTypes + .FromName(ExchangeActionType) + .Map(action => new ExchangeDemographics(entryId, demographicsId, expectedVersion, action, idempotencyKey)); +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/ExchangeDemographicsTool.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/ExchangeDemographicsTool.cs new file mode 100644 index 0000000..0154773 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/ExchangeDemographicsTool.cs @@ -0,0 +1,65 @@ +using System.ComponentModel; +using ModelContextProtocol.Protocol; +using ModelContextProtocol.Server; +using RimBank.Mcp; +using RimBank.SharedKernel; +using Wolverine; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// party_reference_data_directory_exchange_demographics: BIAN Demographics/Exchange, a command that +/// verifies or rejects the recorded details (ADR 0028). It dispatches , as +/// PUT …/Demographics/{demographicsid}/Exchange does, with expectedVersion in place of If-Match, and +/// answers from its acknowledgement (ADR 0039, ADR 0040). +/// +[McpServerToolType] +public sealed class ExchangeDemographicsTool +{ + /// The tool's name (ADR 0021). + public const string Name = "party_reference_data_directory_exchange_demographics"; + + /// The BIAN operation id, which names the tool's authorisation policy (ADR 0038). + public const string OperationId = "Demographics/Exchange"; + + /// Verifies or rejects the party's Demographics, as the HTTP endpoint does. + /// The entry's id. + /// The entry's DemographicsId. + /// The BIAN Exchange body with ExchangeActionType. + /// The entry's version the caller last read (ADR 0027). + /// The command's idempotency key (ADR 0018). + /// The host's message bus. + /// The call's cancellation. + /// The Demographics with the entry's new version, or the Problem Details of the error. + [McpServerTool(Name = Name, Title = "Verify or reject a party's demographics", ReadOnly = false, Destructive = false, Idempotent = true, OpenWorld = false)] + [ToolOperation(OperationId)] + [Description( + "BIAN Party Reference Data Directory: accept, verify, reject etc. the customer's demographic details. In request, " + + "ExchangeActionType is RimBank's extension field and is required: Verify or Reject. The BIAN detail fields are " + + "accepted and ignored; change the details with the Demographics Update. Details never recorded cannot be " + + "exchanged. Send the version you last read as expectedVersion: one that is no longer current is a conflict. The " + + "answer's version is the new one.")] + public static async Task ExchangeAsync( + [Description("The PartyReferenceDataDirectoryEntryId that Register returned.")] string partyReferenceDataDirectoryEntryId, + [Description("The entry's DemographicsId, from Register or Retrieve.")] string demographicsId, + [Description("The BIAN ExchangeDemographics body, with ExchangeActionType.")] ExchangeDemographicsRequest request, + [Description("The entry's version from the last Retrieve or command (the ETag on HTTP).")] long expectedVersion, + [Description("A key of 1 to 255 visible ASCII characters, unique per exchange. Reusing it with other arguments is a conflict.")] string idempotencyKey, + IMessageBus bus, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(bus); + + var command = DemographicsIds.Read(partyReferenceDataDirectoryEntryId, demographicsId) + .Bind(ids => IdempotencyKey.TryCreate(idempotencyKey) + .Bind(key => request.ToCommand(ids.EntryId, ids.DemographicsId, expectedVersion, key))); + if (command.IsFailure) + { + return ToolProblem.Create(command.Error); + } + + var outcome = await bus.InvokeAsync>(command.Value, cancellationToken); + return outcome.ToToolResult(acknowledged => ToolResults.Structured(DemographicsResult.From(acknowledged))); + } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/RetrieveDemographicsTool.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/RetrieveDemographicsTool.cs new file mode 100644 index 0000000..1d15ae0 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/RetrieveDemographicsTool.cs @@ -0,0 +1,55 @@ +using System.ComponentModel; +using ModelContextProtocol.Protocol; +using ModelContextProtocol.Server; +using RimBank.Mcp; +using RimBank.SharedKernel; +using Wolverine; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// party_reference_data_directory_retrieve_demographics: BIAN Demographics/Retrieve, a query (ADR 0024). +/// It dispatches , as GET …/Demographics/{demographicsid}/Retrieve does, and +/// answers only from the entry's inline view (tech-stack §6, §8, ADR 0039). +/// +[McpServerToolType] +public sealed class RetrieveDemographicsTool +{ + /// The tool's name (ADR 0021). + public const string Name = "party_reference_data_directory_retrieve_demographics"; + + /// The BIAN operation id, which names the tool's authorisation policy (ADR 0038). + public const string OperationId = "Demographics/Retrieve"; + + /// Retrieves the party's Demographics, as the HTTP endpoint does: the same query and errors. + /// The entry's id. + /// The entry's DemographicsId. + /// The host's message bus. + /// The call's cancellation. + /// The Demographics with the entry's version, or the Problem Details of the error. + [McpServerTool(Name = Name, Title = "Retrieve a party's demographics", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false)] + [ToolOperation(OperationId)] + [Description( + "BIAN Party Reference Data Directory: retrieve details about the customer's demographics. Returns the demographic " + + "details and whether the bank has verified them, with the entry's version (send it as expectedVersion to change " + + "the entry). Unknown details are left out, and EthnicityReligion is never returned.")] + public static async Task RetrieveAsync( + [Description("The PartyReferenceDataDirectoryEntryId that Register returned.")] string partyReferenceDataDirectoryEntryId, + [Description("The entry's DemographicsId, from Register or Retrieve.")] string demographicsId, + IMessageBus bus, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(bus); + + var ids = DemographicsIds.Read(partyReferenceDataDirectoryEntryId, demographicsId); + if (ids.IsFailure) + { + return ToolProblem.Create(ids.Error); + } + + var view = await bus.InvokeAsync>( + new RetrieveDemographics(ids.Value.EntryId, ids.Value.DemographicsId), + cancellationToken); + return view.ToToolResult(found => ToolResults.Structured(DemographicsResult.From(found))); + } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/UpdateDemographicsRequest.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/UpdateDemographicsRequest.cs new file mode 100644 index 0000000..9bd037b --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/UpdateDemographicsRequest.cs @@ -0,0 +1,53 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// The request argument of party_reference_data_directory_update_demographics: BIAN's +/// UpdateDemographics body with its property names, mirroring the HTTP request (ADR 0039, ADR 0040). It is a +/// partial update: a value left out keeps its value, an empty one clears it, and Employment replaces the whole +/// employment. EthnicityReligion is accepted and never stored. +/// +public sealed record UpdateDemographicsRequest +{ + /// BIAN Socio-EconomicClassification. + [JsonPropertyName("Socio-EconomicClassification")] + public string? SocioEconomicClassification { get; init; } + + /// BIAN EthnicityReligion: accepted and never stored. + [JsonPropertyName("EthnicityReligion")] + public JsonElement? EthnicityReligion { get; init; } + + /// BIAN Employment. + [JsonPropertyName("Employment")] + public DemographicsEmployment? Employment { get; init; } + + /// BIAN EmploymentHistory. + [JsonPropertyName("EmploymentHistory")] + public string? EmploymentHistory { get; init; } + + /// BIAN EducationHistory. + [JsonPropertyName("EducationHistory")] + public string? EducationHistory { get; init; } + + /// BIAN ServicingConstraints. + [JsonPropertyName("ServicingConstraints")] + public string? ServicingConstraints { get; init; } + + /// The command this request asks for, or the first validation error. + /// The entry. + /// The entry's Demographics. + /// The entry's version the caller last read (ADR 0027). + /// The command's idempotency key (ADR 0018). + /// The command, or the validation error. + public Result ToCommand( + PartyReferenceDataDirectoryEntryId entryId, + DemographicsId demographicsId, + long expectedVersion, + IdempotencyKey idempotencyKey) => + DemographicsChanges + .Create(SocioEconomicClassification, Employment?.ToEmployment(), EmploymentHistory, EducationHistory, ServicingConstraints) + .Map(changes => new UpdateDemographics(entryId, demographicsId, expectedVersion, changes, idempotencyKey)); +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/UpdateDemographicsTool.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/UpdateDemographicsTool.cs new file mode 100644 index 0000000..6c39f85 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Demographics/UpdateDemographicsTool.cs @@ -0,0 +1,65 @@ +using System.ComponentModel; +using ModelContextProtocol.Protocol; +using ModelContextProtocol.Server; +using RimBank.Mcp; +using RimBank.SharedKernel; +using Wolverine; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// party_reference_data_directory_update_demographics: BIAN Demographics/Update, a command (ADR 0024). It +/// dispatches , as PUT …/Demographics/{demographicsid}/Update does, with +/// expectedVersion in place of If-Match, and answers from its acknowledgement (ADR 0039, ADR 0040). +/// +[McpServerToolType] +public sealed class UpdateDemographicsTool +{ + /// The tool's name (ADR 0021). + public const string Name = "party_reference_data_directory_update_demographics"; + + /// The BIAN operation id, which names the tool's authorisation policy (ADR 0038). + public const string OperationId = "Demographics/Update"; + + /// Updates the party's Demographics, as the HTTP endpoint does: the same command, idempotency and errors. + /// The entry's id. + /// The entry's DemographicsId. + /// The BIAN Update body. + /// The entry's version the caller last read (ADR 0027). + /// The command's idempotency key (ADR 0018). + /// The host's message bus. + /// The call's cancellation. + /// The Demographics with the entry's new version, or the Problem Details of the error. + [McpServerTool(Name = Name, Title = "Update a party's demographics", ReadOnly = false, Destructive = false, Idempotent = true, OpenWorld = false)] + [ToolOperation(OperationId)] + [Description( + "BIAN Party Reference Data Directory: update details about the customer's demographics. request is the BIAN " + + "UpdateDemographics body: Socio-EconomicClassification, Employment (PartyReference, InvolvementReference), " + + "EmploymentHistory, EducationHistory and ServicingConstraints. It is a partial update: a field left out keeps its " + + "value, an empty one clears it, and Employment replaces the whole employment. Changed details become Unverified " + + "until an Exchange verifies them. EthnicityReligion is accepted and never stored. Send the version you last read " + + "as expectedVersion: one that is no longer current is a conflict. The answer's version is the new one.")] + public static async Task UpdateAsync( + [Description("The PartyReferenceDataDirectoryEntryId that Register returned.")] string partyReferenceDataDirectoryEntryId, + [Description("The entry's DemographicsId, from Register or Retrieve.")] string demographicsId, + [Description("The BIAN UpdateDemographics body, with BIAN's property names.")] UpdateDemographicsRequest request, + [Description("The entry's version from the last Retrieve or command (the ETag on HTTP).")] long expectedVersion, + [Description("A key of 1 to 255 visible ASCII characters, unique per update. Reusing it with other arguments is a conflict.")] string idempotencyKey, + IMessageBus bus, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(bus); + + var command = DemographicsIds.Read(partyReferenceDataDirectoryEntryId, demographicsId) + .Bind(ids => IdempotencyKey.TryCreate(idempotencyKey) + .Bind(key => request.ToCommand(ids.EntryId, ids.DemographicsId, expectedVersion, key))); + if (command.IsFailure) + { + return ToolProblem.Create(command.Error); + } + + var outcome = await bus.InvokeAsync>(command.Value, cancellationToken); + return outcome.ToToolResult(acknowledged => ToolResults.Structured(DemographicsResult.From(acknowledged))); + } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryTools.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryTools.cs index f8ac9e8..657afc3 100644 --- a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryTools.cs +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryTools.cs @@ -5,7 +5,7 @@ namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; /// The Party Reference Data Directory's MCP tools, registered by its host module (ADR 0021, ADR 0039). public static class PartyReferenceDataDirectoryTools { - /// Adds a tool for each implemented BIAN operation that has one (roadmap 1.16; the others in 1.17). + /// Adds a tool for every implemented BIAN operation (roadmap 1.16 and 1.17, ADR 0039, ADR 0040). /// The host's MCP server builder. /// The same builder. public static IMcpServerBuilder AddPartyReferenceDataDirectoryTools(this IMcpServerBuilder tools) @@ -14,6 +14,17 @@ public static IMcpServerBuilder AddPartyReferenceDataDirectoryTools(this IMcpSer return tools .WithTools() - .WithTools(); + .WithTools() + .WithTools() + .WithTools() + .WithTools() + .WithTools() + .WithTools() + .WithTools() + .WithTools() + .WithTools() + .WithTools() + .WithTools() + .WithTools(); } } diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/CountryModel.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/CountryModel.cs new file mode 100644 index 0000000..2ca218a --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/CountryModel.cs @@ -0,0 +1,20 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// BIAN's Reference Country object (Nationality, PartyCountryOfResidence), in requests and responses. +/// RimBank records its ISO 3166 Code (roadmap 1.18, ADR 0029); a request that sends any other part of it is refused. +/// +public sealed record CountryModel +{ + /// BIAN Code: the ISO 3166-1 alpha-2 country code, for example FR. + [JsonPropertyName("Code")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Code { get; init; } + + /// The other parts a request sent (for example Citizen), which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/DocumentDirectoryEntryModel.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/DocumentDirectoryEntryModel.cs new file mode 100644 index 0000000..33e7bb4 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/DocumentDirectoryEntryModel.cs @@ -0,0 +1,21 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// BIAN's Reference DocumentDirectoryEntryInstanceReference (a DocumentDirectoryEntry), in requests and +/// responses. RimBank records its DocumentDirectoryEntryIdentification as an opaque reference (roadmap 1.20, +/// ADR 0032); a request that sends any other part of it is refused. +/// +public sealed record DocumentDirectoryEntryModel +{ + /// BIAN DocumentDirectoryEntryIdentification (Max35Text). + [JsonPropertyName("DocumentDirectoryEntryIdentification")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? DocumentDirectoryEntryIdentification { get; init; } + + /// The other parts a request sent (for example DirectoryEntryStatus), which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/EmailAddressModel.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/EmailAddressModel.cs new file mode 100644 index 0000000..5f6cb3d --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/EmailAddressModel.cs @@ -0,0 +1,21 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// BIAN's Reference eMailAddress (a ContactPoint), in requests and responses. RimBank reads the address from +/// the ISO 20022 ElectronicAddress.EmailAddress part (roadmap 1.19, ADR 0031); a request that sends any other part +/// of it is refused. +/// +public sealed record EmailAddressModel +{ + /// ISO 20022 EmailAddress: the email address, for example name@example.com. + [JsonPropertyName("EmailAddress")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? EmailAddress { get; init; } + + /// The other parts a request sent (for example Identification), which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/GovernmentIssuedIdentityModel.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/GovernmentIssuedIdentityModel.cs new file mode 100644 index 0000000..16b456e --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/GovernmentIssuedIdentityModel.cs @@ -0,0 +1,26 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// BIAN's Reference GovernmentIssuedIdentityReference (ISO 20022 PartyIdentificationInformation), in +/// requests and responses. RimBank records the tax identification number and the national registration number +/// (ADR 0029); a request that sends any other part of it is refused. +/// +public sealed record GovernmentIssuedIdentityModel +{ + /// BIAN TaxIdentificationNumber (Max35Text). + [JsonPropertyName("TaxIdentificationNumber")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? TaxIdentificationNumber { get; init; } + + /// BIAN NationalRegistrationNumber (Max35Text). + [JsonPropertyName("NationalRegistrationNumber")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? NationalRegistrationNumber { get; init; } + + /// The other parts a request sent (for example OtherIdentification), which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/MobileNumberModel.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/MobileNumberModel.cs new file mode 100644 index 0000000..c1bdea8 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/MobileNumberModel.cs @@ -0,0 +1,21 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// BIAN's Reference CellPhoneNumber (a ContactPoint), in requests and responses. RimBank reads the number +/// from the ISO 20022 PhoneAddress.MobileNumber part (roadmap 1.19, ADR 0031); a request that sends any other part +/// of it (PhoneNumber, FaxNumber, …) is refused. +/// +public sealed record MobileNumberModel +{ + /// ISO 20022 MobileNumber: an E.164 number, for example +33612345678. + [JsonPropertyName("MobileNumber")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? MobileNumber { get; init; } + + /// The other parts a request sent (for example PhoneNumber), which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/PartyDocumentModel.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/PartyDocumentModel.cs new file mode 100644 index 0000000..f874696 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/PartyDocumentModel.cs @@ -0,0 +1,152 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// BIAN's Reference GovernmentIssuedDocumentDetails (a PartyDocument), in requests and responses. RimBank +/// records its PartyDocumentType and, in its DocumentReference, the document number, name and validity +/// period (roadmap 1.20, ADR 0032); a request that sends any other part of it, at any depth, is refused. +/// +public sealed record PartyDocumentModel +{ + /// BIAN PartyDocumentType: WorkDocument, CertificationDocument or PersonalDocument. + [JsonPropertyName("PartyDocumentType")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? PartyDocumentType { get; init; } + + /// BIAN DocumentReference: the document itself. + [JsonPropertyName("DocumentReference")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public DocumentModel? DocumentReference { get; init; } + + /// The other parts a request sent (for example PartyReference), which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } + + /// The model of a recorded document. + /// The document, or null. + /// The model, or null when no document is recorded. + public static PartyDocumentModel? From(GovernmentIssuedDocument? document) => + document switch + { + null => null, + _ => new PartyDocumentModel + { + PartyDocumentType = document.Type.ToString(), + DocumentReference = new DocumentModel + { + DocumentIdentification = new IdentifierModel { IdentifierValue = document.Number.Value }, + DocumentName = document.Name?.Value, + DocumentValidityPeriod = (document.ValidFrom, document.ValidTo) switch + { + (null, null) => null, + var (from, to) => new DateTimePeriodModel { FromDateTime = DateOf(from), ToDateTime = DateOf(to) }, + }, + }, + }, + }; + + /// The parts of this document as the core reads them. + /// The input. + public PartyDocumentInput ToInput() => + new( + PartyDocumentType, + DocumentReference?.DocumentIdentification?.IdentifierValue, + DocumentReference?.DocumentName, + DocumentReference?.DocumentValidityPeriod?.FromDateTime?.DateTimeContent, + DocumentReference?.DocumentValidityPeriod?.ToDateTime?.DateTimeContent); + + /// + /// The BIAN paths, relative to , of every part this document sends with a value that RimBank + /// does not record. + /// + /// The BIAN field that holds the document. + /// The paths, for example GovernmentIssuedDocumentDetails.DocumentReference.DocumentStatus. + public IEnumerable UnsupportedParts(string field) => + ReferenceModelParts.Present(field, Other) + .Concat(ReferenceModelParts.Present($"{field}.{GovernmentIssuedDocument.DocumentReferencePart}", DocumentReference?.Other)) + .Concat(ReferenceModelParts.Present( + $"{field}.{GovernmentIssuedDocument.DocumentIdentificationPart}", DocumentReference?.DocumentIdentification?.Other)) + .Concat(ReferenceModelParts.Present( + $"{field}.{GovernmentIssuedDocument.ValidityPeriodPart}", DocumentReference?.DocumentValidityPeriod?.Other)) + .Concat(ReferenceModelParts.Present( + $"{field}.{GovernmentIssuedDocument.FromDateTimePart}", DocumentReference?.DocumentValidityPeriod?.FromDateTime?.Other)) + .Concat(ReferenceModelParts.Present( + $"{field}.{GovernmentIssuedDocument.ToDateTimePart}", DocumentReference?.DocumentValidityPeriod?.ToDateTime?.Other)); + + private static DateTimeModel? DateOf(DateOnly? date) => + date switch + { + null => null, + { } day => new DateTimeModel { DateTimeContent = day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) }, + }; +} + +/// BIAN's Document object, inside (roadmap 1.20). +public sealed record DocumentModel +{ + /// BIAN DocumentIdentification: the document number in its IdentifierValue. + [JsonPropertyName("DocumentIdentification")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public IdentifierModel? DocumentIdentification { get; init; } + + /// BIAN DocumentName, for example Passport (Max140Text). + [JsonPropertyName("DocumentName")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? DocumentName { get; init; } + + /// BIAN DocumentValidityPeriod: the first and last day of validity. + [JsonPropertyName("DocumentValidityPeriod")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public DateTimePeriodModel? DocumentValidityPeriod { get; init; } + + /// The other parts a request sent (for example DocumentStatus), which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } +} + +/// BIAN's Identifier object, inside (roadmap 1.20). +public sealed record IdentifierModel +{ + /// BIAN IdentifierValue: the document number (Max35Text). + [JsonPropertyName("IdentifierValue")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? IdentifierValue { get; init; } + + /// The other parts a request sent (for example IdentifierIssuerReference), which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } +} + +/// BIAN's Datetimeperiod object, inside (roadmap 1.20). +public sealed record DateTimePeriodModel +{ + /// BIAN FromDateTime: the first day of validity. + [JsonPropertyName("FromDateTime")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public DateTimeModel? FromDateTime { get; init; } + + /// BIAN ToDateTime: the last day of validity. + [JsonPropertyName("ToDateTime")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public DateTimeModel? ToDateTime { get; init; } + + /// The other parts a request sent, which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } +} + +/// BIAN's Datetime object, inside (roadmap 1.20). +public sealed record DateTimeModel +{ + /// BIAN DateTimeContent: an ISO 8601 date (answered as YYYY-MM-DD) or date-time. + [JsonPropertyName("DateTimeContent")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? DateTimeContent { get; init; } + + /// The other parts a request sent (for example TimeZoneCode), which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/PartyLegalEntityModel.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/PartyLegalEntityModel.cs new file mode 100644 index 0000000..dd2f5ef --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/PartyLegalEntityModel.cs @@ -0,0 +1,20 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// BIAN's Reference PartyLegalEntityReference (ISO 20022 Party), in requests and responses. RimBank keeps +/// the party's LEI in its Identification (ADR 0029); a request that sends any other part of it is refused. +/// +public sealed record PartyLegalEntityModel +{ + /// BIAN Identification: the party's LEI (ISO 17442). + [JsonPropertyName("Identification")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Identification { get; init; } + + /// The other parts a request sent (for example ContactPoint), which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/PartyReferenceResult.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/PartyReferenceResult.cs new file mode 100644 index 0000000..59eec54 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/PartyReferenceResult.cs @@ -0,0 +1,165 @@ +using System.Globalization; +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// The result of the Reference tools: the fields of the HTTP Reference response with BIAN's names (ADR 0029), which it +/// mirrors (a parity test proves the JSON is equal, ADR 0039), and the entry's , which HTTP sends as +/// the ETag header. Update builds it from its acknowledgement, Retrieve from the entry's view (tech-stack §5). +/// Unknown values, and objects with none, are left out. +/// +/// The entry: the {partyreferencedatadirectoryid} of its operations. +/// The entry's Reference: the {referenceid} of its operations. +/// BIAN GovernmentIssuedIdentityReference. +/// BIAN PartyLegalEntityReference, with the LEI. +/// BIAN PartyFullLegalName. +/// BIAN PartyNameSalutation. +/// BIAN DateofBirth, as an ISO 8601 date (YYYY-MM-DD, ADR 0029). +/// BIAN Nationality. +/// BIAN PartyCountryOfResidence. +/// BIAN ResidencyStatus. +/// BIAN ResidentialAddress. +/// BIAN PartyAddress. +/// BIAN CorporateAddress. +/// BIAN eMailAddress. +/// BIAN CellPhoneNumber. +/// BIAN SocialNetworkContacts. +/// BIAN PartyLegalStructure, in BIAN spelling (for example Co-Operative). +/// BIAN PoliticalExposureType, in BIAN spelling. +/// BIAN PoliticalExposureDescriptionRecord. +/// BIAN CustomerSinceDate, as an ISO 8601 date (YYYY-MM-DD, ADR 0032). +/// BIAN GovernmentIssuedDocumentDetails. +/// BIAN DocumentDirectoryEntryInstanceReference. +/// BIAN CorporateCustomerReference, with the entry id in its PartyReference. +/// BIAN CorporateCustomerLegalEntityReference. +/// BIAN CompanyOfficerReference. +/// BIAN CompanyOfficerRole, as the role text (ADR 0034). +/// The entry's version: the expectedVersion of a later command (ADR 0027). +public sealed record PartyReferenceResult( + [property: JsonPropertyName("PartyReferenceDataDirectoryEntryId")] Guid PartyReferenceDataDirectoryEntryId, + [property: JsonPropertyName("ReferenceId")] Guid ReferenceId, + [property: JsonPropertyName("GovernmentIssuedIdentityReference"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] GovernmentIssuedIdentityModel? GovernmentIssuedIdentityReference, + [property: JsonPropertyName("PartyLegalEntityReference"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] PartyLegalEntityModel? PartyLegalEntityReference, + [property: JsonPropertyName("PartyFullLegalName"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? PartyFullLegalName, + [property: JsonPropertyName("PartyNameSalutation"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? PartyNameSalutation, + [property: JsonPropertyName("DateofBirth"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? DateofBirth, + [property: JsonPropertyName("Nationality"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] CountryModel? Nationality, + [property: JsonPropertyName("PartyCountryOfResidence"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] CountryModel? PartyCountryOfResidence, + [property: JsonPropertyName("ResidencyStatus"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] ResidencyStatusModel? ResidencyStatus, + [property: JsonPropertyName("ResidentialAddress"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] PostalAddressModel? ResidentialAddress, + [property: JsonPropertyName("PartyAddress"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] PostalAddressModel? PartyAddress, + [property: JsonPropertyName("CorporateAddress"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] PostalAddressModel? CorporateAddress, + [property: JsonPropertyName("eMailAddress"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] EmailAddressModel? EMailAddress, + [property: JsonPropertyName("CellPhoneNumber"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] MobileNumberModel? CellPhoneNumber, + [property: JsonPropertyName("SocialNetworkContacts"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] SocialNetworkContactModel? SocialNetworkContacts, + [property: JsonPropertyName("PartyLegalStructure"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? PartyLegalStructure, + [property: JsonPropertyName("PoliticalExposureType"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? PoliticalExposureType, + [property: JsonPropertyName("PoliticalExposureDescriptionRecord"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? PoliticalExposureDescriptionRecord, + [property: JsonPropertyName("CustomerSinceDate"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? CustomerSinceDate, + [property: JsonPropertyName("GovernmentIssuedDocumentDetails"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] PartyDocumentModel? GovernmentIssuedDocumentDetails, + [property: JsonPropertyName("DocumentDirectoryEntryInstanceReference"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] DocumentDirectoryEntryModel? DocumentDirectoryEntryInstanceReference, + [property: JsonPropertyName("CorporateCustomerReference"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] InvolvedPartyModel? CorporateCustomerReference, + [property: JsonPropertyName("CorporateCustomerLegalEntityReference"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] InvolvedPartyModel? CorporateCustomerLegalEntityReference, + [property: JsonPropertyName("CompanyOfficerReference"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] InvolvedPartyModel? CompanyOfficerReference, + [property: JsonPropertyName("CompanyOfficerRole"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? CompanyOfficerRole, + [property: JsonPropertyName("version")] long Version) +{ + /// The result for an Update's acknowledgement. + /// The outcome of . + /// The tool's result. + public static PartyReferenceResult From(UpdatePartyReferenceAcknowledged acknowledged) + { + ArgumentNullException.ThrowIfNull(acknowledged); + return From(acknowledged.EntryId, acknowledged.PartyReferenceId, acknowledged.Reference, acknowledged.Version); + } + + /// The result for the Reference section of an entry's view. + /// The entry's view, as returns it. + /// The tool's result. + public static PartyReferenceResult From(PartyReferenceDataDirectoryEntryView view) + { + ArgumentNullException.ThrowIfNull(view); + return From(view.EntryId, view.PartyReferenceId, view.CurrentReference, view.Version); + } + + private static PartyReferenceResult From( + PartyReferenceDataDirectoryEntryId entryId, + PartyReferenceId referenceId, + PartyReferenceDetails reference, + long version) + { + var identifiers = reference.Identifiers; + var names = reference.CurrentNames; + var residency = reference.CurrentResidency; + var addresses = reference.CurrentAddresses; + var contactPoints = reference.CurrentContactPoints; + var legalStanding = reference.CurrentLegalStanding; + var documents = reference.CurrentDocuments; + var corporate = reference.CurrentCorporateReferences; + return new PartyReferenceResult( + entryId.Value, + referenceId.Value, + (identifiers.TaxIdentificationNumber, identifiers.NationalRegistrationNumber) switch + { + (null, null) => null, + var (tax, national) => new GovernmentIssuedIdentityModel + { + TaxIdentificationNumber = tax?.Value, + NationalRegistrationNumber = national?.Value, + }, + }, + identifiers.LegalEntityIdentifier switch + { + null => null, + var lei => new PartyLegalEntityModel { Identification = lei.Value }, + }, + names.FullLegalName?.Value, + names.Salutation?.Value, + reference.DateOfBirth?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + CountryOf(residency.Nationality), + CountryOf(residency.CountryOfResidence), + residency.ResidencyStatus switch + { + null => null, + var status => new ResidencyStatusModel + { + StatusDescription = status.Code.ToString(), + StatusDateTime = status.StatusDateTime?.ToString("yyyy-MM-dd'T'HH:mm:ss.FFFFFFFzzz", CultureInfo.InvariantCulture), + }, + }, + PostalAddressModel.From(addresses.ResidentialAddress), + PostalAddressModel.From(addresses.PartyAddress), + PostalAddressModel.From(addresses.CorporateAddress), + contactPoints.EmailAddress is { } email ? new EmailAddressModel { EmailAddress = email.Value } : null, + contactPoints.MobileNumber is { } mobile ? new MobileNumberModel { MobileNumber = mobile.Value } : null, + contactPoints.SocialNetwork is { } social ? new SocialNetworkContactModel { URLAddress = social.Value } : null, + legalStanding.LegalStructure?.ToBianName(), + legalStanding.PoliticalExposureType?.ToBianName(), + legalStanding.PoliticalExposureDescription?.Value, + legalStanding.CustomerSince?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + PartyDocumentModel.From(documents.GovernmentIssuedDocument), + documents.DocumentDirectoryEntry is { } directory + ? new DocumentDirectoryEntryModel { DocumentDirectoryEntryIdentification = directory.Value } + : null, + InvolvedPartyOf(corporate.CorporateCustomer), + InvolvedPartyOf(corporate.LegalEntity), + InvolvedPartyOf(corporate.CompanyOfficer), + corporate.CompanyOfficerRole?.Value, + version); + } + + private static InvolvedPartyModel? InvolvedPartyOf(PartyReferenceDataDirectoryEntryId? entryId) => + entryId switch + { + null => null, + { } referenced => new InvolvedPartyModel { PartyReference = referenced.ToString() }, + }; + + private static CountryModel? CountryOf(SharedKernel.CountryCode? country) => + country switch + { + null => null, + { } code => new CountryModel { Code = code.Code }, + }; +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/PostalAddressModel.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/PostalAddressModel.cs new file mode 100644 index 0000000..c093c7c --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/PostalAddressModel.cs @@ -0,0 +1,103 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// BIAN's Reference PostalAddress object (ResidentialAddress, PartyAddress, CorporateAddress), +/// in requests and responses. RimBank records its structured parts and the ISO 3166 Country.Code (roadmap 1.19, +/// ADR 0031); a request that sends any other part of it (AddressType, Location, …) is refused. +/// +public sealed record PostalAddressModel +{ + /// BIAN Department (Max70Text). + [JsonPropertyName("Department")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Department { get; init; } + + /// BIAN SubDepartment (Max70Text). + [JsonPropertyName("SubDepartment")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? SubDepartment { get; init; } + + /// BIAN StreetName (Max35Text). + [JsonPropertyName("StreetName")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? StreetName { get; init; } + + /// BIAN StreetBuildingIdentification: the building number (Max35Text). + [JsonPropertyName("StreetBuildingIdentification")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? StreetBuildingIdentification { get; init; } + + /// BIAN BuildingName (Max35Text). + [JsonPropertyName("BuildingName")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? BuildingName { get; init; } + + /// BIAN Floor (Max16Text). + [JsonPropertyName("Floor")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Floor { get; init; } + + /// BIAN PostOfficeBox (Max16Text). + [JsonPropertyName("PostOfficeBox")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? PostOfficeBox { get; init; } + + /// BIAN PostCodeIdentification: the post code (Max16Text). + [JsonPropertyName("PostCodeIdentification")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? PostCodeIdentification { get; init; } + + /// BIAN TownName (Max35Text), required in an address. + [JsonPropertyName("TownName")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? TownName { get; init; } + + /// BIAN Country: the ISO 3166 code in its Code, required in an address. + [JsonPropertyName("Country")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public CountryModel? Country { get; init; } + + /// The other parts a request sent (for example AddressType), which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } + + /// The model of a recorded address. + /// The address, or null. + /// The model, or null when no address is recorded. + public static PostalAddressModel? From(PostalAddress? address) => + address switch + { + null => null, + _ => new PostalAddressModel + { + Department = address.Department, + SubDepartment = address.SubDepartment, + StreetName = address.StreetName, + StreetBuildingIdentification = address.StreetBuildingIdentification, + BuildingName = address.BuildingName, + Floor = address.Floor, + PostOfficeBox = address.PostOfficeBox, + PostCodeIdentification = address.PostCodeIdentification, + TownName = address.TownName, + Country = new CountryModel { Code = address.Country.Code }, + }, + }; + + /// The parts of this address as the core reads them. + /// The input. + public PostalAddressInput ToInput() => + new( + Department, + SubDepartment, + StreetName, + StreetBuildingIdentification, + BuildingName, + Floor, + PostOfficeBox, + PostCodeIdentification, + TownName, + Country is { } country ? new PartyCountryInput(country.Code) : null); +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/ReferenceIds.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/ReferenceIds.cs new file mode 100644 index 0000000..a7e3f98 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/ReferenceIds.cs @@ -0,0 +1,21 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// Reads the entry and Reference ids of a Reference tool, with the errors HTTP gives for its route values. +internal static class ReferenceIds +{ + /// The two ids, or the error of the first invalid one. + /// The entry's id, as sent. + /// The Reference id, as sent. + /// The typed ids, or the validation error. + public static Result<(PartyReferenceDataDirectoryEntryId EntryId, PartyReferenceId PartyReferenceId)> Read( + string partyReferenceDataDirectoryEntryId, + string referenceId) => + (PartyReferenceDataDirectoryEntryId.TryCreate(partyReferenceDataDirectoryEntryId), PartyReferenceId.TryCreate(referenceId)) switch + { + ({ IsFailure: true }, _) => PartyReferenceDataDirectoryEntryErrors.EntryIdInvalid, + (_, { IsFailure: true }) => PartyReferenceErrors.ReferenceIdInvalid, + var (entryId, reference) => (entryId.Value, reference.Value), + }; +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/ReferenceModelParts.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/ReferenceModelParts.cs new file mode 100644 index 0000000..01d80f7 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/ReferenceModelParts.cs @@ -0,0 +1,15 @@ +using System.Text.Json; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// Names the parts of a Reference request object that were sent with a value but are not recorded (ADR 0029). +internal static class ReferenceModelParts +{ + /// The names of the properties sent with a value (not null). + public static IEnumerable Present(Dictionary? properties) => + (properties ?? []).Where(property => property.Value.ValueKind != JsonValueKind.Null).Select(property => property.Key); + + /// The BIAN paths of the properties sent with a value, under . + public static IEnumerable Present(string field, Dictionary? properties) => + Present(properties).Select(name => $"{field}.{name}"); +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/ResidencyStatusModel.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/ResidencyStatusModel.cs new file mode 100644 index 0000000..ef16082 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/ResidencyStatusModel.cs @@ -0,0 +1,26 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// BIAN's Reference ResidencyStatus (ISO 20022 Status), in requests and responses. RimBank records the code in +/// StatusDescription and the time it was assigned in StatusDateTime (roadmap 1.18, ADR 0029); a request that +/// sends any other part of it is refused. +/// +public sealed record ResidencyStatusModel +{ + /// BIAN StatusDescription: Resident or NonResident. + [JsonPropertyName("StatusDescription")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? StatusDescription { get; init; } + + /// BIAN StatusDateTime: when the status was assigned, an ISO 8601 date-time. + [JsonPropertyName("StatusDateTime")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? StatusDateTime { get; init; } + + /// The other parts a request sent (for example StatusReason), which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/RetrievePartyReferenceTool.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/RetrievePartyReferenceTool.cs new file mode 100644 index 0000000..134f49b --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/RetrievePartyReferenceTool.cs @@ -0,0 +1,59 @@ +using System.ComponentModel; +using ModelContextProtocol.Protocol; +using ModelContextProtocol.Server; +using RimBank.Mcp; +using RimBank.SharedKernel; +using Wolverine; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// party_reference_data_directory_retrieve_reference: BIAN Reference/Retrieve, a query (ADR 0024). It +/// dispatches , as GET …/Reference/{referenceid}/Retrieve does, and answers +/// only from the entry's inline view (tech-stack §6, §8, ADR 0039). +/// +[McpServerToolType] +public sealed class RetrievePartyReferenceTool +{ + /// The tool's name (ADR 0021). + public const string Name = "party_reference_data_directory_retrieve_reference"; + + /// The BIAN operation id, which names the tool's authorisation policy (ADR 0038). + public const string OperationId = "Reference/Retrieve"; + + /// Retrieves the party's Reference, as the HTTP endpoint does: the same query and errors. + /// The entry's id. + /// The entry's ReferenceId. + /// The host's message bus. + /// The call's cancellation. + /// The Reference with the entry's version, or the Problem Details of the error. + [McpServerTool(Name = Name, Title = "Retrieve a party's reference", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false)] + [ToolOperation(OperationId)] + [Description( + "BIAN Party Reference Data Directory: retrieve details about the customer's reference entry. Returns the tax " + + "identification and national registration numbers in GovernmentIssuedIdentityReference, the LEI in " + + "PartyLegalEntityReference.Identification, PartyFullLegalName, PartyNameSalutation, DateofBirth (YYYY-MM-DD), " + + "Nationality and PartyCountryOfResidence (ISO 3166 Code), ResidencyStatus, the ResidentialAddress, PartyAddress " + + "and CorporateAddress postal addresses, the eMailAddress, CellPhoneNumber and SocialNetworkContacts contact " + + "points, the declared legal standing and documents, and the corporate and officer references, with the entry's " + + "version (send it as expectedVersion to change the entry). Unknown values are left out.")] + public static async Task RetrieveAsync( + [Description("The PartyReferenceDataDirectoryEntryId that Register returned.")] string partyReferenceDataDirectoryEntryId, + [Description("The entry's ReferenceId, from Register or Retrieve.")] string referenceId, + IMessageBus bus, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(bus); + + var ids = ReferenceIds.Read(partyReferenceDataDirectoryEntryId, referenceId); + if (ids.IsFailure) + { + return ToolProblem.Create(ids.Error); + } + + var view = await bus.InvokeAsync>( + new RetrievePartyReference(ids.Value.EntryId, ids.Value.PartyReferenceId), + cancellationToken); + return view.ToToolResult(found => ToolResults.Structured(PartyReferenceResult.From(found))); + } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/SocialNetworkContactModel.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/SocialNetworkContactModel.cs new file mode 100644 index 0000000..d58927b --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/SocialNetworkContactModel.cs @@ -0,0 +1,21 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// BIAN's Reference SocialNetworkContacts (a ContactPoint), in requests and responses. RimBank reads the +/// profile from the ISO 20022 ElectronicAddress.URLAddress part (roadmap 1.19, ADR 0031); a request that sends any +/// other part of it is refused. +/// +public sealed record SocialNetworkContactModel +{ + /// ISO 20022 URLAddress: an absolute https URL, for example https://www.linkedin.com/in/name. + [JsonPropertyName("URLAddress")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? URLAddress { get; init; } + + /// The other parts a request sent (for example BICAddress), which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceRequest.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceRequest.cs new file mode 100644 index 0000000..36598af --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceRequest.cs @@ -0,0 +1,246 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// The request argument of party_reference_data_directory_update_reference, mirroring the HTTP request +/// (ADR 0039, ADR 0040): BIAN's UpdateReference with its property names (ADR 0024, ADR 0029), as a partial update +/// of the Reference. A value left out keeps its value, and an empty one (or an object whose parts are all empty) clears it. Parts of BIAN objects +/// RimBank does not record are refused; properties that are not BIAN's are ignored. +/// +public sealed record UpdatePartyReferenceRequest +{ + /// BIAN GovernmentIssuedIdentityReference: the tax identification and national registration numbers. + [JsonPropertyName("GovernmentIssuedIdentityReference")] + public GovernmentIssuedIdentityModel? GovernmentIssuedIdentityReference { get; init; } + + /// BIAN PartyLegalEntityReference: the LEI in its Identification. + [JsonPropertyName("PartyLegalEntityReference")] + public PartyLegalEntityModel? PartyLegalEntityReference { get; init; } + + /// BIAN PartyFullLegalName (Max140Text). + [JsonPropertyName("PartyFullLegalName")] + public string? PartyFullLegalName { get; init; } + + /// BIAN PartyNameSalutation (Max35Text). + [JsonPropertyName("PartyNameSalutation")] + public string? PartyNameSalutation { get; init; } + + /// BIAN DateofBirth: an ISO 8601 date, or a date-time whose date is kept as written. + [JsonPropertyName("DateofBirth")] + public string? DateofBirth { get; init; } + + /// BIAN Nationality: the ISO 3166 code in its Code. + [JsonPropertyName("Nationality")] + public CountryModel? Nationality { get; init; } + + /// BIAN PartyCountryOfResidence: the ISO 3166 code in its Code. + [JsonPropertyName("PartyCountryOfResidence")] + public CountryModel? PartyCountryOfResidence { get; init; } + + /// BIAN ResidencyStatus: Resident or NonResident in its StatusDescription. + [JsonPropertyName("ResidencyStatus")] + public ResidencyStatusModel? ResidencyStatus { get; init; } + + /// BIAN ResidentialAddress (1.19): an ISO 20022 postal address. + [JsonPropertyName("ResidentialAddress")] + public PostalAddressModel? ResidentialAddress { get; init; } + + /// BIAN PartyAddress (1.19): an ISO 20022 postal address. + [JsonPropertyName("PartyAddress")] + public PostalAddressModel? PartyAddress { get; init; } + + /// BIAN CorporateAddress (1.19): an ISO 20022 postal address. + [JsonPropertyName("CorporateAddress")] + public PostalAddressModel? CorporateAddress { get; init; } + + /// BIAN eMailAddress (1.19): the address in its EmailAddress (ADR 0031). + [JsonPropertyName("eMailAddress")] + public EmailAddressModel? EMailAddress { get; init; } + + /// BIAN CellPhoneNumber (1.19): the E.164 number in its MobileNumber (ADR 0031). + [JsonPropertyName("CellPhoneNumber")] + public MobileNumberModel? CellPhoneNumber { get; init; } + + /// BIAN SocialNetworkContacts (1.19): the https profile URL in its URLAddress (ADR 0031). + [JsonPropertyName("SocialNetworkContacts")] + public SocialNetworkContactModel? SocialNetworkContacts { get; init; } + + /// + /// BIAN PartyLegalStructure (1.20), as a plain string (BIAN's enum wrapper flattened, ADR 0024), for example + /// PrivateLimitedCompany or Co-Operative. + /// + [JsonPropertyName("PartyLegalStructure")] + public string? PartyLegalStructure { get; init; } + + /// + /// BIAN PoliticalExposureType (1.20), as a plain string: Politicalexposureforeign, + /// Politicalexposuredomestic or Nopoliticalexposure. + /// + [JsonPropertyName("PoliticalExposureType")] + public string? PoliticalExposureType { get; init; } + + /// BIAN PoliticalExposureDescriptionRecord (1.20, Max350Text), only with a foreign or domestic exposure. + [JsonPropertyName("PoliticalExposureDescriptionRecord")] + public string? PoliticalExposureDescriptionRecord { get; init; } + + /// BIAN CustomerSinceDate (1.20): an ISO 8601 date, or a date-time whose date is kept as written. + [JsonPropertyName("CustomerSinceDate")] + public string? CustomerSinceDate { get; init; } + + /// BIAN GovernmentIssuedDocumentDetails (1.20): the declared identity document. + [JsonPropertyName("GovernmentIssuedDocumentDetails")] + public PartyDocumentModel? GovernmentIssuedDocumentDetails { get; init; } + + /// BIAN DocumentDirectoryEntryInstanceReference (1.20): the opaque document directory reference. + [JsonPropertyName("DocumentDirectoryEntryInstanceReference")] + public DocumentDirectoryEntryModel? DocumentDirectoryEntryInstanceReference { get; init; } + + /// + /// BIAN CorporateCustomerReference (1.21, ADR 0034): the company, as the id of a registered organisation in its + /// PartyReference. + /// + [JsonPropertyName("CorporateCustomerReference")] + public InvolvedPartyModel? CorporateCustomerReference { get; init; } + + /// + /// BIAN CorporateCustomerLegalEntityReference (1.21): the legal entity, as the id of a registered organisation in + /// its PartyReference. + /// + [JsonPropertyName("CorporateCustomerLegalEntityReference")] + public InvolvedPartyModel? CorporateCustomerLegalEntityReference { get; init; } + + /// + /// BIAN CompanyOfficerReference (1.21): the company officer, as the id of a registered person in its + /// PartyReference. + /// + [JsonPropertyName("CompanyOfficerReference")] + public InvolvedPartyModel? CompanyOfficerReference { get; init; } + + /// + /// BIAN CompanyOfficerRole (1.21, Max35Text): the officer's role as a plain string, for example Director. + /// BIAN types it as a Party, which has no role property (ADR 0034): an object is read for its parts, which are + /// all refused, and an empty one clears the role. + /// + [JsonPropertyName("CompanyOfficerRole")] + public JsonElement? CompanyOfficerRole { get; init; } + + /// Every other property sent: the BIAN Reference fields RimBank does not record yet are found here. + [JsonExtensionData] + public Dictionary? Other { get; init; } + + /// + /// The BIAN names of the Reference fields this request sends with a value that RimBank does not record: the staged + /// top-level fields (, matched without regard to case) and every other part + /// of the objects it reads. A field sent as null is not sent. + /// + /// The field names, in the order sent. + public IReadOnlyList UnsupportedFields() => + [ + .. Present(Other) + .Select(name => PartyReferenceFields.Staged.Keys.FirstOrDefault(staged => string.Equals(staged, name, StringComparison.OrdinalIgnoreCase))) + .OfType(), + .. PartsOf(PartyReferenceFields.GovernmentIssuedIdentityReference, GovernmentIssuedIdentityReference?.Other), + .. PartsOf(PartyReferenceFields.PartyLegalEntityReference, PartyLegalEntityReference?.Other), + .. PartsOf(PartyReferenceFields.Nationality, Nationality?.Other), + .. PartsOf(PartyReferenceFields.PartyCountryOfResidence, PartyCountryOfResidence?.Other), + .. PartsOf(PartyReferenceFields.ResidencyStatus, ResidencyStatus?.Other), + .. AddressPartsOf(PartyReferenceFields.ResidentialAddress, ResidentialAddress), + .. AddressPartsOf(PartyReferenceFields.PartyAddress, PartyAddress), + .. AddressPartsOf(PartyReferenceFields.CorporateAddress, CorporateAddress), + .. PartsOf(PartyReferenceFields.EMailAddress, EMailAddress?.Other), + .. PartsOf(PartyReferenceFields.CellPhoneNumber, CellPhoneNumber?.Other), + .. PartsOf(PartyReferenceFields.SocialNetworkContacts, SocialNetworkContacts?.Other), + .. GovernmentIssuedDocumentDetails?.UnsupportedParts(PartyReferenceFields.GovernmentIssuedDocumentDetails) ?? [], + .. PartsOf(PartyReferenceFields.DocumentDirectoryEntryInstanceReference, DocumentDirectoryEntryInstanceReference?.Other), + .. PartsOf(PartyReferenceFields.CorporateCustomerReference, CorporateCustomerReference?.Other), + .. PartsOf(PartyReferenceFields.CorporateCustomerLegalEntityReference, CorporateCustomerLegalEntityReference?.Other), + .. PartsOf(PartyReferenceFields.CompanyOfficerReference, CompanyOfficerReference?.Other), + .. RolePartsOf(CompanyOfficerRole), + ]; + + /// + /// The command this request asks for, party.reference-field-not-supported for a field RimBank does not record + /// yet, or party.reference-invalid for an invalid value. + /// + /// The entry the route names. + /// The Reference the route names. + /// The version from If-Match (ADR 0027). + /// The request's Idempotency-Key (ADR 0018). + /// The command, or the validation error. + public Result ToCommand( + PartyReferenceDataDirectoryEntryId entryId, + PartyReferenceId referenceId, + long expectedVersion, + IdempotencyKey idempotencyKey) => + PartyReferenceChanges + .Create( + new PartyReferenceInput( + GovernmentIssuedIdentityReference?.TaxIdentificationNumber, + GovernmentIssuedIdentityReference?.NationalRegistrationNumber, + PartyLegalEntityReference?.Identification, + PartyFullLegalName, + PartyNameSalutation, + DateofBirth, + Nationality is { } nationality ? new PartyCountryInput(nationality.Code) : null, + PartyCountryOfResidence is { } residence ? new PartyCountryInput(residence.Code) : null, + ResidencyStatus is { } status ? new ResidencyStatusInput(status.StatusDescription, status.StatusDateTime) : null, + ResidentialAddress?.ToInput(), + PartyAddress?.ToInput(), + CorporateAddress?.ToInput(), + EMailAddress is { } email ? email.EmailAddress ?? string.Empty : null, + CellPhoneNumber is { } phone ? phone.MobileNumber ?? string.Empty : null, + SocialNetworkContacts is { } social ? social.URLAddress ?? string.Empty : null, + PartyLegalStructure, + PoliticalExposureType, + PoliticalExposureDescriptionRecord, + CustomerSinceDate, + GovernmentIssuedDocumentDetails?.ToInput(), + DocumentDirectoryEntryInstanceReference is { } directory + ? directory.DocumentDirectoryEntryIdentification ?? string.Empty + : null, + PartyReferenceOf(CorporateCustomerReference), + PartyReferenceOf(CorporateCustomerLegalEntityReference), + PartyReferenceOf(CompanyOfficerReference), + RoleOf(CompanyOfficerRole)), + UnsupportedFields()) + .Map(changes => new UpdatePartyReference(entryId, referenceId, expectedVersion, changes, idempotencyKey)); + + private static string? PartyReferenceOf(InvolvedPartyModel? reference) => + reference switch + { + null => null, + _ => reference.PartyReference ?? string.Empty, + }; + + // A string is the role; null is not sent; an object (the BIAN Party shape) has no role, so it clears the role and its + // parts are reported as unsupported; any other JSON value is read as its text, which the role then checks. + private static string? RoleOf(JsonElement? role) => + role switch + { + null or { ValueKind: JsonValueKind.Null or JsonValueKind.Undefined } => null, + { ValueKind: JsonValueKind.String } text => text.GetString(), + { ValueKind: JsonValueKind.Object } => string.Empty, + { } other => other.GetRawText(), + }; + + private static IEnumerable RolePartsOf(JsonElement? role) => + role switch + { + { ValueKind: JsonValueKind.Object } parts => parts.EnumerateObject() + .Where(part => part.Value.ValueKind != JsonValueKind.Null) + .Select(part => $"{PartyReferenceFields.CompanyOfficerRole}.{part.Name}"), + _ => [], + }; + + private static IEnumerable AddressPartsOf(string field, PostalAddressModel? address) => + PartsOf(field, address?.Other).Concat(PartsOf($"{field}.{PostalAddress.CountryPart}", address?.Country?.Other)); + + private static IEnumerable PartsOf(string field, Dictionary? parts) => + ReferenceModelParts.Present(field, parts); + + private static IEnumerable Present(Dictionary? properties) => + ReferenceModelParts.Present(properties); +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceTool.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceTool.cs new file mode 100644 index 0000000..195e48c --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceTool.cs @@ -0,0 +1,81 @@ +using System.ComponentModel; +using ModelContextProtocol.Protocol; +using ModelContextProtocol.Server; +using RimBank.Mcp; +using RimBank.SharedKernel; +using Wolverine; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// party_reference_data_directory_update_reference: BIAN Reference/Update, a command (ADR 0024, ADR 0029). +/// It dispatches , as PUT …/Reference/{referenceid}/Update does, with +/// expectedVersion in place of If-Match, and answers from its acknowledgement (ADR 0039, ADR 0040). +/// +[McpServerToolType] +public sealed class UpdatePartyReferenceTool +{ + /// The tool's name (ADR 0021). + public const string Name = "party_reference_data_directory_update_reference"; + + /// The BIAN operation id, which names the tool's authorisation policy (ADR 0038). + public const string OperationId = "Reference/Update"; + + /// Updates the party's Reference, as the HTTP endpoint does: the same command, idempotency and errors. + /// The entry's id. + /// The entry's ReferenceId. + /// The BIAN Update body. + /// The entry's version the caller last read (ADR 0027). + /// The command's idempotency key (ADR 0018). + /// The host's message bus. + /// The call's cancellation. + /// The Reference with the entry's new version, or the Problem Details of the error. + [McpServerTool(Name = Name, Title = "Update a party's reference", ReadOnly = false, Destructive = false, Idempotent = true, OpenWorld = false)] + [ToolOperation(OperationId)] + [Description( + "BIAN Party Reference Data Directory: update details about the customer's reference entry. request is the BIAN " + + "UpdateReference body, a partial update: GovernmentIssuedIdentityReference.TaxIdentificationNumber and " + + "NationalRegistrationNumber, the LEI (ISO 17442, check digits verified) in PartyLegalEntityReference.Identification, " + + "PartyFullLegalName (at most 140 characters), PartyNameSalutation (at most 35), DateofBirth (an ISO 8601 date, " + + "from 1900-01-01 to today), Nationality.Code and PartyCountryOfResidence.Code (ISO 3166-1 alpha-2), and " + + "ResidencyStatus (StatusDescription Resident or NonResident, and an optional StatusDateTime). ResidentialAddress, " + + "PartyAddress and CorporateAddress are ISO 20022 postal addresses: Department, SubDepartment, StreetName, " + + "StreetBuildingIdentification, BuildingName, Floor, PostOfficeBox, PostCodeIdentification, TownName and " + + "Country.Code, with TownName and Country required. eMailAddress.EmailAddress, CellPhoneNumber.MobileNumber (E.164, " + + "for example +33612345678) and SocialNetworkContacts.URLAddress (an https URL) are the contact points. The party's " + + "declared legal standing is PartyLegalStructure (the BIAN code list, for example PrivateLimitedCompany or " + + "Co-Operative), PoliticalExposureType (Politicalexposureforeign, Politicalexposuredomestic or " + + "Nopoliticalexposure), PoliticalExposureDescriptionRecord (at most 350 characters, only with a foreign or domestic " + + "exposure) and CustomerSinceDate (an ISO 8601 date, not before DateofBirth). GovernmentIssuedDocumentDetails " + + "records PartyDocumentType and, in DocumentReference, DocumentIdentification.IdentifierValue (both required), " + + "DocumentName and DocumentValidityPeriod (FromDateTime and ToDateTime DateTimeContent dates); " + + "DocumentDirectoryEntryInstanceReference records DocumentDirectoryEntryIdentification. On an organisation only, " + + "CorporateCustomerReference and CorporateCustomerLegalEntityReference name registered organisations and " + + "CompanyOfficerReference a registered person, each in its PartyReference, with CompanyOfficerRole as text. A " + + "value left out keeps its value, an empty one clears it, and a given address or document replaces the whole of " + + "it. Other parts of these objects are refused with party.reference-field-not-supported. Send the version you " + + "last read as expectedVersion: one that is no longer current is a conflict. The answer's version is the new one.")] + public static async Task UpdateAsync( + [Description("The PartyReferenceDataDirectoryEntryId that Register returned.")] string partyReferenceDataDirectoryEntryId, + [Description("The entry's ReferenceId, from Register or Retrieve.")] string referenceId, + [Description("The BIAN UpdateReference body, with BIAN's property names.")] UpdatePartyReferenceRequest request, + [Description("The entry's version from the last Retrieve or command (the ETag on HTTP).")] long expectedVersion, + [Description("A key of 1 to 255 visible ASCII characters, unique per update. Reusing it with other arguments is a conflict.")] string idempotencyKey, + IMessageBus bus, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(bus); + + var command = ReferenceIds.Read(partyReferenceDataDirectoryEntryId, referenceId) + .Bind(ids => IdempotencyKey.TryCreate(idempotencyKey) + .Bind(key => request.ToCommand(ids.EntryId, ids.PartyReferenceId, expectedVersion, key))); + if (command.IsFailure) + { + return ToolProblem.Create(command.Error); + } + + var outcome = await bus.InvokeAsync>(command.Value, cancellationToken); + return outcome.ToToolResult(acknowledged => ToolResults.Structured(PartyReferenceResult.From(acknowledged))); + } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryRequest.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryRequest.cs new file mode 100644 index 0000000..17fdce4 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryRequest.cs @@ -0,0 +1,45 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// The request argument of party_reference_data_directory_update: BIAN's +/// UpdatePartyReferenceDataDirectoryEntry body with its property names, mirroring the HTTP request (a parity test +/// proves both give the same answer, ADR 0039, ADR 0040). PartyType is optional; the other BIAN fields are +/// accepted and ignored, as on HTTP. +/// +public sealed record UpdatePartyReferenceDataDirectoryEntryRequest +{ + /// BIAN PartyReference: accepted and ignored. + [JsonPropertyName("PartyReference")] + public JsonElement? PartyReference { get; init; } + + /// BIAN DirectoryEntryDateType: accepted and ignored. + [JsonPropertyName("DirectoryEntryDateType")] + public JsonElement? DirectoryEntryDateType { get; init; } + + /// BIAN DirectoryEntryDate: accepted and ignored. + [JsonPropertyName("DirectoryEntryDate")] + public JsonElement? DirectoryEntryDate { get; init; } + + /// BIAN PartyType: Person or Organisation; left out keeps the current one. + [JsonPropertyName("PartyType")] + public string? PartyType { get; init; } + + /// The command this request asks for, or the error of an invalid PartyType. + /// The entry. + /// The entry's version the caller last read (ADR 0027). + /// The command's idempotency key (ADR 0018). + /// The command, or the validation error. + public Result ToCommand( + PartyReferenceDataDirectoryEntryId entryId, + long expectedVersion, + IdempotencyKey idempotencyKey) => + PartyTypes.FromOptionalBianName(PartyType) switch + { + null => new UpdatePartyReferenceDataDirectoryEntry(entryId, expectedVersion, null, idempotencyKey), + var partyType => partyType.Map(type => new UpdatePartyReferenceDataDirectoryEntry(entryId, expectedVersion, type, idempotencyKey)), + }; +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryResult.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryResult.cs new file mode 100644 index 0000000..eff3bf9 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryResult.cs @@ -0,0 +1,51 @@ +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// The result of party_reference_data_directory_update: the fields of the HTTP Update response with BIAN's names, +/// which it mirrors (a parity test proves the JSON is equal, ADR 0039), and the entry's new , which +/// HTTP sends as the ETag header. It is built from the command's acknowledgement, never from a read model. +/// +/// The entry. +/// BIAN PartyType: Person or Organisation. +/// BIAN DirectoryEntryDateType: OpenDate. +/// BIAN DirectoryEntryDate: when the directory registered the party. +/// When this update was recorded. +/// The entry's Demographics. +/// The entry's Reference. +/// The entry's BankRelations. +/// The entry's new version: the expectedVersion of the next command (ADR 0027). +public sealed record UpdatePartyReferenceDataDirectoryEntryResult( + [property: JsonPropertyName("PartyReferenceDataDirectoryEntryId")] Guid PartyReferenceDataDirectoryEntryId, + [property: JsonPropertyName("PartyType")] string PartyType, + [property: JsonPropertyName("DirectoryEntryDateType")] string DirectoryEntryDateType, + [property: JsonPropertyName("DirectoryEntryDate")] DateTimeOffset DirectoryEntryDate, + [property: JsonPropertyName("RefreshDate")] DateTimeOffset RefreshDate, + [property: JsonPropertyName("DemographicsId")] Guid DemographicsId, + [property: JsonPropertyName("ReferenceId")] Guid ReferenceId, + [property: JsonPropertyName("BankRelationsId")] Guid BankRelationsId, + [property: JsonPropertyName("version")] long Version) +{ + /// The DirectoryEntryDateType of the entry's open date. + public const string OpenDate = "OpenDate"; + + /// The result for . + /// The outcome of . + /// The tool's result. + public static UpdatePartyReferenceDataDirectoryEntryResult From(UpdatePartyReferenceDataDirectoryEntryAcknowledged acknowledged) + { + ArgumentNullException.ThrowIfNull(acknowledged); + + return new UpdatePartyReferenceDataDirectoryEntryResult( + acknowledged.EntryId.Value, + acknowledged.PartyType.ToString(), + OpenDate, + acknowledged.OpenDate, + acknowledged.RefreshDate, + acknowledged.DemographicsId.Value, + acknowledged.PartyReferenceId.Value, + acknowledged.BankRelationsId.Value, + acknowledged.Version); + } +} diff --git a/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryTool.cs b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryTool.cs new file mode 100644 index 0000000..5cb8499 --- /dev/null +++ b/src/RimBank.Mcp/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryTool.cs @@ -0,0 +1,68 @@ +using System.ComponentModel; +using ModelContextProtocol.Protocol; +using ModelContextProtocol.Server; +using RimBank.Mcp; +using RimBank.SharedKernel; +using Wolverine; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp; + +/// +/// party_reference_data_directory_update: BIAN PartyReferenceDataDirectoryEntry/Update, a command +/// (ADR 0024). It dispatches , as +/// PUT /PartyReferenceDataDirectory/{id}/Update does, with expectedVersion in place of If-Match, and +/// answers from its acknowledgement, never from a read model (tech-stack §6, ADR 0039, ADR 0040). +/// +[McpServerToolType] +public sealed class UpdatePartyReferenceDataDirectoryEntryTool +{ + /// The tool's name (ADR 0021). + public const string Name = "party_reference_data_directory_update"; + + /// The BIAN operation id, which names the tool's authorisation policy (ADR 0038). + public const string OperationId = "PartyReferenceDataDirectoryEntry/Update"; + + /// Updates a directory entry, as the HTTP endpoint does: the same command, idempotency and errors. + /// The entry's id. + /// The BIAN Update body. + /// The entry's version the caller last read (ADR 0027). + /// The command's idempotency key (ADR 0018). + /// The host's message bus. + /// The call's cancellation. + /// The updated entry with its new version, or the Problem Details of the error. + [McpServerTool(Name = Name, Title = "Update a party directory entry", ReadOnly = false, Destructive = false, Idempotent = true, OpenWorld = false)] + [ToolOperation(OperationId)] + [Description( + "BIAN Party Reference Data Directory: update details about the customer's directory entry, and record the time of " + + "the update as its RefreshDate. In request, PartyType (Person or Organisation) is optional: leave it out to keep " + + "the current one; PartyReference and the directory entry date fields are accepted and ignored. Send the version " + + "you last read as expectedVersion: one that is no longer current is a conflict, so retrieve the entry and retry. " + + "The answer's version is the new one.")] + public static async Task UpdateAsync( + [Description("The PartyReferenceDataDirectoryEntryId that Register returned.")] string partyReferenceDataDirectoryEntryId, + [Description("The BIAN UpdatePartyReferenceDataDirectoryEntry body, with BIAN's property names.")] UpdatePartyReferenceDataDirectoryEntryRequest request, + [Description("The entry's version from the last Retrieve or command (the ETag on HTTP).")] long expectedVersion, + [Description("A key of 1 to 255 visible ASCII characters, unique per update. Reusing it with other arguments is a conflict.")] string idempotencyKey, + IMessageBus bus, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(bus); + + var entryId = PartyReferenceDataDirectoryEntryId.TryCreate(partyReferenceDataDirectoryEntryId); + if (entryId.IsFailure) + { + return ToolProblem.Create(PartyReferenceDataDirectoryEntryErrors.EntryIdInvalid); + } + + var command = IdempotencyKey.TryCreate(idempotencyKey) + .Bind(key => request.ToCommand(entryId.Value, expectedVersion, key)); + if (command.IsFailure) + { + return ToolProblem.Create(command.Error); + } + + var outcome = await bus.InvokeAsync>(command.Value, cancellationToken); + return outcome.ToToolResult(acknowledged => ToolResults.Structured(UpdatePartyReferenceDataDirectoryEntryResult.From(acknowledged))); + } +} diff --git a/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationParityTests.cs b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationParityTests.cs new file mode 100644 index 0000000..a0bc42d --- /dev/null +++ b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationParityTests.cs @@ -0,0 +1,110 @@ +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp.Tests; + +// Roadmap 1.17: the Associations tools answer as their HTTP endpoints do: the same body with the association's ETag as +// version, and the same Problem Details (ADR 0039, ADR 0040). +public sealed class PartyAssociationParityTests(PostgresqlServer server) +{ + private const string Period = """, "AssociationValidFromToDate": { "FromDateTime": "2024-01-01", "ToDateTime": "2030-12-31T12:00:00Z" } }"""; + + private static readonly string[] _ids = ["AssociationsId"]; + + [Fact] + public async Task Register_gives_the_http_body_and_the_etag_as_version() + { + await using var host = await server.StartHostAsync(); + var owner = await Entry.RegisterAsync(host); + var associate = await Entry.RegisterAsync(host); + var body = WithPeriod(associate.Id, "PartyActsOnBehalfOfParty"); + + var http = await Parity.HttpAsync(host, HttpMethod.Post, $"/PartyReferenceDataDirectory/{owner.Id}/Associations/Register", 200, body, PartyTools.Key("http")); + var tool = await PartyAssociationToolTests.RegisterAsync(host, owner.Id, body, PartyTools.Key("mcp")); + + await Parity.ShouldMirrorAsync(http, tool, _ids); + } + + [Fact] + public async Task Update_and_retrieve_give_the_http_body_and_the_etag_as_version() + { + await using var host = await server.StartHostAsync(); + var owner = await Entry.RegisterAsync(host); + var associate = await Entry.RegisterAsync(host); + var overHttp = await RegisterAsync(host, owner, associate); + var overMcp = await RegisterAsync(host, owner, associate); + const string body = """{ "AssociateType": "PartyIsContactPointForParty", "AssociationValidFromToDate": { "ToDateTime": "2031-01-01" } }"""; + + var http = await Parity.HttpAsync(host, HttpMethod.Put, Url(owner, overHttp, "Update"), 200, body, PartyTools.Key("http"), 1); + var tool = await PartyAssociationToolTests.UpdateAsync(host, owner.Id, overMcp, body, 1, PartyTools.Key("mcp")); + await Parity.ShouldMirrorAsync(http, tool, _ids); + + var httpRetrieve = await Parity.HttpAsync(host, HttpMethod.Get, Url(owner, overMcp, "Retrieve"), 200); + var toolRetrieve = await PartyAssociationToolTests.RetrieveAsync(host, owner.Id.ToString(), overMcp.ToString()); + await Parity.ShouldMirrorAsync(httpRetrieve, toolRetrieve); + } + + [Theory] + [InlineData("{}")] + [InlineData("""{ "AssociateType": "PartyIsFriendOfParty", "AssociateReference": { "PartyReference": "x" } }""")] + [InlineData("""{ "AssociateReference": { "PartyReference": "x", "InvolvementReference": "Guarantor" }, "productinstancereference": { "ProductInstanceReference": "P-1" } }""")] + public async Task An_invalid_or_refused_registration_is_the_same_problem(string body) + { + await using var host = await server.StartHostAsync(); + var owner = await Entry.RegisterAsync(host); + + var http = await Parity.HttpAsync(host, HttpMethod.Post, $"/PartyReferenceDataDirectory/{owner.Id}/Associations/Register", 400, body, PartyTools.Key("http")); + var tool = await PartyAssociationToolTests.RegisterAsync(host, owner.Id, body, PartyTools.Key("mcp")); + + await Parity.ShouldBeSameProblemAsync(http, tool); + } + + [Fact] + public async Task An_unregistered_associate_is_the_same_problem() + { + await using var host = await server.StartHostAsync(); + var owner = await Entry.RegisterAsync(host); + var body = PartyAssociationToolTests.Body(Guid.CreateVersion7(), "PartyIsMarriedToParty"); + + var http = await Parity.HttpAsync(host, HttpMethod.Post, $"/PartyReferenceDataDirectory/{owner.Id}/Associations/Register", 422, body, PartyTools.Key("http")); + var tool = await PartyAssociationToolTests.RegisterAsync(host, owner.Id, body, PartyTools.Key("mcp")); + + await Parity.ShouldBeSameProblemAsync(http, tool); + } + + [Fact] + public async Task A_stale_association_version_is_the_same_problem() + { + await using var host = await server.StartHostAsync(); + var owner = await Entry.RegisterAsync(host); + var associate = await Entry.RegisterAsync(host); + var association = await RegisterAsync(host, owner, associate); + (await PartyAssociationToolTests.UpdateAsync(host, owner.Id, association, "{}", 1, PartyTools.Key("first"))).Success(); + + var http = await Parity.HttpAsync(host, HttpMethod.Put, Url(owner, association, "Update"), 409, "{}", PartyTools.Key("http"), 1); + var tool = await PartyAssociationToolTests.UpdateAsync(host, owner.Id, association, "{}", 1, PartyTools.Key("mcp")); + + await Parity.ShouldBeSameProblemAsync(http, tool); + } + + [Theory] + [InlineData("not-a-guid", 400)] + [InlineData("01a1b031-8dc0-74cc-a63a-f954f0f3f1f4", 404)] + public async Task A_malformed_or_unknown_association_id_is_the_same_problem(string associationsId, int status) + { + await using var host = await server.StartHostAsync(); + var owner = await Entry.RegisterAsync(host); + + var http = await Parity.HttpAsync(host, HttpMethod.Get, $"/PartyReferenceDataDirectory/{owner.Id}/Associations/{associationsId}/Retrieve", status); + var tool = await PartyAssociationToolTests.RetrieveAsync(host, owner.Id.ToString(), associationsId); + + await Parity.ShouldBeSameProblemAsync(http, tool); + } + + private static string WithPeriod(Guid associate, string type) => + $$"""{ "AssociateReference": { "PartyReference": "{{associate}}" }, "AssociateType": "{{type}}" """ + Period; + + private static async Task RegisterAsync(PartyMcpHost host, Entry owner, Entry associate) => + (await PartyAssociationToolTests.RegisterAsync(host, owner.Id, WithPeriod(associate.Id, "PartyIsTrustedByParty"), PartyTools.Key("register"))) + .Success().GetProperty("AssociationsId").GetGuid(); + + private static string Url(Entry owner, Guid association, string operation) => + $"/PartyReferenceDataDirectory/{owner.Id}/Associations/{association}/{operation}"; +} diff --git a/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationToolTests.cs b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationToolTests.cs new file mode 100644 index 0000000..cf733d3 --- /dev/null +++ b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationToolTests.cs @@ -0,0 +1,123 @@ +using System.Text.Json; +using ModelContextProtocol.Protocol; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp.Tests; + +// Roadmap 1.17: the Associations tools send the same Register, Update and Retrieve as the HTTP endpoints. An association +// is its own aggregate, so its version is its own stream's (ADR 0024, ADR 0033, ADR 0039, ADR 0040). +public sealed class PartyAssociationToolTests(PostgresqlServer server) +{ + [Fact] + public async Task Register_retrieve_then_update_with_the_associations_version() + { + await using var host = await server.StartHostAsync(); + var owner = await Entry.RegisterAsync(host, "Organisation"); + var associate = await Entry.RegisterAsync(host, "Organisation"); + + var registered = (await RegisterAsync(host, owner.Id, Body(associate.Id, "PartyIsParentOfParty"), PartyTools.Key("register"))).Success(); + var associationId = registered.GetProperty("AssociationsId").GetGuid(); + var retrieved = (await RetrieveAsync(host, owner.Id.ToString(), associationId.ToString())).Success(); + var updated = (await UpdateAsync( + host, + owner.Id, + associationId, + """{ "AssociateType": "PartyIsSubsidiaryOfParty", "AssociationValidFromToDate": { "FromDateTime": "2024-01-01" } }""", + retrieved.GetProperty("version").GetInt64(), + PartyTools.Key("update"))) + .Success(); + + registered.GetProperty("version").GetInt64().ShouldBe(1); + registered.GetProperty("PartyReferenceDataDirectoryEntryId").GetGuid().ShouldBe(owner.Id); + registered.GetProperty("AssociateReference").GetProperty("PartyReference").GetGuid().ShouldBe(associate.Id); + JsonElement.DeepEquals(retrieved, registered).ShouldBeTrue($"{retrieved} vs {registered}"); + updated.GetProperty("AssociateType").GetString().ShouldBe("PartyIsSubsidiaryOfParty"); + updated.GetProperty("AssociationValidFromToDate").GetProperty("FromDateTime").GetString().ShouldBe("2024-01-01T00:00:00Z"); + updated.GetProperty("version").GetInt64().ShouldBe(2); + } + + [Fact] + public async Task An_unregistered_associate_or_the_party_itself_is_refused() + { + await using var host = await server.StartHostAsync(); + var owner = await Entry.RegisterAsync(host); + + (await RegisterAsync(host, owner.Id, Body(Guid.CreateVersion7(), "PartyIsMarriedToParty"), PartyTools.Key("unknown"))) + .Problem(422, "party.associate-not-registered"); + (await RegisterAsync(host, owner.Id, Body(owner.Id, "PartyIsMarriedToParty"), PartyTools.Key("self"))) + .Problem(422, "party.self-association"); + } + + [Fact] + public async Task A_bian_field_rimbank_does_not_record_is_refused() + { + await using var host = await server.StartHostAsync(); + var owner = await Entry.RegisterAsync(host); + var associate = await Entry.RegisterAsync(host); + + (await RegisterAsync( + host, + owner.Id, + $$"""{ "AssociateReference": { "PartyReference": "{{associate.Id}}", "InvolvementReference": "Guarantor" }, "AssociateType": "PartyIsTrustedByParty" }""", + PartyTools.Key("refused"))) + .Problem(400, "party.association-field-not-supported"); + } + + [Fact] + public async Task The_associate_cannot_change_and_a_stale_version_is_a_conflict() + { + await using var host = await server.StartHostAsync(); + var owner = await Entry.RegisterAsync(host); + var associate = await Entry.RegisterAsync(host); + var other = await Entry.RegisterAsync(host); + var associationId = (await RegisterAsync(host, owner.Id, Body(associate.Id, "PartyIsTrustedByParty"), PartyTools.Key("register"))).Success() + .GetProperty("AssociationsId").GetGuid(); + + (await UpdateAsync(host, owner.Id, associationId, Body(other.Id, "PartyIsTrustedByParty"), 1, PartyTools.Key("change"))) + .Problem(422, "party.associate-cannot-change"); + (await UpdateAsync(host, owner.Id, associationId, "{}", 1, PartyTools.Key("first"))).Success(); + (await UpdateAsync(host, owner.Id, associationId, "{}", 1, PartyTools.Key("stale"))) + .Problem(409, PartyReferenceDataDirectoryEntryErrors.VersionConflict.Code); + } + + [Fact] + public async Task Only_the_owner_finds_the_association() + { + await using var host = await server.StartHostAsync(); + var owner = await Entry.RegisterAsync(host); + var associate = await Entry.RegisterAsync(host); + var associationId = (await RegisterAsync(host, owner.Id, Body(associate.Id, "PartyIsTrustedByParty"), PartyTools.Key("register"))).Success() + .GetProperty("AssociationsId").GetGuid(); + + (await RetrieveAsync(host, associate.Id.ToString(), associationId.ToString())).Problem(404, "party.association-not-found"); + } + + internal static string Body(Guid associate, string type) => + $$"""{ "AssociateReference": { "PartyReference": "{{associate}}" }, "AssociateType": "{{type}}" }"""; + + internal static Task RegisterAsync(PartyMcpHost host, Guid owner, string request, string key) => + host.CallAsync( + RegisterPartyAssociationTool.Name, + new() + { + ["partyReferenceDataDirectoryEntryId"] = owner.ToString(), + ["request"] = JsonElement.Parse(request), + ["idempotencyKey"] = key, + }); + + internal static Task UpdateAsync(PartyMcpHost host, Guid owner, Guid association, string request, long expectedVersion, string key) => + host.CallAsync( + UpdatePartyAssociationTool.Name, + new() + { + ["partyReferenceDataDirectoryEntryId"] = owner.ToString(), + ["associationsId"] = association.ToString(), + ["request"] = JsonElement.Parse(request), + ["expectedVersion"] = expectedVersion, + ["idempotencyKey"] = key, + }); + + internal static Task RetrieveAsync(PartyMcpHost host, string owner, string association) => + host.CallAsync( + RetrievePartyAssociationTool.Name, + new() { ["partyReferenceDataDirectoryEntryId"] = owner, ["associationsId"] = association }); +} diff --git a/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsParityTests.cs b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsParityTests.cs new file mode 100644 index 0000000..c1e5ef0 --- /dev/null +++ b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsParityTests.cs @@ -0,0 +1,84 @@ +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp.Tests; + +// Roadmap 1.17: the BankRelations tools answer as their HTTP endpoints do: the same body with the ETag as version, and +// the same Problem Details (ADR 0039, ADR 0040). +public sealed class BankRelationsParityTests(PostgresqlServer server) +{ + private static readonly string[] _ids = ["PartyReferenceDataDirectoryEntryId", "BankRelationsId"]; + + [Fact] + public async Task Update_gives_the_http_body_and_the_etag_as_version() + { + await using var host = await server.StartHostAsync(); + var manager = await Entry.RegisterAsync(host, "Person"); + var overHttp = await Entry.RegisterAsync(host); + var overMcp = await Entry.RegisterAsync(host); + var body = BankRelationsToolTests.Managed(manager.Id, "AccountOfficer"); + + var http = await Parity.HttpAsync(host, HttpMethod.Put, Url(overHttp, "Update"), 200, body, PartyTools.Key("http"), overHttp.Version); + var tool = await BankRelationsToolTests.UpdateAsync(host, overMcp, body, overMcp.Version, PartyTools.Key("mcp")); + + await Parity.ShouldMirrorAsync(http, tool, _ids); + } + + [Fact] + public async Task Retrieve_gives_the_http_body_and_the_etag_as_version() + { + await using var host = await server.StartHostAsync(); + var unit = await Entry.RegisterAsync(host, "Organisation"); + var customer = await Entry.RegisterAsync(host); + (await BankRelationsToolTests.UpdateAsync( + host, customer, BankRelationsToolTests.Managed(unit.Id, "ServicingBusinessUnit"), customer.Version, PartyTools.Key("unit"))).Success(); + + var http = await Parity.HttpAsync(host, HttpMethod.Get, Url(customer, "Retrieve"), 200); + var tool = await BankRelationsToolTests.RetrieveAsync(host, customer.Id.ToString(), customer.BankRelationsId.ToString()); + + await Parity.ShouldMirrorAsync(http, tool); + } + + [Theory] + [InlineData("""{ "BankRelationReference": { "RelationshipType": "Primary", "RelationshipStartDate": { "TimeZoneCode": "CET" } } }""", 400)] + [InlineData("""{ "BankRelationReference": { "RelationshipStartDate": { "DateTimeContent": "2025-01-02" }, "RelationshipEndDate": { "DateTimeContent": "2025-01-01" } } }""", 400)] + [InlineData("""{ "BankRelationType": "Customer" }""", 400)] + public async Task A_refused_part_or_invalid_value_is_the_same_problem(string body, int status) + { + await using var host = await server.StartHostAsync(); + var customer = await Entry.RegisterAsync(host); + + var http = await Parity.HttpAsync(host, HttpMethod.Put, Url(customer, "Update"), status, body, PartyTools.Key("http"), customer.Version); + var tool = await BankRelationsToolTests.UpdateAsync(host, customer, body, customer.Version, PartyTools.Key("mcp")); + + await Parity.ShouldBeSameProblemAsync(http, tool); + } + + [Fact] + public async Task A_wrong_type_reference_is_the_same_problem() + { + await using var host = await server.StartHostAsync(); + var customer = await Entry.RegisterAsync(host); + var person = await Entry.RegisterAsync(host, "Person"); + var body = BankRelationsToolTests.Managed(person.Id, "ServicingBranch"); + + var http = await Parity.HttpAsync(host, HttpMethod.Put, Url(customer, "Update"), 422, body, PartyTools.Key("http"), customer.Version); + var tool = await BankRelationsToolTests.UpdateAsync(host, customer, body, customer.Version, PartyTools.Key("mcp")); + + await Parity.ShouldBeSameProblemAsync(http, tool); + } + + [Theory] + [InlineData("not-a-guid", 400)] + [InlineData("01a1b031-8dc0-74cc-a63a-f954f0f3f1f4", 404)] + public async Task A_malformed_or_unknown_bank_relations_id_is_the_same_problem(string bankRelationsId, int status) + { + await using var host = await server.StartHostAsync(); + var customer = await Entry.RegisterAsync(host); + + var http = await Parity.HttpAsync(host, HttpMethod.Get, $"/PartyReferenceDataDirectory/{customer.Id}/BankRelations/{bankRelationsId}/Retrieve", status); + var tool = await BankRelationsToolTests.RetrieveAsync(host, customer.Id.ToString(), bankRelationsId); + + await Parity.ShouldBeSameProblemAsync(http, tool); + } + + private static string Url(Entry entry, string operation) => + $"/PartyReferenceDataDirectory/{entry.Id}/BankRelations/{entry.BankRelationsId}/{operation}"; +} diff --git a/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsToolTests.cs b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsToolTests.cs new file mode 100644 index 0000000..be72c85 --- /dev/null +++ b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsToolTests.cs @@ -0,0 +1,104 @@ +using System.Text.Json; +using ModelContextProtocol.Protocol; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp.Tests; + +// Roadmap 1.17: the BankRelations tools send the same Update and Retrieve as the HTTP endpoints, with expectedVersion in +// place of If-Match and the BIAN body as their request argument (ADR 0035, ADR 0039, ADR 0040). +public sealed class BankRelationsToolTests(PostgresqlServer server) +{ + [Fact] + public async Task A_relationship_manager_is_recorded_and_retrieved() + { + await using var host = await server.StartHostAsync(); + var customer = await Entry.RegisterAsync(host); + var manager = await Entry.RegisterAsync(host, "Person"); + + var updated = (await UpdateAsync(host, customer, Managed(manager.Id, "RelationshipManager"), customer.Version, PartyTools.Key("update"))).Success(); + var retrieved = (await RetrieveAsync(host, customer.Id.ToString(), customer.BankRelationsId.ToString())).Success(); + + updated.GetProperty("BankRelationType").GetString().ShouldBe("RelationshipManager"); + updated.GetProperty("BusinessUnitEmployeeReference").GetProperty("PartyReference").GetGuid().ShouldBe(manager.Id); + updated.GetProperty("BankRelationReference").GetProperty("RelationshipLifecycleStatus").GetProperty("StatusDescription").GetString() + .ShouldBe("Active"); + updated.GetProperty("version").GetInt64().ShouldBe(customer.Version + 1); + JsonElement.DeepEquals(retrieved, updated).ShouldBeTrue($"{retrieved} vs {updated}"); + } + + [Fact] + public async Task A_servicing_branch_names_an_organisation() + { + await using var host = await server.StartHostAsync(); + var customer = await Entry.RegisterAsync(host); + var branch = await Entry.RegisterAsync(host, "Organisation"); + + var updated = (await UpdateAsync(host, customer, Managed(branch.Id, "ServicingBranch"), customer.Version, PartyTools.Key("branch"))).Success(); + + updated.GetProperty("BankRelationType").GetString().ShouldBe("ServicingBranch"); + } + + [Fact] + public async Task A_person_as_servicing_branch_or_an_unregistered_party_is_refused_and_nothing_is_stored() + { + await using var host = await server.StartHostAsync(); + var customer = await Entry.RegisterAsync(host); + var person = await Entry.RegisterAsync(host, "Person"); + + (await UpdateAsync(host, customer, Managed(person.Id, "ServicingBranch"), customer.Version, PartyTools.Key("mismatch"))) + .Problem(422, "party.referenced-party-type-mismatch"); + (await UpdateAsync(host, customer, Managed(Guid.CreateVersion7(), "RelationshipManager"), customer.Version, PartyTools.Key("unknown"))) + .Problem(422, "party.referenced-party-not-registered"); + + (await host.ScalarAsync(PartyTools.EventsOf(customer.Id))).ShouldBe(1); + } + + [Fact] + public async Task A_part_rimbank_does_not_record_is_refused() + { + await using var host = await server.StartHostAsync(); + var customer = await Entry.RegisterAsync(host); + + (await UpdateAsync(host, customer, """{ "BankRelationReference": { "RelationshipType": "Primary" } }""", customer.Version, PartyTools.Key("refused"))) + .Problem(400, "party.bank-relations-field-not-supported"); + } + + [Fact] + public async Task A_version_that_is_no_longer_current_is_a_conflict() + { + await using var host = await server.StartHostAsync(); + var customer = await Entry.RegisterAsync(host); + (await UpdateAsync(host, customer, "{}", customer.Version, PartyTools.Key("first"))).Success(); + + (await UpdateAsync(host, customer, "{}", customer.Version, PartyTools.Key("stale"))) + .Problem(409, PartyReferenceDataDirectoryEntryErrors.VersionConflict.Code); + } + + internal static string Managed(Guid party, string type) => + $$""" + { + "BankRelationType": "{{type}}", + "BusinessUnitEmployeeReference": { "PartyReference": "{{party}}" }, + "BankRelationReference": { + "RelationshipStartDate": { "DateTimeContent": "2024-01-01" }, + "RelationshipLifecycleStatus": { "StatusDescription": "Active" } + } + } + """; + + internal static Task UpdateAsync(PartyMcpHost host, Entry entry, string request, long expectedVersion, string key) => + host.CallAsync( + UpdateBankRelationsTool.Name, + new() + { + ["partyReferenceDataDirectoryEntryId"] = entry.Id.ToString(), + ["bankRelationsId"] = entry.BankRelationsId.ToString(), + ["request"] = JsonElement.Parse(request), + ["expectedVersion"] = expectedVersion, + ["idempotencyKey"] = key, + }); + + internal static Task RetrieveAsync(PartyMcpHost host, string entryId, string bankRelationsId) => + host.CallAsync( + RetrieveBankRelationsTool.Name, + new() { ["partyReferenceDataDirectoryEntryId"] = entryId, ["bankRelationsId"] = bankRelationsId }); +} diff --git a/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Demographics/DemographicsParityTests.cs b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Demographics/DemographicsParityTests.cs new file mode 100644 index 0000000..3901b93 --- /dev/null +++ b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Demographics/DemographicsParityTests.cs @@ -0,0 +1,106 @@ +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp.Tests; + +// Roadmap 1.17: the Demographics tools answer as their HTTP endpoints do: the same body with the ETag as version, and +// the same Problem Details (ADR 0039, ADR 0040). +public sealed class DemographicsParityTests(PostgresqlServer server) +{ + private const string Details = """ + { + "Socio-EconomicClassification": "Professional", + "Employment": { "PartyReference": "Acme", "InvolvementReference": "Engineer" }, + "EmploymentHistory": "Acme since 2020", + "EducationHistory": "MSc", + "ServicingConstraints": "Large print" + } + """; + + private static readonly string[] _ids = ["PartyReferenceDataDirectoryEntryId", "DemographicsId"]; + + [Fact] + public async Task Update_gives_the_http_body_and_the_etag_as_version() + { + await using var host = await server.StartHostAsync(); + var overHttp = await Entry.RegisterAsync(host); + var overMcp = await Entry.RegisterAsync(host); + + var http = await Parity.HttpAsync(host, HttpMethod.Put, Url(overHttp, "Update"), 200, Details, PartyTools.Key("http"), overHttp.Version); + var tool = await DemographicsToolTests.UpdateAsync(host, overMcp, Details, overMcp.Version, PartyTools.Key("mcp")); + + await Parity.ShouldMirrorAsync(http, tool, _ids); + } + + [Fact] + public async Task Exchange_gives_the_http_body_and_the_etag_as_version() + { + await using var host = await server.StartHostAsync(); + var overHttp = await Entry.RegisterAsync(host); + var overMcp = await Entry.RegisterAsync(host); + (await DemographicsToolTests.UpdateAsync(host, overHttp, Details, overHttp.Version, PartyTools.Key("details"))).Success(); + (await DemographicsToolTests.UpdateAsync(host, overMcp, Details, overMcp.Version, PartyTools.Key("details"))).Success(); + const string verify = """{ "ExchangeActionType": "Verify" }"""; + + var http = await Parity.HttpAsync(host, HttpMethod.Put, Url(overHttp, "Exchange"), 200, verify, PartyTools.Key("http"), overHttp.Version + 1); + var tool = await DemographicsToolTests.ExchangeAsync(host, overMcp, verify, overMcp.Version + 1, PartyTools.Key("mcp")); + + await Parity.ShouldMirrorAsync(http, tool, _ids); + } + + [Fact] + public async Task Retrieve_gives_the_http_body_and_the_etag_as_version() + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + (await DemographicsToolTests.UpdateAsync(host, entry, Details, entry.Version, PartyTools.Key("details"))).Success(); + + var http = await Parity.HttpAsync(host, HttpMethod.Get, Url(entry, "Retrieve"), 200); + var tool = await DemographicsToolTests.RetrieveAsync(host, entry.Id.ToString(), entry.DemographicsId.ToString()); + + await Parity.ShouldMirrorAsync(http, tool); + } + + [Theory] + [InlineData("{}")] + [InlineData("""{ "ExchangeActionType": "Approve" }""")] + [InlineData("""{ "ExchangeActionType": "Verify" }""")] + public async Task An_invalid_or_premature_exchange_is_the_same_problem(string request) + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + var status = request.Contains("Verify", StringComparison.Ordinal) ? 422 : 400; + + var http = await Parity.HttpAsync(host, HttpMethod.Put, Url(entry, "Exchange"), status, request, PartyTools.Key("http"), entry.Version); + var tool = await DemographicsToolTests.ExchangeAsync(host, entry, request, entry.Version, PartyTools.Key("mcp")); + + await Parity.ShouldBeSameProblemAsync(http, tool); + } + + [Fact] + public async Task An_invalid_detail_is_the_same_problem() + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + var tooLong = $$"""{ "EducationHistory": "{{new string('x', 5000)}}" }"""; + + var http = await Parity.HttpAsync(host, HttpMethod.Put, Url(entry, "Update"), 400, tooLong, PartyTools.Key("http"), entry.Version); + var tool = await DemographicsToolTests.UpdateAsync(host, entry, tooLong, entry.Version, PartyTools.Key("mcp")); + + await Parity.ShouldBeSameProblemAsync(http, tool); + } + + [Theory] + [InlineData("not-a-guid", 400)] + [InlineData("01a1b031-8dc0-74cc-a63a-f954f0f3f1f4", 404)] + public async Task A_malformed_or_unknown_demographics_id_is_the_same_problem(string demographicsId, int status) + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + + var http = await Parity.HttpAsync(host, HttpMethod.Get, $"/PartyReferenceDataDirectory/{entry.Id}/Demographics/{demographicsId}/Retrieve", status); + var tool = await DemographicsToolTests.RetrieveAsync(host, entry.Id.ToString(), demographicsId); + + await Parity.ShouldBeSameProblemAsync(http, tool); + } + + private static string Url(Entry entry, string operation) => + $"/PartyReferenceDataDirectory/{entry.Id}/Demographics/{entry.DemographicsId}/{operation}"; +} diff --git a/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Demographics/DemographicsToolTests.cs b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Demographics/DemographicsToolTests.cs new file mode 100644 index 0000000..905193f --- /dev/null +++ b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Demographics/DemographicsToolTests.cs @@ -0,0 +1,119 @@ +using System.Text.Json; +using ModelContextProtocol.Protocol; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp.Tests; + +// Roadmap 1.17: the Demographics tools send the same Update, Exchange and Retrieve as the HTTP endpoints, with +// expectedVersion in place of If-Match and the BIAN body as their request argument (ADR 0028, ADR 0039, ADR 0040). +public sealed class DemographicsToolTests(PostgresqlServer server) +{ + private const string Details = """ + { + "Socio-EconomicClassification": "Professional", + "Employment": { "PartyReference": "Acme", "InvolvementReference": "Engineer" }, + "EducationHistory": "MSc", + "EthnicityReligion": "never stored" + } + """; + + [Fact] + public async Task Update_then_retrieve_answers_the_details_and_the_versions() + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + + var updated = (await UpdateAsync(host, entry, Details, entry.Version, PartyTools.Key("update"))).Success(); + var retrieved = (await RetrieveAsync(host, entry.Id.ToString(), entry.DemographicsId.ToString())).Success(); + + updated.GetProperty("Socio-EconomicClassification").GetString().ShouldBe("Professional"); + updated.GetProperty("Employment").GetProperty("InvolvementReference").GetString().ShouldBe("Engineer"); + updated.GetProperty("VerificationStatus").GetString().ShouldBe("Unverified"); + updated.TryGetProperty("EthnicityReligion", out _).ShouldBeFalse(); + updated.GetProperty("version").GetInt64().ShouldBe(entry.Version + 1); + JsonElement.DeepEquals(retrieved, updated).ShouldBeTrue($"{retrieved} vs {updated}"); + } + + [Fact] + public async Task A_left_out_field_keeps_its_value_and_an_empty_one_clears_it() + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + var first = (await UpdateAsync(host, entry, Details, entry.Version, PartyTools.Key("first"))).Success(); + + var second = (await UpdateAsync(host, entry, """{ "EducationHistory": "" }""", first.GetProperty("version").GetInt64(), PartyTools.Key("second"))) + .Success(); + + second.GetProperty("Socio-EconomicClassification").GetString().ShouldBe("Professional"); + second.TryGetProperty("EducationHistory", out _).ShouldBeFalse(); + } + + [Fact] + public async Task Exchange_verifies_the_recorded_details() + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + var updated = (await UpdateAsync(host, entry, Details, entry.Version, PartyTools.Key("update"))).Success(); + + var verified = (await ExchangeAsync(host, entry, """{ "ExchangeActionType": "Verify" }""", updated.GetProperty("version").GetInt64(), PartyTools.Key("verify"))) + .Success(); + + verified.GetProperty("VerificationStatus").GetString().ShouldBe("Verified"); + verified.GetProperty("VerificationDate").GetDateTimeOffset().ShouldBe(PostgresqlServer.Now); + verified.GetProperty("version").GetInt64().ShouldBe(entry.Version + 2); + } + + [Theory] + [InlineData("{}", 400, "party.exchange-action-type-required")] + [InlineData("""{ "ExchangeActionType": "Approve" }""", 400, "party.exchange-action-type-invalid")] + [InlineData("""{ "ExchangeActionType": "Verify" }""", 422, "party.demographics-not-recorded")] + public async Task An_exchange_without_a_valid_action_or_recorded_details_is_refused(string request, int status, string errorCode) + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + + (await ExchangeAsync(host, entry, request, entry.Version, PartyTools.Key("exchange"))).Problem(status, errorCode); + } + + [Fact] + public async Task A_version_that_is_no_longer_current_is_a_conflict() + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + (await UpdateAsync(host, entry, Details, entry.Version, PartyTools.Key("first"))).Success(); + + (await UpdateAsync(host, entry, Details, entry.Version, PartyTools.Key("stale"))) + .Problem(409, PartyReferenceDataDirectoryEntryErrors.VersionConflict.Code); + } + + [Theory] + [InlineData("not-a-guid", 400, "shared.invalid-identifier")] + [InlineData("01a1b031-8dc0-74cc-a63a-f954f0f3f1f4", 404, "party.behavior-qualifier-not-found")] + public async Task A_malformed_or_unknown_demographics_id_is_refused(string demographicsId, int status, string errorCode) + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + + (await RetrieveAsync(host, entry.Id.ToString(), demographicsId)).Problem(status, errorCode); + } + + internal static Task UpdateAsync(PartyMcpHost host, Entry entry, string request, long expectedVersion, string key) => + host.CallAsync(UpdateDemographicsTool.Name, Command(entry, request, expectedVersion, key)); + + internal static Task ExchangeAsync(PartyMcpHost host, Entry entry, string request, long expectedVersion, string key) => + host.CallAsync(ExchangeDemographicsTool.Name, Command(entry, request, expectedVersion, key)); + + internal static Task RetrieveAsync(PartyMcpHost host, string entryId, string demographicsId) => + host.CallAsync( + RetrieveDemographicsTool.Name, + new() { ["partyReferenceDataDirectoryEntryId"] = entryId, ["demographicsId"] = demographicsId }); + + private static Dictionary Command(Entry entry, string request, long expectedVersion, string key) => + new() + { + ["partyReferenceDataDirectoryEntryId"] = entry.Id.ToString(), + ["demographicsId"] = entry.DemographicsId.ToString(), + ["request"] = JsonElement.Parse(request), + ["expectedVersion"] = expectedVersion, + ["idempotencyKey"] = key, + }; +} diff --git a/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Parity.cs b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Parity.cs new file mode 100644 index 0000000..2fb9c4f --- /dev/null +++ b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Parity.cs @@ -0,0 +1,122 @@ +using System.Globalization; +using System.Text.Json; +using Alba; +using Microsoft.Net.Http.Headers; +using ModelContextProtocol.Protocol; +using RimBank.Host.Testing; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp.Tests; + +/// +/// The checks that a tool answers as its HTTP endpoint does (mission principles 6 and 8, tech-stack §6, ADR 0039): the +/// same body with the ETag as version, or the same Problem Details. +/// +public static class Parity +{ + /// The Problem Details members that do not depend on the request. + private static readonly string[] _problemMembers = ["type", "title", "status", "detail", "errorCode", "errors"]; + + /// Sends to with every scope, as a command or a query. + /// The host. + /// GET, POST or PUT. + /// The BIAN route, with its ids. + /// The expected status. + /// The JSON body of a command. + /// The Idempotency-Key of a command. + /// The expected version of a command that changes a record. + /// The scenario's result. + public static Task HttpAsync( + PartyMcpHost host, + HttpMethod method, + string url, + int status, + string? body = null, + string? key = null, + long? ifMatch = null) => + host.Alba.Scenario(_ => + { + switch (method.Method) + { + case "GET": + _.Get.Url(url); + break; + case "POST": + _.Post.Text(body ?? "{}").ToUrl(url); + break; + case "PUT": + _.Put.Text(body ?? "{}").ToUrl(url); + break; + default: + throw new ArgumentOutOfRangeException(nameof(method), method, "Only GET, POST and PUT are BIAN routes here."); + } + + if (body is not null) + { + _.WithRequestHeader(HeaderNames.ContentType, "application/json"); + } + + if (key is not null) + { + _.WithRequestHeader("Idempotency-Key", key); + } + + if (ifMatch is { } version) + { + _.WithRequestHeader(HeaderNames.IfMatch, $"\"{version.ToString(CultureInfo.InvariantCulture)}\""); + } + + _.WithRequestHeader(HeaderNames.Authorization, "Bearer " + TestTokens.Issue()); + _.StatusCodeShouldBe(status); + }); + + /// + /// Checks that the tool's result is the HTTP body plus version, and that version is the ETag. + /// Members whose value depends on the call (an id the command created, the time) are compared by presence only. + /// + /// The HTTP answer. + /// The tool's answer. + /// Members that differ between two calls, such as a new id. + public static async Task ShouldMirrorAsync(IScenarioResult http, CallToolResult tool, params string[] volatileMembers) + { + var body = await http.ReadAsJsonAsync(); + var result = tool.Success(); + + Members(result).ShouldBe([.. Members(body), "version"], ignoreOrder: true); + foreach (var member in Members(body).Except(volatileMembers, StringComparer.Ordinal)) + { + JsonElement.DeepEquals(result.GetProperty(member), body.GetProperty(member)) + .ShouldBeTrue($"{member}: {result.GetProperty(member)} vs {body.GetProperty(member)}"); + } + + ETagOf(http).ShouldBe(result.GetProperty("version").GetInt64()); + } + + /// Checks that the tool's error is the HTTP Problem Details, member by member. + /// The HTTP answer. + /// The tool's answer. + public static async Task ShouldBeSameProblemAsync(IScenarioResult http, CallToolResult tool) + { + var expected = await http.ReadAsJsonAsync(); + http.Context.Response.ContentType.ShouldBe("application/problem+json"); + var actual = tool.Problem(expected.GetProperty("status").GetInt32(), expected.GetProperty("errorCode").GetString()!); + foreach (var member in _problemMembers) + { + expected.TryGetProperty(member, out var wanted).ShouldBe(actual.TryGetProperty(member, out var got), member); + if (wanted.ValueKind != JsonValueKind.Undefined) + { + JsonElement.DeepEquals(got, wanted).ShouldBeTrue($"{member}: {got} vs {wanted}"); + } + } + } + + /// The version an HTTP answer sent as its ETag. + public static long ETagOf(IScenarioResult http) => + long.Parse(http.Context.Response.Headers.ETag.ToString().Trim('"'), CultureInfo.InvariantCulture); + + /// without . + public static JsonElement Without(JsonElement element, string member) => + JsonSerializer.SerializeToElement( + element.EnumerateObject().Where(property => property.Name != member).ToDictionary(property => property.Name, property => property.Value)); + + private static string[] Members(JsonElement element) => [.. element.EnumerateObject().Select(property => property.Name)]; +} diff --git a/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/PartyMcpParityTests.cs b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/PartyMcpParityTests.cs index f698e7d..8bd78aa 100644 --- a/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/PartyMcpParityTests.cs +++ b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/PartyMcpParityTests.cs @@ -1,7 +1,6 @@ using System.Text.Json; using Alba; using Microsoft.Net.Http.Headers; -using ModelContextProtocol.Protocol; using RimBank.Host; using RimBank.Host.Testing; @@ -13,9 +12,6 @@ public sealed class PartyMcpParityTests(PostgresqlServer server) { private const string Register = "/PartyReferenceDataDirectory/Register"; - /// The Problem Details members that do not depend on the request. - private static readonly string[] _problemMembers = ["type", "title", "status", "detail", "errorCode", "errors"]; - [Fact] public async Task Register_gives_the_http_body_and_the_etag_as_version() { @@ -31,7 +27,7 @@ public async Task Register_gives_the_http_body_and_the_etag_as_version() JsonElement.DeepEquals(tool.GetProperty(member), body.GetProperty(member)).ShouldBeTrue(member); } - ETagOf(http).ShouldBe(tool.GetProperty("version").GetInt64()); + Parity.ETagOf(http).ShouldBe(tool.GetProperty("version").GetInt64()); } [Fact] @@ -45,8 +41,8 @@ public async Task Retrieve_gives_the_http_body_and_the_etag_as_version() var tool = (await RetrievePartyReferenceDataDirectoryEntryToolTests.RetrieveAsync(host, id.ToString())).Success(); var body = await http.ReadAsJsonAsync(); - JsonElement.DeepEquals(Without(tool, "version"), body).ShouldBeTrue($"{tool} vs {body}"); - ETagOf(http).ShouldBe(tool.GetProperty("version").GetInt64()); + JsonElement.DeepEquals(Parity.Without(tool, "version"), body).ShouldBeTrue($"{tool} vs {body}"); + Parity.ETagOf(http).ShouldBe(tool.GetProperty("version").GetInt64()); } [Theory] @@ -63,7 +59,7 @@ public async Task An_invalid_party_type_is_the_same_problem(string partyType) }); var tool = await RegisterPartyToolTests.RegisterAsync(host, partyType, "parity-invalid-mcp"); - await ShouldBeSameProblemAsync(http, tool); + await Parity.ShouldBeSameProblemAsync(http, tool); } [Fact] @@ -80,7 +76,7 @@ public async Task A_reused_idempotency_key_is_the_same_problem() }); var tool = await RegisterPartyToolTests.RegisterAsync(host, "Organisation", "parity-reused-mcp"); - await ShouldBeSameProblemAsync(http, tool); + await Parity.ShouldBeSameProblemAsync(http, tool); } [Theory] @@ -93,7 +89,7 @@ public async Task A_malformed_or_unknown_id_is_the_same_problem(string id, int s var http = await host.Alba.Scenario(_ => GetRetrieve(_, id, status)); var tool = await RetrievePartyReferenceDataDirectoryEntryToolTests.RetrieveAsync(host, id); - await ShouldBeSameProblemAsync(http, tool); + await Parity.ShouldBeSameProblemAsync(http, tool); } [Fact] @@ -115,22 +111,7 @@ public async Task A_missing_scope_is_the_same_problem() new() { ["partyType"] = "Person", ["idempotencyKey"] = "parity-forbidden" }, [PartyReferenceDataDirectoryModule.ReadScope]); - await ShouldBeSameProblemAsync(http, tool); - } - - private static async Task ShouldBeSameProblemAsync(IScenarioResult http, CallToolResult tool) - { - var expected = await http.ReadAsJsonAsync(); - http.Context.Response.ContentType.ShouldBe("application/problem+json"); - var actual = tool.Problem(expected.GetProperty("status").GetInt32(), expected.GetProperty("errorCode").GetString()!); - foreach (var member in _problemMembers) - { - expected.TryGetProperty(member, out var wanted).ShouldBe(actual.TryGetProperty(member, out var got), member); - if (wanted.ValueKind != JsonValueKind.Undefined) - { - JsonElement.DeepEquals(got, wanted).ShouldBeTrue($"{member}: {got} vs {wanted}"); - } - } + await Parity.ShouldBeSameProblemAsync(http, tool); } private static void PostRegister(Scenario scenario, string body, string key) @@ -148,12 +129,5 @@ private static void GetRetrieve(Scenario scenario, string id, int status) scenario.StatusCodeShouldBe(status); } - private static long ETagOf(IScenarioResult http) => - long.Parse(http.Context.Response.Headers.ETag.ToString().Trim('"'), System.Globalization.CultureInfo.InvariantCulture); - private static string[] Members(JsonElement element) => [.. element.EnumerateObject().Select(property => property.Name)]; - - private static JsonElement Without(JsonElement element, string member) => - JsonSerializer.SerializeToElement( - element.EnumerateObject().Where(property => property.Name != member).ToDictionary(property => property.Name, property => property.Value)); } diff --git a/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/PartyToolCatalogTests.cs b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/PartyToolCatalogTests.cs index 2cc6dd6..00e0c56 100644 --- a/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/PartyToolCatalogTests.cs +++ b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/PartyToolCatalogTests.cs @@ -6,32 +6,23 @@ namespace RimBank.Party.PartyReferenceDataDirectory.Mcp.Tests; -// Roadmap 1.16, pulled forward from 1.17: the tool list matches the implemented BIAN operations, each tool is named after -// its operation, carries its operation's policy and the annotations of its kind (ADR 0021, ADR 0038, ADR 0039). +// Roadmap 1.16 and 1.17: the tool list is exactly the implemented BIAN operations, each tool is named after its +// operation, carries its operation's policy, the annotations of its kind and the arguments of its kind (ADR 0021, +// ADR 0038, ADR 0039, ADR 0040). public sealed class PartyToolCatalogTests(PostgresqlServer server) { private const string ServiceDomainTool = "party_reference_data_directory"; private const string ControlRecord = "PartyReferenceDataDirectoryEntry"; - /// The implemented operations whose tools roadmap 1.17 adds. 1.17 empties this list. - private static readonly string[] _toolsIn117 = - [ - "PartyReferenceDataDirectoryEntry/Update", - "Demographics/Update", - "Demographics/Exchange", - "Demographics/Retrieve", - "Reference/Update", - "Reference/Retrieve", - "Associations/Register", - "Associations/Update", - "Associations/Retrieve", - "BankRelations/Update", - "BankRelations/Retrieve", - ]; + /// The Control Record Register's one body field, a flat argument since 1.16 (ADR 0039, ADR 0040). + private const string RegisterPartyFlatBody = "partyType"; + + /// The arguments a command tool takes in addition to its ids (ADR 0018, ADR 0027, ADR 0040). + private static readonly string[] _commandArguments = ["request", "expectedVersion", "idempotencyKey"]; [Fact] - public async Task The_tool_list_is_the_implemented_operations_that_have_their_tool_yet() + public async Task The_tool_list_is_the_implemented_operations() { await using var host = await server.StartHostAsync(); var catalog = host.Alba.Services.GetRequiredService(); @@ -39,13 +30,9 @@ public async Task The_tool_list_is_the_implemented_operations_that_have_their_to var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken); - _toolsIn117.ShouldBeSubsetOf(catalog.Policies.Select(policy => policy.OperationId)); + tools.Count.ShouldBe(13); tools.Select(tool => tool.Name).Order(StringComparer.Ordinal).ShouldBe( - catalog.Policies - .Select(policy => policy.OperationId) - .Except(_toolsIn117, StringComparer.Ordinal) - .Select(ToolName) - .Order(StringComparer.Ordinal)); + catalog.Policies.Select(policy => ToolName(policy.OperationId)).Order(StringComparer.Ordinal)); } [Fact] @@ -58,9 +45,8 @@ public async Task Each_tool_carries_its_operations_policy_and_the_annotations_of tools.ShouldNotBeEmpty(); foreach (var tool in tools) { - var operationId = tool.Metadata.OfType().ShouldHaveSingleItem().OperationId; - var policy = catalog.Find(operationId).ShouldNotBeNull($"{tool.ProtocolTool.Name} names an operation no policy protects"); - tool.ProtocolTool.Name.ShouldBe(ToolName(operationId)); + var policy = PolicyOf(tool, catalog); + tool.ProtocolTool.Name.ShouldBe(ToolName(policy.OperationId)); tool.ProtocolTool.Description.ShouldNotBeNullOrWhiteSpace(); tool.ProtocolTool.InputSchema.GetProperty("properties").EnumerateObject().ShouldNotBeEmpty(); var annotations = tool.ProtocolTool.Annotations.ShouldNotBeNull(); @@ -72,27 +58,95 @@ public async Task Each_tool_carries_its_operations_policy_and_the_annotations_of } [Fact] - public async Task A_command_tool_requires_its_idempotency_key() + public async Task Each_tool_requires_the_ids_and_the_arguments_of_its_kind() { await using var host = await server.StartHostAsync(); + var catalog = host.Alba.Services.GetRequiredService(); - var register = host.Alba.Services.GetServices().Single(tool => tool.ProtocolTool.Name == RegisterPartyTool.Name); + foreach (var tool in host.Alba.Services.GetServices()) + { + var policy = PolicyOf(tool, catalog); + var schema = tool.ProtocolTool.InputSchema; + var properties = schema.GetProperty("properties").EnumerateObject().Select(property => property.Name).ToList(); + var required = schema.GetProperty("required").EnumerateArray().Select(name => name.GetString()!).ToList(); + + required.ShouldBe(properties, ignoreOrder: true, tool.ProtocolTool.Name); + properties.Except([.. _commandArguments, RegisterPartyFlatBody]) + .ShouldAllBe(name => name.EndsWith("Id", StringComparison.Ordinal), tool.ProtocolTool.Name); + properties.Intersect(_commandArguments).Order(StringComparer.Ordinal).ShouldBe( + ArgumentsOf(policy).Order(StringComparer.Ordinal), + tool.ProtocolTool.Name); + } + } - register.ProtocolTool.InputSchema.GetProperty("required").EnumerateArray().Select(name => name.GetString()) - .ShouldBe(["partyType", "idempotencyKey"], ignoreOrder: true); + [Fact] + public async Task A_command_tools_request_is_the_bian_body_with_its_property_names() + { + await using var host = await server.StartHostAsync(); + var reference = host.Alba.Services.GetServices().Single(tool => tool.ProtocolTool.Name == UpdatePartyReferenceTool.Name); + + var request = reference.ProtocolTool.InputSchema.GetProperty("properties").GetProperty("request"); + + request.GetProperty("properties").EnumerateObject().Select(property => property.Name) + .ShouldContain("ResidentialAddress"); + request.GetProperty("properties").GetProperty("ResidentialAddress").ToString().ShouldContain("TownName"); + request.GetProperty("properties").EnumerateObject().Select(property => property.Name).ShouldContain("eMailAddress"); } [Fact] - public async Task A_query_tool_takes_no_idempotency_key() + public async Task A_caller_with_only_the_read_scope_sees_only_the_retrieve_tools_and_cannot_call_a_command() { await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + var client = await host.ConnectAsync([PartyReferenceDataDirectoryModule.ReadScope]); + + var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken); + var update = await host.CallAsync( + UpdatePartyReferenceTool.Name, + new() + { + ["partyReferenceDataDirectoryEntryId"] = entry.Id.ToString(), + ["referenceId"] = entry.ReferenceId.ToString(), + ["request"] = JsonElement.Parse("""{ "PartyFullLegalName": "Jeanne Dupont" }"""), + ["expectedVersion"] = entry.Version, + ["idempotencyKey"] = PartyTools.Key("denied"), + }, + [PartyReferenceDataDirectoryModule.ReadScope]); + + tools.Select(tool => tool.Name).ShouldAllBe(name => name.StartsWith($"{ServiceDomainTool}_retrieve", StringComparison.Ordinal)); + tools.Count.ShouldBe(5); + update.Problem(403, "shared.forbidden"); + (await host.ScalarAsync(PartyTools.EventsOf(entry.Id))).ShouldBe(1); + } - var retrieve = host.Alba.Services.GetServices() - .Single(tool => tool.ProtocolTool.Name == RetrievePartyReferenceDataDirectoryEntryTool.Name); + /// + /// The arguments a tool takes besides its ids: none for a query; for a command, a required idempotencyKey + /// (ADR 0018), an expectedVersion when it changes a record (ADR 0027), and a request body unless it is + /// the Control Record's Register, whose only field is a flat partyType (ADR 0039, ADR 0040). + /// + private static IEnumerable ArgumentsOf(OperationPolicy policy) + { + if (policy.Kind == OperationKind.Query) + { + yield break; + } - retrieve.ProtocolTool.InputSchema.GetProperty("properties").EnumerateObject().Select(property => property.Name) - .ShouldBe(["partyReferenceDataDirectoryEntryId"]); - retrieve.ProtocolTool.InputSchema.GetProperty("required").ValueKind.ShouldBe(JsonValueKind.Array); + yield return "idempotencyKey"; + if (!policy.OperationId.EndsWith("/Register", StringComparison.Ordinal)) + { + yield return "expectedVersion"; + } + + if (policy.OperationId != RegisterPartyTool.OperationId) + { + yield return "request"; + } + } + + private static OperationPolicy PolicyOf(McpServerTool tool, OperationPolicyCatalog catalog) + { + var operationId = tool.Metadata.OfType().ShouldHaveSingleItem().OperationId; + return catalog.Find(operationId).ShouldNotBeNull($"{tool.ProtocolTool.Name} names an operation no policy protects"); } /// diff --git a/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/PartyTools.cs b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/PartyTools.cs new file mode 100644 index 0000000..9a423df --- /dev/null +++ b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/PartyTools.cs @@ -0,0 +1,38 @@ +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp.Tests; + +/// A registered directory entry: its id, version and the ids of its Behavior Qualifiers. +public sealed record Entry(Guid Id, long Version, Guid DemographicsId, Guid ReferenceId, Guid BankRelationsId) +{ + /// Registers a party through its tool, with a fresh idempotency key. + public static async Task RegisterAsync(PartyMcpHost host, string partyType = "Person") + { + var entry = (await RegisterPartyToolTests.RegisterAsync(host, partyType, PartyTools.Key("register"))).Success(); + return new Entry( + entry.GetProperty("PartyReferenceDataDirectoryEntryId").GetGuid(), + entry.GetProperty("version").GetInt64(), + entry.GetProperty(nameof(DemographicsId)).GetGuid(), + entry.GetProperty(nameof(ReferenceId)).GetGuid(), + entry.GetProperty(nameof(BankRelationsId)).GetGuid()); + } +} + +/// Shared steps of the Party tool tests (roadmap 1.17). +public static class PartyTools +{ + private static int _keys; + + /// Registers a party through its tool, with a fresh idempotency key. + /// The entry's id and version. + public static async Task<(Guid Id, long Version)> RegisterAsync(PartyMcpHost host, string partyType) + { + var entry = (await RegisterPartyToolTests.RegisterAsync(host, partyType, Key("register"))).Success(); + return (entry.GetProperty("PartyReferenceDataDirectoryEntryId").GetGuid(), entry.GetProperty("version").GetInt64()); + } + + /// A fresh idempotency key starting with . + public static string Key(string prefix) => $"{prefix}-{Interlocked.Increment(ref _keys)}"; + + /// The number of events of the stream . + public static string EventsOf(Guid id) => + $"SELECT count(*) FROM party_reference_data_directory.mt_events WHERE stream_id = '{id}'"; +} diff --git a/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Reference/PartyReferenceParityTests.cs b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Reference/PartyReferenceParityTests.cs new file mode 100644 index 0000000..fcba092 --- /dev/null +++ b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Reference/PartyReferenceParityTests.cs @@ -0,0 +1,94 @@ +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp.Tests; + +// Roadmap 1.17: the Reference tools answer as their HTTP endpoints do: the same body with the ETag as version, and the +// same Problem Details (ADR 0039, ADR 0040). +public sealed class PartyReferenceParityTests(PostgresqlServer server) +{ + private static readonly string[] _ids = ["PartyReferenceDataDirectoryEntryId", "ReferenceId"]; + + [Fact] + public async Task Update_of_every_person_field_gives_the_http_body_and_the_etag_as_version() + { + await using var host = await server.StartHostAsync(); + var overHttp = await Entry.RegisterAsync(host); + var overMcp = await Entry.RegisterAsync(host); + + var http = await Parity.HttpAsync(host, HttpMethod.Put, Url(overHttp, "Update"), 200, PartyReferenceToolTests.Person, PartyTools.Key("http"), overHttp.Version); + var tool = await PartyReferenceToolTests.UpdateAsync(host, overMcp, PartyReferenceToolTests.Person, overMcp.Version, PartyTools.Key("mcp")); + + await Parity.ShouldMirrorAsync(http, tool, _ids); + } + + [Fact] + public async Task Update_of_an_organisations_corporate_fields_gives_the_http_body() + { + await using var host = await server.StartHostAsync(); + var group = await Entry.RegisterAsync(host, "Organisation"); + var officer = await Entry.RegisterAsync(host, "Person"); + var overHttp = await Entry.RegisterAsync(host, "Organisation"); + var overMcp = await Entry.RegisterAsync(host, "Organisation"); + var body = $$""" + { + "PartyLegalEntityReference": { "Identification": "5493001kjtiigc8y1r12" }, + "PartyFullLegalName": "Dupont SA", + "PartyLegalStructure": "private limited company", + "CorporateAddress": { "Department": "Finance", "StreetName": "Avenue Louise", "TownName": "Ixelles", "Country": { "Code": "BE" } }, + "CorporateCustomerReference": { "PartyReference": "{{group.Id}}" }, + "CorporateCustomerLegalEntityReference": { "PartyReference": "{{group.Id}}" }, + "CompanyOfficerReference": { "PartyReference": "{{officer.Id}}" }, + "CompanyOfficerRole": " Director " + } + """; + + var http = await Parity.HttpAsync(host, HttpMethod.Put, Url(overHttp, "Update"), 200, body, PartyTools.Key("http"), overHttp.Version); + var tool = await PartyReferenceToolTests.UpdateAsync(host, overMcp, body, overMcp.Version, PartyTools.Key("mcp")); + + await Parity.ShouldMirrorAsync(http, tool, _ids); + } + + [Fact] + public async Task Retrieve_gives_the_http_body_and_the_etag_as_version() + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + (await PartyReferenceToolTests.UpdateAsync(host, entry, PartyReferenceToolTests.Person, entry.Version, PartyTools.Key("person"))).Success(); + + var http = await Parity.HttpAsync(host, HttpMethod.Get, Url(entry, "Retrieve"), 200); + var tool = await PartyReferenceToolTests.RetrieveAsync(host, entry.Id.ToString(), entry.ReferenceId.ToString()); + + await Parity.ShouldMirrorAsync(http, tool); + } + + [Theory] + [InlineData("""{ "PartyLegalEntityReference": { "Identification": "5493001KJTIIGC8Y1R13" }, "DateofBirth": "1850-01-01" }""", 400)] + [InlineData("""{ "eMailAddress": { "EmailAddress": "jeanne@example.fr", "Identification": "x" }, "PartyAddress": { "TownName": "Paris", "Country": { "Code": "FR", "Name": "France" } } }""", 400)] + [InlineData("""{ "CompanyOfficerRole": { "PartyName": "x" } }""", 400)] + [InlineData("""{ "CorporateCustomerReference": { "PartyReference": "01a1b031-8dc0-74cc-a63a-f954f0f3f1f4" } }""", 422)] + public async Task An_invalid_value_or_refused_part_is_the_same_problem(string body, int status) + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host, "Organisation"); + + var http = await Parity.HttpAsync(host, HttpMethod.Put, Url(entry, "Update"), status, body, PartyTools.Key("http"), entry.Version); + var tool = await PartyReferenceToolTests.UpdateAsync(host, entry, body, entry.Version, PartyTools.Key("mcp")); + + await Parity.ShouldBeSameProblemAsync(http, tool); + } + + [Theory] + [InlineData("not-a-guid", 400)] + [InlineData("01a1b031-8dc0-74cc-a63a-f954f0f3f1f4", 404)] + public async Task A_malformed_or_unknown_reference_id_is_the_same_problem(string referenceId, int status) + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + + var http = await Parity.HttpAsync(host, HttpMethod.Get, $"/PartyReferenceDataDirectory/{entry.Id}/Reference/{referenceId}/Retrieve", status); + var tool = await PartyReferenceToolTests.RetrieveAsync(host, entry.Id.ToString(), referenceId); + + await Parity.ShouldBeSameProblemAsync(http, tool); + } + + private static string Url(Entry entry, string operation) => + $"/PartyReferenceDataDirectory/{entry.Id}/Reference/{entry.ReferenceId}/{operation}"; +} diff --git a/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Reference/PartyReferenceToolTests.cs b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Reference/PartyReferenceToolTests.cs new file mode 100644 index 0000000..e98dc1e --- /dev/null +++ b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Reference/PartyReferenceToolTests.cs @@ -0,0 +1,164 @@ +using System.Text.Json; +using ModelContextProtocol.Protocol; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp.Tests; + +// Roadmap 1.17: the Reference tools send the same Update and Retrieve as the HTTP endpoints, with expectedVersion in +// place of If-Match and the BIAN UpdateReference body as their request argument (ADR 0029, ADR 0034, ADR 0039, ADR 0040). +public sealed class PartyReferenceToolTests(PostgresqlServer server) +{ + internal const string Person = + """ + { + "GovernmentIssuedIdentityReference": { "TaxIdentificationNumber": " FR12345678901 ", "NationalRegistrationNumber": "185057800608436" }, + "PartyFullLegalName": " Jeanne Marie Dupont ", + "PartyNameSalutation": "Ms", + "DateofBirth": "1990-05-17", + "Nationality": { "Code": "fr" }, + "PartyCountryOfResidence": { "Code": "BE" }, + "ResidencyStatus": { "StatusDescription": "nonresident", "StatusDateTime": "2024-01-01T00:00:00Z" }, + "ResidentialAddress": { + "StreetName": " Rue de Rivoli ", + "StreetBuildingIdentification": "12", + "PostCodeIdentification": "75001", + "TownName": "Paris", + "Country": { "Code": "fr" } + }, + "eMailAddress": { "EmailAddress": " jeanne@example.fr " }, + "CellPhoneNumber": { "MobileNumber": "+33 6 12 34 56 78" }, + "SocialNetworkContacts": { "URLAddress": "https://www.linkedin.com/in/jdupont" }, + "PoliticalExposureType": "Politicalexposuredomestic", + "PoliticalExposureDescriptionRecord": " Member of a regional council since 2021 ", + "CustomerSinceDate": "2015-03-02T10:00:00+01:00", + "GovernmentIssuedDocumentDetails": { + "PartyDocumentType": "PersonalDocument", + "DocumentReference": { + "DocumentIdentification": { "IdentifierValue": "23AB45678" }, + "DocumentName": "Passport", + "DocumentValidityPeriod": { + "FromDateTime": { "DateTimeContent": "2023-04-01" }, + "ToDateTime": { "DateTimeContent": "2033-03-31T00:00:00Z" } + } + } + }, + "DocumentDirectoryEntryInstanceReference": { "DocumentDirectoryEntryIdentification": " DOC-000123 " } + } + """; + + [Fact] + public async Task Update_then_retrieve_answers_the_reference_and_the_versions() + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + + var updated = (await UpdateAsync(host, entry, Person, entry.Version, PartyTools.Key("update"))).Success(); + var retrieved = (await RetrieveAsync(host, entry.Id.ToString(), entry.ReferenceId.ToString())).Success(); + + updated.GetProperty("PartyFullLegalName").GetString().ShouldBe("Jeanne Marie Dupont"); + updated.GetProperty("Nationality").GetProperty("Code").GetString().ShouldBe("FR"); + updated.GetProperty("ResidentialAddress").GetProperty("TownName").GetString().ShouldBe("Paris"); + updated.GetProperty("CustomerSinceDate").GetString().ShouldBe("2015-03-02"); + updated.GetProperty("version").GetInt64().ShouldBe(entry.Version + 1); + JsonElement.DeepEquals(retrieved, updated).ShouldBeTrue($"{retrieved} vs {updated}"); + } + + [Fact] + public async Task A_left_out_field_keeps_its_value_an_empty_one_clears_it_and_an_address_is_replaced_whole() + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + var first = (await UpdateAsync(host, entry, Person, entry.Version, PartyTools.Key("first"))).Success(); + + var second = (await UpdateAsync( + host, + entry, + """{ "PartyNameSalutation": "", "ResidentialAddress": { "TownName": "Lyon", "Country": { "Code": "FR" } } }""", + first.GetProperty("version").GetInt64(), + PartyTools.Key("second"))) + .Success(); + + second.GetProperty("PartyFullLegalName").GetString().ShouldBe("Jeanne Marie Dupont"); + second.TryGetProperty("PartyNameSalutation", out _).ShouldBeFalse(); + var address = second.GetProperty("ResidentialAddress"); + address.GetProperty("TownName").GetString().ShouldBe("Lyon"); + address.TryGetProperty("StreetName", out _).ShouldBeFalse(); + } + + [Theory] + [InlineData("""{ "PartyLegalEntityReference": { "Identification": "5493001KJTIIGC8Y1R13" } }""")] + [InlineData("""{ "eMailAddress": { "EmailAddress": "not-an-email" } }""")] + [InlineData("""{ "Nationality": { "Code": "XX" } }""")] + public async Task An_invalid_value_is_a_validation_problem(string request) + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + + (await UpdateAsync(host, entry, request, entry.Version, PartyTools.Key("invalid"))).Problem(400, "party.reference-invalid"); + (await host.ScalarAsync(PartyTools.EventsOf(entry.Id))).ShouldBe(1); + } + + [Fact] + public async Task A_part_rimbank_does_not_record_is_refused() + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + + (await UpdateAsync(host, entry, """{ "eMailAddress": { "EmailAddress": "jeanne@example.fr", "Identification": "x" } }""", entry.Version, PartyTools.Key("refused"))) + .Problem(400, "party.reference-field-not-supported"); + } + + [Fact] + public async Task Corporate_and_officer_references_are_recorded_on_an_organisation_only() + { + await using var host = await server.StartHostAsync(); + var company = await Entry.RegisterAsync(host, "Organisation"); + var person = await Entry.RegisterAsync(host, "Person"); + var group = await Entry.RegisterAsync(host, "Organisation"); + var references = Corporate(group.Id, person.Id); + + var recorded = (await UpdateAsync(host, company, references, company.Version, PartyTools.Key("company"))).Success(); + (await UpdateAsync(host, person, references, person.Version, PartyTools.Key("person"))) + .Problem(422, "party.corporate-references-need-organisation"); + + recorded.GetProperty("CompanyOfficerReference").GetProperty("PartyReference").GetGuid().ShouldBe(person.Id); + recorded.GetProperty("CompanyOfficerRole").GetString().ShouldBe("Director"); + } + + [Fact] + public async Task A_version_that_is_no_longer_current_is_a_conflict() + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + (await UpdateAsync(host, entry, "{}", entry.Version, PartyTools.Key("first"))).Success(); + + (await UpdateAsync(host, entry, "{}", entry.Version, PartyTools.Key("stale"))) + .Problem(409, PartyReferenceDataDirectoryEntryErrors.VersionConflict.Code); + } + + internal static string Corporate(Guid organisation, Guid person) => + $$""" + { + "CorporateCustomerReference": { "PartyReference": "{{organisation}}" }, + "CorporateCustomerLegalEntityReference": { "PartyReference": "{{organisation}}" }, + "CompanyOfficerReference": { "PartyReference": "{{person}}" }, + "CompanyOfficerRole": " Director " + } + """; + + internal static Task UpdateAsync(PartyMcpHost host, Entry entry, string request, long expectedVersion, string key) => + host.CallAsync( + UpdatePartyReferenceTool.Name, + new() + { + ["partyReferenceDataDirectoryEntryId"] = entry.Id.ToString(), + ["referenceId"] = entry.ReferenceId.ToString(), + ["request"] = JsonElement.Parse(request), + ["expectedVersion"] = expectedVersion, + ["idempotencyKey"] = key, + }); + + internal static Task RetrieveAsync(PartyMcpHost host, string entryId, string referenceId) => + host.CallAsync( + RetrievePartyReferenceTool.Name, + new() { ["partyReferenceDataDirectoryEntryId"] = entryId, ["referenceId"] = referenceId }); +} diff --git a/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryParityTests.cs b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryParityTests.cs new file mode 100644 index 0000000..46b4bd5 --- /dev/null +++ b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryParityTests.cs @@ -0,0 +1,63 @@ +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp.Tests; + +// Roadmap 1.17: party_reference_data_directory_update answers as PUT …/{id}/Update does: the same body with the ETag as +// version, and the same Problem Details (ADR 0039, ADR 0040). +public sealed class UpdatePartyReferenceDataDirectoryEntryParityTests(PostgresqlServer server) +{ + private static readonly string[] _ids = ["PartyReferenceDataDirectoryEntryId", "DemographicsId", "ReferenceId", "BankRelationsId"]; + + [Fact] + public async Task Update_gives_the_http_body_and_the_etag_as_version() + { + await using var host = await server.StartHostAsync(); + var (overHttp, httpVersion) = await PartyTools.RegisterAsync(host, "Person"); + var (overMcp, mcpVersion) = await PartyTools.RegisterAsync(host, "Person"); + const string body = """{ "PartyType": "Organisation" }"""; + + var http = await Parity.HttpAsync(host, HttpMethod.Put, Url(overHttp), 200, body, PartyTools.Key("http"), httpVersion); + var tool = await UpdatePartyReferenceDataDirectoryEntryToolTests.UpdateAsync(host, overMcp, body, mcpVersion, PartyTools.Key("mcp")); + + await Parity.ShouldMirrorAsync(http, tool, _ids); + } + + [Theory] + [InlineData("""{ "PartyType": "Alien" }""", 400)] + [InlineData("""{ "PartyType": "" }""", 400)] + public async Task An_invalid_party_type_is_the_same_problem(string body, int status) + { + await using var host = await server.StartHostAsync(); + var (id, version) = await PartyTools.RegisterAsync(host, "Person"); + + var http = await Parity.HttpAsync(host, HttpMethod.Put, Url(id), status, body, PartyTools.Key("http"), version); + var tool = await UpdatePartyReferenceDataDirectoryEntryToolTests.UpdateAsync(host, id, body, version, PartyTools.Key("mcp")); + + await Parity.ShouldBeSameProblemAsync(http, tool); + } + + [Fact] + public async Task A_stale_version_is_the_same_problem() + { + await using var host = await server.StartHostAsync(); + var (id, version) = await PartyTools.RegisterAsync(host, "Person"); + (await UpdatePartyReferenceDataDirectoryEntryToolTests.UpdateAsync(host, id, "{}", version, PartyTools.Key("first"))).Success(); + + var http = await Parity.HttpAsync(host, HttpMethod.Put, Url(id), 409, "{}", PartyTools.Key("http"), version); + var tool = await UpdatePartyReferenceDataDirectoryEntryToolTests.UpdateAsync(host, id, "{}", version, PartyTools.Key("mcp")); + + await Parity.ShouldBeSameProblemAsync(http, tool); + } + + [Fact] + public async Task An_unknown_entry_is_the_same_problem() + { + await using var host = await server.StartHostAsync(); + var id = Guid.CreateVersion7(); + + var http = await Parity.HttpAsync(host, HttpMethod.Put, Url(id), 404, "{}", PartyTools.Key("http"), 1); + var tool = await UpdatePartyReferenceDataDirectoryEntryToolTests.UpdateAsync(host, id, "{}", 1, PartyTools.Key("mcp")); + + await Parity.ShouldBeSameProblemAsync(http, tool); + } + + private static string Url(Guid id) => $"/PartyReferenceDataDirectory/{id}/Update"; +} diff --git a/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryToolTests.cs b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryToolTests.cs new file mode 100644 index 0000000..98c3523 --- /dev/null +++ b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryToolTests.cs @@ -0,0 +1,135 @@ +using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; +using ModelContextProtocol.Protocol; +using ModelContextProtocol.Server; + +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp.Tests; + +// Roadmap 1.17: party_reference_data_directory_update sends the same UpdatePartyReferenceDataDirectoryEntry as the HTTP +// endpoint, with expectedVersion in place of If-Match and the BIAN body as its request argument (ADR 0039, ADR 0040). +public sealed class UpdatePartyReferenceDataDirectoryEntryToolTests(PostgresqlServer server) +{ + [Fact] + public async Task The_request_argument_is_the_bian_body_with_its_property_names() + { + await using var host = await server.StartHostAsync(); + var tool = host.Alba.Services.GetServices().Single(tool => tool.ProtocolTool.Name == UpdatePartyReferenceDataDirectoryEntryTool.Name); + var schema = tool.ProtocolTool.InputSchema; + TestContext.Current.TestOutputHelper?.WriteLine(schema.GetRawText()); + + schema.GetProperty("required").EnumerateArray().Select(name => name.GetString()).ShouldBe( + ["partyReferenceDataDirectoryEntryId", "request", "expectedVersion", "idempotencyKey"], + ignoreOrder: true); + var request = schema.GetProperty("properties").GetProperty("request"); + request.GetProperty("properties").EnumerateObject().Select(property => property.Name) + .ShouldBe(["PartyReference", "DirectoryEntryDateType", "DirectoryEntryDate", "PartyType"], ignoreOrder: true); + schema.GetProperty("properties").GetProperty("expectedVersion").GetProperty("type").GetString().ShouldBe("integer"); + } + + [Fact] + public async Task Update_answers_the_entry_with_its_new_version_and_refresh_date() + { + await using var host = await server.StartHostAsync(); + var (id, version) = await PartyTools.RegisterAsync(host, "Person"); + + var entry = (await UpdateAsync(host, id, """{ "PartyType": "Organisation" }""", version, "update-1")).Success(); + + entry.GetProperty("PartyReferenceDataDirectoryEntryId").GetGuid().ShouldBe(id); + entry.GetProperty("PartyType").GetString().ShouldBe("Organisation"); + entry.GetProperty("RefreshDate").GetDateTimeOffset().ShouldBe(PostgresqlServer.Now); + entry.GetProperty("version").GetInt64().ShouldBe(version + 1); + } + + [Fact] + public async Task A_left_out_party_type_keeps_the_current_one_and_ignored_fields_are_accepted() + { + await using var host = await server.StartHostAsync(); + var (id, version) = await PartyTools.RegisterAsync(host, "Person"); + + var entry = (await UpdateAsync(host, id, """{ "PartyReference": { "x": 1 }, "Unknown": true }""", version, "update-keep")).Success(); + + entry.GetProperty("PartyType").GetString().ShouldBe("Person"); + } + + [Fact] + public async Task A_version_that_is_no_longer_current_is_a_conflict() + { + await using var host = await server.StartHostAsync(); + var (id, version) = await PartyTools.RegisterAsync(host, "Person"); + (await UpdateAsync(host, id, "{}", version, "update-first")).Success(); + + (await UpdateAsync(host, id, "{}", version, "update-stale")).Problem(409, PartyReferenceDataDirectoryEntryErrors.VersionConflict.Code); + } + + [Fact] + public async Task The_same_key_and_arguments_replay_the_first_answer() + { + await using var host = await server.StartHostAsync(); + var (id, version) = await PartyTools.RegisterAsync(host, "Person"); + + var first = (await UpdateAsync(host, id, """{ "PartyType": "Organisation" }""", version, "update-twice")).Success(); + var second = (await UpdateAsync(host, id, """{ "PartyType": "Organisation" }""", version, "update-twice")).Success(); + + second.GetRawText().ShouldBe(first.GetRawText()); + (await host.ScalarAsync(PartyTools.EventsOf(id))).ShouldBe(2); + } + + [Theory] + [InlineData("", "party.party-type-invalid")] + [InlineData("Alien", "party.party-type-invalid")] + public async Task An_invalid_party_type_is_a_validation_problem(string partyType, string errorCode) + { + await using var host = await server.StartHostAsync(); + var (id, version) = await PartyTools.RegisterAsync(host, "Person"); + + (await UpdateAsync(host, id, JsonSerializer.Serialize(new { PartyType = partyType }), version, "update-invalid")) + .Problem(400, errorCode); + } + + [Fact] + public async Task An_unknown_entry_is_a_not_found_problem() + { + await using var host = await server.StartHostAsync(); + + (await UpdateAsync(host, Guid.CreateVersion7(), "{}", 1, "update-unknown")) + .Problem(404, PartyReferenceDataDirectoryEntryErrors.PartyNotFound.Code); + } + + [Theory] + [InlineData("request")] + [InlineData("expectedVersion")] + [InlineData("idempotencyKey")] + public async Task A_missing_argument_is_a_tool_arguments_problem(string missing) + { + await using var host = await server.StartHostAsync(); + var (id, version) = await PartyTools.RegisterAsync(host, "Person"); + var arguments = Arguments(id, "{}", version, "update-missing"); + arguments.Remove(missing); + + (await host.CallAsync(UpdatePartyReferenceDataDirectoryEntryTool.Name, arguments)).Problem(400, "shared.tool-arguments-invalid"); + (await host.ScalarAsync(PartyTools.EventsOf(id))).ShouldBe(1); + } + + [Fact] + public async Task A_request_that_is_not_an_object_is_a_tool_arguments_problem() + { + await using var host = await server.StartHostAsync(); + var (id, version) = await PartyTools.RegisterAsync(host, "Person"); + var arguments = Arguments(id, "{}", version, "update-not-object"); + arguments["request"] = "Organisation"; + + (await host.CallAsync(UpdatePartyReferenceDataDirectoryEntryTool.Name, arguments)).Problem(400, "shared.tool-arguments-invalid"); + } + + internal static Task UpdateAsync(PartyMcpHost host, Guid id, string request, long expectedVersion, string key) => + host.CallAsync(UpdatePartyReferenceDataDirectoryEntryTool.Name, Arguments(id, request, expectedVersion, key)); + + private static Dictionary Arguments(Guid id, string request, long expectedVersion, string key) => + new() + { + ["partyReferenceDataDirectoryEntryId"] = id.ToString(), + ["request"] = JsonElement.Parse(request), + ["expectedVersion"] = expectedVersion, + ["idempotencyKey"] = key, + }; +} diff --git a/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/VersionRoundTripTests.cs b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/VersionRoundTripTests.cs new file mode 100644 index 0000000..69cf2ff --- /dev/null +++ b/tests/RimBank.Mcp.Tests/Party/PartyReferenceDataDirectory/VersionRoundTripTests.cs @@ -0,0 +1,61 @@ +namespace RimBank.Party.PartyReferenceDataDirectory.Mcp.Tests; + +// Roadmap 1.17: expectedVersion is MCP's If-Match (ADR 0027, ADR 0040). The version a Retrieve gives lets one Update +// through, that Update's version lets the next one through, and a version already used is a conflict. +public sealed class VersionRoundTripTests(PostgresqlServer server) +{ + [Fact] + public async Task A_retrieved_version_updates_once_and_the_answers_version_updates_next() + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + var retrieved = (await PartyReferenceToolTests.RetrieveAsync(host, entry.Id.ToString(), entry.ReferenceId.ToString())).Success(); + var version = retrieved.GetProperty("version").GetInt64(); + + var first = (await PartyReferenceToolTests.UpdateAsync(host, entry, """{ "PartyFullLegalName": "Jeanne Dupont" }""", version, PartyTools.Key("first"))) + .Success(); + var stale = await PartyReferenceToolTests.UpdateAsync(host, entry, """{ "PartyNameSalutation": "Ms" }""", version, PartyTools.Key("stale")); + var next = (await DemographicsToolTests.UpdateAsync( + host, entry, """{ "EducationHistory": "MSc" }""", first.GetProperty("version").GetInt64(), PartyTools.Key("next"))) + .Success(); + + first.GetProperty("version").GetInt64().ShouldBe(version + 1); + stale.Problem(409, PartyReferenceDataDirectoryEntryErrors.VersionConflict.Code); + next.GetProperty("version").GetInt64().ShouldBe(version + 2); + (await host.ScalarAsync(PartyTools.EventsOf(entry.Id))).ShouldBe(3); + } + + [Fact] + public async Task The_same_key_and_request_return_the_first_answer_without_a_second_event() + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + const string request = """{ "PartyFullLegalName": "Jeanne Dupont" }"""; + + var first = (await PartyReferenceToolTests.UpdateAsync(host, entry, request, entry.Version, "reference-once")).Success(); + var again = (await PartyReferenceToolTests.UpdateAsync(host, entry, request, entry.Version, "reference-once")).Success(); + + again.GetRawText().ShouldBe(first.GetRawText()); + (await host.ScalarAsync(PartyTools.EventsOf(entry.Id))).ShouldBe(2); + } + + [Fact] + public async Task A_missing_expected_version_is_a_tool_arguments_problem_and_nothing_is_stored() + { + await using var host = await server.StartHostAsync(); + var entry = await Entry.RegisterAsync(host); + + var result = await host.CallAsync( + UpdateBankRelationsTool.Name, + new() + { + ["partyReferenceDataDirectoryEntryId"] = entry.Id.ToString(), + ["bankRelationsId"] = entry.BankRelationsId.ToString(), + ["request"] = System.Text.Json.JsonElement.Parse("{}"), + ["idempotencyKey"] = PartyTools.Key("missing"), + }); + + result.Problem(400, "shared.tool-arguments-invalid"); + (await host.ScalarAsync(PartyTools.EventsOf(entry.Id))).ShouldBe(1); + } +}