文档
CodeRabbit
Cloudflare
AG Grid
Netlify
Neon
WorkOS
Clerk
Convex
Electric
PowerSync
Sentry
Railway
Prisma
Strapi
Unkey
CodeRabbit
Cloudflare
AG Grid
Netlify
Neon
WorkOS
Clerk
Convex
Electric
PowerSync
Sentry
Railway
Prisma
Strapi
Unkey
类引用
函数引用
接口引用
类型别名引用
变量引用
函数引用

toolDefinition

函数: toolDefinition()

ts
function toolDefinition<TInput, TOutput, TName>(config): ToolDefinition<TInput, TOutput, TName>;

定义于: activities/chat/tools/tool-definition.ts:183

创建一个同构工具定义,可以直接使用或实例化用于服务器/客户端

该定义包含所有工具元数据(名称、描述、schemas),并且可以

  1. 直接在服务器上的 chat() 中使用(作为没有 execute 的工具定义)
  2. 使用 .server() 实例化为服务器工具
  3. 使用 .client() 实例化为客户端工具

支持任何符合标准 JSON Schema 规范的库(Zod v4+、ArkType、Valibot 等)或纯 JSON Schema 对象。

类型参数

TInput

TInput extends SchemaInput = SchemaInput

TOutput

TOutput extends SchemaInput = SchemaInput

TName

TName extends string = string

参数

config

ToolDefinitionConfig<TInput, TOutput, TName>

Returns (返回)

ToolDefinition<TInput, TOutput, TName>

示例

typescript
import { toolDefinition } from '@tanstack/ai';
import { z } from 'zod';

// Using Zod (natively supports Standard JSON Schema)
const addToCartTool = toolDefinition({
  name: 'addToCart',
  description: 'Add a guitar to the shopping cart (requires approval)',
  needsApproval: true,
  inputSchema: z.object({
    guitarId: z.string(),
    quantity: z.number(),
  }),
  outputSchema: z.object({
    success: z.boolean(),
    cartId: z.string(),
    totalItems: z.number(),
  }),
});

// Use directly in chat (server-side, no execute function)
chat({
  tools: [addToCartTool],
  // ...
});

// Or create server-side implementation
const addToCartServer = addToCartTool.server(async (args) => {
  // args is typed as { guitarId: string; quantity: number }
  return {
    success: true,
    cartId: 'CART_' + Date.now(),
    totalItems: args.quantity,
  };
});

// Or create client-side implementation
const addToCartClient = addToCartTool.client(async (args) => {
  // Client-specific logic (e.g., localStorage)
  return { success: true, cartId: 'local', totalItems: 1 };
});