cloud-functions

GitHub 作者 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.

安装 / 下载方式

TotalClaw CLI推荐
totalclaw install github:LeoYeAI~openclaw-master-skills~cloud-functions
cURL直接下载,无需登录
curl -fsSL https://skills.taituai.com/api/skills/github%3ALeoYeAI~openclaw-master-skills~cloud-functions/file -o cloud-functions.md
# Cloud 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 `cloudrun-development` skill)
- Complex container-based services (use `cloudrun-development` skill)
- Database operations (use database skills)

## How to use this skill (for a coding agent)

1. **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

2. **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

3. **Deploy functions correctly**
   - **MCP Tool**: Use `createFunction` with `type: "Event"` or `type: "HTTP"`
   - **CLI**: Use `tcb fn deploy` (Event) or `tcb fn deploy --httpFn` (HTTP)
   - HTTP Functions require `scf_bootstrap` file in the function directory
   - 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)

---

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

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

### Event Function Structure

Event 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

### Event 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

---

## 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 `scf_bootstrap` startup script
- Supports multiple languages: Node.js, Python, Go, Java
- Supports HTTP, SSE, WebSocket protocols

### 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:**
```bash
# 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):**
```javascript
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:**
```javascript
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:**
```bash
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 `node_modules` or use layers

### Invoking HTTP Functions

**Method 1: HTTP API (with Access Token)**
```bash
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:

```javascript
createFunctionHTTPAccess({
  name: "myHttpFunction",
  type: "HTTP",           // "HTTP" for HTTP Function
  path: "/api/hello",     // Trigger path
  // domain: "your-domain.com"  // Optional custom domain
})
```

```bash
# 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-s