Cloud functions

From LeoYeAI/openclaw-master-skills · View interactive version

Cloud functions is an AI agent skill from the GitHub repository LeoYeAI/openclaw-master-skills. 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.

How to use this skill

Skill file

Cloud Functions Development

Use this skill when developing, deploying, and managing CloudBase cloud functions. CloudBase supports two types of cloud functions:

When to use this skill

Use this skill for cloud function operations when you need to:

Do NOT use for:

How to use this skill (for a coding agent)

  1. Choose the right function type
  1. Understand runtime limitations
  1. Deploy functions correctly
  1. Query logs properly

Function Types Comparison

| Feature | Event Function (普通云函数) | HTTP Function (HTTP 云函数) |

|---------|---------------------------|----------------------------|

| Trigger | Event-driven (SDK, timer) | HTTP request |

| Entry Point | exports.main = async (event, context) => {} | Web Server (Express/Flask/Gin etc.) |

| Port | No port required | Must listen on port 9000 |

| Bootstrap | Not required | Requires scf_bootstrap |

| 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:

  1. Delete the existing function
  2. Create a new function with the desired runtime

Supported Node.js Runtimes:

Runtime Selection Guidelines:

Event Function Structure

Event functions require:

  1. Function Directory: Contains function code
  1. Function Root Path: Parent directory containing function directories
  1. Entry Point: Default is index.js with exports.main

Event Function Deployment

Creating New Functions:

Use createFunction tool (see MCP tool documentation for full parameter list):

Updating Function Code:

Use updateFunctionCode tool:

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

Core Knowledge - HTTP Functions

HTTP Function Overview

HTTP Functions are optimized for Web service scenarios, supporting standard HTTP request/response patterns.

Key Characteristics:

scf_bootstrap Startup Script

⚠️ CRITICAL: HTTP Functions require scf_bootstrap file

| Requirement | Description |

|-------------|-------------|

| File name | Must be exactly scf_bootstrap (no extension) |

| Permission | Must have execute permission (chmod +x scf_bootstrap) |

| 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:

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 webfn=true parameter

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 (?webfn=true) | 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:

  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:

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

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:

HTTP Access Configuration (for Event Functions)

HTTP Access vs HTTP API:

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:

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:

  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:

// 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:

Timeout Configuration:

Set via func.timeout (in seconds):

Timer Triggers:

Configure via func.triggers:

VPC Configuration:

For accessing VPC resources:

{
  vpc: {
    vpcId: "vpc-xxxxx",
    subnetId: "subnet-xxxxx"
  }
}

MCP Tools Reference

Function Management:

Logging:

HTTP Access:

Triggers:

CLI Commands:

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

  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

HTTP Function Specific Best Practices

  1. Port Configuration: Always listen on port 9000
  2. scf_bootstrap: Ensure correct file permissions and LF line endings
  3. Health Check: Add /health endpoint for monitoring
  4. CORS: Configure CORS headers for browser access
  5. Graceful Shutdown: Handle process signals properly
  6. Dependencies: Include node_modules in package or use layers (no auto-install for HTTP Functions)
  7. Timeout: Set appropriate timeout for long-running SSE/WebSocket connections
  8. 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

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.