Skip to content
English

defineTool ​

SUPPORT · function · 运行时值

Validate one tool declaration and freeze a detached copy of it.

authorize must settle with void; a rejection has to be thrown, so a returned false cannot silently pass. Handlers are bound to the declaration object, and the input schema is re-snapshotted so later mutation cannot widen the accepted input.

导入 ​

ts
import { defineTool } from '@jangts/agent-core/support';
js
import { defineTool } from '@jangts/agent-core/support';

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

定义 ​

泛型参数 ​

类型参数约束默认类型
Input——
Output——
App——
Idstringstring

调用 ​

ts
defineTool<Input, Output, App, const Id extends string = string>(definition: ToolDefinition<Input, Output, App> & { readonly id: Id; }): ExecutableTool<Input, Output, App, Id>

Validate one tool declaration and freeze a detached copy of it.

authorize must settle with void; a rejection has to be thrown, so a returned false cannot silently pass. Handlers are bound to the declaration object, and the input schema is re-snapshotted so later mutation cannot widen the accepted input.

类型参数约束默认类型
Input——
Output——
App——
Idstringstring
参数类型传递说明
definitionOmit<ExecutableTool<Input, Output, App, string>, "resolve"> & { readonly resolve?: ((input: Input, context: Readonly<{ stageId: string; }>) => ToolProposal) | undefined; } & { readonly id: Id; }必需—
definition 的字段
字段类型必需说明
idId必需只读。Stable id; also the name the model calls.
descriptionstring必需只读。Model-visible explanation of when to call the tool.
inputSchemaSchemaAdapter<Input>必需只读。Schema applied to raw model arguments before authorize and execute.
activeToolCondition<App> | undefined可省略只读。Omitted means active. Authorization remains a separate execution boundary.
asIntentAsIntent<App> | undefined可省略只读。Omitted means this tool is not advertised by withIntent().
kindstring必需只读。Declared grouping used by registries and documentation; not an authorization boundary.
authorize(input: Input, context: OperationContext<App>) => MaybePromise<void>必需Host permission check. Runs before execution and may be asynchronous.
execute(input: Input, context: OperationContext<App> & NodeReportingContext) => MaybePromise<Output>必需Executes the already-authorized input; must not repeat authorization decisions.
debugSteps((result: Output, context: import("../debug.js").NodeReportingContext) => void) | undefined可省略Optional result hook; writes through context.createSubFlowLogger() are recorded immediately.
parseOutput(value: unknown) => Output必需Validates untrusted output (for example a cached replay) before it is returned.
resolve((input: Input, context: Readonly<{ stageId: string; }>) => ToolProposal) | undefined可省略只读。见类型定义及调用场景。

返回: ExecutableTool<Input, Output, App, Id>。

返回值结构
字段类型必需说明
idId必需只读。Stable id; also the name the model calls.
kindstring必需只读。Declared grouping used by registries and documentation; not an authorization boundary.
descriptionstring必需只读。Model-visible explanation of when to call the tool.
inputSchemaSchemaAdapter<Input>必需只读。Schema applied to raw model arguments before authorize and execute.
authorize(input: Input, context: OperationContext<App>) => MaybePromise<void>必需Host permission check. Runs before execution and may be asynchronous.
execute(input: Input, context: OperationContext<App> & NodeReportingContext) => MaybePromise<Output>必需Executes the already-authorized input; must not repeat authorization decisions.
debugSteps((result: Output, context: import("../debug.js").NodeReportingContext) => void) | undefined可省略Optional result hook; writes through context.createSubFlowLogger() are recorded immediately.
parseOutput(value: unknown) => Output必需Validates untrusted output (for example a cached replay) before it is returned.
activeToolCondition<App> | undefined可省略只读。Omitted means active. Authorization remains a separate execution boundary.
asIntentAsIntent<App> | undefined可省略只读。Omitted means this tool is not advertised by withIntent().
resolve(input: Input, context: Readonly<{ stageId: string; }>) => ToolProposal必需Converts validated arguments into the value handed back to the caller. Runs inside the model call, so it must return synchronously; throwing rejects the selection.

使用示例 ​

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

入门 · 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);

相关策略源码 ​

相关定义 ​

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