This is the fourth 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 (This Post)
- 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
- Observability, Cost Control and MCP Security
The source code for this tutorial is available on GitHub.
Wiring MCP Tools to Azure SQL and External APIs
Everything so far has run off a hard coded list in memory. That was deliberate, because it kept the first three parts about the protocol. Now we throw it away.
In this post the data moves into Azure SQL, the tools talk to it with EF Core, and one tool calls a public API on the internet. We also fix something I left broken in Part 2. Searching for one employee returns every line item of every matching report, whether you asked for them or not. That’s harmless with five rows and expensive with five thousand.
This is the first part that needs an Azure subscription. The database runs on the Azure SQL free offer, so it costs nothing.
What we’re changing
ExpenseStore, the in-memory list, is replaced byExpensesDbContext.- Tools stop returning database entities and start returning purpose built shapes.
- A new
convert_currencytool calls the Frankfurter exchange rate API. - Two new tools,
create_expense_reportandsubmit_expense_report, write to the database. That’s the first time anything our server does cannot be undone by the model.
Creating the database
Everything here is Azure CLI. I’d rather give you commands you can read and re-run than a sequence of portal screenshots that go stale.
Step 1: Set your variables
|
1 2 3 4 5 6 7 |
$SUBSCRIPTION_ID = "<your subscription id>" $LOCATION = "westeurope" $SUFFIX = "tj01" $RESOURCE_GROUP = "rg-bitoftech-expenses" $SQL_SERVER = "sql-bitoftech-expenses-$SUFFIX" $SQL_DATABASE = "sqldb-bitoftech-expenses" |
Important note: $SUFFIX exists because some Azure names have to be unique across the whole of Azure, not just your subscription. A SQL server becomes <name>.database.windows.net, so it has to be. Change tj01 to something of your own or creation will fail telling you the name is taken.
Only globally unique names carry the suffix. The resource group and the database don’t need one, because they’re scoped to your subscription and to the server. We use exactly this pattern again in Part 8 for the container registry.
Step 2: Sign in and create the resource group
|
1 2 3 4 5 6 |
az login az account set --subscription $SUBSCRIPTION_ID az group create ` --name $RESOURCE_GROUP ` --location $LOCATION |
Step 3: Create the logical server
This is the part I’d encourage you not to skim, because it decides how the rest of the series handles secrets.
|
1 2 3 4 5 6 7 8 9 10 11 |
$MY_UPN = az ad signed-in-user show --query userPrincipalName -o tsv $MY_OID = az ad signed-in-user show --query id -o tsv az sql server create ` --name $SQL_SERVER ` --resource-group $RESOURCE_GROUP ` --location $LOCATION ` --enable-ad-only-auth ` --external-admin-principal-type User ` --external-admin-name $MY_UPN ` --external-admin-sid $MY_OID |
Let’s review the parameters:
--enable-ad-only-authturns off SQL username and password authentication completely. There is no admin password on this server, because there is no admin login to have one.--external-admin-nameand--external-admin-sidmake you the Microsoft Entra administrator. The two lines above fetch them so you don’t have to look them up.--external-admin-principal-typeisUserhere. It can also beGroup, which is what you’d want on a real team.
The reason this matters is that our connection string will contain no secret at all. Nothing to keep out of the repository, nothing to rotate, nothing to put in Key Vault. Part 8 gets the same benefit for free when the server runs in Azure with a managed identity.
Step 4: Open the firewall
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$MY_IP = (Invoke-RestMethod -Uri "https://api.ipify.org") az sql server firewall-rule create ` --resource-group $RESOURCE_GROUP ` --server $SQL_SERVER ` --name AllowMyMachine ` --start-ip-address $MY_IP ` --end-ip-address $MY_IP az sql server firewall-rule create ` --resource-group $RESOURCE_GROUP ` --server $SQL_SERVER ` --name AllowAzureServices ` --start-ip-address 0.0.0.0 ` --end-ip-address 0.0.0.0 |
The first rule lets your machine in. The second is the special “allow Azure services” rule, which we need in Part 8 when the server runs in a container.
Note: if you get “client IP is not allowed” later, your address has changed. Re-run the first command, the error message tells you the address it saw.
Step 5: Create the database
|
1 2 3 4 5 6 |
az sql db create ` --resource-group $RESOURCE_GROUP ` --server $SQL_SERVER ` --name $SQL_DATABASE ` --use-free-limit true ` --free-limit-exhaustion-behavior AutoPause |
Let’s review the two that matter:
--use-free-limit trueputs the database on the free offer, which gives you 100,000 vCore seconds and 32 GB a month at no charge.--free-limit-exhaustion-behavior AutoPausemeans that when you run out, the database pauses until next month rather than billing you.BillOverUsageis the other option.
Important note: you get one free database per subscription, and the first one fixes the region for any others. If the command fails saying you already have one, either use it or drop --use-free-limit and pick a paid tier.
Step 6: Build the connection string
|
1 2 |
$CONNECTION_STRING = "Server=tcp:$SQL_SERVER.database.windows.net,1433;Database=$SQL_DATABASE;Authentication=Active Directory Default;Encrypt=True;TrustServerCertificate=False;" $CONNECTION_STRING |
Authentication=Active Directory Default is what makes this work without a password. On your machine it uses whoever is signed in to the Azure CLI. In Part 8 the identical string uses the container’s managed identity. Same string, both places, no secret in either.
Moving the data into EF Core
Step 7: Add the packages
|
1 2 3 4 5 6 7 |
cd src/BitOfTech.Expenses.Mcp dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 10.0.12 dotnet add package Microsoft.EntityFrameworkCore.Design --version 10.0.12 dotnet add package Microsoft.Extensions.Http --version 10.0.12 dotnet tool install --global dotnet-ef |
Microsoft.Extensions.Http is for the Frankfurter client later. Design and the dotnet-ef tool are only needed to create and apply migrations.
Step 8: Write the DbContext
Delete Data/ExpenseStore.cs and add Data/ExpensesDbContext.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 |
using BitOfTech.Expenses.Mcp.Models; using Microsoft.EntityFrameworkCore; namespace BitOfTech.Expenses.Mcp.Data; public class ExpensesDbContext(DbContextOptions<ExpensesDbContext> options) : DbContext(options) { public DbSet<Employee> Employees => Set<Employee>(); public DbSet<ExpenseReport> Reports => Set<ExpenseReport>(); public DbSet<ExpenseLine> Lines => Set<ExpenseLine>(); protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Employee>(entity => { entity.Property(e => e.Name).HasMaxLength(200).IsRequired(); entity.Property(e => e.Email).HasMaxLength(320).IsRequired(); }); modelBuilder.Entity<ExpenseReport>(entity => { entity.Property(e => e.Title).HasMaxLength(200).IsRequired(); entity.Property(e => e.Currency).HasMaxLength(3).IsRequired(); entity.Property(e => e.TotalAmount).HasPrecision(18, 2); // Stored as text so the database is readable and the values survive reordering. entity.Property(e => e.Status).HasConversion<string>().HasMaxLength(20); entity.HasMany(e => e.Lines).WithOne().HasForeignKey(l => l.ExpenseReportId); entity.HasIndex(e => e.EmployeeId); entity.HasIndex(e => e.Status); }); modelBuilder.Entity<ExpenseLine>(entity => { entity.Property(e => e.Description).HasMaxLength(300).IsRequired(); entity.Property(e => e.Category).HasMaxLength(60).IsRequired(); entity.Property(e => e.Amount).HasPrecision(18, 2); }); Seed(modelBuilder); } } |
What we have done here is the following:
- The
DbSetnames areEmployees,ReportsandLines, which are the same names the oldExpenseStoreused. That’s not a coincidence, and it means the LINQ in the tools barely changes. HasConversion<string>()on the status storesSubmittedrather than1. Your database stays readable, and reordering the enum later can’t silently corrupt anything.HasPrecision(18, 2)on the money columns. Without it EF warns about precision loss and picks a default you didn’t choose.- The two indexes match the two things
search_expense_reportsfilters on.
The Seed method is the five reports from Part 2, moved into HasData. It’s long and not interesting, so I’ve left it in the repo rather than printing it here.
The models themselves don’t change at all. I wrote them in Part 2 knowing this was coming.
Step 9: Add the design time factory
Add Data/ExpensesDbContextFactory.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 |
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.Extensions.Configuration; namespace BitOfTech.Expenses.Mcp.Data; // dotnet ef needs a DbContext without running Program.cs, which would start the MCP // server and take over stdio. This factory gives it one. public class ExpensesDbContextFactory : IDesignTimeDbContextFactory<ExpensesDbContext> { public ExpensesDbContext CreateDbContext(string[] args) { var configuration = new ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory) .AddJsonFile("appsettings.json", optional: false) .AddEnvironmentVariables() .Build(); var connectionString = configuration.GetConnectionString("ExpensesDb") ?? throw new InvalidOperationException("ConnectionStrings:ExpensesDb is not set."); return new ExpensesDbContext( new DbContextOptionsBuilder<ExpensesDbContext>() .UseSqlServer(connectionString) .Options); } } |
This file exists for a reason specific to MCP servers. When you run dotnet ef, it normally finds your DbContext by running your application’s startup code. Our startup code begins talking MCP on standard input and output, so letting EF run it is a bad idea. The factory gives EF a DbContext without going anywhere near Program.cs.
Step 10: Put the connection string in configuration
Add appsettings.json next to Program.cs:
|
1 2 3 4 5 |
{ "ConnectionStrings": { "ExpensesDb": "Server=tcp:sql-bitoftech-expenses-tj01.database.windows.net,1433;Database=sqldb-bitoftech-expenses;Authentication=Active Directory Default;Encrypt=True;TrustServerCertificate=False;" } } |
Change the server name to yours. Then tell the build to copy it, in the csproj:
|
1 2 3 4 |
<ItemGroup> <Content Include="appsettings.json" CopyToOutputDirectory="PreserveNewest" /> <Content Include="Resources\policy.md" CopyToOutputDirectory="PreserveNewest" /> </ItemGroup> |
Note: this file is committed to the repository, which usually makes people uncomfortable. Look at what’s in it. A hostname, a database name and an instruction to use whoever is signed in. There’s no password because the server doesn’t have one. That’s the payoff from Step 3, and it’s the reason there’s no Key Vault, no user secrets and no environment variable juggling in this post.
Step 11: Create and apply the migration
|
1 2 |
dotnet ef migrations add InitialCreate dotnet ef database update |
Important note: if dotnet ef says “Build failed” and then dotnet build succeeds, check whether the MCP server is running in VS Code. A running server holds its own executable open, so the build can’t replace it, and the real reason is buried under ten retry warnings. Stop it from MCP: List Servers, run your migration, then start it again. This will catch you more than once.
Step 12: Wire it up
Program.cs changes. The first one is the line that creates the builder:
|
1 2 3 4 5 6 7 |
var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings { Args = args, // An MCP host starts us with whatever working directory it likes, so appsettings.json // has to be read from the folder the binary is in rather than the current directory. ContentRootPath = AppContext.BaseDirectory }); |
This one cost me an hour, so it’s worth explaining properly.
Host.CreateApplicationBuilder(args) looks for appsettings.json in the current working directory. For a console app you launch yourself, that’s usually the folder you’re standing in, and everything works. An MCP server isn’t launched by you. VS Code starts it with dotnet run --project ... and the working directory is the workspace root, which is two folders up from appsettings.json. The file is never found.
Configuration then returns null for the connection string, and nothing complains until the first query. You get this, from deep inside the SQL client:
|
1 |
System.InvalidOperationException: The ConnectionString property has not been initialized. |
What the model sees is worse. VS Code shows An error occurred invoking 'search_expense_reports' and nothing else, because the real exception isn’t an McpException. Setting ContentRootPath to AppContext.BaseDirectory points configuration at the folder the binary is in, which is where the csproj copies appsettings.json to.
Important note: this applies to anything else your server reads from disk. You cannot assume the working directory. It belongs to whoever started you.
Then the registrations:
|
1 2 3 4 5 6 7 8 |
builder.Services.AddDbContext<ExpensesDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("ExpensesDb"))); builder.Services.AddHttpClient<FrankfurterClient>(client => { client.BaseAddress = new Uri("https://api.frankfurter.dev/"); client.Timeout = TimeSpan.FromSeconds(10); }); |
The AddSingleton<ExpenseStore>() line is gone.
Note: AddDbContext registers the context as scoped, which in a web application means one per request. A stdio server has no requests, so it’s worth knowing what a scope is here. I checked, and the SDK creates one per tool call, so everything you already know about DbContext lifetime still applies.
Not returning your database tables
Here’s the problem I left in Part 2. Searching for Sara returned every line item of both her reports, 846 characters of JSON.
That costs you twice. You pay for every character in tokens, on every call, for as long as the server runs. And every field the model doesn’t need is another thing it can reason about wrongly. Part 1 made that argument with a hypothetical forty column table. This is the real one.
Step 13: Add contracts
Create a Contracts folder with ExpenseReportSummary.cs:
|
1 2 3 4 5 6 7 8 9 |
public record ExpenseReportSummary( int Id, string Title, string EmployeeName, ExpenseReportStatus Status, string Currency, decimal TotalAmount, DateOnly? SubmittedOn, int LineCount); |
And ExpenseReportDetail.cs:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public record ExpenseReportDetail( int Id, string Title, string EmployeeName, string EmployeeEmail, ExpenseReportStatus Status, string Currency, decimal TotalAmount, DateOnly? SubmittedOn, IReadOnlyList<ExpenseLineDetail> Lines); public record ExpenseLineDetail( string Description, string Category, decimal Amount, DateOnly IncurredOn); |
Two decisions worth naming:
- The summary has a
LineCountinstead of the lines. A search result should tell the model whether a report is worth opening, not hand it everything. - Both carry
EmployeeNamerather thanEmployeeId. The model can’t do anything with an integer foreign key, and asking it to make a second tool call to turn one into a name is a wasted round trip.
I could have added these in Part 2 and avoided the problem. I didn’t, because with five rows the entity was fine, and I wanted the reason for the change to be something you’d seen rather than something I asserted.
Step 14: Rewrite the read tools
Tools/ExpenseTools.cs. The constructor changes and the methods become async:
|
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 |
[McpServerToolType] public class ExpenseTools(ExpensesDbContext db) { [McpServerTool(Name = "search_expense_reports")] [Description("Searches expense reports by employee and by where they are in the approval workflow. Returns a summary of each match without the line items. Call get_expense_report when you need the lines.")] public async Task<IReadOnlyList<ExpenseReportSummary>> SearchExpenseReportsAsync( [Description("Part of an employee name, matched case insensitively. Omit to search across all employees.")] string? employeeName = null, [Description("Where the report sits in the approval workflow right now. Only use this when the question is about the current state. A report that was approved or rejected was also submitted at some point, so do not filter on Submitted to answer questions about what somebody has submitted.")] ExpenseReportStatus? currentStatus = null, CancellationToken cancellationToken = default) { var query = from report in db.Reports.AsNoTracking() join employee in db.Employees on report.EmployeeId equals employee.Id select new { Report = report, Employee = employee }; if (!string.IsNullOrWhiteSpace(employeeName)) { query = query.Where(x => x.Employee.Name.Contains(employeeName)); } if (currentStatus is not null) { query = query.Where(x => x.Report.Status == currentStatus); } return await query .OrderByDescending(x => x.Report.SubmittedOn) .Select(x => new ExpenseReportSummary( x.Report.Id, x.Report.Title, x.Employee.Name, x.Report.Status, x.Report.Currency, x.Report.TotalAmount, x.Report.SubmittedOn, x.Report.Lines.Count)) .ToListAsync(cancellationToken); } } |
What we have done here is the following:
ExpenseStorebecameExpensesDbContextin the constructor. That’s the whole migration, and it’s why I didn’t put an interface in front of the store back in Part 2. There was nothing to abstract.- The filters are the same LINQ as before. They now run in SQL instead of in memory.
Selectinto the summary happens in the database, so the line items are never fetched at all.Lines.Countbecomes a subquery.AsNoTracking()because nothing here is being changed.CancellationTokenis a normal parameter and the SDK supplies it. It does not appear in the JSON schema, so the model never sees it.
The description gained one sentence pointing at get_expense_report, because now that search returns less, the model needs to know where to get more.
Measured after the change: 352 characters instead of 846, for the same query. The gap widens with every row, because the old version grew with line items and this one doesn’t.
Tools that write
Step 15: Create a draft report
Every tool so far only reads. Nothing in the server can put a new row in the database, which means the only draft that exists is the one in the seed data. Submit it once and there is nothing left to demonstrate.
So the first write tool is the one that creates a report. It takes an employee, a title, a currency and the line items, and it saves all of that as a draft.
Add an input contract, Contracts/NewExpenseLine.cs:
|
1 2 3 4 5 |
public record NewExpenseLine( string Description, string Category, decimal Amount, DateOnly IncurredOn); |
Then the tool, in ExpenseTools.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 |
[McpServerTool(Name = "create_expense_report")] [Description("Creates a new expense report as a draft, together with its line items. A report cannot be edited after it is created. If the user did not give a title, or gave a date without a year, ask them for it before calling this tool rather than choosing a value yourself. The report is not submitted, so tell the user the new report id and ask whether they want it submitted, then call submit_expense_report.")] public async Task<ExpenseReportDetail> CreateExpenseReportAsync( [Description("Part of the name of the employee the report belongs to. Must match exactly one employee.")] string employeeName, [Description("A short title for the report, for example Berlin customer workshop.")] string title, [Description("Three letter ISO 4217 code the expenses were paid in, for example EUR.")] string currency, [Description("The line items on the report. At least one is required.")] IReadOnlyList<NewExpenseLine> lines, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(title)) { throw new McpException("The report needs a title. Ask the user what the expenses were for."); } if (lines is null or { Count: 0 }) { throw new McpException("An expense report needs at least one line item. Ask the user what they are claiming for."); } if (lines.Any(line => line.Amount <= 0)) { throw new McpException("Every line item must have an amount greater than zero."); } if (currency is null || currency.Trim().Length != 3) { throw new McpException("Currency must be a three letter ISO 4217 code, for example EUR."); } var matches = await db.Employees .Where(e => e.Name.Contains(employeeName)) .Select(e => new { e.Id, e.Name }) .ToListAsync(cancellationToken); if (matches.Count == 0) { throw new McpException($"No employee matches '{employeeName}'. Ask the user for the full name."); } if (matches.Count > 1) { var names = string.Join(", ", matches.Select(m => m.Name)); throw new McpException($"'{employeeName}' matches more than one employee: {names}. Ask the user which one they mean."); } var report = new ExpenseReport { EmployeeId = matches[0].Id, Title = title.Trim(), Currency = currency.Trim().ToUpperInvariant(), Status = ExpenseReportStatus.Draft, SubmittedOn = null, TotalAmount = lines.Sum(line => line.Amount), Lines = [.. lines.Select(line => new ExpenseLine { Description = line.Description.Trim(), Category = line.Category.Trim(), Amount = line.Amount, IncurredOn = line.IncurredOn })] }; db.Reports.Add(report); await db.SaveChangesAsync(cancellationToken); return await db.ReportDetail(report.Id).FirstAsync(cancellationToken); } |
Look at what this tool does not accept. No id, because the database assigns it. No status, because it is always a draft. And no total, because it is the sum of the lines.
A tool’s parameters are the entire extent of what the model can do. Anything you leave out is something it cannot do, no matter what it is asked. If status were a parameter, a model could file a report that was already approved. If totalAmount were a parameter, it could file one whose header disagreed with its lines. Neither is a hypothetical risk once you reach Part 10 and start thinking about prompt injection.
What the description has to carry
One sentence in the description does the mirror image of leaving a parameter out. “A report cannot be edited after it is created” is a fact about this server, because there’s no tool that updates one. The model can’t work that out for itself. It sees the tools it has, not a list of the things it can’t do, so it will cheerfully offer to change a title it made up for you.
The sentence after it does the real work. If there’s no title, or a date with no year, ask instead of picking something. The question then arrives before the row exists, rather than as a correction afterwards that the model has no way to make.
Be specific about which fields. “Confirm anything you’re unsure about” is the kind of instruction a model reads and skips, because it doesn’t consider a missing title to be something it was unsure about. It just fills one in. Naming the title and the missing year gives it two concrete things to check before it acts, and that’s the difference between the instruction working and being ignored.
The other thing worth looking at is what the SDK made of that lines parameter. Every tool so far has taken strings, numbers and enums. This one takes a list of objects:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
"lines": { "type": "array", "items": { "type": "object", "properties": { "description": { "type": "string" }, "category": { "type": "string" }, "amount": { "type": "number" }, "incurredOn": { "type": "string", "format": "date" } }, "required": ["description", "category", "amount", "incurredOn"] } } |
You didn’t write any of that. DateOnly even produced "format": "date" on its own, which tells the model what shape to send without you having to say so in a description.
The validation messages all end with an instruction, the same idea as Part 3. If you ask for a report for “a”, you get:
|
1 |
'a' matches more than one employee: Sara Haddad, Omar Nasser, Lina Farah. Ask the user which one they mean. |
Step 16: Submit it
A draft sits there until someone sends it for approval. That’s the second write tool, and it’s a much smaller piece of code because all it changes is a status and a date.
It’s also the first tool in the series with a consequence the user can’t take back, so the interesting part is what it refuses to do.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
[McpServerTool(Name = "submit_expense_report")] [Description("Submits a draft expense report for approval. Only works on a report that is still a draft, and it cannot be undone.")] public async Task<ExpenseReportDetail> SubmitExpenseReportAsync( [Description("The id of the draft expense report to submit.")] int reportId, CancellationToken cancellationToken = default) { var report = await db.Reports.FirstOrDefaultAsync(r => r.Id == reportId, cancellationToken) ?? throw new McpException( $"No expense report found with id {reportId}. Call search_expense_reports to find valid ids."); if (report.Status is not ExpenseReportStatus.Draft) { throw new McpException( $"Report {reportId} is {report.Status}, so it has already been submitted and cannot be submitted again."); } report.Status = ExpenseReportStatus.Submitted; report.SubmittedOn = DateOnly.FromDateTime(DateTime.UtcNow); await db.SaveChangesAsync(cancellationToken); return await db.ReportDetail(reportId).FirstAsync(cancellationToken); } |
Three things I’d do on any tool that writes:
- Say so in the description. “It cannot be undone” is there for the model, and for whatever approval interface ends up sitting in front of it.
- Guard the state, and explain the refusal. Submitting twice returns a message naming the current status, so the model can tell the user something useful instead of retrying.
- Return the new state. The model gets the updated report back and doesn’t have to call another tool to find out what happened.
Notice there’s no check on who is submitting. There’s no way to know yet. That’s Part 7.
Calling an API from a tool
A tool doesn’t have to read from your database. It’s just a method, so it can call anything your code can call, and most useful servers end up doing both.
Our reports are filed in whatever currency the employee spent in. Finance wants to see them in one currency, at the rate from the day the money was spent. That needs an exchange rate we don’t have, so we go and get it.
Step 17: A typed client
The HTTP call goes in its own class first. There’s no MCP in this file at all, and that’s deliberate – it’s an ordinary typed client you could lift into any project.
Services/FrankfurterClient.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 |
public class FrankfurterClient(HttpClient http) { public async Task<FrankfurterRate> GetRateAsync( string from, string to, DateOnly? onDate, CancellationToken cancellationToken) { var path = $"v2/rate/{Uri.EscapeDataString(from.Trim().ToLowerInvariant())}/{Uri.EscapeDataString(to.Trim().ToLowerInvariant())}"; if (onDate is not null) { path += $"?date={onDate:yyyy-MM-dd}"; } using var response = await http.GetAsync(path, cancellationToken); if (!response.IsSuccessStatusCode) { // Frankfurter returns a readable reason, for example "invalid currency: ZZZ". var error = await response.Content.ReadFromJsonAsync<FrankfurterError>(cancellationToken); throw new McpException(error?.Message is { Length: > 0 } message ? $"Exchange rate lookup failed: {message}" : $"Exchange rate lookup failed with status {(int)response.StatusCode}."); } return await response.Content.ReadFromJsonAsync<FrankfurterRate>(cancellationToken) ?? throw new McpException("The exchange rate service returned an empty response."); } } public record FrankfurterRate(DateOnly Date, string Base, string Quote, decimal Rate); public record FrankfurterError(int Status, string Message); |
Frankfurter publishes exchange rates from central banks. It needs no API key and has no quota, which is why I picked it. A request looks like this:
|
1 2 3 |
GET https://api.frankfurter.dev/v2/rate/eur/gbp?date=2026-09-02 {"date":"2026-09-02","base":"EUR","quote":"GBP","rate":0.85771} |
The error path is the part worth copying. Frankfurter returns a readable reason, and we pass it straight through to the model rather than replacing it with “the request failed”.
Step 18: The tool
Now the thin layer on top that turns the client into something a model can call. The descriptions carry the company rule about which rate to use, and the catch blocks decide what the model is told when the service is slow or down.
Tools/CurrencyTools.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 |
[McpServerToolType] public class CurrencyTools(FrankfurterClient frankfurter) { [McpServerTool(Name = "convert_currency")] [Description("Converts an amount between two currencies using published reference rates. Company policy converts at the rate for the date the expense was incurred, so pass that date rather than relying on today's rate.")] public async Task<CurrencyConversion> ConvertCurrencyAsync( [Description("The amount to convert, in the source currency.")] decimal amount, [Description("Three letter ISO 4217 code to convert from, for example EUR.")] string from, [Description("Three letter ISO 4217 code to convert to, for example GBP.")] string to, [Description("The date the expense was incurred, as yyyy-MM-dd. Omit only when the date is genuinely unknown, in which case the latest rate is used.")] DateOnly? onDate = null, CancellationToken cancellationToken = default) { try { var rate = await frankfurter.GetRateAsync(from, to, onDate, cancellationToken); return new CurrencyConversion( amount, rate.Base, rate.Quote, rate.Rate, rate.Date, Math.Round(amount * rate.Rate, 2, MidpointRounding.AwayFromZero)); } catch (TaskCanceledException) when (!cancellationToken.IsCancellationRequested) { throw new McpException( "The exchange rate service did not respond in time. Tell the user the converted amount is unavailable rather than estimating a rate."); } catch (HttpRequestException ex) { throw new McpException( $"Could not reach the exchange rate service: {ex.Message}. Tell the user the converted amount is unavailable rather than estimating a rate."); } } } |
Let’s review the parts that aren’t obvious:
- The tool description references company policy. Rule 1.1 of the expense policy from Part 3 says conversion uses the rate on the date of the expense. The description says the same thing, so the model passes
onDateinstead of quietly using today’s rate. - The result carries
RateDate, the date the rate actually applies to. The model can then say which rate it used rather than implying it used the one you asked for. - Both failure messages end with an instruction. “Tell the user the converted amount is unavailable rather than estimating a rate.” Without that, a model handed a failure will often produce a plausible looking number from its own training data. It’s the single most useful sentence in the file.
Here’s the tool converting the Berlin report:
|
1 2 |
{"amount":842.50,"from":"EUR","to":"GBP","rate":0.85771, "rateDate":"2026-09-02","convertedAmount":722.62} |
And here it is refusing:
|
1 |
Exchange rate lookup failed: invalid currency: ZZZ |
Trying it
Restart the server and ask Copilot something that needs more than one tool:
|
1 |
Omar filed a report for the London offsite. What did it cost in euros, using the rate from when it was incurred? |
That needs a search to find the report, a detail call to get the amount and date, and a currency conversion. You should see three tool calls in the response.
Then try creating one, and leave two things out on purpose:
|
1 |
Create an expense report for Lina. Flight to Madrid 198.40 euros and one night in a hotel 141 euros, both on 18 September. |
There’s no title in that sentence and no year on the date. Watch what the model does with it. No tool gets called. It comes back and asks for both, and it says why:
|
1 |
Two things I need before I create this, because a report can't be edited once it exists. |
That reason came from the tool description. Nothing else in the conversation mentions that reports are immutable.
Answer it, and the tool finally runs:
|
1 |
Title should be Madrid Trip Q3 2026, and the current year for sure. |
You get a new draft back with an id, the nested lines array filled in the way the schema asked for, and a question about submitting it.
Say yes and it calls submit_expense_report with the id it just got back:
|
1 |
Yes, submit it for approval. |
That’s the chain the descriptions were written for. create_expense_report told the model to offer the submission, and submit_expense_report told it the step cannot be undone. Neither tool knows the other exists in code. They only know about each other through the sentences we wrote.
Summary
The move from a list to a database was one constructor parameter, because there was no abstraction in the way. The interesting work was everything else: deciding what shape to hand the model, choosing which parameters to leave out, and writing failure messages that tell it what to do next.
If you take one thing from this post, make it the 846 characters becoming 352. Returning your entities is the default and it’s almost always wrong, because you pay for every field on every call and hand the model more chances to reason about the wrong one.
In Part 5 the server stops being a process on your machine. We move it to ASP.NET Core and Streamable HTTP, which is what lets anything other than your own editor connect to it.
The source code for this tutorial is available on GitHub.
Follow me on X @TJoudeh and on LinkedIn
References:
- Azure SQL Database free offer
- az sql db command reference
- Microsoft Entra authentication for Azure SQL
- EF Core, DbContext lifetime and configuration
- Frankfurter exchange rates API
- IHttpClientFactory in .NET



Leave a Reply