Skip to main content
Glama

EngramSec

Version 1.0.0 · Changelog · License: PolyForm Shield 1.0.0 (source-available)

EngramSec is a local-first, Claude Code-native penetration-testing platform built on the Model Context Protocol (MCP). It is meant for authorized work only: CTF labs and bug-bounty programs whose scope you hold. It gives Claude Code:

  • scope-enforced tool orchestration;

  • persistent engagement memory;

  • hash-chained evidence integrity;

  • artifact search;

  • an execution trace;

  • workflows that keep large scanner output out of the model's context.

License notice. EngramSec is source-available, not open source. It is licensed under the PolyForm Shield License 1.0.0, which is not an OSI-approved open-source license. You may use, modify and distribute it for any purpose except providing a product that competes with it; read the LICENSE for the exact terms. Methodology files that declare CC-BY-SA-4.0 keep that license (see THIRD_PARTY_NOTICES.md).

What it is (and isn't)

  • Claude Code reasons, EngramSec executes, the disk remembers. There is no built-in LLM loop and no provider abstraction. The MCP host, Claude Code, is the reasoning engine. EngramSec supplies real local tool execution and scope enforcement. Under sessions/<engagement>/ it keeps the memory: evidence, findings, trace, inventory, checkpoints and metrics.

  • Local-first. Nothing leaves the machine unless a tool says so. The opt-in exceptions are NVD CVE enrichment, crt.sh subdomain lookups, gau archives and the optional HTB API group.

  • Read-only enumeration by design. It never sprays, brute-forces, cracks, relays, exploits, moves laterally, escalates or evades WAF/EDR. Recommendations are never executed automatically. Scanner output is a candidate, never a verified finding.

  • Context-efficient. Raw output is stored as immutable evidence. Tools return compact summaries plus artifact ids. Claude reads selectively (artifact_read(id, grep=…)) and reuses earlier scans through a fingerprinted cache instead of rescanning.

Related MCP server: mcp-shodan

Architecture

Claude Code ── native skills (.claude/skills, 10) ── CLAUDE.md (level-1 guide)
     │  MCP (stdio, server id "pentest-mcp", 89 tools by default, schemas loaded on demand)
     ▼
server.py ─┬─ scope.py ............ central scope policy (CTF effective scope / bug-bounty scope files)
           ├─ tools/ .............. nmap, DNS, web (ffuf/gobuster/…), P7 service enumerators
           ├─ evidence.py ......... immutable evidence + candidate findings (stable identity)
           ├─ evidence_integrity.py SHA-256 hash chain, capsules, anchors
           ├─ trace.py ............ append-only execution trace, replay/resume
           ├─ engagement.py ....... summary, checkpoint (<4 KB), resume, hypotheses
           ├─ artifact_index.py ... derived SQLite FTS5 index (search, relations)
           ├─ scan_cache.py ....... shared scan-reuse cache
           ├─ methodology.py ...... methodology engine (25 methods, 9 decision trees)
           └─ metrics.py .......... usage and context-efficiency metrics
     ▼
sessions/<engagement>/ (local, gitignored)

The same core functions are exposed three ways: as MCP tools, as the ctf-recon CLI (cli.py) and as standalone scripts (scripts/). The repository layout is shown under Repository layout.

Requirements

  • Linux. Developed and tested on Arch Linux. Package hints exist for pacman, apt, xbps, apk and emerge.

  • Python. Tested on Python 3.14; older versions are untested.

  • Python packages from requirements.txt: mcp SDK 2.x, httpx, PyYAML, python-dotenv.

  • Claude Code, as the MCP host.

  • External scanners, all optional. Each tool reports what is missing, with an install hint, and falls back to an alternative where one exists:

    • core: nmap, ffuf (or gobuster/feroxbuster/dirsearch), nikto/whatweb, curl;

    • service enumeration: smbclient, ssh, snmpwalk, dig;

    • tmux, for the interactive shell_* tools.

    • The full test suite also needs named (bind9), smbd, sshd and snmpd for its local labs.

Installation

git clone https://github.com/b33r00/engramsec.git
cd engramsec
python3 -m venv .venv
.venv/bin/pip install -r requirements.txt
cp .env.example .env          # optional: only for the HTB API group or auto-install
.venv/bin/python cli.py --version

Claude Code configuration

Register the MCP server, using absolute paths to your clone. The server id stays pentest-mcp, so existing configurations keep working.

cd engramsec
claude mcp add --scope user pentest-mcp -- "$PWD/.venv/bin/python" "$PWD/server.py"

Open Claude Code inside the repository so that CLAUDE.md and the native skills in .claude/skills/ load. Then check with /mcp that pentest-mcp is connected.

The optional HackTheBox API and writeup tools stay off by default. Enable them with PENTEST_MCP_TOOL_GROUPS=htb,writeup in the server's environment.

CTF quick start

The prompts below are typed into Claude Code. The tool calls show what happens underneath.

session_start(engagement="lab-1", target="10.10.10.5")   # scope = 10.10.10.5/32 (persisted)
skill_suggest()                                           # pick the native skill for the state
scan_quick(target="10.10.10.5")                           # raw output -> evidence; summary returned
web_dir_scan(url="http://10.10.10.5/")                    # repeats are served from the cache
artifact_search("backup") ; artifact_read("ev-…", grep="zip")
finding_add(title=…, target=…, evidence_ids=["ev-…"])     # candidate, never auto-verified
checkpoint_create(reason="completion")

In a new session, engagement_resume() presents the saved state and next steps without executing anything.

Bug-bounty scope setup

Bug-bounty mode fails closed. Without a valid scope, nothing is authorized:

  • exclusions always win;

  • discovered hosts, redirects and CNAMEs never become authorized automatically;

  • intrusive commands are refused.

set_mode(mode="bugbounty")
scope_validate(path="examples/scope.example.yaml")       # validate only, never applied
session_start(engagement="acme", target="app.example.com",
              scope_file="examples/scope.example.yaml")  # stored byte-for-byte with its SHA-256
scope_check(target="https://api.example.com/v1/")

The format and rules for scope files (hosts, wildcards, CIDRs, URL path prefixes, ports, schemes, rate limits, forbidden tools) are described in SCOPE.md.

Skills

Ten native Claude Code skills live in .claude/skills/:

  • engagement-manager

  • ctf-investigator

  • bugbounty-recon

  • network-enumeration

  • web-enumeration

  • api-security

  • active-directory

  • finding-validation

  • evidence-management

  • reporting

skill_suggest() ranks them from the real engagement state, and skill_context('<name>') loads one. Methodology detail is loaded on demand with methodology_show(...). The complete tool reference follows below.

Evidence and artifact storage

Everything is stored per engagement under sessions/<engagement>/, which is local and gitignored:

Path

Contents

raw/

Immutable, content-addressed evidence. Large blobs are stored beside the records.

findings/

Candidate and verified findings (one record per resource).

integrity/manifest.jsonl

The SHA-256 hash chain.

trace.ndjson

The execution trace.

state/

Checkpoint, resume summary and the derived SQLite FTS5 index.

metrics/

Usage and context-efficiency events.

Run evidence_verify(full=True) before calling anything verified, and keep an evidence_anchor(out_path=…) copy outside the engagement directory. See Evidence integrity.

Testing

.venv/bin/python tests/run_all.py

Every suite runs against throwaway session stores and local labs on 127.0.0.1. The runner fails if anything under the real sessions/ changes. v1.0.0 result: 1,334 passed, 0 failed, 6 skipped. The skips are 5 integration checks for scanners that were not installed (feroxbuster, dirsearch, katana, gowitness, gau) and 1 opt-in live Claude Code check. Status and history are in references/PROJECT_STATUS.md.

Security limitations

  • Integrity is not authenticity. The hash chain detects modification, but someone with write access can rebuild the whole chain. Only an anchor exported to an independent location (evidence_anchor) can reveal that.

  • CTF mode is operator-trusted. The supplied target is the engagement's effective scope and is labelled in_scope. Other hosts stay allowed but are labelled unscoped. Bug-bounty mode is the enforcing mode.

  • shell_* runs commands with your local privileges. Its scope check is a tripwire, not a sandbox.

  • Findings are candidates until you verify them. Scanner hits are leads, not vulnerabilities.

  • Not included in v1.0.0: Burp Suite integration, an expanded wordlist manager and further bug-bounty platform API integrations.

  • Authorized use only. You are responsible for holding permission for every target.

Repository layout

engramsec/
├── LICENSE                # PolyForm Shield 1.0.0 (+ Required Notice)
├── CHANGELOG.md
├── version.py             # product name + version (single source)
├── server.py              # MCP entrypoint — registers all tools + the session:// resource
├── dependency_manager.py  # OS/init detection, tool availability, install hints
├── tools_config.yml       # tool -> package name (per distro) + alternatives
├── session.py             # engagement state: target, findings/creds/flags, journal
├── shell.py                # tmux-backed persistent interactive shell sessions
├── writeup.py              # writeup ingestion -> structured steps (heading + code block)
├── htb_api.py              # best-effort HTB v4 API client
├── evidence.py             # P4: immutable evidence store + findings/observations
├── trace.py                # P5: append-only execution trace, replay/resume
├── inventory.py            # P6: engagement-local web endpoint inventory / correlation graph
├── artifacts.py            # artifact list/search/read/metadata/asset_show (read-only, paginated)
├── ratelimit.py            # engagement-wide rate budget shared across processes (leases)
├── scope.py                # central scope policy: YAML scope files, exclusions, URL/port/scheme rules (SCOPE.md)
├── engagement.py           # engagement state: summary, resume, <4 KB checkpoint, hypotheses
├── metrics.py              # usage & token-efficiency metrics (append-only, rotated, per engagement)
├── output_flags.py         # suspicious-output flags (review-only, never findings)
├── artifact_index.py       # derived SQLite FTS5 artifact index (search, relations, integrity checks)
├── scan_cache.py           # shared fingerprinted scan reuse cache (P6 web + P7 services)
├── skills.py               # native Claude Code skill selection, context, validation, context budget
├── evidence_integrity.py   # SHA-256 hash chain, capsule integrity, anchors, tamper detection
├── CLAUDE.md               # Level-1 project guide for Claude Code (< 3 KB)
├── .claude/skills/         # 10 native Claude Code skills (thin entry points, < 2 KB bodies)
├── service_inventory.py    # P7: normalized services (from nmap XML/text), correlation, recommendations
├── cve.py                  # P7: optional, cached, unverified service -> CVE enrichment (NVD)
├── methodology.py          # P8: methodology engine (list/show/next/status/mark), never executes tools
├── methodology/            # P8: catalog.yaml, skill schema, ctf/ + bugbounty/ SKILL.md files, decision trees
├── THIRD_PARTY_NOTICES.md  # OWASP (CC BY-SA 4.0) attribution, cited standards, exclusions
├── cli.py                  # ctf-recon CLI (same core functions as the MCP tools)
├── tools/
│   ├── runner.py           # shared async subprocess runner + NDJSON activity log
│   ├── recon.py            # nmap / rustscan / masscan
│   ├── dns.py              # subdomain_enum / dns_lookup / dns_resolve / dns_zone_transfer
│   ├── web.py              # web_dir_scan (ffuf/feroxbuster/gobuster/dirsearch), ffuf_fuzz, http_probe, nikto
│   ├── webcore.py          # P6 shared core: scope/CNAME gate, rate limiter, safe HTTP client, parsers
│   ├── scope_proxy.py      # per-request scope-enforcing proxy for browsers / katana
│   ├── web_surface.py      # P6: vhost_enum, sitemap_build, endpoint_inventory, http_repeat, http_diff, screenshot_capture
│   ├── jwt_analyze.py      # P6: passive JWT inspection
│   └── services/           # P7: core.py, smb, ftp, snmp, ssh, smtp, ldap (+ber.py), rdp, inventory_api
├── scripts/<area>/*.py     # standalone scripts (thin wrappers over the same core)
├── wordlists/              # tiny bundled fallback wordlists (dirs, vhost prefixes)
├── tests/                  # self-contained suites + local labs (web_lab.py, dns_lab.py, service_lab.py)
├── sessions/<slug>/        # per-engagement state.json + journal.ndjson (gitignored)
├── logs/activity.ndjson    # every dependency resolution + command run (gitignored)
├── requirements.txt
└── .env.example

Tools

Tool

Purpose

dependency_status

Environment (distro/init) + availability of every configured tool. Read-only, never installs.

session_start / session_note / session_set_phase / session_status / session_list

Engagement state: pin a target, log findings/creds/flags, get a compact status brief instead of re-deriving context from scrollback.

shell_open / shell_send / shell_read / shell_list / shell_close

Persistent tmux-backed interactive shell — reverse shells, msfconsole, mysql/ftp prompts, anything one-shot commands can't do.

writeup_load_text / writeup_load_file / writeup_get_steps / writeup_mark_step

(optional writeup group) Load a writeup, get it structured into steps (heading + fenced code blocks), track progress through it.

nmap_scan

Port/service scan. Falls back nmap → rustscan → masscan.

web_dir_scan

Directory / file / extension discovery. Prefers ffuf → feroxbuster → gobuster → dirsearch; response filtering, soft-404 baseline, status + length analysis (P6).

vhost_enum

Host-header virtual-host discovery with response-fingerprint comparison and catch-all dedup (P6).

sitemap_build

robots.txt + sitemap.xml + katana/built-in crawl + JS endpoint extraction + optional gau; parameter inventory (P6).

endpoint_inventory

Query / correlate / link the engagement's endpoint inventory (P6).

http_repeat

Controlled, sanitized, scope-revalidated replay of a captured request (P6).

http_diff

Compare two HTTP responses; comparison stored as evidence (P6).

jwt_analyze

Passive JWT decode + configuration inspection — no brute force, no forgery (P6).

screenshot_capture

gowitness / headless chromium / firefox screenshot into evidence (P6).

ffuf_fuzz

Raw ffuf fuzzing (FUZZ keyword required in the URL). Falls back to wfuzz.

nikto_scan

Web vuln/misconfig scan. Falls back to whatweb (fingerprinting only — not equivalent coverage, see dependency_message).

htb_profile / htb_list_machines / htb_active_machine / htb_machine_profile / htb_submit_flag

(optional htb group) HTB v4 API wrappers. Require HTB_TOKEN.

htb_start_engagement

(optional htb group) Fetch an HTB machine's profile and pin its IP as the session target in one step.

resource session://current

Current engagement's status as JSON, readable without a tool call.

Web enumeration & attack-surface discovery (P6)

Eight tools, one core implementation each, exposed identically as MCP tools, ctf-recon subcommands and standalone scripts under scripts/web/:

MCP tool

CLI

Script

web_dir_scan

ctf-recon web-dir URL [--tool ffuf] [--scan-mode dir|file|ext] [--ext php,bak] [--fc 404] [--fs 0]

scripts/web/web_dir_scan.py

vhost_enum

ctf-recon vhost-enum URL --domain target.htb [--candidates a,b]

scripts/web/vhost_enum.py

sitemap_build

ctf-recon sitemap-build URL [--depth 2] [--katana auto|always|never] [--passive]

scripts/web/sitemap_build.py

endpoint_inventory

ctf-recon endpoint-inventory query|show|stats|params|externals|vhosts|link|add ...

scripts/web/endpoint_inventory.py

http_repeat

ctf-recon http-repeat --evidence-id ev-… | --raw-file req.txt --base-url http://t

scripts/web/http_repeat.py

http_diff

ctf-recon http-diff --url-a … --url-b … | --a ev-… --b ev-…

scripts/web/http_diff.py

jwt_analyze

ctf-recon jwt-analyze TOKEN | --evidence-id ev-…

scripts/web/jwt_analyze.py

screenshot_capture

ctf-recon screenshot URL

scripts/web/screenshot_capture.py

Security model (all enforced in tools/webcore.py, shared by every tool):

  • Scope is checked before every request and re-checked on every redirect hop against the current config; a hop leaving scope is not requested (redirect_blocked). External tools never follow redirects.

  • Bugbounty mode fails closed without a scope. An in-scope hostname whose CNAME chain points outside scope is refused (CNAME boundary).

  • Discovered hosts/vhosts/URLs are recorded with their scope_status but are never added to scope. Out-of-scope references live in external_refs and are never requested.

  • GET/HEAD/OPTIONS only by default; any other method needs approve_state_change=True. Forms are inventoried, never submitted.

  • Engagement-wide rate budget (rate_limit req/s, ratelimit.py): every sender — each external scanner process and each process's native client — holds a lease; leases never sum above the budget, across processes (shared flock'd state in the engagement dir). Scanners are paced at 90% of their lease and a released share cools down for 1 s, so no 1-second window exceeds the budget (verified with 3 concurrent ffuf processes).

  • Screenshots and katana run behind a scope-enforcing proxy (tools/scope_proxy.py): every request — subresources, iframes, redirects, fetch/XHR, JS navigation, CONNECT tunnels — is gated against scope + CNAME boundary and blocked with 403 if out of scope. Browsers are configured so nothing (not even loopback/DNS prefetch/WebRTC) bypasses it; a screenshot whose target never passed the proxy is discarded (bypass detection). gowitness is CTF-only (its Chrome bypasses proxies for loopback).

  • No credential spraying, no brute-force auth, no WAF evasion (fixed honest User-Agent), no exploitation, no JWT key recovery or token forgery.

  • http_repeat strips Authorization/Cookie/API-key/token headers unless include_credentials=True; all returned/traced data is sanitized (headers, sensitive query/body params, JWTs). Raw evidence stays verbatim and local.

Output integration. Every tool stores raw output as immutable P4 evidence (full ffuf/ferox/gobuster/katana output files, every HTTP exchange, screenshots, diffs), upserts the normalized discovery records (pentest-mcp/web-discovery/v1) into sessions/<slug>/web/inventory.json, creates/merges candidate observations (never auto-verified), and emits one P5 trace event referencing all of it. The inventory keeps the correlation chain subdomain → HTTP service → discovery run → endpoint → parameter → observation → finding; endpoint_inventory show walks it.

Token efficiency. Tool responses are compact summaries (counts, top-N, evidence ids). Identical earlier runs are served from the artifact cache (cached: true, pass force=True to re-scan). Use endpoint_inventory (filtered + paginated) and trace_resume (reports inventory counts) instead of re-running scans.

Optional external tools (report-only if missing, with install hints): ffuf, feroxbuster, gobuster, dirsearch, katana, gau, gowitness, chromium / google-chrome / firefox / brave (screenshots). Without katana the built-in crawler is used; without gowitness a headless browser is used.

Tests: .venv/bin/python tests/test_p6_web.py (runs against the local lab in tests/web_lab.py; no internet needed).

Evidence integrity (SHA-256 hash chain)

MCP tool

CLI

Purpose

evidence_verify

ctf-recon integrity verify [--full] [--anchor FILE]

chain + file + capsule + finding + trace checks; exit code 2 on tampering

evidence_integrity_status

ctf-recon integrity status

counts (verified/missing/modified files, valid/invalid capsules, events, head)

evidence_manifest

ctf-recon integrity manifest [--seq-from --event --issues-only]

exports the manifest to a local file and returns a small selective page

evidence_anchor

ctf-recon integrity anchor [--out DIR]

exports the chain head; keep it outside the engagement directory

Scripts: scripts/integrity/*.py.

sessions/<slug>/integrity/manifest.jsonl is an append-only chain of canonical JSON events (sorted keys, compact, UTF-8):

{"v":1,"seq":7,"event":"evidence_created","engagement":"eng","artifact_id":"ev-…","relative_path":"raw/ev-….json",
 "content_sha256":"…","file_size":812,"ts":"…","meta":{"kind":"command","tool":"scan_quick"},
 "prev_hash":"<event_hash of seq 6 | GENESIS>","event_hash":"sha256(canonical(event without event_hash))"}

Event types:

  • evidence_created, blob_created, evidence_adopted (evidence that predates Step 6, after its content address is checked);

  • finding_saved (every add, update or link: findings change only through new events, raw evidence is never touched);

  • capsule_created, checkpoint, trace_snapshot (append-only prefix hash of the trace), export, anchor_exported;

  • tamper_quarantined, tamper_detected, recovery.

What evidence_verify checks:

  • chain continuity, every event hash, prev-hash links, sequence numbers (missing or reordered) and the engagement field;

  • the streamed file SHA-256 of every evidence file, blob, capsule and finding against the latest event, which also catches metadata edits the content address cannot see;

  • the content address (payload hash), as a second, independent check;

  • removed and unrecorded files, and symlinks (including dangling ones);

  • capsules: integrity hash plus every referenced evidence hash;

  • findings referencing missing evidence, or evidence from another engagement;

  • the trace prefix against the last snapshot;

  • optionally, an anchor.

Verification is incremental by default: unchanged files, by (inode, mtime_ns, size), are not re-hashed. --full re-hashes everything.

Results are a compact summary. The full report goes to integrity/reports/; on tampering, a detailed incident goes to integrity/incidents/ and one tamper_detected event is chained per new issue. Original files are never modified, and broken manifests are never rewritten.

Torn records: a torn final record (a crash mid-append) is preserved byte-exact in integrity/torn/ and a recovery event is appended. Valid history is never rewritten.

Proof capsules (capsule format v2) carry:

  • the engagement and finding ids;

  • the evidence ids and each evidence file's (and blob's) SHA-256;

  • execution references (runs, tool) and sanitized reproduction data;

  • integrity_sha256, the SHA-256 of the canonical capsule without its integrity fields.

Building a capsule from evidence that fails a check is refused; a capsule is never silently regenerated. Reading a capsule reports integrity_status: valid | compromised | legacy.

Integration:

  • artifact_read checks both the content address and the manifest hash before serving;

  • the scan cache rejects entries whose evidence changed;

  • explicit checkpoints and the metrics/manifest exports are chained;

  • all verification is metered as Step 3 integrity events (bytes, seconds).

Threat model: see references/PROJECT_STATUS.md. In short, this is integrity (drift and tamper evidence), not authenticity. Anyone with full write access can rebuild a consistent chain; only an anchor stored independently of the engagement directory detects that.

Tests: tests/test_evidence_integrity.py.

Native Claude Code skills & context budget

There are three disclosure levels:

  • Level 1 (always loaded): CLAUDE.md (2.8 KB) plus the native skills' name/description frontmatter (3.5 KB for 10 skills).

  • Level 2 (loaded on demand): one .claude/skills/<name>/SKILL.md (1.5–1.9 KB body), and only the one that is relevant.

  • Level 3 (loaded on demand): methodology_show(id[, section|reference]), only for the ids that skill_context returns. The 67 KB of methodology plus 6 KB of references are never loaded wholesale.

The 10 skills are engagement-manager, ctf-investigator, bugbounty-recon, network-enumeration, web-enumeration, api-security, active-directory, finding-validation, evidence-management and reporting. The registry and the rules for adding a skill are in references/SKILL_REGISTRY.md.

MCP tool

CLI

Purpose

skill_suggest

ctf-recon skills suggest

ranks skills from the engagement's real state (open 445 → network-enumeration, HTTP → web-enumeration, API/JWT → api-security, LDAP/Kerberos → active-directory, candidates → finding-validation, verified → reporting), lists reusable artifacts first, executes nothing

skill_context

ctf-recon skills context <name>

first call of every skill: relevant methodology ids (with reference names), matching methodology_next steps, trees, reuse_first artifacts; flags unnecessary or wrong-mode loads

context_report

ctf-recon context report

measured sizes per level, MCP tool metadata vs the pre-Step-5 baseline, the engagement's skill and methodology loading

—

ctf-recon skills list|validate

registry and file validation

Scripts: scripts/skills/*.py.

MCP metadata: Claude Code 2.1.x already defers MCP tool schemas (ToolSearch), so only tool names stay resident. The reductions apply to what a tool costs when it is loaded:

  • 37 long descriptions shortened, with their security restrictions kept;

  • cosmetic schema title keywords stripped (parameter names are kept);

  • optional anyOf [X, null] collapsed. Server-side pydantic validation is unchanged.

Result: 92 tools / 59,547 B before, 85 tools / 32,478 B by default after Step 5 (−45.5%; about 6.8k tokens, estimated). After Step 6 added the 4 integrity tools: 89 tools / 33,639 B (−43.5%).

Optional groups: the HTB and writeup tools are off by default. Enable them with PENTEST_MCP_TOOL_GROUPS=htb,writeup (or PENTEST_MCP_ENABLE_HTB=1) and restart the server; config_status shows which groups are enabled. Local CTF mode never needs HTB credentials or API calls.

Tests: tests/test_native_skills.py.

Artifact index, search & scan reuse

The filesystem remains authoritative. sessions/<slug>/state/artifact_index.sqlite is a derived index, one per engagement, and can always be rebuilt from the stored files.

MCP tool

CLI

Purpose

artifact_search

ctf-recon artifact search "api admin" [--target --type --tool --finding --service --endpoint --since --until --scope-status --limit --offset --metadata-only]

FTS5 search (bm25 relevance 0..1), compact rows with snippets; --regex uses the old linear scan

artifact_list

ctf-recon artifact list [--doc-type evidence|finding|hypothesis|endpoint|service|capsule|run|all] [--type ...]

rows from the index

artifact_read

ctf-recon artifact read <id> [--field --offset --start-line --grep] [--allow-unverified]

selective, paginated read; evidence integrity verified first

artifact_metadata / asset_show

ctf-recon artifact meta|show <id>

structure, index info, integrity status, references

artifact_related

ctf-recon artifact related <id> [--depth 2]

provenance graph: run, evidence, finding, endpoint, service, hypothesis, capsule

artifact_reindex

ctf-recon artifact reindex [--full]

rebuild from the filesystem; reports integrity issues

artifact_search_history

ctf-recon artifact history

recent searches (redacted)

Scripts: scripts/artifacts/*.py.

What the index holds:

  • Documents: evidence records and blobs, findings (including notes and classification history), proof capsules, hypotheses, P6 endpoints, web services and vhosts, P7 services with enumeration summaries, methodology progress, and trace runs.

  • Contentless FTS5: only the inverted index of sanitized, secret-redacted text is stored. Snippets are cut from the source file at query time for the returned page only.

  • Never indexed: values under sensitive keys (password, token, cookie, community, …), registered secrets, JWTs, bearer tokens and key=value secrets.

  • Relations: derived from existing references (trace, findings, inventories, hypotheses). There is no separately maintained graph.

Keeping it current:

  • Store hooks index new evidence, findings and hypotheses immediately.

  • Before each query, a cheap pass compares (mtime, size); SHA-256 is recomputed only when those change. The append-only trace is indexed from a stored byte offset.

  • Changed or removed raw evidence is recorded as an integrity event.

Recovery: a corrupt, foreign or incompatible database is quarantined (state/corrupt-*) and rebuilt automatically. artifact_reindex --full rebuilds from scratch.

Integrity before serving:

  • artifact_read verifies the evidence content hash. The result is cached per (path, mtime, size) and invalidated by any change.

  • Modified evidence is refused unless allow_unverified=True, in which case the response is marked integrity: modified.

  • Symlinks, ids that would traverse paths, and blob paths outside the engagement are refused.

  • If a content-addressed file is found modified when the same content is stored again, the modified file is preserved in raw/tampered/ (with incidents.ndjson) and the genuine record is written back.

Scan reuse (scan_cache.py, P6 web tools and all 7 P7 enumerators): before probing, an equivalent earlier result is reused.

  • The fingerprint covers:

    • the tool and implementation version;

    • the binary identity (path, size and mtime of the executables);

    • the target, protocol and port;

    • relevant arguments (volatile ones such as observe and timeout are excluded);

    • the wordlist SHA-256;

    • the scope-policy SHA-256;

    • the mode and rate settings;

    • a keyed hash of any supplied credentials, which is never stored.

  • Rules:

    • The scope gate runs before every lookup.

    • Only complete, successful runs are stored.

    • The original evidence must still verify.

    • Entries expire after 24 h (max_age, or PENTEST_MCP_SCAN_CACHE_MAX_AGE).

    • The cache is per engagement only.

  • Bypass: force=True (--force in the CLI).

  • A hit is traced as one op that points at the original run, and is counted in metrics as a duplicate scan avoided.

Tests: tests/test_artifact_index.py.

Usage metrics, token efficiency & output flags

MCP tool

CLI

Purpose

metrics_summary

ctf-recon metrics summary

aggregates plus a token-efficiency analysis

metrics_export

ctf-recon metrics export [--event E] [--since TS] [--fmt ndjson|json|csv]

writes a local file and returns only its path

output_flags_list / output_flags_show

ctf-recon output-flags list|show

suspicious-output flags

output_flag_review

ctf-recon output-flags review <id> acknowledged|false_positive|resolved|open

records a review decision

Scripts: scripts/metrics/*.py. Storage is per engagement in sessions/<slug>/metrics/:

File

Content

events.ndjson

append-only, flock-guarded event log

events-<n>.ndjson.gz

rotated segments (threshold PENTEST_MCP_METRICS_ROTATE_BYTES, default 2 MB)

rollup.json

exact aggregates of the segments, rebuilt from them if corrupt

flags.ndjson

output flags plus appended review records

What is recorded

Collected automatically:

  • Every MCP response: measured serialized bytes, per tool.

  • Tool executions: by status (ran, failed, denied, timeout, missing_dependency).

  • Artifact activity: reads (bytes read from disk vs. bytes returned, full raw retrievals), searches (query stored only as a hash), and index cache hits and misses.

  • Scan cache: hits and misses, i.e. duplicate scans avoided.

  • Methodology loading: bytes loaded.

  • Checkpoint and resume: their sizes.

The summary reads actual bytes stored on disk per store.

Measured vs. estimated

  • Measured: all byte figures.

  • Estimated: token figures, labelled estimated_* and derived with a ~4 bytes/token heuristic. They are not authoritative token counts.

Privacy and isolation

  • Events hold ids, counts and sizes only, through a field whitelist plus secret redaction.

  • No raw output, HTTP bodies, queries or credentials are stored.

  • Metrics never change execution, scope or findings.

Output flags are produced in trace.finalize_tool for every tool. The types are:

  • wildcard_response: web length clusters, wildcard DNS, catch-all vhosts.

  • fake_404: soft-404 calibration, or HTTP 200 with a "not found" title.

  • malformed_output: parser errors, NUL bytes, nmap output without its trailer.

  • large_output: more than 1 MB of raw output.

  • repeated_identical: identical rows within a run, or byte-identical output across targets.

  • unusual_http: 429/503 throttling, mostly 5xx, blanket 403, every row redirecting to the same place.

  • scope_anomaly: denied by scope, off-scope redirects, wordlist filtered by scope.

Every flag carries its type, reason (no raw output), source artifact, run id, timestamp and requires_review. Flags are never vulnerabilities and never create findings. Marking a flag false_positive suppresses identical later flags; they are still recorded and linked to that decision.

engagement_summary includes a compact metrics block. Tests: tests/test_metrics.py.

Engagement state, summary & resume

Continue an investigation in a new session without reloading history or repeating work.

MCP tool

CLI

Purpose

engagement_resume

ctf-recon engagement resume

runs the steps below and executes nothing

engagement_summary

ctf-recon engagement summary

bounded overview with ids for drilling down

checkpoint_create / checkpoint_read

ctf-recon checkpoint create [--reason completion] / read [--markdown]

compact state

hypothesis_add / hypothesis_update / hypothesis_list

ctf-recon hypothesis add|update|list

investigation hypotheses

engagement_resume does the following, in order:

  1. Loads the checkpoint, rebuilding it if missing, corrupt or stale.

  2. Verifies the engagement identity and the scope hash.

  3. Shows key findings and services.

  4. Lists open hypotheses.

  5. Fetches metadata of only the relevant artifacts.

  6. Recommends next steps.

Scripts: scripts/engagement/*.py.

State lives in sessions/<slug>/state/:

File

Content

checkpoint.json

compact JSON, under 4 KB

resume.md

the same state as Markdown, under 4 KB

hypotheses.json

the hypothesis store

progress.json

a larger derived snapshot, not loaded by default

How the checkpoint is kept:

  • It is derived from the trace, findings, inventories, methodology status and hypotheses. It holds counts, ids and one-liners, never raw output. Full history stays in the trace.

  • If it would exceed 4 KB, the lowest-priority lists are trimmed first and recorded in omitted.

  • It refreshes automatically: tool executions and finding, methodology and hypothesis changes go through trace.record, debounced to at most once per second. A read with a newer trace sequence rebuilds it. Session start, resume and completion always rebuild.

  • A missing, corrupt or foreign checkpoint is quarantined and rebuilt. A corrupt hypotheses.json is rebuilt from the hypothesis snapshots recorded in the trace.

Hypotheses:

  • Statuses: proposed, investigating, supported, rejected, inconclusive.

  • Supporting and contradicting evidence references (ev-, fnd-, run-, cap-, ep-, srv-) are validated against the engagement.

  • supported requires supporting evidence and is never set automatically from scanner output.

Scope changes: a change since earlier work is flagged on resume. Recommendations are always computed under the current scope.

Tests: tests/test_engagement_state.py.

Scope policy (bug-bounty scope files)

Bug-bounty engagements start from a YAML scope file:

ctf-recon --mode bugbounty session-start acme app.example.com --scope-file program.yaml

The file is preserved unchanged with its SHA-256, normalized into that engagement only, and enforced by one central policy for every tool.

Rule type

Example

exact host

example.com

label-boundary wildcard, no implicit apex

*.example.com

IPv4/IPv6 address and CIDR

10.0.0.0/24, 2001:db8::/48

URL path scope, segment-boundary matched and traversal-safe

https://app/api/

per-target ports, schemes, rate limits, concurrency, methods, forbidden tools

{target: h, ports: […], rate_limit: …}

Explicit exclusions always win. Redirects are re-validated on every hop, CNAME destinations never expand authorization, and missing or invalid scope fails closed. Concurrent engagements are isolated: the active engagement is pinned per process, and no engagement can inherit another's scope.

Tools: scope_validate, scope_show, scope_check, scope_summary (MCP, ctf-recon scope …, scripts/scope/). Full semantics are in SCOPE.md, with an example in examples/scope.example.yaml. Tests: tests/test_scope.py.

Methodology & skill engine (P8)

Structured testing knowledge for Claude Code. It guides and never executes. The engine reads the engagement's real state and returns recommendations with reasons. Claude Code or the user decides what to run.

The state it reads:

  • the service inventory (P7);

  • the endpoint inventory (P6);

  • findings (P4);

  • the trace (P5);

  • the current mode and scope.

MCP tool

CLI

What it returns

methodology_list

ctf-recon methodology list [--for-mode all] [--category web]

Level-1 metadata of the current mode's skills + decision-tree ids

methodology_show

ctf-recon methodology show ID [--section S] [--reference F]

one SKILL.md (≤ 4 KB), one section, one paged reference file, or a tree

methodology_next

ctf-recon methodology next [--tree tree.network-services]

ranked skills with why (citing the actual ports, endpoints and findings), suggested tool calls, existing artifacts to reuse, blocked / prerequisite / out-of-scope lists; or a decision-tree walk explaining each branch

methodology_status

ctf-recon methodology status [--skill ID] [--validate]

per-skill progress with linked findings/runs and trace-derived activity; catalog validation

methodology_mark

ctf-recon methodology mark ID completed --note … --finding fnd-… --run run-…

persisted status (not_started / in_progress / completed / not_applicable / blocked) + history; traced; finding back-links

Scripts: scripts/methodology/*.py.

Contents:

  • 25 skills: 15 CTF (initial recon, network services, web, AD read-only, Linux/Windows host enumeration, privilege-configuration enumeration) and 10 bug-bounty (scope, assets, web mapping, configuration, API Top 10, authentication, authorization, business logic, input handling, reporting).

  • 9 decision trees: initial recon, network services, web enumeration, authentication, authorization, API, AD, vulnerability verification, finding documentation.

Sources and licensing:

  • Skills cite OWASP WSTG 4.2, the API Security Top 10 2023, ASVS 4.0.3, NIST SP 800-115, RFCs and vendor documentation, each with a version.

  • OWASP-referencing files are CC BY-SA 4.0. See THIRD_PARTY_NOTICES.md and methodology/README.md.

Guarantees:

  • CTF and bug-bounty methodologies are separated and validated.

  • Bug-bounty recommendations fail closed without scope.

  • Out-of-scope targets are excluded.

  • Only enumeration-only MCP tools may be referenced.

  • Methodology bytes served are metered in metrics.ndjson.

Tests: .venv/bin/python tests/test_p8_methodology.py.

Network & service enumeration (P7)

Every nmap_scan / scan_quick / scan_tcp / scan_udp run now also writes nmap XML, normalizes the open services into the engagement service inventory (product, version, CPE, linked to the scan's P5 run id) and returns recommendations — e.g. TCP 445 open → smb_enum, TCP 21 → ftp_enum, UDP 161 → snmp_enum (community must be supplied). Nothing is executed automatically; pick the next step with service_inventory(action="recommend").

MCP tool

CLI

What it does (read-only)

smb_enum

ctf-recon smb-enum HOST

dialects/SMBv1, signing, OS/domain/workgroup, shares, per-share READ check (root ls only), null-session RPC — smbclient, rpcclient, approved nmap scripts, enum4linux-ng (no RID cycling)

ftp_enum

ctf-recon ftp-enum HOST [--list-files]

banner/version, SYST/FEAT, AUTH TLS + cert, anonymous login; listing only with list_files

snmp_enum

ctf-recon snmp-enum HOST --community-env VAR

v3 engine discovery; with a SUPPLIED community / v3 user: versions, system info, interfaces, walks. No guessing, no SET

ssh_enum

ctf-recon ssh-enum HOST

banner/version, KEX/hostkey/cipher/MAC (weak flagged), host-key fingerprints, advertised auth methods (none method, no creds)

smtp_enum

ctf-recon smtp-enum HOST

banner, EHLO caps, STARTTLS + cert, AUTH mechs pre/post TLS; never MAIL/RCPT/VRFY/EXPN/AUTH

ldap_enum

ctf-recon ldap-enum HOST [--authorized-search --base DN]

RootDSE, naming contexts, domain + functional levels, StartTLS/LDAPS cert, supplied bind (TLS only); search only when authorized, size-limited, secrets redacted

rdp_enum

ctf-recon rdp-enum HOST [--nmap]

accepted security protocols, NLA available/required, negotiation flags, certificate

service_inventory

ctf-recon service-inventory list|show|recommend|stats|ingest

normalized services + chain scan → enumeration → observations → CVEs

cve_enrich

ctf-recon cve-enrich --host H --port P [--online]

optional CVE candidates by CPE/version (NVD); offline cache by default; confidence + basis; never "vulnerable"

Standalone scripts: scripts/services/*.py.

Policy (central): scope + CNAME gate before every connection; nmap NSE scripts only from config.NMAP_APPROVED_SCRIPTS (no *-brute, *-vuln-*, psexec/webexec, or smb-enum-shares — it writes a test file); every external binary runs through runner.py under a lease on the shared rate budget (nmap gets --max-rate). No credential spraying, brute force, cracking, relay, exploitation or lateral movement. Credentials are only ever explicitly supplied; they are passed via authfile/stdin where the tool allows, registered as secrets and redacted from command evidence, traces, capsules, the activity log and tool output. CLI credentials: prefer --password-env VAR / --password-stdin (also --community-env, --v3-auth-pass-env, …).

Evidence & correlation: raw command output and protocol transcripts are immutable P4 evidence; configuration/access findings become candidate observations; each enumeration's P5 trace event has the originating Nmap scan as parent_run_id, so trace_replay(run_id=<scan>) shows the follow-ups.

Tests: .venv/bin/python tests/test_p7_services.py — real Samba, OpenSSH and net-snmp daemons (unprivileged, high ports) plus FTP/SMTP/LDAP/RDP emulators (tests/service_lab.py).

Artifact retrieval (token-efficient)

All stored artifacts (immutable evidence, raw scanner files, screenshots, diffs, proxy logs, capsules) are reachable through five read-only tools — MCP, ctf-recon artifact list|search|read|meta|show, and scripts/artifacts/*.py:

Tool

Returns

artifact_list

compact rows (id, kind, tool, target, size, one-line summary), filtered + paginated

artifact_search

ids + field + line + short sanitized snippet (evidence, raw text blobs, finding titles)

artifact_read

one field, paged: chars (offset/limit, ≤20 000), lines (start_line/max_lines) or grep

artifact_metadata

field tree with sizes, hashes, paths, back-references (findings, trace runs, endpoints) — no content

asset_show

binary asset path, mime, size, image dimensions — never the bytes

Large raw output is never pushed into the model context: tools store the complete output as evidence and return a head/tail preview plus context_compacted: {total_chars, evidence_id} (stdout > 6 000 chars, lists

100 items). Everything returned is sanitized; raw evidence on disk stays verbatim.

Run all regression suites: .venv/bin/python tests/run_all.py. Project status and known limitations: references/PROJECT_STATUS.md.

Usage: writeup-guided solving (optional htb,writeup tool group)

These tools are only registered when the server runs with PENTEST_MCP_TOOL_GROUPS=htb,writeup.

  1. htb_start_engagement("Lame") (or session_start("Lame", "10.10.10.5") if you'd rather set the target by hand).

  2. writeup_load_text(text=...) with your writeup — your own notes from a prior solve, or a retired-machine writeup.

  3. writeup_get_steps() to see the structured step list. Walk through it — for each step, decide (you, the AI in this chat) whether to run its commands as-is or adapt them, using nmap_scan / web_dir_scan / shell_open+shell_send / raw commands as appropriate.

  4. writeup_mark_step(index, "done" | "skipped" | "adapted", note=...) as you go, so a later writeup_get_steps() (even in a new session — state is on disk) shows where you left off.

  5. session_note("credential", ...) / session_note("flag", ...) as you find things.

  6. htb_submit_flag(machine_id, flag) when you've got one.

Usage: fully autonomous (no writeup)

Same tools, skip the writeup_* calls — session_start → nmap_scan → reason about the output → web_dir_scan / shell_open / etc. → session_note → repeat. Nothing stops you from asking Claude to just run the loop itself turn after turn in this chat; there's intentionally no separate unattended driver process (a deliberate design choice — you stay in the loop and can redirect at any point, rather than a BoxPwnr-style background process running unattended).

Dependency handling

Default is report-only: a missing tool is reported with the exact install command for your distro's package manager, and a configured alternative is used automatically if one is present on disk. Nothing is installed without you running the command yourself.

To let the server attempt installs itself, set in .env:

PENTEST_MCP_AUTO_INSTALL=1

This uses sudo -n <pkg-mgr> install <pkg> — non-interactive only. If you don't have a NOPASSWD sudo rule for that command, it fails cleanly (no password prompt, no hang) and falls through to the alternative/report path. Supported package managers: pacman (Arch/Artix/Manjaro), apt-get (Debian/Ubuntu/Kali/Parrot), xbps-install (Void), apk (Alpine), emerge (Gentoo — untested).

Add new tools by editing tools_config.yml — no code changes needed unless the CLI syntax differs enough to need translation (see _build_cmd in tools/recon.py / _build_scan_cmd in tools/web.py).

HTB API caveats

HTB doesn't publish official API docs. htb_api.py's convenience methods (get_profile, list_machines, etc.) use commonly-cited v4 paths that may have drifted. If one breaks, use HTBClient.request(method, path, **kwargs) directly and adjust — every response comes back as raw JSON so a wrong assumption fails loudly instead of silently.

Known rough edges

  • ports/extra_args translation between nmap and its fallbacks (rustscan, masscan) is best-effort — verify the actual command in the tool's result.cmd field before trusting a fallback scan's coverage.

  • No Docker-container fallback yet (mentioned as a stretch goal in the original design) — add a docker run --rm <image> ... branch to DependencyManager._attempt_install or a parallel _container_fallback if you want it.

  • No AUR helper (yay/paru) fallback for Arch/Artix packages not in the official repos.

  • logs/activity.ndjson grows unbounded — rotate or truncate it periodically.

  • shell.py requires tmux. Everything else (session, writeup, dependency_status, recon/web tools) works without it.

  • writeup._structure() is intentionally dumb (headings + fenced code blocks only) — a writeup with no markdown structure at all becomes one big step with no commands extracted; that's fine, the AI reading it can still work from the raw prose in steps[0]["prose"].

  • The scope guard in shell_send only regex-matches IPv4 literals against the pinned target string — it won't catch a hostname, a CIDR the target falls inside of, or a command with no IP in it at all. It's a tripwire for the common "wrong terminal" mistake, not a policy engine.

  • The active engagement is pinned per process (read once from sessions/_current.json); set PENTEST_MCP_ENGAGEMENT=<slug> or pass engagement= explicitly when running several engagements in parallel.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      B
      quality
      C
      maintenance
      Enables automated bug bounty reconnaissance such as subdomain enumeration, web fingerprinting, API endpoint extraction, port scanning, and vulnerability scanning with authorization controls inside Claude Code.
      18
      1
      MIT
    • F
      license
      Not graded
      quality
      A
      maintenance
      Enables AI agents to search internet-connected devices, perform IP and host reconnaissance with port, banner and TLS data, run DNS lookups, and retrieve CVE/CPE vulnerability intelligence including CVSS, EPSS and KEV status. It supports credit-aware queries with both stdio and HTTP streaming transports for clients like Claude Code, Codex, Gemini CLI and Claude Desktop.
      -
    • A
      license
      Not graded
      quality
      A
      maintenance
      Enables AI agents to search internet-connected devices, perform IP and hostname reconnaissance (open ports, banners, TLS certificates, DNS records), and retrieve CVE/CPE vulnerability intelligence including CVSS, EPSS, and KEV status. Supports both stdio and HTTP streaming transports and works with Claude Code, Codex, Gemini CLI, and Claude Desktop.
      MIT
    • F
      license
      B
      quality
      B
      maintenance
      Enables AI agents to run passive, boundary, and gated active reconnaissance and web-security CLI tools (nmap, sqlmap, commix, httpx, ffuf, nikto, subfinder, and more) against authorized targets through a persistent, API-key-protected HTTP service. Scope gates, authorization windows, evidence capture, and a full audit trail are enforced in code so every tool call stays within the engagement's declared rules.
      29
      1
      -