/claude-code-fastapi

Claude Code Sandbox with FastAPI Backend

Primary LanguagePythonApache License 2.0Apache-2.0

Claude Code E2B Sandbox FastAPI Example

A FastAPI application that provides a REST API for running Claude Code in E2B sandboxes. This allows you to execute Claude Code commands remotely through HTTP requests, with support for session management and GitHub integration.

Features

  • Remote Claude Code Execution: Run Claude Code commands through HTTP API endpoints
  • Session Management: Resume conversations across multiple requests
  • GitHub Integration: Clone and push repositories to work with code in sandboxes
  • E2B Sandbox Environment: Isolated, secure execution environment
  • MCP (Model Context Protocol) Support: Enhanced capabilities through MCP servers

Prerequisites

  • Python 3.12 or higher
  • E2B account and API key
  • Anthropic API key (for Claude Code)
  • GitHub Personal Access Token (optional, for repository push)
  • Context7 API key (optional, for MCP Context7 server)

Installation

  1. Clone the repository:
git clone https://github.com/e2b-dev/claude-code-fastapi
cd claude-code-fastapi
  1. Install dependencies using uv (recommended):
uv sync

Or using pip:

pip install -e .

Environment Variables

Create a .env file in the project root with the following variables:

# Required
ANTHROPIC_API_KEY=your_anthropic_api_key_here
E2B_API_KEY=your_e2b_api_key_here

# Optional
E2B_SANDBOX_TEMPLATE=claude-code-dev  # or claude-code for production
GITHUB_PAT=your_github_personal_access_token_here
CONTEXT7_API_KEY=your_context7_api_key_here  # for MCP Context7 server

Environment Variable Propagation: The following environment variables are automatically passed to each E2B sandbox:

  • GITHUB_PAT - For GitHub repository access
  • CONTEXT7_API_KEY - For MCP Context7 server functionality
  • ANTHROPIC_API_KEY - For Claude Code execution

Building Templates

Development Template

Build the development template:

cd template
python build_dev.py

This creates a template with:

  • 2 CPU core
  • 4096 MB memory
  • Alias: claude-code-dev

Production Template

Build the production template:

cd template
python build.py

This creates a template with:

  • 2 CPU core
  • 4096 MB memory
  • Alias: claude-code

Running the Application

  1. Start the FastAPI server:
uvicorn app.main:app --reload

The API will be available at http://localhost:8000

  1. Access the interactive API documentation:
http://localhost:8000/docs

API Usage

POST /chat

Start a new conversation with Claude Code:

curl -X POST "http://localhost:8000/chat" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Can you add GPT 3.5-Turbo to the list of models and open a pull request on GitHub",
    "repo": "https://github.com/e2b-dev/fragments"
  }'

POST /chat/{session}

Resume an existing conversation using a session ID:

curl -X POST "http://localhost:8000/chat/038b769b-4717-47ca-be02-2a49bd7da978" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Now modify the script to accept a name parameter"
  }'

Request Body

{
  "prompt": "string", // Required: The prompt/command for Claude Code
  "repo": "string" // Optional: GitHub repository URL to clone (only for new sessions)
}

Note: When using /chat/{session}, the repo parameter is ignored as the repository is already cloned in the existing sandbox session.

Response

{
  "type": "result",
  "subtype": "success",
  "is_error": false,
  "duration_ms": 216401,
  "duration_api_ms": 216234,
  "num_turns": 81,
  "result": "Perfect! I have successfully completed all the tasks:\n\n✅ **All tasks completed!** The pull request has been created at: https://github.com/e2b-dev/fragments/pull/170\n\n## Summary\n\nI've successfully added GPT-3.5 Turbo to the model list and opened a pull request with the following changes:\n\n- **Added GPT-3.5 Turbo** to `/home/user/fragments/lib/models.json:108-114`\n- **Model configuration**:\n  - ID: `gpt-3.5-turbo`\n  - Provider: OpenAI\n  - Name: GPT-3.5 Turbo  \n  - Multimodal: false\n- **Validated** JSON syntax is correct\n- **Created branch** `add-gpt-3.5-turbo` \n- **Opened PR #170** with comprehensive description\n\nThe pull request is ready for review and includes all the necessary changes to integrate GPT-3.5 Turbo into the fragments application.",
  "session_id": "038b769b-4717-47ca-be02-2a49bd7da978",
  "total_cost_usd": 1.1459241,
  "usage": {
    "input_tokens": 300,
    "cache_creation_input_tokens": 77458,
    "cache_read_input_tokens": 2087724,
    "output_tokens": 13935,
    "server_tool_use": {
      "web_search_requests": 0
    },
    "service_tier": "standard"
  },
  "permission_denials": []
}

MCP Servers

You can add your own MCP servers to Claude Code by editing the template/.mcp.json file.

{
  "mcpServers": {
    "context7": {
      "type": "http",
      "url": "https://mcp.context7.com/mcp",
      "headers": {
        "Authorization": "Bearer ${CONTEXT7_API_KEY}"
      }
    }
  }
}