Skip to content
Approve a tool call

Approve a tool call

Pause an execution for a person’s decision, then follow it through to its final result.

Before you start#

Complete the Quick start. For a reproducible example, add the hello greet tool from Build a custom integration to your world. In the integration’s tool permissions, choose Ask before running. Ensure no user Allow override skips approval for your test user.

For an external provider tool, also connect the user’s account. A hidden tool or disabled integration cannot be made available by approving a call.

A tool call hook can also ask for approval of a call whose tool is allowed. Such an approval works the same way, and its reason says why the hook asked.

1. Add backend helpers#

Keep the API key on your server. These functions read the execution, wait for a pause or terminal state, and submit one decision. Derive userId from your signed-in application user; API keys can access the whole workspace, so your backend owns user authorization.

Approval helpers · server-side TypeScript
const baseUrl = "https://api.smallworld.sh/api/v1";
const apiKey = process.env.SMALLWORLD_API_KEY;
if (!apiKey) throw new Error("Set SMALLWORLD_API_KEY on your server");

async function request<T>(path: string, body?: unknown): Promise<T> {
  const response = await fetch(baseUrl + path, {
    method: body === undefined ? "GET" : "POST",
    headers: {
      Authorization: `Bearer ${apiKey}`,
      ...(body === undefined ? {} : { "Content-Type": "application/json" }),
    },
    ...(body === undefined ? {} : { body: JSON.stringify(body) }),
  });
  const data = await response.json();
  if (!response.ok) throw new Error(`${response.status} ${data.code}: ${data.message}`);
  return data as T;
}

type ToolCall = {
  id: string;
  userId: string;
  integration: string;
  account: string | null;
  connectionSource: "personal" | "group" | "none" | null;
  group: { id: string; name: string | null } | null;
  toolName: string;
  arguments: Record<string, unknown>;
  status: string;
  expiresAt: string;
  error: string | null;
  errorCode: string | null;
  providerApproval?: {
    id: string;
    message: string;
    question: string;
    choices: { value: string; label: string }[];
  } | null;
};
type ApprovalDecision =
  | { kind: "local"; decision: "approve" | "deny" }
  | { kind: "provider"; approvalId: string; choice: string };
type ExecutionResult = {
  user: { id: string };
  session: { id: string };
  execution: {
    id: string;
    status: "running" | "requires_approval" | "completed" | "timed_out" | "interrupted";
    stdout: string | null;
    stderr: string | null;
    exitCode: number | null;
    errorCode: string | null;
  };
  toolCalls: ToolCall[];
};

async function readExecution(userId: string, executionId: string) {
  const result = await request<ExecutionResult>(
    `/executions/${encodeURIComponent(executionId)}`,
  );
  if (result.user.id !== userId) throw new Error("This execution belongs to another user");
  return result;
}

async function waitForUserOrResult(userId: string, executionId: string) {
  for (;;) {
    const result = await readExecution(userId, executionId);
    const pending = result.toolCalls.filter((call) => call.status === "pending");
    if (result.execution.status === "requires_approval" && pending.length)
      return result; // Render the pending calls and wait for a real user decision.
    if (!["running", "requires_approval"].includes(result.execution.status))
      return result; // A terminal result: inspect status, exitCode, output, and calls.
    // Still running: the next read is held until the command finishes or needs
    // an approval, so no pause is needed here.
  }
}

// Call only from an authenticated, authorized human decision handler.
async function decideToolCall(
  userId: string,
  savedExecutionId: string,
  toolCallId: string,
  decision: ApprovalDecision,
) {
  const current = await readExecution(userId, savedExecutionId);
  const pending = current.toolCalls.find(
    (call) => call.id === toolCallId && call.status === "pending",
  );
  if (!pending) throw new Error("The call is no longer awaiting a decision");
  if (pending.userId !== userId) throw new Error("This call belongs to another user");

  const prompt = pending.providerApproval;
  if (decision.kind === "provider") {
    if (!prompt || prompt.id !== decision.approvalId)
      throw new Error("The provider prompt changed. Refresh the approval UI");
    if (!prompt.choices.some((option) => option.value === decision.choice))
      throw new Error("Choose an option offered by this provider prompt");
    return request<ToolCall>(
      "/tool-approvals/" + encodeURIComponent(pending.id) + "/provider/" + encodeURIComponent(prompt.id),
      { choice: decision.choice },
    );
  }
  if (prompt) throw new Error("The provider requires one of its offered choices");
  if (!["approve", "deny"].includes(decision.decision))
    throw new Error("Choose Approve or Deny");
  return request<ToolCall>(
    `/tool-approvals/${encodeURIComponent(pending.id)}/${decision.decision}`,
    {}, // Approve or deny this call only; no remembered policy change.
  );
}

A read is held for up to 30 seconds while the command runs. For long-running work, persist execution IDs and read from a worker, so the wait survives your application’s request timeout.

2. Run a tool that asks for approval#

Execute the greeting command in your configured world. Store session.id to reuse the session and execution.id to resume monitoring after a page reload. The first response can already require approval.

Start and monitor the execution
// Reuse request<T> and the types above. userId comes from your login session.
// Use a world with the hello integration from Build a custom integration.
async function startGreeting(userId: string, worldId: string) {
  const result = await request<ExecutionResult>(
    `/worlds/${encodeURIComponent(worldId)}/execute`,
    { userId, command: `hello greet --json '{"name":"Ada"}'` },
  );
  // Save both IDs in your backend before continuing.
  const sessionId = result.session.id;
  const executionId = result.execution.id;
  const next = await waitForUserOrResult(userId, executionId);
  return { sessionId, executionId, next };
}

When execution.status is requires_approval, display each pending call’s integration, tool name, complete recorded arguments, and expiresAt. Render arguments as text or escaped JSON. For this example the user sees hello, greet, and {"name":"Ada"}, with explicit Approve and Deny buttons.

Use toolCall.id for the decision, not the execution ID. Bind the displayed call to your saved execution record. A single execution may have several pending calls; each needs its own decision. List tool approvals can also recover pending calls for an execution.

Show the acting userId, account, connectionSource, and group alongside the invocation. When providerApproval is present, display its message and question and render each offered choice label. Preserve its ID and each choice value for submission. The following UI creates buttons from the current prompt and renders provider text as text.

Render the current approval choices · browser TypeScript
// Browser code. submit sends this decision to your authenticated backend handler.
function renderApproval(
  container: HTMLElement,
  call: ToolCall,
  submit: (callId: string, decision: ApprovalDecision) => void,
) {
  container.replaceChildren();
  const details = document.createElement("pre");
  details.textContent = JSON.stringify({
    userId: call.userId, integration: call.integration, account: call.account,
    connectionSource: call.connectionSource, group: call.group,
    tool: call.toolName, arguments: call.arguments, expiresAt: call.expiresAt,
  }, null, 2);
  container.append(details);
  if (call.status !== "pending") return;

  const prompt = call.providerApproval;
  const actions: { label: string; decision: ApprovalDecision }[] = [];
  if (prompt) {
    for (const text of [prompt.message, prompt.question]) {
      const paragraph = document.createElement("p");
      paragraph.textContent = text;
      container.append(paragraph);
    }
    for (const choice of prompt.choices)
      actions.push({ label: choice.label, decision: {
        kind: "provider", approvalId: prompt.id, choice: choice.value,
      } });
  } else {
    actions.push({ label: "Approve", decision: { kind: "local", decision: "approve" } });
    actions.push({ label: "Deny", decision: { kind: "local", decision: "deny" } });
  }
  for (const action of actions) {
    const button = document.createElement("button");
    button.type = "button";
    button.textContent = action.label;
    button.addEventListener("click", () => submit(call.id, action.decision));
    container.append(button);
  }
}

3. Submit the person’s decision#

After the authenticated user chooses Approve or Deny, validate the submitted decision and call your backend helper. Authorize access to the saved execution and protect the decision handler like other authenticated mutations in your app. Do not let the agent approve its own requests.

Handle a human decision, then read the execution again
// In your backend's human decision handler:
// authenticatedUserId is from login; savedExecutionId is from your backend record.
// Validate the submitted ApprovalDecision and authorize this user for the record.
async function handleDecision(
  authenticatedUserId: string,
  savedExecutionId: string,
  toolCallId: string,
  decision: ApprovalDecision,
) {
  await decideToolCall(authenticatedUserId, savedExecutionId, toolCallId, decision);
  return waitForUserOrResult(authenticatedUserId, savedExecutionId);
}
// Render another approval request or the final result, as appropriate.

Approval runs the exact recorded invocation; arguments cannot be edited. The approval response acknowledges the decision, and the provider result may still be pending. Continue reading the same execution. After each pause, repeat the human decision step for any new pending calls until the execution finishes.

Sending {} approves only this call. Offer remember: true only as a separate, explicit choice: it saves an Allow override for this user and tool across worlds. Denials do not support remembering.

A provider can pause the same call after its local approval. When providerApproval is present, submit the selected choice.value through Respond to a provider approval, including the displayed providerApproval.id. Refresh after each decision and render the next prompt if one appears. Provider choices can include persistent permissions, which apply at that provider. Smallworld's remembered tool permissions are a separate decision.

4. Show the outcome#

After approval, the greeting normally completes with exit code 0 and {"greeting":"Hello, Ada!"} in stdout. Denying the call prevents provider dispatch and supplies a tool error to the command. A script can catch that error and continue, so denial does not necessarily finish the execution.

  • completed: check exitCode, stdout, stderr, and tool-call errors. HTTP 200 alone does not mean the command succeeded.
  • timed_out or interrupted: inspect output, errorCode, and tool-call history before deciding whether another command is needed.
  • interrupted with errorCode: "session_closed": the user left the session’s group or the group was deleted, and the session is closed for good. Start a new session for further commands.
  • A call marked unknown may have reached its remote service. Check that service before retrying a write.

Approvals expire after the workspace's approval timeout, which defaults to 15 minutes and can be set from 5 minutes to 1 month (30 days) in Settings → Terminal. Use each call's expiresAt for its deadline. Approval waits pause the one-hour execution limit. On approval_expired, approval_interrupted, or approval_already_processed, refresh the execution and replace the stale approval UI. If approval_policy_denied is returned, the call stays pending; let the user deny it or wait for expiry.

If a decision response is lost, read the execution before retrying. Repeating the same decision without remembering does not dispatch the tool twice. If the initial execution response is lost before you receive its ID, do not automatically resend the command: it may already have run.

On provider_approval_required, refresh and render the provider prompt. On provider_approval_already_processed, replace the stale prompt with the current call state. Submit each provider decision with the ID of the prompt the person saw.