Spensara Spensara Knowledge Base & Documentation Repository

Repository Docs & Knowledge Base

Consolidated Spensara documentation repository (722 Markdown & architecture documents in ../repository)
Built Word Documents (.docx): Spensara Overview (.docx) Capability Assessment (.docx) Brink POS Ingestion Analysis (.docx) The Borg Ingestion Architecture (.docx)

Implementation Specs (157)

Detailed engineering and feature implementation specifications.
implementation-specs/specs/AnomalyDetection/TASK5.2.md 7,543 bytes · Updated Oct 23, 2026 10:44 AM EDT
Raw File

TASK 5.2: Wire Up AnomalyDetector Module DI in CLI

Summary

Register all AnomalyDetector module services in the CLI application's dependency injection container, enabling the CLI commands to access the full anomaly detection stack. This builds on the base DI from TASK 1.4 and adds all remaining services.

Dependencies

  • TASK 1.4 (McpToolProvider + base DI extensions)
  • TASK 2.2 (AnomalyDetectorAgent)
  • TASK 3.2 (EfMonitorSpecRepository)
  • TASK 4.2 (MonitorRunOrchestrator)
  • TASK 4.3 (AlertEmitter)
  • TASK 4.4 (EfMonitorRunRepository)
  • TASK 3.3 (MonitorSpecSeeder)
  • TASK 5.1 (CLI commands that need the services)

Files to Modify

1. backend/Kds.Ai.AnomalyDetector/DependencyInjectionExtensions.cs

Ensure all services are registered (extends TASK 1.4's base registration):

csharp
using Kds.Ai.AnomalyDetector.Agents;
using Kds.Ai.AnomalyDetector.Alerts;
using Kds.Ai.AnomalyDetector.Mcp;
using Kds.Ai.AnomalyDetector.Orchestration;
using Kds.Ai.AnomalyDetector.Repositories;
using Kds.Ai.AnomalyDetector.Seeding;
using Kds.Ai.AnomalyDetector.Settings;
using Kds.Ai.Core;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;

namespace Kds.Ai.AnomalyDetector;

public static class DependencyInjectionExtensions
{
    /// <summary>
    /// Add the AnomalyDetector module with all required services.
    /// Note: IMonitorSpecRepository is registered by AddDataModule() - do not re-register here.
    /// </summary>
    public static IHostApplicationBuilder AddAnomalyDetectorModule(this IHostApplicationBuilder builder)
    {
        // === Settings ===
        builder.AddOptions<McpMySqlSettings>();
        
        // === MCP Tool Provider ===
        builder.Services.AddSingleton(provider =>
        {
            var settings = provider.GetRequiredService<IOptions<McpMySqlSettings>>();
            return new McpToolProvider(settings.Value);
        });
        
        // === Repositories ===
        // IMonitorSpecRepository is registered by AddDataModule() (lives in Kds.Ai.Data.Repositories)
        builder.Services.AddScoped<IMonitorRunRepository, EfMonitorRunRepository>();
        
        // === Agent ===
        builder.Services.AddScoped<IAnomalyDetectorAgent, AnomalyDetectorAgent>();
        
        // === Orchestration ===
        builder.Services.AddScoped<IMonitorRunOrchestrator, MonitorRunOrchestrator>();
        builder.Services.AddScoped<IAlertEmitter, AlertEmitter>();
        
        // === Seeding ===
        builder.Services.AddScoped<MonitorSpecSeeder>();
        
        return builder;
    }
}

2. backend/Kds.Ai.Cli/Program.cs

Add the AnomalyDetector module:

csharp
using ConsoleAppFramework;
using Kds.Ai.AgentsCommon;
using Kds.Ai.AnomalyDetector;
using Kds.Ai.Data;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);

// Add service defaults (Aspire integration)
builder.AddServiceDefaults();

// Add data layer (EF Core)
builder.AddDataModule();

// Add agents common (Bedrock IChatClient)
builder.AddAgentsCommonModule();

// Add anomaly detector module
builder.AddAnomalyDetectorModule();

var app = builder.ToConsoleAppBuilder();

await app.RunAsync(args);

3. backend/Kds.Ai.Cli/Kds.Ai.Cli.csproj

Ensure project references are correct:

xml
<Project Sdk="Microsoft.NET.Sdk">
  <ItemGroup>
    <ProjectReference Include="..\Kds.Ai.AgentsCommon\Kds.Ai.AgentsCommon.csproj" />
    <ProjectReference Include="..\Kds.Ai.AnomalyDetector\Kds.Ai.AnomalyDetector.csproj" />
    <ProjectReference Include="..\Kds.Ai.Data\Kds.Ai.Data.csproj" />
    <ProjectReference Include="..\Kds.Ai.ServiceDefaults\Kds.Ai.ServiceDefaults.csproj" />
  </ItemGroup>
  
  <ItemGroup>
    <PackageReference Include="ConsoleAppFramework" />
  </ItemGroup>
</Project>

Service Registration Summary

ServiceLifetimeImplementationRegistered By
McpMySqlSettingsOptionsFrom configurationAnomalyDetector
McpToolProviderSingletonSelf (manages MCP client lifecycle)AnomalyDetector
IMonitorSpecRepositoryScopedEfMonitorSpecRepositoryData module (AddDataModule)
IMonitorRunRepositoryScopedEfMonitorRunRepositoryAnomalyDetector
IAnomalyDetectorAgentScopedAnomalyDetectorAgentAnomalyDetector
IMonitorRunOrchestratorScopedMonitorRunOrchestratorAnomalyDetector
IAlertEmitterScopedAlertEmitterAnomalyDetector
MonitorSpecSeederScopedSelfAnomalyDetector

Module Dependencies

Kds.Ai.Cli
    ├── Kds.Ai.ServiceDefaults (Aspire defaults)
    ├── Kds.Ai.Data (DbContext, Entities)
    ├── Kds.Ai.AgentsCommon (IChatClient from Bedrock)
    └── Kds.Ai.AnomalyDetector (All anomaly detection services)

Configuration Requirements

The CLI needs these configuration sections (via environment variables or appsettings.json):

json
{
  "ConnectionStrings": {
    "kdsaidb": "Server=localhost;Database=kdsaidb;User=root;Password=xxx;"
  },
  "AwsBedrockCredentials": {
    "AccessKeyId": "xxx",
    "SecretAccessKey": "xxx",
    "ModelId": "anthropic.claude-3-sonnet-20240229-v1:0"
  },
  "McpMySqlSettings": {
    "Command": "npx",
    "Arguments": ["-y", "benborla-mcp-server-mysql"],
    "EnvironmentVariables": {
      "MYSQL_HOST": "localhost",
      "MYSQL_PORT": "3306",
      "MYSQL_USER": "root",
      "MYSQL_PASS": "password",
      "MYSQL_DB": "kdsdev"
    }
  }
}

Changes from Old Design

  • Removed IMcpClient/McpClient registration (replaced by McpToolProvider using official MCP SDK)
  • Removed PrepTimeQueryBuilder registration (deleted - agent formulates own SQL)
  • Removed IKdsDataAccessService/McpKdsDataAccessService registration (deleted - agent uses MCP tools directly)
  • Removed IAnomalyDetectorAgentFactory/AnomalyDetectorAgentFactory registration (no factory pattern)
  • Changed IAnomalyDetectorAgent implementation from PrepTimeAnomalyDetectorAgent to generic AnomalyDetectorAgent
  • Settings class renamed from McpConnectionSettings to McpMySqlSettings

Acceptance Criteria

  • [ ] AddAnomalyDetectorModule registers all AnomalyDetector-owned services (NOT IMonitorSpecRepository -- that comes from AddDataModule)
  • [ ] CLI Program.cs calls AddAnomalyDetectorModule()
  • [ ] CLI project references AnomalyDetector project
  • [ ] Service lifetimes are appropriate (scoped for DB access, singleton for MCP)
  • [ ] No registration of deleted services (IMcpClient, PrepTimeQueryBuilder, IKdsDataAccessService, IAnomalyDetectorAgentFactory)
  • [ ] Configuration sections documented
  • [ ] Solution builds without errors
  • [ ] CLI can execute anomaly run --help

Testing the Wiring

bash
# Verify the CLI loads without errors
dotnet run --project backend/Kds.Ai.Cli -- --help

# Verify anomaly commands are registered
dotnet run --project backend/Kds.Ai.Cli -- anomaly --help

# Verify DI works (will fail if config missing, but shows wiring works)
dotnet run --project backend/Kds.Ai.Cli -- anomaly list

Notes

  • Order of Add*Module calls matters if there are dependencies
  • The AddServiceDefaults provides OpenTelemetry, health checks, etc.
  • Scoped services are created per CLI command execution
  • McpToolProvider is singleton because the MCP server process is long-lived
  • Consider adding validation that all required config is present at startup