cloud-functions

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Cloud Functions Development

CloudBase云函数开发

Use this skill when developing, deploying, and managing CloudBase cloud functions (Node.js serverless functions).
在开发、部署和管理CloudBase云函数(Node.js无服务器函数)时使用本技能。

When to use this skill

何时使用本技能

Use this skill for cloud function operations when you need to:
  • Create and deploy Node.js cloud functions
  • Understand runtime limitations and selection
  • Query function logs and monitor execution
  • Invoke cloud functions from applications
  • Configure HTTP access for cloud functions
Do NOT use for:
  • CloudRun backend services (use
    cloudrun-development
    skill)
  • Multi-language backend services (use
    cloudrun-development
    skill)
  • Database operations (use database skills)
当你需要进行以下云函数操作时,使用本技能:
  • 创建并部署Node.js云函数
  • 了解运行时限制与选择方法
  • 查询函数日志并监控执行情况
  • 从应用中调用云函数
  • 为云函数配置HTTP访问
请勿用于:
  • CloudRun后端服务(使用
    cloudrun-development
    技能)
  • 多语言后端服务(使用
    cloudrun-development
    技能)
  • 数据库操作(使用数据库相关技能)

How to use this skill (for a coding agent)

如何使用本技能(针对编码Agent)

  1. Understand runtime limitations
    • Runtime CANNOT be changed after function creation
    • Must select correct runtime during initial creation
    • If runtime needs to change, must delete and recreate function
  2. Choose the right runtime
    • Check supported runtimes list below
    • Default:
      Nodejs18.15
      (recommended)
    • Consider Node.js version compatibility with dependencies
  3. Deploy functions correctly
    • Use
      createFunction
      for new functions
    • Use
      updateFunctionCode
      for code updates (runtime cannot be changed)
    • Provide correct
      functionRootPath
      (parent directory of function folder)
  4. Query logs properly
    • Use
      getFunctionLogs
      for log list (basic info)
    • Use
      getFunctionLogDetail
      with RequestId for detailed logs
    • Note time range limitations (max 1 day interval)

  1. 了解运行时限制
    • 函数创建后无法更改运行时
    • 初始创建时必须选择正确的运行时
    • 若需更改运行时,必须删除并重新创建函数
  2. 选择合适的运行时
    • 查看下方支持的运行时列表
    • 默认值:
      Nodejs18.15
      (推荐)
    • 考虑Node.js版本与依赖的兼容性
  3. 正确部署函数
    • 新函数使用
      createFunction
    • 代码更新使用
      updateFunctionCode
      (无法更改运行时)
    • 提供正确的
      functionRootPath
      (函数文件夹的父目录)
  4. 正确查询日志
    • 使用
      getFunctionLogs
      获取日志列表(基础信息)
    • 结合RequestId使用
      getFunctionLogDetail
      获取详细日志
    • 注意时间范围限制(最大间隔1天)

Core Knowledge

核心知识

Runtime Environment

运行时环境

⚠️ CRITICAL: Runtime cannot be modified after function creation
Once a cloud function is created with a specific runtime, the runtime cannot be changed. If you need a different runtime:
  1. Delete the existing function
  2. Create a new function with the desired runtime
Supported Node.js Runtimes:
  • Nodejs18.15
    (Default, Recommended)
  • Nodejs16.13
  • Nodejs14.18
  • Nodejs12.16
  • Nodejs10.15
  • Nodejs8.9
Runtime Selection Guidelines:
  • Use
    Nodejs18.15
    for new projects (default, most modern)
  • Choose older versions only if dependencies require specific Node.js versions
  • Consider security updates and support lifecycle
  • Test thoroughly with selected runtime before deployment
⚠️ 重要提示:函数创建后无法修改运行时
一旦云函数使用特定运行时创建,该运行时无法更改。若需要不同的运行时:
  1. 删除现有函数
  2. 使用所需运行时创建新函数
支持的Node.js运行时:
  • Nodejs18.15
    (默认,推荐)
  • Nodejs16.13
  • Nodejs14.18
  • Nodejs12.16
  • Nodejs10.15
  • Nodejs8.9
运行时选择指南:
  • 新项目使用
    Nodejs18.15
    (默认,最现代化)
  • 仅当依赖需要特定Node.js版本时才选择旧版本
  • 考虑安全更新与支持生命周期
  • 部署前使用所选运行时进行全面测试

Function Structure

函数结构

Cloud functions require:
  1. Function Directory: Contains function code
    • Must have
      index.js
      (or specified entry file)
    • Must export handler:
      exports.main = async (event, context) => {}
    • Include
      package.json
      with dependencies
  2. Function Root Path: Parent directory containing function directories
    • Example: If function is at
      /project/cloudfunctions/myFunction/
    • functionRootPath
      should be
      /project/cloudfunctions/
    • Important: Do NOT include function name in root path
  3. Entry Point: Default is
    index.js
    with
    exports.main
    • Can be customized via
      handler
      parameter
云函数需要包含:
  1. 函数目录:包含函数代码
    • 必须有
      index.js
      (或指定的入口文件)
    • 必须导出处理函数:
      exports.main = async (event, context) => {}
    • 包含带有依赖的
      package.json
  2. 函数根路径:包含函数目录的父目录
    • 示例:若函数位于
      /project/cloudfunctions/myFunction/
    • functionRootPath
      应为
      /project/cloudfunctions/
    • 重要提示:根路径中请勿包含函数名称
  3. 入口点:默认是带有
    exports.main
    index.js
    • 可通过
      handler
      参数自定义

Function Deployment

函数部署

Creating New Functions:
Use
createFunction
tool (see MCP tool documentation for full parameter list):
  • Important: Always specify
    func.runtime
    explicitly (defaults to
    Nodejs18.15
    )
  • Provide
    functionRootPath
    as parent directory of function folders (absolute path)
  • Use
    force=true
    to overwrite existing function
Updating Function Code:
Use
updateFunctionCode
tool:
  • ⚠️ Note: Only updates code, cannot change runtime
  • If runtime needs to change, delete and recreate function
Deployment Best Practices:
  1. Always specify runtime explicitly when creating functions
  2. Use absolute paths for
    functionRootPath
  3. Don't upload node_modules - dependencies installed automatically
  4. Test locally before deployment when possible
  5. Use environment variables for configuration, not hardcoded values
创建新函数:
使用
createFunction
工具(详见MCP工具文档的完整参数列表):
  • 重要提示:创建时始终显式指定
    func.runtime
    (默认值为
    Nodejs18.15
  • 提供
    functionRootPath
    作为函数文件夹的父目录(绝对路径)
  • 使用
    force=true
    覆盖现有函数
更新函数代码:
使用
updateFunctionCode
工具:
  • ⚠️ 注意:仅更新代码,无法更改运行时
  • 若需更改运行时,需删除并重新创建函数
部署最佳实践:
  1. 创建函数时始终显式指定运行时
  2. functionRootPath
    使用绝对路径
  3. 不要上传node_modules - 依赖会自动安装
  4. 尽可能在本地测试后再部署
  5. 使用环境变量进行配置,而非硬编码值

Function Logs

函数日志

Querying Logs:
Primary Method: Use
getFunctionLogs
and
getFunctionLogDetail
tools (see MCP tool documentation).
Alternative Method (Plan B): If tools unavailable, use
callCloudApi
:
  1. Get Log List - Use
    GetFunctionLogs
    action:
callCloudApi({
  service: "tcb",
  action: "GetFunctionLogs",
  params: {
    EnvId: "{envId}",
    FunctionName: "functionName",
    Offset: 0,
    Limit: 10,
    StartTime: "2024-01-01 00:00:00",
    EndTime: "2024-01-01 23:59:59",
    LogRequestId: "optional-request-id",
    Qualifier: "$LATEST"
  }
})
  1. Get Log Details - Use
    GetFunctionLogDetail
    action (requires LogRequestId from step 1):
callCloudApi({
  service: "tcb",
  action: "GetFunctionLogDetail",
  params: {
    StartTime: "2024-01-01 00:00:00",
    EndTime: "2024-01-01 23:59:59",
    LogRequestId: "request-id-from-log-list"
  }
})
Log Query Limitations:
  • Offset + Limit
    cannot exceed 10000
  • StartTime
    and
    EndTime
    interval cannot exceed 1 day
  • Use pagination for large time ranges
Log Query Best Practices:
  1. Query logs within 1-day windows
  2. Use RequestId for specific invocation debugging
  3. Combine list and detail queries for comprehensive debugging
  4. Check logs after deployment to verify function behavior
查询日志:
主要方法:使用
getFunctionLogs
getFunctionLogDetail
工具(详见MCP工具文档)。
备选方法(方案B):若工具不可用,使用
callCloudApi
  1. 获取日志列表 - 使用
    GetFunctionLogs
    操作:
callCloudApi({
  service: "tcb",
  action: "GetFunctionLogs",
  params: {
    EnvId: "{envId}",
    FunctionName: "functionName",
    Offset: 0,
    Limit: 10,
    StartTime: "2024-01-01 00:00:00",
    EndTime: "2024-01-01 23:59:59",
    LogRequestId: "optional-request-id",
    Qualifier: "$LATEST"
  }
})
  1. 获取日志详情 - 使用
    GetFunctionLogDetail
    操作(需要步骤1中的LogRequestId):
callCloudApi({
  service: "tcb",
  action: "GetFunctionLogDetail",
  params: {
    StartTime: "2024-01-01 00:00:00",
    EndTime: "2024-01-01 23:59:59",
    LogRequestId: "request-id-from-log-list"
  }
})
日志查询限制:
  • Offset + Limit
    不能超过10000
  • StartTime
    EndTime
    的间隔不能超过1天
  • 大范围时间查询使用分页
日志查询最佳实践:
  1. 在1天的时间窗口内查询日志
  2. 使用RequestId调试特定调用
  3. 结合列表与详情查询进行全面调试
  4. 部署后检查日志以验证函数行为

Invoking Cloud Functions

调用云函数

From Web Applications:
javascript
import cloudbase from "@cloudbase/js-sdk";

import cloudbaseSDK from "@cloudbase/js-sdk";

const cloudbase = cloudbaseSDK.init({
  env: 'your-env-id',
  region: 'ap-shanghai',
  accessKey: 'your-access-key'
});

// Call cloud function
const result = await cloudbase.callFunction({
  name: "functionName",
  data: { /* function parameters */ }
});
From Mini Programs:
javascript
wx.cloud.callFunction({
  name: "functionName",
  data: { /* function parameters */ }
}).then(res => {
  console.log(res.result);
});
From Node.js Backend:
javascript
const cloudbase = require("@cloudbase/node-sdk");

const app = cloudbase.init({
  env: "your-env-id"
});

const result = await app.callFunction({
  name: "functionName",
  data: { /* function parameters */ }
});
From HTTP API:
Use CloudBase HTTP API to invoke functions:
  • Endpoint:
    https://api.cloudbase.net/v1/{envId}/functions/{functionName}/invoke
  • Requires authentication token
  • See
    http-api
    skill for details
从Web应用调用:
javascript
import cloudbase from "@cloudbase/js-sdk";

import cloudbaseSDK from "@cloudbase/js-sdk";

const cloudbase = cloudbaseSDK.init({
  env: 'your-env-id',
  region: 'ap-shanghai',
  accessKey: 'your-access-key'
});

// 调用云函数
const result = await cloudbase.callFunction({
  name: "functionName",
  data: { /* 函数参数 */ }
});
从小程序调用:
javascript
wx.cloud.callFunction({
  name: "functionName",
  data: { /* 函数参数 */ }
}).then(res => {
  console.log(res.result);
});
从Node.js后端调用:
javascript
const cloudbase = require("@cloudbase/node-sdk");

const app = cloudbase.init({
  env: "your-env-id"
});

const result = await app.callFunction({
  name: "functionName",
  data: { /* 函数参数 */ }
});
从HTTP API调用:
使用CloudBase HTTP API调用函数:
  • 端点:
    https://api.cloudbase.net/v1/{envId}/functions/{functionName}/invoke
  • 需要认证令牌
  • 详见
    http-api
    技能

HTTP Access Configuration

HTTP访问配置

HTTP Access vs HTTP API:
  • HTTP API: Uses CloudBase API endpoint (
    https://api.cloudbase.net/v1/{envId}/functions/{functionName}/invoke
    ) with authentication token
  • HTTP Access: Creates direct HTTP/HTTPS endpoint for standard REST API access (GET, POST, etc.) without SDK or CloudBase API format
Creating HTTP Access:
Primary Method: Use
createFunctionHTTPAccess
tool (see MCP tool documentation).
Alternative Method (Plan B): If tool unavailable, use
callCloudApi
with
CreateCloudBaseGWAPI
:
callCloudApi({
  service: "tcb",
  action: "CreateCloudBaseGWAPI",
  params: {
    EnableUnion: true,
    Path: "/api/users",
    ServiceId: "{envId}",
    Type: 6,
    Name: "functionName",
    AuthSwitch: 2,
    PathTransmission: 2,
    EnableRegion: true,
    Domain: "*"  // Use "*" for default domain, or custom domain name
  }
})
Key Parameters:
  • Type: 6
    - Cloud Function type (required)
  • AuthSwitch: 2
    - No auth (1 = with auth)
  • Domain: "*"
    - Default domain, or specify custom domain
Access URL:
https://{envId}.{region}.app.tcloudbase.com/{path}
or
https://{domain}/{path}
HTTP访问与HTTP API的区别:
  • HTTP API:使用CloudBase API端点(
    https://api.cloudbase.net/v1/{envId}/functions/{functionName}/invoke
    ),需要认证令牌
  • HTTP访问:创建直接的HTTP/HTTPS端点,支持标准REST API访问(GET、POST等),无需SDK或CloudBase API格式
创建HTTP访问:
主要方法:使用
createFunctionHTTPAccess
工具(详见MCP工具文档)。
备选方法(方案B):若工具不可用,使用带有
CreateCloudBaseGWAPI
callCloudApi
callCloudApi({
  service: "tcb",
  action: "CreateCloudBaseGWAPI",
  params: {
    EnableUnion: true,
    Path: "/api/users",
    ServiceId: "{envId}",
    Type: 6,
    Name: "functionName",
    AuthSwitch: 2,
    PathTransmission: 2,
    EnableRegion: true,
    Domain: "*"  // 使用"*"表示默认域名,或指定自定义域名
  }
})
关键参数:
  • Type: 6
    - 云函数类型(必填)
  • AuthSwitch: 2
    - 无需认证(1 = 需要认证)
  • Domain: "*"
    - 默认域名,或指定自定义域名
访问URL
https://{envId}.{region}.app.tcloudbase.com/{path}
https://{domain}/{path}

Function Configuration

函数配置

Environment Variables:
Set via
func.envVariables
when creating/updating:
javascript
{
  envVariables: {
    "DATABASE_URL": "mysql://...",
    "API_KEY": "secret-key"
  }
}
⚠️ CRITICAL: Environment Variable Update Constraint
When updating environment variables for existing functions:
  1. MUST first query current environment variables using
    getFunctionList
    with
    action=detail
    to get the function's current configuration
  2. MUST merge new environment variables with existing ones
  3. DO NOT directly overwrite - this will delete existing environment variables not included in the update
Correct Update Pattern:
javascript
// 1. First, get current function details
const currentFunction = await getFunctionList({
  action: "detail",
  name: "functionName"
});

// 2. Merge existing envVariables with new ones
const mergedEnvVariables = {
  ...currentFunction.EnvVariables,  // Existing variables
  ...newEnvVariables                 // New/updated variables
};

// 3. Update with merged variables
await updateFunctionConfig({
  funcParam: {
    name: "functionName",
    envVariables: mergedEnvVariables
  }
});
Why This Matters:
  • Direct overwrite will delete all environment variables not included in the update
  • This can break function functionality if critical variables are removed
  • Always preserve existing configuration when making partial updates
Timeout Configuration:
Set via
func.timeout
(in seconds):
  • Default timeout varies by runtime
  • Maximum timeout depends on runtime version
  • Consider function execution time when setting
Timer Triggers:
Configure via
func.triggers
:
  • Type:
    timer
    (only supported type)
  • Config: Cron expression (7 fields: second minute hour day month week year)
  • Examples:
    • "0 0 2 1 * * *"
      - 2:00 AM on 1st of every month
    • "0 30 9 * * * *"
      - 9:30 AM every day
VPC Configuration:
For accessing VPC resources:
javascript
{
  vpc: {
    vpcId: "vpc-xxxxx",
    subnetId: "subnet-xxxxx"
  }
}
环境变量:
创建/更新时通过
func.envVariables
设置:
javascript
{
  envVariables: {
    "DATABASE_URL": "mysql://...",
    "API_KEY": "secret-key"
  }
}
⚠️ 重要提示:环境变量更新约束
更新现有函数的环境变量时:
  1. 必须首先使用
    getFunctionList
    并设置
    action=detail
    查询当前环境变量,以获取函数的当前配置
  2. 必须合并新环境变量与现有变量
  3. 请勿直接覆盖 - 这会删除更新中未包含的现有环境变量
正确的更新模式:
javascript
// 1. 首先,获取当前函数详情
const currentFunction = await getFunctionList({
  action: "detail",
  name: "functionName"
});

// 2. 合并现有envVariables与新变量
const mergedEnvVariables = {
  ...currentFunction.EnvVariables,  // 现有变量
  ...newEnvVariables                 // 新/更新的变量
};

// 3. 使用合并后的变量进行更新
await updateFunctionConfig({
  funcParam: {
    name: "functionName",
    envVariables: mergedEnvVariables
  }
});
为什么这很重要:
  • 直接覆盖会删除所有未包含在更新中的环境变量
  • 这可能会删除关键变量,导致函数功能异常
  • 进行部分更新时始终保留现有配置
超时配置:
通过
func.timeout
设置(单位:秒):
  • 默认超时时间因运行时而异
  • 最大超时时间取决于运行时版本
  • 设置时考虑函数执行时间
定时触发器:
通过
func.triggers
配置:
  • 类型:
    timer
    (仅支持此类型)
  • 配置:Cron表达式(7个字段:秒 分 时 日 月 周 年)
  • 示例:
    • "0 0 2 1 * * *"
      - 每月1日凌晨2:00
    • "0 30 9 * * * *"
      - 每天上午9:30
VPC配置:
用于访问VPC资源:
javascript
{
  vpc: {
    vpcId: "vpc-xxxxx",
    subnetId: "subnet-xxxxx"
  }
}

MCP Tools Reference

MCP工具参考

Function Management:
  • getFunctionList
    - List functions or get function details
  • createFunction
    - Create new cloud function
  • updateFunctionCode
    - Update function code (runtime cannot change)
  • updateFunctionConfig
    - Update function configuration (⚠️ when updating envVariables, must first query and merge with existing values to avoid overwriting)
Logging:
  • getFunctionLogs
    - Get function log list (basic info)
  • getFunctionLogDetail
    - Get detailed log content by RequestId
  • callCloudApi
    (Plan B) - Use
    GetFunctionLogs
    and
    GetFunctionLogDetail
    actions if direct tools unavailable
HTTP Access:
  • createFunctionHTTPAccess
    - Create HTTP access for function
  • callCloudApi
    (Plan B) - Use
    CreateCloudBaseGWAPI
    action if direct tool unavailable
Triggers:
  • manageFunctionTriggers
    - Create or delete function triggers
函数管理:
  • getFunctionList
    - 列出函数或获取函数详情
  • createFunction
    - 创建新云函数
  • updateFunctionCode
    - 更新函数代码(无法更改运行时)
  • updateFunctionConfig
    - 更新函数配置(⚠️ 更新envVariables时,必须先查询并与现有值合并,避免覆盖)
日志管理:
  • getFunctionLogs
    - 获取函数日志列表(基础信息)
  • getFunctionLogDetail
    - 通过RequestId获取详细日志内容
  • callCloudApi
    (方案B):若直接工具不可用,使用
    GetFunctionLogs
    GetFunctionLogDetail
    操作
HTTP访问:
  • createFunctionHTTPAccess
    - 为函数创建HTTP访问
  • callCloudApi
    (方案B):若直接工具不可用,使用
    CreateCloudBaseGWAPI
    操作
触发器:
  • manageFunctionTriggers
    - 创建或删除函数触发器

Console Management

控制台管理

Function Console URLs:
  • Function List:
    https://tcb.cloud.tencent.com/dev?envId=${envId}#/scf
  • Function Detail:
    https://tcb.cloud.tencent.com/dev?envId=${envId}#/scf/detail?id=${functionName}&NameSpace=${envId}
Console Features:
  • View function code and configuration
  • Monitor function invocations and performance
  • Manage environment variables
  • Configure triggers
  • View logs and execution history
函数控制台URL:
  • 函数列表
    https://tcb.cloud.tencent.com/dev?envId=${envId}#/scf
  • 函数详情
    https://tcb.cloud.tencent.com/dev?envId=${envId}#/scf/detail?id=${functionName}&NameSpace=${envId}
控制台功能:
  • 查看函数代码与配置
  • 监控函数调用与性能
  • 管理环境变量
  • 配置触发器
  • 查看日志与执行历史

Common Patterns

常见模式

Error Handling

错误处理

javascript
exports.main = async (event, context) => {
  try {
    // Function logic
    return {
      code: 0,
      message: "Success",
      data: result
    };
  } catch (error) {
    return {
      code: -1,
      message: error.message,
      data: null
    };
  }
};
javascript
exports.main = async (event, context) => {
  try {
    // 函数逻辑
    return {
      code: 0,
      message: "成功",
      data: result
    };
  } catch (error) {
    return {
      code: -1,
      message: error.message,
      data: null
    };
  }
};

Environment Variable Usage

环境变量使用

javascript
exports.main = async (event, context) => {
  const apiKey = process.env.API_KEY;
  const dbUrl = process.env.DATABASE_URL;
  
  // Use environment variables
};
javascript
exports.main = async (event, context) => {
  const apiKey = process.env.API_KEY;
  const dbUrl = process.env.DATABASE_URL;
  
  // 使用环境变量
};

Database Operations

数据库操作

javascript
const cloudbase = require("@cloudbase/node-sdk");

const app = cloudbase.init({
  env: process.env.ENV_ID
});

exports.main = async (event, context) => {
  const db = app.database();
  const result = await db.collection("users").get();
  return result;
};
javascript
const cloudbase = require("@cloudbase/node-sdk");

const app = cloudbase.init({
  env: process.env.ENV_ID
});

exports.main = async (event, context) => {
  const db = app.database();
  const result = await db.collection("users").get();
  return result;
};

Best Practices

最佳实践

  1. Runtime Selection: Always specify runtime explicitly, use
    Nodejs18.15
    for new projects
  2. Code Organization: Keep functions focused and single-purpose
  3. Error Handling: Always implement proper error handling
  4. Environment Variables: Use env vars for configuration, never hardcode secrets
  5. Logging: Add meaningful logs for debugging
  6. Testing: Test functions locally when possible before deployment
  7. Security: Implement authentication/authorization for HTTP access
  8. Performance: Optimize cold start time, use connection pooling for databases
  9. Monitoring: Regularly check logs and monitor function performance
  10. Documentation: Document function parameters and return values
  1. 运行时选择:始终显式指定运行时,新项目使用
    Nodejs18.15
  2. 代码组织:保持函数聚焦,单一职责
  3. 错误处理:始终实现完善的错误处理
  4. 环境变量:使用环境变量进行配置,绝不硬编码敏感信息
  5. 日志记录:添加有意义的日志以便调试
  6. 测试:尽可能在本地测试函数后再部署
  7. 安全:为HTTP访问实现认证/授权
  8. 性能:优化冷启动时间,为数据库使用连接池
  9. 监控:定期检查日志并监控函数性能
  10. 文档:记录函数参数与返回值

Related Skills

相关技能

  • cloudrun-development
    - For multi-language backend services
  • http-api
    - For HTTP API invocation patterns
  • cloudbase-platform
    - For general CloudBase platform knowledge
  • cloudrun-development
    - 用于多语言后端服务
  • http-api
    - 用于HTTP API调用模式
  • cloudbase-platform
    - 用于通用CloudBase平台知识