Path: redb-route/redb.Route.Llm.Abstractions/Extensions/LlmToolDsl.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm.Abstractions/Extensions/LlmToolDsl.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Definitions; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Tools; namespace redb.Route.Llm.Extensions; /// /// Apache-Camel-style DSL aspect that registers the current route as an /// in the global . /// Place .AsLlmTool(name) immediately after .From(uri) — it is route-level /// metadata, not a step in the pipeline. Close the metadata block with .End() /// or .Then() to return to the parent . /// /// /// route.From("direct:order-lookup") /// .AsLlmTool("get_order") /// .Description("Returns order details by id.") /// .Input("""{"type":"object","properties":{"orderId":{"type":"string"}},"required":["orderId"]}""") /// .SideEffect(ToolSideEffect.ReadOnly) /// .Cost(ToolCostClass.Cheap) /// .Then() /// .Bean<IOrderService>((svc, ex) => svc.HandleAsync(ex)); /// /// /// public static class LlmToolDsl { /// /// Marks the current route's source endpoint as an LLM tool. Returns a metadata /// builder; call .End() or .Then() to return to the route. /// /// The owning route — must already have .From(uri) set. /// Tool name exposed to the model (must be unique per registry). public static LlmToolBuilderDefinition AsLlmTool(this IRouteDefinition route, string name) { ArgumentNullException.ThrowIfNull(route); ArgumentException.ThrowIfNullOrWhiteSpace(name); var fromUri = route.GetFromUri() ?? throw new InvalidOperationException( $".AsLlmTool('{name}') must follow .From(uri) — the route has no source endpoint yet."); return new LlmToolBuilderDefinition(route, name, fromUri); } } /// /// Metadata builder for . Collects the tool capability /// fields and registers a in the /// when or is called. /// public sealed class LlmToolBuilderDefinition { private readonly IRouteDefinition _route; private readonly string _name; private readonly string _endpointUri; private string _description = string.Empty; private string _inputSchema = RouteToolBridge.DefaultInputSchema; private ToolSideEffect _sideEffect = ToolSideEffect.ReadOnly; private ToolCachingPolicy _caching = ToolCachingPolicy.None; private ToolCostClass _cost = ToolCostClass.Cheap; private bool _requiresApproval; private List? _requiredClaims; private bool _registered; internal LlmToolBuilderDefinition(IRouteDefinition route, string name, string endpointUri) { _route = route; _name = name; _endpointUri = endpointUri; } /// Sets the human-readable description shown to the model. public LlmToolBuilderDefinition Description(string description) { ArgumentException.ThrowIfNullOrWhiteSpace(description); _description = description; return this; } /// Sets the JSON Schema describing the tool's input arguments. public LlmToolBuilderDefinition Input(string jsonSchema) { ArgumentException.ThrowIfNullOrWhiteSpace(jsonSchema); _inputSchema = jsonSchema; return this; } /// Declares the tool's side-effect class (read-only / mutating / external). public LlmToolBuilderDefinition SideEffect(ToolSideEffect sideEffect) { _sideEffect = sideEffect; return this; } /// Declares the caching policy. public LlmToolBuilderDefinition Caching(ToolCachingPolicy caching) { _caching = caching; return this; } /// Declares the cost class — drives budget enforcement. public LlmToolBuilderDefinition Cost(ToolCostClass cost) { _cost = cost; return this; } /// /// Marks the tool as requiring explicit approval before each call. /// The configured IApprovalGate is consulted at dispatch time. /// public LlmToolBuilderDefinition RequiresApproval(bool requiresApproval = true) { _requiresApproval = requiresApproval; return this; } /// /// Declares a claim the calling principal must carry for the tool to fire. /// Enforced — the engine verifies the requirement against the registered /// IToolClaimsSource (the caller's principal by default) and refuses the call when it cannot; /// see . /// public LlmToolBuilderDefinition RequireClaim(string claim) { ArgumentException.ThrowIfNullOrWhiteSpace(claim); (_requiredClaims ??= []).Add(claim); return this; } /// /// Closes the metadata block, registers the descriptor in the /// and returns the parent /// so the route pipeline can continue. /// public IRouteDefinition End() => Register(); /// /// Alias for — reads more naturally when chaining the rest /// of the route as a continuation (e.g. .AsLlmTool(...).Then().Bean<...>()). /// public IRouteDefinition Then() => Register(); private IRouteDefinition Register() { if (_registered) return _route; _registered = true; // Fail fast rather than ship a tool that always refuses: a declared claim with no claims source // can never be verified, because the engine denies what it cannot check. AddRedbRouteLlm() // registers the default source (the caller's principal), so this fires only when a host // replaced or removed it — and then breaking the route build beats a silently dead tool. if (_requiredClaims is { Count: > 0 } && !HasClaimsSource()) throw new InvalidOperationException( $"Tool '{_name}' requires claims [{string.Join(", ", _requiredClaims)}] but no IToolClaimsSource is registered. " + "Remove the registration that disabled the default source, register one of your own " + "(services.AddSingleton), or drop .RequireClaim(...)."); // Only read-only tools may be cached. A cache hit suppresses the side effect the entry stands // for, so caching a mutation would silently drop a legitimate repeat ("send that invoice // again") for the whole TTL. Same call HTTP made: caches are for safe methods by default. if (_caching != ToolCachingPolicy.None && _sideEffect != ToolSideEffect.ReadOnly) throw new InvalidOperationException( $"Tool '{_name}' declares Caching={_caching} with SideEffect={_sideEffect}. " + "Only read-only tools may be cached — a cache hit would suppress the side effect."); var capability = new LlmToolCapability { Name = _name, Description = _description, InputSchema = _inputSchema, Safety = new LlmToolSafety { SideEffect = _sideEffect, Caching = _caching, Cost = _cost, RequiresApproval = _requiresApproval, RequiredClaims = _requiredClaims is { Count: > 0 } cs ? [.. cs] : [] } }; var descriptor = new RouteToolBridge(capability, _endpointUri); var registry = ResolveRegistry(); registry.Register(descriptor); return _route; } /// /// Whether a claims source is reachable from the route's context. Absence is the fail-closed /// default, so a claim-declaring tool must not build against it. /// private bool HasClaimsSource() { if (_route is RouteDefinitionBase rdef && rdef.Context is { } ctx) { var sp = ctx.GetServiceProvider(); if (sp?.GetService() is not null) return true; if (ctx.GetService() is not null) return true; } return false; } private IToolDescriptorRegistry ResolveRegistry() { if (_route is RouteDefinitionBase rdef && rdef.Context is { } ctx) { var sp = ctx.GetServiceProvider(); var fromSp = sp?.GetService(); if (fromSp is not null) return fromSp; var fromCtx = ctx.GetService(); if (fromCtx is not null) return fromCtx; } throw new InvalidOperationException( $".AsLlmTool('{_name}') could not resolve IToolDescriptorRegistry. " + "Call services.AddRedbRouteLlm() before building the routes."); } }