Twilio Agent Payments MCP Server

Integrations

  • Uses Express to handle asynchronous callbacks from Twilio, processing payment stage notifications and updating payment session state.

  • Built on Node.js, allowing the server to maintain in-memory state stores for payment sessions and handle the MCP protocol communication.

  • Enables handling agent-assisted payments via the Twilio API, allowing secure processing of payment card information (card number, security code, expiration date) during voice calls, with support for tokenization, payment status tracking, and field re-entry.

Twilio 代理支付 MCP 服务器

MCP(模型上下文协议)服务器可通过 Twilio API 处理代理协助支付,并具有异步回调和通过上下文提示引导工作流程的增强功能。

特征

  • 通过 Twilio 在语音通话期间处理安全支付
  • 获取付款信息(卡号、安全码、有效期)
  • 标记支付信息以符合 PCI 合规性
  • 通过 MCP 资源进行异步回调
  • 使用 MCP Prompts 指导支付流程的每个步骤
  • 支持重新输入付款信息
  • 与 Claude Desktop 等 MCP 客户端集成
  • 安全凭证处理
  • 使用 Twilio API 密钥来提高安全性
  • 基于事件的日志记录架构

安装

您可以通过 npx 直接使用此服务器:

npx twilio-agent-payments-mcp-server <accountSid> <apiKey> <apiSecret>

或者全局安装:

npm install -g twilio-agent-payments-mcp-server twilio-agent-payments-mcp-server <accountSid> <apiKey> <apiSecret>

环境参数

安装服务器时需要提供以下参数:

  1. 命令行参数(必需):
    • accountSid :您的 Twilio 帐户 SID
    • apiKey :您的 Twilio API 密钥
    • apiSecret :您的 Twilio API 密钥
  2. 环境变量(运行服务器之前设置):
    • TOKEN_TYPE :用于付款的令牌类型(例如“可重复使用”、“一次性”)
    • CURRENCY :付款货币(例如“USD”、“EUR”)
    • PAYMENT_CONNECTOR :与 Twilio 一起使用的支付连接器
    • NGROK_AUTH_TOKEN :您的 Ngrok 身份验证令牌(回调处理所需)
    • NGROK_CUSTOM_DOMAIN :Ngrok 的可选自定义域

环境变量示例:

TOKEN_TYPE=reusable CURRENCY=USD PAYMENT_CONNECTOR=your_connector NGROK_AUTH_TOKEN=your_token npx twilio-agent-payments-mcp-server <accountSid> <apiKey> <apiSecret>

有关这些参数的更多详细信息,请参阅下面的配置部分。

配置

服务器需要以下参数:

  • accountSid :您的 Twilio 帐户 SID(必须以“AC”开头,将被验证)
  • apiKey :您的 Twilio API 密钥(以“SK”开头)
  • apiSecret :您的 Twilio API 密钥

环境变量

以下环境变量用于配置:

  • TOKEN_TYPE :用于付款的令牌类型(例如“可重复使用”、“一次性”)
  • CURRENCY :付款货币(例如“USD”、“EUR”)
  • PAYMENT_CONNECTOR :与 Twilio 一起使用的支付连接器
  • NGROK_AUTH_TOKEN :您的 Ngrok 身份验证令牌(回调处理所需)
  • NGROK_CUSTOM_DOMAIN :Ngrok 的可选自定义域

注意:Twilio 凭证(accountSid、apiKey、apiSecret)作为命令行参数提供,而不是环境变量。

安全说明

此服务器使用 API 密钥和机密信息(而非身份验证令牌)来提高安全性。此方法提供了更好的访问控制,并能够在需要时撤销凭证。有关更多信息,请参阅Twilio API 密钥文档

与 Claude Desktop 一起使用

本地开发

对于本地开发(当软件包未发布到 npm 时),将以下内容添加到您的 Claude Desktop 配置文件(macOS 上的~/Library/Application Support/Claude/claude_desktop_config.json或 Windows 上的%APPDATA%\Claude\claude_desktop_config.json )中:

{ "mcpServers": { "twilio-agent-payments": { "command": "node", "args": [ "/PATHTONODE/twilio-agent-payments-mcp-server/build/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", "NGROK_CUSTOM_DOMAIN": "your_custom_domain_here" // Optional } } } }

用您的实际 Twilio 凭证和配置替换这些值。

发布到 npm 后

一旦包发布到 npm,您就可以使用以下配置:

{ "mcpServers": { "twilio-agent-payments": { "command": "npx", "args": [ "-y", "twilio-agent-payments-mcp-server", "your_account_sid_here", "your_api_key_here", "your_api_secret_here" ], "env": { ...process.env, // Include existing environment variables so child process has access to the path "TOKEN_TYPE": "reusable", "CURRENCY": "USD", "PAYMENT_CONNECTOR": "your_connector_name", "NGROK_AUTH_TOKEN": "your_ngrok_auth_token_here", "NGROK_CUSTOM_DOMAIN": "your_custom_domain_here" // Optional } } } }

与主机应用程序集成

模型上下文协议 (MCP) 的主要优势之一是它消除了 LLM 上下文的大量手动配置需求。MCP 服务器会自动向 LLM 客户端提供所有必要的工具定义、资源模板和功能。

设置主机应用程序

要将此 MCP 服务器集成到您自己的主机应用程序中:

  1. 实现 MCP 客户端:使用现有的 MCP 客户端库或在您的应用程序中实现 MCP 客户端协议。
  2. 连接到 MCP 服务器:配置您的应用程序以连接到 Twilio Agent Payments MCP 服务器。
  3. 让协议处理其余部分:MCP 服务器将自动:
    • 向您的客户注册其工具和资源
    • 为所有工具提供输入模式
    • 提供上下文提示,指导法学硕士完成付款流程

您的 LLM 上下文中不需要手动定义工具或资源 - MCP 协议会自动处理此发现。

示例集成代码

以下是如何与 MCP 客户端集成的简化示例:

// Initialize your MCP client const mcpClient = new McpClient(); // Connect to the Twilio Agent Payments MCP server await mcpClient.connectToServer({ name: "twilio-agent-payments", // Connection details depend on your specific MCP client implementation // This could be a WebSocket URL, stdio connection, or other transport }); // The client will automatically discover available tools and resources // When the LLM wants to use a tool, your application can handle it like this: function handleLlmToolRequest(toolRequest) { // The toolRequest would contain: // - server_name: "twilio-agent-payments" // - tool_name: e.g., "startPaymentCapture" // - arguments: e.g., { callSid: "CA1234567890abcdef" } return mcpClient.callTool(toolRequest); } // Similarly for resources: function handleLlmResourceRequest(resourceRequest) { // The resourceRequest would contain: // - server_name: "twilio-agent-payments" // - uri: e.g., "payment://CA1234567890abcdef/PA9876543210abcdef/status" return mcpClient.accessResource(resourceRequest); }

最低限度的法学硕士背景要求

LLM 只需要知道可以使用 Twilio Agent Payments MCP 服务器来处理付款。系统提示符中的一条简单指令即可:

You have access to a Twilio Agent Payments MCP server that can help process secure payments during voice calls. When a customer wants to make a payment, you can use the tools provided by this server to securely capture payment information while maintaining PCI compliance. The server will guide you through the payment process with contextual prompts at each step.

MCP 服务器本身提供所有详细的工具定义、输入模式和上下文提示,以指导 LLM 完成支付流程。

开发人员实施说明

本节介绍如何在不同的组件和文件中组织 MCP 服务器实现,重点介绍所使用的架构模式。

组件组织

服务器实现分为几个目录:

  1. src/index.ts :主要入口点:
    • 初始化 MCP 服务器
    • 初始化 TwilioAgentPaymentServer 单例
    • 通过自动发现功能发现并向 MCP 服务器注册所有组件
    • 设置日志记录事件监听器
    • 将服务器连接到传输层
  2. src/tools/ :包含各个工具实现
    • 每个工具都实现为一个工厂函数,该函数返回一个具有名称、描述、形状和执行属性的对象。
    • 工具处理特定的支付操作(例如,StartPaymentCaptureTool,CaptureCardNumberTool)
    • 每个工具都使用 Zod 定义其输入模式并实现执行方法
    • 工具通过 getInstance() 访问 TwilioAgentPaymentServer 单例
  3. src/prompts/ :包含提示实现
    • 每个提示都实现为一个工厂函数,该函数返回一个具有名称、描述和执行属性的对象。
    • 提示为 LLM 支付流程的每个步骤提供上下文指导
    • 一些提示接受可用于自定义提示内容的参数
  4. src/resources/ :包含资源实现
    • 资源提供对数据的访问(例如 PaymentStatusResource)
    • 每个资源都实现为一个工厂函数,该函数返回一个具有名称、模板、描述和读取属性的对象。
    • 资源通过 getInstance() 访问 TwilioAgentPaymentServer 单例
  5. src/api-servers/ :包含 Twilio API 客户端的实现
    • 将 TwilioAgentPaymentServer 实现为单例
    • 处理与 Twilio API 的通信
    • 管理支付会话状态
    • 提供访问单例实例的静态方法
  6. src/utils/ :包含实用函数
    • autoDiscovery.ts 文件处理工具、提示和资源的自动发现和注册

TwilioAgentPaymentServer 的单例模式

此代码库中的一个关键架构模式是 TwilioAgentPaymentServer 使用 Singleton 模式:

class TwilioAgentPaymentServer extends EventEmitter { // Singleton instance private static instance: TwilioAgentPaymentServer | null = null; /** * Static method to get the instance */ public static getInstance(): TwilioAgentPaymentServer { if (!TwilioAgentPaymentServer.instance) { throw new Error('TwilioAgentPaymentServer not initialized. Call initialize() first.'); } return TwilioAgentPaymentServer.instance; } /** * Static method to initialize the 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 to prevent direct instantiation private constructor(accountSid: string, apiKey: string, apiSecret: string) { // Initialization code... } }

这种方法的好处:

  • 确保整个应用程序中只有一个 TwilioAgentPaymentServer 实例
  • 无需通过多个函数传递实例
  • 提供更简洁的 API 和更简单的函数签名
  • 可以更轻松地从代码库中的任何位置访问 TwilioAgentPaymentServer

工厂函数模式

工具、提示和资源是使用工厂功能模式实现的:

  1. 在工具中
    // Example from StartPaymentCaptureTool.ts export function startPaymentCaptureTool() { // Get the TwilioAgentPaymentServer instance const twilioAgentPaymentServer = TwilioAgentPaymentServer.getInstance(); // Create an event emitter for logging const emitter = new EventEmitter(); return { name: "startPaymentCapture", description: "Start a new payment capture session", shape: schema.shape, execute: async function execute(params: z.infer<typeof schema>, extra: any): Promise<ToolResult> { // Implementation that calls Twilio API and returns result }, emitter // For attaching event listeners } }
  2. 在资源中
    // Example from PaymentStatusResource.ts export function paymentStatusResource() { // Get the TwilioAgentPaymentServer instance const twilioAgentPaymentServer = TwilioAgentPaymentServer.getInstance(); // Create an event emitter for logging const emitter = new EventEmitter(); return { name: "PaymentStatus", template: new ResourceTemplate("payment://{callSid}/{paymentSid}/status", { list: undefined }), description: "Get the current status of a payment session", read: async (uri: URL, variables: Record<string, string | string[]>, extra: any): Promise<ResourceReadResult> => { // Implementation that retrieves and formats payment status data }, emitter // For attaching event listeners }; }
  3. 在提示中
    // Example from a prompt factory function export function startCapturePrompt() { return { name: "StartCapture", description: "Prompt for starting the payment capture process", execute: (args: { callSid: string }, extra: RequestHandlerExtra): GetPromptResult | Promise<GetPromptResult> => { // Return prompt content } }; }

自动发现和注册

服务器使用自动发现机制来查找并注册所有组件:

// In src/utils/autoDiscovery.ts export async function discoverComponents(mcpServer: McpServer) { // Get the current directory path 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')) ]); }

这种方法:

  • 自动查找各自目录中的所有工具、提示和资源
  • 动态导入并注册到 MCP 服务器
  • 无需修改主文件即可轻松添加新组件
  • 减少样板代码并提高可维护性

提示中的参数

某些提示可以接受参数,用于自定义提示内容。StartCapturePrompt 就是一个很好的例子:

  1. 参数定义
    // In the prompt factory function return { name: "StartCapture", description: "Prompt for starting the payment capture process", schema: { callSid: z.string().describe("The Twilio Call SID") }, // Parameter schema execute: (args: { callSid: string }, extra: RequestHandlerExtra) => { // Implementation } };
    • schema 属性使用 Zod 定义参数模式
    • 在这种情况下,它需要一个字符串类型的callSid参数
  2. 提示中的参数使用
    execute: (args: { callSid: string }, extra: RequestHandlerExtra): GetPromptResult | Promise<GetPromptResult> => { const { callSid } = args; if (!callSid) { throw new Error("callSid parameter is required"); } return { messages: [ { role: "assistant", content: { type: "text", text: getStartCapturePromptText(callSid), // Use the parameter in the prompt text } } ] }; }
    • 执行方法接受参数作为其第一个参数
    • 可以验证参数,并自定义提示内容
    • 在这种情况下,callSid 在提示文本中用于提供上下文

这种模式允许提示动态且具有上下文,根据支付流程的当前状态提供定制的指导。

可用工具

开始支付捕获

为活动呼叫启动付款捕获流程。

参数:

  • callSid :当前通话的 Twilio 呼叫 SID

重要提示:StartCapturePrompt.ts 要求用户在 MCP 客户端输入一个调用 SID。这是一个必需参数,如果未提供,提示将会抛出错误。

注意:处理 Twilio 呼叫时,您需要了解正在使用的呼叫 SID。Twilio 支付需要连接到 PSTN 侧呼叫线路。如果应用于 Twilio 客户端,则不会捕获 DTMF 数字。因此,此 MCP 服务器会假定正在使用正确的呼叫线路。通常检查方式如下:

// Pseudo code: direction of the call if (event.CallDirection === "toPSTN") { theCallSid = event.CallSid; } if (event.CallDirection == "toSIP") { theCallSid = event.ParentCallSid; }

返回:

  • paymentSid :新付款会话的 Twilio 付款 SID

捕获卡号

开始捕获支付卡号。

参数:

  • callSid :当前通话的 Twilio 呼叫 SID
  • paymentSid :支付会话的 Twilio 支付 SID
  • captureType :设置为“支付卡号”

返回:

  • 卡号捕获操作的状态

捕获安全码

开始捕获卡安全码。

参数:

  • callSid :当前通话的 Twilio 呼叫 SID
  • paymentSid :支付会话的 Twilio 支付 SID
  • captureType :设置为“安全码”

返回:

  • 安全代码捕获操作的状态

捕获到期日期

开始捕获卡到期日期。

参数:

  • callSid :当前通话的 Twilio 呼叫 SID
  • paymentSid :支付会话的 Twilio 支付 SID
  • captureType :设置为“expiration-date”

返回:

  • 到期日期捕获操作的状态

完成付款捕获

完成付款捕获会话。

参数:

  • callSid :当前通话的 Twilio 呼叫 SID
  • paymentSid :支付会话的 Twilio 支付 SID

返回:

  • 付款完成操作的状态

可用资源

付款://{callSid}/{paymentSid}/status

获取支付会话的当前状态(以 JSON 对象表示)。此资源提供有关支付捕获流程当前状态的详细信息,包括:

  • 付款 SID
  • 支付卡号(屏蔽)
  • 支付卡类型
  • 安全码状态
  • 截止日期
  • 付款确认码
  • 付款结果
  • 支付令牌

MCP 提示

服务器提供上下文提示,指导 LLM 完成支付流程的每个步骤:

开始捕获提示

提供有关如何启动付款捕获流程的指导,包括:

  • 询问客户是否准备好提供付款信息的说明
  • 安全处理和标记化的解释
  • 使用 startPaymentCapture 工具的步骤
  • 重要提示:要求用户从 MCP 客户端输入呼叫 SID,这是必需参数

卡号提示

指导LLM如何处理卡号捕获流程,包括:

  • 向客户解释所需信息的说明
  • 处理客户问题或疑虑的技巧
  • 使用captureCardNumber工具的步骤

安全码提示

提供获取卡片安全码的指导,包括:

  • 解释安全码的说明
  • 处理客户问题或疑虑的技巧
  • 使用captureSecurityCode工具的步骤

到期日期提示

指导法学硕士获取卡片到期日期,包括:

  • 解释所需格式的说明(MM/YY)
  • 处理客户问题或疑虑的技巧
  • 使用captureExpirationDate工具的步骤

完成捕获提示

提供完成付款捕获流程的指导,包括:

  • 确认已收集所有信息的说明
  • 使用 completePaymentCapture 工具的步骤

完成提示

指导法学硕士在付款成功处理后应采取的措施,包括:

  • 确认付款成功的说明
  • 对话后续步骤的建议

错误提示

提供处理付款过程中错误的指导,包括:

  • 向客户解释错误的说明
  • 解决常见问题的建议
  • 重试付款捕获流程的步骤

建筑学

该 MCP 服务器实现了增强的架构来处理支付流程:

基于事件的架构

服务器使用基于事件的架构,通过 EventEmitter 实现组件之间的通信:

  • 每个工具、资源和服务器组件都扩展了 EventEmitter
  • 组件发出用于日志记录和回调的事件
  • 事件监听器将日志转发到 MCP 服务器的日志系统

回调处理

服务器使用@deshartman/mcp-status-callback 包来处理来自 Twilio 的异步回调:

  • 使用 Ngrok 创建用于接收回调的安全隧道
  • 处理不同支付阶段的回调
  • 根据回调数据更新状态存储
  • 处理错误情况和重新进入的情况

状态管理

付款状态通过基于 Map 的商店进行管理:

  • statusCallbackMap 存储按付款 SID 索引的付款会话数据
  • 每次回调都会用最新信息更新状态
  • PaymentStatusResource 提供对此状态数据的访问

MCP 集成

服务器通过以下方式与 MCP 协议集成:

  • 工具:使用 Zod 模式定义输入验证
  • 资源:提供对支付状态数据的访问
  • 提示:支付流程每个步骤的上下文指导
  • 日志记录:基于事件的日志转发到 MCP 服务器

发展

要构建项目:

npm install npm run build

先决条件

  • Node.js 18+
  • Express(用于回调处理)
  • Twilio SDK
  • 带有授权令牌的 Ngrok 帐户

手动运行服务器

要手动启动服务器进行测试(在 Claude Desktop 之外):

# Run with actual credentials node build/index.js "your_account_sid_here" "your_api_key_here" "your_api_secret" # Or use the npm script (which uses ts-node for development) npm run dev -- "your_account_sid_here" "your_api_key_here" "your_api_secret"

服务器将启动并等待 MCP 客户端连接。

与 Claude Desktop 一起使用时,Claude 加载配置文件时服务器会自动启动。您无需手动启动它。

PCI合规性

此服务器通过标记支付卡信息来帮助满足 PCI 合规性。实际的卡数据由 Twilio 处理,绝不会存储在您的系统中。有关 Twilio PCI 合规性的更多信息,请参阅Twilio 安全支付文档

执照

麻省理工学院

MCP 检查器兼容性

将此服务器与 MCP 检查器一起使用时,请注意,所有日志记录均通过 MCP 日志记录功能完成,而不是console.log() 。这是有意为之,并且为了与使用 stdout 进行 JSON 通信的 MCP 协议兼容所必需的。

如果您正在扩展此服务器或调试问题:

  1. 通过发出 LOG_EVENT 事件来使用基于事件的日志系统
  2. 避免使用console.log() ,因为它会干扰 MCP 协议在 stdout 上的 JSON 消息
  3. 对于 MCP 上下文之外的调试,可以使用console.error()将其输出到 stderr

基于事件的日志记录架构

服务器使用基于事件的日志记录架构:

  1. 事件发射器:所有工具和资源类都扩展了 Node.js 的EventEmitter ,并发出带有级别和消息数据的“日志”事件。
  2. 日志转发:这些事件由事件监听器捕获并转发到 MCP 服务器的日志系统:
    // Set up event listeners for tool logs startPaymentCaptureTool.on(LOG_EVENT, logToMcp); captureCardNumberTool.on(LOG_EVENT, logToMcp); // ... other tools
  3. MCP 集成logToMcp函数将这些事件转换为与 MCP 兼容的日志消息:
    const logToMcp = (data: { level: string, message: string }) => { // Only use valid log levels: info, error, debug // If level is 'warn', treat it as 'info' const mcpLevel = data.level === 'warn' ? 'info' : data.level as "info" | "error" | "debug"; // Send the log message to the MCP server's underlying Server instance mcpServer.server.sendLoggingMessage({ level: mcpLevel, data: data.message, }); };

支持的日志级别

服务器支持以下日志级别:

  • info :一般信息消息
  • error :错误消息和异常
  • debug :详细调试信息
  • warn :警告信息(为了兼容 MCP,自动转换为“info”)

支付回调数据结构

服务器处理来自 Twilio 的两种主要类型的回调数据:

初始连接器数据

首次创建支付会话时,Twilio 会发送连接器数据:

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

捕获数据

当获取到支付信息后,Twilio 会发送更新的数据:

{ "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" }

服务器将该数据存储在 statusCallbackMap 中,通过付款 SID 进行索引,并通过 PaymentStatusResource 提供该数据。

Related MCP Servers

  • A
    security
    A
    license
    A
    quality
    The Voyp MCP Server enables AI systems to integrate with VOYP's calling capabilities, allowing for secure telephony actions such as making calls, scheduling appointments, and tracking call statuses through the Model Context Protocol.
    Last updated -
    7
    11
    4
    JavaScript
    MIT License
    • Apple
    • Linux
  • -
    security
    F
    license
    -
    quality
    An MCP (Model Context Protocol) server that lets users send SMS messages through Twilio API directly from Claude Desktop via natural language commands.
    Last updated -
    1
    TypeScript
    • Apple
  • -
    security
    F
    license
    -
    quality
    A server that connects Claude AI to Twilio through the Model Context Protocol, enabling prompt-assisted management of Twilio accounts, phone numbers, and regulatory compliance.
    Last updated -
    Python
    • Linux
    • Apple
  • -
    security
    F
    license
    -
    quality
    An MCP server that enables AI assistants to interact with Flutterwave payment services, providing tools for transaction management, payment link generation, and automated customer support.
    Last updated -
    TypeScript

View all related MCP servers

ID: 4mmirsww6y