Skip to content

API Reference parrot_tools.tool_optimizations.hooks

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot_tools.tool_optimizations.hooks

View source

Opt-in host read guards for Claude Code and Codex (FEAT-543).

A PreToolUse hook that denies unbounded reads of large files and replies with the exact bounded-reader call to make instead. It uses the same thresholds as the MCP reader, and it is a convenience, not an enforcement boundary: the reader's own limits hold regardless of whether this hook is installed.

Scope is deliberately narrow and honestly documented (see :func:coverage_matrix). v1 understands Claude's structured Read tool and a small literal shell subset (cat, head, tail, less, more). Anything else — command substitution, redirection, globs, compound statements, other interpreters — produces no decision, and the host behaves normally. A pipe never makes a large read safe: the reading segment decides.

SDD command instructions under .claude/commands/sdd-*.md are exempt: hosts must be able to load the complete workflow in one read. This exception does not change the bounded MCP reader's limits.

Two invariants:

  • This module never breaks a host session. Any exception, malformed payload, or unreadable file results in exit 0 with no output.
  • This module is stdlib-only at import. No pydantic, no parrot.*. A hook runs on every tool call, so its import cost must stay negligible.

Run as::

python -m parrot_tools.tool_optimizations.hooks --host claude
python -m parrot_tools.tool_optimizations.hooks --host codex

Attribute DENY_VALUE

Class GuardDecision

The guard's verdict for one tool call.

Parameter Type Default Description
deny bool False
reason str ''
path Optional[str] None
lines Optional[int] None
size Optional[int] None
coverage str 'not_applicable'

Fields:

Field Type Default Description
deny bool False True when the call should be blocked.
reason str '' The message shown to the assistant.
path Optional[str] None The file the decision is about, if any.
lines Optional[int] None The file's line count, when it was counted.
size Optional[int] None The file's size in bytes.
coverage str 'not_applicable' Which rule produced the verdict — structured, shell, unrecognized or not_applicable.

Class GuardPolicy

Thresholds and reader identity used by the guard.

Parameter Type Default Description
max_lines int 350
large_file_bytes int 64000
reader_server str 'parrot-bounded-source'
tool str 'source_read'

Fields:

Field Type Default Description
max_lines int 350 Line threshold above which a read must be bounded.
large_file_bytes int 64000 Byte threshold above which a read must be bounded.
reader_server str 'parrot-bounded-source' MCP server name to recommend in a denial.
tool str 'source_read' Bounded-reader tool name to recommend in a denial.

Method GuardPolicy.load

Load thresholds from <root>/.parrot/tool-guards.json.

Any problem — missing file, bad JSON, wrong types — falls back to the defaults rather than failing the host's tool call.

load(root: Path) -> GuardPolicy

Parameter Type Default Description
root Path The repository root reported by the host.

Returns: GuardPolicy — The effective policy.

Function build_reason

Build the denial message, naming the exact call to make instead.

build_reason(decision: GuardDecision, policy: GuardPolicy, cwd: Optional[Path] = None) -> str

Parameter Type Default Description
decision GuardDecision The denial being explained.
policy GuardPolicy The active policy.
cwd Optional[Path] None The host's working directory, used to relativize the path.

Returns: str — A concise, actionable reason.

Function count_lines_bounded

Count logical lines, stopping early once the bound is exceeded.

This intentionally duplicates :func:parrot_tools.tool_optimizations.reader.count_lines_bounded. Importing the reader would pull pydantic into a hook that runs on every tool call; twenty stdlib lines are cheaper than that. A test asserts the two implementations agree.

count_lines_bounded(path: Path, stop_after: int) -> tuple[int, bool]

Parameter Type Default Description
path Path The file to count.
stop_after int The threshold to compare against.

Returns: tuple[int, bool] — A (count, exceeded) tuple; when exceeded the exact count is unknown and count is stop_after + 1.

Function coverage_matrix

Return the honest, machine-readable coverage table.

Publishing what the guard does not intercept is deliberate: a guard that appears total but is not creates a false sense of enforcement.

coverage_matrix() -> list[dict[str, Any]]

Returns: list[dict[str, Any]] — Rows of {"form", "covered", "note"}.

Function evaluate_read

Evaluate Claude Code's structured Read tool.

evaluate_read(tool_input: dict[str, Any], cwd: Path, policy: GuardPolicy) -> GuardDecision

Parameter Type Default Description
tool_input dict[str, Any] The host's tool_input mapping.
cwd Path The host's working directory.
policy GuardPolicy The active policy.

Returns: GuardDecision — The guard's verdict.

Function evaluate_shell

Evaluate a shell command against the documented reader subset.

evaluate_shell(command: str, cwd: Path, policy: GuardPolicy) -> GuardDecision

Parameter Type Default Description
command str The raw shell command.
cwd Path The host's working directory.
policy GuardPolicy The active policy.

Returns: GuardDecision — The guard's verdict. Unrecognised commands yield unrecognized, which renders no output.

Function is_large

Decide whether a file exceeds either configured threshold.

Only file metadata and newline counts are inspected; contents are never loaded.

is_large(path: Path, policy: GuardPolicy) -> tuple[bool, Optional[int], int]

Parameter Type Default Description
path Path The file to inspect.
policy GuardPolicy The active policy.

Returns: tuple[bool, Optional[int], int] — A (large, line_count_or_None, size_bytes) tuple. line_count is None when counting stopped early.

Raises:

  • OSError — The path is unreadable.
  • ValueError — The path is not a regular file.

Function main

Run the guard over one hook payload.

Always returns 0. A denial is communicated by the printed JSON, never by the exit code, and any internal failure results in silence — a broken guard must not break the host session.

main(argv: Optional[list[str]] = None, stdin: Any = None, stdout: Any = None) -> int

Parameter Type Default Description
argv Optional[list[str]] None Command-line arguments.
stdin Any None Input stream carrying the hook JSON.
stdout Any None Output stream for the decision.

Returns: int — Always 0.

Function parse_shell_subset

Parse a command if — and only if — it is in the documented subset.

parse_shell_subset(command: str) -> Optional[list[list[str]]]

Parameter Type Default Description
command str The raw shell command.

Returns: Optional[list[list[str]]] — Pipeline segments as argv lists, or None when the command uses any construct outside the subset (in which case the guard makes no decision at all).

Function render_output

Render a host-appropriate hook response.

Both hosts use deny within the hookSpecificOutput envelope.

render_output(decision: Optional[GuardDecision], host: str) -> Optional[str]

Parameter Type Default Description
decision Optional[GuardDecision] The guard's verdict, if any.
host str claude or codex.

Returns: Optional[str] — The JSON to print, or None when there is no decision to report.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally