Skip to main content
Glama
bch1212

agentfetch-mcp

estimate_tokens

Estimate the token count of a URL's content without performing a full fetch. This allows you to check if the content fits your remaining context window before deciding to retrieve it.

Instructions

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 }

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
urlYes

Implementation Reference

  • Registers the 'estimate_tokens' FastMCP tool, decorated with @mcp.tool(), which calls the _estimate_tokens helper.
    @mcp.tool()
    def estimate_tokens(url: str) -> dict:
        """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
            }
        """
        return _estimate_tokens(url=url)
  • MCP tool handler that delegates to estimate_url_tokens from the core pipeline.
    def estimate_tokens(url: str) -> dict:
        """Estimate the token count of a URL's content WITHOUT fetching the body.
    
        Use this to decide whether a URL is worth fetching given your context
        budget. Returns the estimated token count along with the byte size and
        content type that informed the estimate.
        """
        return estimate_url_tokens(url)
  • Core implementation: sends a HEAD request (or fallback GET) to the URL, extracts Content-Length and Content-Type, then calls estimate_tokens_from_size to produce the estimate.
    def estimate_url_tokens(url: str, timeout: int = 10) -> Dict[str, Any]:
        """HEAD the URL and convert Content-Length to a token estimate.
    
        Cheap and fast — no body fetch. Falls back to a tiny GET if HEAD isn't
        supported by the server.
        """
        started = time.time()
        import httpx
    
        try:
            validate_url(url)
        except UnsafeURLError as e:
            return {
                "url": url,
                "success": False,
                "estimated_tokens": None,
                "error": f"URL rejected: {e}",
                "fetch_time_ms": int((time.time() - started) * 1000),
            }
    
        try:
            resp = httpx.head(url, timeout=timeout, follow_redirects=True)
            if resp.status_code == 405 or resp.status_code >= 400:
                # Some servers reject HEAD; do a streamed GET and just read headers.
                with httpx.stream("GET", url, timeout=timeout, follow_redirects=True) as s:
                    headers = s.headers
                    status = s.status_code
            else:
                headers = resp.headers
                status = resp.status_code
        except httpx.HTTPError as e:
            return {
                "url": url,
                "success": False,
                "estimated_tokens": 0,
                "error": str(e),
                "fetch_time_ms": int((time.time() - started) * 1000),
            }
    
        if status >= 400:
            return {
                "url": url,
                "success": False,
                "estimated_tokens": 0,
                "error": f"HEAD returned {status}",
                "fetch_time_ms": int((time.time() - started) * 1000),
            }
    
        content_length = int(headers.get("content-length", 0) or 0)
        content_type = headers.get("content-type", "text/html")
        estimate = estimate_tokens_from_size(content_length, content_type)
    
        # Many servers omit Content-Length on dynamic / chunked / compressed
        # responses. Don't lie to the agent — flag the estimate as unavailable.
        confident = content_length > 0
        return {
            "url": url,
            "success": True,
            "estimated_tokens": estimate if confident else None,
            "byte_size": content_length if confident else None,
            "content_type": content_type,
            "fetch_time_ms": int((time.time() - started) * 1000),
            "confident": confident,
            "note": (
                "Estimate based on Content-Length + content type. Actual count after "
                "cleaning may be lower."
                if confident
                else "Server did not return Content-Length. Estimate unavailable — "
                "fetch the URL to get the actual token count."
            ),
        }
  • Return type schema documented in the tool's docstring (url, success, estimated_tokens, byte_size, content_type, confident, note).
    Returns:
        {
          "url": str, "success": bool,
          "estimated_tokens": int | null,
          "byte_size": int | null,
          "content_type": str,
          "confident": bool,
          "note": str
        }
  • Low-level heuristic: converts byte_size + content_type to estimated token count based on content-type survival ratios (HTML ~30%, PDF ~50%, text ~95%, etc.).
    def estimate_tokens_from_size(byte_size: int, content_type: str = "text/html") -> int:
        """Rough estimate from a Content-Length header before fetching the body.
    
        Cheap heuristic — actual token count after cleaning will be lower because
        we strip nav/ads/scripts. We bias the estimate slightly high so agents
        don't over-fetch into a context-window blowout.
    
        Heuristics:
          - HTML: ~30% of bytes survive cleaning, ~4 chars/token → bytes * 0.3 / 4
          - Plain text: ~95% survives, ~4 chars/token → bytes * 0.95 / 4
          - PDF: ~50% extractable text, ~4 chars/token → bytes * 0.5 / 4
        """
        if byte_size <= 0:
            return 0
    
        ct = (content_type or "").lower()
        if "html" in ct:
            return int(byte_size * 0.30 / 4)
        if "pdf" in ct:
            return int(byte_size * 0.50 / 4)
        if "json" in ct or "xml" in ct:
            return int(byte_size * 0.80 / 4)
        if "text" in ct:
            return int(byte_size * 0.95 / 4)
        # Unknown — assume HTML-ish
        return int(byte_size * 0.30 / 4)
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations exist, but the description fully discloses behavior: no body fetch, 10x cheaper, fallback when Content-Length missing, and return structure with confident flag.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Well-structured with sections, but includes a full return example that is slightly verbose yet informative.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a one-parameter tool, the description covers purpose, usage, fallback, and return format completely, compensating for lack of output schema.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema has 0% coverage, but the description includes an 'Args' section explaining the url parameter, adding meaning beyond the schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool estimates token count without fetching the body, and distinguishes from sibling tools like fetch_url by emphasizing it does not fetch the body.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly provides when-to-use (unsure about context window, triaging URLs) and when-not-to-use (if confident=false, use fetch_url with max_tokens).

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/bch1212/agentfetch-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server