twilio-payment-orchestrator-mcp
A centralized Model Context Protocol (MCP) gateway for orchestrating secure, PCI-compliant financial transactions during live voice interactions mediated by the Twilio platform. It manages asynchronous payment lifecycle events, employs step-by-step conversational guidance via contextual prompts, and ensures robust credential security.
Author

deshartman
Quick Info
Actions
Tags
Twilio Payment Orchestration Gateway (MCP Server)
This is a specialized MCP server engineered to facilitate agent-assisted financial settlement over Twilio voice sessions. It strictly adheres to security protocols, utilizing asynchronous communication patterns and structured contextual interactions for LLM-driven workflows.
Core Capabilities
- Secure Transaction Execution: Triggers and manages the capture of sensitive cardholder data (PAN, CVV, Expiry) through the Twilio API during active telephony engagements.
- PCI DSS Scope Reduction: All sensitive credentials are immediately tokenized by Twilio services, minimizing exposure and ensuring compliance.
- Asynchronous Feedback Loop: Leverages MCP Resources for stable, asynchronous notification handling via webhooks.
- Guided Conversational Flow: Directs the supervising AI agent step-by-step using curated MCP Prompts for optimal data acquisition.
- Resilience: Supports secure re-submission of transactional details if initial attempts fail.
- Host Integration: Seamlessly interfaces with various MCP clients, such as Claude Desktop, by exposing necessary tool definitions.
- Credential Security: Explicitly mandates the use of Twilio API Keys over traditional Auth Tokens for superior access governance.
- Auditability: Implements an event-driven logging mechanism for comprehensive traceability.
Deployment and Initialization
Execution can be initiated directly via package runner or after global installation:
bash
Direct execution
npx twilio-payment-orchestrator-mcp
Alternatively, install globally:
bash
npm install -g twilio-payment-orchestrator-mcp
twilio-payment-orchestrator-mcp
Required Launch Parameters
Initialization requires command-line arguments for core credentials:
-
CLI Inputs (Mandatory):
accountSid: Your unique Twilio Account Identifier.apiKey: The key for API authorization.apiSecret: The secret corresponding to the API Key.
-
Runtime Environment Variables (Optional configuration overrides):
TOKEN_TYPE: Defines token validity (e.g., 'reusable', 'one-time').CURRENCY: Specifies the transaction denomination (e.g., 'USD').PAYMENT_CONNECTOR: Identifies the specific Twilio payment gateway integration.NGROK_AUTH_TOKEN: Required for establishing the secure ingress tunnel for callbacks.NGROK_CUSTOM_DOMAIN: An optional setting to use a predefined public hostname.
Example Launch with Environment Overrides: bash TOKEN_TYPE=one-time CURRENCY=EUR PAYMENT_CONNECTOR=SecurePay NGROK_AUTH_TOKEN=ngrok_xyz npx twilio-payment-orchestrator-mcp ACxxxxxxxx SKxxxxxxxx ASxxxxxxxx
Configuration Reference
Authentication credentials must be supplied via the CLI. Auxiliary operational settings are configured via environment variables:
- CLI-Provided:
accountSid,apiKey,apiSecret. - Environment Variables:
TOKEN_TYPE,CURRENCY,PAYMENT_CONNECTOR,NGROK_AUTH_TOKEN,NGROK_CUSTOM_DOMAIN.
Security Posture
This service prioritizes the use of API Keys and Secrets over legacy Auth Tokens, aligning with current best practices for enhanced credential revocation and granular access control. Consult Twilio API Key Documentation for specifics.
Host Integration (Claude Desktop Example)
Local Development Setup
When building locally (before npm publication), configure your host application's settings file (e.g., claude_desktop_config.json) as follows:
{ "mcpServers": { "twilio-payment-orchestrator": { "command": "node", "args": [ "/PATH/TO/your/compiled/index.js", "your_account_sid_here", "your_api_key_here", "your_api_secret_here" ], "env": { "TOKEN_TYPE": "reusable", "CURRENCY": "USD", "PAYMENT_CONNECTOR": "your_connector_name", "NGROK_AUTH_TOKEN": "your_ngrok_auth_token_here" } } } }
Post-Publication Setup
Once deployed to the registry, the configuration simplifies:
{ "mcpServers": { "twilio-payment-orchestrator": { "command": "npx", "args": [ "-y", "twilio-payment-orchestrator-mcp", "your_account_sid_here", "your_api_key_here", "your_api_secret_here" ], "env": { ...process.env, "TOKEN_TYPE": "reusable", "CURRENCY": "USD", "PAYMENT_CONNECTOR": "your_connector_name", "NGROK_AUTH_TOKEN": "your_ngrok_auth_token_here" } } } }
MCP Protocol Synergy
The primary benefit of this MCP service is eliminating manual tool definition within the LLM's context window. The server automatically advertises its capabilities (tools, resource schemas, contextual guidance) to the connecting client.
Integration Workflow
- Client Initialization: The host application establishes a connection to this running MCP server.
- Capability Discovery: The server immediately registers all defined tools and resources with the client.
- LLM Context Minimization: The LLM only requires a high-level declaration of capability:
You possess access to the Twilio Payment Orchestrator MCP service, capable of securely finalizing financial transfers during ongoing voice interactions, strictly maintaining PCI safeguards.
Example Client Interaction Snippet (Conceptual JavaScript):
javascript // Assume McpClient is initialized await mcpClient.linkToServer({ serviceName: "twilio-payment-orchestrator", transport: "WebSocket_URL_or_STDIO" });
// LLM initiates payment via tool invocation function executeLlmAction(request) { if (request.service_name === "twilio-payment-orchestrator") { // Client routes the request internally based on discovered schemas return mcpClient.invokeManagedTool(request); } }
Internal Architecture Overview
The server structure is segmented for modularity:
src/index.ts: Bootstrap; initializes the MCP transport, instantiates theTwilioAgentPaymentServersingleton, triggers component auto-discovery, and sets up event-based logging pipelines.src/tools/: Contains discrete, actionable transaction tools (e.g., initiating capture, finalizing settlement). Each tool uses Zod for rigorous input validation and exposes anexecutefunction.src/prompts/: Defines the sequential conversational guidance presented to the AI agent for each transactional phase.src/resources/: Implements endpoints for reading ephemeral data, primarily the current state of an active payment session.src/api-servers/: Houses the singleton implementation (TwilioAgentPaymentServer) responsible for managing Twilio API interactions and session state persistence.src/utils/: Contains infrastructure helpers, most notablyautoDiscovery.ts, which dynamically loads components.
Singleton Enforcement: TwilioAgentPaymentServer
To guarantee a single point of truth for API credentials and active session state across the application:
typescript class TwilioAgentPaymentServer extends EventEmitter { private static uniqueInstance: TwilioAgentPaymentServer | null = null;
public static retrieveInstance(): TwilioAgentPaymentServer {
if (!TwilioAgentPaymentServer.uniqueInstance) {
throw new Error('Server instance is uninitialized. Must call bootstrap() first.');
}
return TwilioAgentPaymentServer.uniqueInstance;
}
public static bootstrap(sid: string, key: string, secret: string): TwilioAgentPaymentServer {
if (!TwilioAgentPaymentServer.uniqueInstance) {
TwilioAgentPaymentServer.uniqueInstance = new TwilioAgentPaymentServer(sid, key, secret);
}
return TwilioAgentPaymentServer.uniqueInstance;
}
// Private constructor enforces instantiation only via static methods
private constructor(sid: string, key: string, secret: string) {
// ... setup Twilio client, event handlers ...
}
}
Component Definition: Factory Pattern
Tools, prompts, and resources are instantiated using factory functions, which abstracts away boilerplate setup (like dependency injection of the singleton):
- Tool Example: The factory returns the tool descriptor, including the schema (Zod definition) and the asynchronous
executelogic. - Resource Example: The factory returns a structure defining the URI template, description, and the asynchronous
readhandler logic.
Dynamic Registration via Auto-Discovery
Components are located and registered automatically upon server startup using Node.js path utilities, minimizing manual linkage in the main entry file:
typescript // src/utils/autoDiscovery.ts export async function scanAndRegisterComponents(serverInstance: McpServer) { const baseDir: string = path.dirname(fileURLToPath(import.meta.url));
await Promise.all([
scanDirectoryForTools(serverInstance, path.join(baseDir, '../tools')),
scanDirectoryForPrompts(serverInstance, path.join(baseDir, '../prompts')),
scanDirectoryForResources(serverInstance, path.join(baseDir, '../resources'))
]);
}
Tool Inventory
initiatePaymentSession
Establishes the primary transaction context.
- Parameters:
callSid(The active telephony identifier). - Output: Returns the generated
paymentSid.
ingestCardNumberData
Collects the Primary Account Number (PAN).
- Parameters:
callSid,paymentSid,captureType: 'payment-card-number'. - Output: Operational status confirmation.
retrieveSecurityCode
Collects the Card Verification Value (CVV).
- Parameters:
callSid,paymentSid,captureType: 'security-code'. - Output: Operational status confirmation.
recordExpiryDetails
Collects the card validity period.
- Parameters:
callSid,paymentSid,captureType: 'expiration-date'. - Output: Operational status confirmation.
finalizeTransaction
Signals Twilio to submit the tokenized data for authorization.
- Parameters:
callSid,paymentSid. - Output: Final confirmation status of the submission attempt.
Data Access via Resources
state:/transaction/{paymentSid}/details
Provides the transient, granular details of the session as captured so far. This JSON object includes masked card data, status flags for CVV/Expiry, and any temporary confirmation codes generated during the process.
Guiding Prompts (LLM Contextualization)
These prompts are dynamically injected by the server to instruct the AI on the next required action:
requestInitiation: Instructs the LLM to prompt the user for consent and to invokeinitiatePaymentSession, emphasizing the need for thecallSid.elicitPAN: Guides the LLM to request the full card number securely, referencing theingestCardNumberDatatool.fetchCVV: Directs the LLM to ask for the security code, noting its location (e.g., back of card).getExpiry: Provides scripting advice for obtaining the month/year format for expiration.confirmAndSubmit: Guides the LLM to summarize collected data and executefinalizeTransaction.notifySuccess/notifyFailure: Provides template responses for confirming final outcome to the end-user.
Architectural Deep Dive: Eventing and Compliance
Event-Driven State Propagation
Node's EventEmitter is the backbone for internal coordination. Every component emits lifecycle events (e.g., data received, error encountered). These events are intercepted and routed to the main MCP logging sink.
Asynchronous Callback Management
This component integrates the @deshartman/mcp-status-callback utility to establish a temporary, public endpoint (via Ngrok) to receive asynchronous status updates directly from Twilio regarding payment webhook events. State is updated based on these external confirmations.
State Persistence
Session data is held transiently in a Map store (statusCallbackMap), keyed by the paymentSid. This data is made consumable via the dedicated resource endpoint.
Development Toolchain
To compile and run:
bash npm install npm run build
Execution Modes
Manual Test Mode (Bypassing Desktop Integration):
bash
Execute compiled TypeScript output
node build/index.js "SID" "KEY" "SECRET"
PCI Compliance Philosophy
The system's design mandates that raw cardholder data never persists on the orchestrator server. Twilio performs the sensitive capture and vaulting, providing only non-sensitive tokens or status confirmations back to this service.
Logging Protocol Adherence
Crucial Note for Debugging: All operational telemetry is funneled through the MCP standardized logging mechanism via event emission, not standard console.log(). This prevents log output from corrupting the structured JSON messages exchanged over STDOUT/STDIN with the MCP client.
- Use emitted 'log' events (with levels: info, error, debug).
console.error()remains acceptable for writing only to STDERR for non-protocol related diagnostics.
Log Level Mapping
| Internal Level | MCP Output Level |
|---|---|
info |
info |
error |
error |
debug |
debug |
warn |
info |
Twilio Callback Data Manifestation
Session Initiation Payload
Initial webhook data confirming connector setup:
{ "PaymentConnector": "MockGateway", "DateCreated": "YYYY-MM-DDTHH:MM:SS.ZZZ", "PaymentMethod": "credit-card", "CallSid": "CA...", "Sid": "PKxxxx" }
Data Capture Update Payload
Subsequent payloads reflecting step-by-step data acquisition:
{ "SecurityCode": "[Redacted]", "PaymentCardType": "mastercard", "Sid": "PKxxxx", "Result": "pending", "PaymentCardNumber": "**4321", "ExpirationDate": "1124" }
