ClaudeAgentSdk 0.2.1
dotnet add package ClaudeAgentSdk --version 0.2.1
NuGet\Install-Package ClaudeAgentSdk -Version 0.2.1
<PackageReference Include="ClaudeAgentSdk" Version="0.2.1" />
<PackageVersion Include="ClaudeAgentSdk" Version="0.2.1" />
<PackageReference Include="ClaudeAgentSdk" />
paket add ClaudeAgentSdk --version 0.2.1
#r "nuget: ClaudeAgentSdk, 0.2.1"
#:package ClaudeAgentSdk@0.2.1
#addin nuget:?package=ClaudeAgentSdk&version=0.2.1
#tool nuget:?package=ClaudeAgentSdk&version=0.2.1
Claude Agent SDK for .NET (Unofficial)
Unofficial .NET SDK for Claude Code. Build production-ready AI applications with Claude's advanced code generation, analysis, and agentic capabilities.
๐ฏ Status: Production Ready | ๐ Docs: Complete
Note: This is an unofficial community SDK. For official Anthropic SDKs, visit anthropic.com.
โจ Features
- ๐ Simple Query API - One-shot queries with
ClaudeAgent.QueryAsync() - ๐ฌ Interactive Client - Multi-turn conversations with
ClaudeSdkClient - ๐ก Streaming Responses - Real-time partial message updates
- ๐ ๏ธ Tool Support - File operations (Read, Write, Edit), Bash commands, Web fetching
- ๐ Type-Safe - Strongly-typed messages and content blocks
- โก Async/Await - Built on modern C# async patterns with
IAsyncEnumerable<T> - ๐ฏ Error Handling - Comprehensive exception hierarchy
- ๐งน Resource Management - Automatic cleanup with
IAsyncDisposable - โ Battle-Tested - 117 comprehensive tests covering edge cases
- ๐ Todo & Token Tracking - Monitor Claude's task progress and API usage
- ๐ Well-Documented - Complete guides and interactive examples
๐ฆ Installation
Via NuGet Package Manager
dotnet add package ClaudeAgentSdk
Prerequisites
.NET 8.0 or higher
dotnet --version # Should be 8.0+Claude Code CLI
npm install -g @anthropic-ai/claude-codeAnthropic API Key - Set as environment variable:
# Windows (PowerShell) $env:ANTHROPIC_API_KEY = "your-api-key-here" # Linux/macOS export ANTHROPIC_API_KEY="your-api-key-here"
๐ Quick Start
Simple Query
using ClaudeAgentSdk;
await foreach (var message in ClaudeAgent.QueryAsync("What is 2 + 2?"))
{
if (message is AssistantMessage assistantMsg)
{
foreach (var block in assistantMsg.Content)
{
if (block is TextBlock textBlock)
{
Console.WriteLine(textBlock.Text);
}
}
}
else if (message is ResultMessage resultMsg)
{
Console.WriteLine($"โ Completed in {resultMsg.DurationMs}ms");
}
}
Interactive Multi-Turn Conversation
using ClaudeAgentSdk;
var options = new ClaudeAgentOptions { MaxTurns = 50 };
await using var client = new ClaudeSdkClient(options);
await client.ConnectAsync();
// First query
await client.QueryAsync("Create a Python web server");
await foreach (var msg in client.ReceiveResponseAsync())
{
// Handle response...
}
// Follow-up query in same session
await client.QueryAsync("Now add authentication to it");
await foreach (var msg in client.ReceiveResponseAsync())
{
// Handle response...
}
With Tool Support
var options = new ClaudeAgentOptions
{
AllowedTools = new List<string> { "Read", "Write", "Edit", "Bash" },
PermissionMode = PermissionMode.Default
};
await foreach (var message in ClaudeAgent.QueryAsync(
"Create a file called hello.txt with 'Hello World'", options))
{
if (message is AssistantMessage assistantMsg)
{
foreach (var block in assistantMsg.Content)
{
if (block is ToolUseBlock toolUse)
{
Console.WriteLine($"๐ง Using tool: {toolUse.Name}");
}
}
}
}
Tracking Todo Tasks and Token Usage
await foreach (var message in ClaudeAgent.QueryAsync("Build a REST API with auth"))
{
switch (message)
{
case SystemMessage { Subtype: "todo" } sysMsg:
// Display Claude's todo list
break;
case AssistantMessage { Content: var content }:
foreach (var block in content)
{
if (block is ToolUseBlock { Name: "TodoWrite" } toolUse)
{
// Parse and display todos from toolUse.Input
}
}
break;
case ResultMessage resultMsg:
// Display token usage and cost
var inputTokens = resultMsg.Usage["input_tokens"];
var outputTokens = resultMsg.Usage["output_tokens"];
Console.WriteLine($"Tokens: {inputTokens + outputTokens:N0}");
Console.WriteLine($"Cost: ${resultMsg.TotalCostUsd:F6}");
break;
}
}
๐ Documentation
Guides
- Getting Started Guide - Comprehensive tutorial with code examples
- Tracking Guide - Monitor todos, tokens, and costs in real-time
- Implementation Notes - Technical architecture and design decisions
- Project Summary - Overview of all components
Examples
- ClaudeChat - Full-featured interactive CLI application
- Simple query mode
- Interactive conversation mode
- Streaming mode
- Tools demo mode
- Todo and usage tracking mode
API Reference
Core Types
ClaudeAgent- Static class for simple queriesQueryAsync(prompt, options)- Execute a one-shot query
ClaudeSdkClient- Interactive client for multi-turn conversationsConnectAsync(prompt?)- Connect to ClaudeQueryAsync(prompt)- Send a queryReceiveResponseAsync()- Receive messages until ResultMessageReceiveMessagesAsync()- Receive all messages continuously
Message Types
Message- Base class for all messagesAssistantMessage- Messages from ClaudeUserMessage- Messages from userSystemMessage- System notifications (including todos)ResultMessage- Query completion with metricsStreamEvent- Streaming progress updates
Content Blocks
TextBlock- Text contentThinkingBlock- Claude's internal reasoningToolUseBlock- Tool invocationToolResultBlock- Tool execution result
Options
public class ClaudeAgentOptions
{
public List<string> AllowedTools { get; set; } // ["Read", "Write", "Bash"]
public List<string> DisallowedTools { get; set; }
public string? SystemPrompt { get; set; }
public PermissionMode? PermissionMode { get; set; } // Default, AllowAll, Deny
public int? MaxTurns { get; set; } // Default: 25
public string? Model { get; set; } // Default: claude-sonnet-4
public bool IncludePartialMessages { get; set; } // Enable streaming
public string? Cwd { get; set; } // Working directory
public Dictionary<string, string> Env { get; set; } // Environment variables
// ... and more
}
๐ฏ Use Cases
Code Generation
await foreach (var msg in ClaudeAgent.QueryAsync(
"Create a REST API for a blog with CRUD operations in C#"))
{
// Claude will generate the code with proper structure
}
Code Analysis
var options = new ClaudeAgentOptions
{
AllowedTools = new List<string> { "Read", "Grep" }
};
await foreach (var msg in ClaudeAgent.QueryAsync(
"Analyze the code in src/ directory for potential bugs", options))
{
// Claude will read and analyze your code
}
File Operations
var options = new ClaudeAgentOptions
{
AllowedTools = new List<string> { "Read", "Write", "Edit" }
};
await foreach (var msg in ClaudeAgent.QueryAsync(
"Refactor all .cs files to use nullable reference types", options))
{
// Claude will read, analyze, and modify files
}
Testing and QA
var options = new ClaudeAgentOptions
{
AllowedTools = new List<string> { "Read", "Write", "Bash" }
};
await foreach (var msg in ClaudeAgent.QueryAsync(
"Create unit tests for MyService.cs and run them", options))
{
// Claude will write tests and execute them
}
๐ง Advanced Features
Custom Transport
public class MyCustomTransport : ITransport
{
public bool IsReady => true;
public async Task ConnectAsync(CancellationToken ct) { /* ... */ }
public async IAsyncEnumerable<Dictionary<string, object>> ReadMessagesAsync(
CancellationToken ct)
{
// Custom message reading logic
yield return message;
}
public async Task WriteAsync(string data, CancellationToken ct) { /* ... */ }
}
var client = new ClaudeSdkClient(options, new MyCustomTransport());
Permission Callbacks
var options = new ClaudeAgentOptions
{
CanUseTool = (toolName, toolInput) =>
{
Console.WriteLine($"Allow tool {toolName}?");
var response = Console.ReadLine();
return response?.ToLower() == "yes"
? PermissionBehavior.Allow
: PermissionBehavior.Deny;
}
};
Error Handling
try
{
await foreach (var msg in ClaudeAgent.QueryAsync("Your query"))
{
// Process messages
}
}
catch (CliNotFoundException ex)
{
Console.WriteLine("Claude Code CLI not found. Install with:");
Console.WriteLine(" npm install -g @anthropic-ai/claude-code");
}
catch (CliConnectionException ex)
{
Console.WriteLine($"Connection error: {ex}");
}
catch (ProcessException ex)
{
Console.WriteLine($"Process failed: {ex.ExitCode}");
}
๐ฆ Building NuGet Package
cd src/ClaudeAgentSdk
dotnet pack --configuration Release
The package will be created in bin/Release/ClaudeAgentSdk.0.1.0.nupkg
Publishing to NuGet
dotnet nuget push bin/Release/ClaudeAgentSdk.0.1.0.nupkg \
--api-key YOUR_API_KEY \
--source https://api.nuget.org/v3/index.json
๐ค Contributing
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development Setup
# Clone repository
git clone https://github.com/gunpal5/claude-agent-sdk-dotnet.git
cd claude-agent-sdk-dotnet
# Restore dependencies
dotnet restore
# Build
dotnet build
# Run example
cd examples/ClaudeChat
dotnet run
๐ License
MIT License - see LICENSE file for details.
๐ Links
- NuGet Package: https://www.nuget.org/packages/ClaudeAgentSdk/
- GitHub Repository: https://github.com/gunpal5/claude-agent-sdk-dotnet
- Official Python SDK: https://github.com/anthropics/claude-agent-sdk-python
- Claude Code Documentation: https://docs.claude.com/claude-code
- Anthropic Website: https://anthropic.com
๐ก Support
- Documentation: See guides in this repository
- Issues: Report bugs via GitHub Issues
- Discussions: Join GitHub Discussions
- Claude Code Help: https://docs.claude.com/claude-code
๐ Example Projects
Check out the examples/ directory for complete working examples:
- ClaudeChat - Interactive CLI with 5 modes (simple, interactive, streaming, tools, stats)
- TodoAndUsageExample - Real-time tracking of todos and token usage
โก Performance
- Streaming responses with minimal latency
- Efficient JSON parsing with System.Text.Json
- Async/await throughout for non-blocking I/O
- Automatic resource cleanup
- Subprocess communication optimized for large outputs (1MB buffer)
๐ Security
- API keys handled securely via environment variables
- Permission modes for tool usage control
- Custom tool approval callbacks
- No sensitive data logged by default
- Process isolation for CLI execution
๐ Metrics & Monitoring
Track your usage:
if (message is ResultMessage result)
{
// Token usage
var tokens = result.Usage["input_tokens"] + result.Usage["output_tokens"];
// Cost in USD
var cost = result.TotalCostUsd;
// Performance
var duration = result.DurationMs;
var apiTime = result.DurationApiMs;
// Conversation
var turns = result.NumTurns;
}
๐ Why This SDK?
- Production-Ready: Complete port of the official Python SDK
- Idiomatic C#: Async/await, IAsyncEnumerable, IAsyncDisposable patterns
- Type-Safe: Strong typing throughout with nullable reference types
- Well-Tested: 117 comprehensive tests ensure reliability
- Community-Driven: Open source and community maintained
- Great Documentation: Multiple guides and working examples
This is an unofficial community SDK. For official Anthropic SDKs, visit anthropic.com.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.0
- Microsoft.Extensions.AI.Abstractions (>= 9.10.1)
- System.Text.Json (>= 9.0.10)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
v0.1.0 - Initial Release
- Simple query API with ClaudeAgent.QueryAsync()
- Interactive multi-turn conversations with ClaudeSdkClient
- Streaming response support
- Comprehensive tool support (Read, Write, Edit, Bash, etc.)
- Type-safe message and content block handling
- Full async/await support
- 117 comprehensive tests with 100% pass rate
- Complete documentation and examples