El Protocolo de contexto modelo (MCP) permite a los agentes de IA llamar a herramientas externas a través de una interfaz estandarizada. Un agente MCP multiherramienta puede combinar búsqueda web, acceso al sistema de archivos, consultas de bases de datos y API personalizadas en una sola conversación. Este tutorial crea un agente MCP con una herramienta de búsqueda respaldada por la API de Scavio, una herramienta de archivos y una herramienta de calculadora. El patrón se adapta a cualquier número de herramientas. Las llamadas de búsqueda cuestan $0.005 cada una a través de Scavio.
Requisitos previos
- Python 3.10+ instalado
- Paquete mcp instalado (pip install mcp)
- Una clave API de Scavio de scavio.dev
- Comprensión básica de los patrones de uso de herramientas
Guia paso a paso
Paso 1: Definir el servidor de la herramienta de búsqueda MCP
Cree un servidor de herramientas MCP que exponga una función web_search. Este servidor maneja la llamada API y devuelve resultados estructurados al agente.
from mcp.server import Server
from mcp.types import Tool, TextContent
import requests, os, json
server = Server('search-tools')
API_KEY = os.environ['SCAVIO_API_KEY']
@server.tool()
async def web_search(query: str, country: str = 'us') -> str:
"""Search the web for current information."""
resp = requests.post('https://api.scavio.dev/api/v1/search',
headers={'x-api-key': API_KEY, 'Content-Type': 'application/json'},
json={'query': query, 'country_code': country})
results = resp.json().get('organic_results', [])[:5]
return json.dumps([{'title': r['title'], 'url': r['link'],
'snippet': r.get('snippet', '')} for r in results], indent=2)Paso 2: Agregar una herramienta de búsqueda de TikTok al mismo servidor
Agrega una segunda herramienta que busca en TikTok. Ambas herramientas comparten el mismo servidor MCP, por lo que el agente puede usar cualquiera de ellas en una sola sesión.
@server.tool()
async def tiktok_search(keyword: str, count: int = 10) -> str:
"""Search TikTok for videos about a topic."""
resp = requests.post('https://api.scavio.dev/api/v1/tiktok/search/videos',
headers={'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'},
json={'keyword': keyword, 'count': count, 'cursor': 0})
videos = resp.json().get('data', {}).get('videos', [])
return json.dumps([{'author': v.get('author', {}).get('nickname', ''),
'desc': v.get('desc', ''), 'plays': v.get('stats', {}).get('playCount', 0)}
for v in videos], indent=2)Paso 3: Agregar una calculadora y una herramienta de lectura de archivos
Demuestre el patrón de herramientas múltiples agregando herramientas que no sean de búsqueda. El agente decide qué herramienta utilizar en función de la consulta del usuario.
import math
@server.tool()
async def calculate(expression: str) -> str:
"""Evaluate a mathematical expression safely."""
allowed = set('0123456789+-*/.() ')
if not all(c in allowed for c in expression):
return 'Error: only numeric expressions allowed'
try:
result = eval(expression)
return str(result)
except Exception as e:
return f'Error: {e}'
@server.tool()
async def read_file(path: str) -> str:
"""Read a local text file."""
try:
with open(path, 'r') as f:
content = f.read(10000) # limit to 10KB
return content
except FileNotFoundError:
return f'File not found: {path}'Paso 4: Configurar el manifiesto del servidor MCP
Cree el archivo de configuración .mcp.json que le indique al cliente MCP dónde encontrar su servidor de herramientas y qué herramientas están disponibles.
// .mcp.json
{
"mcpServers": {
"search-tools": {
"command": "python",
"args": ["search_tools_server.py"],
"env": {
"SCAVIO_API_KEY": "your_scavio_api_key"
}
}
}
}
// The server exposes: web_search, tiktok_search, calculate, read_filePaso 5: Ejecute el servidor MCP
Inicie el servidor con transporte stdio. Cualquier cliente compatible con MCP (Claude Desktop, Cursor, agentes personalizados) ahora puede conectarse y utilizar las cuatro herramientas.
import asyncio
from mcp.server.stdio import stdio_server
async def main():
async with stdio_server() as (read_stream, write_stream):
await server.run(read_stream, write_stream)
if __name__ == '__main__':
asyncio.run(main())
# Test manually:
# echo '{"jsonrpc":"2.0","method":"tools/list","id":1}' | python search_tools_server.py
# Should list: web_search, tiktok_search, calculate, read_fileEjemplo en Python
from mcp.server import Server
from mcp.server.stdio import stdio_server
import requests, os, json, asyncio
server = Server('search-tools')
API_KEY = os.environ['SCAVIO_API_KEY']
@server.tool()
async def web_search(query: str, country: str = 'us') -> str:
"""Search the web for current information."""
resp = requests.post('https://api.scavio.dev/api/v1/search',
headers={'x-api-key': API_KEY, 'Content-Type': 'application/json'},
json={'query': query, 'country_code': country})
results = resp.json().get('organic_results', [])[:5]
return json.dumps([{'title': r['title'], 'snippet': r.get('snippet', '')} for r in results])
@server.tool()
async def tiktok_search(keyword: str, count: int = 10) -> str:
"""Search TikTok videos."""
resp = requests.post('https://api.scavio.dev/api/v1/tiktok/search/videos',
headers={'Authorization': f'Bearer {API_KEY}', 'Content-Type': 'application/json'},
json={'keyword': keyword, 'count': count, 'cursor': 0})
return json.dumps(resp.json().get('data', {}).get('videos', [])[:5])
async def main():
async with stdio_server() as (read, write):
await server.run(read, write)
if __name__ == '__main__':
asyncio.run(main())Ejemplo en JavaScript
// MCP servers are typically Python; this shows a JS HTTP wrapper
const API_KEY = process.env.SCAVIO_API_KEY;
const tools = {
async web_search({ query, country = 'us' }) {
const resp = await fetch('https://api.scavio.dev/api/v1/search', {
method: 'POST',
headers: { 'x-api-key': API_KEY, 'Content-Type': 'application/json' },
body: JSON.stringify({ query, country_code: country })
});
const data = await resp.json();
return (data.organic_results || []).slice(0, 5)
.map(r => ({ title: r.title, snippet: r.snippet || '' }));
},
async tiktok_search({ keyword, count = 10 }) {
const resp = await fetch('https://api.scavio.dev/api/v1/tiktok/search/videos', {
method: 'POST',
headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ keyword, count, cursor: 0 })
});
return (await resp.json()).data?.videos || [];
}
};
async function main() {
const results = await tools.web_search({ query: 'MCP protocol 2026' });
console.log(JSON.stringify(results, null, 2));
}
main().catch(console.error);Salida esperada
Available tools:
- web_search: Search the web for current information
- tiktok_search: Search TikTok for videos about a topic
- calculate: Evaluate a mathematical expression
- read_file: Read a local text file
[
{"title": "MCP Protocol Documentation", "snippet": "The Model Context Protocol..."}
{"title": "Building MCP Agents in 2026", "snippet": "A guide to creating..."}
]
Cost: $0.005 per web_search call, $0.005 per tiktok_search call