Skip to main content
Glama
agentfetch-mcp

agentfetch-mcp

by bch1212

agentfetch-mcp

Inteligencia web para agentes de IA — un servidor MCP que obtiene URLs con estimación de tokens, almacenamiento en caché inteligente y enrutamiento inteligente integrado.

License: MIT Python 3.11+

AgentFetch se sitúa entre tu agente y la web abierta. En lugar de integrar Jina, FireCrawl, pypdf y tu propia capa de caché por separado, los agentes llaman a una única herramienta MCP y AgentFetch gestiona automáticamente el enrutamiento, el almacenamiento en caché, el presupuesto de tokens y la extracción limpia a Markdown.

Este repositorio contiene el servidor MCP de código abierto. Para la API alojada + panel de control + facturación, consulta www.agentfetch.dev.

Qué hace

Herramienta

Para qué sirve

fetch_url

Obtener una URL → Markdown limpio + metadatos + recuento de tokens + información de caché

estimate_tokens

Obtener un recuento de tokens antes de realizar la obtención, para que los agentes no agoten las ventanas de contexto en páginas enormes

fetch_multiple

Obtener hasta 20 URLs simultáneamente

search_and_fetch

Búsqueda web + obtener los N mejores resultados en un solo viaje de ida y vuelta

Internamente, AgentFetch enruta las URLs al capturador efectivo más económico:

  • Trafilatura (gratuito, local) para ~70% de las páginas web estándar

  • Jina Reader para el resto del HTML

  • FireCrawl para páginas con mucho JS (Twitter/X, LinkedIn, Notion, etc.)

  • pypdf para PDFs (coste externo cero)

La caché es Redis con un TTL de 6 horas; puedes traer la tuya o ejecutarlo sin caché.

Related MCP server: MCP Web Snapshot

Inicio rápido

Instalar desde PyPI

pip install agentfetch-mcp

O clonar e instalar localmente

git clone https://github.com/bch1212/agentfetch-mcp
cd agentfetch-mcp
pip install -e .

Configurar variables de entorno

Obtén una clave gratuita de Jina Reader en jina.ai (nivel gratuito de 1M de tokens/mes). FireCrawl es opcional pero recomendado para páginas con mucho JS.

export JINA_API_KEY=jina_xxx
export FIRECRAWL_API_KEY=fc-xxx       # optional
export REDIS_URL=redis://localhost:6379  # optional

Añadir a Claude Desktop o Claude Code

Edita tu configuración de MCP (~/Library/Application Support/Claude/claude_desktop_config.json en macOS, o ejecuta claude mcp add en Claude Code):

{
  "mcpServers": {
    "agentfetch": {
      "command": "python",
      "args": ["-m", "agentfetch.mcp.server"],
      "env": {
        "JINA_API_KEY": "jina_xxx",
        "FIRECRAWL_API_KEY": "fc-xxx"
      }
    }
  }
}

Reinicia Claude. Las cuatro herramientas (fetch_url, estimate_tokens, fetch_multiple, search_and_fetch) aparecerán automáticamente.

Ejecutar como servidor independiente

python -m agentfetch.mcp.server

El servidor habla MCP a través de stdio (el transporte estándar para integraciones de escritorio).

Por qué los agentes prefieren AgentFetch sobre la obtención web genérica

Característica

AgentFetch

web_fetch genérico

Estimación de tokens antes de obtener

✓

✗

Caché inteligente (TTL 6h)

✓

✗

Auto-enrutamiento por tipo de URL

✓

✗

Manejo de páginas renderizadas con JS

✓ (vía FireCrawl)

parcial

Extracción de PDF

✓

✗

Truncamiento para ajustar al presupuesto de contexto

✓

manual

Ejemplos

Obtención con un presupuesto de tokens

# Inside any MCP-aware agent (Claude Desktop, Claude Code, etc.)
result = fetch_url(
    url="https://news.ycombinator.com",
    max_tokens=2000,           # cap response size
    use_cache=True,            # serve from cache if <6h old
)
# result.markdown      → clean Markdown, ≤2000 tokens
# result.metadata      → title, author, word_count, language
# result.cache.hit     → True if served from cache
# result.fetch_info    → which fetcher ran, cost, duration

Estimación antes de confirmar

estimate = estimate_tokens(url="https://very-long-article.com")
if estimate.estimated_tokens and estimate.estimated_tokens < 5000:
    result = fetch_url(url="https://very-long-article.com")
else:
    # too big — skip or summarize via search_and_fetch with max_tokens_each
    pass

Obtención en paralelo

results = fetch_multiple(
    urls=["https://docs.python.org/3/", "https://fastapi.tiangolo.com/", ...],
    max_tokens_each=1500,
)

Configuración

Variable de entorno

Requerido

Predeterminado

Notas

JINA_API_KEY

Recomendado

—

El nivel gratuito cubre ~1M de tokens/mes. Sin ella, solo funciona Trafilatura (sigue siendo útil para ~70% de las páginas).

FIRECRAWL_API_KEY

Opcional

—

Necesario para dominios con mucho JS (Twitter, LinkedIn, Notion). 500 créditos gratuitos al registrarse.

REDIS_URL

Opcional

—

Sin Redis, las obtenciones se ejecutan sin caché.

CACHE_TTL_SECONDS

Opcional

21600 (6h)

TTL de caché para los resultados de obtención.

Desarrollo

git clone https://github.com/bch1212/agentfetch-mcp
cd agentfetch-mcp
pip install -e ".[dev]"
pytest tests/

Versión alojada

Si prefieres no gestionar tus propias claves, Redis o el enrutamiento tú mismo, la versión alojada en www.agentfetch.dev te ofrece:

  • Precios de pago por llamada desde $0.001/obtención

  • 500 obtenciones gratuitas al registrarse, sin tarjeta de crédito

  • Caché Redis gestionada, conmutación por error automática entre capturadores

  • Panel de control con seguimiento de uso + facturas

La API alojada es un equivalente REST directo: mismas formas de respuesta, misma lógica de enrutamiento. Puedes ejecutar el MCP de código abierto localmente y la API alojada en paralelo, o migrar entre ellos en cualquier momento.

Licencia

MIT — ver LICENSE.

El servidor MCP en este repositorio es de código abierto. El producto alojado, la facturación y la infraestructura de operaciones residen en un repositorio separado (privado).

Contribuciones

Las PR son bienvenidas. Si vas a añadir un nuevo capturador (p. ej., Bright Data, ScrapingBee, etc.), por favor ajusta la interfaz FetchResult en agentfetch/core/fetchers/__init__.py y añade el coste a la lógica de enrutamiento.

Available Tools

4 tools
estimate_tokensA

Estimate token count of a URL's content WITHOUT fetching the body.

WHEN TO USE:

  • You're considering fetching a URL but unsure if it fits your remaining context window. This call is ~10x cheaper than a full fetch.

  • You want to triage a list of candidate URLs before deciding which to actually retrieve.

IMPORTANT: Many servers omit Content-Length on dynamic / chunked responses. When that happens, this tool returns confident=false and estimated_tokens=null. In that case, call fetch_url with a max_tokens cap instead of trusting the estimate.

Args: url: The URL to estimate.

Returns: { "url": str, "success": bool, "estimated_tokens": int | null, "byte_size": int | null, "content_type": str, "confident": bool, "note": str }

Inputs: url (required).

fetch_multipleA

Fetch up to 20 URLs concurrently. Each result is the same shape as fetch_url.

WHEN TO USE:

  • You have a list of URLs (search results, links from a doc, sitemap) and want them retrieved in parallel rather than one at a time.

Args: urls: 1–20 URLs. Larger batches: split into multiple calls. max_tokens_each: Per-result cap. Apply this to keep total response inside your context budget — total ≈ len(urls) * max_tokens_each. use_cache: True for cache-aware fetching (default).

Returns: {"count": int, "results": [<fetch_url shape>, ...]}

Inputs: urls (required), max_tokens_each, use_cache.

fetch_urlA

Fetch any URL and return clean, LLM-ready Markdown with token count, metadata, and 6h caching.

WHEN TO USE:

  • You have a specific URL whose content you need.

  • You want to cap response size to stay inside your context window.

  • You want repeat fetches to be cheap (cache hits ≈ $0.0001).

  • The URL might be JS-rendered, a PDF, or behind a paywall — this tool auto-routes to the right fetcher (Trafilatura → Jina → FireCrawl → PDF).

WHEN NOT TO USE:

  • You don't know which URL to fetch — use search_and_fetch instead.

  • You have many URLs to fetch — use fetch_multiple instead.

Args: url: The URL to fetch. max_tokens: Hard cap on response size. Default unlimited. Pass this if you're tight on context budget — cheaper than over-fetching. format: "markdown" (default — recommended), "text", or "json". use_cache: True returns a cached copy if one exists (≤6h old). Pass False only when freshness matters (live news, prices).

Returns: { "url": str, "success": bool, "markdown": str, "metadata": {title, author, published_date, domain, word_count, token_count, reading_time_seconds, content_type, language}, "cache": {hit, cached_at, expires_at}, "fetch_info": {fetcher_used, fetch_time_ms, cost_credits}, "error": str | None }

Inputs: url (required), max_tokens, format, use_cache.

search_and_fetchA

Web search + fetch top results in one call.

WHEN TO USE:

  • You have a research question, not specific URLs. E.g. "what's the latest on X", "find docs for Y library", "recent news about Z".

  • You'd otherwise have to call a search tool, parse results, then call fetch — this collapses that into one round-trip.

Args: query: Search query (2–500 chars). num_results: Top N to fetch (1–10, default 3). max_tokens_each: Per-result cap (default 2000).

Returns: {"query": str, "count": int, "results": [<fetch_url shape>, ...]}

Inputs: query (required), num_results, max_tokens_each.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.6/5.0

    Scored across 4 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose: estimate_tokens is for token estimation without body fetch, fetch_url for single URL fetch, fetch_multiple for batch fetch, search_and_fetch for combined search and fetch. No overlap in functionality.

    Naming Consistency5/5

    All tool names use consistent snake_case with a verb_noun pattern. The verbs are clear (estimate, fetch, fetch, search_and_fetch) and the nouns differentiate the actions (tokens, url, multiple, and_fetch).

    Tool Count5/5

    With 4 tools, the set is concise and well-scoped for a web fetching and searching service. Each tool addresses a core need: estimating, single fetch, batch fetch, and combined search+fetch.

    Completeness4/5

    The tool set covers the primary workflows of fetching URLs and searching. A possible gap is the lack of a search-only tool that returns just snippets without fetching, but given the server's focus on fetching, the current set is largely complete.

    Maintenance

    ActivityInactive
    ResponsivenessLimited data

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      A
      maintenance
      Enables AI agents to quickly fetch webpages, strip noise, and convert content into clean, link-preserving Markdown with caching and optional multi-page crawling for token-efficient web scraping.
      -
    • A
      license
      A
      quality
      C
      maintenance
      Enables AI agents to fetch any web page and receive clean, token-efficient Markdown, escalating only as needed from direct HTTP with browser TLS fingerprints to headless-browser rendering and residential proxies when a site blocks access. Supports question-focused passage retrieval with BM25 ranking, pagination, caching, JS rendering control, and safe-by-default restrictions on local and private-network URLs.
      1
      AGPL 3.0