Community编程与开发github.com

joshi-chinmay-016/AgentProof

在 NitroStack SDK 中实现和保护 Guards、Interceptors、Middleware、Pipes 及 Exception Filters 的最佳实践。

AgentProof 是什么?

该技能聚焦于 NitroStack SDK 中五种关键的 AOP(面向切面编程)构件:Guards(守卫)、Interceptors(拦截器)、Middleware(中间件)、Pipes(管道)和 Exception Filters(异常过滤器)。它面向使用 TypeScript 和 @nitrostack/core 框架开发 AI 工具和智能体的开发者,旨在简化请求验证、授权检查、响应转换、日志记录、错误处理及性能监控的实现。技能以清晰的中文文档呈现,包含每种构件的接口定义、可注入类的示例代码以及如何通过装饰器(如 @UseGuards、@UseInterceptors、@UseMiddleware、@UsePipes、@UseFilters)将它们应用到工具方法上。遵循这些最佳实践,开发者能构建更健壮、可维护且易于调试的 AI Agent 系统,专注于业务逻辑而不必重复处理横切关注点。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/joshi-chinmay-016/AgentProof/tree/HEAD/agentproof/.agents/skills/middleware-pipeline

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

何时使用

当需要对 NitroStack 工具方法实现请求验证、授权检查、响应映射、日志记录、错误处理或性能追踪时,使用此技能。


1. 守卫(Guard 和 @UseGuards)

守卫基于身份验证、授权或其他条件决定是否应由工具处理程序处理请求。

接口:

import { Guard, ExecutionContext } from '@nitrostack/core';

export interface Guard {
  canActivate(context: ExecutionContext): boolean | Promise<boolean>;
}

示例:

import { Guard, ExecutionContext, Injectable } from '@nitrostack/core';

@Injectable()
export class RolesGuard implements Guard {
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const userRoles = context.clientMetadata?.roles || [];
    return userRoles.includes('admin');
  }
}

使用 @UseGuards(...) 应用守卫:

import { Tool, UseGuards, z } from '@nitrostack/core';
import { RolesGuard } from './roles.guard.js';

export class AdminTools {
  @Tool({
    name: 'delete_system_logs',
    description: '从服务器删除所有系统日志。',
    inputSchema: z.object({}),
  })
  @UseGuards(RolesGuard)
  async deleteLogs() {
    return { success: true };
  }
}

2. 拦截器(InterceptorInterface 和 @UseInterceptors)

拦截器可以转换/拦截输入参数或工具方法执行后的映射输出。

接口:

import { ExecutionContext } from '@nitrostack/core';

export interface InterceptorInterface {
  intercept(context: ExecutionContext, next: () => Promise<unknown>): Promise<unknown>;
}

示例:

import { InterceptorInterface, ExecutionContext, Injectable } from '@nitrostack/core';

@Injectable()
export class TimingInterceptor implements InterceptorInterface {
  async intercept(context: ExecutionContext, next: () => Promise<unknown>): Promise<unknown> {
    const start = Date.now();
    const result = await next();
    const duration = Date.now() - start;
    context.logger.info(`执行耗时 ${duration}ms`);
    return {
      ...result,
      _meta: { durationMs: duration }
    };
  }
}

3. 异常过滤器(ExceptionFilterInterface 和 @UseFilters)

异常过滤器捕获守卫、拦截器或工具处理程序自身抛出的任何错误,并将其映射为用户友好的 JSON 载荷。

接口:

import { ExecutionContext } from '@nitrostack/core';

export interface ExceptionFilterInterface {
  catch(exception: unknown, context: ExecutionContext): unknown | Promise<unknown>;
}

示例:

import { ExceptionFilterInterface, ExecutionContext, Injectable } from '@nitrostack/core';

@Injectable()
export class CustomExceptionFilter implements ExceptionFilterInterface {
  catch(exception: unknown, context: ExecutionContext) {
    const message = exception instanceof Error ? exception.message : '未知错误';
    return {
      error: true,
      message,
      timestamp: new Date().toISOString()
    };
  }
}

在工具方法上使用 @UseFilters(...) 应用过滤器:

import { Tool, UseFilters, z } from '@nitrostack/core';
import { CustomExceptionFilter } from './custom-exception.filter.js';

export class LoggingTools {
  @Tool({
    name: 'generate_report',
    description: '生成系统使用情况报告。',
    inputSchema: z.object({}),
  })
  @UseFilters(CustomExceptionFilter)
  async generateReport() {
    throw new Error('报告生成功能尚未实现。');
  }
}

4. 中间件(MiddlewareInterface、@Middleware 和 @UseMiddleware)

中间件在请求到达工具处理程序之前执行,并且可以通过调用 next() 来包装处理程序的执行。

接口:

import { ExecutionContext } from '@nitrostack/core';

export interface MiddlewareInterface {
  use(context: ExecutionContext, next: () => Promise<unknown>): Promise<unknown>;
}

示例:

import { Middleware, MiddlewareInterface, ExecutionContext } from '@nitrostack/core';

@Middleware()
export class LoggingMiddleware implements MiddlewareInterface {
  async use(context: ExecutionContext, next: () => Promise<unknown>): Promise<unknown> {
    context.logger.info(`进入工具:${context.toolName}`);
    try {
      const result = await next();
      context.logger.info(`退出工具:${context.toolName}`);
      return result;
    } catch (error) {
      context.logger.error(`工具中出错:${error}`);
      throw error;
    }
  }
}

在工具方法上使用 @UseMiddleware(...) 应用中间件:

import { Tool, UseMiddleware, z } from '@nitrostack/core';
import { LoggingMiddleware } from './logging.middleware.js';

export class StationTools {
  @Tool({
    name: 'fetch_logs',
    description: '获取站台操作日志。',
    inputSchema: z.object({}),
  })
  @UseMiddleware(LoggingMiddleware)
  async fetchLogs() {
    return { status: 'operational' };
  }
}

5. 管道(PipeInterface、@Pipe 和 @UsePipes)

管道用于在输入参数到达工具处理程序方法之前对其进行转换或验证。

接口:

import { ArgumentMetadata } from '@nitrostack/core';

export interface PipeInterface<T = unknown, R = unknown> {
  transform(value: T, metadata: ArgumentMetadata): R | Promise<R>;
}

示例:

import { Pipe, PipeInterface, ArgumentMetadata } from '@nitrostack/core';

@Pipe()
export class TrimPipe implements PipeInterface<Record<string, unknown>, Record<string, unknown>> {
  transform(value: Record<string, unknown>, metadata: ArgumentMetadata) {
    const trimmed: Record<string, unknown> = {};
    for (const [key, val] of Object.entries(value)) {
      trimmed[key] = typeof val === 'string' ? val.trim() : val;
    }
    return trimmed;
  }
}

在工具方法上使用 @UsePipes(...) 应用管道:

import { Tool, UsePipes, z } from '@nitrostack/core';
import { TrimPipe } from './trim.pipe.js';

export class MessagingTools {
  @Tool({
    name: 'send_message',
    description: '向其他站台发送消息。',
    inputSchema: z.object({ text: z.string() }),
  })
  @UsePipes(TrimPipe)
  async sendMessage(input: { text: string }) {
    return { sentText: input.text };
  }
}

Individual skills in this repo

This repo contains 2 individual skills — each has its own dedicated page.

相关技能