Agent Integration

Sub-millisecond codebase search for AI agents, structured JSON output, 35x fewer tokens than reading files.

Why CLI beats MCP

35x
fewer tokens than reading file contents via MCP
MCP file read approach
  • Read entire file to find pattern
  • 1000+ tokens per file
  • Need to guess which files to read
  • Slow: network round-trips
  • Context window fills quickly
ig CLI approach
  • Only matching lines returned
  • ~30 tokens per match
  • Index finds relevant files instantly
  • Sub-10ms local process, no network
  • Structured JSON, easy to parse

Claude Code Integration

Claude Code uses ig as its primary codebase search tool when available. It falls back to ripgrep otherwise. The JSON output lets Claude parse results without regex.

Claude Code uses ig like this
# Claude exploring a new codebase
ig files --json -t rust .                   # list all Rust files
ig symbols --json -t rust .                 # get all function/struct definitions
ig context src/main.rs 42 --json            # read the full function at line 42
ig --json "handleAuth" src/               # search for pattern

# Claude searching for function implementations
ig --json "fn build_covering_ngrams" src/

{
  "matches": [{"file": "src/index/ngram.rs", "line": 142, "text": "pub fn build_covering_ngrams..."}],
  "stats": {"duration_ms": 0.9, "candidates": 2, "matches": 1}
}

# Claude finding all public API surface
ig --json --type rs "^pub (fn|struct|enum|trait)" src/

# Claude finding TODO items before a refactor
ig --json -i "TODO|FIXME|HACK" .
Configuration: ig is configured as a Bash tool in Claude Code's environment. Claude calls ig --json and receives structured results without needing to read full file contents.

ig setup — Zero-Config Agent Setup

Run ig setup (alias ig init) after installation to automatically configure every detected AI CLI agent on your system — 11 agents supported: claude, codex, cursor, copilot, gemini, opencode, windsurf, cline, hermes, kilocode, antigravity.

ig setup output
$ ig setup

 Claude Code  → PreToolUse hook + settings.json patch + Bash(ig *) permission + CLAUDE.md block
 Codex CLI    → AGENTS.md search-tools block
 Cursor       → .cursor/rules/ig-search.mdc (alwaysApply)
 OpenCode     → AGENTS.md + opencode.json
… copilot, gemini, windsurf, cline, hermes, kilocode, antigravity
Flag Effect
--agent NAMETarget one agent instead of all
--showList installed artifacts for the selected agent(s)
--uninstallRemove ig artifacts for the selected agent(s)
--hook-onlyInstall hook scripts / settings.json patches only, skip rule files
--auto-patchCreate missing agent config dirs (default: patch existing only)
--dry-runPreview every planned action without writing
Idempotent and non-destructive: running ig setup multiple times is safe — it never overwrites existing config, only writes the managed block and what is missing. It is also called automatically by install.sh after the binary is installed, and by ig update (as ig setup --quiet) so the config stays aligned with the current binary.

Hook Exit-Code Protocol

The Claude Code PreToolUse hook uses the RTK 0/1/2/3 exit-code protocol, so behaviour is identical to RTK's hooks. Run ig hook-audit to audit installed hooks and the recent permission-verdict histogram.

Exit code Meaning
0Rewrite / allow — command runs (transparently compressed)
1Passthrough — no rewrite, command runs as typed
2Deny — destructive command blocked by the hook
3Ask — rewritten but the user must confirm

Agent-Optimized Commands

Three commands designed specifically for AI agents that need to understand a codebase without reading every file. All support --json for structured output.

ig files --json
List all project files. Replaces find, ls -R, and tree. Respects .gitignore and ig's exclude list.
example
ig files --json -t rust .
ig symbols --json
Extract all symbol definitions — functions, structs, classes, enums. Replaces grepping for ^pub fn or ^class across the codebase.
example
ig symbols --json -t rust .
ig context FILE LINE
Show the full code block surrounding a line — the complete function or struct body. Replaces reading entire files to understand a single definition.
example
ig context src/main.rs 42 --json
agent-optimized workflow example
# Step 1 — get a map of the project
ig files --json -t rust .

# Step 2 — scan all symbol definitions without reading files
ig symbols --json -t rust .

# Step 3 — search for the relevant pattern
ig --json "handleAuth" src/

# Step 4 — read only the precise block you need
ig context src/main.rs 42 --json

Codex and Other Agent Integration

Any agent with shell access can use ig. Build the index once, then query from any agent or script.

agent setup script
#!/bin/bash
# Set up ig for agent use

# 0. Auto-configure agent (run once after install)
ig setup

# 1. Every search is a one-shot process — the index auto-builds
#    on first use and rebuilds inline when stale. No daemon.
RESULT=$(ig --json "$PATTERN" "$PROJECT_ROOT")
echo "$RESULT" | jq '.matches[] | .file + ":" + (.line|tostring)'
Python agent integration
import subprocess, json

def search_codebase(pattern: str, path: str = ".") -> list:
    """Search codebase with instant-grep. Returns list of matches."""
    result = subprocess.run(
        ["ig", "--json", pattern, path],
        capture_output=True,
        text=True
    )
    data = json.loads(result.stdout)
    return data["matches"]

# Usage
matches = search_codebase("async fn", "./src")
for m in matches:
    print(f"{m['file']}: {m['text'].strip()}")

JSON Output Format

The --json flag outputs a single JSON object. Always valid JSON — even with zero matches. Easy to pipe to jq.

full JSON schema
{
  "pattern": "<regex string>",
  "matches": [
    {
      "file":    "<relative path from index root>",
      "line":    <1-based line number>,
      "text":    "<raw line content>",
      "before":  [...context lines]  // only with -B or -C
      "after":   [...context lines]  // only with -A or -C
    }
  ],
  "stats": {
    "duration_ms":    <float>,
    "candidates":    <int — files passing index filter>,
    "files_searched": <int — total files in index>,
    "matches":       <int — total match count>
  }
}
Token count comparison
Read 10 full files (MCP): ~12,000 tokens
ig search --json (10 matches): ~350 tokens
Savings: 35x fewer tokens
jq recipes for agents
file:line list
ig --json "pat" . | jq '.matches[] | "\(.file):\(.line)"'
just file paths
ig --json "pat" . | jq '[.matches[].file] | unique'

Search Latency

Every ig command is a one-shot process — there is no daemon to start or keep alive. The first search on a project pays a cold-cache cost (and an inline index build if none exists); subsequent searches in the same shell session hit the warm OS page cache and match the old daemon hot-path numbers.

~5-15ms
First query (cold)
+ inline index build if needed
2-8ms
Warm queries
OS page cache resident
<1ms
Zero-result search
trigram short-circuit

Token Optimization

Beyond fast search, ig reduces token consumption through smart file reading, compact listings, and pre-generated project context.

new commands (v1.2.0)
# Compact directory listing (81% fewer tokens vs ls -la)
ig ls src/

# Smart file reading — signatures + imports only
ig read src/main.rs --signatures

# 2-line summary per file (role + public API)
ig smart src/

# Generate project context for AI agents
ig pack  # writes .ig/context.md (auto-generated on ig index)

# Token savings dashboard
ig gain

ig setup installs a PreToolUse hook that transparently rewrites shell commands to ig equivalents:

Agent command Rewritten to Token savings
cat file.ts ig read file.ts +line numbers
grep -rn pattern . ig "pattern" indexed, sub-ms
ls -la src/ ig ls src/ 81% fewer bytes
tree ig tree capped depth, gitignore-aware
find . -name "*.ts" ig files --glob "*.ts" indexed listing
Benchmark: project exploration (1,285-file Next.js app)
18s
ig
4 turns · $0.15
19s
RTK
4 turns · $0.15
45s
Baseline
2 turns · $0.30

Migrating from RTK

As of v2.0.0, ig ships feature parity with rtk — the same command-output filtering, the same 0/1/2/3 hook exit-code protocol, plus a trigram search engine RTK does not have. Switching is two commands.

RTK → ig
# 1. Translate your RTK filter files into ig's format
ig import-rtk             # reads ~/.config/rtk/filters.toml + ./.rtk/filters.toml
ig import-rtk --dry-run   # preview the translation first

# 2. Re-install agent hooks for ig (replaces RTK's)
ig setup                 # or: ig setup --import-rtk to do both at once

RTK filter fields (match, strip_ansi, keep, drop, truncate, head, tail, …) map 1:1. RTK-only features that ig already covers with a native Rust parser (e.g. ig vitest, ig go-test) are skipped with a comment. See the full migration guide.