Skip to main content

OpenAgentKernel (Official SDK)

@cloudbase/open-agent-kernel (OAK) is CloudBase's official server-side Agent SDK, open-sourced under Apache-2.0. It ships the infrastructure that every Agent project ends up rebuilding — session persistence, multi-turn context, MCP tool integration, human-in-the-loop approval (HITL), long-term user memory, and sandboxed execution — so you only write business logic.

Quickstart

Prerequisites: Node.js 20.19+, a CloudBase environment envId, and the environment's server-side API Key (get one here).

npm install @cloudbase/open-agent-kernel
import { createAgent } from "@cloudbase/open-agent-kernel";

process.env.CLOUDBASE_APIKEY = "your-cloudbase-api-key";

const agent = createAgent({
envId: "your-env-id",
model: "deepseek-v4-pro",
systemPrompt: "You are a helpful assistant.",
});

const session = await agent.startSession({ userId: "user-1" });

for await (const msg of session.send("Explain Serverless in one sentence.")) {
const update = msg.params?.update;
if (update?.sessionUpdate === "agent_message_chunk") {
process.stdout.write(update.content.text);
}
}
// The loop exits automatically when the turn completes

A plain model string goes through the CloudBase AI gateway, authenticated with CLOUDBASE_APIKEY; you can also pass { id, apiKey, apiBaseUrl } to bring your own model endpoint. Models must be enabled in the console first; calling a model that is not enabled returns 403 AI_MODEL_NOT_SUPPORTED (error reference).

Create from the console

Open the Agent section of the CloudBase console and pick the official cloudbase-agent template when creating an Agent. What you get is an OpenAgentKernel project: session persistence, MCP tools, and HITL approval work out of the box, and you can chat with it right away on the "Integrate & Debug" page.

For deeper customization, follow the "Local development" page:

tcb fn code download # pull the code locally
# make your changes...
tcb fn deploy # deploy back to the cloud

The console handles hosting, logs, and the debugging entry point; OpenAgentKernel handles the runtime.

Core configuration

Common fields of createAgent(config):

FieldRequiredDescription
envIdYesCloudBase environment ID; the model gateway, database, storage, and sandbox are all anchored to it
modelYesModel ID (via the CloudBase AI gateway) or a full { id, apiKey, apiBaseUrl } spec
systemPromptNoSystem prompt (persona and behavioral constraints)
streamNoIncremental streaming output, defaults to true. Note: if the deployment gateway buffers the whole response, the client still receives everything at the end of the turn — that is gateway behavior, unrelated to this switch
mcpServersNoMCP server config; supports in-process, local stdio, and remote HTTP forms
permissionsNoTool approval (HITL): requireApproval accepts '*', an array of tool names, or a function
sessionNoSession persistence, defaults to the CloudBase database
storageNoMultimodal attachment storage, defaults to CloudBase cloud storage
sandboxNoRemote sandbox (currently in private beta; contact us if needed)
userMemoryNoLong-term user memory, synced to CloudBase cloud storage across sessions
credentialsDependsTencent Cloud SecretId/SecretKey; with only CLOUDBASE_APIKEY, sessions and approvals still persist, but workspace file sync and multimodal attachment upload require it

For the full field list and defaults, see the "Complete parameters" section of the GitHub README.

Configure MCP tools

const agent = createAgent({
envId,
model: "deepseek-v4-pro",
systemPrompt: "You are a helpful assistant.",
mcpServers: {
// remote HTTP MCP
remote: {
type: "http",
url: "https://example.com/mcp/v1",
headers: { Authorization: "Bearer xxx" },
},
// local stdio MCP
stdio: {
type: "stdio",
command: "npx",
args: ["-y", "@modelcontextprotocol/server-everything"],
},
},
});

Tool names follow the mcp__{serverName}__{toolName} convention. For in-process custom tools, see the README section on MCP tool extension.

Tool approval (HITL)

const agent = createAgent({
envId,
model: "deepseek-v4-pro",
permissions: {
requireApproval: ["database_delete", "reset_password"],
},
});

A matched tool call pauses the turn and emits a session/request_permission request frame in the event stream; after your UI collects the user's decision, call session.respondApproval() to continue.

Session persistence and cross-process resume

Session records persist to the CloudBase database by default and do not depend on process memory. Resume the context in another invocation with the conversationId:

const session = await agent.startSession({ userId: "user-1" });
const conversationId = session.id;

// another process / the next function invocation
const resumed = await agent.resumeSession(conversationId);

Event stream

session.send() returns an AsyncIterable. Each item is a JSON-RPC formatted ACP notification, with the actual update in msg.params.update. A real frame looks like this:

{
"jsonrpc": "2.0",
"method": "session/update",
"params": {
"sessionId": "a8ea09e4-3ae4-4856-a285-bc2a7c9d76ab",
"update": {
"sessionUpdate": "agent_message_chunk",
"content": { "type": "text", "text": "Serverless is a" }
}
}
}

Possible values of update.sessionUpdate:

TypeMeaning
agent_message_chunkIncremental response text, for streaming rendering
agent_thought_chunkIncremental reasoning output (from reasoning models)
tool_call / tool_call_updateTool call start, progress, and result
agent_phaseRun phase change (idle when the turn ends)
usage_updateUsage statistics for the turn
logRuntime logs

End-of-turn detection: the for await loop exiting naturally means the turn is over — there is no separate end event to watch for.

OAK's event stream is based on ACP (Agent Client Protocol): when bridging to SSE, AG-UI, or a custom protocol, do the event mapping in your application layer.

Deploy and integrate

Deploy your Agent to CloudBase:

Client and channel integration follows the existing guides: Web / Node.js / Mini Program / cURL / WeChat channels.

Migrating from visual configuration

Everything you used to configure in the console's visual interface has a code-level home:

Visual configurationCode-first equivalent
Persona / role settingssystemPrompt in createAgent
Model selectionthe model field
Tools / MCPmcpServers config
Sensitive-operation confirmationpermissions.requireApproval
Welcome message / opening questionssee "Dynamic configuration" below — store in the database, change config without changing code

Dynamic welcome message and opening questions

Welcome messages and opening questions are presentation-layer data and should not be hardcoded. Store them in a config collection in the CloudBase database and read them at runtime — changes take effect immediately, no redeploy needed:

// Cloud function entry: read the config collection per request
const db = app.database();
const { data } = await db.collection("agent_config").doc("my-agent").get();

const agent = createAgent({
envId,
model: data.model,
systemPrompt: data.systemPrompt,
});

The frontend (including the Agent UI component) reads welcomeMessage and openingQuestions from the same collection to render the opening screen. In this pattern, persona, welcome message, and opening questions all become data instead of code — changing them is as easy as updating a database record.

Migrating from beta versions

0.1.1 is the first stable release (previous npm versions were 0.1.0-beta.x). If you wrote code against the early beta docs, migrate with this table:

beta.15 / beta.160.1.1
npm install @cloudbase/open-agent-kernel@betanpm install @cloudbase/open-agent-kernel
Env var TCB_API_KEYCLOUDBASE_APIKEY
event.type === "message_delta", text in event.textmsg.params.update.sessionUpdate === "agent_message_chunk", text in update.content.text
session_idle event marks end of turnthe for await loop exiting marks end of turn
tool_approval_required eventsession/request_permission request frame
message_complete (full text)no equivalent frame; concatenate the increments yourself
Node.js 22+Node.js 20.19+

FAQ

What is CLOUDBASE_APIKEY? The server-side API Key of your CloudBase environment, used for the default model gateway calls and data-plane authentication. It is not the same thing as Tencent Cloud platform credentials (SecretId/SecretKey), which let the SDK operate CloudBase resources directly.

Which capabilities require credentials? Session persistence and approval state work with only CLOUDBASE_APIKEY; syncing local workspace files to the cloud and multimodal attachment upload require credentials. When missing, workspace sync is skipped with an [oak/workspacePersist] warning — the conversation itself is unaffected.

Is the sandbox available? Sandbox capability is currently in private beta; contact us if you need it.