Introducing a new way to review your PRs.

Read the announcement

affaan-m / agentshield

AI agent security scanner. Detect vulnerabilities in agent configurations, MCP servers, and tool permissions. Available as CLI, GitHub Action, ECC plugin, and GitHub App integration. 🛡️

View on GitHub

20 documents · Updated Sep 11, 2026

docs / runtime-and-miniclaw-services

Runtime and MiniClaw services

AgentShield provides two related runtime surfaces. The runtime monitor adds policy checks to tool use in a Claude Code settings target. MiniClaw provides a small HTTP agent service with short-lived sessions, a sandbox, a limited tool set, and a dashboard-ready event view. Together they move protection from scan-time advice to controls and visibility during agent use. See Runtime and operations and Reporting, remediation, and monitoring.

Runtime monitor

The runtime monitor is a project-local PreToolUse hook that checks tool calls before they run. It uses .agentshield/runtime-policy.json as its policy source and writes decision records to the configured runtime log. The monitor is installed into the first available settings target: .claude/settings.json, then settings.json, or a new .claude/settings.json path.

Installation lifecycle

Installation creates a valid default policy when none exists and adds one marked AgentShield hook to the settings file. It does not add a second copy when the marker is already present. Uninstall removes only hooks with that marker, so unrelated hooks remain in place. Repair backs up unreadable settings or policy files before restoring a working monitor.

The lifecycle has four operator actions:

ActionSystem result
agentshield runtime installAdd the hook and create a policy if needed.
agentshield runtime statusInspect settings, hook, policy, and log readiness.
agentshield runtime repairBack up invalid runtime files and recreate the monitor.
agentshield runtime uninstallRemove the AgentShield hook from settings.

References: src/index.ts• L1001-1091 src/…/install.ts• L8-15 src/…/install.ts• L90-181 src/…/install.ts• L184-286

Runtime policy

The runtime policy is a version-1 document that describes deny rules, optional rate-limit data, and log settings. A deny rule can match every tool, an exact tool, or a tool-name prefix. It can then deny every call for that tool or deny only input that matches a case-insensitive pattern. The generated policy starts with examples for destructive shell use and remote-script piping, plus a 30-per-minute limit for Bash and Write calls.

The policy loader treats a missing or malformed policy as an allow-all in-process default. Installation and status do not use that fallback as proof of readiness: they require a present policy that passes schema validation. This distinction lets library callers continue with a safe data shape while the CLI can report a broken installation.

References: src/…/types.ts• L3-24 src/…/policy.ts• L6-13 src/…/policy.ts• L15-63 src/…/evaluator.ts• L9-76

Evaluation and audit log

Each tool call is evaluated against deny rules in order. The result is either allow or block, with the tool name, timestamp, and when relevant the matched rule and reason. The evaluator supports exact and simple wildcard tool matches. It uses a case-insensitive regular expression for input patterns and falls back to a text match when the pattern is not valid regular expression syntax.

The evaluation result can be appended as one NDJSON record. A log record keeps the decision and reason with the evaluation duration. A logging error does not change the tool decision, so a broken log path does not silently turn logging into an execution gate.

References: src/…/evaluator.ts• L9-105 src/…/types.ts• L26-54

Runtime health

Status reports whether the monitor can enforce policy, not whether a log entry already exists. It checks the selected settings file, the marked hook count, the policy file, the policy schema, and the resolved log path. With --check, the status command returns success only for ready.

HealthMeaningCheck exit code
readySettings and hook exist, and the policy is valid.0
not_installedNo marked AgentShield hook is present.1
missing_policyThe hook exists but its policy file is absent.1
invalid_policyThe policy file exists but fails validation.2
invalid_settingsThe settings file exists but cannot be parsed.2

References: src/…/status.ts• L15-106 src/…/types.ts• L78-100 src/index.ts• L1037-1065

MiniClaw service

MiniClaw is a local-first HTTP service for running a small, contained agent session. The public entry point can start a server with secure defaults or create a session for embedding in another application. The default service binds to localhost:3847, allows no sandbox network access, limits requests per IP, and limits request size and session duration.

Service surfaces

The server exposes one prompt path and a small control surface around it. Session creation establishes the sandbox and tool permissions. Prompt processing uses an existing session. Session listing, deletion, events, and health support the dashboard and operators without adding other agent entry points.

SurfacePurpose
POST /api/sessionCreate a short-lived sandbox session.
GET /api/sessionList active sessions and their allowed tools.
POST /api/promptProcess a prompt through the security envelope.
DELETE /api/session/:idEnd a session and remove its sandbox.
GET /api/events/:sessionIdRead security events for a session.
GET /api/healthReport that the server is alive and show the active session count.

Requests pass through CORS checks, per-IP rate limiting, and body-size checks before route work. JSON errors use a common error shape. The server does not serve files or accept uploads, which keeps the service surface narrow.

References: src/…/server.ts• L1-17 src/…/server.ts• L183-336 src/…/server.ts• L338-461 src/…/types.ts• L246-286

Prompt routing

The prompt router is the security envelope for the prompt path. It removes hidden characters and known injection or direct-execution fragments from input. It checks session age before work. It then routes the sanitized text through the current deterministic fallback responder and filters response text for system-prompt leakage, stack traces, and unsafe absolute paths.

The current service does not call an external language model. Its fallback response reports the active security context and sanitized prompt. The routing function remains the integration point for a future model while keeping input sanitization, tool checks, and output filtering in the request path.

This diagram shows the order that a prompt follows before the server returns a response and records security events.

flowchart LR
    A[Client prompt] --> B[Request limits and session lookup]
    B --> C[Input sanitization]
    C --> D[Session timeout check]
    D --> E[Fallback responder or future model]
    E --> F[Output filtering]
    F --> G[Response]
    C --> H[Security events]
    D --> H
    F --> H
    H --> I[Session event view]

References: src/…/router.ts• L140-235 src/…/router.ts• L238-300 src/…/router.ts• L302-390 src/…/router.ts• L393-464

Tool permissions

MiniClaw uses a whitelist, which means a tool must be known and enabled for the session before it can run. Tools are grouped by risk so read-only work can be enabled without also granting file changes or shell access. The standard safe session includes read, search, and list; guarded tools add write, edit, and glob; restricted tools include bash, network, and external_api.

Tool calls also receive sandbox-scoped paths before execution and are checked again at the execution boundary. Unknown tools and tools outside the session whitelist produce denied results. The exported whitelist builders give callers a safe default, a safe-plus-guarded mode, or a custom set drawn only from the known registry.

References: src/…/tools.ts• L28-175 src/…/tools.ts• L178-220 src/…/tools.ts• L223-367 src/…/types.ts• L97-156

Sandbox sessions

Each session gets a unique directory below the configured sandbox root and an immutable set of allowed tools. Session directories use owner-only access. Path checks prevent traversal outside the sandbox and reject symlink escapes for existing paths. File extension and size checks limit the kind and amount of data that file tools can handle. Sandbox removal accepts only a direct child of the configured root, which prevents cleanup from deleting the root or a deeper path by mistake. The default network policy is none, with optional localhost or host-allowlist modes.

Sessions are ephemeral. Explicit deletion, server stop, or timeout ends the session and removes its sandbox. Session state and security events stay in memory, so a server restart does not restore prior sessions or their data.

References: src/…/sandbox.ts• L22-152 src/…/sandbox.ts• L154-244 src/…/sandbox.ts• L246-267 tests/…/sandbox.test.ts• L36-87 tests/…/sandbox.test.ts• L233-308

Dashboard interface

The dashboard is a self-contained React component for a consumer application. It creates and ends sessions, submits prompts, displays the response and duration, shows the session's tool whitelist, and refreshes the session's security events after each prompt. It shows idle, active, and error states so the user can see whether the service is ready for input.

The component is embedded from src/…/dashboard.tsx and needs React 18 or later from the consuming application. It is not a separate package export. Its endpoint must point to the MiniClaw server and its browser origin must be allowed by the server's CORS settings.

References: src/…/dashboard.tsx• L1-22 src/…/dashboard.tsx• L272-376 src/…/dashboard.tsx• L370-470 src/…/dashboard.tsx• L490-602 src/…/README.md• L216-239

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the runtime hook marker, install/uninstall behavior, and status hook count aligned. A changed marker can make an installed hook appear absent.
  • Keep the runtime policy schema, generated policy, evaluator, and inline hook command aligned. A field accepted by one path but ignored by another creates a silent policy gap.
  • Keep MiniClaw route names and response shapes aligned with the dashboard fetch calls. A route or field change can leave the UI in an error state without changing the server's health result.
  • Keep tool registry names, whitelist builders, risk labels, and dashboard risk display aligned. New tools must have a clear authorization tier and a matching client display.
  • Keep session cleanup tied to both server state and sandbox deletion. Removing only one side can leave an active-looking session or orphaned files.
  • Keep sandbox network and file limits consistent across MiniClawConfig, CLI options, and the defaults used by embedded callers.

Important failure modes

TriggerConsequenceGuard
Malformed settings.jsonRuntime install and status cannot trust the hook location.Status reports invalid_settings; repair backs up the file before reinstalling.
Missing or invalid runtime policyThe hook cannot be treated as ready for enforcement.Status reports missing_policy or invalid_policy; repair recreates the policy.
Prompt sent with an unknown or expired sessionNo agent work runs for that request.The server returns a client error for an unknown session; the router returns an expired-session response and records a timeout event.
Prompt contains injection or hidden execution textThe unsafe fragment is replaced before routing and an event is recorded.Input sanitization runs before the responder.
Tool is unknown or outside the session whitelistThe call is denied and cannot use the session sandbox.Registry membership and session whitelist checks run before execution.
Path traversal or symlink escapeFile access is refused and a sandbox violation event is created.Path resolution and existing-target symlink checks enforce the sandbox boundary.
Sandbox removal targets the root or a nested pathCleanup is refused instead of deleting outside one session directory.Removal requires a direct child of the configured sandbox root.
Request exceeds size or IP rate limitThe server rejects the request before prompt processing.Request-size and sliding-window rate checks return HTTP 413 or 429.
Server stops while sessions existSessions end; cleanup may leave an orphan only if file removal fails.The stop path removes sessions from memory and attempts recursive sandbox cleanup.

Key files

FileWhy to read it
src/index.tsShows the CLI commands that expose runtime install, repair, uninstall, status, and MiniClaw start.
src/…/install.tsDefines the runtime monitor lifecycle and settings-file selection.
src/…/policy.tsDefines the default runtime policy and policy loading behavior.
src/…/evaluator.tsDefines allow/block decisions and runtime log records.
src/…/status.tsDefines the readiness view used by operators and checks.
src/…/index.tsDefines the public MiniClaw API for standalone and embedded use.
src/…/server.tsDefines the HTTP service and session/control surfaces.
src/…/router.tsDefines the prompt security envelope and current fallback response.
src/…/tools.tsDefines tool risk tiers, whitelist creation, and tool-call authorization.
src/…/sandbox.tsDefines session sandbox creation, path containment, limits, and cleanup.
src/…/dashboard.tsxShows how a React client uses the service and presents its security state.
src/…/types.tsDefines the shared contracts for sessions, prompts, tools, events, and service defaults.