Guides configuring user-defined AI tool instances in CrestApps.Core 2.0: creating IAIToolInstanceSource, registering with AddSource, parameter binding, HTTP/OAuth sources, documentation/data search with RRF, and per-instance authorization.
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.
Read when SKILL.md points to them.
A developer writes a source (IAIToolInstanceSource) once; users create many instances (AIToolInstance) of it, each with its own name, description and settings. Every instance reaches the model as a distinct function, so the model only decides when to call it.
AddToolInstances(...) registers the catalog manager, the completion handler and the default IAIToolParameterContextResolver; with useDefaultRegistry: true (default) it also registers ToolInstanceRegistryProvider.AddYesSqlStores() or AddEntityCoreStores()); the feature does not pick one. YesSql hosts create the table with schemaBuilder.CreateAIToolInstanceIndexSchemaAsync(yesSqlStoreOptions).Name is its stable lookup key and is fixed after creation. Its function name is instance.GetFunctionName(): tool_instance_ plus a provider-safe version of the name, capped at 64 characters, with a deterministic hash when normalization is lossy, so it never collides with an AddCoreAITool name.Description; it is the model's main signal for choosing between instances.Fixed or Context parameter fills for values the model must not choose.builder.Services.AddCrestAppsCore(crestApps => crestApps
.AddAISuite(ai => ai
.AddYesSqlStores()
.AddToolInstances(toolInstances => toolInstances
.AddYesSqlStores()
.AddHttpApiRequestSource()
.AddDocumentationSearchSources()
.AddDataSourceSearchSource()
.AddSource<OrderStatusToolInstanceSource>("order-status", entry =>
{
entry.DisplayName = new LocalizedString("order-status", "Order status");
entry.Description = new LocalizedString("order-status", "Looks up orders in a configured order system.");
entry.Category = new LocalizedString("Integrations", "Integrations");
}))));
AddSource<TSource>(name, configure) registers a keyed scoped IAIToolInstanceSource under name (the value stored in each instance's Source) and records AIToolInstanceSourceEntry metadata (DisplayName, Description, Category, Parameters). An empty display name defaults to the source name.
using CrestApps.Core;
using CrestApps.Core.AI.Tooling;
using Microsoft.Extensions.AI;
public sealed class OrderStatusToolInstanceSource : IAIToolInstanceSource
{
public AITool CreateTool(AIToolInstance instance)
{
ArgumentNullException.ThrowIfNull(instance);
var settings = instance.TryGet<OrderStatusToolSettings>(out var stored)
? stored
: new OrderStatusToolSettings();
var functionName = instance.GetFunctionName();
var description = string.IsNullOrWhiteSpace(instance.Description) ? functionName : instance.Description;
return new OrderStatusToolFunction(functionName, description, settings, instance);
}
}
public sealed class OrderStatusToolSettings
{
public string BaseUrl { get; set; }
public string ProtectedApiKey { get; set; }
}
OrderStatusToolFunction is the application's AIFunction; a full parameter-aware version is in tool-instance-parameters-examples.md. Save settings with instance.Put(new OrderStatusToolSettings { ... }).
profile.Alter<AIToolInstanceMetadata>(metadata =>
{
metadata.ToolInstanceNames = ["orders-eu", "weather-api"];
});
The same works on a ChatInteraction. AIToolInstanceCompletionContextBuilderHandler copies the names onto AICompletionContext.ToolInstanceNames, and the registry provider materializes each one, so every orchestrator honors them.
Parameters let whoever configures an instance declare typed, described arguments instead of an untyped bag. Each parameter (AIToolInstanceParameter) has a Name, Description, Type (String, Integer, Number, Boolean), Required, DefaultValue, AllowedValues, IsSecret, a fill and a binding:
AIToolParameterFill | In the schema | Value from |
|---|---|---|
Model | Yes | The model, or the default when omitted |
Fixed | No | A value pinned on the instance |
Context | No | An IAIToolParameterContextResolver key such as user.id, user.name, user.email, resource.id, now.utc |
Parameter support is opt-in per source. A source advertises what it can honor with AIToolInstanceSourceEntry.Parameters; a source without capabilities hides the editor and rejects saved parameters, so a parameter can never be shown to the model and then dropped.
.AddSource<OrderStatusToolInstanceSource>("order-status", entry =>
{
entry.DisplayName = new LocalizedString("order-status", "Order status");
entry.Parameters = new AIToolInstanceParameterCapabilities
{
ReservedNames = ["query"],
Bindings =
[
new AIToolParameterBindingOption("Argument")
{
DisplayName = new LocalizedString("Argument", "Call argument"),
},
new AIToolParameterBindingOption("Header")
{
DisplayName = new LocalizedString("Header", "Request header"),
AllowedFills = [AIToolParameterFill.Fixed, AIToolParameterFill.Context],
},
],
};
});
Then consume them in the function: AIToolParameterBinder.GetParameters(instance), AIToolParameterSchemaBuilder.Merge(baseSchema, parameters) for the schema (only model-filled parameters appear), and AIToolParameterBinder.Resolve(parameters, arguments, services, unprotect) at invocation, which applies precedence, coercion, allowed values and defaults and returns errors to report to the model. Declaring without consuming silently drops values; test both halves.
Register an IAIToolParameterContextResolver (SupportedKeys plus TryResolve(contextKey, services, out value)) to add context keys; resolvers are tried in registration order.
| Registration | Source name | What an instance does |
|---|---|---|
AddHttpApiRequestSource() | http-api-request | Calls one HTTP API with stored auth (None, ApiKey, Bearer, Basic, OAuth2 with cached tokens), headers, PathTemplate and parameter bindings Query:<key>, Path, Body:<dotted.path>, Header:<name> (model fills refused for headers) |
AddSitemapDocumentationSource() | sitemap-documentation | Crawls a site's sitemap (index, gzip, RSS/Atom, text, robots.txt discovery) and ranks pages locally |
AddSearchIndexDocumentationSource() | search-index-documentation | Downloads a prebuilt JSON search index and ranks it locally |
AddAlgoliaDocumentationSource() | algolia-documentation | Queries Algolia DocSearch |
AddWebsiteSearchSource() | website-search | Queries a site's own search API live (WordPress REST by default; paths overridable) |
AddDataSourceSearchSource() | data-source-search | Vector search over one AI data source |
With AuthenticationType = OAuth2, the tool caches its tokens on the instance as HttpApiRequestTokenState (access and refresh tokens data-protected with HttpApiRequestToolConstants.DataProtectionPurpose, token type, expiry, plus the BaseUrl and TokenEndpoint they were issued for):
BaseUrl and TokenEndpoint match the instance's current settings, so an access token never goes to another host and a refresh token is never posted to another endpoint. A state saved by an older version has no addresses and is ignored once (a new token is requested).refresh_token, else password when Username is set, else client_credentials. When every token request fails, the call goes out without a token; an expired cached token is never sent.AuthenticationType, BaseUrl, TokenEndpoint, ClientId, ClientSecret, Username, Password, Scope) changed during the call; otherwise the state is written onto the stored copy, keeping concurrent edits.BoundedHttpContent and cut to 16,000 characters, so the tool never buffers more than it returns.AddDocumentationSearchSources() adds all four documentation sources. DocumentationSearchOptions sets MaxResultsPerSite (5), MaxPagesPerSite (200), MaxConcurrentRequests (4), CacheDuration (1 hour) and FirstSearchWaitBudget (8 seconds): the first search on an unindexed site builds the corpus in the background and answers "still indexing" after the budget instead of blocking. Empty crawls are cached for only 5 minutes, and empty results tell the model rewording will not help.
DataSourceSearchToolSettings holds DataSourceId, RetrievalMode (DataSourceRetrievalMode.Chunk or Hierarchical), TopNDocuments, Strictness and an OData Filter. Queries use the embedding deployment the index was built with. One call may carry up to three phrases; they are embedded in one batch, searched in parallel and merged with Reciprocal Rank Fusion under shared [doc:N] citations. Hierarchical returns whole source documents and degrades to chunks when they cannot be read.
ToolInstanceRegistryProvider is public. Subclass it and override ShouldIncludeInstanceAsync:
using CrestApps.Core.AI.Models;
using CrestApps.Core.AI.Tooling;
using CrestApps.Core.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
public sealed class PermissionAwareToolInstanceRegistryProvider : ToolInstanceRegistryProvider
{
private readonly IAuthorizationService _authorizationService;
private readonly IUserAccessor _userAccessor;
public PermissionAwareToolInstanceRegistryProvider(
IServiceProvider serviceProvider,
ILogger<ToolInstanceRegistryProvider> logger,
IAuthorizationService authorizationService,
IUserAccessor userAccessor)
: base(serviceProvider, logger)
{
_authorizationService = authorizationService;
_userAccessor = userAccessor;
}
protected override async ValueTask<bool> ShouldIncludeInstanceAsync(
AIToolInstance instance,
AICompletionContext context,
CancellationToken cancellationToken)
{
var user = _userAccessor.User;
if (user is null)
{
return true;
}
var result = await _authorizationService.AuthorizeAsync(user, instance, "UseToolInstance");
return result.Succeeded;
}
}
ai.AddToolInstances(toolInstances => toolInstances
.AddYesSqlStores()
.AddHttpApiRequestSource(),
useDefaultRegistry: false);
builder.Services.AddScoped<IToolRegistryProvider, PermissionAwareToolInstanceRegistryProvider>();
Keep useDefaultRegistry: true only when a custom provider is additive. The provider skips unknown sources with a warning and catches exceptions from CreateTool.
DocumentationToolConstants.MaxPageBytes, MaxSearchIndexBytes); oversized pages are skipped.ToolInstanceRegistryProvider's constructor takes (IServiceProvider, ILogger<ToolInstanceRegistryProvider>) and resolves INamedCatalog<AIToolInstance> lazily; subclasses written against samples that passed the catalog must change their base call.AddDataSourceSearchSource() and the live AddWebsiteSearchSource(). The sitemap source now follows sitemap indexes, gzip, feeds and robots.txt, and no longer blocks on a slow first crawl.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
/crestapps-core:crestapps-core-tool-instancesfrom 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