Cloud Functions Development
Use this skill when developing, deploying, and managing CloudBase cloud functions (Node.js serverless functions).
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)
- Multi-language backend services (use skill)
- Database operations (use database skills)
How to use this skill (for a coding 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)
- Consider Node.js version compatibility with dependencies
-
Deploy functions correctly
- Use for new functions
- Use for code updates (runtime cannot be changed)
- Provide correct (parent directory of function folder)
-
Query logs properly
- Use for log list (basic info)
- Use with RequestId for detailed logs
- Note time range limitations (max 1 day interval)
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:
Runtime Selection Guidelines:
- Use 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
Function Structure
Cloud functions require:
-
Function Directory: Contains function code
- Must have (or specified entry file)
- Must export handler:
exports.main = async (event, context) => {}
- Include with dependencies
-
Function Root Path: Parent directory containing function directories
- Example: If function is at
/project/cloudfunctions/myFunction/
- should be
- Important: Do NOT include function name in root path
-
Entry Point: Default is
with
- Can be customized via parameter
Function Deployment
Creating New Functions:
Use
tool (see MCP tool documentation for full parameter list):
- Important: Always specify explicitly (defaults to )
- Provide as parent directory of function folders (absolute path)
- Use to overwrite existing function
Updating Function Code:
- ⚠️ 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
- Don't upload node_modules - dependencies installed automatically
- Test locally before deployment when possible
- Use environment variables for configuration, not hardcoded values
Function Logs
Querying Logs:
Primary Method: Use
and
tools (see MCP tool documentation).
Alternative Method (Plan B): If tools unavailable, use
:
- Get Log List - Use 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"
}
})
- Get Log Details - Use 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:
- cannot exceed 10000
- and interval cannot exceed 1 day
- 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
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 Access Configuration
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
tool (see MCP tool documentation).
Alternative Method (Plan B): If tool unavailable, use
with
:
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:
- - Cloud Function type (required)
- - No auth (1 = with auth)
- - Default domain, or specify custom domain
Access URL: https://{envId}.{region}.app.tcloudbase.com/{path}
or
Function Configuration
Environment Variables:
Set via
when creating/updating:
javascript
{
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 to get the function's current configuration
- 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:
- Default timeout varies by runtime
- Maximum timeout depends on runtime version
- Consider function execution time when setting
Timer Triggers:
- Type: (only supported type)
- Config: Cron expression (7 fields: second minute hour day month week year)
- Examples:
- - 2:00 AM on 1st of every month
- - 9:30 AM every day
VPC Configuration:
For accessing VPC resources:
javascript
{
vpc: {
vpcId: "vpc-xxxxx",
subnetId: "subnet-xxxxx"
}
}
MCP Tools Reference
Function Management:
- - List functions or get function details
- - Create new cloud function
- - Update function code (runtime cannot change)
- - Update function configuration (⚠️ when updating envVariables, must first query and merge with existing values to avoid overwriting)
Logging:
- - Get function log list (basic info)
- - Get detailed log content by RequestId
- (Plan B) - Use and actions if direct tools unavailable
HTTP Access:
- - Create HTTP access for function
- (Plan B) - Use action if direct tool unavailable
Triggers:
- - Create or delete function triggers
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
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
};
}
};
Environment Variable Usage
javascript
exports.main = async (event, context) => {
const apiKey = process.env.API_KEY;
const dbUrl = process.env.DATABASE_URL;
// Use environment variables
};
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;
};
Best Practices
- Runtime Selection: Always specify runtime explicitly, use for new projects
- 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
Related Skills
- - For multi-language backend services
- - For HTTP API invocation patterns
- - For general CloudBase platform knowledge