Bit of Technology

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

Part 9: Connecting an MCP Server to Microsoft Foundry Agent Service

October 20, 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 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:

  1. A project inside the Foundry account we created in Part 6.
  2. A connection that holds how to authenticate to our server.
  3. A toolbox that holds the connection and publishes its own MCP endpoint.
  4. 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.

PowerShell
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.

PowerShell
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:

C#
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.

PowerShell
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:

  1. Foundry User lets you build and test agents.
  2. Foundry Project Manager lets you create connections, which we do in Step 6.
  3. --scope $PROJECT_ID is 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.

  1. Foundry is a service. It runs on Azure, it can keep a secret, and it needs one. BitOfTech Expenses Clients is registered as a public client and cannot hold a secret at all.
  2. Foundry returns a web redirect URI. Our clients registration holds public client redirect URIs, which is a different category of application.
  3. Keeping them apart means you can revoke Foundry’s access without touching our Part 6 agent, VS Code or Claude.

PowerShell
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.

PowerShell
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.

PowerShell
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:

  1. Sent the whole api object, not just the new entry. A Graph PATCH replaces a property rather than merging into it. If you send only the Foundry pre-authorization, you delete the Expenses.Access scope, and that breaks Part 7 along with our agent, VS Code and Claude.
  2. Listed both registrations. BitOfTech Expenses Clients from Part 7, and the new BitOfTech Expenses Foundry.
  3. 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:

FieldValue
MCP server endpointhttps://ca-bitoftech-expenses-mcp.YOUR-DOMAIN.azurecontainerapps.io/mcp
Client IDthe $FOUNDRY_APP_ID from Step 4
Client secretthe secret from Step 4
Auth URLhttps://login.microsoftonline.com/YOUR-TENANT-ID/oauth2/v2.0/authorize
Token URLhttps://login.microsoftonline.com/YOUR-TENANT-ID/oauth2/v2.0/token
Refresh URLsame as Token URL
Scopeshttps://ca-bitoftech-expenses-mcp.YOUR-DOMAIN.azurecontainerapps.io/mcp/Expenses.Access offline_access

Let’s review the fields:

  1. The endpoint ends in /mcp, the same value we registered as an Application ID URI in Part 8.
  2. The scope is fully qualified and carries the Application ID URI in front of it. A bare Expenses.Access gets resolved against Microsoft Graph, which has never heard of it.
  3. offline_access is 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.
  4. 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:

C#
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.

PowerShell
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:

  1. 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.
  2. 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.
  3. 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.
  4. Guardrails. You can attach a content filter that inspects tool calls and tool responses. We leave this at None.
  5. 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.

ConfigurationTotal input tokensVersus direct
Direct to our MCP server3,860baseline
Direct, repeat run3,885+0.6%, run to run noise
Through the toolbox4,005+3.8%
Through the toolbox, tool search on4,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 situationWhat to do
One or two MCP servers, a handful of toolsPoint the agent at the server. You are done
One team owns both the server and the agentSame
Many agents consuming the same toolsToolbox. Configure once
Tools and agents owned by different teamsToolbox. The owner boundary is the point
Tool count outgrowing your context budgetToolbox, for tool search
You need the same guardrails whoever callsToolbox
You need to swap a tool without redeploying agentsToolbox, 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.

  1. Name it expenses-toolbox.
  2. Under Included, add the mcp-expenses connection.
  3. Remove FoundryMCPServerpreview, which gets added by default and is not ours.
  4. 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:

C#
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:

C#
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.

  1. Model: expenses-chat, the deployment from Part 6.
  2. Instructions: You help with expense reports. Use the available tools. Never invent report ids.
  3. 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.
  4. Then add a Custom MCP tool pointing at the toolbox endpoint above, named expenses-toolbox-mcp, with Microsoft Entra authentication, type Agent Identity, and audience https://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.

C#
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:

C#
1
Approve report 1001

It approves. Then try one of your own:

PowerShell
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:

  1. The tool was offered at all. Our server drops approve_expense_report from tools/list for anyone without the Expenses.Approver role, so the roles claim survived.
  2. Our server found an employee. It matched the oid in the token to a row in the database, so it knew the caller was you.
  3. It recognised the owner. Check the row in SQL and ApprovedByEmployeeId on 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:

  1. 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.
  2. 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.
  3. 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.
  4. 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

C#
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

XHTML
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:

  1. There is no ModelContextProtocol package. This application does not speak MCP at all.
  2. NoWarn for OPENAI001. 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 OPENAI001 in the source instead. I would rather declare it once in the project file than scatter it through code.

src/BitOfTech.Expenses.FoundryAgent/appsettings.json

C#
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

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
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:

  1. Named an agent and nothing else. GetProjectResponsesClientForAgent takes 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.
  2. Used DefaultAzureCredential. It picks up your az login. That is the identity Foundry maps to your stored consent, which is how your oid ends up reaching our server three hops later.
  3. 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.
  4. Caught ClientResultException. More on that below.
  5. Only advanced previousResponseId after 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:

C#
1
dotnet run --project src/BitOfTech.Expenses.FoundryAgent

PowerShell
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

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 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
  • Part 5: Hosting an MCP Server in ASP.NET Core with Streamable HTTP

Filed Under: AI, Azure, MCP Tagged With: .NET 10, AI Agents, Azure, MCP, Microsoft Foundry, Model Context Protocol, OAuth 2.1

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