#!/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
});
// New MCP server URL with the fix
const MCP_BASE = 'https://accommodations-liverpool-louise-blair.trycloudflare.com';
async function testMcpWithFix() {
console.log('\n════════════════════════════════════════════════════════════');
console.log(' TESTING BANK LEUMI THROUGH MCP PROTOCOL (WITH FIX)');
console.log('════════════════════════════════════════════════════════════\n');
try {
// Step 1: Get OAuth metadata
console.log('1️⃣ Getting OAuth metadata...');
const metadataResponse = await axiosInstance.get(`${MCP_BASE}/.well-known/oauth-authorization-server`);
console.log('✅ Got OAuth metadata');
// Step 2: Register client
console.log('\n2️⃣ Registering OAuth client...');
const registerResponse = await axiosInstance.post(`${MCP_BASE}/register`, {
client_name: "Test Client",
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;
console.log(`✅ Registered client: ${clientId}`);
// Step 3: Simulate login (direct POST to avoid browser)
console.log('\n3️⃣ Authenticating as david+allcloud@umbrellacost.com...');
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
}
);
// Extract session cookie
const cookies = loginResponse.headers['set-cookie'];
const sidCookie = cookies?.find(c => c.startsWith('sid='));
const sid = sidCookie?.split(';')[0].split('=')[1];
console.log(`✅ Logged in, session: ${sid}`);
// Step 4: Get authorization code
console.log('\n4️⃣ Getting authorization code...');
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}`
}
});
// Parse the authorization page to find the code
const codeMatch = authResponse.data.match(/code=([^&"]+)/);
const authCode = codeMatch ? codeMatch[1] : null;
console.log(`✅ Got authorization code: ${authCode?.substring(0, 20)}...`);
// Step 5: Exchange code for token
console.log('\n5️⃣ Exchanging code for access token...');
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(`✅ Got access token: ${accessToken.substring(0, 50)}...`);
// Step 6: Initialize MCP session
console.log('\n6️⃣ Initializing MCP session...');
const initResponse = await axiosInstance.post(`${MCP_BASE}/mcp`, {
method: "initialize",
params: {
protocolVersion: "2025-06-18",
capabilities: {},
clientInfo: {
name: "test-client",
version: "1.0.0"
}
},
jsonrpc: "2.0",
id: 0
}, {
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream'
}
});
if (initResponse.data && initResponse.data.result) {
console.log(`✅ MCP initialized: ${JSON.stringify(initResponse.data.result.protocolVersion)}`);
} else {
console.log(`⚠️ MCP initialized but response format unexpected: ${JSON.stringify(initResponse.data)}`);
}
// Step 7: Test Bank Leumi query
console.log('\n7️⃣ Testing Bank Leumi query through MCP...');
console.log('════════════════════════════════════════════════════════════');
const bankLeumiRequest = {
method: "tools/call",
params: {
name: "api__invoices_caui",
arguments: {
accountId: "696314371547",
customer_account_key: "22676",
customer_division_id: "139",
startDate: "2025-08-01",
endDate: "2025-08-31",
periodGranLevel: "month",
groupBy: "none",
costType: "[\"cost\", \"discount\"]",
isUnblended: "true",
userQuery: "Show me Bank Leumi costs for August 2025"
}
},
jsonrpc: "2.0",
id: 1
};
console.log('📤 Request parameters:');
console.log(` accountId: ${bankLeumiRequest.params.arguments.accountId}`);
console.log(` customer_account_key: ${bankLeumiRequest.params.arguments.customer_account_key}`);
console.log(` customer_division_id: ${bankLeumiRequest.params.arguments.customer_division_id}`);
console.log(` Date range: Aug 2025`);
const startTime = Date.now();
const mcpResponse = await axiosInstance.post(`${MCP_BASE}/mcp`, bankLeumiRequest, {
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream'
}
});
const responseTime = Date.now() - startTime;
console.log(`\n📥 Response received in ${responseTime}ms`);
// Parse the response
if (mcpResponse.data.result?.content?.[0]?.text) {
const responseText = mcpResponse.data.result.content[0].text;
console.log('\n📊 MCP Response:');
console.log('════════════════════════════════════════════════════════════');
// Extract account and cost information from the response
const accountMatch = responseText.match(/account_id["\s:]+(\d+)/);
const costMatch = responseText.match(/total_cost["\s:]+([0-9.]+)/);
if (accountMatch) {
const returnedAccount = accountMatch[1];
console.log(` Account returned: ${returnedAccount}`);
if (returnedAccount === '696314371547') {
console.log(' ✅ CORRECT! This is the Bank Leumi account!');
} else if (returnedAccount === '268413799883') {
console.log(' ❌ WRONG! This is Mark.Watson_Sandbox account!');
console.log(' 🔴 THE FIX DIDN\'T WORK - Still getting wrong account');
} else {
console.log(` ⚠️ Unknown account: ${returnedAccount}`);
}
}
if (costMatch) {
const cost = parseFloat(costMatch[1]);
console.log(` Total cost: $${cost}`);
if (Math.abs(cost - 0.002684) < 0.001) {
console.log(' ✅ Cost matches expected Bank Leumi value');
} else if (cost > 20) {
console.log(' ❌ Cost is too high - this is Mark.Watson_Sandbox data');
}
}
// Show first 500 chars of response for debugging
console.log('\n📝 Raw response preview:');
console.log(responseText.substring(0, 500));
} else {
console.log('⚠️ Unexpected response format:', JSON.stringify(mcpResponse.data, null, 2));
}
console.log('\n════════════════════════════════════════════════════════════');
console.log(' TEST COMPLETE');
console.log('════════════════════════════════════════════════════════════');
} 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));
}
}
}
testMcpWithFix().catch(console.error);