@phqb/mcp-server
Version:
PHQB MCP Payment Server - AI-powered payment processing for Claude and other AI assistants
362 lines (349 loc) • 15.7 kB
JavaScript
"use strict";
// PHQB MCP 服务器核心实现
Object.defineProperty(exports, "__esModule", { value: true });
exports.PHQBMCPServer = void 0;
const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
const auth_1 = require("./auth");
const payment_1 = require("./tools/payment");
const refund_1 = require("./tools/refund");
const types_1 = require("./types");
class PHQBMCPServer {
constructor(apiKey, baseURL) {
this.server = new index_js_1.Server({
name: 'phqb-payment-server',
version: '1.0.0',
capabilities: {
tools: {},
},
});
this.authManager = new auth_1.MCPAuthManager(apiKey, baseURL);
this.paymentTools = new payment_1.PaymentTools(apiKey, baseURL);
this.refundTools = new refund_1.RefundTools(apiKey, baseURL);
}
async initialize() {
// 验证 API Key 并加载权限
const isValid = await this.authManager.validateAndLoadPermissions();
if (!isValid) {
throw new types_1.AuthenticationError('Invalid API Key or authentication failed');
}
console.log('✅ PHQB MCP Server initialized successfully');
console.log(`📋 Available tools: ${this.authManager.getAvailableTools().length}`);
this.setupHandlers();
}
setupHandlers() {
// 工具列表处理器
this.server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => {
const availableTools = this.authManager.getAvailableTools();
const tools = [];
// 根据用户权限动态生成工具列表
for (const toolName of availableTools) {
const tool = this.getToolDefinition(toolName);
if (tool) {
tools.push(tool);
}
}
return { tools };
});
// 工具调用处理器
this.server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
const { name: toolName, arguments: args } = request.params;
const startTime = Date.now();
let success = false;
let errorMessage;
try {
// 验证工具调用权限
await this.authManager.validateToolCall(toolName);
// 执行工具
const result = await this.executeTool(toolName, args);
success = true;
// 记录使用日志
const executionTime = Date.now() - startTime;
await this.authManager.logToolUsage(toolName, success, errorMessage, executionTime);
return result;
}
catch (error) {
success = false;
errorMessage = error instanceof Error ? error.message : 'Unknown error';
// 记录错误日志
const executionTime = Date.now() - startTime;
await this.authManager.logToolUsage(toolName, success, errorMessage, executionTime);
// 返回友好的错误信息
return this.handleError(error, toolName);
}
});
}
getToolDefinition(toolName) {
const toolDefinitions = {
// 支付创建工具组
create_wechat_payment: {
name: 'create_wechat_payment',
description: 'Create WeChat payment order with WeChat-specific QR code',
inputSchema: {
type: 'object',
properties: {
amount: { type: 'number', description: 'Payment amount (USD)' },
description: { type: 'string', description: 'Payment description' },
customer_email: { type: 'string', description: 'Customer email (optional)' },
expires_in: { type: 'number', default: 3600, description: 'Expiration time in seconds' },
success_url: { type: 'string', description: 'Success redirect URL (optional)' }
},
required: ['amount', 'description']
}
},
create_alipay_payment: {
name: 'create_alipay_payment',
description: 'Create Alipay payment order with Alipay-specific QR code',
inputSchema: {
type: 'object',
properties: {
amount: { type: 'number', description: 'Payment amount (USD)' },
description: { type: 'string', description: 'Payment description' },
customer_email: { type: 'string', description: 'Customer email (optional)' },
expires_in: { type: 'number', default: 3600, description: 'Expiration time in seconds' },
success_url: { type: 'string', description: 'Success redirect URL (optional)' }
},
required: ['amount', 'description']
}
},
create_auto_payment: {
name: 'create_auto_payment',
description: 'Create smart aggregated payment order, supports WeChat and Alipay',
inputSchema: {
type: 'object',
properties: {
amount: { type: 'number', description: 'Payment amount (USD)' },
description: { type: 'string', description: 'Payment description' },
customer_email: { type: 'string', description: 'Customer email (optional)' },
expires_in: { type: 'number', default: 3600, description: 'Expiration time in seconds' },
success_url: { type: 'string', description: 'Success redirect URL (optional)' }
},
required: ['amount', 'description']
}
},
// 订单管理工具组
get_order_details: {
name: 'get_order_details',
description: 'Get detailed information for a specific order',
inputSchema: {
type: 'object',
properties: {
order_id: { type: 'string', description: 'Order ID' }
},
required: ['order_id']
}
},
search_orders: {
name: 'search_orders',
description: 'Search orders by criteria',
inputSchema: {
type: 'object',
properties: {
status: {
type: 'string',
enum: ['all', 'pending', 'paid', 'failed', 'expired', 'refunded'],
default: 'all',
description: 'Order status'
},
amount_min: { type: 'number', description: 'Minimum amount' },
amount_max: { type: 'number', description: 'Maximum amount' },
date_from: { type: 'string', description: 'Start date (YYYY-MM-DD)' },
date_to: { type: 'string', description: 'End date (YYYY-MM-DD)' },
customer_email: { type: 'string', description: 'Customer email' },
limit: { type: 'number', default: 20, maximum: 100, description: 'Number of results' }
}
}
},
get_recent_orders: {
name: 'get_recent_orders',
description: 'Get recent orders list',
inputSchema: {
type: 'object',
properties: {
limit: {
type: 'number',
default: 10,
maximum: 100,
description: 'Number of results (max 100)'
},
status: {
type: 'string',
enum: ['all', 'pending', 'paid', 'failed'],
default: 'all',
description: 'Status filter'
}
}
}
},
cancel_order: {
name: 'cancel_order',
description: 'Cancel unpaid order',
inputSchema: {
type: 'object',
properties: {
order_id: { type: 'string', description: 'Order ID' },
reason: { type: 'string', description: 'Cancellation reason (optional)' }
},
required: ['order_id']
}
},
// 退款工具组
create_refund: {
name: 'create_refund',
description: 'Create refund for paid order',
inputSchema: {
type: 'object',
properties: {
order_id: { type: 'string', description: 'Original order ID' },
amount: { type: 'number', description: 'Refund amount (full refund if not specified)' },
reason: { type: 'string', description: 'Refund reason' }
},
required: ['order_id', 'reason']
}
},
get_refund_status: {
name: 'get_refund_status',
description: 'Query refund processing status',
inputSchema: {
type: 'object',
properties: {
refund_id: { type: 'string', description: 'Refund ID' }
},
required: ['refund_id']
}
},
get_refund_history: {
name: 'get_refund_history',
description: 'Get refund history records',
inputSchema: {
type: 'object',
properties: {
limit: { type: 'number', default: 20, description: 'Number of results' },
status: {
type: 'string',
enum: ['all', 'processing', 'completed', 'failed'],
default: 'all',
description: 'Refund status'
}
}
}
}
};
return toolDefinitions[toolName] || null;
}
async executeTool(toolName, args) {
// 根据工具名称执行相应的工具
switch (toolName) {
// 支付创建工具组
case 'create_wechat_payment':
const wechatArgs = types_1.CreatePaymentSchema.parse(args);
return await this.paymentTools.createWechatPayment(wechatArgs);
case 'create_alipay_payment':
const alipayArgs = types_1.CreatePaymentSchema.parse(args);
return await this.paymentTools.createAlipayPayment(alipayArgs);
case 'create_auto_payment':
const autoArgs = types_1.CreatePaymentSchema.parse(args);
return await this.paymentTools.createAutoPayment(autoArgs);
// 订单管理工具组
case 'get_order_details':
const orderDetailsArgs = types_1.OrderDetailsSchema.parse(args);
return await this.paymentTools.getOrderDetails(orderDetailsArgs);
case 'search_orders':
const searchArgs = types_1.SearchOrdersSchema.parse(args);
return await this.paymentTools.searchOrders(searchArgs);
case 'get_recent_orders':
const recentArgs = types_1.RecentOrdersSchema.parse(args);
return await this.paymentTools.getRecentOrders(recentArgs);
case 'cancel_order':
const cancelArgs = types_1.CancelOrderSchema.parse(args);
return await this.paymentTools.cancelOrder(cancelArgs);
// 退款工具组
case 'create_refund':
const refundArgs = types_1.CreateRefundSchema.parse(args);
return await this.refundTools.createRefund(refundArgs);
case 'get_refund_status':
const refundStatusArgs = types_1.RefundStatusSchema.parse(args);
return await this.refundTools.getRefundStatus(refundStatusArgs);
case 'get_refund_history':
const refundHistoryArgs = types_1.RefundHistorySchema.parse(args);
return await this.refundTools.getRefundHistory(refundHistoryArgs);
default:
throw new types_1.ValidationError(`Unknown tool: ${toolName}`);
}
}
handleError(error, toolName) {
if (error instanceof types_1.AuthenticationError) {
return {
content: [{
type: "text",
text: `❌ 认证失败
您的 API Key 无效或已过期。
💡 解决方案:
1. 检查 API Key 是否正确
2. 在 PHQB Dashboard 中重新生成 API Key
3. 确保 API Key 具有必要的权限
🔗 管理 API Key: https://www.phqb.com/dashboard?tab=apikey`
}],
isError: true
};
}
if (error instanceof types_1.PermissionError) {
return {
content: [{
type: "text",
text: `❌ 权限不足
您的 API Key 没有使用 "${toolName}" 工具的权限。
💡 解决方案:
1. 在 PHQB Dashboard 中编辑您的 API Key
2. 添加所需的权限
3. 或者升级到更高的套餐以获得更多权限
🔗 管理 API Key: https://www.phqb.com/dashboard?tab=apikey
🔗 升级套餐: https://www.phqb.com/dashboard?tab=subscription`
}],
isError: true
};
}
if (error instanceof types_1.ValidationError) {
return {
content: [{
type: "text",
text: `❌ 参数错误
${error.message}
💡 请检查输入参数是否正确,并参考工具说明。`
}],
isError: true
};
}
if (error instanceof types_1.MCPError) {
return {
content: [{
type: "text",
text: `❌ 操作失败
${error.message}
💡 如果问题持续存在,请联系 PHQB 客服。`
}],
isError: true
};
}
// 未知错误
console.error('Unexpected error:', error);
return {
content: [{
type: "text",
text: `❌ 系统错误
执行工具 "${toolName}" 时发生未知错误。
💡 请稍后重试,如果问题持续存在,请联系 PHQB 客服。
🔗 联系客服: https://www.phqb.com/support`
}],
isError: true
};
}
async run() {
const transport = new stdio_js_1.StdioServerTransport();
await this.server.connect(transport);
console.log('🚀 PHQB MCP Server is running...');
}
}
exports.PHQBMCPServer = PHQBMCPServer;
//# sourceMappingURL=server.js.map