From b5b84f398fb3059b72e3a54c2bb36ded7b117bc8 Mon Sep 17 00:00:00 2001 From: Cycle Five Date: Thu, 19 Nov 2026 17:18:56 -0500 Subject: [PATCH 1/9] feat: broker-core with shared utilities and tool types (0.3.0) Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) --- README.md | 6 +- brokers/discord/package.json | 3 +- brokers/discord/src/auth.ts | 14 +--- brokers/discord/src/index.ts | 9 +-- brokers/discord/src/tools.ts | 70 ++----------------- brokers/discord/test/flow.test.ts | 22 +----- brokers/discord/vitest.config.ts | 13 +--- brokers/github/package.json | 3 +- brokers/github/src/auth.ts | 7 +- brokers/github/src/github/app.ts | 9 +-- brokers/github/src/index.ts | 11 +-- brokers/github/src/tools.ts | 66 +---------------- brokers/github/test/flow.test.ts | 22 +----- .../github/test/stubs/cloudflare-workers.ts | 8 --- brokers/github/test/tools.test.ts | 11 +-- brokers/github/vitest.config.ts | 13 +--- package-lock.json | 26 +++++-- package.json | 2 +- packages/core/package.json | 19 +++++ packages/core/src/index.ts | 4 ++ packages/core/src/tools.ts | 66 +++++++++++++++++ packages/core/src/util.ts | 17 +++++ packages/core/src/version.ts | 1 + .../core/test-support}/cloudflare-workers.ts | 0 packages/core/test-support/index.ts | 22 ++++++ packages/core/test/tools.test.ts | 32 +++++++++ packages/core/test/util.test.ts | 17 +++++ packages/core/test/version.test.ts | 10 +++ packages/core/tsconfig.json | 1 + packages/core/vitest.config.ts | 4 ++ vitest.shared.ts | 16 +++++ 31 files changed, 260 insertions(+), 264 deletions(-) delete mode 100644 brokers/github/test/stubs/cloudflare-workers.ts create mode 100644 packages/core/package.json create mode 100644 packages/core/src/index.ts create mode 100644 packages/core/src/tools.ts create mode 100644 packages/core/src/util.ts create mode 100644 packages/core/src/version.ts rename {brokers/discord/test/stubs => packages/core/test-support}/cloudflare-workers.ts (100%) create mode 100644 packages/core/test-support/index.ts create mode 100644 packages/core/test/tools.test.ts create mode 100644 packages/core/test/util.test.ts create mode 100644 packages/core/test/version.test.ts create mode 100644 packages/core/tsconfig.json create mode 100644 packages/core/vitest.config.ts create mode 100644 vitest.shared.ts diff --git a/README.md b/README.md index 1df45b4..dbf5efa 100644 --- a/README.md +++ b/README.md @@ -14,11 +14,15 @@ allowlist, without ever exposing the upstream token or key. ``` brokers/discord Discord broker Worker brokers/github GitHub broker Worker -packages/ shared packages (none yet) +packages/core broker-core: code both brokers share ``` One npm workspace; `npm install` at the root installs everything. +## What is shared + +`packages/core` (`broker-core`) holds what both brokers use: the version number (`VERSION`), `publicUrl`, `required` and `base64url`, the tool types with `ToolInputError`, `validateArgs` and `truncate`, and, under `broker-core/testing`, the in-memory KV the flow tests use. `vitest.shared.ts` holds the test settings every package shares, including the Node stand-in for `cloudflare:workers`. Every `package.json` states the same version, and a core test checks that. + ## Commands ```sh diff --git a/brokers/discord/package.json b/brokers/discord/package.json index f2a6bc5..9c148e9 100644 --- a/brokers/discord/package.json +++ b/brokers/discord/package.json @@ -1,6 +1,6 @@ { "name": "discord-broker", - "version": "0.2.0", + "version": "0.3.0", "private": true, "license": "MIT", "description": "Remote MCP server on Cloudflare Workers that brokers a Discord bot without exposing its token", @@ -13,6 +13,7 @@ "cf-typegen": "wrangler types" }, "dependencies": { + "broker-core": "*", "@cloudflare/workers-oauth-provider": "1.2.4" } } diff --git a/brokers/discord/src/auth.ts b/brokers/discord/src/auth.ts index 33fb4e8..871e51f 100644 --- a/brokers/discord/src/auth.ts +++ b/brokers/discord/src/auth.ts @@ -10,6 +10,7 @@ import { type ConsentDescription, type OAuthHelpers, } from "@cloudflare/workers-oauth-provider"; +import { VERSION, base64url, publicUrl } from "broker-core"; import type { Env } from "./env"; export const SCOPE = "discord"; @@ -39,12 +40,6 @@ export function isAllowed(raw: string | undefined, user: { id: string | number } return parseAllowlist(raw).ids.has(String(user.id)); } -export function base64url(bytes: Uint8Array): string { - let bin = ""; - for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]); - return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); -} - /** Catch the usual configuration mix-ups before sending anyone to Discord, which answers them with an unhelpful page. */ export function configProblem(env: Env): string | null { const cid = env.DISCORD_CLIENT_ID ?? ""; @@ -278,13 +273,6 @@ export async function exchangeDiscordCode( return { ok: true, id: user.id, username: user.username }; } -export const VERSION = "0.2.0"; - export function userAgent(env: Env): string { return `DiscordBot (${env.PUBLIC_URL || "https://github.com/cycle-five"}, ${VERSION}) discord-broker`; } - -export function publicUrl(env: Env): string { - if (!env.PUBLIC_URL) throw new Error("PUBLIC_URL is not set"); - return env.PUBLIC_URL.replace(/\/+$/, ""); -} diff --git a/brokers/discord/src/index.ts b/brokers/discord/src/index.ts index c2c668a..bf7f84d 100644 --- a/brokers/discord/src/index.ts +++ b/brokers/discord/src/index.ts @@ -12,7 +12,8 @@ import { insufficientScope, type OAuthResourceContext, } from "@cloudflare/workers-oauth-provider"; -import { AuthProps, SCOPE, VERSION, handleAuthorize, handleCallback, isAllowed, publicUrl, userAgent } from "./auth"; +import { VERSION, publicUrl, required } from "broker-core"; +import { AuthProps, SCOPE, handleAuthorize, handleCallback, isAllowed, userAgent } from "./auth"; import { DiscordClient } from "./discord/client"; import { Scope } from "./discord/scope"; import type { Env } from "./env"; @@ -83,12 +84,6 @@ function getRoles(env: Env): Roles { return roles; } -function required(env: Env, key: keyof Env): string { - const v = env[key]; - if (typeof v !== "string" || !v) throw new Error(`${key} is not set`); - return v; -} - export default { async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { try { diff --git a/brokers/discord/src/tools.ts b/brokers/discord/src/tools.ts index 1ae69e6..f39e49a 100644 --- a/brokers/discord/src/tools.ts +++ b/brokers/discord/src/tools.ts @@ -2,43 +2,18 @@ // discord_request, a passthrough for what the named tools don't cover. Every tool that // names a channel or guild goes through the scope check first. +import { ToolInputError, truncate, validateArgs, type ToolDef, type ToolResult } from "broker-core"; import { DiscordClient, DiscordError, normalizePath } from "./discord/client"; import { ChannelInfo, Scope, ScopeError } from "./discord/scope"; +export { ToolInputError }; + export interface ToolContext { dc: DiscordClient; scope: Scope; user: { id: string; username: string }; } -type JsonSchema = { - type: "object"; - properties: Record; - required?: string[]; - additionalProperties?: boolean; -}; - -export interface ToolDef { - name: string; - title: string; - description: string; - inputSchema: JsonSchema; - annotations: { - readOnlyHint?: boolean; - destructiveHint?: boolean; - idempotentHint?: boolean; - openWorldHint?: boolean; - }; - run(args: Record, ctx: ToolContext): Promise; -} - -export interface ToolResult { - content: { type: "text"; text: string }[]; - isError: boolean; -} - -export class ToolInputError extends Error {} - const DEFAULT_MAX_CHARS = 100_000; const MAX_MESSAGE = 2000; const SNOWFLAKE = /^\d{5,25}$/; @@ -68,11 +43,6 @@ function id(args: Record, key: string): string { return v; } -function truncate(text: string, max: number): string { - if (text.length <= max) return text; - return `${text.slice(0, max)}\n\n[truncated: ${text.length - max} more characters; raise max_chars or narrow the request]`; -} - export function jumpUrl(guildId: string | undefined, channelId: string, messageId: string): string { return `https://discord.com/channels/${guildId ?? "@me"}/${channelId}/${messageId}`; } @@ -196,38 +166,6 @@ function allowedMentions(args: Record) { return { parse, replied_user: args.ping_reply_author ?? true }; } -/** Validate tool arguments: required keys, primitive types, enums, unknown keys. */ -export function validateArgs(schema: JsonSchema, args: unknown): string | null { - if (args === undefined || args === null) args = {}; - if (typeof args !== "object" || Array.isArray(args)) return "arguments must be an object"; - const a = args as Record; - for (const r of schema.required ?? []) { - if (a[r] === undefined || a[r] === null) return `missing required argument "${r}"`; - } - for (const [k, v] of Object.entries(a)) { - const prop = schema.properties[k]; - if (!prop) { - if (schema.additionalProperties === false) return `unknown argument "${k}"`; - continue; - } - if (v === undefined || v === null) continue; - const t = prop.type; - const ok = - t === undefined || - (t === "string" && typeof v === "string") || - (t === "integer" && Number.isInteger(v)) || - (t === "number" && typeof v === "number") || - (t === "boolean" && typeof v === "boolean") || - (t === "array" && Array.isArray(v)) || - (t === "object" && typeof v === "object" && !Array.isArray(v)); - if (!ok) return `argument "${k}" must be ${t}`; - if (prop.enum && !prop.enum.includes(v)) return `argument "${k}" must be one of ${prop.enum.join(", ")}`; - if (t === "integer" && prop.minimum !== undefined && (v as number) < prop.minimum) return `argument "${k}" must be at least ${prop.minimum}`; - if (t === "integer" && prop.maximum !== undefined && (v as number) > prop.maximum) return `argument "${k}" must be at most ${prop.maximum}`; - } - return null; -} - const channelProp = { type: "string", description: "Channel or thread ID (numeric)." }; const messageProp = { type: "string", description: "Message ID (numeric)." }; const rawProp = { type: "boolean", description: "Return Discord's full objects instead of the compact form." }; @@ -235,7 +173,7 @@ const maxCharsProp = { type: "integer", description: `Truncate the result to thi // ---------- tools ---------- -export const TOOLS: ToolDef[] = [ +export const TOOLS: ToolDef[] = [ { name: "bot_info", title: "Bot info", diff --git a/brokers/discord/test/flow.test.ts b/brokers/discord/test/flow.test.ts index 79072c2..6dfee83 100644 --- a/brokers/discord/test/flow.test.ts +++ b/brokers/discord/test/flow.test.ts @@ -4,6 +4,7 @@ import { createHash, randomBytes } from "node:crypto"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { MemoryKV } from "broker-core/testing"; import worker from "../src/index"; import type { Env } from "../src/env"; import { BOT_TOKEN, C1, fakeDiscord, jsonRes } from "./fake-discord"; @@ -12,27 +13,6 @@ import { resetBotCache } from "../src/tools"; vi.spyOn(console, "log").mockImplementation(() => {}); vi.spyOn(console, "warn").mockImplementation(() => {}); -class MemoryKV { - m = new Map(); - async get(k: string, type?: any) { - const e = this.m.get(k); - if (!e || (e.exp && e.exp < Date.now())) return null; - const t = typeof type === "string" ? type : type?.type; - return t === "json" ? JSON.parse(e.v) : e.v; - } - async put(k: string, v: string, o?: { expirationTtl?: number; expiration?: number; metadata?: unknown }) { - const exp = o?.expirationTtl ? Date.now() + o.expirationTtl * 1000 : o?.expiration ? o.expiration * 1000 : undefined; - this.m.set(k, { v, exp, metadata: o?.metadata }); - } - async delete(k: string) { - this.m.delete(k); - } - async list(o?: { prefix?: string; limit?: number; cursor?: string }) { - const keys = [...this.m.keys()].filter((k) => !o?.prefix || k.startsWith(o.prefix)).sort(); - return { keys: keys.map((name) => ({ name, metadata: this.m.get(name)!.metadata })), list_complete: true, cursor: "" }; - } -} - const BASE = "https://broker.test"; const REDIRECT = "https://claude.ai/api/mcp/auth_callback"; diff --git a/brokers/discord/vitest.config.ts b/brokers/discord/vitest.config.ts index 92246e7..0d99c38 100644 --- a/brokers/discord/vitest.config.ts +++ b/brokers/discord/vitest.config.ts @@ -1,13 +1,4 @@ -import { fileURLToPath } from "node:url"; import { defineConfig } from "vitest/config"; +import { brokerVitest } from "../../vitest.shared"; -export default defineConfig({ - resolve: { - alias: { "cloudflare:workers": fileURLToPath(new URL("./test/stubs/cloudflare-workers.ts", import.meta.url)) }, - }, - test: { - include: ["test/**/*.test.ts"], - environment: "node", - server: { deps: { inline: ["@cloudflare/workers-oauth-provider"] } }, - }, -}); +export default defineConfig(brokerVitest()); diff --git a/brokers/github/package.json b/brokers/github/package.json index 96418c1..b5a3faa 100644 --- a/brokers/github/package.json +++ b/brokers/github/package.json @@ -1,6 +1,6 @@ { "name": "github-broker", - "version": "0.2.0", + "version": "0.3.0", "private": true, "license": "MIT", "description": "Remote MCP server on Cloudflare Workers that brokers a GitHub App installation without exposing its private key", @@ -13,6 +13,7 @@ "cf-typegen": "wrangler types" }, "dependencies": { + "broker-core": "*", "@cloudflare/workers-oauth-provider": "1.2.4" } } diff --git a/brokers/github/src/auth.ts b/brokers/github/src/auth.ts index 9c7997a..cef144d 100644 --- a/brokers/github/src/auth.ts +++ b/brokers/github/src/auth.ts @@ -8,7 +8,7 @@ import { type ConsentDescription, type OAuthHelpers, } from "@cloudflare/workers-oauth-provider"; -import { base64url } from "./github/app"; +import { base64url, publicUrl } from "broker-core"; import type { Env } from "./env"; export const SCOPE = "github"; @@ -214,8 +214,3 @@ export async function handleCallback( console.log(JSON.stringify({ event: "sign_in", login: user.login, id: user.id, client: authReq.clientId })); return redirect(redirectTo, headers); } - -export function publicUrl(env: Env): string { - if (!env.PUBLIC_URL) throw new Error("PUBLIC_URL is not set"); - return env.PUBLIC_URL.replace(/\/+$/, ""); -} diff --git a/brokers/github/src/github/app.ts b/brokers/github/src/github/app.ts index 4d6f125..6c6223e 100644 --- a/brokers/github/src/github/app.ts +++ b/brokers/github/src/github/app.ts @@ -3,6 +3,8 @@ // The private key only ever lives in the Worker's secret store. Nothing here logs it, // returns it, or puts it in an error message. +import { base64url } from "broker-core"; + const RSA_ENCRYPTION_ALG_ID = new Uint8Array([ // SEQUENCE { OID 1.2.840.113549.1.1.1 (rsaEncryption), NULL } 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, @@ -46,13 +48,6 @@ function base64ToBytes(b64: string): Uint8Array { return out; } -export function base64url(bytes: Uint8Array | string): string { - const b = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes; - let bin = ""; - for (let i = 0; i < b.length; i++) bin += String.fromCharCode(b[i]); - return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); -} - /** * Parse a PEM private key into PKCS#8 DER. Accepts GitHub's PKCS#1 * ("BEGIN RSA PRIVATE KEY") and PKCS#8 ("BEGIN PRIVATE KEY"). Tolerates the diff --git a/brokers/github/src/index.ts b/brokers/github/src/index.ts index 8b9c144..311611f 100644 --- a/brokers/github/src/index.ts +++ b/brokers/github/src/index.ts @@ -12,7 +12,8 @@ import { insufficientScope, type OAuthResourceContext, } from "@cloudflare/workers-oauth-provider"; -import { AuthProps, SCOPE, handleAuthorize, handleCallback, isAllowed, publicUrl } from "./auth"; +import { VERSION, publicUrl, required } from "broker-core"; +import { AuthProps, SCOPE, handleAuthorize, handleCallback, isAllowed } from "./auth"; import type { Env } from "./env"; import { tokens } from "./github/app"; import { GitHubClient } from "./github/client"; @@ -20,8 +21,6 @@ import { handleMcp } from "./mcp"; export { Feed } from "./feed"; -const VERSION = "0.2.0"; - const INSTRUCTIONS = "Tools act as a GitHub App installation, with whatever permissions the app was granted (installation_info shows them). " + 'Pass repositories as "OWNER/NAME" (or NAME when a default owner is configured). ' + @@ -89,12 +88,6 @@ function getRoles(env: Env): Roles { return roles; } -function required(env: Env, key: keyof Env): string { - const v = env[key]; - if (typeof v !== "string" || !v) throw new Error(`${key} is not set`); - return v; -} - export default { async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { const { pathname } = new URL(request.url); diff --git a/brokers/github/src/tools.ts b/brokers/github/src/tools.ts index 7f1a631..84c3e56 100644 --- a/brokers/github/src/tools.ts +++ b/brokers/github/src/tools.ts @@ -1,6 +1,7 @@ // MCP tool definitions. Each tool is a small wrapper over the GitHub REST API, plus // github_request, a passthrough for everything the named tools don't cover. +import { ToolInputError, truncate, validateArgs, type ToolDef, type ToolResult } from "broker-core"; import { GitHubClient, GitHubError } from "./github/client"; export interface ToolContext { @@ -9,32 +10,6 @@ export interface ToolContext { user: { login: string; id: string }; } -type JsonSchema = { - type: "object"; - properties: Record; - required?: string[]; - additionalProperties?: boolean; -}; - -export interface ToolDef { - name: string; - title: string; - description: string; - inputSchema: JsonSchema; - annotations: { - readOnlyHint?: boolean; - destructiveHint?: boolean; - idempotentHint?: boolean; - openWorldHint?: boolean; - }; - run(args: Record, ctx: ToolContext): Promise; -} - -export interface ToolResult { - content: { type: "text"; text: string }[]; - isError: boolean; -} - const DEFAULT_MAX_CHARS = 200_000; // ---------- helpers ---------- @@ -65,13 +40,6 @@ function encodePath(p: string): string { .join("/"); } -export class ToolInputError extends Error {} - -function truncate(text: string, max: number): string { - if (text.length <= max) return text; - return `${text.slice(0, max)}\n\n[truncated: ${text.length - max} more characters; raise max_chars or narrow the request]`; -} - async function defaultBranch(gh: GitHubClient, rp: string): Promise { const repo = await gh.call<{ default_branch: string }>({ path: rp }); return repo.default_branch; @@ -83,36 +51,6 @@ async function resolveSha(gh: GitHubClient, rp: string, ref: string): Promise; - for (const r of schema.required ?? []) { - if (a[r] === undefined || a[r] === null) return `missing required argument "${r}"`; - } - for (const [k, v] of Object.entries(a)) { - const prop = schema.properties[k]; - if (!prop) { - if (schema.additionalProperties === false) return `unknown argument "${k}"`; - continue; - } - if (v === undefined || v === null) continue; - const t = prop.type; - const ok = - t === undefined || - (t === "string" && typeof v === "string") || - (t === "integer" && Number.isInteger(v)) || - (t === "number" && typeof v === "number") || - (t === "boolean" && typeof v === "boolean") || - (t === "array" && Array.isArray(v)) || - (t === "object" && typeof v === "object" && !Array.isArray(v)); - if (!ok) return `argument "${k}" must be ${t}`; - if (prop.enum && !prop.enum.includes(v)) return `argument "${k}" must be one of ${prop.enum.join(", ")}`; - } - return null; -} - const repoProp = { type: "string", description: 'Repository as "OWNER/NAME", or just NAME to use the default owner.', @@ -124,7 +62,7 @@ const pageProps = { // ---------- tools ---------- -export const TOOLS: ToolDef[] = [ +export const TOOLS: ToolDef[] = [ { name: "installation_info", title: "Installation info", diff --git a/brokers/github/test/flow.test.ts b/brokers/github/test/flow.test.ts index 74bc134..d04a870 100644 --- a/brokers/github/test/flow.test.ts +++ b/brokers/github/test/flow.test.ts @@ -4,6 +4,7 @@ import { createHash, randomBytes } from "node:crypto"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { MemoryKV } from "broker-core/testing"; import worker from "../src/index"; import type { Env } from "../src/env"; import { TEST_PEM, jsonRes } from "./fake-github"; @@ -11,27 +12,6 @@ import { TEST_PEM, jsonRes } from "./fake-github"; vi.spyOn(console, "log").mockImplementation(() => {}); vi.spyOn(console, "warn").mockImplementation(() => {}); -class MemoryKV { - m = new Map(); - async get(k: string, type?: any) { - const e = this.m.get(k); - if (!e || (e.exp && e.exp < Date.now())) return null; - const t = typeof type === "string" ? type : type?.type; - return t === "json" ? JSON.parse(e.v) : e.v; - } - async put(k: string, v: string, o?: { expirationTtl?: number; expiration?: number; metadata?: unknown }) { - const exp = o?.expirationTtl ? Date.now() + o.expirationTtl * 1000 : o?.expiration ? o.expiration * 1000 : undefined; - this.m.set(k, { v, exp, metadata: o?.metadata }); - } - async delete(k: string) { - this.m.delete(k); - } - async list(o?: { prefix?: string; limit?: number; cursor?: string }) { - const keys = [...this.m.keys()].filter((k) => !o?.prefix || k.startsWith(o.prefix)).sort(); - return { keys: keys.map((name) => ({ name, metadata: this.m.get(name)!.metadata })), list_complete: true, cursor: "" }; - } -} - const BASE = "https://broker.test"; const REDIRECT = "https://claude.ai/api/mcp/auth_callback"; diff --git a/brokers/github/test/stubs/cloudflare-workers.ts b/brokers/github/test/stubs/cloudflare-workers.ts deleted file mode 100644 index 77ff4b5..0000000 --- a/brokers/github/test/stubs/cloudflare-workers.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Node stand-in for the workerd-only module, so code that imports the OAuth library loads in vitest. -export class WorkerEntrypoint { - constructor( - readonly ctx: unknown, - readonly env: E, - ) {} -} -export const env = {}; diff --git a/brokers/github/test/tools.test.ts b/brokers/github/test/tools.test.ts index ba39c89..02d6823 100644 --- a/brokers/github/test/tools.test.ts +++ b/brokers/github/test/tools.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from "vitest"; import { normalizePath } from "../src/github/client"; -import { TOOLS, callTool, splitRepo, validateArgs } from "../src/tools"; +import { TOOLS, callTool, splitRepo } from "../src/tools"; import { SHA_MAIN, fakeGitHub, jsonRes, toolContext } from "./fake-github"; vi.spyOn(console, "log").mockImplementation(() => {}); @@ -16,15 +16,6 @@ describe("argument handling", () => { expect(() => splitRepo("../b", "a")).toThrow(); }); - it("validates required keys, types, enums and unknown keys", () => { - const s = TOOLS.find((t) => t.name === "list_prs")!.inputSchema; - expect(validateArgs(s, {})).toMatch(/missing required argument "repo"/); - expect(validateArgs(s, { repo: 1 })).toMatch(/must be string/); - expect(validateArgs(s, { repo: "a/b", state: "merged" })).toMatch(/one of/); - expect(validateArgs(s, { repo: "a/b", nope: 1 })).toMatch(/unknown argument/); - expect(validateArgs(s, { repo: "a/b", state: "all", per_page: 5 })).toBeNull(); - }); - it("keeps github_request on the API host", () => { expect(normalizePath("repos/o/r")).toBe("/repos/o/r"); for (const bad of ["https://evil.example/x", "//evil.example/x", "/https://evil.example", "/repos/../../x"]) { diff --git a/brokers/github/vitest.config.ts b/brokers/github/vitest.config.ts index 92246e7..0d99c38 100644 --- a/brokers/github/vitest.config.ts +++ b/brokers/github/vitest.config.ts @@ -1,13 +1,4 @@ -import { fileURLToPath } from "node:url"; import { defineConfig } from "vitest/config"; +import { brokerVitest } from "../../vitest.shared"; -export default defineConfig({ - resolve: { - alias: { "cloudflare:workers": fileURLToPath(new URL("./test/stubs/cloudflare-workers.ts", import.meta.url)) }, - }, - test: { - include: ["test/**/*.test.ts"], - environment: "node", - server: { deps: { inline: ["@cloudflare/workers-oauth-provider"] } }, - }, -}); +export default defineConfig(brokerVitest()); diff --git a/package-lock.json b/package-lock.json index b5f5e17..99d5fc0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "brokers", - "version": "0.2.0", + "version": "0.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "brokers", - "version": "0.2.0", + "version": "0.3.0", "license": "MIT", "workspaces": [ "packages/*", @@ -23,18 +23,20 @@ }, "brokers/discord": { "name": "discord-broker", - "version": "0.2.0", + "version": "0.3.0", "license": "MIT", "dependencies": { - "@cloudflare/workers-oauth-provider": "1.2.4" + "@cloudflare/workers-oauth-provider": "1.2.4", + "broker-core": "*" } }, "brokers/github": { "name": "github-broker", - "version": "0.2.0", + "version": "0.3.0", "license": "MIT", "dependencies": { - "@cloudflare/workers-oauth-provider": "1.2.4" + "@cloudflare/workers-oauth-provider": "1.2.4", + "broker-core": "*" } }, "node_modules/@cloudflare/kv-asset-handler": { @@ -1928,6 +1930,10 @@ "url": "https://opencollective.com/express" } }, + "node_modules/broker-core": { + "resolved": "packages/core", + "link": true + }, "node_modules/bytes": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", @@ -4180,6 +4186,14 @@ "peerDependencies": { "zod": "^3.25.28 || ^4" } + }, + "packages/core": { + "name": "broker-core", + "version": "0.3.0", + "license": "MIT", + "dependencies": { + "@cloudflare/workers-oauth-provider": "1.2.4" + } } } } diff --git a/package.json b/package.json index 1f21bc6..9cd4568 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "brokers", - "version": "0.2.0", + "version": "0.3.0", "private": true, "license": "MIT", "type": "module", diff --git a/packages/core/package.json b/packages/core/package.json new file mode 100644 index 0000000..9e3e822 --- /dev/null +++ b/packages/core/package.json @@ -0,0 +1,19 @@ +{ + "name": "broker-core", + "version": "0.3.0", + "private": true, + "license": "MIT", + "description": "Code shared by the Cloudflare Worker MCP brokers", + "type": "module", + "exports": { + ".": "./src/index.ts", + "./testing": "./test-support/index.ts" + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "dependencies": { + "@cloudflare/workers-oauth-provider": "1.2.4" + } +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts new file mode 100644 index 0000000..0bb2ebe --- /dev/null +++ b/packages/core/src/index.ts @@ -0,0 +1,4 @@ +export { VERSION } from "./version"; +export { publicUrl, required, base64url } from "./util"; +export { ToolInputError, truncate, validateArgs } from "./tools"; +export type { JsonSchema, ToolDef, ToolResult } from "./tools"; diff --git a/packages/core/src/tools.ts b/packages/core/src/tools.ts new file mode 100644 index 0000000..f753ca5 --- /dev/null +++ b/packages/core/src/tools.ts @@ -0,0 +1,66 @@ +// Types and helpers every broker's MCP tools share. + +export type JsonSchema = { + type: "object"; + properties: Record; + required?: string[]; + additionalProperties?: boolean; +}; + +export interface ToolDef { + name: string; + title: string; + description: string; + inputSchema: JsonSchema; + annotations: { + readOnlyHint?: boolean; + destructiveHint?: boolean; + idempotentHint?: boolean; + openWorldHint?: boolean; + }; + run(args: Record, ctx: C): Promise; +} + +export interface ToolResult { + content: { type: "text"; text: string }[]; + isError: boolean; +} + +export class ToolInputError extends Error {} + +export function truncate(text: string, max: number): string { + if (text.length <= max) return text; + return `${text.slice(0, max)}\n\n[truncated: ${text.length - max} more characters; raise max_chars or narrow the request]`; +} + +/** Validate tool arguments: required keys, primitive types, enums, unknown keys. */ +export function validateArgs(schema: JsonSchema, args: unknown): string | null { + if (args === undefined || args === null) args = {}; + if (typeof args !== "object" || Array.isArray(args)) return "arguments must be an object"; + const a = args as Record; + for (const r of schema.required ?? []) { + if (a[r] === undefined || a[r] === null) return `missing required argument "${r}"`; + } + for (const [k, v] of Object.entries(a)) { + const prop = schema.properties[k]; + if (!prop) { + if (schema.additionalProperties === false) return `unknown argument "${k}"`; + continue; + } + if (v === undefined || v === null) continue; + const t = prop.type; + const ok = + t === undefined || + (t === "string" && typeof v === "string") || + (t === "integer" && Number.isInteger(v)) || + (t === "number" && typeof v === "number") || + (t === "boolean" && typeof v === "boolean") || + (t === "array" && Array.isArray(v)) || + (t === "object" && typeof v === "object" && !Array.isArray(v)); + if (!ok) return `argument "${k}" must be ${t}`; + if (prop.enum && !prop.enum.includes(v)) return `argument "${k}" must be one of ${prop.enum.join(", ")}`; + if (t === "integer" && prop.minimum !== undefined && (v as number) < prop.minimum) return `argument "${k}" must be at least ${prop.minimum}`; + if (t === "integer" && prop.maximum !== undefined && (v as number) > prop.maximum) return `argument "${k}" must be at most ${prop.maximum}`; + } + return null; +} diff --git a/packages/core/src/util.ts b/packages/core/src/util.ts new file mode 100644 index 0000000..8c238d6 --- /dev/null +++ b/packages/core/src/util.ts @@ -0,0 +1,17 @@ +export function publicUrl(env: { PUBLIC_URL?: string }): string { + if (!env.PUBLIC_URL) throw new Error("PUBLIC_URL is not set"); + return env.PUBLIC_URL.replace(/\/+$/, ""); +} + +export function required(env: E, key: keyof E & string): string { + const v = env[key]; + if (typeof v !== "string" || !v) throw new Error(`${key} is not set`); + return v; +} + +export function base64url(input: Uint8Array | string): string { + const b = typeof input === "string" ? new TextEncoder().encode(input) : input; + let bin = ""; + for (let i = 0; i < b.length; i++) bin += String.fromCharCode(b[i]); + return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); +} diff --git a/packages/core/src/version.ts b/packages/core/src/version.ts new file mode 100644 index 0000000..387b59e --- /dev/null +++ b/packages/core/src/version.ts @@ -0,0 +1 @@ +export const VERSION = "0.3.0"; diff --git a/brokers/discord/test/stubs/cloudflare-workers.ts b/packages/core/test-support/cloudflare-workers.ts similarity index 100% rename from brokers/discord/test/stubs/cloudflare-workers.ts rename to packages/core/test-support/cloudflare-workers.ts diff --git a/packages/core/test-support/index.ts b/packages/core/test-support/index.ts new file mode 100644 index 0000000..5fcdf92 --- /dev/null +++ b/packages/core/test-support/index.ts @@ -0,0 +1,22 @@ +// Test doubles shared by the brokers: imported as "broker-core/testing". + +export class MemoryKV { + m = new Map(); + async get(k: string, type?: any) { + const e = this.m.get(k); + if (!e || (e.exp && e.exp < Date.now())) return null; + const t = typeof type === "string" ? type : type?.type; + return t === "json" ? JSON.parse(e.v) : e.v; + } + async put(k: string, v: string, o?: { expirationTtl?: number; expiration?: number; metadata?: unknown }) { + const exp = o?.expirationTtl ? Date.now() + o.expirationTtl * 1000 : o?.expiration ? o.expiration * 1000 : undefined; + this.m.set(k, { v, exp, metadata: o?.metadata }); + } + async delete(k: string) { + this.m.delete(k); + } + async list(o?: { prefix?: string; limit?: number; cursor?: string }) { + const keys = [...this.m.keys()].filter((k) => !o?.prefix || k.startsWith(o.prefix)).sort(); + return { keys: keys.map((name) => ({ name, metadata: this.m.get(name)!.metadata })), list_complete: true, cursor: "" }; + } +} diff --git a/packages/core/test/tools.test.ts b/packages/core/test/tools.test.ts new file mode 100644 index 0000000..bf20740 --- /dev/null +++ b/packages/core/test/tools.test.ts @@ -0,0 +1,32 @@ +import { expect, it } from "vitest"; +import { truncate, validateArgs, type JsonSchema } from "../src"; + +it("validates required keys, types, enums and unknown keys", () => { + const s: JsonSchema = { + type: "object", + properties: { + repo: { type: "string" }, + state: { type: "string", enum: ["open", "closed", "all"] }, + per_page: { type: "integer" }, + }, + required: ["repo"], + additionalProperties: false, + }; + expect(validateArgs(s, {})).toMatch(/missing required argument "repo"/); + expect(validateArgs(s, { repo: 1 })).toMatch(/must be string/); + expect(validateArgs(s, { repo: "a/b", state: "merged" })).toMatch(/one of/); + expect(validateArgs(s, { repo: "a/b", nope: 1 })).toMatch(/unknown argument/); + expect(validateArgs(s, { repo: "a/b", state: "all", per_page: 5 })).toBeNull(); +}); + +it("enforces integer bounds", () => { + const s = { type: "object", properties: { n: { type: "integer", minimum: 1, maximum: 5 } }, additionalProperties: false } as const; + expect(validateArgs(s as unknown as JsonSchema, { n: 0 })).toBe('argument "n" must be at least 1'); + expect(validateArgs(s as unknown as JsonSchema, { n: 6 })).toBe('argument "n" must be at most 5'); + expect(validateArgs(s as unknown as JsonSchema, { n: 3 })).toBeNull(); +}); + +it("truncates with a note saying how much was cut", () => { + expect(truncate("abc", 3)).toBe("abc"); + expect(truncate("abcdef", 3)).toMatch(/^abc\n\n\[truncated: 3 more characters/); +}); diff --git a/packages/core/test/util.test.ts b/packages/core/test/util.test.ts new file mode 100644 index 0000000..d58794c --- /dev/null +++ b/packages/core/test/util.test.ts @@ -0,0 +1,17 @@ +import { expect, it } from "vitest"; +import { base64url, publicUrl, required } from "../src"; + +it("publicUrl strips trailing slashes and insists on being set", () => { + expect(publicUrl({ PUBLIC_URL: "https://b.test//" })).toBe("https://b.test"); + expect(() => publicUrl({})).toThrow("PUBLIC_URL is not set"); +}); + +it("required returns a non-empty string setting or names the missing key", () => { + expect(required({ A: "x" }, "A")).toBe("x"); + expect(() => required({ A: "" }, "A")).toThrow("A is not set"); +}); + +it("base64url is unpadded and URL-safe, for bytes and strings", () => { + expect(base64url(new Uint8Array([251, 255, 254]))).toBe("-__-"); + expect(base64url("{}")).toBe("e30"); +}); diff --git a/packages/core/test/version.test.ts b/packages/core/test/version.test.ts new file mode 100644 index 0000000..26b3843 --- /dev/null +++ b/packages/core/test/version.test.ts @@ -0,0 +1,10 @@ +import { readFileSync } from "node:fs"; +import { expect, it } from "vitest"; +import { VERSION } from "../src"; + +it("is the one version every package.json states", () => { + for (const p of ["package.json", "packages/core/package.json", "brokers/discord/package.json", "brokers/github/package.json"]) { + expect(JSON.parse(readFileSync(new URL(`../../../${p}`, import.meta.url), "utf8")).version, p).toBe(VERSION); + } + expect(VERSION).toBe("0.3.0"); +}); diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json new file mode 100644 index 0000000..45764b0 --- /dev/null +++ b/packages/core/tsconfig.json @@ -0,0 +1 @@ +{ "extends": "../../tsconfig.base.json", "include": ["src/**/*.ts", "test-support/**/*.ts"] } diff --git a/packages/core/vitest.config.ts b/packages/core/vitest.config.ts new file mode 100644 index 0000000..0d99c38 --- /dev/null +++ b/packages/core/vitest.config.ts @@ -0,0 +1,4 @@ +import { defineConfig } from "vitest/config"; +import { brokerVitest } from "../../vitest.shared"; + +export default defineConfig(brokerVitest()); diff --git a/vitest.shared.ts b/vitest.shared.ts new file mode 100644 index 0000000..0ab954a --- /dev/null +++ b/vitest.shared.ts @@ -0,0 +1,16 @@ +import { fileURLToPath } from "node:url"; +import type { UserConfig } from "vitest/config"; + +// Vitest settings every package shares: the workerd-only `cloudflare:workers` module is aliased to a Node stand-in. +export function brokerVitest(): UserConfig { + return { + resolve: { + alias: { "cloudflare:workers": fileURLToPath(new URL("./packages/core/test-support/cloudflare-workers.ts", import.meta.url)) }, + }, + test: { + include: ["test/**/*.test.ts"], + environment: "node", + server: { deps: { inline: ["@cloudflare/workers-oauth-provider"] } }, + }, + }; +} From 7cb59049610b5ab1dd4879cf24b3a7016cc454f0 Mon Sep 17 00:00:00 2001 From: Cycle Five Date: Thu, 19 Nov 2026 17:21:15 -0500 Subject: [PATCH 2/9] refactor: one MCP server implementation in broker-core Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) --- brokers/discord/src/index.ts | 5 +- brokers/discord/test/mcp.test.ts | 165 ++------------ brokers/github/src/index.ts | 5 +- brokers/github/src/mcp.ts | 168 -------------- brokers/github/test/mcp.test.ts | 165 ++------------ packages/core/src/index.ts | 2 + {brokers/discord => packages/core}/src/mcp.ts | 19 +- packages/core/test/mcp.test.ts | 211 ++++++++++++++++++ 8 files changed, 258 insertions(+), 482 deletions(-) delete mode 100644 brokers/github/src/mcp.ts rename {brokers/discord => packages/core}/src/mcp.ts (93%) create mode 100644 packages/core/test/mcp.test.ts diff --git a/brokers/discord/src/index.ts b/brokers/discord/src/index.ts index bf7f84d..5353fb8 100644 --- a/brokers/discord/src/index.ts +++ b/brokers/discord/src/index.ts @@ -12,13 +12,13 @@ import { insufficientScope, type OAuthResourceContext, } from "@cloudflare/workers-oauth-provider"; -import { VERSION, publicUrl, required } from "broker-core"; +import { VERSION, handleMcp, publicUrl, required } from "broker-core"; import { AuthProps, SCOPE, handleAuthorize, handleCallback, isAllowed, userAgent } from "./auth"; import { DiscordClient } from "./discord/client"; import { Scope } from "./discord/scope"; import type { Env } from "./env"; -import { handleMcp } from "./mcp"; import { channels, limiter } from "./shared"; +import { TOOLS, callTool } from "./tools"; export { Feed } from "./feed"; @@ -65,6 +65,7 @@ function getRoles(env: Env): Roles { } return handleMcp( request, + { list: TOOLS, call: callTool }, () => ({ dc: new DiscordClient({ token: required(env, "DISCORD_BOT_TOKEN"), userAgent: userAgent(env) }, limiter), scope: new Scope(env.DISCORD_ALLOWED_GUILDS, env.DISCORD_ALLOWED_CHANNELS, channels), diff --git a/brokers/discord/test/mcp.test.ts b/brokers/discord/test/mcp.test.ts index 6499049..a29fb77 100644 --- a/brokers/discord/test/mcp.test.ts +++ b/brokers/discord/test/mcp.test.ts @@ -1,12 +1,9 @@ -// Conformance against the official MCP clients: @modelcontextprotocol/client 2.4 -// (2026-07-28 and legacy eras) and @modelcontextprotocol/sdk 1.x (legacy only). +// The real MCP SDK client against this broker's real tools. Protocol cases live in broker-core. -import { Client as Client2, StreamableHTTPClientTransport as Transport2 } from "@modelcontextprotocol/client"; -import { Client as Client1 } from "@modelcontextprotocol/sdk/client/index.js"; -import { StreamableHTTPClientTransport as Transport1 } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"; import { describe, expect, it, vi } from "vitest"; -import { MODERN_VERSION, SUPPORTED_VERSIONS, handleMcp } from "../src/mcp"; -import { TOOLS } from "../src/tools"; +import { handleMcp } from "broker-core"; +import { TOOLS, callTool } from "../src/tools"; import { fakeDiscord, toolContext } from "./fake-discord"; vi.spyOn(console, "log").mockImplementation(() => {}); @@ -14,160 +11,24 @@ vi.spyOn(console, "log").mockImplementation(() => {}); const URL_ = "https://broker.test/mcp"; const opts = { serverInfo: { name: "discord-broker", version: "0.0.0-test" }, instructions: "test" }; -function serverFetch(seen: { method: string; headers: Headers; body?: any }[] = []) { +function serverFetch() { const ctx = toolContext(fakeDiscord().fetchImpl); const f = async (input: RequestInfo | URL, init?: RequestInit) => { const req = new Request(input, init); - const clone = req.clone(); - let body: any; - try { - body = await clone.json(); - } catch {} - seen.push({ method: req.method, headers: req.headers, body }); - return handleMcp(req, () => ctx, opts); + return handleMcp(req, { list: TOOLS, call: callTool }, () => ctx, opts); }; return f as typeof fetch; } -async function exercise(client: { listTools: () => Promise; callTool: (p: any) => Promise }) { +it("the MCP client lists the tools and calls a real one", async () => { + const client = new Client({ name: "t", version: "1" }); + await client.connect(new StreamableHTTPClientTransport(new URL(URL_), { fetch: serverFetch() })); const tools = await client.listTools(); - expect(tools.tools.map((t: any) => t.name)).toEqual(TOOLS.map((t) => t.name)); - const res = await client.callTool({ name: "bot_info", arguments: {} }); + expect(tools.tools.map((t) => t.name)).toEqual(TOOLS.map((t) => t.name)); + const res: any = await client.callTool({ name: "bot_info", arguments: {} }); expect(res.isError).toBe(false); expect(res.content[0].text).toContain("message_content"); - const bad = await client.callTool({ name: "read_messages", arguments: {} }); + const bad: any = await client.callTool({ name: "read_messages", arguments: {} }); expect(bad.isError).toBe(true); -} - -describe("MCP over Streamable HTTP", () => { - it("2026-07-28: client 2.4 in auto mode discovers and uses the modern era", async () => { - const seen: any[] = []; - const client = new Client2({ name: "t", version: "1" }, { versionNegotiation: { mode: "auto" } }); - await client.connect(new Transport2(new URL(URL_), { fetch: serverFetch(seen) })); - await exercise(client as any); - const methods = seen.filter((s) => s.body).map((s) => s.body.method); - expect(methods[0]).toBe("server/discover"); - expect(methods).not.toContain("initialize"); - const call = seen.find((s) => s.body?.method === "tools/call"); - expect(call.headers.get("mcp-protocol-version")).toBe(MODERN_VERSION); - expect(call.body.params._meta["io.modelcontextprotocol/protocolVersion"]).toBe(MODERN_VERSION); - await client.close(); - }); - - it("2026-07-28: pinned client works too", async () => { - const client = new Client2({ name: "t", version: "1" }, { versionNegotiation: { mode: { pin: MODERN_VERSION } } }); - await client.connect(new Transport2(new URL(URL_), { fetch: serverFetch() })); - await exercise(client as any); - await client.close(); - }); - - it("legacy: client 2.4 default mode uses initialize", async () => { - const seen: any[] = []; - const client = new Client2({ name: "t", version: "1" }); - await client.connect(new Transport2(new URL(URL_), { fetch: serverFetch(seen) })); - await exercise(client as any); - expect(seen.find((s) => s.body)?.body.method).toBe("initialize"); - await client.close(); - }); - - it("legacy: SDK 1.x client", async () => { - const client = new Client1({ name: "t", version: "1" }); - await client.connect(new Transport1(new URL(URL_), { fetch: serverFetch() })); - await exercise(client as any); - await client.close(); - }); -}); - -describe("transport edges", () => { - const ctx = () => toolContext(fakeDiscord().fetchImpl); - const post = (body: unknown, headers: Record = {}) => - handleMcp( - new Request(URL_, { - method: "POST", - headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...headers }, - body: typeof body === "string" ? body : JSON.stringify(body), - }), - ctx, - { ...opts, allowedOrigins: ["https://claude.ai"] }, - ); - - it("GET and DELETE are 405", async () => { - for (const method of ["GET", "DELETE"]) { - const r = await handleMcp(new Request(URL_, { method }), ctx, opts); - expect(r.status).toBe(405); - } - }); - - it("notifications get 202 with no body", async () => { - const r = await post({ jsonrpc: "2.0", method: "notifications/initialized" }); - expect(r.status).toBe(202); - expect(await r.text()).toBe(""); - }); - - it("parse errors and batches are 400", async () => { - expect((await post("{nope")).status).toBe(400); - expect((await post([{ jsonrpc: "2.0", id: 1, method: "ping" }])).status).toBe(400); - }); - - it("an unsupported modern version gets 400 -32022 with the supported list", async () => { - const r = await post( - { jsonrpc: "2.0", id: 1, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": "2099-01-01" } } }, - { "mcp-protocol-version": "2099-01-01" }, - ); - expect(r.status).toBe(400); - const b: any = await r.json(); - expect(b.error.code).toBe(-32022); - expect(b.error.data.supported).toEqual(SUPPORTED_VERSIONS); - }); - - it("header and _meta version mismatch is 400 -32020", async () => { - const r = await post( - { jsonrpc: "2.0", id: 1, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": MODERN_VERSION } } }, - { "mcp-protocol-version": "2025-11-25" }, - ); - expect(r.status).toBe(400); - expect(((await r.json()) as any).error.code).toBe(-32020); - }); - - it("modern results carry resultType, cache hints and serverInfo", async () => { - const r = await post( - { jsonrpc: "2.0", id: 7, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": MODERN_VERSION } } }, - { "mcp-protocol-version": MODERN_VERSION, "mcp-method": "tools/list" }, - ); - const b: any = await r.json(); - expect(b.result.resultType).toBe("complete"); - expect(b.result.cacheScope).toBe("private"); - expect(b.result.ttlMs).toBeGreaterThan(0); - expect(b.result._meta["io.modelcontextprotocol/serverInfo"].name).toBe("discord-broker"); - expect(r.headers.get("mcp-session-id")).toBeNull(); - }); - - it("unknown methods: 404 in the modern era, JSON-RPC error in legacy", async () => { - const modern = await post( - { jsonrpc: "2.0", id: 1, method: "nope", params: { _meta: { "io.modelcontextprotocol/protocolVersion": MODERN_VERSION } } }, - { "mcp-protocol-version": MODERN_VERSION }, - ); - expect(modern.status).toBe(404); - const legacy = await post({ jsonrpc: "2.0", id: 1, method: "nope" }); - expect(legacy.status).toBe(200); - expect(((await legacy.json()) as any).error.code).toBe(-32601); - }); - - it("unknown tool is -32602", async () => { - const r = await post({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "nope", arguments: {} } }); - expect(((await r.json()) as any).error.code).toBe(-32602); - }); - - it("a foreign Origin is 403 when an allowlist is set", async () => { - expect((await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { origin: "https://evil.example" })).status).toBe(403); - expect((await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { origin: "https://claude.ai" })).status).toBe(200); - }); - - it("initialize answers the client's legacy version, or the newest legacy one", async () => { - const ask = async (v: string) => - ((await (await post({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: v, capabilities: {}, clientInfo: { name: "x", version: "1" } } })).json()) as any).result - .protocolVersion; - expect(await ask("2025-06-18")).toBe("2025-06-18"); - expect(await ask("2024-11-05")).toBe("2025-11-25"); - }); + await client.close(); }); diff --git a/brokers/github/src/index.ts b/brokers/github/src/index.ts index 311611f..2ffae6f 100644 --- a/brokers/github/src/index.ts +++ b/brokers/github/src/index.ts @@ -12,12 +12,12 @@ import { insufficientScope, type OAuthResourceContext, } from "@cloudflare/workers-oauth-provider"; -import { VERSION, publicUrl, required } from "broker-core"; +import { VERSION, handleMcp, publicUrl, required } from "broker-core"; import { AuthProps, SCOPE, handleAuthorize, handleCallback, isAllowed } from "./auth"; import type { Env } from "./env"; import { tokens } from "./github/app"; import { GitHubClient } from "./github/client"; -import { handleMcp } from "./mcp"; +import { TOOLS, callTool } from "./tools"; export { Feed } from "./feed"; @@ -62,6 +62,7 @@ function getRoles(env: Env): Roles { } return handleMcp( request, + { list: TOOLS, call: callTool }, () => ({ gh: new GitHubClient( { diff --git a/brokers/github/src/mcp.ts b/brokers/github/src/mcp.ts deleted file mode 100644 index 288fdee..0000000 --- a/brokers/github/src/mcp.ts +++ /dev/null @@ -1,168 +0,0 @@ -// A small, stateless MCP server over Streamable HTTP. Every POST gets one -// application/json answer; there are no sessions and no SSE streams. -// -// It speaks both protocol eras: -// - 2026-07-28: no handshake; server/discover; version in params._meta and the -// MCP-Protocol-Version header; results carry resultType and serverInfo in _meta. -// - 2025-11-25 / 2025-06-18 / 2025-03-26: initialize + notifications/initialized. - -import { TOOLS, ToolContext, callTool } from "./tools"; - -export const MODERN_VERSION = "2026-07-28"; -export const LEGACY_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26"]; -export const SUPPORTED_VERSIONS = [MODERN_VERSION, ...LEGACY_VERSIONS]; - -const META_VERSION = "io.modelcontextprotocol/protocolVersion"; -const META_SERVER_INFO = "io.modelcontextprotocol/serverInfo"; - -const ERR = { - parse: -32700, - invalidRequest: -32600, - methodNotFound: -32601, - invalidParams: -32602, - internal: -32603, - headerMismatch: -32020, - unsupportedVersion: -32022, -}; - -export interface McpOptions { - serverInfo: { name: string; version: string; title?: string }; - instructions?: string; - /** If set, requests with an Origin header outside this list get 403. */ - allowedOrigins?: string[]; - /** How long clients may cache tools/list and server/discover (2026-07-28). */ - listTtlMs?: number; -} - -type Id = string | number | null; - -function json(body: unknown, status = 200, extra: Record = {}): Response { - return new Response(JSON.stringify(body), { - status, - headers: { "Content-Type": "application/json", ...extra }, - }); -} - -function rpcError(id: Id, code: number, message: string, data?: unknown, status = 200): Response { - return json({ jsonrpc: "2.0", id, error: data === undefined ? { code, message } : { code, message, data } }, status); -} - -function isNewer(v: string): boolean { - // Revision ids are dates, so string order is chronological. - return v >= MODERN_VERSION; -} - -export async function handleMcp( - request: Request, - getContext: () => ToolContext | Promise, - opts: McpOptions, -): Promise { - const origin = request.headers.get("origin"); - if (origin && opts.allowedOrigins && opts.allowedOrigins.length && !opts.allowedOrigins.includes(origin)) { - return rpcError(null, ERR.invalidRequest, "Origin not allowed", undefined, 403); - } - if (request.method !== "POST") { - return new Response("Method Not Allowed", { status: 405, headers: { Allow: "POST" } }); - } - - let msg: any; - try { - msg = await request.json(); - } catch { - return rpcError(null, ERR.parse, "Parse error", undefined, 400); - } - if (Array.isArray(msg)) return rpcError(null, ERR.invalidRequest, "Batch requests are not supported", undefined, 400); - if (!msg || typeof msg !== "object" || msg.jsonrpc !== "2.0") { - return rpcError(null, ERR.invalidRequest, "Invalid Request", undefined, 400); - } - - // Responses from the client and notifications need no answer. - if (typeof msg.method !== "string") return new Response(null, { status: 202 }); - if (msg.id === undefined) return new Response(null, { status: 202 }); - - const id: Id = msg.id; - const method: string = msg.method; - const params = msg.params && typeof msg.params === "object" ? msg.params : {}; - - const headerVersion = request.headers.get("mcp-protocol-version") ?? undefined; - const metaVersion: string | undefined = params._meta?.[META_VERSION]; - const modern = method === "server/discover" || metaVersion !== undefined || (headerVersion !== undefined && isNewer(headerVersion)); - - if (headerVersion && metaVersion && headerVersion !== metaVersion) { - return rpcError(id, ERR.headerMismatch, "MCP-Protocol-Version header does not match _meta protocol version", undefined, 400); - } - const mcpMethod = request.headers.get("mcp-method"); - if (mcpMethod && mcpMethod !== method) { - return rpcError(id, ERR.headerMismatch, "Mcp-Method header does not match the request method", undefined, 400); - } - const requested = metaVersion ?? headerVersion; - if (requested && !SUPPORTED_VERSIONS.includes(requested) && method !== "initialize" && method !== "server/discover") { - return rpcError( - id, - ERR.unsupportedVersion, - "Unsupported protocol version", - { supported: SUPPORTED_VERSIONS, requested }, - 400, - ); - } - - const ok = (result: Record) => - json({ - jsonrpc: "2.0", - id, - result: modern ? { resultType: "complete", ...result, _meta: { [META_SERVER_INFO]: opts.serverInfo } } : result, - }); - const ttlMs = opts.listTtlMs ?? 5 * 60 * 1000; - - switch (method) { - case "initialize": { - const asked = typeof params.protocolVersion === "string" ? params.protocolVersion : ""; - const protocolVersion = LEGACY_VERSIONS.includes(asked) ? asked : LEGACY_VERSIONS[0]; - return json({ - jsonrpc: "2.0", - id, - result: { - protocolVersion, - capabilities: { tools: { listChanged: false } }, - serverInfo: opts.serverInfo, - ...(opts.instructions ? { instructions: opts.instructions } : {}), - }, - }); - } - case "server/discover": - return ok({ - supportedVersions: SUPPORTED_VERSIONS, - capabilities: { tools: { listChanged: false } }, - ...(opts.instructions ? { instructions: opts.instructions } : {}), - ttlMs, - cacheScope: "private", - }); - case "ping": - return ok({}); - case "tools/list": - return ok({ - tools: TOOLS.map((t) => ({ - name: t.name, - title: t.title, - description: t.description, - inputSchema: t.inputSchema, - annotations: t.annotations, - })), - ...(modern ? { ttlMs, cacheScope: "private" } : {}), - }); - case "tools/call": { - if (typeof params.name !== "string") return rpcError(id, ERR.invalidParams, "params.name is required"); - let ctx: ToolContext; - try { - ctx = await getContext(); - } catch (e) { - return rpcError(id, ERR.internal, `Server not configured: ${(e as Error).message}`); - } - const result = await callTool(params.name, params.arguments ?? {}, ctx); - if (!result) return rpcError(id, ERR.invalidParams, `Unknown tool: ${params.name}`); - return ok({ ...result }); - } - default: - return rpcError(id, ERR.methodNotFound, `Method not found: ${method}`, undefined, modern ? 404 : 200); - } -} diff --git a/brokers/github/test/mcp.test.ts b/brokers/github/test/mcp.test.ts index d836b6f..d2a5ab2 100644 --- a/brokers/github/test/mcp.test.ts +++ b/brokers/github/test/mcp.test.ts @@ -1,12 +1,9 @@ -// Conformance against the official MCP clients: @modelcontextprotocol/client 2.4 -// (2026-07-28 and legacy eras) and @modelcontextprotocol/sdk 1.x (legacy only). +// The real MCP SDK client against this broker's real tools. Protocol cases live in broker-core. -import { Client as Client2, StreamableHTTPClientTransport as Transport2 } from "@modelcontextprotocol/client"; -import { Client as Client1 } from "@modelcontextprotocol/sdk/client/index.js"; -import { StreamableHTTPClientTransport as Transport1 } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"; import { describe, expect, it, vi } from "vitest"; -import { MODERN_VERSION, SUPPORTED_VERSIONS, handleMcp } from "../src/mcp"; -import { TOOLS } from "../src/tools"; +import { handleMcp } from "broker-core"; +import { TOOLS, callTool } from "../src/tools"; import { fakeGitHub, toolContext } from "./fake-github"; vi.spyOn(console, "log").mockImplementation(() => {}); @@ -14,161 +11,25 @@ vi.spyOn(console, "log").mockImplementation(() => {}); const URL_ = "https://broker.test/mcp"; const opts = { serverInfo: { name: "github-broker", version: "0.0.0-test" }, instructions: "test" }; -function serverFetch(seen: { method: string; headers: Headers; body?: any }[] = []) { +function serverFetch() { const gh = fakeGitHub(); const ctx = toolContext(gh.fetchImpl); const f = async (input: RequestInfo | URL, init?: RequestInit) => { const req = new Request(input, init); - const clone = req.clone(); - let body: any; - try { - body = await clone.json(); - } catch {} - seen.push({ method: req.method, headers: req.headers, body }); - return handleMcp(req, () => ctx, opts); + return handleMcp(req, { list: TOOLS, call: callTool }, () => ctx, opts); }; return f as typeof fetch; } -async function exercise(client: { listTools: () => Promise; callTool: (p: any) => Promise }) { +it("the MCP client lists the tools and calls a real one", async () => { + const client = new Client({ name: "t", version: "1" }); + await client.connect(new StreamableHTTPClientTransport(new URL(URL_), { fetch: serverFetch() })); const tools = await client.listTools(); - expect(tools.tools.map((t: any) => t.name)).toEqual(TOOLS.map((t) => t.name)); - const res = await client.callTool({ name: "installation_info", arguments: {} }); + expect(tools.tools.map((t) => t.name)).toEqual(TOOLS.map((t) => t.name)); + const res: any = await client.callTool({ name: "installation_info", arguments: {} }); expect(res.isError).toBe(false); expect(res.content[0].text).toContain("workflows"); - const bad = await client.callTool({ name: "list_prs", arguments: {} }); + const bad: any = await client.callTool({ name: "list_prs", arguments: {} }); expect(bad.isError).toBe(true); -} - -describe("MCP over Streamable HTTP", () => { - it("2026-07-28: client 2.4 in auto mode discovers and uses the modern era", async () => { - const seen: any[] = []; - const client = new Client2({ name: "t", version: "1" }, { versionNegotiation: { mode: "auto" } }); - await client.connect(new Transport2(new URL(URL_), { fetch: serverFetch(seen) })); - await exercise(client as any); - const methods = seen.filter((s) => s.body).map((s) => s.body.method); - expect(methods[0]).toBe("server/discover"); - expect(methods).not.toContain("initialize"); - const call = seen.find((s) => s.body?.method === "tools/call"); - expect(call.headers.get("mcp-protocol-version")).toBe(MODERN_VERSION); - expect(call.body.params._meta["io.modelcontextprotocol/protocolVersion"]).toBe(MODERN_VERSION); - await client.close(); - }); - - it("2026-07-28: pinned client works too", async () => { - const client = new Client2({ name: "t", version: "1" }, { versionNegotiation: { mode: { pin: MODERN_VERSION } } }); - await client.connect(new Transport2(new URL(URL_), { fetch: serverFetch() })); - await exercise(client as any); - await client.close(); - }); - - it("legacy: client 2.4 default mode uses initialize", async () => { - const seen: any[] = []; - const client = new Client2({ name: "t", version: "1" }); - await client.connect(new Transport2(new URL(URL_), { fetch: serverFetch(seen) })); - await exercise(client as any); - expect(seen.find((s) => s.body)?.body.method).toBe("initialize"); - await client.close(); - }); - - it("legacy: SDK 1.x client", async () => { - const client = new Client1({ name: "t", version: "1" }); - await client.connect(new Transport1(new URL(URL_), { fetch: serverFetch() })); - await exercise(client as any); - await client.close(); - }); -}); - -describe("transport edges", () => { - const ctx = () => toolContext(fakeGitHub().fetchImpl); - const post = (body: unknown, headers: Record = {}) => - handleMcp( - new Request(URL_, { - method: "POST", - headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...headers }, - body: typeof body === "string" ? body : JSON.stringify(body), - }), - ctx, - { ...opts, allowedOrigins: ["https://claude.ai"] }, - ); - - it("GET and DELETE are 405", async () => { - for (const method of ["GET", "DELETE"]) { - const r = await handleMcp(new Request(URL_, { method }), ctx, opts); - expect(r.status).toBe(405); - } - }); - - it("notifications get 202 with no body", async () => { - const r = await post({ jsonrpc: "2.0", method: "notifications/initialized" }); - expect(r.status).toBe(202); - expect(await r.text()).toBe(""); - }); - - it("parse errors and batches are 400", async () => { - expect((await post("{nope")).status).toBe(400); - expect((await post([{ jsonrpc: "2.0", id: 1, method: "ping" }])).status).toBe(400); - }); - - it("an unsupported modern version gets 400 -32022 with the supported list", async () => { - const r = await post( - { jsonrpc: "2.0", id: 1, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": "2099-01-01" } } }, - { "mcp-protocol-version": "2099-01-01" }, - ); - expect(r.status).toBe(400); - const b: any = await r.json(); - expect(b.error.code).toBe(-32022); - expect(b.error.data.supported).toEqual(SUPPORTED_VERSIONS); - }); - - it("header and _meta version mismatch is 400 -32020", async () => { - const r = await post( - { jsonrpc: "2.0", id: 1, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": MODERN_VERSION } } }, - { "mcp-protocol-version": "2025-11-25" }, - ); - expect(r.status).toBe(400); - expect(((await r.json()) as any).error.code).toBe(-32020); - }); - - it("modern results carry resultType, cache hints and serverInfo", async () => { - const r = await post( - { jsonrpc: "2.0", id: 7, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": MODERN_VERSION } } }, - { "mcp-protocol-version": MODERN_VERSION, "mcp-method": "tools/list" }, - ); - const b: any = await r.json(); - expect(b.result.resultType).toBe("complete"); - expect(b.result.cacheScope).toBe("private"); - expect(b.result.ttlMs).toBeGreaterThan(0); - expect(b.result._meta["io.modelcontextprotocol/serverInfo"].name).toBe("github-broker"); - expect(r.headers.get("mcp-session-id")).toBeNull(); - }); - - it("unknown methods: 404 in the modern era, JSON-RPC error in legacy", async () => { - const modern = await post( - { jsonrpc: "2.0", id: 1, method: "nope", params: { _meta: { "io.modelcontextprotocol/protocolVersion": MODERN_VERSION } } }, - { "mcp-protocol-version": MODERN_VERSION }, - ); - expect(modern.status).toBe(404); - const legacy = await post({ jsonrpc: "2.0", id: 1, method: "nope" }); - expect(legacy.status).toBe(200); - expect(((await legacy.json()) as any).error.code).toBe(-32601); - }); - - it("unknown tool is -32602", async () => { - const r = await post({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "nope", arguments: {} } }); - expect(((await r.json()) as any).error.code).toBe(-32602); - }); - - it("a foreign Origin is 403 when an allowlist is set", async () => { - expect((await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { origin: "https://evil.example" })).status).toBe(403); - expect((await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { origin: "https://claude.ai" })).status).toBe(200); - }); - - it("initialize answers the client's legacy version, or the newest legacy one", async () => { - const ask = async (v: string) => - ((await (await post({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: v, capabilities: {}, clientInfo: { name: "x", version: "1" } } })).json()) as any).result - .protocolVersion; - expect(await ask("2025-06-18")).toBe("2025-06-18"); - expect(await ask("2024-11-05")).toBe("2025-11-25"); - }); + await client.close(); }); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 0bb2ebe..c900af9 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -2,3 +2,5 @@ export { VERSION } from "./version"; export { publicUrl, required, base64url } from "./util"; export { ToolInputError, truncate, validateArgs } from "./tools"; export type { JsonSchema, ToolDef, ToolResult } from "./tools"; +export { handleMcp, MODERN_VERSION, LEGACY_VERSIONS, SUPPORTED_VERSIONS } from "./mcp"; +export type { McpOptions, McpTools } from "./mcp"; diff --git a/brokers/discord/src/mcp.ts b/packages/core/src/mcp.ts similarity index 93% rename from brokers/discord/src/mcp.ts rename to packages/core/src/mcp.ts index 288fdee..87b83a0 100644 --- a/brokers/discord/src/mcp.ts +++ b/packages/core/src/mcp.ts @@ -6,7 +6,7 @@ // MCP-Protocol-Version header; results carry resultType and serverInfo in _meta. // - 2025-11-25 / 2025-06-18 / 2025-03-26: initialize + notifications/initialized. -import { TOOLS, ToolContext, callTool } from "./tools"; +import type { ToolDef, ToolResult } from "./tools"; export const MODERN_VERSION = "2026-07-28"; export const LEGACY_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26"]; @@ -34,6 +34,12 @@ export interface McpOptions { listTtlMs?: number; } +export interface McpTools { + list: readonly ToolDef[]; + /** null = unknown tool */ + call(name: string, args: unknown, ctx: C): Promise; +} + type Id = string | number | null; function json(body: unknown, status = 200, extra: Record = {}): Response { @@ -52,9 +58,10 @@ function isNewer(v: string): boolean { return v >= MODERN_VERSION; } -export async function handleMcp( +export async function handleMcp( request: Request, - getContext: () => ToolContext | Promise, + tools: McpTools, + getContext: () => C | Promise, opts: McpOptions, ): Promise { const origin = request.headers.get("origin"); @@ -141,7 +148,7 @@ export async function handleMcp( return ok({}); case "tools/list": return ok({ - tools: TOOLS.map((t) => ({ + tools: tools.list.map((t) => ({ name: t.name, title: t.title, description: t.description, @@ -152,13 +159,13 @@ export async function handleMcp( }); case "tools/call": { if (typeof params.name !== "string") return rpcError(id, ERR.invalidParams, "params.name is required"); - let ctx: ToolContext; + let ctx: C; try { ctx = await getContext(); } catch (e) { return rpcError(id, ERR.internal, `Server not configured: ${(e as Error).message}`); } - const result = await callTool(params.name, params.arguments ?? {}, ctx); + const result = await tools.call(params.name, params.arguments ?? {}, ctx); if (!result) return rpcError(id, ERR.invalidParams, `Unknown tool: ${params.name}`); return ok({ ...result }); } diff --git a/packages/core/test/mcp.test.ts b/packages/core/test/mcp.test.ts new file mode 100644 index 0000000..aae21db --- /dev/null +++ b/packages/core/test/mcp.test.ts @@ -0,0 +1,211 @@ +// Conformance against the official MCP clients: @modelcontextprotocol/client 2.4 +// (2026-07-28 and legacy eras) and @modelcontextprotocol/sdk 1.x (legacy only). + +import { Client as Client2, StreamableHTTPClientTransport as Transport2 } from "@modelcontextprotocol/client"; +import { Client as Client1 } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport as Transport1 } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { describe, expect, it, vi } from "vitest"; +import { MODERN_VERSION, SUPPORTED_VERSIONS, handleMcp, type McpTools } from "../src/mcp"; +import { type ToolDef, type ToolResult, validateArgs } from "../src/tools"; + +vi.spyOn(console, "log").mockImplementation(() => {}); + +type Ctx = { tag: string }; + +const TOOLS: ToolDef[] = [ + { + name: "echo", + title: "Echo", + description: "Return text.", + inputSchema: { type: "object", properties: { text: { type: "string" } }, required: ["text"], additionalProperties: false }, + annotations: { readOnlyHint: true }, + run: async (a) => a.text, + }, + { + name: "boom", + title: "Boom", + description: "Always throws.", + inputSchema: { type: "object", properties: {}, additionalProperties: false }, + annotations: {}, + run: async () => { + throw new Error("boom"); + }, + }, +]; + +const tools: McpTools = { + list: TOOLS, + async call(name, args, ctx): Promise { + const tool = TOOLS.find((t) => t.name === name); + if (!tool) return null; + const bad = validateArgs(tool.inputSchema, args); + if (bad) return { content: [{ type: "text", text: bad }], isError: true }; + try { + return { content: [{ type: "text", text: String(await tool.run((args ?? {}) as any, ctx)) }], isError: false }; + } catch (e) { + return { content: [{ type: "text", text: (e as Error).message }], isError: true }; + } + }, +}; + +const URL_ = "https://broker.test/mcp"; +const opts = { serverInfo: { name: "test-broker", version: "0.0.0-test" }, instructions: "test" }; + +function serverFetch(seen: { method: string; headers: Headers; body?: any }[] = []) { + const ctx: Ctx = { tag: "t" }; + const f = async (input: RequestInfo | URL, init?: RequestInit) => { + const req = new Request(input, init); + const clone = req.clone(); + let body: any; + try { + body = await clone.json(); + } catch {} + seen.push({ method: req.method, headers: req.headers, body }); + return handleMcp(req, tools, () => ctx, opts); + }; + return f as typeof fetch; +} + +async function exercise(client: { listTools: () => Promise; callTool: (p: any) => Promise }) { + const tools = await client.listTools(); + expect(tools.tools.map((t: any) => t.name)).toEqual(TOOLS.map((t) => t.name)); + const res = await client.callTool({ name: "echo", arguments: { text: "hi" } }); + expect(res.isError).toBe(false); + expect(res.content[0].text).toBe("hi"); + const bad = await client.callTool({ name: "echo", arguments: {} }); + expect(bad.isError).toBe(true); +} + +describe("MCP over Streamable HTTP", () => { + it("2026-07-28: client 2.4 in auto mode discovers and uses the modern era", async () => { + const seen: any[] = []; + const client = new Client2({ name: "t", version: "1" }, { versionNegotiation: { mode: "auto" } }); + await client.connect(new Transport2(new URL(URL_), { fetch: serverFetch(seen) })); + await exercise(client as any); + const methods = seen.filter((s) => s.body).map((s) => s.body.method); + expect(methods[0]).toBe("server/discover"); + expect(methods).not.toContain("initialize"); + const call = seen.find((s) => s.body?.method === "tools/call"); + expect(call.headers.get("mcp-protocol-version")).toBe(MODERN_VERSION); + expect(call.body.params._meta["io.modelcontextprotocol/protocolVersion"]).toBe(MODERN_VERSION); + await client.close(); + }); + + it("2026-07-28: pinned client works too", async () => { + const client = new Client2({ name: "t", version: "1" }, { versionNegotiation: { mode: { pin: MODERN_VERSION } } }); + await client.connect(new Transport2(new URL(URL_), { fetch: serverFetch() })); + await exercise(client as any); + await client.close(); + }); + + it("legacy: client 2.4 default mode uses initialize", async () => { + const seen: any[] = []; + const client = new Client2({ name: "t", version: "1" }); + await client.connect(new Transport2(new URL(URL_), { fetch: serverFetch(seen) })); + await exercise(client as any); + expect(seen.find((s) => s.body)?.body.method).toBe("initialize"); + await client.close(); + }); + + it("legacy: SDK 1.x client", async () => { + const client = new Client1({ name: "t", version: "1" }); + await client.connect(new Transport1(new URL(URL_), { fetch: serverFetch() })); + await exercise(client as any); + await client.close(); + }); +}); + +describe("transport edges", () => { + const ctx = (): Ctx => ({ tag: "t" }); + const post = (body: unknown, headers: Record = {}) => + handleMcp( + new Request(URL_, { + method: "POST", + headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...headers }, + body: typeof body === "string" ? body : JSON.stringify(body), + }), + tools, + ctx, + { ...opts, allowedOrigins: ["https://claude.ai"] }, + ); + + it("GET and DELETE are 405", async () => { + for (const method of ["GET", "DELETE"]) { + const r = await handleMcp(new Request(URL_, { method }), tools, ctx, opts); + expect(r.status).toBe(405); + } + }); + + it("notifications get 202 with no body", async () => { + const r = await post({ jsonrpc: "2.0", method: "notifications/initialized" }); + expect(r.status).toBe(202); + expect(await r.text()).toBe(""); + }); + + it("parse errors and batches are 400", async () => { + expect((await post("{nope")).status).toBe(400); + expect((await post([{ jsonrpc: "2.0", id: 1, method: "ping" }])).status).toBe(400); + }); + + it("an unsupported modern version gets 400 -32022 with the supported list", async () => { + const r = await post( + { jsonrpc: "2.0", id: 1, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": "2099-01-01" } } }, + { "mcp-protocol-version": "2099-01-01" }, + ); + expect(r.status).toBe(400); + const b: any = await r.json(); + expect(b.error.code).toBe(-32022); + expect(b.error.data.supported).toEqual(SUPPORTED_VERSIONS); + }); + + it("header and _meta version mismatch is 400 -32020", async () => { + const r = await post( + { jsonrpc: "2.0", id: 1, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": MODERN_VERSION } } }, + { "mcp-protocol-version": "2025-11-25" }, + ); + expect(r.status).toBe(400); + expect(((await r.json()) as any).error.code).toBe(-32020); + }); + + it("modern results carry resultType, cache hints and serverInfo", async () => { + const r = await post( + { jsonrpc: "2.0", id: 7, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": MODERN_VERSION } } }, + { "mcp-protocol-version": MODERN_VERSION, "mcp-method": "tools/list" }, + ); + const b: any = await r.json(); + expect(b.result.resultType).toBe("complete"); + expect(b.result.cacheScope).toBe("private"); + expect(b.result.ttlMs).toBeGreaterThan(0); + expect(b.result._meta["io.modelcontextprotocol/serverInfo"].name).toBe("test-broker"); + expect(r.headers.get("mcp-session-id")).toBeNull(); + }); + + it("unknown methods: 404 in the modern era, JSON-RPC error in legacy", async () => { + const modern = await post( + { jsonrpc: "2.0", id: 1, method: "nope", params: { _meta: { "io.modelcontextprotocol/protocolVersion": MODERN_VERSION } } }, + { "mcp-protocol-version": MODERN_VERSION }, + ); + expect(modern.status).toBe(404); + const legacy = await post({ jsonrpc: "2.0", id: 1, method: "nope" }); + expect(legacy.status).toBe(200); + expect(((await legacy.json()) as any).error.code).toBe(-32601); + }); + + it("answers an unknown tool with -32602", async () => { + const res = await post({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "nope" } }); + expect(((await res.json()) as any).error.code).toBe(-32602); + }); + + it("a foreign Origin is 403 when an allowlist is set", async () => { + expect((await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { origin: "https://evil.example" })).status).toBe(403); + expect((await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { origin: "https://claude.ai" })).status).toBe(200); + }); + + it("initialize answers the client's legacy version, or the newest legacy one", async () => { + const ask = async (v: string) => + ((await (await post({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: v, capabilities: {}, clientInfo: { name: "x", version: "1" } } })).json()) as any).result + .protocolVersion; + expect(await ask("2025-06-18")).toBe("2025-06-18"); + expect(await ask("2024-11-05")).toBe("2025-11-25"); + }); +}); From a5b5f084b332ff36e0febcb4069cd7a03927df41 Mon Sep 17 00:00:00 2001 From: Cycle Five Date: Thu, 19 Nov 2026 17:26:12 -0500 Subject: [PATCH 3/9] feat: sign-in flow and request router in broker-core Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) --- packages/core/src/index.ts | 5 + packages/core/src/pages.ts | 48 +++++ packages/core/src/signin.ts | 160 ++++++++++++++++ packages/core/src/worker.ts | 121 ++++++++++++ packages/core/test-support/index.ts | 85 +++++++++ packages/core/test-support/workers-flags.ts | 3 + packages/core/test/pages.test.ts | 29 +++ packages/core/test/worker.test.ts | 201 ++++++++++++++++++++ packages/core/vitest.config.ts | 4 +- 9 files changed, 654 insertions(+), 2 deletions(-) create mode 100644 packages/core/src/pages.ts create mode 100644 packages/core/src/signin.ts create mode 100644 packages/core/src/worker.ts create mode 100644 packages/core/test-support/workers-flags.ts create mode 100644 packages/core/test/pages.test.ts create mode 100644 packages/core/test/worker.test.ts diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index c900af9..1442614 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -4,3 +4,8 @@ export { ToolInputError, truncate, validateArgs } from "./tools"; export type { JsonSchema, ToolDef, ToolResult } from "./tools"; export { handleMcp, MODERN_VERSION, LEGACY_VERSIONS, SUPPORTED_VERSIONS } from "./mcp"; export type { McpOptions, McpTools } from "./mcp"; +export { escapeHtml, page, consentPage, errorPage } from "./pages"; +export { handleAuthorize, handleCallback } from "./signin"; +export type { Exchanged, SignInProvider, WaitUntil } from "./signin"; +export { createBroker } from "./worker"; +export type { BaseEnv, BrokerConfig } from "./worker"; diff --git a/packages/core/src/pages.ts b/packages/core/src/pages.ts new file mode 100644 index 0000000..2ebc044 --- /dev/null +++ b/packages/core/src/pages.ts @@ -0,0 +1,48 @@ +// The HTML pages of the sign-in flow: consent and error. + +import type { ConsentDescription } from "@cloudflare/workers-oauth-provider"; + +export function escapeHtml(s: string): string { + return s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!); +} + +export function page(title: string, body: string, headers?: Headers, status = 200): Response { + const h = headers ?? new Headers(); + h.set("Content-Type", "text/html; charset=utf-8"); + h.set("Cache-Control", "no-store"); + h.set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'"); + return new Response( + `${escapeHtml(title)} + +${body}`, + { status, headers: h }, + ); +} + +export function consentPage( + d: ConsentDescription, + handle: string, + headers: Headers, + text: { title: string; label: string; grants: string }, +): Response { + const who = d.clientDomain ? `${escapeHtml(d.clientName)} (verified domain ${escapeHtml(d.clientDomain)})` : escapeHtml(d.clientName); + return page( + `Connect ${text.title}`, + `

Connect ${escapeHtml(text.title)}

+

${who} ${escapeHtml(text.grants)}

+

Access will be sent to ${escapeHtml(d.redirectHost)}${d.redirectIsLoopback ? " (an app on this computer)" : ""}.

+

Only continue if you started this yourself, from Claude, and that host is claude.ai (or localhost for Claude Code).

+
+ + + +
`, + headers, + ); +} + +export function errorPage(message: string, status = 400): Response { + return page("Sign-in failed", `

Sign-in failed

${escapeHtml(message)}

`, undefined, status); +} diff --git a/packages/core/src/signin.ts b/packages/core/src/signin.ts new file mode 100644 index 0000000..3daf6d0 --- /dev/null +++ b/packages/core/src/signin.ts @@ -0,0 +1,160 @@ +// Sign-in for the MCP endpoint: a consent page, then sign-in with the upstream service +// (through a SignInProvider), then an allowlist check. The upstream user token is used +// once to identify the user and then revoked; it is never stored. + +import { + AuthorizationError, + CimdFetchError, + authorizationErrorRedirect, + type OAuthHelpers, +} from "@cloudflare/workers-oauth-provider"; +import { consentPage, errorPage } from "./pages"; +import { base64url, publicUrl } from "./util"; +import type { BaseEnv } from "./worker"; + +export type Exchanged

= { ok: true; userId: string; props: P } | { ok: false; status: number; message: string }; + +export interface WaitUntil { + waitUntil(p: Promise): void; +} + +export interface SignInProvider { + /** The one OAuth scope this broker grants (besides offline_access). */ + scope: string; + /** Upstream service name on buttons and messages: "Discord". */ + label: string; + /** Consent sentence after the client's name. */ + grants: string; + /** Text describing a configuration mistake, or null when configured. */ + configProblem(env: E): string | null; + /** Whether to send a PKCE challenge upstream. */ + pkce(env: E): boolean; + /** The complete upstream authorize URL. */ + authorizeUrl(env: E, p: { redirectUri: string; state: string; challenge?: string }): string; + /** Trade the upstream code for the user's identity; revoke the user token via ctx.waitUntil. */ + exchange( + env: E, + p: { code: string; redirectUri: string; verifier?: string }, + ctx: WaitUntil, + fetchImpl?: typeof fetch, + ): Promise>; + isAllowed(env: E, props: P): boolean; + refusal(props: P): string; +} + +async function sha256b64url(s: string): Promise { + return base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)))); +} + +function randomVerifier(): string { + const b = new Uint8Array(32); + crypto.getRandomValues(b); + return base64url(b); +} + +function redirect(location: string, headers?: Headers): Response { + const h = headers ?? new Headers(); + h.set("Location", location); + return new Response(null, { status: 302, headers: h }); +} + +function renderAuthError(e: unknown): Response { + if (e instanceof AuthorizationError) { + console.log(JSON.stringify({ event: "authorize_error", code: e.code, description: e.description, redirect: Boolean(e.redirectTo) })); + if (e.redirectTo) return redirect(e.redirectTo); + return errorPage(e.description, 400); + } + if (e instanceof CimdFetchError) { + // The client identified itself by a metadata URL that this Worker could not fetch. + console.log(JSON.stringify({ event: "cimd_fetch_failed", url: e.metadataUrl, detail: e.detail })); + return errorPage(`Could not fetch the client's metadata document (${e.metadataUrl}): ${e.detail}. Setting DISABLE_CIMD="true" makes clients register instead.`, 502); + } + console.log(JSON.stringify({ event: "authorize_exception", message: (e as Error)?.message })); + return errorPage(`Unexpected error: ${(e as Error)?.message ?? String(e)}`, 500); +} + +/** GET and POST /authorize. */ +export async function handleAuthorize( + request: Request, + env: E, + oauth: OAuthHelpers, + signIn: SignInProvider, + title: string, +): Promise { + try { + if (request.method === "GET") { + const authReq = await oauth.parseAuthRequest(request); + const details = await oauth.describeConsent(authReq); + const consent = await oauth.beginConsent(authReq); + return consentPage(details, consent.handle, consent.headers, { title, label: signIn.label, grants: signIn.grants }); + } + if (request.method !== "POST") return new Response("Method Not Allowed", { status: 405 }); + + const form = await request.formData(); + const handle = String(form.get("handle") ?? ""); + if (form.get("decision") !== "approve") { + const denied = await oauth.denyConsent(request, handle); + return new Response(null, { status: 302, headers: denied.headers }); + } + // One scope covers everything; offline_access lets the client refresh without a new sign-in. + const approved = await oauth.approveConsent(request, handle, { scope: [signIn.scope, "offline_access"] }); + + const problem = signIn.configProblem(env); + if (problem) { + console.log(JSON.stringify({ event: "config_error", message: problem })); + return errorPage(problem, 500); + } + const pkce = signIn.pkce(env); + const verifier = pkce ? randomVerifier() : ""; + const up = await oauth.beginUpstream(approved.request, { data: { verifier }, headers: approved.headers }); + const url = signIn.authorizeUrl(env, { + redirectUri: `${publicUrl(env)}/callback`, + state: up.state, + challenge: pkce ? await sha256b64url(verifier) : undefined, + }); + return redirect(url, up.headers); + } catch (e) { + return renderAuthError(e); + } +} + +/** GET /callback from the upstream service. */ +export async function handleCallback( + request: Request, + env: E, + oauth: OAuthHelpers, + ctx: WaitUntil, + signIn: SignInProvider, + fetchImpl: typeof fetch = (...a) => fetch(...a), +): Promise { + let resumed; + try { + resumed = await oauth.finishUpstream<{ verifier: string }>(request); + } catch (e) { + return renderAuthError(e); + } + const { request: authReq, data, headers } = resumed; + const params = new URL(request.url).searchParams; + const code = params.get("code"); + if (params.get("error") || !code) { + console.log(JSON.stringify({ event: "sign_in_cancelled", error: params.get("error"), description: params.get("error_description") })); + return redirect(authorizationErrorRedirect(authReq, "access_denied", `${signIn.label} sign-in was cancelled`), headers); + } + + const id = await signIn.exchange(env, { code, redirectUri: `${publicUrl(env)}/callback`, verifier: data.verifier }, ctx, fetchImpl); + if (!id.ok) return errorPage(id.message, id.status); + if (!signIn.isAllowed(env, id.props)) { + console.log(JSON.stringify({ event: "sign_in_refused", ...id.props })); + return errorPage(signIn.refusal(id.props), 403); + } + + const { redirectTo } = await oauth.completeAuthorization({ + request: authReq, + userId: id.userId, + metadata: id.props, + scope: authReq.scope, + props: id.props, + }); + console.log(JSON.stringify({ event: "sign_in", ...id.props, client: authReq.clientId })); + return redirect(redirectTo, headers); +} diff --git a/packages/core/src/worker.ts b/packages/core/src/worker.ts new file mode 100644 index 0000000..02c962d --- /dev/null +++ b/packages/core/src/worker.ts @@ -0,0 +1,121 @@ +// The Worker entry point shared by the brokers: OAuth endpoints, sign-in pages and /mcp. +// +// /mcp MCP endpoint (OAuth bearer required) +// /.well-known/oauth-protected-resource RFC 9728 metadata (resource server) +// /.well-known/oauth-authorization-server, /oauth/token, /oauth/register (library) +// /authorize, /callback consent page + sign-in with the upstream service + +import { + OAuthAuthorizationServer, + OAuthResourceServer, + insufficientScope, + type OAuthResourceContext, +} from "@cloudflare/workers-oauth-provider"; +import { handleMcp, type McpTools } from "./mcp"; +import { handleAuthorize, handleCallback, type SignInProvider } from "./signin"; +import { publicUrl } from "./util"; +import { VERSION } from "./version"; + +export interface BaseEnv { + OAUTH_KV: KVNamespace; + PUBLIC_URL: string; + ALLOWED_ORIGINS?: string; + DISABLE_CIMD?: string; +} + +export interface BrokerConfig { + /** "discord-broker": serverInfo.name and the "/" banner. */ + name: string; + /** "Discord broker": serverInfo.title, resource_name, page headings. */ + title: string; + instructions: string; + signIn: SignInProvider; + tools: McpTools; + /** May throw; handleMcp reports it as "Server not configured: ...". */ + context(env: E, user: P): C; +} + +export function createBroker( + cfg: BrokerConfig, +): { fetch(request: Request, env: E, ctx: ExecutionContext): Promise } { + const { signIn } = cfg; + + interface Roles { + key: string; + as: OAuthAuthorizationServer; + rs: OAuthResourceServer; + } + let roles: Roles | undefined; + + function getRoles(env: E): Roles { + const url = publicUrl(env); + const key = `${url}|${env.DISABLE_CIMD ?? ""}`; + if (roles && roles.key === key) return roles; + const resource = `${url}/mcp`; + + const as = new OAuthAuthorizationServer({ + issuer: url, + resources: [resource], + scopesSupported: [signIn.scope, "offline_access"], + clientRegistrationEndpoint: "/oauth/register", + // Claude prefers CIMD when advertised. DISABLE_CIMD="true" forces Dynamic Client Registration. + clientIdMetadataDocumentEnabled: env.DISABLE_CIMD !== "true", + accessTokenTTL: 3600, + }); + + const rs = new OAuthResourceServer({ + resourceMetadata: { resource, authorization_servers: [url], resource_name: cfg.title }, + requiredScopes: [signIn.scope], + validateToken: (e) => (res, token) => as.validateToken

(res, token, e), + handler: { + async fetch(request: Request, env: E, ctx: OAuthResourceContext

) { + if (!ctx.auth.scope.includes(signIn.scope)) return insufficientScope(ctx.auth, [signIn.scope]); + const props = ctx.props; + // Re-check on every request, so removing someone from the allowlist takes effect at once. + if (!props || !signIn.isAllowed(env, props)) { + return new Response("Forbidden", { status: 403 }); + } + return handleMcp(request, cfg.tools, () => cfg.context(env, props), { + serverInfo: { name: cfg.name, title: cfg.title, version: VERSION }, + instructions: cfg.instructions, + allowedOrigins: env.ALLOWED_ORIGINS?.split(",").map((s) => s.trim()).filter(Boolean), + }); + }, + }, + }); + + roles = { key, as, rs }; + return roles; + } + + async function route(request: Request, env: E, ctx: ExecutionContext): Promise { + const { pathname } = new URL(request.url); + const { as, rs } = getRoles(env); + + if (pathname === "/authorize") return handleAuthorize(request, env, as.getOAuthApi(env), signIn, cfg.title); + if (pathname === "/callback") return handleCallback(request, env, as.getOAuthApi(env), ctx, signIn); + if (pathname === "/mcp" || pathname.startsWith("/mcp/") || pathname.startsWith("/.well-known/oauth-protected-resource")) { + return rs.fetch(request, env, ctx); + } + if (pathname === "/" && request.method === "GET") { + return new Response(`${cfg.name} ${VERSION}: MCP endpoint at ${publicUrl(env)}/mcp\n`, { + headers: { "Content-Type": "text/plain; charset=utf-8" }, + }); + } + // Log every OAuth endpoint hit (path and status only) to make connector problems visible in `wrangler tail`. + const res = await as.fetch(request, env, ctx); + console.log(JSON.stringify({ event: "oauth_endpoint", method: request.method, path: pathname, status: res.status })); + return res; + } + + return { + async fetch(request: Request, env: E, ctx: ExecutionContext): Promise { + try { + return await route(request, env, ctx); + } catch (e) { + console.log(JSON.stringify({ event: "unhandled", method: request.method, path: new URL(request.url).pathname, message: (e as Error)?.message })); + return new Response(`Internal error: ${(e as Error)?.message ?? "unknown"}\n`, { status: 500, headers: { "Content-Type": "text/plain" } }); + } + }, + }; +} diff --git a/packages/core/test-support/index.ts b/packages/core/test-support/index.ts index 5fcdf92..ce84829 100644 --- a/packages/core/test-support/index.ts +++ b/packages/core/test-support/index.ts @@ -20,3 +20,88 @@ export class MemoryKV { return { keys: keys.map((name) => ({ name, metadata: this.m.get(name)!.metadata })), list_complete: true, cursor: "" }; } } + +/** Fold a response's Set-Cookie headers into a request Cookie header value. */ +export function cookieHeader(res: Response, prior = ""): string { + const jar = new Map(prior.split("; ").filter(Boolean).map((c) => c.split("=", 2) as [string, string])); + for (const sc of res.headers.getSetCookie()) { + const [nv] = sc.split(";"); + const i = nv.indexOf("="); + jar.set(nv.slice(0, i), nv.slice(i + 1)); + } + return [...jar].map(([k, v]) => `${k}=${v}`).join("; "); +} + +export const DRIVER_REDIRECT = "https://claude.ai/api/mcp/auth_callback"; + +export interface SignInDriver { + /** Send a request to the Worker under test. */ + call(path: string, init?: RequestInit): Promise; + /** Base URL of the Worker, no trailing slash. */ + base: string; + clientName?: string; +} + +/** + * Drive the OAuth flow up to the approval: register a client, fetch the consent page, approve. + * Returns what each step answered so a test can look at any of them. + */ +export async function startSignIn(d: SignInDriver) { + const reg = await d.call("/oauth/register", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ client_name: d.clientName ?? "Claude", redirect_uris: [DRIVER_REDIRECT], token_endpoint_auth_method: "none" }), + }); + const { client_id } = (await reg.json()) as { client_id: string }; + + const verifier = btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); + const challenge = btoa(String.fromCharCode(...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))))) + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); + const q = new URLSearchParams({ + response_type: "code", + client_id, + redirect_uri: DRIVER_REDIRECT, + scope: "fake offline_access", + state: "st8", + code_challenge: challenge, + code_challenge_method: "S256", + resource: `${d.base}/mcp`, + }); + const consent = await d.call(`/authorize?${q}`); + const html = await consent.clone().text(); + const handle = html.match(/name="handle" value="([^"]+)"/)?.[1] ?? ""; + const cookies = cookieHeader(consent); + const approve = await d.call("/authorize", { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded", cookie: cookies }, + body: new URLSearchParams({ handle, decision: "approve" }).toString(), + }); + return { client_id, verifier, consent, html, approve, cookies: cookieHeader(approve, cookies) }; +} + +/** Finish the flow from an approved start: call /callback with the upstream code and, if it redirects with a code, redeem it. */ +export async function finishSignIn(d: SignInDriver, s: Awaited>, upstreamCode: string) { + const up = new URL(s.approve.headers.get("location")!); + const cb = await d.call(`/callback?code=${encodeURIComponent(upstreamCode)}&state=${encodeURIComponent(up.searchParams.get("state")!)}`, { + headers: { cookie: s.cookies }, + }); + const back = cb.headers.get("location") ? new URL(cb.headers.get("location")!) : null; + const code = back?.searchParams.get("code"); + if (!code) return { cb, token: null as string | null }; + const tok = await d.call("/oauth/token", { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + grant_type: "authorization_code", + code, + redirect_uri: DRIVER_REDIRECT, + client_id: s.client_id, + code_verifier: s.verifier, + resource: `${d.base}/mcp`, + }).toString(), + }); + const t = (await tok.json()) as { access_token?: string }; + return { cb, token: t.access_token ?? null }; +} diff --git a/packages/core/test-support/workers-flags.ts b/packages/core/test-support/workers-flags.ts new file mode 100644 index 0000000..dea9493 --- /dev/null +++ b/packages/core/test-support/workers-flags.ts @@ -0,0 +1,3 @@ +// Production runs with the global_fetch_strictly_public compatibility flag; Node cannot see it, +// so the OAuth library prints a "CIMD is disabled" notice on import. Present the flag. +(globalThis as any).Cloudflare = { compatibilityFlags: { global_fetch_strictly_public: true } }; diff --git a/packages/core/test/pages.test.ts b/packages/core/test/pages.test.ts new file mode 100644 index 0000000..2b740a9 --- /dev/null +++ b/packages/core/test/pages.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; +import { consentPage, errorPage, escapeHtml } from "../src/pages"; + +describe("pages", () => { + it("escapes HTML", () => { + expect(escapeHtml(`&`)).toBe("<a href="x" onclick='y'>&</a>"); + }); + + it("errorPage carries the status, the CSP and no-store", () => { + const r = errorPage("x", 418); + expect(r.status).toBe(418); + expect(r.headers.get("content-security-policy")).toBe("default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'"); + expect(r.headers.get("cache-control")).toBe("no-store"); + }); + + it("consentPage names the broker, the grant and the upstream service", async () => { + const r = consentPage( + { clientName: "C", redirectHost: "claude.ai", redirectIsLoopback: false } as any, + "h", + new Headers(), + { title: "Fake broker", label: "Fake", grants: "wants to test." }, + ); + const html = await r.text(); + expect(html).toContain("Connect Fake broker"); + expect(html).toContain("wants to test."); + expect(html).toContain("Continue to Fake"); + expect(r.headers.get("cache-control")).toBe("no-store"); + }); +}); diff --git a/packages/core/test/worker.test.ts b/packages/core/test/worker.test.ts new file mode 100644 index 0000000..36d209b --- /dev/null +++ b/packages/core/test/worker.test.ts @@ -0,0 +1,201 @@ +import { createHash } from "node:crypto"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { MemoryKV, cookieHeader, finishSignIn, startSignIn, type SignInDriver } from "broker-core/testing"; +import { VERSION } from "../src/version"; +import { createBroker, type BaseEnv } from "../src/worker"; +import type { SignInProvider } from "../src/signin"; + +const logs: string[] = []; +vi.spyOn(console, "log").mockImplementation((s: string) => void logs.push(String(s))); +vi.spyOn(console, "warn").mockImplementation(() => {}); + +type P = { id: string; name: string }; +interface TestEnv extends BaseEnv { + ALLOWED: string; + BROKEN?: string; + PKCE?: string; +} +let seen: { code: string; redirectUri: string; verifier?: string }[] = []; +const signIn: SignInProvider = { + scope: "fake", + label: "Fake", + grants: "wants to test.", + configProblem: (e) => (e.BROKEN ? "BROKEN is set" : null), + pkce: (e) => e.PKCE === "true", + authorizeUrl: (_e, p) => + `https://up.test/authorize?${new URLSearchParams({ state: p.state, redirect_uri: p.redirectUri, ...(p.challenge ? { code_challenge: p.challenge } : {}) })}`, + exchange: async (_e, p) => { + seen.push(p); + return p.code === "bad" + ? { ok: false, status: 502, message: "Fake did not return a token." } + : { ok: true, userId: p.code, props: { id: p.code, name: "n" } }; + }, + isAllowed: (e, u) => e.ALLOWED.split(",").includes(u.id), + refusal: (u) => `Fake account ${u.id} is not allowed.`, +}; + +let contexts: P[] = []; +const broker = createBroker({ + name: "fake-broker", + title: "Fake broker", + instructions: "Fake tools.", + signIn, + tools: { + list: [ + { + name: "whoami", + title: "Who am I", + description: "Return the context.", + inputSchema: { type: "object", properties: {}, additionalProperties: false }, + annotations: { readOnlyHint: true }, + run: async (_a, ctx) => JSON.stringify(ctx, null, 2), + }, + ], + async call(name, _args, ctx) { + if (name !== "whoami") return null; + return { content: [{ type: "text", text: JSON.stringify(ctx, null, 2) }], isError: false } as any; + }, + }, + context: (_e, user) => { + contexts.push(user); + return user; + }, +}); + +const BASE = "https://broker.test"; +const ctx = { waitUntil() {}, passThroughOnException() {}, props: {} } as unknown as ExecutionContext; +const env = (extra: Partial = {}): TestEnv => ({ OAUTH_KV: new MemoryKV() as unknown as KVNamespace, PUBLIC_URL: BASE, ALLOWED: "u1", ...extra }); +const driver = (e: TestEnv): SignInDriver => ({ base: BASE, call: (path, init) => broker.fetch(new Request(BASE + path, init), e, ctx) }); +const mcp = (e: TestEnv, token: string, body: unknown) => + broker.fetch( + new Request(BASE + "/mcp", { + method: "POST", + headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json, text/event-stream" }, + body: JSON.stringify(body), + }), + e, + ctx, + ); +const whoami = { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "whoami", arguments: {} } }; + +async function signedIn(e: TestEnv, code = "u1") { + const d = driver(e); + const s = await startSignIn(d); + return { d, s, ...(await finishSignIn(d, s, code)) }; +} + +beforeEach(() => { + logs.length = 0; + seen = []; + contexts = []; +}); +afterEach(() => vi.unstubAllGlobals()); + +describe("createBroker", () => { + it("signs in and serves MCP", async () => { + const e = env(); + const { token } = await signedIn(e); + expect(token).toBeTruthy(); + const r = (await (await mcp(e, token!, whoami)).json()) as any; + expect(r.result.content[0].text).toContain('"id": "u1"'); + const root = await broker.fetch(new Request(BASE + "/"), e, ctx); + expect(await root.text()).toBe(`fake-broker ${VERSION}: MCP endpoint at https://broker.test/mcp\n`); + }); + + it("hands the provider's props to the context unchanged", async () => { + const e = env(); + const { token } = await signedIn(e); + await mcp(e, token!, whoami); + expect(contexts[0]).toEqual({ id: "u1", name: "n" }); + }); + + it("re-checks the allowlist on every request", async () => { + const e = env(); + const { token } = await signedIn(e); + e.ALLOWED = ""; + expect((await mcp(e, token!, whoami)).status).toBe(403); + }); + + it("stops at the config check before going upstream", async () => { + const s = await startSignIn(driver(env({ BROKEN: "1" }))); + expect(s.approve.status).toBe(500); + expect(await s.approve.text()).toContain("BROKEN is set"); + expect(s.approve.headers.get("location")).toBeNull(); + expect(logs.some((l) => l.includes('"config_error"'))).toBe(true); + }); + + it("sends a PKCE challenge only when the provider asks", async () => { + const off = await signedIn(env()); + expect(new URL(off.s.approve.headers.get("location")!).searchParams.has("code_challenge")).toBe(false); + expect(seen[0].verifier).toBeFalsy(); + + seen = []; + const on = await signedIn(env({ PKCE: "true" })); + const challenge = new URL(on.s.approve.headers.get("location")!).searchParams.get("code_challenge"); + expect(challenge).toBeTruthy(); + expect(createHash("sha256").update(seen[0].verifier!).digest("base64url")).toBe(challenge); + }); + + it("refuses an account the provider rejects", async () => { + const { cb } = await signedIn(env(), "u2"); + expect(cb.status).toBe(403); + expect(await cb.text()).toContain("Fake account u2 is not allowed."); + }); + + it("sends a cancelled sign-in back as access_denied", async () => { + const d = driver(env()); + const s = await startSignIn(d); + const state = new URL(s.approve.headers.get("location")!).searchParams.get("state")!; + const cb = await d.call(`/callback?error=access_denied&state=${encodeURIComponent(state)}`, { headers: { cookie: s.cookies } }); + expect(cb.status).toBe(302); + const loc = cb.headers.get("location")!; + expect(loc.startsWith("https://claude.ai/api/mcp/auth_callback")).toBe(true); + expect(new URL(loc).searchParams.get("error")).toBe("access_denied"); + }); + + it("shows the provider's message when the exchange fails", async () => { + const { cb } = await signedIn(env(), "bad"); + expect(cb.status).toBe(502); + expect(await cb.text()).toContain("Fake did not return a token."); + }); + + it("DISABLE_CIMD turns client metadata documents off", async () => { + // The flag is presented by test-support/workers-flags.ts, as it is in production. + const meta = async (e: TestEnv) => (await (await driver(e).call("/.well-known/oauth-authorization-server")).json()) as any; + const on = await meta(env()); + expect(on.client_id_metadata_document_supported).toBe(true); + expect(on.scopes_supported).toEqual(["fake", "offline_access"]); + const off = await meta(env({ DISABLE_CIMD: "true" })); + expect(off.client_id_metadata_document_supported).not.toBe(true); + expect(off.scopes_supported).toEqual(["fake", "offline_access"]); + }); + + it("an exception becomes a logged 500", async () => { + const r = await broker.fetch(new Request(BASE + "/"), env({ PUBLIC_URL: "" }), ctx); + expect(r.status).toBe(500); + expect(await r.text()).toBe("Internal error: PUBLIC_URL is not set\n"); + expect(logs.some((l) => l.includes('"unhandled"'))).toBe(true); + }); + + it("a trailing slash on PUBLIC_URL still gives one issuer", async () => { + const e = env({ PUBLIC_URL: BASE + "/" }); + const m = (await (await broker.fetch(new Request(BASE + "/.well-known/oauth-authorization-server"), e, ctx)).json()) as any; + expect(m.issuer).toBe(BASE); + }); + + it("escapes the client's name on the consent page", async () => { + const s = await startSignIn({ ...driver(env()), clientName: "" }); + expect(s.html).toContain("<script>"); + expect(s.html).not.toContain("