La mayoría de los agentes de IA codifican qué herramienta utilizar para cada tipo de consulta. MCP cambia esto al permitir que los agentes descubran herramientas en tiempo de ejecución y seleccionen la mejor según el contexto. Este tutorial crea un agente de enrutamiento que se conecta al servidor MCP de Scavio, descubre 11 herramientas de búsqueda y elige dinámicamente la plataforma óptima para cada consulta. No se requiere lógica de enrutamiento if-else: el LLM toma la decisión de enrutamiento basándose en las descripciones de las herramientas.
Requisitos previos
- Node.js 18+ instalado
- @modelcontextprotocol/paquete sdk
- Una clave API de Scavio de scavio.dev
- Una clave API Anthropic u OpenAI para el LLM
Guia paso a paso
Paso 1: Instalar el SDK de MCP
Agregue el SDK del cliente MCP a su proyecto.
npm install @modelcontextprotocol/sdkPaso 2: Conéctese al servidor MCP y descubra herramientas
Cree un cliente que se conecte al servidor MCP de Scavio y enumere todas las herramientas disponibles.
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
const transport = new StreamableHTTPClientTransport(
new URL('https://mcp.scavio.dev/mcp'),
{ requestInit: { headers: { 'x-api-key': process.env.SCAVIO_API_KEY } } }
);
const client = new Client({ name: 'routing-agent', version: '1.0.0' });
await client.connect(transport);
const { tools } = await client.listTools();
console.log(`Discovered ${tools.length} tools:`);
tools.forEach(t => console.log(` - ${t.name}: ${t.description}`));Paso 3: Convertir herramientas MCP en definiciones de herramientas LLM
Asigne las herramientas MCP descubiertas al formato que su LLM espera para la llamada de herramientas.
function mcpToLlmTools(mcpTools) {
return mcpTools.map(t => ({
type: 'function',
function: {
name: t.name,
description: t.description,
parameters: t.inputSchema
}
}));
}
const llmTools = mcpToLlmTools(tools);Paso 4: Construya el bucle de enrutamiento
Envíe consultas de usuarios al LLM con la lista de herramientas. El LLM elige la herramienta; su código lo ejecuta a través de MCP.
async function routingAgent(userQuery) {
const messages = [{ role: 'user', content: userQuery }];
const response = await llm.chat({
messages,
tools: llmTools,
tool_choice: 'auto'
});
if (response.tool_calls) {
for (const call of response.tool_calls) {
const result = await client.callTool({
name: call.function.name,
arguments: JSON.parse(call.function.arguments)
});
messages.push({ role: 'tool', content: JSON.stringify(result), tool_call_id: call.id });
}
const final = await llm.chat({ messages, tools: llmTools });
return final.content;
}
return response.content;
}Ejemplo en Python
# Python MCP client with routing:
import requests, os, json
H = {'x-api-key': os.environ['SCAVIO_API_KEY']}
# Simplified routing without full MCP SDK:
PLATFORM_MAP = {
'product': 'amazon', 'price': 'amazon', 'buy': 'walmart',
'video': 'youtube', 'tutorial': 'youtube', 'how to': 'youtube',
'reddit': 'reddit', 'community': 'reddit', 'opinion': 'reddit',
}
def route_search(query: str) -> str:
q_lower = query.lower()
platform = 'google'
for keyword, p in PLATFORM_MAP.items():
if keyword in q_lower:
platform = p
break
resp = requests.post('https://api.scavio.dev/api/v1/search', headers=H,
json={'platform': platform, 'query': query}, timeout=10)
return json.dumps({'platform': platform, 'results': resp.json().get('organic', [])[:3]}, indent=2)Ejemplo en JavaScript
// Full MCP routing example in the steps above.
// Simplified version without MCP SDK:
const PLATFORM_MAP = { product: 'amazon', video: 'youtube', reddit: 'reddit', opinion: 'reddit' };
async function routeSearch(query) {
let platform = 'google';
for (const [kw, p] of Object.entries(PLATFORM_MAP)) {
if (query.toLowerCase().includes(kw)) { platform = p; break; }
}
const resp = await fetch('https://api.scavio.dev/api/v1/search', {
method: 'POST', headers: {'x-api-key': process.env.SCAVIO_API_KEY, 'Content-Type': 'application/json'},
body: JSON.stringify({platform, query})
});
return {platform, results: (await resp.json()).organic?.slice(0, 3)};
}Salida esperada
An MCP routing agent that discovers search tools dynamically and lets the LLM select the optimal platform per query context.