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
  • 0.9ms local process
  • 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 after installation to automatically configure all detected AI CLI agents on your system. It writes the right permissions and tool hints into each agent's config file so you never have to do it manually.

ig setup output
$ ig setup

 Claude Code  → Adds Bash(ig *) permission + Search Tools to CLAUDE.md
 Codex CLI    → Adds Search Tools entry to AGENTS.md
 Gemini CLI   → Manual config: add ig to allowed shell commands in settings.json
 Cursor       → Manual config: add ig to terminal allowlist in .cursor/settings.json
 Windsurf     → Manual config: add ig to shell tool permissions in .windsurf/config.json
Idempotent and non-destructive: running ig setup multiple times is safe — it will never overwrite existing config, only append what is missing. It is also called automatically by install.sh after the binary is installed.

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. Build index at session start
ig index "$PROJECT_ROOT"

# 2. Start daemon for sub-ms queries
ig daemon "$PROJECT_ROOT" &

# 3. Agent can now use ig query for all searches
RESULT=$(ig query --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'

Daemon Mode for High-Frequency Agents

Agents often search the same codebase dozens of times per session. The daemon eliminates repeated index loading overhead.

recommended agent session setup
# 1. At session start: build + start daemon
ig index . && ig daemon . &

# 2. All agent searches use daemon (0.3ms)
ig query --json "$PATTERN" .

# 3. If code changes during session: re-index
ig index .  # daemon auto-detects and hot-reloads

# 4. At session end: daemon exits automatically
~15ms
First query (cold)
with index build
0.9ms
Warm queries
ig search
0.3ms
Daemon queries
ig query

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 cat .ig/tree.txt pre-generated
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

v1.4 — Universal Setup

ig setup now auto-configures four AI agents and installs a full hook suite. Run once after install — idempotent, non-destructive, safe to re-run.

Supported Agents

Agent What ig setup installs
Claude Code 4 hook scripts + 9 hook registrations + permissions + env vars + CLAUDE.md
Codex CLI AGENTS.md
OpenCode AGENTS.md + opencode.json
Cursor ig-search.mdc
💡
New flag — --dry-run: preview what ig setup would write without touching any files. Prints each planned action to stdout so you can review before committing.
ig setup --dry-run

Hook Scripts Installed for Claude Code

Nine hook registrations across four scripts — each targeting a different phase of Claude Code's tool lifecycle.

Hook scripts
  • ig-rewrite.sh — Rewrites shell commands to ig equivalents
  • prefer-ig.sh — Blocks grep/find, suggests ig replacement
  • session-start.sh — Injects project context at session start
  • format.sh — Normalizes output format for token efficiency
Hook registrations (9 total)
  • Grep blocker — blocks direct grep calls
  • npm blocker — enforces bun over npm
  • git blocker — routes git through ig git
  • Secret detection — warns on credential patterns
  • .env warning — flags accidental .env reads
  • SubagentStart context injection
  • TaskCompleted quality gate
ig setup output (v1.4)
$ ig setup

 Claude Code
  → 4 hook scripts installed (ig-rewrite.sh, prefer-ig.sh, session-start.sh, format.sh)
  → 9 hook registrations (grep, npm, git, secret, env, subagent, task gates)
  → Bash(ig *) permission added to settings.json
  → Search Tools section added to CLAUDE.md

 Codex CLI
  → Search Tools entry added to AGENTS.md

 OpenCode
  → Search Tools entry added to AGENTS.md
  → ig tool registered in opencode.json

 Cursor
  → ig-search.mdc rule installed in .cursor/rules/