cloud-functions by tencentcloudbase/skills
npx skills add https://github.com/tencentcloudbase/skills --skill cloud-functionsscf_bootstrap、函数日志或函数部署。../auth-tool/SKILL.md../ai-model-nodejs/SKILL.mdexports.main(event, context)) 与 HTTP 函数代码结构 (在端口 9000 上使用 req / res) 混淆。广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
node_modules。app.use(express.json()) 或等效的请求体解析中间件。在开发、部署和管理 CloudBase 云函数时使用此技能。CloudBase 支持两种类型的云函数:
exports.main = async (event, context) => {} 的事件函数。9000 并处理 req / res 的HTTP 函数。当您需要进行云函数操作时,请使用此技能:
请勿用于:
cloudrun-development 技能)cloudrun-development 技能)选择正确的函数类型
了解运行时限制
编写代码并部署——不要只写文件就停止
manageFunctions 进行部署。仅在本地创建文件而不部署是不完整的。manageFunctions(action="createFunction") 一步完成创建和部署functionRootPath 作为函数文件夹的父目录(例如,/project/cloudfunctions/ 而不是 /project/cloudfunctions/myFunction/)queryFunctions 进行读取,manageFunctions(action="createFunction") 进行创建,manageFunctions(action="updateFunctionCode") 进行代码更新createFunction / updateFunctionCode,请将它们映射到上述 manageFunctions 操作tcb fn deploy(事件函数)或 tcb fn deploy --httpFn(HTTP 函数)作为备用方案manageFunctionsmanageFunctions 并设置 func.type="HTTP" 作为主要路径来创建或更新它们scf_bootstrap 文件functionRootPath(函数文件夹的父目录)正确查询日志
queryFunctions(action="listFunctionLogs") 获取日志列表(基本信息)queryFunctions(action="getFunctionLogDetail") 并附带 RequestId 获取详细日志getFunctionLogs / getFunctionLogDetail 视为上述两个 queryFunctions 操作安全处理旧工具名称
queryFunctions、manageFunctions、queryGateway、manageGatewaygetFunctionList -> queryFunctionscreateFunction -> manageFunctions(action="createFunction")updateFunctionCode -> manageFunctions(action="updateFunctionCode")| 特性 | 事件函数(普通云函数) | HTTP 函数(HTTP 云函数) |
|---|---|---|
| 触发方式 | 事件驱动(SDK、定时器) | HTTP 请求 |
| 入口点 | exports.main = async (event, context) => {} | Web 服务器(Express/Flask/Gin 等) |
| 端口 | 无需端口 | 必须监听端口 9000 |
| 启动脚本 | 不需要 | 需要 scf_bootstrap |
| 连接方式 | 短连接 | 支持长连接 |
| 支持语言 | 仅 Node.js | Node.js、Python、Go、Java |
| 支持协议 | 不适用 | HTTP、SSE、WebSocket |
| 使用场景 | 事件处理、定时任务 | Web API、REST 服务、实时流 |
⚠️ 关键:函数创建后运行时无法修改
一旦云函数以特定运行时创建,运行时无法更改。如果需要不同的运行时:
支持的 Node.js 运行时:
Nodejs18.15(默认,推荐)Nodejs16.13Nodejs14.18Nodejs12.16Nodejs10.15Nodejs8.9运行时选择指南:
Nodejs18.15(默认,最现代)事件函数需要:
函数目录:包含函数代码
index.js(或指定的入口文件)exports.main = async (event, context) => {}package.json函数根路径:包含函数目录的父目录
/project/cloudfunctions/myFunction/functionRootPath 应为 /project/cloudfunctions/入口点:默认为 index.js 和 exports.main
handler 参数自定义创建新函数:
使用 manageFunctions(action="createFunction")(完整参数列表请参阅 MCP 工具文档):
func.runtime(默认为 Nodejs18.15)functionRootPath 作为函数文件夹的父目录(绝对路径)force=true 覆盖现有函数createFunction,请保持相同的负载,但通过 manageFunctions 发送更新函数代码:
使用 manageFunctions(action="updateFunctionCode"):
updateFunctionCode,请将其映射到此 manageFunctions 操作部署最佳实践:
functionRootPathHTTP 函数针对 Web 服务场景进行了优化,支持标准的 HTTP 请求/响应模式。
HTTP 函数编码模型
req / res 的 Web 服务器风格处理程序exports.main(event, context) 作为主要的 HTTP 函数结构关键特性:
scf_bootstrap 启动脚本⚠️ 关键:HTTP 函数需要 scf_bootstrap 文件
| 要求 | 描述 |
|---|---|
| 文件名 | 必须恰好是 scf_bootstrap(无扩展名) |
| 权限 | 必须具有执行权限(chmod +x scf_bootstrap) |
| 端口 | 必须在端口 9000 上启动服务器 |
| 行尾符 | 必须使用 LF(Unix),而不是 CRLF(Windows) |
示例:
# 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 函数是标准的 Web 服务器。 它们接收完整的 HTTP 请求(方法、请求头、查询字符串、请求体),并且必须返回完整的 HTTP 响应(状态码、响应头、响应体)。与事件函数不同,没有 CloudBase 特定的请求封装。
依赖项:
node_modules 或使用层。express、body-parser(Express 4.16+ 内置)、cors、helmet处理不同的 HTTP 方法:
const express = require('express');
const app = express();
// 重要:必须为 POST/PUT 请求解析 JSON 请求体
app.use(express.json());
// GET - 从 req.query 读取查询参数
app.get('/users', (req, res) => {
const { userId, page = 1, pageSize = 10 } = req.query;
if (!userId) {
return res.status(400).json({ error: 'userId is required' });
}
res.json({
method: 'GET',
params: { userId, page: Number(page), pageSize: Number(pageSize) },
message: 'Query parameters processed'
});
});
// POST - 从 req.body 读取请求体,从 req.query 读取查询参数
app.post('/users', (req, res) => {
const { action } = req.query; // 查询字符串:?action=create
const { name, email } = req.body; // JSON 请求体
if (!name || !email) {
return res.status(400).json({ error: 'name and email are required' });
}
res.json({
method: 'POST',
action,
data: { name, email },
message: 'Body and query parameters processed'
});
});
// PUT - 从 req.headers 读取自定义请求头
app.put('/users/:id', (req, res) => {
const userId = req.headers['x-user-id']; // 自定义请求头
if (!userId) {
return res.status(401).json({ error: 'x-user-id header is required' });
}
const { status } = req.body;
res.json({
method: 'PUT',
userId,
status,
message: 'Headers and body processed'
});
});
// 对于不支持的方法,返回 405
app.all('*', (req, res) => {
res.status(405).json({ error: 'Method Not Allowed' });
});
app.listen(9000); // 必须是端口 9000
关键规则:
req.query - URL 查询字符串参数(例如,?userId=123&page=1)req.body - 解析后的请求体(需要 app.use(express.json()) 或等效的中间件)req.headers - 所有 HTTP 请求头(小写,例如,req.headers['x-user-id'])req.params - URL 路径参数(例如,/users/:id)res.json()、res.send() 或 res.status().json() 来发送响应my-http-function/
├── scf_bootstrap # 必需:启动脚本
├── package.json # 依赖项
├── node_modules/ # HTTP 函数必需(不会自动安装)
└── index.js # 应用程序代码
最小 Node.js 示例(Express):
const express = require('express');
const app = express();
app.use(express.json());
app.get('/', (req, res) => res.json({ message: 'Hello!' }));
app.listen(9000); // 必须是端口 9000
MCP 工具:
manageFunctions({
action: "createFunction",
func: {
name: "myHttpFunction",
type: "HTTP", // HTTP 函数必需
protocolType: "HTTP", // "HTTP"(默认)或 "WS"(WebSocket)
timeout: 60
},
functionRootPath: "/path/to/functions",
force: false
})
CLI:
tcb fn deploy <name> --httpFn # HTTP 函数
tcb fn deploy <name> --httpFn --ws # 带 WebSocket
⚠️ 注意事项:
node_modules 或使用层方法 1:HTTP API(带访问令牌)
curl -L 'https://{envId}.api.tcloudbasegateway.com/v1/functions/{name}?webfn=true' \
-H 'Authorization: Bearer <TOKEN>'
⚠️ 必须包含 webfn=true 参数
方法 2:HTTP 访问服务(自定义域名)
使用 manageGateway(action="createAccess") 配置 HTTP 访问:
manageGateway({
action: "createAccess",
targetType: "function",
targetName: "myHttpFunction",
type: "HTTP", // HTTP 函数使用 "HTTP"
path: "/api/hello", // 触发路径
// auth: false // 可选:仅在您确实需要匿名/公共访问时才设置此项
})
注意事项:
manageFunctions(action="createFunction") 只创建 HTTP 云函数本身,不会默认替你创建 HTTP 访问路径。manageGateway(action="createAccess")。EXCEED_AUTHORITY 再反馈给 AI。只要场景涉及匿名 URL 访问,就要主动确认两件事:访问路径是否已创建,以及函数安全规则是否允许该访问方式。EXCEED_AUTHORITY,先调用 readSecurityRule(resourceType="function") 查看当前规则,再根据实际需求决定是否用 writeSecurityRule(resourceType="function", aclTag="CUSTOM", rule="true") 或更细粒度规则放开权限。# 通过默认域名访问
curl https://{envId}.{region}.app.tcloudbase.com/{path}
# 通过自定义域名访问
curl https://your-domain.com/{path}
| 方法 | 需要认证 | 使用场景 |
|---|---|---|
HTTP API (?webfn=true) | 是(Bearer Token) | 服务器到服务器 |
| HTTP 访问服务 | 可选 | 浏览器、公共 API |
SSE(服务器发送事件): 默认启用,用于服务器到客户端的流式传输(AI 聊天、进度更新)。
// 服务器
res.setHeader('Content-Type', 'text/event-stream');
res.write(`data: ${JSON.stringify({ content: 'Hello' })}\n\n`);
// 客户端
const es = new EventSource('https://your-domain/stream');
es.onmessage = (e) => console.log(JSON.parse(e.data));
WebSocket: 通过在 manageFunctions(action="createFunction") 中设置 protocolType: "WS" 来启用。用于双向实时通信。
| 限制 | 值 |
|---|---|
| 空闲超时 | 10 - 7200 秒 |
| 最大消息大小 | 256KB |
const wss = new WebSocket.Server({ port: 9000 });
wss.on('connection', (ws) => {
ws.on('message', (msg) => ws.send(`Echo: ${msg}`));
});
查询日志:
主要方法: 使用 queryFunctions(action="listFunctionLogs") 和 queryFunctions(action="getFunctionLogDetail")(请参阅 MCP 工具文档)。
备用方法(方案 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"
}
})
GetFunctionLogDetail 操作(需要步骤 1 中的 LogRequestId):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"
}
})
日志查询限制:
Offset + Limit 不能超过 10000StartTime 和 EndTime 的间隔不能超过 1 天日志查询最佳实践:
从 Web 应用程序:
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: { /* function parameters */ }
});
从小程序:
wx.cloud.callFunction({
name: "functionName",
data: { /* function parameters */ }
}).then(res => {
console.log(res.result);
});
从 Node.js 后端:
const cloudbase = require("@cloudbase/node-sdk");
const app = cloudbase.init({
env: "your-env-id"
});
const result = await app.callFunction({
name: "functionName",
data: { /* function parameters */ }
});
从 HTTP API:
使用 CloudBase HTTP API 调用事件函数:
https://{envId}.api.tcloudbasegateway.com/v1/functions/{functionName}http-api 技能HTTP 访问服务 vs HTTP API:
创建 HTTP 访问服务:
主要方法: 使用 manageGateway(action="createAccess")(请参阅 MCP 工具文档)。
备用方法(方案 B): 如果工具不可用,请使用 callCloudApi 和 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: "*" // 使用 "*" 表示默认域名,或自定义域名
}
})
关键参数:
Type: 6 - 云函数类型(必需)AuthSwitch: 2 - 无认证(1 = 需要认证)Domain: "*" - 默认域名,或指定自定义域名访问 URL: https://{envId}.{region}.app.tcloudbase.com/{path} 或 https://{domain}/{path}
环境变量:
在创建/更新时通过 func.envVariables 设置:
{
envVariables: {
"DATABASE_URL": "mysql://...",
"API_KEY": "secret-key"
}
}
⚠️ 关键:环境变量更新约束
更新现有函数的环境变量时:
queryFunctions(action="getFunctionDetail") 获取函数的当前配置正确的更新模式:
// 1. 首先,获取当前函数详情
const currentFunction = await queryFunctions({
action: "getFunctionDetail",
functionName: "functionName"
});
// 2. 合并现有 envVariables 与新变量
const mergedEnvVariables = {
...currentFunction.EnvVariables, // 现有变量
...newEnvVariables // 新/更新的变量
};
// 3. 使用合并后的变量进行更新
await manageFunctions({
action: "updateFunctionConfig",
functionName: "functionName",
envVariables: mergedEnvVariables
});
为什么这很重要:
超时配置:
通过 func.timeout 设置(以秒为单位):
定时器触发器:
通过 func.triggers 配置:
timer(唯一支持的类型)"0 0 2 1 * * *" - 每月 1 日凌晨 2:00"0 30 9 * * * *" - 每天上午 9:30VPC 配置:
用于访问 VPC 资源:
{
vpc: {
vpcId: "vpc-xxxxx",
subnetId: "subnet-xxxxx"
}
}
函数管理:
queryFunctions(action="listFunctions"|"getFunctionDetail") - 函数清单和详情的首选读取入口manageFunctions(action="createFunction") - 创建云函数(通过 func.type 支持事件和 HTTP 两种类型)
func.type: "Event" - 事件函数(默认)func.type: "HTTP" - HTTP 函数func.protocolType: "WS" - 为 HTTP 函数启用 WebSocketmanageFunctions(action="updateFunctionCode") - 更新函数代码(运行时无法更改)manageFunctions(action="updateFunctionConfig") - 更新函数配置(⚠️ 更新 envVariables 时,必须首先查询并与现有值合并,以避免覆盖)getFunctionList、createFunction、updateFunctionCode、updateFunctionConfig日志记录:
queryFunctions(action="listFunctionLogs") - 获取函数日志列表(基本信息)queryFunctions(action="getFunctionLogDetail") - 通过 RequestId 获取详细日志内容callCloudApi(方案 B)- 如果直接工具不可用,请使用 GetFunctionLogs 和 GetFunctionLogDetail 操作getFunctionLogs、getFunctionLogDetailHTTP 访问服务:
queryGateway(action="getAccess") - 查询当前函数网关暴露情况manageGateway(action="createAccess") - 为函数创建 HTTP 访问服务callCloudApi(方案 B)- 如果直接工具不可用,请使用 CreateCloudBaseGWAPI 操作createFunctionHTTPAccess触发器:
queryFunctions(action="listFunctionTriggers") - 检查触发器manageFunctions(action="createFunctionTrigger"|"deleteFunctionTrigger") - 创建或删除函数触发器manageFunctionTriggersCLI 命令:
tcb fn deploy <name> - 部署事件函数tcb fn deploy <name> --httpFn - 部署 HTTP 函数tcb fn deploy <name> --httpFn --ws - 部署带 WebSocket 的 HTTP 函数tcb fn deploy --all - 部署配置中的所有函数exports.main = async (event, context) => {
try {
// 函数逻辑
return {
code: 0,
message: "Success",
data: result
};
} catch (error) {
return {
code: -1,
message: error.message,
data: null
};
}
};
exports.main = async (event, context) => {
const apiKey = process.env.API_KEY;
const dbUrl = process.env.DATABASE_URL;
// 使用环境变量
};
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;
};
Nodejs18.15/health 端点node_modules 或使用层(HTTP 函数不会自动安装)| 场景 | 推荐类型 |
|---|---|
| SDK/小程序调用 | 事件函数 |
| 定时任务(cron) | 事件函数 |
| REST API / Web 服务 | HTTP 函数 |
| SSE 流式传输(AI 聊天) | HTTP 函数 |
| WebSocket 实时通信 | HTTP 函数 |
| 文件上传/下载 | HTTP 函数 |
| 多语言支持 | HTTP 函数 |
cloudrun-development - 用于基于容器的后端服务http-api - 用于 HTTP API 调用模式cloudbase-platform - 用于通用 CloudBase 平台知识每周安装次数
609
代码仓库
GitHub 星标数
39
首次出现时间
2026 年 1 月 22 日
安全审计
安装于
codex536
opencode532
gemini-cli523
github-copilot509
kimi-cli499
amp496
scf_bootstrap, function logs, or function deployment.../auth-tool/SKILL.md../ai-model-nodejs/SKILL.mdexports.main(event, context)) with HTTP Function code shape (req / res on port 9000).node_modules.app.use(express.json()) or equivalent body parsing middleware for POST/PUT requests.Use this skill when developing, deploying, and managing CloudBase cloud functions. CloudBase supports two types of cloud functions:
exports.main = async (event, context) => {}.9000 and handles req / res.Use this skill for cloud function operations when you need to:
Do NOT use for:
cloudrun-development skill)cloudrun-development skill)Choose the right function type
Understand runtime limitations
Write code AND deploy — do not stop after writing files
manageFunctions. Creating files locally without deploying is incomplete.manageFunctions(action="createFunction") to create AND deploy in one stepfunctionRootPath as the parent directory of the function folder (e.g., /project/cloudfunctions/ not )| 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 |
⚠️ 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:
Supported Node.js Runtimes:
Nodejs18.15 (Default, Recommended)Nodejs16.13Nodejs14.18Nodejs12.16Nodejs10.15Nodejs8.9Runtime Selection Guidelines:
Nodejs18.15 for new projects (default, most modern)Event functions require:
Function Directory : Contains function code
index.js (or specified entry file)exports.main = async (event, context) => {}package.json with dependenciesFunction Root Path : Parent directory containing function directories
/project/cloudfunctions/myFunction/functionRootPath should be /project/cloudfunctions/Entry Point : Default is index.js with
Creating New Functions:
Use manageFunctions(action="createFunction") (see MCP tool documentation for full parameter list):
func.runtime explicitly (defaults to Nodejs18.15)functionRootPath as parent directory of function folders (absolute path)force=true to overwrite existing functioncreateFunction, keep the same payload but send it through manageFunctionsUpdating Function Code:
Use manageFunctions(action="updateFunctionCode"):
updateFunctionCode, map it to this manageFunctions actionDeployment Best Practices:
functionRootPathHTTP Functions are optimized for Web service scenarios, supporting standard HTTP request/response patterns.
HTTP Function coding model
req / resexports.main(event, context) as the primary HTTP Function shapeKey Characteristics:
scf_bootstrap startup script⚠️ CRITICAL: HTTP Functions requirescf_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
⚠️ CRITICAL: HTTP Functions are standard web servers. They receive full HTTP requests (method, headers, query string, body) and must return complete HTTP responses (status code, headers, body). Unlike Event Functions, there is no CloudBase-specific request envelope.
Dependencies:
node_modules in the function directory or use layers.express, body-parser (built into Express 4.16+), cors, helmetHandling Different HTTP Methods:
const express = require('express');
const app = express();
// IMPORTANT: Must parse JSON body for POST/PUT requests
app.use(express.json());
// GET - read query parameters from req.query
app.get('/users', (req, res) => {
const { userId, page = 1, pageSize = 10 } = req.query;
if (!userId) {
return res.status(400).json({ error: 'userId is required' });
}
res.json({
method: 'GET',
params: { userId, page: Number(page), pageSize: Number(pageSize) },
message: 'Query parameters processed'
});
});
// POST - read body from req.body, query from req.query
app.post('/users', (req, res) => {
const { action } = req.query; // query string: ?action=create
const { name, email } = req.body; // JSON body
if (!name || !email) {
return res.status(400).json({ error: 'name and email are required' });
}
res.json({
method: 'POST',
action,
data: { name, email },
message: 'Body and query parameters processed'
});
});
// PUT - read custom headers from req.headers
app.put('/users/:id', (req, res) => {
const userId = req.headers['x-user-id']; // custom header
if (!userId) {
return res.status(401).json({ error: 'x-user-id header is required' });
}
const { status } = req.body;
res.json({
method: 'PUT',
userId,
status,
message: 'Headers and body processed'
});
});
// For unsupported methods, return 405
app.all('*', (req, res) => {
res.status(405).json({ error: 'Method Not Allowed' });
});
app.listen(9000); // Must be port 9000
Key Rules:
req.query - URL query string parameters (e.g., ?userId=123&page=1)req.body - Parsed request body (requires app.use(express.json()) or equivalent middleware)req.headers - All HTTP headers (lowercased, e.g., req.headers['x-user-id'])req.params - URL path parameters (e.g., /users/:id)res.json(), res.send(), or to send a responsemy-http-function/
├── scf_bootstrap # Required: startup script
├── package.json # Dependencies
├── node_modules/ # Required for HTTP Functions (no auto-install)
└── index.js # Application code
Minimal Node.js Example (Express):
const express = require('express');
const app = express();
app.use(express.json());
app.get('/', (req, res) => res.json({ message: 'Hello!' }));
app.listen(9000); // Must be port 9000
MCP Tool:
manageFunctions({
action: "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:
node_modules or use layersMethod 1: HTTP API (with Access Token)
curl -L 'https://{envId}.api.tcloudbasegateway.com/v1/functions/{name}?webfn=true' \
-H 'Authorization: Bearer <TOKEN>'
⚠️ Must includewebfn=true parameter
Method 2: HTTP Access Service (Custom Domain)
Use manageGateway(action="createAccess") to configure HTTP access:
manageGateway({
action: "createAccess",
targetType: "function",
targetName: "myHttpFunction",
type: "HTTP", // "HTTP" for HTTP Function
path: "/api/hello", // Trigger path
// auth: false // Optional: only set this when you intentionally need anonymous/public access
})
Notes:
manageFunctions(action="createFunction") 只创建 HTTP 云函数本身,不会默认替你创建 HTTP 访问路径。
如果用户明确说“不需要配置 HTTP 访问服务”,不要额外调用 manageGateway(action="createAccess")。
评测、浏览器或其他外部调用方可能会以匿名身份访问,而且失败后不一定会把 EXCEED_AUTHORITY 再反馈给 AI。只要场景涉及匿名 URL 访问,就要主动确认两件事:访问路径是否已创建,以及函数安全规则是否允许该访问方式。
若外部请求已经报 EXCEED_AUTHORITY,先调用 readSecurityRule(resourceType="function") 查看当前规则,再根据实际需求决定是否用 writeSecurityRule(resourceType="function", aclTag="CUSTOM", rule="true") 或更细粒度规则放开权限。
curl https://{envId}.{region}.app.tcloudbase.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 (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 manageFunctions(action="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}`));
});
Querying Logs:
Primary Method: Use queryFunctions(action="listFunctionLogs") and queryFunctions(action="getFunctionLogDetail") (see MCP tool documentation).
Alternative Method (Plan B): If tools unavailable, use callCloudApi:
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"
}
})
2. 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:
Offset + Limit cannot exceed 10000StartTime and EndTime interval cannot exceed 1 dayLog Query Best Practices:
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:
https://{envId}.api.tcloudbasegateway.com/v1/functions/{functionName}http-api skill for detailsHTTP Access vs HTTP API:
Creating HTTP Access:
Primary Method: Use manageGateway(action="createAccess") (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:
Type: 6 - Cloud Function type (required)AuthSwitch: 2 - No auth (1 = with auth)Domain: "*" - Default domain, or specify custom domainAccess URL: https://{envId}.{region}.app.tcloudbase.com/{path} or https://{domain}/{path}
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:
queryFunctions(action="getFunctionDetail") to get the function's current configurationCorrect Update Pattern:
// 1. First, get current function details
const currentFunction = await queryFunctions({
action: "getFunctionDetail",
functionName: "functionName"
});
// 2. Merge existing envVariables with new ones
const mergedEnvVariables = {
...currentFunction.EnvVariables, // Existing variables
...newEnvVariables // New/updated variables
};
// 3. Update with merged variables
await manageFunctions({
action: "updateFunctionConfig",
functionName: "functionName",
envVariables: mergedEnvVariables
});
Why This Matters:
Timeout Configuration:
Set via func.timeout (in seconds):
Timer Triggers:
Configure via func.triggers:
timer (only supported type)"0 0 2 1 * * *" - 2:00 AM on 1st of every month"0 30 9 * * * *" - 9:30 AM every dayVPC Configuration:
For accessing VPC resources:
{
vpc: {
vpcId: "vpc-xxxxx",
subnetId: "subnet-xxxxx"
}
}
Function Management:
queryFunctions(action="listFunctions"|"getFunctionDetail") - Preferred read entrance for function inventory and detailmanageFunctions(action="createFunction") - Create cloud function (supports both Event and HTTP types via func.type)
func.type: "Event" - Event Function (default)func.type: "HTTP" - HTTP Functionfunc.protocolType: "WS" - Enable WebSocket for HTTP FunctionmanageFunctions(action="updateFunctionCode") - Update function code (runtime cannot change)manageFunctions(action="updateFunctionConfig") - Update function configuration (⚠️ when updating envVariables, must first query and merge with existing values to avoid overwriting)Logging:
queryFunctions(action="listFunctionLogs") - Get function log list (basic info)queryFunctions(action="getFunctionLogDetail") - Get detailed log content by RequestIdcallCloudApi (Plan B) - Use GetFunctionLogs and GetFunctionLogDetail actions if direct tools unavailablegetFunctionLogs, getFunctionLogDetailHTTP Access:
queryGateway(action="getAccess") - Query current function gateway exposuremanageGateway(action="createAccess") - Create HTTP access for functioncallCloudApi (Plan B) - Use CreateCloudBaseGWAPI action if direct tool unavailablecreateFunctionHTTPAccessTriggers:
queryFunctions(action="listFunctionTriggers") - Inspect triggersmanageFunctions(action="createFunctionTrigger"|"deleteFunctionTrigger") - Create or delete function triggersmanageFunctionTriggersCLI Commands:
tcb fn deploy <name> - Deploy Event Functiontcb fn deploy <name> --httpFn - Deploy HTTP Functiontcb fn deploy <name> --httpFn --ws - Deploy HTTP Function with WebSockettcb fn deploy --all - Deploy all functions in configexports.main = async (event, context) => {
try {
// Function logic
return {
code: 0,
message: "Success",
data: result
};
} catch (error) {
return {
code: -1,
message: error.message,
data: null
};
}
};
exports.main = async (event, context) => {
const apiKey = process.env.API_KEY;
const dbUrl = process.env.DATABASE_URL;
// Use environment variables
};
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;
};
Nodejs18.15 for new projects/health endpoint for monitoringnode_modules in package or use layers (no auto-install for 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 |
cloudrun-development - For container-based backend serviceshttp-api - For HTTP API invocation patternscloudbase-platform - For general CloudBase platform knowledgeWeekly Installs
609
Repository
GitHub Stars
39
First Seen
Jan 22, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykFail
Installed on
codex536
opencode532
gemini-cli523
github-copilot509
kimi-cli499
amp496
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
103,800 周安装
updateFunctionConfig -> manageFunctions(action="updateFunctionConfig")getFunctionLogs -> queryFunctions(action="listFunctionLogs")getFunctionLogDetail -> queryFunctions(action="getFunctionLogDetail")manageFunctionTriggers -> manageFunctions(action="createFunctionTrigger"|"deleteFunctionTrigger")readFunctionLayers -> queryFunctions(action="listLayers"|"listLayerVersions"|"getLayerVersionDetail"|"listFunctionLayers")writeFunctionLayers -> manageFunctions(action="createLayerVersion"|"deleteLayerVersion"|"attachLayer"|"detachLayer"|"updateFunctionLayers")createFunctionHTTPAccess -> manageGateway(action="createAccess")/project/cloudfunctions/myFunction/queryFunctions for reads, manageFunctions(action="createFunction") for creation, and manageFunctions(action="updateFunctionCode") for code updatescreateFunction / updateFunctionCode, map them to the manageFunctions actions abovetcb fn deploy (Event) or tcb fn deploy --httpFn (HTTP) only as a fallback when MCP tools are unavailablemanageFunctionsmanageFunctions with func.type="HTTP" as the primary pathscf_bootstrap file in the function directoryfunctionRootPath (parent directory of function folder)Query logs properly
queryFunctions(action="listFunctionLogs") for log list (basic info)queryFunctions(action="getFunctionLogDetail") with RequestId for detailed logsgetFunctionLogs / getFunctionLogDetail as the two queryFunctions actions aboveHandle legacy tool names safely
queryFunctions, manageFunctions, queryGateway, manageGatewaygetFunctionList -> queryFunctionscreateFunction -> manageFunctions(action="createFunction")updateFunctionCode -> manageFunctions(action="updateFunctionCode")updateFunctionConfig -> manageFunctions(action="updateFunctionConfig")getFunctionLogs -> queryFunctions(action="listFunctionLogs")getFunctionLogDetail -> queryFunctions(action="getFunctionLogDetail")manageFunctionTriggers -> manageFunctions(action="createFunctionTrigger"|"deleteFunctionTrigger")readFunctionLayers -> queryFunctions(action="listLayers"|"listLayerVersions"|"getLayerVersionDetail"|"listFunctionLayers")writeFunctionLayers -> manageFunctions(action="createLayerVersion"|"deleteLayerVersion"|"attachLayer"|"detachLayer"|"updateFunctionLayers")createFunctionHTTPAccess -> manageGateway(action="createAccess")| Use Cases | Event processing, scheduled tasks | Web APIs, REST services, real-time streaming |
exports.mainhandler parameterres.status().json()getFunctionList, createFunction, updateFunctionCode, updateFunctionConfig