Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
C

claude-code-api-rs

> AI 编程
Open source

A high-performance Rust implementation of an OpenAI-compatible API gateway for Claude Code CLI.

174 stars0 likes2 views
WebsiteGitHub

About

A high-performance Rust implementation of an OpenAI-compatible API gateway for Claude Code CLI.

Claude Code API

中文文档 | 日本語 | English


cc-sdk v0.8.1 - Rust SDK for Claude Code

NEW: LLM Proxy — use CC subscription as direct LLM | WebSocket Reconnection | Python SDK v0.1.55 Full Parity cc-sdk is a community-driven Rust SDK for Claude Code CLI:

  • LLM Proxy — llm::query("prompt") → text (bypasses agent layer, uses CC subscription)
  • Full Agent SDK — permissions, hooks, MCP servers, file checkpointing
  • WebSocket — production-grade reconnection with exponential backoff
  • Budget Control — max_budget_usd, cache token tracking
rust
use cc_sdk::llm;

#[tokio::main]
async fn main() -> cc_sdk::Result {
    // Simple: use CC subscription as LLM proxy
    let response = llm::query("Explain quantum entanglement", None).await?;
    println!("{}", response.text);
    Ok(())
}
rust
use cc_sdk::{query, ClaudeCodeOptions};
use futures::StreamExt;

#[tokio::main]
async fn main() -> cc_sdk::Result {
    // Full agent mode with streaming
    let options = ClaudeCodeOptions::builder()
        .model("sonnet")
        .max_budget_usd(10.0)
        .build();

    let mut stream = query("Hello, Claude!", Some(options)).await?;
    while let Some(msg) = stream.next().await {
        println!("{:?}", msg?);
    }
    Ok(())
}

Full SDK Documentation | API Docs


A high-performance Rust implementation of an OpenAI-compatible API gateway for Claude Code CLI. Built on top of the robust cc-sdk, this project provides a RESTful API interface that allows you to interact with Claude Code using the familiar OpenAI API format.

Who's Using Claude Code API

  • url-preview v0.6.0 - A Rust library for extracting structured data from web pages using LLMs. It leverages claude-code-api to provide Claude-powered web content extraction alongside OpenAI support.

✨ Features

  • ** OpenAI API Compatibility** - Drop-in replacement for OpenAI API, works with existing OpenAI client libraries
  • ** High Performance** - Built with Rust, Axum, and Tokio for exceptional performance
  • ** Powered by claude-code-sdk-rs** - Built on a robust SDK with full Claude Code CLI integration
  • ⚡ Connection Pooling - Reuse Claude processes with optimized connection pooling for 5-10x faster responses
  • ** Conversation Management** - Built-in session support for multi-turn conversations
  • ️ Multimodal Support - Process images alongside text in your requests
  • ⚡ Response Caching - Intelligent caching system to reduce latency and costs
  • ** MCP Support** - Model Context Protocol integration for accessing external tools and services
  • ** File Access Control** - Configurable file system permissions for secure operations
  • ** Streaming Responses** - Real-time streaming support for long-form content
  • ️ Robust Error Handling - Comprehensive error handling with automatic retries
  • ** Statistics API** - Monitor usage and performance metrics
  • ** Multiple Client Modes** - OneShot, Interactive, and Batch processing modes
  • ** Tool Calling** - OpenAI tools format support for AI tool integrations
  • ** WebSocket Bridge** - Real-time bidirectional communication between CLI and external clients via WebSocket

Quick Start

Prerequisites

  • Rust 1.75 or higher
  • Claude CLI installed and configured
  • (Optional) MCP servers for extended functionality

Installation

Option 1: Install from crates.io

bash
cargo install claude-code-api

Then run:

bash
RUST_LOG=info claude-code-api
# or use the short alias
RUST_LOG=info ccapi

Option 2: Build from source

bash
git clone https://github.com/ZhangHanDong/claude-code-api-rs.git
cd claude-code-api-rs

Build the entire workspace (API server + SDK):

bash
cargo build --release

Start the server:

bash
./target/release/claude-code-api

Note: The API server automatically includes and uses claude-code-sdk-rs for all Claude Code CLI interactions.

The API server will start on http://localhost:8080 by default.

Quick Test

bash
curl -X POST http://localhost:8080/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-opus-4-5-20251101",
    "messages": [
      {"role": "user", "content": "Hello, Claude!"}
    ]
  }'

Supported Models

Model ID Alias
Opus 4.6 claude-opus-4-6 "opus"
Sonnet 4.6 claude-sonnet-4-6 "sonnet"
Haiku 4.5 claude-haiku-4-5-20251001 "haiku"
bash
# Use aliases — they always point to the latest version
curl -X POST http://localhost:8080/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model": "sonnet", "messages": [{"role": "user", "content": "Hello"}]}'

Core Features

1. OpenAI-Compatible Chat API

python
import openai

# Configure the client to use Claude Code API
client = openai.OpenAI(
    base_url="http://localhost:8080/v1",
    api_key="not-needed"  # API key is not required
)

response = client.chat.completions.create(
    model="opus",  # or "sonnet" for faster responses
    messages=[
        {"role": "user", "content": "Write a hello world in Python"}
    ]
)

print(response.choices[0].message.content)

2. Conversation Management

Maintain context across multiple requests:

python
# First request - creates a new conversation
response = client.chat.completions.create(
    model="sonnet-4",
    messages=[
        {"role": "user", "content": "My name is Alice"}
    ]
)
conversation_id = response.conversation_id

# Subsequent request - continues the conversation
response = client.chat.completions.create(
    model="sonnet-4",
    conversation_id=conversation_id,
    messages=[
        {"role": "user", "content": "What's my name?"}
    ]
)
# Claude will remember: "Your name is Alice"

3. Multimodal Support

Process images with text:

python
response = client.chat.completions.create(
    model="claude-opus-4-20250514",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "What's in this image?"},
            {"type": "image_url", "image_url": {"url": "/path/to/image.png"}}
        ]
    }]
)

Supported image formats:

  • Local file paths
  • HTTP/HTTPS URLs
  • Base64 encoded data URLs

4. Streaming Responses

python
stream = client.chat.completions.create(
    model="claude-opus-4-20250514",
    messages=[{"role": "user", "content": "Write a long story"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")

5. MCP (Model Context Protocol)

Enable Claude to access external tools and services:

bash
# Create MCP configuration
cat > mcp_config.json  cc_sdk::Result {
    // LLM proxy mode — simplest way to use Claude
    let resp = llm::query("Explain quantum computing in one sentence", None).await?;
    println!("{}", resp.text);

    // With custom system prompt
    let opts = LlmOptions::builder()
        .system_prompt("You are a Rust expert. Be concise.")
        .model("sonnet")
        .build();
    let resp = llm::query("What's the difference between Arc and Rc?", Some(opts)).await?;
    println!("{}", resp.text);

    Ok(())
}

API Endpoints

Chat Completions

  • POST /v1/chat/completions - Create a chat completion

Models

  • GET /v1/models - List available models

Conversations

  • POST /v1/conversations - Create a new conversation
  • GET /v1/conversations - List active conversations
  • GET /v1/conversations/:id - Get conversation details

WebSocket Sessions

  • POST /v1/sessions - Create a new WebSocket session (spawns CLI with --sdk-url)
  • GET /v1/sessions - List all active WebSocket sessions
  • GET /v1/sessions/{id} - Get session details
  • DELETE /v1/sessions/{id} - Delete a session (kills CLI process)
  • WS /ws/cli/{session_id} - WebSocket endpoint for CLI process connection
  • WS /ws/session/{session_id} - WebSocket endpoint for external client connection

Statistics

  • GET /stats - Get API usage statistics

Health Check

  • GET /health - Check service health

️ Advanced Usage

Using with LangChain

python
from langchain.chat_models import ChatOpenAI

llm = ChatOpenAI(
    base_url="http://localhost:8080/v1",
    api_key="not-needed",
    model="claude-opus-4-20250514"
)

response = llm.invoke("Explain quantum computing")
print(response.content)

Using with Node.js

javascript
const OpenAI = require('openai');

const client = new OpenAI({
  baseURL: 'http://localhost:8080/v1',
  apiKey: 'not-needed'
});

async function chat() {
  const response = await client.chat.completions.create({
    model: 'claude-opus-4-20250514',
    messages: [{ role: 'user', content: 'Hello!' }]
  });

  console.log(response.choices[0].message.content);
}

Using with curl

…

Security

  • File access is controlled through configurable permissions
  • MCP servers run in isolated processes
  • No API key required (relies on Claude CLI authentication)
  • Supports CORS for web applications
  • Request ID tracking for audit trails

⚡ Performance Optimization

Advanced Performance Features (via claude-code-sdk-rs)

The API leverages advanced performance optimizations from the underlying SDK:

Connection Pooling

  • First request: 2-5 seconds (with pre-warmed connection pool)
  • Subsequent requests: < 0.1 seconds (reusing existing connections)
  • Concurrent handling: Multiple requests can share the connection pool

Client Modes

  1. OneShot Mode: Simple, stateless queries (default)
  2. Interactive Mode: Maintains conversation context across requests
  3. Batch Mode: Process multiple queries concurrently for high throughput

Performance Metrics

bash
# Example performance improvements with OptimizedClient:
- Sequential queries: ~5s for 5 queries
- Batch processing: ~1.5s for 5 queries (3x speedup)
- With connection pooling: < 100ms per query after warm-up

Configuration for Performance

toml
[claude]
max_concurrent_sessions = 10  # Increase for higher throughput
use_interactive_sessions = true  # Enable for conversation context
timeout_seconds = 300  # Adjust based on query complexity

[cache]
enabled = true
max_entries = 1000
ttl_seconds = 3600

Best Practices

  1. Use the optimized REST endpoints that leverage OptimizedClient from the SDK
  2. Enable connection pooling for frequently used endpoints
  3. Use batch endpoints for processing multiple queries
  4. Monitor performance via the /stats endpoint
  5. Configure appropriate connection pool size based on load

For detailed performance tuning, see the SDK Performance Guide.

Troubleshooting

Common Issues

  1. "Permission denied" errors

    bash
    # Enable file permissions
    export CLAUDE_CODE__FILE_ACCESS__SKIP_PERMISSIONS=true
    # Or use the startup script
    ./start_with_permissions.sh
  2. MCP servers not working

    bash
    # Enable debug mode
    export CLAUDE_CODE__MCP__DEBUG=true
    # Check MCP server installation
    npx -y @modelcontextprotocol/server-filesystem --version
  3. High latency on first request

    • This is normal as Claude CLI needs to start up
    • Subsequent requests will be faster due to process reuse

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (`git commi

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rustclaudeclaude-codeclaude-code-agent-rust-sdk

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
CategoryAI 编程
PricingOpen source

> Related tools

G
GitHub Copilot
GitHub 官方 AI 编程助手,覆盖补全、Chat 与 Agent 模式。
C
Cursor
AI 原生代码编辑器,对话改代码、多文件 Agent 与规则体系是其核心。
S
skills
Skills for Real Engineers. Straight from my .agents directory.