Bit of Technology

  • Archive
  • About Me
    • Advertise
    • Disclaimer
  • Speaking
  • Contact

Part 6: Building an MCP Client and AI Agent in .NET

October 11, 2026 By Taiseer Joudeh Leave a Comment

Share this:

  • Share on X (Opens in new window) X
  • Share on LinkedIn (Opens in new window) LinkedIn
  • Share on Reddit (Opens in new window) Reddit
  • Share on Facebook (Opens in new window) Facebook
  • Email a link to a friend (Opens in new window) Email

This is the sixth part of Building MCP Servers in .NET for AI Agents. The topics we’ll cover are:

  • What is the Model Context Protocol? An Introduction for .NET Developers
  • Building Your First MCP Server in C#
  • MCP Tools, Resources and Prompts in .NET
  • Wiring MCP Tools to Azure SQL and External APIs
  • Hosting an MCP Server in ASP.NET Core with Streamable HTTP
  • Building an MCP Client and AI Agent in .NET (This Post)
  • Securing an MCP Server with Microsoft Entra ID
  • Deploying an MCP Server to Azure Container Apps
  • Connecting an MCP Server to Microsoft Foundry Agent Service
  • Observability, Cost Control and MCP Security

The source code for this tutorial is available on GitHub.

Building an MCP Client and AI Agent in .NET

Five parts in, our server has always been used by somebody else’s software. VS Code Copilot connects to it, decides which tool to call, and shows you an answer. We write the tools and then hand them over.

That’s fine until something goes wrong. When Copilot gives a strange answer you can’t tell whether the model picked the wrong tool, passed bad arguments, or got a result it didn’t understand. You’re guessing from the outside.

In this post we write the client. It connects to our MCP server, asks the model what to do, calls the tools, and feeds the results back. Every step prints to the console.

I’ll say now that this is the post where one of our own tool descriptions turned out to be wrong, and the client is how I found out.

What an agent actually is

The word gets used loosely, so here’s the version that fits in a paragraph.

A chat model can’t call anything. It reads text and writes text. What it can do is write back a message that says “I want to call search_expense_reports with these arguments”. That’s it. Something else has to notice that message, run the tool, and tell the model what happened.

That something else is the agent. It’s a loop:

  1. Send the conversation to the model, along with a list of the tools that exist.
  2. Read the reply. If it’s an answer, you’re done.
  3. If it’s a tool call, run the tool.
  4. Append the result to the conversation and go back to step 1.

There’s no more to it. The loop is a small piece of C#, and we’re going to write it before we use a library that writes it for us.

The reason to write it yourself once is debugging. When your agent calls the wrong tool six months from now, you need to know which of those four steps went wrong.

Where the model comes from

We need a model to call. That means a Microsoft Foundry resource in your subscription and a model deployed into it.

This is the first thing in the series that costs money. Azure SQL ran on the free offer, and Frankfurter is free. Model calls don’t. A tutorial’s worth of gpt-5.4-mini is pennies, but it isn’t zero, and an agent that loops badly can spend more than you expect. We put a ceiling on that in a moment.

Step 1: Set your variables

Same pattern as Part 4, with one new name.

PowerShell
1
2
3
4
5
6
$SUFFIX            = "tj01"
$LOCATION          = "westeurope"
$RESOURCE_GROUP    = "rg-bitoftech-expenses"
 
$FOUNDRY_NAME      = "aif-bitoftech-expenses-$SUFFIX"
$MODEL_DEPLOYMENT  = "expenses-chat"

$FOUNDRY_NAME carries the suffix because it becomes a hostname. $MODEL_DEPLOYMENT is a label you invent. It has nothing to do with which model you deploy, and I’ve named it after the job it does rather than after the model, so that swapping gpt-5.4-mini for something else later doesn’t leave a misleading name behind.

Step 2: Create the Foundry resource

PowerShell
1
2
3
4
5
6
7
8
az cognitiveservices account create `
  --name $FOUNDRY_NAME `
  --resource-group $RESOURCE_GROUP `
  --location $LOCATION `
  --kind AIServices `
  --sku S0 `
  --custom-domain $FOUNDRY_NAME `
  --yes

Let’s review the parameters:

  1. --name and --resource-group are the resource name and the group we created back in Part 4. Nothing new here.
  2. --kind AIServices asks for the combined Foundry resource. One resource gives you the OpenAI models plus speech, vision and the rest. There’s an older OpenAI kind that only does the models, and you don’t want it for new work.
  3. --sku S0 is the only tier on offer, so there’s no decision to make. It’s pay as you go. The resource itself costs nothing until you call a model.
  4. --custom-domain gives the resource its own hostname, which is what makes Microsoft Entra ID tokens work against it. If you leave it out, you’re on key based access, which this series doesn’t use. It can’t be added later either, so set it now.
  5. --yes skips the prompt asking you to accept the responsible AI terms. Drop it if you’d rather read them first.

Of those, --custom-domain is the one that catches people out, because the failure shows up much later as a confusing 401.

Step 3: Deploy the model

PowerShell
1
2
3
4
5
6
7
8
9
az cognitiveservices account deployment create `
  --name $FOUNDRY_NAME `
  --resource-group $RESOURCE_GROUP `
  --deployment-name $MODEL_DEPLOYMENT `
  --model-name gpt-5.4-mini `
  --model-version 2026-03-17 `
  --model-format OpenAI `
  --sku-name GlobalStandard `
  --sku-capacity 10

Let’s review the parameters:

  1. --name and --resource-group point at the Foundry resource from Step 2. This command puts a model inside it.
  2. --deployment-name is our own label, expenses-chat. This is the string the code uses in Step 9, and the one place people mix up the deployment with the model.
  3. --model-name and --model-version say which model goes in. Pinning the version matters. Leave it floating and a new version can land under you, and a model that behaves differently is the hardest kind of change to notice.
  4. --model-format OpenAI is the publisher. Foundry hosts models from several of them, so this tells it which catalogue to look in.
  5. --sku-name GlobalStandard is pay per token, with your requests routed to wherever there’s free capacity. The alternatives keep the request inside a region or a geography and cost more. Take GlobalStandard unless you have a data residency rule that says otherwise.
  6. --sku-capacity 10 is your rate limit, in units of 1,000 tokens per minute.

That last one is worth setting deliberately. Ten units is plenty for a console app, and it caps how fast a runaway loop can spend your money.

Step 4: Give yourself access

PowerShell
1
2
3
4
5
6
7
8
9
10
$FOUNDRY_ID = az cognitiveservices account show `
  --name $FOUNDRY_NAME --resource-group $RESOURCE_GROUP --query id -o tsv
 
$MY_OID = az ad signed-in-user show --query id -o tsv
 
az role assignment create `
  --assignee-object-id $MY_OID `
  --assignee-principal-type User `
  --role "Cognitive Services OpenAI User" `
  --scope $FOUNDRY_ID

Same idea as the Azure SQL setup in Part 4. No key, no secret in the repository, and the agent runs as whoever is signed in to the Azure CLI.

Note: role assignments take a minute or two to apply. If your first run gets a 401, wait before you start changing code.

Step 5: Get the endpoint

PowerShell
1
2
3
az cognitiveservices account show `
  --name $FOUNDRY_NAME --resource-group $RESOURCE_GROUP `
  --query properties.endpoint -o tsv

Mine printed https://aif-bitoftech-expenses-tj01.cognitiveservices.azure.com/. Keep it, it goes into configuration in Step 7.

Building the agent

Step 6: Create the project

This is the second project in the solution, which is why there’s been a solution file since Part 2.

C#
1
2
3
4
5
6
7
8
9
10
11
12
dotnet new console -o src/BitOfTech.Expenses.Agent
dotnet sln add src/BitOfTech.Expenses.Agent
 
cd src/BitOfTech.Expenses.Agent
 
dotnet add package ModelContextProtocol.Core --version 2.2.0
dotnet add package Microsoft.Extensions.AI --version 10.10.0
dotnet add package Microsoft.Extensions.AI.OpenAI --version 10.10.0
dotnet add package Azure.AI.OpenAI --version 2.9.0-beta.1
dotnet add package Azure.Identity --version 1.21.0
dotnet add package Microsoft.Agents.AI --version 1.22.0
dotnet add package Microsoft.Extensions.Configuration.Json --version 10.0.12

Seven packages looks like a lot. Here’s what each one is for:

  1. ModelContextProtocol.Core is the MCP client. It’s a different package from the one the server uses, because a client needs neither hosting nor ASP.NET Core.
  2. Microsoft.Extensions.AI gives you IChatClient, which is to models what HttpClient is to the web. One interface, many providers.
  3. Microsoft.Extensions.AI.OpenAI and Azure.AI.OpenAI connect that interface to Azure. The beta on the Azure package is normal and has been for a long time.
  4. Azure.Identity gives us DefaultAzureCredential, so we can authenticate without a key.
  5. Microsoft.Agents.AI is the agent framework. We don’t touch it until the end of the post.
  6. Microsoft.Extensions.Configuration.Json reads appsettings.json. A console project doesn’t get that for free the way a web project does.

Step 7: Configuration

Two endpoints, neither of them secret. The same argument as the connection string in Part 4: there’s nothing in here worth hiding.

src/BitOfTech.Expenses.Agent/appsettings.json

C#
1
2
3
4
5
6
7
8
9
{
  "Mcp": {
    "Endpoint": "http://localhost:5000/mcp"
  },
  "Foundry": {
    "Endpoint": "https://aif-bitoftech-expenses-tj01.cognitiveservices.azure.com/",
    "Deployment": "expenses-chat"
  }
}

Then one item in the csproj, which the web SDK handled for us in Part 5 but a console project will not:

src/BitOfTech.Expenses.Agent/BitOfTech.Expenses.Agent.csproj

C#
1
2
3
<ItemGroup>
  <Content Include="appsettings.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

Miss that and you get a FileNotFoundException pointing at your bin folder. I missed it.

Step 8: Connect to the MCP server

Open Program.cs, delete the Hello, World! line the template gave you, and start with configuration and the MCP connection.

src/BitOfTech.Expenses.Agent/Program.cs

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using Azure.AI.OpenAI;
using Azure.Identity;
using BitOfTech.Expenses.Agent;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Configuration;
using ModelContextProtocol.Client;
 
// Models reply in Markdown with characters the default Windows console cannot render.
Console.OutputEncoding = System.Text.Encoding.UTF8;
 
var configuration = new ConfigurationBuilder()
    .SetBasePath(AppContext.BaseDirectory)
    .AddJsonFile("appsettings.json")
    .Build();
 
var mcpEndpoint = configuration["Mcp:Endpoint"]!;
var foundryEndpoint = configuration["Foundry:Endpoint"]!;
var deploymentName = configuration["Foundry:Deployment"]!;
 
await using var transport = new HttpClientTransport(new HttpClientTransportOptions
{
    Endpoint = new Uri(mcpEndpoint),
    Name = "bitoftech-expenses"
});
 
await using var mcpClient = await McpClient.CreateAsync(transport);
 
var tools = await mcpClient.ListToolsAsync();
 
Console.WriteLine($"Connected to {mcpClient.ServerInfo?.Name} at {mcpEndpoint}");
Console.WriteLine($"{tools.Count} tools: {string.Join(", ", tools.Select(t => t.Name))}");

What we have done here is the following:

  1. SetBasePath(AppContext.BaseDirectory) is the same lesson as Part 4 and Part 5. Read configuration from the folder the binary is in, not from wherever the command was typed.
  2. HttpClientTransport points at the server. Name is a label that shows up in logs on both ends.
  3. McpClient.CreateAsync opens the connection. This is the line that negotiates the protocol, and we’re about to look at what it actually sent.
  4. ListToolsAsync asks the server what it has. Nothing in this file knows the tools are about expenses. It would work the same against any MCP server.
  5. Console.OutputEncoding is a small thing that saves confusion. Models write Markdown with characters the default Windows console turns into nonsense.

Run this now, with the server going in another terminal:

C#
1
2
Connected to BitOfTech.Expenses.Mcp at http://localhost:5000/mcp
5 tools: create_expense_report, search_expense_reports, submit_expense_report, convert_currency, get_expense_report

Then look at the server’s terminal. This is what Part 5 said would happen, happening:

C#
1
2
3
4
5
6
method 'server/discover' request handler called
method 'server/discover' request handler completed in 11.2826ms
POST /mcp - 200 - text/event-stream
 
method 'tools/list' request handler called
POST /mcp - 200 - text/event-stream

No initialize. The client preferred the 2026-07-28 revision, probed with server/discover, and our stateless server accepted it. We configured none of that. McpClientOptions.ProtocolVersion defaults to null, which means prefer the newest and fall back if the server can’t keep up.

The server also logs the caller as Client (BitOfTech.Expenses.Agent 1.0.0.0). It still knows who is asking, even without a handshake. Hold that thought until Part 7.

Why there’s no conversion code

Worth a short detour here, because this is the part that surprises people who have wired MCP into an agent in another language.

Two different worlds have to meet. The MCP server describes its tools in the protocol’s own JSON, sent over the network. The model libraries want tools as .NET objects: a name, a description, a JSON schema and something they can actually call. Getting from one to the other is normally your job. You read the tool list, build an object for each tool, and write the callback that sends a tools/call back over the wire when the model picks one.

In .NET that work is already done for you. ListToolsAsync hands back McpClientTool objects, and McpClientTool derives from AIFunction:

C#
1
McpClientTool -> AIFunction -> AIFunctionDeclaration -> AITool

AITool is exactly the type Microsoft.Extensions.AI expects in ChatOptions.Tools. So the tools that arrived from a server over HTTP are already the objects your chat call wants. When you get to Step 11 you’ll see the whole integration is Tools = [.. tools], and there’s nothing else to it.

Calling one works the same way. You call InvokeAsync on it like any other AIFunction, and the SDK quietly turns that into a tools/call request to the server, waits for the response and hands you the result.

Five tools, defined in another project, running in another process, and there’s no code in the middle translating between them.

Step 9: Add the model client

Still in Program.cs, directly below what you just wrote. Three chained calls turn an Azure resource into the interface the rest of the code uses.

src/BitOfTech.Expenses.Agent/Program.cs, added below the previous block:

C#
1
2
3
4
5
IChatClient chatClient = new AzureOpenAIClient(
        new Uri(foundryEndpoint),
        new DefaultAzureCredential())
    .GetChatClient(deploymentName)
    .AsIChatClient();

Reading it from the inside out:

  1. AzureOpenAIClient is the Azure specific client. DefaultAzureCredential finds your Azure CLI login, so there’s no key anywhere. It’s the same credential type the server uses for Azure SQL, and when that server runs in Azure from Part 8 it picks up a managed identity instead, with no code change.
  2. GetChatClient(deploymentName) takes the deployment name, expenses-chat, and not the model name. That distinction bites people, because most code samples name the deployment after the model and the two strings end up looking interchangeable. They aren’t.
  3. AsIChatClient() is the bridge. Above this line you’re holding something from Azure. Below it you’re holding IChatClient, which doesn’t know which provider is underneath.

That last point is why the next two steps contain no Azure code at all.

Step 10: Write the system prompt

The model needs to know what job it’s doing. This gets a small file of its own, because it’s the piece you’ll edit most while tuning behaviour and it’s easier to find when it isn’t buried in Program.cs.

src/BitOfTech.Expenses.Agent/AgentInstructions.cs

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
namespace BitOfTech.Expenses.Agent;
 
public static class AgentInstructions
{
    public const string System = """
        You are the BitOfTech expenses assistant. You help employees look up, create and
        submit expense reports.
 
        Use the tools you are given. Never invent a report id, an amount or an exchange rate.
        If a tool fails, tell the user what it said rather than guessing an answer.
        Keep replies short.
        """;
}

Two of those sentences are doing real work.

“Never invent a report id, an amount or an exchange rate.” Part 4 put the same instruction in the convert_currency failure messages. A model handed a failure will often produce a plausible number rather than admit it doesn’t have one. Saying it in both places is not redundant.

“If a tool fails, tell the user what it said.” All those McpException messages we wrote in Parts 3 and 4 only help if the agent passes them on.

Notice what this prompt does not do. It doesn’t list the tools or explain when to use them. That information already lives in the tool descriptions on the server, which is where it belongs. If you find yourself describing your tools in the system prompt, the descriptions are what need the work.

Step 11: Write the loop

Now the part that makes it an agent. It’s one small class, and it’s the only file in this project doing anything clever.

src/BitOfTech.Expenses.Agent/ToolLoop.cs

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using Microsoft.Extensions.AI;
 
namespace BitOfTech.Expenses.Agent;
 
// The tool calling loop, written out by hand so every step is visible.
// The numbered comments match the four steps described in the post.
public sealed class ToolLoop(IChatClient chatClient, IReadOnlyList<AITool> tools)
{
    // The system prompt goes in once. Everything after it is appended as the conversation grows.
    private readonly List<ChatMessage> _messages =
        [new ChatMessage(ChatRole.System, AgentInstructions.System)];
 
    // The MCP tools go in as they arrived, because McpClientTool is already an AITool.
    private readonly ChatOptions _options = new() { Tools = [.. tools] };
 
    public async Task RunTurnAsync(string userInput, CancellationToken cancellationToken = default)
    {
        _messages.Add(new ChatMessage(ChatRole.User, userInput));
 
        // One question can take several trips to the model, so keep going until it stops
        // asking for tools.
        while (true)
        {
            // Step 1. Send the whole conversation and the tool list.
            var response = await chatClient.GetResponseAsync(_messages, _options, cancellationToken);
            _messages.AddMessages(response);
 
            // Step 2. Read the reply. One reply can ask for several tools at once.
            var calls = response.Messages
                .SelectMany(message => message.Contents)
                .OfType<FunctionCallContent>()
                .ToList();
 
            // No tool call means the model is answering, which is the only way out of the loop.
            if (calls.Count == 0)
            {
                Console.WriteLine(response.Text);
                return;
            }
 
            var results = new List<AIContent>();
 
            foreach (var call in calls)
            {
                Console.WriteLine($"  -> {call.Name}({FormatArguments(call.Arguments)})");
 
                var tool = tools.OfType<AIFunction>().FirstOrDefault(t => t.Name == call.Name);
 
                // A model can ask for a tool that isn't there. Tell it so instead of throwing,
                // and it gets a chance to correct itself on the next trip.
                if (tool is null)
                {
                    results.Add(new FunctionResultContent(call.CallId, $"No tool named {call.Name}."));
                    continue;
                }
 
                // Step 3. Run the tool. This goes over HTTP to the MCP server.
                var arguments = new AIFunctionArguments(call.Arguments);
                var result = await tool.InvokeAsync(arguments, cancellationToken);
 
                Console.WriteLine($"  <- {Truncate(result?.ToString())}");
 
                // CallId is what ties this result back to the request the model made.
                results.Add(new FunctionResultContent(call.CallId, result));
            }
 
            // Step 4. Put the results into the conversation and go round again.
            _messages.Add(new ChatMessage(ChatRole.Tool, results));
        }
    }
 
    private static string FormatArguments(IDictionary<string, object?>? arguments) =>
        arguments is null or { Count: 0 }
            ? string.Empty
            : string.Join(", ", arguments.Select(a => $"{a.Key}: {a.Value}"));
 
    private static string Truncate(string? text, int max = 160) =>
        text is null ? "null" : text.Length <= max ? text : text[..max] + " ...";
}

The comments mark the four steps, so you can read the code against the list at the top of the post:

  1. GetResponseAsync sends the conversation and the tool list.
  2. calls.Count == 0 means the model gave an answer, so print it and stop.
  3. tool.InvokeAsync runs the tool. That goes over HTTP to our MCP server, which runs SQL, which returns JSON.
  4. The results go back in as a Tool message and the loop repeats.

Four details in that file are worth pausing on.

The _messages field is the conversation, and you own it. Nothing remembers it for you. Every trip sends the whole history, which is also why a long conversation costs more than a short one.

The _options field is where the MCP tools go. Tools = [.. tools] and nothing else. This is the payoff from the type chain in “Why there’s no conversion code” above.

calls is a list because one reply can ask for several tools. The model can ask for three things at once, and it expects three results back in one Tool message. That’s what CallId is for, since it ties each result to the request it answers.

The two Console.WriteLine calls inside the loop are the reason this post exists. They print the tool name, the arguments the model chose, and what came back. Without them an agent is a black box: you see a confident answer and have no way to check how it was reached. With them, every decision the model made is on your screen as it happens. You’ll see why that matters once we run it.

Step 12: Wire up the console

Last piece. Back in Program.cs, below the chat client, add a prompt and a read loop.

src/BitOfTech.Expenses.Agent/Program.cs, added at the end:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Console.WriteLine("Type a question, or an empty line to quit.");
Console.WriteLine();
 
var loop = new ToolLoop(chatClient, [.. tools]);
 
while (ReadInput() is { } input)
{
    await loop.RunTurnAsync(input);
    Console.WriteLine();
}
 
static string? ReadInput()
{
    Console.Write("> ");
    var line = Console.ReadLine();
    return string.IsNullOrWhiteSpace(line) ? null : line;
}

That’s the whole application. Configuration, an MCP connection, a chat client, a loop and a prompt. The ToolLoop holds the conversation, so the same instance handles every turn and the model remembers what you said earlier.

Running it

Start the server in one terminal and the agent in another.

PowerShell
1
2
3
dotnet run --project src/BitOfTech.Expenses.Mcp
 
dotnet run --project src/BitOfTech.Expenses.Agent

The agent connects, prints the tools it found and waits. I started with a question that can’t be answered in one lookup.

PowerShell
1
2
3
4
5
6
7
8
9
10
11
12
> What's on Omar's London offsite report?
  -> search_expense_reports(employeeName: Omar)
  <- [{"id":1003,"title":"London team offsite","employeeName":"Omar Nasser", ...
  -> get_expense_report(reportId: 1003)
  <- {"id":1003,"lines":[{"description":"Train tickets","category":"Travel", ...
 
Omar Nasser's London team offsite report (1003) comes to GBP 1,205.75 and is still
Submitted. It has three lines:
 
- Train tickets, Travel, GBP 96.75, 7 September
- Hotel, three nights, Accommodation, GBP 689.00, 7 September
- Team meals, Meals, GBP 420.00, 8 September

Those four indented lines come from the two Console.WriteLine calls we added in Step 11. They let you watch the model work.

What we have here is the following:

  1. I asked about a report without giving an id, so the model called search_expense_reports first to find one.
  2. It read 1003 out of that JSON and passed it to get_expense_report.
  3. The while loop went round twice. Two replies carrying tool calls, then a third carrying text.
  4. Nothing in our code decided any of that. We never wrote “search, then fetch”. The model worked out the order from the two tool descriptions.

That last point matters. We wrote those tools back in Part 2 and Part 3, with no idea what anyone would ask.

A question it gets wrong

Then I asked something that looks easier.

PowerShell
1
2
3
4
5
6
7
> What has Sara submitted?
  -> search_expense_reports(employeeName: Sara, currentStatus: Submitted)
  <- [{"id":1001,"title":"Berlin customer workshop","employeeName":"Sara Haddad", ...
 
Sara Haddad has submitted 1 report:
 
- 1001 Berlin customer workshop, EUR 842.50, submitted 2026-09-02

That answer is wrong, and the trace tells you why before you go looking.

Sara has two reports. 1001 is Submitted. 1002 is Approved, and it has a submission date of 2026-08-14. It was submitted, then approved. The question asked what she submitted, so both count. The model passed currentStatus: Submitted and cut one of them off.

Now look at what we wrote in Part 3, which was still in the code when I ran this:

C#
1
2
A report that was approved or rejected was also submitted at some point, so do not
filter on Submitted to answer questions about what somebody has submitted.

That sentence is there for this exact case. It worked when I tested it against Copilot in Part 3. It doesn’t work against gpt-5.4-mini, and I ran the question three times to be sure it wasn’t a one off.

Two things follow from that.

A tool description guides a model, it doesn’t bind one. We’ve been using descriptions to shape behaviour since Part 2 and it mostly works well. This is a reminder of what kind of thing a description is.

Behaviour travels with the model, not with your code. Nothing in the server changed between Part 3 and now. An instruction that works on one model may not on another, and it needs checking again whenever you switch.

This is also the answer to why we wrote the loop by hand. In Copilot the reply reads perfectly well and you’d have no reason to doubt it. Here, -> search_expense_reports(employeeName: Sara, currentStatus: Submitted) is printed on the screen right above the answer.

Fixing it

My first attempt was to make the parameter description blunter, lead with the rule, and add the positive case:

C#
1
2
3
4
The report's current state. Leave this out unless the user asks about a specific state.
Do not set it to Submitted when the user asks what somebody submitted or filed, because
approved and rejected reports were submitted too. Only set Submitted when the user asks
what is still waiting for approval.

Three runs. Same wrong call every time.

What worked was moving the rule out of the parameter and into the tool description.

src/BitOfTech.Expenses.Mcp/Tools/ExpenseTools.cs

C#
1
2
3
4
5
6
7
8
[McpServerTool(Name = "search_expense_reports")]
[Description("Searches expense reports by employee. Returns a summary of each match without the line items. The word submitted in a question is not a status filter: every report that is now Approved or Rejected was submitted earlier too. To answer what somebody submitted or filed, pass employeeName only and leave currentStatus empty. Call get_expense_report when you need the lines.")]
public async Task<IReadOnlyList<ExpenseReportSummary>> SearchExpenseReportsAsync(
    [Description("Part of an employee name, matched case insensitively. Omit to search across all employees.")]
    string? employeeName = null,
    [Description("Filters to reports sitting in this exact state right now. Omit it unless the user asked for one specific state.")]
    ExpenseReportStatus? currentStatus = null,
    CancellationToken cancellationToken = default)

Restart the server and ask the same question:

PowerShell
1
2
3
4
5
> What has Sara submitted?
  -> search_expense_reports(employeeName: Sara)
 
Sara Haddad has submitted 2 expense reports:
...

Three for three. And the opposite case still works, so the filter isn’t simply broken now:

PowerShell
1
2
> Which reports are still waiting for approval?
  -> search_expense_reports(currentStatus: Submitted)

Why the move mattered. My reading is that a parameter description gets consulted once the model has already decided to use that parameter, and by then the decision is made. The tool description is read while the model is deciding what to call. That’s when the rule needs to arrive.

The other half is naming the trigger. “The word submitted in a question is not a status filter” points straight at the thing causing the mistake. The old version described the domain and left the model to draw the conclusion itself.

Important note: none of this is a guarantee. It works on this model today. If you have a rule that must hold, put it in code, the way create_expense_report simply refuses to accept a status at all. Descriptions steer, they don’t enforce.

The same thing with the agent framework

Everything so far used Microsoft.Extensions.AI, which is the plumbing layer. Microsoft.Agents.AI sits on top of it and writes the loop for you.

This is the layer to build on for real work. If you start an agent project today, start here. And if you do, you don’t need ToolLoop.cs at all. The whole class goes away, because the framework does that job.

So why did we write it? Because a loop somebody else wrote is hard to trust until you’ve written one yourself. You’ve seen the four steps in your own code now. When the framework does them for you, you know what it’s doing behind that one method call.

I’m keeping both in the project so you can run the same question through each and see the difference, so we add a command line switch rather than deleting what we have.

src/BitOfTech.Expenses.Agent/Program.cs. Replace the block you added in Step 12 with this:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
var useAgentFramework = args.Contains("--agent");
 
Console.WriteLine(useAgentFramework
    ? "Mode: Microsoft.Agents.AI"
    : "Mode: hand written tool loop");
Console.WriteLine("Type a question, or an empty line to quit.");
Console.WriteLine();
 
if (useAgentFramework)
{
    AIAgent agent = chatClient.AsAIAgent(
        instructions: AgentInstructions.System,
        name: "expenses",
        tools: [.. tools]);
 
    var session = await agent.CreateSessionAsync();
 
    while (ReadInput() is { } input)
    {
        var response = await agent.RunAsync(new ChatMessage(ChatRole.User, input), session);
        Console.WriteLine(response.Text);
        Console.WriteLine();
    }
}
else
{
    var loop = new ToolLoop(chatClient, [.. tools]);
 
    while (ReadInput() is { } input)
    {
        await loop.RunTurnAsync(input);
        Console.WriteLine();
    }
}
 
static string? ReadInput()
{
    Console.Write("> ");
    var line = Console.ReadLine();
    return string.IsNullOrWhiteSpace(line) ? null : line;
}

The else branch is exactly what you had in Step 12. Only the if branch is new, and it’s worth reading next to ToolLoop.cs, because those five statements replace that entire class.

Line by line:

  1. args.Contains("--agent") picks the mode. If you run it normally, you get the loop you wrote. If you add the switch, you get the framework.
  2. chatClient.AsAIAgent(...) wraps the same IChatClient we built in Step 9. The system prompt becomes instructions, a property of the agent, instead of the first message in a list.
  3. tools: [.. tools] is the same MCP tools going in, unchanged.
  4. CreateSessionAsync() returns an AgentSession. That’s the conversation. You no longer hold a List<ChatMessage>, because the session holds it for you.
  5. RunAsync(message, session) does everything RunTurnAsync did: sends the conversation, reads the reply, runs any tools, loops until the model has an answer.

Note: if you find older samples using CreateAIAgent or AgentThread, those names have changed. In 1.22.0 it’s AsAIAgent and AgentSession.

Run both and compare.

PowerShell
1
2
3
dotnet run --project src/BitOfTech.Expenses.Agent
 
dotnet run --project src/BitOfTech.Expenses.Agent -- --agent

Same question, same correct answer. But the framework version prints this:

PowerShell
1
2
3
> What has Sara submitted?
Sara Haddad has submitted 2 expense reports:
...

The tool call isn’t there. It happened, and the framework didn’t mention it.

That’s the trade. You get less code to maintain and proper handling of retries and cancellation. You give up the window into the model’s decisions, and that window is what found the problem in the previous section. So ship the framework version, and keep the hand written loop in the solution as a debugging tool. When an agent starts answering oddly, running the same question through it takes a minute and usually shows you the cause.

Summary

The client was easier to build than the server, mostly because McpClientTool is already an AIFunction and nothing needed adapting.

The part I’d remember is what happened when we pointed a different model at a description written for another one. It had worked fine for three posts. It stopped working without anything in the server changing, and two Console.WriteLine calls made that obvious in under a minute.

If you write MCP servers, write a small client too. Not to ship it. To watch what models actually do with the tools you gave them.

Part 7 is the one this has been building toward. Right now anyone who can reach our server can call submit_expense_report, and the server has no idea who’s asking. We put Microsoft Entra ID in front of it, and the tools start caring about identity.

The source code for this tutorial is available on GitHub.

Follow me on X @TJoudeh and on LinkedIn

References:

  • Microsoft.Extensions.AI libraries
  • Microsoft Agent Framework
  • MCP C# SDK on GitHub
  • Microsoft Foundry documentation
  • Azure Identity client library for .NET
  • az cognitiveservices account command reference

Share this:

  • Share on X (Opens in new window) X
  • Share on LinkedIn (Opens in new window) LinkedIn
  • Share on Reddit (Opens in new window) Reddit
  • Share on Facebook (Opens in new window) Facebook
  • Email a link to a friend (Opens in new window) Email

Like this:

Like Loading…

Related Posts

  • Part 10: Observability, Cost Control and MCP Security
  • Part 9: Connecting an MCP Server to Microsoft Foundry Agent Service
  • Part 8: Deploying an MCP Server to Azure Container Apps
  • Part 7: Securing an MCP Server with Microsoft Entra ID
  • Part 5: Hosting an MCP Server in ASP.NET Core with Streamable HTTP

Filed Under: AI, Azure, MCP Tagged With: .NET 10, Agent Framework, AI Agents, Azure OpenAI, MCP, Microsoft Foundry, Microsoft.Extensions.AI, Model Context Protocol

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About Taiseer

Husband, Father, Consultant @ MSFT, Life Time Learner... Read More…

Buy me a coffeeBuy me a coffee

Recent Posts

  • Part 10: Observability, Cost Control and MCP Security
  • Part 9: Connecting an MCP Server to Microsoft Foundry Agent Service
  • Part 8: Deploying an MCP Server to Azure Container Apps
  • Part 7: Securing an MCP Server with Microsoft Entra ID
  • Part 6: Building an MCP Client and AI Agent in .NET

Blog Archives

Recent Posts

  • Part 10: Observability, Cost Control and MCP Security
  • Part 9: Connecting an MCP Server to Microsoft Foundry Agent Service
  • Part 8: Deploying an MCP Server to Azure Container Apps
  • Part 7: Securing an MCP Server with Microsoft Entra ID
  • Part 6: Building an MCP Client and AI Agent in .NET

Tags

.NET .NET 10 AI Agents AJAX AngularJS API API Versioning ASP.NET ASP.NET 6 Authentication Autherization Server Azure Azure Active Directory B2C Azure AD B2C Azure Container Apps C# Code First Dapr Dependency Injection Entity Framework Foursquare API GitHub Copilot jQuery JSON JSON Web Tokens JWT MCP Microservice Model Context Protocol Ninject OAuth OData Redis Resource Server REST RESTful Single Page Applications SPA Token Authentication Tutorial VS Code Web API Web API 2 Web API Security Web Service

Search

Copyright © 2026 Ā· eleven40 Pro Theme on Genesis Framework Ā· WordPress Ā· Log in

%d