/**
* Stripe MCP Integration Example
*
* Author: Yobie Benjamin
* Version: 0.2
* Date: July 28, 2025
*
* Example integration showing how Llama Maverick Hub orchestrates
* Stripe MCP operations for complex payment workflows.
*/
import winston from 'winston';
import { MCPClientManager } from '../clients/mcp-client-manager.js';
import { HubOrchestrator } from '../orchestrator/hub-orchestrator.js';
const logger = winston.createLogger({
level: 'debug',
format: winston.format.simple()
});
/**
* Stripe-specific workflow definitions
* These workflows demonstrate multi-service orchestration with Stripe
*/
export class StripeIntegration {
private orchestrator: HubOrchestrator;
private clientManager: MCPClientManager;
constructor(orchestrator: HubOrchestrator, clientManager: MCPClientManager) {
this.orchestrator = orchestrator;
this.clientManager = clientManager;
/**
* Register Stripe-specific workflows
* These workflows combine Stripe with other services
*/
this.registerStripeWorkflows();
}
/**
* Register pre-defined Stripe workflows
* Complex payment operations that span multiple services
*/
private registerStripeWorkflows(): void {
/**
* Customer Onboarding Workflow
* Creates customer, sets up payment, stores in database
*/
this.orchestrator.registerWorkflow({
id: 'stripe-customer-onboarding',
name: 'Complete Customer Onboarding',
description: 'Onboard a new customer with payment setup',
steps: [
{
id: 'create-customer',
service: 'stripe',
tool: 'create_customer',
arguments: {
email: '{{parameters.email}}',
name: '{{parameters.name}}',
metadata: {
source: 'llama-hub',
onboarding_date: new Date().toISOString()
}
}
},
{
id: 'create-payment-method',
service: 'stripe',
tool: 'create_payment_method',
arguments: {
type: 'card',
card: '{{parameters.card}}'
},
dependsOn: ['create-customer']
},
{
id: 'attach-payment-method',
service: 'stripe',
tool: 'attach_payment_method',
arguments: {
payment_method: '{{create-payment-method.id}}',
customer: '{{create-customer.id}}'
},
dependsOn: ['create-payment-method']
},
{
id: 'create-subscription',
service: 'stripe',
tool: 'create_subscription',
arguments: {
customer: '{{create-customer.id}}',
items: '{{parameters.subscription_items}}',
default_payment_method: '{{create-payment-method.id}}'
},
dependsOn: ['attach-payment-method'],
retryPolicy: {
maxRetries: 3,
backoffMs: 2000
}
},
{
id: 'store-customer',
service: 'database',
tool: 'insert_record',
arguments: {
table: 'customers',
data: {
stripe_customer_id: '{{create-customer.id}}',
email: '{{parameters.email}}',
name: '{{parameters.name}}',
subscription_id: '{{create-subscription.id}}',
status: 'active'
}
},
dependsOn: ['create-subscription']
},
{
id: 'send-welcome-email',
service: 'email',
tool: 'send_email',
arguments: {
to: '{{parameters.email}}',
subject: 'Welcome to Our Service!',
template: 'welcome',
data: {
name: '{{parameters.name}}',
subscription: '{{create-subscription}}'
}
},
dependsOn: ['store-customer']
}
],
context: new Map()
});
/**
* Refund Processing Workflow
* Processes refund with audit trail and notifications
*/
this.orchestrator.registerWorkflow({
id: 'stripe-refund-processing',
name: 'Process Customer Refund',
description: 'Handle refund with full audit trail',
steps: [
{
id: 'retrieve-charge',
service: 'stripe',
tool: 'retrieve_charge',
arguments: {
charge_id: '{{parameters.charge_id}}'
}
},
{
id: 'validate-refund',
service: 'stripe',
tool: 'validate_refund_eligibility',
arguments: {
charge: '{{retrieve-charge}}',
reason: '{{parameters.reason}}'
},
dependsOn: ['retrieve-charge']
},
{
id: 'create-refund',
service: 'stripe',
tool: 'create_refund',
arguments: {
charge: '{{parameters.charge_id}}',
amount: '{{parameters.amount}}',
reason: '{{parameters.reason}}',
metadata: {
processed_by: 'llama-hub',
workflow_id: '{{workflow.id}}'
}
},
dependsOn: ['validate-refund']
},
{
id: 'log-refund',
service: 'database',
tool: 'insert_record',
arguments: {
table: 'refund_audit',
data: {
refund_id: '{{create-refund.id}}',
charge_id: '{{parameters.charge_id}}',
amount: '{{parameters.amount}}',
reason: '{{parameters.reason}}',
timestamp: new Date().toISOString()
}
},
dependsOn: ['create-refund']
},
{
id: 'notify-customer',
service: 'email',
tool: 'send_email',
arguments: {
to: '{{retrieve-charge.customer.email}}',
subject: 'Refund Processed',
template: 'refund_confirmation',
data: {
refund: '{{create-refund}}',
original_charge: '{{retrieve-charge}}'
}
},
dependsOn: ['log-refund']
}
],
context: new Map()
});
/**
* Subscription Upgrade Workflow
* Handles plan changes with proration
*/
this.orchestrator.registerWorkflow({
id: 'stripe-subscription-upgrade',
name: 'Upgrade Customer Subscription',
description: 'Process subscription plan upgrade with proration',
steps: [
{
id: 'retrieve-subscription',
service: 'stripe',
tool: 'retrieve_subscription',
arguments: {
subscription_id: '{{parameters.subscription_id}}'
}
},
{
id: 'calculate-proration',
service: 'stripe',
tool: 'preview_proration',
arguments: {
subscription: '{{retrieve-subscription}}',
new_plan: '{{parameters.new_plan}}'
},
dependsOn: ['retrieve-subscription']
},
{
id: 'update-subscription',
service: 'stripe',
tool: 'update_subscription',
arguments: {
subscription_id: '{{parameters.subscription_id}}',
items: [{
id: '{{retrieve-subscription.items.data[0].id}}',
price: '{{parameters.new_plan}}'
}],
proration_behavior: 'create_prorations'
},
dependsOn: ['calculate-proration']
},
{
id: 'update-database',
service: 'database',
tool: 'update_record',
arguments: {
table: 'subscriptions',
where: {
stripe_subscription_id: '{{parameters.subscription_id}}'
},
data: {
plan: '{{parameters.new_plan}}',
upgraded_at: new Date().toISOString()
}
},
dependsOn: ['update-subscription']
},
{
id: 'send-upgrade-confirmation',
service: 'email',
tool: 'send_email',
arguments: {
to: '{{retrieve-subscription.customer.email}}',
subject: 'Subscription Upgraded Successfully',
template: 'upgrade_confirmation',
data: {
old_plan: '{{retrieve-subscription.items.data[0].price}}',
new_plan: '{{parameters.new_plan}}',
proration: '{{calculate-proration}}'
}
},
dependsOn: ['update-database']
}
],
context: new Map()
});
logger.info('Registered Stripe integration workflows');
}
/**
* Execute a Stripe-specific workflow
* Convenience method for Stripe operations
*/
async executeStripeWorkflow(
workflowId: string,
parameters: Record<string, any>
): Promise<any> {
logger.info(`Executing Stripe workflow: ${workflowId}`, { parameters });
try {
const result = await this.orchestrator.executeWorkflow(
`stripe-${workflowId}`,
parameters
);
if (result.success) {
logger.info(`Stripe workflow completed successfully: ${workflowId}`);
} else {
logger.error(`Stripe workflow failed: ${workflowId}`, result.errors);
}
return result;
} catch (error) {
logger.error(`Stripe workflow execution error: ${workflowId}`, error);
throw error;
}
}
/**
* Handle Stripe webhooks
* Process Stripe events and trigger workflows
*/
async handleStripeWebhook(event: any): Promise<void> {
logger.info(`Processing Stripe webhook: ${event.type}`);
try {
switch (event.type) {
case 'customer.subscription.created':
/**
* New subscription created
* Trigger onboarding completion workflow
*/
await this.orchestrator.executeTool('hub_execute_workflow', {
workflowId: 'stripe-onboarding-complete',
parameters: {
subscription: event.data.object
}
});
break;
case 'charge.failed':
/**
* Payment failed
* Trigger retry and notification workflow
*/
await this.orchestrator.executeTool('hub_execute_workflow', {
workflowId: 'stripe-payment-failure',
parameters: {
charge: event.data.object
}
});
break;
case 'customer.subscription.deleted':
/**
* Subscription cancelled
* Trigger cleanup workflow
*/
await this.orchestrator.executeTool('hub_execute_workflow', {
workflowId: 'stripe-subscription-cleanup',
parameters: {
subscription: event.data.object
}
});
break;
default:
logger.debug(`Unhandled Stripe event type: ${event.type}`);
}
} catch (error) {
logger.error(`Failed to handle Stripe webhook: ${event.type}`, error);
throw error;
}
}
/**
* Smart payment routing
* Uses Llama AI to determine best payment processing strategy
*/
async smartPaymentRouting(
amount: number,
currency: string,
customer: any
): Promise<{
method: string;
processor: string;
reasoning: string;
}> {
logger.info('Determining optimal payment routing', { amount, currency });
/**
* Use Llama to analyze and route payment
* AI considers multiple factors for optimal routing
*/
const routing = await this.orchestrator.executeTool('hub_smart_route', {
query: `Determine the best payment processing method for:
Amount: ${amount} ${currency}
Customer Location: ${customer.location}
Customer History: ${customer.payment_history}
Risk Score: ${customer.risk_score}`,
context: {
available_processors: ['stripe', 'paypal', 'square'],
fee_structures: {
stripe: '2.9% + $0.30',
paypal: '2.99% + $0.49',
square: '2.6% + $0.10'
}
}
});
return routing;
}
/**
* Fraud detection workflow
* Combines Stripe's fraud tools with custom checks
*/
async runFraudDetection(
charge: any,
customer: any
): Promise<{
risk_level: 'low' | 'medium' | 'high';
factors: string[];
recommendation: string;
}> {
logger.info('Running fraud detection', {
charge_id: charge.id,
customer_id: customer.id
});
/**
* Parallel fraud checks across services
* Aggregate results from multiple sources
*/
const fraudResults = await this.orchestrator.executeTool('hub_parallel_query', {
services: ['stripe', 'fraud_service', 'database'],
query: JSON.stringify({
charge: charge,
customer: customer,
check_type: 'fraud_detection'
})
});
/**
* Use Llama to synthesize fraud analysis
* AI provides comprehensive risk assessment
*/
const analysis = await this.orchestrator.executeTool('hub_smart_route', {
query: 'Analyze these fraud detection results and provide risk assessment',
context: fraudResults
});
return analysis;
}
/**
* Revenue optimization workflow
* Uses AI to optimize pricing and discounts
*/
async optimizeRevenue(
customer: any,
product: any
): Promise<{
recommended_price: number;
discount_strategy: string;
expected_conversion: number;
}> {
logger.info('Running revenue optimization', {
customer_id: customer.id,
product_id: product.id
});
/**
* Gather data from multiple sources
* Combine Stripe data with analytics
*/
const data = await this.orchestrator.executeTool('hub_parallel_query', {
services: ['stripe', 'analytics', 'database'],
query: JSON.stringify({
customer_segment: customer.segment,
product_category: product.category,
historical_performance: true
})
});
/**
* Use Llama for pricing optimization
* AI analyzes patterns and suggests pricing
*/
const optimization = await this.orchestrator.executeTool('hub_smart_route', {
query: `Optimize pricing strategy for:
Customer Segment: ${customer.segment}
Product: ${product.name}
Current Price: ${product.price}
Historical Data: ${JSON.stringify(data)}`,
context: {
business_goals: 'maximize_revenue',
constraints: {
min_margin: 0.3,
max_discount: 0.25
}
}
});
return optimization;
}
}