Cloud functions

From infometa/workbuddyskills · View interactive version

Cloud functions is an AI agent skill from the GitHub repository infometa/workbuddyskills. 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.

How to use this skill

Skill file

Sibling skills (local only)

Sibling CloudBase skills ship beside this skill. Use local relative paths such as ../auth-tool-cloudbase/SKILL.md.

If a referenced sibling skill file is missing from this environment, ask the user to install the full CloudBase plugin (or the missing skill). Do not HTTP-fetch remote skill or protocol markdown into the agent context.

Cross-cutting protocols (required before code changes or deployments):

Cloud Functions Development

Activation Contract

Use this first when

Read before writing code if

Exception only (do not read by default)

Then also read

Do NOT use for

Common mistakes / gotchas

Minimal checklist

MCP image deployment with polling

For real cloud or local custom-image deployments, prefer:

{
  "action": "deployFunction",
  "dryRun": false,
  "confirm": true,
  "wait": false,
  "deployConfig": {}
}

The wait field controls whether the current MCP Tool call waits for the complete deployment:

When wait=false returns a taskId, the deployment workflow is not complete. Automatically call queryFunctions with action="getFunctionDeployStatus" and that taskId; continue while the status is running, then stop only at succeeded or failed. Wait about 5 seconds before the first follow-up query and use the returned progress/nextActions to continue without aggressive polling. Do not tell the user to ask again or imply success before a terminal status is returned. An expired status means the task exceeded the maximum retention window and was force-terminated locally — the cloud deployment may still be in progress, so confirm the real state with getFunctionDetail instead of reporting failure.

If a reasonable polling limit is reached, report only that the task is still running, including the taskId, current status, current stage, and latest progress. For a terminal result, report the deployment strategy, action, image URI/digest, build ID, function status, Gateway URL, or the failed stage, error code, request ID, and diagnostic next step.

Personal-tier TCR credentials — never put the password in tool arguments

Personal-tier image builds (imageConfig.imageType="personal" with local / cloud) need a TCR push credential. Read it from the MCP process environment, not from tool arguments:

Know when that environment channel does not exist. It works only for a local stdio MCP server whose client configuration exposes a custom env block. Some GUI clients do not inherit shell exports, and IDE-embedded MCP servers usually inject credentials from a hard-coded allowlist (often only TENCENTCLOUD_*), leaving the user no way to set arbitrary variables. Telling those users to "set it in the MCP env block" is an instruction they cannot act on. Route them to an enterprise registry (imageType="enterprise", which mints a short-lived TCR token instead of using a fixed password) or to buildStrategy="image" with an already-pushed image.

Enterprise-tier builds require a login state with CAM permission

cloud / local builds against an enterprise registry mint a TCR token through CAM (as does autoGrant). Environment-level API Keys and OAuth-issued STS credentials carry no CAM policy, so those calls fail with UnauthorizedOperation. The MCP probes the login state before starting a real enterprise build and refuses up front rather than failing midway; treat that error as a routing signal, not a retryable fault:

Writing mode at a glance

HTTP Function authoring contract

Use these rules whenever you are writing the function code itself:

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 custom system libraries / arbitrary runtime, but still SCF request-driven + scale-to-zero? | HTTP Function with Runtime: CustomImage (deploy from a TCR image) |

| Has a Dockerfile but is a stateless HTTP service (no long connections / custom runtime / VPC DB)? | HTTP Function (or Custom Image HTTP Function) — not CloudRun |

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

  1. Choose the correct runtime model first
  1. Use the converged MCP entrances
  1. Write code and deploy, do not stop at local files
  1. Prefer doc-first fallbacks
  1. Read the right detailed reference

Database write reminder

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) => {
  // Do not return event/context/process.env — they may contain platform secrets.
  const name = typeof event?.name === "string" ? event.name : "world";
  return {
    ok: true,
    message: `hello ${name} from event function`,
  };
};

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: leave this empty when the function is reached through the HTTP gateway.
// The gateway already fills Access-Control-Allow-Origin from the environment
// security-domain allowlist; adding a second value makes the header illegal
// ('<origin>,*') and browsers block every request. Only set CORS headers here
// when the function is called directly, outside the gateway.
const CORS_HEADERS = {};

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

Create and update functions through manageFunctions, not through callCloudApi:

Why this is a rule and not a preference. manageFunctions owns the execution role and the log binding, and it re-checks the resulting Status after a config or code change — a failure surfaces with its real StatusReasons instead of a bare success.

Calling tcb:CreateFunction / tcb:UpdateFunctionCode / tcb:UpdateFunctionConfig directly is an asynchronous path: the SCF-level failure is carried in SCFErrorCode, and that field can be an empty string even when the function ends up in CreateFailed. The synchronous response then looks like success. Callers then "fix" parameters that were never wrong and end up in a delete-recreate loop.

Exception: an integration / platform-tier environment that must give each tenant its own execution role. Only then use callCloudApi, and still poll DescribeFunctions for Status yourself. See references/custom-execution-role.md before going down that path — it has a price.

Layers (SCF Layer)

Layers are account-scoped, not env-scoped. Align with MCP manageFunctions / queryFunctions layer guidance:

Logs

Query function logs — use the queryFunctions tool:

queryFunctions vs queryLogs:

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:

If these are unavailable, read ./references/operations-and-config.md before any callCloudApi fallback

Gateway exposure

Related skills

Reference index

All packaged reference files (required for skill lint reachability):

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.