Chat with Claude over your own data

Run Claude on your server as the chat's agent. It sees your tables through a list_tables tool, draws charts, tables and numbers from the catalog, and those components run their SQL through your read-only data source. The browser talks only to your server, so the API key never reaches it.

How it fits together:

  • anthropicAgent from @surfaces-ui/agent-anthropic turns Claude into an AgentBackend. Claude draws by calling render_surface with A2UI messages; checkSurface checks each one against the catalog, and anything with problems goes back to Claude to fix in the same turn instead of being drawn.
  • The system prompt is catalogPrompt(analyticsCatalog), which describes every component Claude may use, plus a few lines about your data.
  • createSurfacesServer serves that agent as AgentService next to the query and catalog services. In the browser, connectAgent and connectDataSource reach them.

Defaults worth knowing: anthropicAgent uses the model claude-sonnet-5-5 with effort "high", and turns on server-side refusal fallbacks (when the model declines, the API re-runs the request on a fallback model in the same call). Pass fallbacks: false to turn them off; you must on Bedrock, Vertex or Foundry, which do not offer them. The system prompt is cached, since the catalog prompt is long and does not change.

The agent and its one tool. list_tables gives names, types and descriptions only, never row values:

agent.ts:

ts
import Anthropic from "@anthropic-ai/sdk";
import type { AgentBackend, RunnableTool } 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";

/** Lets Claude see which sources and tables exist, with their columns. Names and types only; no row values. */
export function listTablesTool(dataSource: DataSource): RunnableTool {
  return {
    name: "list_tables",
    description: "List the data sources and their tables, with column names and types. Call this before writing SQL.",
    inputSchema: { type: "object", properties: { sourceId: { type: "string", description: "Only this source" } }, additionalProperties: false },
    run: async (input) => {
      const only = (input as { sourceId?: string }).sourceId;
      const { sources } = await dataSource.listSources({});
      const out = [];
      for (const source of sources.filter((s) => !only || s.id === only)) {
        const { tables } = await dataSource.listTables({ sourceId: source.id, pageSize: 200 });
        const described = [];
        for (const t of tables) {
          const { table } = await dataSource.describeTable({ sourceId: source.id, ref: t.ref });
          described.push({ name: t.ref?.table, comment: t.comment, columns: table?.columns.map((c) => `${c.name} ${c.nativeType}`) ?? [] });
        }
        out.push({ sourceId: source.id, tables: described });
      }
      return out.length > 0 ? out : { note: "No data sources are configured on this server." };
    },
  };
}

const NOTES = `
You answer questions about the data on this server. Call list_tables first to see what exists.
Write SQL as a single read-only SELECT and let components run it: Metric for a headline number,
Chart with an aggregate for anything over many rows, DataGrid to show records.
Say what each view shows in one sentence.`;

/** Claude over your data. On a server, `new Anthropic()` reads ANTHROPIC_API_KEY from the environment. */
export function claudeAgent(dataSource: DataSource, client: Anthropic = new Anthropic()): AgentBackend {
  return anthropicAgent({
    client,
    // Defaults: model claude-sonnet-5-5, effort "high", refusal fallbacks on.
    // Pass `fallbacks: false` on Bedrock, Vertex or Foundry, which do not offer them.
    system: `${catalogPrompt(analyticsCatalog)}\n${NOTES}`,
    tools: [listTablesTool(dataSource)],
    // A surface with problems is not drawn; the problems go back to Claude to fix in the same turn.
    checkSurface: (message) => analyticsCatalog.validateMessage(message),
  });
}

The server. new Anthropic() reads ANTHROPIC_API_KEY from the server's environment. agent is given as a function, so it gets the server's own data source for its tools:

server.ts:

ts
import { fileURLToPath } from "node:url";
import type Anthropic from "@anthropic-ai/sdk";
import { type SurfacesServer, type SurfacesServerOptions, createSurfacesServer, openSources, serverOptions } from "@surfaces-ui/dev-server";
import { claudeAgent } from "./agent.js";

/**
 * A dev server whose AgentService is Claude, with a `list_tables` tool over
 * the server's own sources: `agent` as a function is given the server's
 * DataSource.
 */
export function createClaudeChatServer(options: Omit<SurfacesServerOptions, "agent">, client?: Anthropic): Promise<SurfacesServer> {
  return createSurfacesServer({ ...options, agent: (dataSource) => claudeAgent(dataSource, client) });
}

/** Serves the six sample industry models with Claude on http://127.0.0.1:5220. */
export async function main() {
  const config = { seeds: true };
  const dir = process.cwd();
  const server = await createClaudeChatServer(await serverOptions(config, await openSources(config, dir), dir));
  const { url } = await server.listen(5220);
  console.log(`Chat with Claude at ${url}`);
}

if (process.argv[1] === fileURLToPath(import.meta.url)) await main();

Run it with a TypeScript runner, for example ANTHROPIC_API_KEY=... npx tsx server.ts. With seeds: true it serves the six sample industry models (retail, healthcare and the rest). To serve your own data, build the options from your surfaces.config.ts with loadConfig, openSources and serverOptions instead.

In the browser, Chat draws the thread and any component Claude asks for. browserStorage() keeps the conversation across reloads, and user says who is asking, from your own sign-in. Import @surfaces-ui/components/styles.css once in your app's entry file.

App.tsx:

tsx
import { Chat } from "@surfaces-ui/chat";
import { connectAgent, connectDataSource } from "@surfaces-ui/client-connect";
import { DataSourceProvider } from "@surfaces-ui/components";
import { browserStorage } from "@surfaces-ui/state";
// Import "@surfaces-ui/components/styles.css" once in your app's entry file.

// The browser talks to your server only. The model key never leaves it.
const baseUrl = "http://localhost:5220";
const data = connectDataSource({ baseUrl });
const agent = connectAgent({ baseUrl });
const storage = browserStorage();

export function App({ user }: { user: { id: string; name: string } }) {
  return (
    // Components Claude draws (charts, tables, metrics) run their SQL through this DataSource.
    <DataSourceProvider dataSource={data}>
      <Chat
        agent={agent}
        user={user}
        storage={storage}
        starters={["What tables are there?", "Revenue by month in retail", "Which stores sell the most?"]}
      />
    </DataSourceProvider>
  );
}

The test starts the real server on a free port with an Anthropic client whose transport replays recorded server-sent events: Claude calls list_tables, then render_surface, then finishes. It checks that the surface arrives over Connect and that the request Claude received carried the catalog prompt and both tools. It needs no API key, no engine and no network:

claude-chat.test.ts:

ts
import Anthropic from "@anthropic-ai/sdk";
import { createConnectTransport } from "@connectrpc/connect-node";
import { connectAgent } from "@surfaces-ui/client-connect";
import type { SurfacesServer } from "@surfaces-ui/dev-server";
import { A2UI_VERSION, analyticsCatalog, catalogPrompt } from "@surfaces-ui/spec";
import { afterAll, describe, expect, it } from "vitest";
import { createClaudeChatServer } from "./server.js";

/** Server-sent events for one streamed message, as the Messages API sends them. */
function sse(blocks: ({ type: "text"; text: string } | { type: "tool_use"; id: string; name: string; input: unknown })[], stopReason: string): string {
  const events: [string, unknown][] = [
    ["message_start", { type: "message_start", message: { id: "msg_1", type: "message", role: "assistant", model: "claude-sonnet-5-5", content: [], stop_reason: null, usage: { input_tokens: 100, output_tokens: 0 } } }],
  ];
  blocks.forEach((block, index) => {
    if (block.type === "text") {
      events.push(["content_block_start", { type: "content_block_start", index, content_block: { type: "text", text: "" } }]);
      events.push(["content_block_delta", { type: "content_block_delta", index, delta: { type: "text_delta", text: block.text } }]);
    } else {
      events.push(["content_block_start", { type: "content_block_start", index, content_block: { type: "tool_use", id: block.id, name: block.name, input: {} } }]);
      events.push(["content_block_delta", { type: "content_block_delta", index, delta: { type: "input_json_delta", partial_json: JSON.stringify(block.input) } }]);
    }
    events.push(["content_block_stop", { type: "content_block_stop", index }]);
  });
  events.push(["message_delta", { type: "message_delta", delta: { stop_reason: stopReason }, usage: { output_tokens: 20 } }]);
  events.push(["message_stop", { type: "message_stop" }]);
  return events.map(([name, data]) => `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`).join("");
}

/** An Anthropic client whose transport answers each request with the next scripted stream, recording what was sent. */
function scripted(replies: string[]) {
  const sent: Record<string, unknown>[] = [];
  const fetch = async (_url: RequestInfo | URL, init?: RequestInit) => {
    sent.push(JSON.parse(String(init?.body)));
    return new Response(replies.shift() ?? "", { status: 200, headers: { "content-type": "text/event-stream" } });
  };
  return { client: new Anthropic({ apiKey: "test-key", fetch: fetch as typeof globalThis.fetch, maxRetries: 0 }), sent };
}

const surface = [
  { version: A2UI_VERSION, createSurface: { surfaceId: "main", catalogId: analyticsCatalog.id } },
  { version: A2UI_VERSION, updateComponents: { surfaceId: "main", components: [{ id: "root", component: "Text", text: "No sources are set up yet." }] } },
];

let server: SurfacesServer | undefined;
afterAll(async () => server?.close());

describe("chat with Claude over your own data", () => {
  it("serves Claude as AgentService: lists tables, draws a checked surface, and streams the reply", async () => {
    for (const m of surface) expect(analyticsCatalog.validateMessage(m)).toEqual([]);
    const { client, sent } = scripted([
      sse([{ type: "tool_use", id: "tu_1", name: "list_tables", input: {} }], "tool_use"),
      sse([{ type: "text", text: "Here it is." }, { type: "tool_use", id: "tu_2", name: "render_surface", input: { messages: surface } }], "tool_use"),
      sse([{ type: "text", text: " Done." }], "end_turn"),
    ]);
    // No sources and no discovery, so the test needs no engine and downloads nothing.
    server = await createClaudeChatServer({ sources: [], discovery: false }, client);
    const { url } = await server.listen(0);
    const remote = connectAgent({ transport: createConnectTransport({ baseUrl: url, httpVersion: "1.1" }) });

    const events = [];
    for await (const e of remote.send({ input: { case: "text", value: "What data is there?" } })) events.push(e.event);
    const kinds = events.map((e) => e.case);
    expect(kinds).toContain("surface");
    expect(kinds.at(-1)).toBe("done");
    expect(events.filter((e) => e.case === "text").map((e) => (e.value as { delta: string }).delta).join("")).toBe("Here it is. Done.");

    // What Claude received: the catalog prompt, both tools, and the list_tables result.
    const first = sent[0]!;
    expect(first.model).toBe("claude-sonnet-5-5");
    expect((first.system as { text: string }[])[0]!.text).toContain(catalogPrompt(analyticsCatalog));
    expect((first.tools as { name: string }[]).map((t) => t.name).sort()).toEqual(["list_tables", "render_surface"]);
    const toolResult = (sent[1]!.messages as { content: unknown }[]).at(-1)!.content as { type: string; content: string }[];
    expect(toolResult[0]).toMatchObject({ type: "tool_result", tool_use_id: "tu_1" });
    expect(toolResult[0]!.content).toContain("No data sources are configured");
  });
});

Not verified here: a turn against the live Anthropic API, and the browser page running against this server (the test drives connectAgent from Node). The test server has no sources, so list_tables answers that none are configured.

Source and test: apps/recipes/src/claude-chat