logo
Free, unlimited AI code reviews that run on commit
git-lrc git-lrc GitHub Install Now We'd appreciate a star git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt

twilio-agent-payments-mcp-gateway

A dedicated MCP server facilitating secure, PCI-compliant financial transaction processing during live voice interactions utilizing the Twilio Telephony API infrastructure. It manages asynchronous state updates, structured workflow orchestration via contextual cues, and secure handling of sensitive client credentials.

Author

twilio-agent-payments-mcp-gateway logo

deshartman

MIT License

Quick Info

GitHub GitHub Stars 5
NPM Weekly Downloads 0
Tools 1
Last Updated 2026-02-19

Tags

twiliomcppaymentsusing twiliotwilio agenttwilio api

Twilio Agent Payments MCP Gateway

This service acts as an MCP (Model Context Protocol) intermediary, enabling robust handling of agent-assisted financial dealings through the Twilio communications platform. It incorporates advanced capabilities like asynchronous state synchronization via resource polling and structured conversational guidance through defined MCP Prompts.

Core Capabilities

  • Execute safeguarded financial clearances within active voice sessions via Twilio integration.
  • Systematically acquire sensitive transactional data (e.g., account numbers, verification digits, validity dates).
  • Employ tokenization techniques for payment data to strictly adhere to Payment Card Industry Data Security Standard (PCI DSS) mandates.
  • Facilitate non-blocking data retrieval through MCP Resources leveraging asynchronous callbacks.
  • Implement a step-by-step procedural framework using MCP Prompts to navigate the required data entry sequence.
  • Offer mechanisms for re-submission of erroneous payment inputs.
  • Native compatibility with MCP client interfaces, such as Claude Desktop.
  • Rigorous security protocols for managing operational secrets.
  • Leverage Twilio API Credentials (Keys/Secrets) for enhanced authorization boundaries.
  • Structured architecture built around an event-driven logging paradigm.

Deployment Instructions

This server can be invoked immediately using npx:

bash npx twilio-agent-payments-mcp-gateway

Alternatively, global installation is supported:

bash npm install -g twilio-agent-payments-mcp-gateway twilio-agent-payments-mcp-gateway

Initialization Parameters

Upon startup, the gateway requires the following inputs:

  1. Positional Arguments (Mandatory):
  2. accountSid: The unique identifier for your Twilio Account.
  3. apiKey: Your designated Twilio API Key for authentication.
  4. apiSecret: The corresponding secret key associated with the API Key.

  5. Environmental Variables (Optional Configuration):

  6. TOKEN_TYPE: Specifies the token generation lifecycle (e.g., 'reusable', 'one-time').
  7. CURRENCY: The mandated financial denomination for transactions (e.g., 'USD', 'GBP').
  8. PAYMENT_CONNECTOR: The specific backend payment service provider integrated with Twilio.
  9. NGROK_AUTH_TOKEN: Essential token for establishing the Ngrok tunnel to receive webhooks/callbacks.
  10. NGROK_CUSTOM_DOMAIN: An optional, user-defined public domain name for the callback endpoint.

Example invoking with environment settings: bash TOKEN_TYPE=one-time CURRENCY=EUR PAYMENT_CONNECTOR=secure_processor NGROK_AUTH_TOKEN=ngrok_xyz npx twilio-agent-payments-mcp-gateway ACxxxxxxxxxx SKyyyyyyyyyy ZZZZZZZZZZ

Refer to the Configuration section for parameter specifics.

Parameter Configuration

The operational requirements are defined as follows:

  • accountSid: Twilio Account Identifier (must adhere to 'AC' prefix validation).
  • apiKey: Twilio API Key identifier (must adhere to 'SK' prefix validation).
  • apiSecret: Twilio API Secret key.

Environment Overrides

Configuration adjustable via environment variables:

  • TOKEN_TYPE: Token usage scope setting.
  • CURRENCY: Transactional monetary unit.
  • PAYMENT_CONNECTOR: Twilio endpoint specification.
  • NGROK_AUTH_TOKEN: Tunnel authentication credential.
  • NGROK_CUSTOM_DOMAIN: Optional public hostname for ingress.

Note: Core Twilio authentication parameters are injected via CLI arguments, not environment variables.

Security Posture

This implementation prioritizes security by utilizing API Keys and Secrets instead of legacy Auth Tokens. This grants granular credential management and simplified revocation capabilities. Consult Twilio API Keys documentation for details.

Integration with Host Applications (e.g., Claude Desktop)

One primary advantage of the MCP framework is the abstraction of complex tool definitions away from the language model's direct context. The Gateway automatically broadcasts all required tool definitions, data templates, and operational capacities to the connected LLM client.

Host Application Setup

To embed this Gateway within your application:

  1. Establish an MCP Client: Utilize an existing MCP client library or build a compatible client implementation.

  2. Link to the Gateway: Configure your client application to establish a connection session with the Twilio Agent Payments Gateway.

  3. Protocol Automation: Upon connection, the Gateway autonomously performs:

  4. Registration of its service capabilities (tools, resources) with the client.
  5. Provisioning of precise input specifications (schemas) for all exposed tools.
  6. Delivery of sequential, contextual prompts guiding the conversational agent through the entire payment workflow.

Manual definition of tools or data structures within the LLM's prompt context becomes obsolete; the MCP protocol manages this discovery process.

Minimal Context Requirement

The employing LLM needs only high-level awareness of the Gateway's purpose via its system prompt:

You possess the capability to interface with a Twilio Agent Payments MCP Gateway dedicated to processing secure financial exchanges during customer voice interactions. Invoke the provided server tools to securely collect payment credentials while strictly enforcing PCI compliance standards.

The Gateway will supply necessary, context-aware prompts to shepherd the process completion.

Detailed schemas, operational constraints, and step-by-step guidance are supplied dynamically by the Gateway itself.

Internal Implementation Architecture

This section outlines the structural organization of the Gateway components.

Component Organization

The server logic is segmented across specific directories:

  1. src/index.ts: The primary execution point responsible for:
  2. Instantiating the MCP server entity.
  3. Initializing the TwilioAgentPaymentServer singleton instance.
  4. Executing auto-discovery to register all tools, prompts, and resources with the MCP host.
  5. Configuring event conduits for structured logging transmission.
  6. Establishing the connection to the underlying communication transport layer.

  7. src/tools/: Houses the specific operational functions (Tools):

  8. Each tool is structured as a factory generating an object containing its identifier, semantic description, input schema definition (using Zod), and execution logic.
  9. Tools manage distinct payment activities (e.g., StartPaymentCaptureTool, CaptureCardNumberTool).
  10. Schema validation is mandatory via Zod definitions.
  11. Tools interact with the core logic via the TwilioAgentPaymentServer.getInstance() accessor.

  12. src/prompts/: Contains the conversational guidance scripts (Prompts):

  13. Implemented as factory functions defining the prompt's identifier, descriptive text, and execution logic.
  14. Prompts inject contextual directives aligned with the current payment stage.
  15. Select prompts are parameterized to allow dynamic content generation.

  16. src/resources/: Manages data retrieval capabilities (Resources):

  17. Provides external interfaces to retrieve transactional data (e.g., PaymentStatusResource).
  18. Each resource is a factory returning an object specifying its identifier, URI template, description, and read function.
  19. Resources query the central state via the singleton instance.

  20. src/api-servers/: Contains the primary service abstraction layer for Twilio interactions:

  21. Implements the TwilioAgentPaymentServer as a critical application singleton.
  22. Manages all external communication with the Twilio API services.
  23. Maintains the lifecycle and state of active payment sessions.
  24. Exposes static methods for standardized access to the singleton.

  25. src/utils/: Houses supporting utilities.

  26. autoDiscovery.ts: Manages the automated scanning and registration process for all service components.

Singleton Enforcement: TwilioAgentPaymentServer

A fundamental design choice is the Single Responsibility Principle enforced via the Singleton pattern for TwilioAgentPaymentServer:

typescript class TwilioAgentPaymentServer extends EventEmitter { private static instance: TwilioAgentPaymentServer | null = null;

public static getInstance(): TwilioAgentPaymentServer {
    if (!TwilioAgentPaymentServer.instance) {
        throw new Error('TwilioAgentPaymentServer not initialized. Call initialize() first.');
    }
    return TwilioAgentPaymentServer.instance;
}

public static initialize(accountSid: string, apiKey: string, apiSecret: string): TwilioAgentPaymentServer {
    if (!TwilioAgentPaymentServer.instance) {
        TwilioAgentPaymentServer.instance = new TwilioAgentPaymentServer(accountSid, apiKey, apiSecret);
    }
    return TwilioAgentPaymentServer.instance;
}

private constructor(accountSid: string, apiKey: string, apiSecret: string) {
    // Core initialization logic executed once
}

}

Advantages: - Guarantees exactly one active instance across the application lifecycle. - Prevents dependency injection complexity by providing global, stable access. - Simplifies method signatures throughout the codebase. - Centralizes access control for core resources.

Component Definition: Factory Functions

Tools, prompts, and resources adhere to a factory pattern for initialization:

  1. Tool Example: typescript // Conceptually from StartPaymentCaptureTool.ts export function startPaymentCaptureTool() { const serverInstance = TwilioAgentPaymentServer.getInstance(); const emitter = new EventEmitter();

    return { name: "startPaymentCapture", description: "Initiate a session for financial data collection", shape: schema.shape, execute: async function execute(params: z.infer, extra: any): Promise { // Twilio API invocation and result handling }, emitter } }

  2. Resource Example: typescript // Conceptually from PaymentStatusResource.ts export function paymentStatusResource() { const serverInstance = TwilioAgentPaymentServer.getInstance(); const emitter = new EventEmitter();

    return { name: "PaymentStatus", template: new ResourceTemplate("payment://{callSid}/{paymentSid}/status", { list: undefined }), description: "Retrieve the current state object for an active payment record", read: async (uri: URL, variables: Record, extra: any): Promise => { // Logic to query internal state store }, emitter }; }

Dynamic Component Registration (Auto-Discovery)

The Gateway dynamically loads its functional components:

typescript // In src/utils/autoDiscovery.ts export async function discoverComponents(mcpServer: McpServer) { const basePath: string = path.dirname(fileURLToPath(import.meta.url));

await Promise.all([
    discoverTools(mcpServer, path.join(basePath, '../tools')),
    discoverPrompts(mcpServer, path.join(basePath, '../prompts')),
    discoverResources(mcpServer, path.join(basePath, '../resources'))
]);

}

This method promotes modularity by automatically indexing and registering new tools/resources without modifying the main startup file, significantly enhancing maintainability.

Parameterization within Prompts

Certain guidance prompts are context-aware through parameter injection. The StartCapturePrompt demonstrates this:

  1. Schema Definition: typescript // Within the prompt factory return { name: "StartCapture", description: "Guidance for initializing payment capture", schema: { callSid: z.string().describe("The unique identifier for the active Twilio call leg") }, execute: (args: { callSid: string }, extra: RequestHandlerExtra) => { // Logic execution } };

  2. Parameter Application: typescript execute: (args: { callSid: string }, extra: RequestHandlerExtra): GetPromptResult | Promise => { const { callSid } = args;

    if (!callSid) { throw new Error("Mandatory parameter 'callSid' missing for prompt execution."); }

    return { messages: [ { role: "assistant", content: { type: "text", text: Begin payment initiation for Call ID: ${callSid}. Confirm customer readiness..., } } ] }; }

This allows prompts to adapt their messaging dynamically based on input arguments received from the LLM client.

Exposed Tools

startPaymentCapture

Initiates the formal financial handling procedure for a designated voice session.

Parameters: - callSid: The Twilio Call Session Identifier.

IMPORTANT: The StartCapturePrompt mandates the provision of a valid CallSid from the MCP Client; failure to supply it will result in execution failure.

NOTE: Crucially, this server operates under the assumption that the provided callSid targets the Public Switched Telephone Network (PSTN) call leg. Applying this function to the Twilio Client leg will prevent DTMF digit collection. Standard logic often involves checking the call direction:

javascript // Contextual logic for selecting the PSTN leg SID if (event.CallDirection === "toPSTN") { theCallSid = event.CallSid; } else if (event.CallDirection == "toSIP") { theCallSid = event.ParentCallSid; }

Returns: - paymentSid: The unique Twilio identifier assigned to the new payment instrument session.

captureCardNumber

Triggers the secure input sequence for the primary account number.

Parameters: - callSid: Active Twilio Call Identifier. - paymentSid: Identifier for the active payment record. - captureType: Hardcoded to 'payment-card-number'.

Returns: - Operational confirmation status of the card number collection.

captureSecurityCode

Commences the capture sequence for the card verification value (CVV/CVC).

Parameters: - callSid: Active Twilio Call Identifier. - paymentSid: Identifier for the active payment record. - captureType: Hardcoded to 'security-code'.

Returns: - Operational confirmation status of the security code collection.

captureExpirationDate

Initiates the process to acquire the card's validity period.

Parameters: - callSid: Active Twilio Call Identifier. - paymentSid: Identifier for the active payment record. - captureType: Hardcoded to 'expiration-date'.

Returns: - Operational confirmation status of the expiration date collection.

completePaymentCapture

Finalizes the data acquisition phase and submits the transaction for processing.

Parameters: - callSid: Active Twilio Call Identifier. - paymentSid: Identifier for the active payment record.

Returns: - Final processing status of the submitted transaction.

Available Resources

payment://{callSid}/{paymentSid}/status

Provides the current state snapshot of the payment engagement as a structured JSON object. This state report includes:

  • Payment SID identifier
  • Masked Primary Account Number (PAN)
  • Card brand classification
  • Verification Code collection status
  • Validity date status
  • Authorization receipt code
  • Transaction final outcome
  • Generated Payment Token (if available)

Orchestration Prompts (MCP Guided Flow)

The Gateway delivers sequential, prescriptive prompts to the LLM for step-by-step execution:

StartCapture Prompt

Provides conversational guidance on initiating the capture sequence, detailing: - Scripting for soliciting customer consent to transmit financial details. - Messaging emphasizing the secure, tokenized nature of the data handling. - Direct instructions for invoking the startPaymentCapture utility. - Critical Requirement: Demands the CallSid parameter supplied by the MCP Client context.

CardNumber Prompt

Directs the LLM on managing the primary account number collection, including: - Standardized phrasing for requesting the full card number. - Best practices for addressing customer queries or hesitation. - Steps required to execute the captureCardNumber utility.

SecurityCode Prompt

Guidance for obtaining the card verification value (CVV): - Clear explanation of what the security code represents. - Strategies for resolving customer confusion regarding the code's location. - Steps required to execute the captureSecurityCode utility.

ExpirationDate Prompt

Guides the LLM through acquiring the card's validity period: - Specific formatting instructions (e.g., MM/YY). - Tips for managing customer input errors. - Steps required to execute the captureExpirationDate utility.

FinishCapture Prompt

Provides conversational direction for concluding the data gathering phase: - Instructions for verifying all required components have been successfully entered. - Steps required to invoke the completePaymentCapture utility.

Completion Prompt

Instructs the LLM on post-transaction dialogue: - Steps for confirming successful financial clearance to the customer. - Suggestions for subsequent conversational actions.

Error Prompt

Provides remediation guidance for operational failures during the process: - Instructions for communicating the failure event clearly to the customer. - Suggested troubleshooting paths for recurrent issues. - Guidance on initiating a controlled retry sequence.

Architectural Overview

This Gateway utilizes an advanced, decoupled operational structure:

Event-Driven Communication

Communication internal to the system relies on an event-driven model via EventEmitter: - All functional modules (Tools, Resources) inherit from EventEmitter. - Events are dispatched for internal auditing and external logging transmission. - Listeners capture these events and route them to the centralized MCP logging sink.

Asynchronous Callback Management

Callback reception from Twilio is managed via dedicated modules (leveraging packages like @deshartman/mcp-status-callback): - Establishes a public ingress point using Ngrok for receiving HTTP callbacks. - Interprets incoming payment lifecycle notifications. - Persistently updates the internal session state store based on callback payload data. - Handles state transitions related to failures and re-entry requirements.

State Persistence

Payment session context is maintained via an in-memory, Map-based registry: - The statusCallbackMap indexes mutable session data using the Payment SID. - Each incoming webhook updates the record to reflect the latest progress. - The PaymentStatusResource retrieves the finalized state from this map.

MCP Protocol Adherence

Integration with the Model Context Protocol is achieved through: - Tools: Input validation strictly governed by Zod schemas. - Resources: Providing controlled access to the ephemeral payment state. - Prompts: Delivering dynamic, step-specific conversational direction. - Logging: Event-based output channeled conformantly to the MCP server interface.

Development Workflow

To compile the source code:

bash npm install npm run build

Prerequisites

  • Minimum Node.js version 18.x.
  • Dependencies: Express (for tunneling infrastructure), Twilio Client Library, Active Ngrok Credentials.

Local Execution for Debugging

To initiate the server independently of the host environment:

bash

Direct execution using compiled JavaScript

node build/index.js "AC_CREDENTIAL" "SK_CREDENTIAL" "SECRET_CREDENTIAL"

Using npm script (often uses ts-node for live development)

npm run dev -- "AC_CREDENTIAL" "SK_CREDENTIAL" "SECRET_CREDENTIAL"

When integrated into Claude Desktop, startup is automated via the configuration file, negating the need for manual execution.

PCI Compliance Adherence

This service ensures PCI compliance by strictly ensuring that raw payment card data is immediately tokenized by Twilio, meaning sensitive information is never persisted within the local application environment. Further details on Twilio's security posture can be found at Twilio documentation on secure payments.

Licensing

MIT License applies.

Compatibility with MCP Inspector

When diagnosing performance using the MCP Inspector, note that all operational feedback is routed through the designated MCP logging stream, bypassing standard console.log() calls.

For debugging or extending this Gateway:

  1. Utilize the internal event dispatch mechanism by emitting specific LOG_EVENT payloads.
  2. Avoid direct console output (console.log()) as it corrupts the JSON stream expected by the MCP host on standard output.
  3. In non-MCP diagnostic contexts, console.error() (outputting to stderr) is permissible for error tracing.

Internal Logging Mechanism

The system employs a strict event-driven strategy for operational logging:

  1. Event Dispatch: All service components (Tools, Resources) are implemented with EventEmitter capabilities, emitting standardized 'log' events containing level and descriptive content.

  2. Log Redirection: Registered listeners intercept these events and process them for transmission to the MCP framework's logging facility:

javascript // Listener registration example startPaymentCaptureTool.on(LOG_EVENT, forwardToMcp); captureCardNumberTool.on(LOG_EVENT, forwardToMcp); // ... and all other components

  1. MCP Serialization: The forwardToMcp function transforms the internal event structure into the MCP-compliant log format:

javascript const forwardToMcp = (data: { level: string, message: string }) => { // Map internal levels to MCP standards: info, error, debug // 'warn' level is normalized to 'info' const mcpLevel = data.level === 'warn' ? 'info' : data.level as "info" | "error" | "debug";

   // Dispatch the formatted message through the underlying MCP Server interface
   mcpServer.server.sendLoggingMessage({
       level: mcpLevel,
       data: data.message,
   });

};

Log Level Hierarchy

The supported hierarchical levels for auditing are:

  • info: Standard operational reporting.
  • error: Exceptions and critical faults.
  • debug: Verbose, detailed tracing data.
  • warn: Non-critical warnings (translated to 'info' for MCP consumption).

Twilio Callback Payload Schemas

The Gateway interprets two primary webhook data structures received from the Twilio platform:

Initial Session Establishment Data

Sent when the payment mechanism is first instantiated:

{ "PaymentConnector": "PGP_MOCK", "DateCreated": "2021-08-10T03:55:53.408Z", "PaymentMethod": "credit-card", "CallSid": "CAzzzzz", "ChargeAmount": "9.99", "AccountSid": "ACxxxxx", "Sid": "PKxxxx" }

Data Capture Progress Updates

Sent incrementally as card details are successfully acquired:

{ "SecurityCode": "xxx", "PaymentCardType": "visa", "Sid": "PKxxxx", "PaymentConfirmationCode": "ch_a9dc6297cd1a4fb095e61b1a9cf2dd1d", "CallSid": "CAxxxxx", "Result": "success", "AccountSid": "AC75xxxxxx", "ProfileId": "", "DateUpdated": "2021-08-10T03:58:27.290Z", "PaymentToken": "", "PaymentMethod": "credit-card", "PaymentCardNumber": "xxxxxxxxxxxx1111", "ExpirationDate": "1225" }

This data payload is persistently mapped against its Payment SID within the state store, making it immediately queryable via the PaymentStatusResource.

WIKIPEDIA: Business management tools encompass all methodologies, software applications, analytical controls, and frameworks utilized by organizations to adapt to evolving market dynamics, maintain a competitive edge, and systematically enhance operational efficiency.

See Also

`