Skip to main content
Version: Latest

Custom AI Tools

Register functions that the AI model can invoke during orchestration using the fluent builder pattern.

Quick Start​

builder.Services
.AddCoreAIServices()
.AddCoreAIOrchestration()
.AddCoreAITool<WeatherTool>("get-weather")
.WithTitle("Get Weather")
.WithDescription("Returns current weather for a location.")
.WithCategory("Utilities")
.Selectable();

Problem & Solution​

AI models can call functions (tools) to access external data or perform actions. The framework needs a way to:

  • Register tools with metadata (name, description, category)
  • Classify tools as system (auto-included) or selectable (user-assignable)
  • Scope tools dynamically based on context (profile, session, available data)
  • Control access to tools based on permissions or context

The tool builder pattern provides a fluent API for all of this.

Tool Types​

TypeRegistrationVisibilityUse Case
Selectable.Selectable()Visible in UI for profile assignmentUser-facing tools (calculator, search)
Hidden.Hidden()Not shown in the picker or generic public exports; usable only when a profile or agent names it explicitlyPrivate helper tools for specialized agents
SystemDefault (no .Selectable())Hidden, auto-included by orchestratorInternal tools (RAG search, image gen)

Fluent Builder API​

AddCoreAITool<TTool>(name)​

Returns an AIToolBuilder<TTool> for fluent configuration:

MethodDescription
.WithTitle(string)Display title in UI
.WithDescription(string)Description shown to the AI model
.WithCategory(string)UI grouping category
.WithPurpose(string)Semantic purpose tag (see below)
.WithDependency(string) / .WithDependencies(params string[])Registers dependency tools that should be added automatically
.WithoutDependency(string) / .WithoutDependencies(params string[])Removes previously registered dependency tools
.Hidden()Makes the tool private to explicitly named profiles or agents and excludes it from picker-style/public export surfaces
.Selectable()Makes the tool visible in UI and assignable to profiles
.RequireApproval()Asks the user to approve each call before it runs, in chat runs that can ask (AG-UI runs). Where nobody can be asked (other chats, realtime, workflows, background work), the tool does not run, and the model is told why. .RequireApproval(false) lets a tool run without asking. See AG-UI tool approvals
.AsRead() / .AsWrite() / .AsDestructive() / .AsExternal() / .AsSecurity()Says what the tool does (its kind). See Tool Kinds
.WithKind(AIToolKind)Sets the kind from a value
.WithAlias(string, bool grantsAccess = false) / .WithAliases(params string[])Adds an earlier name of the tool, so stored references keep working; grantsAccess: true also carries the earlier name's access (for a rename). See Renaming a Tool

Tool Kinds​

A kind says what a tool does to the application's data and to the outside world. Hosts use it to decide from data which tools need an approval and which tools a setting that exposes every tool leaves out.

KindBuilder methodMeaningNeeds an approval
Read.AsRead()Returns data and changes nothingNo
Write.AsWrite()Creates or changes data that can be changed backNo
Destructive.AsDestructive()Deletes data, or cannot be undoneYes
External.AsExternal()Sends something outside the application (an email, a text message, a call, a webhook), calls a paid service, or moves moneyYes
Security.AsSecurity()Changes who can access what, how people sign in, secrets, or what code or templates the application runsYes
builder.Services
.AddCoreAITool<ListOrdersTool>("listOrders")
.AsRead()
.Selectable();

builder.Services
.AddCoreAITool<DeleteOrderTool>("deleteOrder")
.AsDestructive()
.Selectable();

The kind does these things:

  • A Destructive, External or Security tool requires an approval, as if its registration called .RequireApproval(). Call .RequireApproval() for the exceptions: on a tool of another kind that should ask, or as .RequireApproval(false) on a tool of one of these kinds that should not ask. The explicit call wins, whichever is called first.
  • ExposeAllTools of the MCP server and of WebMCP leaves out the Destructive and Security tools, and every tool that requires an approval (so External tools too, unless they call .RequireApproval(false)), because their clients call a tool directly and cannot be asked. Name such a tool in the Tools list to expose it.
  • The MCP server tells its clients the kind through the MCP tool annotations (readOnlyHint, destructiveHint, openWorldHint), and the WebMCP tool list has a kind value for each tool.
  • AIToolDefinitionEntry.Kind and ToolRegistryEntry.Kind carry the kind, so a tool picker or a custom tool pipeline can read it.

A tool registered without a kind has AIToolKind.Unspecified and behaves as before: it asks for an approval only when its registration calls .RequireApproval(), and ExposeAllTools includes it unless it does. An approval is a confirmation for the person in the chat, not an access check. Callers that cannot ask for an approval are described in AG-UI tool approvals.

Running a Profile's Tools Without Asking​

A profile's AIToolApprovalSettings (stored in AIProfile.Settings) can let the tools that require an approval because of their kind run without asking. A rule per kind sets the ToolApprovalMode:

profile.AlterSettings<AIToolApprovalSettings>(settings =>
{
settings.Kinds[nameof(AIToolKind.External)] = new ToolApprovalRule { Mode = ToolApprovalMode.Never };
});

// Or every kind that requires an approval (Destructive, External and Security):
profile.AlterSettings<AIToolApprovalSettings>(settings => settings.SetRunAllWithoutAsking(true));
ModeWhat it does
EveryCall (the default, and a kind with no rule)Asks before every call.
OncePerSessionReserved for session grants. Until they exist, it asks before every call.
NeverRuns without asking. Each call is logged at Information level and counted in AITelemetry.ToolAutoApprovals.

The MVC and Blazor sample hosts show it in the AI Tools section of the profile editor's Capabilities tab, as Tool approval: Ask for approval (recommended), the default, or Allow all tools without asking (Never for Destructive, External and Security).

SettingA tool that requires an approval because of its kind, where a person can be asked (an AG-UI chat run)Where nobody can be asked (see Callers that cannot be asked)
Ask for approval (default)Asks first: Allow or DenyDoes not run, and the model is told why
Allow all tools without askingRuns at onceRuns at once
  • A tool's own floor is never lowered. A tool registered with an explicit .RequireApproval() (AIToolDefinitionEntry.RequiresApprovalExplicit), and a consequential WebMCP page tool while Allow consequential page tools is off, have an approval floor (ToolRegistryEntry.ApprovalFloor): they ask, whatever the profile says.
  • Inside an agent, the stricter side wins. A call an agent makes runs without asking only when both the agent's profile and the profile that calls it allow it (ToolApprovalPolicy.ForAgent). An agent set to Allow all still asks when its caller asks, so one shared or always-available agent cannot take approvals away from the profiles that use it. A caller with no profile, such as an MCP client that calls the agent directly, allows nothing.
  • Each call is audited. A tool that runs without asking is wrapped so that every call writes an Information log (the tool, its kind, whether an agent made the call, and the chat session) and adds to the crestapps.core.ai.tool.auto_approved counter, tagged with the reason, the tool kind and whether an agent made the call. A tool that is not an AIFunction cannot be audited, so it is still left out.
  • Only the approval is skipped. The profile still has only the tools picked for it, and the access checks are unchanged: a Chat Interaction checks each listable tool it picked with IAIToolAccessEvaluator, and an AI Session runs the profile's tools as configured. An agent's tools follow the agent, not the person who reaches it, so control who can use an agent that runs its tools without asking.
  • AIProfileCompletionContextBuilderHandler resolves each profile's settings into a ToolApprovalPolicy under AICompletionContextKeys.ToolApprovalPolicy (read it with GetToolApprovalPolicy()), and the tool pipeline passes it to the tool materializer as ToolMaterializationOptions.ApprovalPolicy.
  • It does not change ExposeAllTools of the MCP server or WebMCP, nor the post-session tasks, where a tool that requires an approval never runs.

Turn it on only for a profile whose tools are safe to run unchecked wherever the profile is used: with it, a tool that sends, changes or deletes things also runs for a caller that nobody watches, and content the model reads (a document, a web page, an email) can lead it to call one.

Callers that cannot be asked​

An approval needs a person who can click Allow or Deny. These callers have none, so where a profile asks, the answer is no: a tool that requires an approval does not run, and the model is told why.

CallerWhat it isAsk for approval (default)Allow all tools without asking
MCP client calling an agentAnother app, such as VS Code or Claude Desktop, calls one of your agents through the MCP serverThe agent's tools that require an approval do not runStill do not run: there is no calling profile, and inside an agent the stricter side wins
MCP client calling a toolThe MCP server exposes a tool itself, not through a profileThe profile setting does not apply. ExposeAllTools leaves the tool out; a tool named in the Tools list runs, because naming it is the host's decisionSame
A2A clientAnother AI agent calls one of your agents through the A2A hostThe sample hosts' A2A host runs the agent with its tools turned off, so no tool runs. A host that turns them on follows this tableSame in the sample hosts: no tool runs
A2A connectionYour profile calls a remote agent, picked on the Capabilities tabThe remote agent runs on its own system, under that system's rulesSame
VoiceA realtime voice conversationThe tool does not runIt runs

The text-only chat stream, the Claude and Copilot orchestrators, workflows, channels such as SMS and background work cannot ask either, and follow the same rule.

Asking through these callers is not built. MCP elicitation and the A2A input-required task state could carry an approval later, and a voice session could ask out loud.

Renaming a Tool​

Tool names are stored: on AI profiles and templates, on chat interactions, in the Tools lists of the MCP server and WebMCP settings, and in whatever a host derives from them (such as a permission for each tool). Give a renamed tool its earlier name as an alias, and the stored names keep working:

builder.Services
.AddCoreAITool<ListUsersTool>("listUsers")
.WithAlias("searchForUsers", grantsAccess: true)
.Selectable();
  • A profile, template or chat interaction that still stores searchForUsers gets the listUsers tool. The model sees the tool under its current name.
  • A Tools list of the MCP server or WebMCP settings that still names searchForUsers still exposes the tool.
  • A dependency declared with the earlier name (.WithDependency("searchForUsers")) still resolves.
  • With grantsAccess: true, the access check accepts the earlier name: when IAIToolAccessEvaluator authorizes the tool's name or that alias, the user may use the tool. A host that grants access by tool name therefore does not have to grant it again after a rename.
  • Listings show the tool once, under its current name. AIToolDefinitionOptions.Tools and GetSelectableTools() do not list aliases.

Pass grantsAccess: true only for a rename, where the tool does what the earlier name did. When a narrower tool is merged into a broader one (a read-only getOrder into a manageOrder that can also cancel orders), add the earlier name with .WithAlias("getOrder") alone: stored names still resolve, but a role granted only getOrder does not get manageOrder. .WithAliases(...) adds aliases without access. AIToolDefinitionEntry.AccessAliases lists the aliases that carry access.

To look a tool up by a name that may be an alias, use AIToolDefinitionOptions.TryGetTool(nameOrAlias, out definition). ResolveToolName and ResolveToolNames return the current names for stored names. IAIToolsService.GetByNameAsync also accepts an alias. A tool is registered as a keyed AITool under its current name only, so code that resolves GetKeyedService<AITool>(name) itself resolves the name with ResolveToolName first.

An alias must not be the name or an alias of another tool. When it is, the tool definitions fail to build with an InvalidOperationException that names both tools. This happens the first time the application reads AIToolDefinitionOptions, which is at startup or on the first request that uses AI tools. Call .WithAlias(...) once for each earlier name. When no stored data uses an earlier name anymore, remove the alias.

Tool Purposes​

Purpose tags allow the orchestrator to include tools automatically based on context:

ConstantValueWhen Auto-Included
AIToolPurposes.ContentGeneration"ContentGeneration"When the model wants to generate images or charts
AIToolPurposes.DocumentProcessing"DocumentProcessing"When documents are attached to the session
AIToolPurposes.DataSourceSearch"DataSourceSearch"When data sources are configured

Tool Dependencies​

Use dependencies when one tool expects another tool to be present in the same completion.

builder.Services
.AddCoreAITool<CreateContentItemTool>("create_content_item")
.WithTitle("Create Content Item")
.WithDescription("Creates a content item from validated structured input.")
.WithDependency("get_content_item_schema")
.Selectable();

builder.Services
.AddCoreAITool<GetContentItemSchemaTool>("get_content_item_schema")
.WithTitle("Get Content Item Schema")
.WithDescription("Returns the schema and required fields for a content type.");

When create_content_item is selected, CrestApps.Core automatically expands the tool set to include get_content_item_schema when that dependency is registered. The same dependency expansion is also applied when built-in system-tool selection brings in a tool with registered dependencies.

Dependency behavior:

  • missing dependencies are ignored safely
  • shared and circular dependency graphs are deduplicated
  • profiles and chat interactions only need to store the top-level tool name
  • dependency tools can stay hidden system tools when they should not be assigned directly in the UI

Implementing a Tool​

Tools inherit from AITool (which extends AIFunction from Microsoft.Extensions.AI):

public sealed class WeatherTool : AITool
{
public const string TheName = "get-weather";

// Tool parameters are defined as a record or class
private sealed record WeatherInput(string Location, string Units = "celsius");

protected override async ValueTask<object> InvokeCoreAsync(
AIFunctionArguments arguments,
CancellationToken cancellationToken)
{
var input = arguments.Deserialize<WeatherInput>();
// Call weather API...
return new { Temperature = 22, Condition = "Sunny", Location = input.Location };
}
}

Register it:

builder.Services
.AddCoreAITool<WeatherTool>(WeatherTool.TheName)
.WithTitle("Weather")
.WithDescription("Gets current weather for a location.")
.WithCategory("Utilities")
.Selectable();

Tool Access Control​

Tool access is governed differently for the two ways the AI is invoked.

AI Sessions — the profile is the authorization boundary​

For an AI Session, the AI Profile is the authorization boundary. A profile only exposes the tools its author selected — the profile-selected functions, the MCP connections attached to the profile, and the context-driven system tools. Every one of those is curated by an operator when the profile is configured. If a caller is allowed to run a session against a profile, they are allowed to use the tools that profile exposes; the runtime does not apply a per-user gate. This matters because a session may be anonymous — it runs the profile exactly as configured.

Access is therefore decided where the profile (and which tools it may contain) is configured — for example, the profile's Capabilities tab in the consuming application — rather than at completion time. Profile editors already list only selectable (non-system, non-hidden) tools; consuming applications own that selection UI and any permission checks around it.

Chat Interactions — IAIToolAccessEvaluator re-verifies listable tools​

A Chat Interaction is different: there is no session. Each interaction persists its own settings (model, prompt, and the selected tool names) and starts a chat from them. Because those saved tool names are attacker-controllable, a caller who tampered with an interaction could reference a selectable tool they were never granted. To close that gap, when a Chat Interaction sends a message the completion pipeline re-checks every listable (user-selectable) tool against IAIToolAccessEvaluator:

public interface IAIToolAccessEvaluator
{
Task<bool> IsAuthorizedAsync(ClaimsPrincipal user, string toolName);
}

Tools the caller is not authorized for are excluded from the request (and reported in a single Warning log entry) rather than failing it. Only listable tools are checked — system tools (auto-injected by the orchestrator) and hidden/dependency tools are never subject to the check. A null caller (a trusted server-side invocation such as a background task) skips the check entirely.

The default implementation permits every tool. Consuming applications that enforce per-user tool permissions replace it with an authorization-aware implementation, using the same permission model that backs the Chat Interaction tool-selection UI.

IUserAccessor​

The caller principal used by the completion pipeline (for auditing, rate limiting, and any host-side policy) comes from IUserAccessor, not from IHttpContextAccessor:

public interface IUserAccessor
{
ClaimsPrincipal User { get; set; }
}

It follows the same shape as IHttpContextAccessor. The default implementation resolves the caller in two steps:

  1. If a principal was assigned on the current asynchronous flow, that principal wins.
  2. Otherwise it falls back to HttpContext.User for ordinary HTTP requests.

This indirection exists because IHttpContextAccessor.HttpContext is unreliable inside SignalR hub invocations. Long-lived transports such as WebSockets, backplane-delivered invocations, and hosted SignalR services all run hub methods outside the request that opened the connection, so the accessor is frequently null there. The built-in hubs therefore assign Context.User at the start of every invocation:

userAccessor.User = Context.User;

await DoWorkAsync();

The principal is tracked with an AsyncLocal<T>, exactly as HttpContextAccessor tracks the current request, so the assignment is confined to the invocation that made it. Concurrent connections never observe one another's caller, and the value does not leak back to the caller of the method that assigned it.

:::info Null means "no caller" User returns null only when there is no caller at all, such as a background task, a workflow, or a recipe running server-side. An unauthenticated caller is different: hubs and HTTP requests always provide a non-null ClaimsPrincipal with an unauthenticated identity. :::

Custom hosts that invoke completions outside of an HTTP request or a hub should assign the caller themselves so host-side policy sees the right principal.

Custom Tool Registry Provider​

Supply tools from an external source (database, API, etc.):

public sealed class MyToolRegistryProvider : IToolRegistryProvider
{
public async ValueTask<IEnumerable<AIToolMetadataEntry>> GetToolsAsync(
AICompletionContext context,
CancellationToken cancellationToken = default)
{
// Return tools dynamically based on context
}
}

// Register
builder.Services.AddScoped<IToolRegistryProvider, MyToolRegistryProvider>();

Complex Tool Example​

A tool that queries an external API with nested object parameters, async operations, and error handling:

public sealed class OrderLookupTool : AITool
{
public const string TheName = "lookup-order";

private sealed record OrderQuery(
string OrderId,
CustomerFilter Customer = null,
bool IncludeLineItems = true);

private sealed record CustomerFilter(
string Email = null,
string Phone = null);

protected override async ValueTask<object> InvokeCoreAsync(
AIFunctionArguments arguments,
CancellationToken cancellationToken)
{
var logger = arguments.Services.GetRequiredService<ILogger<OrderLookupTool>>();
var httpClientFactory = arguments.Services.GetRequiredService<IHttpClientFactory>();

// Deserialize nested parameters
var query = arguments.Deserialize<OrderQuery>();

if (string.IsNullOrEmpty(query?.OrderId) && query?.Customer is null)
{
logger.LogWarning("AI tool '{ToolName}' requires an order ID or customer filter.", Name);
return "Please provide either an order ID or customer information (email or phone).";
}

try
{
var client = httpClientFactory.CreateClient("OrderApi");

HttpResponseMessage response;

if (!string.IsNullOrEmpty(query.OrderId))
{
response = await client.GetAsync(
$"/api/orders/{Uri.EscapeDataString(query.OrderId)}?includeItems={query.IncludeLineItems}",
cancellationToken);
}
else
{
var searchParams = new Dictionary<string, string>();

if (!string.IsNullOrEmpty(query.Customer?.Email))
{
searchParams["email"] = query.Customer.Email;
}

if (!string.IsNullOrEmpty(query.Customer?.Phone))
{
searchParams["phone"] = query.Customer.Phone;
}

var queryString = string.Join("&",
searchParams.Select(kvp => $"{kvp.Key}={Uri.EscapeDataString(kvp.Value)}"));

response = await client.GetAsync(
$"/api/orders/search?{queryString}",
cancellationToken);
}

if (!response.IsSuccessStatusCode)
{
logger.LogWarning(
"Order API returned {StatusCode} for tool '{ToolName}'.",
response.StatusCode, Name);

return response.StatusCode == System.Net.HttpStatusCode.NotFound
? "No order found matching the provided criteria."
: "Unable to look up the order at this time. Please try again later.";
}

var order = await response.Content.ReadFromJsonAsync<JsonElement>(
cancellationToken: cancellationToken);

return order;
}
catch (TaskCanceledException)
{
logger.LogWarning("Order API timed out for tool '{ToolName}'.", Name);
return "The order lookup timed out. Please try again.";
}
catch (Exception ex)
{
logger.LogError(ex, "Unhandled exception in tool '{ToolName}'.", Name);
return "An error occurred while looking up the order.";
}
}
}

Register it:

builder.Services
.AddCoreAITool<OrderLookupTool>(OrderLookupTool.TheName)
.WithTitle("Order Lookup")
.WithDescription("Looks up an order by ID or customer email/phone. Returns order details and line items.")
.WithCategory("Commerce")
.Selectable();

Tool Error Handling​

When InvokeCoreAsync throws an exception, the orchestrator catches it and returns an error message to the AI model so the conversation can continue. However, best practice is to never throw from a tool. Instead, catch exceptions and return a descriptive error string:

PatternBehaviorRecommended
Return error stringModel sees the message and can respond to the user✅ Yes
Throw exceptionOrchestrator catches, logs, returns generic error to model❌ Avoid
Return nullModel sees an empty result❌ Avoid
// ✅ Good: Return a user-friendly error message
protected override async ValueTask<object> InvokeCoreAsync(
AIFunctionArguments arguments, CancellationToken cancellationToken)
{
try
{
// ... tool logic
return new { result = "success", data = someData };
}
catch (HttpRequestException ex)
{
logger.LogError(ex, "External API call failed in tool '{ToolName}'.", Name);
return "The external service is temporarily unavailable. Please try again later.";
}
}

// ❌ Avoid: Letting exceptions propagate
protected override async ValueTask<object> InvokeCoreAsync(
AIFunctionArguments arguments, CancellationToken cancellationToken)
{
// This will crash and return a generic error to the model
var result = await httpClient.GetStringAsync("/api/data", cancellationToken);
return result;
}
tip

Use guard clauses with ILogger at each validation point. This creates a clear audit trail and gives the AI model actionable error messages that it can relay to the user.

Tool Return Types​

InvokeCoreAsync returns ValueTask<object>. The framework serializes the return value to JSON before passing it to the AI model. Here's how different return types are handled:

Return TypeSerializationExample
stringPassed as-isreturn "The weather is sunny."
Anonymous objectSerialized to JSONreturn new { temp = 22, condition = "Sunny" }
Record/classSerialized to JSONreturn new WeatherResult { Temp = 22 }
JsonElementPassed as raw JSONreturn JsonDocument.Parse(apiResponse).RootElement
Primitive (int, bool)Converted to stringreturn 42 → "42"
nullEmpty resultAvoid — return an error string instead

For complex return types, use explicit JSON serialization for maximum control:

protected override async ValueTask<object> InvokeCoreAsync(
AIFunctionArguments arguments, CancellationToken cancellationToken)
{
var result = await FetchDataAsync(cancellationToken);

// Explicit serialization with custom options
return JsonSerializer.Serialize(new
{
result.Id,
result.Name,
result.Description,
result.CreatedUtc,
ItemCount = result.Items.Count,
});
}
info

Keep return values concise. Large JSON payloads consume tokens and may hit model context limits. Return only the fields the AI model needs to formulate a response.

Testing Tools​

Unit test tools by creating a mock AIFunctionArguments with the required services:

public sealed class WeatherToolTests
{
[Fact]
public async Task InvokeAsync_WithValidLocation_ShouldReturnWeatherData()
{
// Arrange
var mockHandler = new MockHttpMessageHandler(
new HttpResponseMessage(HttpStatusCode.OK)
{
Content = JsonContent.Create(new { temp = 22, condition = "Sunny" }),
});

var httpClient = new HttpClient(mockHandler)
{
BaseAddress = new Uri("https://api.weather.test/"),
};

var httpClientFactory = Substitute.For<IHttpClientFactory>();
httpClientFactory.CreateClient("WeatherApi").Returns(httpClient);

var services = new ServiceCollection()
.AddSingleton(httpClientFactory)
.AddLogging()
.BuildServiceProvider();

var tool = new WeatherTool();

var arguments = new AIFunctionArguments(
new Dictionary<string, object>
{
["Location"] = "Seattle",
["Units"] = "celsius",
})
{
Services = services,
};

// Act
var result = await tool.InvokeAsync(arguments);

// Assert
Assert.NotNull(result);
var json = result.ToString();
Assert.Contains("22", json);
Assert.Contains("Sunny", json);
}

[Fact]
public async Task InvokeAsync_WithMissingLocation_ShouldReturnErrorMessage()
{
// Arrange
var services = new ServiceCollection()
.AddLogging()
.BuildServiceProvider();

var tool = new WeatherTool();

var arguments = new AIFunctionArguments(
new Dictionary<string, object>())
{
Services = services,
};

// Act
var result = await tool.InvokeAsync(arguments);

// Assert
Assert.NotNull(result);
Assert.Contains("location", result.ToString(), StringComparison.OrdinalIgnoreCase);
}

private sealed class MockHttpMessageHandler(HttpResponseMessage response) : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
=> Task.FromResult(response);
}
}
tip

Test tools in isolation from the AI model. Focus on:

  1. Valid input → correct API call and return value
  2. Missing/invalid input → descriptive error string (no exceptions)
  3. External service failure → graceful error message
  4. Cancellation → respects CancellationToken