GH05TCREW/pentestagent
Python TUI agent that plans a task, runs shell, browser and MCP tools through LiteLLM, and records findings as structured JSON notes.
Overview
PentestAgent (v0.2.0) is a single-process Python application. An LLM picks tools in a loop, and those tools are mostly a general terminal (any shell command), a Playwright browser, a notes store and a Tavily web_search. You use it from a Textual TUI with /agent, /crew and /interact modes, from a headless run command, or as an MCP server that other agents can drive.
The design is simple. There is no curated tool catalogue with typed arguments: the model writes shell command lines, and the runtime runs them on the local machine or inside a Docker container. The structure lives in the loop around those calls. A forced planning step comes first, plan steps are tracked with a finish tool, replanning happens when a step fails, and an iteration cap ends the run. Crew mode adds an orchestrator LLM that starts worker agents with the same loop.
Safety is the weak point. The prompts tell the model that permission is granted and that it should not ask. The only hard scope check reads named argument keys such as target or url. It does not look inside a terminal command, which is how almost all scanning happens.
Architecture
flowchart LR
UI["TUI / CLI / MCP server"] --> AG["PentestAgentAgent"]
UI --> CREW["CrewOrchestrator"]
CREW --> POOL["WorkerPool"]
POOL --> AG
AG --> LOOP["BaseAgent._run_loop"]
LOOP --> LLM["LLM (LiteLLM) + ConversationMemory"]
LOOP --> GATE["Workspace scope check"]
GATE --> TOOLS["Tool registry"]
TOOLS --> RT["LocalRuntime / DockerRuntime"]
TOOLS --> NOTES["notes.json"]
TOOLS --> MCP["MCP servers + child agents"]
NOTES --> GRAPH["ShadowGraph (crew)"]
GRAPH --> CREW
| Component | Path | Role |
|---|---|---|
| Agent loop | pentestagent/agents/base_agent.py |
Plan, generate, execute tools, replan, stop; also the assist, interact and MCP loops |
| Main agent | pentestagent/agents/pa_agent/pa_agent.py |
Renders the Jinja prompt with target, scope, RAG context and notes |
| Crew | pentestagent/agents/crew/ |
Orchestrator LLM with spawn_agent, wait_for_agents, formulate_strategy, finish |
| Tools | pentestagent/tools/ |
@register_tool registry: terminal, browser, notes, web_search, finish, MCP-agent spawning |
| Runtimes | pentestagent/runtime/ |
LocalRuntime (host subprocess + Playwright), DockerRuntime (exec_run in a container) |
| Scope | pentestagent/workspaces/ |
YAML workspaces with a targets list; IP/CIDR/hostname matching |
| LLM | pentestagent/llm/ |
LiteLLM wrapper, retry with backoff, token-budget summarisation |
| Knowledge | pentestagent/knowledge/ |
Optional RAG over local files; NetworkX ShadowGraph built from notes |
| MCP | pentestagent/mcp/ |
MCP client manager, RAG tool optimiser, and a server exposing run_task and memory tools |
How a request flows
Take /agent scan the web server on the target in the TUI:
- Reset and plan.
agent_loopclears history and the plan, then enters_run_loop(base_agent.py). On iteration 1,_auto_generate_planmakes a separate LLM call with a singlecreate_plantool and turns the returned strings intoPlanSteps. If that call fails, the whole request becomes one step (base_agent.py). - Generate. Each iteration calls
llm.generatewith the rendered system prompt (plan, notes, RAG context, detected local tools) and the enabled tools. A text-only reply does not end the loop; it is recorded as “thinking” and the loop continues (base_agent.py). - Gate. For each tool call,
_execute_singleloads the active workspace. If there is one, it pulls candidate targets out of the arguments and rejects the call if any candidate is outside the workspace’stargets(base_agent.py). - Execute. Tool calls run concurrently (default 4) unless a tool marks itself unsafe for that, as
browserdoes.terminalpasses the command string toruntime.execute_command.LocalRuntimeusesasyncio.create_subprocess_shellwith a timeout and strips ANSI codes (runtime.py). Output over 50,000 characters is cut down to its head and tail (terminal). - Track. The model is told to call
finish(action="complete" | "skip" | "fail")per step. Afailtriggers_replan, which can declare the task infeasible. When every step is complete or skipped, a final summary call ends the run (base_agent.py). - Stop. Otherwise the loop stops at
PENTESTAGENT_AGENT_MAX_ITERATIONS(default 30; 50 for the crew orchestrator) or on an empty model response (constants.py).
Key components
Plan-enforced loop
The planning step is enforced by the loop, not just by the prompt. The model cannot finish while plan steps are open, and failures go through an explicit replan call. The cost is extra LLM calls. Plans are also shallow: the planner prompt asks for “typically 2-4 steps”, one tool action each.
Tools and runtimes
Tools register themselves with a decorator that stores a name, a JSON schema and an async function (registry.py). If the model sends only flags to terminal, a heuristic adds a likely binary name in front (terminal). DockerRuntime runs bash -c in a bridge-networked container with NET_ADMIN for VPN (docker_runtime.py). Its execute_command ignores the timeout argument and calls the blocking Docker SDK directly from async code (docker_runtime.py). Crew workers always get a fresh LocalRuntime, even when the session was started with --docker (worker_pool.py).
Scope and safety controls
- Prompt. Every mode’s template says the engagement is authorized and tells the model not to ask for permission (pa_agent.jinja). There is no approval step before a command runs.
- Workspace gate.
gather_candidate_targetsreads only top-level keys namedtarget,host,hostname,ip,address,url,hostsortargets(validation.py).terminaltakes acommandstring, so shell commands are never checked. Full URLs failnormalize_target, so abrowsernavigate tohttps://...is rejected while a workspace is active (manager.py). With no active workspace, nothing is checked. --scopeflags (TUI andmcp_server) only reach the prompt template. They do not feed the gate (pa_agent.py).- Exposure.
mcp_server --type ssebinds0.0.0.0:8080by default and exposesrun_task(main.py). The streamable-HTTP transport only checks for a session-id header, so anyone who can reach the port can start agent runs. The Kali compose service isprivileged. - Tested.
tests/security/test_scope_bypass.pycovers the IP/CIDR comparison logic well. It does not cover target extraction, which is where the gap is.
Findings and state
notes is the findings store. It is a notes.json file in the active workspace’s loot directory, or in a global loot/ folder when no workspace is active, with categories (credential, vulnerability, finding, …), confidence, status and structured metadata. Per-category rules reject, for example, a vulnerability with no target or no CVE/weakness (notes). Nothing re-runs a proof or reviews a finding: status and confidence are whatever the model writes. In crew mode, ShadowGraph uses regexes to pull hosts, services and credentials out of the notes and gives the orchestrator path hints (graph.py). Notes persist across sessions and are put back into every system prompt, truncated to 200 characters each. Conversation history and the plan do not persist.
Models and context
LLM wraps litellm.acompletion, so any LiteLLM model string works. Ollama is set up through environment variables (llm.py). There is one model per session, and crew workers share the orchestrator’s LLM object. ConversationMemory summarises older messages once history passes 60% of the token budget and keeps the last 10 (memory.py). Token usage is tracked. There is no cost cap.
Extending it
- New tool: add a module under
pentestagent/tools/with@register_tool. Setmetadata={"supports_concurrent_execution": False}if it holds shared state. - MCP servers: list them in
mcp_servers.json. Above 128 tools, the RAG optimiser swaps them for a retrieval meta-tool.spawn_mcp_agentstarts child PentestAgent processes and mounts their MCP tools in the parent. - Playbooks: subclass
BasePlaybookwith phases and techniques;get_task()turns them into one task prompt. - Knowledge: drop
.txt,.mdor.jsonfiles in the workspace knowledge folder for the optional FAISS RAG.
Running it
Install with the setup script or pip, set PENTESTAGENT_MODEL (there is no default model) and the provider key, then run pentestagent for the TUI or pentestagent run -t <target> <task> headless. --docker runs the main agent’s tools in the pentestagent or Kali image. docker compose can also run the whole app in a container. pentestagent mcp_server --type stdio|sse exposes it to other agents.
Strengths and caveats
- Strength: small and readable. One loop, a handful of tools, and LiteLLM for any provider. It is easy to see what the model was given and what it ran.
- Strength: loop-enforced planning and replanning, with an iteration cap, so runs end predictably.
- Strength: structured notes with schema checks give the crew and graph something better than free text to work from.
- Caveat: scope is not enforced for shell commands. The gate only reads named target keys, needs an active workspace, and never parses
terminalcommands. Treat the workspace target list as advisory and run it in an isolated network. - Caveat: no human approval and no finding validation. The prompts suppress permission checks, and findings are self-reported by the model.
- Caveat: weak isolation by default.
LocalRuntimeis the default and crew workers always use it. The Docker path ignores timeouts. - Caveat: shared summary cache. The summary cache sits on the
LLMobject that crew workers share and is keyed only by message count. Concurrent workers can therefore receive each other’s summaries once their histories pass the threshold. - Caveat: unauthenticated SSE server on all interfaces by default.
Sources: code at 8dde193, verified Q&A.
How it answers the Open-source AI pentest and offensive-security agents questions
Each answer was drafted by a code-reading agent at commit 8dde193. Its citations were checked mechanically. Compare with the other open-source ai pentest and offensive-security agents →
How is the agent loop and planning implemented?
answeredSingle-agent (default) vs crew mode. The primary agent is PentestAgentAgent (agents/pa_agent/pa_agent.py:15), which extends BaseAgent (agents/base_agent.py:142). In crew mode, a CrewOrchestrator (agents/crew/orchestrator.py:19) manages a WorkerPool (agents/crew/worker_pool.py:15) that spawns independent PentestAgentAgent workers, each in its own LocalRuntime for state isolation. The orchestrator calls spawn_agent, wait_for_agents, formulate_strategy, and finish via dedicated crew tools (agents/crew/tools.py:14).
Task planning and tracking. On iteration 1 of the agent loop, _auto_generate_plan() (base_agent.py:816) forces the LLM to decompose the user request into a TaskPlan (tools/finish/__init__.py:44) of PlanStep objects (id, description, status). Steps advance via the finish tool (complete/skip/fail). If a step is marked fail, _replan() (base_agent.py:924) generates a new plan or declares the task infeasible. The loop blocks completion until plan.is_complete() returns true (base_agent.py:474).
Turn structure. The core loop _run_loop() (base_agent.py:316) iterates: (1) LLM generates a response with tool definitions; (2) if the response has tool calls they execute with bounded concurrency (_execute_tools, line 736); (3) text-only responses do NOT terminate the loop — they are treated as thinking aloud (line 365); (4) after tool execution the plan is checked for failures and completeness. This contrasts with assist mode (single LLM call + one tool round, _assist_loop, line 1077), interact mode (streaming chat with tool calls, _interact_loop, line 1175), and MCP mode (autonomous loop terminating on stop with no tools, run_mcp, line 1265).
Stop conditions. The loop exits when: all plan steps are complete (auto-summary generated), a step fails and replanning determines it infeasible, AGENT_MAX_ITERATIONS (default 30 from config/constants.py:67) is reached — emits a forced-stop warning — or the LLM returns an empty response.
How are security tools integrated and executed?
answeredTool registration. Tools self-register via the @register_tool decorator (tools/registry.py:127), which binds a name, description, JSON Schema, category, and executor function into a Tool dataclass (tools/registry.py:35). The loader (tools/loader.py:11) discovers tool modules under pentestagent/tools/ and imports them. Currently registered tools: terminal, browser, notes, web_search, finish, spawn_mcp_agent, despawn_mcp_agent, plus the crew-orchestrator tools (spawn_agent, wait_for_agents, etc.) and the MCP-exposed tools (get_server_status, run_task, store_memory, etc.).
How tools are called. The terminal tool (tools/terminal/__init__.py:35) takes a command string and passes it to runtime.execute_command(). The Runtime abstraction (runtime/runtime.py:353) has two implementations: LocalRuntime (runtime/runtime.py:443) spawns a shell subprocess with asyncio.create_subprocess_shell, strips ANSI codes, and enforces a 300s timeout. DockerRuntime (runtime/docker_runtime.py:39) runs commands inside a Docker container via exec_run(cmd=['bash', '-c', command]), with optional VPN setup and network isolation. Both return structured CommandResult objects (exit_code, stdout, stderr). The terminal tool also attempts auto-prefixing (line 59-129): if the LLM emits flags without a binary name, it heuristically prepends the likely tool (e.g., nmap when -sV is seen).
Browser and web search. The browser tool (tools/browser/__init__.py:61) calls runtime.browser_action(), which uses Playwright (runtime/runtime.py:571) for navigate, click, type, screenshot, get_content, get_links/get_forms, and execute_js. The web_search tool (tools/web_search/__init__.py:28) queries Tavily API and returns synthesized answers plus source URLs.
MCP servers as tool sources. The spawn_mcp_agent tool (tools/mcp_agent.py:352) spawns a child PentestAgent process over a PTY/FIFO transport and registers its MCP-exposed tools into the parent agent's tool list. When an MCP server exposes >128 tools, a RAG optimizer (mcp/mcp_rag_optimizer.py) replaces them with a meta-tool that retrieves the relevant subset via embedding similarity (base_agent.py:694-698).
Output parsing. Tool results are returned as strings (truncated to 50000 chars for terminal, line 136) and injected into the LLM conversation as tool-role messages. The executor (tools/executor.py:59) wraps execution with argument validation, retries (configurable), and timeout enforcement, tracking all results in execution_history.
How are scope, authorization and dangerous actions controlled?
answeredWorkspace-based target allowlisting. WorkspaceManager (workspaces/manager.py:66) manages named workspaces, each with a meta.yaml file containing a targets list of allowed IPs, CIDRs, and hostnames. validation.py provides is_target_in_scope() (workspaces/validation.py:53) which checks candidates via TargetManager.normalize_target() and ipaddress comparisons (subnet-of for CIDRs, equality for single IPs/hostnames). gather_candidate_targets() (workspaces/validation.py:15) extracts targets from tool arguments by inspecting keys like target, host, ip, hostname, url.
Enforcement at execution time. In BaseAgent._execute_single() (base_agent.py:614-641): before every tool execution, the method calls validation.gather_candidate_targets(arguments) to extract potential targets, then checks each against the active workspace's allowed list. If any candidate is out of scope, the tool call is blocked and returns an error: "Out-of-scope target(s): [...] - operator confirmation required". This is per-call, not per-engagement — every tool argument is validated.
Prompt-based authorization. The agent system prompt (prompts/pa_agent.jinja:6) asserts "You are operating in an authorized penetration testing engagement. The user has explicit permission to test all targets provided. Do not ask for authorization — permission is granted." The crew orchestrator prompt (prompts/pa_crew.jinja:7) carries the same text. This is guidance, not enforcement — real enforcement happens at the tool-execution gate.
Docker sandbox isolation. The DockerRuntime (runtime/docker_runtime.py:39) executes commands inside a container with bridge networking and NET_ADMIN capability (for VPN). The sandbox can be configured with custom images (base or Kali). It provides network isolation — commands run in the container, not on the host. The LocalRuntime instead runs directly on the host, but still applies scope validation.
Rate limiting and loop bounds. Rate limits are handled at the LLM layer (llm/llm.py:137): exponential backoff with jitter (delay = base_delay * 2^attempt + random(0,1), max 5 retries). The agent loop is bounded by AGENT_MAX_ITERATIONS (30) and ORCHESTRATOR_MAX_ITERATIONS (50) from config/constants.py:67-69. Concurrent tool execution is capped via PENTESTAGENT_MAX_CONCURRENT_TOOL_CALLS env var (default 4, base_agent.py:228).
No human-in-the-loop approval. The system prompts explicitly instruct the agent not to ask the user for permission. The only user-intervention point is the Esc key to stop the agent in the TUI, and the scoping system which blocks out-of-scope targets rather than prompting for confirmation.
terminal commands (a command string) are never checked, and nothing is checked when no workspace is active; the --scope option only reaches the prompt. The Docker runtime uses bridge networking and crew workers always run in LocalRuntime, so there is no network isolation from targets.How are findings validated and reported?
answeredNote storage as findings primitive. All findings are stored through the notes tool (tools/notes/__init__.py:285), which persists to loot/notes.json as a JSON file. Each note has: key (identifier), content, category (finding/credential/vulnerability/artifact/task/info), confidence (high/medium/low), status (open/closed/filtered/confirmed/potential), and structured metadata fields (target, source, username, password, port, cve, services, technologies, endpoints, weaknesses, evidence_path).
Schema validation per category. The notes tool enforces structural validation (tools/notes/__init__.py:98-113) via declarative rules:
credentialrequiresusername+ (passwordORprotocol) +targetvulnerabilityrequirestarget+ (cveORweaknesses[])findingrequirestarget+ at least one of (services, endpoints, technologies, port)- Host-specific data (services/endpoints/technologies/port) always requires
target. If validation fails the note is rejected with an error message — the LLM sees the error and must fix its input.
No automated re-verification or duplicates. There is no mechanism to re-run a proof-of-concept or verify a finding via a second agent. The status field (open/closed/filtered/confirmed/potential) is set by the agent at creation time and is self-reported. The notes tool rejects duplicate keys on create ("Error: note 'key' already exists. Use 'update' to modify") which prevents accidental duplicate entries but does not detect semantic duplicates (e.g., two keys for the same CVE).
Reporting format. The finish tool's CompletionReport (tools/finish/__init__.py:156) models reports with: status (success/partial/failed), summary, findings list, artifacts list, and recommendations list. In crew mode, the orchestrator's finish tool calls the LLM to synthesize all agent results into a unified summary (agents/crew/tools.py:105-125). The CompletionReport.format_display() produces a human-readable report with status icon, summary, findings, artifact paths, and recommendations. The is_task_complete() sentinel signals completion across the agent loop.
ShadowGraph for derived insights (knowledge/graph.py:46): In crew mode, notes are fed into a NetworkX-backed ShadowGraph that extracts entities (hosts, services, credentials, vulnerabilities) and relationships (AFFECTED_BY, AUTH_ACCESS, HAS_SERVICE, USES_TECH). The graph produces strategic insights for the orchestrator (e.g., "We have credentials that provide access to: ...", attack paths via NetworkX shortest_path). This is advisory only — it does not validate findings.
How is engagement state and knowledge kept across a long run?
answeredPersistent notes store. The primary persistence mechanism is the notes tool, which writes to loot/notes.json (tools/notes/__init__.py:18-23). Notes survive across sessions and are loaded into the agent system prompt on each turn (truncated to 200 chars per note to save tokens, pa_agent.py:86-88). The full content can be retrieved via the notes tool's read action. An asyncio lock (_notes_lock) ensures safe concurrent access from multiple agents.
Workspace-based state. WorkspaceManager (workspaces/manager.py:66) stores per-workspace YAML at workspaces/{name}/meta.yaml containing targets list, creation timestamp, last active timestamp, operator notes, and tool run history. All operations read/write files directly — no in-memory caching. Loot directories are organized under each workspace (loot/, knowledge/sources/, knowledge/embeddings/, notes/, memory/).
Conversation history summarization. ConversationMemory (llm/memory.py:31) manages token budgets. When the conversation exceeds 60% of the token budget (summarize_threshold=0.6), the oldest messages (beyond recent_to_keep=10) are summarized by the LLM itself into a technical summary that preserves targets, versions, credentials, and attack vectors. Summarization is chunked in groups of 10 messages. The cached summary is prepended as a system message on subsequent turns. Token counting uses tiktoken (cl100k_base) with a fallback to word-count estimation.
ShadowGraph (crew mode only). The ShadowGraph (knowledge/graph.py:46) builds a NetworkX directed graph from notes, extracting entities: hosts (via IP regex), services (port/product/version), credentials (username/password), vulnerabilities (CVE/weaknesses), endpoints, and technologies. It produces strategic insights for the crew orchestrator, including attack paths via nx.shortest_path. The graph is rebuilt each orchestrator cycle from the notes.
MCP-level memory. The MCP server provides store_memory/retrieve_memory/clear_memory tools (mcp/server/mcp_tools.py:838-923) as an in-memory key-value store with timestamps and substring search. This is session-scoped and not persisted to disk.
Conversation store (TUI). When a user forks a conversation from the TUI, ConversationStore (interface/conversation_store.py) saves the full conversation to the workspace directory, enabling retrieval and branching while preserving alternative threads.
No engagement resume mechanism. While notes survive to disk, there is no structured facility to reload agent state (conversation history, plan state, worker pool) from a previous session. Each agent_loop() call resets the plan and conversation history (base_agent.py:264).
Which models are supported and how are cost and context managed?
answeredProvider-agnostic via LiteLLM. The LLM class (llm/llm.py:29) wraps litellm.acompletion and supports any provider LiteLLM does, including Anthropic, OpenAI, Google Gemini, Groq, Ollama, and custom endpoints. The model is set via the PENTESTAGENT_MODEL environment variable (config/constants.py:60-62) or the --model CLI flag. get_available_models() (llm/llm.py:417) lists common options including gpt-5, claude-sonnet-4-20250514, gemini-2.5-pro, ollama/llama3, and groq/llama3-70b-8192.
No per-role model selection. Both the single agent and crew orchestrator use the same LLM instance with the same model. Worker agents in crew mode also share the orchestrator's LLM instance (crew/worker_pool.py:114: PentestAgentAgent(llm=self.llm, ...)). The spawn_mcp_agent tool (tools/mcp_agent.py:137) accepts a per-child model override. There is no router or model-specific assignment per role/phase.
Configuration. ModelConfig (llm/config.py:10) provides: temperature (default 0.7), max_tokens (4096), top_p (1.0), frequency/presence penalties, max_context_tokens (128000), retry settings (max_retries=5, exponential backoff), and openai_api_base for routing through custom OpenAI-compatible endpoints. Three presets exist: CREATIVE_CONFIG (0.9 temp), PRECISE_CONFIG (0.1 temp), BALANCED_CONFIG (0.7 temp).
Context-window management. ConversationMemory (llm/memory.py:31) manages the 128K token budget. It reserves 80% for message history (leaving 20% for the response), triggers LLM-based summarization when history exceeds 60% of budget, keeps the 10 most recent messages in full, and truncates from the front if still over budget. get_messages_with_summary() (llm/memory.py:118) is the main entry point: it splits history at the summarize threshold, passes older messages to the LLM for chunked summarization, and prepends the cached summary as a system message on subsequent turns.
Token/cost tracking. Usage is recorded per-response via response.usage (llm/llm.py:241-253) and forwarded to a persistent token_tracker (best-effort, llm.py:256-269). In the orchestrator loop, token usage per phase is yielded as progress events (orchestrator.py:183-184). The worker pool tracks per-worker token consumption and exposes finish_tokens for synthesis costs. There is no explicit cost budget or cap beyond the iteration limit.
Ollama support. When OLLAMA_BASE_URL or OLLAMA_URL is set in the environment, the LLM init populates several environment variable names (OLLAMA_HOST, LITELLM_OLLAMA_BASE_URL, etc.) to support varying LiteLLM/Ollama client conventions (llm/llm.py:57-68). Models are referenced with the ollama/ prefix (e.g., ollama/llama3).