#!/usr/bin/env node
/**
* Complete debug of division ID flow with detailed logging
*/
const { spawn } = require('child_process');
async function debugCompleteFlow() {
console.log('π COMPLETE DIVISION ID FLOW DEBUG\n');
console.log('=====================================\n');
// Add detailed logging to dual-auth
const mcp = spawn('node', ['dist/index.js'], {
env: {
...process.env,
USERNAME: 'david+allcloud@umbrellacost.com',
PASSWORD: 'B4*zcI7#F7poEC',
DEBUG: 'true'
}
});
let requestId = 1;
let fullDebugOutput = [];
mcp.stdout.on('data', (data) => {
const text = data.toString();
const lines = text.split('\n');
for (const line of lines) {
if (line.trim() && line.startsWith('{')) {
try {
const msg = JSON.parse(line);
// Handle initialization
if (msg.id === 0 && msg.result) {
console.log('β
Server initialized\n');
// First authenticate
setTimeout(() => {
const authRequest = {
jsonrpc: '2.0',
id: requestId++,
method: 'tools/call',
params: {
name: 'authenticate_user',
arguments: {
username: 'david+allcloud@umbrellacost.com',
password: 'B4*zcI7#F7poEC'
}
}
};
console.log('π Authenticating...\n');
mcp.stdin.write(JSON.stringify(authRequest) + '\n');
}, 500);
}
// Handle authentication response
if (msg.id === 1 && msg.result) {
console.log('β
Authentication successful\n');
console.log('βββββββββββββββββββββββββββββββββββββ\n');
// Now request Bank Leumi costs - exact same params as Claude Desktop
setTimeout(() => {
const request = {
jsonrpc: '2.0',
id: requestId++,
method: 'tools/call',
params: {
name: 'api___invoices_caui',
arguments: {
userQuery: 'Bank Leumi costs last 3 months',
startDate: '2025-06-01',
endDate: '2025-08-31',
groupBy: 'none',
periodGranLevel: 'month',
isUnblended: true,
costType: ['cost', 'discount'],
excludeFilters: { chargetype: 'Tax' }
}
}
};
console.log('π€ REQUEST: Bank Leumi costs last 3 months\n');
console.log('Arguments:', JSON.stringify(request.params.arguments, null, 2), '\n');
console.log('βββββββββββββββββββββββββββββββββββββ\n');
mcp.stdin.write(JSON.stringify(request) + '\n');
}, 500);
}
// Handle cost response
if (msg.id === 2 && msg.result) {
console.log('π RESPONSE RECEIVED - ANALYZING FLOW\n');
console.log('βββββββββββββββββββββββββββββββββββββ\n');
// Step 1: Customer Detection
console.log('1οΈβ£ CUSTOMER DETECTION\n');
const detectionLines = fullDebugOutput.filter(line =>
line.includes('[CUSTOMER-DETECTION]') ||
line.includes('[MSP-CUSTOMER-DETECTION]')
);
let detectedAccountKey = null;
let detectedDivisionId = null;
detectionLines.forEach(line => {
if (line.includes('Using accountKey') && line.includes('divisionId')) {
const accountMatch = line.match(/accountKey (\d+)/);
const divisionMatch = line.match(/divisionId (\d+)/);
if (accountMatch) detectedAccountKey = accountMatch[1];
if (divisionMatch) detectedDivisionId = divisionMatch[1];
console.log(` β
Detected: accountKey=${accountMatch?.[1]}, divisionId=${divisionMatch?.[1]}`);
} else if (line.includes('Selected first non-multicloud')) {
console.log(` ${line.split(']')[1].trim()}`);
}
});
console.log('');
// Step 2: Server Parameter Setting
console.log('2οΈβ£ SERVER PARAMETER SETTING\n');
const serverLines = fullDebugOutput.filter(line =>
line.includes('customer_account_key:') ||
line.includes('customer_division_id:') ||
line.includes('Detected customer account key')
);
serverLines.forEach(line => {
if (line.includes('Detected customer account key')) {
const accountMatch = line.match(/key: (\d+)/);
const divisionMatch = line.match(/division: (\d+)/);
console.log(` β
Set params: customer_account_key=${accountMatch?.[1]}, customer_division_id=${divisionMatch?.[1]}`);
}
});
console.log('');
// Step 3: API Client Receiving
console.log('3οΈβ£ API CLIENT RECEIVING\n');
const apiClientLines = fullDebugOutput.filter(line =>
line.includes('[API-CLIENT]') &&
(line.includes('customer') || line.includes('division'))
);
let apiClientAccountKey = null;
let apiClientDivisionId = null;
apiClientLines.forEach(line => {
if (line.includes('Using customer-specific API key')) {
const accountMatch = line.match(/account (\d+)/);
if (accountMatch) apiClientAccountKey = accountMatch[1];
console.log(` Received customer_account_key: ${accountMatch?.[1]}`);
}
});
// Check if division ID was logged
const divisionIdReceived = fullDebugOutput.some(line =>
line.includes('customerDivisionId=') && !line.includes('undefined')
);
if (!divisionIdReceived) {
console.log(' β οΈ Division ID may not be reaching API client');
}
console.log('');
// Step 4: Dual Auth Building API Key
console.log('4οΈβ£ DUAL AUTH API KEY BUILDING\n');
const authLines = fullDebugOutput.filter(line =>
line.includes('[DUAL-AUTH]')
);
let finalApiKey = null;
let usedDivisionId = null;
authLines.forEach(line => {
if (line.includes('Building API key for customer account')) {
const accountMatch = line.match(/account: (\d+)/);
console.log(` Building for account: ${accountMatch?.[1]}`);
} else if (line.includes('Using division') && line.includes('from customer detection')) {
const divMatch = line.match(/division (\d+)/);
usedDivisionId = divMatch?.[1];
console.log(` β
Using division ${divMatch?.[1]} from customer detection`);
} else if (line.includes('No division ID provided')) {
console.log(` β οΈ ${line.split(']')[1].trim()}`);
} else if (line.includes('Final API key') || line.includes('Built customer API key')) {
const keyMatch = line.match(/([a-f0-9-]{36}:\d+:\d+)/);
if (keyMatch) {
finalApiKey = keyMatch[1];
const parts = keyMatch[1].split(':');
console.log(` π Final API key parts:`);
console.log(` Account Key: ${parts[1]}`);
console.log(` Division ID: ${parts[2]} ${parts[2] === '139' ? 'β
' : 'β WRONG!'}`);
}
}
});
console.log('');
// Step 5: API Request
console.log('5οΈβ£ API REQUEST\n');
const requestLines = fullDebugOutput.filter(line =>
line.includes('API REQUEST') ||
line.includes('apikey:')
);
requestLines.forEach(line => {
if (line.includes('Customer Account:')) {
console.log(` ${line.trim()}`);
}
});
if (finalApiKey) {
const parts = finalApiKey.split(':');
console.log(` API Key Used: ...${parts[0].slice(-8)}:${parts[1]}:${parts[2]}`);
}
console.log('');
// Step 6: Response Analysis
console.log('6οΈβ£ RESPONSE ANALYSIS\n');
if (msg.result.content && msg.result.content[0]) {
const content = msg.result.content[0];
try {
const text = content.text || '';
if (text.includes('```json')) {
const jsonMatch = text.match(/```json\s*([\s\S]*?)\s*```/);
if (jsonMatch) {
const jsonData = JSON.parse(jsonMatch[1]);
console.log(` Records returned: ${jsonData.length}`);
if (jsonData.length > 0) {
const total = jsonData.reduce((sum, row) => sum + (row.total_cost || 0), 0);
console.log(` Total cost: $${total.toFixed(2)}`);
if (total > 100000) {
console.log(' β WRONG DATA: Got BL Test Env (division 1) instead of Reseller-1 (division 139)');
} else if (total < 1) {
console.log(' β
CORRECT DATA: Got Reseller-1 (division 139) data');
} else {
console.log(' π€ Unexpected cost range');
}
}
}
}
} catch (e) {
console.log(' Could not parse response');
}
}
console.log('');
// Summary
console.log('βββββββββββββββββββββββββββββββββββββ\n');
console.log('π SUMMARY\n');
console.log(` Expected Division: 139 (Reseller-1)`);
console.log(` Detected Division: ${detectedDivisionId || 'NOT DETECTED'}`);
console.log(` Division Used in API Key: ${usedDivisionId || finalApiKey?.split(':')[2] || 'UNKNOWN'}`);
if (usedDivisionId === '139' || finalApiKey?.split(':')[2] === '139') {
console.log(` Result: β
Division ID correctly propagated`);
} else {
console.log(` Result: β Division ID lost or defaulted`);
console.log(`\n ISSUE: Division ID ${detectedDivisionId} detected but ${usedDivisionId || finalApiKey?.split(':')[2] || '0'} used`);
}
console.log('\nπ Analysis complete\n');
setTimeout(() => {
mcp.kill();
process.exit(0);
}, 1000);
}
} catch (e) {
// Not JSON
}
}
}
});
mcp.stderr.on('data', (data) => {
const text = data.toString();
fullDebugOutput.push(...text.split('\n'));
});
// Initialize
setTimeout(() => {
const init = {
jsonrpc: '2.0',
id: 0,
method: 'initialize',
params: {
protocolVersion: '1.0.0',
capabilities: {},
clientInfo: {
name: 'complete-flow-debug',
version: '1.0.0'
}
}
};
console.log('π€ Initializing MCP server...\n');
mcp.stdin.write(JSON.stringify(init) + '\n');
}, 1000);
// Timeout
setTimeout(() => {
console.log('\nβ±οΈ Timeout');
mcp.kill();
process.exit(1);
}, 15000);
}
debugCompleteFlow().catch(console.error);