https://github.com/sweihub/ai-agent-sdk
Idiomatic agent sdk inspired by the claude code source leak.
https://github.com/sweihub/ai-agent-sdk
claude-agent-sdk claudecode
Last synced: 3 months ago
JSON representation
Idiomatic agent sdk inspired by the claude code source leak.
- Host: GitHub
- URL: https://github.com/sweihub/ai-agent-sdk
- Owner: sweihub
- Created: 2026-04-02T05:11:28.000Z (3 months ago)
- Default Branch: main
- Last Pushed: 2026-04-07T14:45:05.000Z (3 months ago)
- Last Synced: 2026-04-07T17:02:46.876Z (3 months ago)
- Topics: claude-agent-sdk, claudecode
- Language: Rust
- Homepage:
- Size: 1.38 MB
- Stars: 10
- Watchers: 0
- Forks: 3
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# AI Agent SDK (Rust)
[](https://crates.io/crates/ai-agent-sdk)
[](https://www.rust-lang.org)
[](./LICENSE)
[English](README.md) | [中文](READCN.md)
One to one Rust translation of `claude code source`.
Idiomatic agent sdk inspired by the `claude code source` leak, written in Rust that runs the full agent loop **in-process** — no subprocess or CLI required. Deploy anywhere: cloud, serverless, Docker, CI/CD.
## Quick Demo
```rust
use ai_agent_sdk::Agent;
let mut agent = Agent::new("MiniMaxAI/MiniMax-M2.5", 10);
let result = agent.prompt("List files in current directory").await?;
println!("{}", result.text);
```
> That's it! The agent automatically uses 20+ built-in tools (Bash, Read, Write, Edit, Glob, Grep, WebFetch, etc.) to accomplish tasks.
## Core Features
| Feature | Description |
|---------|-------------|
| **Agent** | Create agents with custom models, tools, and prompts |
| **Subagent** | Spawn subagents for parallel or specialized tasks |
| **Session** | Persist, resume, fork conversations on disk |
| **Skills** | Load external skills or use 15+ bundled skills |
| **Command** | Register and execute slash commands with arguments |
| **Plugin** | Load plugins with commands, skills, MCP servers |
| **Hooks** | 20+ lifecycle events for custom workflows |
| **Tools** | 20+ built-in tools + custom tool registration |
| **Memory** | Automatic session memory management |
| **Permission** | Tool access control with modes and rules |
| **Services** | Retry, rate limiting, token estimation, model cost |
## Quick Start
Install:
```bash
cargo add ai-agent-sdk
```
Configure your API key:
```bash
export AI_AUTH_TOKEN=your-api-key
export AI_MODEL=MiniMaxAI/MiniMax-M2.5
```
Or use `.env` file:
```text
AI_AUTH_TOKEN=your-token
AI_MODEL=MiniMaxAI/MiniMax-M2.5
AI_BASE_URL=https://api.minimax.chat/v1
```
### Simple Prompt
```rust
use ai_agent_sdk::Agent;
let mut agent = Agent::new("MiniMaxAI/MiniMax-M2.5", 10);
let result = agent.prompt("What files are in this project?").await?;
println!("{}", result.text);
```
### Multi-turn Conversation
```rust
use ai_agent_sdk::Agent;
let mut agent = Agent::new("MiniMaxAI/MiniMax-M2.5", 5);
let r1 = agent.prompt("Create file /tmp/hello.txt with 'Hello'").await?;
let r2 = agent.prompt("Read that file back").await?;
println!("Session messages: {}", agent.get_messages().len());
```
### Custom Tools
```rust
use ai_agent_sdk::{Agent, ToolDefinition, ToolInputSchema};
fn calculator_impl(input: serde_json::Value, _ctx: ()) -> impl std::future::Future> + Send {
async move {
let expr = input["expression"].as_str().unwrap_or("0");
Ok(ai_agent_sdk::ToolResult {
result_type: "tool_result".to_string(),
tool_use_id: "".to_string(),
content: format!("Result of {}", expr),
is_error: None,
})
}
}
let calculator = ai_agent_sdk::Tool {
name: "Calculator".to_string(),
description: "Evaluate math expressions".to_string(),
input_schema: ToolInputSchema::Json(serde_json::json!({
"type": "object",
"properties": {"expression": {"type": "string"}},
"required": ["expression"]
})),
executor: Box::new(calculator_impl),
};
let mut agent = Agent::new("MiniMaxAI/MiniMax-M2.5", 10);
// Note: Tool registration via agent tools currently uses ToolDefinition
```
### MCP Servers
```rust
use ai_agent_sdk::{Agent, McpServerConfig};
let config = McpServerConfig::Stdio(ai_agent_sdk::McpStdioConfig {
command: "npx".to_string(),
args: Some(vec!["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]),
..Default::default()
});
let mut agent = Agent::new("MiniMaxAI/MiniMax-M2.5", 10);
// Note: MCP servers configured via AgentOptions
```
### Subagents
```rust
use ai_agent_sdk::{Agent, AgentDefinition};
let mut agent = Agent::new("MiniMaxAI/MiniMax-M2.5", 10);
// Note: Subagents are used via the Agent tool at runtime
```
### Skills
```rust
use ai_agent_sdk::{Agent, load_skill_from_dir};
let skill = load_skill_from_dir("skills/debug")?;
let mut agent = Agent::new("MiniMaxAI/MiniMax-M2.5", 10);
// Note: Skills are applied via agent configuration
```
### Plugin System
```rust
use ai_agent_sdk::{load_plugin, load_plugins_from_dir, CommandRegistry};
let plugin = load_plugin("plugins/hello-plugin").await?;
let plugins = load_plugins_from_dir("plugins").await?;
let registry = CommandRegistry::new();
```
### Hooks
```rust
use ai_agent_sdk::hooks::{HookRegistry, HookDefinition, HookInput};
let mut registry = HookRegistry::new();
registry.register("PreToolUse", HookDefinition {
command: Some("echo pre-tool".to_string()),
timeout: Some(5000),
matcher: Some("Read.*".to_string()),
});
let mut input = HookInput::new("PreToolUse");
input.tool_name = Some("Read".to_string());
let results = registry.execute("PreToolUse", input).await;
```
## Configuration
### Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `model` | string | MiniMaxAI/MiniMax-M2.5 | LLM model ID |
| `api_key` | string | env var | API key |
| `base_url` | string | — | Custom API endpoint |
| `cwd` | string | process.cwd() | Working directory |
| `max_turns` | u32 | 10 | Max agentic turns |
| `max_budget_usd` | f64 | — | Spending cap |
| `max_tokens` | u32 | 16384 | Max response tokens |
| `tools` | Vec | All built-in | Available tools |
| `allowed_tools` | Vec | — | Tool allow-list |
| `disallowed_tools` | Vec | — | Tool deny-list |
### Environment Variables
| Variable | Description |
|----------|-------------|
| `AI_AUTH_TOKEN` | API authentication token (required) |
| `AI_MODEL` | Model name |
| `AI_BASE_URL` | API endpoint |
### Context & Memory
| Variable | Default | Description |
|----------|---------|-------------|
| `AI_CONTEXT_WINDOW` | 200000 | Override context window size |
| `AI_DISABLE_AUTO_MEMORY` | false | Disable automatic memory |
| `AI_MEMORY_PATH_OVERRIDE` | ~/.ai | Override memory directory |
| `AI_REMOTE_MEMORY_DIR` | — | Remote/shared memory directory |
| `AI_SIMPLE` | false | Use simple memory mode |
### Auto-Compact
| Variable | Default | Description |
|----------|---------|-------------|
| `AI_AUTO_COMPACT_WINDOW` | model-based | Override auto-compact trigger window |
| `AI_AUTOCOMPACT_PCT_OVERRIDE` | — | Override threshold as % (0-100) |
| `AI_BLOCKING_LIMIT_OVERRIDE` | — | Override blocking limit for testing |
## Built-in Tools
| Tool | Description |
|------|-------------|
| **Bash** | Execute shell commands |
| **Read** | Read files with line numbers |
| **Write** | Create / overwrite files |
| **Edit** | Precise string replacement |
| **Glob** | Find files by pattern |
| **Grep** | Search with regex |
| **WebFetch** | Fetch web content |
| **WebSearch** | Web search |
| **NotebookEdit** | Edit Jupyter cells |
| **Agent** | Spawn subagents |
| **TaskCreate/List/Update/Get** | Task management |
| **TeamCreate/Delete** | Multi-agent teams |
| **SendMessage** | Inter-agent messaging |
| **EnterWorktree/ExitWorktree** | Git worktree |
| **EnterPlanMode/ExitPlanMode** | Planning workflow |
| **AskUserQuestion** | Request user input |
| **CronCreate/Delete/List** | Scheduled tasks |
| **TodoWrite** | Session todo list |
## Architecture
```
┌─────────────────────────────────────┐
│ Your Application │
│ use ai_agent_sdk::Agent │
└──────────────┬──────────────────────┘
│
┌──────────▼──────────┐
│ Agent │ Session state, tools
│ prompt() │ MCP connections
└──────────┬──────────┘
│
┌──────────▼──────────┐
│ QueryEngine │ Agent loop:
│ submitMessage() │ API → tools → repeat
└──────────┬──────────┘
│
┌──────────┼──────────┐
│ │ │
┌───▼───┐ ┌───▼───┐ ┌──▼────┐
│ LLM │ │ 20+ │ │ MCP │
│ API │ │Tools │ │Server │
└───────┘ └───────┘ └───────┘
```
## Examples
Run examples from `examples/` directory:
```bash
# Configure your .env first
cargo run --example 01_simple_query
cargo run --example 18_plugin
cargo run --example 19_hooks
```
## License
MIT