Bit of Technology

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

Part 8: Deploying an MCP Server to Azure Container Apps

October 15, 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 eighth 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 (This Post)
  • Connecting an MCP Server to Microsoft Foundry Agent Service
  • Observability, Cost Control and MCP Security

The source code for this tutorial is available on GitHub.

Deploying an MCP Server to Azure Container Apps

Our server has run on localhost for six parts. Only one client has ever reached it, the .NET agent we wrote in Part 6.

That was a limit we hit in Part 7, not a choice. VS Code wouldn’t trust the local development certificate, and Claude connects from Anthropic’s cloud so localhost means nothing to it. A public address with a real certificate fixes both at once.

There’s a second thing that changes, and it’s bigger than the URL. Every part so far has run as me. When I start the server it picks up my Azure CLI sign-in and uses it to reach Azure SQL. There is no me inside a container, so the container needs an identity of its own.

We’ll also add notify_employee, the last tool in the series. It sends an email when a report is approved, which gives us a tool whose result you can see outside the chat window.

Note: we add a few Azure resources in this post. A container registry, a Container Apps environment, a Log Analytics workspace and a Communication Services resource. The container app scales to zero when nothing is calling it.

What deployment changes about an MCP server

Most of this post is ordinary Azure work. One part isn’t, and it’s worth getting straight before we start.

An MCP server built on Streamable HTTP used to keep a session in memory. The client got an Mcp-Session-Id header on its first call and sent it back on every later call, and the server looked up the session each time. Servers like that need every request from one client to land on the same instance. That makes scaling awkward.

That is no longer how it works. The 2026-07-28 revision removed sessions from Streamable HTTP. The Mcp-Session-Id header is gone, and so is the initialize handshake.

The C# SDK follows the spec. Here is what the 2.2.0 XML documentation says about the option that controls it:

C#
1
2
3
4
5
6
Gets or sets a value that indicates how the server tracks state between requests.
 
The default is HttpServerSessionMode.Stateless as of the 2026-07-28 protocol revision.
 
Stateless doesn't track state between requests, allowing for load balancing
without session affinity.

So our server has been stateless since Part 5 and we never had to ask for it. The .WithHttpTransport() call we wrote back then already gets this.

For deployment that means we can scale to zero, run as many replicas as we like, and skip session affinity entirely. Scaling an MCP server is now the same problem as scaling any stateless web API, which is to say it is not much of a problem.

Note: stateless mode turns some things off. The GET and DELETE endpoints are gone, and the server can’t send unsolicited messages or make requests back to the client. So anything where the server speaks first, like a resource update notification, has nowhere to go. Sampling, elicitation and roots are disabled for the same reason, since each of those is the server asking the client for something. There is a replacement for them, and it’s worth knowing the name. We use none of them, so it costs us nothing here.

The replacement is Multi Round-Trip Requests. Instead of the server calling the client mid-request, the tool returns an unfinished answer with a small piece of state attached, and the client calls the tool again, sending that state back. The state travels in the request instead of sitting in one server’s memory, so any replica can pick up where the last one stopped.

Putting the server in a container

Step 1: Set your variables

Four new names, and the SQL ones from Part 4 repeated so everything resolves in one shell. Only names that have to be unique across all of Azure carry the suffix, which here means the registry and the SQL server.

PowerShell
1
2
3
4
5
6
7
8
9
10
11
$SUFFIX          = "tj01"
$LOCATION        = "westeurope"
$RESOURCE_GROUP  = "rg-bitoftech-expenses"
 
$SQL_SERVER      = "sql-bitoftech-expenses-$SUFFIX"
$SQL_DATABASE    = "sqldb-bitoftech-expenses"
 
$ACR_NAME        = "acrbitoftechexpenses$SUFFIX"
$ACA_ENV         = "cae-bitoftech-expenses"
$ACA_APP         = "ca-bitoftech-expenses-mcp"
$LOG_NAME        = "log-bitoftech-expenses"

Note: a container registry name allows letters and numbers only. No hyphens, which is why that one looks different from the rest.

Step 2: Add the Dockerfile

Two stages. The first builds and publishes, the second runs what the first produced. The runtime image has no SDK in it, which keeps the result small.

Dockerfile, in the repository root:

PowerShell
1
2
3
4
5
6
7
8
9
10
11
12
13
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
 
COPY src/BitOfTech.Expenses.Mcp/BitOfTech.Expenses.Mcp.csproj src/BitOfTech.Expenses.Mcp/
RUN dotnet restore src/BitOfTech.Expenses.Mcp/BitOfTech.Expenses.Mcp.csproj
 
COPY src/BitOfTech.Expenses.Mcp/ src/BitOfTech.Expenses.Mcp/
RUN dotnet publish src/BitOfTech.Expenses.Mcp/BitOfTech.Expenses.Mcp.csproj -c Release -o /app
 
FROM mcr.microsoft.com/dotnet/aspnet:10.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "BitOfTech.Expenses.Mcp.dll"]

What we have done here is the following:

  1. Copied the csproj on its own first, then restored, then copied the rest. Docker caches each step. If you change a C# file, the restore layer is reused, which makes rebuilds much faster.
  2. Published to /app and copied only that into the runtime image.
  3. Left out EXPOSE and ASPNETCORE_URLS. The ASP.NET Core runtime images already listen on port 8080, so setting it again would be noise. That port number matters in Step 6.

Note: remember ContentRootPath = AppContext.BaseDirectory in Program.cs, from Part 5. We added it so the server could be launched from any folder. It’s also what makes appsettings.json resolve correctly inside the container.

Add a .dockerignore next to it. Everything not listed here gets uploaded when we build, so this keeps the upload small and stops build output from ending up in the image.

.dockerignore

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
.git/
.github/
.vscode/
entra-setup/
 
**/bin/
**/obj/
artifacts/
 
Dockerfile
.dockerignore
docker-compose.yml
README.md
LICENSE

Skipping this file is a common way to end up with a slow build and a bigger image than you expected.

Step 3: Create the registry and build the image

PowerShell
1
2
3
4
5
6
7
8
9
10
az acr create `
  --resource-group $RESOURCE_GROUP `
  --name $ACR_NAME `
  --sku Basic `
  --admin-enabled true
 
az acr build `
  --registry $ACR_NAME `
  --image bitoftech-expenses-mcp:v1 `
  .

Let’s review the parameters:

  1. az acr build uploads the source and builds the image in Azure. You don’t need Docker installed. If you have it and would rather build locally, docker build then az acr login and docker push does the same job.
  2. --image bitoftech-expenses-mcp:v1 is the name and tag. I’m using explicit versions rather than latest, so I can tell which build is running.
  3. --admin-enabled true lets Container Apps pull with a username and password. A production setup would give the container app a managed identity and the AcrPull role instead. I’m using the simpler path here so the post stays on MCP.

The Azure pieces

Step 4: Create the Container Apps environment

An environment is the boundary the apps run inside. It owns the network and the log destination, and apps in the same environment can reach each other.

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
az extension add --name containerapp --upgrade
 
az provider register --namespace Microsoft.App
az provider register --namespace Microsoft.OperationalInsights
 
az monitor log-analytics workspace create `
  --resource-group $RESOURCE_GROUP `
  --workspace-name $LOG_NAME `
  --location $LOCATION
 
$LOG_ID = az monitor log-analytics workspace show `
  --resource-group $RESOURCE_GROUP --workspace-name $LOG_NAME `
  --query customerId -o tsv
 
$LOG_KEY = az monitor log-analytics workspace get-shared-keys `
  --resource-group $RESOURCE_GROUP --workspace-name $LOG_NAME `
  --query primarySharedKey -o tsv
 
az containerapp env create `
  --name $ACA_ENV `
  --resource-group $RESOURCE_GROUP `
  --location $LOCATION `
  --logs-workspace-id $LOG_ID `
  --logs-workspace-key $LOG_KEY

The Log Analytics workspace is where az containerapp logs reads from later. Container Apps will create one for you if you leave it out, with a generated name. I’d rather name it myself.

Step 5: Work out the public URL before creating the app

Here we hit a small ordering problem, and it’s worth seeing why rather than working around it.

  1. Entra only issues tokens for a name it knows. The public URL has to be registered on the app registration from Part 7 as a second Application ID URI.
  2. The container needs Entra:ServerUrl set to the public URL, because that value goes into the metadata document clients read after a 401.
  3. Neither can happen until the URL exists, and the URL belongs to an app we haven’t created.

The way out is that the address is predictable once the environment exists. Every app in an environment gets <app-name>.<environment-default-domain>. So we can read the domain now and work out the URL before the app exists.

PowerShell
1
2
3
4
5
6
7
8
9
$ACA_DOMAIN = az containerapp env show `
  --name $ACA_ENV --resource-group $RESOURCE_GROUP `
  --query properties.defaultDomain -o tsv
 
$MCP_PUBLIC_URL = "https://$ACA_APP.$ACA_DOMAIN"
$MCP_RESOURCE   = "$MCP_PUBLIC_URL/mcp"
 
Write-Output "Domain:     $ACA_DOMAIN"
Write-Output "Public URL: $MCP_PUBLIC_URL"

PowerShell
1
2
Domain:     kindsea-d84c8163.westeurope.azurecontainerapps.io
Public URL: https://ca-bitoftech-expenses-mcp.kindsea-d84c8163.westeurope.azurecontainerapps.io

Note: that kindsea-d84c8163 is generated when the environment is created, and yours will be different. That’s the reason we read the domain instead of building the URL from the region. You can’t guess it.

Now register it with Entra, alongside the localhost one from Part 7. Remember the Application ID URI is the endpoint, so it ends with /mcp. The Graph API replaces the whole property, so we have to send both.

PowerShell
1
2
3
4
5
6
7
8
9
10
11
12
13
$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
 
New-Item -ItemType Directory -Force -Path entra-setup | Out-Null
 
@{ identifierUris = @("https://localhost:7040/mcp", $MCP_RESOURCE) } | ConvertTo-Json -Compress |
  Set-Content -Path entra-setup/identifier-public.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/identifier-public.json"
 
az ad app show --id $MCP_APP_ID --query identifierUris -o json

That last line should print both URLs back.

Keeping localhost matters. One registration now answers for the local server and the deployed one, so you can keep developing without touching Entra again.

Important note: the aud claim doesn’t change. It’s still the app registration’s client ID, the same value we put in Entra:ClientId in Part 7. Adding a second name to a registration doesn’t give it a second audience, so no server code changes here.

In the portal: App registrations > BitOfTech Expenses MCP > Manage > Manifest, then look at identifierUris. Both are there. The Expose an API page only shows one of them in its Application ID URI box, which is worth knowing before you think the second one didn’t save.

Step 6: Create the container app

PowerShell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$TENANT_ID = az account show --query tenantId -o tsv
$SQL_CONN  = "Server=tcp:$SQL_SERVER.database.windows.net,1433;Database=$SQL_DATABASE;Authentication=Active Directory Default;Encrypt=True;TrustServerCertificate=False;"
 
az containerapp create `
  --name $ACA_APP `
  --resource-group $RESOURCE_GROUP `
  --environment $ACA_ENV `
  --image "$ACR_NAME.azurecr.io/bitoftech-expenses-mcp:v1" `
  --registry-server "$ACR_NAME.azurecr.io" `
  --target-port 8080 `
  --ingress external `
  --min-replicas 0 `
  --max-replicas 3 `
  --system-assigned `
  --env-vars `
    "ConnectionStrings__ExpensesDb=$SQL_CONN" `
    "Entra__TenantId=$TENANT_ID" `
    "Entra__ClientId=$MCP_APP_ID" `
    "Entra__ServerUrl=$MCP_PUBLIC_URL"
 
az containerapp show --name $ACA_APP --resource-group $RESOURCE_GROUP `
  --query properties.configuration.ingress.fqdn -o tsv

Let’s review the parameters:

  1. --target-port 8080 matches the port the .NET runtime image listens on.
  2. --ingress external gives the app a public hostname and a certificate. This one line is what makes VS Code and Claude possible.
  3. --min-replicas 0 is scale to zero. The app shuts down when nobody is calling it and starts again on the next request. We can do this because the server keeps nothing between requests. The first call after a quiet period is slow.
  4. --max-replicas 3 is also safe for the same reason. No session affinity, no sticky cookie, nothing to configure.
  5. --system-assigned gives the app its own identity in Entra. Step 7 uses it.
  6. Double underscores in the environment variable names. That’s how .NET configuration reads nesting from environment variables, so Entra__ClientId becomes Entra:ClientId.

The FQDN printed at the end should match the $MCP_PUBLIC_URL we predicted in Step 5. If it doesn’t, go back and fix the identifier URI before carrying on.

The app is running now. Signing in works and listing the tools works, because neither touches the database. If you call any tool, it fails. The container has no access to SQL yet.

Step 7: Give the container access to SQL

This is the part I’d slow down for. Everything up to here is packaging. This is the bit that’s actually different about running in the cloud.

Look at the connection string in Step 6. It’s the same one that’s been in appsettings.json since Part 4, character for character:

C#
1
Authentication=Active Directory Default

On my laptop that resolves to my Azure CLI sign-in. In Container Apps there is no signed in user, so it resolves to the container’s system assigned identity instead. Same string, two different identities, because Active Directory Default means “work out who I am from the environment”.

That’s why the connection string never needed a password and never needed editing. The identity comes from where the code is running, not from the configuration.

Azure SQL doesn’t know about that identity yet. Connect to the database as yourself and create a user for it.

C#
1
2
3
4
CREATE USER [ca-bitoftech-expenses-mcp] FROM EXTERNAL PROVIDER;
 
ALTER ROLE db_datareader ADD MEMBER [ca-bitoftech-expenses-mcp];
ALTER ROLE db_datawriter ADD MEMBER [ca-bitoftech-expenses-mcp];

What we have done here is the following:

  1. Named the user after the container app. A system assigned identity takes the name of the resource it belongs to, so ca-bitoftech-expenses-mcp is both the app name and the identity name.
  2. FROM EXTERNAL PROVIDER tells SQL this user lives in Entra, not in the database. There’s no password to set because there’s no password anywhere.
  3. Granted read and write, and nothing else. The app can’t change the schema. Migrations still run from my machine, where I’m an administrator.

Note: this only works if your SQL server uses Microsoft Entra only authentication, which we set up in Part 4.

Restart the app so it picks up a fresh token, then check it:

PowerShell
1
2
3
4
5
6
7
8
az containerapp revision restart `
  --name $ACA_APP --resource-group $RESOURCE_GROUP `
  --revision (az containerapp show --name $ACA_APP --resource-group $RESOURCE_GROUP --query properties.latestRevisionName -o tsv)
 
curl.exe -i -s -X POST "$MCP_PUBLIC_URL/mcp" `
  -H "Content-Type: application/json" `
  -H "Accept: application/json, text/event-stream" `
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

C#
1
2
3
4
HTTP/1.1 401 Unauthorized
content-length: 0
server: Kestrel
www-authenticate: Bearer resource_metadata="http://ca-bitoftech-expenses-mcp.kindsea-d84c8163.westeurope.azurecontainerapps.io/.well-known/oauth-protected-resource/mcp"

A 401 is the right answer. Look at the scheme in that header though.

The server thinks it’s running on HTTP

It says http://. We called an https address, and everything about the app looks healthy, but the one URL an MCP client has to follow is wrong.

Container Apps terminates TLS at its ingress, then forwards the request to your container over plain HTTP. So Kestrel is telling the truth about what it received. The request really did arrive as HTTP.

The ingress does say what happened, in an X-Forwarded-Proto: https header. ASP.NET Core ignores forwarded headers unless you ask it to read them, because trusting them blindly lets a caller lie about where a request came from.

This matters more for an MCP server than for a normal API. A client that gets a 401 has exactly one thing to go on, the resource_metadata URL. If you send it to the wrong scheme, discovery breaks for every client, while health checks and logs keep looking fine. Entra also issues tokens for the https name, so nothing downstream would line up either.

Step 8: Trust the headers the ingress sends

src/BitOfTech.Expenses.Mcp/Program.cs, near the top:

C#
1
2
3
4
5
6
7
8
using Microsoft.AspNetCore.HttpOverrides;
 
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    options.KnownIPNetworks.Clear();
    options.KnownProxies.Clear();
});

And as the first thing in the pipeline:

C#
1
2
3
4
5
6
var app = builder.Build();
 
app.UseForwardedHeaders();
 
app.UseAuthentication();
app.UseAuthorization();

What we have done here is the following:

  1. Read X-Forwarded-Proto, which is the one that fixes the scheme. X-Forwarded-For comes along for the client IP, which you’ll want in logs later.
  2. Cleared KnownIPNetworks and KnownProxies. By default ASP.NET Core only trusts these headers from a loopback address, and the Container Apps ingress isn’t one. Clearing both lists means the headers are trusted from anywhere. On .NET 9 and earlier the first one is called KnownNetworks, which is now deprecated.
  3. Put UseForwardedHeaders first. It has to run before anything that reads the scheme, and that includes the MCP challenge handler writing the 401.

Important note: clearing those lists does mean trusting whatever sent the header. That’s acceptable here because ingress is the only way into the container. It would not be acceptable on a server reachable directly, where a caller could set the header themselves. If that’s your situation, list your proxy addresses in KnownProxies instead of clearing it.

Note: there’s a shortcut for containers, the environment variable ASPNETCORE_FORWARDEDHEADERS_ENABLED=true, which turns on the same middleware with much the same settings. It’s useful for testing a theory quickly without a rebuild. I’d rather have it in code, where the next person can see it and change it.

We’ll rebuild once at the end, after the email tool is in, rather than pushing a new image now.

Sending an email from an MCP tool

The notify_employee tool sends an email to the employee after an expense report is approved. We’ll use Azure Communication Services to send that email from the MCP server.

Step 9: Create the Communication Services resources

Azure splits email across two resources. An Email Communication Service owns the domain, and a Communication Services resource owns the connection string. You create both and link them.

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
30
31
32
33
34
az extension add --name communication --upgrade
 
$ACS_EMAIL = "acs-email-bitoftech-expenses"
$ACS_NAME  = "acs-bitoftech-expenses"
 
az communication email create `
  --name $ACS_EMAIL `
  --resource-group $RESOURCE_GROUP `
  --location global `
  --data-location Europe
 
az communication email domain create `
  --domain-name AzureManagedDomain `
  --email-service-name $ACS_EMAIL `
  --resource-group $RESOURCE_GROUP `
  --location global `
  --domain-management AzureManaged
 
$DOMAIN_ID = az communication email domain show `
  --domain-name AzureManagedDomain --email-service-name $ACS_EMAIL `
  --resource-group $RESOURCE_GROUP --query id -o tsv
 
az communication create `
  --name $ACS_NAME `
  --resource-group $RESOURCE_GROUP `
  --location global `
  --data-location Europe `
  --linked-domains $DOMAIN_ID
 
$SENDER = az communication email domain show `
  --domain-name AzureManagedDomain --email-service-name $ACS_EMAIL `
  --resource-group $RESOURCE_GROUP --query fromSenderDomain -o tsv
 
Write-Output "Sender: DoNotReply@$SENDER"

C#
1
Sender: DoNotReply@ae0d3cac-b4c8-4a1a-abcf-1601f8caef8d.azurecomm.net

That GUID is your domain. It’s generated, so yours will be different.

If you run az communication email domain show without the query, you’ll see something worth noticing: SPF, DKIM, DKIM2, DMARC and the domain itself all come back Verified straight away. That’s what you’re paying for with a managed domain. With your own domain you’d be adding DNS records and waiting.

Let’s review the parameters:

  1. --location global and --data-location Europe are two different things. The resource itself is global. The data location decides which region your data sits in, and you can’t change it later.
  2. --domain-management AzureManaged gives you a domain Azure owns, ready straight away. The sender address it produces is ugly, something like DoNotReply@a1b2c3d4.azurecomm.net. A real system would use its own domain and add DNS records. We’re proving a tool can send mail, so the ugly address is fine.
  3. --linked-domains connects the two resources. Without it the Communication Services resource has no domain it’s allowed to send from.

Note: the az communication email command group is in preview, so these flags may move. The portal has the same screens under Email Communication Service if a command fails.

An Azure Managed Domain has a hard sending limit: 5 emails a minute and 10 an hour, per subscription, and you can’t ask for more. Custom domains start at 30 a minute and 100 an hour and can be raised. So if you test this a few times in a row you will hit the ceiling. Check your spam folder too, since mail from an azurecomm.net address has no reputation behind it.

Step 10: Add the connection string as a secret

Now a contrast worth noticing.

The SQL connection string has no credential in it. That’s why we committed it to the repository in Part 4 and passed it as a plain environment variable in Step 6.

The Communication Services connection string has an access key in it. Anyone holding it can send email as you. So it cannot go in appsettings.json and it cannot be an ordinary environment variable.

Container Apps has secrets for this. You store the value once, then reference it by name.

PowerShell
1
2
3
4
5
6
7
8
9
10
11
12
13
$ACS_CONN = az communication list-key `
  --name $ACS_NAME --resource-group $RESOURCE_GROUP `
  --query primaryConnectionString -o tsv
 
az containerapp secret set `
  --name $ACA_APP --resource-group $RESOURCE_GROUP `
  --secrets "acs-connection=$ACS_CONN"
 
az containerapp update `
  --name $ACA_APP --resource-group $RESOURCE_GROUP `
  --set-env-vars `
    "Email__ConnectionString=secretref:acs-connection" `
    "Email__SenderAddress=DoNotReply@$SENDER"

The secretref: prefix is the part to remember. The app reads Email:ConnectionString like any other setting, but the value isn’t stored in the environment variable. It sits in the app’s secret collection, and reading it back needs a separate call and the right permissions on the resource.

Two connection strings, two different answers. The difference is only whether there’s a credential inside.

Step 11: Write the email sender

Add the package, pinned as usual:

XHTML
1
<PackageReference Include="Azure.Communication.Email" Version="1.1.0" />

src/BitOfTech.Expenses.Mcp/Services/EmailSender.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
using Azure;
using Azure.Communication.Email;
 
namespace BitOfTech.Expenses.Mcp.Services;
 
public sealed class EmailSender(IConfiguration configuration)
{
    private readonly EmailClient _client = new(configuration["Email:ConnectionString"]!);
    private readonly string _sender = configuration["Email:SenderAddress"]!;
 
    public async Task SendAsync(
        string recipient,
        string subject,
        string html,
        CancellationToken cancellationToken)
    {
        await _client.SendAsync(
            WaitUntil.Completed,
            _sender,
            recipient,
            subject,
            html,
            cancellationToken: cancellationToken);
    }
}

Note: WaitUntil.Completed waits for the service to accept the message before returning. Accepted is not the same as delivered. WaitUntil.Started returns immediately and gives you an operation id to poll, which is what you’d want for anything sending in bulk.

Register it in Program.cs:

C#
1
builder.Services.AddSingleton<EmailSender>();

Step 12: Add the notify_employee tool

src/BitOfTech.Expenses.Mcp/Tools/NotificationTools.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
using System.ComponentModel;
using BitOfTech.Expenses.Mcp.Data;
using BitOfTech.Expenses.Mcp.Models;
using BitOfTech.Expenses.Mcp.Services;
using Microsoft.EntityFrameworkCore;
using ModelContextProtocol;
using ModelContextProtocol.Server;
 
namespace BitOfTech.Expenses.Mcp.Tools;
 
[McpServerToolType]
public class NotificationTools(ExpensesDbContext db, EmailSender emailSender)
{
    [McpServerTool(Name = "notify_employee")]
    [Description("Emails the employee who owns an expense report to tell them it has been approved. Only works on a report that is already Approved. The message text is fixed, so there is nothing to write and no wording to ask the user for.")]
    public async Task<string> NotifyEmployeeAsync(
        [Description("The id of the approved expense report.")] int reportId,
        CancellationToken cancellationToken = default)
    {
        var target = await (
            from report in db.Reports.AsNoTracking()
            join employee in db.Employees on report.EmployeeId equals employee.Id
            where report.Id == reportId
            select new { report.Title, report.Status, employee.Name, employee.Email })
            .FirstOrDefaultAsync(cancellationToken)
            ?? throw new McpException(
                $"No expense report found with id {reportId}. Call search_expense_reports to find valid ids.");
 
        if (target.Status is not ExpenseReportStatus.Approved)
        {
            throw new McpException(
                $"Report {reportId} is {target.Status}. Only an approved report can be notified about.");
        }
 
        // The body is built here, not by the model. A tool that sends whatever text it is handed
        // is a tool that will eventually send something you did not write.
        await emailSender.SendAsync(
            target.Email,
            $"Your expense report has been approved",
            $"<p>Hello {target.Name},</p><p>Your expense report <strong>{target.Title}</strong> has been approved.</p>",
            cancellationToken);
 
        return $"Emailed {target.Name} at {target.Email} about report {reportId}.";
    }
}

What we have done here is the following:

  1. Took one parameter. A report id. Not a recipient, not a subject, not a body.
  2. Read the recipient from the database. The model picks which report to notify about. It doesn’t pick who gets the mail.
  3. Built the body in code. This is the same reason we didn’t accept an approverName parameter in Part 7. If the model could choose the text and the address, it could send an email you never wrote to a person you never chose. A fixed template means it can’t.
  4. Refused anything that isn’t Approved, so the tool can’t announce an approval that hasn’t happened.

Step 13: Make the approval offer to send it

There’s a design problem with what we just built, and it’s worth facing rather than hoping nobody notices.

In a real expense system the email goes out inside the approval. Nobody has to remember to send it. By making it a separate tool, we’ve built something where an approval can quietly succeed and the employee never hears about it, because the user forgot to ask.

The reason to keep them apart is that you can watch the model chain two tools, and that’s worth seeing. But the workflow shouldn’t depend on the user remembering.

Here’s the constraint: we can’t fix this in the client. We don’t own the client. VS Code, Claude and our own agent each decide for themselves what to call and when. There’s no system prompt we control and no code path we can hook.

What we do own is the tool description, and every client sends it to its model. So that’s where workflow guidance goes.

src/BitOfTech.Expenses.Mcp/Tools/ExpenseTools.cs, appended to the existing description on approve_expense_report:

C#
1
2
3
After approving, ask the user whether the employee should be emailed about it, and call
notify_employee only if they say yes. If they already asked for the employee to be told,
call notify_employee without asking again.

Two sentences, and the second matters as much as the first:

  1. The first turns a forgettable step into a question the user gets asked. The approval offers, rather than waiting to be told.
  2. The second stops it becoming annoying. Without it, saying “approve 1013 and let Sara know” still gets you “would you like me to notify Sara?”, which is worse than not offering at all.

This technique is worth keeping. A tool description isn’t only documentation for one call. It’s the only channel you have for saying how your tools fit together, and it reaches every client that ever connects.

It has a limit, and I’d rather say so. This is guidance, not a guarantee. A model can ignore it, and different models read it differently. Anything that must happen belongs in the server code, where a refusal is a refusal. Use the description for what should usually happen, not for what has to.

Rebuild, push and update the app. This picks up all three code changes: the forwarded headers from Step 8, the email tool, and this description.

PowerShell
1
2
3
4
5
az acr build --registry $ACR_NAME --image bitoftech-expenses-mcp:v2 .
 
az containerapp update `
  --name $ACA_APP --resource-group $RESOURCE_GROUP `
  --image "$ACR_NAME.azurecr.io/bitoftech-expenses-mcp:v2"

Check the header again, and this time it should say https:

PowerShell
1
2
3
4
curl.exe -i -s -X POST "$MCP_PUBLIC_URL/mcp" `
  -H "Content-Type: application/json" `
  -H "Accept: application/json, text/event-stream" `
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

C#
1
2
HTTP/1.1 401 Unauthorized
www-authenticate: Bearer resource_metadata="https://ca-bitoftech-expenses-mcp.kindsea-d84c8163.westeurope.azurecontainerapps.io/.well-known/oauth-protected-resource/mcp"

Point the agent at the deployed server

Two settings in the Part 6 agent, and nothing else.

src/BitOfTech.Expenses.Agent/appsettings.json

C#
1
2
3
4
5
6
"Mcp": {
  "Endpoint": "https://ca-bitoftech-expenses-mcp.kindsea-d84c8163.westeurope.azurecontainerapps.io/mcp"
},
"Entra": {
  "Scope": "https://ca-bitoftech-expenses-mcp.kindsea-d84c8163.westeurope.azurecontainerapps.io/mcp/Expenses.Access"
}

The endpoint is where to call. The scope starts with the Application ID URI we registered in Step 5, which is why both change together. No C# changes at all. The agent doesn’t care that the server moved to Azure.

Run the agent, and sign in when the browser opens:

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

PowerShell
1
2
3
4
5
Connected to BitOfTech.Expenses.Mcp at https://ca-bitoftech-expenses-mcp.kindsea-d84c8163.westeurope.azurecontainerapps.io/mcp
7 tools: approve_expense_report, create_expense_report, search_expense_reports,
         submit_expense_report, notify_employee, convert_currency, get_expense_report
Mode: hand written tool loop
Type a question, or an empty line to quit.

Seven tools now, because notify_employee joined the six from Part 7.

Now approve something:

PowerShell
1
2
3
4
5
6
7
8
9
10
11
> Approve report 1014
  -> approve_expense_report(reportId: 1014)
  <- {"id":1014,"title":"Amman client visit","employeeName":"Sara Haddad","status":"Approved","currency":"JOD", ...
Approved report 1014.
 
Do you want me to email Sara Haddad about it?
 
> yes, send her an email
  -> notify_employee(reportId: 1014)
  <- Emailed Sara Haddad at sara.haddad@bitoftech.net about report 1014.
Done, Sara Haddad has been emailed.

That question came from the tool description. Nothing else could have produced it.

Our agent doesn’t know these two tools are related. ToolLoop.cs from Part 6 hasn’t changed since we wrote it, and it has no idea what an expense report is. The model didn’t know either, until it read the sentence we added.

Say it in one sentence and it skips the question:

PowerShell
1
2
3
4
5
6
> approve report 1015 and notify the sender
  -> approve_expense_report(reportId: 1015)
  <- {"id":1015,"title":"Chicago client visit","employeeName":"Sara Haddad","status":"Approved", ...
  -> notify_employee(reportId: 1015)
  <- Emailed Sara Haddad at sara.haddad@bitoftech.net about report 1015.
Approved report 1015 and emailed Sara Haddad.

Two tools, one sentence, no question. The second sentence of the description is what stops it asking something you’ve already answered.

Notice the model worked out who “the sender” was. We never passed a name to either tool. approve_expense_report takes only a report id and reads the approver from the token, and notify_employee takes only a report id and reads the recipient from the database.

Then check the inbox. Mail from a new Azure Managed Domain usually lands in the spam folder, so look there first.

Letting the other two clients sign in

The agent works because Part 7 registered the redirect URI it uses. VS Code and Claude each sign in a different way, so each needs a redirect URI of its own before it can connect.

Step 14: Register the redirect URIs both clients need

Part 7 registered three redirect URIs on BitOfTech Expenses Clients. VS Code and Claude each need one more, and it’s easier to add both now than to stop twice.

PowerShell
1
2
3
4
5
6
7
az ad app update --id $CLIENT_APP_ID `
  --public-client-redirect-uris `
    "https://vscode.dev/redirect" `
    "http://127.0.0.1:33418" `
    "http://localhost:8080/callback" `
    "ms-appx-web://Microsoft.AAD.BrokerPlugin/$CLIENT_APP_ID" `
    "https://claude.ai/api/mcp/auth_callback"

Let’s review the two new ones:

  1. ms-appx-web://Microsoft.AAD.BrokerPlugin/$CLIENT_APP_ID is for VS Code on Windows, which signs in through the Windows account broker rather than a browser. The client ID appears twice in that line, once as the app being changed and once inside the URI. That’s the format the broker uses.
  2. https://claude.ai/api/mcp/auth_callback is for Claude, and it’s worth a second look. It’s a claude.ai address even if you’re using the desktop app, because the sign-in is brokered through Anthropic’s cloud rather than your machine.

Note: the flag replaces the whole list, so the three from Part 7 have to be repeated. If you leave one out, you break the client that needed it.

Connecting VS Code

VS Code has been our client since Part 2, and it stopped working in Part 7 when we moved to HTTPS on localhost. Its MCP client runs on Node, Node uses OpenSSL, and OpenSSL won’t accept the ASP.NET Core development certificate. Container Apps gives us a certificate from a public authority, which every client already trusts.

.vscode/mcp.json

C#
1
2
3
4
5
6
7
8
9
{
  "servers": {
    "bitoftech-expenses": {
      "type": "http",
      "url": "https://ca-bitoftech-expenses-mcp.kindsea-d84c8163.westeurope.azurecontainerapps.io/mcp",
      "oauth": { "clientId": "your client app registration id" }
    }
  }
}

Replace the localhost URL rather than keeping both. Two entries pointing at the same server means two sets of tools in the picker, with identical names.

Let’s review the parameters:

  1. "type": "http" is Streamable HTTP, the transport we’ve used since Part 5.
  2. oauth.clientId is the $CLIENT_APP_ID from Part 7, Step 2, belonging to BitOfTech Expenses Clients. If you leave it out, VS Code signs in with its own built in Microsoft account instead, which is a different application that your API has never heard of.

That second one is the part worth understanding, and the next section shows it more clearly than I can describe it.

Start the server from the editor. VS Code asks which account to sign in with, in a picker that looks like the Command Palette.

Pick your account, and the tools appear. Ask Copilot something:

C#
1
What expense reports is Sara waiting on?

Seven tools, the same list the .NET agent sees, including approve_expense_report, because it’s the same account with the same app role. Different client, same identity, same answer. If you try approving your own report, you’ll get the same refusal we built in Part 7.

Approve somebody else’s and Copilot offers to email them, exactly as our agent did. That’s the tool description from Step 13 doing its work in a client we never wrote a line for, against a model we didn’t choose.

To see what you’ve granted, open Accounts > Manage Trusted MCP Servers.

Connecting Claude

Claude reaches your server from Anthropic’s cloud, not from your machine. That’s why it could never have used the localhost server, on the desktop app as much as the website. A public URL is what makes it possible at all.

Open Settings > Connectors, then Add custom connector, and paste the same /mcp URL. The next screen is worth reading rather than clicking through.

Under OAuth client, Claude offers three choices. They’re the three ways an MCP client can get a client ID, and seeing them named in a product makes the spec concrete:

  1. Use Claude’s published identity. Client ID Metadata Documents. Claude publishes a URL describing itself, and the server reads it. Nothing to configure, but the authorization server has to support it.
  2. Register automatically. Dynamic Client Registration, RFC 7591. Claude asks the authorization server to create a client as each user connects.
  3. Use your own OAuth client. Pre-registration. You supply an ID that already exists.

Claude reads our metadata document, works out which of these our authorization server supports, and marks the answer Detected. It lands on the third one, because Entra advertises neither of the first two. You can check that yourself: fetch https://login.microsoftonline.com/<tenant-id>/v2.0/.well-known/openid-configuration and look for registration_endpoint and client_id_metadata_document_supported. Neither is there.

So put the $CLIENT_APP_ID from Part 7, Step 2 in the OAuth client ID field and leave the secret blank. BitOfTech Expenses Clients is a public client and doesn’t have one.

This is the same thing oauth.clientId did for VS Code, and it isn’t a workaround. Pre-registration is the first choice in the spec’s own order of preference, and it’s what most enterprise deployments use, because it means an administrator decides which applications may call the API.

Click Add, then Connect, and sign in. The connector page then lists the tools:

Seven again, the same list, because it’s the same account with the same app role.

One thing on that page is worth noticing. Claude puts a permission next to every tool, defaulting to Needs approval, so it asks before each call. That’s a different kind of protection from ours. Our server decides what you’re allowed to do, from the token. Claude decides what it may do without asking you first. A client can only ever be more cautious than the server, never less, and the two layers are worth keeping straight.

Note: custom connectors work on the free plan, limited to one. On Team and Enterprise plans only an owner can add a connector, under Organization settings > Connectors, and members connect to it individually afterwards.

Three clients now, all talking to one server. Our .NET agent, VS Code and Claude. None of them share a line of code, and we didn’t write anything specific to any of them. That’s the part of MCP worth stopping on for a second.

Summary

The deployment itself was ordinary. A Dockerfile, a registry, an environment, an app.

Two things were worth the post. The first is that scaling an MCP server turned out to be a non event. The 2026-07-28 revision removed sessions from Streamable HTTP, the C# SDK defaults to stateless because of it, and so scale to zero and three replicas both work with nothing configured. If you read older material on hosting MCP servers you’ll find advice about session affinity that no longer applies.

The second is the connection string that never changed. Authentication=Active Directory Default meant me on my laptop and means the container’s own identity in Azure, with no edit and no password in either place. The same idea also shows its edge: the Communication Services connection string does hold a key, so that one had to become a secret.

Part 9 connects this server to Microsoft Foundry Agent Service, where the agent runs in Azure rather than in a console window on your machine. That’s the last client in the series, and the deployed URL from this post is what it connects to.

The source code for this tutorial is available on GitHub.

Follow me on X @TJoudeh and on LinkedIn

References:

  • Azure Container Apps overview
  • Manage secrets in Azure Container Apps
  • Microsoft Entra authentication for Azure SQL
  • Create an Email Communication Service resource
  • Containerize a .NET app
  • MCP Streamable HTTP transport
  • Claude custom connectors using remote MCP

Share this:

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

Like this:

Like Loading…

Related Posts

  • Part 10: Observability, Cost Control and MCP Security
  • Part 9: Connecting an MCP Server to Microsoft Foundry Agent Service
  • Part 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, Azure Communication Services, Azure Container Apps, Docker, Managed Identity, MCP, Model Context Protocol

Leave a Reply Cancel reply

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

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

About Taiseer

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

Buy me a coffeeBuy me a coffee

Recent Posts

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

Blog Archives

Recent Posts

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

Tags

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

Search

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

%d