Skip to main content
Glama

AWS Payment Cryptography MCP Server

CI Release Latest Release Python 3.11+ License

An MCP server for AWS Payment Cryptography (APC). Gives AI coding assistants direct access to the APC control plane (key lifecycle) and data plane (cryptographic operations), along with embedded knowledge of payment standards, HSM vendor command sets, and PCI PIN v3.1 compliance requirements. This tool is for development and testing purposes only and should not be used directly within a production system. It is designed to accelerate the 'Proof of Concept' phase and migration analysis by providing a domain-aware interface for AWS Payment Cryptography. Works with Claude Code, Codex CLI, and any MCP-compatible client.

There are three reasons to use this:

  1. You're building a new acquirer or processor integration on APC and want an AI co-pilot that understands the domain — key hierarchies, DUKPT, TR-31/TR-34, PIN formats, compliance constraints — without reading documentation for every API call.

  2. You have existing code that runs against a Thales payShield 10K or Futurex Excrypt Enterprise SSP v.2 and want to understand what it's doing before migrating to APC.

  3. You're using apc-hsm-proxy to move an application to APC without refactoring it, and need to build handlers for the specific commands your application sends.

Issuer functions — card personalization, IMK/CMK derivation, issuer script processing — are out of scope. A small number of issuer-adjacent APC operations (PIN generation schemes, EMV secure messaging) are exposed for completeness but are not the focus. This is a template, not a production system.


Architecture & Trust Boundaries

graph LR
      subgraph "Your Local Host"
          A[AI Client] <--> B[MCP Server]
          B --> G([Boto3])
      end
      subgraph "Your AWS Account"
          D[APC Control Plane]
          E[APC Data Plane]
      end
      subgraph "Your LLM Provider"
          F[LLM API]
      end

      G --> D
      G --> E
      A <-- "Prompts/Responses" --> F
      D ~~~ F
      D ~~~ E

Related MCP server: code-security-skill

Setup

pip install -e .
apc-agent        # starts the MCP server over stdio

The MCP server is client-agnostic — it speaks the standard Model Context Protocol over stdio and works with any MCP-compatible client. .claude/ contains Claude Code settings; .codex/ is the Codex CLI equivalent. Neither is required to run the server itself.

Claude Code — .claude/settings.json in this repo registers the server automatically. For Claude Desktop, add the same block to ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or %APPDATA%\Claude\claude_desktop_config.json (Windows):

{
  "mcpServers": {
    "apc-agent": {
      "command": "apc-agent",
      "env": { "AWS_REGION": "us-east-1" }
    }
  }
}

Codex CLI — .codex/config.toml in this repo registers the server automatically. For user-level registration (applies across all projects), add the same block to ~/.codex/config.toml:

[mcp_servers.apc-agent]
command = "apc-agent"
env = { AWS_REGION = "us-east-1" }

Or register via the CLI:

codex mcp add apc-agent --env AWS_REGION=us-east-1 -- apc-agent

Kiro — Add to Kiro

AWS credentials are consumed via the standard boto3 chain: IAM role, ~/.aws/credentials, or environment variables. Set AWS_REGION to the region where your APC resources live.

See EXAMPLES.md for end-to-end session excerpts — one per workflow — showing exact prompts, tool calls, and results.


Workflow 1 — Building a new integration

Who it's for: Payment engineers and solutions architects building a new acquirer or processor system on AWS, starting from scratch or greenfield on APC.

What you do: Describe your architecture in plain language. The AI calls APC directly, explains every decision, and checks compliance before making any API call. You get working code and a key hierarchy — not just documentation references.

How it works:

  1. Install the MCP server and connect it to your AI client (Claude Code, Codex CLI, etc.).

  2. Describe what you're building. Example: "I need AES DUKPT for a fleet of POS terminals. PIN blocks should go to ISO Format 4, translated over a ZPK to my network processor, with CMAC on ISO 8583 field 64."

  3. The AI creates the keys in APC, explains the hierarchy, writes the integration code, and flags any compliance issues before calling any API.

The default for a new acquirer integration:

Terminal / POI
  └── AES DUKPT (BDK in APC, KSN per transaction)
        └── ISO Format 4 PIN block → translate_pin_data
              └── ZPK (AES P0) → host-to-host PIN routing
                    └── CMAC (AES M6) on ISO 8583 field 64

Key Exchange with Network / Processor
  └── TR-34 (asymmetric KEK establishment)
        └── TR-31 / X9.143 for all subsequent symmetric key transport

Card Data Protection
  └── AES (D0) or FF1 FPE for format-preserving tokenization

Deviating from this path — TDES, Format 0 PIN blocks, TDES DUKPT, CBC-MAC — requires explicit confirmation. The agent explains why the modern approach is preferred, asks whether you've confirmed the downstream system doesn't support it, then helps implement the legacy path correctly with a documented code comment and a notice that a QSA exception may be required.

Compliance enforcement is built into the tool layer and is not configurable off. Hard stops enforced in code: illegal PIN format translation pairs (PCI PIN Req 3-3), AES keys with non-CMAC KCV (PCI PIN Annex C), unknown TR-31 key usage codes. Legacy construct warnings (Format 0, CBC-MAC, retail MAC) require explicit confirmation before proceeding. PAN identity during PIN translation and algorithm-level prohibitions (single DES, RSA < 2048) are enforced by APC at the API level — calls with prohibited parameters are rejected by the service.


Workflow 2 — Migrating existing HSM code

Who it's for: Developers migrating an application that currently sends commands to a Thales payShield 10K or Futurex Excrypt Enterprise SSP v.2, who need to understand what the code is doing before writing the APC replacement.

What you do: Show the AI your existing source code. It identifies every HSM operation in use, maps each one to the equivalent APC call with the correct key type, and flags anything with no direct equivalent or that requires architectural changes.

How it works:

  1. Connect the MCP server to your AI client and open the relevant source files.

  2. Ask it to analyze them. Example: "What HSM operations does this code use and what are the APC equivalents?"

  3. The AI calls hsm_analyze_code, which scans for Futurex Excrypt bracket-delimited commands ([AOTPIN;...] / [TPIN;...]) and Thales two-char command codes (CA, G0, M6, etc.) in the source, then looks each one up in the command registry.

  4. For each command detected: the APC operation to call, the required key type (TR-31 usage code), a confidence level, and migration notes.

  5. The AI writes the refactored code using the APC SDK and validates it against the compliance rules.

LMK key migration: Keys stored as LMK-encrypted blobs in your application or database can't be imported into APC directly. They must be exported from the source HSM in TR-31 or TR-34 format first. The server surfaces this when it detects LMK references and guides the import process using get_parameters_for_import and import_key.

Coverage: Futurex Excrypt Enterprise SSP v.2 / Standard API (authoritative — Futurex General Payment HSM Integration Guide 2024), Thales payShield 10K Legacy commands (authoritative — Thales payShield 10K Legacy Host Commands manual), Thales payShield 10K International/Core commands (mixed — core PIN/MAC/CVV/ARQC codes authoritative via Futurex Integration Guide; key management and PIN verify codes reference quality), Atalla/HPE/NCR (directory quality — command names and APC mappings only, no parameter detail; proxy support not implemented).


Workflow 3 — Building proxy handlers

Who it's for: Teams using apc-hsm-proxy — where the application is a black box, third-party, or can't be refactored, so a protocol translation layer handles the HSM-to-APC conversion instead.

What you do: Run the proxy in discovery mode to observe what commands your application actually sends, then use this server to build handlers for those specific commands.

How it works:

  1. Configure apc-hsm-proxy with discover.enabled: true, hsm_host pointing at your real HSM, and log_file: discovery.jsonl. Start the proxy between your application and the real HSM. The proxy forwards unhandled commands to the real HSM while writing one JSON record per unique command code to discovery.jsonl — command code, vendor, and parameter names (key blocks and PIN blocks are redacted).

  2. Run your application through a representative set of transactions. Stop the proxy. Open discovery.jsonl — it will have one entry per distinct command your application sent.

  3. In an AI coding session with the MCP server connected, read discovery.jsonl and call hsm_analyze_discovery_log with its contents. The tool returns: which commands already have proxy handlers, which need to be built, the APC operation and key type for each, and the exact file path and handler structure to implement for each one.

  4. The AI writes the Rust handler for each command modeled on the existing handlers in the proxy's src/handlers/<vendor>/ directory. You add the file, register it in mod.rs, and rebuild the proxy.

  5. Disable discovery mode (discover.enabled: false) and test with the real application. The proxy now routes the handled commands to APC and returns error 68 for anything unrecognized.

Common APC constraints when implementing handlers — surfaced during live integration testing of apc-hsm-proxy against real APC:

  • DUKPT key variant: DukptKeyVariant::Bidirectional is valid for AES DUKPT (X9.24-3) only. 3DES DUKPT (X9.24-1 / TDES_2KEY) requires Request or Response — passing Bidirectional returns ValidationException: Invalid DukptKeyVariant provided for key algorithm. Use Request for terminal-originated MACs.

  • AES-CMAC truncated verify: verify_mac for AES-CMAC requires the full 16-byte (32H) MAC. payShield M8 sends a truncated MAC (e.g., 4 bytes). Passing truncated output causes ValidationException. Workaround: call generate_mac and compare the leading mac_size bytes in the handler.

  • IBM 3624 PIN offset padding: verify_pin_data for IBM 3624 requires a digits-only PinOffset (^[0-9]+$). payShield pads the offset to 12 hex characters with F (e.g., 9237FFFFFFFF). Strip trailing F characters in the handler before calling APC.

The discovery log is the handoff between the two tools. Because it deduplicates — writing once per command code, not once per transaction — it stays small and works directly as source context in an AI coding session.


Testing

pip install pytest pytest-asyncio "moto[payment-cryptography]"
python -m pytest

Project Structure

src/apc_agent/
├── server.py          — FastMCP entry point; registers all tool groups and the KB resource
├── control_plane.py   — Key lifecycle tools (payment-cryptography client)
├── data_plane.py      — Cryptographic operation tools (payment-cryptography-data client)
├── hsm_tools.py       — HSM analysis and discovery log MCP tools
├── hsm_analysis.py    — HSM command registry and regex patterns
├── system_prompt.py   — Domain knowledge injected as MCP instructions
└── compliance.py      — PCI guard-rail logic: hard stops, warnings, key usage registry

payment-knowledge-base.md                    — MCP resource: payment://knowledge-base
aws-payment-cryptography-data-plane-use-cases.json  — APC data plane capability catalog (source of truth for tool implementation)

The knowledge base is exposed as an MCP resource at payment://knowledge-base. It covers card data, PIN blocks, card verification values, EMV tags, ISO 8583 fields, key types, HSM commands, cryptographic algorithms, and constraint rules. The agent reads it on demand; it is not injected into the system prompt. Add new entries to payment-knowledge-base.md and update the Sources table at the bottom — no server restart required.

HSM command mapping reference: docs/hsm-apc-command-mapping.md — human-readable tables mapping Thales payShield (International/Core and Legacy) command codes to APC operations and TR-31 key types, with migration notes. Futurex Excrypt and Atalla sections are stubbed for future addition.


Testimonial

While working on CyberChef Payments:

Me: "tell me, did the apc-agent mcp server help at all in the work you completed"

Kiro: "Yes, genuinely — and in specific ways that reading the code alone wouldn't have caught. It acted as a fast, authoritative reference for the parts of the payment domain that are hard to verify from code alone — key type constraints, PCI requirement numbers, and the AES DUKPT migration boundary. Worth having for that kind of domain-grounding work."


Security & Privacy

Production Data: Never use this tool with production cryptographic keys, real Primary Account Numbers (PANs), or live PIN blocks.

Data Handling: This tool interfaces with Large Language Models (LLMs). Any data provided in a prompt—including key metadata, command logs, or test identifiers—may be sent to the LLM provider. Ensure all data used with this server is strictly for development or synthetic testing.

Credential Safety: The server uses the standard boto3 credential chain. Ensure your environment is configured with the least-privilege IAM permissions required for payment-cryptography actions.

No Plaintext Keys: This tool does not support and will never prompt for plaintext key material (Clear Components). All key operations must be performed using encrypted tokens or service-managed keys within AWS Payment Cryptography.


Development Note

This project was built with AI-assisted development. AI was used to accelerate implementation, testing, documentation, and research synthesis. Architecture, scope, source selection, review, and final publish decisions were made by the author.

Because this project touches payment-cryptography topics, claims in the code and documentation were reviewed against authoritative vendor and AWS documentation where possible. Remaining limitations and uncertainty are called out explicitly.


Authoritative References

All APC API behavior in this codebase is derived from these sources.

Available Tools

58 tools
add_key_replication_regionsA

Call this to make an existing key usable from additional regions — e.g. standing up a DR region, or moving an acquirer workload closer to the processor.

Replication copies the key into the named regions so cryptographic calls can be served there. It does not export key material: the key never leaves APC's HSMs, and the replica keeps the same key ARN semantics and usage restrictions.

Args: key_identifier: ARN or alias of the key replication_regions: Regions to add, e.g. ["us-west-2", "eu-west-1"]

Inputs: key_identifier (required), replication_regions (required).

associate_mpa_teamA

Call this to put a sensitive key-management operation behind Multi-Party Approval, so it requires sign-off from an AWS MPA approval team before it takes effect.

This is the APC equivalent of the dual-control requirement PCI PIN places on key management: no single custodian can complete the operation alone. Associating a team does not itself need approval; it changes how the named operation behaves from then on.

Once associated, calls to the covered operation return with an MpaStatus of PENDING rather than completing. See import_key for what that means in practice.

Args: action: The operation to protect. Currently only IMPORT_ROOT_PUBLIC_KEY_CERTIFICATE is supported by APC. mpa_team_arn: ARN of the AWS Multi-Party Approval team, of the form arn:aws:mpa:::approval-team/ requester_comment: Optional reason for the change, max 200 characters. Appears in CloudTrail in plaintext — no sensitive data.

Inputs: action (required), mpa_team_arn (required), requester_comment.

contribute_kb_findingA

Call this whenever you discover a gap while working in any repo — apc-hsm-proxy, CyberChef-Payments, or any other session — and the finding belongs in this MCP server's knowledge base, HSM command registry, proxy handler list, or compliance rules. Works without AWS credentials.

Stages the finding as a GitHub issue so the MCP server session can apply it at the next session start. Returns a formatted issue body and the exact gh CLI command to run.

finding_type options: "kb_entry" — new or corrected entry for payment-knowledge-base.md "hsm_command" — new HSM command to add to hsm_analysis.py ALL_COMMANDS "proxy_handler" — handler completed in apc-hsm-proxy; needs _PROXY_HANDLERS update "compliance_rule" — new PCI or scheme rule for compliance.py "apc_constraint" — APC API gap or undocumented constraint for AGENTS.md

Args: finding_type: One of the five types above summary: One-line description — becomes the GitHub issue title content: The content to add, formatted for the target file (KB YAML, HsmCommand(), etc.) source_repo: Which repo or context revealed this — e.g. "apc-hsm-proxy GW handler" context: Optional additional context — related files, downstream impact, etc.

Inputs: content (required), summary (required), source_repo (required), finding_type (required), +1 more.

create_aliasA

Call this when establishing a stable name for a key so application code does not need to change when keys are rotated.

Create a friendly-name alias for a key.

Args: alias_name: Must start with 'alias/' — e.g. alias/prod-bdk key_arn: Key ARN to associate (optional at creation time)

Inputs: alias_name (required), key_arn.

create_keyA

Call this when creating a new cryptographic key — BDK, ZPK, CVK, MAC key, KEK, etc. Call explain_key_usage first to confirm the right key usage code — APC keys are typed at creation and the type cannot change.

AES keys must use CMAC for KCV (not ANSI_X9_24). Enforced here.

Args: key_algorithm: AES_128, AES_256, TDES_3KEY, RSA_2048, RSA_3072, RSA_4096, ECC_NIST_P256, etc. key_usage: TR-31 key usage code, e.g. TR31_P0_PIN_ENCRYPTION_KEY key_class: SYMMETRIC_KEY, ASYMMETRIC_KEY_PAIR, or PRIVATE_KEY exportable: Whether the key can be exported via TR-31 or TR-34 enabled: Whether the key is immediately active (default true) key_check_value_algorithm: CMAC, ANSI_X9_24, HMAC, or SHA_1. AES keys must use CMAC (ANSI_X9_24 is rejected here per PCI PIN Annex C); TDES may use either. HMAC keys use HMAC — the construction is fixed but the hash is the one bound to the key at creation, over a zero-length message, so reproducing the KCV outside APC requires knowing that hash. Asymmetric keys use SHA_1. tags: Optional list of {Key, Value} tag dicts derive_key_usage: For a BDK (B0) only — the TR-31 usage the derived DUKPT working keys will carry, e.g. TR31_P0_PIN_ENCRYPTION_KEY. APC binds this at creation, so a BDK created without it cannot later derive keys of that usage. replication_regions: Optional list of regions to replicate this key into, e.g. ["us-west-2", "eu-west-1"]. Omit to use the account default (see get_default_key_replication_regions). Replication is a property of the key, so set it here or via add_key_replication_regions afterwards.

Inputs: key_class (required), key_usage (required), exportable (required), key_algorithm (required), +5 more.

decrypt_dataA

Call this when decrypting cardholder data or payment fields received from a terminal, acquiring host, or issuer — including DUKPT session-key decryption and EMV confidentiality decryption.

Supported key types: D0, D1, B0 (DUKPT), E1/E6 (EMV). All inputs and outputs are hexBinary encoded.

Args: key_identifier: Key ARN or alias of the KEK (when using wrapped_key) or the working key cipher_text: Hex-encoded ciphertext decryption_attributes: Algorithm-specific parameters (mirrors encrypt_data) wrapped_key: Optional TR-31 wrapped working key (key_identifier becomes the KEK)

Inputs: cipher_text (required), key_identifier (required), decryption_attributes (required), wrapped_key.

delete_aliasA

Call this when removing a friendly name that is no longer needed. The underlying key is unaffected.

Delete an alias (does not delete the underlying key).

Args: alias_name: Full alias name including 'alias/' prefix

Inputs: alias_name (required).

delete_keyA

Call this when decommissioning a test key or retiring a key that is no longer needed. Deletion is scheduled — the key enters DELETE_PENDING state first.

Schedule a key for deletion.

Args: key_identifier: Key ARN or alias delete_key_in_days: Waiting period before deletion (3-180 days, default 7)

Inputs: key_identifier (required), delete_key_in_days.

delete_resource_policyA

Call this when revoking all cross-account or resource-based access grants on a key.

Remove the resource policy from a key.

Args: resource_arn: Key ARN

Inputs: resource_arn (required).

disable_default_key_replication_regionsA

Call this to stop new keys from automatically replicating into the named regions.

Account-level and forward-looking only: existing keys keep whatever replication they already have. Use remove_key_replication_regions to change those.

Args: replication_regions: Regions to remove from the default, e.g. ["eu-west-1"]

Inputs: replication_regions (required).

disassociate_mpa_teamA

Call this to remove Multi-Party Approval from an operation, returning it to single-principal control.

This weakens a dual-control boundary, so it is worth confirming intent before calling — under PCI PIN, removing dual control from key management is a compliance-relevant change, not a routine configuration tweak.

The association moves to DELETE_PENDING and may itself require approval from the currently associated team before it clears.

Args: action: The operation to stop protecting, e.g. IMPORT_ROOT_PUBLIC_KEY_CERTIFICATE requester_comment: Optional reason, max 200 characters. Plaintext in CloudTrail.

Inputs: action (required), requester_comment.

enable_default_key_replication_regionsA

Call this to add regions to the account-wide default, so subsequently created keys replicate there automatically.

This is account-level and affects future keys only — it does not retroactively replicate existing keys. Use add_key_replication_regions for keys that already exist.

Args: replication_regions: Regions to enable by default, e.g. ["us-west-2"]

Inputs: replication_regions (required).

encrypt_dataA

Call this when encrypting cardholder data, PIN blocks, or sensitive payment fields for storage or transmission. Also use when implementing DUKPT session encryption or EMV session-key-based data confidentiality.

Supported key types: D0 (symmetric), D1 (asymmetric RSA), B0 (DUKPT), E1/E6 (EMV). All inputs and outputs are hexBinary encoded.

encryption_attributes examples: Symmetric AES-CBC: {"Symmetric": {"Mode": "CBC", "InitializationVector": "<16-byte hex>"}} DUKPT AES: {"Dukpt": {"KeySerialNumber": "", "Mode": "CBC", "DukptKeyDerivationType": "AES_128"}} EMV: {"Emv": {"MajorKeyDerivationMode": "EMV_OPTION_A", "PrimaryAccountNumber": "...", "PanSequenceNumber": "01", "SessionDerivationData": "...", "Mode": "CBC"}}

wrapped_key (dynamic key — TR-31 key block passed directly): {"WrappedKeyMaterial": {"Tr31KeyBlock": ""}, "KeyCheckValueAlgorithm": "CMAC"}

Args: key_identifier: Key ARN or alias of the KEK (when using wrapped_key) or the working key plain_text: Hex-encoded plaintext to encrypt encryption_attributes: Algorithm-specific parameters dict wrapped_key: Optional TR-31 wrapped working key (key_identifier becomes the KEK)

Inputs: plain_text (required), key_identifier (required), encryption_attributes (required), wrapped_key.

explain_key_usageA

Call this whenever a TR-31 key usage code appears or someone asks "which key type should I use for X?" — P0, B0, E0, E1, E2, M6, C0, V1, V2, K0, K1, D0, etc. Works without AWS credentials.

Returns what the key type is, what operations it permits, which APC data-plane calls accept it, and any PCI compliance considerations.

Args: key_usage: TR-31 key usage code, e.g. TR31_P0_PIN_ENCRYPTION_KEY

Inputs: key_usage (required).

export_keyA

Call this when distributing an APC-generated key to an external HSM or system, wrapped in a TR-31 key block, a TR-34 structure, an RSA cryptogram, an ECDH-derived key block, or an AS2805 cryptogram.

key_material is a single-member union naming the export method. The wrapping material lives inside it — unlike import_key, there is no separate "type" argument:

{"Tr31KeyBlock": {"WrappingKeyIdentifier": ""}}

{"Tr34KeyBlock": {"CertificateAuthorityPublicKeyIdentifier": "", "WrappingKeyCertificate": "", "KeyBlockFormat": "X9_TR34_2012", "ExportToken": ""}}

{"KeyCryptogram": {"CertificateAuthorityPublicKeyIdentifier": "", "WrappingKeyCertificate": "", "WrappingSpec": "RSA_OAEP_SHA_256"}}

{"DiffieHellmanTr31KeyBlock": {...}} ECDH-derived; needed for AES-192/256 {"As2805KeyCryptogram": {...}} AS2805 (Australian standard)

Args: export_key_identifier: ARN or alias of the key to export key_material: Single-member union selecting the export method, see above export_attributes: Optional. ExportDukptInitialKey (for IPEK export) and/or KeyCheckValueAlgorithm.

Inputs: key_material (required), export_key_identifier (required), export_attributes.

generate_as2805_kek_validationA

Call this when implementing Australian AS2805 payment network key exchange — generating the KEK validation request or response value for node-to-node symmetric key establishment between an acquirer switch and a card scheme.

Generate an AS2805 Key Encryption Key validation value. Used in Australian payment network node-to-node key exchange.

kek_validation_type: KekValidationRequest — initiating node generates a validation request KekValidationResponse — responding node generates the validation response

random_key_send_variant_mask: VARIANT_MASK_82C0 — standard AS2805 variant mask VARIANT_MASK_82 — alternate AS2805 variant mask

Args: key_identifier: ARN or alias of the AS2805 KEK kek_validation_type: KekValidationRequest or KekValidationResponse random_key_send_variant_mask: VARIANT_MASK_82C0 or VARIANT_MASK_82

Inputs: key_identifier (required), kek_validation_type (required), random_key_send_variant_mask (required).

generate_auth_request_cryptogramA

Call this to mint a test/reference ARQC — e.g. to exercise an ARQC verification path, drive a proxy differential test, or produce the APC leg of a cross-implementation check. Issuers normally VERIFY ARQCs (the chip generates them), so this operation is primarily a test-vector generator. The inverse of verify_auth_request_cryptogram (POST /cryptogram/generate).

Required key type: E0 (EMV Application Cryptogram Master Key), TDES only, created/imported with DeriveKey mode. Every AES E0 key is rejected — asymmetric with verify_auth_request_cryptogram, which requires AES-256 E0 for AES ARQCs — so APC cannot mint an AES ARQC. NoRestrictions E0 keys are also rejected by this operation specifically.

transaction_data must be pre-padded with ISO 9797-1 method-2 (EMV) padding: append 0x80 then 0x00 to the next 8-byte boundary. APC does not pad, exactly as on the verify side.

session_key_derivation_attributes — exactly one member; PAN and PSN live inside it. Amex and Visa take only PAN+PSN (no ATC/UN — do not forward payShield ATC/UN wire fields for these schemes): {"Visa": {"PrimaryAccountNumber": "...", "PanSequenceNumber": "01"}} {"Amex": {"PrimaryAccountNumber": "...", "PanSequenceNumber": "01"}} {"Emv2000": {..., "ApplicationTransactionCounter": "0001"}} {"EmvCommon": {..., "ApplicationTransactionCounter": "0001"}} {"Mastercard": {..., "ApplicationTransactionCounter": "0001", "UnpredictableNumber": "12345678"}} {"UnionPay": {..., "ApplicationTransactionCounter": "0001"}}

UnionPay (CUP / PBOC) takes PAN + PSN + ATC and no UnpredictableNumber. It was added to APC on 2026-07-15 and needs boto3 >= 1.43.49 — on older boto3 the member is not in the service model and the call fails client-side with ParamValidationError.

Args: key_identifier: ARN or alias of TDES E0 key (DeriveKey mode) transaction_data: Hex-encoded EMV transaction data, method-2 pre-padded major_key_derivation_mode: EMV_OPTION_A (PAN <= 16 digits) or EMV_OPTION_B (PAN > 16 digits) session_key_derivation_attributes: single-member union, see above

Inputs: key_identifier (required), transaction_data (required), major_key_derivation_mode (required), session_key_derivation_attributes (required).

generate_card_validation_dataA

Call this when implementing card personalization, CVV/CVV2/iCVV generation, or validating card data for testing. Also use to generate test vectors for CVK-based validation before writing production code.

Generates CVV, CVV2, iCVV, or dynamic card verification values. Supported key types: C0 (CVK), E4/E6 (EMV).

generation_attributes examples: CVV: {"CardVerificationValue1": {"CardExpiryDate": "0128", "ServiceCode": "101"}} CVV2: {"CardVerificationValue2": {"CardExpiryDate": "0128"}} iCVV: {"CardVerificationValue1": {"CardExpiryDate": "0128", "ServiceCode": "999"}} ARQC: {"DynamicCardVerificationCode": {"ApplicationTransactionCounter": "0001", "PanSequenceNumber": "01", "TrackData": "..."}}

Args: key_identifier: ARN or alias of CVK (C0) or EMV key primary_account_number: 12-19 digit PAN generation_attributes: Algorithm and card data parameters validation_data_length: Optional output length override

Inputs: key_identifier (required), generation_attributes (required), primary_account_number (required), validation_data_length.

generate_macA

Call this when implementing or validating MAC generation for ISO 8583 transactions, EMV issuer scripts, or any payment message authentication. Also call to verify which MAC algorithm a given M-key type supports before writing code.

Preferred key type: M6 (CMAC). Legacy: M1 (CBC-MAC), M3 (Retail MAC), M0 (AS2805). ISO 8583 field 64 (primary MAC) or field 128 (secondary MAC).

generation_attributes examples: CMAC: {"Algorithm": "CMAC"} ISO 9797-1 Alg 1 (CBC-MAC): {"Algorithm": "ISO9797_ALGORITHM1"} ISO 9797-1 Alg 3 (Retail): {"Algorithm": "ISO9797_ALGORITHM3"} HMAC-SHA256: {"Algorithm": "HMAC_SHA256"} DUKPT CMAC (AES): {"DukptCmac": {"KeySerialNumber": "...", "DukptKeyVariant": "BIDIRECTIONAL", "DukptDerivationType": "AES_128"}} DUKPT Alg 1 (3DES): {"DukptIso9797Algorithm1": {"KeySerialNumber": "...", "DukptKeyVariant": "REQUEST", "DukptDerivationType": "TDES_2KEY"}} DUKPT Alg 3 (3DES): {"DukptIso9797Algorithm3": {"KeySerialNumber": "...", "DukptKeyVariant": "REQUEST", "DukptDerivationType": "TDES_2KEY"}}

DUKPT key variant rules: BIDIRECTIONAL is only valid for AES DUKPT (DukptDerivationType: AES_128/AES_192/AES_256). For 3DES DUKPT (TDES_2KEY/TDES_3KEY) use REQUEST (terminal→host) or RESPONSE (host→terminal). Passing BIDIRECTIONAL with a TDES derivation type returns ValidationException.

CMAC mac_length note: generate_mac with CMAC always returns the full 16-byte (32H) MAC regardless of the mac_length parameter — APC returns the full value and the caller truncates. If you need verify_mac to accept a truncated CMAC (e.g. 4-byte / 8H from a payShield M8 flow), see verify_mac docstring for the workaround.

Args: key_identifier: ARN or alias of MAC key (M0, M1, M3, M6, or M7) message_data: Hex-encoded message to authenticate generation_attributes: MAC algorithm parameters mac_length: Output MAC length in nibbles/hex-digits (NOT bytes): 8=4-byte MAC, 16=8-byte MAC; omit for algorithm default

Inputs: message_data (required), key_identifier (required), generation_attributes (required), mac_length.

generate_mac_emv_pin_changeA

Call this before implementing any EMV PIN change flow — issuer script, CHANGE REFERENCE DATA (INS=24), or offline PIN change MAC assembly.

IMPORTANT: This operation requires THREE separate keys, not one: P0 — PIN Encryption Key: encrypts the new PIN block E2 — EMV Integrity Key: generates the script MAC E1 — EMV Confidentiality Key: encrypts the script data

Single-key EMV MAC helpers (E2 only) cannot replicate this. A full EMV PIN change requires all three key types to be provisioned in APC separately.

Required key types: new_pin_pek_identifier: P0 (PIN Encryption Key for new PIN) secure_messaging_integrity_key_identifier: E2 (EMV integrity) secure_messaging_confidentiality_key_identifier: E1 (EMV confidentiality)

Args: new_pin_pek_identifier: ARN or alias of P0 key for new PIN secure_messaging_integrity_key_identifier: ARN or alias of E2 key secure_messaging_confidentiality_key_identifier: ARN or alias of E1 key message_data: Hex-encoded script command data new_encrypted_pin_block: Hex-encoded new PIN block encrypted under PEK pin_block_format: ISO_FORMAT_0, ISO_FORMAT_1, or ISO_FORMAT_3 (ISO_FORMAT_4 is not supported by this operation) derivation_method_attributes: EMV derivation method (Visa, Mastercard, etc.)

Inputs: message_data (required), pin_block_format (required), new_pin_pek_identifier (required), new_encrypted_pin_block (required), +3 more.

generate_pin_dataA

Call this when implementing IBM 3624 or Visa PVV PIN generation, generating a PIN offset for card personalization, or producing a test PIN block for a given PAN. Issuer function — use with care in acquirer contexts.

Supported schemes via generation_attributes: Visa PVV: {"VisaPin": {"PinVerificationKeyIndex": 1}} Visa PVV value: {"VisaPinVerificationValue": {"EncryptedPinBlock": "...", "PinVerificationKeyIndex": 1}} IBM3624 offset: {"Ibm3624PinOffset": {"DecimalizationTable": "...", "PinValidationData": "..."}} IBM3624 random: {"Ibm3624RandomPin": {"DecimalizationTable": "..."}} IBM3624 natural: {"Ibm3624NaturalPin": {"DecimalizationTable": "..."}} IBM3624 from offset: {"Ibm3624PinFromOffset": {"DecimalizationTable": "...", "PinOffset": "...", "PinValidationData": "..."}}

Supported key types: generation_key_identifier: V1 (IBM3624) or V2 (Visa) PVK encryption_key_identifier: P0 PIN Encryption Key (or KEK when using encryption_wrapped_key)

primary_account_number is optional for ISO_FORMAT_1 (which does not include PAN).

Args: generation_key_identifier: ARN or alias of PVK (V1 or V2 key) encryption_key_identifier: ARN or alias of PEK (P0 key) to encrypt output PIN block generation_attributes: Scheme-specific generation parameters pin_block_format: ISO_FORMAT_0, ISO_FORMAT_1, ISO_FORMAT_3, or ISO_FORMAT_4 primary_account_number: 12-19 digit PAN (required for all formats except ISO_FORMAT_1) pin_data_length: PIN length (4-12); omit to use scheme default encryption_wrapped_key: Optional TR-31 wrapped PEK (encryption_key_identifier becomes the KEK)

Inputs: pin_block_format (required), generation_attributes (required), encryption_key_identifier (required), generation_key_identifier (required), +3 more.

get_aliasA

Call this when resolving an alias to its key ARN, or verifying which key an alias currently points to.

Retrieve alias details.

Args: alias_name: Full alias name including 'alias/' prefix

Inputs: alias_name (required).

get_certificate_signing_requestA

Call this to get a PKCS #10 CSR for an APC-held asymmetric key, so an external CA (or a partner's PKI) can issue a certificate for it. This is the APC counterpart of the payShield/Futurex "generate certificate request" commands — Futurex RSAR, for instance, is a PKCS #10 CSR generator.

The private key stays in APC's HSMs; only the CSR leaves. Typical use is TR-34 key distribution or ECDH key exchange, where the counterparty must trust an APC key.

Args: key_identifier: ARN or alias of the asymmetric key (RSA or ECC) to request a certificate for signing_algorithm: Hash used to sign the CSR — SHA224, SHA256, SHA384, or SHA512 certificate_subject: X.509 subject. CommonName is required; OrganizationUnit, Organization, City, Country, StateOrProvince and EmailAddress are optional: {"CommonName": "acquirer-tr34-2026", "Organization": "Example Bank", "Country": "US"}

Inputs: key_identifier (required), signing_algorithm (required), certificate_subject (required).

get_default_key_replication_regionsA

Call this to see which regions new keys replicate into by default, before creating keys or when auditing why a key landed in a region you did not expect.

Keys created or imported without an explicit replication_regions inherit this account-level default.

Inputs: no named parameters.

get_keyA

Call this when you need the current state, algorithm, usage, or enabled status of a key before using it in an operation.

Retrieve metadata for a key by ARN or alias.

Args: key_identifier: Key ARN (arn:aws:payment-cryptography:...) or alias (alias/name)

Inputs: key_identifier (required).

get_mpa_team_associationA

Call this to check whether an operation is under Multi-Party Approval, which team approves it, and whether a change to that association is still settling.

Use it before an import that may be gated, and when auditing dual control.

Returns MpaTeamAssociation with: Action — the protected operation MpaTeamArn — the approving team AssociationState — ACTIVE, UPDATE_PENDING, or DELETE_PENDING MpaStatus — present when an approval session is in flight, carrying MpaSessionArn, Status (PENDING / APPROVED / FAILED / CANCELLED) and InitiationDate

Args: action: The operation to inspect, e.g. IMPORT_ROOT_PUBLIC_KEY_CERTIFICATE

Inputs: action (required).

get_parameters_for_exportA

Call this before export_key when using TR-34 — you need APC's signing certificate before constructing the export payload for an external system.

Args: key_material_type: Tr31KeyBlock or Tr34KeyBlock signing_key_algorithm: RSA_2048, RSA_3072, RSA_4096 reuse_last_generated_token: Reuse the existing export token and signing key certificate when one is still valid for the same key material type and algorithm, with at least 7 days of validity left. Default false, which mints a new token on every call. Set true when retrying, or when building an export payload across several steps, so the token does not change underneath you.

Inputs: key_material_type (required), signing_key_algorithm (required), reuse_last_generated_token.

get_parameters_for_importA

Call this before import_key when using TR-34 or KeyCryptogram — you need APC's public wrapping key and import token before constructing the import payload.

Key-strength rules enforced by APC (wrapping key strength ≥ working key strength): AES-128 (128-bit): RSA_3072 (~128-bit) or RSA_4096 (~140-bit) — both acceptable. AES-256 (256-bit): RSA of any size is too weak (~140-bit max for RSA_4096). Use ECC_NIST_P521 (~261-bit) — the only KEY_CRYPTOGRAM path for AES-256. TDES (112-bit): RSA_2048 (~112-bit) or higher.

For AES-256 keys (E0, E1, E2, E4, E6, D0 at 256-bit, M6 at 256-bit): wrapping_key_algorithm must be ECC_NIST_P521. Attempting RSA_2048/RSA_3072/RSA_4096 with an AES-256 key will fail. Alternative: use create_key (APC generates the key material — no import needed, but the key value is not externally known, so cross-system test vectors are not possible).

Args: key_material_type: KEY_CRYPTOGRAM, Tr34KeyBlock, Tr31KeyBlock, RootCertificatePublicKey, or TrustedCertificatePublicKey wrapping_key_algorithm: RSA_2048, RSA_3072, RSA_4096, or ECC_NIST_P521 (required for AES-256) reuse_last_generated_token: Reuse the existing import token and wrapping key certificate when one is still valid for the same key material type and algorithm, with at least 7 days of validity left. Default false, which mints a new token on every call. Set true when retrying, or when building an import payload across several steps, so the token does not change underneath you.

Inputs: key_material_type (required), wrapping_key_algorithm (required), reuse_last_generated_token.

get_public_key_certificateA

Call this to fetch the certificate and chain for an APC asymmetric key — to hand a counterparty the public half for TR-34 or ECDH key exchange, or to check what APC currently holds for a key.

Returns KeyCertificate and KeyCertificateChain, both base64-encoded. Public material only; no private key is ever returned.

Args: key_identifier: ARN or alias of the asymmetric key

Inputs: key_identifier (required).

get_resource_policyA

Call this when auditing who has access to a key or inspecting a cross-account policy.

Retrieve the resource policy attached to a key.

Args: resource_arn: Key ARN

Inputs: resource_arn (required).

hsm_analyze_codeA

Call this whenever reviewing legacy payment code that may contain HSM socket calls — Python, Java, C, Go, or any language. Even a single file or function is worth scanning. Works without AWS credentials.

Detects Futurex Excrypt commands ([AOCCCC;...] frames), Thales/International 2-char command codes, and Atalla/Futurex Standard numeric codes. Returns identified commands, their APC migration path, and migration notes for LMK, DUKPT, and fixed-key patterns.

Args: source_code: Raw source code containing HSM socket calls or command strings.

Inputs: source_code (required).

hsm_analyze_discovery_logA

Call this when analyzing the output of apc-hsm-proxy running in discovery mode (a discovery.jsonl file). Returns per-command APC mappings, which proxy handlers already exist, which still need to be written, and migration notes. Works without AWS credentials.

IMPORTANT — handler_exists reflects _PROXY_HANDLERS in hsm_tools.py, not the apc-hsm-proxy source tree. When a handler is completed in the proxy, update _PROXY_HANDLERS in this file so handler_exists reports correctly. Until that update is committed and the MCP server restarted, handler_exists will show false even for commands that already have working handlers.

Each log line is a JSON object: vendor — "futurex_excrypt" or "thales_payshield" cmd — HSM command code, e.g. "TPIN" or "CA" params — Futurex: parameter codes → values (sensitive fields = "[REDACTED]") payload_len — Thales: observed payload length in bytes

Args: log_content: Full text of the discovery.jsonl file (newline-delimited JSON).

Inputs: log_content (required).

hsm_get_apc_mappingA

Call this for a quick command-code → APC operation lookup when you already know the command and just need the migration target — faster than hsm_lookup_command when you don't need the full description and notes. Works without AWS credentials.

Returns just the APC operation and key type for an HSM command.

Args: command_code: The HSM command code, e.g. "TPIN", "CA", "31"

Inputs: command_code (required).

hsm_list_commandsA

Call this to discover which HSM commands are known and what APC operations they map to — useful when scoping a migration, reviewing an HSM integration, or deciding which APC operations a proxy handler needs to implement. Works without AWS credentials.

Args: category: PIN, MAC, CVV, KEY_MGMT, ENCRYPT, ARQC, or P2PE — omit for all vendor: "Futurex" or "Thales" — omit for all vendors

Inputs: vendor, category.

hsm_lookup_commandA

Call this whenever you see an HSM command code in legacy payment code, documentation, or logs — e.g. "TPIN", "CA", "G0", "M6", "CC", "CI", "CW", "CY", "B2", "KQ", "GW", or numeric Atalla codes like "31", "5D". Works without AWS credentials.

Returns the command name, category (PIN/MAC/CVV/KEY_MGMT/ENCRYPT/ARQC), description, and the APC operation + key type that replaces it.

Coverage: Futurex Excrypt (authoritative), Thales payShield legacy + international (authoritative/reference quality), Atalla numeric codes (directory quality).

Args: command_code: The HSM command code, e.g. "TPIN", "CA", "31" api: Optional API filter — "Excrypt", "Standard", or "International"

Inputs: command_code (required), api.

hsm_migration_notesA

Call this when discussing HSM migration for concepts that have no direct APC equivalent — LMK (Local Master Key), DUKPT initial key loading, or fixed ZPK key schemes. Returns detailed migration guidance for the selected topic. Works without AWS credentials.

Args: topic: One of "lmk", "dukpt", "fixed_key"

Inputs: topic (required).

import_keyA

Call this to bring an externally generated key into APC via TR-31 key block or TR-34. The key_material dict structure depends on the import method.

IMPORTANT — this call does not always mean the key is imported. If the account has Multi-Party Approval associated with the import operation (see get_mpa_team_association), the response carries an MpaStatus with Status PENDING and the key is NOT yet usable. Approval by the MPA team has to land first. Treat a successful response as "submitted", not "done": check MpaStatus before using the key or reporting the import as complete, and poll get_key until the status clears. A response with no MpaStatus is an ordinary immediate import.

For TR-31 (wrapping an existing key): key_material = { "Tr31KeyBlock": { "WrappingKeyIdentifier": "", "WrappedKeyBlock": "" } }

For TR-34 (distributing a symmetric key using asymmetric techniques): key_material = { "Tr34KeyBlock": { "CertificateAuthorityPublicKeyIdentifier": "", "ImportToken": "", "KeyBlockFormat": "X9_TR34_2012", "WrappingKeyCertificate": "", "SigningKeyCertificate": "", "EncryptedKeyBlock": "" } }

Args: key_material: Import method and wrapped key material key_check_value_algorithm: CMAC, ANSI_X9_24, HMAC, or SHA_1. AES keys must use CMAC (ANSI_X9_24 is rejected here per PCI PIN Annex C); TDES may use either. HMAC keys use HMAC — the construction is fixed but the hash is the one bound to the key at creation, over a zero-length message, so reproducing the KCV outside APC requires knowing that hash. Asymmetric keys use SHA_1. enabled: Activate key immediately after import tags: Optional list of {Key, Value} tag dicts replication_regions: Optional list of regions to replicate the imported key into. Omit to use the account default (see get_default_key_replication_regions). requester_comment: Optional reason for the import, max 200 characters. Shown to Multi-Party Approval reviewers when the import is gated. Appears in CloudTrail in plaintext — no personal or sensitive data.

Inputs: key_material (required), tags, enabled, requester_comment, +2 more.

list_aliasesA

Call this when auditing all friendly names in the account, or finding aliases associated with a specific key.

List aliases, optionally filtered by key ARN.

Args: key_arn: Filter to aliases associated with this key max_results: Max results (1-100) next_token: Pagination token

Inputs: key_arn, next_token, max_results.

list_all_key_usagesA

Call this when designing key infrastructure, selecting key types for a new payment operation, or when asked what key types APC supports. Works without AWS credentials.

Returns all TR-31 key usage codes with names, descriptions, and APC support status.

Inputs: no named parameters. Returns: result

list_keysA

Call this when auditing which keys exist, finding a key ARN, or checking key state before an import or operation.

List APC keys with optional state filter.

Args: key_state: CREATE_COMPLETE, CREATE_IN_PROGRESS, DELETE_PENDING, DELETE_COMPLETE max_results: Max keys to return (1-100) next_token: Pagination token from a previous response

Inputs: key_state, next_token, max_results.

list_tags_for_resourceA

Call this when auditing the tags on a key or verifying classification metadata.

List all tags on an APC key.

Args: resource_arn: Key ARN max_results: Max results (1-100) next_token: Pagination token

Inputs: resource_arn (required), next_token, max_results.

pan_change_advisoryA

Call this before implementing any PIN translation flow where the PAN might differ between the inbound and outbound formats, or when asked about PCI PIN Req 3-3 / ISO 9564 PAN handling. Works without AWS credentials.

Returns the PCI PIN rule: the PAN must not change during any PIN block translation.

Inputs: no named parameters.

pin_block_retention_advisoryA

Call this before designing any transaction logging, audit trail, or database schema that processes ISO 8583 transactions containing field 52 (PIN block). Works without AWS credentials.

Returns the PCI PIN Req 4 rule: encrypted PIN blocks must not be retained in logs after the authorization response is received — even encrypted form is prohibited.

Inputs: no named parameters.

put_resource_policyA

Call this when granting cross-account access to a key or restricting which principals may use it.

Attach an IAM resource policy to a key.

Args: resource_arn: Key ARN policy: JSON policy document string

Inputs: policy (required), resource_arn (required).

re_encrypt_dataA

Call this when rewrapping payment data under a new key — for example when rotating zone encryption keys, moving data between security domains, or transitioning from TDES to AES. The plaintext never leaves the HSM boundary.

Re-encrypts data from one key to another without exposing plaintext. The decryption and re-encryption occur entirely within the APC HSM boundary.

Args: incoming_key_identifier: ARN or alias of the current encryption key (or KEK) outgoing_key_identifier: ARN or alias of the target encryption key (or KEK) cipher_text: Hex-encoded ciphertext under the incoming key incoming_encryption_attributes: Algorithm params for decryption outgoing_encryption_attributes: Algorithm params for re-encryption incoming_wrapped_key: Optional TR-31 wrapped incoming working key outgoing_wrapped_key: Optional TR-31 wrapped outgoing working key

Inputs: cipher_text (required), incoming_key_identifier (required), outgoing_key_identifier (required), incoming_encryption_attributes (required), +3 more.

remove_key_replication_regionsA

Call this when decommissioning a region or narrowing a key's blast radius.

Removing a region makes the key unusable there. Confirm nothing is still authorizing against it in that region first — in-flight PIN or ARQC traffic will start failing as soon as the replica is gone.

Args: key_identifier: ARN or alias of the key replication_regions: Regions to remove, e.g. ["eu-west-1"]

Inputs: key_identifier (required), replication_regions (required).

restore_keyA

Call this when a key was scheduled for deletion by mistake and needs to be recovered before the waiting period expires.

Cancel a pending key deletion.

Args: key_identifier: Key ARN or alias in DELETE_PENDING state

Inputs: key_identifier (required).

start_key_usageA

Call this when enabling a key that was created with enabled=False or that was previously disabled with stop_key_usage.

Activate a key that was created in disabled state.

Args: key_identifier: Key ARN or alias

Inputs: key_identifier (required).

stop_key_usageA

Call this when temporarily disabling a key — for example during key rotation before the old key is confirmed unused and can be deleted.

Deactivate a key without deleting it.

Args: key_identifier: Key ARN or alias

Inputs: key_identifier (required).

tag_resourceA

Call this when adding classification, environment, or ownership metadata to a key.

Add or update tags on an APC key.

Args: resource_arn: Key ARN tags: List of {Key, Value} dicts

Inputs: tags (required), resource_arn (required).

translate_key_materialA

Call this when implementing ECDH-based key agreement — for example, deriving a shared session key from an ECC key pair and a counterparty certificate, then wrapping the result as a TR-31 key block for local use. Also use when a key exchange protocol delivers a key via Diffie-Hellman and you need it in APC format.

Translate an ECDH-wrapped TR-31 key block into a KEK-wrapped TR-31 key block without ever importing the working key into APC storage.

The only documented use case is ECDH → TR-31 (KEK): incoming_key_material = { "DiffieHellmanTr31KeyBlock": { "CertificateAuthorityPublicKeyIdentifier": "", "KeyBlockHeaders": {...}, "PrivateKeyIdentifier": "", "PublicKeyCertificate": "", "DerivationData": "", "KeyAlgorithm": "AES_128", "KeyDerivationFunction": "NIST_SP800", "KeyDerivationHashAlgorithm": "SHA_256" } } outgoing_key_material = { "Tr31KeyBlock": { "WrappingKeyIdentifier": "" } }

key_check_value_algorithm: CMAC, ANSI_X9_24, HMAC, or SHA_1

Args: incoming_key_material: ECDH-wrapped TR-31 key block (DiffieHellmanTr31KeyBlock) outgoing_key_material: Target KEK-wrapped TR-31 output (Tr31KeyBlock) key_check_value_algorithm: Optional KCV algorithm for the output key block

Inputs: incoming_key_material (required), outgoing_key_material (required), key_check_value_algorithm.

translate_pin_dataA

Call this when implementing acquirer PIN routing, verifying a PIN translation flow, or checking whether a given format-to-format translation is legal under PCI PIN. This is the core HSM operation in every acquiring PIN path.

Translates a PIN block between encryption zones inside the APC HSM boundary — the PIN is never exposed in clear text. Compliance rules are enforced:

  • PAN must not change between incoming and outgoing formats (PCI PIN Req 3-3)

  • Only legal ISO 9564 format translations are permitted (Req 3-3)

  • Fixed TDES PIN keys are prohibited since 1 January 2023 (Req 2-2)

Preferred flow: AES DUKPT (Format 4) inbound → ZPK AES (Format 4 or 0) outbound

incoming_translation_attributes examples: ISO Format 4 (AES): {"IsoFormat4": {"PrimaryAccountNumber": "1712345678901234"}} ISO Format 0 (TDES): {"IsoFormat0": {"PrimaryAccountNumber": "1712345678901234"}} AS2805 Format 0: {"As2805Format0": {"PrimaryAccountNumber": "1712345678901234"}}

incoming_dukpt_attributes (when incoming key is a BDK): {"KeySerialNumber": "<10 or 12 byte KSN hex>"}

incoming_as2805_attributes (when incoming block uses AS2805 format): {"SessionKeyDerivationAttributes": {...}}

incoming_wrapped_key / outgoing_wrapped_key (dynamic key — TR-31 block passed directly): {"WrappedKeyMaterial": {"Tr31KeyBlock": ""}, "KeyCheckValueAlgorithm": "CMAC"}

Args: incoming_key_identifier: ARN or alias of inbound PEK or BDK (or KEK for wrapped key) outgoing_key_identifier: ARN or alias of outbound PEK or BDK (or KEK for wrapped key) incoming_translation_attributes: PIN block format and PAN for inbound outgoing_translation_attributes: PIN block format and PAN for outbound encrypted_pin_block: Hex-encoded encrypted PIN block incoming_dukpt_attributes: Required when incoming key is a BDK (DUKPT) outgoing_dukpt_attributes: Required when outgoing key is a BDK (DUKPT) incoming_as2805_attributes: Required when incoming block uses AS2805 format incoming_wrapped_key: Optional TR-31 wrapped incoming PEK outgoing_wrapped_key: Optional TR-31 wrapped outgoing PEK

Inputs: encrypted_pin_block (required), incoming_key_identifier (required), outgoing_key_identifier (required), incoming_translation_attributes (required), +6 more.

untag_resourceA

Call this when removing stale or incorrect tags from a key.

Remove tags from an APC key.

Args: resource_arn: Key ARN tag_keys: List of tag key names to remove

Inputs: tag_keys (required), resource_arn (required).

update_aliasA

Call this when rotating a key — point the existing alias to the new key ARN so application code referencing the alias picks up the rotation automatically.

Point an alias to a different key (enables key rotation without code changes).

Args: alias_name: Full alias name including 'alias/' prefix key_arn: New key ARN to associate

Inputs: key_arn (required), alias_name (required).

verify_auth_request_cryptogramA

Call this when implementing EMV transaction authorization (ARQC verification), generating an issuer ARPC response, or validating EMV session key derivation. ISO 8583 field 55 carries the ARQC and ATC from the chip card.

Verifies an EMV Authorization Request Cryptogram (ARQC) and optionally generates an Authorization Response Cryptogram (ARPC) in the same call.

Required key type: E0 (EMV Application Cryptogram Master Key). APC requires AES-256 E0 keys — AES-128 E0 keys are rejected at the API level.

major_key_derivation_mode options: EMV_OPTION_A — Visa/Amex ARQC derivation EMV_OPTION_B — Mastercard ARQC derivation

session_key_derivation_attributes — exactly one member, same union as generate_auth_request_cryptogram (Visa, Amex, Emv2000, EmvCommon, Mastercard, UnionPay): {"EmvCommon": {"ApplicationTransactionCounter": "0001", "PanSequenceNumber": "01", "ApplicationCryptogram": ""}} {"UnionPay": {"PrimaryAccountNumber": "...", "PanSequenceNumber": "01", "ApplicationTransactionCounter": "0001"}}

UnionPay (CUP / PBOC) was added to APC on 2026-07-15 and needs boto3 >= 1.43.49 — on older boto3 the call fails client-side with ParamValidationError. This is the APC target for the payShield JS command and for KW Scheme ID 'C'.

auth_response_attributes (to generate ARPC in same call): {"ArpcMethod1": {"AuthResponseCode": "0010"}} or {"ArpcMethod2": {"CardStatusUpdate": "00000000", "ProprietaryAuthenticationData": ""}}

ISO 8583 field 55 contains the EMV data including ARQC and ATC (tag 0x9F36).

Args: key_identifier: ARN or alias of E0 key transaction_data: Hex-encoded EMV transaction data for ARQC verification auth_request_cryptogram: Hex-encoded ARQC from the chip card major_key_derivation_mode: EMV_OPTION_A or EMV_OPTION_B session_key_derivation_attributes: ATC and session key derivation params auth_response_attributes: Optional ARPC generation parameters

Inputs: key_identifier (required), transaction_data (required), auth_request_cryptogram (required), major_key_derivation_mode (required), +2 more.

verify_card_validation_dataA

Call this when validating a card presented at POS or in CNP — verifying a CVV, CVV2, or iCVV value against the issuer's CVK. Also use to test CVK-based validation before writing production card-present or card-not-present logic.

Verify card validation data (CVV, CVV2, iCVV, dynamic values).

Supported key types: C0 (CVK), E4/E6 (EMV).

Args: key_identifier: ARN or alias of CVK or EMV key primary_account_number: 12-19 digit PAN verification_attributes: Algorithm and card data (mirrors generate_card_validation_data) validation_data: The CVV/CVV2/iCVV value to verify

Inputs: key_identifier (required), validation_data (required), primary_account_number (required), verification_attributes (required).

verify_macA

Call this to verify a MAC on a received payment message or issuer script. Mirrors generate_mac — use the same algorithm and key.

CMAC truncation warning: verify_mac with CMAC requires the FULL MAC value (16 bytes / 32H for AES-128). Passing a truncated CMAC — e.g. 4 bytes / 8H produced by payShield M6 with mac_size=0 — returns ValidationException with no descriptive error message. ISO 9797-1 Alg 1/3 produce 4-byte MACs natively and are not affected.

Workaround for truncated CMAC verify (e.g. bridging a payShield M8 flow):

  1. Call generate_mac with the same key and message.

  2. Compare the leading mac_length bytes of the returned 32H MAC against the received value. This costs one extra APC call per verify.

Args: key_identifier: ARN or alias of MAC key message_data: Hex-encoded message that was authenticated mac: Hex-encoded MAC value to verify (CMAC: must be full 32H, not truncated) verification_attributes: MAC algorithm parameters (mirrors generate_mac) mac_length: MAC length in nibbles/hex-digits (NOT bytes): 8=4-byte MAC, 16=8-byte MAC; must match the value used during generation

Inputs: mac (required), message_data (required), key_identifier (required), verification_attributes (required), +1 more.

verify_pin_dataA

Call this when implementing PIN verification at an issuer host — checking a cardholder-entered PIN against a stored IBM 3624 offset or Visa PVV. Also use to validate PIN verification logic end-to-end before deploying to production.

Verify a cardholder PIN against a stored PIN verification value.

Supported key types: verification_key_identifier: V1 (IBM3624) or V2 (Visa) PVK encryption_key_identifier: P0 PIN Encryption Key or B0 BDK (DUKPT)

primary_account_number is optional for ISO_FORMAT_1 (which does not include PAN).

dukpt_attributes (when encryption_key_identifier is a BDK): {"KeySerialNumber": "", "DukptKeyDerivationType": "AES_128"}

Args: verification_key_identifier: ARN or alias of PVK encrypted_pin_block: Hex-encoded encrypted PIN block encryption_key_identifier: ARN or alias of PEK or BDK (or KEK for wrapped key) verification_attributes: Scheme-specific verification params (mirrors generate_pin_data) pin_block_format: ISO_FORMAT_0, ISO_FORMAT_1, ISO_FORMAT_3, or ISO_FORMAT_4 primary_account_number: 12-19 digit PAN (required for all formats except ISO_FORMAT_1) pin_data_length: Optional PIN length override dukpt_attributes: Required when encryption_key_identifier is a BDK encryption_wrapped_key: Optional TR-31 wrapped PEK (encryption_key_identifier becomes the KEK)

Inputs: pin_block_format (required), encrypted_pin_block (required), verification_attributes (required), encryption_key_identifier (required), +5 more.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4/5.0

    Scored across 58 tools

    Disambiguation4/5

    Most tools target a distinct resource-action pair, and the descriptions are thorough enough to disambiguate. The only true overlap is hsm_lookup_command vs hsm_get_apc_mapping, which return nearly the same information; the account-default vs per-key replication tools also require careful reading but are clearly differentiated.

    Naming Consistency4/5

    The vast majority follow a consistent verb_noun snake_case pattern (create_key, list_keys, verify_mac, etc.). Minor deviations exist: pin_block_retention_advisory and pan_change_advisory are noun-phrase names without a leading verb, and the hsm_* prefix creates a distinct sub-pattern.

    Tool Count2/5

    58 tools is well beyond the 25+ threshold, even for a broad domain like payment cryptography. While every tool appears purposeful and the domain genuinely spans key management, crypto operations, EMV, HSM migration, and compliance, the sheer count creates significant selection overhead for an agent.

    Completeness5/5

    The surface is remarkably complete: full key lifecycle (create/get/list/delete/restore/start/stop), alias management, replication, import/export, tagging, resource policies, MPA, and all major crypto operations (encrypt/decrypt, PIN translate/generate/verify, CVV, MAC, EMV ARQC, AS2805). HSM migration and compliance advisory tools fill the remaining gaps. No critical missing operations or dead ends are apparent.

    Maintenance

    ActivityNo data
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      An MCP server for KG Financial's payment services integration, enabling AI coding tools to generate accurate code by automatically searching payment integration documentation through natural language queries.
      6
      31 npm
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      An MCP server that provides ephemeral credentials and persistent MCP connections for AI coding agents, enabling secure access to services like GitHub and AWS without exposing secrets to the agent.
      16 npm
      1
      Apache 2.0
    • A
      license
      Not graded
      quality
      F
      maintenance
      MCP server for AI-native credential management, enabling agents to securely store, retrieve, and manage API keys with encryption, spending budgets, and audit logging.
      MIT