Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

15.2 KB
Raw Blame
import * as Match from "effect/Match";
import * as Schema from "effect/Schema";
import {
  environmentId,
  tabId,
  alternateTabId,
  screenshot,
  invocation,
  client,
  TestLayer,
} from "./testUtils/mcpHttpServer.ts";
import { expect, it } from "@effect/vitest";
import { NodeHttpServer } from "@effect/platform-node";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import { McpProtocol, McpSchema, McpServer } from "effect/unstable/ai";
import { HttpBody, HttpClient, HttpRouter, HttpServerResponse } from "effect/unstable/http";
import { PNG } from "pngjs";
import * as McpHttpServer from "./McpHttpServer.ts";
import * as McpInvocationContext from "./McpInvocationContext.ts";
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";

it("normalizes empty successful notification responses to accepted", () => {
  const notificationResponse = McpHttpServer.normalizeMcpHttpResponse(
    HttpServerResponse.text("", { status: 200, contentType: "application/json" }),
  );

  expect(notificationResponse.status).toBe(202);

  const resultResponse = McpHttpServer.normalizeMcpHttpResponse(
    HttpServerResponse.jsonUnsafe({ jsonrpc: "2.0", id: 1, result: {} }),
  );

  expect(resultResponse.status).toBe(200);
});

it("normalizes only conflict-free scalar allOf constraints", () => {
  expect(
    McpHttpServer.normalizeProviderToolInputSchema({
      type: "object",
      properties: {
        url: {
          anyOf: [
            {
              type: "string",
              description: "parent",
              allOf: [
                { pattern: "^https://" },
                { minLength: 1 },
                { maxLength: 100, description: "child" },
              ],
            },
          ],
        },
      },
    } as never),
  ).toEqual({
    type: "object",
    properties: {
      url: {
        anyOf: [
          {
            type: "string",
            description: "parent",
            pattern: "^https://",
            minLength: 1,
            maxLength: 100,
          },
        ],
      },
    },
  });

  for (const schema of [
    { type: "string", allOf: [{ pattern: "^a" }, { pattern: "b$" }] },
    { type: "string", minLength: 2, allOf: [{ minLength: 1 }] },
    { type: "string", allOf: [{ not: { const: "x" } }] },
    { type: "object", allOf: [{ properties: { a: { type: "string" } } }] },
  ]) {
    expect(McpHttpServer.normalizeProviderToolInputSchema(schema as never)).toEqual(schema);
  }
});

it.effect("terminates HTTP MCP sessions with DELETE", () =>
  Effect.scoped(
    Effect.gen(function* () {
      const serverLayer = McpServer.layerHttp({
        name: "MCP termination test",
        version: "1.0.0",
        path: "/mcp",
        protocols: [McpProtocol.v2025_06_18],
      });

      yield* HttpRouter.serve(serverLayer, {
        disableListenLog: true,
        disableLogger: true,
      }).pipe(Layer.build);
      const httpClient = yield* HttpClient.HttpClient;

      const initializeResponse = yield* httpClient.post("/mcp", {
        headers: { accept: "application/json, text/event-stream" },
        body: HttpBody.text(
          `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-test","version":"1.0.0"}}}`,
          "application/json",
        ),
      });

      const sessionId = initializeResponse.headers["mcp-session-id"];
      expect(initializeResponse.status).toBe(200);
      expect(sessionId).not.toBeNull();

      const missingSessionResponse = yield* httpClient.del("/mcp");
      expect(missingSessionResponse.status).toBe(400);

      const unknownSessionResponse = yield* httpClient.del("/mcp", {
        headers: { "mcp-session-id": "unknown-session" },
      });

      expect(unknownSessionResponse.status).toBe(404);

      const terminateResponse = yield* httpClient.del("/mcp", {
        headers: { "mcp-session-id": sessionId! },
      });

      expect(terminateResponse.status).toBe(204);

      const reusedSessionResponse = yield* httpClient.post("/mcp", {
        headers: {
          accept: "application/json, text/event-stream",
          "mcp-session-id": sessionId!,
        },
        body: HttpBody.text(
          `{"jsonrpc":"2.0","id":2,"method":"ping","params":{}}`,
          "application/json",
        ),
      });

      expect(reusedSessionResponse.status).toBe(404);
    }),
  ).pipe(Effect.provide(NodeHttpServer.layerTest)),
);

it.effect("registers annotated tools and preserves authenticated request context", () =>
  Effect.scoped(
    Effect.gen(function* () {
      const server = yield* McpServer.McpServer;
      const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;

      const routedRequests: Array<{
        readonly operation: string;
        readonly tabId?: string | undefined;
      }> = [];

      const events = yield* broker.connect({
        clientId: "mcp-test-client",
        environmentId,
      });

      yield* Stream.runForEach(events, (event) => {
        if (event.type === "connected") return Effect.void;
        routedRequests.push(event.request);

        if (event.request.operation === "navigate") {
          return broker.respond({
            clientId: "mcp-test-client",
            connectionId: event.connectionId,
            requestId: event.request.requestId,
            ok: false,
            error: {
              _tag: "PreviewAutomationExecutionError",
              message: "host cause: provider-secret",
              detail: { token: "provider-secret" },
            },
          });
        }

        return broker.respond({
          clientId: "mcp-test-client",
          connectionId: event.connectionId,
          requestId: event.request.requestId,
          ok: true,
          result: Match.value(event.request.operation).pipe(
            Match.when("snapshot", () => ({
              url: "http://example.test/",
              title: "Example",
              loading: false,
              visibleText: "[email protected] token=secret-value",
              interactiveElements: [],
              accessibilityTree: {},
              consoleEntries: [],
              networkEntries: [],
              actionTimeline: [],
              screenshot: {
                mimeType: "image/png",
                data: screenshot,
                width: 10,
                height: 5,
              },
            })),
            Match.when("evaluate", () => ({
              arbitrary: "unrecognizable-secret",
              chatPath: "/Users/leo/.akeru/chat.json",
              screenshot,
            })),
            Match.when("recordingStop", () => ({
              id: "recording-1",
              tabId,
              path: "/Users/leo/.akeru/browser-artifacts/recording.webm",
              mimeType: "video/webm",
              sizeBytes: 123,
              createdAt: "2026-01-01T00:00:00Z",
            })),
            Match.when("press", () => undefined),
            Match.orElse(() => ({
              available: true,
              visible: true,
              tabId,
              url: "http://example.test/",
              title: "Example",
              loading: false,
            })),
          ),
        });
      }).pipe(Effect.forkScoped);
      yield* Effect.yieldNow;

      const statusTool = server.tools.find(({ tool }) => tool.name === "preview_status");
      expect(statusTool?.tool.annotations?.readOnlyHint).toBe(true);
      expect(statusTool?.tool.annotations?.idempotentHint).toBe(true);
      expect(statusTool?.tool.annotations?.destructiveHint).toBe(false);

      const snapshotTool = server.tools.find(({ tool }) => tool.name === "preview_snapshot");
      expect(snapshotTool?.tool.annotations?.readOnlyHint).toBe(true);
      expect(snapshotTool?.tool.annotations?.idempotentHint).toBe(true);
      expect(snapshotTool?.tool.annotations?.openWorldHint).toBe(true);

      const clickTool = server.tools.find(({ tool }) => tool.name === "preview_click");
      expect(clickTool?.tool.annotations?.readOnlyHint).toBe(false);
      expect(clickTool?.tool.annotations?.destructiveHint).toBe(true);
      expect(clickTool?.tool.annotations?.openWorldHint).toBe(true);
      expect(clickTool?.tool.outputSchema).toEqual({
        type: "object",
        additionalProperties: false,
        description: "The preview action completed successfully.",
      });

      const navigateTool = server.tools.find(({ tool }) => tool.name === "preview_navigate");
      expect(navigateTool?.tool.annotations?.destructiveHint).toBe(false);
      expect(navigateTool?.tool.annotations?.openWorldHint).toBe(true);

      const advertisedString = (toolName: string, field: string) => {
        const registered = server.tools.find(({ tool }) => tool.name === toolName)?.tool;
        expect(registered, `${toolName} must be advertised`).toBeDefined();

        const inputSchema = registered?.inputSchema as {
          readonly properties?: Readonly<Schema.JsonObject>;
        };

        const fieldSchema = inputSchema.properties?.[field] as Schema.JsonObject;

        const variants = Array.isArray(fieldSchema.anyOf)
          ? (fieldSchema.anyOf as Array<Schema.JsonObject>)
          : [fieldSchema];

        return variants.find((variant) => variant.type === "string");
      };

      for (const [toolName, field] of [
        ["preview_navigate", "url"],
        ["preview_press", "key"],
        ["preview_evaluate", "expression"],
      ] as const) {
        const scalar = advertisedString(toolName, field);
        expect(scalar, `${toolName}.${field} must advertise as a string`).toBeDefined();
        expect(scalar?.allOf, `${toolName}.${field} must not expose nested allOf`).toBeUndefined();
      }

      const status = yield* server
        .callTool({ name: "preview_status", arguments: {} })
        .pipe(
          Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
          Effect.provideService(McpSchema.McpServerClient, client),
        );

      expect(status.isError).toBe(false);
      expect(status.structuredContent).toMatchObject({
        available: true,
        tabId,
      });

      const malformed = yield* server
        .callTool({ name: "preview_click", arguments: { selector: "" } })
        .pipe(
          Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
          Effect.provideService(McpSchema.McpServerClient, client),
          Effect.flip,
        );

      expect(malformed._tag).toBe("InvalidParams");

      for (const request of [
        { name: "preview_press", arguments: { key: "" } },
        { name: "preview_evaluate", arguments: { expression: "   " } },
      ]) {
        const invalid = yield* server
          .callTool(request)
          .pipe(
            Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
            Effect.provideService(McpSchema.McpServerClient, client),
            Effect.flip,
          );

        expect(invalid._tag).toBe("InvalidParams");
      }

      const snapshot = yield* server
        .callTool({ name: "preview_snapshot", arguments: { tabId: alternateTabId } })
        .pipe(
          Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
          Effect.provideService(McpSchema.McpServerClient, client),
        );

      expect(snapshot.isError).toBe(false);
      expect(snapshot.content.some((content) => content.type === "image")).toBe(true);
      expect(snapshot.structuredContent).toMatchObject({
        visibleText: "[REDACTED] [REDACTED]",
        screenshot: { mimeType: "image/png", width: 10, height: 5, redacted: true },
      });
      const image = snapshot.content.find((content) => content.type === "image");

      if (!image || image.type !== "image") throw new Error("Expected a redacted snapshot image.");
      const png = PNG.sync.read(Buffer.from(image.data));
      expect([...png.data.subarray(0, 4)]).toEqual([0, 0, 0, 255]);
      expect(routedRequests.find(({ operation }) => operation === "snapshot")?.tabId).toBe(
        alternateTabId,
      );

      const textOnly = yield* server
        .callTool({
          name: "preview_snapshot",
          arguments: { tabId: alternateTabId, includeImage: false },
        })
        .pipe(
          Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
          Effect.provideService(McpSchema.McpServerClient, client),
        );

      expect(textOnly.isError).toBe(false);
      expect(textOnly.content.some((content) => content.type === "image")).toBe(false);
      expect(textOnly.structuredContent).toMatchObject({
        screenshot: { mimeType: "image/png", width: 10, height: 5, redacted: true },
      });

      const evaluation = yield* server
        .callTool({ name: "preview_evaluate", arguments: { expression: "document.body" } })
        .pipe(
          Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
          Effect.provideService(McpSchema.McpServerClient, client),
        );

      expect(evaluation.structuredContent).toEqual({
        redactionStatus: "omitted-unverified-preview-evaluation",
      });
      expect(evaluation.content).toEqual([
        {
          type: "text",
          text: '{"redactionStatus":"omitted-unverified-preview-evaluation"}',
        },
      ]);

      const recording = yield* server
        .callTool({ name: "preview_recording_stop", arguments: {} })
        .pipe(
          Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
          Effect.provideService(McpSchema.McpServerClient, client),
        );

      expect(recording.structuredContent).toMatchObject({ path: "[REDACTED]" });
      expect(recording.content).toEqual([
        {
          type: "text",
          text: '{"id":"recording-1","tabId":"tab-mcp-test","path":"[REDACTED]","mimeType":"video/webm","sizeBytes":123,"createdAt":"2026-01-01T00:00:00Z"}',
        },
      ]);

      const navigation = yield* server
        .callTool({ name: "preview_navigate", arguments: { url: "https://example.test" } })
        .pipe(
          Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
          Effect.provideService(McpSchema.McpServerClient, client),
        );

      expect(navigation.isError).toBe(true);
      expect(navigation.content).toEqual([
        {
          type: "text",
          text: "Preview automation navigate failed on client mcp-test-client.",
        },
      ]);

      const actionRequests = [
        { name: "preview_click", arguments: { x: 10, y: 10 } },
        { name: "preview_type", arguments: { text: "Hello" } },
        { name: "preview_press", arguments: { key: "Enter" } },
        { name: "preview_scroll", arguments: { deltaY: 100 } },
        { name: "preview_wait_for", arguments: { text: "Example" } },
      ];

      for (const request of actionRequests) {
        const result = yield* server
          .callTool(request)
          .pipe(
            Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
            Effect.provideService(McpSchema.McpServerClient, client),
          );

        expect(result.isError).toBe(false);
        expect(result.structuredContent).toEqual({});
        expect(result.content).toEqual([{ type: "text", text: "{}" }]);
      }
    }),
  ).pipe(Effect.provide(TestLayer)),
);