CasCap.Common.AI 4.15.0

Prefix Reserved
dotnet add package CasCap.Common.AI --version 4.15.0
                    
NuGet\Install-Package CasCap.Common.AI -Version 4.15.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="CasCap.Common.AI" Version="4.15.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CasCap.Common.AI" Version="4.15.0" />
                    
Directory.Packages.props
<PackageReference Include="CasCap.Common.AI" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add CasCap.Common.AI --version 4.15.0
                    
#r "nuget: CasCap.Common.AI, 4.15.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package CasCap.Common.AI@4.15.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=CasCap.Common.AI&version=4.15.0
                    
Install as a Cake Addin
#tool nuget:?package=CasCap.Common.AI&version=4.15.0
                    
Install as a Cake Tool

CasCap.Common.AI

AI agent framework infrastructure — agent creation, session management, MCP tool/prompt resolution, chat history compaction, and slash-command handling.

Installation

dotnet add package CasCap.Common.AI

Purpose

Provides the shared infrastructure for building multi-agent AI systems with support for multiple providers (Azure OpenAI, OpenAI, Ollama), automatic MCP tool discovery from [McpServerTool]-decorated service types, sub-agent delegation (fan-out pattern), persistent session state, and context-window compaction for edge GPU devices.

This library contains no domain-specific MCP query services — those live in downstream consumer projects. It provides the framework that consumer projects use to wire agents, tools, sessions, and prompts together.

Target frameworks: net10.0

Services

Type Description
AgentCommandHandler Shared handler for ChatCommand slash-commands (/session info, /session reset, /model, etc.) and agent session persistence. Override state (/model, /instructions, /session enable\|disable) is held per agent, keyed by AgentConfig.Name
ToolOutputStrippingChatReducer IChatReducer that strips FunctionCallContent/FunctionResultContent from the history while retaining a sliding window of recent exchanges — critical for reducing context size on edge devices
InMemorySessionStore Volatile in-memory ISessionStore backed by ConcurrentDictionary
DistributedCacheSessionStore Redis-backed ISessionStore wrapping IDistributedCache with sliding expiry
AgentTypeRegistry Deterministic name-to-type lookup for tool services and MCP prompt types, built once at startup by AddAgentTypeRegistry()

Abstractions

Interface Description
ISessionStore Persistence abstraction for serialised agent session state (GetAsync, SetAsync, DeleteAsync)

Extensions

Class Key Methods
AgentExtensions CreateAgent — creates IChatClient + AIAgent from config (Ollama, AzureOpenAI, OpenAI); RunAnalysisAsync — runs inference returning AgentRunResult; CreateToolsFromServiceProvider<T> — discovers [McpServerTool] methods as AITools; CreateToolsForAgent — resolves all tool sources with include/exclude filters; CreateAgentTool — wraps a peer agent as a callable AITool (delegation); ResolveInstructions — resolves from embedded resource, file, or inline string
AgentServiceCollectionExtensions AddAgentTypeRegistry — indexes tool service types from the service collection and prompt types from supplied assemblies
ChatCommandParser TryParseCommand — parses / slash-commands; TryCompactSession — manual session compaction; GetStateBagEntries — session state diagnostics

Configuration

Type Description
AIConfig Root configuration record (IAppConfig) — Providers, Agents, McpUrl, InstructionsPrefix/Suffix, TimeZoneId, SessionTtlDays
AgentConfig Per-agent behavioural config — Provider, Instructions/InstructionsSource, MaxMessages (compaction depth), Tools (tool sources), Prompts (prompt sources), Enabled
ProviderConfig AI provider infrastructure config — Type (AgentType), Endpoint, ModelName, ReasoningEffort, ApiKey

Models

Type Description
AgentRunResult Accumulated result of an AI agent run — output text, token usage, tool calls, attachments, timing, streaming support
AgentRunAttachment Binary attachment produced by a tool during an agent run (Base64Content, MimeType, FileName)
AgentRunScope Per-run host callbacks (delegation, completion, compaction), nesting depth and shared attachment collection
CompactionStats Summary of a single chat-history compaction pass
AgentInfo MCP-friendly projection of AgentConfig (all properties carry [Description])
ProviderInfo MCP-friendly projection of ProviderConfig excluding sensitive fields (all properties carry [Description])
ToolSource Identifies a tool source — in-process Service, remote Endpoint, or peer Agent (fan-out delegation) with IncludeTools/ExcludeTools filters
PromptSource Identifies a prompt source — in-process Service or remote Endpoint with include/exclude filters
ToolCallInfo Captures a single tool/function call name and arguments
McpPromptDescriptor Lightweight descriptor for an MCP prompt (remote or in-process)
AudioDebugArtifacts Captures original and transcoded audio bytes for debug messages
StateBagEntry Summary of a single AgentSessionStateBag entry (key, size, message counts)

Enums

Enum Values
AgentType None, AzureOpenAI, AzureAIFoundry, Ollama, OpenAI
ChatCommand Help, SessionInfo, SessionReset, SessionBypass, SessionCompact, SessionDisable, SessionEnable, SessionSave, SessionLoad, SessionDelete, Model, Instructions

Service Architecture

Agent framework infrastructure showing how AgentExtensions creates agents and resolves tools from multiple source types:

graph TD
    classDef core fill:#dbeafe,stroke:#3b82f6,color:#1e3a8a
    classDef service fill:#d1fae5,stroke:#10b981,color:#064e3b
    classDef config fill:#fef3c7,stroke:#f59e0b,color:#78350f
    classDef store fill:#e0f2fe,stroke:#0284c7,color:#0c4a6e

    AE["AgentExtensions"]:::core

    subgraph AgentCreation["Agent Creation"]
        CREATE["CreateAgent()<br/>(IChatClient + AIAgent)"]:::core
        RUN["RunAnalysisAsync()<br/>(AgentRunResult)"]:::core
    end

    subgraph ToolResolution["Tool Resolution"]
        SVC_TOOLS["CreateToolsFromServiceProvider&lt;T&gt;()<br/>(discovers [McpServerTool] methods)"]:::core
        AGENT_TOOL["CreateAgentTool()<br/>(wraps peer agent as AITool)"]:::core
        HTTP_TOOLS["GetHttpTools()<br/>(remote MCP endpoint)"]:::core
        FILTER["FilterTools()<br/>(include/exclude)"]:::core
    end

    subgraph Providers["Provider Support"]
        OLLAMA["Ollama"]:::config
        AZURE["Azure OpenAI"]:::config
        OPENAI["OpenAI"]:::config
    end

    subgraph SessionMgmt["Session Management"]
        CMD["AgentCommandHandler<br/>(slash-commands)"]:::service
        MEM_STORE["InMemorySessionStore"]:::store
        DIST_STORE["DistributedCacheSessionStore<br/>(Redis)"]:::store
    end

    subgraph Compaction["Chat History Compaction"]
        REDUCER["ToolOutputStrippingChatReducer<br/>(IChatReducer)"]:::service
    end

    AE --> AgentCreation
    AE --> ToolResolution
    CREATE --> Providers
    CREATE -.configures.-> REDUCER
    CMD --> MEM_STORE
    CMD --> DIST_STORE

Agent Instruction Resolution

AgentExtensions.ResolveInstructions resolves the InstructionsSource property on each AgentConfig using a two-step fallback:

  1. Embedded resource — looks for a matching manifest resource name in the supplied assembly.
  2. File system path — if the value is an absolute path to an existing file, reads it from disk.

If neither source is found an exception is thrown. The fallback Instructions string property can still be used for simple inline text.

Chat History Compaction

Long conversations accumulate large context windows — especially from verbose tool call/result JSON payloads. Automatic compaction is configured per-agent via AgentConfig.MaxMessages.

When MaxMessages is set to a positive value, AgentExtensions.CreateAgent configures the agent's InMemoryChatHistoryProvider with a ToolOutputStrippingChatReducer that:

  1. Preserves the first system message (agent instructions are never lost).
  2. Strips all FunctionCallContent and FunctionResultContent from non-system messages (the primary source of context bloat), dropping any message left with no remaining content.
  3. Keeps a sliding window of the most recent MaxMessages non-system exchanges.

Tool content is removed from every message rather than only from messages consisting solely of tool content. An assistant message mixing narration text with a FunctionCallContent would otherwise be retained while its matching FunctionResultContent was dropped, leaving an orphaned tool call — OpenAI and Azure OpenAI reject such a request with HTTP 400.

The reducer runs automatically before each agent invocation. Set MaxMessages to 0 or null to disable automatic compaction.

Run Scope

Host callbacks and per-run state are carried by an AgentRunScope passed to RunAnalysisAsync, replacing the ambient Set*/Clear* callback pairs that callers previously had to balance in a finally block:

var scope = new AgentRunScope
{
    OnDelegation = (agentKey, depth, provider, ct) => NotifyAsync(agentKey, depth, ct),
    OnCompletion = (agentKey, depth, result, ct) => RecordAsync(agentKey, result, ct),
    OnCompaction = stats => Debug($"{stats.InputCount} → {stats.OutputCount}"),
};

var result = await agent.RunAnalysisAsync(provider, agentConfig, message, chatOptions, scope: scope);
Member Description
Depth 0 for the top-level agent, 1 for a sub-agent, and so on
OnDelegation Fired when a sub-agent delegation begins — use for live progress notifications
OnCompletion Fired when a sub-agent delegation completes, with its AgentRunResult
OnCompaction Fired when the chat history is compacted, with a CompactionStats
Attachments / AddAttachment / DrainAttachments Thread-safe attachment collection shared with every sub-agent scope beneath the run

ForSubAgent() creates a child scope with an incremented Depth that shares the parent's callbacks and attachment collection, so an image produced several delegations deep still surfaces on the top-level AgentRunResult.

CompactionStats carries InputCount, OutputCount, ToolDropped, WindowTrimmed and Target.

Session Isolation

Each agent uses its own AgentSession keyed by AgentConfig.Name. Sub-agents invoked via the fan-out pattern (ToolSource.Agent) create a fresh stateless session per invocation, ensuring no cross-agent context leakage.

Session Persistence

Store Implementation Use Case
InMemorySessionStore ConcurrentDictionary Console app (volatile)
DistributedCacheSessionStore Redis via IDistributedCache Server / background service (persistent)

Dependencies

NuGet Packages

Package Purpose
Azure.AI.OpenAI Azure OpenAI client
Microsoft.Agents.AI Agent framework
Microsoft.Extensions.AI AI abstractions (ChatMessage, ChatRole)
Microsoft.Extensions.AI.Abstractions AI abstraction interfaces
Microsoft.Extensions.AI.OpenAI OpenAI provider for Microsoft.Extensions.AI
ModelContextProtocol MCP server attributes and types
OllamaSharp Ollama .NET client

Project References

Project Purpose
CasCap.Common.Abstractions Shared abstractions and interfaces
CasCap.Common.Caching Redis caching abstractions
CasCap.Common.Extensions Shared extension helpers

License

This project is released under The Unlicense. See the LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on CasCap.Common.AI:

Package Downloads
CasCap.Common.AI.Evaluation

Evaluation harness for Microsoft Agent Framework agents built with CasCap.Common.AI — fixture-backed MCP tools, instruction and tool-surface variants, per-request timing, grading and model comparison reports.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
4.15.0 221 10/6/2026
4.14.4 149 10/4/2026
4.14.3 139 9/28/2026
4.14.2 148 9/25/2026
4.14.1 164 9/23/2026
4.14.0 183 9/19/2026
4.13.0 115 9/15/2026
4.12.8 133 9/10/2026
4.12.7 123 9/4/2026
4.12.6 130 9/1/2026
4.12.5 133 8/20/2026
4.12.4 130 8/18/2026
4.12.3 152 7/15/2026
4.12.2 152 6/26/2026
4.12.1 151 6/14/2026
4.12.0 145 6/12/2026
4.11.9 143 6/10/2026
4.11.8 150 5/27/2026
4.11.7 149 5/27/2026
4.11.6 160 5/26/2026
Loading failed