What it does
- Schema generated from the C++ struct
- Dispatch by perfect hash
- Parallel execution
- Optional human approval
Measured
- Name lookup with 10,000 tools: 17.5 ns (GCC)
- Dispatch: 237.5 ns at p50 (GCC), 256 ns (MSVC), p99 within 1 µs
- Name lookup on MSVC: 21.3 ns. Target of 20 ns not met
Known limits
- A tool's time limit is cooperative: the handler has to look at it
C++ functions as tools a language model can call (Ethereal::Ai::Tools). A registry holds each tool with its JSON Schema, generated from a described C++ struct or given as JSON, and writes the tool list once for Anthropic, OpenAI and MCP. A runner takes the calls the model made, decodes the arguments straight into the struct (with validation), runs the handler and gives back a result text for the model. Errors become useful messages for the model instead of crashes. The calls of one turn can run in parallel, under policies: approval, allow and block lists, per-tool rate limits and an output size cap. A bridge to Ai::Llm puts the list in a request and runs the agent loop.
The module is optional: -DETHEREAL_AI_TOOLS=ON (off by default). It requires -DETHEREAL_AI_LLM=ON, which in turn requires -DETHEREAL_AI_SCHEMA=ON, and CMake stops with the reason when one is missing. When disabled, none of it goes into the binary.
#include <ethereal/cpp/ai/tools/tools_inc.hpp>
namespace Llm = Ethereal::Ai::Llm;
namespace Tools = Ethereal::Ai::Tools;
namespace Sc = Ethereal::Ai::Schema;
namespace M = Ethereal::Meta;
struct SReadFileArgs
{
char sPath[ 260 ];
ETL_INT32 iMaxBytes;
};
ETL_META_DESCRIBE( SReadFileArgs,
ETL_META_FIELD( sPath, M::Description( "Relative path of a text file" ), Sc::MinLength( 1 ) ),
ETL_META_FIELD( iMaxBytes, M::Description( "Most bytes to read" ), M::Range( 1, 65536 ), M::Default( 4096 ) ) );
static Tools::EToolStatus ReadFile( const SReadFileArgs & A, Tools::CToolContext & Ctx, Tools::CToolOutput & Out )
{
// A is already decoded and valid against the schema. Rules the schema cannot say go here.
// IsInsideCurrentDirectory and ReadText stand for your own code.
if( !IsInsideCurrentDirectory( A.sPath ) )
{
static_cast< void >( Out.Error( "only relative paths inside the current directory" ) );
return Tools::EToolStatus::eInvalidArguments;
}
static_cast< void >( Out.Text( ReadText( A.sPath, A.iMaxBytes ) ) ); // or Out.JsonOf( Value ), Out.Image( Bytes, "image/png" )
return Tools::EToolStatus::eOk;
}
Tools::SToolMeta Meta;
Meta.sDescription = "Reads a text file of the current directory";
Meta.bReadOnly = true;
Meta.iTimeoutMs = 2000;
Tools::CToolRegistry Registry;
Registry.Add< SReadFileArgs >( "read_file", &ReadFile, Meta );
Registry.Finalize(); // immutable from here, shared by threads
Tools::CToolRunner Runner( Registry ); // the policies, usable from several threads
Tools::CToolWorkspace Work; // the memory of the calls, one per thread
// With Ai::Llm: the list goes into the request, and the loop runs until the model stops calling tools.
Tools::ApplyTools( Registry, Request, Llm::EProvider::eAnthropic );
const Tools::EStatus e = Tools::RunAgent( Client, Request, Runner, Work, Response, Result );
// Or one call by hand (an MCP server, your own loop).
Tools::SToolResult R;
Runner.Execute( Work, Tools::SToolCall{ sId, "read_file", sArgsJson }, R ); // R.sText, R.bIsErrorAlways include tools_inc.hpp: it brings in the module and Ai::Llm. The SDK ships a complete program, a terminal chat where the model can read a file, calculate and tell the time, in examples/ai/chat_tool_calling.cpp. Like chat_basic, it reads the API key from an environment variable (ANTHROPIC_API_KEY, OPENAI_API_KEY, or ETL_COMPAT_API_KEY for a compatible server) and never from the code.
---
The API
The registry (CToolRegistry)
| Call | What it does |
|---|---|
Add< TArgs >( name, pfnHandler, Meta ) | a typed tool: the schema is generated from the described struct, and the arguments are decoded straight into it |
AddStructured< TArgs, TOut >( name, pfnHandler, Meta ) | a typed tool with an output schema. The handler writes with CToolOutput::JsonOf, and the runner validates it |
Add( name, PFN_ToolNoArgs, Meta ) | a tool with no arguments (the arguments must be {} or empty) |
AddJson( name, inputSchema, PFN_ToolJson, pUser, Meta, outputSchema ) | a tool with its schemas as JSON. The input schema is compiled here (eInvalidSchema on error) |
Include, IncludeTagged, IncludeNamed | views: tools of another registry referenced, not copied |
Finalize() | freezes the registry: perfect hash of the names, and the three tool lists written once |
ToolsJson( EToolDialect ) / ToolsJsonStatus( EToolDialect ) | the list for eAnthropic, eOpenAi or eMcp, and why it is empty when it is |
Find( name ), Tool( index ), Count(), Suggest( name ) | lookup, the tool (STool), the count, the closest name |
CheckDialect( EToolDialect, Report, &uTool ) | runs the Ai::Schema dialect check on every input schema |
SRegistryOptions chooses the name rules (ENameRules), the strict mode of the provider lists (bStrict) and the maximum number of tools (uMaxTools, up to 65,534).
ENameRules | Names taken |
|---|---|
ePortable (default) | [a-zA-Z0-9_-], 1 to 64 bytes. The list goes to any dialect |
eAnthropic | [a-zA-Z0-9_-], 1 to 128 bytes |
eMcp | [a-zA-Z0-9_.-], 1 to 128 bytes. The provider lists refuse the names they cannot take |
SToolMeta describes a tool beyond its schema: sTitle, sDescription, the four MCP hints (bReadOnly, bDestructive, bIdempotent, bOpenWorld, with the MCP defaults: not read only, destructive, not idempotent, open world), iTimeoutMs, uMaxConcurrency, bExclusive, uCallsPerMinute and comma-separated sTags for the filtered views.
The handler
A handler returns an EToolStatus: eOk, eError, eInvalidArguments (the arguments decoded but make no sense), eCancelled or eTimedOut. It writes into CToolOutput: Text, Json or JsonOf( Value ) (the structured content, at most one per output), Image( bytes, mime ), Resource( uri, mime, text ) and Error( message ), up to kMaxOutputParts (16) parts. CToolContext gives the call id, the tool name, the user pointer, IsCancelled(), RemainingMs(), an arena for the call and Log().
The runner (CToolRunner) and the workspace (CToolWorkspace)
| Call | What it does |
|---|---|
Execute( Work, Call, Result ) | one call |
ExecuteAll( Work, Calls, Results, pParallel ) | the calls of one turn, results in the order of the calls |
Prepare( Work, Calls ) / Run( Work, Results, pParallel ) | the two halves of ExecuteAll, with the asynchronous approval in between |
CToolWorkspace::PendingCount(), Pending( u ), Decide( u, Decision ), Discard() | the calls waiting for approval, and the decision on each |
SToolCall is sId, sName, sArgs (JSON, empty means {}). SToolResult gives sText (the text for the model), bIsError, eError (EErrorClass), bTruncated, sStructured, pOutput (every part, for MCP) and uHandlerNs. SExecOptions adds a cancel flag (std::atomic< bool >), a per-call time limit and a user pointer for one execution.
ExecuteAll runs on a Job::IParallelFor (from ethereal/cpp/concurrency/parallel_for.hpp). Job::CJobParallelFor uses the job system, Job::CInlineParallelFor runs on the calling thread, and a null pointer runs the calls one after the other. uMaxConcurrency and bExclusive hold across every execution of the runner.
Policies (SRunnerOptions)
| Option | Default | What it does |
|---|---|---|
eApprovalScope | eNone | which calls need approval: eSideEffects (not read only), eDestructive, eAll |
pfnApprove | null | the synchronous hook. Null makes the approval asynchronous: ePendingApproval, then Decide and Run |
AllowList / BlockList | empty | only these tools run / these never run |
uMaxOutputBytes | 100,000 | longer result texts are cut at a UTF-8 boundary, and a note tells the model |
iDefaultTimeoutMs | 0 (none) | time limit of a call whose tool has none |
eArgsDialect | eGeneric | eOpenAIStrict accepts the null of an optional field, for a strict registry with OpenAI |
bSuggestNames | true | suggest the closest name for an unknown tool |
pfnLog, pfnNow | null | where the logs go, and the clock |
An approval can approve, deny with a reason the model sees (EApproval::eDeny), or run the call with other arguments (eModify), which are validated again.
Errors for the model
A call that fails is not an error of the API: Execute returns eOk, and the result carries bIsError and a message for the model.
EErrorClass | When, and what the model reads |
|---|---|
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), or the handler said so |
eHandlerFailed | the handler returned eError or threw an exception |
eTimedOut / eCancelled | the time limit passed / the caller cancelled |
eDenied / eNotAllowed | the approval said no / the allow or block list |
eRateLimited | the rate limit of the tool |
eInvalidOutput | the structured output breaks the output schema |
eInternal | out of memory inside the runner |
The module's own functions return Tools::EStatus (eOk, eInvalidName, eDuplicateName, eInvalidSchema, eFinalized, eNotFinalized, ePendingApproval, eModelError and the usual ones), named by StatusName. ErrorClassName names the classes.
The bridge to Ai::Llm
| Call | What it does |
|---|---|
ApplyTools( Registry, Request, eProvider ) | copies the list in the provider's dialect into the request (CRequest::SetToolsRaw) |
ContinueWithTools( Runner, Work, Response, Request, &uCalls ) | runs every tool use of the response and appends the response and the results, ready for the next turn |
RunAgent( Client, Request, Runner, Work, Response, Result, Options ) | a minimal agent loop: send, run the tool uses, answer, repeat until the model stops calling tools |
SAgentOptions sets uMaxTurns (8 by default), streaming (bStream, pfnEvent), a callback per tool result (pfnOnResult), the pParallel and the execution options. RunAgent returns eOk when the model answered without tools, eModelError when a call to the model failed (Result says why), ePendingApproval (decide, then call again: the loop goes on from there) or eLimitExceeded when the turns ran out. The request keeps the whole conversation. CRequest::Reset clears the tool list, so call ApplyTools again after it.
---
Limits and behavior
- Threads. The final registry is immutable and thread safe. Execution state (running calls, rate limits) belongs to the runner. Call memory belongs to the workspace, one thread at a time. Result texts live until the next execution with the same workspace.
- Memory. Building the registry allocates. After warm-up, a call does not allocate.
- Time limits are cooperative.
CToolContext::IsCancelled()turns true on cancellation or when the time limit passes. The module never kills a thread: a handler that never looks runs to its end. - Nothing from the model crashes the process. Lookup, decode, validation and the handler (inside a
try) all end in a result. - Provider results are text. For Anthropic and OpenAI the text parts, the JSON and a short note per image or resource become the tool result text. The full parts stay in
CToolOutputfor the Ai::Mcp module, which sends each one as its own content block. - Not here: sandboxing of the handlers, and the providers' server-side tools (Ai::Llm can carry those as raw JSON).
---
C layer
Header ethereal/c/ai/tools.h, the dynamic path. A tool is a C callback (ETLC_ToolFn) that receives the JSON of the arguments, already validated against its schema, and writes its result into a buffer. When the buffer is too small it returns ETLC_TOOL_BUFFER_TOO_SMALL with the size needed, and the layer calls again with that much (up to 16 MB). It is slower than the typed C++ tools (no decode into a struct) and is what a C program or a language binding uses.
static int32_t Echo( void * pUser, const ETLC_ToolCallInfo * pCall, char * pOut, size_t uCapacity, size_t * puWritten )
{
*puWritten = pCall->uArgsLen;
if( pCall->uArgsLen > uCapacity )
return ETLC_TOOL_BUFFER_TOO_SMALL;
memcpy( pOut, pCall->pArgs, pCall->uArgsLen );
return ETLC_TOOL_OK;
}
ETLC_ToolRegistryCreate( NULL, &hRegistry );
ETLC_ToolRegistryAdd( hRegistry, "echo", "{\"type\":\"object\"}", NULL, Echo, NULL, NULL );
ETLC_ToolRegistryFinalize( hRegistry );
ETLC_ToolRunnerCreate( hRegistry, NULL, &hRunner );
ETLC_ToolsApply( hRegistry, hLlmRequest, ETLC_LLM_PROVIDER_ANTHROPIC );
do
{
if( ETLC_LlmSend( hClient, hLlmRequest, NULL, NULL ) != ETLC_OK )
break;
if( ETLC_ToolsContinue( hRunner, hLlmRequest, &uCalls ) != ETLC_OK )
break;
} while( uCalls != 0 );Covered: the registry (ETLC_ToolRegistryAdd, Include, IncludeTagged, Finalize, Find, ToolsJson), the runner with its options (approval scope, synchronous hook, allow and block lists, output cap, default time limit), the asynchronous approval (ETLC_ToolRunnerPendingCount, ETLC_ToolRunnerDecide, ETLC_ToolRunnerRunPrepared), and the bridge to the Llm C layer (ETLC_ToolsApply, ETLC_ToolsContinue). Two module codes: ETLC_AI_INVALID_TOOL_NAME (-5811) and ETLC_AI_PENDING_APPROVAL (-5812). A runner handle holds one workspace: one thread at a time per runner, so create one per thread. Left out compared with C++: typed tools, approval with modified arguments, IncludeNamed, and ExecuteAll on a parallel executor.
The C layer is tested as C11 and C17, and with a full conversation through the two C layers against a local test server, for Anthropic and OpenAI.
---
What was verified
- Registration, names, the three lists, views, perfect hash with 1 to 10,000 random names (no false positive on names that are not there), every error class with its exact message, parallel order of results, concurrency limits, exclusive tools, cooperative time limits, both approval modes, per-tool rate limit, output truncation, and three-turn conversations through
RunAgentfor the three providers, whole and streamed, against a local test server. - Clean on GCC, MSVC (Release and Debug), ASan with UBSan, and TSan. One hour of libFuzzer on the dispatch (152.8 million executions) with no finding. Line coverage of the module: 90.6%.
- Live provider tests are pending.
chat_tool_callinghas not yet been run by the vendor against the real Anthropic or OpenAI API.
---
Performance
Release builds, one thread. GCC on Linux and MSVC on Windows.
| Measure | Target | GCC | MSVC |
|---|---|---|---|
| Name lookup p50, 16 / 1,000 / 10,000 tools | 20 ns | 8.0 / 13.0 / 19.3 ns | 10.0 / 15.2 / 21.2 ns |
| Full dispatch p50 (lookup, decode of a 3-field struct, empty handler, short text) | 300 ns | 237.5 ns | 256 to 259 ns |
| Full dispatch p99 | 1 µs | 430 to 442 ns | 397 to 602 ns |
Zero allocations per call after warm-up, enforced by the tests.
Target not met: the name lookup with 10,000 tools on MSVC, 21.2 ns against 20 ns. The cause is memory latency and the Windows x64 calling convention, which passes the std::string_view of the name by pointer. GCC meets the target at every size.