How to See What a Microsoft Agent Framework Agent Sends to the Model in C#
One run of a Microsoft Agent Framework agent can be several requests to the model, and each request carries its own instructions, tools and messages. IChatClient middleware sees every one of them before it leaves your app. This guide adds middleware that prints each request of a small C# agent with one tool, and the second request turned out to carry far less than the first.
Syntax
AIAgent <agent> = <projectClient>.AsAIAgent(
<options>,
clientFactory: chatClient => chatClient.AsBuilder()
.Use(getResponseFunc: <Middleware>, getStreamingResponseFunc: null)
.Build());
async Task<ChatResponse> <Middleware>(
IEnumerable<ChatMessage> messages,
ChatOptions? options,
IChatClient innerClient,
CancellationToken cancellationToken)
{
// Read messages and options here.
return await innerClient.GetResponseAsync(messages, options, cancellationToken);
}
| Part | What it is |
|---|---|
<agent> | The variable that holds the agent. |
<projectClient> | An AIProjectClient for your Microsoft Foundry project. |
<options> | The agent's ChatClientAgentOptions: its name, model, instructions and tools. |
clientFactory | A function that gets the chat client the agent would use and returns the one it should use instead. Its reference: Provides a way to customize the creation of the underlying IChatClient used by the agent. |
chatClient.AsBuilder() | Creates a new ChatClientBuilder using innerClient as its inner client. The builder stacks middleware on top of the chat client. |
.Use(getResponseFunc: <Middleware>, getStreamingResponseFunc: null) | Adds <Middleware> to the stack. With only getResponseFunc given, the reference says: If only one of the delegates is provided, it will be used for both methods. |
.Build() | Builds an IChatClient that represents the entire pipeline. |
<Middleware> | Your method. It runs once for every request to the model. |
messages | The messages this request sends. |
options | The request's ChatOptions, including Instructions, Tools and ConversationId. |
innerClient | The next chat client in the stack, the one that calls the model. |
innerClient.GetResponseAsync(...) | Sends the request on and returns the model's response. Use makes your method the chat client's implementation of GetResponseAsync, so without this call nothing reaches the model. |
Agent Framework's middleware guide describes this kind: IChatClient middleware: Allows interception of calls to an IChatClient implementation, where an agent is using IChatClient for inference calls, for example, when using ChatClientAgent.
The Example
A console app called RequestLog has an agent, WeatherHelper, with one function tool, get_weather, that returns the same made-up forecast for any city: rain all day, 14 °C. The middleware numbers each request to the model and prints its instructions, its tools and each of its messages, with the message's role and a short description of its parts. The app asks Do I need an umbrella in Paris today? and prints the answer.
The model is billed per token. gpt-5.6-luna on a Global Standard deployment costs $0.20 per million input tokens and $1.20 per million output tokens, and the final run below made 2 requests to the model with 183 input and 38 output tokens in all: $0.00008.
Prerequisites
- The .NET 10 SDK.
- A Microsoft Foundry project with a deployed chat model, and the Foundry User role on it.
- The Azure CLI, signed in with
az login.
Step 1: Create a Console App
dotnet new console -n RequestLog
cd RequestLog
dotnet add package Microsoft.Agents.AI.Foundry --version 1.28.0-preview.261106.1
dotnet add package Azure.Identity --version 1.21.0
dotnet new console -n RequestLogcreates a console app in a newRequestLogfolder, andcdmoves into it.Microsoft.Agents.AI.Foundryis Agent Framework's package for Microsoft Foundry. Version 1.28.0-preview.261106.1 is a preview release. It brings in Agent Framework itself,Microsoft.Agents.AI1.28.0, which is generally available.Azure.Identitylets the app sign in to Foundry with your Azure CLI account.
Step 2: Create the Agent with the Middleware
Replace everything in Program.cs with this:
using System.ComponentModel;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
// Counts the requests the agent sends to the model.
int requestNumber = 0;
AIAgent agent = new AIProjectClient(
new Uri("https://foundry-devblogs-exp.services.ai.azure.com/api/projects/proj-devblogs-exp"),
new AzureCliCredential())
.AsAIAgent(new ChatClientAgentOptions
{
Name = "WeatherHelper",
ChatOptions = new ChatOptions
{
ModelId = "gpt-5.6-luna",
Instructions = "You answer questions about the weather in one short sentence.",
Tools = [AIFunctionFactory.Create(GetWeather, name: "get_weather")],
},
},
clientFactory: chatClient => chatClient.AsBuilder()
.Use(getResponseFunc: ShowRequestAsync, getStreamingResponseFunc: null)
.Build());
int requestNumber = 0;counts the requests. It's declared above the statement that creates the agent on purpose: that statement turnsShowRequestAsyncinto a delegate, and the C# specification says that for a local function used that way, Captured variables are definitely assigned for the body if they are definitely assigned before the conversion. Declared below it, the counter makes the build fail: Fixed: "error CS0165: Use of unassigned local variable" When a C# Local Function Becomes a Delegate.new AIProjectClient(...)connects to the Foundry project at that endpoint, andAzureCliCredentialsigns in with the account you used foraz login. Use your own project endpoint and model deployment..AsAIAgent(...)creates the agent from the options: its name, the model deployment inModelId, its instructions, and its tools.Tools = [AIFunctionFactory.Create(GetWeather, name: "get_weather")]makes theGetWeathermethod a tool.name:gives it a readable name, because a tool made from a local function gets a compiler-made one otherwise: How to Give a Microsoft Agent Framework Function Tool a Clean Name in C#.clientFactory: chatClient => ...wraps the agent's chat client in a builder, addsShowRequestAsyncwith.Use(...), and builds the result.
Step 3: Ask the Question
Add the run below the agent:
AgentResponse response = await agent.RunAsync("Do I need an umbrella in Paris today?");
Console.WriteLine($"Answer: {response.Text}");
agent.RunAsync(...) sends the question and returns the agent's response, and response.Text is its answer. Every line the app prints before Answer: comes from the middleware.
Step 4: Write the Middleware
Add the middleware and a helper that describes each part of a message:
// IChatClient middleware: prints what each request to the model carries, then sends it on.
async Task<ChatResponse> ShowRequestAsync(
IEnumerable<ChatMessage> messages,
ChatOptions? options,
IChatClient innerClient,
CancellationToken cancellationToken)
{
requestNumber++;
Console.WriteLine($"[request {requestNumber}] instructions: {options?.Instructions}");
Console.WriteLine($"[request {requestNumber}] tools: {string.Join(", ", options?.Tools?.Select(tool => tool.Name) ?? [])}");
foreach (ChatMessage message in messages)
{
Console.WriteLine($"[request {requestNumber}] {message.Role} message: {string.Join(" ", message.Contents.Select(Describe))}");
}
return await innerClient.GetResponseAsync(messages, options, cancellationToken);
}
// A short description of one part of a message.
static string Describe(AIContent content) => content switch
{
TextContent text => $"\"{text.Text}\"",
FunctionCallContent call => $"call {call.Name}",
FunctionResultContent result => $"result \"{result.Result}\"",
_ => content.GetType().Name,
};
ShowRequestAsynchas the shapeUseexpects: the request's messages and options, the inner client, and a cancellation token. It's a local function, a function written among the program's own statements, so it can userequestNumber.options?.Instructionsandoptions?.Toolsare the instructions and the tools this request sends to the model.?.reads them only whenoptionsisn't null, and?? []stands in an empty list when there are no tools.message.Roleis who the message is from, such asuserortool, andmessage.Contentsare its parts.Describeturns each part into a few words with aswitchexpression: text in quotes, a tool call ascalland the tool's name, a tool result asresultand the result, and any other part by its type's name.innerClient.GetResponseAsync(...)sends the request on to the model, unchanged, and returns the model's response.
This middleware prints everything a request carries, including the user's own words and the tools' results. Use it on your own machine while you build and debug, and keep it out of production logs.
Step 5: Add the Tool
Add the tool at the end of the file:
[Description("Gets today's weather for a city.")]
static string GetWeather([Description("The city.")] string city) => $"Rain all day in {city}, 14 °C.";
GetWeather returns the same forecast for any city. The [Description] on the method becomes the tool's description; the reference of AIFunctionFactory.Create: If null, a description will be derived from any DescriptionAttribute on method, if available. The second [Description] describes its one parameter, city.
Step 6: Run It
dotnet run
[request 1] instructions: You answer questions about the weather in one short sentence.
[request 1] tools: get_weather
[request 1] user message: "Do I need an umbrella in Paris today?"
[request 2] instructions: You answer questions about the weather in one short sentence.
[request 2] tools: get_weather
[request 2] tool message: result "Rain all day in Paris, 14 °C."
Answer: Yes—bring an umbrella, as rain is expected all day in Paris today.

One RunAsync made two requests to the model, and the middleware saw both because of where it sits. An agent made with AsAIAgent is a ChatClientAgent, and it doesn't use the chat client from clientFactory as it is. The reference of ChatClientAgentOptions.UseProvidedChatClientAsIs: By default the ChatClientAgent applies decorators to the provided IChatClient for doing for example automatic function invocation. So the function-calling loop sits on top of your middleware, and every request the loop sends to the model passes through it:
Request 1 carried the instructions, the tool and the question. The model answered it with a call to get_weather, which isn't in the output because the middleware prints only requests. The loop, a FunctionInvokingChatClient, then ran the tool, producing a FunctionResultContent that it sends back to the inner client, as its reference puts it. The inner client is your middleware, and that's request 2.
And request 2 carried only the tool's result. It has no user message and no record of the model's call to get_weather, so on its own it says nothing about what the result answers. That isn't what the IChatClient guide describes for the messages of a request: This list represents the history of all messages that are part of the conversation. The rest of the conversation had to be somewhere else.
Step 7: Print the Conversation ID
The reference for ChatResponse.ConversationId explains where: Some IChatClient implementations are capable of storing the state for a conversation, so that a request needs to send only the messages beyond what's already stored. The ID of that stored state travels in the request's options, ChatOptions.ConversationId, documented as Gets or sets an optional identifier used to associate a request with an existing conversation.
To see it, add one line to ShowRequestAsync, after the tools line:
Console.WriteLine($"[request {requestNumber}] conversation: {options?.ConversationId ?? "(none)"}");
?? prints (none) when a request has no conversation ID. The middleware now reads:
// IChatClient middleware: prints what each request to the model carries, then sends it on.
async Task<ChatResponse> ShowRequestAsync(
IEnumerable<ChatMessage> messages,
ChatOptions? options,
IChatClient innerClient,
CancellationToken cancellationToken)
{
requestNumber++;
Console.WriteLine($"[request {requestNumber}] instructions: {options?.Instructions}");
Console.WriteLine($"[request {requestNumber}] tools: {string.Join(", ", options?.Tools?.Select(tool => tool.Name) ?? [])}");
Console.WriteLine($"[request {requestNumber}] conversation: {options?.ConversationId ?? "(none)"}");
foreach (ChatMessage message in messages)
{
Console.WriteLine($"[request {requestNumber}] {message.Role} message: {string.Join(" ", message.Contents.Select(Describe))}");
}
return await innerClient.GetResponseAsync(messages, options, cancellationToken);
}
Run it again:
dotnet run
[request 1] instructions: You answer questions about the weather in one short sentence.
[request 1] tools: get_weather
[request 1] conversation: (none)
[request 1] user message: "Do I need an umbrella in Paris today?"
[request 2] instructions: You answer questions about the weather in one short sentence.
[request 2] tools: get_weather
[request 2] conversation: resp_0e54b4…
[request 2] tool message: result "Rain all day in Paris, 14 °C."
Answer: Yes—rain is expected all day in Paris today, so bring an umbrella.
The conversation ID is shortened here. The real one is much longer, and yours will be different.

That's the missing history:
- Request 1 has no conversation ID. It starts the conversation, so it sends the question itself.
- Request 2 has the conversation ID
resp_0e54b4…, the ID of the response Foundry stored for request 1. The question and the model's call toget_weatherare kept under that ID, so request 2 sends only what's new: the tool's result.
Microsoft's guide to IChatClient calls the two kinds of service stateless and stateful: Stateless services require all relevant conversation history to be sent back on every request. In contrast, stateful services keep track of the history and require only additional messages to be sent with a request. The agent's Responses API behaved as a stateful service here.
For a caller that doesn't know which kind of service it's talking to, the same guide says to check the response's conversation ID: If it's set, then that value is propagated to the options and the history is cleared so as to not resend the same history again. Request 2 shows both halves: the ID in its options, and none of the earlier messages. The answer is worded differently from the first run's; the requests are the same apart from the new line.
Clean Up
The agent works on Foundry's Responses API, and Foundry stores the responses a run creates, so each run left two responses in the project. The conversation ID the second run printed is the ID of the first of its two. Microsoft's Responses API guide: By default, response data is retained for 30 days. How to Delete a Stored Response in Microsoft Foundry with the Azure CLI deletes one sooner by its ID, and How to Keep Microsoft Foundry from Storing an Agent's Conversations in C# shows an agent that stores nothing.
The Complete File
using System.ComponentModel;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
// Counts the requests the agent sends to the model.
int requestNumber = 0;
AIAgent agent = new AIProjectClient(
new Uri("https://foundry-devblogs-exp.services.ai.azure.com/api/projects/proj-devblogs-exp"),
new AzureCliCredential())
.AsAIAgent(new ChatClientAgentOptions
{
Name = "WeatherHelper",
ChatOptions = new ChatOptions
{
ModelId = "gpt-5.6-luna",
Instructions = "You answer questions about the weather in one short sentence.",
Tools = [AIFunctionFactory.Create(GetWeather, name: "get_weather")],
},
},
clientFactory: chatClient => chatClient.AsBuilder()
.Use(getResponseFunc: ShowRequestAsync, getStreamingResponseFunc: null)
.Build());
AgentResponse response = await agent.RunAsync("Do I need an umbrella in Paris today?");
Console.WriteLine($"Answer: {response.Text}");
// IChatClient middleware: prints what each request to the model carries, then sends it on.
async Task<ChatResponse> ShowRequestAsync(
IEnumerable<ChatMessage> messages,
ChatOptions? options,
IChatClient innerClient,
CancellationToken cancellationToken)
{
requestNumber++;
Console.WriteLine($"[request {requestNumber}] instructions: {options?.Instructions}");
Console.WriteLine($"[request {requestNumber}] tools: {string.Join(", ", options?.Tools?.Select(tool => tool.Name) ?? [])}");
Console.WriteLine($"[request {requestNumber}] conversation: {options?.ConversationId ?? "(none)"}");
foreach (ChatMessage message in messages)
{
Console.WriteLine($"[request {requestNumber}] {message.Role} message: {string.Join(" ", message.Contents.Select(Describe))}");
}
return await innerClient.GetResponseAsync(messages, options, cancellationToken);
}
// A short description of one part of a message.
static string Describe(AIContent content) => content switch
{
TextContent text => $"\"{text.Text}\"",
FunctionCallContent call => $"call {call.Name}",
FunctionResultContent result => $"result \"{result.Result}\"",
_ => content.GetType().Name,
};
[Description("Gets today's weather for a city.")]
static string GetWeather([Description("The city.")] string city) => $"Rain all day in {city}, 14 °C.";

Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Declaring requestNumber below the statement that creates the agent | The build fails with error CS0165 | Declare it above that statement |
Not calling innerClient.GetResponseAsync in the middleware | The request never reaches the model | Pass the request on and return the response |
| Expecting every request to carry the whole conversation | On Foundry's Responses API, later requests carry only the new messages and a conversation ID | Print options.ConversationId along with the messages |
| Leaving the middleware on in production | The users' messages and the tools' results end up in your logs | Use it while you debug, then take it out |
FAQ
Can the middleware show the model's answers too?
Yes. Keep the response from innerClient.GetResponseAsync(...) in a variable, read it, and then return it. Microsoft's own middleware sample does that: it prints the number of messages in the response before it returns it.
Does the middleware work when the agent streams?
With only getResponseFunc given, the same method also serves the chat client's streaming method, GetStreamingResponseAsync, and the reference warns that it then will employ limited streaming, as it will be operating on the batch output produced by getResponseFunc. To keep real streaming, give Use a getStreamingResponseFunc as well: If both are provided, they will be used for their respective methods.
Why doesn't the model's tool call show up?
Because it's in the model's response to request 1, not in a request. The middleware prints only what goes to the model, and with Foundry's Responses API the call isn't sent back: it stays in the stored response that the conversation ID points to.
Conclusion
IChatClient middleware added with clientFactory sees each request the agent sends, because the agent's function-calling loop sits on top of it. Here it showed that one run was two requests, that the second carried only the tool's result, and, with the conversation line added, why: request 2 pointed at the response Foundry stored for request 1, and the rest of the history stayed there.
Additional Resources
- Agent Middleware — the three kinds of middleware in Agent Framework, including
IChatClientmiddleware added through a client factory. - Use the IChatClient interface — custom middleware with
Use, and stateless and stateful clients. - ChatClientBuilder.Use Method — the overload with
getResponseFuncandgetStreamingResponseFunc. - ChatResponse.ConversationId Property — the ID of a conversation's stored state.
