# 工具

来源：https://docs.nestjs.com/ai/tools

代理函数是你某个提供者的方法，模型可以调用它，并自行填好参数，用于查询或改动某些东西：模型读取该方法返回的内容，然后调用更多函数或作答。你编写代理函数，模型则把它作为工具使用。

这家商店的助手回答订单相关的问题，因此其模型必须查询订单。在 `@nestjs/ai` 中，负责这件事的方法用 `@AgentFunction()` 装饰，它会以其类和方法的守卫、拦截器、管道和异常过滤器运行，并以模型所代表的用户身份执行。除了 `@nestjs/ai`，它不需要别的东西。

#### 定义代理函数

`inputSchema` 描述函数的参数：模型会收到其 JSON Schema，每次调用在执行方法之前都按它校验。模型依据名称和描述挑选函数，并根据各参数的 `.describe()` 文字填写参数：

```typescript
@@filename(orders/orders.tools)
import { Injectable, NotFoundException } from '@nestjs/common';
import { AgentFunction } from '@nestjs/ai';
import * as z from 'zod';
import { OrdersService } from './orders.service.js';

@Injectable()
export class OrdersTools {
  constructor(private readonly orders: OrdersService) {}

  @AgentFunction({
    name: 'find-order',
    description: 'Find an order by its id, with its status',
    inputSchema: z.object({
      orderId: z.string().describe('The order id, such as ord_123'),
    }),
  })
  async find({ orderId }: { orderId: string }) {
    const order = await this.orders.findById(orderId);
    if (!order) {
      throw new NotFoundException(`There is no order ${orderId}`);
    }
    return { id: order.id, status: order.status, total: order.total };
  }
}
```

`@AgentFunction()` 接受四个选项，全部可选：

- **`name`**：调用以什么名字列出该函数，模型也以什么名字调用它。默认为方法名，必须是 1 到 64 个字符，取自 `A-Z a-z 0-9 _ -`，这也是模型提供者接受的工具名。
- **`description`**：该函数做什么，写给模型看。
- **`inputSchema`**：它的参数，为一个对象模式（schema）。没有它时，函数不接受参数。
- **`scopes`**：调用方必须持有的作用域：见[代理代表谁行动](/ai/tools#who-the-agent-acts-for)。

像其他任何提供者一样注册该类：

```typescript
@@filename(orders/orders.module)
@Module({
  providers: [OrdersService, OrdersTools],
  exports: [OrdersService],
})
export class OrdersModule {}
```

`AiModule` 会找出应用每个模块中的代理函数；它自己的 `include` 选项可把搜索限制在所列模块中。

#### 为调用指定工具

调用在 `tools` 中列出其模型可以使用的代理函数，可用名称或提供者类（该类中的每个代理函数），并用 `caller` 说明它代表谁行动：

```typescript
@@filename(assistant/assistant.controller)
import { Body, Controller, Post, Req } from '@nestjs/common';
import { AiService } from '@nestjs/ai';
import type { Request } from 'express';

@Controller('assistant')
export class AssistantController {
  constructor(private readonly ai: AiService) {}

  @Post('questions')
  async ask(@Body() body: { question: string }, @Req() request: Request) {
    const { text } = await this.ai.generateText({
      instructions:
        'You help customers of the cat store with their orders. ' +
        'Look an order up before you answer about it.',
      prompt: body.question,
      tools: ['find-order'],
      caller: { request },
    });
    return { answer: text };
  }
}
```

模型只会被提供该调用所列的函数作为工具，别的一概没有。当它调用其中一个时，参数按函数的模式校验，方法执行，其返回值送回模型，模型再调用更多函数或作答。模型的每一次作答都是一次模型调用，`maxSteps`（默认 10）限定一次调用最多做多少次：见[代理循环](/ai/agents#the-agent-loop)。模式拒绝的参数永远不会到达方法，也不会到达其守卫：模型会被告知问题所在，并可以再试一次。

错误会尽早失败：

- 列出了不存在的代理函数、或列出没有任何代理函数的类的调用，会在发送任何内容之前被拒：`There is no agent function named "find-orders". Agent functions: find-order, change-address.`
- 模型提供者拒绝的名称会在启动时失败，并指出该方法。两个同名代理函数、以及请求作用域提供者上的代理函数，同样如此：请改为通过 `caller` 传入调用所需的内容。
- 不是带 JSON Schema 的 Standard Schema、或未描述对象的模式，也同样如此。

模型把方法返回的内容当作 JSON 读取：`Date` 读作其 ISO 字符串，`undefined` 读作 `null`。同时服务 MCP 客户端的方法可以返回 MCP 的 `CallToolResult`：模型读取其 `structuredContent`，没有则读取其各文本块拼接后的内容。图片、音频等块不会到达模型，日志中会给出警告。带有 `isError: true` 的结果是工具错误，带其文本。

#### 调用上下文

代理函数被调用时会收到其参数和一个 `AgentFunctionContext`，来自 `@nestjs/ai`：

| 属性 | 含义 |
| --- | --- |
| `name` | 该代理函数的名字 |
| `request` | 该调用所在的 HTTP 请求，即 `caller.request`，带其请求头，以及你的认证在其上设置的 `user` |
| `user`、`scopes` | `caller.user` 与 `caller.scopes`：在没有请求的地方（例如队列任务中）该调用代表谁行动 |
| `toolCallId` | 模型为这次工具调用给出的 ID，用于把函数的日志与对话对应起来 |
| `idempotencyKey` | 在[持久化运行](/ai/agents#durable-agent-runs)中，对此调用每次尝试都相同；其他场景为 `undefined` |
| `messages` | 模型在调用该函数时已读过的对话，不含系统提示词（system prompt） |
| `signal` | 一个 `AbortSignal`，调用被中止时中止：请把它传给 `fetch()` 和你的数据库 |
| `reportProgress(progress, total?, message?)` | 在[流式答案](/ai/agents#streaming-to-the-browser)中，把该调用的进度发给浏览器；其他场景下什么都不做 |

`change-address` 让助手修改订单的收货地址。它把调用的 `signal` 传给数据库，并由一个守卫检查该订单是否属于当前顾客：

```typescript
@@filename(assistant/assistant.tools)
import { Injectable, UseGuards } from '@nestjs/common';
import { AgentFunction, type AgentFunctionContext } from '@nestjs/ai';
import * as z from 'zod';
import { OrdersService } from '../orders/orders.service.js';
import { OrderOwnerGuard } from './order-owner.guard.js';

@Injectable()
export class AssistantTools {
  constructor(private readonly orders: OrdersService) {}

  @AgentFunction({
    name: 'change-address',
    description:
      'Change the delivery address of an order that has not shipped yet',
    inputSchema: z.object({
      orderId: z.string().describe('The order id, such as ord_123'),
      address: z.string().min(10).describe('The full new address'),
    }),
  })
  @UseGuards(OrderOwnerGuard)
  async changeAddress(
    { orderId, address }: { orderId: string; address: string },
    ctx: AgentFunctionContext,
  ) {
    const order = await this.orders.changeAddress(orderId, address, {
      signal: ctx.signal,
    });
    return { id: order.id, address: order.address };
  }
}
```

#### 代理代表谁行动

`caller` 说明一次调用代表谁行动，代理函数、其守卫以及认证包都从上下文读取它：

- **`request`**：在路由中，是 Express、Fastify 或 Node 适配器的 HTTP 请求，正如 `@Req()` 注入的那样。函数以 `ctx.request` 看到它，其中带有你的认证设置的 `user`，与路由的守卫所见相同。
- **`user`** 与 **`scopes`**：在没有请求的地方，例如队列任务或定时任务中，说明该调用代表谁行动、可以做什么。它们是 `ctx.user` 与 `ctx.scopes`。

若某个代理函数的 `@AgentFunction()` 声明了 `scopes`，它就只为在 `caller.scopes` 中持有这些作用域的调用方运行：否则调用会在任何守卫运行之前被拒，模型读到 `Forbidden: this tool needs the scope(s) orders:refund`。一个每晚运行的任务以商店的退款机器人身份，审查无人应答的退款请求：

```typescript
@@filename(refunds/refund-review.service)
import { Injectable } from '@nestjs/common';
import { AiService } from '@nestjs/ai';

@Injectable()
export class RefundReviewService {
  constructor(private readonly ai: AiService) {}

  review(ticket: { body: string }) {
    return this.ai.generateText({
      label: 'refund-review',
      instructions:
        'Decide whether the refund request is justified, and refund the ' +
        'order if it is.',
      prompt: ticket.body,
      tools: ['find-order', 'refund'],
      caller: {
        user: { id: 'refund-bot', team: 'support' },
        scopes: ['orders:refund'],
      },
    });
  }
}
```

调用方没有的东西一律不凭空补上：没有 `caller` 的调用，其代理函数运行时没有请求、没有用户、没有作用域。

#### 守卫、拦截器、管道与过滤器

每次代理函数调用都会经过 Nest 的增强器，它们可绑定在类上、方法上或全局，与路由相同。其执行上下文的类型为 `'ai'`，由 `AiExecutionContext` 读取该调用。顾客只能修改自己的订单：

```typescript
@@filename(assistant/order-owner.guard)
import {
  Injectable,
  type CanActivate,
  type ExecutionContext,
} from '@nestjs/common';
import { AiExecutionContext, type AiContextType } from '@nestjs/ai';
import { OrdersService } from '../orders/orders.service.js';

@Injectable()
export class OrderOwnerGuard implements CanActivate {
  constructor(private readonly orders: OrdersService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    if (context.getType<AiContextType>() !== 'ai') {
      return false;
    }
    const call = AiExecutionContext.create(context);
    const { orderId } = call.getInput<{ orderId: string }>();
    const order = await this.orders.findById(orderId);
    return order?.customerId === call.getRequest()?.user?.id;
  }
}
```

`AiExecutionContext.create(context)` 提供 `getType()`、`getInput()`（即参数，也可用 `switchToRpc().getData()` 取得）、`getContext()`（即 `AgentFunctionContext`）、`getName()` 和 `getRequest()`。一次代理函数调用按以下顺序经过这些：

1. 参数按函数的模式校验。
2. 函数的 `scopes` 与调用方的作用域比对。
3. 守卫运行，全局的在前，然后是拦截器和管道，与围绕路由处理器时相同。
4. 方法执行，带着参数和上下文。

管道把参数视为该调用的 `body`，因此 `ValidationPipe` 能校验你用它们标注的 DTO 类，且是在函数模式校验之后；管道把上下文视为 `custom` 参数，`ValidationPipe` 会跳过它。用 `createParamDecorator()` 制作的自定义参数装饰器在参数和上下文之后起作用：`changeAddress(input, ctx, @CurrentUser() user)`。

拦截器在模型之前看到方法的返回值。下面这个拦截器记录每次调用，带模型工具调用的 ID：

```typescript
@@filename(common/tool-audit.interceptor)
import {
  Injectable,
  Logger,
  type CallHandler,
  type ExecutionContext,
  type NestInterceptor,
} from '@nestjs/common';
import { AiExecutionContext } from '@nestjs/ai';
import { tap, type Observable } from 'rxjs';

@Injectable()
export class ToolAuditInterceptor implements NestInterceptor {
  private readonly logger = new Logger('AgentFunctions');

  intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
    const call = AiExecutionContext.create(context);
    const { toolCallId } = call.getContext();
    return next
      .handle()
      .pipe(tap(() => this.logger.log(`${call.getName()} (${toolCallId})`)));
  }
}
```

代理函数抛出的内容会作为模型可以从中恢复、并向用户说明的错误到达模型：守卫的拒绝为 `Forbidden resource`，`HttpException` 的消息（如 `BadRequestException('The address has no postcode')`），以及其他任何错误都是 `Internal server error`，后者由 Nest 的异常处理器记录，其消息永远不会到达模型。异常过滤器可以改为给出响应：它返回的内容就是函数的结果。

> warning **警告** 全局守卫、拦截器和过滤器（`APP_GUARD`、`app.useGlobalGuards()`）也会在代理函数调用上运行，正如它们在 MCP 调用上运行一样。为 HTTP 路由编写、会读取 `context.switchToHttp()` 的增强器，应先检查 `context.getType() === 'http'`。

#### 同时服务 MCP 客户端

订单 API 已经有一个 [MCP 服务器](/mcp/overview)，其客户端——客服团队的助手——也调用 `find-order`。一个方法同时服务两个使用方：它带有来自 [`@nestjs/mcp`](/mcp/primitives#tools) 的 `@Tool()`，供 MCP 客户端使用；也带有 `@AgentFunction()`，供应用的代理使用，各自有自己的选项。两个装饰器互不读取对方的：只有 `@Tool()` 的方法不是代理函数，只有 `@AgentFunction()` 的方法也不是 MCP 工具。用一个模式常量可以免去把模式写两遍：

```typescript
@@filename(orders/orders.tools)
import { Injectable, NotFoundException, UseGuards } from '@nestjs/common';
import { AgentFunction } from '@nestjs/ai';
import { Tool } from '@nestjs/mcp';
import * as z from 'zod';
import { OrderVisibilityGuard } from './order-visibility.guard.js';
import { OrdersService } from './orders.service.js';

const FindOrderInput = z.object({
  orderId: z.string().describe('The order id, such as ord_123'),
});

@Injectable()
export class OrdersTools {
  constructor(private readonly orders: OrdersService) {}

  @Tool({
    name: 'find-order',
    description: 'Find an order by its id, with its status',
    inputSchema: FindOrderInput,
    annotations: { readOnlyHint: true },
  })
  @AgentFunction({
    name: 'find-order',
    description: 'Find an order by its id, with its status',
    inputSchema: FindOrderInput,
  })
  @UseGuards(OrderVisibilityGuard)
  async find({ orderId }: { orderId: string }) {
    const order = await this.orders.findById(orderId);
    if (!order) {
      throw new NotFoundException(`There is no order ${orderId}`);
    }
    return { id: order.id, status: order.status, total: order.total };
  }
}
```

每个使用方找到各自的装饰器：`McpModule` 提供其 `include` 所列模块中带 `@Tool()` 的方法，`AiModule` 找出带 `@AgentFunction()` 的方法：

```typescript
@@filename(app.module)
@Module({
  imports: [
    AiModule.forRoot({
      isGlobal: true,
      models: { default: anthropic('claude-opus-5-5') },
    }),
    McpModule.forRoot({
      name: 'cat-store',
      version: '1.0.0',
      include: [OrdersModule],
    }),
    OrdersModule,
    AssistantModule,
  ],
})
export class AppModule {}
```

MCP 客户端得到 `find-order`，助手则可以调用 `find-order` 和 `change-address`，后者没有 `@Tool()`。

两类调用各有自己的上下文类型：MCP 客户端的调用为 `'mcp'`，由 `McpExecutionContext` 读取；代理的调用为 `'ai'`，由 `AiExecutionContext` 读取。同时服务两者的方法，其守卫、拦截器和过滤器会看到两者，并用 `context.getType()` 区分。`find-order` 通过助手只向顾客显示其自己的订单，而向客服团队的 MCP 客户端显示全部订单：

```typescript
@@filename(orders/order-visibility.guard)
import {
  Injectable,
  type CanActivate,
  type ExecutionContext,
} from '@nestjs/common';
import { AiExecutionContext, type AiContextType } from '@nestjs/ai';
import type { McpContextType } from '@nestjs/mcp';
import { OrdersService } from './orders.service.js';

@Injectable()
export class OrderVisibilityGuard implements CanActivate {
  constructor(private readonly orders: OrdersService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    switch (context.getType<AiContextType | McpContextType>()) {
      case 'mcp':
        return true;
      case 'ai': {
        const call = AiExecutionContext.create(context);
        const { orderId } = call.getInput<{ orderId: string }>();
        const order = await this.orders.findById(orderId);
        return !order || order.customerId === call.getRequest()?.user?.id;
      }
      default:
        return false;
    }
  }
}
```

MCP 客户端的调用中，方法的第二个参数是 `McpContext`；代理的调用中是 `AgentFunctionContext`。用 `createParamDecorator()` 制作的自定义参数装饰器对两类调用同样起作用，它们收到的 `ExecutionContext` 就是其所服务调用的类型。

#### 配合 `@nestjs/authentication` 与 `@nestjs/authorization`

[`@nestjs/authentication`](/security/authentication) 与 [`@nestjs/authorization`](/security/authorization) 读取代理函数调用的方式，与读取 MCP 客户端调用的方式相同：从它们的参数、用该调用所在的请求来读。在路由中，全局认证守卫按每次调用所在的请求进行认证（只做一次：路由的结果会被复用），`@CurrentUser()` 和 `AuthenticationContext` 在代理函数中可用，`@Can()` 策略逐次调用判定。未声明 `@Can()` 的代理函数会被拒绝，与路由一样，模型读到 `Forbidden`：

```typescript
@@filename(orders/orders.tools)
@AgentFunction({
  name: 'cancel-order',
  description: 'Cancel an order that has not shipped yet',
  inputSchema: z.object({ orderId: z.string() }),
})
@Can(OrderPolicy, 'cancel')
cancel(
  { orderId }: { orderId: string },
  ctx: AgentFunctionContext,
  @CurrentUser() customer: Customer,
) {
  return this.orders.cancel(orderId, customer.id);
}
```

在任务中没有请求。`@Can()` 从上下文上找到调用方的 `user`，认证守卫把该调用当作匿名处理，与经 stdio 的调用一样，因此请把任务所调用代理函数的提供者标注为 `@Public()`：

```typescript
@@filename(refunds/refund.tools)
@Injectable()
@Public()
export class RefundTools {
  constructor(private readonly orders: OrdersService) {}

  @AgentFunction({
    name: 'refund',
    description: 'Refund an order to the card it was paid with',
    inputSchema: z.object({ orderId: z.string() }),
    scopes: ['orders:refund'],
  })
  @Can(OrderPolicy, 'refund')
  refund({ orderId }: { orderId: string }) {
    return this.orders.refund(orderId);
  }
}
```

拒绝就是 Nest 的 `UnauthorizedException` 或 `ForbiddenException`，与路由上相同，模型把它读作工具的错误：`Unauthorized` 或 `Forbidden`。

> info **提示** 这需要 `@nestjs/authentication` 0.1.4 与 `@nestjs/authorization` 0.1.2 或更高版本，它们是最早认识 `'ai'` 上下文类型的版本。

#### 在自己的 AI SDK 调用中使用工具

`AiTools` 把代理函数变成 AI SDK 的工具：`select()` 接受的列表与调用的 `tools` 相同，并可指定它们的调用以谁的身份运行，供自己调用 AI SDK 的代码使用。这些函数保留其模式、作用域和增强器：

```typescript
@@filename(support/summaries.service)
@Injectable()
export class SummariesService {
  constructor(
    @InjectModel('fast') private readonly model: LanguageModel,
    private readonly tools: AiTools,
  ) {}

  summarize(thread: string, request: Request) {
    return generateText({
      model: this.model,
      prompt: thread,
      tools: this.tools.select(['find-order'], { caller: { request } }),
      stopWhen: stepCountIs(3),
    });
  }
}
```

`stopWhen` 与 `stepCountIs()` 是 AI SDK 的：这里由它运行自己的循环，与它处理自身的任何调用时一样。
