@ratel-ai/sdk
Raw API of @ratel-ai/sdk — every exported class, function, type, and constant of the TypeScript SDK.
v0.7.0 · TypeScript · npm · source
Generated from the doc comments at
ratel-ai/ratel@d8635d5— do not edit by hand. Regenerate withpnpm sync:apiinapps/docs.
@ratel-ai/sdk — TypeScript SDK for Ratel, the context engineering platform
for AI agents. In-process, no infra: a native (Rust) BM25/semantic/hybrid
index behind ToolCatalog and SkillCatalog, MCP ingestion via
registerMcpServer, and the framework-neutral capability tools
(searchCapabilitiesTool, invokeToolTool,
getSkillContentTool) that let a model discover and run what the
catalogs hold. Everything emits OTel ratel.*/gen_ai.* spans plus a local
trace stream (ADR-0007).
Classes
DimensionMismatchError
A vector's dimension did not match the embedding cache's — the model changed
under an existing corpus. A subclass of EmbedderError (so
instanceof EmbedderError still catches it), mirroring Python's
DimensionMismatchError. Its EmbedderError.code is "DimensionMismatch".
Extends
Constructors
Constructor
new DimensionMismatchError(
message):DimensionMismatchError
Parameters
| Parameter | Type | Description |
|---|---|---|
message | string | The underlying dimension-mismatch description. |
Returns
Overrides
Properties
cause?
optionalcause?:unknown
Inherited from
code
readonlycode:string
Stable machine-readable discriminant — one of "Load", "Download",
"NotCached", "ModelMismatch", "DimensionMismatch",
"EmbeddingsNotBuilt", "Inference", or "CacheUnwritable". Prefer this (or
instanceof) over parsing Error.message.
Inherited from
message
message:
string
Inherited from
name
name:
string
Inherited from
stack?
optionalstack?:string
Inherited from
stackTraceLimit
staticstackTraceLimit:number
The Error.stackTraceLimit property specifies the number of stack frames
collected by a stack trace (whether generated by new Error().stack or
Error.captureStackTrace(obj)).
The default value is 10 but may be set to any valid JavaScript number. Changes
will affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will not capture any frames.
Inherited from
Methods
captureStackTrace()
staticcaptureStackTrace(targetObject,constructorOpt?):void
Creates a .stack property on targetObject, which when accessed returns
a string representing the location in the code at which
Error.captureStackTrace() was called.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`The first line of the trace will be prefixed with
${myObject.name}: ${myObject.message}.
The optional constructorOpt argument accepts a function. If given, all frames
above constructorOpt, including constructorOpt, will be omitted from the
generated stack trace.
The constructorOpt argument is useful for hiding implementation
details of error generation from the user. For instance:
function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();Parameters
| Parameter | Type |
|---|---|
targetObject | object |
constructorOpt? | Function |
Returns
void
Inherited from
EmbedderError.captureStackTrace
prepareStackTrace()
staticprepareStackTrace(err,stackTraces):any
Parameters
| Parameter | Type |
|---|---|
err | Error |
stackTraces | CallSite[] |
Returns
any
See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Inherited from
EmbedderError.prepareStackTrace
EmbedderError
An embedding model failed to load, download, or run — the base class for every
dense-retrieval failure raised from register / searchAsync on a
"semantic"/"hybrid" catalog. Mirrors Python's EmbedderError.
Extends
Error
Extended by
Constructors
Constructor
new EmbedderError(
message,code):EmbedderError
Parameters
| Parameter | Type | Description |
|---|---|---|
message | string | The underlying failure description (the core error text). |
code | string | The stable EmbedderError.code discriminant. |
Returns
Overrides
Error.constructor
Properties
cause?
optionalcause?:unknown
Inherited from
Error.cause
code
readonlycode:string
Stable machine-readable discriminant — one of "Load", "Download",
"NotCached", "ModelMismatch", "DimensionMismatch",
"EmbeddingsNotBuilt", "Inference", or "CacheUnwritable". Prefer this (or
instanceof) over parsing Error.message.
message
message:
string
Inherited from
Error.message
name
name:
string
Inherited from
Error.name
stack?
optionalstack?:string
Inherited from
Error.stack
stackTraceLimit
staticstackTraceLimit:number
The Error.stackTraceLimit property specifies the number of stack frames
collected by a stack trace (whether generated by new Error().stack or
Error.captureStackTrace(obj)).
The default value is 10 but may be set to any valid JavaScript number. Changes
will affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will not capture any frames.
Inherited from
Error.stackTraceLimit
Methods
captureStackTrace()
staticcaptureStackTrace(targetObject,constructorOpt?):void
Creates a .stack property on targetObject, which when accessed returns
a string representing the location in the code at which
Error.captureStackTrace() was called.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`The first line of the trace will be prefixed with
${myObject.name}: ${myObject.message}.
The optional constructorOpt argument accepts a function. If given, all frames
above constructorOpt, including constructorOpt, will be omitted from the
generated stack trace.
The constructorOpt argument is useful for hiding implementation
details of error generation from the user. For instance:
function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();Parameters
| Parameter | Type |
|---|---|
targetObject | object |
constructorOpt? | Function |
Returns
void
Inherited from
Error.captureStackTrace
prepareStackTrace()
staticprepareStackTrace(err,stackTraces):any
Parameters
| Parameter | Type |
|---|---|
err | Error |
stackTraces | CallSite[] |
Returns
any
See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Inherited from
Error.prepareStackTrace
IntentGraph
A shared usage-ranking intent graph (ADR-0014): clusters of past queries, each remembering the capabilities invoked after them.
Hand the same instance to both registries. One cluster carries a tools
map and a skills map, so a tool catalog and a skill catalog sharing a graph
learn from and rank against one set of clusters. Giving them separate graphs
duplicates every cluster and halves the evidence behind each.
Constructors
Constructor
new IntentGraph():
IntentGraph
An empty graph — knows nothing until a search is followed by an invoke.
Returns
Accessors
clusterCount
Get Signature
get clusterCount():
number
How many clusters the graph holds. 0 is the cold-start state, in which
the graph contributes nothing to ranking.
Returns
number
rev
Get Signature
get rev():
number
Monotonic write counter — bumped once per mutation (a confirmed
observation, a rebuild). Never affects ranking; it is a primitive for your
storage layer. Snapshot it after each save: a later value means unsaved
learning (save-when-changed), and a stored graph whose rev is higher than
the one you loaded was written by another process (stale-base detection).
Returns
number
Methods
toJson()
toJson():
string
Serialize to the protocol/v1 wire form — for inspection, or to carry
what was learned across processes.
The graph is in-process only; persistence is yours. It mutates on every
confirmed invoke, so unsaved observations are lost on a crash — persist on
a cadence or at shutdown. Use rev to save only when it changed and to
detect a concurrent writer; single-writer is the supported model.
SENSITIVE: the output contains the raw text of past user queries (the
cluster members). Treat a persisted graph like your query/telemetry log
— restrict permissions (0600), keep it out of version control and
images, and do not ship it to a less-trusted store.
Returns
string
fromJson()
staticfromJson(json):IntentGraph
Adopt a graph serialized in the protocol/v1 wire form — produced by
a previous toJson or by Ratel Cloud.
Throws if the JSON is malformed or declares a schema version this build does not read (a consumer rejects rather than degrading).
Parameters
| Parameter | Type |
|---|---|
json | string |
Returns
McpToolsListError
Paginated MCP tools/list failed — repeated cursor or page cap exceeded.
Thrown by registerMcpServer when listing upstream tools; mirrors Python's
McpToolsListError.
Extends
Error
Constructors
Constructor
new McpToolsListError(
message,code):McpToolsListError
Parameters
| Parameter | Type | Description |
|---|---|---|
message | string | Human-readable failure description. |
code | McpToolsListErrorCode | Stable McpToolsListErrorCode discriminant. |
Returns
Overrides
Error.constructor
Properties
cause?
optionalcause?:unknown
Inherited from
Error.cause
code
readonlycode:McpToolsListErrorCode
Prefer McpToolsListErrorCode (or instanceof) over parsing Error.message.
message
message:
string
Inherited from
Error.message
name
name:
string
Inherited from
Error.name
stack?
optionalstack?:string
Inherited from
Error.stack
stackTraceLimit
staticstackTraceLimit:number
The Error.stackTraceLimit property specifies the number of stack frames
collected by a stack trace (whether generated by new Error().stack or
Error.captureStackTrace(obj)).
The default value is 10 but may be set to any valid JavaScript number. Changes
will affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will not capture any frames.
Inherited from
Error.stackTraceLimit
Methods
captureStackTrace()
staticcaptureStackTrace(targetObject,constructorOpt?):void
Creates a .stack property on targetObject, which when accessed returns
a string representing the location in the code at which
Error.captureStackTrace() was called.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`The first line of the trace will be prefixed with
${myObject.name}: ${myObject.message}.
The optional constructorOpt argument accepts a function. If given, all frames
above constructorOpt, including constructorOpt, will be omitted from the
generated stack trace.
The constructorOpt argument is useful for hiding implementation
details of error generation from the user. For instance:
function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();Parameters
| Parameter | Type |
|---|---|
targetObject | object |
constructorOpt? | Function |
Returns
void
Inherited from
Error.captureStackTrace
prepareStackTrace()
staticprepareStackTrace(err,stackTraces):any
Parameters
| Parameter | Type |
|---|---|
err | Error |
stackTraces | CallSite[] |
Returns
any
See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Inherited from
Error.prepareStackTrace
SkillCatalog
In-memory catalog of skills, ranked by the native SkillRegistry retrieval
engine. The on-demand analog of ToolCatalog: registered skills are
searched by relevance; the matching body is fetched only on
SkillCatalog.invoke.
Constructors
Constructor
new SkillCatalog(
options?):SkillCatalog
Create an empty catalog.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | SkillCatalogOptions | Trace sink, default retrieval method, and embedding model. Construction validates configuration but never loads a model. |
Returns
Accessors
experimentalAdaptiveRankingStatus
Get Signature
get experimentalAdaptiveRankingStatus():
AdaptiveRankingStatus
Whether adaptive usage ranking is active, inactive, or paused by a model
change — see the native AdaptiveRankingStatus.
Returns
Methods
drainTraceEvents()
drainTraceEvents():
unknown[]
Drain the envelopes captured by a "memory" trace sink, emptying its
buffer. Same contract as ToolCatalog.drainTraceEvents.
Returns
unknown[]
The captured envelopes in record order; [] unless the active
sink is "memory".
experimentalDisableAdaptiveRanking()
experimentalDisableAdaptiveRanking():
void
Turn adaptive usage ranking off; the graph keeps what it learned.
Returns
void
experimentalEnableAdaptiveRanking()
experimentalEnableAdaptiveRanking(
graph,options?):void
Turn on adaptive usage ranking against graph (ADR-0014): the catalog
ranks against what users have actually invoked after similar queries, and
keeps learning as it is used.
Pass the same IntentGraph to a ToolCatalog so both learn into one set of clusters.
Set rebuildOnModelChange to auto-recover a model-mismatched graph on the
next dense (semantic/hybrid) search rather than staying paused until you
call experimentalRebuildIntentGraph yourself. Off by default — the rebuild is an
embedding pass (cost, possible EmbedderError, and it mutates the graph).
Parameters
| Parameter | Type |
|---|---|
graph | IntentGraph |
options | { rebuildOnModelChange?: boolean; warnOnModelMismatch?: boolean; } |
options.rebuildOnModelChange? | boolean |
options.warnOnModelMismatch? | boolean |
Returns
void
experimentalRebuildIntentGraph()
experimentalRebuildIntentGraph():
Promise<void>
Re-embed the intent graph's members under the current model and replace its centroids — call after changing the embedding model. Preserves members, support, and edges. See experimentalEnableAdaptiveRanking.
Returns
Promise<void>
get()
get(
skillId):Skill|undefined
Look up a skill by id.
Parameters
| Parameter | Type | Description |
|---|---|---|
skillId | string | The id to look up. |
Returns
Skill | undefined
The skill as registered (including body), or undefined for an
unknown id.
has()
has(
skillId):boolean
Whether a skill with this id is registered.
Parameters
| Parameter | Type | Description |
|---|---|---|
skillId | string | The id to look up. |
Returns
boolean
true if SkillCatalog.invoke would find it.
invoke()
invoke(
skillId):string
Return a skill's body for dispatch, recording a skill_invoke event.
Throws on an unknown id — callers at the capability-tool boundary translate that
into a structured error for the agent.
Parameters
| Parameter | Type | Description |
|---|---|---|
skillId | string | Id of a registered skill. |
Returns
string
The skill's body ("" when it was registered without one).
recordEvent()
recordEvent(
event):void
Record a custom event on the local trace stream (ADR-0007). Same contract
as ToolCatalog.recordEvent: the event is a tagged wire-shape object
({ type: "...", ... }, snake_case fields) and an unknown shape throws.
Parameters
| Parameter | Type | Description |
|---|---|---|
event | object | The trace event to record. |
Returns
void
register()
register(
skills):Promise<void>
Add one skill or a batch to the catalog — the single entry point for
both. Replaces an id in place when already registered. Name,
description, and tags are indexed for ranking; tools, metadata, and
body are stored but not indexed (body is the dispatch payload,
fetched by SkillCatalog.invoke). On a "semantic"/"hybrid"
catalog, embeds the batch in one pass on a libuv worker after metadata is
indexed — embedding errors surface here, at registration. A
"bm25" catalog never loads a model.
A model or dimension change is not recovered in place — construct a new catalog and re-register.
Parameters
| Parameter | Type | Description |
|---|---|---|
skills | Skill | readonly Skill[] | A single skill or a readonly array of them. Pass the whole batch at once for a single embedding request. |
Returns
Promise<void>
replaceAll()
replaceAll(
skills):PendingReplace
Make skills the entire content of the catalog: ids absent from the batch
are removed, the rest are added or updated. The whole-catalog counterpart
to SkillCatalog.register, for a source that reloads a catalog
rather than pushing individual changes. Mutates in place, so every holder
of this catalog — ratel()'s r.skills, each adapted view, and the
capability tools taken from modelTools() — observes the reload without
being rebuilt.
Removal is unconditional. Skills registered in-process are dropped just
like any others, since the batch is the catalog. A host that keeps local
skills alongside a remote source composes the batch itself:
await catalog.replaceAll([...localSkills, ...remoteSkills]).
Embedding follows the same two-phase contract as
SkillCatalog.register: the corpus swap lands first, then the batch
is embedded. Only genuinely new or re-worded skills are embedded — an
unchanged id keeps its vector, so reloading an unchanged catalog costs no
embedding calls at all. If the embedding pass fails, the new corpus is
already live and BM25 still ranks it; semantic search reports
EmbeddingsNotBuilt until a later pass succeeds.
A concurrent operation refuses the call outright rather than applying it
half-way, so two overlapping reloads can never blend into one corpus.
Because the swap is the synchronous half, that refusal throws at the call
site rather than rejecting the returned promise. Note that any in-flight
SkillCatalog.searchAsync can trigger it, including a plain BM25 one
— registry busy is retryable and not exclusive to dense work.
Parameters
| Parameter | Type | Description |
|---|---|---|
skills | readonly Skill[] | The complete catalog contents. A repeated id keeps its last entry. An empty array clears the catalog. |
Returns
The counts, already final, over a promise for the embedding pass —
see PendingReplace. .added/.removed can be read before that
pass settles, but the value must still always be awaited (or
.catch()-ed), or an embedding failure becomes an unhandled rejection.
search()
search(
query,topK,origin?,method?):SkillHit[]
Search the catalog synchronously with BM25. A "semantic"/"hybrid"
call throws synchronously with guidance to use
SkillCatalog.searchAsync.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
query | string | undefined | Natural-language description of the task at hand. |
topK | number | undefined | Maximum number of hits to return. |
origin | SearchOrigin | "direct" | Who initiated the call (default "direct"); recorded on the trace event and span, never affects ranking. |
method? | SearchMethod | undefined | Per-call override of the catalog's default retrieval method. |
Returns
SkillHit[]
Up to topK BM25 hits, best-first with ties broken by skill id.
Semantic/dense/hybrid methods throw migration guidance; use
SkillCatalog.searchAsync for those methods.
searchAsync()
searchAsync(
query,topK,origin?,method?):Promise<SkillHit[]>
Search with any retrieval method without blocking the Node.js event loop.
Parameters
| Parameter | Type | Default value |
|---|---|---|
query | string | undefined |
topK | number | undefined |
origin | SearchOrigin | "direct" |
method? | SearchMethod | undefined |
Returns
Promise<SkillHit[]>
size()
size():
number
Number of registered skills (distinct ids). searchCapabilitiesTool uses
this to decide whether to advertise a skills bucket at all.
Returns
number
The count.
SkillRegistry
Typed facade over the native skill registry — the skill twin of ToolRegistry. SkillCatalog is the higher-level surface; reach for this directly only when bare metadata is enough.
Constructors
Constructor
new SkillRegistry(
embedding?,method?):SkillRegistry
Create a registry with an optional embedding model and retrieval method.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
embedding? | EmbeddingSpec | undefined | Embedding model for semantic/hybrid retrieval — see ToolRegistry.constructor. |
method? | SearchMethod | "bm25" | "bm25" (default, model-free) or "semantic"/"hybrid", which makes SkillRegistry.register embed the batch inline. |
Returns
Accessors
experimentalAdaptiveRankingStatus
Get Signature
get experimentalAdaptiveRankingStatus():
AdaptiveRankingStatus
Whether adaptive usage ranking is contributing ("active"), off
("inactive"), not yet determinable ("unknown"), or paused because the
embedding model changed ("paused: dim mismatch" / "paused: model mismatch"). Gate on this instead of reading stderr if you prefer.
Returns
Methods
drainTraceEvents()
drainTraceEvents():
unknown[]
Drain captured envelopes from a "memory" sink; [] otherwise.
Returns
unknown[]
experimentalDisableAdaptiveRanking()
experimentalDisableAdaptiveRanking():
void
Turn adaptive usage ranking off: ranking returns to the base engine and the graph stops growing. The graph keeps what it learned, so re-enabling resumes rather than restarts.
Returns
void
experimentalEnableAdaptiveRanking()
experimentalEnableAdaptiveRanking(
graph,options?):void
Turn on adaptive usage ranking against graph (ADR-0014).
Wires both halves: the registry ranks against the graph, and its trace sink is decorated with a learner that grows it from search-then-invoke pairs — a capability the user actually invoked after a query becomes evidence for similar queries later.
Pass the same IntentGraph to the tool and skill registries. One cluster holds both a tool and a skill edge map, so sharing gives one set of clusters with all the evidence behind it; separate graphs duplicate every cluster and split the evidence.
Only queries that match a cluster are affected — anything else ranks exactly
as it would have. With a graph attached, SearchHit.score becomes a fusion
score rather than a raw BM25 score, so use rank for ordering and
fused to detect the scale, not the raw score.
Parameters
| Parameter | Type |
|---|---|
graph | IntentGraph |
options | { rebuildOnModelChange?: boolean; warnOnModelMismatch?: boolean; } |
options.rebuildOnModelChange? | boolean |
options.warnOnModelMismatch? | boolean |
Returns
void
experimentalRebuildIntentGraph()
experimentalRebuildIntentGraph():
Promise<void>
Re-embed the intent graph's members under the current embedding model and replace its centroids. Call after changing the model: a graph's centroids are only comparable to queries from the model that built them, so on a swap the usage arm pauses until this runs. Members, support, and edges are preserved — only the centroids move to the new space.
Returns
Promise<void>
recordEvent()
recordEvent(
event):void
Record a custom event on the local trace stream (ADR-0007).
Parameters
| Parameter | Type |
|---|---|
event | object |
Returns
void
register()
register(
item):Promise<void>
Register one skill or a batch, replacing any existing id in place — see ToolRegistry.register for the embed-inside contract.
Parameters
Returns
Promise<void>
search()
search(
query,topK):SkillHit[]
Lexical BM25 search over skills — see ToolRegistry.search.
Parameters
| Parameter | Type |
|---|---|
query | string |
topK | number |
Returns
SkillHit[]
searchWithMethod()
searchWithMethod(
query,topK,origin,method):SkillHit[]
Synchronous search restricted to BM25 — see ToolRegistry.searchWithMethod.
Parameters
| Parameter | Type |
|---|---|
query | string |
topK | number |
origin | SearchOrigin |
method | SearchMethod |
Returns
SkillHit[]
searchWithMethodAsync()
searchWithMethodAsync(
query,topK,origin,method):Promise<SkillHit[]>
Search on a libuv worker — see ToolRegistry.searchWithMethodAsync.
Parameters
| Parameter | Type |
|---|---|
query | string |
topK | number |
origin | SearchOrigin |
method | SearchMethod |
Returns
Promise<SkillHit[]>
searchWithOrigin()
searchWithOrigin(
query,topK,origin):SkillHit[]
BM25 search with an explicit trace origin.
Parameters
| Parameter | Type |
|---|---|
query | string |
topK | number |
origin | SearchOrigin |
Returns
SkillHit[]
setTraceSink()
setTraceSink(
config):void
Replace the trace sink; subsequent events go to the new destination.
Parameters
| Parameter | Type |
|---|---|
config | TraceSinkConfig |
Returns
void
ToolCatalog
In-process catalog of executable tools, ranked by the native Rust registry.
The SDK's central surface: ToolCatalog.register tools (or ingest an
MCP server's via registerMcpServer), ToolCatalog.search them by
relevance, and ToolCatalog.invoke the chosen one. Every operation
emits both an OTel span (to whatever provider is active — see telemetry.ts)
and a local trace event (to the sink from ToolCatalogOptions.trace),
per ADR-0007.
Example
import { ToolCatalog } from "@ratel-ai/sdk";
import { readFile } from "node:fs/promises";
const catalog = new ToolCatalog();
await catalog.register({
id: "read_file",
name: "read_file",
description: "Read a file from local disk and return its textual contents.",
inputSchema: {
type: "object",
properties: { path: { type: "string", description: "absolute path to the file" } },
required: ["path"],
},
outputSchema: { type: "object" },
execute: async ({ path }) => ({ contents: await readFile(path, "utf8") }),
});
const [hit] = catalog.search("read a file from disk", 5);
const result = await catalog.invoke(hit.toolId, { path: "/tmp/notes.txt" });Constructors
Constructor
new ToolCatalog(
options?):ToolCatalog
Create an empty catalog.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | ToolCatalogOptions | Trace sink, default retrieval method, and embedding model. Construction validates configuration but never loads a model. |
Returns
Accessors
experimentalAdaptiveRankingStatus
Get Signature
get experimentalAdaptiveRankingStatus():
AdaptiveRankingStatus
Whether adaptive usage ranking is active, inactive, or paused by a model
change — see the native AdaptiveRankingStatus.
Returns
Methods
drainTraceEvents()
drainTraceEvents():
unknown[]
Drain the envelopes captured by a "memory" trace sink, emptying its
buffer.
Returns
unknown[]
The captured envelopes ({ v, ts, session_id, type, ... } — the
event fields are flattened alongside the envelope stamp) in record
order. Always [] unless the active sink is "memory".
experimentalDisableAdaptiveRanking()
experimentalDisableAdaptiveRanking():
void
Turn adaptive usage ranking off; the graph keeps what it learned.
Returns
void
experimentalEnableAdaptiveRanking()
experimentalEnableAdaptiveRanking(
graph,options?):void
Turn on adaptive usage ranking against graph (ADR-0014): the catalog
ranks against what users have actually invoked after similar queries, and
keeps learning as it is used.
Pass the same IntentGraph to a SkillCatalog so both learn into one set of clusters.
Set rebuildOnModelChange to auto-recover a model-mismatched graph on the
next dense (semantic/hybrid) search rather than staying paused until you
call experimentalRebuildIntentGraph yourself. Off by default — the rebuild is an
embedding pass (cost, possible EmbedderError, and it mutates the graph).
Parameters
| Parameter | Type |
|---|---|
graph | IntentGraph |
options | { rebuildOnModelChange?: boolean; warnOnModelMismatch?: boolean; } |
options.rebuildOnModelChange? | boolean |
options.warnOnModelMismatch? | boolean |
Returns
void
experimentalRebuildIntentGraph()
experimentalRebuildIntentGraph():
Promise<void>
Re-embed the intent graph's members under the current model and replace its centroids — call after changing the embedding model. Preserves members, support, and edges. See experimentalEnableAdaptiveRanking.
Returns
Promise<void>
get()
get(
toolId):Tool|undefined
Look up a tool's searchable metadata (no executor attached).
Parameters
| Parameter | Type | Description |
|---|---|---|
toolId | string | The id to look up. |
Returns
Tool | undefined
The metadata as registered, or undefined for an unknown id.
getExecutable()
getExecutable(
toolId):ExecutableTool|undefined
Look up a tool with its executor reattached.
Parameters
| Parameter | Type | Description |
|---|---|---|
toolId | string | The id to look up. |
Returns
ExecutableTool | undefined
A copy of the registered tool including execute, or undefined
for an unknown id.
has()
has(
toolId):boolean
Whether a tool with this id is registered.
Parameters
| Parameter | Type | Description |
|---|---|---|
toolId | string | The id to look up. |
Returns
boolean
true if ToolCatalog.invoke would find an executor for it.
invoke()
invoke(
toolId,args,context?):Promise<unknown>
Run a registered tool's executor. Sync-absorbing: a plain value or
Promise settles through the returned promise, and a synchronous throw
surfaces as a rejection — invoke never throws synchronously, including
for an unknown toolId (that rejects with unknown toolId: …). An
AsyncIterable is the resolved value; its instrumentation settles when
the iterator completes, is cancelled, or fails.
The call is wrapped in an execute_tool OTel span and bracketed by
invoke_start / invoke_end (or invoke_error, with the error message)
events on the local trace stream, took_ms in wall-clock milliseconds.
Parameters
| Parameter | Type | Description |
|---|---|---|
toolId | string | Id of a registered tool. |
args | Record<string, unknown> | Arguments object validated and possibly transformed before execution. |
context? | unknown | Optional opaque invocation context forwarded unchanged. |
Returns
Promise<unknown>
Whatever the executor returns (resolved if it returned a promise).
invokeRaw()
invokeRaw(
toolId,args,context?):unknown
Run a registered tool without erasing its immediate return shape after
synchronous validation. A plain value stays plain, a promise stays a
promise, and an AsyncIterable stays synchronously iterable. An async
validator necessarily makes this method return a promise of the executor's
result. Instrumentation settles only when that returned shape settles
(including iterator completion, cancellation, or failure).
Most callers should use invoke; capability-tool bridges use this path so a host framework can observe streamed preliminary outputs.
Parameters
| Parameter | Type |
|---|---|
toolId | string |
args | Record<string, unknown> |
context? | unknown |
Returns
unknown
invokeValidatedRaw()
invokeValidatedRaw(
toolId,input,context?):unknown
Execute input already parsed by validateInput, preserving its
immediate scalar, promise, or AsyncIterable return shape. Framework
bridges call this only after their host has run the capability tool's live
validator; ordinary callers should use invoke.
Parameters
| Parameter | Type |
|---|---|
toolId | string |
input | unknown |
context? | unknown |
Returns
unknown
recordEvent()
recordEvent(
event):void
Record a custom event on the local trace stream (ADR-0007), e.g. an
upstream_register from an ingestion layer. Delivered to the sink
configured at construction; a no-op sink discards it.
Parameters
| Parameter | Type | Description |
|---|---|---|
event | object | A tagged trace event in wire shape: { type: "...", ... } with snake_case fields. Throws if the object is not a known trace event. |
Returns
void
register()
register(
tools):Promise<void>
Add one tool or a batch to the catalog — the single entry point for
both. Replaces an id in place when already registered (metadata,
executor, and index entry; the corpus never holds a duplicate). On a
"semantic"/"hybrid" catalog, embeds the batch in one pass on a libuv
worker after metadata is indexed, so the event loop is never blocked;
embedding errors (model load / endpoint / auth / dimension) surface
here, at registration — metadata still persists even if the
embedding pass that follows fails. A "bm25" catalog never loads a
model and resolves as soon as metadata is indexed.
A model or dimension change is not recovered in place — construct a new catalog and re-register.
Parameters
| Parameter | Type | Description |
|---|---|---|
tools | ExecutableTool | readonly ExecutableTool[] | A single tool or a readonly array of tools; each execute must be set. Pass the whole batch at once for a single embedding request — separate register calls embed separately. |
Returns
Promise<void>
Throws
EmbedderError on a "semantic"/"hybrid" catalog when
embedding fails (model load / endpoint / auth / dimension) — a
DimensionMismatchError for a vector-width change. A missing
execute handler throws a plain Error.
search()
search(
query,topK,origin?,method?):SearchHit[]
Search the catalog. method overrides the catalog default for this call.
"semantic"/"hybrid" rank against the prebuilt embedding cache and throw
synchronously with guidance to use ToolCatalog.searchAsync.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
query | string | undefined | Natural-language description of what the caller wants to do. |
topK | number | undefined | Maximum number of hits to return. |
origin | SearchOrigin | "direct" | Who initiated the call (default "direct"); recorded on the trace event and span, never affects ranking. |
method? | SearchMethod | undefined | Per-call override of the catalog's default retrieval method. |
Returns
Up to topK BM25 hits, best-first with ties broken by tool id.
Semantic/dense/hybrid methods throw migration guidance; use
ToolCatalog.searchAsync for those methods.
searchAsync()
searchAsync(
query,topK,origin?,method?):Promise<SearchHit[]>
Search with any retrieval method without blocking the Node.js event loop.
Parameters
| Parameter | Type | Default value |
|---|---|---|
query | string | undefined |
topK | number | undefined |
origin | SearchOrigin | "direct" |
method? | SearchMethod | undefined |
Returns
Promise<SearchHit[]>
validateInput()
validateInput(
toolId,input):InputValidationResult|Promise<InputValidationResult>
Run a registered framework validator without executing the tool. A tool without one succeeds with its input unchanged. The returned success value is the exact input the executor should receive, including any defaults or root-level transformation.
Parameters
| Parameter | Type |
|---|---|
toolId | string |
input | unknown |
Returns
InputValidationResult | Promise<InputValidationResult>
ToolRegistry
Typed facade over the native tool registry: metadata-only indexing and
retrieval, with the SDK's public embedding config and an async, batch-aware
register. ToolCatalog layers executors, OTel spans, and defaults
on top; reach for this directly only when bare metadata (no executors) is
enough.
Constructors
Constructor
new ToolRegistry(
embedding?,method?):ToolRegistry
Create a registry with an optional embedding model and retrieval method.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
embedding? | EmbeddingSpec | undefined | Embedding model for semantic/hybrid retrieval; a bare string is a local model directory path. Validated at construction, never loaded eagerly here. |
method? | SearchMethod | "bm25" | "bm25" (default, model-free) or "semantic"/"hybrid", which makes ToolRegistry.register embed the batch inline. |
Returns
Accessors
experimentalAdaptiveRankingStatus
Get Signature
get experimentalAdaptiveRankingStatus():
AdaptiveRankingStatus
Whether adaptive usage ranking is contributing ("active"), off
("inactive"), not yet determinable ("unknown"), or paused because the
embedding model changed ("paused: dim mismatch" / "paused: model mismatch"). Gate on this instead of reading stderr if you prefer.
Returns
Methods
drainTraceEvents()
drainTraceEvents():
unknown[]
Drain captured envelopes from a "memory" sink; [] otherwise.
Returns
unknown[]
experimentalDisableAdaptiveRanking()
experimentalDisableAdaptiveRanking():
void
Turn adaptive usage ranking off: ranking returns to the base engine and the graph stops growing. The graph keeps what it learned, so re-enabling resumes rather than restarts.
Returns
void
experimentalEnableAdaptiveRanking()
experimentalEnableAdaptiveRanking(
graph,options?):void
Turn on adaptive usage ranking against graph (ADR-0014).
Wires both halves: the registry ranks against the graph, and its trace sink is decorated with a learner that grows it from search-then-invoke pairs — a capability the user actually invoked after a query becomes evidence for similar queries later.
Pass the same IntentGraph to the tool and skill registries. One cluster holds both a tool and a skill edge map, so sharing gives one set of clusters with all the evidence behind it; separate graphs duplicate every cluster and split the evidence.
Only queries that match a cluster are affected — anything else ranks exactly
as it would have. With a graph attached, SearchHit.score becomes a fusion
score rather than a raw BM25 score, so use rank for ordering and
fused to detect the scale, not the raw score.
Parameters
| Parameter | Type |
|---|---|
graph | IntentGraph |
options | { rebuildOnModelChange?: boolean; warnOnModelMismatch?: boolean; } |
options.rebuildOnModelChange? | boolean |
options.warnOnModelMismatch? | boolean |
Returns
void
experimentalRebuildIntentGraph()
experimentalRebuildIntentGraph():
Promise<void>
Re-embed the intent graph's members under the current embedding model and replace its centroids. Call after changing the model: a graph's centroids are only comparable to queries from the model that built them, so on a swap the usage arm pauses until this runs. Members, support, and edges are preserved — only the centroids move to the new space.
Returns
Promise<void>
recordEvent()
recordEvent(
event):void
Record a custom event on the local trace stream (ADR-0007). Throws on an object that doesn't parse as a known trace event.
Parameters
| Parameter | Type |
|---|---|
event | object |
Returns
void
register()
register(
item):Promise<void>
Register one tool or a batch, replacing any existing id in place — the
corpus never holds a duplicate. On a "semantic"/"hybrid" registry,
embeds the whole batch in one pass on a libuv worker after metadata is
indexed, so the event loop is never blocked; awaiting surfaces embedding
errors here. A "bm25" registry resolves as soon as metadata is indexed
and never loads a model.
Parameters
Returns
Promise<void>
search()
search(
query,topK):SearchHit[]
Lexical BM25 search: up to topK hits, best-first with ties broken by
id. Model-free and infallible; records the query on the local trace
stream with origin "direct".
Parameters
| Parameter | Type |
|---|---|
query | string |
topK | number |
Returns
searchWithMethod()
searchWithMethod(
query,topK,origin,method):SearchHit[]
Synchronous search restricted to BM25; "semantic"/"hybrid" throw with
guidance to use ToolRegistry.searchWithMethodAsync.
Parameters
| Parameter | Type |
|---|---|
query | string |
topK | number |
origin | SearchOrigin |
method | SearchMethod |
Returns
searchWithMethodAsync()
searchWithMethodAsync(
query,topK,origin,method):Promise<SearchHit[]>
Search on a libuv worker; supports "bm25", "semantic", and "hybrid".
Parameters
| Parameter | Type |
|---|---|
query | string |
topK | number |
origin | SearchOrigin |
method | SearchMethod |
Returns
Promise<SearchHit[]>
searchWithOrigin()
searchWithOrigin(
query,topK,origin):SearchHit[]
BM25 search with an explicit trace origin; ranking is unaffected.
Parameters
| Parameter | Type |
|---|---|
query | string |
topK | number |
origin | SearchOrigin |
Returns
setTraceSink()
setTraceSink(
config):void
Replace the trace sink; subsequent events go to the new destination.
Parameters
| Parameter | Type |
|---|---|
config | TraceSinkConfig |
Returns
void
Interfaces
AdaptedBase
The framework-shaped surface every adapter inherits from the core. Adapters add their idioms via RatelAdapter.extend; universal capability lives here.
Type Parameters
| Type Parameter |
|---|
TTool |
TMessage |
Properties
skills
readonlyskills:SkillCatalog
The shared skill catalog (skills are framework-neutral).
tools
readonlytools:AdaptedToolCollection<TTool>
This view's handle over the shared catalog, in the framework's tool shape.
Methods
modelTools()
modelTools():
Record<string,TTool>
The model-facing toolset in the framework's shape: this view's passthroughs
plus the three capability tools run through the adapter's expose codec.
Fresh objects per call — take it once per agent instance and reuse it, so
the prompt cache survives. Tools registered later are still discoverable
(the capability tools search the live catalog); only a passthrough
registered later needs a fresh modelTools() to reach the model.
Returns
Record<string, TTool>
recall()
recall(
query):Promise<TMessage[]>
Rank query and return the synthetic search_capabilities message pair in
the framework's shape (origin "direct"), or [] when nothing matched
(spending no call id). Pure: it builds fresh messages and never mutates a
host array.
Parameters
| Parameter | Type |
|---|---|
query | string |
Returns
Promise<TMessage[]>
AdaptedToolCollection
An adapted view's handle over the same shared catalog, speaking the
framework's tool shape. Registration runs the adapter's ingest codec;
first registration of an id wins across every view of the core, including
ids claimed by framework-local passthroughs, so repeated calls are idempotent.
register/has are framework-aware (register takes the framework's tool
shape; has also covers this view's passthroughs); get/search/invoke
are at parity with ToolCollection — they read and run the shared
catalog in its neutral shapes, so they're catalog-only: a passthrough is
provider-executed and un-indexed, so has reports it but get returns
undefined, search never ranks it, and invoke can't run it.
Type Parameters
| Type Parameter |
|---|
TTool |
Properties
catalog
readonlycatalog:ToolCatalog
The shared catalog itself — the unguarded driver-level escape hatch.
Methods
get()
get(
id):Tool|undefined
A catalog tool's searchable metadata, or undefined (incl. for a passthrough).
Parameters
| Parameter | Type |
|---|---|
id | string |
Returns
Tool | undefined
has()
has(
id):boolean
Whether this id is registered — in the catalog or as this view's passthrough.
Parameters
| Parameter | Type |
|---|---|
id | string |
Returns
boolean
invoke()
invoke(
id,args):Promise<unknown>
Execute a catalog tool by id with the args object (not a passthrough).
Parameters
| Parameter | Type |
|---|---|
id | string |
args | Record<string, unknown> |
Returns
Promise<unknown>
register()
register(
tools):Promise<void>
Ingest framework tools (keyed by tool id) into the shared catalog. Async,
with the same semantics as ToolCollection.register: ids are validated
and ingested synchronously (a reserved id throws at the call site), then the
returned promise resolves when the batch is indexed and, on a semantic/hybrid
core, embedded — rejecting if embedding fails. await it before a dense search.
Parameters
| Parameter | Type |
|---|---|
tools | Record<string, TTool> |
Returns
Promise<void>
search()
search(
query,topK,method?):SearchHit[]
Rank the shared catalog for query synchronously (host-driven, origin
"direct"). BM25 only — semantic/hybrid throws with a pointer to
searchAsync. topK is clamped to [1, 50] (invalid values fall
back to 5); passthroughs are never ranked. Drop to catalog for an
unclamped search.
Parameters
| Parameter | Type |
|---|---|
query | string |
topK | number |
method? | SearchMethod |
Returns
searchAsync()
searchAsync(
query,topK,method?):Promise<SearchHit[]>
Rank the shared catalog for query with any retrieval method off the event
loop (origin "direct"). Same topK clamp as search; passthroughs
are never ranked. await register(...) first so a dense tool is embedded.
Parameters
| Parameter | Type |
|---|---|
query | string |
topK | number |
method? | SearchMethod |
Returns
Promise<SearchHit[]>
AdaptiveRankingStatus
SDK-facing view of whether adaptive usage ranking is contributing. status
is "active" | "inactive" | "unknown" | "paused: dim mismatch" | "paused: model mismatch"; built/active/dimMismatch are set only when paused.
Properties
active?
optionalactive?:string
When paused: the currently active embedding model (or its dimension). Absent unless paused.
built?
optionalbuilt?:string
When paused: the embedding model (or its dimension) the graph's centroids were built with. Absent unless paused.
dimMismatch?
optionaldimMismatch?:boolean
When paused: true if the mismatch is a dimension difference, false if
it is a same-dimension model-identity difference. Absent unless paused.
status
status:
string
One of "active" | "inactive" | "unknown" | "paused: dim mismatch" | "paused: model mismatch".
CapabilitiesSearchOptions
Options for runCapabilitiesSearch.
Properties
origin?
optionalorigin?:SearchOrigin
Who initiated the search — stamped on the gateway_search trace event and
the ratel.search span. Default "agent" (a model-synthesized call); the
host-driven recall path passes "direct".
skillCatalog?
optionalskillCatalog?:SkillCatalog
Catalog the skills bucket is ranked from (and whose declared tool deps ride in).
topKSkills?
optionaltopKSkills?:number
Max skills bucket size; capped at 50, default 3; invalid values fall back to the default.
topKTools?
optionaltopKTools?:number
Max tools bucket size; capped at 50, default 5 (same as the tool); 0, negative, or non-integer values fall back to the default.
upstreamServers?
optionalupstreamServers?: readonlyUpstreamServerInfo[]
Upstream-server metadata attached to the matching result groups.
CapabilitySkillHit
One ranked skill in the skills bucket of SearchCapabilitiesResult.
Properties
description
description:
string
The skill's description, compacted to ~160 chars for the listing.
score
score:
number
Retrieval score from the skill catalog's search (BM25 by default).
skillId
skillId:
string
Skill id to pass to get_skill_content.
CapabilityToolGroup
Tool hits grouped by upstream server. The group key is the <server>__ id
prefix (a plain, un-prefixed tool id groups under itself); description and
instructions are attached when a matching UpstreamServerInfo was
provided.
Properties
hits
hits:
CapabilityToolHit[]
The server's ranked hits, in overall result order.
server
server:
object
The owning server: its name, plus optional description/instructions metadata.
description?
optionaldescription?:string
The server's one-line summary, when known.
instructions?
optionalinstructions?:string
The server's usage instructions, when known.
name
name:
string
Server name (the <server>__ prefix of the group's tool ids).
CapabilityToolHit
One ranked tool in the tools bucket of SearchCapabilitiesResult.
Properties
description
description:
string
The tool's description, as registered.
inputSchema
inputSchema:
Record<string,unknown>
The tool's input JSON Schema, so the model can call it without another lookup.
score
score:
number
Retrieval score from the tool catalog's search (scale depends on the
catalog's method — BM25 by default), or 0 when the tool was pulled in as
a matched skill's declared dependency rather than by the query itself.
toolId
toolId:
string
Catalog id to pass to invoke_tool (<server>__<tool> for MCP-proxied tools).
CatalogRegistration
A framework tool ingested into the catalog: what an adapter's RatelAdapter.ingest returns for an executable tool. The core registers it verbatim (id/name are the app's tool key), so the schemas are the SDK's public JSONSchema7 spelling and adapters need no casts.
Properties
description
description:
string
Retrieval ranks on this; resolve dynamic descriptions at ingest time.
inputSchema
inputSchema:
JSONSchema7
Input JSON Schema (the catalog's native spelling).
outputSchema?
optionaloutputSchema?:JSONSchema7
Output JSON Schema; defaults to { type: "object" } when omitted.
validateInput?
optionalvalidateInput?:InputValidator
Framework-native parser retained in the shared catalog. Capability-tool exposure delegates to this live parser, so every adapted view observes native replacements and root-level transformations.
Methods
execute()
execute(
input,context?):unknown
Runs the tool through the capability funnel with args and optional opaque
adapter context. An adapter that supports live framework context tags it in
expose and validates that private tag here before unwrapping it; a missing
or foreign tag must take the framework's context-free fallback.
Parameters
| Parameter | Type |
|---|---|
input | unknown |
context? | unknown |
Returns
unknown
ExecutableTool
A tool the catalog can both retrieve and run: the searchable metadata of a
Tool (id, name, description, schemas) plus its Executor. The unit
ToolCatalog.register accepts and ToolCatalog.getExecutable
returns.
Extends
Properties
description
description:
string
What the tool does and when to use it — the main ranking signal.
Inherited from
execute
execute:
Executor
Runs the tool. Called by ToolCatalog.invoke with args and optional context.
id
id:
string
Unique id, the registry key. Re-registering an existing id replaces the
entry in place. MCP-proxied tools use the <server>__<tool> convention.
Inherited from
inputSchema
inputSchema:
JSONSchema7
JSON Schema of the arguments. Property names and their descriptions
(nested included) are indexed for ranking.
Inherited from
name
name:
string
Callable name (typically the same as id for local tools); indexed for
ranking both whole and split on snake_case/camelCase boundaries.
Inherited from
outputSchema
outputSchema:
JSONSchema7
JSON Schema of the result; indexed the same way as inputSchema.
Inherited from
validateInput?
optionalvalidateInput?:InputValidator
Shared parser used before execution and by model-facing host bridges.
InvokeToolError
A generic invoke_tool error whose original target failure is available to framework adapters.
Properties
[INVOKE_TOOL_ERROR_CAUSE]
readonly[INVOKE_TOOL_ERROR_CAUSE]:unknown
Original thrown value, hidden from enumeration and serialization.
error
error:
string
Human-readable failure passed to the model.
isError
isError:
true
Stable discriminator used by generic capability hosts.
InvokeToolToolOptions
Options for invokeToolTool.
Properties
onUnauthorized?
optionalonUnauthorized?: (upstream) =>void|Promise<void>
Notified when the underlying tool throws UnauthorizedError, with the upstream name inferred from the toolId.
Parameters
| Parameter | Type |
|---|---|
upstream | string |
Returns
void | Promise<void>
JSONSchema7
Properties
$comment?
optional$comment?:string
$defs?
optional$defs?:object
Index Signature
[key: string]: JSONSchema7Definition
See
- https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-00#section-8.2.4
- https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#appendix-A
$id?
optional$id?:string
$ref?
optional$ref?:string
$schema?
optional$schema?:string
additionalItems?
optionaladditionalItems?:JSONSchema7Definition
additionalProperties?
optionaladditionalProperties?:JSONSchema7Definition
allOf?
optionalallOf?:JSONSchema7Definition[]
See
https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.7
anyOf?
optionalanyOf?:JSONSchema7Definition[]
const?
optionalconst?:JSONSchema7Type
contains?
optionalcontains?:JSONSchema7Definition
contentEncoding?
optionalcontentEncoding?:string
contentMediaType?
optionalcontentMediaType?:string
See
https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-8
default?
optionaldefault?:JSONSchema7Type
definitions?
optionaldefinitions?:object
Index Signature
[key: string]: JSONSchema7Definition
See
https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-9
dependencies?
optionaldependencies?:object
Index Signature
[key: string]: string[] | JSONSchema7Definition
description?
optionaldescription?:string
else?
optionalelse?:JSONSchema7Definition
enum?
optionalenum?:JSONSchema7Type[]
examples?
optionalexamples?:JSONSchema7Type
exclusiveMaximum?
optionalexclusiveMaximum?:number
exclusiveMinimum?
optionalexclusiveMinimum?:number
format?
optionalformat?:string
See
https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-7
if?
optionalif?:JSONSchema7Definition
See
https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.6
items?
optionalitems?:JSONSchema7Definition|JSONSchema7Definition[]
See
https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.4
maximum?
optionalmaximum?:number
maxItems?
optionalmaxItems?:number
maxLength?
optionalmaxLength?:number
See
https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.3
maxProperties?
optionalmaxProperties?:number
See
https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.5
minimum?
optionalminimum?:number
minItems?
optionalminItems?:number
minLength?
optionalminLength?:number
minProperties?
optionalminProperties?:number
multipleOf?
optionalmultipleOf?:number
See
https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.2
not?
optionalnot?:JSONSchema7Definition
oneOf?
optionaloneOf?:JSONSchema7Definition[]
pattern?
optionalpattern?:string
patternProperties?
optionalpatternProperties?:object
Index Signature
[key: string]: JSONSchema7Definition
properties?
optionalproperties?:object
Index Signature
[key: string]: JSONSchema7Definition
propertyNames?
optionalpropertyNames?:JSONSchema7Definition
readOnly?
optionalreadOnly?:boolean
required?
optionalrequired?:string[]
then?
optionalthen?:JSONSchema7Definition
title?
optionaltitle?:string
See
https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-10
type?
optionaltype?:JSONSchema7TypeName|JSONSchema7TypeName[]
See
https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1
uniqueItems?
optionaluniqueItems?:boolean
writeOnly?
optionalwriteOnly?:boolean
McpServerHandle
What registerMcpServer returns: the ingested ids plus lifecycle control.
Properties
close
close: () =>
Promise<void>
Close the underlying MCP client connection. The proxied tools stay in the catalog but invoking them after close fails.
Returns
Promise<void>
serverInstructions
serverInstructions:
string|undefined
The usage instructions the server declared during the MCP initialize
handshake, or undefined if it declared none. Useful as
UpstreamServerInfo.instructions when building capability tools.
toolIds
toolIds:
string[]
Namespaced ids in upstream list order (all pages). Duplicate names may appear more than once; ToolCatalog.register keeps the last row.
Ratel
One ratel(config) core: a single ToolCatalog + SkillCatalog
- recall-id counter shared by every Ratel.adaptTo view. Genuinely usable standalone — register native tools on Ratel.tools, hand the model Ratel.modelTools, rank with Ratel.recall — and adaptable on top for a framework's native shapes.
Properties
skills
readonlyskills:SkillCatalog
The shared skill catalog — exposed raw (skills are framework-neutral and
need no ingest codec), so it is the unguarded escape hatch at parity with
ToolCollection.catalog: its search top-K is not clamped. Use
recall for a clamped, capability-shaped skills ranking.
tools
readonlytools:ToolCollection
Handle over the shared tool catalog (native shapes, guarded).
Methods
adaptTo()
adaptTo<
A>(adapter):AdaptedRatel<A>
Adapt the core to a framework, inferring its tool/message types and helpers.
Type Parameters
| Type Parameter |
|---|
A extends RatelAdapter<unknown, unknown, Record<never, never>> |
Parameters
| Parameter | Type |
|---|---|
adapter | A |
Returns
AdaptedRatel<A>
modelTools()
modelTools():
Record<string,ExecutableTool>
The three capability tools (search_capabilities, invoke_tool,
get_skill_content) in native shape, for framework-free hosts. All three
are always advertised — the set never depends on registration order, so the
prompt cache survives; loading a skill from an empty catalog returns a
structured error, not a missing tool. Fresh objects per call: take it once
and reuse it. Tools and skills registered later are still discoverable.
Returns
Record<string, ExecutableTool>
recall()
recall(
query):Promise<SearchCapabilitiesResult|null>
Rank query into the canonical search_capabilities result (origin
"direct", top-K from recallTopK), or null when nothing matched. A
pure query: no call id is minted — ids exist only on the adapted views,
whose synthetic message pairs need them. Ranks whatever is registered and
(on a dense core) embedded now — await r.tools.register(...) first.
Parameters
| Parameter | Type |
|---|---|
query | string |
Returns
Promise<SearchCapabilitiesResult | null>
RatelAdapter
The framework boundary: one complementary package per framework implements
this so Ratel speaks that framework's native tool and message shapes. The
three codecs (ingest / expose / recallMessages) are the whole contract;
extend adds framework idioms. The core owns all state and guards, so an
adapter is ~three pure functions.
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
TTool | unknown | The framework's tool type (e.g. AI SDK Tool). |
TMessage | unknown | The framework's message type (e.g. AI SDK ModelMessage). |
TExt extends object | Record<never, never> | The framework-idiomatic helpers merged onto the adapted object. |
Properties
name
readonlyname:string
Names the adapter in error messages (and, once adapter packages emit it, in
the ratel.adapter telemetry attribute — stamping is deferred to them per ADR-0013).
Methods
expose()
expose(
tool):TTool
Ratel capability tool → framework tool. Context-aware adapters wrap the framework's complete live execution context in a private, stable tag before passing it as the capability executor's optional second argument.
Parameters
| Parameter | Type |
|---|---|
tool | ExecutableTool |
Returns
TTool
extend()?
optionalextend(base):TExt
Framework-idiomatic helpers, merged onto the adapted object.
Parameters
| Parameter | Type |
|---|---|
base | AdaptedBase<TTool, TMessage> |
Returns
TExt
ingest()
ingest(
id,tool):CatalogRegistration|"passthrough"
Framework tool → catalog registration, or "passthrough" for tools the
catalog can't execute (provider-executed) that must stay eagerly exposed.
Parameters
| Parameter | Type |
|---|---|
id | string |
tool | TTool |
Returns
CatalogRegistration | "passthrough"
recallMessages()
recallMessages(
ref,recall):TMessage[]
Synthetic recall pair in the framework's message shape.
Parameters
| Parameter | Type |
|---|---|
ref | RecallRef |
recall | SearchCapabilitiesResult |
Returns
TMessage[]
RatelConfig
Construction options for ratel. Shared by every adapter view of the core.
Properties
embedding?
optionalembedding?:EmbeddingSpec
Embedding model backing "semantic"/"hybrid" retrieval, forwarded to both
catalogs — see ToolCatalogOptions.embedding. A string is a local model
directory path; every other source is a keyed object ({ huggingface },
{ ollama }, { url, model, apiKeyEnv }). Omit to use the built-in default
model. await r.tools.register(...) awaits the embedding pass and rejects if
it fails, so errors surface at registration.
method?
optionalmethod?:SearchMethod
Default retrieval method for the tool and skill catalogs (default "bm25", model-free).
recallTopK?
optionalrecallTopK?:number
Max tools each host-driven recall returns: capped at 50; 0, negative, or
non-integer values fall back to the default 5.
trace?
optionaltrace?:TraceSinkConfig
Local trace-stream destination for both catalogs (default: discard).
RecallRef
The identity of one synthetic recall call, handed to RatelAdapter.recallMessages.
Properties
callId
callId:
string
Unique call id from the core's private counter (never a transcript position).
query
query:
string
The recall query (the last user turn's text, in the AI SDK adapter).
RegisterMcpServerOptions
Options for registerMcpServer.
Properties
name
name:
string
Namespace for the server's tools inside the catalog: each tool is
registered as <name>__<toolName>. Also the server name that trace
events and result groups report for these tools.
transport
transport:
Transport
An MCP client transport for the server (e.g. StdioClientTransport,
StreamableHTTPClientTransport, or an InMemoryTransport pair in tests).
registerMcpServer connects it; it must not be connected already.
ReplaceOutcome
What a SkillRegistry.replaceAll changed, counted by id. updated covers
any field edit (including a body-only rewrite); unchanged ids are identical
to what was registered and keep their cached embedding.
Properties
added
added:
number
Ids in the new corpus that were not in the old one.
removed
removed:
number
Ids in the old corpus that are absent from the new one.
unchanged
unchanged:
number
Ids present in both with identical content.
updated
updated:
number
Ids present in both whose content differs in any field.
SearchCapabilitiesOptions
Options for searchCapabilitiesTool.
Properties
advertiseSkills?
optionaladvertiseSkills?:boolean
Override the skills clause in the tool description. Default: present only
when the skill catalog is non-empty at build time. Hosts that always expose
get_skill_content (the ratel() facade) pass true so the description is
byte-identical regardless of when the first skill registers.
upstreamServers?
optionalupstreamServers?: readonlyUpstreamServerInfo[]
Upstream MCP servers to advertise in the tool description and result groups.
SearchCapabilitiesResult
Result shape of the search_capabilities tool: two independently-ranked
buckets with separate top-K budgets. Scores are comparable within a bucket,
not across the two (tools and skills are indexed as different text shapes).
Properties
skills
skills:
CapabilitySkillHit[]
Skill hits — playbooks to load via get_skill_content.
tools
tools:
object
Executable tool hits, grouped by upstream server.
groups
groups:
CapabilityToolGroup[]
Groups in ranking order (a server appears where its best hit ranked).
SearchHit
One ranked tool from a registry search, best-first.
Properties
fused
fused:
boolean
true when score is an RRF score (ordering-only) rather than the raw
method score: the usage arm fused into this search, or the method is
hybrid. Uniform across one result list; lets a caller detect the scale.
rank
rank:
number
0-based position in this result list (best is 0). Stable across methods
and across the fused switch — the field to order or threshold on.
score
score:
number
Relevance score; higher is better, ties break by id ascending. Its scale
depends on the method (raw BM25 / cosine / RRF) AND on fused — with
adaptive ranking a matched query returns small RRF scores while an
unmatched one on the same catalog returns the raw score. Order by rank
and branch on fused; treat score as a within-list hint only.
toolId
toolId:
string
Id of the matched tool, as registered.
SearchToolHit
Deprecated
Use CapabilityToolHit.
Properties
description
description:
string
The tool's description, as registered.
inputSchema
inputSchema:
Record<string,unknown>
The tool's input JSON Schema.
score
score:
number
Retrieval score from the catalog's search (BM25 by default).
toolId
toolId:
string
Catalog id to pass to invoke_tool.
SearchToolsGroup
Deprecated
Use CapabilityToolGroup.
Properties
hits
hits:
SearchToolHit[]
The server's ranked hits, in overall result order.
server
server:
object
The owning server: its name, plus optional description/instructions metadata.
description?
optionaldescription?:string
The server's one-line summary, when known.
instructions?
optionalinstructions?:string
The server's usage instructions, when known.
name
name:
string
Server name (the <server>__ prefix of the group's tool ids).
SearchToolsResult
Deprecated
Use SearchCapabilitiesResult (the tools.groups field).
Properties
groups
groups:
SearchToolsGroup[]
Tool hits grouped by upstream server, in ranking order.
SearchToolsToolOptions
Deprecated
Use SearchCapabilitiesOptions.
Properties
upstreamServers?
optionalupstreamServers?: readonlyUpstreamServerInfo[]
Upstream MCP servers to advertise in the tool description and result groups.
Skill
A reusable playbook: instructions the agent reads and follows, in
contrast to a Tool it executes. Name, description, and tags are indexed
for ranking; the body is the dispatch payload, deliberately excluded from
the index so it can't drown the description's term weights.
Properties
body?
optionalbody?:string
The full instructions (Markdown) returned on load — the dispatch
payload, never indexed for ranking.
Optional (defaults to "") — parity with the Python SDK's default body.
description
description:
string
What the skill covers and when to reach for it — the main ranking signal.
id
id:
string
Unique id, the registry key. Re-registering an existing id replaces the entry in place.
metadata?
optionalmetadata?:Record<string,string[]>
Free-form, non-indexed context for higher layers — e.g.
{ stacks: ["react"] } for the push ranker to boost by project context.
name
name:
string
Human-readable name; indexed for ranking both whole and split on
snake_case/camelCase boundaries.
tags?
optionaltags?:string[]
Author-declared labels and task phrases ("frontend", "login form");
indexed for ranking. Optional (defaults to []) — a minimal
Skill(id, name, description) is valid, in parity with the Python SDK.
tools?
optionaltools?:string[]
Ids of tools this skill's instructions call; surfaced into the
search_capabilities tools bucket — not indexed as query terms.
SkillCatalogOptions
Construction options for SkillCatalog.
Properties
embedding?
optionalembedding?:EmbeddingSpec
Embedding model for semantic/hybrid retrieval — see ToolCatalogOptions.embedding. Retained for asynchronous overrides.
method?
optionalmethod?:SearchMethod
Default retrieval method for search (default "bm25").
trace?
optionaltrace?:TraceSinkConfig
Local trace stream destination (default: discard). See TraceSinkConfig.
SkillHit
One ranked skill from a registry search, best-first — the skill twin of
SearchHit, with the same score semantics per method.
Properties
fused
fused:
boolean
true when score is an RRF score — as on SearchHit.fused.
rank
rank:
number
0-based position in this result list — as on SearchHit.rank.
score
score:
number
Relevance score; scale depends on the method and on fused, as on
SearchHit.score. Order by rank, branch on fused.
skillId
skillId:
string
Id of the matched skill, as registered.
Tool
A tool's searchable metadata: what the registry indexes and what a search
hit resolves back to. Execution lives a layer up (the SDK's ToolCatalog
pairs each Tool with its executor).
Extended by
Properties
description
description:
string
What the tool does and when to use it — the main ranking signal.
id
id:
string
Unique id, the registry key. Re-registering an existing id replaces the
entry in place. MCP-proxied tools use the <server>__<tool> convention.
inputSchema
inputSchema:
JSONSchema7
JSON Schema of the arguments. Property names and their descriptions
(nested included) are indexed for ranking.
name
name:
string
Callable name (typically the same as id for local tools); indexed for
ranking both whole and split on snake_case/camelCase boundaries.
outputSchema
outputSchema:
JSONSchema7
JSON Schema of the result; indexed the same way as inputSchema.
ToolCatalogOptions
Construction options for ToolCatalog.
Properties
embedding?
optionalembedding?:EmbeddingSpec
Embedding model backing semantic/hybrid retrieval. A string is a local
model directory path ("/opt/models/bge"); every other source is a keyed
object: { huggingface: "BAAI/bge-base-en-v1.5" }, { ollama: "…" }, or
{ url, model, apiKeyEnv }. Chosen once, used for both document and query
embedding. Retained and validated even when the default method is "bm25",
allowing a later asynchronous semantic override.
method?
optionalmethod?:SearchMethod
Default retrieval method for search (default "bm25", model-free). A
per-call method argument overrides it.
trace?
optionaltrace?:TraceSinkConfig
Local trace stream destination (default: discard). See TraceSinkConfig.
ToolCollection
The core's handle over its shared ToolCatalog — registration and lookup in the SDK's native shapes, callable at any time (also after Ratel.modelTools: the capability tools search the live catalog at invocation time). Guards live here: the reserved capability-tool ids throw, and a framework-shaped tool throws an actionable install-the-adapter error. Registration keeps the catalog's own replace-in-place semantics — the native path is authoritative, unlike the first-wins adapted path — and embeds the batch on a semantic/hybrid catalog.
Properties
catalog
readonlycatalog:ToolCatalog
The shared catalog itself — the unguarded driver-level escape hatch.
Methods
get()
get(
id):Tool|undefined
The tool's searchable metadata, or undefined when unregistered.
Parameters
| Parameter | Type |
|---|---|
id | string |
Returns
Tool | undefined
has()
has(
id):boolean
Whether a tool with this id is registered.
Parameters
| Parameter | Type |
|---|---|
id | string |
Returns
boolean
invoke()
invoke(
id,args):Promise<unknown>
Execute a registered tool by id with the args object.
Parameters
| Parameter | Type |
|---|---|
id | string |
args | Record<string, unknown> |
Returns
Promise<unknown>
register()
register(...
tools):Promise<void>
Register native tools (replace-in-place on a duplicate id). Async: input is
validated synchronously (a missing execute, a reserved id, or a
framework-shaped tool throws at the call site, before the promise), then
the returned promise resolves when the batch is indexed and — on a
"semantic"/"hybrid" core — embedded, rejecting if that embedding fails.
await it before searching a dense core; embedding errors surface as the
rejection. Pass the whole batch in one call for a single embedding pass.
Parameters
| Parameter | Type |
|---|---|
...tools | ExecutableTool[] |
Returns
Promise<void>
search()
search(
query,topK,method?):SearchHit[]
Rank the catalog for query synchronously (host-driven, origin "direct").
BM25 only: a "semantic"/"hybrid" catalog (or a per-call method
override to one) throws with a pointer to searchAsync, since dense
ranking runs against the prebuilt embedding cache off the event loop. topK
is clamped to [1, 50] (invalid values fall back to 5), like the capability
funnel — drop to catalog for an unclamped search.
Parameters
| Parameter | Type |
|---|---|
query | string |
topK | number |
method? | SearchMethod |
Returns
searchAsync()
searchAsync(
query,topK,method?):Promise<SearchHit[]>
Rank the catalog for query with any retrieval method without blocking the
event loop (origin "direct", same topK clamp as search). Ranks
whatever is embedded now — await register(...) first so a dense tool is in
the cache.
Parameters
| Parameter | Type |
|---|---|
query | string |
topK | number |
method? | SearchMethod |
Returns
Promise<SearchHit[]>
UpstreamServerInfo
Descriptive metadata about one upstream MCP server behind the catalog. Fed
to searchCapabilitiesTool via SearchCapabilitiesOptions: the
servers are listed in the tool's description (via
formatUpstreamLine), and description/instructions enrich the
matching CapabilityToolGroup.server in results.
Properties
description?
optionaldescription?:string
One-line summary of what the server offers; compacted in the listing.
instructions?
optionalinstructions?:string
The server's own usage instructions (e.g. McpServerHandle.serverInstructions).
name
name:
string
Server name; must match the name the server was registered under
(registerMcpServer), i.e. the <name>__ prefix of its tool ids.
needsAuth?
optionalneedsAuth?:boolean
True when the upstream rejected its boot connection with 401 / requires re-authorization.
toolCount?
optionaltoolCount?:number
Number of tools the server contributes; shown in the listing when set.
Type Aliases
AdaptedRatel
AdaptedRatel<
A> =AextendsRatelAdapter<infer TTool, infer TMessage, infer TExt> ?AdaptedBase<TTool,TMessage> &TExtextendsobject?TExt:unknown:never
The object Ratel.adaptTo returns: the base surface plus the adapter's
extend helpers. An adapter whose extend returns a non-object degrades to
the bare base type here (instead of collapsing the whole view to never,
which would surface as a cryptic error far from the broken adapter).
Type Parameters
| Type Parameter |
|---|
A extends RatelAdapter |
ContentCapture
ContentCapture = typeof
ContentCapture[keyof typeofContentCapture]
Message/tool content capture modes for
OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT (CONVENTIONS.md § Capture
gating). Default off.
EmbeddingModelConfig
EmbeddingModelConfig =
ExclusiveEmbeddingFields<"huggingface"|"revision"|"pooling"|"download"> &object|ExclusiveEmbeddingFields<"local"|"pooling"> &object|ExclusiveEmbeddingFields<"ollama"> &object|ExclusiveEmbeddingFields<"url"|"model"|"apiKeyEnv"> &object
Object form of the embedding-model selection for semantic/hybrid retrieval. Each variant accepts exactly one source; fields from other variants are rejected at compile time. Use the bare string form only for a local model directory path.
EmbeddingSpec
EmbeddingSpec =
string|EmbeddingModelConfig
Embedding-model selection: a bare string is a local model directory path; every other source is an explicit EmbeddingModelConfig object.
Executor
Executor = (
input,context?) =>Promise<unknown> |unknown
The function that runs a tool. Receives the arguments object and an optional
opaque invocation context supplied by a framework adapter. It may return
a plain value, Promise, or AsyncIterable. ToolCatalog.invoke
absorbs synchronous values and throws into its promise contract;
ToolCatalog.invokeRaw preserves the immediate return shape when
validation is synchronous, while ToolCatalog.invokeValidatedRaw
guarantees that shape after a host has already validated the input.
One-argument executors remain valid; framework-neutral callers normally omit
context.
Parameters
| Parameter | Type |
|---|---|
input | any |
context? | unknown |
Returns
Promise<unknown> | unknown
InputValidationResult
InputValidationResult = {
success:true;value:unknown; } | {error:Error;success:false; }
Result returned by a framework-native input validator.
Union Members
Type Literal
{ success: true; value: unknown; }
| Name | Type | Description |
|---|---|---|
success | true | The input was accepted. |
value | unknown | Parsed value, including defaults or transformations. |
Type Literal
{ error: Error; success: false; }
| Name | Type | Description |
|---|---|---|
error | Error | Framework-native validation failure. |
success | false | The input was rejected. |
InputValidator
InputValidator = (
input) =>InputValidationResult|PromiseLike<InputValidationResult>
Optional framework-native parser retained by the shared catalog. It may validate, apply defaults, or transform the input before execution.
Parameters
| Parameter | Type |
|---|---|
input | unknown |
Returns
InputValidationResult | PromiseLike<InputValidationResult>
McpToolsListErrorCode
McpToolsListErrorCode =
"RepeatedCursor"|"PaginationExceeded"
Stable discriminant for McpToolsListError from paginated MCP tools/list.
PendingReplace
PendingReplace =
Promise<ReplaceOutcome> &ReplaceOutcome
What SkillCatalog.replaceAll returns: the ReplaceOutcome counts, readable immediately, over a promise for the embedding pass.
The corpus swap commits synchronously, so the counts are final the moment
replaceAll returns and can be read before the embedding pass settles — a
source that must report what a reload changed can therefore do so even when
that pass fails.
Always await (or .catch()) the value, even when you only want the
counts. It is a real promise for the embedding pass, so leaving it
unhandled turns an embedding failure into an unhandled rejection — which
terminates the process under Node's default --unhandled-rejections=throw.
Reading the counts is not a substitute for handling it:
const reload = catalog.replaceAll(batch); // corpus live, counts final
try {
await reload;
} catch {
log.warn(`applied +${reload.added} -${reload.removed}, embeddings pending`);
}SearchMethod
SearchMethod =
"bm25"|"semantic"|"hybrid"
Retrieval engine for ToolCatalog.search (and the skill catalog's
search):
"bm25"— lexical ranking; model-free and infallible (the default)."semantic"— cosine similarity over prebuilt embeddings."hybrid"— BM25 and semantic rankings fused with Reciprocal Rank Fusion (ADR-0011).
"semantic"/"hybrid" embed inline during ToolCatalog.register;
ranking against that cache needs searchAsync().
SearchOrigin
SearchOrigin =
"direct"|"agent"
Who initiated a search: "direct" for host code calling the SDK itself
(pre-fetch helpers, benchmarks), "agent" for a call the model synthesized
through the capability tools (search_capabilities). Recorded on trace
events and the ratel.origin span attribute so consumers can separate the
two paths.
TraceSinkConfig
TraceSinkConfig = {
kind:"noop"; } | {kind:"memory";sessionId:string; } | {kind:"jsonl";path:string;sessionId:string; }
Where the local trace stream (ADR-0007) goes. Distinct from the OTel spans in ToolCatalog's docs — this is the in-process channel drained via ToolCatalog.drainTraceEvents or written to disk.
"noop"— discard every event (the default when notraceoption is given)."memory"— buffer envelopes in-process; read them back with ToolCatalog.drainTraceEvents.sessionIdis stamped on each envelope."jsonl"— append one JSON envelope per line to the file atpath(parent directories are created).sessionIdis stamped on each envelope.
Union Members
Type Literal
{ kind: "noop"; }
| Name | Type | Description |
|---|---|---|
kind | "noop" | Discard every event. |
Type Literal
{ kind: "memory"; sessionId: string; }
| Name | Type | Description |
|---|---|---|
kind | "memory" | Buffer envelopes in-process for drainTraceEvents. |
sessionId | string | Session id stamped on every envelope. |
Type Literal
{ kind: "jsonl"; path: string; sessionId: string; }
| Name | Type | Description |
|---|---|---|
kind | "jsonl" | Append one JSON envelope per line to path. |
path | string | File to append to; parent directories are created. |
sessionId | string | Session id stamped on every envelope. |
Variables
ContentCapture
constContentCapture:object
Message/tool content capture modes for
OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT (CONVENTIONS.md § Capture
gating). Default off.
Type Declaration
| Name | Type |
|---|---|
EventOnly | "EVENT_ONLY" |
NoContent | "NO_CONTENT" |
SpanAndEvent | "SPAN_AND_EVENT" |
SpanOnly | "SPAN_ONLY" |
GET_SKILL_CONTENT_ID
constGET_SKILL_CONTENT_ID:"get_skill_content"
Wire id ("get_skill_content") of the skill-loading capability tool built
by getSkillContentTool — the name the model calls it by.
INVOKE_TOOL_ERROR_CAUSE
constINVOKE_TOOL_ERROR_CAUSE: uniquesymbol
Non-enumerable cause carried by a structured error from a target executor.
INVOKE_TOOL_ID
constINVOKE_TOOL_ID:"invoke_tool"
Wire id ("invoke_tool") of the execution capability tool built by
invokeToolTool — the name the model calls it by.
SEARCH_CAPABILITIES_ID
constSEARCH_CAPABILITIES_ID:"search_capabilities"
Wire id ("search_capabilities") of the discovery capability tool built by
searchCapabilitiesTool — the name the model calls it by.
SEARCH_TOOLS_ID
constSEARCH_TOOLS_ID:"search_tools"
Deprecated
Use SEARCH_CAPABILITIES_ID ("search_capabilities").
Functions
clearContentCapture()
clearContentCapture(
generation):void
Clear the programmatic content-capture override, but only when generation —
the token returned by setContentCapture — still identifies the most
recent set. A stale token no-ops, so an old handle shutting down late cannot
clobber an override a newer caller installed (and silently re-enable, or
disable, capture via the env fallback). For an unconditional clear, use
setContentCapture(null).
Parameters
| Parameter | Type |
|---|---|
generation | number |
Returns
void
formatUpstreamLine()
formatUpstreamLine(
s):string
Format one upstream server as the bullet line the capability-tool
descriptions embed (- <name> — <description> (<n> tools) (auth required),
omitting the parts that are unset). Exported for the deprecated
searchToolsTool shim, which builds the same listing.
Parameters
| Parameter | Type | Description |
|---|---|---|
s | UpstreamServerInfo | The server to describe. |
Returns
string
A single - -prefixed line with the description compacted.
getSkillContentTool()
getSkillContentTool(
catalog):ExecutableTool
Build the get_skill_content capability tool: load a skill's full
instructions by id — the counterpart to invoke_tool. Skills are read,
not executed: the agent discovers a skill in the skills bucket of
search_capabilities, then pulls its playbook into context here.
The tool takes { skillId } and resolves to { body } (the skill's
Markdown) on success, or { error, isError: true } for an unknown id — a
structured result rather than a rejection, so the model can recover. Each
load records a ratel.skill.load span plus a skill_invoke trace event
(unknown ids record gateway_error).
Parameters
| Parameter | Type | Description |
|---|---|---|
catalog | SkillCatalog | Catalog whose skills this serves. |
Returns
The tool, ready to expose to the model.
invokeToolTool()
invokeToolTool(
catalog,opts?):ExecutableTool
Build the invoke_tool capability tool: the execution counterpart to
searchCapabilitiesTool. Takes { toolId, args }, delegates input
parsing to the selected catalog tool's live validator, then runs the
prevalidated input through ToolCatalog.invokeValidatedRaw. That
preserves a target AsyncIterable so framework adapters can expose
preliminary outputs even when validation itself was asynchronous.
Failures come back as structured { error, isError: true } results, not
rejections, so the model can read and recover from them: an unknown
toolId (with a hint to search first), a non-object args, or a thrown
executor error. Target executor errors also carry their original thrown
value under the non-enumerable INVOKE_TOOL_ERROR_CAUSE marker so an
adapter can restore its framework's native error lifecycle. A tool that
throws UnauthorizedError gets special
handling — opts.onUnauthorized fires with the upstream name inferred from
the <server>__ id prefix, a ratel.auth.flow span records the outcome,
and the result is { error: "needs_auth", isError: true, upstream?, hint }.
A call with args missing (or null) is tolerated by treating the
remaining top-level keys as the arguments. The capability executor's optional
opaque context is forwarded unchanged to the selected catalog executor; the
core never reads or records it. Outcomes are recorded as
gateway_invoke / gateway_error events on the local trace stream.
Parameters
| Parameter | Type | Description |
|---|---|---|
catalog | ToolCatalog | Catalog whose tools this executes. |
opts | InvokeToolToolOptions | Optional auth-failure callback. |
Returns
The tool, ready to expose to the model.
isInvokeToolError()
isInvokeToolError(
value):value is InvokeToolError
Whether value is a structured error produced from a target executor failure.
Parameters
| Parameter | Type |
|---|---|
value | unknown |
Returns
value is InvokeToolError
ratel()
ratel(
config?):Ratel
Create a framework-neutral Ratel core. It works standalone — register native
tools on r.tools, skills on r.skills, hand the model r.modelTools(), rank
with r.recall(query) — and adapts to a framework
with a RatelAdapter for that framework's native shapes. The core owns
all state (the catalogs, the recall-id counter) and every
framework-independent guard — reserved capability-tool ids, top-K clamping,
first-registration-wins on the adapted path, passthrough of non-executable
tools — so adapters stay tiny. One core can back several adapter views (they
share the catalog, embeddings, and counter).
Parameters
| Parameter | Type | Description |
|---|---|---|
config | RatelConfig | Retrieval method, embedding model (for semantic/hybrid), recall budget, and trace sink. |
Returns
The standalone core; call .adaptTo(adapter()) for a framework-shaped view.
Example
import { ratel } from "@ratel-ai/sdk";
import { aiSdk } from "@ratel-ai/vercel-ai-sdk";
const r = ratel({ recallTopK: 5 }).adaptTo(aiSdk());
await r.tools.register(myTools);
const tools = r.modelTools(); // stable capability set for the model — take once, reuse
const messages = await r.appendRecall(history); // per-turn recall (AI SDK idiom)registerMcpServer()
registerMcpServer(
catalog,options):Promise<McpServerHandle>
Ingest an MCP server into a ToolCatalog: connect over the given
transport, list every paginated tools/list page (no live refresh), and register each as an
executable tool whose executor proxies
callTool on the live client. A missing tool description registers as "";
a missing output schema as { type: "object" }.
The whole registration is one ratel.upstream.register OTel span and an
upstream_register local trace event; each later invocation records
upstream_invoke (or upstream_error) alongside the catalog's own events
(ADR-0007). Rejects if connecting or listing tools fails.
Parameters
| Parameter | Type | Description |
|---|---|---|
catalog | ToolCatalog | Catalog that receives the proxied tools. |
options | RegisterMcpServerOptions | Server name (the id namespace) and transport. |
Returns
Promise<McpServerHandle>
A handle with the registered ids, the server's instructions, and
close().
Example
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { registerMcpServer, ToolCatalog } from "@ratel-ai/sdk";
const catalog = new ToolCatalog();
const github = await registerMcpServer(catalog, {
name: "github",
transport: new StdioClientTransport({ command: "github-mcp-server" }),
});
// github.toolIds → ["github__create_issue", "github__get_pull_request", ...]
const result = await catalog.invoke("github__create_issue", {
title: "Flaky test on main",
});
await github.close();runCapabilitiesSearch()
runCapabilitiesSearch(
toolCatalog,query,opts?):Promise<SearchCapabilitiesResult>
Rank a query into the search_capabilities result shape — the single source
of truth for that shape, shared by searchCapabilitiesTool (agent
origin) and both ratel() recall paths, standalone core and adapted views
(direct origin), so they can never drift. Ranks the tools bucket (grouped by
upstream server, a matched skill's declared tool deps pulled in additively at
score 0, deduped) and the independently-budgeted skills bucket, caps both
top-Ks at 50 (invalid values fall back to their defaults), and records one
gateway_search event with the given origin.
Parameters
| Parameter | Type | Description |
|---|---|---|
toolCatalog | ToolCatalog | Catalog the tools bucket is ranked from. |
query | string | Natural-language description of what the caller wants to do. |
opts | CapabilitiesSearchOptions | Bucket sizes, skill catalog, origin, and upstream metadata. |
Returns
Promise<SearchCapabilitiesResult>
A promise for the SearchCapabilitiesResult.
searchCapabilitiesTool()
searchCapabilitiesTool(
toolCatalog,skillCatalog?,opts?):ExecutableTool
Build the search_capabilities capability tool: unified discovery over
tools AND skills. Its result carries two independently-ranked buckets, each
with its own top-K budget — so a relevant skill can never be starved out of
the results by a large number of matching tools (and we avoid comparing BM25
scores across the two different text shapes).
The tool takes { query, topKTools?, topKSkills? } (defaults 5 and 3;
values above 50 are capped, anything else non-positive or non-integer falls
back to the default) and resolves to a SearchCapabilitiesResult. A
matched skill's declared tool dependencies are pulled into the tools
bucket additively — score 0, beyond the topKTools budget, deduped
against query hits. The skills clause of the tool description appears when
skillCatalog is non-empty at build time (override with
SearchCapabilitiesOptions.advertiseSkills); the result's skills
bucket always ranks the live catalog. Each call records a gateway_search
event on the local trace stream.
Parameters
| Parameter | Type | Description |
|---|---|---|
toolCatalog | ToolCatalog | Catalog the tools bucket is ranked from. |
skillCatalog? | SkillCatalog | Optional catalog the skills bucket is ranked from. |
opts? | SearchCapabilitiesOptions | Upstream-server metadata for the description and result groups. |
Returns
The tool, ready to expose to the model (and to register alongside invokeToolTool, which executes what this discovers).
Example
import { searchCapabilitiesTool, type SearchCapabilitiesResult } from "@ratel-ai/sdk";
const discovery = searchCapabilitiesTool(toolCatalog, skillCatalog, {
upstreamServers: [{ name: "github", description: "GitHub API", toolCount: 30 }],
});
const result = (await discovery.execute({
query: "open a pull request",
})) as SearchCapabilitiesResult;searchToolsTool()
searchToolsTool(
catalog,opts?):ExecutableTool
The pre-0.2.0 tools-only discovery tool, preserved verbatim (id search_tools,
{ groups } result, topK input). New code should use
searchCapabilitiesTool, which additionally returns a reserved skills
bucket. Registering both lets a host serve the old and new names during a
migration window.
Parameters
| Parameter | Type |
|---|---|
catalog | ToolCatalog |
opts? | SearchToolsToolOptions |
Returns
Deprecated
Use searchCapabilitiesTool. Tracked for removal in RAT-250.
setContentCapture()
setContentCapture(
mode):number
Programmatically set the content-capture mode. While set,
contentCaptureMode returns this mode regardless of
OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT — programmatic config wins
over the environment, matching how OpenTelemetry treats env vars as the
fallback for code-level configuration. Pass null/undefined to clear the
override unconditionally and return to env-driven parsing.
The mode is validated like the env var (case-insensitive, legacy true/false/
1/0 accepted) and throws a TypeError on anything unrecognized — failing
loud at config time instead of storing a value that would both disable capture
and mask the env var.
Returns a generation token identifying this call as the current owner of the override; pass it to clearContentCapture to clear only if no newer set has happened since (the safe form for shutdown/teardown hooks).
Parameters
| Parameter | Type |
|---|---|
mode | ContentCapture | null | undefined |
Returns
number