import express from 'express';
import { mcpClient } from '../mcpClient';
import { interpretNaturalLanguage, summarizeResultsWithClaude } from '../utils/interpret';
const router = express.Router();
router.post('/nlp-search', async (req, res) => {
try {
const { query } = req.body;
// Check if MCP client is ready
if (!mcpClient.isReady()) {
return res.status(503).json({ error: 'MCP server not ready' });
}
console.log('User query:', query);
// Check if query is a single word (likely a Pokemon name)
const words = query.trim().split(/\s+/);
let intent;
console.log(words.length);
if (words.length === 1) {
// Single word query - assume it's a Pokemon name search
intent = {
searchQuery: query.trim(),
indexName: 'pokemon',
includeBattleAnalysis: true // Added flag for battle analysis
};
} else {
// Multi-word query - use natural language interpretation
intent = await interpretNaturalLanguage(query);
}
console.log('Search intent:', JSON.stringify(intent, null, 2));
// Step 2: Use MCP server to search indices
let allResults: any[] = [];
if (intent.indexName) {
const searchResult = await mcpClient.searchIndex({
indexName: intent.indexName,
query: intent.searchQuery || '',
filters: intent.filters,
hitsPerPage: 10
});
allResults = searchResult.results;
}
else {
// Search multiple Pokemon-related indices
const indices = ['pokemon',
'pokemon_moves',
'abilities',
'items',
'competitive_stats',
'team_synergies',
'team_compositions',
'meta_analysis',
'type_effectiveness'
];
for (const indexName of indices) {
try {
const searchResult = await mcpClient.searchIndex({
indexName,
query: intent.searchQuery || '',
filters: intent.filters,
hitsPerPage: 10
});
allResults.push(...searchResult.results);
} catch (indexError) {
console.warn(`Failed to search index ${indexName}:`, indexError);
// Continue with other indices even if one fails
}
}
}
// console.log("Algolia results: ", allResults);
// Step 3: For single Pokemon searches, return data for battle analysis
// For multi-word searches, use Claude to summarize
let summary = '';
if (words.length === 1 && intent.indexName === 'pokemon') {
// Single Pokemon search - frontend will handle battle analysis
res.json({
summary: '',
results: allResults,
isSinglePokemon: true,
includeBattleAnalysis: true
});
return;
}
// Multi-word queries get AI summarization
summary = await summarizeResultsWithClaude(query, allResults);
console.log('Results Summary:', JSON.stringify(summary, null, 2));
res.json({
summary,
results: allResults,
isSinglePokemon: false
});
} catch (err: any) {
console.error('MCP AI search error:', err);
res.status(500).json({ error: err.message });
}
});
// New endpoint to list all available indices
router.get('/indices', async (_req, res) => {
try {
if (!mcpClient.isReady()) {
return res.status(503).json({ error: 'MCP server not ready' });
}
const result = await mcpClient.listIndices();
// Parse the result from MCP server
if (result.content && Array.isArray(result.content) && result.content[0] && 'text' in result.content[0]) {
const indices = JSON.parse(result.content[0].text);
res.json({ indices });
} else {
res.json({ indices: [] });
}
} catch (error: any) {
console.error('Error listing indices:', error);
res.status(500).json({ error: error.message });
}
});
// Test endpoint to debug MCP connection and list indices
router.get('/test-mcp', async (_req, res) => {
try {
if (!mcpClient.isReady()) {
return res.status(503).json({ error: 'MCP server not ready' });
}
console.log('Testing MCP connection...');
console.log('Environment variables:');
console.log('ALGOLIA_APP_ID:', process.env.ALGOLIA_APP_ID ? `${process.env.ALGOLIA_APP_ID.substring(0, 4)}...` : 'NOT SET');
console.log('ALGOLIA_API_KEY:', process.env.ALGOLIA_API_KEY ? `${process.env.ALGOLIA_API_KEY.substring(0, 8)}...` : 'NOT SET');
// Try to list indices
const result = await mcpClient.listIndices();
console.log('List indices result:', result);
res.json({
status: 'MCP connection working',
result: result,
debug: {
appId: process.env.ALGOLIA_APP_ID ? `${process.env.ALGOLIA_APP_ID.substring(0, 4)}...` : 'NOT SET',
apiKeySet: !!process.env.ALGOLIA_API_KEY
}
});
} catch (error: any) {
console.error('MCP test error:', error);
res.status(500).json({
error: error.message,
details: error.toString()
});
}
});
export default router;