Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

4.5 KB
Raw Blame
import http from "node:http";

let server: http.Server | null = null;

type MockLlmToolCall = {
  name: string;
  input: Record<string, unknown>;
};

type MockLlmServerOptions =
  | {
      port: number;
      responseText: string;
      toolCall?: never;
    }
  | {
      port: number;
      responseText?: never;
      toolCall: MockLlmToolCall;
    };

/**
 * Build a raw Anthropic SSE response that streams the given text as a single
 * content_block_delta and then closes the message cleanly.
 *
 * The format follows the Anthropic /v1/messages streaming specification:
 * https://docs.anthropic.com/en/api/messages-streaming
 */
function buildAnthropicSSE(text: string): string {
  const lines = [
    "event: message_start",
    `data: ${JSON.stringify({ type: "message_start", message: { id: "msg_mock", type: "message", role: "assistant", content: [], model: "claude-haiku-4-5", stop_reason: null, usage: { input_tokens: 10, output_tokens: 0 } } })}`,
    "",
    "event: content_block_start",
    `data: ${JSON.stringify({ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } })}`,
    "",
    "event: content_block_delta",
    `data: ${JSON.stringify({ type: "content_block_delta", index: 0, delta: { type: "text_delta", text } })}`,
    "",
    "event: content_block_stop",
    `data: ${JSON.stringify({ type: "content_block_stop", index: 0 })}`,
    "",
    "event: message_delta",
    `data: ${JSON.stringify({ type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 8 } })}`,
    "",
    "event: message_stop",
    `data: ${JSON.stringify({ type: "message_stop" })}`,
    "",
  ];
  return lines.join("\n");
}

function buildAnthropicToolUseSSE({ name, input }: MockLlmToolCall): string {
  const lines = [
    "event: message_start",
    `data: ${JSON.stringify({ type: "message_start", message: { id: "msg_mock", type: "message", role: "assistant", content: [], model: "claude-haiku-4-5", stop_reason: null, usage: { input_tokens: 10, output_tokens: 0 } } })}`,
    "",
    "event: content_block_start",
    `data: ${JSON.stringify({ type: "content_block_start", index: 0, content_block: { type: "tool_use", id: "toolu_mock", name, input: {} } })}`,
    "",
    "event: content_block_delta",
    `data: ${JSON.stringify({ type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: JSON.stringify(input) } })}`,
    "",
    "event: content_block_stop",
    `data: ${JSON.stringify({ type: "content_block_stop", index: 0 })}`,
    "",
    "event: message_delta",
    `data: ${JSON.stringify({ type: "message_delta", delta: { stop_reason: "tool_use", stop_sequence: null }, usage: { output_tokens: 8 } })}`,
    "",
    "event: message_stop",
    `data: ${JSON.stringify({ type: "message_stop" })}`,
    "",
  ];
  return lines.join("\n");
}

const MOCK_MODEL_CATALOG = [
  { id: "claude-haiku-4-5", display_name: "Claude Haiku 4.5" },
  { id: "claude-sonnet-4-6", display_name: "Claude Sonnet 4.6" },
];

/**
 * Start a mock server that impersonates the Anthropic API.
 *
 * GET /v1/models responds with a static model catalog (used by the provider
 * credential validation when connecting). Every other request responds with a
 * valid /v1/messages SSE stream containing either the given `responseText` or
 * a tool-use call. The server listens on `port`.
 *
 * Call `stopMockLlmServer` to tear it down.
 */
export function startMockLlmServer(
  options: MockLlmServerOptions,
): Promise<null> {
  const { port } = options;

  return new Promise((resolve, reject) => {
    if (server) {
      server.close();
      server = null;
    }

    const response = options.toolCall
      ? buildAnthropicToolUseSSE(options.toolCall)
      : buildAnthropicSSE(options.responseText);

    server = http.createServer((req, res) => {
      if (req.method === "GET" && req.url?.includes("/models")) {
        res.writeHead(200, { "content-type": "application/json" });
        res.end(JSON.stringify({ data: MOCK_MODEL_CATALOG }));
        return;
      }

      res.writeHead(200, {
        "content-type": "text/event-stream",
        "cache-control": "no-cache",
        connection: "keep-alive",
      });
      res.end(response);
    });

    server.on("error", reject);
    server.listen(port, () => resolve(null));
  });
}

/**
 * Stop the mock LLM server started by `startMockLlmServer`.
 */
export function stopMockLlmServer(): Promise<null> {
  return new Promise((resolve) => {
    if (server) {
      server.close(() => resolve(null));
      server = null;
    } else {
      resolve(null);
    }
  });
}