npm package: @posthog/code-agent
Description: Unified TypeScript SDK for coding agents (Claude Code + Codex) with MCP Bridge
Author: Peter K.
Latest version: 0.2.0

# Code Agent SDK

A unified TypeScript SDK for orchestrating coding agent tasks using Claude Code (Anthropic) or OpenAI models with MCP (Model Context Protocol) bridge support.

## Features

- **Unified Interface**: Single API for both Anthropic and OpenAI coding agents
- **MCP Bridge**: Register and use MCP tools across different agent implementations
- **Streaming Events**: Real-time event stream for tokens, tool calls, diffs, and metrics
- **Auth Discovery**: Ambient authentication from environment variables
- **Diff Normalization**: Standardized code change representation across vendors
- **Task Management**: Async task lifecycle with cancellation support
- **Unified Permissions**: Common permission modes that work across providers
- **Tool Execution**: Built-in tool execution with configurable permissions

## Installation

```bash
npm install @code-agent/sdk
```

## Quick Start

```typescript
import { createAgent, ClaudeCodeAgent, CodexAgent } from '@code-agent/sdk';

// Using Claude Code
const claudeAgent = createAgent(new ClaudeCodeAgent({ 
  model: 'claude-3-5-sonnet-20241022' 
}));

// Using OpenAI Codex
const openAIAgent = createAgent(new CodexAgent({ 
  profile: 'balanced' 
}));

// Run a task
const { taskId, stream } = await claudeAgent.run({
  prompt: 'Add a health check endpoint to the Express server',
  repoPath: process.cwd(),
  onEvent: (event) => {
    console.log(event.type, event);
  }
});

// Stream events
for await (const event of stream) {
  if (event.type === 'token') {
    process.stdout.write(event.content);
  }
}

// Wait for completion
const result = await claudeAgent.waitForCompletion(taskId);
```

## MCP Integration

```typescript
await agent.run({
  prompt: 'Create a pull request for the new feature',
  mcp: {
    servers: [
      { 
        id: 'github', 
        transport: 'sse', 
        url: 'https://mcp.github.example/sse' 
      }
    ],
    allowTools: ['github.create_pr', 'github.list_branches']
  }
});
```

## Unified Permissions

The SDK provides unified permission modes that work consistently across providers:

### Permission Modes

- `strict`: Restrictive mode, limits tool usage (maps to read-only for Codex, default for Claude)
- `auto`: Balanced mode, auto-approves safe operations (maps to auto for both)
- `permissive`: Allows all operations (maps to full-access for Codex, bypassPermissions for Claude)

### Basic Usage

```typescript
// Works with both Claude and OpenAI
await agent.run({
  prompt: 'Create a new feature',
  permissionMode: 'auto', // Unified mode
  tools: {
    allow: ['Read', 'Write', 'Edit'],     // Only allow these tools
    deny: ['Bash', 'WebSearch'],          // Block these tools
    autoApprove: ['Read', 'Glob']         // Auto-approve these without prompts
  }
});
```

### Vendor-Specific Permissions

For fine-grained control, use vendor-specific configurations:

```typescript
// Claude Code specific
const claudeAgent = createAgent(new ClaudeCodeAgent({
  vendor: {
    anthropic: {
      permissionMode: 'bypassPermissions',  // Claude-specific mode
      canUseTool: async (toolName, input, options) => {
        // Custom approval logic
        if (toolName === 'Write' && input.file_path?.includes('.env')) {
          return { behavior: 'deny', message: 'Cannot write to .env files' };
        }
        return { behavior: 'allow', updatedInput: input };
      },
      hooks: {
        PreToolUse: [{
          hooks: [async (input) => {
            console.log(`Tool called: ${input.tool_name}`);
            return { continue: true };
          }]
        }]
      }
    }
  }
}));

// OpenAI Codex specific
const codexAgent = createAgent(new CodexAgent({
  vendor: {
    openai: {
      approvalMode: 'full-access',  // Codex-specific mode
      profile: 'high',
      verbose: true
    }
  }
}));
```

### Mixed Approach

Combine unified settings with vendor overrides:

```typescript
await agent.run({
  prompt: 'Add tests for the new feature',
  
  // Unified settings
  permissionMode: 'auto',
  tools: { allow: ['Read', 'Write', 'Edit'] },
  
  // Vendor overrides (these take precedence)
  vendor: {
    anthropic: {
      permissionMode: 'acceptEdits',  // Override unified mode
      model: 'claude-3-opus-20240229'
    }
  }
});
```

## Authentication

The SDK discovers credentials from environment:
- `ANTHROPIC_API_KEY` for Claude Code
- `OPENAI_API_KEY` for OpenAI/Codex

Override per-run:
```typescript
await agent.run({
  prompt: 'Refactor the utils module',
  auth: { 
    anthropicApiKey: 'sk-ant-...' 
  }
});
```

## Tool Execution

The Claude Code SDK includes built-in tool execution for file operations, bash commands, and more. The SDK executes these tools directly rather than just suggesting changes:

```typescript
// The agent will actually create/edit files and run commands
await agent.run({
  prompt: 'Create a new Express server with error handling',
  permissionMode: 'auto',  // Will prompt for dangerous operations
  tools: {
    allow: ['Read', 'Write', 'Edit', 'Bash'],
    autoApprove: ['Read']  // Never prompt for read operations
  }
});
```

### Available Tools

- **File Operations**: `Read`, `Write`, `Edit`, `MultiEdit`
- **Search**: `Grep`, `Glob`, `LS`
- **Execution**: `Bash` (with timeout and background support)
- **Web**: `WebSearch`, `WebFetch` 
- **Notebooks**: `NotebookRead`, `NotebookEdit`
- **Task Management**: `TodoWrite`
- **MCP Tools**: Any tools provided by MCP servers

## Event Types

- `status`: Task lifecycle phases
- `token`: Streaming text output
- `tool_call`/`tool_result`: Tool execution events
- `diff`: Code changes in unified diff format
- `file_write`: File modifications
- `metric`: Performance metrics
- `error`: Error events