Tutorial

How to Build an MCP Routing Agent

Learn how to build an AI agent that dynamically discovers and routes to MCP search tools based on query context, without hardcoded tool selection logic.

Most AI agents hardcode which tool to use for each query type. MCP changes this by letting agents discover tools at runtime and select the best one based on context. This tutorial builds a routing agent that connects to Scavio's MCP server, discovers 11 search tools, and dynamically picks the optimal platform for each query. No if-else routing logic required: the LLM makes the routing decision based on tool descriptions.

Prerequisites

  • Node.js 18+ installed
  • @modelcontextprotocol/sdk package
  • A Scavio API key from scavio.dev
  • An Anthropic or OpenAI API key for the LLM

Walkthrough

Step 1: Install the MCP SDK

Add the MCP client SDK to your project.

Bash
npm install @modelcontextprotocol/sdk

Step 2: Connect to the MCP server and discover tools

Create a client that connects to Scavio's MCP server and lists all available tools.

JavaScript
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}`));

Step 3: Convert MCP tools to LLM tool definitions

Map the discovered MCP tools into the format your LLM expects for tool calling.

JavaScript
function mcpToLlmTools(mcpTools) {
  return mcpTools.map(t => ({
    type: 'function',
    function: {
      name: t.name,
      description: t.description,
      parameters: t.inputSchema
    }
  }));
}

const llmTools = mcpToLlmTools(tools);

Step 4: Build the routing loop

Send user queries to the LLM with the tool list. The LLM picks the tool; your code executes it via MCP.

JavaScript
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;
}

Python Example

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)

JavaScript Example

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)};
}

Expected Output

JSON
An MCP routing agent that discovers search tools dynamically and lets the LLM select the optimal platform per query context.

Related Tutorials

Frequently Asked Questions

Most developers complete this tutorial in 15 to 30 minutes. You will need a Scavio API key (free tier works) and a working Python or JavaScript environment.

Node.js 18+ installed. @modelcontextprotocol/sdk package. A Scavio API key from scavio.dev. An Anthropic or OpenAI API key for the LLM. A Scavio API key gives you 500 free credits per month.

Yes. The free tier includes 500 credits per month, which is more than enough to complete this tutorial and prototype a working solution.

Scavio has a native LangChain package (langchain-scavio), an MCP server, and a plain REST API that works with any HTTP client. This tutorial uses the raw REST API, but you can adapt to your framework of choice.

Start Building

Learn how to build an AI agent that dynamically discovers and routes to MCP search tools based on query context, without hardcoded tool selection logic.