# Long-tail finder

The same question asked twice, with and without the most popular sites, side by side, and the pages only the second search found.

Available · Python 3.9+ · One file, nothing to install · Tested 2026-11-19

> **For agents.** Read the API key from the `MILLIONSHORT_API_KEY` environment variable. Never print it; where a client needs it in a settings file, use a file that is not committed.
> The MCP address is https://mcp.millionshort.com/mcp (streamable HTTP; send `Authorization: Bearer <key>`, or no header for the no-key mode).
> On `INSUFFICIENT_CREDITS` stop and ask a person; on `RATE_LIMITED` or `CAPACITY` wait the `Retry-After` seconds, then retry once.
> Set-up steps written for agents: https://millionshort.com/docs/auth.md. Every integration: https://millionshort.com/docs/integrations.md.

`remove_top_sites` leaves out the results of the N most popular sites. This script shows what that does to one query: the left column searches every site, the right one leaves out the top 1,000 (or the number you give), and the list underneath is the pages from sites the first search did not show.

## 1. Get the code

```python long_tail.py
"""Long-tail finder: the same question with and without the most popular sites, side by side.

    export MILLIONSHORT_API_KEY=ms-YOUR_API_KEY
    python long_tail.py "cast iron skillet restoration" [--remove 1000]

No package to install: Python 3.9 or later. Two searches, 2 credits.
"""
import argparse
import json
import os
import urllib.error
import urllib.request

API = os.environ.get("MILLIONSHORT_BASE_URL", "https://api.millionshort.com").rstrip("/")


def search(query, remove_top_sites):
    body = {"query": query, "num_results": 10, "remove_top_sites": remove_top_sites}
    request = urllib.request.Request(
        f"{API}/v1/search",
        data=json.dumps(body).encode(),
        headers={"Authorization": "Bearer " + os.environ["MILLIONSHORT_API_KEY"], "Content-Type": "application/json"},
    )
    with urllib.request.urlopen(request, timeout=60) as response:
        return json.load(response)["data"]["results"]


def row(result):
    return f"{result['site'][:28]:<28} {result['popularity']['bucket']:<9}"


def main():
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("query")
    parser.add_argument("--remove", type=int, default=1000, help="how many of the most popular sites to leave out (default 1000)")
    args = parser.parse_args()

    try:
        everything = search(args.query, 0)
        long_tail = search(args.query, args.remove)
    except urllib.error.HTTPError as failure:
        raise SystemExit(f"The search failed: HTTP {failure.code} {failure.read().decode(errors='replace')[:300]}")
    print(f"{'All sites':<38} | Without the top {args.remove:,}")
    print("-" * 38 + "-+-" + "-" * 38)
    for n in range(max(len(everything), len(long_tail))):
        left = row(everything[n]) if n < len(everything) else ""
        right = row(long_tail[n]) if n < len(long_tail) else ""
        print(f"{left:<38} | {right}")

    seen = {r["site"] for r in everything}
    new = [r for r in long_tail if r["site"] not in seen]
    print(f"\n{len(new)} of {len(long_tail)} results are on sites that the search of all sites did not show:")
    for r in new:
        print(f"  {r['title'][:70]}\n    {r['url']}")


if __name__ == "__main__":
    main()
```

## 2. Run it

```bash
export MILLIONSHORT_API_KEY=ms-YOUR_API_KEY
python long_tail.py "fountain pen restoration"
python long_tail.py "sourdough starter" --remove 10000
```

## 3. What you get

First the two columns: each result's site and its popularity band, from `top-100` to `top-1m`, then `long-tail`. For `"fountain pen restoration"`, the left column had an encyclopedia in the top 100 and two blog hosts in the top 1,000; the right column was long-tail sites only. Then the list:

```text Output (the end)
6 of 10 results are on sites that the search of all sites did not show:
  Pens Waterman [Fountain Pen]
    https://www.penparents.org/Waterman/pens-waterman
  Parker Pen renovation ⋆ Parker pen ⋆ Fountain pen. Calligraphy.
    https://pspbuddies.com/parker-pen/parker-pen-renovation.html
  Plunger filler - Vintage Fountain Pen Doctor
    https://vintagependoctor.com/plunger-filler/
  ...
```

Some queries change little: when no top site ranks for them, both columns are the same.

## 4. Change it

| To | Change |
|---|---|
| Cut deeper | `--remove 100000` |
| Compare the mainstream view | Search the second time with `only_top_sites` in place of `remove_top_sites` |
| Look at forums only | Add `"page_types": ["forums"]` to the body ([topics and page types](https://millionshort.com/docs/search/topics-and-page-types)) |

## Costs and limits

Two searches, 1 credit each.

## When it fails

| What you see | Why | Fix |
|---|---|---|
| `401 AUTH_MISSING_KEY` or `AUTH_INVALID_KEY` | The key is missing or wrong | Set `MILLIONSHORT_API_KEY`; keys start with `ms-` |
| `400 INVALID_PARAM` | A field name or value the API does not take | The `message` names the field; the [search reference](https://millionshort.com/docs/search/parameters) lists them all |
| `429 RATE_LIMITED` or `CAPACITY` | Too many calls a minute, or no free capacity right now | Wait the `Retry-After` seconds, then retry |
| `429 INSUFFICIENT_CREDITS` | The plan's credits are used up | Stop and add credits; do not retry |

## Related

- [Remove the top sites](https://millionshort.com/docs/search/remove-top-sites): what the cut does and how it is counted.
- [Popularity and risk](https://millionshort.com/docs/search/popularity-and-risk): the bands in the second column.
- [Domain check](https://millionshort.com/docs/integrations/cookbook-domain-check): the same bands for a list of sites.
