pentest-mcp
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
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.0keep 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:mcpSDK 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(orgobuster/feroxbuster/dirsearch),nikto/whatweb,curl;service enumeration:
smbclient,ssh,snmpwalk,dig;tmux, for the interactiveshell_*tools.The full test suite also needs
named(bind9),smbd,sshdandsnmpdfor 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 --versionClaude 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-managerctf-investigatorbugbounty-reconnetwork-enumerationweb-enumerationapi-securityactive-directoryfinding-validationevidence-managementreporting
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 |
| Immutable, content-addressed evidence. Large blobs are stored beside the records. |
| Candidate and verified findings (one record per resource). |
| The SHA-256 hash chain. |
| The execution trace. |
| Checkpoint, resume summary and the derived SQLite FTS5 index. |
| 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.pyEvery 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 labelledunscoped. 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.exampleTools
Tool | Purpose |
| Environment (distro/init) + availability of every configured tool. Read-only, never installs. |
| Engagement state: pin a target, log findings/creds/flags, get a compact status brief instead of re-deriving context from scrollback. |
| Persistent tmux-backed interactive shell — reverse shells, msfconsole, mysql/ftp prompts, anything one-shot commands can't do. |
| (optional |
| Port/service scan. Falls back nmap → rustscan → masscan. |
| Directory / file / extension discovery. Prefers ffuf → feroxbuster → gobuster → dirsearch; response filtering, soft-404 baseline, status + length analysis (P6). |
| Host-header virtual-host discovery with response-fingerprint comparison and catch-all dedup (P6). |
| robots.txt + sitemap.xml + katana/built-in crawl + JS endpoint extraction + optional gau; parameter inventory (P6). |
| Query / correlate / link the engagement's endpoint inventory (P6). |
| Controlled, sanitized, scope-revalidated replay of a captured request (P6). |
| Compare two HTTP responses; comparison stored as evidence (P6). |
| Passive JWT decode + configuration inspection — no brute force, no forgery (P6). |
| gowitness / headless chromium / firefox screenshot into evidence (P6). |
| Raw ffuf fuzzing ( |
| Web vuln/misconfig scan. Falls back to whatweb (fingerprinting only — not equivalent coverage, see |
| (optional |
| (optional |
resource | 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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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_statusbut are never added to scope. Out-of-scope references live inexternal_refsand 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_limitreq/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_repeatstrips Authorization/Cookie/API-key/token headers unlessinclude_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 |
|
| chain + file + capsule + finding + trace checks; exit code 2 on tampering |
|
| counts (verified/missing/modified files, valid/invalid capsules, events, head) |
|
| exports the manifest to a local file and returns a small selective page |
|
| 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_readchecks 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
integrityevents (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/descriptionfrontmatter (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 thatskill_contextreturns. 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 |
|
| 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 |
|
| first call of every skill: relevant methodology ids (with reference names), matching |
|
| measured sizes per level, MCP tool metadata vs the pre-Step-5 baseline, the engagement's skill and methodology loading |
— |
| 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
titlekeywords 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 |
|
| FTS5 search (bm25 relevance 0..1), compact rows with snippets; |
|
| rows from the index |
|
| selective, paginated read; evidence integrity verified first |
|
| structure, index info, integrity status, references |
|
| provenance graph: run, evidence, finding, endpoint, service, hypothesis, capsule |
|
| rebuild from the filesystem; reports integrity issues |
|
| 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=valuesecrets.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_readverifies 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 markedintegrity: 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/(withincidents.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
observeandtimeoutare 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, orPENTEST_MCP_SCAN_CACHE_MAX_AGE).The cache is per engagement only.
Bypass:
force=True(--forcein 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 |
|
| aggregates plus a token-efficiency analysis |
|
| writes a local file and returns only its path |
|
| suspicious-output flags |
|
| records a review decision |
Scripts: scripts/metrics/*.py. Storage is per engagement in sessions/<slug>/metrics/:
File | Content |
| append-only, flock-guarded event log |
| rotated segments (threshold |
| exact aggregates of the segments, rebuilt from them if corrupt |
| 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 |
|
| runs the steps below and executes nothing |
|
| bounded overview with ids for drilling down |
|
| compact state |
|
| investigation hypotheses |
engagement_resume does the following, in order:
Loads the checkpoint, rebuilding it if missing, corrupt or stale.
Verifies the engagement identity and the scope hash.
Shows key findings and services.
Lists open hypotheses.
Fetches metadata of only the relevant artifacts.
Recommends next steps.
Scripts: scripts/engagement/*.py.
State lives in sessions/<slug>/state/:
File | Content |
| compact JSON, under 4 KB |
| the same state as Markdown, under 4 KB |
| the hypothesis store |
| 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.jsonis 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.supportedrequires 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.yamlThe 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 |
|
label-boundary wildcard, no implicit apex |
|
IPv4/IPv6 address and CIDR |
|
URL path scope, segment-boundary matched and traversal-safe |
|
per-target ports, schemes, rate limits, concurrency, methods, forbidden tools |
|
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 |
|
| Level-1 metadata of the current mode's skills + decision-tree ids |
|
| one SKILL.md (≤ 4 KB), one section, one paged reference file, or a tree |
|
| 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 |
|
| per-skill progress with linked findings/runs and trace-derived activity; catalog validation |
|
| 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.mdandmethodology/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) |
|
| dialects/SMBv1, signing, OS/domain/workgroup, shares, per-share READ check (root |
|
| banner/version, SYST/FEAT, AUTH TLS + cert, anonymous login; listing only with |
|
| v3 engine discovery; with a SUPPLIED community / v3 user: versions, system info, interfaces, walks. No guessing, no SET |
|
| banner/version, KEX/hostkey/cipher/MAC (weak flagged), host-key fingerprints, advertised auth methods ( |
|
| banner, EHLO caps, STARTTLS + cert, AUTH mechs pre/post TLS; never MAIL/RCPT/VRFY/EXPN/AUTH |
|
| RootDSE, naming contexts, domain + functional levels, StartTLS/LDAPS cert, supplied bind (TLS only); search only when authorized, size-limited, secrets redacted |
|
| accepted security protocols, NLA available/required, negotiation flags, certificate |
|
| normalized services + chain scan → enumeration → observations → CVEs |
|
| 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 |
| compact rows (id, kind, tool, target, size, one-line summary), filtered + paginated |
| ids + field + line + short sanitized snippet (evidence, raw text blobs, finding titles) |
| one field, paged: chars ( |
| field tree with sizes, hashes, paths, back-references (findings, trace runs, endpoints) — no content |
| 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.
htb_start_engagement("Lame")(orsession_start("Lame", "10.10.10.5")if you'd rather set the target by hand).writeup_load_text(text=...)with your writeup — your own notes from a prior solve, or a retired-machine writeup.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, usingnmap_scan/web_dir_scan/shell_open+shell_send/ raw commands as appropriate.writeup_mark_step(index, "done" | "skipped" | "adapted", note=...)as you go, so a laterwriteup_get_steps()(even in a new session — state is on disk) shows where you left off.session_note("credential", ...)/session_note("flag", ...)as you find things.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=1This 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_argstranslation between nmap and its fallbacks (rustscan, masscan) is best-effort — verify the actual command in the tool'sresult.cmdfield 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 toDependencyManager._attempt_installor a parallel_container_fallbackif you want it.No AUR helper (
yay/paru) fallback for Arch/Artix packages not in the official repos.logs/activity.ndjsongrows unbounded — rotate or truncate it periodically.shell.pyrequirestmux. 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 insteps[0]["prose"].The scope guard in
shell_sendonly 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); setPENTEST_MCP_ENGAGEMENT=<slug>or passengagement=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…
This server cannot be deployed
Maintenance
Related MCP Connectors
Browser-local and CLI static evidence for deployed AI model artifacts.
Governed security assessments, findings and signed reports for your domains, from your AI agent.
A second brain for Claude: remembers your work, plans your day, encrypted under a key only you hold.
Source-checked CLI guides and model-aware planning for Claude Code, Codex, and Grok Build.
Related MCP Servers
- AlicenseBqualityCmaintenanceEnables automated bug bounty reconnaissance such as subdomain enumeration, web fingerprinting, API endpoint extraction, port scanning, and vulnerability scanning with authorization controls inside Claude Code.181MIT
- FlicenseNot gradedqualityAmaintenanceEnables 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.-
- AlicenseNot gradedqualityAmaintenanceEnables 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
- FlicenseBqualityBmaintenanceEnables 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.291-