Ask a person before a query runs

An agent that wants to run SQL shows it to a person first. The person can allow it, deny it, or edit it and allow their version. Only what they allowed runs, and only after the agent has checked the answer.

How it works:

  • A tool with an approval function pauses the turn: the agent sends an approval event with the SQL, a subject and a digest of both, and stops.
  • Chat shows it as an approval card. When the person decides, the card sends who decided, when, why, any edit, and the digest of exactly what they saw.
  • On the next turn the agent calls checkApproval. It refuses an answer whose digest does not match, one that has expired, one missing a required reason, or one from someone mayDecide rejects. Only then does it call run with approved.sql, which is the person's version if they edited it.
  • A refusal or a failed check goes back to the model as the tool's result, so the model can explain it or try something else. Nothing runs.

The tool:

tools.ts:

ts
import type { ApprovedRun, RunnableTool } from "@surfaces-ui/agent";
import { type DataSource, collect, toRows } from "@surfaces-ui/data";
import { ApprovalRisk } from "@surfaces-ui/proto";

const MAX_ROWS = 200;

/**
 * A `run_query` tool that shows the SQL to a person before it runs. The
 * person may edit it; whatever they allow is what runs, and only after the
 * agent has checked the answer (digest, expiry, reason, who decided).
 * Queries still go through the read-only DataSource.
 */
export function approvedQueryTool(dataSource: DataSource, sourceId: string): RunnableTool {
  return {
    name: "run_query",
    description: `Run one read-only SQL query on the "${sourceId}" source and get up to ${MAX_ROWS} rows back. A person reviews the SQL first and may change it.`,
    inputSchema: {
      type: "object",
      properties: { sql: { type: "string", description: "One SELECT or WITH statement" }, why: { type: "string", description: "What the answer is for, shown to the person" } },
      required: ["sql", "why"],
      additionalProperties: false,
    },
    approval: (input) => {
      const { sql, why } = input as { sql: string; why: string };
      return {
        title: "Run this query?",
        detail: why,
        sql,
        subject: { source: sourceId, rowLimit: MAX_ROWS },
        risk: ApprovalRisk.LOW,
        editable: true,
        // Ten minutes: after that the person is asked again.
        expiresAt: new Date(Date.now() + 10 * 60_000).toISOString(),
      };
    },
    run: async (_input, signal, approved?: ApprovedRun) => {
      // Run what the person allowed, never the model's original input.
      if (!approved) throw new Error("run_query only runs after a person allows it.");
      const result = await collect(dataSource.execute({ sourceId, query: { baseSql: approved.sql, page: { limit: MAX_ROWS, offset: 0n } } }, { signal }));
      return { ran: approved.sql, edited: approved.edited, allowedBy: approved.approvals.map((a) => a.decidedBy?.name), rows: toRows(result.table) };
    },
  };
}

On the server, give it to Claude:

agent.ts:

ts
import Anthropic from "@anthropic-ai/sdk";
import type { AgentBackend } from "@surfaces-ui/agent";
import { anthropicAgent } from "@surfaces-ui/agent-anthropic";
import type { DataSource } from "@surfaces-ui/data";
import { analyticsCatalog, catalogPrompt } from "@surfaces-ui/spec";
import { approvedQueryTool } from "./tools.js";

/** On the server: Claude with a query tool that waits for a person. The key comes from ANTHROPIC_API_KEY. */
export function analystAgent(dataSource: DataSource): AgentBackend {
  return anthropicAgent({
    client: new Anthropic(),
    system: `${catalogPrompt(analyticsCatalog)}\n\nAnswer questions about the "retail" source. Use run_query to look at data; say what each query is for.`,
    tools: [approvedQueryTool(dataSource, "retail")],
    checkSurface: (message) => analyticsCatalog.validateMessage(message),
    // Your rule for who may allow a query, checked on the server.
    mayDecide: (actor) => Boolean(actor?.id),
  });
}

In the browser nothing special is needed. Chat draws the card, and user says who is deciding:

tsx
<Chat agent={connectAgent({ baseUrl: "http://localhost:5220" })} user={{ id: session.userId, name: session.name }} />

For changes that cannot be undone, set risk: ApprovalRisk.IRREVERSIBLE: the card then asks the person to type "confirm". Set approvalsRequired: 2 to need two different people, and reasonRequired: true to make each of them say why. Then report what ran with an ActionReceipt.

The test drives the real Chat against a stand-in model and the in-memory data source:

approval.test.tsx:

tsx
// @vitest-environment jsdom
import { type ModelChunk, type ModelMessage, toolCallingAgent } from "@surfaces-ui/agent";
import { Chat } from "@surfaces-ui/chat";
import { DataSourceProvider } from "@surfaces-ui/components";
import { memoryDataSource } from "@surfaces-ui/data";
import { EditorView } from "@codemirror/view";
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import { approvedQueryTool } from "./tools.js";

afterEach(cleanup);

const data = memoryDataSource({
  sourceId: "retail",
  tables: {
    orders: [{ order_id: 1, amount: 40 }, { order_id: 2, amount: 15 }],
    returns: [{ order_id: 2, reason: "damaged" }],
  },
});

describe("an approval before SQL runs", () => {
  it("shows the model's SQL, runs the person's edited version, and hands the rows back to the model", async () => {
    const seen: ModelMessage[][] = [];
    // A stand-in for Claude: asks for one query, then reports what came back.
    const agent = toolCallingAgent({
      system: "s",
      tools: [approvedQueryTool(data, "retail")],
      complete: async function* ({ messages }): AsyncIterable<ModelChunk> {
        seen.push([...messages]);
        const last = messages.at(-1)!;
        if (last.role === "tool") yield { type: "text", delta: "Here is what came back." };
        else yield { type: "tool_call", call: { id: "q1", name: "run_query", input: { sql: "SELECT * FROM orders", why: "Count orders" } } };
        yield { type: "done", model: "stand-in" };
      },
    });

    render(
      <DataSourceProvider dataSource={data}>
        <Chat agent={agent} user={{ id: "u1", name: "Ada" }} />
      </DataSourceProvider>,
    );
    fireEvent.change(screen.getByLabelText("Message"), { target: { value: "How many returns?" } });
    fireEvent.click(screen.getByRole("button", { name: "Send" }));

    expect(await screen.findByText("Run this query?")).toBeTruthy();
    expect(screen.getByText("Count orders")).toBeTruthy();
    fireEvent.click(screen.getByRole("button", { name: "Edit before allowing" }));
    // The SQL is edited in the SQL editor (CodeMirror), so the test types through its view.
    const editor = EditorView.findFromDOM(screen.getByLabelText("SQL"))!;
    act(() => editor.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: "SELECT * FROM returns" } }));
    const allow = screen.getByRole("button", { name: "Allow my version" });
    await waitFor(() => expect((allow as HTMLButtonElement).disabled).toBe(false));
    fireEvent.click(allow);

    expect(await screen.findByText("Here is what came back.")).toBeTruthy();
    const result = JSON.parse(seen.at(-1)!.at(-1)!.content);
    expect(result).toEqual({ ran: "SELECT * FROM returns", edited: true, allowedBy: ["Ada"], rows: [{ order_id: 2, reason: "damaged" }] });
  });

  it("never runs when the person says no", async () => {
    let ran = false;
    const tool = approvedQueryTool(data, "retail");
    const agent = toolCallingAgent({
      system: "s",
      tools: [{ ...tool, run: async (...args) => ((ran = true), tool.run(...args)) }],
      complete: async function* ({ messages }): AsyncIterable<ModelChunk> {
        if (messages.at(-1)!.role === "tool") yield { type: "text", delta: "Understood, I did not run it." };
        else yield { type: "tool_call", call: { id: "q1", name: "run_query", input: { sql: "SELECT * FROM orders", why: "Count orders" } } };
      },
    });
    render(<Chat agent={agent} user={{ id: "u1", name: "Ada" }} />);
    fireEvent.change(screen.getByLabelText("Message"), { target: { value: "Count orders" } });
    fireEvent.click(screen.getByRole("button", { name: "Send" }));
    fireEvent.click(await screen.findByRole("button", { name: "Deny" }));
    expect(await screen.findByText("Understood, I did not run it.")).toBeTruthy();
    expect(ran).toBe(false);
  });
});

Source and test: apps/recipes/src/approval-before-sql