Function and tool calling in .NET: the model returns tool-call requests with JSON arguments, the app executes them; AIFunctionFactory, ChatOptions.Tools and UseFunctionInvocation; schemas from method signatures and descriptions; argument validation, authorisation in the tool, iteration limits, approval for side effects, and structured output.
With tool calling, you describe functions (name, description, JSON schema of parameters) in the request. The model can reply with a tool-call request instead of text; your app executes it and sends the result back, and the model continues. In Microsoft.Extensions.AI, AIFunctionFactory.Create turns a C# method into a tool, you pass it in ChatOptions.Tools, and UseFunctionInvocation() runs the loop.
The model chooses the arguments, so treat them as untrusted input: validate them, authorise against the signed-in user inside the tool, expose only least-privilege tools, require approval for side effects and cap iterations. The trade-off: tools make the model useful, but every tool widens what a confused or manipulated model can do.
"The model doesn't run anything. I send it the conversation plus a list of tool definitions, each a name, a description and a JSON schema for the parameters. If it decides a tool would help, the response contains a function-call request with the name and JSON arguments instead of text. My code runs the function, adds the result as a tool message, and calls the model again so it can use the result. In Microsoft.Extensions.AI,
AIFunctionFactory.Createbuilds the schema from my method signature and[Description]attributes, I put the functions inChatOptions.Tools, andUseFunctionInvocation()on the client pipeline does the call-and-resend loop for me, with a cap on iterations.The important part is that the arguments come from the model, which means they come indirectly from the user and from any document in the context. So I treat them exactly like a request body: validate types and ranges, and do authorisation inside the tool using the signed-in user from
HttpContext, never trusting an order id or customer id the model passed. For example, on [a customer-support assistant] we [exposed read-only order lookups first]; the lookup tool ignores any customer id from the model and always scopes to the authenticated customer, so a prompt like 'show me order 1234 for another customer' just returns nothing.The mistake I see is giving the model a generic tool like 'run SQL' or 'call any API'. I keep tools narrow and read-only by default; anything that changes data, like a refund, returns a proposal that the user confirms in the UI, and the actual change is idempotent. If I only need data extracted into a shape, I use structured output instead of tools. The model proposes; my code decides."
| Step | Who | What happens |
|---|---|---|
| 1 | App | Sends messages + tool definitions |
| 2 | Model | Returns FunctionCallContent (name, JSON args) or text |
| 3 | App | Validates, authorises, executes the C# method |
| 4 | App | Appends FunctionResultContent as a tool message, calls the model again |
| 5 | Model | Answers in text or requests another tool (bounded) |
| Rule | Why |
|---|---|
| Narrow, task-specific tools | Smaller blast radius, better tool selection |
| Clear descriptions and parameter names | The model chooses tools from the description |
| Scope by the authenticated user in code | Model-supplied IDs can be manipulated |
| Read-only by default; confirm writes | Prevents unintended changes |
| Return compact, non-sensitive results | Results go back into the prompt and the logs |
| Idempotency keys on writes | Retries and repeated calls don't double-apply |
On [the support assistant], tool calls handled [about 40%] of order-status questions without an agent. Average tool calls per conversation were [1.3], with MaximumIterationsPerRequest set to [5]. After adding schema validation and user scoping, [three] red-team prompts that previously exposed other customers' order data returned nothing.
Checks that the candidate understands tool calling mechanically and treats model-chosen arguments as untrusted.
Green flags
AIFunctionFactory, ChatOptions.Tools and UseFunctionInvocationRed flags
{
"tools": [{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Gets the status of one of the signed-in customer's orders.",
"parameters": {
"type": "object",
"properties": { "orderNumber": { "type": "string", "description": "Order number like SO-12345" } },
"required": ["orderNumber"]
}
}
}]
}
The model may respond with tool_calls: [{ name: "get_order_status", arguments: "{\"orderNumber\":\"SO-12345\"}" }]. Arguments are a JSON string generated token by token; they can be malformed or contain values outside your schema.
your call ─► FunctionInvokingChatClient ─► inner client ─► model
│ ◄── FunctionCallContent
├─ find AIFunction by name
├─ bind JSON args to parameters (System.Text.Json)
├─ invoke (with cancellation)
└─ append FunctionResultContent, call model again (until text or limit)
AIFunctionFactory.Create reflects over the delegate: parameter types become JSON schema, [Description] becomes descriptions, and CancellationToken and IServiceProvider parameters are supplied by the framework, not the model. FunctionInvokingChatClient exposes MaximumIterationsPerRequest, AllowConcurrentInvocation and IncludeDetailedErrors (keep that off in production so exception messages don't go to the model).
Models can request several calls in one turn ("check stock in Sydney and Melbourne"). Allow concurrency only for side-effect-free tools.
Treat the model like an untrusted client that can be talked into anything:
user text ─┐
documents ─┤─► model ─► tool call ─► [validate] ─► [authorise as signed-in user] ─► [execute] ─► result
emails ────┘ ▲ your code is the security boundary
That is the OWASP Top 10 for LLM Applications "excessive agency" risk: too much functionality, too many permissions, too much autonomy.
If you want data in a shape (extract invoice fields), use structured output: GetResponseAsync<Invoice>() sends a JSON schema and deserialises the reply. Tools are for when the model needs information or actions from your system mid-conversation.
Every tool round trip is another model call with the whole conversation resent. Three tool calls can triple latency and input tokens, so keep tool results compact and the loop bounded.
FunctionCallContent with its arguments.[Description] attributes and see tool selection get worse.MaximumIterationsPerRequest = 1 and observe the behaviour on a two-step question.GetResponseAsync<T>() for an extraction task and compare reliability.Read-only tool scoped to the signed-in customer, plus a write that only proposes.
// Packages: Microsoft.Extensions.AI, Microsoft.Extensions.AI.OpenAI, Azure.AI.OpenAI, Azure.Identity
using System.ComponentModel;
using System.Security.Claims;
using System.Text.RegularExpressions;
using Microsoft.Extensions.AI;
namespace Support.Assistant;
public sealed record OrderStatus(string OrderNumber, string Status, DateOnly? Eta);
public sealed record RefundProposal(string OrderNumber, decimal Amount, string Reason);
public interface IOrderRepository
{
Task<OrderStatus?> FindForCustomerAsync(string customerId, string orderNumber, CancellationToken ct);
}
public sealed partial class SupportTools(IOrderRepository orders, IHttpContextAccessor http)
{
// Identity comes from the authenticated request, never from model arguments.
private string CustomerId =>
http.HttpContext?.User.FindFirstValue(ClaimTypes.NameIdentifier)
?? throw new UnauthorizedAccessException();
[Description("Gets the status of one of the signed-in customer's orders.")]
public async Task<OrderStatus?> GetOrderStatus(
[Description("Order number, format SO-12345")] string orderNumber,
CancellationToken ct)
{
if (!OrderNumberRegex().IsMatch(orderNumber))
return null; // validate like any request input
return await orders.FindForCustomerAsync(CustomerId, orderNumber, ct);
}
[Description("Proposes a refund for the customer to confirm. Does not issue it.")]
public RefundProposal ProposeRefund(
[Description("Order number, format SO-12345")] string orderNumber,
[Description("Amount in AUD, 0.01 to 500")] decimal amount,
[Description("Short reason")] string reason)
{
if (!OrderNumberRegex().IsMatch(orderNumber) || amount is <= 0 or > 500m)
throw new ArgumentException("Invalid refund proposal.");
// The UI shows this; the real refund runs only after the user confirms.
return new(orderNumber, decimal.Round(amount, 2), reason[..Math.Min(reason.Length, 200)]);
}
[GeneratedRegex(@"^SO-\d{5}$")]
private static partial Regex OrderNumberRegex();
}
Wiring and calling:
// Program.cs
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<SupportTools>();
builder.Services
.AddChatClient(new AzureOpenAIClient(endpoint, new DefaultAzureCredential())
.GetChatClient("gpt-4.1-mini").AsIChatClient())
.UseFunctionInvocation(configure: c =>
{
c.MaximumIterationsPerRequest = 5; // bound the loop
c.IncludeDetailedErrors = false; // don't leak exception text to the model
})
.UseOpenTelemetry();
app.MapPost("/api/support/ask", async (AskRequest req, IChatClient chat, SupportTools tools, CancellationToken ct) =>
{
var options = new ChatOptions
{
Tools = [AIFunctionFactory.Create(tools.GetOrderStatus), AIFunctionFactory.Create(tools.ProposeRefund)]
};
var response = await chat.GetResponseAsync(
[new(ChatRole.System, "You help customers with their own orders."), new(ChatRole.User, req.Question)],
options, ct);
return Results.Ok(new { answer = response.Text });
}).RequireAuthorization();
public sealed record AskRequest(string Question);
IAuthorizationService for resource-based checks.MaximumIterationsPerRequest, timeouts and cancellation.IncludeDetailedErrors = true in production. Why it is wrong: exception messages and internals are sent to the model and may reach the user. Instead: return a generic error result and log details server-side.GetResponseAsync<T>().Design tools like a public API for an untrusted client, because that is what the model is. The security boundary is the tool implementation, not the system prompt. Start read-only, add writes with confirmation, and log every call with user, tool, arguments (redacted) and outcome so you can audit what the model did.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Read-only tools | Lookups, search, status | Low risk | Never a reason to skip auth scoping |
| Write tools with human confirmation | Refunds, bookings, updates | Extra UI step | High-volume automation with strong validation (then use workflows) |
| Structured output, no tools | Extraction, classification | One call | Needs live data mid-answer |
| Deterministic workflow calling the model | Known sequence of steps | More code | Open-ended tasks |
Measure tool-call rate, failure rate, iterations per request and token cost per conversation; a rising iteration count is often the first sign of confusing tool descriptions.
Use Microsoft.Extensions.AI: build an AzureOpenAIClient with the endpoint and DefaultAzureCredential, take the chat client for your deployment and call AsIChatClient(). Register it once with builder.Services.AddChatClient(...), which returns a ChatClientBuilder so you can add logging, OpenTelemetry and caching as middleware. In Azure the app's managed identity gets the Cognitive Services OpenAI User role, so there is no key anywhere.
For streaming, call GetStreamingResponseAsync and return the IAsyncEnumerable (or server-sent events) so the first words reach the browser in under a second. Pass RequestAborted as the cancellation token. The trade-off: streaming improves perceived latency but you can't validate the whole answer before the user sees it.
Structured output constrains the model's final answer to a JSON schema you send. Use it when you want data in a fixed shape: extract invoice fields, or classify a ticket with a reason. In the Microsoft.Extensions.AI package (the standard .NET AI abstractions), IChatClient.GetResponseAsync<T>() generates the schema from T and deserialises the reply into ChatResponse<T>. A valid shape can still hold wrong data, so validate the values (ranges, enums, totals that add up) with FluentValidation or data annotations, and retry or reject on failure.
Tools (function calling) are C# methods you describe to the model with AIFunctionFactory.Create. The model asks to call them mid-conversation to fetch live data ("look up order 123") or take an action, and your code runs them and returns the result. Use tools only when the model needs something it doesn't have. Structured output is one call with fewer failure modes than a tool loop.
How to tell it (STAR)
**S:** In a red-team exercise on our [support assistant], a tester got the order tool to return another customer's order with their address. **T:** I [owned the assistant's backend] and had to contain it and make sure it couldn't recur. **A:** I switched the tool off by feature flag within the hour, checked [90 days] of tool-call logs for real misuse, then changed the tool to take the customer from the authenticated claims, return only status and ETA, and added integration tests that try cross-customer lookups through the chat endpoint. **R:** The re-test passed, logs showed [no real exposure], so no notification was needed, and the checklist became mandatory for every new tool.
Last updated 23 Nov 2026.