🤖 妙趣AI

OpenClaw Agent能力扩展

世界上有一种Agent叫OpenClaw,它的能力边界,取决于你的想象力。

📌 功能介绍

OpenClaw Agent的能力扩展是一套插件化的架构设计。通过自定义工具(Custom Tools)、外部API集成和功能插件,你可以让Agent做任何事情——从控制智能家居到管理服务器集群,从分析股票数据到自动发推文。你的Agent,你做主。

💡 妙趣提示:能力扩展的核心原则是「最小权限原则」。每个工具只给Agent需要的最小权限,不要一股脑全给。就像你不会把家门钥匙给快递员一样——给他开信箱的钥匙就够了。

🛠️ 使用方法

1. 自定义工具开发

// tools/weather-tool.js
module.exports = {
  name: 'get_weather',
  description: '获取指定城市的天气预报信息',
  parameters: {
    type: 'object',
    properties: {
      city: { type: 'string', description: '城市名称' },
      days: { type: 'number', description: '预报天数(1-7)', default: 3 }
    },
    required: ['city']
  },
  
  async execute({ city, days }) {
    const response = await fetch(
      `https://api.weather.com/v1/forecast?city=${encodeURIComponent(city)}&days=${days}`,
      { headers: { 'Authorization': `Bearer ${process.env.WEATHER_API_KEY}` } }
    );
    
    if (!response.ok) throw new Error(`天气API错误: ${response.status}`);
    
    const data = await response.json();
    
    return {
      city: city,
      forecast: data.forecast.map(day => ({
        date: day.date,
        temp: `${day.tempMin}°C ~ ${day.tempMax}°C`,
        condition: day.condition,
        suggestion: getSuggestion(day.condition)
      }))
    };
  }
};

function getSuggestion(condition) {
  const suggestions = {
    'sunny': '适合户外活动,记得防晒!',
    'rainy': '出门带伞,别淋成落汤鸡。',
    'cloudy': '天气一般般,适合宅家写代码。',
    'snowy': '可以堆雪人了!但要小心路滑。'
  };
  return suggestions[condition] || '正常出门就行。';
}

2. 注册自定义工具

# 通过配置文件注册
# tools-config.yaml
tools:
  - path: ./tools/weather-tool.js
    permissions:
      - weather:read
    rateLimit: 100/hour
    
  - path: ./tools/database-tool.js
    permissions:
      - database:read
      - database:write
    rateLimit: 50/hour
    sandbox: true  # 在沙箱中运行

# 或通过CLI注册
openclaw tool register --path ./tools/weather-tool.js \
  --session session_abc123 \
  --permissions weather:read \
  --rate-limit 100/hour

3. 外部API集成

// tools/api-bridge.js - 通用API桥接工具
module.exports = {
  name: 'api_bridge',
  description: '通用API桥接工具,支持调用任意配置的外部API',
  parameters: {
    type: 'object',
    properties: {
      service: { 
        type: 'string', 
        enum: ['slack', 'github', 'jira', 'notion', 'stripe'],
        description: '服务名称' 
      },
      endpoint: { type: 'string', description: 'API端点' },
      method: { type: 'string', enum: ['GET', 'POST', 'PUT', 'DELETE'], default: 'GET' },
      body: { type: 'object', description: '请求体(POST/PUT时使用)' }
    },
    required: ['service', 'endpoint']
  },
  
  async execute({ service, endpoint, method, body }) {
    const configs = {
      slack: { baseUrl: 'https://slack.com/api', auth: 'Bearer' },
      github: { baseUrl: 'https://api.github.com', auth: 'token' },
      jira: { baseUrl: process.env.JIRA_BASE_URL, auth: 'Basic' },
      notion: { baseUrl: 'https://api.notion.com/v1', auth: 'Bearer' },
      stripe: { baseUrl: 'https://api.stripe.com/v1', auth: 'Bearer' }
    };
    
    const config = configs[service];
    if (!config) throw new Error(`不支持的服务: ${service}`);
    
    const headers = {
      'Content-Type': 'application/json',
      'Authorization': `${config.auth} ${process.env[`${service.toUpperCase()}_API_KEY`]}`
    };
    
    const response = await fetch(`${config.baseUrl}${endpoint}`, {
      method,
      headers,
      body: body ? JSON.stringify(body) : undefined
    });
    
    return await response.json();
  }
};

🏆 最佳实践

能力扩展设计原则

  1. 单一职责:每个工具只做一件事,做好一件事
  2. 幂等设计:相同输入总是返回相同结果(读取类工具必须幂等)
  3. 错误友好:提供清晰的错误信息,不要让Agent猜
  4. 限流保护:为每个工具设置合理的速率限制
  5. 审计日志:记录工具调用,便于排查问题
⚠️ 安全警告:永远不要把数据库的写入权限直接给Agent!使用预编译语句、输入验证和操作确认。你不会想让Agent「优化」你的数据库——比如把所有用户密码改成「password123」。

💻 代码示例

带确认的危险操作工具

module.exports = {
  name: 'database_write',
  description: '安全的数据库写入工具,支持操作预览和确认',
  parameters: {
    type: 'object',
    properties: {
      operation: { type: 'string', enum: ['insert', 'update', 'delete'] },
      table: { type: 'string' },
      data: { type: 'object' },
      where: { type: 'object', description: 'update/delete条件' },
      dryRun: { type: 'boolean', default: true, description: '预览模式,不实际执行' }
    },
    required: ['operation', 'table']
  },
  
  async execute({ operation, table, data, where, dryRun }, context) {
    // 1. 生成预览SQL
    const sql = generateSQL(operation, table, data, where);
    
    // 2. 预览模式:返回影响预览
    if (dryRun) {
      const preview = await db.execute(`EXPLAIN ${sql}`);
      return {
        mode: 'preview',
        sql: sanitizeSQL(sql),
        estimatedRows: preview.rows,
        requiresConfirmation: true,
        confirmCommand: `database_write(operation="${operation}", table="${table}", dryRun=false)`
      };
    }
    
    // 3. 实际执行:需要确认令牌
    if (!context.confirmationToken) {
      throw new Error('危险操作需要确认令牌。请先运行dryRun=true获取预览。');
    }
    
    // 4. 执行并返回结果
    const result = await db.execute(sql);
    
    // 5. 记录审计日志
    await auditLog.record({
      agent: context.sessionId,
      operation,
      table,
      affectedRows: result.affectedRows,
      timestamp: new Date()
    });
    
    return {
      success: true,
      affectedRows: result.affectedRows,
      message: `${operation} on ${table}: ${result.affectedRows} rows affected`
    };
  }
};

🔗 相关链接

📅 更新时间:2026-05-11 | 📖 更多OpenClaw教程请访问 工具教程索引