Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

feat: add ix Claude Code plugin with hook-based auto-ingest and search intercept

kagebinary0a8313075b86
diff --git a/docs/claude-plugin/README.md b/docs/claude-plugin/README.md
new file mode 100644
index 00000000..a94f826c
--- /dev/null
+++ b/docs/claude-plugin/README.md
@@ -0,0 +1,50 @@
+# Claude Code Plugin — Developer Guide
+
+A Claude Code plugin can use **hooks**, **MCP servers**, or both depending on
+what behavior you need. Read [hooks-vs-mcp.md](./hooks-vs-mcp.md) first if you
+are unsure which to use.
+
+The Ix Memory plugin (`ix-plugin/`) uses hooks only — see
+[ix-plugin-reference.md](./ix-plugin-reference.md) for the concrete implementation.
+
+## Contents
+
+### Decision Guide
+| File | Description |
+|------|-------------|
+| [hooks-vs-mcp.md](./hooks-vs-mcp.md) | When to use hooks vs MCP — the front-run pattern, blocking, additionalContext |
+
+### Ix Plugin (Hooks-Based)
+| File | Description |
+|------|-------------|
+| [ix-plugin-reference.md](./ix-plugin-reference.md) | The actual Ix Memory plugin — structure, hooks, scripts |
+
+### MCP Server Reference
+| File | Description |
+|------|-------------|
+| [overview.md](./overview.md) | What MCP is, how Claude Code loads MCP servers, core concepts |
+| [capabilities.md](./capabilities.md) | Tools, Resources, and Prompts — definitions and schemas |
+| [configuration.md](./configuration.md) | Registering and configuring an MCP server with Claude Code |
+| [error-handling.md](./error-handling.md) | Protocol errors vs. execution errors, best practices |
+| [security.md](./security.md) | Permissions model, OAuth, user consent requirements |
+| [testing.md](./testing.md) | How to test and debug an MCP server |
+| [example-typescript.md](./example-typescript.md) | Minimal working TypeScript MCP server |
+| [example-python.md](./example-python.md) | Minimal working Python MCP server |
+
+## Quick Decision
+
+**Want automatic behavior with no user approval?** → Use hooks.
+- File change tracking → `PostToolUse` on `Write|Edit`
+- Front-run native searches → `PreToolUse` on `Grep|Glob`
+
+**Want Claude to call a function on demand?** → Use MCP tools.
+- Requires user approval per call
+- Claude decides when to invoke based on context
+
+## Key Facts (MCP)
+
+- Protocol: **JSON-RPC 2.0** over stdio, HTTP, or SSE
+- Official SDKs: **TypeScript** (`@modelcontextprotocol/sdk`) and **Python** (`mcp`)
+- Three capability types: **Tools** (LLM-invoked), **Resources** (data context), **Prompts** (user commands)
+- Schema format: **JSON Schema Draft 2020-12**
+- All tool invocations require **explicit user approval**
diff --git a/docs/claude-plugin/capabilities.md b/docs/claude-plugin/capabilities.md
new file mode 100644
index 00000000..f622a404
--- /dev/null
+++ b/docs/claude-plugin/capabilities.md
@@ -0,0 +1,260 @@
+# Capabilities — Tools, Resources, and Prompts
+
+## Tools (Model-Controlled Functions)
+
+Tools are functions the LLM can discover and call based on task context. The LLM decides
+when to call them; the user must approve each invocation.
+
+### Tool Definition
+
+```json
+{
+ "name": "get_user_by_id",
+ "title": "Get User Information",
+ "description": "Retrieves user details by user ID",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "user_id": {
+ "type": "string",
+ "description": "The user's unique identifier"
+ },
+ "include_details": {
+ "type": "boolean",
+ "description": "Include detailed information"
+ }
+ },
+ "required": ["user_id"]
+ }
+}
+```
+
+### Tool Name Rules
+
+- Characters: A–Z, a–z, 0–9, underscore `_`, hyphen `-`, dot `.`
+- Length: 1–128 characters
+- Case-sensitive
+- Must be unique within the server
+- Examples: `getUser`, `fetch_data`, `admin.tools.list`
+
+### Tool Result Content Types
+
+**Text:**
+```json
+{ "type": "text", "text": "Result text" }
+```
+
+**Image:**
+```json
+{ "type": "image", "data": "<base64>", "mimeType": "image/png" }
+```
+
+**Resource link:**
+```json
+{
+ "type": "resource_link",
+ "uri": "file:///path/to/file",
+ "name": "File Name",
+ "mimeType": "text/plain"
+}
+```
+
+**Embedded resource:**
+```json
+{
+ "type": "resource",
+ "resource": { "uri": "file:///path", "mimeType": "text/plain", "text": "Content" }
+}
+```
+
+### Returning a Tool Result
+
+```json
+{
+ "jsonrpc": "2.0",
+ "id": 2,
+ "result": {
+ "content": [
+ { "type": "text", "text": "Operation completed successfully." }
+ ]
+ }
+}
+```
+
+For errors the LLM should see and self-correct from, set `isError: true` in the result
+(not as a JSON-RPC error). See [error-handling.md](./error-handling.md).
+
+### Output Schema (Optional)
+
+Declare expected output structure for validation:
+
+```json
+{
+ "outputSchema": {
+ "type": "object",
+ "properties": {
+ "status": { "type": "string", "enum": ["success", "error"] },
+ "count": { "type": "integer" }
+ },
+ "required": ["status"]
+ }
+}
+```
+
+---
+
+## Resources (Application-Controlled Context)
+
+Resources provide contextual data — files, schemas, documentation — to the LLM.
+The application (Claude Code) controls when they are included; the LLM does not
+call resources directly.
+
+### Resource Definition
+
+```json
+{
+ "uri": "file:///project/src/main.rs",
+ "name": "main.rs",
+ "title": "Application Entry Point",
+ "description": "Primary Rust source file",
+ "mimeType": "text/x-rust",
+ "size": 2048,
+ "annotations": {
+ "audience": ["assistant"],
+ "priority": 0.9,
+ "lastModified": "2025-03-14T10:30:00Z"
+ }
+}
+```
+
+### Resource Content
+
+Text resource:
+```json
+{ "uri": "file:///example.txt", "mimeType": "text/plain", "text": "File contents" }
+```
+
+Binary resource:
+```json
+{ "uri": "file:///image.png", "mimeType": "image/png", "blob": "<base64>" }
+```
+
+### URI Templates (Parameterized Resources)
+
+Servers can expose templates using URI templates (RFC 6570):
+
+```json
+{
+ "uriTemplate": "file:///{path}",
+ "name": "Project Files",
+ "description": "Access any file in the project",
+ "mimeType": "application/octet-stream"
+}
+```
+
+### Annotations
+
+| Field | Values | Meaning |
+|-------|--------|---------|
+| `audience` | `["user"]`, `["assistant"]`, or both | Who the resource is for |
+| `priority` | 0.0 – 1.0 | Importance (1.0 = most important) |
+| `lastModified` | ISO 8601 timestamp | When the resource was last changed |
+
+### Common URI Schemes
+
+- `file://` — Filesystem-like resources
+- `git://` — Version control resources
+- `https://` — Web resources
+- Custom schemes (must follow RFC 3986)
+
+---
+
+## Prompts (User-Controlled Templates)
+
+Prompts are templated messages invoked by the user — similar to slash commands.
+The user explicitly triggers a prompt; no additional approval is needed.
+
+### Prompt Definition
+
+```json
+{
+ "name": "code_review",
+ "title": "Request Code Review",
+ "description": "Analyzes code and suggests improvements",
+ "arguments": [
+ {
+ "name": "code",
+ "description": "Code to review",
+ "required": true
+ },
+ {
+ "name": "language",
+ "description": "Programming language",
+ "required": false
+ }
+ ]
+}
+```
+
+### Prompt Response (Messages)
+
+```json
+{
+ "description": "Code review prompt",
+ "messages": [
+ {
+ "role": "user",
+ "content": {
+ "type": "text",
+ "text": "Please review this {{language}} code:\n\n{{code}}"
+ }
+ }
+ ]
+}
+```
+
+### Prompt Message Content Types
+
+- `text` — Plain text message
+- `image` — Base64-encoded image (`data` + `mimeType`)
+- `audio` — Base64-encoded audio (`data` + `mimeType`)
+- `resource` — Embedded resource with URI and content
+
+---
+
+## JSON Schema Reference
+
+MCP uses **JSON Schema Draft 2020-12** by default. Specify an explicit version with:
+
+```json
+{ "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", ... }
+```
+
+Tool with no parameters:
+```json
+{ "inputSchema": { "type": "object", "additionalProperties": false } }
+```
+
+Complex nested input:
+```json
+{
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "filters": {
+ "type": "object",
+ "properties": {
+ "date_range": {
+ "type": "object",
+ "properties": {
+ "start": { "type": "string", "format": "date" },
+ "end": { "type": "string", "format": "date" }
+ },
+ "required": ["start", "end"]
+ }
+ }
+ }
+ }
+ }
+}
+```
diff --git a/docs/claude-plugin/configuration.md b/docs/claude-plugin/configuration.md
new file mode 100644
index 00000000..48b09281
--- /dev/null
+++ b/docs/claude-plugin/configuration.md
@@ -0,0 +1,135 @@
+# Configuration — Registering a Plugin with Claude Code
+
+## Method 1: CLI Commands (Recommended for Development)
+
+```bash
+# Stdio server (local process)
+claude mcp add --transport stdio my-server -- node /path/to/server.js
+
+# HTTP server (remote)
+claude mcp add --transport http my-api https://api.example.com/mcp
+
+# With environment variables
+claude mcp add --transport stdio db-server --env DB_URL=postgres://... -- python server.py
+
+# With authentication headers
+claude mcp add --transport http secure-api --header "Authorization: Bearer token" https://api.example.com/mcp
+```
+
+## Method 2: .mcp.json (Recommended for Distribution)
+
+Place `.mcp.json` in your project root. This is checked into version control so
+all contributors get the plugin automatically.
+
+```json
+{
+ "mcpServers": {
+ "my-server": {
+ "command": "node",
+ "args": ["/path/to/server.js"],
+ "env": {
+ "API_KEY": "${API_KEY}",
+ "DEBUG": "true"
+ }
+ },
+ "remote-api": {
+ "type": "http",
+ "url": "https://api.example.com/mcp",
+ "headers": {
+ "Authorization": "Bearer ${MCP_TOKEN}"
+ }
+ }
+ }
+}
+```
+
+## Scopes
+
+| Scope | Location | Who Sees It |
+|-------|----------|-------------|
+| `local` | `~/.claude.json` | Only you, not committed |
+| `project` | `.mcp.json` in project root | All contributors via git |
+| `user` | User-level config | You, across all projects |
+
+```bash
+claude mcp add --scope local my-server -- node server.js # local only
+claude mcp add --scope project my-server -- node server.js # project-wide
+claude mcp add --scope user my-server -- node server.js # all projects
+```
+
+## Environment Variable Expansion
+
+Supported inside `.mcp.json`:
+
+```json
+{
+ "mcpServers": {
+ "db": {
+ "command": "${PYTHON_PATH:-python}",
+ "args": ["server.py"],
+ "env": {
+ "DB_URL": "${DATABASE_URL}",
+ "LOG_LEVEL": "${LOG_LEVEL:-info}"
+ }
+ }
+ }
+}
+```
+
+- `${VAR}` — expands to environment variable
+- `${VAR:-default}` — fallback if not set
+- `${CLAUDE_PLUGIN_ROOT}` — directory of the plugin itself
+
+## OAuth Configuration
+
+For servers requiring OAuth 2.0 authentication:
+
+```bash
+# Add the server
+claude mcp add --transport http myauth https://api.example.com/mcp
+
+# In Claude Code, trigger authentication
+/mcp
+# Follow the browser login flow
+```
+
+Pre-configured client credentials:
+```bash
+claude mcp add --transport http \
+ --client-id your-client-id \
+ --client-secret \
+ --callback-port 8080 \
+ my-server https://api.example.com/mcp
+```
+
+In `.mcp.json`:
+```json
+{
+ "mcpServers": {
+ "my-server": {
+ "type": "http",
+ "url": "https://api.example.com/mcp",
+ "oauth": {
+ "clientId": "your-client-id",
+ "callbackPort": 8080,
+ "authServerMetadataUrl": "https://auth.example.com/.well-known/openid-configuration"
+ }
+ }
+ }
+}
+```
+
+Credentials are stored in the system keychain — never in config files.
+
+## Managing Servers
+
+```bash
+claude mcp list # List all configured servers
+claude mcp get my-server # Show details for one server
+claude mcp remove my-server # Remove a server
+```
+
+Inside Claude Code:
+```
+/mcp # View all servers, status, capabilities, and authentication
+```
diff --git a/docs/claude-plugin/error-handling.md b/docs/claude-plugin/error-handling.md
new file mode 100644
index 00000000..2889c6eb
--- /dev/null
+++ b/docs/claude-plugin/error-handling.md
@@ -0,0 +1,87 @@
+# Error Handling
+
+MCP has two distinct error categories. Using the right one matters — they serve
+different purposes.
+
+## Protocol Errors (Invalid Requests)
+
+Use JSON-RPC errors for malformed requests, unknown methods, or server crashes.
+The LLM cannot self-correct from these.
+
+Standard JSON-RPC error codes:
+
+| Code | Meaning | When to Use |
+|------|---------|-------------|
+| `-32602` | Invalid params | Unknown tool name, malformed input |
+| `-32603` | Internal error | Unexpected server crash |
+| `-32002` | Resource not found | Missing resource URI |
+
+```json
+{
+ "jsonrpc": "2.0",
+ "id": 1,
+ "error": {
+ "code": -32602,
+ "message": "Unknown tool: invalid_tool_name"
+ }
+}
+```
+
+## Tool Execution Errors (Actionable Feedback)
+
+When a tool runs but fails in a way the LLM can learn from (bad input values,
+business logic violations), return the error **inside the result** with `isError: true`.
+Claude Code shows this to the LLM and it can retry.
+
+```json
+{
+ "jsonrpc": "2.0",
+ "id": 2,
+ "result": {
+ "content": [
+ {
+ "type": "text",
+ "text": "Error: User ID must be numeric. Got: 'abc'. Try again with an integer ID."
+ }
+ ],
+ "isError": true
+ }
+}
+```
+
+## Decision Rule
+
+```
+Is the request malformed / un-parseable?
+ → JSON-RPC error (code field)
+
+Did the tool run but produce a failure the LLM should know about?
+ → Result with isError: true
+```
+
+## Best Practices
+
+1. **Validate inputs before processing** — check schema constraints before doing any work
+2. **Include context in errors** — name the bad field and the expected type/format
+3. **Distinguish actionable from fatal** — only use `isError: true` when the LLM can fix it
+4. **Log to stderr, not stdout** — stdout is reserved for JSON-RPC messages
+5. **Set timeouts** — use `MCP_TIMEOUT` env var or implement per-operation deadlines
+6. **Rate limit** — implement backpressure for expensive tools
+
+## Timeout Configuration
+
+```bash
+MCP_TIMEOUT=10000 claude # 10 second timeout per tool call
+```
+
+## Logging
+
+Write all debug output to **stderr**. stdout must contain only valid JSON-RPC:
+
+```typescript
+// Correct
+console.error("Debug: processing request", requestId);
+
+// Wrong — pollutes the JSON-RPC stream
+console.log("Debug: processing request", requestId);
+```
diff --git a/docs/claude-plugin/example-python.md b/docs/claude-plugin/example-python.md
new file mode 100644
index 00000000..b350f2d0
--- /dev/null
+++ b/docs/claude-plugin/example-python.md
@@ -0,0 +1,175 @@
+# Example — Minimal Python MCP Server
+
+## 1. Setup
+
+```bash
+pip install mcp
+# Optional: use a virtual environment
+python -m venv venv && source venv/bin/activate
+pip install mcp
+```
+
+## 2. Server Code
+
+Create `server.py`:
+
+```python
+import asyncio
+import sys
+from mcp.server import Server
+from mcp.server.stdio import stdio_server
+from mcp.types import TextContent, Tool
+
+# Create the server instance
+app = Server("my-mcp-server")
+
+
+async def list_tools() -> list[Tool]:
+ return [
+ Tool(
+ name="add",
+ description="Add two numbers together",
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "a": {"type": "number", "description": "First number"},
+ "b": {"type": "number", "description": "Second number"},
+ },
+ "required": ["a", "b"],
+ },
+ ),
+ Tool(
+ name="greet",
+ description="Generate a greeting for a person",
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "name": {"type": "string", "description": "Person's name"},
+ },
+ "required": ["name"],
+ },
+ ),
+ ]
+
+
+async def call_tool(name: str, arguments: dict) -> list[TextContent]:
+ print(f"[debug] tool called: {name} {arguments}", file=sys.stderr)
+
+ if name == "add":
+ a = arguments.get("a")
+ b = arguments.get("b")
+
+ if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
+ return [TextContent(type="text", text="Error: a and b must be numbers")]
+
+ return [TextContent(type="text", text=f"{a} + {b} = {a + b}")]
+
+ if name == "greet":
+ person_name = arguments.get("name", "")
+
+ if not isinstance(person_name, str) or not person_name.strip():
+ return [TextContent(type="text", text="Error: name must be a non-empty string")]
+
+ return [TextContent(type="text", text=f"Hello, {person_name.strip()}! Welcome to MCP.")]
+
+ # Unknown tool — raise so MCP SDK returns a protocol error
+ raise ValueError(f"Unknown tool: {name}")
+
+
+async def main():
+ print("[info] MCP server starting on stdio", file=sys.stderr)
+ async with stdio_server(app) as (read_stream, write_stream):
+ await app.run(read_stream, write_stream, app.create_initialization_options())
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
+```
+
+## 3. Register with Claude Code
+
+```bash
+# Stdio transport (local process)
+claude mcp add --transport stdio py-server -- python /absolute/path/to/server.py
+
+# If using a virtualenv
+claude mcp add --transport stdio py-server -- /path/to/venv/bin/python /path/to/server.py
+```
+
+Or in `.mcp.json`:
+```json
+{
+ "mcpServers": {
+ "py-server": {
+ "command": "python",
+ "args": ["./server.py"]
+ }
+ }
+}
+```
+
+## 4. Test It
+
+```bash
+# Verify the server is connected
+# Inside Claude Code:
+/mcp
+
+# Ask Claude to use it:
+# "Use the add tool to calculate 10 + 7"
+# "Use the greet tool for Bob"
+```
+
+## 5. Adding Resources
+
+```python
+from mcp.types import Resource, TextContent, ReadResourceResult
+
[email protected]_resources()
+async def list_resources() -> list[Resource]:
+ return [
+ Resource(
+ uri="config://app/settings",
+ name="App Settings",
+ description="Current application configuration",
+ mimeType="application/json",
+ )
+ ]
+
+
+async def read_resource(uri: str) -> ReadResourceResult:
+ import json
+
+ if uri == "config://app/settings":
+ return ReadResourceResult(
+ contents=[
+ TextContent(
+ type="text",
+ text=json.dumps({"version": "1.0.0", "debug": False}, indent=2),
+ )
+ ]
+ )
+
+ raise ValueError(f"Unknown resource: {uri}")
+```
+
+Update the Server constructor to declare the `resources` capability:
+
+```python
+from mcp.server import Server
+from mcp.types import ServerCapabilities, ResourcesCapability
+
+app = Server(
+ "my-mcp-server",
+ capabilities=ServerCapabilities(resources=ResourcesCapability()),
+)
+```
+
+## Notes
+
+- Always write debug output to `sys.stderr` — stdout is the JSON-RPC channel
+- Tool errors the LLM can learn from: return them as `TextContent` (not exceptions)
+- Protocol errors (unknown tool, bad method): raise an exception — the SDK handles it
diff --git a/docs/claude-plugin/example-typescript.md b/docs/claude-plugin/example-typescript.md
new file mode 100644
index 00000000..6e9105d5
--- /dev/null
+++ b/docs/claude-plugin/example-typescript.md
@@ -0,0 +1,208 @@
+# Example — Minimal TypeScript MCP Server
+
+## 1. Project Setup
+
+```bash
+mkdir my-mcp-server && cd my-mcp-server
+npm init -y
+npm install @modelcontextprotocol/sdk
+npm install -D typescript @types/node
+npx tsc --init
+```
+
+Update `tsconfig.json`:
+```json
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "outDir": "./dist",
+ "strict": true,
+ "esModuleInterop": true
+ },
+ "include": ["src/**/*"]
+}
+```
+
+Update `package.json`:
+```json
+{
+ "name": "my-mcp-server",
+ "version": "1.0.0",
+ "type": "module",
+ "scripts": {
+ "build": "tsc",
+ "start": "node dist/server.js"
+ }
+}
+```
+
+## 2. Server Code
+
+Create `src/server.ts`:
+
+```typescript
+import { Server } from "@modelcontextprotocol/sdk/server/index.js";
+import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
+import {
+ CallToolRequestSchema,
+ ListToolsRequestSchema,
+} from "@modelcontextprotocol/sdk/types.js";
+
+// Create the server instance
+const server = new Server(
+ { name: "my-mcp-server", version: "1.0.0" },
+ { capabilities: { tools: {} } }
+);
+
+// Declare available tools
+server.setRequestHandler(ListToolsRequestSchema, async () => {
+ return {
+ tools: [
+ {
+ name: "add",
+ description: "Add two numbers together",
+ inputSchema: {
+ type: "object",
+ properties: {
+ a: { type: "number", description: "First number" },
+ b: { type: "number", description: "Second number" },
+ },
+ required: ["a", "b"],
+ },
+ },
+ {
+ name: "greet",
+ description: "Generate a greeting for a person",
+ inputSchema: {
+ type: "object",
+ properties: {
+ name: { type: "string", description: "Person's name" },
+ },
+ required: ["name"],
+ },
+ },
+ ],
+ };
+});
+
+// Handle tool calls
+server.setRequestHandler(CallToolRequestSchema, async (request) => {
+ const { name, arguments: args } = request.params;
+
+ console.error("[debug] tool called:", name, args);
+
+ if (name === "add") {
+ const a = args?.a as number;
+ const b = args?.b as number;
+
+ if (typeof a !== "number" || typeof b !== "number") {
+ return {
+ content: [{ type: "text", text: "Error: a and b must be numbers" }],
+ isError: true,
+ };
+ }
+
+ return {
+ content: [{ type: "text", text: `${a} + ${b} = ${a + b}` }],
+ };
+ }
+
+ if (name === "greet") {
+ const personName = args?.name as string;
+
+ if (typeof personName !== "string" || personName.trim() === "") {
+ return {
+ content: [{ type: "text", text: "Error: name must be a non-empty string" }],
+ isError: true,
+ };
+ }
+
+ return {
+ content: [{ type: "text", text: `Hello, ${personName.trim()}! Welcome to MCP.` }],
+ };
+ }
+
+ // Unknown tool — protocol error
+ throw new Error(`Unknown tool: ${name}`);
+});
+
+// Connect to Claude Code via stdio
+const transport = new StdioServerTransport();
+await server.connect(transport);
+console.error("[info] MCP server running on stdio");
+```
+
+## 3. Build and Register
+
+```bash
+npm run build
+
+# Register with Claude Code (stdio transport)
+claude mcp add --transport stdio my-server -- node /absolute/path/to/dist/server.js
+```
+
+Or add to `.mcp.json` in your project root for project-wide access:
+```json
+{
+ "mcpServers": {
+ "my-server": {
+ "command": "node",
+ "args": ["./my-mcp-server/dist/server.js"]
+ }
+ }
+}
+```
+
+## 4. Test It
+
+In Claude Code:
+```
+/mcp # verify server shows as connected
+Use the add tool to add 5 + 3
+Use the greet tool for Alice
+```
+
+## 5. Adding Resources
+
+To also expose resources, update capabilities and add a handler:
+
+```typescript
+// In Server constructor
+{ capabilities: { tools: {}, resources: {} } }
+
+// Add handler
+import { ListResourcesRequestSchema, ReadResourceRequestSchema } from "@modelcontextprotocol/sdk/types.js";
+
+server.setRequestHandler(ListResourcesRequestSchema, async () => {
+ return {
+ resources: [
+ {
+ uri: "config://app/settings",
+ name: "App Settings",
+ description: "Current application configuration",
+ mimeType: "application/json",
+ },
+ ],
+ };
+});
+
+server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
+ const { uri } = request.params;
+
+ if (uri === "config://app/settings") {
+ return {
+ contents: [
+ {
+ uri,
+ mimeType: "application/json",
+ text: JSON.stringify({ version: "1.0.0", debug: false }, null, 2),
+ },
+ ],
+ };
+ }
+
+ throw new Error(`Unknown resource: ${uri}`);
+});
+```
diff --git a/docs/claude-plugin/hooks-vs-mcp.md b/docs/claude-plugin/hooks-vs-mcp.md
new file mode 100644
index 00000000..1d7dda0b
--- /dev/null
+++ b/docs/claude-plugin/hooks-vs-mcp.md
@@ -0,0 +1,89 @@
+# Hooks vs MCP — Choosing the Right Mechanism
+
+## Summary
+
+| Need | Use |
+|------|-----|
+| Guarantee execution on every tool call | **Hooks** |
+| Automatic file change tracking | **Hooks** (PostToolUse on Write/Edit) |
+| Front-run native searches with better data | **Hooks** (PreToolUse on Grep/Glob) |
+| Give Claude an on-demand callable function | **MCP tool** |
+| Expose file/data context to Claude | **MCP resource** |
+| Add a user-invocable slash command | **MCP prompt** or **skill** |
+
+## Hooks
+
+Hooks are shell commands registered in `hooks.json` that fire automatically on
+Claude Code events. They require **no user approval** and cannot be skipped.
+
+### Key Events
+
+| Event | When | Can Block Claude? |
+|-------|------|-------------------|
+| `PreToolUse` | Before any tool runs | Yes (exit 2 + stderr) |
+| `PostToolUse` | After any tool succeeds | No |
+| `SessionStart` | Session begins | No |
+| `Stop` | Claude finishes a response | Yes |
+
+### Injecting Into Claude's Context
+
+A hook script can write JSON to stdout:
+
+```json
+{"additionalContext": "text that gets added to Claude's context window"}
+```
+
+Claude sees this on the next turn. Use it to give Claude pre-fetched data so
+it doesn't need to run additional tool calls.
+
+### Blocking a Tool Call
+
+Return exit code 2 and write to stderr — Claude reads the stderr message and
+can self-correct:
+
+```bash
+echo "Don't use Grep for this — run: ix text '$PATTERN'" >&2
+exit 2
+```
+
+### The Front-Run Pattern
+
+The most powerful pattern for search optimization:
+
+1. Claude decides to run `Grep "foo"`
+2. `PreToolUse` hook intercepts, runs `ix text "foo"` silently
+3. Hook returns `additionalContext` with the Ix results
+4. Claude sees the Ix results already — often skips or shortens the Grep
+5. Grep still runs (not blocked), but Claude may not need it
+
+This is how `ix-intercept.sh` works in the Ix plugin.
+
+## MCP
+
+MCP servers expose **tools**, **resources**, and **prompts** to Claude. Unlike hooks:
+
+- Tool calls require explicit **user approval** every time
+- Claude decides when to call them based on context
+- They can be called from any point in the conversation on demand
+
+### When MCP Makes Sense
+
+Use MCP when you want Claude to be able to **ask for something** interactively —
+for example, querying a database, calling an API, or fetching a document — and
+the user should see and approve each call.
+
+For the Ix use case (`ix search`, `ix impact`, `ix overview`, etc.), MCP is
+useful for on-demand investigative commands that Claude calls mid-reasoning.
+The CLAUDE.md routing rules in this project already push Claude toward these.
+
+## The Ix Plugin Uses Both (Implicitly)
+
+The Ix plugin uses only hooks because the goal is **automatic, silent, guaranteed**
+behavior:
+
+- **Auto-ingest**: PostToolUse hook → no user interaction needed
+- **Search intercept**: PreToolUse hook → runs before Claude even sees the result
+
+The `ix` CLI commands Claude calls manually (via CLAUDE.md instructions) are not
+MCP tools — they are called via the native `Bash` tool, which requires normal
+user approval just like any shell command.
diff --git a/docs/claude-plugin/ix-plugin-reference.md b/docs/claude-plugin/ix-plugin-reference.md
new file mode 100644
index 00000000..d8900a45
--- /dev/null
+++ b/docs/claude-plugin/ix-plugin-reference.md
@@ -0,0 +1,151 @@
+# Ix Memory Plugin — Reference
+
+The Ix plugin lives at `ix-plugin/` in the repo root. It is a hooks-only Claude
+Code plugin — no MCP server required.
+
+## What It Does
+
+| Hook | Event | Trigger | Effect |
+|------|-------|---------|--------|
+| `ix-intercept.sh` | `PreToolUse` | `Grep` or `Glob` | Runs `ix text` + `ix locate` (or `ix inventory`) and injects results as `additionalContext` before the native tool fires |
+| `ix-ingest.sh` | `PostToolUse` (async) | `Write`, `Edit`, `MultiEdit` | Ingests the modified file into the Ix graph silently in the background |
+
+Both hooks bail silently if `ix` is not in PATH or the backend is unreachable.
+The ingest hook is `async: true` — it never blocks Claude's response.
+
+## Directory Structure
+
+```
+ix-plugin/
+ .claude-plugin/
+ plugin.json # plugin manifest
+ hooks/
+ hooks.json # event → script registration
+ ix-intercept.sh # PreToolUse handler
+ ix-ingest.sh # PostToolUse handler
+ README.md
+```
+
+## plugin.json
+
+```json
+{
+ "name": "ix-memory",
+ "version": "1.0.0",
+ "description": "...",
+ "author": { "name": "Ix Memory" },
+ "hooks": "./hooks/hooks.json"
+}
+```
+
+The manifest lives in `.claude-plugin/plugin.json`. Only `plugin.json` belongs
+in that directory — scripts and other files go at the plugin root.
+
+## hooks.json
+
+```json
+{
+ "hooks": {
+ "PreToolUse": [
+ {
+ "matcher": "Grep|Glob",
+ "hooks": [{ "type": "command", "command": "${CLAUDE_PLUGIN_ROOT}/hooks/ix-intercept.sh", "timeout": 10 }]
+ }
+ ],
+ "PostToolUse": [
+ {
+ "matcher": "Write|Edit|MultiEdit",
+ "hooks": [{ "type": "command", "command": "${CLAUDE_PLUGIN_ROOT}/hooks/ix-ingest.sh", "timeout": 30, "async": true }]
+ }
+ ]
+ }
+}
+```
+
+`${CLAUDE_PLUGIN_ROOT}` is resolved by Claude Code to the absolute path of the
+installed plugin directory. Always use it for script paths — never hardcode.
+
+## How ix-intercept.sh Works
+
+1. Reads the hook JSON payload from **stdin**
+2. Extracts `tool_name` (Grep or Glob) and `tool_input.pattern`
+3. For **Grep**: runs `ix text <pattern> --limit 20 --format json` and `ix locate <pattern> --limit 10 --format json`, passing through any `--path` or `--language` filters from the original tool call
+4. For **Glob**: runs `ix inventory --format json` (with `--path` filter if present)
+5. Formats results and writes `{"additionalContext": "..."}` to **stdout**
+6. Exits 0 — native tool still runs
+
+Claude Code injects `additionalContext` into Claude's context window. Claude
+sees the Ix results first and often uses them instead of the raw Grep/Glob output.
+
+### Hook Input Shape (Grep example)
+
+```json
+{
+ "hook_event_name": "PreToolUse",
+ "tool_name": "Grep",
+ "tool_input": {
+ "pattern": "verify_token",
+ "path": "/home/user/project/src",
+ "type": "scala"
+ },
+ "cwd": "/home/user/project"
+}
+```
+
+### Hook Output Shape
+
+```json
+{
+ "additionalContext": "[ix] Pre-search results for pattern: 'verify_token'\n\n--- ix text ---\n{...}\n\n--- ix locate ---\n{...}"
+}
+```
+
+## How ix-ingest.sh Works
+
+1. Reads the hook JSON payload from **stdin**
+2. Extracts `tool_input.file_path`
+3. Runs `ix ingest <file_path>` (suppresses output)
+4. Returns a short `additionalContext` confirmation
+5. Exits 0
+
+Because the hook is `async: true`, it runs in the background and Claude's
+response is never delayed waiting for ingestion to complete.
+
+### Hook Input Shape (Edit example)
+
+```json
+{
+ "hook_event_name": "PostToolUse",
+ "tool_name": "Edit",
+ "tool_input": {
+ "file_path": "/home/user/project/src/auth/AuthService.scala",
+ "old_str": "...",
+ "new_str": "..."
+ }
+}
+```
+
+## Installation
+
+```bash
+# From the IX-Memory repo root
+claude plugin install ./ix-plugin
+
+# Project-scoped (recommended for team use)
+claude plugin install ./ix-plugin --scope project
+
+# Verify
+claude mcp list # or /mcp inside Claude Code
+```
+
+## Requirements
+
+- `ix` CLI available in PATH
+- Ix backend running (`ix status` returns ok)
+- `jq` available in PATH
+
+## Uninstall
+
+```bash
+claude plugin uninstall ix-memory
+```
diff --git a/docs/claude-plugin/overview.md b/docs/claude-plugin/overview.md
new file mode 100644
index 00000000..9963ea76
--- /dev/null
+++ b/docs/claude-plugin/overview.md
@@ -0,0 +1,90 @@
+# Overview — What Is an MCP Server / Claude Plugin
+
+## What Is MCP?
+
+**MCP (Model Context Protocol)** is an open standard protocol that enables integration
+between LLM applications (like Claude Code) and external tools, data sources, and services.
+
+A **Claude plugin** is an MCP server: a program you write that exposes capabilities to
+Claude Code through this standardized protocol.
+
+## Architecture
+
+Three roles in every MCP interaction:
+
+| Role | What It Is |
+|------|-----------|
+| **Host** | Claude Code — initiates connections to servers |
+| **Client** | The connection manager running inside Claude Code |
+| **Server** | Your MCP server — exposes tools, resources, prompts |
+
+## What Can a Plugin Do?
+
+Three capability types:
+
+| Type | Who Controls It | What It Does |
+|------|----------------|-------------|
+| **Tools** | LLM (model-controlled) | Functions the LLM can invoke based on task context |
+| **Resources** | Application (app-controlled) | Context/data provided to the LLM (files, schemas, docs) |
+| **Prompts** | User (user-controlled) | Templated messages invoked by user commands |
+
+## How Claude Code Loads a Plugin
+
+1. You register the server: `claude mcp add --transport stdio my-server -- node server.js`
+2. Claude Code starts (or connects to) the server process
+3. **Capability negotiation**: both sides declare what features they support
+4. Claude Code discovers tools, resources, and prompts via `tools/list`, `resources/list`, `prompts/list`
+5. During a session, Claude Code routes tool calls to your server and returns results to the LLM
+
+## Transport Types
+
+| Transport | Use Case | How Claude Connects |
+|-----------|----------|---------------------|
+| **stdio** | Local process on user's machine | Spawns process, communicates via stdin/stdout |
+| **HTTP** (Streamable HTTP) | Remote cloud services | HTTP POST with streaming response |
+| **SSE** (Server-Sent Events) | Remote services with events | HTTP with event stream (legacy, prefer HTTP) |
+
+For local plugins, **stdio is the standard choice**. The server reads JSON-RPC messages
+from stdin and writes responses to stdout. Log debug output to stderr.
+
+## Protocol Foundation
+
+- All messages are **JSON-RPC 2.0**
+- Each session is **stateful** — one connection, one session
+- The server declares its capabilities during the `initialize` handshake
+- Servers can send `list_changed` notifications when their capabilities change dynamically
+
+## Initialization Handshake
+
+Claude Code sends:
+```json
+{
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2025-11-25",
+ "capabilities": { "sampling": {} },
+ "clientInfo": { "name": "claude-code", "version": "1.0.0" }
+ }
+}
+```
+
+Your server responds with:
+```json
+{
+ "jsonrpc": "2.0",
+ "id": 1,
+ "result": {
+ "protocolVersion": "2025-11-25",
+ "capabilities": {
+ "tools": { "listChanged": true },
+ "resources": { "subscribe": true, "listChanged": true },
+ "prompts": { "listChanged": true }
+ },
+ "serverInfo": { "name": "my-mcp-server", "version": "1.0.0" }
+ }
+}
+```
+
+Then Claude Code sends `initialized` to confirm, and the session is live.
diff --git a/docs/claude-plugin/security.md b/docs/claude-plugin/security.md
new file mode 100644
index 00000000..09adb03d
--- /dev/null
+++ b/docs/claude-plugin/security.md
@@ -0,0 +1,100 @@
+# Security — Permissions, Consent, and Authentication
+
+## User Consent Model
+
+### Tools — Always Require Confirmation
+
+Before Claude Code invokes any tool, it shows the user:
+- Which tool is being called
+- The input parameters
+- An approve/deny prompt
+
+There is no way to bypass this. Every tool call goes through user approval.
+
+### Resources — Application-Controlled
+
+Claude Code decides when to include resources. This may be automatic or require
+user selection, depending on the client implementation.
+
+### Prompts — User-Initiated
+
+Prompts are triggered explicitly by the user (like a slash command). No additional
+approval is required beyond the user having invoked the prompt.
+
+## Data Privacy Rules
+
+1. Servers receive only the context necessary for the current tool call
+2. Servers do not have access to the full conversation history
+3. User data is only shared with explicit user consent
+
+## Tool Implementation Security
+
+Always validate inputs before trusting them:
+
+```typescript
+server.setRequestHandler(CallToolRequestSchema, async (request) => {
+ const { name, arguments: args } = request.params;
+
+ // Validate required fields
+ if (typeof args.user_id !== "string" || args.user_id.trim() === "") {
+ return {
+ content: [{ type: "text", text: "Error: user_id must be a non-empty string" }],
+ isError: true,
+ };
+ }
+
+ // Sanitize before using in any query
+ const userId = args.user_id.trim();
+ // ... proceed
+});
+```
+
+Security checklist for tools:
+- [ ] Validate all input types and ranges
+- [ ] Sanitize strings before use in queries, shell commands, or file paths
+- [ ] Implement access controls — not every caller should invoke every tool
+- [ ] Rate-limit expensive operations
+- [ ] Never expose secrets in tool results
+
+## Claude Code Permission System
+
+Configure which MCP tools are auto-approved or denied in `.claude/settings.json`:
+
+```json
+{
+ "permissions": {
+ "allow": [
+ "MCP(my-server:read_file)",
+ "MCP(database:query)"
+ ],
+ "deny": [
+ "MCP(untrusted-server:*)"
+ ]
+ }
+}
+```
+
+The `*` wildcard matches all tools on a server.
+
+## OAuth & Credentials
+
+When using HTTP servers with OAuth:
+- Credentials are stored in the **system keychain**, never in config files
+- Tokens are refreshed automatically
+- Use `${TOKEN}` environment variable expansion in `.mcp.json` rather than hardcoding
+
+Never put secrets directly in `.mcp.json`:
+```json
+// Wrong
+{ "headers": { "Authorization": "Bearer sk-live-abc123" } }
+
+// Correct
+{ "headers": { "Authorization": "Bearer ${MY_API_TOKEN}" } }
+```
+
+## LLM Sampling (If Your Server Requests It)
+
+If your server uses the `sampling` capability (asks Claude to generate text):
+- The user must explicitly approve the sampling request
+- The user controls what prompt is sent to the LLM
+- The user controls what the server sees in the response
diff --git a/docs/claude-plugin/testing.md b/docs/claude-plugin/testing.md
new file mode 100644
index 00000000..eb9172f6
--- /dev/null
+++ b/docs/claude-plugin/testing.md
@@ -0,0 +1,102 @@
+# Testing and Debugging an MCP Server
+
+## Run Claude Code in Debug Mode
+
+```bash
+claude --debug
+```
+
+This prints MCP initialization messages, tool discovery, and every JSON-RPC
+message exchanged. Most issues are visible here.
+
+## Inspect Configured Servers
+
+Inside Claude Code:
+```
+/mcp
+```
+
+Shows all configured servers with:
+- Connection status (running / error)
+- Declared capabilities (tools, resources, prompts)
+- List of available tools with descriptions
+
+CLI commands:
+```bash
+claude mcp list # All configured servers
+claude mcp get my-server # Details for one server
+```
+
+## Test stdio Transport Directly
+
+Send a raw JSON-RPC message to your server via stdin:
+
+```bash
+echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"test","version":"0.0.1"}}}' \
+ | node dist/server.js
+```
+
+Then follow with `initialized`:
+```bash
+printf '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"test","version":"0.0.1"}}}\n{"jsonrpc":"2.0","method":"notifications/initialized"}\n{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}\n' \
+ | node dist/server.js
+```
+
+## Common Issues and Fixes
+
+| Symptom | Likely Cause | Fix |
+|---------|-------------|-----|
+| "Connection closed" immediately | Server process crashes on start | Check stderr output; verify all imports resolve |
+| Tool not appearing in `/mcp` | `tools` not declared in capabilities | Add `tools: {}` to `capabilities` in `initialize` response |
+| Tool appears but call fails | Input schema mismatch | Log the raw `arguments` object to stderr and compare |
+| Authentication fails | Bad OAuth config | Verify `--client-id`, `--callback-port`, and auth server URL |
+| Timeout on tool call | Server too slow to respond | Increase `MCP_TIMEOUT` or add progress notifications |
+| "Unknown tool" error | Tool name typo or case mismatch | Tool names are case-sensitive; verify exact match |
+| Output to stdout corrupts stream | Debug `console.log` in server code | Change all debug output to `console.error` |
+
+## Logging
+
+Always write debug output to **stderr** — stdout is the JSON-RPC channel:
+
+```typescript
+// TypeScript
+console.error("[debug] received request:", JSON.stringify(request.params));
+
+// Python
+import sys
+print("[debug] received request:", args, file=sys.stderr)
+```
+
+## Testing Tool Calls in Claude Code
+
+Once your server is registered, ask Claude directly:
+
+```
+Call the add tool with a=5 and b=3
+```
+
+Claude Code will show the approval prompt, then invoke the tool, and display
+the result. Watch `--debug` output for the full round-trip.
+
+## Reload After Changes
+
+After rebuilding your server:
+```bash
+npm run build # rebuild
+/mcp # inside Claude Code — reconnects servers
+```
+
+Or remove and re-add the server:
+```bash
+claude mcp remove my-server
+claude mcp add --transport stdio my-server -- node dist/server.js
+```
+
+## MCP Timeout Environment Variable
+
+```bash
+MCP_TIMEOUT=30000 claude # 30-second timeout per tool call
+```
+
+Useful when debugging slow operations — prevents premature timeouts while
+you're stepping through code.
diff --git a/ix-plugin/.claude-plugin/plugin.json b/ix-plugin/.claude-plugin/plugin.json
new file mode 100644
index 00000000..65f37d2d
--- /dev/null
+++ b/ix-plugin/.claude-plugin/plugin.json
@@ -0,0 +1,9 @@
+{
+ "name": "ix-memory",
+ "version": "1.0.0",
+ "description": "Ix Memory integration — auto-ingests edited files and front-runs Grep/Glob/Read with graph-aware ix searches for token-efficient codebase understanding.",
+ "author": {
+ "name": "Ix Memory"
+ },
+ "hooks": "./hooks/hooks.json"
+}
diff --git a/ix-plugin/README.md b/ix-plugin/README.md
new file mode 100644
index 00000000..b30a399e
--- /dev/null
+++ b/ix-plugin/README.md
@@ -0,0 +1,74 @@
+# Ix Memory — Claude Code Plugin
+
+A Claude Code plugin that makes Claude use Ix for codebase searches instead of
+native `Grep`/`Glob`, and keeps the Ix graph current as Claude edits files.
+
+## What It Does
+
+| Trigger | Hook | Effect |
+|---------|------|--------|
+| Claude runs `Grep` or `Glob` | `PreToolUse` → `ix-intercept.sh` | Runs `ix text` + `ix locate` (or `ix inventory`) first and injects results into Claude's context before the native tool fires |
+| Claude runs `Write`, `Edit`, or `MultiEdit` | `PostToolUse` → `ix-ingest.sh` (async) | Ingests the changed file into the Ix graph silently in the background |
+
+Both hooks bail silently if `ix` is not in PATH or the Ix backend is unreachable.
+
+## Why Hooks Instead of MCP
+
+- **No user approval prompt** — hooks fire silently and automatically
+- **Guaranteed execution** — every Grep/Glob gets front-run, every edit gets ingested
+- **Token-efficient** — Ix returns structured, bounded results vs. raw file content
+
+## Installation
+
+```bash
+# From the IX-Memory repo root
+claude plugin install ./ix-plugin
+
+# Or for a single project only
+claude plugin install ./ix-plugin --scope project
+```
+
+## Requirements
+
+- `ix` CLI in PATH and Ix backend running (`ix status` should return ok)
+- `jq` in PATH (used to parse hook JSON input)
+
+## Structure
+
+```
+ix-plugin/
+ .claude-plugin/
+ plugin.json # manifest
+ hooks/
+ hooks.json # hook event registration
+ ix-intercept.sh # PreToolUse: Grep|Glob → ix text/locate/inventory
+ ix-ingest.sh # PostToolUse: Write|Edit|MultiEdit → ix ingest
+ README.md
+```
+
+## How the Intercept Hook Works
+
+When Claude runs `Grep "verify_token"`:
+
+1. `ix-intercept.sh` fires with the tool input as JSON on stdin
+2. Script runs `ix text "verify_token" --limit 20 --format json`
+3. Script also runs `ix locate "verify_token" --limit 10 --format json`
+4. Results are returned as `additionalContext` — injected into Claude's next context window
+5. Claude sees the Ix results and typically uses them instead of waiting for Grep output
+
+For `Glob`, the script runs `ix inventory` (optionally filtered by path) instead.
+
+## How the Ingest Hook Works
+
+When Claude edits a file:
+
+1. `ix-ingest.sh` fires asynchronously after the edit succeeds
+2. Reads `tool_input.file_path` from stdin
+3. Runs `ix ingest <file_path>` silently
+4. Returns a short `additionalContext` confirmation: `[ix] Graph updated — ingested: <path>`
+
+## Uninstall
+
+```bash
+claude plugin uninstall ix-memory
+```
diff --git a/ix-plugin/hooks/hooks.json b/ix-plugin/hooks/hooks.json
new file mode 100644
index 00000000..ba178bf8
--- /dev/null
+++ b/ix-plugin/hooks/hooks.json
@@ -0,0 +1,29 @@
+{
+ "hooks": {
+ "PreToolUse": [
+ {
+ "matcher": "Grep|Glob",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "${CLAUDE_PLUGIN_ROOT}/hooks/ix-intercept.sh",
+ "timeout": 10
+ }
+ ]
+ }
+ ],
+ "PostToolUse": [
+ {
+ "matcher": "Write|Edit|MultiEdit",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "${CLAUDE_PLUGIN_ROOT}/hooks/ix-ingest.sh",
+ "timeout": 30,
+ "async": true
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/ix-plugin/hooks/ix-ingest.sh b/ix-plugin/hooks/ix-ingest.sh
new file mode 100755
index 00000000..dd070c48
--- /dev/null
+++ b/ix-plugin/hooks/ix-ingest.sh
@@ -0,0 +1,28 @@
+#!/usr/bin/env bash
+# ix-ingest.sh — PostToolUse hook for Write, Edit, MultiEdit
+#
+# Fires after Claude modifies a file. Automatically ingests the changed file
+# into the Ix graph so the next query reflects the current code state.
+#
+# Runs async (does not block Claude's response).
+
+set -euo pipefail
+
+INPUT=$(cat)
+FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
+[ -z "$FILE_PATH" ] && exit 0
+
+# Bail silently if ix is not in PATH
+command -v ix >/dev/null 2>&1 || exit 0
+
+# Bail silently if ix backend is not reachable
+ix status >/dev/null 2>&1 || exit 0
+
+# Ingest the modified file
+ix ingest "$FILE_PATH" >/dev/null 2>&1 || exit 0
+
+# Inject a short confirmation into Claude's context so it knows the graph is current
+jq -n --arg fp "$FILE_PATH" \
+ '{"additionalContext": ("[ix] Graph updated — ingested: " + $fp)}'
+
+exit 0
diff --git a/ix-plugin/hooks/ix-intercept.sh b/ix-plugin/hooks/ix-intercept.sh
new file mode 100755
index 00000000..1ef04d84
--- /dev/null
+++ b/ix-plugin/hooks/ix-intercept.sh
@@ -0,0 +1,72 @@
+#!/usr/bin/env bash
+# ix-intercept.sh — PreToolUse hook for Grep and Glob
+#
+# Fires before Grep/Glob executes. Runs the ix equivalent silently and injects
+# the result as additionalContext so Claude already has a graph-aware, token-
+# efficient answer before the native tool runs.
+#
+# Exit 0 + JSON stdout → injects additionalContext, native tool still runs
+# Exit 0 + no stdout → no-op, native tool runs normally
+
+set -euo pipefail
+
+INPUT=$(cat)
+TOOL=$(echo "$INPUT" | jq -r '.tool_name // empty')
+[ -z "$TOOL" ] && exit 0
+
+# Bail silently if ix is not in PATH
+command -v ix >/dev/null 2>&1 || exit 0
+
+# Bail silently if ix backend is not reachable
+ix status >/dev/null 2>&1 || exit 0
+
+# ── Grep: text/symbol search ─────────────────────────────────────────────────
+if [ "$TOOL" = "Grep" ]; then
+ PATTERN=$(echo "$INPUT" | jq -r '.tool_input.pattern // empty')
+ [ -z "$PATTERN" ] && exit 0
+
+ # Run ix text search (line-level matches, respects --language and --path)
+ PATH_ARG=$(echo "$INPUT" | jq -r '.tool_input.path // empty')
+ LANG_ARG=$(echo "$INPUT" | jq -r '.tool_input.type // empty')
+
+ TEXT_ARGS=("$PATTERN" "--limit" "20" "--format" "json")
+ [ -n "$PATH_ARG" ] && TEXT_ARGS+=("--path" "$PATH_ARG")
+ [ -n "$LANG_ARG" ] && TEXT_ARGS+=("--language" "$LANG_ARG")
+
+ TEXT_RESULT=$(ix text "${TEXT_ARGS[@]}" 2>/dev/null) || TEXT_RESULT=""
+
+ # Also run ix locate for symbol-level matches (class, function, etc.)
+ LOCATE_RESULT=$(ix locate "$PATTERN" --limit 10 --format json 2>/dev/null) || LOCATE_RESULT=""
+
+ [ -z "$TEXT_RESULT" ] && [ -z "$LOCATE_RESULT" ] && exit 0
+
+ CONTEXT="[ix] Pre-search results for pattern: '${PATTERN}'"
+ [ -n "$TEXT_RESULT" ] && CONTEXT="${CONTEXT}\n\n--- ix text ---\n${TEXT_RESULT}"
+ [ -n "$LOCATE_RESULT" ] && CONTEXT="${CONTEXT}\n\n--- ix locate ---\n${LOCATE_RESULT}"
+
+# ── Glob: file pattern search ─────────────────────────────────────────────────
+elif [ "$TOOL" = "Glob" ]; then
+ PATTERN=$(echo "$INPUT" | jq -r '.tool_input.pattern // empty')
+ [ -z "$PATTERN" ] && exit 0
+
+ PATH_ARG=$(echo "$INPUT" | jq -r '.tool_input.path // empty')
+
+ INV_ARGS=("--format" "json")
+ [ -n "$PATH_ARG" ] && INV_ARGS+=("--path" "$PATH_ARG")
+
+ INV_RESULT=$(ix inventory "${INV_ARGS[@]}" 2>/dev/null) || INV_RESULT=""
+
+ [ -z "$INV_RESULT" ] && exit 0
+
+ CONTEXT="[ix] Pre-search inventory for glob: '${PATTERN}'"
+ [ -n "$PATH_ARG" ] && CONTEXT="${CONTEXT} (path: ${PATH_ARG})"
+ CONTEXT="${CONTEXT}\n\n--- ix inventory ---\n${INV_RESULT}"
+
+else
+ exit 0
+fi
+
+[ -z "$CONTEXT" ] && exit 0
+
+jq -n --arg ctx "$CONTEXT" '{"additionalContext": $ctx}'
+exit 0