{"id":29806333,"url":"https://github.com/ZhangHanDong/claude-code-api-rs","last_synced_at":"2025-07-28T14:08:07.262Z","repository":{"id":305617551,"uuid":"1023381953","full_name":"ZhangHanDong/claude-code-api-rs","owner":"ZhangHanDong","description":"A high-performance Rust implementation of an OpenAI-compatible API gateway for Claude Code CLI.","archived":false,"fork":false,"pushed_at":"2025-07-21T06:05:03.000Z","size":1,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-07-21T06:23:36.460Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ZhangHanDong.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-21T04:54:08.000Z","updated_at":"2025-07-21T06:05:06.000Z","dependencies_parsed_at":"2025-07-21T06:35:17.806Z","dependency_job_id":null,"html_url":"https://github.com/ZhangHanDong/claude-code-api-rs","commit_stats":null,"previous_names":["zhanghandong/claude-code-api-rs"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/ZhangHanDong/claude-code-api-rs","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZhangHanDong%2Fclaude-code-api-rs","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZhangHanDong%2Fclaude-code-api-rs/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZhangHanDong%2Fclaude-code-api-rs/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZhangHanDong%2Fclaude-code-api-rs/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ZhangHanDong","download_url":"https://codeload.github.com/ZhangHanDong/claude-code-api-rs/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZhangHanDong%2Fclaude-code-api-rs/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":267527835,"owners_count":24102019,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-28T02:00:09.689Z","response_time":68,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-07-28T14:05:57.535Z","updated_at":"2025-07-28T14:08:07.246Z","avatar_url":"https://github.com/ZhangHanDong.png","language":"Rust","readme":"# Claude Code API\n\n[![Version](https://img.shields.io/badge/version-0.1.5-blue.svg)](https://github.com/ZhangHanDong/claude-code-api-rs)\n[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)\n[![Rust](https://img.shields.io/badge/rust-1.75+-orange.svg)](https://www.rust-lang.org)\n\n[中文文档](README_CN.md) | English\n\nA high-performance Rust implementation of an OpenAI-compatible API gateway for Claude Code CLI. Built on top of the robust [claude-code-sdk-rs](https://github.com/ZhangHanDong/claude-code-api-rs/tree/main/claude-code-sdk-rs), this project provides a RESTful API interface that allows you to interact with Claude Code using the familiar OpenAI API format.\n\n## ✨ Features\n\n- **🔌 OpenAI API Compatibility** - Drop-in replacement for OpenAI API, works with existing OpenAI client libraries\n- **🚀 High Performance** - Built with Rust, Axum, and Tokio for exceptional performance\n- **📦 Powered by claude-code-sdk-rs** - Built on a robust SDK with full Claude Code CLI integration\n- **⚡ Connection Pooling** - Reuse Claude processes with optimized connection pooling for 5-10x faster responses\n- **💬 Conversation Management** - Built-in session support for multi-turn conversations\n- **🖼️ Multimodal Support** - Process images alongside text in your requests\n- **⚡ Response Caching** - Intelligent caching system to reduce latency and costs\n- **🔧 MCP Support** - Model Context Protocol integration for accessing external tools and services\n- **📁 File Access Control** - Configurable file system permissions for secure operations\n- **🌊 Streaming Responses** - Real-time streaming support for long-form content\n- **🛡️ Robust Error Handling** - Comprehensive error handling with automatic retries\n- **📊 Statistics API** - Monitor usage and performance metrics\n- **🔄 Multiple Client Modes** - OneShot, Interactive, and Batch processing modes\n\n## 🚀 Quick Start\n\n### Prerequisites\n\n- Rust 1.75 or higher\n- [Claude CLI](https://claude.ai/download) installed and configured\n- (Optional) MCP servers for extended functionality\n\n### Installation\n\n**Option 1: Install from crates.io**\n\n```bash\ncargo install claude-code-api\n```\n\nThen run:\n```bash\nRUST_LOG=info claude-code-api\n# or use the short alias\nRUST_LOG=info ccapi\n```\n\n**Option 2: Build from source**\n\n```bash\ngit clone https://github.com/ZhangHanDong/claude-code-api-rs.git\ncd claude-code-api-rs\n```\n\nBuild the entire workspace (API server + SDK):\n```bash\ncargo build --release\n```\n\nStart the server:\n```bash\n./target/release/claude-code-api\n```\n\n**Note**: The API server automatically includes and uses `claude-code-sdk-rs` for all Claude Code CLI interactions.\n\nThe API server will start on `http://localhost:8080` by default.\n\n### Quick Test\n\n```bash\ncurl -X POST http://localhost:8080/v1/chat/completions \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"model\": \"claude-opus-4-20250514\",\n    \"messages\": [\n      {\"role\": \"user\", \"content\": \"Hello, Claude!\"}\n    ]\n  }'\n```\n\n## 📖 Core Features\n\n### 1. OpenAI-Compatible Chat API\n\n```python\nimport openai\n\n# Configure the client to use Claude Code API\nclient = openai.OpenAI(\n    base_url=\"http://localhost:8080/v1\",\n    api_key=\"not-needed\"  # API key is not required\n)\n\nresponse = client.chat.completions.create(\n    model=\"claude-opus-4-20250514\",\n    messages=[\n        {\"role\": \"user\", \"content\": \"Write a hello world in Python\"}\n    ]\n)\n\nprint(response.choices[0].message.content)\n```\n\n### 2. Conversation Management\n\nMaintain context across multiple requests:\n\n```python\n# First request - creates a new conversation\nresponse = client.chat.completions.create(\n    model=\"claude-opus-4-20250514\",\n    messages=[\n        {\"role\": \"user\", \"content\": \"My name is Alice\"}\n    ]\n)\nconversation_id = response.conversation_id\n\n# Subsequent request - continues the conversation\nresponse = client.chat.completions.create(\n    model=\"claude-opus-4-20250514\",\n    conversation_id=conversation_id,\n    messages=[\n        {\"role\": \"user\", \"content\": \"What's my name?\"}\n    ]\n)\n# Claude will remember: \"Your name is Alice\"\n```\n\n### 3. Multimodal Support\n\nProcess images with text:\n\n```python\nresponse = client.chat.completions.create(\n    model=\"claude-opus-4-20250514\",\n    messages=[{\n        \"role\": \"user\",\n        \"content\": [\n            {\"type\": \"text\", \"text\": \"What's in this image?\"},\n            {\"type\": \"image_url\", \"image_url\": {\"url\": \"/path/to/image.png\"}}\n        ]\n    }]\n)\n```\n\nSupported image formats:\n- Local file paths\n- HTTP/HTTPS URLs\n- Base64 encoded data URLs\n\n### 4. Streaming Responses\n\n```python\nstream = client.chat.completions.create(\n    model=\"claude-opus-4-20250514\",\n    messages=[{\"role\": \"user\", \"content\": \"Write a long story\"}],\n    stream=True\n)\n\nfor chunk in stream:\n    if chunk.choices[0].delta.content:\n        print(chunk.choices[0].delta.content, end=\"\")\n```\n\n### 5. MCP (Model Context Protocol)\n\nEnable Claude to access external tools and services:\n\n```bash\n# Create MCP configuration\ncat \u003e mcp_config.json \u003c\u003c EOF\n{\n  \"mcpServers\": {\n    \"filesystem\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-filesystem\", \"/allowed/path\"]\n    },\n    \"github\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-github\"],\n      \"env\": {\n        \"GITHUB_PERSONAL_ACCESS_TOKEN\": \"your-token\"\n      }\n    }\n  }\n}\nEOF\n\n# Start with MCP support\nexport CLAUDE_CODE__MCP__ENABLED=true\nexport CLAUDE_CODE__MCP__CONFIG_FILE=\"./mcp_config.json\"\n./target/release/claude-code-api\n```\n\n## 🔧 Configuration\n\n### Environment Variables\n\n```bash\n# Server configuration\nCLAUDE_CODE__SERVER__HOST=0.0.0.0\nCLAUDE_CODE__SERVER__PORT=8080\n\n# Claude CLI configuration\nCLAUDE_CODE__CLAUDE__COMMAND=claude\nCLAUDE_CODE__CLAUDE__TIMEOUT_SECONDS=300\nCLAUDE_CODE__CLAUDE__MAX_CONCURRENT_SESSIONS=10\nCLAUDE_CODE__CLAUDE__USE_INTERACTIVE_SESSIONS=true\n\n# File access permissions\nCLAUDE_CODE__FILE_ACCESS__SKIP_PERMISSIONS=false\nCLAUDE_CODE__FILE_ACCESS__ADDITIONAL_DIRS='[\"/path1\", \"/path2\"]'\n\n# MCP configuration\nCLAUDE_CODE__MCP__ENABLED=true\nCLAUDE_CODE__MCP__CONFIG_FILE=\"./mcp_config.json\"\nCLAUDE_CODE__MCP__STRICT=false\nCLAUDE_CODE__MCP__DEBUG=false\n\n# Cache configuration\nCLAUDE_CODE__CACHE__ENABLED=true\nCLAUDE_CODE__CACHE__MAX_ENTRIES=1000\nCLAUDE_CODE__CACHE__TTL_SECONDS=3600\n\n# Conversation management\nCLAUDE_CODE__CONVERSATION__MAX_HISTORY_MESSAGES=20\nCLAUDE_CODE__CONVERSATION__SESSION_TIMEOUT_MINUTES=30\n```\n\n### Configuration File\n\nCreate `config/local.toml`:\n\n```toml\n[server]\nhost = \"0.0.0.0\"\nport = 8080\n\n[claude]\ncommand = \"claude\"\ntimeout_seconds = 300\nmax_concurrent_sessions = 10\nuse_interactive_sessions = false  # Disabled by default due to stability issues\n\n[file_access]\nskip_permissions = false\nadditional_dirs = [\"/Users/me/projects\", \"/tmp\"]\n\n[mcp]\nenabled = true\nconfig_file = \"./mcp_config.json\"\nstrict = false\ndebug = false\n```\n\n## 📦 Built on claude-code-sdk-rs\n\nThis API server is built on top of [claude-code-sdk-rs](https://github.com/ZhangHanDong/claude-code-api-rs/tree/main/claude-code-sdk-rs), a powerful Rust SDK for Claude Code CLI that provides:\n\n- **Full Feature Parity** with the official Python SDK\n- **Multiple Client Types**: \n  - `query()` - Simple one-shot queries\n  - `InteractiveClient` - Stateful conversations with context\n  - `OptimizedClient` - Advanced client with connection pooling and performance features\n- **Streaming Support** - Real-time message streaming\n- **Complete Type Safety** - Strongly typed with serde support\n- **Async/Await** - Built on Tokio for high-performance async operations\n\n### Using the SDK Directly\n\nIf you prefer to build your own integration, you can use the SDK directly:\n\n```toml\n[dependencies]\ncc-sdk = \"0.1.5\"\ntokio = { version = \"1.0\", features = [\"full\"] }\n```\n\n```rust\nuse cc_sdk::{query, ClaudeCodeOptions, PermissionMode};\n\n#[tokio::main]\nasync fn main() -\u003e Result\u003c(), Box\u003cdyn std::error::Error\u003e\u003e {\n    // Simple query\n    let response = query(\"Explain quantum computing\").await?;\n    println!(\"{}\", response);\n\n    // With options\n    let options = ClaudeCodeOptions::builder()\n        .model(\"claude-3.5-sonnet\")\n        .permission_mode(PermissionMode::AcceptAll)\n        .build();\n    \n    let response = cc_sdk::query_with_options(\"Write a haiku\", options).await?;\n    println!(\"{}\", response);\n    \n    Ok(())\n}\n```\n\n## 📚 API Endpoints\n\n### Chat Completions\n- `POST /v1/chat/completions` - Create a chat completion\n\n### Models\n- `GET /v1/models` - List available models\n\n### Conversations\n- `POST /v1/conversations` - Create a new conversation\n- `GET /v1/conversations` - List active conversations\n- `GET /v1/conversations/:id` - Get conversation details\n\n### Statistics\n- `GET /stats` - Get API usage statistics\n\n### Health Check\n- `GET /health` - Check service health\n\n## 🛠️ Advanced Usage\n\n### Using with LangChain\n\n```python\nfrom langchain.chat_models import ChatOpenAI\n\nllm = ChatOpenAI(\n    base_url=\"http://localhost:8080/v1\",\n    api_key=\"not-needed\",\n    model=\"claude-opus-4-20250514\"\n)\n\nresponse = llm.invoke(\"Explain quantum computing\")\nprint(response.content)\n```\n\n### Using with Node.js\n\n```javascript\nconst OpenAI = require('openai');\n\nconst client = new OpenAI({\n  baseURL: 'http://localhost:8080/v1',\n  apiKey: 'not-needed'\n});\n\nasync function chat() {\n  const response = await client.chat.completions.create({\n    model: 'claude-opus-4-20250514',\n    messages: [{ role: 'user', content: 'Hello!' }]\n  });\n\n  console.log(response.choices[0].message.content);\n}\n```\n\n### Using with curl\n\n```bash\n# Basic request\ncurl -X POST http://localhost:8080/v1/chat/completions \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"model\": \"claude-opus-4-20250514\",\n    \"messages\": [{\"role\": \"user\", \"content\": \"Hello\"}]\n  }'\n\n# With conversation ID\ncurl -X POST http://localhost:8080/v1/chat/completions \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"model\": \"claude-opus-4-20250514\",\n    \"conversation_id\": \"uuid-here\",\n    \"messages\": [{\"role\": \"user\", \"content\": \"Continue our chat\"}]\n  }'\n\n# With image\ncurl -X POST http://localhost:8080/v1/chat/completions \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"model\": \"claude-opus-4-20250514\",\n    \"messages\": [{\n      \"role\": \"user\",\n      \"content\": [\n        {\"type\": \"text\", \"text\": \"What is this?\"},\n        {\"type\": \"image_url\", \"image_url\": {\"url\": \"/path/to/image.png\"}}\n      ]\n    }]\n  }'\n```\n\n## 🔒 Security\n\n- File access is controlled through configurable permissions\n- MCP servers run in isolated processes\n- No API key required (relies on Claude CLI authentication)\n- Supports CORS for web applications\n- Request ID tracking for audit trails\n\n## ⚡ Performance Optimization\n\n### Advanced Performance Features (via claude-code-sdk-rs)\n\nThe API leverages advanced performance optimizations from the underlying SDK:\n\n#### Connection Pooling\n- **First request**: 2-5 seconds (with pre-warmed connection pool)\n- **Subsequent requests**: \u003c 0.1 seconds (reusing existing connections)\n- **Concurrent handling**: Multiple requests can share the connection pool\n\n#### Client Modes\n1. **OneShot Mode**: Simple, stateless queries (default)\n2. **Interactive Mode**: Maintains conversation context across requests\n3. **Batch Mode**: Process multiple queries concurrently for high throughput\n\n#### Performance Metrics\n```bash\n# Example performance improvements with OptimizedClient:\n- Sequential queries: ~5s for 5 queries\n- Batch processing: ~1.5s for 5 queries (3x speedup)\n- With connection pooling: \u003c 100ms per query after warm-up\n```\n\n### Configuration for Performance\n\n```toml\n[claude]\nmax_concurrent_sessions = 10  # Increase for higher throughput\nuse_interactive_sessions = true  # Enable for conversation context\ntimeout_seconds = 300  # Adjust based on query complexity\n\n[cache]\nenabled = true\nmax_entries = 1000\nttl_seconds = 3600\n```\n\n### Best Practices\n\n1. **Use the optimized REST endpoints** that leverage `OptimizedClient` from the SDK\n2. **Enable connection pooling** for frequently used endpoints\n3. **Use batch endpoints** for processing multiple queries\n4. **Monitor performance** via the `/stats` endpoint\n5. **Configure appropriate connection pool size** based on load\n\nFor detailed performance tuning, see the [SDK Performance Guide](https://github.com/ZhangHanDong/claude-code-api-rs/tree/main/claude-code-sdk-rs#performance-optimization).\n\n## 🐛 Troubleshooting\n\n### Common Issues\n\n1. **\"Permission denied\" errors**\n   ```bash\n   # Enable file permissions\n   export CLAUDE_CODE__FILE_ACCESS__SKIP_PERMISSIONS=true\n   # Or use the startup script\n   ./start_with_permissions.sh\n   ```\n\n2. **MCP servers not working**\n   ```bash\n   # Enable debug mode\n   export CLAUDE_CODE__MCP__DEBUG=true\n   # Check MCP server installation\n   npx -y @modelcontextprotocol/server-filesystem --version\n   ```\n\n3. **High latency on first request**\n   - This is normal as Claude CLI needs to start up\n   - Subsequent requests will be faster due to process reuse\n\n## 🤝 Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -m 'Add some amazing feature'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Open a Pull Request\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## 🙏 Acknowledgments\n\n- Built on top of [claude-code-sdk-rs](https://github.com/ZhangHanDong/claude-code-api-rs/tree/main/claude-code-sdk-rs) - The robust Rust SDK for Claude Code CLI\n- Powered by [Claude Code CLI](https://claude.ai/download) from Anthropic\n- Inspired by OpenAI's API design for maximum compatibility\n- Web framework: [Axum](https://github.com/tokio-rs/axum) for high-performance HTTP serving\n- Async runtime: [Tokio](https://tokio.rs/) for blazing-fast async I/O\n\n## 📞 Support\n\n- [Report Issues](https://github.com/ZhangHanDong/claude-code-api-rs/issues)\n- [Documentation](https://github.com/ZhangHanDong/claude-code-api-rs/wiki)\n- [Discussions](https://github.com/ZhangHanDong/claude-code-api-rs/discussions)\n\n---\n\nMade with ❤️ by the Claude Code API team\n","funding_links":[],"categories":["SDKs \u0026 Development Kits"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FZhangHanDong%2Fclaude-code-api-rs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FZhangHanDong%2Fclaude-code-api-rs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FZhangHanDong%2Fclaude-code-api-rs/lists"}