Implements AIFunction tools with JSON schema in CrestApps.Core 2.0. Covers registration, tool kinds, approval settings, aliases, dependencies, and authorization for code-defined callable functions.
Ships in crestapps-core. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
A code-defined tool is a Microsoft.Extensions.AI AIFunction registered under a name. The orchestrator adds it to requests through the tool registry; the model supplies all its arguments. Use tool instances (crestapps-core-tool-instances) when end users configure the tool, and agents (crestapps-core-ai-agents) when the callable thing is a whole profile.
AIFunction and override Name, Description, JsonSchema and InvokeCoreAsync.AddCoreAITool<TTool>(name). Tools are singletons, also registered as keyed AITool services under the name..Selectable() for tools users attach to profiles, and .Hidden() for helper tools only explicitly configured profiles or agents may use; hidden tools stay out of picker and shared MCP listings.null.content_generation, not ContentGeneration); always use the AIToolPurposes constants.AIFunctionArguments.Services, not from the constructor (the tool is a singleton).toolCalling, or capability enforcement removes every tool from the request..AsRead(), .AsWrite(), .AsDestructive(), .AsExternal() or .AsSecurity(). A Destructive, External or Security tool requires a person's approval without .RequireApproval(), and ExposeAllTools of the MCP server and WebMCP leaves it out (see Tool Kinds)..WithAlias("earlierName", grantsAccess: true) so stored profiles, settings and grants keep working (see Renaming a Tool).builder.Services
.AddCoreAITool<WeatherTool>(WeatherTool.TheName)
.WithTitle("Get Weather")
.WithDescription("Returns current weather for a location.")
.WithCategory("Utilities")
.AsRead()
.Selectable();
| Builder method | Use |
|---|---|
.WithTitle(...) | UI title (defaults to the name) |
.WithDescription(...) | Description (defaults to the name) |
.WithCategory(...) | UI grouping |
.WithPurpose(...) | Purpose tag: AIToolPurposes.DocumentProcessing (document_processing), ContentGeneration (content_generation), DataSourceSearch (data_source_search), Memory (memory) |
.WithDependency(...) / .WithDependencies(...) | Tools added automatically when this one is selected |
.WithoutDependency(...) / .WithoutDependencies(...) | Remove registered dependencies |
.Selectable() | User-assignable |
.Hidden() | Only for profiles or agents that name it |
.RequireApproval() | A person approves each call before it runs (AIToolDefinitionEntry.RequiresApproval); .RequireApproval(false) lets a tool of an approval kind run without asking. The explicit call wins over the kind, whichever is called first |
.AsRead() / .AsWrite() / .AsDestructive() / .AsExternal() / .AsSecurity() / .WithKind(AIToolKind) | What the tool does (AIToolDefinitionEntry.Kind, ToolRegistryEntry.Kind) |
.WithAlias(name, grantsAccess: false) / .WithAliases(...) | Earlier names that keep resolving to this tool |
AddCoreAIToolServices<TTool>(name) registers the singleton and keyed service without a definition, for tools resolved only in code.
using System.Text.Json;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
public sealed class WeatherTool : AIFunction
{
public const string TheName = "get-weather";
private static readonly JsonElement _jsonSchema = JsonSerializer.Deserialize<JsonElement>("""
{
"type": "object",
"required": ["location"],
"properties": {
"location": { "type": "string", "description": "City name." },
"units": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature units." }
},
"additionalProperties": false
}
""");
public override string Name => TheName;
public override string Description => "Returns current weather for a location.";
public override JsonElement JsonSchema => _jsonSchema;
protected override async ValueTask<object> InvokeCoreAsync(
AIFunctionArguments arguments,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(arguments);
if (!arguments.TryGetValue("location", out var raw) || raw?.ToString() is not { Length: > 0 } location)
{
return """{"error":"A location is required."}""";
}
var weatherClient = arguments.Services.GetRequiredService<IWeatherClient>();
try
{
var forecast = await weatherClient.GetCurrentAsync(location, cancellationToken);
return JsonSerializer.Serialize(new { forecast.Temperature, forecast.Condition, Location = location });
}
catch (HttpRequestException)
{
return """{"error":"The weather service is unavailable. Try again later."}""";
}
}
}
IWeatherClient stands for the application's own service. Arguments arrive as JsonElement values from most providers, so read them with ToString() or deserialize rather than casting to string.
builder.Services
.AddCoreAITool<CreateOrderTool>("create_order")
.WithDescription("Creates an order from validated input.")
.WithDependency("get_order_schema")
.AsWrite()
.Selectable();
builder.Services
.AddCoreAITool<GetOrderSchemaTool>("get_order_schema")
.WithDescription("Returns the fields an order needs.")
.AsRead()
.Hidden();
Profiles store only the top-level name. Missing dependencies are ignored, and shared or circular graphs are deduplicated.
| Kind | Builder | Meaning | Requires approval | ExposeAllTools includes it |
|---|---|---|---|---|
Unspecified | (none) | Behaves as before kinds existed | Only with .RequireApproval() | Unless it requires an approval |
Read | .AsRead() | Returns data, changes nothing | No | Yes |
Write | .AsWrite() | Creates or changes data that can be changed back | No | Yes |
Destructive | .AsDestructive() | Deletes data or cannot be undone | Yes | Only when Tools names it |
External | .AsExternal() | Sends something outside (email, SMS, call, webhook), calls a paid service, moves money | Yes | Only when Tools names it, or with .RequireApproval(false) |
Security | .AsSecurity() | Changes access, sign-in, secrets, or what code or templates run | Yes | Only when Tools names it |
builder.Services
.AddCoreAITool<ListOrdersTool>("listOrders")
.AsRead()
.Selectable();
builder.Services
.AddCoreAITool<DeleteOrderTool>("deleteOrder")
.AsDestructive()
.Selectable();
AIToolKindExtensions.RequiresApproval(kind) and IsExposedWithAllTools(kind) give these rules in code.readOnlyHint, destructiveHint, openWorldHint); WebMCP gives a kind value per tool. A tool without a kind has no annotations.A tool requires an approval when its registration calls .RequireApproval(), or its kind is Destructive, External or Security and it does not call .RequireApproval(false).
builder.Services
.AddCoreAITool<SendInvoiceTool>(SendInvoiceTool.TheName)
.WithDescription("Emails an invoice to the customer.")
.AsExternal()
.Selectable();
DefaultToolMaterializer reads ToolRegistryEntry.RequiresApproval. When ToolMaterializationOptions.SupportsToolApproval is true (an AG-UI chat run, where AIChatResponseHandler sets AICompletionContextKeys.ToolApprovalSupported), the tool is wrapped in Microsoft.Extensions.AI's ApprovalRequiredAIFunction: the run pauses with an interrupt and the chat shows Allow and Deny. Inside an agent, the agent pauses and the assistant's run asks (see crestapps-core-ai-agents and crestapps-core-ag-ui).SupportsToolApproval is false (the text-only SendMessage stream, chat interactions, realtime sessions, workflows, SMS and voice channels, post-session processing, an agent an MCP client calls, the Claude and Copilot orchestrators, background work), the model still sees the tool, but it is replaced with an internal stand-in (same name and schema) whose result says the tool was not run because it needs a person's approval this conversation cannot ask for, so the model tells the user. Each one counts on crestapps.core.ai.tool.denied with reason=approval. PostSessionProcessingService and CopilotOrchestrator apply the same rule without the metric.AIFunction and requires an approval is left out of every request, AG-UI runs included, with a warning.IToolRegistryProvider sets RequiresApproval = true (and optionally Kind) on its own ToolRegistryEntry values. ToolRegistryEntry.ApprovalFloor = ToolApprovalMode.EveryCall marks a tool that no profile policy may run unasked; an explicit .RequireApproval() sets it..RequireApproval(false), or let the profile run its kind without asking.AIToolApprovalSettings in AIProfile.Settings holds a ToolApprovalRule per kind name, with a ToolApprovalMode of EveryCall (the default), OncePerSession (reserved; asks every call for now) or Never.
profile.AlterSettings<AIToolApprovalSettings>(settings =>
{
settings.Kinds[nameof(AIToolKind.External)] = new ToolApprovalRule { Mode = ToolApprovalMode.Never };
});
// Or every approval kind (Destructive, External and Security):
profile.AlterSettings<AIToolApprovalSettings>(settings => settings.SetRunAllWithoutAsking(true));
Never kind runs without asking everywhere, also where nobody can be asked (voice, the Claude and Copilot orchestrators). Each call writes an Information log and counts on crestapps.core.ai.tool.auto_approved (AITelemetry.ToolAutoApprovals, tagged with the reason, tool.kind and agent)..RequireApproval() (AIToolDefinitionEntry.RequiresApprovalExplicit) or a consequential WebMCP page tool always asks.ToolApprovalPolicy.ForAgent(callerPolicy, agentPolicy) keeps only the kinds both allow, and a caller with no profile (an MCP client) allows nothing.AIProfileCompletionContextBuilderHandler resolves the settings into a ToolApprovalPolicy under AICompletionContextKeys.ToolApprovalPolicy (GetToolApprovalPolicy(), SetToolApprovalPolicy()), passed to the materializer as ToolMaterializationOptions.ApprovalPolicy. Access checks are unchanged, and ExposeAllTools and post-session tasks ignore it.builder.Services
.AddCoreAITool<ListUsersTool>("listUsers")
.WithAlias("searchForUsers", grantsAccess: true)
.Selectable();
searchForUsers gets listUsers (ProfileToolRegistryProvider). Dependencies, the MCP server and WebMCP Tools lists, and IAIToolsService.GetByNameAsync resolve the alias too.grantsAccess: true adds the alias to AIToolDefinitionEntry.AccessAliases; the IAIToolAccessEvaluator.IsAuthorizedAsync(user, toolName, definition) extension then authorizes the tool when the evaluator authorizes its name or such an alias. Use it only for a rename. When a narrower tool is merged into a broader one, use .WithAlias("getOrder") alone so its grants do not reach the broader tool.AIToolDefinitionOptions.Tools, GetSelectableTools()) show the tool once, under its current name. Look up a stored name with AIToolDefinitionOptions.TryGetTool(nameOrAlias, out var definition), ResolveToolName or ResolveToolNames; the keyed AITool service exists under the current name only.InvalidOperationException naming both tools when AIToolDefinitionOptions is first read.A result that is more than text can implement IAIToolContentProvider (IReadOnlyList<AIContent> ToContents()); the MCP server maps it to content blocks (for example text plus resource links) instead of one text block. A plain string is still one text block.
using CrestApps.Core.AI.Models;
using CrestApps.Core.AI.Tooling;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
public sealed class FeatureFlagToolRegistryProvider : IToolRegistryProvider
{
private readonly IFeatureFlags _featureFlags;
public FeatureFlagToolRegistryProvider(IFeatureFlags featureFlags)
{
_featureFlags = featureFlags;
}
public async Task<IReadOnlyList<ToolRegistryEntry>> GetToolsAsync(
AICompletionContext context,
CancellationToken cancellationToken = default)
{
if (context is null || context.DisableTools || !await _featureFlags.IsEnabledAsync("beta-tools", cancellationToken))
{
return [];
}
return
[
new ToolRegistryEntry
{
Id = "beta:get-weather",
Name = WeatherTool.TheName,
Description = "Returns current weather for a location.",
Source = ToolRegistryEntrySource.Local,
CreateAsync = services => ValueTask.FromResult<AITool>(services.GetRequiredService<WeatherTool>()),
},
];
}
}
builder.Services.AddScoped<IToolRegistryProvider, FeatureFlagToolRegistryProvider>();
IFeatureFlags stands for the host's own service. IToolRegistry.GetAllAsync(context) concatenates every provider; the built-ins are SystemToolRegistryProvider, ProfileToolRegistryProvider, AgentToolRegistryProvider, ToolInstanceRegistryProvider, SharedStateToolRegistryProvider (update_shared_state when an AG-UI run shares state) and ClientToolRegistryProvider (an AG-UI client's frontend tools), plus McpToolRegistryProvider, A2AToolRegistryProvider and WebMcpPageToolRegistryProvider from their packages. ToolRegistryEntrySource is Local, McpServer, System or Agent.
IAIToolAccessEvaluator.IsAuthorizedAsync(ClaimsPrincipal user, string toolName) (through the alias-aware IsAuthorizedAsync(user, toolName, definition) extension) and drops the ones the caller may not use (one warning). System, hidden and dependency tools are not checked, and a null user (server-side work) skips the check. The default evaluator allows everything.using System.Security.Claims;
using CrestApps.Core.AI.Tooling;
using Microsoft.AspNetCore.Authorization;
public sealed class PermissionToolAccessEvaluator : IAIToolAccessEvaluator
{
private readonly IAuthorizationService _authorizationService;
public PermissionToolAccessEvaluator(IAuthorizationService authorizationService)
{
_authorizationService = authorizationService;
}
public async Task<bool> IsAuthorizedAsync(ClaimsPrincipal user, string toolName)
{
var result = await _authorizationService.AuthorizeAsync(user, toolName, "UseAITool");
return result.Succeeded;
}
}
builder.Services.AddScoped<IAIToolAccessEvaluator, PermissionToolAccessEvaluator>();
The caller comes from IUserAccessor.User (namespace CrestApps.Core.Security), which prefers a principal assigned on the current async flow and falls back to HttpContext.User. The built-in hubs assign Context.User at the start of each invocation; custom hosts that run completions outside a request or hub should assign it too.
An MCP server built on CrestApps.Core publishes registered tools through its own allow-list (ExposeAllTools or a list of tool names) and agents through a separate Agents/ExposeAllAgents switch. Hidden tools are not listed. ExposeAllTools leaves out Destructive and Security tools and every tool that requires an approval; naming one in Tools exposes it, and the client then runs it without an approval. Each MCP tool call runs inside an AIInvocationScope. See crestapps-core-mcp.
AIToolApprovalSettings are new; registrations without a kind or alias behave as before.FunctionInvocationAICompletionServiceHandler no longer filters AI session tools through IAIToolAccessEvaluator. Keep a custom evaluator; it now governs Chat Interaction sends. It is not obsolete.IToolRegistryProvider.GetToolsAsync returns Task<IReadOnlyList<ToolRegistryEntry>>. Some published samples still show ValueTask<IEnumerable<AIToolMetadataEntry>>; follow the interface.toolCalling on deployments; a 1.x Chat purpose projects to textGeneration only, and tools are then stripped.What SKILL.md sets; muted values are Claude Code's defaults
/crestapps-core:crestapps-core-custom-toolsfrom crestapps-core
npx claudepluginhub crestapps/crestapps.agentskills --plugin crestapps-core51 skills in this plugin
/crestapps-core-a2aSkill for Agent-to-Agent (A2A) protocol support in CrestApps.Core on the A2A 1.0 SDK. Covers AddA2AClient and AddCoreAIA2AClient with Entity Framework Core or YesSql connection stores, A2AConnection and A2AConnectionMetadata authentication, AIProfileA2AMetadata, the agent card cache and A2AToolRegistryProvider, the listAvailableAgents, findAgentForTask and findToolsForTask tools, building an A2A host with IAgentHandler, A2AServer, ITaskStore and MapA2A, A2A 1.0 agent cards with supportedInterfaces published at /.well-known/agent-card.json, A2AHostOptions authentication and ExposeAgentsAsSkill, system agents exposed through the host, and upgrading from the 0.3 SDK./crestapps-core-ag-uiSkill for running the CrestApps.Core 2.0 AI chat as an AG-UI agent. Covers the CrestApps.Core.AI.AGUI package (AGUIRunEventWriter, AGUIRunRequest, AGUIJson), AIChatHubCore.RunAgent over SignalR and MapAGUIChat with Server-Sent Events, the RunAgentInput members and streamed events, tool approvals with RequireApproval or an approval tool kind, ApprovalRequiredAIFunction, interrupts and resume, approvals inside agents, page context with crestAppsAGUI.registerContextProvider, shared state with registerStateProvider and update_shared_state, frontend tools, stored tool calls (ChatTurnToolActivity), runs that continue on the next page, AGUIChatOptions.DisconnectedRunTimeout, the protocol and sendPageContext chat options, and the AICompletionContextKeys and ChatResponseHandlerContext members. Use it when showing tool calls in the chat, asking a person before a tool runs, sharing page state with the agent, connecting CopilotKit or another AG-UI client, or troubleshooting approvals and continued runs.Other plugins' skills for the same job