Metadata-Version: 2.1
Name: aiagentblocklist
Version: 1.0.0
Summary: Python feed client for the AI agent blocklist: download the daily files with ETag caching and match AI agent domains, browser extensions, processes and packages locally.
Home-page: https://www.aiagentblocklist.com
Author: Alpha Quantum
Author-email: info@alpha-quantum.com
License: MIT
Project-URL: Homepage, https://www.aiagentblocklist.com
Project-URL: Source, https://github.com/explainableaixai/aiagentblocklist
Project-URL: Tracker, https://www.aiagentblocklist.com/contact.php
Project-URL: GitLab, https://gitlab.com/url-classifications/aiagentblocklist
Project-URL: Pricing, https://www.aiagentblocklist.com/pricing.php
Keywords: ai-agents,ai-agent-blocklist,blocklist,ai-browser,mcp,coding-agents,browser-extensions,dns-filtering,firewall,mdm,endpoint-security,shadow-ai,ai-governance,threat-feed
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: System Administrators
Classifier: Intended Audience :: Information Technology
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Classifier: Topic :: System :: Networking :: Firewalls
Classifier: Topic :: System :: Systems Administration
Classifier: Typing :: Typed
Requires-Python: >=3.7
Description-Content-Type: text/markdown
Requires-Dist: requests>=2.20

# aiagentblocklist for Python

Your proxy logs, form submissions and requirements files already show which AI agents are in use. **aiagentblocklist** brings the daily AI Agent Blocklist into Python so pandas, Django and Airflow can see it too.

The package downloads the feed through your private link, revalidates local copies with ETags, and matches domains, browser extension IDs, process names and package names offline. It depends on `requests` and nothing else.

```python
from aiagentblocklist import Client

bl = Client().load_blocklist("var/aab_full.json")
bl.check_domain("https://api.example-agent.ai/v1/run")   # Entry(... agent_type='Browser agent' ...) or None
```

## What you get

- A feed client: `sync()` keeps a folder of block list files current, writing only files that changed.
- An offline matcher: `Blocklist` answers lookups from dictionaries built once, so even a million log rows cost only in-memory lookups and no HTTP.
- Typed records: each row is a frozen `Entry` dataclass with the ten feed columns, ready for `pandas.DataFrame`.
- Clear errors: a 403 and a 404 raise different exceptions, so a nightly job can tell "subscription paused" from "wrong link".

Inside the JSON your scripts will find 2,600+ AI agent domains and 5,300+ device identifiers, regenerated every day under download links that never change. That stability suits scheduled jobs. The product site, linked at the end of this page, has the full description.

## Installing

```bash
pip install aiagentblocklist
pip install pandas        # optional, only for Blocklist.to_dataframe()
```

Python 3.7 or newer. The package ships type hints (`py.typed`), so mypy and pyright check calls into it.

To download anything you need a subscription token: 32 letters and digits taken from the private link you receive after subscribing. Plans are listed on [the pricing page](https://www.aiagentblocklist.com/pricing.php). Export the token once and every `Client()` picks it up:

```bash
export AIAGENTBLOCKLIST_TOKEN=YourThirtyTwoCharacterTokenHere00
```

## First lines of code

```python
from aiagentblocklist import Client, Blocklist

client = Client()                                   # token from AIAGENTBLOCKLIST_TOKEN
changed = client.sync("/data/aab")                  # {'domains.txt': True, 'hosts.txt': False, ...}

bl = Blocklist.from_file("/data/aab/aab_full.json")
print(bl.version, len(bl), bl.agent_types())

bl.check_domain("chat.sample-browser.app")          # parent domain match
bl.check_extension("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
bl.check_process("SampleBrowser.exe")
bl.check_package("pypi", "Demo_MCP.Server")         # PEP 503: same as demo-mcp-server
bl.check("com.example.agentbrowser")                # any identifier

high = bl.filter(risk_grade=["High", "Severe"], kind="domain")
```

Every name above is a placeholder. The real feed contains real agents, browsers, extensions and packages.

## The data model

`aab_full.json` and `aab_full.csv` carry the same ten columns, and `Entry` mirrors them one to one.

| Field | Example (placeholder) | Meaning |
|---|---|---|
| `tool_name` | Example Agent | the product the row belongs to |
| `tool_domain` | example-agent.ai | that product's main domain |
| `category`, `subcategory` | AI agents, Browser agents | grouping for reports |
| `agent_type` | Browser agent | one of the twelve agent types |
| `kind` | `chrome_ext` | what sort of identifier `ident` is |
| `ident` | abcdefghijklmnopabcdefghijklmnop | the value to block or match |
| `name` | Example Agent for Chrome | display name of this identifier |
| `platform` | chrome | where the identifier applies |
| `risk_grade` | Elevated | Low, Moderate, Elevated, High, Severe or Not graded |

In alphabetical order, the twelve agent types are: AI agent, AI browser, Agent platform, Autonomous agent, Browser agent, Coding agent, MCP server, Personal AI assistant, Research agent, Sales agent, Voice agent, and Workflow automation and RPA.

The eighteen kinds group into five families. Each family has its own check method, and `check()` covers all of them.

| Family | Kinds | Method |
|---|---|---|
| Network | `domain` | `check_domain()` |
| Extensions and plugins | `chrome_ext`, `edge_ext`, `firefox_ext`, `vscode_ext`, `openvsx_ext`, `jetbrains_plugin` | `check_extension()` |
| Processes | `process_win`, `process_mac`, `process_cli` | `check_process()` |
| Packages | `npm`, `pypi` | `check_package()` |
| Installers and apps | `mac_bundle_id`, `brew_cask`, `brew_formula`, `mac_app_store`, `winget`, `ms_store` | `check()` |

## Reference

### `Client`

```python
Client(token=None, base_url="https://www.aiagentblocklist.com", timeout=30.0,
       user_agent="aiagentblocklist-python/1.0.0 (+https://www.aiagentblocklist.com)", session=None)
```

| Method | Returns | What it does |
|---|---|---|
| `file_url(name)` | `str` | full URL of one file; rejects names outside the feed pattern |
| `list_url()` | `str` | the HTML page that lists your files |
| `download(name)` | `bytes` | one GET |
| `download_text(name)` | `str` | the same, decoded as UTF-8 |
| `head(name)` | `dict` | `etag`, `last_modified`, `content_length` |
| `download_to(name, path)` | `bool` | conditional GET; `False` means 304 and the file was left alone |
| `sync(directory, names=None)` | `dict[str, bool]` | `download_to` for each file, all files by default |
| `load_blocklist(cache_path=None)` | `Blocklist` | fetch and parse `aab_full.json`, optionally through a cache file |

`session` accepts your own `requests.Session`, which is the place for retries, client certificates or custom adapters. `repr(client)` shows only the last four characters of the token.

### `Blocklist`

| Member | Returns | Notes |
|---|---|---|
| `Blocklist.from_file(path)` / `from_json(text)` | `Blocklist` | offline use, no token needed |
| `check_domain(host_or_url)` | `Entry` or `None` | host or any parent domain; `kind == "domain"` rows only |
| `check_extension(id)` | `Entry` or `None` | six extension and plugin kinds, case-insensitive |
| `check_process(name)` | `Entry` or `None` | case-insensitive, `.exe` optional, paths reduced to the file name |
| `check_package(ecosystem, name)` | `Entry` or `None` | `"npm"` lowercase exact, `"pypi"` PEP 503 |
| `check(identifier)` | `Entry` or `None` | domain match first, then exact identifier |
| `filter(agent_type=, kind=, risk_grade=)` | `list[Entry]` | strings or lists, case-insensitive |
| `domains()`, `agent_types()`, `kinds()` | `list[str]` | sorted distinct values |
| `to_records()` / `to_dataframe()` | list of dicts / DataFrame | column names as in the CSV |
| `version`, `counts`, `entries`, `len()` | | feed metadata |

## When things go wrong

All exceptions derive from `AiAgentBlocklistError`, which carries `.status` (an HTTP status or `None`) and `.message`.

| Exception | Raised when | Typical reaction |
|---|---|---|
| `TokenError` | no token, or not 32 letters and digits; raised before any request | fix configuration |
| `NotFoundError` | 404: the token or the file name is unknown | check the link; do not retry |
| `AccessEndedError` | 403: the subscription has ended or is paused | keep the last copy, alert someone |
| `HttpError` | another non-2xx status | retry with backoff |
| `AiAgentBlocklistError` | connection errors, timeouts, unreadable JSON | retry; files on disk are untouched |

```python
from aiagentblocklist import Client, AccessEndedError, NotFoundError, AiAgentBlocklistError

try:
    Client().sync("/data/aab")
except AccessEndedError:
    notify("AI agent feed: access ended, firewall keeps yesterday's list")
except NotFoundError:
    notify("AI agent feed: the download link in the vault is wrong")
except AiAgentBlocklistError as exc:
    log.warning("feed sync failed (status=%s): %s", exc.status, exc)
```

Retries belong in your scheduler or in the session, not in a tight loop. A `requests` adapter with `urllib3.util.Retry` on status 500, 502, 503 and 504 handles short outages, while 403 and 404 should never be retried because the answer will not change on its own.

Writes go to `<path>.part` first and are renamed into place, so a crash mid-download never leaves a truncated block list behind.

## Recipes

The [`examples/`](https://github.com/explainableaixai/aiagentblocklist/tree/main/python/examples) folder holds runnable versions of each recipe. The pandas and requirements scripts accept `--feed path/to/aab_full.json` to run without a token.

### Recipe 1: a week of proxy logs in pandas

Analysts usually start with a question like "how many people used agent tools last week, and which kinds?". Check each distinct host once and merge the answer back, so the cost depends on the number of distinct hosts and not on the number of rows.

```python
import pandas as pd
from aiagentblocklist import Blocklist

bl = Blocklist.from_file("/data/aab/aab_full.json")
log = pd.read_csv("proxy_week.csv", usecols=["ts", "user", "host"])

hosts = pd.DataFrame({"host": log["host"].dropna().unique()})
hits = hosts["host"].map(bl.check_domain)
hosts["agent_type"] = hits.map(lambda e: e.agent_type if e else None)
hosts["listed"] = hits.map(lambda e: e.ident if e else None)

agents = log.merge(hosts.dropna(subset=["listed"]), on="host")
print(agents.pivot_table(index="agent_type", values="user", aggfunc=["count", "nunique"]))
```

For an overview of the feed itself, `bl.to_dataframe()` gives one row per identifier. A crosstab of `agent_type` against `kind` shows at a glance how many coding agents arrive as packages and how many as editor plugins.

### Recipe 2: a Django validator for user-supplied URLs

Integration settings, webhook URLs and "import from link" fields let users point your app at any host. A model validator keeps listed agent endpoints out.

```python
# yourapp/aab.py
from django.conf import settings
from django.core.exceptions import ValidationError
from aiagentblocklist import Blocklist

_bl = Blocklist.from_file(settings.AIAGENTBLOCKLIST_CACHE)

def reject_ai_agent_urls(value):
    hit = _bl.check_domain(value)
    if hit:
        raise ValidationError("%(host)s belongs to a listed AI agent (%(t)s).",
                              params={"host": hit.ident, "t": hit.agent_type})

# models.py
callback_url = models.URLField(validators=[reject_ai_agent_urls])
```

Refresh the cache from cron with a management command that calls `Client().download_to("aab_full.json", settings.AIAGENTBLOCKLIST_CACHE)`. The example in `examples/django_validators.py` also reloads the parsed list when the file's mtime changes, so Gunicorn workers pick up a new day without a restart.

### Recipe 3: an Airflow DAG that publishes DNS and firewall files

Data platform teams often own the scheduler. The DAG below syncs every morning and copies the DNS and firewall files to the internal web root only when they changed.

```python
from datetime import datetime
from airflow.decorators import dag, task

@dag(schedule="30 5 * * *", start_date=datetime(2026, 1, 1), catchup=False)
def aiagentblocklist_feed():
    @task(retries=3)
    def sync():
        from aiagentblocklist import Client
        return Client().sync("/data/aab", ["dns_rpz.zone", "firewall_edl.txt", "aab_full.json"])

    @task
    def publish(result: dict):
        import shutil
        for name in ("dns_rpz.zone", "firewall_edl.txt"):
            if result[name]:
                shutil.copy2(f"/data/aab/{name}", f"/srv/feeds/{name}")

    publish(sync())

aiagentblocklist_feed()
```

The return value of `sync()` is a plain dict of booleans, so it travels through XCom without custom serialization.

### Recipe 4: stop agent packages at the merge request

MCP servers and coding agents are often installed as ordinary Python dependencies. `check_package("pypi", ...)` applies PEP 503 normalisation, so `Demo_MCP.Server`, `demo-mcp-server` and `DEMO.mcp__server` are one name.

```python
import re, sys
from aiagentblocklist import Blocklist

bl = Blocklist.from_file("aab_full.json")
names = [re.split(r"[<>=!~;\[ ]", l.strip())[0] for l in open("requirements.txt") if l.strip() and l[0] not in "#-"]
listed = [(n, bl.check_package("pypi", n)) for n in names]
listed = [(n, e) for n, e in listed if e]
for n, e in listed:
    print(f"{n}: listed {e.agent_type}")
sys.exit(1 if listed else 0)
```

### Recipe 5: what changed since yesterday

Security teams like to know which entries are new before a list goes live. Keep the previous `aab_full.json`, load both into DataFrames and compare on the identifier.

```python
import pandas as pd
from aiagentblocklist import Blocklist

old = Blocklist.from_file("/data/aab/prev/aab_full.json").to_dataframe()
new = Blocklist.from_file("/data/aab/aab_full.json").to_dataframe()

key = ["kind", "ident"]
added = new.merge(old[key], on=key, how="left", indicator=True).query("_merge == 'left_only'")
print(added.groupby(["agent_type", "kind"]).size().sort_values(ascending=False).head(15))
```

A short daily summary like this is easy to post to a chat channel or attach to a change ticket. It also helps reviewers spot a new family of agents, for example a burst of fresh editor plugins.

### Recipe 6: match an endpoint inventory export

Most endpoint and MDM tools can export installed software and running processes as CSV. Feed the identifier column through `check()` and you get one table of agent tools per device.

```python
import pandas as pd
from aiagentblocklist import Blocklist

bl = Blocklist.from_file("/data/aab/aab_full.json")
inv = pd.read_csv("inventory.csv")            # columns: device, identifier
inv["entry"] = inv["identifier"].map(bl.check)
found = inv.dropna(subset=["entry"])
found = found.assign(tool=found["entry"].map(lambda e: e.tool_name),
                     agent_type=found["entry"].map(lambda e: e.agent_type))
print(found.groupby("device")["tool"].nunique().sort_values(ascending=False).head(20))
```

`check()` is the right method here because an inventory column mixes bundle IDs, package IDs, process names and extension IDs. Internally it asks the domain index first and falls back to a case-insensitive lookup over all identifiers.

## Feed files worth knowing

`sync()` with no names fetches all nineteen files. Python jobs mostly read the first two and publish the rest.

| File | Role |
|---|---|
| `aab_full.json` | input for `Blocklist`; has `product`, `version`, `counts`, `columns`, `entries` |
| `aab_full.csv` | the same rows for `pd.read_csv` and spreadsheets |
| `domains.txt` | one domain per line; block subdomains too |
| `dns_rpz.zone` | response policy zone that answers NXDOMAIN |
| `firewall_edl.txt` | one host per line for external dynamic lists |
| `pypi_packages.txt`, `npm_packages.txt` | package names for registry proxies |
| `process_names.txt`, `macos_bundle_ids.txt`, `windows_package_ids.txt` | endpoint rules and inventory checks |
| `counts.json` | totals per kind, agent type and risk grade |

Browser policy files, a hosts file, a PAC script and a plain-text `README.txt` are in the feed as well.

## Choosing a scheduler

The feed changes once a day, so any scheduler you already run will do. What differs is where the token lives and who notices a failure.

| Scheduler | Good fit when | Where the token lives |
|---|---|---|
| cron or a systemd timer | one server publishes files for DNS and firewalls | an environment file readable by one service user |
| Airflow | the data team already runs pipelines and wants lineage | an Airflow Variable or a secrets backend |
| Celery beat | a Django app needs the list and already runs workers | Django settings read from the environment |
| A CI schedule | the output is a merge request or a report | a masked CI variable |

Whichever you pick, run `sync()` a little after the start of the working day in your main region and alert on `AccessEndedError` and `NotFoundError`. Plain network errors can retry quietly, because the copy on disk stays valid in the meantime.

## Why this matters

An AI agent acts with the access of whoever launched it. It reads the same mailbox, opens the same internal wiki and runs commands with the same file permissions. If nobody approved it, nobody checked what it keeps or where it sends it.

Agent use rarely shows up in a software inventory, because many agents are browser extensions, editor plugins or a `pip install` away. Logs and dependency files are where they become visible, which is why a Python matcher is a practical place to start. Our guide to [building an AI agent inventory](https://www.aiagentblocklist.com/ai-agents/ai-agent-inventory.php) walks through that first count.

Frameworks give the work a structure. The [NIST AI Risk Management Framework](https://www.nist.gov/itl/ai-risk-management-framework) organizes it into govern, map, measure and manage; a list of which agents run where is the "map" step in practice. [ENISA](https://www.enisa.europa.eu/) and [CISA](https://www.cisa.gov/ai) both publish guidance on securing AI systems that is worth reading next to your own policy.

Developer machines deserve a separate look. Coding agents run shell commands in a repository, and MCP servers give an agent new tools such as file access or database queries. Both arrive through `pip`, `npm` or an editor marketplace, so package names and plugin IDs are as important as domains.

For the scoring side, see our page on [AI agent risk assessment](https://www.aiagentblocklist.com/guides/ai-agent-risk-assessment.php), and for the policy side, [AI agent governance](https://www.aiagentblocklist.com/ai-agents/ai-agent-governance.php).

## Matching rules in detail

- **Domains.** Input may be a URL, `host:port` or a bare host. Scheme, userinfo, port, path, query and fragment are removed, the host is lowercased and a trailing dot is dropped. The host and then each parent domain are looked up, so `api.example-agent.ai` matches `example-agent.ai` and `notexample-agent.ai` does not.
- **Extensions.** Exact match, case-insensitive. Chrome and Edge IDs are 32 letters from a to p; Firefox IDs often look like an email address or a GUID.
- **Processes.** Case-insensitive; `Foo.exe` matches `foo` and the reverse. `C:\Apps\Foo.exe` and `/usr/local/bin/foo` reduce to the file name first.
- **Packages.** npm names are compared in lowercase. PyPI names follow [PEP 503](https://peps.python.org/pep-0503/): runs of `-`, `_` and `.` become one `-`.
- **First row wins.** When two rows share an identifier, the lookup returns the first one in the file. `filter()` still returns every row.

## Questions people ask

### Is the parsed Blocklist safe to share between threads?

Yes. It is read-only after construction, so Django or Flask workers can share one instance. A `Client` holds a `requests.Session`; give each thread its own client if several threads download at once.

### Does the client respect HTTPS_PROXY?

Yes, because it uses `requests`, which reads `HTTPS_PROXY`, `HTTP_PROXY` and `NO_PROXY` from the environment. Pass a session with `trust_env = False` to switch that off.

### Why is `Entry` a frozen dataclass?

Frozen records are hashable, so you can put them in sets, use them as dict keys or group by them. They also cannot be changed by accident in one part of a program while another part reads them.

### How do I unit test code that uses this package?

Write a small `aab_full.json` with made-up rows and load it with `Blocklist.from_file()`. No token and no network are needed, which is how the package's own tests work.

### Can I load the CSV instead of the JSON?

The `Blocklist` class reads the JSON, which also carries the version and counts. For analysis only, `pd.read_csv("aab_full.csv")` is fine and gives the same ten columns.

### Does sync() remove files that are no longer in the feed?

No. The client only creates and replaces files; it never removes anything from your folder. If you pass a shorter list of names, the other files simply stop being refreshed.

### Can I run it in a serverless function?

Yes, as long as the function can write to a temporary folder. Point `load_blocklist()` at a path under `/tmp`, so warm invocations revalidate with a 304 instead of downloading the whole file again.

### What does a 403 mean for the files I already have?

They stay on disk and keep working. `AccessEndedError` only tells you that new downloads stopped; your DNS zone and firewall list keep the last version until you replace them. Write to us through the contact form in the Links section if you think the 403 is a mistake.

### Which Python versions does the package support?

Python 3.7 and newer. The code avoids newer syntax on purpose, and the test suite runs with plain `unittest`, so it also works where pytest is not installed.

### Where should the cache file live in a container?

On a mounted volume if the container restarts often, so the next start revalidates instead of downloading again. Inside the image is fine for short jobs; the first request of each run simply fetches the full file.

## Links

- [AI Agent Blocklist home](https://www.aiagentblocklist.com/)
- [Coding agent risks on developer machines](https://www.aiagentblocklist.com/coding-agents/coding-agent-security-risks.php)
- [MCP security checklist](https://www.aiagentblocklist.com/mcp/mcp-security-checklist.php)
- [Contact and bug reports](https://www.aiagentblocklist.com/contact.php), or email info@alpha-quantum.com
- [Source code on GitHub](https://github.com/explainableaixai/aiagentblocklist) (Python client in `python/`)
- [Package on PyPI](https://pypi.org/project/aiagentblocklist/)

Product names are trademarks of their respective owners.

## License

Distributed under MIT terms, Copyright (c) 2026 Alpha Quantum; the LICENSE file is part of the source distribution.

## Related

- [AI tools blocklist](https://www.aitoolsblocklist.com): domains of generative AI tools.
- [App blocklist for MDM](https://www.appblocklist.com): mobile app lists.
- [Web filtering database](https://www.webfilteringdatabase.com): domain categories.


