A high-performance Rust implementation of an OpenAI-compatible API gateway for Claude Code CLI.
A high-performance Rust implementation of an OpenAI-compatible API gateway for Claude Code CLI.
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::query("prompt") → text (bypasses agent layer, uses CC subscription)max_budget_usd, cache token trackinguse 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(())
}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.
Option 1: Install from crates.io
cargo install claude-code-apiThen run:
RUST_LOG=info claude-code-api
# or use the short alias
RUST_LOG=info ccapiOption 2: Build from source
git clone https://github.com/ZhangHanDong/claude-code-api-rs.git
cd claude-code-api-rsBuild the entire workspace (API server + SDK):
cargo build --releaseStart the server:
./target/release/claude-code-apiNote: 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.
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!"}
]
}'| 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" |
# 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"}]}'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)Maintain context across multiple requests:
# 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"Process images with text:
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:
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="")Enable Claude to access external tools and services:
# 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(())
}POST /v1/chat/completions - Create a chat completionGET /v1/models - List available modelsPOST /v1/conversations - Create a new conversationGET /v1/conversations - List active conversationsGET /v1/conversations/:id - Get conversation detailsPOST /v1/sessions - Create a new WebSocket session (spawns CLI with --sdk-url)GET /v1/sessions - List all active WebSocket sessionsGET /v1/sessions/{id} - Get session detailsDELETE /v1/sessions/{id} - Delete a session (kills CLI process)WS /ws/cli/{session_id} - WebSocket endpoint for CLI process connectionWS /ws/session/{session_id} - WebSocket endpoint for external client connectionGET /stats - Get API usage statisticsGET /health - Check service healthfrom 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)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);
}…The API leverages advanced performance optimizations from the underlying SDK:
# 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[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 = 3600OptimizedClient from the SDK/stats endpointFor detailed performance tuning, see the SDK Performance Guide.
"Permission denied" errors
# Enable file permissions
export CLAUDE_CODE__FILE_ACCESS__SKIP_PERMISSIONS=true
# Or use the startup script
./start_with_permissions.shMCP servers not working
# Enable debug mode
export CLAUDE_CODE__MCP__DEBUG=true
# Check MCP server installation
npx -y @modelcontextprotocol/server-filesystem --versionHigh latency on first request
Contributions are welcome! Please feel free to submit a Pull Request.
git checkout -b feature/amazing-feature)No open issues yet, or sync has not completed.