# Agent Work Context

Research and assessment notes for Claude Agent SDK development in the Vanderlyn homelab.

## Claude Agent SDK Overview

The Claude Agent SDK is Anthropic's official framework for building autonomous AI agents. It provides the same tools, agent loop, and context management that power Claude Code, but programmable via Python or TypeScript.

**Key distinction from Claude Code**: The SDK enables agents to be *components* rather than *interfaces*. Claude Code requires human invocation; SDK agents can run unattended, event-driven, or scheduled.

### Installation

```bash
pip install claude-agent-sdk
```

Requirements: Python 3.10+. The Claude Code CLI is bundled automatically.

### Two Modes of Operation

```python
# 1. query() - Simple async iterator for one-shot tasks
from claude_agent_sdk import query

async for message in query(prompt="What is 2 + 2?"):
    print(message)

# 2. ClaudeSDKClient - Bidirectional, multi-turn, custom tools + hooks
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions

async with ClaudeSDKClient(options=options) as client:
    await client.query("Do something")
    async for msg in client.receive_response():
        print(msg)
```

### Custom Tools (In-Process MCP Servers)

Custom tools run in-process, eliminating subprocess overhead:

```python
from claude_agent_sdk import tool, create_sdk_mcp_server

@tool("greet", "Greet a user", {"name": str})
async def greet_user(args):
    return {"content": [{"type": "text", "text": f"Hello, {args['name']}!"}]}

server = create_sdk_mcp_server(name="my-tools", version="1.0.0", tools=[greet_user])

options = ClaudeAgentOptions(
    mcp_servers={"tools": server},
    allowed_tools=["mcp__tools__greet"]
)
```

### Hooks

Hooks provide deterministic interception at specific points in the agent loop:

```python
from claude_agent_sdk import HookMatcher

async def check_bash_command(input_data, tool_use_id, context):
    if "rm -rf" in input_data["tool_input"].get("command", ""):
        return {
            "hookSpecificOutput": {
                "hookEventName": "PreToolUse",
                "permissionDecision": "deny",
                "permissionDecisionReason": "Dangerous command blocked",
            }
        }
    return {}

options = ClaudeAgentOptions(
    hooks={
        "PreToolUse": [HookMatcher(matcher="Bash", hooks=[check_bash_command])],
    }
)
```

---

## Claude Code vs Custom Agent: Capability Delta

| Capability | Claude Code | Custom Agent |
|------------|-------------|--------------|
| **Invocation** | Interactive CLI session | Programmatic, event-driven, scheduled |
| **Autonomy** | Human-in-the-loop | Can run unattended (CI/CD, cron, webhooks) |
| **Scope** | General-purpose | Purpose-built, constrained |
| **Tool Surface** | Broad (all tools available) | Narrow (only what's needed) |
| **Integration** | You drive it | It integrates into other systems |
| **Cost Control** | Per-session | Budgeted per-task with hard limits |
| **Parallelism** | Single conversation | Spawn multiple agents concurrently |

### When Custom Agents Make Sense

1. **Headless automation** - Webhook receives alert → agent investigates → posts findings. No human initiates.
2. **Constrained specialists** - Agent that *only* does DNS operations with locked-down tool set.
3. **Pipelines** - Agent A triages → Agent B remediates → Agent C validates.
4. **Integration glue** - Sits between systems (alert → agent → action → notification).
5. **Scheduled tasks** - "Every night, review K8s pod restarts and summarize anomalies."

---

## Existing Ecosystem (Python)

### Official Resources

| Repository | Description |
|------------|-------------|
| [anthropics/claude-agent-sdk-python](https://github.com/anthropics/claude-agent-sdk-python) | Official SDK - 4.3k stars |
| [anthropics/claude-agent-sdk-demos](https://github.com/anthropics/claude-agent-sdk-demos) | Official demos (mostly TypeScript) |

### Notable Community Projects

| Project | Description |
|---------|-------------|
| [claude-multi-agent-api-server](https://github.com/is0383kk/claude-multi-agent-api-server) | FastAPI wrapper with session management, cost tracking, HTTP API |
| [Stateless-FileSystem-Agent](https://github.com/BukeLy/Stateless-FileSystem-Agent) | Lambda + DynamoDB session persistence, Telegram bot trigger |
| [CognivAgent](https://github.com/costiash/CognivAgent) | Video → knowledge graph via custom MCP tools |
| [feedback-memory-as-a-tool](https://github.com/vicgalle/feedback-memory-as-a-tool) | Persistent memory framework for amortizing reasoning cost |

### Emerging Patterns

**HTTP API Wrappers**: Wrap SDK in FastAPI, expose agents via REST, add observability.

**Serverless/Event-Driven**: Lambda + DynamoDB for stateless compute with persistent sessions.

**Specialized Pipelines**: Custom MCP tools for domain operations, Claude as orchestrator.

**Memory Augmentation**: File-based persistent memory converting reasoning into retrievable guidelines.

---

## Ecosystem Gaps (Homelab Opportunities)

1. **Infrastructure-focused agents** - No K8s/Vault/DNS specialist agents exist
2. **Incident response patterns** - Webhook → agent → action flow not well-represented
3. **Multi-cluster orchestration** - Agents spanning systems with proper auth
4. **Homelab-scale solutions** - Most examples target cloud/enterprise or toy demos

---

## Potential Homelab Agent Architectures

### Option A: Incident Response Agent

```
Gatus detects service down
    ↓
Webhook hits agent endpoint (FastAPI)
    ↓
Agent (constrained tools: k8s read-only, logs, dns query)
    - Checks pod status
    - Pulls recent logs
    - Verifies DNS resolution
    - Checks recent deployments
    ↓
Posts structured finding to Slack/ntfy
    ↓
Optionally escalates to full Claude Code session
```

### Option B: Scheduled Health Reporter

```
Cron triggers agent daily
    ↓
Agent queries multiple systems
    - K8s: pod restarts, resource pressure
    - Vault: expiring leases, auth failures
    - DNS: resolution failures
    - Komodo: stack health
    ↓
Generates summary report
    ↓
Posts to designated channel
```

### Option C: GitOps Validator

```
GitHub webhook on PR to vanderlyn repo
    ↓
Agent reviews changes
    - Validates YAML syntax
    - Checks for secret exposure
    - Verifies resource limits set
    - Confirms DNS entries exist for ingresses
    ↓
Posts review comment on PR
```

---

## Technical Considerations

### Authentication

The SDK supports multiple auth methods:
- Claude Code OAuth (automatic when installed)
- API key via `ANTHROPIC_API_KEY`
- Cloud providers: Bedrock (`CLAUDE_CODE_USE_BEDROCK=1`), Vertex (`CLAUDE_CODE_USE_VERTEX=1`)

### Cost Control

```python
options = ClaudeAgentOptions(
    max_turns=10,  # Hard limit on agent loop iterations
)
```

### Tool Restrictions

```python
options = ClaudeAgentOptions(
    allowed_tools=["Read", "Grep", "mcp__k8s__get_pods"],  # Whitelist
    disallowed_tools=["Bash", "Write"],  # Blacklist
)
```

### Session Management

```python
# Resume previous session
options = ClaudeAgentOptions(resume=session_id)

# Fork session (explore without modifying original)
options = ClaudeAgentOptions(fork_session=session_id)
```

---

## References

- [Official SDK Documentation](https://platform.claude.com/docs/en/agent-sdk/overview)
- [Python SDK GitHub](https://github.com/anthropics/claude-agent-sdk-python)
- [SDK Demos](https://github.com/anthropics/claude-agent-sdk-demos)
- [Anthropic Blog: Building Agents](https://www.anthropic.com/engineering/building-agents-with-the-claude-agent-sdk)
