Slopsquatting: Stopping Your Coding Agent From Installing Packages That Don't Exist
LLMs invent plausible package names, and attackers register them. Here's how to gate every dependency your coding agent adds, with a runnable verifier, a policy table, and CI checks.
The problem: your agent will confidently pip install a package nobody wrote
Ask a coding agent to "add PDF table extraction" and it may write pip install pdf-table-extractor-pro. If that name doesn't exist on PyPI, the install fails and the agent moves on. The dangerous case is when it does exist, because someone noticed that models repeatedly hallucinate that exact name and registered it with a malicious payload.
This is commonly called slopsquatting: typosquatting's cousin, where the "typo" is a model hallucination. Academic work on package hallucination in code-generating LLMs has found that a meaningful fraction of suggested packages don't exist, and that many hallucinated names recur across runs. Recurrence is what makes the attack practical: an attacker doesn't need to guess, they only need to sample a model a few hundred times and register the names that keep showing up. (Exact rates vary by model, language, and prompt, so check the current research before quoting a number.)
Agents make this worse than chat-based autocomplete. A human reading a suggestion might pause at an odd name. An agent running in a loop executes npm install or pip install itself, often with network access and credentials in the environment, and install scripts run code immediately.
Why it happens
Three mechanisms combine:
- Name plausibility beats existence. A model learns what package names look like (
fastapi-utils,langchain-community-extras), not a live registry. Generating a plausible name is cheap and often wrong. - Stale knowledge. Packages get renamed, deprecated, or removed. The model remembers the old name, which may since have been freed up and re-registered by someone else.
- Cross-ecosystem leakage. A name that exists on npm gets suggested for PyPI (or vice versa). The same name on the other registry may be unclaimed, or claimed by an attacker.
The takeaway: existence on a registry is not evidence of legitimacy. A verifier has to look at age, history, and provenance, not only "does it resolve".
A defense in layers
No single check is enough. Put these in order from cheapest to most expensive:
| Layer | What it catches | Cost | Where it runs |
|---|---|---|---|
| Lockfile + allowlist | Anything not already approved | Free | Agent hook / pre-install |
| Registry existence check | Pure hallucinations | One HTTP call | Pre-install |
| Metadata heuristics (age, releases, downloads) | Freshly squatted names | One HTTP call | Pre-install |
| Install-script blocking | Payloads that run at install time | Config flag | Install command |
| Human review for new deps | Everything else | Minutes | PR review |
The most effective single change is architectural: the agent proposes dependencies, a deterministic script decides. Don't let the model be the judge of whether its own suggestion is safe.
Code: a pre-install verifier
This script checks PyPI metadata for a package and scores it. It uses the public PyPI JSON API (https://pypi.org/pypi/<name>/json), which returns release history with upload timestamps. Check the PyPI docs if you rely on specific fields, since API details can change.
#!/usr/bin/env python3
"""verify_dep.py - gate a Python dependency before an agent installs it."""
import sys
import json
import urllib.request
import urllib.error
from datetime import datetime, timezone
MIN_AGE_DAYS = 30 # first release must be at least this old
MIN_RELEASES = 3 # one-shot uploads are suspicious
ALLOWLIST_FILE = "approved-deps.txt"
def load_allowlist() -> set[str]:
try:
with open(ALLOWLIST_FILE) as f:
return {l.strip().lower() for l in f if l.strip() and not l.startswith("#")}
except FileNotFoundError:
return set()
def fetch_pypi(name: str) -> dict | None:
url = f"https://pypi.org/pypi/{name}/json"
try:
with urllib.request.urlopen(url, timeout=10) as r:
return json.load(r)
except urllib.error.HTTPError as e:
if e.code == 404:
return None
raise
def parse_ts(s: str) -> datetime:
return datetime.fromisoformat(s.replace("Z", "+00:00")).astimezone(timezone.utc)
def verify(name: str) -> tuple[bool, list[str]]:
reasons: list[str] = []
if name.lower() in load_allowlist():
return True, ["on allowlist"]
data = fetch_pypi(name)
if data is None:
return False, ["does not exist on PyPI (likely hallucinated)"]
upload_times = [
parse_ts(f["upload_time_iso_8601"])
for files in data["releases"].values()
for f in files
]
if not upload_times:
return False, ["no uploaded files"]
age_days = (datetime.now(timezone.utc) - min(upload_times)).days
n_releases = len([v for v, f in data["releases"].items() if f])
info = data["info"]
if age_days < MIN_AGE_DAYS:
reasons.append(f"first release only {age_days} days ago")
if n_releases < MIN_RELEASES:
reasons.append(f"only {n_releases} release(s)")
if not (info.get("project_urls") or info.get("home_page")):
reasons.append("no source repository or homepage linked")
return (len(reasons) == 0), reasons or ["passed heuristics"]
if __name__ == "__main__":
ok_all = True
for pkg in sys.argv[1:]:
ok, why = verify(pkg)
print(f"{'OK ' if ok else 'BLOCK'} {pkg}: {'; '.join(why)}")
ok_all &= ok
sys.exit(0 if ok_all else 1)
Run it: python verify_dep.py requests pdf-table-extractor-pro. Blocked packages exit non-zero, which is what makes it hook-friendly.
Note the limits: heuristics are not proof. A patient attacker can publish three releases and wait 30 days. That's why the allowlist and human review layers exist.
Wiring it into the agent loop
The check must sit in the path of the install command, not in the prompt. A prompt that says "verify packages before installing" is a suggestion; a hook is a guarantee.
Many agent harnesses support pre-tool-use hooks that can inspect a shell command and veto it. Here's a TypeScript sketch of a hook body that parses install commands and calls the verifier. The hook input format differs per tool, so adapt the I/O to your agent's documented schema.
import { spawnSync } from "node:child_process";
const INSTALL_RE = /\b(?:pip3?|uv pip|poetry add|npm i(?:nstall)?|pnpm add|yarn add)\s+([^\n;&|]+)/;
export function gateInstall(command: string): { allow: boolean; reason?: string } {
const m = command.match(INSTALL_RE);
if (!m) return { allow: true };
const pkgs = m[1]
.split(/\s+/)
.filter((t) => t && !t.startsWith("-"))
.map((t) => t.replace(/[=<>~!@].*$/, "")); // strip version specifiers
const res = spawnSync("python3", ["verify_dep.py", ...pkgs], { encoding: "utf8" });
if (res.status !== 0) {
return { allow: false, reason: `Dependency gate blocked install:\n${res.stdout}` };
}
return { allow: true };
}
This only covers the Python verifier; for npm you'd add an equivalent check against the npm registry's package metadata endpoint. Also note the regex is deliberately simple. It misses requirements.txt edits and pip install -r, so pair it with the CI check below.
Defense in CI: catch what the hook misses
Agents also edit requirements.txt, pyproject.toml, and package.json directly. In CI, diff the dependency files against the base branch and run the verifier on every added name:
# fail the PR if any newly added dependency fails verification
git diff origin/main -- requirements.txt \
| grep '^+[^+]' | sed 's/^+//; s/[=<>~!].*//' \
| xargs -r python verify_dep.py
Combine that with these settings, all of which are standard features of the tools (confirm flag names in your version's docs):
- Pin and hash.
pip install --require-hashes -r requirements.txtrefuses anything not matching a recorded hash. Lockfiles in uv, Poetry, and npm give you the same property. - Disable install scripts where you can.
npm install --ignore-scriptsstops lifecycle scripts from running. Python wheels avoid arbitrarysetup.pyexecution, but sdists still run build code. - Use a private mirror or proxy. An internal index that only serves approved packages turns "does it exist" into "has someone on the team approved it".
What to do when a name is blocked
Teach the agent to fail usefully instead of retrying with another invented name. Return a message like:
pdf-table-extractor-prois not on the approved list or failed registry checks. Use a package fromapproved-deps.txt, or write the dependency name and justification in the PR description for review.
That last part matters. Without a sanctioned path, agents tend to route around blocks (vendoring code, shelling out to curl | sh). Give them an approved route and a clear escalation.
Common pitfalls
- Trusting "it installed" as proof of safety. Install success only means the name resolved.
- Checking only PyPI for a name the agent intended for npm. Verify against the ecosystem the command actually targets.
- Ignoring transitive dependencies. A legitimate package can depend on a squatted one. Lockfile review and hash pinning cover this; a top-level check does not.
- Over-blocking. If the gate fires on every new library, developers will disable it. Use the allowlist to pre-approve common stacks and reserve heuristics for the unknown tail.
- Relying on the model to self-report. Asking "are you sure this package exists?" often gets a confident yes. Verify against the registry instead.
- Environment exposure. Run agents with minimal credentials. If a malicious install does run, short-lived, narrowly-scoped tokens limit the damage. See also our guide on sandboxing LLM-generated code.
Checklist
- Agent can't run install commands without passing a deterministic gate
- Allowlist of approved dependencies, reviewed in version control
- Registry existence + age/release/provenance heuristics for everything else
- Lockfiles with hashes; CI fails on unpinned additions
- Install scripts disabled or sandboxed
- New-dependency changes require human review in the PR
- Agent credentials are minimal and short-lived
Next steps
Start with the cheapest win this week: add the CI diff check above to one repo and see how many agent-added dependencies it flags. Then add the hook so problems are caught before the install runs, not after. For the broader picture, read our posts on MCP supply chain security and the OWASP agentic AI top 10 checklist.
If you're building agent systems and want hands-on practice with guardrails, sandboxing, and production hardening, that's exactly what our AI Engineering cohort covers.
Want to build this yourself?
Join a live cohort and go from reading about AI to shipping it, with practitioners who do it daily.