MCPInstall

working-with-ms-agent-framework

Use when building AI agents with Microsoft Agent Framework (Semantic Kernel + AutoGen unified); when implementing memory or context providers; when threads won't deserialize; when workflow checkpointing fails; when migrating from Semantic Kernel or AutoGen; when seeing ChatAgent or AgentThread errors

Installs
42
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/mhagrelius/dotfiles --skill working-with-ms-agent-framework
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads working-with-ms-agent-framework automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Working with Microsoft Agent Framework

Microsoft Agent Framework (October 2025) unifies Semantic Kernel and AutoGen into one SDK. Both legacy frameworks are in maintenance mode.

Core principle: Agents are stateless. All state lives in threads. Context providers enforce policy about what enters the prompt, how, and when it decays.

Additional reference files in this skill:

  • context-providers.md - Policy-based memory, capsule pattern, Mem0 integration
  • orchestration-patterns.md - The 5 orchestration patterns with when-to-use guidance
  • design-patterns.md - Production patterns, testing, migration

When to Use

  • Building AI agents with Microsoft's unified framework
  • Implementing custom memory with Context Providers
  • Creating multi-agent workflows with checkpointing
  • Migrating from Semantic Kernel or AutoGen

When NOT to Use

  • Simple single-turn LLM calls (use chat client directly)
  • Projects staying on legacy SK/AutoGen
  • Non-Microsoft frameworks (LangChain, CrewAI)

Technology Stack Hierarchy

Official guidance (Jeremy Licknes, PM): Start with ME AI, escalate only when needed.

LayerUse ForWhen to Escalate
ME AI (Microsoft.Extensions.AI)Chat clients, structured outputs, embeddings, middlewareNeed agents, workflows, memory
Agent FrameworkAgents, threads, orchestration, context providersNeed specific SK adapters
Semantic KernelSpecific adapters, utilities not in ME AINever start here
ME AI (foundation) → Agent Framework (agents/workflows) → SK (specific utilities only)

Key insight: ME AI provides universal APIs that work across OpenAI, Ollama, Foundry Local, etc. Agent Framework builds on ME AI for agentic patterns. SK primitives migrated to ME AI; only use SK for specific adapters not yet in ME AI.

ME AI features you get automatically:

  • Structured outputs (typed responses via extension methods)
  • Middleware (OpenTelemetry, chat reduction)
  • Universal chat client abstraction
  • Embeddings generation

Architecture Quick Reference

ConceptC# TypePurpose
AgentAIAgentStateless LLM wrapper
ThreadAgentThreadStateful conversation container
Context ProviderAIContextBehaviorPolicy-based memory/context injection
OrchestrationSequentialOrchestration, etc.Multi-agent coordination

Installation

dotnet add package Microsoft.Agents.AI.OpenAI --prerelease
dotnet add package Azure.AI.OpenAI --version 2.1.0

Agent Creation

using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

// Azure OpenAI
AIAgent agent = new AzureOpenAIClient(
    new Uri("https://<resource>.openai.azure.com"),
    new AzureCliCredential())
        .GetChatClient("gpt-4o-mini")
        .CreateAIAgent(
            instructions: "You are a helpful assistant.",
            name: "Assistant");

// Direct OpenAI
var agent = new OpenAIClient("api-key")
    .GetChatClient("gpt-4o-mini")
    .AsIChatClient()
    .CreateAIAgent(instructions: "...", name: "Assistant");

// With tools
[Description("Gets weather for a location")]
static string GetWeather(string location) => $"Sunny in {location}";

AIAgent agent = chatClient.CreateAIAgent(
    instructions: "You help with weather queries.",
    tools: [AIFunctionFactory.Create(GetWeather)]
);

Execution

// Simple
Console.WriteLine(await agent.RunAsync("Hello!"));

// With thread for multi-turn
AgentThread thread = agent.GetNewThread();
await agent.RunAsync("My name is Alice.", thread);
await agent.RunAsync("What's my name?", thread); // Remembers "Alice"

// Streaming
await foreach (var update in agent.RunStreamingAsync("Tell me a story.", thread))
{
    Console.Write(update.Text);
}

Streaming with Resilience

For production streaming, add cancellation support and resilience:

// Basic streaming with cancellation
await foreach (var update in agent.RunStreamingAsync("Tell me a story.", thread)
    .WithCancellation(cancellationToken))
{
    Console.Write(update.Text);
}

// With Polly resilience pipeline
var pipeline = new ResiliencePipelineBuilder()
    .AddRetry(new RetryStrategyOptions { MaxRetryAttempts = 3 })
    .AddTimeout(TimeSpan.FromMinutes(2))
    .Build();

await pipeline.ExecuteAsync(async token =>
{
    await foreach (var chunk in agent.RunStreamingAsync(userMessage, thread)
        .WithCancellation(token))
    {
        Console.Write(chunk.Text);
    }
}, cancellationToken);

Error differentiation:

  • OperationCanceledException: User cancelled
  • TimeoutRejectedException: Polly timeout
  • HttpRequestException: Network issues

Development UI (DevUI)

Lightweight web interface for testing agents and workflows. Development only—not for production.

Python Setup

Install:

pip install agent-framework-devui --pre

Option 1: Programmatic Registration

from agent_framework import ChatAgent
from agent_framework.openai import OpenAIChatClient
from agent_framework.devui import serve

agent = ChatAgent(
    name="WeatherAgent",
    chat_client=OpenAIChatClient(),
    tools=[get_weather]
)

# Launch DevUI with tracing
serve(entities=[agent], auto_open=True, tracing_enabled=True)
# Opens browser to http://localhost:8080

Option 2: Directory Discovery (CLI)

devui ./entities --port 8080 --tracing

Directory structure for discovery:

entities/
    weather_agent/
        __init__.py      # Must export: agent = ChatAgent(...)
        .env             # Optional: API keys
    my_workflow/
        __init__.py      # Must export: workflow = WorkflowBuilder()...

C# Setup

C# embeds DevUI as SDK component (docs in progress):

var app = builder.Build();

app.MapOpenAIResponses();
app.MapConversation();

if (app.Environment.IsDevelopment())
{
    app.MapAgentUI(); // Accessible at /ui
}

Features

FeatureDescription
Web interfaceInteractive testing of agents/workflows
OpenAI-compatible APIUse OpenAI SDK against local agents
TracingOpenTelemetry spans in debug panel
File uploadsMultimodal inputs (images, documents)
Auto-generated inputsWorkflow inputs based on first executor type

Tracing in DevUI

Enable with --tracing flag or tracing_enabled=True. View in debug panel:

Agent Execution
├── LLM Call (prompt → response)
├── Tool Call
│   ├── Tool Execution
│   └── Tool Result
└── LLM Call (prompt → response)

Export to external tools (Jaeger, Azure Monitor):

export OTLP_ENDPOINT="http://localhost:4317"
devui ./entities --tracing

OpenAI SDK Integration

Interact with DevUI agents via OpenAI Python SDK:

from openai import OpenAI

client = OpenAI(base_url="http://localhost:8080/v1", api_key="not-needed")
response = client.responses.create(
    metadata={"entity_id": "weather_agent"},
    input="What's the weather in Seattle?"
)

CLI Options

devui [directory] [options]
  --port, -p      Port (default: 8080)
  --tracing       Enable OpenTelemetry tracing
  --reload        Auto-reload on file changes
  --headless      API only, no UI
  --mode          developer|user (default: developer)

Thread Serialization (Critical Pattern)

// Serialize for persistence
JsonElement serialized = await thread.SerializeAsync();
await File.WriteAllTextAsync("thread.json", serialized.GetRawText());

// Later: restore and resume
string json = await File.ReadAllTextAsync("thread.json");
JsonElement element = JsonSerializer.Deserialize<JsonElement>(json);
AgentThread restored = agent.DeserializeThread(element, JsonSerializerOptions.Web);
await agent.RunAsync("Continue...", restored);

Key behaviors:

  • Service-managed threads: Only thread ID serialized
  • In-memory threads: All messages serialized
  • WARNING: Deserializing with different agent config may error

Context Providers (Policy-Based Memory)

Context providers are not "memory injection" — they're policy enforcement:

PolicyWhat It Decides
SelectionWhat becomes memory
GatingWhen it's retrieved
DecayWhen it expires
Noise avoidanceWhen NOT to use
ChatHistoryAgentThread thread = new();

// Long-term user memory
thread.AIContextProviders.Add(new Mem0Provider(httpClient, new() { UserId = "user123" }));

// Short-term conversation context
thread.AIContextProviders.Add(new WhiteboardProvider(chatClient));

// RAG integration
thread.AIContextProviders.Add(new TextSearchProvider(textSearch, new()
{
    SearchTime = TextSearchProviderOptions.RagBehavior.OnDemandFunctionCalling
}));

See context-providers.md for custom implementation patterns.

Orchestration Patterns

PatternUse When
SequentialClear dependencies (draft → review → polish)
ConcurrentIndependent perspectives, ensemble reasoning
HandoffUnknown optimal agent upfront, dynamic expertise
GroupChatCollaborative ideation, human-in-the-loop
MagenticComplex open-ended problems
// Sequential
SequentialOrchestration orchestration = new(analystAgent, writerAgent);

// Handoff - CRITICAL: Always set termination conditions!
var workflow = AgentWorkflowBuilder.StartHandoffWith(triageAgent)
    .WithHandoffs(triageAgent, [mathTutor, historyTutor])
    .WithHandoff(mathTutor, triageAgent)      // Allows routing back
    .WithHandoff(historyTutor, triageAgent)
    .WithMaxHandoffs(10)                      // REQUIRED: Prevent infinite loops
    .Build();

// Execute
InProcessRuntime runtime = new();
await runtime.StartAsync();
var result = await orchestration.InvokeAsync(task, runtime);

CRITICAL for Handoffs: Missing .WithMaxHandoffs() causes infinite loops. Always set termination conditions.

See orchestration-patterns.md for detailed patterns and when-to-use guidance.

Workflow Checkpointing & Durability

For workflows that must survive process restarts:

// Basic checkpointing with CheckpointManager
var checkpointManager = CheckpointManager.Default;

await using Checkpointed<StreamingRun> checkpointedRun =
    await InProcessExecution.StreamAsync(workflow, input, checkpointManager);

// Resume from checkpoint
await InProcessExecution.ResumeStreamAsync(savedCheckpoint, checkpointManager);

Thread-Based Persistence Pattern

For long-running workflows, checkpoint thread state after each step:

// Save thread state after each workflow step
var serialized = await thread.SerializeAsync();
await checkpointStore.SaveAsync(workflowId, currentStep, serialized.GetRawText());

// Resume after restart
var json = await checkpointStore.GetAsync(workflowId);
var element = JsonSerializer.Deserialize<JsonElement>(json);
var restored = agent.DeserializeThread(element, JsonSerializerOptions.Web);
await agent.RunAsync(nextStep, restored);

Recovery on Startup

public class WorkflowRecoveryService : BackgroundService
{
    private readonly ICheckpointStore _store;
    private readonly AIAgent _agent;

    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        var pending = await _store.GetPendingWorkflowsAsync();
        foreach (var workflow in pending)
        {
            var thread = _agent.DeserializeThread(workflow.State, JsonSerializerOptions.Web);
            await _agent.RunAsync(workflow.NextStep, thread, cancellationToken: ct);
        }
    }
}

Key principle: Checkpoint after each step completes, not before. This ensures you can resume from the last successful step.

Migration Quick Reference

From Semantic Kernel

SKAgent Framework
KernelAIAgent
ChatHistoryAgentThread
[KernelFunction][Description] on methods
IPromptFilterAIContextBehavior
KernelFunctionFactory.CreateFromMethodAIFunctionFactory.Create

From AutoGen

AutoGenAgent Framework
AssistantAgentAIAgent via CreateAIAgent()
FunctionToolAIFunctionFactory.Create()
GroupChat/TeamsWorkflowBuilder patterns
TopicSubscriptionAgentWorkflowBuilder.WithHandoffs()
BaseAgent, IHandle<>AIAgent with tools

Topic-Based to Handoff Migration:

// ❌ OLD AutoGen pattern (deprecated)
[TopicSubscription("queries")]
public class MyAgent : BaseAgent, IHandle<Query>
{
    public async Task Handle(Query msg, CancellationToken ct)
    {
        // Process and publish to another topic
        await PublishMessageAsync(new Response(...), "responses");
    }
}

// ✅ NEW Agent Framework pattern
var triageAgent = chatClient.CreateAIAgent(
    instructions: "Route queries to appropriate specialist.",
    name: "Triage");

var mathAgent = chatClient.CreateAIAgent(
    instructions: "Handle math queries.",
    name: "Math");

var workflow = AgentWorkflowBuilder.StartHandoffWith(triageAgent)
    .WithHandoffs(triageAgent, [mathAgent, otherAgent])
    .WithMaxHandoffs(10)  // REQUIRED
    .Build();

await workflow.InvokeStreamingAsync(input, runtime);

Anti-Patterns

Don'tDo
Store state in agent instancesUse AgentThread for all state
Serialize only messagesSerialize entire thread
Share agent instances in workflowsUse factory pattern
Mix thread types across servicesThreads are service-specific
Use Magentic when Sequential sufficesUse simplest pattern that works
Skip UseImmutableKernel with ContextualFunctionProviderAlways set UseImmutableKernel = true
Start with Semantic Kernel for new projectsStart with ME AI, escalate to Agent Framework

Red Flags - STOP

  • Using Kernel instead of AIAgent (old SK)
  • Using AssistantAgent instead of AIAgent (old AutoGen)
  • Thread deserialization fails (missing serialization constructor in context provider)
  • Memory lost between sessions (serializing messages instead of thread)
  • Infinite handoff loops (need termination conditions)

Known Limitations

  • Distributed runtime: In-process only; distributed execution planned
  • C# Magentic: Most examples are Python
  • C# message stores: Redis/database need custom implementation
  • Token counting: Budget calculation in providers undocumented
  • DevUI C# docs: Python has full docs; C# DevUI docs "coming soon" (embedded SDK approach differs)
  • GA timeline: Agent Framework stable release "coming soon" (as of Jan 2025)

Resources

  • GitHub: github.com/microsoft/agent-framework
  • Docs: learn.microsoft.com/en-us/agent-framework/
  • Migration: learn.microsoft.com/en-us/agent-framework/migration-guide/

FAQ

What does the working-with-ms-agent-framework skill do?

Use when building AI agents with Microsoft Agent Framework (Semantic Kernel + AutoGen unified); when implementing memory or context providers; when threads won't deserialize; when workflow checkpointing fails; when migrating from Semantic Kernel or AutoGen; when seeing ChatAgent or AgentThread errors

How do I install working-with-ms-agent-framework?

Run npx skills add https://github.com/mhagrelius/dotfiles --skill working-with-ms-agent-framework in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/working-with-ms-agent-framework/ (personal) or .claude/skills/working-with-ms-agent-framework/ (project).

Which AI agents can use working-with-ms-agent-framework?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is working-with-ms-agent-framework safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains working-with-ms-agent-framework?

It is published by mhagrelius in mhagrelius/dotfiles. It has 42 recorded installs.

More from mhagrelius/dotfiles

View all →

dotnet-10-csharp-14

mhagrelius/dotfiles

Use when building .NET 10 or C 14 applications; when using minimal APIs, modular monolith patterns, or feature folders; when implementing HTTP resilience, Options pattern, Channels, or validation; when seeing outdated patterns like old extension method syntax

Backend & APIs1.9K installs

developing-gtk-apps

mhagrelius/dotfiles

Use for any change to a GTK 4/libadwaita app, new or existing, whether or not the request mentions GTK. Trigger on the repo rather than the wording — if Cargo.toml depends on gtk4/libadwaita, or sources import gi/Gtk (Python) or use Gtk (Vala), this applies to every change to that app, including requests phrased purely as symptoms ("reordering doesn't work", "pressing enter should continue the list", "the window opens too small"). Covers app boilerplate and new features; behaviour bugs in drag-and-drop, context menus, keyboard and text editing, focus, selection, and window sizing; threading, signals, and lifecycle; gtk-rs calls that fail to compile; GSettings, resources, packaging, and tests. Delegates widget choice, layout, and HIG to designing-gnome-ui.

Frontend & Design120 installs

building-tui-apps

mhagrelius/dotfiles

Open the skill to read its SKILL.md instructions.

100 installs

designing-gnome-ui

mhagrelius/dotfiles

Open the skill to read its SKILL.md instructions.

Frontend & Design100 installs

using-typescript-lsp

mhagrelius/dotfiles

Open the skill to read its SKILL.md instructions.

working-with-aspire

mhagrelius/dotfiles

Open the skill to read its SKILL.md instructions.

42 installs

Popular ai & agents skills

View category →

google-agents-cli-publish

google/agents-cli

This skill should be used when the user wants to "publish an agent", "publish my ADK agent", "register an agent with Gemini", "publish to Gemini" (formerly Gemini Enterprise), or needs guidance on the agents-cli publish gemini command. Also use when the user wants to "manage agents in Agent Registry", "list/update/delete registered agents", or "register an MCP server". Covers ADK vs A2A registration modes, programmatic and interactive usage, flag reference, auto-detection from deployment metadata, Agent Registry fleet management, and troubleshooting. Part of the agents-cli skills suite. Do NOT use for deployment (use google-agents-cli-deploy).

AI & Agents513.9K installs

google-agents-cli-eval

google/agents-cli

This skill should be used when the user wants to "run an evaluation", "evaluate my agent", "evaluate my ADK agent", "write an eval dataset", "analyze eval failures", "compare eval results", "optimize agent", or needs guidance on the Gemini platform eval methodology and the Quality Flywheel. Covers eval metrics, dataset schema, LLM-as-judge scoring, and common failure causes. Applies to any agents-cli project, whatever framework the agent is written in. Do NOT use for agent API code patterns (ADK: use google-agents-cli-adk-code), deployment (use google-agents-cli-deploy), or project scaffolding (use google-agents-cli-scaffold).

AI & Agents513.5K installs

skill-creator

anthropics/skills

Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.

OfficialAI & Agents416.4K installs

codex-pet

prime-skills/runcomfy-agent-skills

Codex Pet generator on RunComfy. Build a Codex-compatible Codex Pet spritesheet.webp + pet.json from a single reference image, drop it into ${CODEXHOME:-$HOME/.codex}/pets/ / and Codex picks it up as a custom Codex Pet next to the 8 built-ins. This skill produces the exact Codex Pet atlas Codex expects (1536x1872 PNG/WebP, 8 cols x 9 rows, 192x208 cells, 9 animation states — idle, running-right, running-left, waving, jumping, failed, waiting, running, review). Calls OpenAI GPT Image 2 edit ONCE via the local RunComfy CLI as runcomfy run openai/gpt-image-2/edit to produce a canonical Codex Pet pose, then assembles all 9 animation rows programmatically with ImageMagick micro-transforms — no Codex Pro, no $imagegen, no OPENAIAPIKEY required, only RUNCOMFYTOKEN. Triggers on "codex pet", "create codex pet", "make codex pet", "hatch codex pet", "/hatch image", "desktop pet codex", "codex pets", "spritesheet.webp", or any explicit ask to build a custom pet for OpenAI Codex.

AI & Agents402.1K installs

full-output-enforcement

leonxlnx/taste-skill

Overrides default LLM truncation behavior. Enforces complete code generation, bans placeholder patterns, and handles token-limit splits cleanly. Apply to any task requiring exhaustive, unabridged output.

AI & Agents401K installs

executing-plans

obra/superpowers

Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available

AI & Agents245.7K installs