Leanpub Header

Skip to main content

Building AI Agents with C# and .NET 10

A Developer’s First Guide to the Microsoft Agent Framework

This book is 100% completeLast updated on 2026-07-25
+100% in the last 30 days

Your C# skills are worth more today than they were a year ago — if you know how to put a language model in the loop. This book shows you how, with the Microsoft Agent Framework: real tools, RAG, multi-agent orchestration, plus the hosting, observability, and safety that separate a demo from a system you ship. Nineteen chapters. 120 runnable projects. No Python detours. Just C# and .NET 10.

Minimum price

$29.99

$39.99

You pay

Author earns

$

Also available for 1 book credit with a Reader Membership

Buying multiple copies for your team? See below for a discount!

PDF
Discussion Forum
About

About

About the Book

Between the launch of ChatGPT and the GA release of the Microsoft Agent Framework in April 2026, a new class of .NET applications emerged: programs that hold a language model in one hand and a set of tools in the other, and decide for themselves how to string them together to reach a goal. The framework is ready. The guidance mostly isn't — it lives scattered across API docs, conference talks, and GitHub samples pinned to preview builds that broke last Tuesday.

Building AI Agents with C# and .NET 10 is the picture on the puzzle box. Nineteen chapters take you from your first LLM call in C# to a production-hosted, observability-instrumented, safety-filtered multi-agent system, all on the stable, generally available surface of Microsoft Agent Framework 1.14, .NET 10 LTS, and C# 14.

You will learn how to:

  • Build your first ChatClientAgent, give it a persona, and expose it over HTTP with Minimal API
  • Solve the amnesia problem with sessions, history providers, and context providers
  • Get typed C# records back from the model instead of strings you have to regex
  • Give agents tools and function calling, with human-in-the-loop approval for the dangerous ones
  • Build and consume Model Context Protocol (MCP) servers in C#
  • Ground answers in your own documents with retrieval-augmented generation
  • Send images, audio, and video to multimodal agents — and treat them as untrusted input
  • Coordinate specialists with multi-agent orchestration and typed workflow graphs
  • Host agents with ASP.NET Core and .NET Aspire, and instrument them with OpenTelemetry
  • Layer guardrails against the OWASP LLM Top 10, from input sanitization to critic agents
  • Package domain expertise as Agent Skills and measure quality with local and cloud evaluation

Along the way you build the Contoso FAQ agent, a small but real production system that grows chapter by chapter until it ships: hosted, observable, guarded, and evaluated.

What makes this book different is discipline. Every listing compiles and runs, and every one is paired with its expected console output, so you know what success looks like before you press F5. Chapters follow an Explain–Demonstrate–Practice rhythm. Exercises come in three tiers (Basic, Intermediate, Challenge) with full worked solutions in Appendix E. The companion repository — one solution, 120 runnable projects — works against Azure OpenAI, OpenAI, GitHub Models, or a local Ollama model with a single configuration change, and ships dedicated helpers for Anthropic and Microsoft Foundry.

Written for intermediate C# developers. No AI or machine learning background required: if you can write a class, use LINQ, and wire up dependency injection, you're ready. Coming from Semantic Kernel or AutoGen? Appendices B and C are your migration maps.

Buying for a team? Volume licenses are available from 3 copies, with team pricing up to 40% off for larger groups — one purchase, one invoice, a copy for everyone.

The companion code lives at https://github.com/RachidD68/building-ai-agents-with-csharp-and-dotnet-10

Team Discounts

Team Discounts

Get a team discount on this book!

  • Up to 3 members

    Minimum price
    $69.00
    Suggested price
    $92.00
  • Up to 5 members

    Minimum price
    $109
    Suggested price
    $149
  • Up to 10 members

    Minimum price
    $209
    Suggested price
    $279
  • Up to 15 members

    Minimum price
    $299
    Suggested price
    $399
  • Up to 25 members

    Minimum price
    $449
    Suggested price
    $599

Bundle

Bundles that include this book

Author

About the Author

Rachid DAHIR

I design systems for the long haul.

As a software architect, technical author, and educator based in Morocco, I've spent more than a decade building enterprise-grade .NET solutions in financial services, healthcare, and large-scale enterprise environments — where reliability, performance, and clean architecture are not optional.

I write for developers who are ready to move past tutorials. My books share a deliberate standard: production-grade code only — no toy examples, no shortcuts that would never survive a code review; every concept explained, demonstrated, then practiced; every advanced topic taught with the same patience as an introductory one — because complexity is never an excuse for a poor explanation.

Whether you're a mid-career developer leveling up, a solution architect consolidating best practices, or an enterprise team standardizing modern .NET, my goal stays the same: clarity without compromise.

When I'm not writing code or prose, I explore mathematics, AI research, and natural health.

Contents

Table of Contents

Front Matter
  • Preface
  • Introduction
  • About the Author
Part I — Foundations

Why agentic AI matters for .NET, the C# essentials this book builds on, the mental model behind LLMs, and a working dev environment with your first end-to-end LLM call.

  • Chapter 1 — The AI Revolution in .NET
    • From software you write to software you delegate to
    • What makes software agentic: the agent loop
    • Agents, workflows, and plain LLM calls
    • Where .NET sits in the AI world
    • How Semantic Kernel and AutoGen became the Microsoft Agent Framework
    • Where agents fit in your career
    • Three things that change when the model joins your stack
    • Agents act — and that changes the risk picture
    • What you’ll build in this book
    • A first glimpse of the code
    • A word on how this book treats you
    • When not to reach for an agent
  • Chapter 2 — C# Essentials for AI Development
    • Async, Task, and CancellationToken
    • Records, primary constructors, and required members
    • Raw string literals
    • Pattern matching for LLM response dispatch
    • Collection expressions, nullable references, and extension methods
    • JSON serialization with System.Text.Json
    • Dependency injection and Minimal API
    • What this earns you in the rest of the book
  • Chapter 3 — How LLMs Work: A Developer’s Mental Model
    • Tokens — the atom of the LLM world
    • The conversation is a list of messages
    • Next-token prediction — the mechanism
    • Temperature and top-p — controlling randomness
    • Prompting techniques — just enough for Chapter 5
    • Embeddings and cosine similarity
    • Token economics — what this costs
  • Chapter 4 — Setting Up Your Dev Environment
    • Install the SDK and IDE
    • Pick a provider
    • Provisioning
    • Configure appsettings.json
    • Your first LLM call
    • Your first streaming response
    • When the first call fails
Part II — Your First Agents

Build your first ChatClientAgent. Wire conversations and memory so the agent remembers what it just said. Demand structured output so the model returns a typed C# record instead of free-form prose.

  • Chapter 5 — Hello, Agent!
    • What a ChatClientAgent actually is
    • Three ways to create an agent
    • Sessions are optional
    • Non-streaming: RunAsync
    • Overriding options per call
    • When the call fails
    • Streaming: RunStreamingAsync
    • Exposing the agent over HTTP
    • Putting it together — the mental model
  • Chapter 6 — Conversations and Memory
    • The amnesia problem
    • Sessions and history providers
    • Where does the conversation actually live?
    • Persisting sessions across restarts
    • Context providers
    • Keeping history under the window
    • Short-term vs long-term memory
    • Putting it all together
  • Chapter 7 — Structured Output and Typed Responses
    • Why typed responses matter
    • Your first typed call
    • Records, JSON attributes, schemas
    • Enums as structured validators
    • Not every agent supports structured output
    • The other door: ResponseFormat
    • Typed output while streaming
    • Tightening the schema (strict mode)
    • A production-grade typed call
    • Validating the extraction
    • When typed responses fail
    • The cost of a schema
    • Structured output under trimming and AOT
    • Polymorphic and discriminated-union responses
    • When to reach for typed responses
Part III — Giving Agents Superpowers

Tools and function calling. The Model Context Protocol for plugging in any data source. Embeddings and Retrieval-Augmented Generation so your agent answers from your data, not the training corpus. And multimodal input, so the agent can read images, not just words.

  • Chapter 8 — Tools and Function Calling
    • The tool landscape
    • The tool-calling loop
    • Your first tool
    • Multiple tools and chaining
    • Inside the loop — FunctionInvokingChatClient and its limits
    • Controlling tool choice
    • The shell tool — the most dangerous tool you’ll build
    • Tools backed by dependency injection
    • Concurrent tool calls
    • Graceful degradation
    • Tool approval — keeping a human in the loop
    • Giving an agent its own files: FileAccessProvider
    • Testing your tools
    • Tool design principles
    • Integrating with Chapter 7 — typed tools
    • Putting it together — the agent grows up
  • Chapter 9 — The Model Context Protocol
    • What MCP is (and isn't)
    • Building an MCP server in C#
    • MCP transports — stdio and streamable HTTP
    • Consuming an MCP server from an agent
    • The capability-negotiation handshake
    • Cross-language interop
    • A second MCP server — knowledge base preview
    • When to use MCP (and when not to)
    • Debugging an MCP server
  • Chapter 10 — Introduction to RAG
    • What RAG is
    • Embeddings, revisited in code
    • The RAG pipeline
    • Chunking strategies
    • The Contoso FAQ agent — wiring RAG into an agent
    • One provider, two modes: always-on vs on-demand
    • Metadata filtering
    • RAG-specific security
    • The cost of getting RAG wrong
    • Evaluating RAG quality
    • Hosted RAG — when MAF does the heavy lifting
    • When RAG is the wrong tool
  • Chapter 11 — Multimodal Agents
    • The same agent, a richer message
    • Two ways to send an image: URL and bytes
    • Choosing a vision model
    • From a picture to a typed C# record
    • An image is not free
    • An image is untrusted input
    • Multimodal RAG, honestly
    • Audio: two real paths
    • Video: sample the frames
    • Testing multimodal agents without a model
Part IV — Multi-Agent Collaboration

Two ways to coordinate multiple agents. Multi-Agent Systems for emergent collaboration; Workflows for deterministic orchestration when the steps must run in a known order.

  • Chapter 12 — Multi-Agent Systems
    • When to reach for multi-agent
    • Sequential pipeline — the simplest case
    • The orchestrator-and-specialists pattern
    • Agents-as-tools — the mental model
    • Content pipeline — Researcher → Writer → Editor
    • The built-in orchestrations
    • Streaming through a pipeline
    • Every inter-agent boundary is a trust boundary
    • Testing multi-agent compositions
    • The pattern catalog
    • BuildSequential vs manual chaining
    • Observability, cost, and failure modes
    • Mixing models, and the growing context
    • Design principles for multi-agent
    • When NOT to go multi-agent
  • Chapter 13 — Introduction to Workflows
    • Why workflows
    • The primitives
    • Sequential workflow
    • Conditional edges — branching on data
    • Agents as workflow executors
    • Approval workflow — human-in-the-loop with a revision loop
    • Checkpointing and durable resume
    • State isolation — fresh instance per run
    • Idiomatic fan-out and fan-in
    • Sub-workflows and workflows-as-agents
    • Visualizing a workflow
    • Testing workflows
    • The workflow event stream
    • Workflows vs multi-agent — when to pick which
    • Design principles
    • When workflows are the wrong tool
    • Loop engineering — the agent as a control system
Part V — Going to Production

ASP.NET Core hosting with Aspire. End-to-end observability with OpenTelemetry. Safety, content filtering, and guardrails. Agent Skills for packaging domain expertise. Evaluation for measuring agent quality. The road ahead — what to build next once the book is done.

  • Chapter 14 — Hosting and Deployment
    • Why hosting matters
    • AddAIAgent() — the hosting extension
    • Streaming from a hosted agent
    • .NET Aspire — orchestration and observability in one
    • The A2A protocol — agent discovery and invocation over HTTP
    • Securing the agent API
    • Rate limiting and resilience
    • Deployment considerations
    • Containerizing the agent service
    • Deploying to the cloud
    • A fully-hosted Contoso FAQ agent
  • Chapter 15 — Observability and Debugging
    • The three pillars
    • OpenTelemetry — the .NET story
    • The GenAI semantic conventions
    • Structured logging with ILogger
    • Custom metrics
    • Custom traces with ActivitySource
    • Running it
    • Exporting to production
    • Dashboards worth building
    • When observability fails you
    • Evaluation: the fourth signal
    • Debugging an agent in production
  • Chapter 16 — Safety and Guardrails
    • The Quality Pyramid
    • A threat model to anchor the layers — OWASP LLM Top 10
    • Middleware — DelegatingChatClient and .Use()
    • Input sanitization — prompt injection and PII
    • The critic-agent pattern
    • Injecting safety context mid-run — the AIContextProvider hook
    • Indirect prompt injection — when the attack hides in the data
    • Excessive Agency — gating the tools that can act
    • Improper Output Handling — the answer is untrusted input
    • Unbounded Consumption — denial-of-wallet and runaway loops
    • Graduating from regex — Azure AI Content Safety
    • Closing the loop — logging hygiene and retention
    • Combining the layers
    • Design principles for safety
    • When safety fails
  • Chapter 17 — Agent Skills
    • What a Skill is, and what it is not
    • Progressive disclosure — the four stages
    • Providing skills to an agent — the AgentSkillsProvider
    • Code-defined skills — AgentInlineSkill
    • Class-based skills — AgentClassSkill<T>
    • Mixing skill sources — AgentSkillsProviderBuilder
    • Watching progressive disclosure run
    • Gating scripts with human approval
    • Customizing the system prompt
    • Dependency injection through skills
    • Security — treating skills like dependencies
    • Skills vs. workflows — when to pick which
  • Chapter 18 — Evaluation
    • Why eval is the blind spot of agent dev
    • The three core types
    • LocalEvaluator and the built-in EvalChecks
    • Custom checks with FunctionEvaluator.Create
    • EvaluateAsync — running queries against an evaluator
    • FoundryEvals — cloud-based LLM-as-judge scoring
    • Conversation split strategies
    • Mixing local and cloud evaluators in one pass
    • Evaluating workflows — Run.EvaluateAsync and per-agent breakdown
    • Evaluating a RAG agent: grounding the Contoso FAQ agent
    • The judge client: ChatConfiguration
    • Safety evaluation
    • Eval-driven development
    • Composing with Microsoft.Extensions.AI.Evaluation
    • Wiring eval into CI
  • Chapter 19 — Your Next Steps
    • What to build next
    • The agentic protocol triad: A2A and AG-UI
    • Enterprise governance patterns
    • Contributing to MAF
    • Where the ecosystem is heading
    • Staying current
    • A short send-off
Back Matter
  • Appendix A — NuGet Package Reference
  • Appendix B — Semantic Kernel to MAF Migration Map
  • Appendix C — AutoGen to MAF Migration Map
  • Appendix D — Glossary
  • Appendix E — Exercise Solutions Reference
  • Other Books You'll Enjoy
  • Index

Get the free sample chapters

Click the buttons to get the free sample in PDF or EPUB, or read the sample online here

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

In fact, authors have earned over $15 million writing, publishing and selling on Leanpub.

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub