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.

3.4 KB
Raw Blame
import * as Schema from "effect/Schema";
import * as Predicate from "effect/Predicate";
import * as NodeHttp from "node:http";

const FixtureParams = Schema.Struct({
  protocolVersion: Schema.optional(Schema.String),
  arguments: Schema.optional(Schema.Struct({ text: Schema.optional(Schema.String) })),
});

const FixtureMessage = Schema.Struct({
  id: Schema.optional(Schema.Json),
  method: Schema.optional(Schema.String),
  params: Schema.optional(FixtureParams),
});

const decodeFixtureMessage = Schema.decodeUnknownSync(FixtureMessage);

type JsonRpcMessage = typeof FixtureMessage.Type;

type FixtureParams = typeof FixtureParams.Type;

const initialize = (params: FixtureParams | undefined) => ({
  protocolVersion: params?.protocolVersion ?? "2025-03-26",
  capabilities: { tools: { listChanged: false } },
  serverInfo: { name: "lifecycle-fixture", version: "1.0.0" },
});

const toolsList = () => ({
  tools: [
    {
      name: "echo",
      description: "Echo the supplied text.",
      inputSchema: { type: "object", properties: { text: { type: "string" } } },
      annotations: { readOnlyHint: true },
    },
  ],
});

const toolsCall = (params: FixtureParams | undefined) => ({
  content: [
    {
      type: "text",
      text: `echo:${params?.arguments?.text ?? ""}`,
    },
  ],
});

type FixtureHandler = (
  params: FixtureParams | undefined,
) => ReturnType<typeof initialize> | ReturnType<typeof toolsList> | ReturnType<typeof toolsCall>;

const METHODS = new Map<string, FixtureHandler>([
  ["initialize", initialize],
  ["tools/list", toolsList],
  ["tools/call", toolsCall],
]);

function respond(message: JsonRpcMessage) {
  if (message.id === undefined) return undefined;
  const handler = METHODS.get(message.method ?? "");

  if (!handler) {
    return {
      jsonrpc: "2.0",
      id: message.id,
      error: { code: -32601, message: "Method not found" },
    };
  }

  return { jsonrpc: "2.0", id: message.id, result: handler(message.params) };
}

export interface HttpMcpFixture {
  readonly url: string;
  readonly close: () => Promise<void>;
}

interface HttpMcpFixtureOptions {
  readonly authorization?: string;
}

/**
 * Streamable HTTP MCP server standing in for a vendor endpoint such as
 * `https://mcp.exa.ai/mcp`. Loopback-only; no real vendor traffic.
 */
export async function startHttpMcpFixture(
  options: HttpMcpFixtureOptions = {},
): Promise<HttpMcpFixture> {
  const server = NodeHttp.createServer((request, response) => {
    if (request.method !== "POST") {
      response.writeHead(405).end();

      return;
    }

    if (options.authorization && request.headers.authorization !== options.authorization) {
      response.writeHead(401).end();

      return;
    }

    let body = "";
    request.on("data", (chunk) => (body += chunk));
    request.on("end", () => {
      const reply = respond(decodeFixtureMessage(JSON.parse(body)));

      if (reply === undefined) {
        response.writeHead(202).end();

        return;
      }

      response.writeHead(200, { "content-type": "application/json" });
      response.end(JSON.stringify(reply));
    });
  });

  await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  const address = server.address();

  if (!address || Predicate.isString(address)) throw new Error("Fixture server has no port.");
  const port = address.port;

  return {
    url: `http://127.0.0.1:${port}/mcp`,
    close: () => new Promise<void>((resolve) => server.close(() => resolve())),
  };
}