Skip to content
Myr

mcp.test.ts

This file

Path

packages/protocol/test/mcp.test.ts

453 lines · 13.5 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import { Context, Effect, Layer, Option, Schema } from "effect";3import { Tool } from "effect/ai";4import { Rpc, RpcGroup } from "effect/rpc";56import { Description, NeedsApproval } from "../src/annotations.ts";7import {8  Client,9  Contracts,10  ListAsks,11  SubmitAnswer,12  surfaced,13} from "../src/contracts.ts";14import { PROJECT_DESCRIPTION_CAP } from "../src/domain/front-page.ts";15import { RECENT_LANDINGS_CAP } from "../src/domain/recent-landing.ts";16import { AskId, CommitSha, KindName, ProjectName } from "../src/ids.ts";17import { listTools, toJsonSchema, toToolkit } from "../src/mcp.ts";18import { Refusal, StaleBase } from "../src/refusal.ts";19import { unanswered } from "../src/testing.ts";20import { ask, base, main, path } from "./examples.ts";21import { leaks, nested } from "./leaks.ts";22import { serve } from "./mcp.ts";2324const head = CommitSha.make("3333333333333333333333333333333333333333");2526const project = ProjectName.make("oscabriel/datekit");2728const answer = { ask, base, head, project, requestId: "answer-0001" };2930const ToolResult = Schema.Struct({31  content: Schema.Tuple([32    Schema.Struct({33      text: Schema.fromJsonString(Schema.Unknown),34      type: Schema.Literal("text"),35    }),36  ]),37  isError: Schema.Boolean,38});3940const stale = (refusal: StaleBase) =>41  Layer.mergeAll(42    unanswered,43    Contracts.toLayerHandler("submitAnswer", () => Effect.fail(refusal))44  );4546const ToolList = Schema.Struct({47  tools: Schema.Array(48    Schema.Struct({49      description: Schema.String,50      inputSchema: Schema.Struct({51        required: Schema.optionalKey(Schema.Array(Schema.String)),52      }),53      name: Schema.String,54    })55  ),56});5758const HintedTools = Schema.Struct({59  tools: Schema.Array(60    Schema.Struct({61      annotations: Schema.Struct({62        destructiveHint: Schema.Boolean,63        idempotentHint: Schema.Boolean,64        openWorldHint: Schema.Boolean,65        readOnlyHint: Schema.Boolean,66      }),67      name: Schema.String,68    })69  ),70});7172const ListedTools = Schema.Struct({73  tools: Schema.Array(74    Schema.Struct({75      annotations: Schema.Unknown,76      description: Schema.String,77      inputSchema: Schema.Unknown,78      name: Schema.String,79      outputSchema: Schema.Unknown,80    })81  ),82});8384const ProjectDescriptionSchema = Schema.Struct({85  maxLength: Schema.Int,86  type: Schema.Literal("string"),87});8889const LandingsSchema = Schema.Struct({90  minimum: Schema.Int,91  type: Schema.Literal("integer"),92});9394/** A project's listing in a JSON Schema, its description's and landings' schemas beside what it requires. */95const ListingSchema = Schema.Struct({96  properties: Schema.Struct({97    description: ProjectDescriptionSchema,98    landings: LandingsSchema,99  }),100  required: Schema.Array(Schema.String),101});102103const decodeListingSchema = Schema.decodeUnknownOption(ListingSchema);104105/** An object in a JSON Schema: what it holds and which of it it requires. */106const ObjectSchema = Schema.Struct({107  properties: Schema.Record(Schema.String, Schema.Json),108  required: Schema.Array(Schema.String),109});110111const decodeObjectSchema = Schema.decodeUnknownOption(ObjectSchema);112113const ArraySchema = Schema.Struct({114  maxItems: Schema.Int,115  type: Schema.Literal("array"),116});117118const decodeArraySchema = Schema.decodeUnknownOption(ArraySchema);119120const receipt = {121  additionalProperties: true,122  properties: { main: { pattern: "^[0-9a-f]{40}$", type: "string" } },123  required: ["main"],124  type: "object",125};126127describe("the contracts as MCP tools", () => {128  it.effect(129    "lists each MCP-surfaced contract as a tool, its payload as the input",130    () =>131      Effect.gen(function* () {132        const mcp = yield* serve(unanswered);133134        const { tools } = yield* mcp.call("tools/list", {}, ToolList);135136        const byName = new Map(tools.map((tool) => [tool.name, tool]));137138        expect(tools.map(({ name }) => name)).toStrictEqual([139          ...surfaced("mcp").requests.keys(),140        ]);141        expect(byName.get("listAsks")).toStrictEqual({142          description: Context.get(ListAsks.annotations, Description),143          inputSchema: { required: ["project"] },144          name: "listAsks",145        });146        expect(byName.get("submitAnswer")).toStrictEqual({147          description: Context.get(SubmitAnswer.annotations, Description),148          inputSchema: {149            required: ["ask", "base", "head", "project", "requestId"],150          },151          name: "submitAnswer",152        });153      })154  );155156  it.effect(157    "offers no tool for watching a project, setting a value or reading a log",158    () =>159      Effect.gen(function* () {160        const mcp = yield* serve(unanswered);161162        const { tools } = yield* mcp.call("tools/list", {}, ToolList);163164        const names = tools.map(({ name }) => name);165166        expect(names).toContain("listProjects");167        expect(names).not.toContain("watch");168        expect(names).not.toContain("setEnv");169        expect(names).not.toContain("evidence");170      })171  );172173  it.effect(174    "hints that listing asks only reads, and that an answer can be offered again",175    () =>176      Effect.gen(function* () {177        const mcp = yield* serve(unanswered);178179        const { tools } = yield* mcp.call("tools/list", {}, HintedTools);180181        expect(182          tools.filter(({ name }) =>183            ["listAsks", "submitAnswer"].includes(name)184          )185        ).toStrictEqual([186          {187            annotations: {188              destructiveHint: false,189              idempotentHint: true,190              openWorldHint: false,191              readOnlyHint: true,192            },193            name: "listAsks",194          },195          {196            annotations: {197              destructiveHint: false,198              idempotentHint: true,199              openWorldHint: false,200              readOnlyHint: false,201            },202            name: "submitAnswer",203          },204        ]);205      })206  );207208  it.effect(209    "offers the capped code reads as tools that only read, and neither a commit's diff nor every path",210    () =>211      Effect.gen(function* () {212        const mcp = yield* serve(unanswered);213214        const { tools } = yield* mcp.call("tools/list", {}, HintedTools);215216        const names = tools.map(({ name }) => name);217218        expect(219          tools220            .filter(({ name }) =>221              ["listRefs", "log", "readFile", "readTree", "why"].includes(name)222            )223            .map(({ annotations, name }) => ({224              idempotentHint: annotations.idempotentHint,225              name,226              readOnlyHint: annotations.readOnlyHint,227            }))228        ).toStrictEqual(229          ["listRefs", "readTree", "readFile", "log", "why"].map((name) => ({230            idempotentHint: true,231            name,232            readOnlyHint: true,233          }))234        );235        expect(names).not.toContain("showCommit");236        expect(names).not.toContain("listPaths");237      })238  );239240  it.effect("lists each tool exactly as listTools describes it", () =>241    Effect.gen(function* () {242      const mcp = yield* serve(unanswered);243244      const { tools } = yield* mcp.call("tools/list", {}, ListedTools);245246      expect(tools).toStrictEqual(247        listTools(toToolkit(surfaced("mcp"), Effect.service(Client)).toolkit)248      );249    })250  );251252  it("finds both of Effect's known JSON Schema leaks", () => {253    const leaky = Schema.toJsonSchemaDocument(254      Schema.Struct({255        count: Schema.Number,256        note: Schema.optional(Schema.String),257      })258    );259260    expect(261      leaks(Schema.decodeUnknownSync(Schema.Json)(leaky.schema))262    ).toStrictEqual([263      "null under optional key note",264      "non-finite string Infinity",265      "non-finite string -Infinity",266      "non-finite string NaN",267    ]);268  });269270  it("gives every tool an input and an output schema, with no leak in either", () => {271    const tools = listTools(272      toToolkit(surfaced("mcp"), Effect.service(Client)).toolkit273    );274275    const schemas = tools.flatMap(({ inputSchema, outputSchema }) =>276      [inputSchema, outputSchema].map((schema) =>277        Schema.decodeUnknownSync(Schema.Json)(schema)278      )279    );280281    expect(tools.length).toBeGreaterThan(20);282    expect(schemas).toHaveLength(2 * tools.length);283    expect(schemas.flatMap(leaks)).toStrictEqual([]);284  });285286  it("lists each project with an optional description, capped in length, and an optional count of landings", () => {287    const listProjects = listTools(288      toToolkit(surfaced("mcp"), Effect.service(Client)).toolkit289    ).find(({ name }) => name === "listProjects");290291    const listings = nested(292      Schema.decodeUnknownSync(Schema.Json)(listProjects?.outputSchema)293    ).flatMap((node) => Option.toArray(decodeListingSchema(node)));294295    expect(296      listings.map(({ properties }) => properties.description)297    ).toStrictEqual([{ maxLength: PROJECT_DESCRIPTION_CAP, type: "string" }]);298    expect(listings.map(({ properties }) => properties.landings)).toStrictEqual(299      [{ minimum: 0, type: "integer" }]300    );301    expect(listings.flatMap(({ required }) => required)).not.toContain(302      "description"303    );304    expect(listings.flatMap(({ required }) => required)).not.toContain(305      "landings"306    );307  });308309  it("lists the latest landings across projects as a tool that only reads, at most a cap of them, each refusal by its tag and area alone", () => {310    const recent = listTools(311      toToolkit(surfaced("mcp"), Effect.service(Client)).toolkit312    ).find(({ name }) => name === "recentLandings");313314    const nodes = nested(315      Schema.decodeUnknownSync(Schema.Json)(recent?.outputSchema)316    );317318    const refusals = nodes319      .flatMap((node) => Option.toArray(decodeObjectSchema(node)))320      .filter(({ properties }) => "tag" in properties);321322    expect(recent?.annotations).toMatchObject({323      destructiveHint: false,324      readOnlyHint: true,325    });326    // A non-empty array lists its first item apart from the rest: one shape, twice.327    expect(328      new Set(329        refusals.map(330          ({ properties, required }) =>331            `${Object.keys(properties).toSorted().join(", ")}; requires ${required.join(", ")}`332        )333      )334    ).toStrictEqual(new Set(["area, tag; requires tag"]));335    expect(336      nodes.flatMap((node) => Option.toArray(decodeArraySchema(node)))337    ).toContainEqual({ maxItems: RECENT_LANDINGS_CAP, type: "array" });338    // An agent reads the closed set of tags, not any string.339    expect(refusals.map(({ properties }) => properties.tag)).toStrictEqual(340      refusals.map(() => ({341        enum: Refusal.members.map(({ identifier }) => identifier),342        type: "string",343      }))344    );345  });346347  it("inlines a named root schema, since MCP wants an object at the root", () => {348    expect(349      toJsonSchema(350        Schema.Struct({ main: CommitSha }).annotate({ identifier: "Receipt" })351      )352    ).toStrictEqual({ ...receipt, $defs: { Receipt: receipt } });353  });354355  // The pointer to "Answer receipt" is `#/$defs/Answer%20receipt`.356  it("inlines a named root whose pointer is percent-encoded", () => {357    expect(358      toJsonSchema(359        Schema.Struct({ main: CommitSha }).annotate({360          identifier: "Answer receipt",361        })362      )363    ).toStrictEqual({ ...receipt, $defs: { "Answer receipt": receipt } });364  });365366  it("tells the agent a person approves a contract that needs approval", () => {367    class Abandon extends Rpc.make("abandon", {368      payload: { project: ProjectName },369    })370      .annotate(Description, "Abandon a project.")371      .annotate(NeedsApproval, true) {}372373    const { toolkit } = toToolkit(374      RpcGroup.make(Abandon),375      Effect.die("a listing calls no tool")376    );377378    expect(Tool.getDescription(toolkit.tools.abandon)).toBe(379      "Abandon a project. Asks a person first."380    );381  });382383  it.effect("returns a refusal as JSON that keeps its tag", () =>384    Effect.gen(function* () {385      const refusal = new StaleBase({ base, conflicts: [path], main });386387      const mcp = yield* serve(stale(refusal));388389      const result = yield* mcp.call(390        "tools/call",391        { arguments: answer, name: "submitAnswer" },392        ToolResult393      );394395      const [{ text }] = result.content;396397      expect(result.isError).toBeTruthy();398      expect(text).toHaveProperty("_tag", "StaleBase");399      expect(yield* Schema.decodeUnknownEffect(StaleBase)(text)).toStrictEqual(400        refusal401      );402    })403  );404405  it.effect("returns a contract's success as structured content", () =>406    Effect.gen(function* () {407      const mcp = yield* serve(408        Layer.mergeAll(409          unanswered,410          Contracts.toLayerHandler("listAsks", () =>411            Effect.succeed({412              asks: [413                {414                  ask: AskId.make("fix-parser"),415                  blockedBy: [],416                  claimed: false,417                  kind: KindName.make("fix"),418                  territory: "packages/parser",419                  want: "Parse a trailing comma",420                },421              ],422            })423          )424        )425      );426427      const result = yield* mcp.call(428        "tools/call",429        { arguments: { project: "oscabriel/demo" }, name: "listAsks" },430        Schema.Struct({431          isError: Schema.Boolean,432          structuredContent: Schema.Unknown,433        })434      );435436      expect(result).toStrictEqual({437        isError: false,438        structuredContent: {439          asks: [440            {441              ask: "fix-parser",442              blockedBy: [],443              claimed: false,444              kind: "fix",445              territory: "packages/parser",446              want: "Parse a trailing comma",447            },448          ],449        },450      });451    })452  );453});