Skip to content
中文

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 ​

ts
import { ToolRegistry } from '@jangts/agent-core/tools';
js
import { ToolRegistry } from '@jangts/agent-core/tools';

Other public entry points:@jangts/agent-core, @jangts/agent-core/types, @jangts/agent-core/tools.

Definition ​

ts
class ToolRegistry<Tool>

Type parameters ​

Type parameterConstraintDefault type
ToolErasedToolErasedTool

Constructor ​

ts
new ToolRegistry<Tool extends ErasedTool = ErasedTool>({ execution, errors }?: ToolRegistryOptions): ToolRegistry<Tool>
ParameterTypePassingDescription
__0ToolRegistryOptionsOptional—
Fields of __0
FieldTypeRequiredDescription
executionExecutionOptions | undefinedOptionalRead-only. Execution defaults applied to invocations that do not pass their own.
errorsPick<ToolRegistryPorts, "unavailable" | "errorCode"> | undefinedOptionalRead-only. Error factories shared by every tool in the registry.

Returns: ToolRegistry<Tool>.

Instance properties ​

FieldTypeRequiredDescription
eventsreadonly Readonly<ToolExecutionEvent<Tool["kind"]>>[]RequiredRead-only. Frozen snapshot of the recorded execution facts.
definitionsreadonly Readonly<Readonly<ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>>>[]RequiredRead-only. Frozen snapshot of the registered tools, in declaration order.

Member index ​

MemberPurpose
setDiagnosticsReplace the diagnostics scope used by subsequent calls. Calls already in flight keep the scope they started with.
registerRegister 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.
invokeInvoke a registered tool synchronously.
invokeAsyncInvoke a registered tool and await its result.
registerAllRegister several tools.
getSee the overload below for full inputs and outputs.
idsRegistered tool ids in declaration order.
entriesLive iterator over [id, tool] pairs; it reflects only entries added before sealing.
requireSee the overload below for full inputs and outputs.
hasSee the overload below for full inputs and outputs.
valuesLive iterator over the registered tools.
sealClose 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.

ts
setDiagnostics(diagnostics: ToolRegistryPorts["diagnostics"]): void

Replace the diagnostics scope used by subsequent calls.

Calls already in flight keep the scope they started with.

ParameterTypePassingDescription
diagnosticsDiagnosticContext | undefinedRequired—

Optional shapes of Parameter diagnostics: choose one shape; required fields for each branch are listed separately.

Branch 1

undefined

Branch 2
FieldTypeRequiredDescription
identityReadonly<DiagnosticIdentity> | undefinedOptionalRead-only. Identity of the current scope, when the scope is bound to an execution.
enabled(event: CoreEventName, content?: "metadata" | "content") => booleanRequiredCheap pre-check so callers can skip building expensive payloads.
emit<K extends CoreEventName>(event: K, payload: () => CoreEventPayloads[K], debug?: DebugStepsOutput) => voidRequiredRecords one fact.
deliver<K extends CoreEventName>(event: K, payload: () => CoreEventPayloads[K], sink: (event: Extract<CoreEvent, { type: K; }>) => void | Promise<void>) => Promise<void>RequiredOrdered content delivery uses the same fact, while consumer failures propagate.
child(spanId: string, fields?: Readonly<DiagnosticSpanFields>) => DiagnosticContextRequiredDerives a child span; fields fills values the child knows but the parent does not.
withObserver(observer: import("./execution/events.js").ExecutionObserver) => DiagnosticContextRequiredBind 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.

ts
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.

ParameterTypePassingDescription
toolToolRequired—

Returns: ToolRegistry<Tool>.

invoke ​

Instance method.

Invoke a registered tool synchronously.

ts
invoke(request: ToolInvocationRequest): ToolResult<unknown>

Invoke a registered tool synchronously.

ParameterTypePassingDescription
requestToolInvocationRequest<string>Required—
Fields of request
FieldTypeRequiredDescription
loggerSubFlowLogger | undefinedOptionalRead-only. Explicit recorder for this call, also available to its handler for deliberate use.
toolIdstringRequiredRead-only. See the type definition and usage context.
inputunknownRequiredRead-only. Raw model arguments; parsed by the tool's input schema before authorization.
signalAbortSignal | undefinedOptionalRead-only. Per-call cancellation; can only shorten the surrounding execution lifetime.
diagnosticsDiagnosticContext | undefinedOptionalRead-only. See the type definition and usage context.

Returns: ToolResult<unknown>.

Return value structure
FieldTypeRequiredDescription
valueunknownRequiredRead-only. See the type definition and usage context.
invocationReadonly<ToolCallRecord>RequiredRead-only. See the type definition and usage context.

invokeAsync ​

Instance method.

Invoke a registered tool and await its result.

ts
invokeAsync(request: ToolInvocationRequest): Promise<ToolResult<unknown>>

Invoke a registered tool and await its result.

ParameterTypePassingDescription
requestToolInvocationRequest<string>Required—
Fields of request
FieldTypeRequiredDescription
loggerSubFlowLogger | undefinedOptionalRead-only. Explicit recorder for this call, also available to its handler for deliberate use.
toolIdstringRequiredRead-only. See the type definition and usage context.
inputunknownRequiredRead-only. Raw model arguments; parsed by the tool's input schema before authorization.
signalAbortSignal | undefinedOptionalRead-only. Per-call cancellation; can only shorten the surrounding execution lifetime.
diagnosticsDiagnosticContext | undefinedOptionalRead-only. See the type definition and usage context.

Returns: Promise<ToolResult<unknown>>.

Awaited value: ToolResult<unknown>.

Return value structure
FieldTypeRequiredDescription
valueunknownRequiredRead-only. See the type definition and usage context.
invocationReadonly<ToolCallRecord>RequiredRead-only. See the type definition and usage context.

registerAll ​

Instance method.

Register several tools.

ts
registerAll(tools: Iterable<Tool>): ToolRegistry<Tool>

Register several tools.

ParameterTypePassingDescription
toolsIterable<Tool>Required—

Returns: ToolRegistry<Tool>.

get ​

Instance method.

ts
get(name: string): RegisteredTool<Tool> | undefined
ParameterTypePassingDescription
namestringRequired—

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
FieldTypeRequiredDescription
id(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["id"]RequiredRead-only. See the type definition and usage context.
kind(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["kind"]RequiredRead-only. See the type definition and usage context.
description(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["description"] | undefinedOptionalRead-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"] | undefinedOptionalRead-only. See the type definition and usage context.
parseInput(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["parseInput"]RequiredSee the type definition and usage context.
parseOutput(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["parseOutput"]RequiredSee the type definition and usage context.
execute(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["execute"]RequiredSee the type definition and usage context.

ids ​

Instance method.

Registered tool ids in declaration order.

ts
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.

ts
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.

ts
require(id: string): RegisteredTool<Tool>
ParameterTypePassingDescription
idstringRequired—

Returns: Readonly<ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>>.

Return value structure
FieldTypeRequiredDescription
id(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["id"]RequiredRead-only. See the type definition and usage context.
kind(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["kind"]RequiredRead-only. See the type definition and usage context.
description(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["description"] | undefinedOptionalRead-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"] | undefinedOptionalRead-only. See the type definition and usage context.
parseInput(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["parseInput"]RequiredSee the type definition and usage context.
parseOutput(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["parseOutput"]RequiredSee the type definition and usage context.
execute(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["execute"]RequiredSee the type definition and usage context.

has ​

Instance method.

ts
has(name: string): boolean
ParameterTypePassingDescription
namestringRequired—

Returns: boolean.

values ​

Instance method.

Live iterator over the registered tools.

ts
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.

ts
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 ​

Minimal local read-only tool ​

Beginner · Node.js

ts
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);
js
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.

ts
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({}));
js
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({}));

API reference, usage examples and developer guides.