Code Examples
These examples show common tasks with the FinAegis API. Copy them as a starting point for your own code.
The official SDKs cover accounts, transactions, transfers, assets, exchange rates, baskets, the GCU demo and webhooks. Some JavaScript and Python examples also call helpers the SDKs do not include yet, such as waiting for a transfer, workflows and the AI and MCP clients. For those, call the REST endpoints listed in the API docs.
Browse by Category
Basic Operations
Create accounts, read balances and send simple transfers.
Advanced Workflows
Run multi-step transactions, batch jobs and sagas.
Webhooks
Receive event notifications and handle them.
Error Handling
Handle errors and retry failed requests.
AI Agent Integration
Use the banking AI assistant and its tools.
MCP Tools
Connect agents through the Model Context Protocol.
Cross-Chain and Decentralised Finance
Bridge tokens between networks and swap on decentralised exchanges.
Reporting Modules
Run the Travel Rule check before a transfer.
Partner API
Apply to become a partner institution.
AI Transaction Query
Search transactions with a question in plain language.
Basic Operations
Create Account and Get Balance
This example creates an account and reads its balances.
// Install: npm install @finaegis/sdk
import { FinAegis } from '@finaegis/sdk';
const client = new FinAegis({
apiKey: process.env.ZELTA_API_KEY,
baseURL: 'https://finaegis.org/api/v2'
});
async function createAccountAndCheckBalance() {
try {
// Create a new account
const account = await client.accounts.create({
name: 'My Main Account',
type: 'personal',
metadata: {
customer_id: 'cust_123',
purpose: 'savings'
}
});
console.log('Account created:', account.uuid);
// Get account balances
const balances = await client.accounts.getBalances(account.uuid);
console.log('Current balances:');
balances.data.balances.forEach(balance => {
console.log(`${balance.asset_code}: ${balance.available_balance}`);
});
return account;
} catch (error) {
console.error('Error:', error.message);
throw error;
}
}
createAccountAndCheckBalance();
# Install: pip install finaegis
from finaegis import FinAegis
import os
client = FinAegis(
api_key=os.environ['ZELTA_API_KEY'],
base_url='https://finaegis.org/api/v2'
)
def create_account_and_check_balance():
try:
# Create a new account
account = client.accounts.create(
name='My Main Account',
type='personal',
metadata={
'customer_id': 'cust_123',
'purpose': 'savings'
}
)
print(f'Account created: {account.uuid}')
# Get account balances
balances = client.accounts.get_balances(account.uuid)
print('Current balances:')
for balance in balances.data.balances:
print(f'{balance.asset_code}: {balance.available_balance}')
return account
except Exception as error:
print(f'Error: {error}')
raise
create_account_and_check_balance()
<?php
// Install: composer require finaegis/payment-sdk
require_once 'vendor/autoload.php';
use Zelta\PaymentSDK\Client;
$client = new Client([
'apiKey' => $_ENV['ZELTA_API_KEY'],
'baseURL' => 'https://finaegis.org/api/v2'
]);
function createAccountAndCheckBalance($client) {
try {
// Create a new account
$account = $client->accounts->create([
'name' => 'My Main Account',
'type' => 'personal',
'metadata' => [
'customer_id' => 'cust_123',
'purpose' => 'savings'
]
]);
echo "Account created: {$account->uuid}\n";
// Get account balances
$balances = $client->accounts->getBalances($account->uuid);
echo "Current balances:\n";
foreach ($balances->data->balances as $balance) {
echo "{$balance->asset_code}: {$balance->available_balance}\n";
}
return $account;
} catch (Exception $e) {
echo "Error: {$e->getMessage()}\n";
throw $e;
}
}
createAccountAndCheckBalance($client);
# Create a new account
curl -X POST https://finaegis.org/api/v2/accounts \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "My Main Account",
"type": "personal",
"metadata": {
"customer_id": "cust_123",
"purpose": "savings"
}
}'
# Response
{
"data": {
"uuid": "acct_1234567890abcdef",
"name": "My Main Account",
"type": "personal",
"status": "active",
"created_at": "2025-01-01T12:00:00Z"
}
}
# Get account balances
curl -X GET https://finaegis.org/api/v2/accounts/acct_1234567890abcdef/balances \
-H "Authorization: Bearer YOUR_API_KEY"
Simple Money Transfer
This example moves funds between two accounts. A workflow processes the transfer.
async function transferFunds(fromAccount, toAccount, amount) {
try {
const transfer = await client.transfers.create({
from_account: fromAccount,
to_account: toAccount,
amount: amount,
asset_code: 'USD',
reference: 'Payment for services',
workflow_enabled: true,
metadata: {
invoice_id: 'INV-2025-001',
payment_type: 'service'
}
});
console.log('Transfer initiated:', transfer.uuid);
console.log('Status:', transfer.status);
console.log('Workflow ID:', transfer.workflow_id);
// Poll for completion
const completed = await client.transfers.waitForCompletion(
transfer.uuid,
{ timeout: 30000 }
);
console.log('Transfer completed:', completed.status);
return completed;
} catch (error) {
console.error('Transfer failed:', error.message);
throw error;
}
}
// Usage
transferFunds(
'acct_1234567890',
'acct_0987654321',
'100.00'
);
def transfer_funds(from_account, to_account, amount):
try:
transfer = client.transfers.create(
from_account=from_account,
to_account=to_account,
amount=amount,
asset_code='USD',
reference='Payment for services',
workflow_enabled=True,
metadata={
'invoice_id': 'INV-2025-001',
'payment_type': 'service'
}
)
print(f'Transfer initiated: {transfer.uuid}')
print(f'Status: {transfer.status}')
print(f'Workflow ID: {transfer.workflow_id}')
# Poll for completion
completed = client.transfers.wait_for_completion(
transfer.uuid,
timeout=30000
)
print(f'Transfer completed: {completed.status}')
return completed
except Exception as error:
print(f'Transfer failed: {error}')
raise
# Usage
transfer_funds(
'acct_1234567890',
'acct_0987654321',
'100.00'
)
{
"data": {
"uuid": "txfr_abc123def456",
"from_account": "acct_1234567890",
"to_account": "acct_0987654321",
"amount": "100.00",
"asset_code": "USD",
"status": "pending",
"reference": "Payment for services",
"workflow_id": "wf_789xyz012",
"created_at": "2025-01-01T12:00:00Z",
"estimated_completion": "2025-01-01T12:05:00Z",
"metadata": {
"invoice_id": "INV-2025-001",
"payment_type": "service"
},
"fees": {
"transfer_fee": "0.50",
"currency": "USD"
}
}
}
List Account Transactions
This example reads the transaction history one page at a time, with filters.
async function getAccountTransactions(accountId, options = {}) {
try {
const transactions = await client.accounts.getTransactions(accountId, {
limit: options.limit || 20,
page: options.page || 1,
type: options.type, // 'deposit', 'withdrawal', 'transfer'
status: options.status, // 'pending', 'completed', 'failed'
start_date: options.startDate,
end_date: options.endDate,
sort: options.sort || '-created_at' // - for descending
});
console.log(`Found ${transactions.meta.total} transactions`);
console.log(`Showing page ${transactions.meta.current_page} of ${transactions.meta.last_page}`);
transactions.data.forEach(tx => {
console.log(`${tx.created_at}: ${tx.type} ${tx.amount} ${tx.asset_code} - ${tx.status}`);
});
return transactions;
} catch (error) {
console.error('Failed to fetch transactions:', error.message);
throw error;
}
}
// Usage examples
// Get all transactions
getAccountTransactions('acct_1234567890');
// Get withdrawals from last 30 days
getAccountTransactions('acct_1234567890', {
type: 'withdrawal',
startDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString()
});
# Get all transactions for an account
curl -X GET "https://finaegis.org/api/v2/accounts/acct_1234567890/transactions" \
-H "Authorization: Bearer YOUR_API_KEY"
# Get transactions with filters
curl -X GET "https://finaegis.org/api/v2/accounts/acct_1234567890/transactions?\
limit=20&\
page=1&\
type=withdrawal&\
status=completed&\
start_date=2025-01-01T00:00:00Z&\
end_date=2025-01-31T23:59:59Z&\
sort=-created_at" \
-H "Authorization: Bearer YOUR_API_KEY"
{
"data": [
{
"uuid": "tx_789xyz123abc",
"account_uuid": "acct_1234567890",
"type": "deposit",
"amount": "500.00",
"asset_code": "USD",
"status": "completed",
"reference": "Salary deposit",
"created_at": "2025-01-15T10:30:00Z",
"completed_at": "2025-01-15T10:30:05Z",
"balance_after": "1500.00"
},
{
"uuid": "tx_456def789ghi",
"account_uuid": "acct_1234567890",
"type": "withdrawal",
"amount": "100.00",
"asset_code": "USD",
"status": "completed",
"reference": "ATM withdrawal",
"created_at": "2025-01-14T15:45:00Z",
"completed_at": "2025-01-14T15:45:10Z",
"balance_after": "1000.00"
}
],
"meta": {
"current_page": 1,
"last_page": 5,
"per_page": 20,
"total": 95,
"from": 1,
"to": 20
},
"links": {
"first": "https://finaegis.org/api/v2/accounts/acct_1234567890/transactions?page=1",
"last": "https://finaegis.org/api/v2/accounts/acct_1234567890/transactions?page=5",
"prev": null,
"next": "https://finaegis.org/api/v2/accounts/acct_1234567890/transactions?page=2"
}
}
Advanced Workflows
Multi-Currency Conversion with Transfer
This example converts a currency and sends a transfer in one workflow.
async function convertAndTransfer(fromAccount, toAccount, amount, fromCurrency, toCurrency) {
try {
// Get current exchange rate
const rate = await client.exchangeRates.get(fromCurrency, toCurrency);
const convertedAmount = (parseFloat(amount) * rate.rate).toFixed(2);
console.log(`Exchange rate: 1 ${fromCurrency} = ${rate.rate} ${toCurrency}`);
console.log(`Converting ${amount} ${fromCurrency} to ${convertedAmount} ${toCurrency}`);
// Create workflow for conversion + transfer
const workflow = await client.workflows.create({
type: 'currency_conversion_transfer',
steps: [
{
type: 'currency_conversion',
from_account: fromAccount,
amount: amount,
from_currency: fromCurrency,
to_currency: toCurrency,
max_slippage: 0.01 // 1% max slippage
},
{
type: 'transfer',
from_account: fromAccount,
to_account: toAccount,
amount: convertedAmount,
asset_code: toCurrency,
reference: 'Converted payment'
}
],
compensation_enabled: true
});
console.log('Workflow started:', workflow.uuid);
// Monitor workflow progress
const result = await client.workflows.monitor(workflow.uuid, {
onProgress: (step) => console.log(`Step ${step.name}: ${step.status}`),
timeout: 60000
});
return result;
} catch (error) {
console.error('Workflow failed:', error.message);
// Check if compensation was executed
if (error.compensation_executed) {
console.log('Automatic rollback completed');
}
throw error;
}
}
convertAndTransfer(
'acct_source123',
'acct_dest456',
'1000.00',
'USD',
'EUR'
);
Webhooks
Setting Up Webhook Endpoints
This example receives webhook events and checks their signatures.
Express.js Handler
const express = require('express');
const crypto = require('crypto');
const app = express();
// Middleware to verify webhook signatures
function verifyWebhookSignature(req, res, next) {
const signature = req.headers['x-zelta-signature'];
const payload = JSON.stringify(req.body);
const secret = process.env.WEBHOOK_SECRET;
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
if (signature !== expectedSignature) {
return res.status(401).send('Invalid signature');
}
next();
}
// Webhook endpoint
app.post('/webhooks/zelta',
express.json(),
verifyWebhookSignature,
(req, res) => {
const { event_type, data } = req.body;
console.log(`Received webhook: ${event_type}`);
switch (event_type) {
case 'transfer.completed':
handleTransferCompleted(data);
break;
case 'transfer.failed':
handleTransferFailed(data);
break;
case 'account.balance_updated':
handleBalanceUpdated(data);
break;
case 'workflow.completed':
handleWorkflowCompleted(data);
break;
case 'workflow.compensation_executed':
handleCompensationExecuted(data);
break;
default:
console.log(`Unhandled event type: ${event_type}`);
}
res.status(200).send('OK');
}
);
async function handleTransferCompleted(transfer) {
console.log(`Transfer ${transfer.uuid} completed`);
// Update your database
await updateTransferStatus(transfer.uuid, 'completed');
// Send notification to user
await notifyUser(transfer.from_account, {
type: 'transfer_completed',
amount: transfer.amount,
currency: transfer.asset_code,
reference: transfer.reference
});
}
async function handleWorkflowCompleted(workflow) {
console.log(`Workflow ${workflow.uuid} completed successfully`);
// Process completion logic
await processWorkflowCompletion(workflow);
}
Webhook Configuration
// Configure webhook endpoints
async function setupWebhooks() {
const webhook = await client.webhooks.create({
url: 'https://yourapp.com/webhooks/zelta',
events: [
'transfer.completed',
'transfer.failed',
'account.balance_updated',
'workflow.completed',
'workflow.failed',
'workflow.compensation_executed'
],
secret: process.env.WEBHOOK_SECRET,
active: true
});
console.log('Webhook configured:', webhook.id);
return webhook;
}
// Test webhook delivery
async function testWebhook(webhookId) {
const result = await client.webhooks.test(webhookId, {
event_type: 'test.webhook',
data: { message: 'Test webhook delivery' }
});
console.log('Test result:', result.status);
}
AI Agent Integration
AI Banking Assistant Chat
This example sends chat messages to the banking AI assistant. The assistant keeps the context of the conversation.
// Install: npm install @finaegis/sdk
import { FinAegisAI } from '@finaegis/sdk';
const aiClient = new FinAegisAI({
apiKey: process.env.ZELTA_API_KEY,
conversationId: 'conv_' + Math.random().toString(36).substr(2, 9)
});
async function bankingConversation() {
try {
// Send a message to the AI agent
const response = await aiClient.chat({
message: "I need to transfer $500 to John Smith and check my balance",
context: {
user_id: 'user_123',
account_id: 'acct_primary',
session_type: 'web',
authentication_level: 'mfa_verified'
},
options: {
enable_tools: true,
confidence_threshold: 0.8,
human_approval_required: true
}
});
console.log('AI Response:', response.content);
console.log('Confidence:', response.confidence);
console.log('Tools Used:', response.tools_used);
// Handle tool actions
if (response.requires_action) {
for (const action of response.actions) {
console.log(`Action Required: ${action.type}`);
switch(action.type) {
case 'transfer':
// Execute transfer with human approval
await executeTransferWithApproval(action.parameters);
break;
case 'balance_check':
// Get and display balance
const balance = await getAccountBalance(action.parameters.account_id);
console.log(`Current balance: ${balance}`);
break;
}
}
}
// Provide feedback
await aiClient.feedback({
message_id: response.message_id,
rating: 5,
feedback: "Helpful and accurate"
});
return response;
} catch (error) {
console.error('AI conversation failed:', error);
throw error;
}
}
// Handle streaming responses for real-time interaction
async function streamingChat() {
const stream = await aiClient.chatStream({
message: "Explain my recent transactions and spending patterns",
enable_analysis: true
});
for await (const chunk of stream) {
if (chunk.type === 'content') {
process.stdout.write(chunk.text);
} else if (chunk.type === 'tool_call') {
console.log('\n[Analyzing with:', chunk.tool_name, ']');
} else if (chunk.type === 'complete') {
console.log('\n\nAnalysis complete');
console.log('Insights:', chunk.insights);
}
}
}
# Install: pip install finaegis
from zelta import FinAegisAI
import asyncio
import os
import uuid
ai_client = FinAegisAI(
api_key=os.environ['ZELTA_API_KEY'],
conversation_id=f'conv_{uuid.uuid4().hex[:9]}'
)
async def banking_conversation():
try:
# Send a message to the AI agent
response = await ai_client.chat(
message="I need to transfer $500 to John Smith and check my balance",
context={
'user_id': 'user_123',
'account_id': 'acct_primary',
'session_type': 'web',
'authentication_level': 'mfa_verified'
},
options={
'enable_tools': True,
'confidence_threshold': 0.8,
'human_approval_required': True
}
)
print(f'AI Response: {response.content}')
print(f'Confidence: {response.confidence}')
print(f'Tools Used: {response.tools_used}')
# Handle tool actions
if response.requires_action:
for action in response.actions:
print(f'Action Required: {action.type}')
if action.type == 'transfer':
# Execute transfer with human approval
await execute_transfer_with_approval(action.parameters)
elif action.type == 'balance_check':
# Get and display balance
balance = await get_account_balance(action.parameters['account_id'])
print(f'Current balance: {balance}')
# Provide feedback
await ai_client.feedback(
message_id=response.message_id,
rating=5,
feedback="Helpful and accurate"
)
return response
except Exception as error:
print(f'AI conversation failed: {error}')
raise
# Handle streaming responses
async def streaming_chat():
stream = await ai_client.chat_stream(
message="Explain my recent transactions and spending patterns",
enable_analysis=True
)
async for chunk in stream:
if chunk.type == 'content':
print(chunk.text, end='', flush=True)
elif chunk.type == 'tool_call':
print(f'\n[Analyzing with: {chunk.tool_name}]')
elif chunk.type == 'complete':
print('\n\nAnalysis complete')
print(f'Insights: {chunk.insights}')
# Run the conversation
asyncio.run(banking_conversation())
{
"message_id": "msg_abc123xyz",
"conversation_id": "conv_def456",
"content": "I'll help you transfer $500 to John Smith and check your balance. Let me process this for you.",
"confidence": 0.92,
"requires_action": true,
"actions": [
{
"type": "transfer",
"description": "Transfer $500 to John Smith",
"parameters": {
"amount": "500.00",
"currency": "USD",
"recipient": "John Smith",
"recipient_account": "acct_john_smith_789",
"reference": "Transfer to John Smith",
"requires_approval": true
},
"confidence": 0.89
},
{
"type": "balance_check",
"description": "Check account balance",
"parameters": {
"account_id": "acct_primary",
"include_pending": true
},
"confidence": 0.95
}
],
"tools_used": [
"RecipientLookupTool",
"TransferValidationTool",
"AccountBalanceTool",
"FraudDetectionTool"
],
"context_retained": {
"user_intent": "transfer_and_balance",
"entities": ["John Smith", "$500", "balance"],
"sentiment": "neutral",
"urgency": "normal"
},
"metadata": {
"processing_time_ms": 342,
"model_version": "zelta-ai-v2",
"mcp_tools_available": 12,
"workflow_id": "wf_banking_assist_789"
}
}
AI-Driven Workflow Orchestration
This example lets the AI assistant decide the steps of a multi-step operation.
// AI-powered customer service workflow
async function handleCustomerRequest(customerId, request) {
const workflow = await aiClient.createWorkflow({
type: 'customer_service',
customer_id: customerId,
initial_request: request,
// AI configuration
ai_config: {
enable_sentiment_analysis: true,
enable_intent_detection: true,
enable_fraud_detection: true,
confidence_threshold: 0.85
},
// Workflow steps with AI integration
steps: [
{
name: 'analyze_request',
type: 'ai_analysis',
config: {
detect_urgency: true,
extract_entities: true,
classify_intent: true
}
},
{
name: 'route_request',
type: 'ai_routing',
config: {
routing_rules: 'dynamic',
consider_agent_availability: true,
skill_matching: true
}
},
{
name: 'process_request',
type: 'ai_processing',
config: {
enable_tools: true,
max_iterations: 5,
human_in_loop: 'conditional'
}
},
{
name: 'quality_check',
type: 'ai_validation',
config: {
check_compliance: true,
verify_accuracy: true,
sentiment_threshold: 0.7
}
}
],
// Human-in-the-loop configuration
human_intervention: {
triggers: [
{ condition: 'confidence < 0.7', action: 'escalate_to_human' },
{ condition: 'fraud_score > 0.8', action: 'security_review' },
{ condition: 'amount > 10000', action: 'manual_approval' }
]
}
});
// Monitor workflow progress
workflow.on('step_complete', (step) => {
console.log(`Step ${step.name} completed:`, step.result);
if (step.ai_insights) {
console.log('AI Insights:', step.ai_insights);
}
});
workflow.on('human_intervention_required', async (intervention) => {
console.log('Human intervention needed:', intervention.reason);
// Get human decision
const decision = await requestHumanDecision(intervention);
workflow.resume(decision);
});
// Wait for completion
const result = await workflow.execute();
return {
workflow_id: workflow.id,
status: result.status,
resolution: result.resolution,
ai_summary: result.ai_summary,
customer_satisfaction_prediction: result.satisfaction_score
};
}
// Example usage
handleCustomerRequest('cust_123',
"I noticed unusual charges on my account and need help understanding them"
);
MCP Tools Integration
MCP Tool Registration and Usage
This example registers your own banking tool for AI agents.
// Register custom MCP tools for banking operations
// Install: npm install @finaegis/sdk
import { MCPServer } from '@finaegis/sdk';
const mcpServer = new MCPServer({
name: 'banking-tools',
version: '1.0.0',
description: 'Custom banking tools for AI agents'
});
// Register Account Balance Tool
mcpServer.registerTool({
name: 'get_account_balance',
description: 'Retrieve the current balance for a customer account',
parameters: {
type: 'object',
properties: {
account_id: {
type: 'string',
description: 'The account identifier'
},
include_pending: {
type: 'boolean',
description: 'Include pending transactions in balance',
default: false
},
currency: {
type: 'string',
description: 'Currency code for balance display',
default: 'USD'
}
},
required: ['account_id']
},
handler: async (params) => {
// Tool implementation
const balance = await getAccountBalance(params.account_id);
if (params.include_pending) {
const pending = await getPendingTransactions(params.account_id);
balance.pending = pending.reduce((sum, tx) => sum + tx.amount, 0);
}
return {
account_id: params.account_id,
available_balance: balance.available,
current_balance: balance.current,
pending_balance: balance.pending || 0,
currency: params.currency,
as_of: new Date().toISOString()
};
}
});
// Register Transfer Authorization Tool
mcpServer.registerTool({
name: 'authorize_transfer',
description: 'Authorize and initiate a money transfer between accounts',
parameters: {
type: 'object',
properties: {
from_account: { type: 'string', description: 'Source account ID' },
to_account: { type: 'string', description: 'Destination account ID' },
amount: { type: 'number', description: 'Transfer amount' },
currency: { type: 'string', description: 'Currency code' },
reference: { type: 'string', description: 'Transfer reference' },
require_2fa: { type: 'boolean', default: true }
},
required: ['from_account', 'to_account', 'amount', 'currency']
},
handler: async (params) => {
// Validate transfer
const validation = await validateTransfer(params);
if (!validation.is_valid) {
return {
success: false,
error: validation.error,
error_code: validation.error_code
};
}
// Check 2FA if required
if (params.require_2fa) {
const twoFaStatus = await check2FA(params.from_account);
if (!twoFaStatus.verified) {
return {
success: false,
error: '2FA verification required',
action_required: 'verify_2fa',
verification_url: twoFaStatus.verification_url
};
}
}
// Execute transfer
const transfer = await executeTransfer(params);
return {
success: true,
transfer_id: transfer.id,
status: transfer.status,
estimated_completion: transfer.estimated_completion,
fee: transfer.fee,
exchange_rate: transfer.exchange_rate
};
}
});
// Register Fraud Detection Tool
mcpServer.registerTool({
name: 'check_fraud_risk',
description: 'Analyze transaction or activity for fraud risk',
parameters: {
type: 'object',
properties: {
transaction_data: {
type: 'object',
description: 'Transaction details to analyze'
},
customer_id: {
type: 'string',
description: 'Customer identifier'
},
check_type: {
type: 'string',
enum: ['transaction', 'login', 'account_change'],
description: 'Type of fraud check'
}
},
required: ['transaction_data', 'customer_id', 'check_type']
},
handler: async (params) => {
const riskAnalysis = await analyzeFraudRisk(params);
return {
risk_score: riskAnalysis.score,
risk_level: riskAnalysis.level, // low, medium, high, critical
flags: riskAnalysis.flags,
recommended_action: riskAnalysis.recommended_action,
similar_patterns: riskAnalysis.similar_patterns,
ml_confidence: riskAnalysis.confidence
};
}
});
// Start MCP server
mcpServer.start({
port: 3001,
enableLogging: true,
rateLimiting: {
enabled: true,
maxRequests: 100,
windowMs: 60000
}
});
console.log('MCP Banking Tools Server started on port 3001');
// Using MCP tools in AI conversations
const aiClient = new FinAegisAI({
apiKey: process.env.ZELTA_API_KEY,
mcp_servers: [
{
url: 'http://localhost:3001',
name: 'banking-tools',
api_key: process.env.MCP_TOOLS_KEY
}
]
});
// AI agent automatically discovers and uses available tools
async function intelligentBankingAssistant() {
// List available tools
const tools = await aiClient.getAvailableTools();
console.log('Available MCP Tools:', tools.map(t => t.name));
// Send a message that requires tool usage
const response = await aiClient.chat({
message: "Check my savings account balance and transfer $200 to checking",
enable_tools: true,
tool_preferences: {
preferred_tools: ['get_account_balance', 'authorize_transfer'],
auto_execute: false, // Require confirmation
parallel_execution: true
}
});
// AI automatically selects and uses appropriate tools
console.log('AI Plan:', response.execution_plan);
// Example execution plan:
// 1. Use 'get_account_balance' for savings account
// 2. Use 'get_account_balance' for checking account
// 3. Validate sufficient funds
// 4. Use 'authorize_transfer' to move money
// Review tool calls before execution
for (const toolCall of response.tool_calls) {
console.log(`Tool: ${toolCall.tool_name}`);
console.log(`Parameters:`, toolCall.parameters);
console.log(`Reason: ${toolCall.reasoning}`);
// Approve or modify tool call
const approved = await confirmToolExecution(toolCall);
if (approved) {
const result = await aiClient.executeTool(toolCall);
console.log(`Result:`, result);
}
}
return response;
}
// Advanced: Custom tool selection logic
async function customToolStrategy() {
const response = await aiClient.chat({
message: "Analyze my spending and suggest budget improvements",
tool_strategy: {
// Custom tool selection function
selector: async (availableTools, context) => {
const relevantTools = [];
// Select tools based on context
if (context.intent.includes('spending')) {
relevantTools.push('get_transaction_history');
relevantTools.push('analyze_spending_patterns');
}
if (context.intent.includes('budget')) {
relevantTools.push('create_budget_plan');
relevantTools.push('spending_insights');
}
return relevantTools;
},
// Tool execution order
execution_order: 'dependency_based', // or 'parallel', 'sequential'
// Result aggregation
aggregation: 'smart_summary' // or 'raw', 'structured'
}
});
return response;
}
// Monitor tool performance
aiClient.on('tool_executed', (event) => {
console.log(`Tool ${event.tool_name} executed in ${event.duration_ms}ms`);
console.log(`Success: ${event.success}`);
// Track tool usage metrics
trackToolMetrics({
tool: event.tool_name,
duration: event.duration_ms,
success: event.success,
timestamp: event.timestamp
});
});
{
"name": "zelta-banking-tools",
"version": "1.0.0",
"description": "MCP tools for FinAegis banking operations",
"author": "FinAegis",
"license": "Apache-2.0",
"server": {
"command": "node",
"args": ["./mcp-server.js"],
"env": {
"NODE_ENV": "production",
"MCP_PORT": "3001"
}
},
"tools": [
{
"name": "get_account_balance",
"description": "Retrieve account balance with pending transactions",
"category": "account_management",
"rate_limit": 100,
"cache_ttl": 60
},
{
"name": "authorize_transfer",
"description": "Authorize money transfers between accounts",
"category": "transactions",
"requires_auth": true,
"requires_2fa": true,
"rate_limit": 20
},
{
"name": "check_fraud_risk",
"description": "Analyze activities for fraud risk",
"category": "security",
"ml_enabled": true,
"real_time": true
},
{
"name": "get_transaction_history",
"description": "Retrieve transaction history with filtering",
"category": "account_management",
"pagination": true,
"max_results": 1000
},
{
"name": "analyze_spending_patterns",
"description": "AI-powered spending analysis",
"category": "insights",
"ml_model": "spending-analyzer-v2"
},
{
"name": "create_budget_plan",
"description": "Generate personalized budget recommendations",
"category": "financial_planning",
"personalization": true
}
],
"capabilities": {
"parallel_execution": true,
"batch_operations": true,
"streaming": true,
"webhooks": true,
"rate_limiting": {
"enabled": true,
"default_limit": 100,
"window": "1m"
}
},
"security": {
"authentication": "api_key",
"encryption": "tls_1_3",
"audit_logging": true,
"pii_masking": true
},
"monitoring": {
"metrics_endpoint": "/metrics",
"health_endpoint": "/health",
"logging_level": "info"
}
}
Complex MCP Workflow Integration
This example combines several tools in one banking operation.
// Complex loan application workflow using multiple MCP tools
async function processLoanApplication(customerId, loanDetails) {
const workflow = await aiClient.createWorkflow({
type: 'loan_application',
mcp_enabled: true,
stages: [
{
name: 'eligibility_check',
tools: [
'get_credit_score',
'verify_income',
'check_debt_ratio',
'analyze_bank_statements'
],
parallel: true,
timeout: 30000
},
{
name: 'risk_assessment',
tools: [
'calculate_risk_score',
'check_fraud_history',
'analyze_collateral',
'market_analysis'
],
ai_decision: {
model: 'risk-assessment-v3',
confidence_required: 0.85
}
},
{
name: 'offer_generation',
tools: [
'calculate_interest_rate',
'generate_loan_terms',
'prepare_documentation'
],
human_review: {
required_if: 'loan_amount > 100000',
department: 'credit_risk'
}
},
{
name: 'approval_process',
tools: [
'final_verification',
'compliance_check',
'generate_contract',
'setup_disbursement'
],
sequential: true
}
],
compensation_strategy: {
enabled: true,
checkpoints: ['eligibility_check', 'risk_assessment'],
rollback_actions: {
'approval_process': ['cancel_contract', 'release_funds_hold']
}
}
});
// Execute workflow with progress monitoring
workflow.on('stage_start', (stage) => {
console.log(`Starting stage: ${stage.name}`);
});
workflow.on('tool_execution', (tool) => {
console.log(`Executing MCP tool: ${tool.name}`);
console.log(`Input parameters:`, tool.parameters);
});
workflow.on('ai_decision', (decision) => {
console.log(`AI Decision: ${decision.outcome}`);
console.log(`Confidence: ${decision.confidence}`);
console.log(`Reasoning:`, decision.explanation);
});
workflow.on('human_review_required', async (review) => {
console.log(`Human review needed: ${review.reason}`);
const decision = await requestHumanReview(review);
workflow.continueWithDecision(decision);
});
try {
const result = await workflow.execute({
customer_id: customerId,
loan_details: loanDetails
});
console.log('Loan application processed successfully');
console.log('Decision:', result.decision);
console.log('Offer:', result.offer);
// Send notification to customer
await notifyCustomer(customerId, result);
return result;
} catch (error) {
console.error('Workflow failed:', error);
// Check if compensation was executed
if (error.compensation_executed) {
console.log('Rollback completed successfully');
}
throw error;
}
}
// Usage
processLoanApplication('cust_456', {
loan_type: 'personal',
amount: 50000,
term_months: 36,
purpose: 'debt_consolidation'
});
Cross-Chain and Decentralised Finance
Cross-Chain Bridge: Quote and Initiate
This example gets a bridge quote from the Wormhole, LayerZero and Axelar adapters and starts the transfer. Integration adapters for third-party APIs; no partnership or endorsement implied.
# Step 1: Ask every bridge adapter for a quote
curl -X POST https://finaegis.org/api/v1/crosschain/bridge/quote \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"from_chain": "ethereum",
"to_chain": "polygon",
"token": "USDC",
"amount": "1000.00"
}'
# Step 2: Start the bridge transfer
curl -X POST https://finaegis.org/api/v1/crosschain/bridge/initiate \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"from_chain": "ethereum",
"to_chain": "polygon",
"token": "USDC",
"amount": "1000.00",
"sender_address": "0x1234...abcd",
"recipient_address": "0x5678...efgh"
}'
// POST /api/v1/crosschain/bridge/quote response
{
"data": {
"quote_id": "quote_br_abc123def456",
"bridge_protocol": "wormhole",
"source_chain": "ethereum",
"destination_chain": "polygon",
"token": "USDC",
"input_amount": "1000.00",
"estimated_receive_amount": "998.50",
"fee_amount": "1.50",
"fee_currency": "USDC",
"exchange_rate": "1.0000",
"estimated_duration_seconds": 180,
"quote_expires_at": "2026-01-15T12:15:00Z",
"alternative_quotes": [
{
"bridge_protocol": "layerzero",
"estimated_receive_amount": "997.80",
"fee_amount": "2.20",
"estimated_duration_seconds": 120
},
{
"bridge_protocol": "axelar",
"estimated_receive_amount": "998.00",
"fee_amount": "2.00",
"estimated_duration_seconds": 240
}
]
}
}
// POST /api/v1/crosschain/bridge/initiate response
{
"data": {
"bridge_tx_id": "btx_xyz789012345",
"quote_id": "quote_br_abc123def456",
"status": "pending",
"source_chain": "ethereum",
"destination_chain": "polygon",
"source_tx_hash": null,
"destination_tx_hash": null,
"sender_address": "0x1234...abcd",
"recipient_address": "0x5678...efgh",
"amount": "1000.00",
"token": "USDC",
"bridge_protocol": "wormhole",
"created_at": "2026-01-15T12:05:30Z",
"estimated_completion_at": "2026-01-15T12:08:30Z"
}
}
Quote and Run a Swap on a Decentralised Exchange
This example compares swap quotes across decentralised exchanges and runs the swap through the best route. The adapters cover Uniswap and Curve. Integration adapters for third-party APIs; no partnership or endorsement implied.
# Step 1: Get the best swap quote across decentralised exchanges
curl -X POST https://finaegis.org/api/v1/defi/swap/quote \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"chain": "ethereum",
"from_token": "WETH",
"to_token": "USDC",
"amount": "2.5",
"slippage": 0.5
}'
# Step 2: Run the swap through the best route
curl -X POST https://finaegis.org/api/v1/defi/swap/execute \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"chain": "ethereum",
"from_token": "WETH",
"to_token": "USDC",
"amount": "2.5",
"wallet_address": "0xABCD...1234",
"slippage": 0.5
}'
// POST /api/v1/defi/swap/quote response
{
"data": {
"quote_id": "quote_sw_def456ghi789",
"chain": "ethereum",
"token_in": "WETH",
"token_out": "USDC",
"amount_in": "2.5",
"estimated_output": "4875.32",
"price_impact_percent": "0.12",
"estimated_gas_usd": "8.45",
"best_route": {
"dex": "uniswap_v3",
"path": ["WETH", "USDC"],
"pools": ["0x8ad5...pool1"],
"fee_tier": "0.05%"
},
"alternative_routes": [
{
"dex": "curve",
"estimated_output": "4870.18",
"price_impact_percent": "0.15"
},
{
"dex": "sushiswap",
"estimated_output": "4865.90",
"price_impact_percent": "0.18"
}
],
"quote_expires_at": "2026-01-15T12:10:00Z"
}
}
// POST /api/v1/defi/swap/execute response
{
"data": {
"swap_id": "swap_mno345pqr678",
"quote_id": "quote_sw_def456ghi789",
"status": "submitted",
"tx_hash": "0x9f8e7d6c5b4a3...transaction_hash",
"chain": "ethereum",
"token_in": "WETH",
"token_out": "USDC",
"amount_in": "2.5",
"expected_output": "4875.32",
"dex": "uniswap_v3",
"gas_price_gwei": "35",
"created_at": "2026-01-15T12:06:00Z"
}
}
Reporting Modules
Travel Rule Check
This example runs the data-exchange check modelled on the Travel Rule of the Financial Action Task Force before a transfer. The check does not by itself make a deployment compliant.
# Check which sender and recipient details a transfer needs
curl -X POST https://finaegis.org/api/regtech/travel-rule/check \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"amount": 15000.00,
"currency": "USD",
"originator": {
"name": "Alice Johnson",
"account_number": "acct_1234567890",
"address": "1 Main Street, Springfield"
},
"beneficiary": {
"name": "Bob Smith",
"account_number": "ext_0987654321"
}
}'
{
"data": {
"check_id": "trc_mno345pqr678",
"transfer_id": "txfr_abc123def456",
"is_compliant": true,
"risk_level": "low",
"applicable_jurisdiction": "EU",
"applicable_regulations": [
"FATF_Recommendation_16",
"EU_Transfer_of_Funds_Regulation",
"MiCA_Article_76"
],
"originator_verified": true,
"beneficiary_verified": true,
"threshold_analysis": {
"amount_usd": "15000.00",
"exceeds_threshold": true,
"threshold_amount": "1000.00",
"full_identification_required": true
},
"sanctions_screening": {
"originator_cleared": true,
"beneficiary_cleared": true,
"screening_provider": "internal",
"screened_at": "2026-01-15T12:00:05Z"
},
"compliance_issues": [],
"recommendations": [
"Enhanced due diligence recommended for transfers above 10000 USD"
],
"checked_at": "2026-01-15T12:00:05Z",
"valid_until": "2026-01-15T12:30:05Z"
}
}
Partner API
Partner Institution Application
This example sends an application from a financial institution that wants to become a partner. An operator reviews each application before the partner gets API credentials.
# Send a partner institution application
curl -X POST https://finaegis.org/api/v2/financial-institutions/apply \
-H "Content-Type: application/json" \
-d '{
"institution_name": "Acme Fintech",
"legal_name": "Acme Fintech Ltd",
"registration_number": "12345678",
"tax_id": "GB123456789",
"country": "GB",
"institution_type": "payment_processor",
"years_in_operation": 4,
"contact_name": "Jane Doe",
"contact_email": "[email protected]",
"contact_phone": "+44 20 0000 0000",
"contact_position": "Head of Partnerships",
"headquarters_address": "1 Example Street",
"headquarters_city": "London",
"headquarters_postal_code": "EC1A 1AA",
"headquarters_country": "GB",
"business_description": "At least 100 characters that describe the business, its customers and how it plans to use the platform ...",
"target_markets": ["GB", "EU"],
"product_offerings": ["accounts", "payments"],
"required_currencies": ["GBP", "EUR"],
"integration_requirements": ["rest_api", "webhooks"],
"has_aml_program": true,
"has_kyc_procedures": true,
"has_data_protection_policy": true,
"is_pci_compliant": false,
"is_gdpr_compliant": true
}'
# Check the application status later
curl https://finaegis.org/api/v2/financial-institutions/application/{applicationNumber}/status
{
"data": {
"partner_id": "partner_acme_abc123",
"organization_name": "Acme Fintech",
"status": "active",
"tier": "growth",
"modules_enabled": [
"accounts",
"transfers",
"compliance",
"crosschain"
],
"api_credentials": {
"api_key": "pk_live_xxxxxxxxxxxxxxxxxxxxxxxx",
"sandbox_key": "pk_test_xxxxxxxxxxxxxxxxxxxxxxxx",
"webhook_secret": "whsec_xxxxxxxxxxxxxxxxxxxxxxxx"
},
"sdk_packages": [
{
"language": "typescript",
"version": "3.0.0",
"package_name": "@finaegis/sdk",
"download_url": "https://finaegis.org/developers/sdks/packages/typescript/zelta-sdk-2.0.0.tgz",
"docs_url": "https://finaegis.org/developers/sdk/typescript"
},
{
"language": "python",
"version": "3.0.0",
"package_name": "finaegis",
"download_url": "https://finaegis.org/developers/sdks/packages/python/zelta-sdk-2.0.0.tar.gz",
"docs_url": "https://finaegis.org/developers/sdk/python"
}
],
"rate_limits": {
"requests_per_minute": 5000,
"burst_limit": 500
},
"sandbox_url": "https://finaegis.org",
"dashboard_url": "https://finaegis.org/acme-fintech",
"created_at": "2026-01-15T12:00:00Z",
"onboarding_checklist": {
"api_key_generated": true,
"webhook_configured": true,
"sdk_generated": true,
"sandbox_tested": false,
"compliance_review": "pending"
}
}
}
AI Transaction Query
Transaction Search in Plain Language
This example asks about transactions in plain language. The AI query endpoint turns the question into transaction filters.
# Ask about transactions in plain language
curl -X POST https://finaegis.org/api/ai/query/transactions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"query": "Show me transfers over 5000 dollars in the last 7 days"
}'
{
"data": {
"query_id": "aiq_stu901vwx234",
"original_query": "Show me all cross-chain transfers over $5000 in the last 7 days that had compliance flags",
"interpreted_query": {
"type": ["cross_chain_transfer"],
"amount_min": 5000,
"currency": "USD",
"date_range": {
"from": "2026-01-08T00:00:00Z",
"to": "2026-01-15T23:59:59Z"
},
"has_compliance_flags": true
},
"interpretation_confidence": 0.96,
"total_results": 3,
"transactions": [
{
"uuid": "tx_cross_001",
"type": "cross_chain_transfer",
"amount": "7500.00",
"currency": "USDC",
"status": "completed",
"source_chain": "ethereum",
"destination_chain": "arbitrum",
"bridge_protocol": "wormhole",
"risk_score": 0.35,
"compliance_flags": ["high_value_transfer"],
"created_at": "2026-01-12T14:30:00Z"
},
{
"uuid": "tx_cross_002",
"type": "cross_chain_transfer",
"amount": "12000.00",
"currency": "USDT",
"status": "completed",
"source_chain": "polygon",
"destination_chain": "ethereum",
"bridge_protocol": "layerzero",
"risk_score": 0.62,
"compliance_flags": ["high_value_transfer", "new_destination"],
"created_at": "2026-01-10T09:15:00Z"
},
{
"uuid": "tx_cross_003",
"type": "cross_chain_transfer",
"amount": "25000.00",
"currency": "USDC",
"status": "pending_review",
"source_chain": "ethereum",
"destination_chain": "bsc",
"bridge_protocol": "axelar",
"risk_score": 0.78,
"compliance_flags": ["high_value_transfer", "jurisdiction_mismatch", "velocity_alert"],
"created_at": "2026-01-09T16:45:00Z"
}
],
"analytics": {
"total_volume": "44500.00",
"avg_amount": "14833.33",
"median_amount": "12000.00",
"flagged_count": 3,
"avg_risk_score": 0.58,
"chains_involved": ["ethereum", "polygon", "arbitrum", "bsc"],
"bridges_used": ["wormhole", "layerzero", "axelar"]
}
}
}
Error Handling
Error Handling with Retries
This example retries a failed request automatically and reports the errors it cannot fix.
class FinAegisWrapper {
constructor(apiKey, options = {}) {
this.client = new FinAegis({
apiKey,
baseURL: options.baseURL || 'https://finaegis.org/api/v2'
});
this.retryOptions = {
maxRetries: options.maxRetries || 3,
backoffMultiplier: options.backoffMultiplier || 2,
initialDelay: options.initialDelay || 1000
};
}
async withRetry(operation, context = '') {
let lastError;
let delay = this.retryOptions.initialDelay;
for (let attempt = 1; attempt <= this.retryOptions.maxRetries + 1; attempt++) {
try {
return await operation();
} catch (error) {
lastError = error;
console.log(`Attempt ${attempt} failed for ${context}:`, error.message);
// Don't retry on client errors (4xx)
if (error.status >= 400 && error.status < 500) {
throw error;
}
// Don't retry on the last attempt
if (attempt > this.retryOptions.maxRetries) {
break;
}
// Wait before retrying
console.log(`Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
delay *= this.retryOptions.backoffMultiplier;
}
}
throw lastError;
}
async createTransfer(transferData) {
return this.withRetry(
() => this.client.transfers.create(transferData),
`transfer creation`
);
}
async getAccountBalance(accountId) {
return this.withRetry(
() => this.client.accounts.getBalances(accountId),
`balance query for ${accountId}`
);
}
async executeWithFallback(primaryOperation, fallbackOperation, context) {
try {
return await this.withRetry(primaryOperation, context);
} catch (primaryError) {
console.log(`Primary operation failed, trying fallback:`, primaryError.message);
try {
return await this.withRetry(fallbackOperation, `${context} (fallback)`);
} catch (fallbackError) {
console.error('Both primary and fallback operations failed');
throw new Error(`All operations failed. Primary: ${primaryError.message}, Fallback: ${fallbackError.message}`);
}
}
}
}
// Usage example
const finAegis = new FinAegisWrapper(process.env.ZELTA_API_KEY, {
environment: 'production',
maxRetries: 3,
backoffMultiplier: 2,
initialDelay: 1000
});
async function robustTransfer(fromAccount, toAccount, amount) {
try {
// Primary: Direct transfer
const primaryTransfer = () => finAegis.createTransfer({
from_account: fromAccount,
to_account: toAccount,
amount: amount,
asset_code: 'USD',
workflow_enabled: true
});
// Fallback: Transfer via intermediate account
const fallbackTransfer = () => finAegis.createTransfer({
from_account: fromAccount,
to_account: toAccount,
amount: amount,
asset_code: 'USD',
workflow_enabled: true,
routing: 'alternative'
});
const result = await finAegis.executeWithFallback(
primaryTransfer,
fallbackTransfer,
'USD transfer'
);
console.log('Transfer successful:', result.uuid);
return result;
} catch (error) {
console.error('Transfer completely failed:', error.message);
// Log for monitoring
await logTransferFailure({
fromAccount,
toAccount,
amount,
error: error.message,
timestamp: new Date().toISOString()
});
throw error;
}
}
Start building
Use these examples as a starting point for your FinAegis integration.