cloud-functions
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCloud 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 skill)
cloudrun-development - Multi-language backend services (use skill)
cloudrun-development - Database operations (use database skills)
当你需要进行以下云函数操作时,使用本技能:
- 创建并部署Node.js云函数
- 了解运行时限制与选择方法
- 查询函数日志并监控执行情况
- 从应用中调用云函数
- 为云函数配置HTTP访问
请勿用于:
- CloudRun后端服务(使用技能)
cloudrun-development - 多语言后端服务(使用技能)
cloudrun-development - 数据库操作(使用数据库相关技能)
How to use this skill (for a coding agent)
如何使用本技能(针对编码Agent)
-
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
-
Choose the right runtime
- Check supported runtimes list below
- Default: (recommended)
Nodejs18.15 - Consider Node.js version compatibility with dependencies
-
Deploy functions correctly
- Use for new functions
createFunction - Use for code updates (runtime cannot be changed)
updateFunctionCode - Provide correct (parent directory of function folder)
functionRootPath
- Use
-
Query logs properly
- Use for log list (basic info)
getFunctionLogs - Use with RequestId for detailed logs
getFunctionLogDetail - Note time range limitations (max 1 day interval)
- Use
-
了解运行时限制
- 函数创建后无法更改运行时
- 初始创建时必须选择正确的运行时
- 若需更改运行时,必须删除并重新创建函数
-
选择合适的运行时
- 查看下方支持的运行时列表
- 默认值:(推荐)
Nodejs18.15 - 考虑Node.js版本与依赖的兼容性
-
正确部署函数
- 新函数使用
createFunction - 代码更新使用(无法更改运行时)
updateFunctionCode - 提供正确的(函数文件夹的父目录)
functionRootPath
- 新函数使用
-
正确查询日志
- 使用获取日志列表(基础信息)
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:
- Delete the existing function
- Create a new function with the desired runtime
Supported Node.js Runtimes:
- (Default, Recommended)
Nodejs18.15 Nodejs16.13Nodejs14.18Nodejs12.16Nodejs10.15Nodejs8.9
Runtime Selection Guidelines:
- Use for new projects (default, most modern)
Nodejs18.15 - Choose older versions only if dependencies require specific Node.js versions
- Consider security updates and support lifecycle
- Test thoroughly with selected runtime before deployment
⚠️ 重要提示:函数创建后无法修改运行时
一旦云函数使用特定运行时创建,该运行时无法更改。若需要不同的运行时:
- 删除现有函数
- 使用所需运行时创建新函数
支持的Node.js运行时:
- (默认,推荐)
Nodejs18.15 Nodejs16.13Nodejs14.18Nodejs12.16Nodejs10.15Nodejs8.9
运行时选择指南:
- 新项目使用(默认,最现代化)
Nodejs18.15 - 仅当依赖需要特定Node.js版本时才选择旧版本
- 考虑安全更新与支持生命周期
- 部署前使用所选运行时进行全面测试
Function Structure
函数结构
Cloud functions require:
-
Function Directory: Contains function code
- Must have (or specified entry file)
index.js - Must export handler:
exports.main = async (event, context) => {} - Include with dependencies
package.json
- Must have
-
Function Root Path: Parent directory containing function directories
- Example: If function is at
/project/cloudfunctions/myFunction/ - should be
functionRootPath/project/cloudfunctions/ - Important: Do NOT include function name in root path
- Example: If function is at
-
Entry Point: Default iswith
index.jsexports.main- Can be customized via parameter
handler
- Can be customized via
云函数需要包含:
-
函数目录:包含函数代码
- 必须有(或指定的入口文件)
index.js - 必须导出处理函数:
exports.main = async (event, context) => {} - 包含带有依赖的
package.json
- 必须有
-
函数根路径:包含函数目录的父目录
- 示例:若函数位于
/project/cloudfunctions/myFunction/ - 应为
functionRootPath/project/cloudfunctions/ - 重要提示:根路径中请勿包含函数名称
- 示例:若函数位于
-
入口点:默认是带有的
exports.mainindex.js- 可通过参数自定义
handler
- 可通过
Function Deployment
函数部署
Creating New Functions:
Use tool (see MCP tool documentation for full parameter list):
createFunction- Important: Always specify explicitly (defaults to
func.runtime)Nodejs18.15 - Provide as parent directory of function folders (absolute path)
functionRootPath - Use to overwrite existing function
force=true
Updating Function Code:
Use tool:
updateFunctionCode- ⚠️ Note: Only updates code, cannot change runtime
- If runtime needs to change, delete and recreate function
Deployment Best Practices:
- Always specify runtime explicitly when creating functions
- Use absolute paths for
functionRootPath - Don't upload node_modules - dependencies installed automatically
- Test locally before deployment when possible
- Use environment variables for configuration, not hardcoded values
创建新函数:
使用工具(详见MCP工具文档的完整参数列表):
createFunction- 重要提示:创建时始终显式指定(默认值为
func.runtime)Nodejs18.15 - 提供作为函数文件夹的父目录(绝对路径)
functionRootPath - 使用覆盖现有函数
force=true
更新函数代码:
使用工具:
updateFunctionCode- ⚠️ 注意:仅更新代码,无法更改运行时
- 若需更改运行时,需删除并重新创建函数
部署最佳实践:
- 创建函数时始终显式指定运行时
- 使用绝对路径
functionRootPath - 不要上传node_modules - 依赖会自动安装
- 尽可能在本地测试后再部署
- 使用环境变量进行配置,而非硬编码值
Function Logs
函数日志
Querying Logs:
Primary Method: Use and tools (see MCP tool documentation).
getFunctionLogsgetFunctionLogDetailAlternative Method (Plan B): If tools unavailable, use :
callCloudApi- Get Log List - Use action:
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"
}
})- Get Log Details - Use action (requires LogRequestId from step 1):
GetFunctionLogDetail
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:
- cannot exceed 10000
Offset + Limit - and
StartTimeinterval cannot exceed 1 dayEndTime - Use pagination for large time ranges
Log Query Best Practices:
- Query logs within 1-day windows
- Use RequestId for specific invocation debugging
- Combine list and detail queries for comprehensive debugging
- Check logs after deployment to verify function behavior
查询日志:
主要方法:使用和工具(详见MCP工具文档)。
getFunctionLogsgetFunctionLogDetail备选方法(方案B):若工具不可用,使用:
callCloudApi- 获取日志列表 - 使用操作:
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中的LogRequestId):
GetFunctionLogDetail
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"
}
})日志查询限制:
- 不能超过10000
Offset + Limit - 和
StartTime的间隔不能超过1天EndTime - 大范围时间查询使用分页
日志查询最佳实践:
- 在1天的时间窗口内查询日志
- 使用RequestId调试特定调用
- 结合列表与详情查询进行全面调试
- 部署后检查日志以验证函数行为
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 skill for details
http-api
从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 () with authentication token
https://api.cloudbase.net/v1/{envId}/functions/{functionName}/invoke - 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 tool (see MCP tool documentation).
createFunctionHTTPAccessAlternative Method (Plan B): If tool unavailable, use with :
callCloudApiCreateCloudBaseGWAPIcallCloudApi({
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:
- - Cloud Function type (required)
Type: 6 - - No auth (1 = with auth)
AuthSwitch: 2 - - Default domain, or specify custom domain
Domain: "*"
Access URL: or
https://{envId}.{region}.app.tcloudbase.com/{path}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访问:
主要方法:使用工具(详见MCP工具文档)。
createFunctionHTTPAccess备选方法(方案B):若工具不可用,使用带有的:
CreateCloudBaseGWAPIcallCloudApicallCloudApi({
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 - - 无需认证(1 = 需要认证)
AuthSwitch: 2 - - 默认域名,或指定自定义域名
Domain: "*"
访问URL: 或
https://{envId}.{region}.app.tcloudbase.com/{path}https://{domain}/{path}Function Configuration
函数配置
Environment Variables:
Set via when creating/updating:
func.envVariablesjavascript
{
envVariables: {
"DATABASE_URL": "mysql://...",
"API_KEY": "secret-key"
}
}⚠️ CRITICAL: Environment Variable Update Constraint
When updating environment variables for existing functions:
- MUST first query current environment variables using with
getFunctionListto get the function's current configurationaction=detail - MUST merge new environment variables with existing ones
- 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 (in seconds):
func.timeout- Default timeout varies by runtime
- Maximum timeout depends on runtime version
- Consider function execution time when setting
Timer Triggers:
Configure via :
func.triggers- Type: (only supported type)
timer - Config: Cron expression (7 fields: second minute hour day month week year)
- Examples:
- - 2:00 AM on 1st of every month
"0 0 2 1 * * *" - - 9:30 AM every day
"0 30 9 * * * *"
VPC Configuration:
For accessing VPC resources:
javascript
{
vpc: {
vpcId: "vpc-xxxxx",
subnetId: "subnet-xxxxx"
}
}环境变量:
创建/更新时通过设置:
func.envVariablesjavascript
{
envVariables: {
"DATABASE_URL": "mysql://...",
"API_KEY": "secret-key"
}
}⚠️ 重要提示:环境变量更新约束
更新现有函数的环境变量时:
- 必须首先使用并设置
getFunctionList查询当前环境变量,以获取函数的当前配置action=detail - 必须合并新环境变量与现有变量
- 请勿直接覆盖 - 这会删除更新中未包含的现有环境变量
正确的更新模式:
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个字段:秒 分 时 日 月 周 年)
- 示例:
- - 每月1日凌晨2:00
"0 0 2 1 * * *" - - 每天上午9:30
"0 30 9 * * * *"
VPC配置:
用于访问VPC资源:
javascript
{
vpc: {
vpcId: "vpc-xxxxx",
subnetId: "subnet-xxxxx"
}
}MCP Tools Reference
MCP工具参考
Function Management:
- - List functions or get function details
getFunctionList - - Create new cloud function
createFunction - - Update function code (runtime cannot change)
updateFunctionCode - - Update function configuration (⚠️ when updating envVariables, must first query and merge with existing values to avoid overwriting)
updateFunctionConfig
Logging:
- - Get function log list (basic info)
getFunctionLogs - - Get detailed log content by RequestId
getFunctionLogDetail - (Plan B) - Use
callCloudApiandGetFunctionLogsactions if direct tools unavailableGetFunctionLogDetail
HTTP Access:
- - Create HTTP access for function
createFunctionHTTPAccess - (Plan B) - Use
callCloudApiaction if direct tool unavailableCreateCloudBaseGWAPI
Triggers:
- - Create or delete function triggers
manageFunctionTriggers
函数管理:
- - 列出函数或获取函数详情
getFunctionList - - 创建新云函数
createFunction - - 更新函数代码(无法更改运行时)
updateFunctionCode - - 更新函数配置(⚠️ 更新envVariables时,必须先查询并与现有值合并,避免覆盖)
updateFunctionConfig
日志管理:
- - 获取函数日志列表(基础信息)
getFunctionLogs - - 通过RequestId获取详细日志内容
getFunctionLogDetail - (方案B):若直接工具不可用,使用
callCloudApi和GetFunctionLogs操作GetFunctionLogDetail
HTTP访问:
- - 为函数创建HTTP访问
createFunctionHTTPAccess - (方案B):若直接工具不可用,使用
callCloudApi操作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
最佳实践
- Runtime Selection: Always specify runtime explicitly, use for new projects
Nodejs18.15 - Code Organization: Keep functions focused and single-purpose
- Error Handling: Always implement proper error handling
- Environment Variables: Use env vars for configuration, never hardcode secrets
- Logging: Add meaningful logs for debugging
- Testing: Test functions locally when possible before deployment
- Security: Implement authentication/authorization for HTTP access
- Performance: Optimize cold start time, use connection pooling for databases
- Monitoring: Regularly check logs and monitor function performance
- Documentation: Document function parameters and return values
- 运行时选择:始终显式指定运行时,新项目使用
Nodejs18.15 - 代码组织:保持函数聚焦,单一职责
- 错误处理:始终实现完善的错误处理
- 环境变量:使用环境变量进行配置,绝不硬编码敏感信息
- 日志记录:添加有意义的日志以便调试
- 测试:尽可能在本地测试函数后再部署
- 安全:为HTTP访问实现认证/授权
- 性能:优化冷启动时间,为数据库使用连接池
- 监控:定期检查日志并监控函数性能
- 文档:记录函数参数与返回值
Related Skills
相关技能
- - For multi-language backend services
cloudrun-development - - For HTTP API invocation patterns
http-api - - For general CloudBase platform knowledge
cloudbase-platform
- - 用于多语言后端服务
cloudrun-development - - 用于HTTP API调用模式
http-api - - 用于通用CloudBase平台知识
cloudbase-platform