This is the ninth 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
- 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 (This Post)
- Observability, Cost Control and MCP Security
The source code for this tutorial is available on GitHub.
Connecting an MCP Server to Microsoft Foundry Agent Service
We have three clients now. Our own .NET agent from Part 6, VS Code Copilot, and Claude. They look different, but they have one thing in common: the agent loop runs on somebody’s machine. Your code, or your editor, holds the conversation, asks the model what to do, calls the tool, and feeds the answer back.
This one is different. The loop runs in Azure.
Here is the part worth saying before anything else, because it shapes the whole post. The MCP server does not change. No new package, no new endpoint, no new code. Everything below is configuration, plus a small console application. What we deployed in Part 8 is already everything Foundry needs.
There is one problem to solve. approve_expense_report reads the caller’s identity from the token. A hosted agent has no person sitting in front of it. So who is asking?
What Foundry Agent Service needs from us
Less than you might expect. Foundry Agent Service only accepts a remote MCP endpoint reachable over the public internet. Part 8 produced exactly that.
What we add in this post is the plumbing around it:
- A project inside the Foundry account we created in Part 6.
- A connection that holds how to authenticate to our server.
- A toolbox that holds the connection and publishes its own MCP endpoint.
- A Foundry agent that uses the toolbox.
Put together, a single question travels through four hops, and each one authenticates differently.
Look at where your identity sits. It is only on the last hop, between the toolbox and our server. The two hops above it authenticate as services, with no person behind them. The next section explains why that matters.
Setting up the project
Step 1: Set your variables
Two names from Part 6, and three new ones.
|
1 2 3 4 5 6 7 8 9 10 |
$SUFFIX = "tj01" $LOCATION = "westeurope" $RESOURCE_GROUP = "rg-bitoftech-expenses" $FOUNDRY_NAME = "aif-bitoftech-expenses-$SUFFIX" $MODEL_DEPLOYMENT = "expenses-chat" $FOUNDRY_PROJECT = "proj-bitoftech-expenses" $FOUNDRY_APP_NAME = "BitOfTech Expenses Foundry" $TOOLBOX = "expenses-toolbox" |
Step 2: Create the project
Part 6 created a Foundry account and deployed a model into it. An account is not enough here. Agents, connections and toolboxes all live inside a project, which is a container for one piece of work.
|
1 2 3 4 5 6 7 8 9 10 |
az cognitiveservices account project create ` --name $FOUNDRY_NAME ` --project-name $FOUNDRY_PROJECT ` --resource-group $RESOURCE_GROUP ` --location $LOCATION ` --display-name "BitOfTech Expenses" az cognitiveservices account project show ` --name $FOUNDRY_NAME --project-name $FOUNDRY_PROJECT ` --resource-group $RESOURCE_GROUP --query id -o tsv |
Your project endpoint is the account’s services hostname with the project name on the end:
|
1 |
https://aif-bitoftech-expenses-tj01.services.ai.azure.com/api/projects/proj-bitoftech-expenses |
Write that down. The .NET application in Step 10 needs it, and it is the only endpoint that application ever sees.
Step 3: Give yourself access to the project
This one catches people out, so we do it now rather than when it blocks us. Owning the subscription does not give you access to a Foundry project. Project permissions are their own thing.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
$MY_OID = az ad signed-in-user show --query id -o tsv $PROJECT_ID = az cognitiveservices account project show ` --name $FOUNDRY_NAME --project-name $FOUNDRY_PROJECT ` --resource-group $RESOURCE_GROUP --query id -o tsv az role assignment create ` --assignee-object-id $MY_OID ` --assignee-principal-type User ` --role "Foundry User" ` --scope $PROJECT_ID az role assignment create ` --assignee-object-id $MY_OID ` --assignee-principal-type User ` --role "Foundry Project Manager" ` --scope $PROJECT_ID |
Let’s review the parameters:
Foundry Userlets you build and test agents.Foundry Project Managerlets you create connections, which we do in Step 6.--scope $PROJECT_IDis the project, not the account and not the resource group. That is the level these roles are meant to sit at.
Note: these roles were renamed recently. Foundry User used to be Azure AI User, and Foundry Project Manager used to be Azure AI Project Manager. If you find older material using the old names, it means the same thing.
Role assignments take a moment to apply. If the portal still says you have no access, refresh the page before assuming something went wrong.
The identity problem
Every tool we wrote in Parts 2 through 6 works for anyone holding a valid token. Part 7 changed that. approve_expense_report has no approverName parameter, on purpose. It reads the oid claim out of the token, looks up the matching employee, and refuses if you try to approve your own report.
That design assumes there is a person behind the request.
A hosted agent runs in Azure. It can authenticate as itself, and Foundry offers exactly that: an agent identity, or the project’s managed identity. Either would get a token. Neither would carry a roles claim for you, and neither would have an oid that matches an employee row. Our server would answer honestly that the signed in user is not linked to an employee record, and refuse.
The fix is a mechanism called OAuth identity passthrough. You sign in once, Foundry stores your credential against the connection, and from then on it uses your identity when it calls our server. Microsoft’s guidance is specific here: for a server with an audience you control, rather than a Microsoft one, you bring your own Entra app registration. That is what Steps 4 to 7 do.
Step 4: Register the application Foundry signs in with
We already have two app registrations from Part 7. This is a third, and here is why.
- Foundry is a service. It runs on Azure, it can keep a secret, and it needs one.
BitOfTech Expenses Clientsis registered as a public client and cannot hold a secret at all. - Foundry returns a web redirect URI. Our clients registration holds public client redirect URIs, which is a different category of application.
- Keeping them apart means you can revoke Foundry’s access without touching our Part 6 agent, VS Code or Claude.
|
1 2 3 4 5 6 7 8 9 10 11 |
$FOUNDRY_APP_ID = az ad app create ` --display-name $FOUNDRY_APP_NAME ` --query appId -o tsv az ad sp create --id $FOUNDRY_APP_ID az ad app credential reset ` --id $FOUNDRY_APP_ID ` --display-name "foundry-oauth" Write-Output "Foundry app: $FOUNDRY_APP_ID" |
credential reset prints a password. Keep it somewhere you can reach it in Step 6, because Entra will not show it to you again.
Important note: some tenants restrict client secrets, either blocking them or capping how long they last. If that command fails or gives you a secret that expires in days rather than a year, that is your tenant’s application management policy, not a mistake on your part. Your administrator sets it.
Step 5: Let it ask for our scope
Same two halves as Part 7, and both have to agree. BitOfTech Expenses Foundry asks for the Expenses.Access permission. Then BitOfTech Expenses MCP, which owns that permission, records that it trusts the Foundry registration to ask for it.
|
1 2 3 4 5 6 7 8 9 10 |
$MCP_APP_ID = az ad app list --display-name "BitOfTech Expenses MCP" --query "[0].appId" -o tsv $MCP_OBJ_ID = az ad app show --id $MCP_APP_ID --query id -o tsv $CLIENT_APP_ID = az ad app list --display-name "BitOfTech Expenses Clients" --query "[0].appId" -o tsv $SCOPE_ID = az ad app show --id $MCP_APP_ID ` --query "api.oauth2PermissionScopes[?value=='Expenses.Access'].id | [0]" -o tsv az ad app permission add ` --id $FOUNDRY_APP_ID ` --api $MCP_APP_ID ` --api-permissions "$SCOPE_ID=Scope" |
Now the other half. Read this block before you run it, because there is a trap in it.
|
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 |
@{ api = @{ requestedAccessTokenVersion = 2 oauth2PermissionScopes = @( @{ id = $SCOPE_ID value = "Expenses.Access" type = "User" isEnabled = $true adminConsentDisplayName = "Access expense reports" adminConsentDescription = "Allows the app to read and manage expense reports on behalf of the signed-in user." userConsentDisplayName = "Access your expense reports" userConsentDescription = "Allows the app to read and manage your expense reports." } ) preAuthorizedApplications = @( @{ appId = $CLIENT_APP_ID; delegatedPermissionIds = @($SCOPE_ID) }, @{ appId = $FOUNDRY_APP_ID; delegatedPermissionIds = @($SCOPE_ID) } ) } } | ConvertTo-Json -Depth 6 -Compress | Set-Content -Path entra-setup/api-foundry.json -Encoding ascii az rest --method PATCH ` --url "https://graph.microsoft.com/v1.0/applications/$MCP_OBJ_ID" ` --headers "Content-Type=application/json" --body "@entra-setup/api-foundry.json" az ad app show --id $MCP_APP_ID --query "api.preAuthorizedApplications[].appId" -o json az ad app show --id $MCP_APP_ID --query "api.oauth2PermissionScopes[].value" -o json |
What we have done here is the following:
- Sent the whole
apiobject, not just the new entry. A GraphPATCHreplaces a property rather than merging into it. If you send only the Foundry pre-authorization, you delete theExpenses.Accessscope, and that breaks Part 7 along with our agent, VS Code and Claude. - Listed both registrations.
BitOfTech Expenses Clientsfrom Part 7, and the newBitOfTech Expenses Foundry. - Checked afterwards. Those last two lines should print two app IDs and
Expenses.Access. If the scope list comes back empty, the PATCH replaced it and you need to put it back before going further.
Pre-authorizing matters for the same reason it did in Part 7. It means nobody sees a consent screen asking them to grant access to our own API.
Step 6: Create the connection
A connection is where Foundry stores how to reach our server and how to authenticate to it. This one is easier to create in the portal than from the command line, because Foundry generates a redirect URL as part of saving it, and you need that URL in the next step.
Open ai.azure.com, select the proj-bitoftech-expenses project, go to Tools, then add a Custom MCP tool. Choose OAuth Identity Passthrough and fill in:
| Field | Value |
|---|---|
| MCP server endpoint | https://ca-bitoftech-expenses-mcp.YOUR-DOMAIN.azurecontainerapps.io/mcp |
| Client ID | the $FOUNDRY_APP_ID from Step 4 |
| Client secret | the secret from Step 4 |
| Auth URL | https://login.microsoftonline.com/YOUR-TENANT-ID/oauth2/v2.0/authorize |
| Token URL | https://login.microsoftonline.com/YOUR-TENANT-ID/oauth2/v2.0/token |
| Refresh URL | same as Token URL |
| Scopes | https://ca-bitoftech-expenses-mcp.YOUR-DOMAIN.azurecontainerapps.io/mcp/Expenses.Access offline_access |
Let’s review the fields:
- The endpoint ends in
/mcp, the same value we registered as an Application ID URI in Part 8. - The scope is fully qualified and carries the Application ID URI in front of it. A bare
Expenses.Accessgets resolved against Microsoft Graph, which has never heard of it. offline_accessis separated by a single space, not a comma. It is what lets Foundry refresh your token instead of asking you to sign in again every hour.- Refresh URL is the same as Token URL. Entra uses one endpoint for both.
Name it mcp-expenses and save. Foundry gives you back a redirect URL that looks like this:
|
1 |
https://global.consent.azure-apim.net/redirect/485ada2885714672ad61a30e33efd6d3 |
Note: that hostname tells you something useful. Foundry implements OAuth identity passthrough on API Management’s Credential Manager. Your URL will have a different identifier on the end.
Step 7: Register the redirect URL
Entra will only return a signed-in user to an address the application has declared. Foundry just gave us that address, so we add it now.
|
1 2 3 4 5 |
az ad app update --id $FOUNDRY_APP_ID ` --web-redirect-uris "https://global.consent.azure-apim.net/redirect/YOUR-VALUE-HERE" az ad app show --id $FOUNDRY_APP_ID ` --query "{web:web.redirectUris, public:publicClient.redirectUris}" -o json |
You should see the URL under web and nothing under public. That split is the whole reason we made a separate registration in Step 4. Part 7’s clients registration holds public client redirect URIs, and this one holds a web redirect URI, because Foundry is a service rather than something running on your machine.
Why a Foundry toolbox, and when you should skip one
One word first, because it is about to do two jobs. When I say agent in this section, I mean an agent configured inside Foundry, like the one we build in Step 9. I do not mean VS Code, Claude, or our Part 6 console application. Those three connect straight to our server, and nothing in this section changes for them.
Now, the problem a Foundry toolbox solves.
Suppose your company builds a second Foundry agent next month, and a third after that. Each one needs its own MCP tool configuration. Which server, which connection, which tools are allowed, which of them need approval. That is fine for two agents. It is tedious for ten. If the credential behind that server expires, you go and fix it in ten places.
There is a second problem that only shows up later. Every tool description is sent to the model on every request. Seven tools is nothing. Two hundred tools spread across five servers is thousands of tokens on every turn, and a model picking one name out of a much longer list.
A Foundry toolbox is Microsoft’s answer to both. It is a named collection of tools that lives in your project and publishes its own MCP endpoint. Agents point at that one endpoint. What sits behind it, and how it authenticates, is configured once in the toolbox instead of once per agent.
Now what it is not, because this is a common misreading. A Foundry toolbox does not replace your server. Our Container App is still the thing that reads the database and sends the email. The toolbox holds a reference to it. Part 8 is not optional.
Here is what a Foundry toolbox gives you, and how sure I am about each one:
- One endpoint instead of many. If you add a tool to the toolbox, every agent using it gets that tool, with no change to the agent. True by construction.
- Credentials in one place. The toolbox holds the connection and deals with token refresh. We rely on this in a moment, because the OAuth connection from Step 6 goes into the toolbox rather than onto the agent.
- Versioning. You build a new version, test it, then promote it to default, and agents pick it up with no redeployment. The endpoint in Step 8 has no version number in it for exactly this reason.
- Guardrails. You can attach a content filter that inspects tool calls and tool responses. We leave this at None.
- Tool search. Hides the tools and gives the model two meta tools instead, one to search and one to call. This is the answer to the token problem above, and it is the one claim I can put a number against.
What it costs us
I measured it rather than guessing. Same three questions, same order, approvals switched off on both sides, container already warm.
| Configuration | Total input tokens | Versus direct |
|---|---|---|
| Direct to our MCP server | 3,860 | baseline |
| Direct, repeat run | 3,885 | +0.6%, run to run noise |
| Through the toolbox | 4,005 | +3.8% |
| Through the toolbox, tool search on | 4,040 | +4.0% |
The Foundry toolbox hop costs about four percent more input tokens. Two runs of the direct setup differed by 0.6%, so four percent is real rather than noise. The answers were equivalent and output tokens were the same to within a few dozen.
Then I turned on tool search, which is the toolbox feature that exists specifically to cut token cost. It hides your tools behind two meta-tools and lets the model search for what it needs. At seven tools it changed nothing I could measure.
Now put that next to Microsoft’s own figure for the same feature:
313,000 input tokens per call falling to 18,000, a 94% cut, with tool selection accuracy rising from 48.2% to 52.4%. Both numbers are true. The footnote is what reconciles them: those results are based on an average of 600 or more tools. We have seven.
So when should you use one
| Your situation | What to do |
|---|---|
| One or two MCP servers, a handful of tools | Point the agent at the server. You are done |
| One team owns both the server and the agent | Same |
| Many agents consuming the same tools | Toolbox. Configure once |
| Tools and agents owned by different teams | Toolbox. The owner boundary is the point |
| Tool count outgrowing your context budget | Toolbox, for tool search |
| You need the same guardrails whoever calls | Toolbox |
| You need to swap a tool without redeploying agents | Toolbox, with versioning |
The short version is that a toolbox answers an organizational problem rather than a protocol one. If you can name the person who owns each tool, and it is the same person who owns the Foundry agent, you do not need one yet.
We are using one here anyway, for one reason. You cannot judge a thing you have only read about, and the numbers above exist only because I built one and measured it.
Step 8: Create the toolbox
In the portal, go to Tools, then the Toolboxes tab, and select Create toolbox.
- Name it
expenses-toolbox. - Under Included, add the
mcp-expensesconnection. - Remove
FoundryMCPServerpreview, which gets added by default and is not ours. - Leave Tool search off and Guardrail at None.
Save it, then open it again. The Call this toolbox panel shows an endpoint with a version number in it:
|
1 |
https://aif-bitoftech-expenses-tj01.services.ai.azure.com/api/projects/proj-bitoftech-expenses/toolboxes/expenses-toolbox/versions/1/mcp?api-version=v1 |
Take out the /versions/1 part and use this instead:
|
1 |
https://aif-bitoftech-expenses-tj01.services.ai.azure.com/api/projects/proj-bitoftech-expenses/toolboxes/expenses-toolbox/mcp?api-version=v1 |
Note: the version number pins the agent to one version, which is what you want while testing a change. The shorter form is the consumer endpoint and always serves whichever version is promoted to default. We use the consumer endpoint, which is why editing the toolbox later does not break the agent.
Step 9: Create the Foundry agent
Still in the portal, go to Agents and create one called expenses-agent.
- Model:
expenses-chat, the deployment from Part 6. - Instructions:
You help with expense reports. Use the available tools. Never invent report ids. - Tools: remove
Web search, which is added by default. It costs money through Grounding with Bing and it gives the model a tool we do not want it reaching for. - Then add a Custom MCP tool pointing at the toolbox endpoint above, named
expenses-toolbox-mcp, with Microsoft Entra authentication, type Agent Identity, and audiencehttps://ai.azure.com.
Save the agent.
Notice what that last one means. To attach a toolbox to an agent, you register it as an ordinary remote MCP server. A toolbox is not a special kind of agent feature. It is another MCP endpoint, so MCP ends up carrying MCP.
Does the identity actually survive?
Open the agent’s playground and ask it something.
|
1 |
What expense reports is Sara waiting on? |
The first time, you get a sign-in prompt instead of an answer. Foundry has your connection but not your credential yet. Select Open consent, sign in, and approve.
That screen comes from API Management’s Credential Manager and it names Microsoft Foundry Agent Service as the thing that created the connection. You will not see a second screen asking you to grant Expenses.Access, because Step 5 pre-authorized the application.
Consent is stored per user, per connection, per project. You do this once. If you ever delete and recreate the connection, the stored consent goes with it, and the next call fails with a protocol version error rather than an authentication error.
Now ask again, and you get Sara’s reports. Reads work. Here is the test that matters:
|
1 |
Approve report 1001 |
It approves. Then try one of your own:
|
1 2 3 |
> Approve report 1012 An error occurred invoking 'mcp-expenses___approve_expense_report': Report 1012 belongs to Taiseer Joudeh, who is the signed in user. Nobody can approve their own expense report. |
That message is ours. We wrote it in Part 7 and the server has not changed since. Seeing it here means three things worked:
- The tool was offered at all. Our server drops
approve_expense_reportfromtools/listfor anyone without theExpenses.Approverrole, so therolesclaim survived. - Our server found an employee. It matched the
oidin the token to a row in the database, so it knew the caller was you. - It recognised the owner. Check the row in SQL and
ApprovedByEmployeeIdon the report you did approve is your employee id, not a service principal.
Look at the diagram again. Your identity is only on the last hop. The agent authenticates to the toolbox as itself, and the toolbox authenticates to our server as you. Foundry picks the right stored credential from the conversation, not from the token it was handed. That is the part to verify rather than assume when you build your own chain, which is why the test above is the one that matters.
Note: the tool name in that error is mcp-expenses___approve_expense_report, with three underscores. A toolbox prefixes tool names with the connection they came from, so two servers can expose a tool with the same name without colliding. If you have an approval allow list written against the original names, it stops matching when you move to a toolbox.
Driving it from .NET
The portal is fine for trying things. It is not where this ends up.
Picture the expenses system this series is pretending to build. It has a web application where people fill in forms. Somebody asks for a chat box in the corner, so an employee can type “what am I waiting on” instead of hunting through a list of reports.
There are two ways to build that. Part 6 is one of them: your application holds the conversation, calls the model, reads the tool list, calls the tools, and feeds the results back. You own all of it. The other is what we do here. The agent already exists in Azure, and your application sends it a sentence.
The second approach is worth knowing for a few reasons:
- More than one front end. A web application, a Teams bot, and a nightly job that emails managers about pending approvals. Each one is a handful of lines against the same agent, and the behaviour is defined once.
- Behaviour changes without a deployment. Add a tool, reword the instructions, switch the model, tighten the approval policy. Every front end picks it up on the next request. No rebuild and no release.
- Different people own different parts. Whoever owns the Foundry project owns how the agent behaves. Whoever owns the application owns the screens. They ship on their own schedules.
- Conversation state is not your problem. Foundry keeps the thread. You keep one id.
What we write below is a console loop, because that is the smallest thing that shows all of it working. If you swap Console.ReadLine for an HTTP request, you have the chat box.
Step 10: Add the project
|
1 2 |
dotnet new console -o src/BitOfTech.Expenses.FoundryAgent dotnet sln add src/BitOfTech.Expenses.FoundryAgent |
src/BitOfTech.Expenses.FoundryAgent/BitOfTech.Expenses.FoundryAgent.csproj
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net10.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> <RootNamespace>BitOfTech.Expenses.FoundryAgent</RootNamespace> <!-- The Responses API types ship marked as evaluation only, which the compiler raises as an error. --> <NoWarn>$(NoWarn);OPENAI001</NoWarn> </PropertyGroup> <ItemGroup> <PackageReference Include="Azure.AI.Extensions.OpenAI" Version="2.0.0" /> <PackageReference Include="Azure.AI.Projects" Version="2.0.1" /> <PackageReference Include="Azure.Identity" Version="1.21.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="10.0.12" /> </ItemGroup> <ItemGroup> <Content Include="appsettings.json" CopyToOutputDirectory="PreserveNewest" /> </ItemGroup> </Project> |
Two things in there:
- There is no
ModelContextProtocolpackage. This application does not speak MCP at all. NoWarnforOPENAI001. The Responses API types ship marked as evaluation only, and the compiler treats that as an error rather than a warning, so the project will not build without it. Microsoft’s samples put#pragma warning disable OPENAI001in the source instead. I would rather declare it once in the project file than scatter it through code.
src/BitOfTech.Expenses.FoundryAgent/appsettings.json
|
1 2 3 4 5 6 |
{ "Foundry": { "ProjectEndpoint": "https://aif-bitoftech-expenses-tj01.services.ai.azure.com/api/projects/proj-bitoftech-expenses", "Agent": "expenses-agent" } } |
Two settings. No MCP endpoint, no scope, no client ID, no redirect URI. Compare that with the Part 6 agent’s settings and you can see what moved into Azure.
Note: there is nothing about signing in that file, but the application still authenticates. DefaultAzureCredential in the next file uses the account from your az login, and every call carries that token. The endpoint and the agent name are not secrets. Knowing them gives nobody access on its own.
Two things decide whether a caller gets in. The first is the Foundry User role on the project, which is what we assigned ourselves in Step 3. The second is the consent you gave on the sign-in screen above, which is stored against your own account. Somebody else running this application would need both, and their own identity would reach our server, where Part 7’s role check still applies to them.
src/BitOfTech.Expenses.FoundryAgent/Program.cs
|
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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
using System.ClientModel; using Azure.AI.Extensions.OpenAI; using Azure.AI.Projects; using Azure.Identity; using Microsoft.Extensions.Configuration; using OpenAI.Responses; // 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 projectEndpoint = configuration["Foundry:ProjectEndpoint"]!; var agentName = configuration["Foundry:Agent"]!; // There is no MCP client here. The agent in Azure owns the tool loop, so this application // only ever sends a sentence and reads the reply. AIProjectClient projectClient = new( endpoint: new Uri(projectEndpoint), tokenProvider: new DefaultAzureCredential()); ProjectResponsesClient responsesClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentName); Console.WriteLine($"Connected to {agentName} at {projectEndpoint}"); Console.WriteLine("The tool loop runs in Azure. Type a question, or an empty line to quit."); Console.WriteLine(); string? previousResponseId = null; while (true) { Console.Write("> "); var input = Console.ReadLine(); if (string.IsNullOrWhiteSpace(input)) { break; } CreateResponseOptions options = new(); options.InputItems.Add(ResponseItem.CreateUserMessageItem(input)); if (previousResponseId is not null) { options.PreviousResponseId = previousResponseId; } try { ResponseResult response = await responsesClient.CreateResponseAsync(options); previousResponseId = response.Id; // The agent pauses instead of finishing when it needs something from us. Each pause // arrives as an output item, and we answer it by continuing from this response. while (true) { var follow = HandlePauses(response); if (follow is null) { break; } follow.PreviousResponseId = response.Id; response = await responsesClient.CreateResponseAsync(follow); previousResponseId = response.Id; } Console.WriteLine(response.GetOutputText()); } catch (ClientResultException failure) { // A tool that refuses fails the whole request here, rather than returning text the // model can explain. Our own agent in Part 6 sees the same refusal as content. Console.WriteLine(Readable(failure)); } Console.WriteLine(); } // Returns options to continue the conversation, or null when the agent is not waiting on us. static CreateResponseOptions? HandlePauses(ResponseResult response) { CreateResponseOptions? follow = null; foreach (ResponseItem item in response.OutputItems) { if (item is McpToolCallApprovalRequestItem approval) { Console.WriteLine($" {approval.ServerLabel} wants to call {approval.ToolName}"); Console.Write(" allow it? (y/N) "); var answer = Console.ReadLine(); var approved = string.Equals(answer, "y", StringComparison.OrdinalIgnoreCase); follow ??= new CreateResponseOptions(); follow.InputItems.Add( ResponseItem.CreateMcpApprovalResponseItem(approval.Id, approved)); } // Consent is a Foundry concept rather than an OpenAI one, so it arrives wrapped. else if (item.AsAgentResponseItem() is OAuthConsentRequestResponseItem consent) { Console.WriteLine($" sign in to continue: {consent.ConsentLink}"); Console.Write(" press Enter once you have finished signing in "); Console.ReadLine(); follow ??= new CreateResponseOptions(); } } return follow; } // Pulls the tool's own message out of the HTTP failure and drops the wrapping. static string Readable(ClientResultException failure) { var text = failure.Message; var guide = text.IndexOf("Troubleshooting guide:", StringComparison.Ordinal); if (guide > 0) { text = text[..guide]; } // An HTTP status line, then a blank line, then what the tool actually said. var parts = text.Split(["\r\n\r\n", "\n\n"], 2, StringSplitOptions.None); return parts[^1].Trim(); } |
What we have done here is the following:
- Named an agent and nothing else.
GetProjectResponsesClientForAgenttakes a name. Which tools that agent has, and whether they come from a toolbox or a direct connection, is decided in Azure and this code never learns it. - Used
DefaultAzureCredential. It picks up youraz login. That is the identity Foundry maps to your stored consent, which is how youroidends up reaching our server three hops later. - Answered the agent’s pauses in a loop. An approval request and a consent request both arrive as output items rather than as errors. We answer them and continue from the same response. A turn that calls two tools pauses twice, one after the other, which is why this is a loop and not a single check.
- Caught
ClientResultException. More on that below. - Only advanced
previousResponseIdafter a successful call, so a failed turn leaves the conversation pointing at the last good response.
Important note: a tool refusal does not come back as content here. It fails the whole request with an HTTP 400 and throws. An application that does not catch it exits with a stack trace. That is a real difference between clients, and nothing on our server changed to cause it. Our Part 6 agent receives the same refusal as text, and the model reads it and explains. Foundry treats an MCP tool error as what it is at the protocol level, a failed call.
Run it:
|
1 |
dotnet run --project src/BitOfTech.Expenses.FoundryAgent |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
Connected to expenses-agent at https://aif-bitoftech-expenses-tj01.services.ai.azure.com/api/projects/proj-bitoftech-expenses The tool loop runs in Azure. Type a question, or an empty line to quit. > Create a report for Lina with title "Rome Trip" on 25 Sept 2026 with only Airline ticket of 700 Euro expenses-toolbox-mcp wants to call mcp-expenses___create_expense_report allow it? (y/N) y Created draft expense report 1022 for Lina Farah. It's currently a draft, not submitted yet. Would you like me to submit it? > yes expenses-toolbox-mcp wants to call mcp-expenses___submit_expense_report allow it? (y/N) y Submitted report 1022 for approval. > approve and notify Lina expenses-toolbox-mcp wants to call mcp-expenses___approve_expense_report allow it? (y/N) y expenses-toolbox-mcp wants to call mcp-expenses___notify_employee allow it? (y/N) y Approved report 1022 and notified Lina Farah by email. |
Look at that last exchange. One sentence, two tools, in order. That is the sentence we appended to the approve_expense_report description back in Part 8, steering a model we did not choose, inside a client we did not write, running in Azure. The description travelled all the way through the toolbox and did its job.
Decline an approval and it handles that too. The tool is never called, so the model reports it could not complete the request and offers to try again.
What is missing from that file
This is the reason the project exists at all.
In Part 6 the agent loop ran in your process. ToolLoop.cs held the conversation, asked the model what to do, read the tool list from our server, called the tool, and fed the result back. You owned every step of that.
Here there is no tool loop. There is no IChatClient. There are no tool definitions and no MCP client. Our application sends a sentence and reads a reply.
That is the trade, and it goes both ways. You stop maintaining the loop, and you stop controlling it. Which tools exist, whether they need approval, what the model is, and how a refusal is surfaced are all decided in Azure now. For some applications that is exactly right. For others it is not, and the Part 6 agent is still the better answer.
The other three clients
Nothing happened to them.
Our .NET agent from Part 6 still signs in with its own registration and talks straight to the Container App. VS Code Copilot still reads our metadata document and finds Entra. Claude still connects from Anthropic’s cloud. None of them knows a Foundry project exists, and none of them needed a line changed.
Four clients now, four different ways of connecting, one server that treats them all the same. That is the whole argument for the protocol, and this is the first post where you can see it properly.
Summary
The thing I keep coming back to is that the server did not change. Not a package, not an endpoint, not a line of C#. Everything in this post was configuration around a service that was already finished in Part 8.
The identity chain is the part to look at closely if you are adapting this. Your token reaches our server on the last hop only, after a chain where the agent authenticates as itself and the toolbox authenticates on your behalf. Foundry picks the right stored credential from the conversation rather than from the token it was handed. Part 7’s authorization survives all of it, including the refusal when you try to approve your own report.
On the toolbox, I would rather give you the measurement than the recommendation. Four percent more tokens and no measurable benefit at seven tools, against a documented 94% saving at six hundred. Both are true, and which one applies to you depends on how many tools you have and how many teams are arguing about them.
Part 10 is the last one. Observability, cost control and MCP security, where we look at what all of this actually costs to run, and at what happens when text you did not write reaches the model.
The source code for this tutorial is available on GitHub.
Follow me on X @TJoudeh and on LinkedIn
References:
- Connect agents to MCP server endpoints
- Set up MCP server authentication
- What is Toolbox in Microsoft Foundry?
- Microsoft Foundry Agent Service overview
- Register an application with Microsoft Entra ID
- AIProjectClient API reference





Leave a Reply