Ai::Tools

Beta

Turns C++ functions into tools a model can call: the schema comes from the struct, dispatch is by perfect hash, calls run in parallel and human approval is optional.

Optional module: turn it on with -DETHEREAL_AI_TOOLS=ONInclude #include <ethereal/cpp/ai/tools/tools_inc.hpp>C layer

tools_inc.hpp

#include <ethereal/cpp/ai/tools/tools_inc.hpp>

Aggregated entry point of Ai::Tools (AI-04): C++ functions as tools a model can call.

The vocabulary (tools_types.hpp), the context and the output of a call (tools_output.hpp), the registry (tools_registry.hpp), the runner (tools_runner.hpp) and the bridge to Ai::Llm (tools_llm.hpp). Behind ETHEREAL_AI_TOOLS, which needs ETHEREAL_AI_LLM.

tools_llm.hpp

#include <ethereal/cpp/ai/tools/tools_llm.hpp>

Ai::Tools with Ai::Llm: the tool list in a request, the tool uses of a response run and answered in the next message, and a minimal agent loop for the examples (the full runtime is AI-08).

function

DialectOf

Ethereal::Ai::Tools#
EToolDialect DialectOf( Llm::EProvider eProvider ) noexcept;

The dialect of the tool list of a provider: Anthropic for Anthropic, OpenAI for OpenAI and the compatible servers.

function

ApplyTools

Ethereal::Ai::Tools#
EStatus ApplyTools( const CToolRegistry & Registry, Llm::CRequest & Request, Llm::EProvider eProvider ) noexcept;

Puts the tool list of Registry in Request, in the dialect of eProvider (Llm::CRequest::SetToolsRaw: one copy of the list written by Finalize).

eOk, eNotFinalized, eUnsupported (the list of the dialect could not be written), eOutOfMemory, or eInvalidArgument when the request refused it.
function

ContinueWithTools

Ethereal::Ai::Tools#
EStatus ContinueWithTools( CToolRunner & Runner, CToolWorkspace & Work, const Llm::SResponse & Response, Llm::CRequest & Request, ETL_UINT32 * puCalls = nullptr, Job::IParallelFor * pParallel = nullptr, const SExecOptions * pExec = nullptr ) noexcept;

Runs every tool use of Response and appends to Request the response (an assistant message) and the results (a tool message with one tool result per call, in the order of the calls). Ready for the next turn.

With no tool use in the response nothing is appended and *puCalls is 0. ePendingApproval leaves Request untouched: decide on the workspace and call again with the same response, and the prepared batch runs.

puCalls
Receives the number of tool uses. May be null.
alias

void

Ethereal::Ai::Tools#
using PFN_OnToolResult = void ( * )( void * pUser, const SToolCall & Call, const SToolResult & Result );

Called after each tool result of the agent loop (to show it, to log it).

struct

SAgentOptions

Ethereal::Ai::Tools#
C++
struct   SAgentOptions
{
    /// @brief  Most requests to the model. The loop stops there even when the model
    ///             still calls tools.
    ETL_UINT32                    uMaxTurns = 8u;

    /// @brief  Stream the responses, with the events to this callback.
    bool                        bStream = false;
    Llm::PFN_OnStreamEvent        pfnEvent = nullptr;
    void *                        pEventUser = nullptr;

    /// @brief  Each tool result, after it ran.
    PFN_OnToolResult            pfnOnResult = nullptr;
    void *                        pResultUser = nullptr;

    /// @brief  The calls of a turn run on this (null: one after the other).
    Job::IParallelFor *            pParallel = nullptr;

    /// @brief  The options of the executions.
    const SExecOptions *        pExec = nullptr;
};
function

RunAgent

Ethereal::Ai::Tools#
EStatus RunAgent( Llm::CClient & Client, Llm::CRequest & Request, CToolRunner & Runner, CToolWorkspace & Work, Llm::SResponse & Response, Llm::SCallResult & Result, const SAgentOptions & Options = {}, ETL_UINT32 * puTurns = nullptr ) noexcept;

A minimal agent: sends the request, runs the tool uses of the response, answers them, and repeats until the model stops calling tools or the turns run out. The request keeps the whole conversation.

puTurns
Receives the number of requests sent. May be null.
eOk when the model answered without tools, eModelError when a call to the model failed (Result says why), ePendingApproval when an approval is needed (decide, then call again: the loop goes on from there), or eLimitExceeded when the turns ran out with the model still calling tools.

tools_output.hpp

#include <ethereal/cpp/ai/tools/tools_output.hpp>

What a handler receives besides its arguments (CToolContext) and where it writes its result (CToolOutput).

Both belong to the runner: a handler gets them for one call and must not keep them. The memory of both is reused from one call to the next, so a call allocates nothing once warm.

enum

EPart

Ethereal::Ai::Tools#
C++
enum class   EPart : ETL_UINT8
{
    eText = 0,        /// sText.
    eJson,            /// sText is a JSON value: the structured content (MCP structuredContent).
    eImage,            /// sText holds the bytes (not base64), sMime the media type.
    eResource        /// An embedded resource: sUri, sMime and sText.
};

The kind of one part of an output.

struct

SOutputPart

Ethereal::Ai::Tools#
C++
struct   SOutputPart
{
    EPart                eKind = EPart::eText;
    std::string_view    sText;
    std::string_view    sMime;
    std::string_view    sUri;
};

One part of an output, as read back. The views live until the output is written again.

const

kMaxOutputParts

Ethereal::Ai::Tools#
inline constexpr ETL_UINT32 kMaxOutputParts = 16u;

Most parts in one output.

class

CToolOutput

Ethereal::Ai::Tools#

The result of a call, written by the handler: text, a JSON value (the structured content), images, embedded resources, or an error message.

class CToolOutput

The bytes go to a buffer the output keeps between calls. Each Add returns eOk, eLimitExceeded (more than kMaxOutputParts parts) or eOutOfMemory. A tool with an output schema must write its result with Json or JsonOf: the runner validates it.

For the providers (Ai::Llm), the text parts, the JSON and a short note for each image and resource become the text of the tool result. The MCP server (AI-05) sends every part as its own content block.

constructor

CToolOutput

#
explicit CToolOutput( Memory::IAllocator * pAllocator = nullptr ) noexcept;
function

Text

#
EStatus Text( std::string_view sText ) noexcept;

A text part.

function

Json

#
EStatus Json( std::string_view sJson ) noexcept;

A JSON value given as text (checked to be one JSON value): the structured content. At most one per output (eInvalidArgument for a second).

function

JsonOf

#
template < typename T > EStatus JsonOf( const T & Value ) noexcept

The structured content from a described type (Schema::Encode).

function

Image

#
EStatus Image( std::span< const unsigned char > Bytes, std::string_view sMime ) noexcept;

An image: the bytes (not base64) and the media type ("image/png").

function

Resource

#
EStatus Resource( std::string_view sUri, std::string_view sMime, std::string_view sText ) noexcept;

An embedded resource: its URI, media type and text.

function

Error

#
EStatus Error( std::string_view sMessage ) noexcept;

The message the model sees when the call fails. Return eError (or eInvalidArguments) from the handler with it.

function

Clear

#
void Clear( void ) noexcept;

Forgets every part, keeps the memory.

function

PartCount

#
ETL_UINT32 PartCount( void ) const noexcept

Number of parts.

function

Part

#
SOutputPart Part( ETL_UINT32 u ) const noexcept;

Part u (empty past the last).

function

Structured

#
std::string_view Structured( void ) const noexcept;

The structured content, or empty.

function

HasError

#
bool HasError( void ) const noexcept

True when Error was called.

function

ErrorText

#
std::string_view ErrorText( void ) const noexcept;

The text given to Error.

function

Bytes

#
std::size_t Bytes( void ) const noexcept

Bytes held by the parts.

function

Capacity

#
std::size_t Capacity( void ) const noexcept

Capacity of the buffer (diagnostics).

enum

ELogLevel

Ethereal::Ai::Tools#
C++
enum class   ELogLevel : ETL_UINT8
{
    eDebug = 0,
    eInfo,
    eWarning,
    eError
};
alias

void

Ethereal::Ai::Tools#
using PFN_ToolLog = void ( * )( void * pUser, ELogLevel eLevel, std::string_view sTool, std::string_view sMessage );

Receives what the handlers log (CToolContext::Log) and what the runner says about each call. May be called from several threads at once.

alias

ETL_UINT64

Ethereal::Ai::Tools#
using PFN_NowNs = ETL_UINT64 ( * )( void * pUser );

The monotonic clock of the runner, in nanoseconds (the tests give a manual one).

class

CToolContext

Ethereal::Ai::Tools#

What a handler knows about its call.

class CToolContext

IsCancelled is the cooperative stop: it turns true when the caller cancels or when the time limit of the call passes. A handler that may run long should look at it and return eCancelled. The module never kills a thread: a handler that never looks runs to its end.

function

CallId

#
std::string_view CallId( void ) const noexcept

The id of the call (the tool use id of the provider, or the MCP request).

function

ToolName

#
std::string_view ToolName( void ) const noexcept

The name of the tool.

function

User

#
void * User( void ) const noexcept

The user pointer of the runner (or of the execution).

function

IsCancelled

#
bool IsCancelled( void ) const noexcept;

True when the call should stop: the caller cancelled, or the time limit passed.

function

DeadlineNs

#
ETL_UINT64 DeadlineNs( void ) const noexcept

The deadline on the clock of the runner (nanoseconds), or 0 for none.

function

RemainingMs

#
ETL_INT64 RemainingMs( void ) const noexcept;

Milliseconds left before the deadline (0 when passed), or -1 for none.

function

Arena

#
Memory::CMemoryArena & Arena( void ) noexcept

An arena for the call, empty at the start of each call. The text of the arguments with escapes lives here too.

function

Log

#
void Log( ELogLevel eLevel, std::string_view sMessage ) const noexcept;

Logs through the runner's PFN_ToolLog (nothing without one).

function

DecodeArgs

#
template < typename T > bool DecodeArgs( const std::string_view sJson, T & Out ) noexcept

Decodes JSON into a described type with the decoder of the call. Used by the typed tools before the handler, and by a JSON tool that wants a type for part of its input.

True when the value decoded and is valid. Otherwise the runner reports the error of the decode as invalid arguments when the handler returns.
function

ValidateArgs

#
bool ValidateArgs( const Schema::CSchema & Compiled, std::string_view sJson ) noexcept;

Validates JSON against a compiled schema with the validator of the call. Used by the JSON tools and the tools with no arguments before the handler.

True when valid. Otherwise the runner reports the error as invalid arguments when the handler returns.

tools_registry.hpp

#include <ethereal/cpp/ai/tools/tools_registry.hpp>

The registry of tools: C++ functions with a typed input, tools with a JSON schema, the final form with a perfect hash of the names and the tool lists written once in each dialect.

A registry is built on one thread (Add, Include, the filters), then Finalize freezes it: from there it is immutable and may be shared by any number of threads and runners.

A registry may reference the tools of another (Include, and the filtered ones): nothing of the handlers is copied, and the other registry must outlive it and not change.

alias

EToolStatus

Ethereal::Ai::Tools#
template < typename TArgs > using PFN_Tool = EToolStatus ( * )( const TArgs & Args, CToolContext & Ctx, CToolOutput & Out );

A typed handler: the arguments decoded and validated, the context, the output.

alias

EToolStatus

Ethereal::Ai::Tools#
using PFN_ToolNoArgs = EToolStatus ( * )( CToolContext & Ctx, CToolOutput & Out );

A handler with no arguments.

alias

EToolStatus

Ethereal::Ai::Tools#
using PFN_ToolJson = EToolStatus ( * )( void * pUser, std::string_view sArgsJson, CToolContext & Ctx, CToolOutput & Out );

A handler that takes the JSON of the arguments, already validated against the schema it was registered with.

enum

EToolKind

Ethereal::Ai::Tools#
C++
enum class   EToolKind : ETL_UINT8
{
    eTyped = 0,        /// Add< T >: a described struct.
    eNoArgs,        /// Add with PFN_ToolNoArgs.
    eJson            /// AddJson: a schema given as JSON.
};
struct

STool

Ethereal::Ai::Tools#
C++
struct   STool
{
    std::string_view                sName;
    SToolMeta                        Meta;            /// sTitle, sDescription and sTags point into the registry.
    EToolKind                        eKind = EToolKind::eTyped;

    /// @brief  The input schema: by dialect for a typed tool, as given otherwise.
    std::string_view ( * pfnInputText )( Schema::EDialect eDialect ) noexcept = nullptr;
    std::string_view                sInputSchema;
    const Schema::CSchema *            pInputCompiled = nullptr;        /// The JSON tools: the arguments are validated against it.

    /// @brief  The output schema, when there is one.
    std::string_view ( * pfnOutputText )( Schema::EDialect eDialect ) noexcept = nullptr;
    const Schema::CSchema * ( * pfnOutputCompiled )( Schema::EDialect eDialect ) noexcept = nullptr;
    std::string_view                sOutputSchema;
    const Schema::CSchema *            pOutputCompiled = nullptr;

    /// @brief  The call.
    Detail::PFN_Thunk                pfnThunk = nullptr;
    Detail::PFN_Any                    pfnHandler = nullptr;
    void *                            pUser = nullptr;

    /// @brief  The key of the name in the perfect hash.
    ETL_UINT64                        uKey = 0;

    /// @brief  True when the tool has an output schema.
    ETL_API_NOIGN    bool HasOutputSchema( void ) const ETL_NOEXCEPT { return pfnOutputText != nullptr || !sOutputSchema.empty(); }

    /// @brief  The input schema in a dialect of the AI-02.
    ETL_API_NOIGN    std::string_view InputSchema( Schema::EDialect eDialect ) const ETL_NOEXCEPT
    {
        return pfnInputText != nullptr ? pfnInputText( eDialect ) : sInputSchema;
    }

    /// @brief  The output schema in a dialect, or empty.
    ETL_API_NOIGN    std::string_view OutputSchema( Schema::EDialect eDialect ) const ETL_NOEXCEPT
    {
        return pfnOutputText != nullptr ? pfnOutputText( eDialect ) : sOutputSchema;
    }

    /// @brief  The compiled output schema, or null.
    ETL_API_NOIGN    const Schema::CSchema * OutputCompiled( void ) const ETL_NOEXCEPT
    {
        return pfnOutputCompiled != nullptr ? pfnOutputCompiled( Schema::EDialect::eGeneric ) : pOutputCompiled;
    }
};

A tool as the registry keeps it. Read only for the caller.

struct

SRegistryOptions

Ethereal::Ai::Tools#
C++
struct   SRegistryOptions
{
    /// @brief  The names the registry takes.
    ENameRules            eNameRules = ENameRules::ePortable;

    /// @brief  The provider lists ask for the strict mode ("strict": true and the strict
    ///             dialects of the AI-02: eAnthropicStrict, eOpenAIStrict). The runner must
    ///             then decode with Schema::EDialect::eOpenAIStrict for OpenAI.
    bool                bStrict = false;

    /// @brief  Most tools (the perfect hash takes up to 65534).
    ETL_UINT32            uMaxTools = 65534u;

    /// @brief  Allocator of the tables. Null: the default.
    Memory::IAllocator *    pAllocator = nullptr;
};
class

CToolRegistry

Ethereal::Ai::Tools#

The tools a model may call.

class CToolRegistry

Building allocates (the names, the descriptions, the schemas of the JSON tools compiled, the tables). Lookup, Tool and ToolsJson do not, and are thread safe once the registry is final.

constructor

CToolRegistry

#
explicit CToolRegistry( const SRegistryOptions & Options = {} ) noexcept;
function

Add

#
template < typename TArgs > EStatus Add( const std::string_view sName, const PFN_Tool< TArgs > pfnHandler, const SToolMeta & Meta = {} ) noexcept

A tool whose arguments are the described struct TArgs (ETL_META_DESCRIBE, with the attributes of the AI-02). The schema is Schema::SchemaOf< TArgs > in each dialect, and the arguments are decoded straight into a TArgs.

eOk, eInvalidName, eDuplicateName, eFinalized, eLimitExceeded, eOutOfMemory, eInvalidArgument (a null handler).
function

AddStructured

#
template < typename TArgs, typename TOut > EStatus AddStructured( const std::string_view sName, const PFN_Tool< TArgs > pfnHandler, const SToolMeta & Meta = {} ) noexcept

A typed tool with an output schema: the one of TOut. The handler writes its result with CToolOutput::JsonOf( TOut ), and the runner validates it.

function

Add

#
EStatus Add( std::string_view sName, PFN_ToolNoArgs pfnHandler, const SToolMeta & Meta = {} ) noexcept;

A tool with no arguments. The schema is an object with no properties, and the arguments must be "{}" (or empty).

function

AddJson

#
EStatus AddJson( std::string_view sName, std::string_view sInputSchema, PFN_ToolJson pfnHandler, void * pUser, const SToolMeta & Meta = {}, std::string_view sOutputSchema = {} ) noexcept;

A tool with its schemas as JSON. The input schema is compiled here (an error is eInvalidSchema), and the arguments are validated against it before the handler. The output schema is optional.

function

Include

#
EStatus Include( const CToolRegistry & Other ) noexcept;

Every tool of Other, referenced (not copied). Other must outlive this registry and not change. A name already here is eDuplicateName, and then nothing of Other is added.

function

IncludeTagged

#
EStatus IncludeTagged( const CToolRegistry & Other, std::string_view sTag ) noexcept;

The tools of Other that carry the tag sTag (SToolMeta::sTags), referenced.

function

IncludeNamed

#
EStatus IncludeNamed( const CToolRegistry & Other, std::span< const std::string_view > Names ) noexcept;

The tools of Other with these names, referenced. A name Other does not have is eInvalidArgument, and then nothing is added.

function

Finalize

#
EStatus Finalize( void ) noexcept;

Freezes the registry: the perfect hash of the names and the three tool lists. From here nothing can be added, and the registry is thread safe.

eOk, eOutOfMemory, or eFinalized when called twice. A list that cannot be written (a name the dialect does not take) stays empty: see ToolsJsonStatus.
function

IsFinalized

#
bool IsFinalized( void ) const noexcept;

True after Finalize.

function

Count

#
ETL_UINT32 Count( void ) const noexcept;

Number of tools.

function

Find

#
ETL_UINT32 Find( std::string_view sName ) const noexcept;

The index of the tool named sName, or kNotFound. Before Finalize it is a linear search.

function

Tool

#
const STool & Tool( ETL_UINT32 u ) const noexcept;

Tool u (u below Count).

function

Suggest

#
ETL_UINT32 Suggest( std::string_view sName ) const noexcept;

The index of the name closest to sName (for "did you mean"), or kNotFound when nothing is close. Not for the hot path: it looks at every name.

function

ToolsJson

#
std::string_view ToolsJson( EToolDialect eDialect ) const noexcept;

The tool list in eDialect, written by Finalize: a JSON array for the providers (Llm::CRequest::SetToolsRaw copies it), the array of the "tools" member for MCP. Empty before Finalize, or when the list could not be written (a name the dialect does not take, see ToolsJsonStatus).

function

ToolsJsonStatus

#
EStatus ToolsJsonStatus( EToolDialect eDialect ) const noexcept;

Why a list is empty after Finalize: eOk, eUnsupported (a name the dialect does not take) or eOutOfMemory.

function

CheckDialect

#
EStatus CheckDialect( EToolDialect eDialect, Schema::SDialectReport & Report, ETL_UINT32 * puTool ) const noexcept;

Runs the dialect check of the AI-02 on the input schema of every tool, as the list of eDialect carries it.

Report
Receives the report of the first tool that is not compatible.
puTool
Receives that tool, or kNotFound when every one is compatible.
function

Options

#
const SRegistryOptions & Options( void ) const noexcept

The options.

function

SchemaDialect

#
Schema::EDialect SchemaDialect( EToolDialect eDialect ) const noexcept;

The dialect of the AI-02 the list of eDialect uses for the schemas.

function

HasPerfectHash

#
bool HasPerfectHash( void ) const noexcept;

True when the perfect hash was built (false: the lookup compares one by one, which happens only with equal keys). For the tests.

tools_runner.hpp

#include <ethereal/cpp/ai/tools/tools_runner.hpp>

The execution of tool calls: lookup, decode with validation, the handler, the output, and every error turned into a short result the model can act on. The calls of one turn in parallel, the policies (approval, allow and block lists, rate limit, output size) and the limits of each tool.

A CToolRunner is built over a final registry and may be used by several threads at once: it holds the policies and the state of each tool (calls running, rate limit). A CToolWorkspace belongs to one thread and holds the memory of the calls (decoders, outputs, arenas, messages): the results point into it until the next call with it. Once warm, a call allocates nothing.

Nothing that comes from the model can bring the process down: a name, arguments or a handler that throws become a result with the error flag.

struct

SToolCall

Ethereal::Ai::Tools#
C++
struct   SToolCall
{
    std::string_view    sId;        /// The id of the call (tool use id, MCP request id). May be empty.
    std::string_view    sName;
    std::string_view    sArgs;        /// The JSON of the arguments. Empty is "{}".
};

One call, as the model made it. The views must live until the results are read.

struct

SToolResult

Ethereal::Ai::Tools#
C++
struct   SToolResult
{
    std::string_view        sId;
    std::string_view        sName;
    ETL_UINT32                uTool = kNotFound;            /// The tool, or kNotFound.
    EErrorClass                eError = EErrorClass::eNone;
    bool                    bIsError = false;            /// The is_error / isError of the providers and of MCP.
    bool                    bTruncated = false;            /// The text was cut at SRunnerOptions::uMaxOutputBytes.

    /// @brief  The text for the model: the output as one text (the text parts, the JSON,
    ///             a note per image and resource), or the error message.
    std::string_view        sText;

    /// @brief  The structured content (CToolOutput::Json), or empty.
    std::string_view        sStructured;

    /// @brief  Every part of the output (for MCP). Null when the handler did not run.
    const CToolOutput *        pOutput = nullptr;

    /// @brief  Time in the handler, in nanoseconds of the runner's clock.
    ETL_UINT64                uHandlerNs = 0;
};

The result of one call. The views point into the workspace and into the call, and live until the next execution with the workspace.

enum

EApproval

Ethereal::Ai::Tools#
C++
enum class   EApproval : ETL_UINT8
{
    eApprove = 0,
    eDeny,            /// The model sees "denied" with the reason.
    eModify            /// The call runs with other arguments (validated again).
};
struct

SApprovalDecision

Ethereal::Ai::Tools#
C++
struct   SApprovalDecision
{
    EApproval            eDecision = EApproval::eApprove;
    std::string_view    sReason;        /// For eDeny. Copied.
    std::string_view    sNewArgs;        /// For eModify: the JSON of the new arguments. Copied.
};
struct

SApprovalRequest

Ethereal::Ai::Tools#
C++
struct   SApprovalRequest
{
    ETL_UINT32                uCall = 0;            /// The index of the call in the batch.
    const SToolCall *        pCall = nullptr;
    const STool *            pTool = nullptr;
};
alias

void

Ethereal::Ai::Tools#
using PFN_Approve = void ( * )( void * pUser, const SApprovalRequest & Request, SApprovalDecision & Decision );

The synchronous approval hook: called on the thread of the execution, one call at a time, before any handler of the batch runs.

enum

EApprovalScope

Ethereal::Ai::Tools#
C++
enum class   EApprovalScope : ETL_UINT8
{
    eNone = 0,            /// None.
    eSideEffects,        /// The tools that are not read only.
    eDestructive,        /// The tools that are destructive (and not read only).
    eAll                /// Every call.
};

Which calls need an approval.

struct

SRunnerOptions

Ethereal::Ai::Tools#
C++
struct   SRunnerOptions
{
    /// @brief  Which calls need an approval, and the synchronous hook. Without a hook the
    ///             approval is asynchronous: the execution stops with ePendingApproval, the
    ///             caller decides (CToolWorkspace::Decide) and calls CToolRunner::Run.
    EApprovalScope                            eApprovalScope = EApprovalScope::eNone;
    PFN_Approve                                pfnApprove = nullptr;
    void *                                    pApproveUser = nullptr;

    /// @brief  Only these tools may run (empty: all). Resolved when the runner is built.
    std::span< const std::string_view >        AllowList;

    /// @brief  These tools never run. Resolved when the runner is built.
    std::span< const std::string_view >        BlockList;

    /// @brief  Most bytes of the text of a result: past it the text is cut (at a UTF-8
    ///             boundary) and a note tells the model. Zero: no limit.
    std::size_t                                uMaxOutputBytes = 100000u;

    /// @brief  Time limit of a call whose tool has none, in milliseconds. Zero: none.
    ETL_INT32                                iDefaultTimeoutMs = 0;

    /// @brief  The dialect the decoder takes the arguments in (eOpenAIStrict accepts the
    ///             null of an optional field, for a registry with bStrict).
    Schema::EDialect                        eArgsDialect = Schema::EDialect::eGeneric;

    /// @brief  Suggest the closest name for an unknown tool.
    bool                                    bSuggestNames = true;

    /// @brief  The user pointer of the handlers (CToolContext::User).
    void *                                    pUser = nullptr;

    /// @brief  Where the logs go. Null: nowhere.
    PFN_ToolLog                                pfnLog = nullptr;
    void *                                    pLogUser = nullptr;

    /// @brief  The clock. Null: the monotonic clock of the system.
    PFN_NowNs                                pfnNow = nullptr;
    void *                                    pNowUser = nullptr;

    /// @brief  Allocator of the state. Null: the default.
    Memory::IAllocator *                    pAllocator = nullptr;
};
struct

SExecOptions

Ethereal::Ai::Tools#
C++
struct   SExecOptions
{
    /// @brief  Set to true (from any thread) to cancel: the handlers see IsCancelled.
    const std::atomic< bool > *        pCancel = nullptr;

    /// @brief  Time limit of each call, in milliseconds, when lower than the tool's. Zero: none.
    ETL_INT32                        iTimeoutMs = 0;

    /// @brief  The user pointer of the handlers for this execution. Null: the runner's.
    void *                            pUser = nullptr;
};

Options of one execution.

class

CToolWorkspace

Ethereal::Ai::Tools#

The memory of the calls of one thread, and the calls waiting for approval.

class CToolWorkspace
constructor

CToolWorkspace

#
explicit CToolWorkspace( Memory::IAllocator * pAllocator = nullptr ) noexcept;
function

Reserve

#
EStatus Reserve( ETL_UINT32 uCalls ) noexcept;

Prepares the memory of uCalls calls at once (optional: it grows when needed).

function

PendingCount

#
ETL_UINT32 PendingCount( void ) const noexcept;

Number of calls of the prepared batch waiting for a decision.

function

Pending

#
SApprovalRequest Pending( ETL_UINT32 u ) const noexcept;

Pending call u: which call of the batch, and its tool.

function

Decide

#
EStatus Decide( ETL_UINT32 u, const SApprovalDecision & Decision ) noexcept;

The decision on pending call u (any thread, but one at a time). The texts are copied.

function

IsPrepared

#
bool IsPrepared( void ) const noexcept;

True when a batch is prepared (CToolRunner::Prepare) and not run yet.

function

Discard

#
void Discard( void ) noexcept;

Forgets the prepared batch.

function

ReservedBytes

#
std::size_t ReservedBytes( void ) const noexcept;

Bytes the workspace holds (diagnostics).

class

CToolRunner

Ethereal::Ai::Tools#

Runs calls of the tools of a final registry.

class CToolRunner
constructor

CToolRunner

#
explicit CToolRunner( const CToolRegistry & Registry, const SRunnerOptions & Options = {} ) noexcept;
Registry
A final registry. It must outlive the runner.
Options
The policies.
function

Status

#
EStatus Status( void ) const noexcept

eOk, or why the runner cannot run (eNotFinalized, eOutOfMemory).

function

Registry

#
const CToolRegistry & Registry( void ) const noexcept

The registry.

function

Execute

#
EStatus Execute( CToolWorkspace & Work, const SToolCall & Call, SToolResult & Out, const SExecOptions * pExec = nullptr ) noexcept;

One call. A call that needs an approval with no hook ends ePendingApproval.

eOk (the result says whether the call failed), ePendingApproval, eInvalidArgument, eNotFinalized, eOutOfMemory.
function

ExecuteAll

#
EStatus ExecuteAll( CToolWorkspace & Work, std::span< const SToolCall > Calls, std::span< SToolResult > Results, Job::IParallelFor * pParallel = nullptr, const SExecOptions * pExec = nullptr ) noexcept;

The calls of one turn, in parallel on pParallel (null: one after the other on this thread), with the results in the order of the calls. The limits of each tool (uMaxConcurrency, bExclusive) hold across every execution of the runner.

eOk, ePendingApproval (decide, then Run), eInvalidArgument (fewer results than calls), eOutOfMemory.
function

Prepare

#
EStatus Prepare( CToolWorkspace & Work, std::span< const SToolCall > Calls ) noexcept;

The first half of ExecuteAll: looks every call up, applies the lists and the rate limit, and asks the hook (when there is one). Afterwards the workspace lists the calls waiting for a decision.

function

Run

#
EStatus Run( CToolWorkspace & Work, std::span< SToolResult > Results, Job::IParallelFor * pParallel = nullptr, const SExecOptions * pExec = nullptr ) noexcept;

The second half: runs the prepared batch. A call still waiting is denied ("no decision").

function

Running

#
ETL_UINT32 Running( ETL_UINT32 uTool ) const noexcept;

Calls of tool uTool running now (diagnostics and tests).

function

PeakRunning

#
ETL_UINT32 PeakRunning( ETL_UINT32 uTool ) const noexcept;

The most calls of tool uTool that ran at once (tests).

function

NowNs

#
ETL_UINT64 NowNs( void ) const noexcept;

Now, on the clock of the runner.

tools_types.hpp

#include <ethereal/cpp/ai/tools/tools_types.hpp>

The vocabulary of Ai::Tools: the status codes, what a handler returns, the classes of error the model sees, the dialects of the tool lists, the name rules and the metadata of a tool.

The name rules are the ones of the providers and of MCP, read in their documentation.

enum

EStatus

Ethereal::Ai::Tools#
C++
enum class   EStatus : ETL_UINT32
{
    eOk = 0,
    eInvalidArgument,        /// A null, an empty name, a value out of range.
    eOutOfMemory,
    eNotLicensed,
    eBufferTooSmall,
    eInvalidName,            /// The name breaks the rules of the registry (ENameRules).
    eDuplicateName,            /// A tool with this name is already in the registry.
    eInvalidSchema,            /// A JSON schema that does not compile.
    eFinalized,                /// The registry is final: nothing can be added.
    eNotFinalized,            /// The operation needs a final registry.
    eLimitExceeded,            /// Too many tools, too many parts in an output, a name too long.
    eUnsupported,            /// The dialect cannot carry this tool (a name with a dot for a provider).
    ePendingApproval,        /// Calls wait for a decision (CToolWorkspace::Decide, then CToolRunner::Run).
    eModelError                /// RunAgent: the call to the model failed (its Llm::SCallResult says why).
};

The result of the functions of the module (not of a tool call: a call that failed is a result with an error for the model, see EErrorClass).

function

StatusName

Ethereal::Ai::Tools#
const char * StatusName( EStatus eStatus ) noexcept;

The name of a status ("ok", "invalid name"...). Never null.

enum

EToolStatus

Ethereal::Ai::Tools#
C++
enum class   EToolStatus : ETL_UINT8
{
    eOk = 0,
    eError,                    /// The tool failed.
    eInvalidArguments,        /// The arguments decoded but make no sense (a rule the schema cannot say).
    eCancelled,                /// The handler stopped because the context said so.
    eTimedOut                /// The handler gave up on its own time limit.
};

What a handler returns.

eError and eInvalidArguments send the text of CToolOutput::Error to the model (or a generic one). eCancelled and eTimedOut are for a handler that saw CToolContext::IsCancelled: the runner says which one it was.

enum

EErrorClass

Ethereal::Ai::Tools#
C++
enum class   EErrorClass : ETL_UINT8
{
    eNone = 0,
    eUnknownTool,            /// No tool with this name (with the closest name, when there is one).
    eInvalidArguments,        /// Not JSON, or against the schema (with the JSON Pointer and the rule).
    eHandlerFailed,            /// The handler returned an error, or threw.
    eTimedOut,                /// The time limit passed.
    eCancelled,                /// The caller cancelled.
    eDenied,                /// The approval said no.
    eNotAllowed,            /// The allow list or the block list.
    eRateLimited,            /// The rate limit of the tool.
    eInvalidOutput,            /// The structured output breaks the output schema of the tool.
    eInternal                /// Out of memory inside the runner.
};

Why a call ended as an error for the model (SToolResult::eError).

function

ErrorClassName

Ethereal::Ai::Tools#
const char * ErrorClassName( EErrorClass eClass ) noexcept;

The name of a class ("unknown tool", "invalid arguments"...). Never null.

enum

EToolDialect

Ethereal::Ai::Tools#
C++
enum class   EToolDialect : ETL_UINT8
{
    eAnthropic = 0,        /// [{"name","description","input_schema"}], the Messages API.
    eOpenAi,            /// [{"type":"function","function":{"name","description","parameters"}}], Chat Completions and the compatible servers.
    eMcp,                /// The "tools" of an MCP tools/list result: name, title, description, inputSchema, outputSchema, annotations.
    eCount
};

The shape of a tool list (CToolRegistry::ToolsJson).

function

ToolDialectName

Ethereal::Ai::Tools#
const char * ToolDialectName( EToolDialect eDialect ) noexcept;

The name of a dialect ("anthropic", "openai", "mcp"). Never null.

enum

ENameRules

Ethereal::Ai::Tools#
C++
enum class   ENameRules : ETL_UINT8
{
    ePortable = 0,        /// [a-zA-Z0-9_-], 1 to 64. The default: the list goes to any dialect.
    eAnthropic,            /// [a-zA-Z0-9_-], 1 to 128.
    eMcp                /// [a-zA-Z0-9_.-], 1 to 128. The OpenAI and Anthropic lists refuse the names they cannot take.
};

Which names a registry takes.

From the documentation (stage0.md, section 3): Anthropic takes ^[a-zA-Z0-9_-]{1,128}$, OpenAI the same characters up to 64, and MCP (as a SHOULD) 1 to 128 of the same characters plus the dot. ePortable is what all three take.

function

IsValidToolName

Ethereal::Ai::Tools#
bool IsValidToolName( std::string_view sName, ENameRules eRules = ENameRules::ePortable ) noexcept;

True when sName follows eRules.

const

kMaxToolNameBytes

Ethereal::Ai::Tools#
inline constexpr std::size_t kMaxToolNameBytes = 128u;

The longest name any rule takes.

const

kNotFound

Ethereal::Ai::Tools#
inline constexpr ETL_UINT32 kNotFound = 0xFFFFFFFFu;

Index returned by the lookups when there is no tool.

struct

SToolMeta

Ethereal::Ai::Tools#
C++
struct   SToolMeta
{
    /// @brief  Human readable name (MCP "title"). May be empty.
    std::string_view    sTitle;

    /// @brief  What the tool does, for the model. Strongly recommended.
    std::string_view    sDescription;

    /// @brief  The tool does not change its environment (MCP readOnlyHint, default false).
    bool                bReadOnly = false;

    /// @brief  The changes may destroy (MCP destructiveHint, default true). Meaningful
    ///             only when bReadOnly is false.
    bool                bDestructive = true;

    /// @brief  Calling twice with the same arguments changes nothing more (MCP
    ///             idempotentHint, default false).
    bool                bIdempotent = false;

    /// @brief  The tool reaches an open world (MCP openWorldHint, default true).
    bool                bOpenWorld = true;

    /// @brief  Time limit of one call, in milliseconds. Zero: the runner's default.
    ETL_INT32            iTimeoutMs = 0;

    /// @brief  Most calls of this tool running at once, across the runner. Zero: no limit.
    ETL_UINT32            uMaxConcurrency = 0;

    /// @brief  The tool runs alone: no other call of the runner runs with it.
    bool                bExclusive = false;

    /// @brief  Rate limit of the tool, in calls per minute. Zero: none.
    ETL_UINT32            uCallsPerMinute = 0;

    /// @brief  Free tags, separated by commas ("files,read"), for the filtered views.
    std::string_view    sTags;
};

What a tool says about itself, beyond its schema.

The four hints are the annotations of MCP, with the defaults MCP gives them (a tool that says nothing may write, destroy, repeat effects and reach the world). They go in the MCP list, and the approval policy reads bReadOnly and bDestructive. The texts are copied by the registry.