Bundle: redb-route / redb.Route.Llm.Abstractions (redb.Route.Llm.Abstractions.txt), 15 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== 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."); } } Path: redb-route/redb.Route.Llm.Abstractions/README.md 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/README.md ---- # redb.Route.Llm.Abstractions > Documentation and articles: Contracts package for the `redb.Route.Llm` tool surface. Apache 2.0. Holds the **declarative** types every redb.Route LLM tool author needs, without pulling the provider engine, HttpClient, or Anthropic/OpenAI SDK code. ## What's in this package | Type | Role | |------|------| | `LlmToolCapability` | Tool metadata exposed to the model (name, description, input schema). | | `LlmToolSafety` | Governance metadata — side-effect, cost, caching, approval, claims. | | `ToolSideEffect`, `ToolCostClass`, `ToolCachingPolicy` | Enums used by `LlmToolSafety`. | | `ILlmToolDescriptor` | The contract a tool implements: capability + endpoint URI builder. | | `IToolDescriptorRegistry` | Registry of `ILlmToolDescriptor` resolved by tool name. | | `[ExposeAsLlmTool]` | Attribute that adorns handler classes / methods to declare their tool surface. | ## Why a separate package - The LLM **engine** (`redb.Route.Llm`) is heavy: HTTP transport, SSE parsers, Anthropic / OpenAI providers, governance, conversation persistence. - The **contracts** are tiny: a handful of POCOs, an interface, and an attribute. A connector or third-party tool author who wants to declare an `ILlmToolDescriptor` can take a dependency on this package without inheriting the entire engine surface. ## Dispatch model `ILlmToolDescriptor` is **declarative + URI-building**, not self-executing. The engine in `redb.Route.Llm` resolves the descriptor, calls `BuildEndpointUri(inputJson, parentExchange)`, then dispatches via `IProducerTemplate.RequestBody(endpointUri, message)`. Every tool runs as a redb.Route exchange — gets the parent's transaction scope, headers, principal, and DI scope for free. Path: redb-route/redb.Route.Llm.Abstractions/Tools/ExchangePrincipalClaimsSource.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/Tools/ExchangePrincipalClaimsSource.cs ---- using System.Security.Claims; using redb.Route.Abstractions; namespace redb.Route.Llm.Abstractions.Tools; /// /// Default : the claims of the caller an exchange came from. /// /// The principal is read from , i.e. a property of the exchange /// that only in-process code can write — a caller cannot send it as a header, and it does not travel /// to a broker. That makes it the only identity a tool requirement may be checked against: a header /// naming a user (such as llm.user.id) is audit information, not proof. /// /// /// Values are collected from the scope claim types issuers actually use — scope (OAuth 2.0 / /// OIDC), scp and http://schemas.microsoft.com/identity/claims/scope (Microsoft Entra /// ID) — split on whitespace only and de-duplicated with ordinal comparison, because one logical /// set can arrive as several claims with padded values. The delimiter is space by specification /// (RFC 6749 §3.3) and a comma is a legal character inside a scope token: splitting on it would /// turn one granted scope into two and widen the caller's rights, which is the one direction a security /// check must never fail in. A deployment whose issuer really emits comma-separated lists registers its /// own . Claim values are compared as-is; scope names are case-sensitive. /// /// /// A principal whose identity is not authenticated counts as no principal (null), not as /// an empty set: an anonymous caller cannot satisfy a requirement. This puts a requirement on hosts: a /// resolver must return an identity carrying an authentication type — new ClaimsIdentity(claims) /// without one reports IsAuthenticated == false and would leave claim-required tools denied /// (fail closed, but for a reason the log must make visible). A run that has no inbound request — a /// scheduler-fired one, or one born after a broker hop, where properties do not survive — likewise has /// no principal. A consumer that establishes identity by itself (an AS2 signature check, a bearer token /// validated in a processor) must store the outcome the same way, with /// — a property, never a report header the caller could have written. /// /// /// Deployments with a different vocabulary register their own ; it /// replaces this one. /// /// public sealed class ExchangePrincipalClaimsSource : IToolClaimsSource { private static readonly string[] ScopeClaimTypes = [ "scope", // OAuth 2.0 / OIDC "scp", // Microsoft Entra ID (v2) "http://schemas.microsoft.com/identity/claims/scope" // Microsoft Entra ID (v1) ]; private static readonly char[] Separators = [' ', '\t', '\r', '\n']; /// public IReadOnlyCollection? GetClaims(IExchange exchange) { ArgumentNullException.ThrowIfNull(exchange); var principal = ExchangePrincipal.Get(exchange); if (principal?.Identity is not { IsAuthenticated: true }) return null; var claims = new HashSet(StringComparer.Ordinal); foreach (var claimType in ScopeClaimTypes) { foreach (var claim in principal.FindAll(claimType)) { foreach (var value in claim.Value.Split( Separators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) { claims.Add(value); } } } return claims; } } Path: redb-route/redb.Route.Llm.Abstractions/Tools/ExposeAsLlmToolAttribute.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/Tools/ExposeAsLlmToolAttribute.cs ---- namespace redb.Route.Llm.Abstractions.Tools; /// /// Marks a class, method, or route definition as exposable to an LLM as a tool. /// Discovered by the engine's tool registrars; the attribute carries the same /// metadata as so a descriptor can be built /// without reflecting on the handler body. /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public sealed class ExposeAsLlmToolAttribute : Attribute { /// Stable tool name used by the model. Required. public string Name { get; } /// Human-readable tool description shown to the model. Required. public string Description { get; } /// JSON Schema string for input parameters. Optional — when omitted the engine assigns a permissive object schema. public string? InputSchema { get; init; } /// Side-effect classification. Drives approval and idempotency policies. public ToolSideEffect SideEffect { get; init; } = ToolSideEffect.ReadOnly; /// Cost class hint for budget-aware scheduling. public ToolCostClass Cost { get; init; } = ToolCostClass.Cheap; /// Caching policy hint. public ToolCachingPolicy Caching { get; init; } = ToolCachingPolicy.None; /// When true the tool always requires explicit user approval before execution. public bool RequiresApproval { get; init; } /// /// Comma-separated list of claims required on the calling principal. Empty = no requirements. /// Enforced — the engine verifies the requirement against the registered /// IToolClaimsSource and refuses the call when it cannot. /// public string RequiredClaims { get; init; } = ""; /// Creates a tool exposure attribute. /// Stable tool name (regex [a-zA-Z][a-zA-Z0-9_]{0,63}). /// Human-readable description for the model. public ExposeAsLlmToolAttribute(string name, string description) { Name = name; Description = description; } /// Builds an from this attribute, applying /// when is null. public LlmToolCapability ToCapability(string defaultInputSchema) => new() { Name = Name, Description = Description, InputSchema = InputSchema ?? defaultInputSchema, Safety = new LlmToolSafety { SideEffect = SideEffect, Cost = Cost, Caching = Caching, RequiresApproval = RequiresApproval, RequiredClaims = string.IsNullOrWhiteSpace(RequiredClaims) ? [] : RequiredClaims .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) } }; } Path: redb-route/redb.Route.Llm.Abstractions/Tools/ILlmToolDescriptor.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/Tools/ILlmToolDescriptor.cs ---- using redb.Route.Abstractions; namespace redb.Route.Llm.Abstractions.Tools; /// /// A tool exposable to the LLM. Implementations are declarative — they carry the /// shown to the model and a /// hook that the engine uses to dispatch the call onto a redb.Route endpoint via /// IProducerTemplate.RequestBody. /// /// Descriptors are typically registered as DI singletons (they are stateless metadata). /// Per-call state is not carried by the descriptor: the engine dispatches the tool on a /// linked child of the agent exchange, so the parent's Properties, /// RouteId, DI scope (hence every scoped service the conversation resolved) and /// ambient transaction are the tool's as well. /// /// /// Headers are the exception — they are filtered, not inherited. A tool receives /// the conversation id, both correlation-id spellings, the run's resolved principal /// (llm.user.id) and its resolved audit tags (llm.audit.*), plus whatever /// the route author named via .PropagateToolHeaders(...). The inbound transport's /// header set is never forwarded implicitly. See ToolHeaderPolicy in /// redb.Route.Llm. /// /// public interface ILlmToolDescriptor { /// /// Capability metadata the engine projects to the provider (name, description, input schema) /// and consults for governance: (approval gate), /// (claims), and /// (cache and replay de-duplication). Safety never reaches /// the wire — see for the per-field status. /// LlmToolCapability Capability { get; } /// /// Computes the endpoint URI to which the engine forwards the tool call. /// May return a static URI (e.g. direct:sql-readonly) or build one /// dynamically from the input JSON (e.g. http://{input.url}). /// /// Tool input — JSON object matching . /// /// Parent exchange of the agent route — read-only view of the run for address /// building (headers, properties, DI scope). Note that only what this method /// encodes into the returned URI, plus the propagated header set, reaches the /// tool route; do not use it to smuggle per-call state. /// /// The endpoint URI the engine will dispatch to. string BuildEndpointUri(string inputJson, IExchange parentExchange); } Path: redb-route/redb.Route.Llm.Abstractions/Tools/IToolClaimsSource.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/Tools/IToolClaimsSource.cs ---- using redb.Route.Abstractions; namespace redb.Route.Llm.Abstractions.Tools; /// /// Resolves the claims held by the principal of an agent run. The engine consults it before /// dispatching a tool whose is not empty. /// /// Returning null means "this run has no verifiable principal"; returning an empty set means /// "a principal exists and holds nothing". Both deny a claimed tool — the distinction is diagnostic /// only. AddRedbRouteLlm() registers the default implementation, /// ExchangePrincipalClaimsSource, which reads the caller from the exchange; a host with its /// own vocabulary registers its own source instead (it wins). Removing the default leaves /// claim-declaring tools unbuildable: that is the fail-closed default, not an oversight. /// /// /// Claim names are scope-like strings, matching the vocabulary the ecosystem already issues for /// authorization scopes: redb.Identity hands out values such as identity:scopes:read / /// identity:scopes:write (IdentityScopes) and puts them in the token's scope /// claim. Which source feeds this interface — and therefore which exact names a tool may require — /// is a deployment decision, not something this contract fixes; the engine only compares strings. /// /// public interface IToolClaimsSource { /// /// Returns the claims held by the principal owning , or null /// when the run has no verifiable principal. /// /// The agent run's exchange — carries the DI scope the host resolves its /// identity/security services from. IReadOnlyCollection? GetClaims(IExchange exchange); } /// /// Claims source backed by a delegate — the seam for deployments that resolve claims from their own /// identity layer, and for tests. /// public sealed class DelegateToolClaimsSource : IToolClaimsSource { private readonly Func?> _resolve; /// Creates a source over . /// Delegate returning the claims (or null for "no verifiable principal"). public DelegateToolClaimsSource(Func?> resolve) { ArgumentNullException.ThrowIfNull(resolve); _resolve = resolve; } /// public IReadOnlyCollection? GetClaims(IExchange exchange) => _resolve(exchange); } Path: redb-route/redb.Route.Llm.Abstractions/Tools/IToolDescriptorRegistry.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/Tools/IToolDescriptorRegistry.cs ---- using System.Collections.Concurrent; namespace redb.Route.Llm.Abstractions.Tools; /// /// Registry of tool descriptors available to the agent engine. Resolved by name at dispatch time. /// Descriptors registered via DSL (.AsLlmTool(...) / LlmTool.Define(...)) and /// the [ExposeAsLlmTool] attribute all land here. /// public interface IToolDescriptorRegistry { /// Adds or replaces a descriptor in the registry. void Register(ILlmToolDescriptor descriptor); /// Returns a descriptor by capability name, or null if not registered. ILlmToolDescriptor? Get(string name); /// Snapshot of all currently registered descriptors. IReadOnlyList All(); } /// Default in-memory . public sealed class ToolDescriptorRegistry : IToolDescriptorRegistry { private readonly ConcurrentDictionary _descriptors = new(StringComparer.Ordinal); /// /// /// The descriptor declares a caching policy on a tool that is not read-only. Every descriptor path /// converges here — the .AsLlmTool(...) DSL, LlmTool.Define(...).Build(), the /// [ExposeAsLlmTool] attribute and MCP discovery — so the rule is enforced once, for all of /// them, instead of only where the route author happens to use the DSL. /// public void Register(ILlmToolDescriptor descriptor) { ArgumentNullException.ThrowIfNull(descriptor); // A cached entry answers a call without running the tool, so caching a mutating tool suppresses // the side effect it stands for — up to the whole TTL, including legitimate repeats // ("send that invoice again"). Only a read-only tool may declare a caching policy. var safety = descriptor.Capability.Safety; if (safety.Caching != ToolCachingPolicy.None && safety.SideEffect != ToolSideEffect.ReadOnly) throw new InvalidOperationException( $"Tool '{descriptor.Capability.Name}' declares Caching={safety.Caching} with " + $"SideEffect={safety.SideEffect}. Only read-only tools may be cached — a cache hit would " + "suppress the side effect."); _descriptors[descriptor.Capability.Name] = descriptor; } /// public ILlmToolDescriptor? Get(string name) => _descriptors.TryGetValue(name, out var d) ? d : null; /// public IReadOnlyList All() => [.. _descriptors.Values]; } Path: redb-route/redb.Route.Llm.Abstractions/Tools/LlmTool.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/Tools/LlmTool.cs ---- using redb.Route.Llm.Abstractions.Tools; namespace redb.Route.Llm.Tools; /// /// Homeless static builder for . Use when the /// tool descriptor is authored outside of an /// (e.g. registered directly in DI via services.AddLlmTool(LlmTool.Define(...).Build())), /// or when the same descriptor needs to be shared across multiple routes. /// /// Pairs with the fluent route-level DSL .AsLlmTool(name) (see /// ) and the attribute-driven /// form. All three styles produce the /// same contract. /// /// /// /// var tool = LlmTool.Define("get_order") /// .EndpointUri("direct:order-lookup") /// .Description("Returns order details by id.") /// .Input("""{"type":"object","properties":{"orderId":{"type":"string"}},"required":["orderId"]}""") /// .SideEffect(ToolSideEffect.ReadOnly) /// .Cost(ToolCostClass.Cheap) /// .Build(); /// /// services.AddLlmTool(tool); /// /// /// public static class LlmTool { /// Starts a fluent definition for a tool descriptor with the given name. /// Tool name exposed to the model (must be unique per registry). public static LlmToolStaticBuilder Define(string name) { ArgumentException.ThrowIfNullOrWhiteSpace(name); return new LlmToolStaticBuilder(name); } } /// /// Fluent builder produced by . Call /// once all metadata has been set to materialise an /// . /// public sealed class LlmToolStaticBuilder { private readonly string _name; private 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; internal LlmToolStaticBuilder(string name) { _name = name; } /// Sets the target redb.Route endpoint URI (e.g. direct:order-lookup). public LlmToolStaticBuilder EndpointUri(string endpointUri) { ArgumentException.ThrowIfNullOrWhiteSpace(endpointUri); _endpointUri = endpointUri; return this; } /// Sets the human-readable description shown to the model. public LlmToolStaticBuilder Description(string description) { ArgumentException.ThrowIfNullOrWhiteSpace(description); _description = description; return this; } /// Sets the JSON Schema describing the tool's input arguments. public LlmToolStaticBuilder Input(string jsonSchema) { ArgumentException.ThrowIfNullOrWhiteSpace(jsonSchema); _inputSchema = jsonSchema; return this; } /// Declares the tool's side-effect class. public LlmToolStaticBuilder SideEffect(ToolSideEffect sideEffect) { _sideEffect = sideEffect; return this; } /// Declares the caching policy. public LlmToolStaticBuilder Caching(ToolCachingPolicy caching) { _caching = caching; return this; } /// Declares the cost class \u2014 drives budget enforcement. public LlmToolStaticBuilder Cost(ToolCostClass cost) { _cost = cost; return this; } /// Marks the tool as requiring explicit approval before each call. public LlmToolStaticBuilder 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 LlmToolStaticBuilder RequireClaim(string claim) { ArgumentException.ThrowIfNullOrWhiteSpace(claim); (_requiredClaims ??= []).Add(claim); return this; } /// /// Materialises the descriptor. Throws if was /// not set \u2014 the bridge has nothing to dispatch to without a target URI. /// public ILlmToolDescriptor Build() { if (string.IsNullOrWhiteSpace(_endpointUri)) throw new InvalidOperationException( $"LlmTool.Define('{_name}'): .EndpointUri(uri) must be called before .Build()."); 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] : [] } }; return new RouteToolBridge(capability, _endpointUri); } } Path: redb-route/redb.Route.Llm.Abstractions/Tools/LlmToolCapability.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/Tools/LlmToolCapability.cs ---- namespace redb.Route.Llm.Abstractions.Tools; /// /// Capability descriptor for a tool exposed to the LLM. The engine projects the /// , and into the provider /// request as tools[]; is server-side metadata and is never sent on /// the wire. /// /// What the engine consults in : /// (the approval gate), (claims, fail closed), /// (tool-result cache, read-only tools only) and /// (replay de-duplication and the caching gate). Each field /// states its own status; is the one still reserved. /// /// public sealed class LlmToolCapability { /// Stable tool name. Must match the regex [a-zA-Z][a-zA-Z0-9_]{0,63}. public required string Name { get; init; } /// Human-readable description shown to the model. public required string Description { get; init; } /// JSON Schema (object) describing the tool's input parameters. public required string InputSchema { get; init; } /// Governance metadata — side-effect, cost, caching, approval, claims. public LlmToolSafety Safety { get; init; } = new(); } Path: redb-route/redb.Route.Llm.Abstractions/Tools/LlmToolEnums.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/Tools/LlmToolEnums.cs ---- namespace redb.Route.Llm.Abstractions.Tools; /// /// Side-effect classification declared by a tool author. Read by the engine for two decisions: a tool /// whose is not may not declare a /// caching policy, because a cache hit suppresses the side effect the entry stands for; and an /// tool is not run inside an ambient transaction (a route's .Transacted()), /// because that transaction can roll back while the external action cannot. Beyond that the /// Mutating / External distinction stays declarative — it selects neither the approval gate /// nor the idempotency policy. /// public enum ToolSideEffect { /// Read-only: no state is mutated, so retries are harmless. The only class that may be cached. ReadOnly, /// Mutates internal state. Declared intent: a retry must carry an idempotency key. Mutating, /// Has external irreversible side-effects (mail, payment, deployment). Declared intent: /// requires approval — set explicitly, because /// approval is not derived from this value. Not run inside an ambient transaction: the model receives /// instead. External } /// /// Result-caching policy for . Enforced for read-only tools: the engine /// consults a cache and skips a call it can answer from it, reporting the skip to observers. A tool /// that declares Caching != None together with a mutating side effect is rejected at route /// build. /// public enum ToolCachingPolicy { /// Do not cache. None, /// Memoise per (tool, resolved endpoint address, input) for the lifetime of the agent run, /// in process — the entry dies with the run and never reaches a store. Memoize, /// Memoise across runs in the configured cache store with a TTL (24 h). An output the /// redaction filter changed is not cached. Persist } /// Cost class hint for budget-aware scheduling. Reserved — budgets are computed from /// real provider usage, not from this hint. public enum ToolCostClass { /// Sub-millisecond, no external IO. Cheap, /// Single-digit milliseconds, single network call. Moderate, /// Multi-second / external API / paid call. Expensive } Path: redb-route/redb.Route.Llm.Abstractions/Tools/LlmToolSafety.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/Tools/LlmToolSafety.cs ---- namespace redb.Route.Llm.Abstractions.Tools; /// /// Governance metadata attached to every . These are declarations: /// some are enforced by the engine, some are reserved for later work. Every property states which, /// so a reader never has to guess whether a field is a control point. /// public sealed class LlmToolSafety { /// /// Side-effect classification. Defaults to . /// Enforced — the engine reads it for two decisions. A tool that is not /// is de-duplicated through the idempotency store (a replay /// of the same tool_use id returns the stored result instead of running again); a /// read-only tool is not reserved at all. Only a read-only tool may declare a caching policy. /// Default matters: "declared nothing" and "declared ReadOnly" are indistinguishable, /// so a tool with no explicit class is treated as read-only — no replay protection. Set /// on anything that changes state. /// public ToolSideEffect SideEffect { get; init; } = ToolSideEffect.ReadOnly; /// /// Caching policy. Defaults to . /// Enforced for read-only tools — the engine answers a repeated identical call from a /// cache and reports the skip to observers. A mutating tool that declares a caching policy is /// rejected when its route is built. /// public ToolCachingPolicy Caching { get; init; } = ToolCachingPolicy.None; /// /// Cost class hint. Defaults to . /// Reserved — budgets are computed from real provider usage, not from this hint. /// public ToolCostClass Cost { get; init; } = ToolCostClass.Cheap; /// /// When true the tool requires an explicit approval decision before execution. /// Enforced — the engine awaits IApprovalGate before dispatching. Note that /// the shipped default gate approves automatically; a real control point requires replacing it. /// public bool RequiresApproval { get; init; } /// /// Claims required on the calling exchange's principal. Empty = no requirements. /// Enforced — the engine asks the registered IToolClaimsSource and denies the /// call when the claims cannot be verified. The default source reads the caller's principal from /// the exchange (ExchangePrincipal, a property — not a header) and takes its scope / /// scp values; AddRedbRouteLlm() registers it, so claims work out of the box. A /// deployment with another vocabulary registers its own source. An unrelated identity header, an /// anonymous caller and a run with no inbound request all fail the check. /// public IReadOnlyList RequiredClaims { get; init; } = []; } Path: redb-route/redb.Route.Llm.Abstractions/Tools/RouteToolBridge.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/Tools/RouteToolBridge.cs ---- using redb.Route.Abstractions; using redb.Route.Llm.Abstractions.Tools; namespace redb.Route.Llm.Tools; /// /// Bridges a fixed redb.Route endpoint into the LLM tool surface as an /// . The engine forwards the model's JSON /// input to on a linked child of the agent exchange, /// inheriting its transaction scope, DI scope, properties and route id. /// Headers are propagated by policy rather than inherited — see /// . /// public sealed class RouteToolBridge : ILlmToolDescriptor { /// Permissive default JSON Schema used when no explicit schema is supplied. public const string DefaultInputSchema = """{"type":"object","additionalProperties":true}"""; private readonly string _endpointUri; /// public LlmToolCapability Capability { get; } /// The fixed target endpoint URI this descriptor dispatches to (e.g. direct:order-lookup). public string EndpointUri => _endpointUri; /// Creates a bridge descriptor that forwards calls to . /// Tool capability metadata exposed to the model. /// Target endpoint URI (typically a direct: route). public RouteToolBridge(LlmToolCapability capability, string endpointUri) { ArgumentNullException.ThrowIfNull(capability); ArgumentException.ThrowIfNullOrWhiteSpace(endpointUri); Capability = capability; _endpointUri = endpointUri; } /// Creates a bridge descriptor from a class decorated with . /// Handler type carrying the attribute. /// Target endpoint URI that the handler is mounted on. public static RouteToolBridge FromAttribute(string endpointUri) { var attr = typeof(THandler).GetCustomAttributes(typeof(ExposeAsLlmToolAttribute), inherit: false) .OfType() .FirstOrDefault() ?? throw new InvalidOperationException( $"Type {typeof(THandler).FullName} is not decorated with [ExposeAsLlmTool]."); return new RouteToolBridge(attr.ToCapability(DefaultInputSchema), endpointUri); } /// public string BuildEndpointUri(string inputJson, IExchange parentExchange) => _endpointUri; } Path: redb-route/redb.Route.Llm.Abstractions/Tools/ToolResultErrors.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/Tools/ToolResultErrors.cs ---- namespace redb.Route.Llm.Abstractions.Tools; /// /// Model-facing tool_result error codes: what a tool call that could not execute reports back /// to the LLM. Deliberately terse — the model does not need the required-claims list, and handing it /// over would turn a tool_result into the one channel that leaks the tool's security policy. /// public static class ToolResultErrors { /// The tool requires claims the run's principal does not hold (or cannot prove). public const string ClaimsMissing = "claims_missing"; /// The approval gate refused this call; the reason text stays in the observer channel. public const string ApprovalDenied = "approval_denied"; /// /// The tool has an irreversible external effect and the run is inside a transaction that can still roll /// back, so the tool was not run. /// public const string ExternalInTransaction = "external_in_transaction"; } Path: redb-route/redb.Route.Llm.Abstractions/Tools/ToolSkipReasons.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/Tools/ToolSkipReasons.cs ---- namespace redb.Route.Llm.Abstractions.Tools; /// /// Stable SkipReason values the engine reports to IAgentObserver when a tool call is /// skipped instead of executed. This is the observer/audit channel; model-facing error codes live in /// . /// public static class ToolSkipReasons { /// /// Required claims could not be verified for the run's principal. The engine appends /// :<claim,claim> with the missing names — audit detail that must not reach the model. /// public const string ClaimsMissing = "claims_missing"; /// /// The tool was answered from its cache instead of being dispatched, so the underlying side effect /// did not run. Only and /// — that is, only read-only tools — can produce this. /// public const string CacheHit = "cache_hit"; /// /// This tool_use id was already executed in the same conversation and its stored result was /// returned instead of running the tool again. Only tools with a declared side effect (not /// ) are de-duplicated this way. /// public const string IdempotencyHit = "idempotency_hit"; /// /// The approval gate refused the call. The engine appends the gate's own reason text /// ("denied: <reason>"); the model sees only /// . /// public const string ApprovalDeniedPrefix = "denied:"; /// /// A tool was called while an ambient transaction was open (for /// example inside a route's .Transacted()). Its action cannot be rolled back with that /// transaction, so the engine did not run it; the model sees /// . /// public const string ExternalInTransaction = "external_in_transaction"; } Path: redb-route/redb.Route.Llm.Abstractions/redb.Route.Llm.Abstractions.csproj 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/redb.Route.Llm.Abstractions.csproj ---- redb.Route.Llm.Abstractions redb.Route.Llm.Abstractions Contracts for the redb.Route.Llm tool surface. Carries LlmToolCapability, LlmToolSafety, ILlmToolDescriptor, and the [ExposeAsLlmTool] attribute. Lightweight — depends on redb.Route abstractions only, no provider/HttpClient code. esb;messaging;llm;ai;tools;contracts;redb README.md