refactor(api): migrate MCP listing from DeepNLP to PulseMCP service

- Updated imports to use PulseMCPSearchParams and PulseMCPService instead of DeepNLP equivalents
- Replaced DeepNLP API calls with PulseMCP API endpoints and parameters
- Modified cached MCP transformation to manual mapping for PulseMCP data format
- Enhanced error handling and retry logic in server tools retrieval
- Added PulseMCP API base URL constant for centralized configuration

This change switches the underlying MCP provider from DeepNLP to PulseMCP, ensuring compatibility with the new API while maintaining existing functionality for MCP listing and tool retrieval.
This commit is contained in:
Evandro Fonseca Junior committed 2025-10-28 20:19:00 -03:00
1 parent ce010d39ee
commit 1042f2136b
15 files changed
+1237 -398

No files matched your search

+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env tsx
import { MCPSyncService } from "../lib/services/mcp-sync";
import { MCPCacheRepository } from "../database/repositories/mcp-cache";
import { PulseMCPService } from "../lib/services/pulsemcp";
async function forcePulseMCPSync() {
console.log("🔄 Forçando sincronização completa com PulseMCP...");
try {
// 1. Verificar se PulseMCP API está funcionando
console.log("🔍 Verificando conectividade com PulseMCP API...");
const isHealthy = await PulseMCPService.checkHealth();
if (!isHealthy) {
console.error("❌ PulseMCP API não está acessível");
return;
}
console.log("✅ PulseMCP API está funcionando");
// 2. Limpar cache antigo completamente
console.log("🗑️ Limpando cache antigo do DeepNLP...");
MCPCacheRepository.clearCache();
console.log("✅ Cache antigo limpo");
// 3. Forçar sincronização completa
console.log("📥 Iniciando download completo de servidores PulseMCP...");
const result = await MCPSyncService.syncAll((progress) => {
const percentage =
progress.total > 0
? Math.round((progress.current / progress.total) * 100)
: 0;
console.log(
`📊 Progresso: ${progress.current}/${progress.total} (${percentage}%) - Página ${progress.page}/${progress.totalPages}`
);
});
if (result.success) {
console.log(`✅ Sincronização concluída com sucesso!`);
console.log(`📊 Total de servidores baixados: ${result.totalDownloaded}`);
console.log(`⏱️ Tempo total: ${Math.round(result.duration / 1000)}s`);
// 4. Verificar estatísticas do cache
const stats = MCPCacheRepository.getStats();
console.log(`📈 Estatísticas do cache:`);
console.log(` - Total de itens: ${stats.totalItems}`);
console.log(
` - Última sincronização: ${
stats.lastSync ? new Date(stats.lastSync).toLocaleString() : "Nunca"
}`
);
console.log(` - Cache válido: ${stats.isValid ? "Sim" : "Não"}`);
// 5. Testar busca de alguns servidores
console.log("🔍 Testando busca de servidores...");
const sampleServers = MCPCacheRepository.search({ limit: 5 });
console.log(
`📋 Encontrados ${sampleServers.length} servidores no cache:`
);
sampleServers.forEach((server, index) => {
console.log(
` ${index + 1}. ${server.content_name} (${server.category})`
);
});
} else {
console.error("❌ Sincronização falhou:");
result.errors.forEach((error) => console.error(` - ${error}`));
}
} catch (error) {
console.error("❌ Erro durante sincronização:", error);
}
}
// Executar se chamado diretamente
if (require.main === module) {
forcePulseMCPSync()
.then(() => {
console.log("🎉 Script concluído");
process.exit(0);
})
.catch((error) => {
console.error("💥 Erro fatal:", error);
process.exit(1);
});
}
export { forcePulseMCPSync };
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env tsx
async function testPulseMCPDirect() {
console.log("🔍 Testando PulseMCP API diretamente...");
try {
const url =
"https://api.pulsemcp.com/v0beta/servers?count_per_page=5&offset=0";
console.log(`📡 Fazendo requisição para: ${url}`);
const response = await fetch(url, {
method: "GET",
headers: {
Accept: "application/json",
"User-Agent": "Ollahub-MCP-Client/1.0 (https://ollahub.com)",
"Content-Type": "application/json",
},
});
console.log(`📊 Status: ${response.status} ${response.statusText}`);
console.log(`📋 Headers:`, Object.fromEntries(response.headers.entries()));
if (!response.ok) {
const errorText = await response.text();
console.error(`❌ Erro ${response.status}:`, errorText);
return;
}
const data = await response.json();
console.log(`✅ Sucesso! Total de servidores: ${data.total_count}`);
console.log(`📋 Primeiros 3 servidores:`);
data.servers.slice(0, 3).forEach((server: any, index: number) => {
console.log(` ${index + 1}. ${server.name}`);
console.log(` - Package: ${server.package_name || "N/A"}`);
console.log(` - Registry: ${server.package_registry || "N/A"}`);
console.log(` - Stars: ${server.github_stars || 0}`);
});
} catch (error) {
console.error("❌ Erro na requisição:", error);
}
}
testPulseMCPDirect()
.then(() => {
console.log("🎉 Teste concluído");
process.exit(0);
})
.catch((error) => {
console.error("💥 Erro fatal:", error);
process.exit(1);
});
+87
View File
@@ -0,0 +1,87 @@
import { MCPCacheRepository } from "../database/repositories/mcp-cache";
import { MCPSyncService } from "../lib/services/mcp-sync";
import { PulseMCPService } from "../lib/services/pulsemcp";
async function testSimpleSync() {
console.log("🔄 Testando sincronização simples com PulseMCP...");
try {
// 1. Verificar se PulseMCP API está funcionando
console.log("🔍 Verificando conectividade com PulseMCP API...");
const isHealthy = await PulseMCPService.checkHealth();
if (!isHealthy) {
console.error("❌ PulseMCP API não está acessível");
return;
}
console.log("✅ PulseMCP API está funcionando");
// 2. Limpar cache antigo
console.log("🗑️ Limpando cache antigo...");
MCPCacheRepository.clearCache();
console.log("✅ Cache antigo limpo");
// 3. Testar chamada direta à API
console.log("📡 Testando chamada direta à API PulseMCP...");
const response = await PulseMCPService.getAllServers();
console.log(
`✅ API retornou ${response.servers.length} servidores (total: ${response.total_count})`
);
// 4. Salvar alguns servidores no banco para teste
console.log("💾 Salvando primeiros 10 servidores no banco...");
const testBatch = response.servers.slice(0, 10);
MCPCacheRepository.saveBatch(testBatch);
console.log("✅ Servidores salvos no banco");
// 5. Verificar se foram salvos corretamente
console.log("🔍 Verificando dados salvos...");
const savedServers = MCPCacheRepository.search({ limit: 10 });
console.log(`📋 Encontrados ${savedServers.length} servidores no banco:`);
savedServers.forEach((server, index) => {
console.log(
` ${index + 1}. ${server.content_name} (${server.category})`
);
});
// 6. Testar sincronização completa
console.log("🚀 Iniciando sincronização completa...");
const result = await MCPSyncService.syncAll((progress) => {
const percentage =
progress.total > 0
? Math.round((progress.current / progress.total) * 100)
: 0;
console.log(
`📊 Progresso: ${progress.current}/${progress.total} (${percentage}%)`
);
});
if (result.success) {
console.log(`✅ Sincronização concluída com sucesso!`);
console.log(`📊 Total de servidores baixados: ${result.totalDownloaded}`);
console.log(`⏱️ Tempo total: ${Math.round(result.duration / 1000)}s`);
// 7. Verificar estatísticas finais
const stats = MCPCacheRepository.getStats();
console.log(`📈 Estatísticas finais do cache:`);
console.log(` - Total de itens: ${stats.totalItems}`);
console.log(
` - Última sincronização: ${
stats.lastSync ? new Date(stats.lastSync).toLocaleString() : "Nunca"
}`
);
console.log(` - Cache válido: ${stats.isValid ? "Sim" : "Não"}`);
} else {
console.error("❌ Sincronização falhou:");
result.errors.forEach((error) => console.error(` - ${error}`));
}
} catch (error) {
console.error("❌ Erro durante teste:", error);
}
}
testSimpleSync();
export { testSimpleSync };