Introduction
When adding AI to an existing application, giving the model a database connection string or an endpoint that executes generated SQL creates a second route to business data. That route can bypass the services where application access rules are already enforced.
A read-only database credential is not enough to reproduce application-level permissions. It does not automatically understand tenant boundaries, record-level access, user roles, or business rules.
For ASP.NET Core AI integration, a safer approach is to let the model request an operation, while the application decides how that operation is executed.
This article demonstrates that approach using a customer-support copilot architecture. The assistant uses native tools to retrieve permitted customer information, order status, and company knowledge. Existing .NET services continue to enforce Identity roles and tenant filters.
The key principle is simple:
The model can request an operation, but the application remains responsible for authorization, validation, and execution.
What Native Tool Calling Means
Native tool calling means the model returns a structured request containing a registered function name and its arguments.
The application receives that request, validates it, executes the corresponding operation, and sends the result back to the model.
The model does not execute C# code itself.
For an order-related question, the flow can look like this:
User
↓
AI Model
↓
Tool Call: GetOrderStatus
↓
ASP.NET Core Tool Executor
↓
Existing Order Service
↓
Identity + Tenant Authorization
↓
Database
↓
Tool Result
↓
AI Model
↓
Response DraftFor example, instead of allowing the model to generate SQL such as:
SELECT *
FROM Orders
WHERE Id = 123;the model requests:
GetOrderStatus(orderId = 123)The application then decides whether the request is valid and whether the authenticated user is allowed to access that order.
The model decides that it needs information.
The application decides:
Whether the requested tool exists
Whether the arguments are valid
Who is making the request
Which tenant the request belongs to
Whether the operation is authorized
Which data can be returned
Defining Tools for ASP.NET Core AI Integration
Each tool needs three basic pieces of information:
A tool name
A focused description
A schema describing its arguments
The following .NET 8 examples use simplified service interfaces around an existing ASP.NET Core Identity and EF Core setup.
The imports used across the samples are:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;The tool definitions can remain independent of a specific AI provider:
public sealed record ToolDefinition(
string Name,
string Description,
JsonElement Parameters);
public static class ToolCatalog
{
public static readonly ToolDefinition[] All =
[
Define(
"GetCustomer",
"Read a customer by a known customer ID.",
"customerId",
"integer"),
Define(
"GetOrderStatus",
"Read the current status of a known order.",
"orderId",
"integer"),
Define(
"SearchKnowledgeBase",
"Search company policies and procedures.",
"query",
"string")
];
private static ToolDefinition Define(
string name,
string description,
string argument,
string type) =>
new(
name,
description,
JsonSerializer.SerializeToElement(new
{
type = "object",
properties = new Dictionary<string, object>
{
[argument] = new { type }
},
required = new[] { argument },
additionalProperties = false
}));
}A provider adapter can map these definitions into the native function-tool format required by the selected model provider.
For providers that support strict structured outputs, the adapter can enable strict schema validation and ensure that required properties and additionalProperties: false are configured according to the provider's requirements.
The important design principle is that the tool definition describes what the application can retrieve, not how the underlying storage is queried.
The contract can remain stable even if the service implementation changes.
There is no SQL argument, table name, tenant override, or permission flag.
Positive IDs and search-length limits are validated in .NET before execution.
Mapping Tool Calls to Existing Services
The tool executor should use an explicit allowlist.
It should not discover methods through reflection or execute a model-supplied expression.
The service contracts return small DTOs rather than exposing EF Core entities directly.
public sealed record CustomerSummary(
int Id,
string Name);
public sealed record ToolCall(
string Name,
string ArgumentsJson);
public sealed record ToolResult(
bool Success,
object? Data,
string? Error)
{
public static ToolResult Fail(string code) =>
new(false, null, code);
public static ToolResult From(object? value) =>
value is null
? Fail("not_available")
: new(true, value, null);
}
public sealed class ToolExecutor(
ICustomerService customers,
IOrderService orders,
IKnowledgeSearchService knowledge,
ToolArguments arguments,
ILogger<ToolExecutor> logger)
{
public async Task<ToolResult> ExecuteAsync(
ToolCall call,
CancellationToken ct)
{
try
{
return call.Name switch
{
"GetCustomer" => ToolResult.From(
await customers.GetByIdAsync(
arguments.PositiveId(
call.ArgumentsJson,
"customerId"),
ct)),
"GetOrderStatus" => ToolResult.From(
await orders.GetStatusAsync(
arguments.PositiveId(
call.ArgumentsJson,
"orderId"),
ct)),
"SearchKnowledgeBase" => ToolResult.From(
await knowledge.SearchAsync(
arguments.Query(call.ArgumentsJson),
ct)),
_ => ToolResult.Fail("unknown_tool")
};
}
catch (JsonException)
{
return ToolResult.Fail("invalid_arguments");
}
catch (UnauthorizedAccessException)
{
return ToolResult.Fail("not_available");
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
logger.LogError(
"Tool {Tool} failed: {ErrorType}",
call.Name,
ex.GetType().Name);
return ToolResult.Fail("tool_failed");
}
}
}The executor is an internal application component. It should not be exposed as a public endpoint that accepts arbitrary tool requests from clients.
It uses the same scoped services as the rest of the application.
The returned data should also be deliberately narrow.
For example, an order-status lookup might return:
Order ID
Order Statusrather than an entire EF Core entity with every related property.
Similarly, a knowledge search can return only the relevant passages and their source information.
The service controls the projection. The model cannot request additional database columns or navigation properties.
After execution, the provider adapter serializes ToolResult into the provider's native tool-result format.
Provider-specific correlation information should remain inside the provider adapter. The normalized ToolCall is used for application-level dispatch, while the adapter can retain the provider's original call identifier where required.
Where Permissions Live
User identity and tenant membership should come from the authenticated ASP.NET Core request context.
They should not be supplied by the model.
With ASP.NET Core Identity already configured, a role policy and scoped access helper can be registered:
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<RequestAccess>();
builder.Services.AddAuthorization(options =>
options.AddPolicy(
"Support.Read",
policy => policy
.RequireAuthenticatedUser()
.RequireRole("Admin", "SupportAgent")));Either named role satisfies this policy.
Resource-level access remains the responsibility of the business service.

Join the conversation! Your thoughts help the community grow.