Skip to content
English

ToolCatalog ​

SUPPORT · interface · 类型合同

Frozen tool catalog with model tools and per-request binding.

导入 ​

ts
import type { ToolCatalog } from '@jangts/agent-core/support';
js
/** @typedef {import('@jangts/agent-core/support').ToolCatalog} ToolCatalog */

其他公开入口:@jangts/agent-core/types、@jangts/agent-core/structs、@jangts/agent-core/support。

定义 ​

ts
interface ToolCatalog<App, Tool>

继承或实现: ReadonlyCatalog<ToolCatalogEntry<App, Tool>>。

泛型参数 ​

类型参数约束默认类型
App——
ToolToolDefinition<unknown, unknown, App>ToolDefinition<unknown, unknown, App>

字段结构 ​

字段类型必需说明
toolsToolModelView<App>必需只读。见类型定义及调用场景。
select<const Ids extends readonly string[]>(ids: Ids, context?: App) => ToolCatalog<App, SelectedTools<Tool, Ids[number]>>必需Narrows the catalog while preserving declaration order; throws for unknown ids.
withIntent(context: App) => ToolCatalog<App, Tool>必需Active tools advertising demand-discovery use; descriptions are view-local.
bind(request: { app: App; execution?: ExecutionOptions; errors?: Pick<ToolRegistryPorts, "unavailable" | "errorCode">; }) => ToolRuntime<Tool, App>必需Binds the catalog to one App request and returns an invocable runtime.
definitionsreadonly Readonly<ToolCatalogEntry<App, Tool>>[]必需只读。Definitions in registration order; each entry is frozen by the implementation.
ids() => readonly string[]必需Ids in the same order as definitions.
values() => IterableIterator<Readonly<ToolCatalogEntry<App, Tool>>>必需见类型定义及调用场景。
entries() => IterableIterator<readonly [string, Readonly<ToolCatalogEntry<App, Tool>>]>必需见类型定义及调用场景。
has(id: string) => boolean必需见类型定义及调用场景。
get(id: string) => Readonly<ToolCatalogEntry<App, Tool>> | undefined必需Returns the definition or undefined; the caller decides whether absence is an error.
require(id: string) => Readonly<ToolCatalogEntry<App, Tool>>必需Returns the definition or throws; use when the id is a required reference.

成员目录 ​

成员用途
selectNarrows the catalog while preserving declaration order; throws for unknown ids.
withIntentActive tools advertising demand-discovery use; descriptions are view-local.
bindBinds the catalog to one App request and returns an invocable runtime.
idsIds in the same order as definitions.
values完整输入输出见下方重载。
entries完整输入输出见下方重载。
has完整输入输出见下方重载。
getReturns the definition or undefined; the caller decides whether absence is an error.
requireReturns the definition or throws; use when the id is a required reference.

成员详情 ​

select ​

Narrows the catalog while preserving declaration order; throws for unknown ids.

ts
ToolCatalog.select<const Ids extends readonly string[]>(ids: Ids, context?: App): ToolCatalog<App, SelectedTools<Tool, Ids[number]>>

Narrows the catalog while preserving declaration order; throws for unknown ids.

类型参数约束默认类型
Idsreadonly string[]—
参数类型传递说明
idsIds必需—
contextApp | undefined可省略—

返回: ToolCatalog<App, SelectedTools<Tool, Ids[number]>>。

返回值结构
字段类型必需说明
toolsToolModelView<App>必需只读。见类型定义及调用场景。
select<const Ids extends readonly string[]>(ids: Ids, context?: App) => ToolCatalog<App, SelectedTools<SelectedTools<Tool, Ids[number]>, Ids[number]>>必需Narrows the catalog while preserving declaration order; throws for unknown ids.
withIntent(context: App) => ToolCatalog<App, SelectedTools<Tool, Ids[number]>>必需Active tools advertising demand-discovery use; descriptions are view-local.
bind(request: { app: App; execution?: ExecutionOptions; errors?: Pick<ToolRegistryPorts, "unavailable" | "errorCode">; }) => ToolRuntime<SelectedTools<Tool, Ids[number]>, App>必需Binds the catalog to one App request and returns an invocable runtime.
definitionsreadonly Readonly<ToolCatalogEntry<App, SelectedTools<Tool, Ids[number]>>>[]必需只读。Definitions in registration order; each entry is frozen by the implementation.
ids() => readonly string[]必需Ids in the same order as definitions.
values() => IterableIterator<Readonly<ToolCatalogEntry<App, SelectedTools<Tool, Ids[number]>>>>必需见类型定义及调用场景。
entries() => IterableIterator<readonly [string, Readonly<ToolCatalogEntry<App, SelectedTools<Tool, Ids[number]>>>]>必需见类型定义及调用场景。
has(id: string) => boolean必需见类型定义及调用场景。
get(id: string) => Readonly<ToolCatalogEntry<App, SelectedTools<Tool, Ids[number]>>> | undefined必需Returns the definition or undefined; the caller decides whether absence is an error.
require(id: string) => Readonly<ToolCatalogEntry<App, SelectedTools<Tool, Ids[number]>>>必需Returns the definition or throws; use when the id is a required reference.

withIntent ​

Active tools advertising demand-discovery use; descriptions are view-local.

ts
ToolCatalog.withIntent(context: App): ToolCatalog<App, Tool>

Active tools advertising demand-discovery use; descriptions are view-local.

参数类型传递说明
contextApp必需—

返回: ToolCatalog<App, Tool>。

返回值结构
字段类型必需说明
toolsToolModelView<App>必需只读。见类型定义及调用场景。
select<const Ids extends readonly string[]>(ids: Ids, context?: App) => ToolCatalog<App, SelectedTools<Tool, Ids[number]>>必需Narrows the catalog while preserving declaration order; throws for unknown ids.
withIntent(context: App) => ToolCatalog<App, Tool>必需Active tools advertising demand-discovery use; descriptions are view-local.
bind(request: { app: App; execution?: ExecutionOptions; errors?: Pick<ToolRegistryPorts, "unavailable" | "errorCode">; }) => ToolRuntime<Tool, App>必需Binds the catalog to one App request and returns an invocable runtime.
definitionsreadonly Readonly<ToolCatalogEntry<App, Tool>>[]必需只读。Definitions in registration order; each entry is frozen by the implementation.
ids() => readonly string[]必需Ids in the same order as definitions.
values() => IterableIterator<Readonly<ToolCatalogEntry<App, Tool>>>必需见类型定义及调用场景。
entries() => IterableIterator<readonly [string, Readonly<ToolCatalogEntry<App, Tool>>]>必需见类型定义及调用场景。
has(id: string) => boolean必需见类型定义及调用场景。
get(id: string) => Readonly<ToolCatalogEntry<App, Tool>> | undefined必需Returns the definition or undefined; the caller decides whether absence is an error.
require(id: string) => Readonly<ToolCatalogEntry<App, Tool>>必需Returns the definition or throws; use when the id is a required reference.

bind ​

Binds the catalog to one App request and returns an invocable runtime.

ts
ToolCatalog.bind(request: { app: App; execution?: ExecutionOptions; errors?: Pick<ToolRegistryPorts, "unavailable" | "errorCode">; }): ToolRuntime<Tool, App>

Binds the catalog to one App request and returns an invocable runtime.

参数类型传递说明
request{ app: App; execution?: ExecutionOptions; errors?: Pick<ToolRegistryPorts, "unavailable" | "errorCode">; }必需—
request 的字段
字段类型必需说明
appApp必需见类型定义及调用场景。
executionExecutionOptions | undefined可省略见类型定义及调用场景。
errorsPick<ToolRegistryPorts, "unavailable" | "errorCode"> | undefined可省略见类型定义及调用场景。

返回: ToolRuntime<Tool, App>。

返回值结构
字段类型必需说明
toolsToolModelView<App>必需只读。The catalog's model tools, shared with the catalog instance.
eventsreadonly ToolExecutionEvent<string>[]必需只读。Execution events recorded by this runtime so far, in occurrence order.
invokeSync{ <const Id extends Tool["id"]>(request: ToolInvocationRequest<Id>): ToolResult<ToolOutput<Tool, Id>>; (request: ToolInvocationRequest): ToolResult<unknown>; }必需Synchronous invocation; rejects tools declared as asynchronous.
invoke{ <const Id extends Tool["id"]>(request: ToolInvocationRequest<Id>): Promise<ToolResult<ToolOutput<Tool, Id>>>; (request: ToolInvocationRequest): Promise<ToolResult<unknown>>; }必需Asynchronous invocation; still bounded by the bound execution signal and errors.

ids ​

Ids in the same order as definitions.

ts
ToolCatalog.ids(): readonly string[]

Ids in the same order as definitions.

无调用参数。

返回: readonly string[]。

values ​

ts
ToolCatalog.values(): IterableIterator<Readonly<ToolCatalogEntry<App, Tool>>>

无调用参数。

返回: IterableIterator<Readonly<ToolCatalogEntry<App, Tool>>>。

entries ​

ts
ToolCatalog.entries(): IterableIterator<readonly [string, Readonly<ToolCatalogEntry<App, Tool>>]>

无调用参数。

返回: IterableIterator<readonly [string, Readonly<ToolCatalogEntry<App, Tool>>]>。

has ​

ts
ToolCatalog.has(id: string): boolean
参数类型传递说明
idstring必需—

返回: boolean。

get ​

Returns the definition or undefined; the caller decides whether absence is an error.

ts
ToolCatalog.get(id: string): Readonly<ToolCatalogEntry<App, Tool>> | undefined

Returns the definition or undefined; the caller decides whether absence is an error.

参数类型传递说明
idstring必需—

返回: Readonly<ToolCatalogEntry<App, Tool>> \| undefined。

返回值的可选结构: 选择其中一种结构,各分支的字段要求分别列出。

分支 1

undefined

分支 2
字段类型必需说明
idToolCatalogEntry<App, Tool>["id"]必需只读。Stable id; also the name the model calls.
descriptionToolCatalogEntry<App, Tool>["description"]必需只读。Model-visible explanation of when to call the tool.
resolveToolCatalogEntry<App, Tool>["resolve"] | undefined可省略只读。见类型定义及调用场景。
inputSchemaToolCatalogEntry<App, Tool>["inputSchema"]必需只读。Schema applied to raw model arguments before authorize and execute.
activeToolCatalogEntry<App, Tool>["active"] | undefined可省略只读。Omitted means active. Authorization remains a separate execution boundary.
asIntentToolCatalogEntry<App, Tool>["asIntent"] | undefined可省略只读。Omitted means this tool is not advertised by withIntent().
kindToolCatalogEntry<App, Tool>["kind"]必需只读。Declared grouping used by registries and documentation; not an authorization boundary.
authorizeToolCatalogEntry<App, Tool>["authorize"]必需Host permission check. Runs before execution and may be asynchronous.
executeToolCatalogEntry<App, Tool>["execute"]必需Executes the already-authorized input; must not repeat authorization decisions.
debugStepsToolCatalogEntry<App, Tool>["debugSteps"] | undefined可省略Optional result hook; writes through context.createSubFlowLogger() are recorded immediately.
parseOutputToolCatalogEntry<App, Tool>["parseOutput"]必需Validates untrusted output (for example a cached replay) before it is returned.

require ​

Returns the definition or throws; use when the id is a required reference.

ts
ToolCatalog.require(id: string): Readonly<ToolCatalogEntry<App, Tool>>

Returns the definition or throws; use when the id is a required reference.

参数类型传递说明
idstring必需—

返回: Readonly<ToolCatalogEntry<App, Tool>>。

返回值结构
字段类型必需说明
idToolCatalogEntry<App, Tool>["id"]必需只读。Stable id; also the name the model calls.
descriptionToolCatalogEntry<App, Tool>["description"]必需只读。Model-visible explanation of when to call the tool.
resolveToolCatalogEntry<App, Tool>["resolve"] | undefined可省略只读。见类型定义及调用场景。
inputSchemaToolCatalogEntry<App, Tool>["inputSchema"]必需只读。Schema applied to raw model arguments before authorize and execute.
activeToolCatalogEntry<App, Tool>["active"] | undefined可省略只读。Omitted means active. Authorization remains a separate execution boundary.
asIntentToolCatalogEntry<App, Tool>["asIntent"] | undefined可省略只读。Omitted means this tool is not advertised by withIntent().
kindToolCatalogEntry<App, Tool>["kind"]必需只读。Declared grouping used by registries and documentation; not an authorization boundary.
authorizeToolCatalogEntry<App, Tool>["authorize"]必需Host permission check. Runs before execution and may be asynchronous.
executeToolCatalogEntry<App, Tool>["execute"]必需Executes the already-authorized input; must not repeat authorization decisions.
debugStepsToolCatalogEntry<App, Tool>["debugSteps"] | undefined可省略Optional result hook; writes through context.createSubFlowLogger() are recorded immediately.
parseOutputToolCatalogEntry<App, Tool>["parseOutput"]必需Validates untrusted output (for example a cached replay) before it is returned.

使用示例 ​

定义并使用一项只读工具 ​

入门 · Node.js

ts
import { Support } from '@jangts/agent-core';
const inputSchema = Support.defineSchema({
  jsonSchema: { type: 'object', properties: {}, additionalProperties: false },
  parse(value: unknown) {
    if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length) throw new TypeError('需要空对象');
    return {};
  },
});
const catalog = Support.defineToolCatalog([{ id: 'get_status', kind: 'read', description: '读取服务状态', inputSchema,
  authorize() {},
  execute() { return '服务运行正常'; },
  parseOutput(value: unknown) { if (typeof value !== 'string') throw new TypeError('需要字符串'); return value; },
}]);
const tools = catalog.bind({ app: undefined });
console.log((await tools.invoke({ toolId: 'get_status', input: {} })).value);
console.log(catalog.tools.ids());
js
import { Support } from '@jangts/agent-core';
const inputSchema = Support.defineSchema({
    jsonSchema: { type: 'object', properties: {}, additionalProperties: false },
    parse(value) {
        if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length)
            throw new TypeError('需要空对象');
        return {};
    },
});
const catalog = Support.defineToolCatalog([{ id: 'get_status', kind: 'read', description: '读取服务状态', inputSchema,
        authorize() { },
        execute() { return '服务运行正常'; },
        parseOutput(value) { if (typeof value !== 'string')
            throw new TypeError('需要字符串'); return value; },
    }]);
const tools = catalog.bind({ app: undefined });
console.log((await tools.invoke({ toolId: 'get_status', input: {} })).value);
console.log(catalog.tools.ids());

保留清单,增加本次权限与服务依赖 ​

配置 · Node.js

ts
import { Support } from '@jangts/agent-core';
import type { OperationContext } from '@jangts/agent-core/types';
type App = { allowed: boolean; readStatus(): Promise<string> };
const inputSchema = Support.defineSchema({
  jsonSchema: { type: 'object', properties: {}, additionalProperties: false },
  parse(value: unknown) {
    if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length) throw new TypeError('需要空对象');
    return {};
  },
});
const catalog = Support.defineToolCatalog<App>([{ id: 'get_status', kind: 'read', description: '读取状态', inputSchema,
  authorize(_input: {}, { app }: OperationContext<App>) { if (!app.allowed) throw new Error('当前请求没有读取权限'); },
  execute(_input: {}, { app }: OperationContext<App>) { return app.readStatus(); },
  parseOutput(value: unknown) { if (typeof value !== 'string') throw new TypeError('需要字符串'); return value; },
}]);
const tools = catalog.bind({ app: { allowed: true, readStatus: async () => '服务运行正常' },
  execution: { signal: AbortSignal.timeout(10000) },
});
console.log((await tools.invoke({ toolId: 'get_status', input: {} })).value);
js
import { Support } from '@jangts/agent-core';
const inputSchema = Support.defineSchema({
    jsonSchema: { type: 'object', properties: {}, additionalProperties: false },
    parse(value) {
        if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length)
            throw new TypeError('需要空对象');
        return {};
    },
});
const catalog = Support.defineToolCatalog([{ id: 'get_status', kind: 'read', description: '读取状态', inputSchema,
        authorize(_input, { app }) { if (!app.allowed)
            throw new Error('当前请求没有读取权限'); },
        execute(_input, { app }) { return app.readStatus(); },
        parseOutput(value) { if (typeof value !== 'string')
            throw new TypeError('需要字符串'); return value; },
    }]);
const tools = catalog.bind({ app: { allowed: true, readStatus: async () => '服务运行正常' },
    execution: { signal: AbortSignal.timeout(10000) },
});
console.log((await tools.invoke({ toolId: 'get_status', input: {} })).value);

相关策略源码 ​

相关定义 ​

接口参考、使用示例与开发指南。