返回產品博客

用裝飾器構建 AI 工具,太爽了

本文發佈於 2024年11月19日。產品當前能力參見產品能力。

用裝飾器構建 AI 工具,太爽了

裝飾器就是魔法。

不是那種虛假的、花裡胡哨的魔法。是真正的魔法 - 複雜的操作變得簡單,冗長的代碼變得優雅,而開發變得…有趣。

當我們在 Zhama 構建 @zhama/mcp-server 時,我們只有一個目標:讓為 Claude Desktop 構建 AI 工具的感覺,不再像是與配置搏鬥,而更像是在寫詩。

答案?TypeScript 裝飾器。

讓我展示為什麼用裝飾器構建 AI 工具是擴展 Claude 能力最令人愉悅的方式。

一切改變的那一刻

我記得那個確切的時刻。凌晨 2 點,我正喝著第五杯咖啡,盯著 200 行 JSON Schema 定義,只是為了一個簡單的郵件工具。我的大腦快要融化了。

然後我想:“如果我可以直接…描述我想要的呢?”

@Tool({
  name: 'send_email',
  description: '发送邮件',
  parameters: [
    { name: 'to', type: 'string', required: true },
    { name: 'subject', type: 'string', required: true },
    { name: 'body', type: 'string', required: true }
  ]
})
class EmailTool extends BaseTool {
  async executeInternal(params) {
    // 只需发送邮件
    return await sendEmail(params);
  }
}

**就這樣。**沒有 schema 對象。沒有處理器註冊。沒有請求路由。只有純粹的、聲明式的美。

我刪除了 180 行樣板代碼,開心地去睡覺了。

是什麼讓裝飾器如此優秀?

1. 它們讀起來像自然語言

看看這個:

@Tool({
  name: 'get_weather',
  description: '获取任何城市的当前天气',
  parameters: [
    { name: 'city', type: 'string', description: '城市名称', required: true }
  ]
})

**你能讀懂這個。**你不需要是 TypeScript 專家。你不需要理解 JSON Schema。你就是…理解它。

對比傳統方法:

const weatherToolSchema = {
  type: 'object',
  properties: {
    city: {
      type: 'string',
      description: '城市名称'
    }
  },
  required: ['city']
};

server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [{
    name: 'get_weather',
    description: '获取任何城市的当前天气',
    inputSchema: weatherToolSchema
  }]
}));

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (request.params.name === 'get_weather') {
    // 终于,你的实际代码
  }
});

**你更願意讀哪個?**更願意寫哪個?

2. 它們把相關的東西放在一起

在傳統方法中,你的工具定義散落在多個地方:

  • Schema 定義:第 50 行
  • 處理器註冊:第 120 行
  • 執行邏輯:第 200 行
  • 錯誤處理:第 250 行

想要改變一個參數?訪問四個不同的地方。

使用裝飾器,所有東西都在一個地方:

@Tool({
  name: 'search_database',
  description: '在产品数据库中搜索商品',
  parameters: [
    { name: 'query', type: 'string', description: '搜索查询', required: true },
    { name: 'limit', type: 'number', description: '最大结果数', required: false }
  ]
})
class SearchTool extends BaseTool {
  protected toolDefinition = {
    name: 'search_database',
    description: '搜索产品',
    parameters: []
  };

  protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
    const { query, limit = 10 } = params as { query: string; limit?: number };
    
    // 验证
    if (query.length < 2) {
      throw new Error('查询必须至少 2 个字符');
    }
    
    // 执行
    const results = await this.database.search(query, limit);
    
    // 响应
    return {
      query,
      count: results.length,
      results
    };
  }
}

**關於這個工具的一切都在這裡。**定義、驗證、邏輯、響應。不用在文件中尋找。

3. 它們支持組合

裝飾器組合得很漂亮。想添加認證?日誌?速率限制?堆疊裝飾器:

@Tool({
  name: 'delete_user',
  description: '删除用户账户(仅管理员)',
  parameters: [
    { name: 'userId', type: 'string', required: true }
  ]
})
@RequireAuth('admin')
@RateLimit({ maxCalls: 10, windowMs: 60000 })
@AuditLog()
class DeleteUserTool extends BaseTool {
  protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
    // 你的逻辑 - 认证、速率限制和日志都是自动的
    return await this.userService.delete(params.userId);
  }
}

**每個裝飾器添加一個能力。**簡潔、模塊化、可組合。

讓我感到愉悅的真實示例

讓我分享一些我用 @zhama/mcp-server 構建的工具,它們讓我在編碼時微笑。

示例 1:一行數據庫查詢

@Tool({
  name: 'count_users',
  description: '统计数据库中的用户总数',
  parameters: []
})
class CountUsersTool extends BaseTool {
  protected toolDefinition = { name: 'count_users', description: '统计用户', parameters: [] };
  
  protected async executeInternal(): Promise<unknown> {
    return { count: await this.db.users.count() };
  }
}

**這就是整個工具。**七行實際代碼。在 Claude 中完美工作。

對比傳統方法:60+ 行,包含 schema 定義、處理器註冊、響應格式化。

示例 2:優雅的 API 包裝器

@Tool({
  name: 'shorten_url',
  description: '使用 bit.ly 创建短链接',
  parameters: [
    { name: 'url', type: 'string', description: '要缩短的 URL', required: true }
  ]
})
class ShortenUrlTool extends BaseTool {
  protected toolDefinition = { name: 'shorten_url', description: '缩短 URL', parameters: [] };

  protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
    const { url } = params as { url: string };
    
    const response = await fetch('https://api-ssl.bitly.com/v4/shorten', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.BITLY_TOKEN}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ long_url: url })
    });

    const data = await response.json();
    return {
      original: url,
      shortened: data.link,
      success: true
    };
  }
}

**優美。**裝飾器描述接口,方法實現邏輯。清晰的關注點分離。

示例 3:強大的驗證器

@Tool({
  name: 'register_user',
  description: '注册新用户账户',
  parameters: [
    { name: 'email', type: 'string', description: '用户邮箱', required: true },
    { name: 'username', type: 'string', description: '用户名', required: true },
    { name: 'password', type: 'string', description: '密码', required: true }
  ]
})
class RegisterUserTool extends BaseTool {
  protected toolDefinition = { name: 'register_user', description: '注册用户', parameters: [] };

  protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
    const { email, username, password } = params as {
      email: string;
      username: string;
      password: string;
    };

    // 验证(自动错误格式化)
    if (!this.isValidEmail(email)) {
      throw new Error('邮箱格式无效');
    }

    if (username.length < 3) {
      throw new Error('用户名必须至少 3 个字符');
    }

    if (password.length < 8) {
      throw new Error('密码必须至少 8 个字符');
    }

    // 注册
    const user = await this.userService.create({
      email,
      username,
      passwordHash: await this.hashPassword(password)
    });

    return {
      success: true,
      userId: user.id,
      message: '用户注册成功'
    };
  }

  private isValidEmail(email: string): boolean {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  }

  private async hashPassword(password: string): Promise<string> {
    // 密码哈希逻辑
    return await bcrypt.hash(password, 10);
  }
}

**一切都在它應該在的地方。**驗證邏輯和工具在一起。輔助方法是私有的。簡潔、可維護、可測試。

模式庫

一旦你開始用裝飾器思考,模式就會出現。這是我的個人收藏:

模式 1:可選參數默認值

@Tool({
  name: 'list_files',
  description: '列出目录中的文件',
  parameters: [
    { name: 'path', type: 'string', description: '目录路径', required: true },
    { name: 'limit', type: 'number', description: '返回的最大文件数', required: false }
  ]
})
class ListFilesTool extends BaseTool {
  protected toolDefinition = { name: 'list_files', description: '列出文件', parameters: [] };

  protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
    const { path, limit = 100 } = params as { path: string; limit?: number };
    
    const files = await fs.readdir(path);
    return {
      path,
      files: files.slice(0, limit),
      total: files.length,
      limited: files.length > limit
    };
  }
}

**帶默認值的解構。**如此簡潔,如此 JavaScript。

模式 2:類型安全的枚舉

@Tool({
  name: 'convert_temperature',
  description: '在单位之间转换温度',
  parameters: [
    { name: 'value', type: 'number', description: '温度值', required: true },
    { name: 'from', type: 'string', description: '源单位:celsius、fahrenheit、kelvin', required: true },
    { name: 'to', type: 'string', description: '目标单位:celsius、fahrenheit、kelvin', required: true }
  ]
})
class ConvertTemperatureTool extends BaseTool {
  protected toolDefinition = { name: 'convert_temperature', description: '转换温度', parameters: [] };

  protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
    const { value, from, to } = params as {
      value: number;
      from: 'celsius' | 'fahrenheit' | 'kelvin';
      to: 'celsius' | 'fahrenheit' | 'kelvin';
    };

    const conversions = {
      celsius: {
        fahrenheit: (v: number) => (v * 9/5) + 32,
        kelvin: (v: number) => v + 273.15
      },
      fahrenheit: {
        celsius: (v: number) => (v - 32) * 5/9,
        kelvin: (v: number) => ((v - 32) * 5/9) + 273.15
      },
      kelvin: {
        celsius: (v: number) => v - 273.15,
        fahrenheit: (v: number) => ((v - 273.15) * 9/5) + 32
      }
    };

    if (from === to) {
      return { value, unit: to };
    }

    const convert = conversions[from]?.[to];
    if (!convert) {
      throw new Error(`无法从 ${from} 转换到 ${to}`);
    }

    return {
      original: { value, unit: from },
      converted: { value: convert(value), unit: to }
    };
  }
}

**類型安全 + 查找表。**優雅且安全。

模式 3:異步鏈

@Tool({
  name: 'process_image',
  description: '下载、调整大小并上传图片',
  parameters: [
    { name: 'url', type: 'string', description: '图片 URL', required: true },
    { name: 'width', type: 'number', description: '目标宽度', required: true },
    { name: 'height', type: 'number', description: '目标高度', required: true }
  ]
})
class ProcessImageTool extends BaseTool {
  protected toolDefinition = { name: 'process_image', description: '处理图片', parameters: [] };

  protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
    const { url, width, height } = params as {
      url: string;
      width: number;
      height: number;
    };

    // 优雅的异步管道
    const originalBuffer = await this.downloadImage(url);
    const resizedBuffer = await this.resizeImage(originalBuffer, width, height);
    const uploadedUrl = await this.uploadImage(resizedBuffer);

    return {
      original: url,
      processed: uploadedUrl,
      dimensions: { width, height },
      success: true
    };
  }

  private async downloadImage(url: string): Promise<Buffer> {
    const response = await fetch(url);
    return Buffer.from(await response.arrayBuffer());
  }

  private async resizeImage(buffer: Buffer, width: number, height: number): Promise<Buffer> {
    // 图片处理逻辑
    return buffer; // 简化版
  }

  private async uploadImage(buffer: Buffer): Promise<string> {
    // 上传逻辑
    return 'https://cdn.example.com/processed.jpg'; // 简化版
  }
}

**Async/await 鏈從上到下閱讀。**沒有回調地獄,沒有 promise 鏈,只有清晰的流程。

模式 4:錯誤上下文

@Tool({
  name: 'charge_payment',
  description: '处理支付收费',
  parameters: [
    { name: 'amount', type: 'number', description: '金额(分)', required: true },
    { name: 'currency', type: 'string', description: '货币代码', required: true },
    { name: 'customerId', type: 'string', description: '客户 ID', required: true }
  ]
})
class ChargePaymentTool extends BaseTool {
  protected toolDefinition = { name: 'charge_payment', description: '收费', parameters: [] };

  protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
    const { amount, currency, customerId } = params as {
      amount: number;
      currency: string;
      customerId: string;
    };

    try {
      // 尝试收费
      const charge = await this.stripe.charges.create({
        amount,
        currency,
        customer: customerId
      });

      return {
        success: true,
        chargeId: charge.id,
        amount,
        currency
      };
    } catch (error) {
      // 丰富的错误上下文
      this.logger.error('支付失败', {
        amount,
        currency,
        customerId,
        error: error.message
      });

      throw new Error(
        `支付失败:${error.message}。` +
        `客户:${customerId},金额:${amount/100} ${currency.toUpperCase()}`
      );
    }
  }
}

**帶上下文的錯誤處理。**當出錯時,你確切地知道發生了什麼。

高級裝飾器技術

一旦你熟悉了基礎知識,試試這些高級模式:

自定義裝飾器

為常見模式創建自己的裝飾器:

// 用于缓存的自定义装饰器
function Cached(ttlSeconds: number) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;
    const cache = new Map<string, { data: any; expires: number }>();

    descriptor.value = async function (...args: any[]) {
      const key = JSON.stringify(args);
      const cached = cache.get(key);

      if (cached && cached.expires > Date.now()) {
        return cached.data;
      }

      const result = await originalMethod.apply(this, args);
      cache.set(key, {
        data: result,
        expires: Date.now() + (ttlSeconds * 1000)
      });

      return result;
    };

    return descriptor;
  };
}

// 使用它
@Tool({
  name: 'get_exchange_rate',
  description: '获取货币汇率',
  parameters: [
    { name: 'from', type: 'string', required: true },
    { name: 'to', type: 'string', required: true }
  ]
})
class ExchangeRateTool extends BaseTool {
  protected toolDefinition = { name: 'get_exchange_rate', description: '获取汇率', parameters: [] };

  @Cached(300) // 缓存 5 分钟
  protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
    const { from, to } = params as { from: string; to: string };
    
    const response = await fetch(`https://api.exchangerate.com/${from}/${to}`);
    const data = await response.json();
    
    return { from, to, rate: data.rate, timestamp: Date.now() };
  }
}

裝飾器組合

堆疊裝飾器以獲得強大的組合:

@Tool({
  name: 'admin_action',
  description: '执行管理操作',
  parameters: [
    { name: 'action', type: 'string', required: true },
    { name: 'target', type: 'string', required: true }
  ]
})
@RequireAuth('admin')           // 必须是管理员
@RateLimit(5, 60000)            // 每分钟最多 5 次
@AuditLog()                     // 记录所有操作
@Retry(3, 1000)                 // 重试 3 次,延迟 1 秒
class AdminActionTool extends BaseTool {
  protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
    // 所有装饰器魔法自动发生
    return await this.performAction(params);
  }
}

為什麼這在規模化時很重要

在 Zhama,我們在多個 Claude 集成中維護 50+ 個 AI 工具。裝飾器不僅僅是好 - 它們是必不可少的。

代碼審查速度

裝飾器之前:

开发者:"能审查一下我的新工具吗?"
审查者:*滚动 150 行*
审查者:"参数验证在哪里?"
开发者:"第 87 行"
审查者:"错误处理在哪里?"
开发者:"120-145 行"
审查者:"实际逻辑在哪里?"
开发者:"60-75 行"

使用裝飾器:

开发者:"能审查一下我的新工具吗?"
审查者:*读 40 行*
审查者:"看起来不错,批准"

代碼審查時間:20 分鐘 → 5 分鐘

入職速度

新開發者的第一天:

之前:

  • 第 1-2 小時:理解服務器設置
  • 第 3-4 小時:學習請求處理器模式
  • 第 5-6 小時:研究 schema 定義
  • 第 7-8 小時:構建第一個工具
  • 總計:8 小時

之後:

  • 第 1 小時:“這是一個裝飾器示例”
  • 第 2 小時:構建第一個工具
  • 總計:2 小時

Bug 密度

**裝飾器之前:**每 1000 行代碼 15 個 bug

  • 主要在樣板代碼中:錯誤的 schema、缺少驗證、響應格式化

**使用裝飾器:**每 1000 行代碼 3 個 bug

  • 全部在業務邏輯中,易於修復

**Bug 減少 5 倍。**不是因為我們是更好的程序員 - 而是因為需要搞砸的代碼更少了。

愉悅因子

讓我誠實地說:編程應該讓人感覺良好。

不是每一天都會完美,但當你在構建東西時,工具應該幫助,而不是阻礙。

裝飾器讓我開心,因為:

  1. 我少想機制 - 沒有 schema、處理器、格式化的心理負擔
  2. 我看到全局 - 關於工具的一切一眼可見
  3. 我交付更快 - 5 分鐘而不是 5 小時
  4. 我犯更少錯誤 - 更少的代碼 = 更少的 bug
  5. 我享受過程 - 寫代碼感覺像在打磨,而不是在配置

**那種“好得難以置信”的感覺?**是真的。@zhama/mcp-server 兌現了它。

開始裝飾器驅動開發

準備好親自體驗了嗎?

安裝

npm install @zhama/mcp-server

你的第一個裝飾器工具

import { createMCPServer, BaseTool, Tool } from '@zhama/mcp-server';

@Tool({
  name: 'hello',
  description: '向某人问好',
  parameters: [
    { name: 'name', type: 'string', description: '要问候的名字', required: true }
  ]
})
class HelloTool extends BaseTool {
  protected toolDefinition = {
    name: 'hello',
    description: '打招呼',
    parameters: []
  };

  protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
    const { name } = params as { name: string };
    return {
      greeting: `你好,${name}!👋`,
      timestamp: new Date().toISOString()
    };
  }
}

// 创建并运行
createMCPServer('hello-server', '1.0.0')
  .enableTools()
  .addTool(new HelloTool())
  .runStdio();

保存這個。構建它。看它工作。

當你看到 Claude 使用你的裝飾器定義的工具時,你會明白的。

社區正在增長

使用 @zhama/mcp-server 的開發者已經構建了:

  • 數據庫工具 - 用裝飾器查詢、插入、更新
  • API 集成 - 優雅地包裝任何 REST API
  • 文件處理器 - 上傳、下載、轉換文件
  • 通知系統 - 郵件、短信、Slack、Discord
  • 分析工具 - 查詢和可視化數據
  • 自動化工作流 - 鏈接多個操作

每一個都使用裝飾器。每一個開發者都喜歡它。

接下來是什麼?

我們正在添加更多裝飾器功能:

  • @Validate() - 參數驗證規則
  • @Transform() - 自動數據轉換
  • @Cache() - 響應緩存
  • @Retry() - 自動重試邏輯
  • @RateLimit() - 請求節流
  • @Auth() - 認證要求

裝飾器模式可以無限擴展。

結論:愉悅是一個功能

當我們構建 @zhama/mcp-server 時,我們不僅想讓開發更快。我們想讓它令人愉悅。

裝飾器實現了這一點。它們轉變了:

  • 配置 → 聲明
  • 樣板代碼 → 清晰
  • 複雜性 → 簡單性
  • 工作 → 手藝

**結果?**開發者在編寫 AI 工具時微笑。

這不是誇張。這是我們在 Zhama 的體驗和社區的反饋。

親自試試:

npm install @zhama/mcp-server

五分鐘後,你也會微笑。


由 Zhama 用 ❤️ 和裝飾器打造

訪問:

分享你的裝飾器驅動工具!標記我們或在 GitHub 上開啟討論 - 我們很想看到你構建的東西!

16 個開箱即用的 TeGo 模板技能:IT 運維 + 跨境電商,一上線就能跑

TeGo v3.0.0 一次性補齊了 16 個 TeGo 系列模板技能,覆蓋 IT 運維與跨境電商兩條最高頻的產業鏈路。每個技能都附帶可執行 bash 腳本,不是「提示詞模板」,而是真正能跑——本文系統介紹這 16 個技能、對應業務流程,以及與 per_user / 模板治理 / BusinessMonitor 是怎麼聯動的。

微信交流群二維碼 微信公眾號二維碼