Skills cloud-functions
Complete guide for CloudBase cloud functions development - supports both Event Functions (Node.js) and HTTP Functions (multi-language Web services). Covers runtime selection, deployment, logging, invocation, scf_bootstrap, SSE, WebSocket, and HTTP access configuration.
git clone https://github.com/openclaw/skills
T=$(mktemp -d) && git clone --depth=1 https://github.com/openclaw/skills "$T" && mkdir -p ~/.claude/skills && cp -r "$T/skills/binggg/cloudbase/references/cloud-functions" ~/.claude/skills/openclaw-skills-cloud-functions && rm -rf "$T"
T=$(mktemp -d) && git clone --depth=1 https://github.com/openclaw/skills "$T" && mkdir -p ~/.openclaw/skills && cp -r "$T/skills/binggg/cloudbase/references/cloud-functions" ~/.openclaw/skills/openclaw-skills-cloud-functions && rm -rf "$T"
skills/binggg/cloudbase/references/cloud-functions/SKILL.mdCloud Functions Development
Use this skill when developing, deploying, and managing CloudBase cloud functions. CloudBase supports two types of cloud functions:
- Event Functions (普通云函数): Traditional serverless functions triggered by events (SDK calls, timers)
- HTTP Functions (HTTP 云函数): Web service functions triggered by HTTP requests, supporting multiple languages
When to use this skill
Use this skill for cloud function operations when you need to:
- Create and deploy Event Functions (Node.js)
- Create and deploy HTTP Functions (Node.js/Python/Go/Java)
- Understand runtime limitations and selection
- Query function logs and monitor execution
- Invoke cloud functions from applications
- Configure HTTP access for cloud functions
- Implement SSE (Server-Sent Events) or WebSocket
Do NOT use for:
- CloudRun backend services (use
skill)cloudrun-development - Complex container-based services (use
skill)cloudrun-development - Database operations (use database skills)
How to use this skill (for a coding agent)
-
Choose the right function type
- Event Function: For SDK calls, scheduled tasks, event-driven scenarios
- HTTP Function: For Web APIs, REST services, SSE/WebSocket, multi-language support
-
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
-
Deploy functions correctly
- MCP Tool: Use
withcreateFunction
ortype: "Event"type: "HTTP" - CLI: Use
(Event) ortcb fn deploy
(HTTP)tcb fn deploy --httpFn - HTTP Functions require
file in the function directoryscf_bootstrap - Provide correct
(parent directory of function folder)functionRootPath
- MCP Tool: Use
-
Query logs properly
- Use
for log list (basic info)getFunctionLogs - Use
with RequestId for detailed logsgetFunctionLogDetail - Note time range limitations (max 1 day interval)
- Use
Function Types Comparison
| Feature | Event Function (普通云函数) | HTTP Function (HTTP 云函数) |
|---|---|---|
| Trigger | Event-driven (SDK, timer) | HTTP request |
| Entry Point | | Web Server (Express/Flask/Gin etc.) |
| Port | No port required | Must listen on port 9000 |
| Bootstrap | Not required | Requires |
| Connection | Short connection | Supports long connection |
| Languages | Node.js only | Node.js, Python, Go, Java |
| Protocols | N/A | HTTP, SSE, WebSocket |
| Use Cases | Event processing, scheduled tasks | Web APIs, REST services, real-time streaming |
Core Knowledge - Event Functions
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.15Nodejs16.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
Event Function Structure
Event 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 dependenciespackage.json
- Must have
-
Function Root Path: Parent directory containing function directories
- Example: If function is at
/project/cloudfunctions/myFunction/
should befunctionRootPath/project/cloudfunctions/- Important: Do NOT include function name in root path
- Example: If function is at
-
Entry Point: Default is
withindex.jsexports.main- Can be customized via
parameterhandler
- Can be customized via
Event Function Deployment
Creating New Functions:
Use
createFunction tool (see MCP tool documentation for full parameter list):
- Important: Always specify
explicitly (defaults tofunc.runtime
)Nodejs18.15 - Provide
as parent directory of function folders (absolute path)functionRootPath - Use
to overwrite existing functionforce=true
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:
- 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
Core Knowledge - HTTP Functions
HTTP Function Overview
HTTP Functions are optimized for Web service scenarios, supporting standard HTTP request/response patterns.
Key Characteristics:
- Must listen on port 9000 (platform requirement)
- Requires
startup scriptscf_bootstrap - Supports multiple languages: Node.js, Python, Go, Java
- Supports HTTP, SSE, WebSocket protocols
scf_bootstrap Startup Script
⚠️ CRITICAL: HTTP Functions require
filescf_bootstrap
| Requirement | Description |
|---|---|
| File name | Must be exactly (no extension) |
| Permission | Must have execute permission () |
| Port | Must start server on port 9000 |
| Line endings | Must use LF (Unix), not CRLF (Windows) |
Examples:
# Node.js #!/bin/bash node index.js # Python #!/bin/bash export PYTHONPATH="./third_party:$PYTHONPATH" /var/lang/python310/bin/python3.10 app.py # Go #!/bin/bash ./main # Java #!/bin/bash java -jar *.jar
HTTP Function Structure & Example
my-http-function/ ├── scf_bootstrap # Required: startup script ├── package.json # Dependencies └── index.js # Application code
Node.js Example (Express):
const express = require('express'); const app = express(); app.get('/', (req, res) => res.json({ message: 'Hello!' })); app.listen(9000); // Must be port 9000
HTTP Function Deployment
MCP Tool:
createFunction({ func: { name: "myHttpFunction", type: "HTTP", // Required for HTTP Function protocolType: "HTTP", // "HTTP" (default) or "WS" (WebSocket) timeout: 60 }, functionRootPath: "/path/to/functions", force: false })
CLI:
tcb fn deploy <name> --httpFn # HTTP Function tcb fn deploy <name> --httpFn --ws # With WebSocket
⚠️ Notes:
- Function type cannot be changed after creation
- HTTP Functions do NOT auto-install dependencies; include
or use layersnode_modules
Invoking HTTP Functions
Method 1: HTTP API (with Access Token)
curl -L 'https://{envId}.api.tcloudbasegateway.com/v1/functions/{name}?webfn=true' \ -H 'Authorization: Bearer <TOKEN>'
⚠️ Must include
parameterwebfn=true
Method 2: HTTP Access Service (Custom Domain)
Use
createFunctionHTTPAccess MCP tool to configure HTTP access:
createFunctionHTTPAccess({ name: "myHttpFunction", type: "HTTP", // "HTTP" for HTTP Function path: "/api/hello", // Trigger path // domain: "your-domain.com" // Optional custom domain })
# Access via default domain curl https://{envId}.{region}.app.tcloudbase.com/{path} # Access via custom domain curl https://your-domain.com/{path}
| Method | Auth Required | Use Case |
|---|---|---|
HTTP API () | Yes (Bearer Token) | Server-to-server |
| HTTP Access Service | Optional | Browser, public APIs |
SSE & WebSocket Support
SSE (Server-Sent Events): Enabled by default, for server-to-client streaming (AI chat, progress updates).
// Server res.setHeader('Content-Type', 'text/event-stream'); res.write(`data: ${JSON.stringify({ content: 'Hello' })}\n\n`); // Client const es = new EventSource('https://your-domain/stream'); es.onmessage = (e) => console.log(JSON.parse(e.data));
WebSocket: Enable via
protocolType: "WS" in createFunction. For bidirectional real-time communication.
| Limit | Value |
|---|---|
| Idle timeout | 10 - 7200 seconds |
| Max message size | 256KB |
const wss = new WebSocket.Server({ port: 9000 }); wss.on('connection', (ws) => { ws.on('message', (msg) => ws.send(`Echo: ${msg}`)); });
Function Logs
Querying Logs:
Primary Method: Use
getFunctionLogs and getFunctionLogDetail tools (see MCP tool documentation).
Alternative 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 10000Offset + Limit
andStartTime
interval 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
Invoking Event Functions
From Web Applications:
import cloudbaseSDK from "@cloudbase/js-sdk"; const cloudbase = cloudbaseSDK.init({ env: 'your-env-id', region: 'ap-shanghai', accessKey: 'your-access-key' }); // Call event function const result = await cloudbase.callFunction({ name: "functionName", data: { /* function parameters */ } });
From Mini Programs:
wx.cloud.callFunction({ name: "functionName", data: { /* function parameters */ } }).then(res => { console.log(res.result); });
From Node.js Backend:
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 event functions:
- Endpoint:
https://{envId}.api.tcloudbasegateway.com/v1/functions/{functionName} - Requires authentication token (Bearer Token)
- See
skill for detailshttp-api
HTTP Access Configuration (for Event Functions)
HTTP Access vs HTTP API:
- HTTP API: Uses CloudBase API endpoint with authentication token
- HTTP Access: Creates direct HTTP/HTTPS endpoint for standard REST API access without SDK
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:
- Cloud Function type (required)Type: 6
- No auth (1 = with auth)AuthSwitch: 2
- Default domain, or specify custom domainDomain: "*"
Access URL:
https://{envId}.{region}.app.tcloudbase.com/{path} or https://{domain}/{path}
Function Configuration
Environment Variables:
Set via
func.envVariables when creating/updating:
{ 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
withgetFunctionList
to 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:
// 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:
(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:
{ vpc: { vpcId: "vpc-xxxxx", subnetId: "subnet-xxxxx" } }
MCP Tools Reference
Function Management:
- List functions or get function detailsgetFunctionList
- Create cloud function (supports both Event and HTTP types viacreateFunction
parameter)type
- Event Function (default)type: "Event"
- HTTP Functiontype: "HTTP"
- Enable WebSocket for HTTP FunctionprotocolType: "WS"
- 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 RequestIdgetFunctionLogDetail
(Plan B) - UsecallCloudApi
andGetFunctionLogs
actions if direct tools unavailableGetFunctionLogDetail
HTTP Access:
- Create HTTP access for function (supports both Event and HTTP types viacreateFunctionHTTPAccess
parameter)type
(Plan B) - UsecallCloudApi
action if direct tool unavailableCreateCloudBaseGWAPI
Triggers:
- Create or delete function triggersmanageFunctionTriggers
CLI Commands:
- Deploy Event Functiontcb fn deploy <name>
- Deploy HTTP Functiontcb fn deploy <name> --httpFn
- Deploy HTTP Function with WebSockettcb fn deploy <name> --httpFn --ws
- Deploy all functions in configtcb fn deploy --all
Common Patterns
Error Handling
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
exports.main = async (event, context) => { const apiKey = process.env.API_KEY; const dbUrl = process.env.DATABASE_URL; // Use environment variables };
Database Operations
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
General Best Practices
- Runtime Selection: Always specify runtime explicitly, use
for new projectsNodejs18.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
HTTP Function Specific Best Practices
- Port Configuration: Always listen on port 9000
- scf_bootstrap: Ensure correct file permissions and LF line endings
- Health Check: Add
endpoint for monitoring/health - CORS: Configure CORS headers for browser access
- Graceful Shutdown: Handle process signals properly
- Dependencies: Include
in package or use layers (no auto-install for HTTP Functions)node_modules - Timeout: Set appropriate timeout for long-running SSE/WebSocket connections
- Error Responses: Return proper HTTP status codes and error messages
Choosing Between Event and HTTP Functions
| Scenario | Recommended Type |
|---|---|
| SDK/Mini Program calls | Event Function |
| Scheduled tasks (cron) | Event Function |
| REST API / Web services | HTTP Function |
| SSE streaming (AI chat) | HTTP Function |
| WebSocket real-time | HTTP Function |
| File upload/download | HTTP Function |
| Multi-language support | HTTP Function |
Related Skills
- For container-based backend servicescloudrun-development
- For HTTP API invocation patternshttp-api
- For general CloudBase platform knowledgecloudbase-platform