📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How does function (tool) calling work with an LLM in .NET? Show how you describe C# methods as tools with Microsoft.Extensions.AI, let the model call them, validate the arguments, and stop it doing something it shouldn't.

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.

Mid-Level Coding Intermediate ai aspnet-core function-calling microsoft-extensions-ai security tool-calling

🎯 Key points

  • The model only requests a call: it returns a tool-call (name + JSON arguments); your app decides whether to run it, runs it, and sends the result back as a tool message
  • AIFunctionFactory.Create builds a JSON schema from the method signature plus [Description] attributes
  • ChatOptions.Tools lists available tools; UseFunctionInvocation() runs the call loop automatically
  • Arguments are untrusted input: validate types, ranges and formats like any request body
  • Authorise inside the tool from the authenticated principal (claims via IHttpContextAccessor, or IAuthorizationService for policies); query by (customerId from claims, id from model), never by model-supplied ids alone
  • Least privilege: only the tools this feature needs, read-only by default; side-effecting requests become proposals the user confirms, executed idempotently
  • Bound the loop (MaximumIterationsPerRequest, timeouts, cancellation) and audit every call: user, tool, redacted arguments, outcome, trace id via UseOpenTelemetry
  • For extracting data rather than acting, use structured output (GetResponseAsync<T>) instead of tools

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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.Create builds the schema from my method signature and [Description] attributes, I put the functions in ChatOptions.Tools, and UseFunctionInvocation() 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."


The loop

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)

Tool design rules

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate understands tool calling mechanically and treats model-chosen arguments as untrusted.

Green flags

  • States clearly that the app executes tools, not the model
  • Uses AIFunctionFactory, ChatOptions.Tools and UseFunctionInvocation
  • Scopes data by the authenticated user inside the tool
  • Confirmation for writes, iteration limits, logging
  • Knows when structured output is the better tool

Red flags

  • Gives the model a SQL or generic HTTP tool
  • Trusts IDs from the model
  • No limit on loops; no audit trail
  • Thinks the system prompt prevents misuse

📚 Learn in depth

1. What goes over the wire

{
  "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.

2. How Microsoft.Extensions.AI implements it

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

3. Parallel tool calls

Models can request several calls in one turn ("check stock in Sydney and Melbourne"). Allow concurrency only for side-effect-free tools.

4. Security model

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.

5. Tools vs structured output

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.

6. Cost and latency

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.

Try it yourself

  1. Build the example and log each FunctionCallContent with its arguments.
  2. Ask for another customer's order and confirm the tool returns nothing.
  3. Remove the [Description] attributes and see tool selection get worse.
  4. Set MaximumIterationsPerRequest = 1 and observe the behaviour on a two-step question.
  5. Replace a tool with GetResponseAsync<T>() for an extraction task and compare reliability.

💻 Code

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);

⚠ Common mistakes

  • Mistake: Believing the model executes the function. Why it is wrong: it only requests a call; your code runs it and is responsible. Instead: put validation, authorisation and logging in the tool.
  • Mistake: Trusting IDs in the arguments. Why it is wrong: a user (or an injected document) can make the model pass someone else's ID. Instead: scope every query by the authenticated user from the request claims, and use IAuthorizationService for resource-based checks.
  • Mistake: Generic, powerful tools ("execute SQL", "call HTTP"). Why it is wrong: excessive agency: one manipulated turn can do anything. Instead: narrow, task-specific, read-only tools.
  • Mistake: Wiring a write tool so that the model's request is executed immediately. Why it is wrong: the model can't write anything itself, but if the app runs every requested write without checks, a mistake or an injected instruction changes real data. Instead: the tool returns a proposal, the user confirms in the UI, and only then does the app validate and execute it idempotently.
  • Mistake: No iteration limit. Why it is wrong: tool loops burn tokens and time. Instead: MaximumIterationsPerRequest, timeouts and cancellation.
  • Mistake: Returning whole entities as tool results. Why it is wrong: sensitive fields go into the prompt and logs, and tokens are wasted. Instead: return compact, purpose-built records.
  • Mistake: No audit trail of tool calls. Why it is wrong: when something goes wrong you can't tell what the model asked for or for whom. Instead: log user id, tool, redacted arguments, result status and trace id for every call, and alert on anomalies such as owner mismatches.
  • Mistake: 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.
  • Mistake: Using tools for pure extraction. Why it is wrong: more round trips and more failure modes. Instead: structured output with GetResponseAsync<T>().

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions UseFunctionInvocation or the client pipeline Why: Checks the basic client wiring and pipeline the tool loop runs in
    How to answer

    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.

  2. When: Candidate mentions extracting data with a tool Why: Checks they pick the simplest mechanism for the job
    How to answer

    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.

🛠 Real-world problems: how you handle them

Assistant exposed other customers' order details through a tool
Situation
[A customer-support chat] for [an online retailer with about 200k customers] had an order-lookup tool that took an order number from the model. A security tester showed it would return any customer's order, including [delivery address], creating a potential notifiable data breach under the Privacy Act.
Signals
Red-team report with a transcript; Application Insights traces showing `get_order` calls with order numbers not owned by the session's customer; no alerts had fired.
Investigation
Queried tool-call telemetry (tool name, arguments, user id) for mismatches between order owner and caller, using the OpenTelemetry gen_ai spans and our audit log. Reviewed the tool: it called the repository by order number only. Checked whether real customers had exploited it: [no matches outside the tester's account in 90 days of logs].
Resolution
Disabled the tool within the hour via feature flag. Rewrote it to take the customer id from the authenticated claims and query by (customerId, orderNumber); trimmed the result to status and ETA only (no address). Re-enabled after tests and a re-test by the security team.
Prevention
Integration tests that attempt cross-customer lookups through the chat endpoint; a tool-design checklist (identity from context, minimal result, read-only by default); prompt-injection and authorisation cases added to the AI evaluation suite run in CI; tool-call audit log with an alert on owner mismatches.

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.

↩ Usually asked after

More in .NET and AI

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me