Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

10.2 KB
Raw Blame
import { afterEach, describe, expect, it } from "vitest";

import { McpRpcError, RemoteMcpClient, bypassesProxy, plainHttpProxyFetch } from "./mcp-http.ts";
import { startFakeHttpMcp, type FakeHttpMcp } from "./testing/fake-http-mcp-server.ts";

let fake: FakeHttpMcp | undefined;
let client: RemoteMcpClient | undefined;
afterEach(async () => {
  await client?.close(); client = undefined;
  await fake?.close(); fake = undefined;
});

describe("request cancellation", () => {
  it.each(["initialize", "tools/list", "tools/call"])("cancels an HTTP wait for %s with only eligible notifications", async (method) => {
    const frames: unknown[] = [];
    client = new RemoteMcpClient({ type: "http", url: "https://fixture.example/mcp", headers: {} }, { fetch: async (_url, init) => {
      const frame = JSON.parse(String(init?.body));
      frames.push(frame);
      if (frame.method === "notifications/cancelled") return new Response(null, { status: 202 });
      return new Promise<Response>((_resolve, reject) => {
        init?.signal?.addEventListener("abort", () => reject(new Error("cancelled locally")), { once: true });
      });
    } });
    const controller = new AbortController();
    const request = client.request(method, {}, controller.signal);
    controller.abort();
    await expect(request).rejects.toThrow("cancelled locally");
    expect(frames).toEqual([
      { jsonrpc: "2.0", method, id: 1, params: {} },
      ...(method === "initialize" ? [] : [{ jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: 1, reason: "Request cancelled" } }]),
    ]);
  });
});

describe("a server's own requests to the client", () => {
  it("does not charge earlier SSE replies against a later request's byte limit", async () => {
    fake = await startFakeHttpMcp({ transport: "sse", tools: [{ name: "still_available" }] });
    client = new RemoteMcpClient({ type: "sse", url: fake.url, headers: {} }, { maxBytes: 512 });
    await client.initialize("fixture", AbortSignal.timeout(5_000));
    for (let i = 0; i < 20; i++) {
      await expect(client.request("tools/list", {}, AbortSignal.timeout(1_000))).resolves.toEqual({ tools: [{ name: "still_available" }] });
    }
    expect(fake.toolsLists).toBe(20);
  });

  it("keeps the shared SSE stream alive after the opening request's signal expires", async () => {
    fake = await startFakeHttpMcp({ transport: "sse", tools: [{ name: "still_available" }] });
    let streamSignal: AbortSignal | null | undefined;
    client = new RemoteMcpClient({ type: "sse", url: fake.url, headers: {} }, { fetch: (url, init) => {
      if (init?.method === "GET") streamSignal = init.signal;
      return fetch(url, init);
    } });
    const opening = new AbortController();
    await client.initialize("fixture", opening.signal);
    opening.abort();
    await expect(client.request("tools/list", {}, AbortSignal.timeout(1_000))).resolves.toEqual({ tools: [{ name: "still_available" }] });
    expect(streamSignal?.aborted).toBe(false);
    await client.close();
    expect(streamSignal?.aborted).toBe(true);
  });

  it("still aborts an SSE connection before the endpoint arrives", async () => {
    let streamSignal: AbortSignal | null | undefined;
    client = new RemoteMcpClient({ type: "sse", url: "https://fixture.example/sse", headers: {} }, { fetch: async (_url, init) => {
      streamSignal = init?.signal;
      return new Promise<Response>((_resolve, reject) => {
        streamSignal?.addEventListener("abort", () => reject(new Error("opening cancelled")), { once: true });
      });
    } });
    const opening = new AbortController();
    const reply = client.request("initialize", {}, opening.signal);
    opening.abort();
    await expect(reply).rejects.toThrow("aborted");
    expect(streamSignal?.aborted).toBe(true);
  });

  it("finds a JSON batch response after a server request with the same ID, including a null result", async () => {
    const replies: unknown[] = [];
    client = new RemoteMcpClient({ type: "http", url: "https://fixture.example/mcp", headers: {} }, { fetch: async (_url, init) => {
      const frame = JSON.parse(String(init?.body)) as { id?: number; method?: string };
      if (frame.method) return new Response(JSON.stringify([
        { jsonrpc: "2.0", id: frame.id, method: "ping" },
        { jsonrpc: "2.0", id: frame.id, result: null },
      ]), { headers: { "content-type": "application/json" } });
      replies.push(frame);
      return new Response(null, { status: 202 });
    } });
    await expect(client.request("tools/list", {}, AbortSignal.timeout(1_000))).resolves.toBeNull();
    expect(replies).toEqual([{ jsonrpc: "2.0", id: 1, result: {} }]);
  });

  it.each(["http", "sse"] as const)("do not complete a client request with the same numeric ID over %s", async (transport) => {
    fake = await startFakeHttpMcp({ transport, tools: [{ name: "ask_first" }], askOnCall: "ping", askId: 2 });
    client = new RemoteMcpClient({ type: transport, url: fake.url, headers: {} });
    await client.initialize("fixture", AbortSignal.timeout(5_000));
    const result = await client.request("tools/call", { name: "ask_first", arguments: {} }, AbortSignal.timeout(5_000));
    expect(result).toEqual({ content: [{ type: "text", text: "remote execution recorded" }] });
    expect(fake.replies).toEqual([{ jsonrpc: "2.0", id: 2, result: {} }]);
  });

  it.each(["http", "sse"] as const)("are refused at once over %s, so the call they interrupt still finishes", async (transport) => {
    fake = await startFakeHttpMcp({ transport, tools: [{ name: "ask_first", inputSchema: { type: "object" } }], askOnCall: "elicitation/create" });
    client = new RemoteMcpClient({ type: transport, url: fake.url, headers: {} });
    await client.initialize("fixture", AbortSignal.timeout(5_000));
    // without an answer the server holds the result until this deadline
    const result = await client.request("tools/call", { name: "ask_first", arguments: {} }, AbortSignal.timeout(5_000));
    expect(result).toEqual({ content: [{ type: "text", text: "remote execution recorded" }] });
    expect(fake.replies).toEqual([{ jsonrpc: "2.0", id: "server-ask-1", error: { code: -32601, message: "Method not supported by this client" } }]);
  });

  it.each(["http", "sse"] as const)("include a ping, which gets its empty answer over %s", async (transport) => {
    fake = await startFakeHttpMcp({ transport, tools: [{ name: "ask_first", inputSchema: { type: "object" } }], askOnCall: "ping" });
    client = new RemoteMcpClient({ type: transport, url: fake.url, headers: {} });
    await client.initialize("fixture", AbortSignal.timeout(5_000));
    await client.request("tools/call", { name: "ask_first", arguments: {} }, AbortSignal.timeout(5_000));
    expect(fake.replies).toEqual([{ jsonrpc: "2.0", id: "server-ask-1", result: {} }]);
  });
});

describe("a server's JSON-RPC error", () => {
  it.each(["http", "sse"] as const)("keeps its code and words over %s, apart from transport failures", async (transport) => {
    fake = await startFakeHttpMcp({ transport, tools: [{ name: "report" }], callError: () => ({ code: -32602, message: "Missing required parameter 'campaignId'" }) });
    client = new RemoteMcpClient({ type: transport, url: fake.url, headers: {} });
    await client.initialize("fixture", AbortSignal.timeout(5_000));
    const failure = await client.request("tools/call", { name: "report", arguments: {} }, AbortSignal.timeout(5_000)).catch((error: unknown) => error);
    expect(failure).toBeInstanceOf(McpRpcError);
    expect(failure).toMatchObject({ kind: "protocol", code: -32602, detail: "Missing required parameter 'campaignId'" });
  });
});

describe("the protocol version the server answers with", () => {
  it.each([
    { echo: "2026-07-28", wire: "2025-06-18" },
    { echo: "2024-11-05", wire: "2024-11-05" },
  ])("puts $wire, not the echoed $echo, on later requests", async ({ echo, wire }) => {
    fake = await startFakeHttpMcp({ tools: [{ name: "still_available" }], protocolVersion: echo });
    client = new RemoteMcpClient({ type: "http", url: fake.url, headers: {} });
    await client.initialize("fixture", AbortSignal.timeout(5_000));
    await client.request("tools/list", {}, AbortSignal.timeout(5_000));
    for (const headers of fake.seenHeaders.slice(1)) expect(headers["mcp-protocol-version"]).toBe(wire);
  });
});

describe("which plain http requests go through HTTP_PROXY", () => {
  it("skips loopback and NO_PROXY hosts the way curl does", () => {
    const at = (url: string, list = "") => bypassesProxy(new URL(url), list);
    for (const url of ["http://localhost:3000/mcp", "http://127.0.0.1/mcp", "http://127.8.0.1/mcp", "http://[::1]:8080/mcp", "http://app.localhost/mcp"]) expect(at(url)).toBe(true);
    expect(at("http://mcp.corp.internal/mcp")).toBe(false);
    expect(at("http://mcp.corp.internal/mcp", "corp.internal")).toBe(true);
    expect(at("http://mcp.corp.internal/mcp", ".corp.internal")).toBe(true);
    expect(at("http://mcp.corp.internal/mcp", "*.corp.internal")).toBe(true);
    expect(at("http://mcp.corp.internal/mcp", "*")).toBe(true);
    expect(at("http://mcp.corp.internal/mcp", "other.internal, ,corp.internal:8080")).toBe(false);
    expect(at("http://mcp.corp.internal:8080/mcp", "corp.internal:8080")).toBe(true);
    expect(at("http://notcorp.internal/mcp", "corp.internal")).toBe(false);
    expect(at("http://[fd00::1]/mcp", "[fd00::1]")).toBe(true);
  });

  it("is only set up when an HTTP proxy is", () => {
    expect(plainHttpProxyFetch({})).toBeUndefined();
    expect(plainHttpProxyFetch({ HTTPS_PROXY: "http://proxy.example.test:3128" })).toBeUndefined();
    expect(plainHttpProxyFetch({ HTTP_PROXY: "proxy.example.test:3128" })).toBeTypeOf("function");
  });

  it("leaves https and exempt requests to fetch", async () => {
    const seen: string[] = [];
    const fallback = (async (input: string | URL | Request) => { seen.push(String(input)); return new Response("{}"); }) as typeof fetch;
    const viaProxy = plainHttpProxyFetch({ HTTP_PROXY: "http://127.0.0.1:9", NO_PROXY: "corp.internal" }, fallback)!;
    await viaProxy("https://mcp.example.test/mcp");
    await viaProxy("http://mcp.corp.internal/mcp");
    await viaProxy("http://127.0.0.1:4000/mcp");
    expect(seen).toEqual(["https://mcp.example.test/mcp", "http://mcp.corp.internal/mcp", "http://127.0.0.1:4000/mcp"]);
  });
});