camelAI Documentation

Guides

camelRun v2 tools: local WebSocket, HTTP webhooks, MCP, and built-ins

Give camelRun v2 agents tools via local WebSockets (defineTool), HTTP webhooks, signed MCP servers with runtime JWTs, and built-in suites.

View as Markdown

camelRun v2 supports four ways to give an agent tools. You can combine all four on the same agent.

1. Local tools over WebSocket (defineTool)

When you pass a tool with an execute function in @camelai/run, the SDK registers it with the agent and opens a hibernatable WebSocket to /v2/agents/:idOrKey/ws. When the model invokes the tool, camelRun dispatches { type: "tool_call", callId, name, args } over the socket, your process runs execute(args), and the SDK sends back { type: "tool_result", callId, result, error }.

ts
import { CamelRun, defineTool } from "@camelai/run";

const client = new CamelRun({
  baseUrl: "https://run.camelai.com",
  apiKey: process.env.CAMELRUN_API_KEY!,
});

const getInvoice = defineTool({
  name: "getInvoice",
  description: "Fetch an invoice by ID",
  parameters: {
    type: "object",
    properties: { invoiceId: { type: "string" } },
    required: ["invoiceId"],
  },
  requiresApproval: false,
  execute: async ({ invoiceId }: { invoiceId: string }) => {
    return { invoiceId, amountUsd: 120, paid: true };
  },
});

const agent = await client.agents.upsert("billing-assistant", {
  instructions: "Help users check invoices.",
  tools: [getInvoice],
});

const run = await agent.run("Is invoice INV-9 paid?");
console.log(run.text);
client.close();
  • Each WebSocket tool call has a 30-second timeout on the runtime side.
  • Local tools require your process to stay connected while runs execute. For serverless functions, multi-worker web servers, or scheduled agents, use HTTP webhook tools or remote MCP servers instead.
  • If you attach to an existing agent with client.agents.get("billing-assistant", { tools: [getInvoice] }) or agent.attachTools([getInvoice]), the SDK opens the tool session automatically.

2. HTTP webhook tools

Provide a url (and optional headers) on a tool specification so camelRun calls your HTTPS endpoint directly without holding a persistent WebSocket:

ts
const agent = await client.agents.upsert("orders-agent", {
  instructions: "Help with order lookups and refunds.",
  tools: [
    {
      name: "refundOrder",
      description: "Issue a refund for an order",
      parameters: {
        type: "object",
        properties: {
          orderId: { type: "string" },
          reason: { type: "string" },
        },
        required: ["orderId"],
      },
      url: "https://app.example.com/api/tools/refund-order",
      headers: { Authorization: "Bearer internal-tool-secret" },
      requiresApproval: true,
    },
  ],
});

When invoked, camelRun sends a POST request with JSON body:

json
{
  "callId": "call_...",
  "runId": "run_...",
  "name": "refundOrder",
  "args": { "orderId": "ORD-42", "reason": "duplicate charge" }
}

Any 2xx response body is returned to the model (JSON is parsed automatically). Non-2xx responses are surfaced to the model as a tool error. Setting requiresApproval: true pauses the run with status: "input_required" before calling the URL; see Human input.

3. Remote MCP servers (mcpServers)

Attach any Streamable HTTP MCP server to an agent or definition. At turn start, camelRun calls tools/list on each server, optionally filters by allowTools, and exposes discovered tools to the model as <serverName>__<toolName>.

ts
const agent = await client.agents.upsert("app-builder", {
  instructions: "Use the app tools to inspect and deploy the user's project.",
  toolIdentity: {
    subject: user.id,
    context: { projectId: project.id },
  },
  mcpServers: [
    {
      name: "app",
      url: "https://app.example.com/mcp",
      auth: { type: "runtime" },
      audience: "https://app.example.com/mcp",
      allowTools: ["read_project", "deploy_project"],
    },
  ],
});
FieldDescription
namePrefix for tool names (<name>__<toolName>)
urlStreamable HTTP JSON-RPC endpoint (signed runtime auth requires https://, except http://127.0.0.1 for local dev, and disallows redirects)
headersOptional static HTTP headers sent with every MCP request
authSet { type: "runtime" } to attach a short-lived Ed25519 JWT signed by camelRun
audienceOptional JWT aud claim (defaults to <origin><pathname> of url)
allowToolsOptional allowlist of remote tool names to expose to the model

Verifying runtime tool identity JWTs

When auth: { type: "runtime" } is set, camelRun signs an EdDSA (Ed25519) JWT valid for 2 minutes and sends it in Authorization: Bearer <jwt>. Fetch the runtime's public keys from:

GET https://run.camelai.com/v2/.well-known/jwks.json

JWT claims:

ClaimValue
issRuntime issuer (TOOL_IDENTITY_ISSUER, e.g. https://run.camelai.com/v2)
audConfigured audience or <origin><pathname> of the MCP server URL
subagent.toolIdentity.subject (or agent.id if toolIdentity is unset)
tenantTenant ID (tnt_...)
agentAgent ID (agt_...)
definitionOptional definition slug
ctxOptional agent.toolIdentity.context object
reqRun ID (run_...) on tools/call
tcidTool call ID on tools/call
actRun actor (if set by your tenant credential on POST /v2/agents/:idOrKey/runs)
approval{ input, by: { id }, at } when resuming after a tenant-approved input request

Every tools/call on a signed MCP server also passes _meta:

  • _meta["agent-runtime/callId"]: unique UUID for this attempt
  • _meta["agent-runtime/toolCallId"]: tool call ID
  • _meta["agent-runtime/idempotencyKey"]: stable key [agentId, runId, toolCallId] across retries and human-approval resumes
  • _meta["io.modelcontextprotocol/clientCapabilities"]: { elicitation: { form: {}, url: {} } }

Signed MCP servers can pause a run for approval (agent-runtime/approval) or structured elicitation (elicitation/create in form or url mode). See Human input.

4. Built-in tool suites (builtins)

Enable built-in capabilities by listing suite names in builtins:

SuiteTools exposedDescription
filesread_file, view_image, write_file, edit_file, list_files, grep_files, delete_file, repo_checkpoint, repo_restore, repo_historyGit-backed workspace file operations on the agent's CamelFS repository
imagesrender_imageRender an SVG (with optional repo image inputs) to PNG, save it in the repo, and inspect the result
bashbashPersistent bash shell over /workspace inside a session VM with atomic Git commits
codemodecodemodeExecute sandboxed async JavaScript in QuickJS with access to tools.<name>(args) and fs.readFile / fs.writeFile / fs.readdir
delegatedelegate, spawn_agent, send_message, wait_agentSynchronous and asynchronous child-agent delegation
workflowsworkflow_runRun deterministic replay-cached JavaScript workflows with wf.*
web_searchweb_searchSearch the web (query, optional limit)
web_fetchweb_fetchFetch an HTTP/HTTPS URL (url, optional maxChars)
humanask_humanPause the run and ask a human a question (question, optional options)

Using codemode

With builtins: ["codemode"], the model can write an async JavaScript function body executed in an isolated QuickJS sandbox to chain multiple tool calls and file reads in a single turn step:

js
const files = await fs.readdir("src");
const results = await Promise.all(
  files.filter((f) => f.endsWith(".ts")).map((f) => fs.readFile(`src/${f}`)),
);
return { count: results.length };