ToolRegistry
CORE · class · Runtime value
Registry mechanism only: visibility, authorization policy, schemas and semantic metadata are host registrations. A registry is mutable until sealed and keeps its own call log.
Import
import { ToolRegistry } from '@jangts/agent-core/tools';import { ToolRegistry } from '@jangts/agent-core/tools';Other public entry points:@jangts/agent-core, @jangts/agent-core/types, @jangts/agent-core/tools.
Definition
class ToolRegistry<Tool>Type parameters
| Type parameter | Constraint | Default type |
|---|---|---|
Tool | ErasedTool | ErasedTool |
Constructor
new ToolRegistry<Tool extends ErasedTool = ErasedTool>({ execution, errors }?: ToolRegistryOptions): ToolRegistry<Tool>| Parameter | Type | Passing | Description |
|---|---|---|---|
__0 | ToolRegistryOptions | Optional | — |
Fields of __0
| Field | Type | Required | Description |
|---|---|---|---|
execution | ExecutionOptions | undefined | Optional | Read-only. Execution defaults applied to invocations that do not pass their own. |
errors | Pick<ToolRegistryPorts, "unavailable" | "errorCode"> | undefined | Optional | Read-only. Error factories shared by every tool in the registry. |
Returns: ToolRegistry<Tool>.
Instance properties
| Field | Type | Required | Description |
|---|---|---|---|
events | readonly Readonly<ToolExecutionEvent<Tool["kind"]>>[] | Required | Read-only. Frozen snapshot of the recorded execution facts. |
definitions | readonly Readonly<Readonly<ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>>>[] | Required | Read-only. Frozen snapshot of the registered tools, in declaration order. |
Member index
| Member | Purpose |
|---|---|
setDiagnostics | Replace the diagnostics scope used by subsequent calls. Calls already in flight keep the scope they started with. |
register | Register one executable tool. The stored entry is frozen and its parsers are bound to the tool, so later changes on the caller's object cannot alter validation or execution. |
invoke | Invoke a registered tool synchronously. |
invokeAsync | Invoke a registered tool and await its result. |
registerAll | Register several tools. |
get | See the overload below for full inputs and outputs. |
ids | Registered tool ids in declaration order. |
entries | Live iterator over [id, tool] pairs; it reflects only entries added before sealing. |
require | See the overload below for full inputs and outputs. |
has | See the overload below for full inputs and outputs. |
values | Live iterator over the registered tools. |
seal | Close the registry to further registration. Sealing is idempotent and does not affect existing tools. |
Member details
setDiagnostics
Instance method.
Replace the diagnostics scope used by subsequent calls.
Calls already in flight keep the scope they started with.
setDiagnostics(diagnostics: ToolRegistryPorts["diagnostics"]): voidReplace the diagnostics scope used by subsequent calls.
Calls already in flight keep the scope they started with.
| Parameter | Type | Passing | Description |
|---|---|---|---|
diagnostics | DiagnosticContext | undefined | Required | — |
Optional shapes of Parameter diagnostics: choose one shape; required fields for each branch are listed separately.
Branch 1
undefined
Branch 2
| Field | Type | Required | Description |
|---|---|---|---|
identity | Readonly<DiagnosticIdentity> | undefined | Optional | Read-only. Identity of the current scope, when the scope is bound to an execution. |
enabled | (event: CoreEventName, content?: "metadata" | "content") => boolean | Required | Cheap pre-check so callers can skip building expensive payloads. |
emit | <K extends CoreEventName>(event: K, payload: () => CoreEventPayloads[K], debug?: DebugStepsOutput) => void | Required | Records one fact. |
deliver | <K extends CoreEventName>(event: K, payload: () => CoreEventPayloads[K], sink: (event: Extract<CoreEvent, { type: K; }>) => void | Promise<void>) => Promise<void> | Required | Ordered content delivery uses the same fact, while consumer failures propagate. |
child | (spanId: string, fields?: Readonly<DiagnosticSpanFields>) => DiagnosticContext | Required | Derives a child span; fields fills values the child knows but the parent does not. |
withObserver | (observer: import("./execution/events.js").ExecutionObserver) => DiagnosticContext | Required | Bind live observation without changing the log destination or request identity. |
Returns: void.
register
Instance method.
Register one executable tool.
The stored entry is frozen and its parsers are bound to the tool, so later changes on the caller's object cannot alter validation or execution.
register(tool: Tool): ToolRegistry<Tool>Register one executable tool.
The stored entry is frozen and its parsers are bound to the tool, so later changes on the caller's object cannot alter validation or execution.
| Parameter | Type | Passing | Description |
|---|---|---|---|
tool | Tool | Required | — |
Returns: ToolRegistry<Tool>.
invoke
Instance method.
Invoke a registered tool synchronously.
invoke(request: ToolInvocationRequest): ToolResult<unknown>Invoke a registered tool synchronously.
| Parameter | Type | Passing | Description |
|---|---|---|---|
request | ToolInvocationRequest<string> | Required | — |
Fields of request
| Field | Type | Required | Description |
|---|---|---|---|
logger | SubFlowLogger | undefined | Optional | Read-only. Explicit recorder for this call, also available to its handler for deliberate use. |
toolId | string | Required | Read-only. See the type definition and usage context. |
input | unknown | Required | Read-only. Raw model arguments; parsed by the tool's input schema before authorization. |
signal | AbortSignal | undefined | Optional | Read-only. Per-call cancellation; can only shorten the surrounding execution lifetime. |
diagnostics | DiagnosticContext | undefined | Optional | Read-only. See the type definition and usage context. |
Returns: ToolResult<unknown>.
Return value structure
| Field | Type | Required | Description |
|---|---|---|---|
value | unknown | Required | Read-only. See the type definition and usage context. |
invocation | Readonly<ToolCallRecord> | Required | Read-only. See the type definition and usage context. |
invokeAsync
Instance method.
Invoke a registered tool and await its result.
invokeAsync(request: ToolInvocationRequest): Promise<ToolResult<unknown>>Invoke a registered tool and await its result.
| Parameter | Type | Passing | Description |
|---|---|---|---|
request | ToolInvocationRequest<string> | Required | — |
Fields of request
| Field | Type | Required | Description |
|---|---|---|---|
logger | SubFlowLogger | undefined | Optional | Read-only. Explicit recorder for this call, also available to its handler for deliberate use. |
toolId | string | Required | Read-only. See the type definition and usage context. |
input | unknown | Required | Read-only. Raw model arguments; parsed by the tool's input schema before authorization. |
signal | AbortSignal | undefined | Optional | Read-only. Per-call cancellation; can only shorten the surrounding execution lifetime. |
diagnostics | DiagnosticContext | undefined | Optional | Read-only. See the type definition and usage context. |
Returns: Promise<ToolResult<unknown>>.
Awaited value: ToolResult<unknown>.
Return value structure
| Field | Type | Required | Description |
|---|---|---|---|
value | unknown | Required | Read-only. See the type definition and usage context. |
invocation | Readonly<ToolCallRecord> | Required | Read-only. See the type definition and usage context. |
registerAll
Instance method.
Register several tools.
registerAll(tools: Iterable<Tool>): ToolRegistry<Tool>Register several tools.
| Parameter | Type | Passing | Description |
|---|---|---|---|
tools | Iterable<Tool> | Required | — |
Returns: ToolRegistry<Tool>.
get
Instance method.
get(name: string): RegisteredTool<Tool> | undefined| Parameter | Type | Passing | Description |
|---|---|---|---|
name | string | Required | — |
Returns: Readonly<ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>> \| undefined.
Optional shapes of Return value: choose one shape; required fields for each branch are listed separately.
Branch 1
undefined
Branch 2
| Field | Type | Required | Description |
|---|---|---|---|
id | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["id"] | Required | Read-only. See the type definition and usage context. |
kind | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["kind"] | Required | Read-only. See the type definition and usage context. |
description | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["description"] | undefined | Optional | Read-only. Optional here because the erased view does not require model-facing prose. |
debugSteps | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["debugSteps"] | undefined | Optional | Read-only. See the type definition and usage context. |
parseInput | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["parseInput"] | Required | See the type definition and usage context. |
parseOutput | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["parseOutput"] | Required | See the type definition and usage context. |
execute | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["execute"] | Required | See the type definition and usage context. |
ids
Instance method.
Registered tool ids in declaration order.
ids(): readonly string[]Registered tool ids in declaration order.
No call parameters.
Returns: readonly string[].
entries
Instance method.
Live iterator over [id, tool] pairs; it reflects only entries added before sealing.
entries(): IterableIterator<[string, RegisteredTool<Tool>]>Live iterator over [id, tool] pairs; it reflects only entries added before sealing.
No call parameters.
Returns: IterableIterator<[string, Readonly<ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>>]>.
require
Instance method.
require(id: string): RegisteredTool<Tool>| Parameter | Type | Passing | Description |
|---|---|---|---|
id | string | Required | — |
Returns: Readonly<ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>>.
Return value structure
| Field | Type | Required | Description |
|---|---|---|---|
id | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["id"] | Required | Read-only. See the type definition and usage context. |
kind | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["kind"] | Required | Read-only. See the type definition and usage context. |
description | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["description"] | undefined | Optional | Read-only. Optional here because the erased view does not require model-facing prose. |
debugSteps | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["debugSteps"] | undefined | Optional | Read-only. See the type definition and usage context. |
parseInput | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["parseInput"] | Required | See the type definition and usage context. |
parseOutput | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["parseOutput"] | Required | See the type definition and usage context. |
execute | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["execute"] | Required | See the type definition and usage context. |
has
Instance method.
has(name: string): boolean| Parameter | Type | Passing | Description |
|---|---|---|---|
name | string | Required | — |
Returns: boolean.
values
Instance method.
Live iterator over the registered tools.
values(): IterableIterator<RegisteredTool<Tool>>Live iterator over the registered tools.
No call parameters.
Returns: IterableIterator<Readonly<ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>>>.
seal
Instance method.
Close the registry to further registration.
Sealing is idempotent and does not affect existing tools.
seal(): ToolRegistry<Tool>Close the registry to further registration.
Sealing is idempotent and does not affect existing tools.
No call parameters.
Returns: ToolRegistry<Tool>.
Examples
- Real tool invocation and in-request runtime: Core registers and executes real tools and returns receipts carrying an invocation; business authorization is owned by the implementation registered by the App.
Minimal local read-only tool
Beginner · Node.js
import { ToolRegistry } from '@jangts/agent-core/tools';
const tools = new ToolRegistry().register({
id: 'get_status', kind: 'read', description: '读取演示服务状态',
parseInput(value: unknown) { if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('需要对象'); return {}; },
execute: () => '服务运行正常',
parseOutput(value: unknown) { if (typeof value !== 'string') throw new TypeError('需要文本'); return value; },
}).seal();
const result = tools.invoke({ toolId: 'get_status', input: {} });
console.log(result.value, result.invocation.invocationId);import { ToolRegistry } from '@jangts/agent-core/tools';
const tools = new ToolRegistry().register({
id: 'get_status', kind: 'read', description: '读取演示服务状态',
parseInput(value) { if (!value || typeof value !== 'object' || Array.isArray(value))
throw new TypeError('需要对象'); return {}; },
execute: () => '服务运行正常',
parseOutput(value) { if (typeof value !== 'string')
throw new TypeError('需要文本'); return value; },
}).seal();
const result = tools.invoke({ toolId: 'get_status', input: {} });
console.log(result.value, result.invocation.invocationId);Bind in advance so nodes no longer inject tools repeatedly
Configuration · Node.js
The first example validates external input strictly; the second only shows the binding relationship, and real business code should use the appropriate Schema and authorization.
import { AgentCoreEngine, defineWorkflow, route } from '@jangts/agent-core/engine';
import { ToolRegistry } from '@jangts/agent-core/tools';
type State = { answer?: unknown };
const tools = new ToolRegistry().register({ id: 'get_status', kind: 'read',
parseInput: () => ({}), execute: async () => '服务运行正常', parseOutput: value => value,
}).seal();
const workflow = defineWorkflow<State, unknown>({ id: 'status', nodes: [{
id: 'read', description: '读取状态', startsRound: true,
async run(_state, { tools }) { const { value } = await tools.invoke({ toolId: 'get_status', input: {} }); return { answer: value }; },
routes: [route.deliver('answer')],
}] });
const agent = new AgentCoreEngine({ workflow }).bindToolRuntime(tools);
console.log(await agent.run({}));import { AgentCoreEngine, defineWorkflow, route } from '@jangts/agent-core/engine';
import { ToolRegistry } from '@jangts/agent-core/tools';
const tools = new ToolRegistry().register({ id: 'get_status', kind: 'read',
parseInput: () => ({}), execute: async () => '服务运行正常', parseOutput: value => value,
}).seal();
const workflow = defineWorkflow({ id: 'status', nodes: [{
id: 'read', description: '读取状态', startsRound: true,
async run(_state, { tools }) { const { value } = await tools.invoke({ toolId: 'get_status', input: {} }); return { answer: value }; },
routes: [route.deliver('answer')],
}] });
const agent = new AgentCoreEngine({ workflow }).bindToolRuntime(tools);
console.log(await agent.run({}));