#!/usr/bin/env node
const axios = require('axios');
const https = require('https');
const crypto = require('crypto');
const axiosInstance = axios.create({
httpsAgent: new https.Agent({ rejectUnauthorized: false }),
timeout: 30000
});
const MCP_BASE = 'https://ing-analyzed-offerings-owen.trycloudflare.com';
async function testOAuthFix() {
console.log('\n════════════════════════════════════════════════════════════');
console.log(' 🔧 VERIFYING OAUTH FIX FOR BANK LEUMI');
console.log('════════════════════════════════════════════════════════════\n');
try {
// Step 1: OAuth Authentication
console.log('1️⃣ OAuth Authentication Flow...');
const metadataResponse = await axiosInstance.get(`${MCP_BASE}/.well-known/oauth-authorization-server`);
const registerResponse = await axiosInstance.post(`${MCP_BASE}/register`, {
client_name: "Claude Desktop",
grant_types: ["authorization_code", "refresh_token"],
response_types: ["code"],
token_endpoint_auth_method: "client_secret_post",
scope: "claudeai",
redirect_uris: ["https://claude.ai/api/mcp/auth_callback"]
});
const clientId = registerResponse.data.client_id;
const loginResponse = await axiosInstance.post(`${MCP_BASE}/login`,
'username=david%2Ballcloud%40umbrellacost.com&password=Dsamsung1%21123&state=test&client_id=' + clientId,
{
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
maxRedirects: 0,
validateStatus: (status) => status === 302
}
);
const cookies = loginResponse.headers['set-cookie'];
const sidCookie = cookies?.find(c => c.startsWith('sid='));
const sid = sidCookie?.split(';')[0].split('=')[1];
const codeVerifier = crypto.randomBytes(32).toString('base64url');
const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url');
const authResponse = await axiosInstance.get(`${MCP_BASE}/authorize`, {
params: {
response_type: 'code',
client_id: clientId,
redirect_uri: 'https://claude.ai/api/mcp/auth_callback',
state: 'test-state',
code_challenge: codeChallenge,
code_challenge_method: 'S256'
},
headers: { 'Cookie': `sid=${sid}` }
});
const codeMatch = authResponse.data.match(/code=([^&\"]+)/);
const authCode = codeMatch ? codeMatch[1] : null;
const tokenResponse = await axiosInstance.post(`${MCP_BASE}/oauth/token`,
new URLSearchParams({
grant_type: 'authorization_code',
code: authCode,
redirect_uri: 'https://claude.ai/api/mcp/auth_callback',
client_id: clientId,
code_verifier: codeVerifier
}).toString(),
{
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}
);
const accessToken = tokenResponse.data.access_token;
console.log('✅ OAuth authentication successful\n');
// Step 2: Initialize MCP Session
console.log('2️⃣ Initializing MCP session...');
await axiosInstance.post(`${MCP_BASE}/mcp`, {
method: "initialize",
params: {
protocolVersion: "2025-06-18",
capabilities: {},
clientInfo: { name: "claude-desktop", version: "1.0.0" }
},
jsonrpc: "2.0",
id: 0
}, {
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream'
}
});
console.log('✅ MCP session initialized\n');
// Test 1: WITH both customer_account_key AND customer_division_id
console.log('3️⃣ TEST 1: With BOTH customer_account_key AND customer_division_id');
console.log('─────────────────────────────────────────────────────');
const test1Request = {
method: "tools/call",
params: {
name: "api__invoices_caui",
arguments: {
customer_account_key: "22676", // Bank Leumi account key
customer_division_id: "139", // Bank Leumi division ID - CRITICAL!
startDate: "2025-08-01",
endDate: "2025-08-31",
periodGranLevel: "month",
groupBy: "none",
costType: "[\"cost\", \"discount\"]",
isUnblended: "true",
userQuery: "Bank Leumi August costs"
}
},
jsonrpc: "2.0",
id: 1
};
console.log('📤 Request WITH customer_account_key=22676 AND customer_division_id=139...');
const response1 = await axiosInstance.post(`${MCP_BASE}/mcp`, test1Request, {
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream'
}
});
let result1;
if (typeof response1.data === 'string' && response1.data.includes('event: message')) {
const dataMatch = response1.data.match(/data: ({.*})/);
if (dataMatch) result1 = JSON.parse(dataMatch[1]);
} else {
result1 = response1.data;
}
if (result1?.result?.content?.[0]?.text) {
const content = result1.result.content[0].text;
const costMatch = content.match(/\"total_cost\":\s*([0-9.]+)/);
const accountMatch = content.match(/\"account_id\":\s*\"(\d+)\"/);
if (costMatch && accountMatch) {
const cost = parseFloat(costMatch[1]);
const accountId = accountMatch[1];
console.log(` Account ID: ${accountId}`);
console.log(` Total Cost: $${cost.toFixed(10)}`);
console.log(` Expected: $0.0026837670`);
console.log(` Status: ${Math.abs(cost - 0.0026837670) < 0.0001 ? '✅ CORRECT' : '❌ WRONG'}\n`);
}
}
// Test 2: WITH only customer_account_key (no division)
console.log('4️⃣ TEST 2: With ONLY customer_account_key (no division)');
console.log('─────────────────────────────────────────────────────');
const test2Request = {
method: "tools/call",
params: {
name: "api__invoices_caui",
arguments: {
customer_account_key: "22676", // Only account key, no division
startDate: "2025-08-01",
endDate: "2025-08-31",
periodGranLevel: "month",
groupBy: "none",
costType: "[\"cost\", \"discount\"]",
isUnblended: "true",
userQuery: "Bank Leumi Reseller-1 August costs" // Query should help detect division
}
},
jsonrpc: "2.0",
id: 2
};
console.log('📤 Request WITH ONLY customer_account_key=22676 (should auto-detect division)...');
const response2 = await axiosInstance.post(`${MCP_BASE}/mcp`, test2Request, {
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream'
}
});
let result2;
if (typeof response2.data === 'string' && response2.data.includes('event: message')) {
const dataMatch = response2.data.match(/data: ({.*})/);
if (dataMatch) result2 = JSON.parse(dataMatch[1]);
} else {
result2 = response2.data;
}
if (result2?.result?.content?.[0]?.text) {
const content = result2.result.content[0].text;
const costMatch = content.match(/\"total_cost\":\s*([0-9.]+)/);
const accountMatch = content.match(/\"account_id\":\s*\"(\d+)\"/);
if (costMatch && accountMatch) {
const cost = parseFloat(costMatch[1]);
const accountId = accountMatch[1];
console.log(` Account ID: ${accountId}`);
console.log(` Total Cost: $${cost.toFixed(10)}`);
console.log(` Status: ${accountId === '696314371547' ? '✅ Correct account' : '❌ Wrong account (expected 696314371547)'}`);
if (accountId !== '696314371547') {
console.log(` ⚠️ AUTO-DETECTION ISSUE: Division not detected, probably using default 0`);
}
}
}
// Test 3: WITHOUT customer_account_key (query-based detection)
console.log('\n5️⃣ TEST 3: Without customer_account_key (query-based detection)');
console.log('─────────────────────────────────────────────────────');
const test3Request = {
method: "tools/call",
params: {
name: "api__invoices_caui",
arguments: {
// No customer_account_key or division
startDate: "2025-08-01",
endDate: "2025-08-31",
periodGranLevel: "month",
groupBy: "none",
costType: "[\"cost\", \"discount\"]",
isUnblended: "true",
userQuery: "Bank Leumi August costs" // Query should trigger detection
}
},
jsonrpc: "2.0",
id: 3
};
console.log('📤 Request WITHOUT customer params (should detect from query)...');
const response3 = await axiosInstance.post(`${MCP_BASE}/mcp`, test3Request, {
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream'
}
});
let result3;
if (typeof response3.data === 'string' && response3.data.includes('event: message')) {
const dataMatch = response3.data.match(/data: ({.*})/);
if (dataMatch) result3 = JSON.parse(dataMatch[1]);
} else {
result3 = response3.data;
}
if (result3?.result?.content?.[0]?.text) {
const content = result3.result.content[0].text;
const costMatch = content.match(/\"total_cost\":\s*([0-9.]+)/);
const accountMatch = content.match(/\"account_id\":\s*\"(\d+)\"/);
if (costMatch && accountMatch) {
const cost = parseFloat(costMatch[1]);
const accountId = accountMatch[1];
console.log(` Account ID: ${accountId}`);
console.log(` Total Cost: $${cost.toFixed(10)}`);
console.log(` Status: ${accountId === '696314371547' ? '✅ Query detection worked!' : '❌ Wrong account'}\n`);
}
}
console.log('════════════════════════════════════════════════════════════');
console.log('📊 OAUTH FIX VERIFICATION SUMMARY');
console.log('════════════════════════════════════════════════════════════');
console.log('✅ OAuth authentication works');
console.log('✅ MCP session initialization works');
console.log('🔍 Test 1: With both params - check results above');
console.log('🔍 Test 2: With only account key - check results above');
console.log('🔍 Test 3: Query-based detection - check results above');
console.log('\n🎯 The fix should ensure accounts are fetched before API calls!\n');
} catch (error) {
console.error('\n❌ Error:', error.message);
if (error.response) {
console.error('Status:', error.response.status);
console.error('Response:', JSON.stringify(error.response.data, null, 2));
}
}
}
testOAuthFix().catch(console.error);