ScavioScavio
ProductPricingDocs
Sign InGet Started
  1. Home
  2. Tutorials
  3. How to Build an MCP Routing Agent
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.

Get Free API KeyAPI Docs

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

  • How to Connect MCP Search to Claude Desktop

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 50 free credits on signup.

Yes. The free tier includes 50 credits on signup, 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.

Related Resources

Solution

MCP Routing with Search Fallback

Read more
Use Case

MCP Search Gateway for Multi-Agent Systems

Read more
Glossary

MCP Agent Routing Layer

Read more
Best Of

Best Multi-Agent Search Tool in 2026

Read more
Best Of

Best MCP Search Tools for IDE Integration in 2026

Read more
Solution

Give AI Agents Multi-Source Search via MCP

Read more

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.

Get Free API KeyRead the Docs
ScavioScavio

Real-time search API for AI agents. Search every platform, not just Google.

Product

  • Features
  • Pricing
  • Dashboard
  • Affiliates

Developers

  • Documentation
  • API Reference
  • Quickstart
  • MCP Integration
  • Python SDK

Alternatives

  • Tavily Alternative
  • SerpAPI Alternative
  • Firecrawl Alternative
  • Exa Alternative

Tools

  • JSON Formatter
  • cURL to Code
  • Token Counter
  • All Tools

© 2026 Scavio. All rights reserved.

Featured on TAAFT
Terms of ServicePrivacy Policy