MarketAlly.AIPlugin.Extensions/MarketAlly.AIPlugin.ClaudeCode/README.md

9.9 KiB
Executable File

MarketAlly Claude Code Integration

This package provides comprehensive .NET integration for Claude Code with intelligent rate limiting, learning capabilities, and enterprise-grade features.

Features

  • 🚦 Intelligent Rate Limiting: Multi-tier support with automatic retry and exponential backoff
  • 🧠 Learning-Enhanced Context: AI-powered context management and memory
  • Enterprise-Grade Performance: Production-ready with comprehensive error handling
  • 🌐 Cross-Platform Compatible: Works on Windows, macOS, and Linux
  • 🔄 Automatic Retry Logic: Smart retry with progress indicators
  • 📊 Real-Time Monitoring: Rate limit status and performance tracking
  • 🛡️ Secure by Design: Enterprise security with proper authentication

Installation

dotnet add package MarketAlly.AIPlugin.ClaudeCode

Quick Start

1. Configure Services in Program.cs

using MarketAlly.AIPlugin.ClaudeCode;

var builder = WebApplication.CreateBuilder(args);

// Option 1: Use configuration from appsettings.json
builder.Services.AddClaudeCodeIntegration(builder.Configuration);

// Option 2: Configure with action
builder.Services.AddClaudeCodeIntegration(options =>
{
    options.BaseUrl = "https://your-aizia-instance.com";
    options.ApiKey = "your-api-key";
    options.TenantId = "your-tenant-id";
    options.EnableRateLimiting = true;
    options.EnableLearning = true;
    options.MaxRetries = 3;
});

var app = builder.Build();

// Map Claude Code endpoints (optional - for API exposure)
app.MapClaudeCodeEndpoints();

app.Run();

2. Use in Controllers

[ApiController]
[Route("api/[controller]")]
public class AIAssistantController : ControllerBase
{
    private readonly IClaudeCodeService _claudeCodeService;
    private readonly IChatService _chatService;
    
    public AIAssistantController(
        IClaudeCodeService claudeCodeService,
        IChatService chatService)
    {
        _claudeCodeService = claudeCodeService;
        _chatService = chatService;
    }
    
    [HttpPost("chat")]
    public async Task<IActionResult> Chat([FromBody] ChatRequest request)
    {
        var response = await _claudeCodeService.SendChatMessageAsync(request);
        
        if (response.Success)
        {
            return Ok(new { 
                response = response.Data, 
                rateLimit = response.RateLimitInfo 
            });
        }
        
        return BadRequest(new { 
            error = response.Error, 
            errorCode = response.ErrorCode 
        });
    }
    
    [HttpPost("analyze")]
    public async Task<IActionResult> AnalyzeCode([FromBody] AnalysisRequest request)
    {
        var response = await _claudeCodeService.AnalyzeCodeAsync(request);
        return response.Success ? Ok(response.Data) : BadRequest(response.Error);
    }
    
    [HttpGet("rate-limit")]
    public async Task<IActionResult> GetRateLimit()
    {
        var response = await _claudeCodeService.GetRateLimitStatusAsync();
        return Ok(response.Data);
    }
}

3. Use in Services

public class CodeAnalysisService
{
    private readonly IClaudeCodeService _claudeCode;
    
    public CodeAnalysisService(IClaudeCodeService claudeCode)
    {
        _claudeCode = claudeCode;
    }
    
    public async Task<string> GetCodeReview(string filePath, string code)
    {
        var request = new AnalysisRequest
        {
            FilePath = filePath,
            Code = code,
            AnalysisType = "security",
            Options = new Dictionary<string, object>
            {
                ["includeRecommendations"] = true,
                ["severityLevel"] = "medium"
            }
        };
        
        var response = await _claudeCode.AnalyzeCodeAsync(request);
        return response.Success ? response.Data?.Summary ?? "No analysis available" : response.Error ?? "Analysis failed";
    }
}

Configuration

appsettings.json

{
  "ClaudeCode": {
    "BaseUrl": "https://your-aizia-instance.com",
    "ApiKey": "your-api-key-here",
    "TenantId": "your-tenant-id",
    "MaxRetries": 3,
    "BaseRetryDelay": "00:00:01",
    "MaxRetryDelay": "00:05:00",
    "BackoffMultiplier": 2.0,
    "EnableDetailedLogging": false,
    "EnableRateLimiting": true,
    "EnableLearning": true,
    "RateLimiting": {
      "AutoRetry": true,
      "MaxRetryWait": "00:05:00",
      "ShowWarningsAt": 10,
      "EnableProgressIndicator": true,
      "RespectRateLimits": true
    },
    "Learning": {
      "EnableAdvancedLearning": true,
      "LearningMode": "moderate",
      "MaxHistoricalInsights": 50,
      "ConfidenceThreshold": 0.7,
      "EnablePredictiveAnalytics": true,
      "SessionTimeoutMinutes": 60
    }
  }
}

Rate Limiting Features

The package includes comprehensive rate limiting with:

Multi-Tier Support

  • Free: 100 requests/hour
  • Basic/Starter: 500 requests/hour
  • Professional: 2,000 requests/hour
  • Enterprise: 10,000 requests/hour
  • Aizia Staff/Admin: 5,000-50,000 requests/hour

Automatic Handling

  • Exponential Backoff: Smart retry delays
  • Progress Indicators: Real-time wait progress
  • Rate Limit Awareness: Proactive limit checking
  • Graceful Degradation: Fallback when limits exceeded

Usage Example

// Rate limit status monitoring
var rateLimitInfo = await _claudeCodeService.GetRateLimitStatusAsync();
if (rateLimitInfo.Success && rateLimitInfo.Data.IsNearLimit)
{
    // Handle near-limit scenario
    await Task.Delay(TimeSpan.FromMinutes(1));
}

// The HTTP client automatically handles retries
var response = await _claudeCodeService.SendChatMessageAsync(new ChatRequest
{
    Message = "Analyze this code for security issues",
    ProjectPath = "./src/MyProject",
    IncludeProjectContext = true
});

API Services

IClaudeCodeService - Main Integration

// Chat with Claude
var chatResponse = await claudeCodeService.SendChatMessageAsync(new ChatRequest
{
    Message = "How can I optimize this function?",
    SessionId = "my-session",
    ProjectPath = "./src",
    IncludeProjectContext = true,
    IncludeHistory = true
});

// Analyze code
var analysisResponse = await claudeCodeService.AnalyzeCodeAsync(new AnalysisRequest
{
    FilePath = "./src/MyController.cs",
    AnalysisType = "security",
    ProjectPath = "./src"
});

// Store decisions
await claudeCodeService.StoreDecisionAsync(new StoreDecisionRequest
{
    Decision = "We chose PostgreSQL for ACID compliance",
    Category = "architecture",
    ProjectPath = "./src"
});

IChatService - Session Management

// Start session
var sessionResponse = await chatService.StartSessionAsync(new StartSessionRequest
{
    SessionName = "Code Review Session",
    ProjectPath = "./src",
    Settings = new ChatSessionSettings
    {
        Temperature = 0.7,
        IncludeProjectContext = true
    }
});

// Send messages
if (sessionResponse.Success)
{
    var messageResponse = await chatService.SendMessageAsync(
        sessionResponse.Data.Id, 
        "Please review this function for performance issues"
    );
}

IContextClaudeService - Memory & Context

// Search project context
var contextResponse = await contextService.GetRelevantContextAsync(
    "authentication patterns", 
    "./src", 
    maxResults: 10
);

// Store insights
await contextService.StoreProjectInsightAsync(new ProjectInsight
{
    ProjectPath = "./src",
    Type = "pattern",
    Category = "security",
    Title = "JWT Authentication Pattern",
    Description = "Standardized JWT implementation across controllers"
});

IRateLimitAwareHttpClient - HTTP Operations

// Direct HTTP calls with rate limiting
var response = await httpClient.GetAsync("/api/custom-endpoint");
if (response.IsSuccessStatusCode)
{
    var data = response.DeserializeJson<MyModel>();
}

// Check if request can be made
var canMakeRequest = await httpClient.CanMakeRequestAsync();
if (!canMakeRequest)
{
    await httpClient.WaitForRateLimitResetAsync();
}

Error Handling

The package provides comprehensive error handling:

var response = await claudeCodeService.SendChatMessageAsync(request);

if (!response.Success)
{
    switch (response.ErrorCode)
    {
        case "RATE_LIMITED":
            // Handle rate limiting
            var waitTime = response.RateLimitInfo?.TimeToReset;
            break;
        case "API_ERROR":
            // Handle API errors
            logger.LogError("API Error: {Error}", response.Error);
            break;
        case "EXCEPTION":
            // Handle exceptions
            logger.LogError("Exception: {Error}", response.Error);
            break;
    }
}

Advanced Features

Learning Mode Configuration

services.Configure<LearningOptions>(options =>
{
    options.LearningMode = "aggressive"; // conservative, moderate, aggressive
    options.EnablePredictiveAnalytics = true;
    options.ConfidenceThreshold = 0.8;
});

Custom HTTP Client Configuration

services.Configure<ClaudeCodeOptions>(options =>
{
    options.BaseRetryDelay = TimeSpan.FromSeconds(2);
    options.MaxRetryDelay = TimeSpan.FromMinutes(10);
    options.BackoffMultiplier = 1.5;
    options.EnableDetailedLogging = true;
});

Dependencies

  • .NET 8.0+
  • Microsoft.Extensions.DependencyInjection
  • Microsoft.Extensions.Http
  • Microsoft.AspNetCore.App
  • System.Text.Json

Migration from Raw Implementation

If you were previously using the raw C# files:

  1. Remove old C# files from your project
  2. Install this NuGet package: dotnet add package MarketAlly.AIPlugin.ClaudeCode
  3. Update service registration to use AddClaudeCodeIntegration()
  4. Update controller inheritance (if using controllers)
  5. Migrate configuration to new format

License

MIT License - see LICENSE file for details

Support

For issues and questions: