ToolRegistry
CORE · class · 运行时值
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 { ToolRegistry } from '@jangts/agent-core/tools';import { ToolRegistry } from '@jangts/agent-core/tools';其他公开入口:@jangts/agent-core、@jangts/agent-core/types、@jangts/agent-core/tools。
定义
class ToolRegistry<Tool>泛型参数
| 类型参数 | 约束 | 默认类型 |
|---|---|---|
Tool | ErasedTool | ErasedTool |
构造函数
new ToolRegistry<Tool extends ErasedTool = ErasedTool>({ execution, errors }?: ToolRegistryOptions): ToolRegistry<Tool>| 参数 | 类型 | 传递 | 说明 |
|---|---|---|---|
__0 | ToolRegistryOptions | 可省略 | — |
__0 的字段
| 字段 | 类型 | 必需 | 说明 |
|---|---|---|---|
execution | ExecutionOptions | undefined | 可省略 | 只读。Execution defaults applied to invocations that do not pass their own. |
errors | Pick<ToolRegistryPorts, "unavailable" | "errorCode"> | undefined | 可省略 | 只读。Error factories shared by every tool in the registry. |
返回: ToolRegistry<Tool>。
实例属性
| 字段 | 类型 | 必需 | 说明 |
|---|---|---|---|
events | readonly Readonly<ToolExecutionEvent<Tool["kind"]>>[] | 必需 | 只读。Frozen snapshot of the recorded execution facts. |
definitions | readonly Readonly<Readonly<ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>>>[] | 必需 | 只读。Frozen snapshot of the registered tools, in declaration order. |
成员目录
| 成员 | 用途 |
|---|---|
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 | 完整输入输出见下方重载。 |
ids | Registered tool ids in declaration order. |
entries | Live iterator over [id, tool] pairs; it reflects only entries added before sealing. |
require | 完整输入输出见下方重载。 |
has | 完整输入输出见下方重载。 |
values | Live iterator over the registered tools. |
seal | Close the registry to further registration. Sealing is idempotent and does not affect existing tools. |
成员详情
setDiagnostics
实例方法。
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.
| 参数 | 类型 | 传递 | 说明 |
|---|---|---|---|
diagnostics | DiagnosticContext | undefined | 必需 | — |
参数 diagnostics的可选结构: 选择其中一种结构,各分支的字段要求分别列出。
分支 1
undefined
分支 2
| 字段 | 类型 | 必需 | 说明 |
|---|---|---|---|
identity | Readonly<DiagnosticIdentity> | undefined | 可省略 | 只读。Identity of the current scope, when the scope is bound to an execution. |
enabled | (event: CoreEventName, content?: "metadata" | "content") => boolean | 必需 | Cheap pre-check so callers can skip building expensive payloads. |
emit | <K extends CoreEventName>(event: K, payload: () => CoreEventPayloads[K], debug?: DebugStepsOutput) => void | 必需 | Records one fact. |
deliver | <K extends CoreEventName>(event: K, payload: () => CoreEventPayloads[K], sink: (event: Extract<CoreEvent, { type: K; }>) => void | Promise<void>) => Promise<void> | 必需 | Ordered content delivery uses the same fact, while consumer failures propagate. |
child | (spanId: string, fields?: Readonly<DiagnosticSpanFields>) => DiagnosticContext | 必需 | Derives a child span; fields fills values the child knows but the parent does not. |
withObserver | (observer: import("./execution/events.js").ExecutionObserver) => DiagnosticContext | 必需 | Bind live observation without changing the log destination or request identity. |
返回: void。
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.
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.
| 参数 | 类型 | 传递 | 说明 |
|---|---|---|---|
tool | Tool | 必需 | — |
返回: ToolRegistry<Tool>。
invoke
实例方法。
Invoke a registered tool synchronously.
invoke(request: ToolInvocationRequest): ToolResult<unknown>Invoke a registered tool synchronously.
| 参数 | 类型 | 传递 | 说明 |
|---|---|---|---|
request | ToolInvocationRequest<string> | 必需 | — |
request 的字段
| 字段 | 类型 | 必需 | 说明 |
|---|---|---|---|
logger | SubFlowLogger | undefined | 可省略 | 只读。Explicit recorder for this call, also available to its handler for deliberate use. |
toolId | string | 必需 | 只读。见类型定义及调用场景。 |
input | unknown | 必需 | 只读。Raw model arguments; parsed by the tool's input schema before authorization. |
signal | AbortSignal | undefined | 可省略 | 只读。Per-call cancellation; can only shorten the surrounding execution lifetime. |
diagnostics | DiagnosticContext | undefined | 可省略 | 只读。见类型定义及调用场景。 |
返回: ToolResult<unknown>。
返回值结构
| 字段 | 类型 | 必需 | 说明 |
|---|---|---|---|
value | unknown | 必需 | 只读。见类型定义及调用场景。 |
invocation | Readonly<ToolCallRecord> | 必需 | 只读。见类型定义及调用场景。 |
invokeAsync
实例方法。
Invoke a registered tool and await its result.
invokeAsync(request: ToolInvocationRequest): Promise<ToolResult<unknown>>Invoke a registered tool and await its result.
| 参数 | 类型 | 传递 | 说明 |
|---|---|---|---|
request | ToolInvocationRequest<string> | 必需 | — |
request 的字段
| 字段 | 类型 | 必需 | 说明 |
|---|---|---|---|
logger | SubFlowLogger | undefined | 可省略 | 只读。Explicit recorder for this call, also available to its handler for deliberate use. |
toolId | string | 必需 | 只读。见类型定义及调用场景。 |
input | unknown | 必需 | 只读。Raw model arguments; parsed by the tool's input schema before authorization. |
signal | AbortSignal | undefined | 可省略 | 只读。Per-call cancellation; can only shorten the surrounding execution lifetime. |
diagnostics | DiagnosticContext | undefined | 可省略 | 只读。见类型定义及调用场景。 |
返回: Promise<ToolResult<unknown>>。
等待后的值: ToolResult<unknown>。
返回值结构
| 字段 | 类型 | 必需 | 说明 |
|---|---|---|---|
value | unknown | 必需 | 只读。见类型定义及调用场景。 |
invocation | Readonly<ToolCallRecord> | 必需 | 只读。见类型定义及调用场景。 |
registerAll
实例方法。
Register several tools.
registerAll(tools: Iterable<Tool>): ToolRegistry<Tool>Register several tools.
| 参数 | 类型 | 传递 | 说明 |
|---|---|---|---|
tools | Iterable<Tool> | 必需 | — |
返回: ToolRegistry<Tool>。
get
实例方法。
get(name: string): RegisteredTool<Tool> | undefined| 参数 | 类型 | 传递 | 说明 |
|---|---|---|---|
name | string | 必需 | — |
返回: Readonly<ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>> \| undefined。
返回值的可选结构: 选择其中一种结构,各分支的字段要求分别列出。
分支 1
undefined
分支 2
| 字段 | 类型 | 必需 | 说明 |
|---|---|---|---|
id | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["id"] | 必需 | 只读。见类型定义及调用场景。 |
kind | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["kind"] | 必需 | 只读。见类型定义及调用场景。 |
description | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["description"] | undefined | 可省略 | 只读。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 | 可省略 | 只读。见类型定义及调用场景。 |
parseInput | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["parseInput"] | 必需 | 见类型定义及调用场景。 |
parseOutput | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["parseOutput"] | 必需 | 见类型定义及调用场景。 |
execute | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["execute"] | 必需 | 见类型定义及调用场景。 |
ids
实例方法。
Registered tool ids in declaration order.
ids(): readonly string[]Registered tool ids in declaration order.
无调用参数。
返回: readonly string[]。
entries
实例方法。
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.
无调用参数。
返回: IterableIterator<[string, Readonly<ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>>]>。
require
实例方法。
require(id: string): RegisteredTool<Tool>| 参数 | 类型 | 传递 | 说明 |
|---|---|---|---|
id | string | 必需 | — |
返回: Readonly<ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>>。
返回值结构
| 字段 | 类型 | 必需 | 说明 |
|---|---|---|---|
id | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["id"] | 必需 | 只读。见类型定义及调用场景。 |
kind | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["kind"] | 必需 | 只读。见类型定义及调用场景。 |
description | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["description"] | undefined | 可省略 | 只读。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 | 可省略 | 只读。见类型定义及调用场景。 |
parseInput | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["parseInput"] | 必需 | 见类型定义及调用场景。 |
parseOutput | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["parseOutput"] | 必需 | 见类型定义及调用场景。 |
execute | (ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["execute"] | 必需 | 见类型定义及调用场景。 |
has
实例方法。
has(name: string): boolean| 参数 | 类型 | 传递 | 说明 |
|---|---|---|---|
name | string | 必需 | — |
返回: boolean。
values
实例方法。
Live iterator over the registered tools.
values(): IterableIterator<RegisteredTool<Tool>>Live iterator over the registered tools.
无调用参数。
返回: IterableIterator<Readonly<ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>>>。
seal
实例方法。
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.
无调用参数。
返回: ToolRegistry<Tool>。
使用示例
- 真实工具调用与请求内运行时:Core 注册并执行真实工具,返回带 invocation 的回执;业务授权由 App 注册的实现拥有。
最小本地只读工具
入门 · 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);提前绑定,节点不再重复注入工具
配置 · Node.js
第一个示例严格校验外部输入;第二个仅展示绑定关系,真实业务应使用相应 Schema 与授权。
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({}));