#!/usr/bin/env node
/**
* Debug division ID flow from detection to API key construction
*/
const { spawn } = require('child_process');
async function debugDivisionFlow() {
console.log('π DEBUGGING DIVISION ID FLOW\n');
console.log('=====================================\n');
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 debugOutput = [];
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');
// Now request Bank Leumi costs - simulating Claude Desktop request
setTimeout(() => {
const request = {
jsonrpc: '2.0',
id: requestId++,
method: 'tools/call',
params: {
name: 'api___invoices_caui',
arguments: {
userQuery: 'Bank Leumi costs for September 2025',
startDate: '2025-09-01',
endDate: '2025-09-30',
groupBy: 'none',
periodGranLevel: 'month',
isUnblended: true,
costType: ['cost', 'discount'],
excludeFilters: { chargetype: 'Tax' }
}
}
};
console.log('π€ Requesting: Bank Leumi costs (should use Division 139)\n');
console.log('Request arguments:', JSON.stringify(request.params.arguments, null, 2), '\n');
mcp.stdin.write(JSON.stringify(request) + '\n');
}, 500);
}
// Handle cost response
if (msg.id === 2 && msg.result) {
console.log('π RESPONSE RECEIVED\n');
console.log('βββββββββββββββββββββββββββββββββββββ\n');
// Analyze debug output
console.log('π DIVISION ID FLOW ANALYSIS:\n');
// Check customer detection
const detectionLines = debugOutput.filter(line =>
line.includes('[CUSTOMER-DETECTION]') ||
line.includes('[MSP-CUSTOMER-DETECTION]')
);
if (detectionLines.length > 0) {
console.log('1οΈβ£ Customer Detection:');
detectionLines.forEach(line => {
if (line.includes('Setting customer_division_id')) {
console.log(' β
' + line.split(']')[1].trim());
} else if (line.includes('Using accountKey')) {
console.log(' ' + line.split(']')[1].trim());
}
});
console.log('');
}
// Check parameter validation
const paramLines = debugOutput.filter(line =>
line.includes('customer_division_id') &&
!line.includes('[CUSTOMER-DETECTION]')
);
if (paramLines.length > 0) {
console.log('2οΈβ£ Parameter Passing:');
paramLines.forEach(line => {
console.log(' ' + line);
});
console.log('');
}
// Check dual-auth
const authLines = debugOutput.filter(line =>
line.includes('[DUAL-AUTH]')
);
if (authLines.length > 0) {
console.log('3οΈβ£ Dual Auth (API Key Building):');
authLines.forEach(line => {
const content = line.split('[DUAL-AUTH]')[1]?.trim();
if (content) {
if (content.includes('Using division')) {
console.log(' π ' + content);
} else if (content.includes('No division ID')) {
console.log(' β οΈ ' + content);
} else if (content.includes('Final API key')) {
console.log(' π ' + content);
}
}
});
console.log('');
}
// Check the actual API key used
const apiKeyLines = debugOutput.filter(line =>
line.includes('apikey:') ||
line.includes('API key:') ||
line.includes('Using API key')
);
if (apiKeyLines.length > 0) {
console.log('4οΈβ£ Final API Key:');
apiKeyLines.forEach(line => {
// Extract API key pattern
const keyMatch = line.match(/[a-f0-9-]{36}:\d+:\d+/);
if (keyMatch) {
const parts = keyMatch[0].split(':');
console.log(` User Key: ...${parts[0].slice(-8)}`);
console.log(` Account Key: ${parts[1]}`);
console.log(` Division ID: ${parts[2]} ${parts[2] === '139' ? 'β
CORRECT' : 'β WRONG (should be 139)'}`);
}
});
console.log('');
}
// Check response data
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('5οΈβ£ Response Data:');
console.log(` Records: ${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 > 1000) {
console.log(' β ERROR: Wrong division data (costs > $1000)');
console.log(' This is getting data from division 1 (BL Test Env) instead of 139 (Reseller-1)');
} else if (total < 1) {
console.log(' β
CORRECT: Using division 139 (Reseller-1) data');
}
}
}
}
} catch (e) {
console.log('Could not parse response');
}
}
console.log('\nβββββββββββββββββββββββββββββββββββββ\n');
console.log('π Analysis complete\n');
setTimeout(() => {
mcp.kill();
process.exit(0);
}, 1000);
}
} catch (e) {
// Not JSON
}
}
}
});
mcp.stderr.on('data', (data) => {
const text = data.toString();
debugOutput.push(...text.split('\n'));
// Show important debug lines in real-time
const lines = text.split('\n');
for (const line of lines) {
if (line.includes('Setting customer_division_id') ||
line.includes('Using division') ||
line.includes('No division ID') ||
line.includes('Final API key')) {
console.log(' π', line);
}
}
});
// Initialize
setTimeout(() => {
const init = {
jsonrpc: '2.0',
id: 0,
method: 'initialize',
params: {
protocolVersion: '1.0.0',
capabilities: {},
clientInfo: {
name: 'division-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);
}
debugDivisionFlow().catch(console.error);