@ratel-ai/sdk
Raw API of @ratel-ai/sdk — every exported class, function, type, and constant of the TypeScript SDK.
v0.4.1 · TypeScript · npm · source
Generated from the doc comments at
ratel-ai/ratel@3be0ecb— 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
SkillCatalog
In-memory catalog of skills, ranked by the native BM25 SkillRegistry. 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 and default retrieval method. A "semantic"/ "hybrid" default makes every subsequent register embed the new skill immediately (loading the embedding model on first use); the "bm25" default stays model-free. |
Returns
Methods
buildEmbeddings()
buildEmbeddings():
void
Pre-compute embeddings for not-yet-embedded skills. See ToolCatalog.buildEmbeddings.
Returns
void
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".
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(
skill):void
Add a skill to the catalog, or replace it in place when the id is already
registered. Name, description, and tags are indexed for ranking; the
body is not (it is the dispatch payload, fetched by
SkillCatalog.invoke). On a semantic/hybrid catalog this also
embeds the new skill immediately, and throws if the embedding model fails
to load.
Parameters
| Parameter | Type | Description |
|---|---|---|
skill | Skill | The skill to register; id is its lookup key. |
Returns
void
search()
search(
query,topK,origin?,method?):SkillHit[]
Search the catalog — the skill counterpart of ToolCatalog.search, with
the same method semantics (a "semantic"/"hybrid" call throws
EmbeddingsNotBuilt if the embedding cache isn't built).
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 hits, best-first with ties broken by skill id; the
score scale depends on the method (BM25 / cosine / RRF).
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
Node binding over the ratel-ai-core skill registry — the skill twin of
ToolRegistry, ranking registered skills against a natural-language query.
Skill bodies are stored but never indexed; fetch them a layer up (the SDK's
SkillCatalog.invoke).
Constructors
Constructor
new SkillRegistry():
SkillRegistry
Create an empty registry with a no-op trace sink.
Returns
Methods
buildEmbeddings()
buildEmbeddings():
void
See ToolRegistry.build_embeddings.
Returns
void
drainTraceEvents()
drainTraceEvents():
any[]
Drain captured envelopes from the active sink. Returns [] unless the
active sink is "memory".
Returns
any[]
recordEvent()
recordEvent(
event):void
Record a custom event on the local trace stream — see
ToolRegistry.recordEvent. Throws on an object that doesn't parse as a
known trace event.
Parameters
| Parameter | Type |
|---|---|
event | any |
Returns
void
register()
register(
skill):void
Index a skill, or replace one in place if its id is already registered.
Omitted optional fields default to empty (tags/tools/metadata)
and "" (body). See ToolRegistry.register.
Parameters
| Parameter | Type |
|---|---|
skill | Skill |
Returns
void
search()
search(
query,topK):SkillHit[]
Lexical BM25 search over skills — see ToolRegistry.search for the
contract (best-first, ties by id, infallible, traced as "direct").
Parameters
| Parameter | Type |
|---|---|
query | string |
topK | number |
Returns
SkillHit[]
searchWithMethod()
searchWithMethod(
query,topK,origin,method):SkillHit[]
Search with an explicit method — see [ToolRegistry::search_with_method].
Parameters
| Parameter | Type |
|---|---|
query | string |
topK | number |
origin | string |
method | string |
Returns
SkillHit[]
searchWithOrigin()
searchWithOrigin(
query,topK,origin):SkillHit[]
BM25 search with an explicit origin — see ToolRegistry.searchWithOrigin.
Parameters
| Parameter | Type |
|---|---|
query | string |
topK | number |
origin | string |
Returns
SkillHit[]
setTraceSink()
setTraceSink(
config):void
Replace the trace sink — see ToolRegistry.setTraceSink.
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();
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 and default retrieval method. A "semantic"/ "hybrid" default makes every subsequent register embed the new tool immediately (loading the embedding model on first use); the "bm25" default stays model-free. |
Returns
Methods
buildEmbeddings()
buildEmbeddings():
void
Pre-compute embeddings for any not-yet-embedded tools. Call after a bulk register, or rely on the automatic per-register embedding a semantic/hybrid catalog does. No-op for a BM25 catalog's cache. Incremental: only tools registered since the last call are embedded. Throws if the embedding model fails to load.
Returns
void
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".
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):Promise<unknown>
Run a registered tool's executor. Sync-absorbing: the executor may return
a plain value or a Promise (both are awaited), and a synchronous throw
inside it surfaces as a rejection of the returned promise — invoke never
throws synchronously, including for an unknown toolId (that rejects with
unknown toolId: …).
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 passed through to the executor unchanged. |
Returns
Promise<unknown>
Whatever the executor returns (resolved if it returned a promise).
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(
tool):void
Add a tool to the catalog, or replace it in place when the id is already registered (metadata, executor, and index entry — the corpus never holds a duplicate). On a semantic/hybrid catalog this also embeds the new tool immediately, and throws if the embedding model fails to load.
Parameters
| Parameter | Type | Description |
|---|---|---|
tool | ExecutableTool | The tool's searchable metadata plus its execute function. |
Returns
void
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
EmbeddingsNotBuilt if it isn't built; they never load the model in-search (a
semantic/hybrid catalog builds embeddings eagerly at register).
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 hits, best-first with ties broken by tool id. The
score scale depends on the method: a raw BM25 relevance score, a cosine
similarity, or an RRF fusion score — comparable within one result list,
not across methods.
ToolRegistry
Node binding over the ratel-ai-core tool registry: an in-process index
that ranks registered tools against a natural-language query (BM25 by
default; semantic/hybrid once embeddings are built). Metadata-only — the
SDK's ToolCatalog layers executors, OTel spans, and defaults on top.
Constructors
Constructor
new ToolRegistry():
ToolRegistry
Create an empty registry with a no-op trace sink.
Returns
Methods
buildEmbeddings()
buildEmbeddings():
void
Pre-compute embeddings for not-yet-embedded tools (incremental) so a later
semantic/hybrid search only embeds the query. Throws if the model fails to
load. The catalog calls this after register in semantic mode.
Returns
void
drainTraceEvents()
drainTraceEvents():
any[]
Drain captured envelopes from the active sink. Returns [] unless the
active sink is "memory".
Returns
any[]
recordEvent()
recordEvent(
event):void
Record a custom event on the local trace stream (ADR-0007). event is
the tagged wire shape — { type: "...", ... } with snake_case fields —
and an object that doesn't parse as a known event throws
(invalid trace event). Higher layers use this to put their
invoke/upstream/auth lifecycle events on the same stream as the
registry's own search events.
Parameters
| Parameter | Type |
|---|---|
event | any |
Returns
void
register()
register(
tool):void
Index a tool, or replace one in place if its id is already registered
(the corpus never holds a duplicate). Infallible and model-free; a
semantic caller embeds afterwards via buildEmbeddings.
Parameters
| Parameter | Type |
|---|---|
tool | Tool |
Returns
void
search()
search(
query,topK):SearchHit[]
Lexical BM25 search: up to topK hits, best-first with ties broken by
id. Model-free and infallible; an empty registry returns []. 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[]
Search with an explicit method ("bm25" | "semantic" | "hybrid").
bm25 is infallible; semantic/hybrid rank against the prebuilt embedding
cache and throw (EmbeddingsNotBuilt) if it isn't built — the model loads at
build_embeddings, never inside a search. An unknown method string throws too.
Parameters
| Parameter | Type |
|---|---|
query | string |
topK | number |
origin | string |
method | string |
Returns
searchWithOrigin()
searchWithOrigin(
query,topK,origin):SearchHit[]
BM25 search with an explicit origin — "agent" for a call the model
synthesized (capability tools), anything else counts as "direct"
(host code). Origin only annotates the trace event; ranking is
identical to search.
Parameters
| Parameter | Type |
|---|---|
query | string |
topK | number |
origin | string |
Returns
setTraceSink()
setTraceSink(
config):void
Replace the trace sink; subsequent events go to the new destination,
already-recorded ones are not replayed. Throws on an unknown kind, a
missing sessionId/path, or a "jsonl" file that can't be opened.
Parameters
| Parameter | Type |
|---|---|
config | TraceSinkConfig |
Returns
void
Interfaces
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).
ConfigureTelemetryOptions
Options for configureTelemetry: the exporter wiring of InitOptions plus programmatic control of the message/tool content-capture gate.
Extends
Properties
apiKey?
optionalapiKey?:string
Ratel API key; sent as Authorization: Bearer <apiKey>. Defaults to RATEL_API_KEY.
Inherited from
captureContent?
optionalcaptureContent?:ContentCapture
Exact content-capture mode, set programmatically instead of via
OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT. Code-level config wins
over the env var (OTel treats env vars as the fallback for code-level
configuration), and wins over ConfigureTelemetryOptions.includeSpanAndEvents.
endpoint?
optionalendpoint?:string
Full OTLP traces URL (incl. /v1/traces). Defaults to RATEL_URL.
Inherited from
headers?
optionalheaders?:Record<string,string>
Extra headers merged onto the request. An explicit Authorization here is kept over the RATEL_API_KEY env fallback.
Inherited from
includeSpanAndEvents?
optionalincludeSpanAndEvents?:boolean
Convenience switch over ConfigureTelemetryOptions.captureContent:
true is full capture (SPAN_AND_EVENT), false is none (NO_CONTENT).
Ignored when captureContent is set. When neither is provided, the env var
keeps ruling.
serviceName?
optionalserviceName?:string
service.name resource attribute. Defaults to DEFAULT_SERVICE_NAME.
Inherited from
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 the args object.
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
InitOptions
init() (in @ratel-ai/telemetry-otlp) resolves endpoint + auth from
RATEL_URL / RATEL_API_KEY, with explicit { endpoint, apiKey } values
taking precedence over the environment. An explicit apiKey sets the Bearer
header; the RATEL_API_KEY fallback only applies when neither apiKey nor an
explicit Authorization header is given, so ambient env never overrides an
auth header the caller passed on purpose.
Extended by
Properties
apiKey?
optionalapiKey?:string
Ratel API key; sent as Authorization: Bearer <apiKey>. Defaults to RATEL_API_KEY.
endpoint?
optionalendpoint?:string
Full OTLP traces URL (incl. /v1/traces). Defaults to RATEL_URL.
headers?
optionalheaders?:Record<string,string>
Extra headers merged onto the request. An explicit Authorization here is kept over the RATEL_API_KEY env fallback.
serviceName?
optionalserviceName?:string
service.name resource attribute. Defaults to DEFAULT_SERVICE_NAME.
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>
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 (<name>__<toolName>) of every tool registered, in server order.
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.
SearchCapabilitiesOptions
Options for searchCapabilitiesTool.
Properties
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
score
score:
number
Relevance score; higher is better, ties break by id ascending. The scale
depends on the method: raw BM25 (unbounded) for "bm25", cosine
similarity for "semantic", Reciprocal Rank Fusion for "hybrid" —
comparable within one result list, not across methods.
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
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
score
score:
number
Relevance score; higher is better, ties break by id ascending. Scale
depends on the method (BM25 / cosine / RRF), as on SearchHit.score.
skillId
skillId:
string
Id of the matched skill, as registered.
TelemetryHandle
Handle returned by configureTelemetry; shutdown() flushes the exporter.
Methods
shutdown()
shutdown():
Promise<void>
Flush pending spans and shut the exporter down. Call once at process exit.
Returns
Promise<void>
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
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.
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
ContentCapture
ContentCapture = typeof
ContentCapture[keyof typeofContentCapture]
Message/tool content capture modes for
OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT (CONVENTIONS.md § Capture
gating). Default off.
Executor
Executor = (
input) =>Promise<unknown> |unknown
The function that runs a tool. Receives the arguments object and may return
either a plain value or a Promise — ToolCatalog.invoke awaits both,
so synchronous executors need no wrapping.
Parameters
| Parameter | Type |
|---|---|
input | any |
Returns
Promise<unknown> | unknown
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" require the embedding cache (built eagerly at
registration when they are the catalog default, or via buildEmbeddings()).
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_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
configureTelemetry()
configureTelemetry(
options?):Promise<TelemetryHandle>
Convenience wiring for the greenfield case: register a Ratel-owned OTLP exporter
so the spans this SDK emits are shipped to Ratel Cloud (or any OTLP endpoint).
Delegates to the optional @ratel-ai/telemetry-otlp package, lazily imported so
the base SDK install stays OTel-SDK-free (ADR-0007). A host that already runs its
own OpenTelemetry provider should skip this — the SDK's spans flow to that
provider automatically — and add ratelSpanProcessor from @ratel-ai/telemetry-otlp.
captureContent / includeSpanAndEvents opt into content capture in code via
setContentCapture (an unrecognized captureContent throws a TypeError
before any exporter is wired); the returned handle's shutdown() clears the
override, so tests and hot-reloads return to env-driven behavior. The clear is
generation-scoped: a stale handle shutting down late never clobbers an
override a newer configureTelemetry/setContentCapture installed.
Parameters
| Parameter | Type |
|---|---|
options | ConfigureTelemetryOptions |
Returns
Promise<TelemetryHandle>
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 } and runs the
catalog tool via ToolCatalog.invoke, returning its result.
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. 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. 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.
registerMcpServer()
registerMcpServer(
catalog,options):Promise<McpServerHandle>
Ingest an MCP server into a ToolCatalog: connect over the given
transport, list its tools once (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();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 bucket (and its mention in the tool
description) exists only when skillCatalog is non-empty at build time.
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