Standalone Install Note
If this environment only installed the current skill, start from the CloudBase main entry and use the published cloudbase/references/... paths for sibling skills.
- CloudBase main entry:
https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/SKILL.md
- Current skill raw source:
https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/cloud-functions/SKILL.md
Keep local references/... paths for files that ship with the current skill directory. When this file points to a sibling skill such as auth-tool or web-development, use the standalone fallback URL shown next to that reference.
Cross-cutting protocols (required for public exposure and code changes):
- Change Safety Protocol:
https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/cloudbase-platform/references/protocols/change-safety-protocol.md
- Deployment Gate:
https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/cloudbase-platform/references/protocols/deployment-gate.md
Cloud Functions Development
Activation Contract
Use this first when
- The task is to create, update, deploy, inspect, or debug a CloudBase Event Function or HTTP Function that serves application runtime logic.
- The request mentions function runtime, function logs,
scf_bootstrap, function triggers, or function gateway exposure.
Read before writing code if
- You still need to decide between Event Function and HTTP Function.
- The task mentions
manageFunctions, queryFunctions, manageGateway, or legacy function-tool names.
- The task might require
callCloudApi as a fallback for logs or gateway setup.
Then also read
- Detailed reference routing ->
./references.md
- Auth setup or provider-related backend work ->
../auth-tool/SKILL.md (standalone fallback: https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/auth-tool/SKILL.md)
- CloudBase Integration Center generated WeChat Pay or Official Account functions ->
../cloudbase-wechat-integration/SKILL.md (standalone fallback: https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/cloudbase-wechat-integration/SKILL.md; official docs: https://docs.cloudbase.net/integration/introduce/index.md)
- AI in functions ->
../ai-model-nodejs/SKILL.md (standalone fallback: https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/ai-model-nodejs/SKILL.md)
- Long-lived container services or Agent runtimes ->
../cloudrun-development/SKILL.md (standalone fallback: https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/cloudrun-development/SKILL.md)
- Calling CloudBase official platform APIs from a client or script ->
../http-api/SKILL.md (standalone fallback: https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/http-api/SKILL.md)
Do NOT use for
- CloudRun container services.
- Web authentication UI implementation.
- Database-schema design or general data-model work.
- CloudBase official platform API clients or raw HTTP integrations that only consume platform endpoints.
- Creating Integration Center instances through guessed APIs. For WeChat Pay or Official Account generated functions, use
cloudbase-wechat-integration for the business contract and this skill only for function operations.
- Tasks that the CloudBase JS SDK can handle directly — simple data reads/writes, leaderboards, file uploads, real-time queries. Reach for the matching SDK surface before writing a function:
db.collection(...).get/add/update only for confirmed NoSQL collections, and app.rdb().from(...) for CloudBase PG tables. Functions add deployment complexity, CORS configuration, and HTTP gateway binding that the SDK eliminates entirely.
Common mistakes / gotchas
- Picking the wrong function type and trying to compensate later.
- Confusing official CloudBase API client work with building your own HTTP function.
- Mixing Event Function code shape (
exports.main(event, context)) with HTTP Function code shape (req / res on port 9000).
- Treating HTTP Access as the implementation model for HTTP Functions. HTTP Access is a gateway configuration for Event Functions, not the HTTP Function runtime model.
- Assuming
db.collection("name").add(...) will create a missing document-database collection automatically. Collection creation is a separate management step.
- Forgetting that runtime cannot be changed after creation.
- Using cloud functions as the first answer for Web login.
- Forgetting that HTTP Functions must ship
scf_bootstrap, listen on port 9000, and include dependencies.
- Forgetting to configure function security rules after creating an HTTP Function. Default rules reject anonymous callers with
EXCEED_AUTHORITY. Note: anonymous login is disabled by default for new environments — if the function needs public access without authentication, configure the security rule to allow all callers rather than relying on anonymous login.
- Mismatching the
scf_bootstrap Node.js binary path with the function runtime (e.g. using /var/lang/node18/bin/node but setting runtime: "Nodejs16.13").
- Making code or configuration changes without first following the Change Safety Protocol (
cloudbase-platform/references/protocols/change-safety-protocol.md).
- Exposing functions publicly or deploying without first completing the checks in
cloudbase-platform/references/protocols/deployment-gate.md.
Minimal checklist
- Read Cloud Functions Execution Checklist before deployment or runtime changes.
- Decide whether the task is Event Function, HTTP Function, or actually CloudRun.
- Pick the detailed reference file in references.md before writing implementation code.
Overview
Use this skill when developing, deploying, and operating CloudBase cloud functions. CloudBase has two different programming models:
- Event Functions: serverless handlers driven by SDK calls, timers, and other events.
- HTTP Functions: standard web services for HTTP endpoints, SSE, or WebSocket workloads.
Writing mode at a glance
- If the request is for SDK calls, timers, or event-driven workflows, write an Event Function with
exports.main = async (event, context) => {}.
- If the request is for REST APIs, browser-facing endpoints, SSE, or WebSocket, write an HTTP Function with
req / res on port 9000.
- For Node.js HTTP Functions, default to the native
http module unless the user explicitly asks for Express, Koa, NestJS, or another framework.
- If the user mentions HTTP access for an existing Event Function, keep the Event Function code shape and add gateway access separately.
HTTP Function authoring contract
Use these rules whenever you are writing the function code itself:
- Do not write an HTTP Function as
exports.main(event, context). That is the Event Function contract.
- Treat the function as a standard web server process that must listen on port
9000.
- With Node.js, prefer
http.createServer((req, res) => { ... }) by default so the runtime contract stays explicit.
- With the Node.js native
http module, do not assume Express-style helpers exist. req.body, req.query, and req.params are not provided for you.
- For Node.js HTTP Functions, choose one module system up front and keep it consistent. Default to CommonJS for simple functions (
require(...), no "type": "module" in package.json) unless you explicitly want ES Modules.
- If you do choose ES Modules (
"type": "module" + import ...), do not mix in CommonJS-only globals or APIs such as require(...), module.exports, or bare __dirname. In ESM, derive file paths from import.meta.url with fileURLToPath(...) only when needed.
- With the native
http module, parse req.url yourself with new URL(...), collect the request body from the stream, and only then call JSON.parse. Empty bodies should be handled explicitly instead of assuming JSON is always present.
- Return responses explicitly with
res.writeHead(...) and res.end(...), including Content-Type such as application/json; charset=utf-8 for JSON APIs.
- Handle CORS headers. Browsers block cross-origin requests without proper CORS headers. Default to allowing all origins for simple APIs:
- Respond to
OPTIONS preflight with 200 and CORS headers
- Include
Access-Control-Allow-Origin: * (or specific origin) on all responses
- Include
Access-Control-Allow-Methods: GET, POST, OPTIONS as needed
- Include
Access-Control-Allow-Headers: Content-Type for JSON requests
- Keep routing and method handling explicit. Unknown paths should return
404, and known paths with unsupported methods should normally return 405.
- Keep gateway setup and security-rule changes separate from the runtime code. They affect access, not the HTTP Function programming model.
- Do not add HTTP access service configuration when the task is only to create an HTTP Function itself. Gateway paths or custom domains are separate access-layer work; public invocation requirements should be handled through the function security rule workflow (note: anonymous login is disabled by default).
Quick decision table
| Question |
Choose |
| Triggered by SDK calls or timers? |
Event Function |
| Needs browser-facing HTTP endpoint? |
HTTP Function |
| Needs SSE or WebSocket service? |
HTTP Function |
| Needs long-lived container runtime or custom system environment? |
CloudRun |
| Only needs HTTP access for an existing Event Function? |
Event Function + gateway access |
How to use this skill (for a coding agent)
Choose the correct runtime model first
- Event Function ->
exports.main(event, context)
- HTTP Function -> web server on port
9000
- If the requirement is really a container service, reroute to CloudRun early
Use the converged MCP entrances
- Reads ->
queryFunctions, queryGateway
- Writes ->
manageFunctions, manageGateway
- Translate legacy names before acting rather than copying them literally
Write code and deploy, do not stop at local files
- Use
manageFunctions(action="createFunction") for creation
- Use
manageFunctions(action="updateFunctionCode") for code updates
- Use
manageFunctions(action="updateFunctionConfig") for config updates (timeout, memorySize, envVariables)
- Keep
functionRootPath as the directory that directly contains function folders (e.g., cloudfunctions/ or functions/), NOT the project root and NOT the function subdirectory itself
- Prefer MCP tools over CLI — when MCP tools are available, use
manageFunctions and queryFunctions instead of CLI commands
- Do NOT assume CLI is available from task wording alone — if the available capabilities only include MCP tools, use MCP tools exclusively
- For batch updates (multiple functions), call
manageFunctions(action="updateFunctionConfig") individually for each function — MCP does not have a --all batch parameter like CLI
Prefer doc-first fallbacks
- If a task falls back to
callCloudApi, first check the official docs or knowledge-base entry for that action
- Confirm the exact action name and parameter contract before calling it
- Do not guess raw cloud API payloads from memory
Read the right detailed reference
- Event Function details ->
./references/event-functions.md
- HTTP Function details ->
./references/http-functions.md
- Logs, gateway, env vars, and legacy mappings ->
./references/operations-and-config.md
Database write reminder
- If a function will write to CloudBase document database, create the target collection first through console or management tooling.
db.collection("feedback").add(...) only inserts into an existing collection; it does not auto-create feedback when absent.
- If the product requirement says "create when missing", implement that as an explicit collection-management step before the first write instead of assuming the runtime write call will provision it.
Function types comparison
| Feature |
Event Function |
HTTP Function |
| Primary trigger |
SDK call, timer, event |
HTTP request |
| Entry shape |
exports.main(event, context) |
web server with req / res |
| Port |
No port |
Must listen on 9000 |
scf_bootstrap |
Not required |
Required |
| Dependencies |
Auto-installed from package.json |
Must be packaged with function code |
| Best for |
serverless handlers, scheduled jobs |
APIs, SSE, WebSocket, browser-facing services |
Minimal code skeletons
Event Function hello world
cloudfunctions/hello-event/index.js
exports.main = async (event, context) => {
return {
ok: true,
message: "hello from event function",
event,
};
};
cloudfunctions/hello-event/package.json
{
"name": "hello-event",
"version": "1.0.0"
}
HTTP Function hello world
cloudfunctions/hello-http/index.js
const http = require("http");
const { URL } = require("url");
// CORS headers — default to * for simple cross-origin APIs
const CORS_HEADERS = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
};
function sendJson(res, statusCode, data) {
res.writeHead(statusCode, {
"Content-Type": "application/json; charset=utf-8",
...CORS_HEADERS,
});
res.end(JSON.stringify(data));
}
function sendOptions(res) {
res.writeHead(204, CORS_HEADERS);
res.end();
}
function readJsonBody(req) {
return new Promise((resolve, reject) => {
let raw = "";
req.on("data", (chunk) => { raw += chunk; });
req.on("end", () => {
if (!raw) { resolve({}); return; }
try { resolve(JSON.parse(raw)); } catch (e) { resolve({}); }
});
req.on("error", reject);
});
}
const server = http.createServer(async (req, res) => {
// Handle CORS preflight
if (req.method === "OPTIONS") {
return sendOptions(res);
}
const url = new URL(req.url || "/", "http://127.0.0.1");
if (req.method === "GET" && url.pathname === "/") {
sendJson(res, 200, { ok: true, message: "hello from http function" });
} else if (req.method === "POST" && url.pathname === "/") {
const body = await readJsonBody(req);
sendJson(res, 200, { received: body });
} else {
sendJson(res, 404, { error: "Not Found" });
}
});
server.listen(9000);
For a more complete example with routing, method checks, and error handling, see ./references/http-functions.md.
cloudfunctions/hello-http/scf_bootstrap
#!/bin/bash
/var/lang/node18/bin/node index.js
The scf_bootstrap binary path must match the runtime — see the full mapping table in ./references/http-functions.md.
cloudfunctions/hello-http/package.json
{
"name": "hello-http",
"version": "1.0.0"
}
Preferred tool map
Function management
queryFunctions(action="listFunctions"|"getFunctionDetail")
manageFunctions(action="createFunction")
manageFunctions(action="updateFunctionCode")
manageFunctions(action="updateFunctionConfig")
Logs
Query function logs — use the queryFunctions tool:
queryFunctions(action="listFunctionLogs", functionName="xxx") — list execution logs of a specific function
queryFunctions(action="getFunctionLogDetail", requestId="xxx") — fetch the detail of one log entry
queryFunctions vs queryLogs:
queryFunctions queries execution logs of a single cloud function and requires functionName
queryLogs searches CLS (cross-service log aggregation) using CLS query syntax
Examples:
// List recent logs for cloud function "my-function"
queryFunctions(action="listFunctionLogs", functionName="my-function", limit=10)
// Inspect the log detail for a specific request id
queryFunctions(action="getFunctionLogDetail", requestId="abc-123")
// Cross-service error search via CLS
queryLogs(action="searchLogs", queryString='(src:app OR src:system) AND log:"ERROR"', service="tcb")
queryLogs queryString follows CLS syntax (see https://cloud.tencent.com/document/api/876/128127). The examples below are starting points; adapt them to the concrete log content of your query:
- Function logs:
(src:app OR src:system) AND log:"START RequestId"
- Aggregated function request status:
| select request_id, max(status_code) as status where ((request_id='xxxx' AND retry_num=0) AND retry_num=0) AND status_code!=202 group by request_id, retry_num
- Document database (NoSQL):
module:database
- Document database slow-query events:
module:database AND eventType:(MongoSlowQuery) — MongoSlowQuery is the document-database slow-query event
- Relational database (MySQL):
module:rdb
- Relational database (MySQL) events:
module:rdb AND eventType:(MysqlFreeze OR MysqlRecover OR MysqlSlowQuery) — MysqlFreeze = freeze, MysqlRecover = recover, MysqlSlowQuery = slow query
- Workflow (approval flow):
module:workflow
- Data model:
module:model
- User permissions:
module:auth
- LLM trace logs:
module:llm AND logType:llm-tracelog
- Gateway access logs:
logType:accesslog
- App publish / delete events:
module:app AND eventType:(AppProdPub OR AppProdDel) — AppProdPub = app publish, AppProdDel = app delete
If these are unavailable, read ./references/operations-and-config.md before any callCloudApi fallback
Gateway exposure
queryGateway(action="getAccess")
manageGateway(action="createAccess")
- If gateway operations need raw cloud API fallback, read
./references/operations-and-config.md first
Related skills
cloudrun-development -> container services, long-lived runtimes, Agent hosting
http-api -> raw CloudBase HTTP API invocation patterns
cloudbase-platform -> general CloudBase platform decisions
ops-inspector -> AIOps-style inspection and log search across services
1---2name: cloud-functions3description: CloudBase function runtime guide for building, deploying, and debugging your own Event Functions or HTTP Functions. This skill should be used when users need application runtime code on CloudBase, not when they are merely calling CloudBase official platform APIs.4---56## Standalone Install Note78If this environment only installed the current skill, start from the CloudBase main entry and use the published `cloudbase/references/...` paths for sibling skills.910- CloudBase main entry: `https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/SKILL.md`11- Current skill raw source: `https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/cloud-functions/SKILL.md`1213Keep local `references/...` paths for files that ship with the current skill directory. When this file points to a sibling skill such as `auth-tool` or `web-development`, use the standalone fallback URL shown next to that reference.1415**Cross-cutting protocols** (required for public exposure and code changes):16- Change Safety Protocol: `https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/cloudbase-platform/references/protocols/change-safety-protocol.md`17- Deployment Gate: `https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/cloudbase-platform/references/protocols/deployment-gate.md`1819# Cloud Functions Development2021## Activation Contract2223### Use this first when2425- The task is to create, update, deploy, inspect, or debug a CloudBase Event Function or HTTP Function that serves application runtime logic.26- The request mentions function runtime, function logs, `scf_bootstrap`, function triggers, or function gateway exposure.2728### Read before writing code if2930- You still need to decide between Event Function and HTTP Function.31- The task mentions `manageFunctions`, `queryFunctions`, `manageGateway`, or legacy function-tool names.32- The task might require `callCloudApi` as a fallback for logs or gateway setup.3334### Then also read3536- Detailed reference routing -> `./references.md`37- Auth setup or provider-related backend work -> `../auth-tool/SKILL.md` (standalone fallback: `https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/auth-tool/SKILL.md`)38- CloudBase Integration Center generated WeChat Pay or Official Account functions -> `../cloudbase-wechat-integration/SKILL.md` (standalone fallback: `https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/cloudbase-wechat-integration/SKILL.md`; official docs: `https://docs.cloudbase.net/integration/introduce/index.md`)39- AI in functions -> `../ai-model-nodejs/SKILL.md` (standalone fallback: `https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/ai-model-nodejs/SKILL.md`)40- Long-lived container services or Agent runtimes -> `../cloudrun-development/SKILL.md` (standalone fallback: `https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/cloudrun-development/SKILL.md`)41- Calling CloudBase official platform APIs from a client or script -> `../http-api/SKILL.md` (standalone fallback: `https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/http-api/SKILL.md`)4243### Do NOT use for4445- CloudRun container services.46- Web authentication UI implementation.47- Database-schema design or general data-model work.48- CloudBase official platform API clients or raw HTTP integrations that only consume platform endpoints.49- Creating Integration Center instances through guessed APIs. For WeChat Pay or Official Account generated functions, use `cloudbase-wechat-integration` for the business contract and this skill only for function operations.50- **Tasks that the CloudBase JS SDK can handle directly** — simple data reads/writes, leaderboards, file uploads, real-time queries. Reach for the matching SDK surface before writing a function: `db.collection(...).get/add/update` only for confirmed NoSQL collections, and `app.rdb().from(...)` for CloudBase PG tables. Functions add deployment complexity, CORS configuration, and HTTP gateway binding that the SDK eliminates entirely.5152### Common mistakes / gotchas5354- Picking the wrong function type and trying to compensate later.55- Confusing official CloudBase API client work with building your own HTTP function.56- Mixing Event Function code shape (`exports.main(event, context)`) with HTTP Function code shape (`req` / `res` on port `9000`).57- Treating HTTP Access as the implementation model for HTTP Functions. HTTP Access is a gateway configuration for Event Functions, not the HTTP Function runtime model.58- Assuming `db.collection("name").add(...)` will create a missing document-database collection automatically. Collection creation is a separate management step.59- Forgetting that runtime cannot be changed after creation.60- Using cloud functions as the first answer for Web login.61- Forgetting that HTTP Functions must ship `scf_bootstrap`, listen on port `9000`, and include dependencies.62- Forgetting to configure function security rules after creating an HTTP Function. Default rules reject anonymous callers with `EXCEED_AUTHORITY`. Note: anonymous login is disabled by default for new environments — if the function needs public access without authentication, configure the security rule to allow all callers rather than relying on anonymous login.63- Mismatching the `scf_bootstrap` Node.js binary path with the function runtime (e.g. using `/var/lang/node18/bin/node` but setting `runtime: "Nodejs16.13"`).64- Making code or configuration changes without first following the Change Safety Protocol (`cloudbase-platform/references/protocols/change-safety-protocol.md`).65- Exposing functions publicly or deploying without first completing the checks in `cloudbase-platform/references/protocols/deployment-gate.md`.6667### Minimal checklist6869- Read [Cloud Functions Execution Checklist](checklist.md) before deployment or runtime changes.70- Decide whether the task is Event Function, HTTP Function, or actually CloudRun.71- Pick the detailed reference file in [references.md](references.md) before writing implementation code.7273## Overview7475Use this skill when developing, deploying, and operating CloudBase cloud functions. CloudBase has two different programming models:7677- **Event Functions**: serverless handlers driven by SDK calls, timers, and other events.78- **HTTP Functions**: standard web services for HTTP endpoints, SSE, or WebSocket workloads.7980## Writing mode at a glance8182- If the request is for SDK calls, timers, or event-driven workflows, write an **Event Function** with `exports.main = async (event, context) => {}`.83- If the request is for REST APIs, browser-facing endpoints, SSE, or WebSocket, write an **HTTP Function** with `req` / `res` on port `9000`.84- For Node.js HTTP Functions, default to the native `http` module unless the user explicitly asks for Express, Koa, NestJS, or another framework.85- If the user mentions HTTP access for an existing Event Function, keep the Event Function code shape and add gateway access separately.8687## HTTP Function authoring contract8889Use these rules whenever you are writing the function code itself:9091- Do not write an HTTP Function as `exports.main(event, context)`. That is the Event Function contract.92- Treat the function as a standard web server process that must listen on port `9000`.93- With Node.js, prefer `http.createServer((req, res) => { ... })` by default so the runtime contract stays explicit.94- With the Node.js native `http` module, do not assume Express-style helpers exist. `req.body`, `req.query`, and `req.params` are not provided for you.95- For Node.js HTTP Functions, choose one module system up front and keep it consistent. Default to CommonJS for simple functions (`require(...)`, no `"type": "module"` in `package.json`) unless you explicitly want ES Modules.96- If you do choose ES Modules (`"type": "module"` + `import ...`), do not mix in CommonJS-only globals or APIs such as `require(...)`, `module.exports`, or bare `__dirname`. In ESM, derive file paths from `import.meta.url` with `fileURLToPath(...)` only when needed.97- With the native `http` module, parse `req.url` yourself with `new URL(...)`, collect the request body from the stream, and only then call `JSON.parse`. Empty bodies should be handled explicitly instead of assuming JSON is always present.98- Return responses explicitly with `res.writeHead(...)` and `res.end(...)`, including `Content-Type` such as `application/json; charset=utf-8` for JSON APIs.99- **Handle CORS headers**. Browsers block cross-origin requests without proper CORS headers. Default to allowing all origins for simple APIs:100 - Respond to `OPTIONS` preflight with `200` and CORS headers101 - Include `Access-Control-Allow-Origin: *` (or specific origin) on all responses102 - Include `Access-Control-Allow-Methods: GET, POST, OPTIONS` as needed103 - Include `Access-Control-Allow-Headers: Content-Type` for JSON requests104- Keep routing and method handling explicit. Unknown paths should return `404`, and known paths with unsupported methods should normally return `405`.105- Keep gateway setup and security-rule changes separate from the runtime code. They affect access, not the HTTP Function programming model.106- Do not add HTTP access service configuration when the task is only to create an HTTP Function itself. Gateway paths or custom domains are separate access-layer work; public invocation requirements should be handled through the function security rule workflow (note: anonymous login is disabled by default).107108## Quick decision table109110| Question | Choose |111| --- | --- |112| Triggered by SDK calls or timers? | Event Function |113| Needs browser-facing HTTP endpoint? | HTTP Function |114| Needs SSE or WebSocket service? | HTTP Function |115| Needs long-lived container runtime or custom system environment? | CloudRun |116| Only needs HTTP access for an existing Event Function? | Event Function + gateway access |117118## How to use this skill (for a coding agent)1191201. **Choose the correct runtime model first**121 - Event Function -> `exports.main(event, context)`122 - HTTP Function -> web server on port `9000`123 - If the requirement is really a container service, reroute to CloudRun early1241252. **Use the converged MCP entrances**126 - Reads -> `queryFunctions`, `queryGateway`127 - Writes -> `manageFunctions`, `manageGateway`128 - Translate legacy names before acting rather than copying them literally1291303. **Write code and deploy, do not stop at local files**131 - Use `manageFunctions(action="createFunction")` for creation132 - Use `manageFunctions(action="updateFunctionCode")` for code updates133 - Use `manageFunctions(action="updateFunctionConfig")` for config updates (timeout, memorySize, envVariables)134 - Keep `functionRootPath` as the directory that directly contains function folders (e.g., `cloudfunctions/` or `functions/`), NOT the project root and NOT the function subdirectory itself135 - **Prefer MCP tools over CLI** — when MCP tools are available, use `manageFunctions` and `queryFunctions` instead of CLI commands136 - **Do NOT assume CLI is available from task wording alone** — if the available capabilities only include MCP tools, use MCP tools exclusively137 - For batch updates (multiple functions), call `manageFunctions(action="updateFunctionConfig")` individually for each function — MCP does not have a `--all` batch parameter like CLI1381394. **Prefer doc-first fallbacks**140 - If a task falls back to `callCloudApi`, first check the official docs or knowledge-base entry for that action141 - Confirm the exact action name and parameter contract before calling it142 - Do not guess raw cloud API payloads from memory1431445. **Read the right detailed reference**145 - Event Function details -> `./references/event-functions.md`146 - HTTP Function details -> `./references/http-functions.md`147 - Logs, gateway, env vars, and legacy mappings -> `./references/operations-and-config.md`148149## Database write reminder150151- If a function will write to CloudBase document database, create the target collection first through console or management tooling.152- `db.collection("feedback").add(...)` only inserts into an existing collection; it does not auto-create `feedback` when absent.153- If the product requirement says "create when missing", implement that as an explicit collection-management step before the first write instead of assuming the runtime write call will provision it.154155## Function types comparison156157| Feature | Event Function | HTTP Function |158| --- | --- | --- |159| Primary trigger | SDK call, timer, event | HTTP request |160| Entry shape | `exports.main(event, context)` | web server with `req` / `res` |161| Port | No port | Must listen on `9000` |162| `scf_bootstrap` | Not required | Required |163| Dependencies | Auto-installed from `package.json` | Must be packaged with function code |164| Best for | serverless handlers, scheduled jobs | APIs, SSE, WebSocket, browser-facing services |165166## Minimal code skeletons167168### Event Function hello world169170`cloudfunctions/hello-event/index.js`171172```js173exports.main = async (event, context) => {174 return {175 ok: true,176 message: "hello from event function",177 event,178 };179};180```181182`cloudfunctions/hello-event/package.json`183184```json185{186 "name": "hello-event",187 "version": "1.0.0"188}189```190191### HTTP Function hello world192193`cloudfunctions/hello-http/index.js`194195```js196const http = require("http");197const { URL } = require("url");198199// CORS headers — default to * for simple cross-origin APIs200const CORS_HEADERS = {201 "Access-Control-Allow-Origin": "*",202 "Access-Control-Allow-Methods": "GET, POST, OPTIONS",203 "Access-Control-Allow-Headers": "Content-Type",204};205206function sendJson(res, statusCode, data) {207 res.writeHead(statusCode, {208 "Content-Type": "application/json; charset=utf-8",209 ...CORS_HEADERS,210 });211 res.end(JSON.stringify(data));212}213214function sendOptions(res) {215 res.writeHead(204, CORS_HEADERS);216 res.end();217}218219function readJsonBody(req) {220 return new Promise((resolve, reject) => {221 let raw = "";222 req.on("data", (chunk) => { raw += chunk; });223 req.on("end", () => {224 if (!raw) { resolve({}); return; }225 try { resolve(JSON.parse(raw)); } catch (e) { resolve({}); }226 });227 req.on("error", reject);228 });229}230231const server = http.createServer(async (req, res) => {232 // Handle CORS preflight233 if (req.method === "OPTIONS") {234 return sendOptions(res);235 }236237 const url = new URL(req.url || "/", "http://127.0.0.1");238239 if (req.method === "GET" && url.pathname === "/") {240 sendJson(res, 200, { ok: true, message: "hello from http function" });241 } else if (req.method === "POST" && url.pathname === "/") {242 const body = await readJsonBody(req);243 sendJson(res, 200, { received: body });244 } else {245 sendJson(res, 404, { error: "Not Found" });246 }247});248249server.listen(9000);250```251252For a more complete example with routing, method checks, and error handling, see `./references/http-functions.md`.253254`cloudfunctions/hello-http/scf_bootstrap`255256```bash257#!/bin/bash258/var/lang/node18/bin/node index.js259```260261The `scf_bootstrap` binary path must match the runtime — see the full mapping table in `./references/http-functions.md`.262263`cloudfunctions/hello-http/package.json`264265```json266{267 "name": "hello-http",268 "version": "1.0.0"269}270```271272## Preferred tool map273274### Function management275276- `queryFunctions(action="listFunctions"|"getFunctionDetail")`277- `manageFunctions(action="createFunction")`278- `manageFunctions(action="updateFunctionCode")`279- `manageFunctions(action="updateFunctionConfig")`280281### Logs282283**Query function logs** — use the `queryFunctions` tool:284285- `queryFunctions(action="listFunctionLogs", functionName="xxx")` — list execution logs of a specific function286- `queryFunctions(action="getFunctionLogDetail", requestId="xxx")` — fetch the detail of one log entry287288**`queryFunctions` vs `queryLogs`**:289- `queryFunctions` queries execution logs of a single cloud function and requires `functionName`290- `queryLogs` searches CLS (cross-service log aggregation) using CLS query syntax291292**Examples**:293```javascript294// List recent logs for cloud function "my-function"295queryFunctions(action="listFunctionLogs", functionName="my-function", limit=10)296297// Inspect the log detail for a specific request id298queryFunctions(action="getFunctionLogDetail", requestId="abc-123")299300// Cross-service error search via CLS301queryLogs(action="searchLogs", queryString='(src:app OR src:system) AND log:"ERROR"', service="tcb")302```303304`queryLogs` `queryString` follows CLS syntax (see https://cloud.tencent.com/document/api/876/128127). The examples below are starting points; adapt them to the concrete log content of your query:305- Function logs: `(src:app OR src:system) AND log:"START RequestId"`306- Aggregated function request status: `| select request_id, max(status_code) as status where ((request_id='xxxx' AND retry_num=0) AND retry_num=0) AND status_code!=202 group by request_id, retry_num`307- Document database (NoSQL): `module:database`308- Document database slow-query events: `module:database AND eventType:(MongoSlowQuery)` — `MongoSlowQuery` is the document-database slow-query event309- Relational database (MySQL): `module:rdb`310- Relational database (MySQL) events: `module:rdb AND eventType:(MysqlFreeze OR MysqlRecover OR MysqlSlowQuery)` — `MysqlFreeze` = freeze, `MysqlRecover` = recover, `MysqlSlowQuery` = slow query311- Workflow (approval flow): `module:workflow`312- Data model: `module:model`313- User permissions: `module:auth`314- LLM trace logs: `module:llm AND logType:llm-tracelog`315- Gateway access logs: `logType:accesslog`316- App publish / delete events: `module:app AND eventType:(AppProdPub OR AppProdDel)` — `AppProdPub` = app publish, `AppProdDel` = app delete317318If these are unavailable, read `./references/operations-and-config.md` before any `callCloudApi` fallback319320### Gateway exposure321322- `queryGateway(action="getAccess")`323- `manageGateway(action="createAccess")`324- If gateway operations need raw cloud API fallback, read `./references/operations-and-config.md` first325326## Related skills327328- `cloudrun-development` -> container services, long-lived runtimes, Agent hosting329- `http-api` -> raw CloudBase HTTP API invocation patterns330- `cloudbase-platform` -> general CloudBase platform decisions331- `ops-inspector` -> AIOps-style inspection and log search across services