Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Use the MCP SDK client for MCP connectors and memory providers (#2479)

Regan Bell6c05b97a7bd8
diff --git a/package-lock.json b/package-lock.json
index 24ef9aca8..6edaeb526 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -23,6 +23,7 @@
"@fly/sprites": "0.2.3",
"@grpc/grpc-js": "^1.14.5",
"@grpc/proto-loader": "^0.8.1",
+ "@modelcontextprotocol/sdk": "1.31.0",
"@sentry/node": "10.75.0",
"@slack/bolt": "^4.7.3",
"@slack/socket-mode": "^2.0.7",
@@ -51,7 +52,6 @@
},
"devDependencies": {
"@eslint/js": "^10.0.1",
- "@modelcontextprotocol/sdk": "1.31.0",
"@types/node": "^24.0.0",
"@types/pg": "^8.11.10",
"@types/tar-stream": "^3.1.4",
diff --git a/package.json b/package.json
index 0365d4edd..703d91842 100644
--- a/package.json
+++ b/package.json
@@ -81,6 +81,7 @@
"@fly/sprites": "0.2.3",
"@grpc/grpc-js": "^1.14.5",
"@grpc/proto-loader": "^0.8.1",
+ "@modelcontextprotocol/sdk": "1.31.0",
"@sentry/node": "10.75.0",
"@slack/bolt": "^4.7.3",
"@slack/socket-mode": "^2.0.7",
@@ -127,7 +128,6 @@
},
"devDependencies": {
"@eslint/js": "^10.0.1",
- "@modelcontextprotocol/sdk": "1.31.0",
"@types/node": "^24.0.0",
"@types/pg": "^8.11.10",
"@types/tar-stream": "^3.1.4",
diff --git a/src/mcp/mcp-client.ts b/src/mcp/mcp-client.ts
index 398193218..03fe45f67 100644
--- a/src/mcp/mcp-client.ts
+++ b/src/mcp/mcp-client.ts
@@ -1,98 +1,15 @@
-// Generic Model Context Protocol (MCP) client — HTTP transport only.
-//
-// Speaks JSON-RPC 2.0 over a single POST endpoint, accepting both plain JSON
-// and SSE-framed responses (the two response shapes the spec's streamable
-// HTTP transport allows). Supports three auth modes: none, static bearer
-// token, and OAuth2 client-credentials minted against `<base>/token`.
-//
-// This is the transport layer only: no registry, no tool injection, no
-// policy. See mcp-tool-service.ts for the layer that turns registered
-// servers into agent tools.
+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
+import { ClientCredentialsProvider } from "@modelcontextprotocol/sdk/client/auth-extensions.js";
+import { StreamableHTTPClientTransport, StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
+import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
+import { swallowAs } from "../util/errors.ts";
-const TOKEN_SKEW_MS = 60_000;
-const MCP_ACCEPT = "application/json, text/event-stream";
+const MAX_TOOLS = 64;
+const CALL_TIMEOUT_MS = 300_000;
-interface McpHttpResponse {
- ok: boolean;
- status: number;
- text(): Promise<string>;
- headers?: { get(name: string): string | null };
-}
-
-export type McpFetch = (
- url: string,
- init: { method: string; headers: Record<string, string>; body: string },
-) => Promise<McpHttpResponse>;
-
-const realFetch: McpFetch = (url, init) => fetch(url, { ...init, redirect: "error" });
-
-function endpointUrl(mcpUrl: string): string {
- const trimmed = mcpUrl.replace(/\/+$/g, "");
- return new URL(trimmed).pathname === "/" ? `${trimmed}/mcp` : trimmed;
-}
-
-function hostOf(base: string): string {
- try {
- return new URL(base).host;
- } catch {
- return base;
- }
-}
-
-function safeJson(text: string): unknown {
- try {
- return JSON.parse(text);
- } catch {
- return null;
- }
-}
-
-interface McpEnvelope {
- result?: unknown;
- error?: { message?: string };
- id?: unknown;
-}
-
-function parseSseEnvelopes(body: string): McpEnvelope[] {
- const out: McpEnvelope[] = [];
- for (const frame of body.split(/\r?\n\r?\n/)) {
- const data = frame
- .split(/\r?\n/)
- .filter((line) => line.startsWith("data:"))
- .map((line) => line.slice(5).replace(/^ /, ""))
- .join("\n");
- if (!data) continue;
- const parsed = safeJson(data) as McpEnvelope | null;
- if (parsed) out.push(parsed);
- }
- return out;
-}
-
-function parseMcpEnvelope(text: string, contentType: string | null | undefined, id?: unknown): McpEnvelope | null {
- const isSse = !!contentType && contentType.toLowerCase().includes("text/event-stream");
- if (isSse) {
- const envelopes = parseSseEnvelopes(text);
- const carries = (e: McpEnvelope): boolean => e.result !== undefined || e.error !== undefined;
- return (
- (id !== undefined ? envelopes.find((e) => e.id === id && carries(e)) : undefined) ??
- envelopes.find(carries) ??
- null
- );
- }
- return safeJson(text) as McpEnvelope | null;
-}
-
-export interface McpToolResult {
- content?: Array<{ type?: string; text?: string }>;
- structuredContent?: unknown;
- isError?: boolean;
-}
-
-export function mcpResultText(result: McpToolResult): string {
- if (!Array.isArray(result.content)) return "";
+export function mcpResultText(result: CallToolResult): string {
return result.content
- .filter((c) => c?.type === "text")
- .map((c) => String(c.text ?? ""))
+ .flatMap((c) => (c.type === "text" ? [c.text] : []))
.join("\n")
.trim();
}
@@ -109,99 +26,59 @@ export type McpAuth =
| { mode: "client-credentials"; clientId: string; clientSecret: string };
export interface McpClient {
- readonly base: string;
- readonly host: string;
listTools(): Promise<McpRemoteTool[]>;
- callTool(name: string, args: Record<string, unknown>): Promise<McpToolResult>;
-}
-
-interface CachedToken {
- accessToken: string;
- expiresAt: number;
+ callTool(name: string, args: Record<string, unknown>): Promise<CallToolResult>;
}
-export function createMcpClient(opts: {
- url: string;
- auth: McpAuth;
- fetchImpl?: McpFetch;
- now?: () => number;
-}): McpClient {
- const fetchImpl = opts.fetchImpl ?? realFetch;
- const now = opts.now ?? (() => Date.now());
- const endpoint = endpointUrl(opts.url);
- const base = endpoint.replace(/\/mcp$/g, "");
- const host = hostOf(base);
- let cached: CachedToken | null = null;
- let rpcId = 0;
-
- async function mintToken(clientId: string, clientSecret: string): Promise<string> {
- if (cached && now() < cached.expiresAt - TOKEN_SKEW_MS) return cached.accessToken;
- const res = await fetchImpl(`${base}/token`, {
- method: "POST",
- headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
- body: new URLSearchParams({
- grant_type: "client_credentials",
- client_id: clientId,
- client_secret: clientSecret,
- }).toString(),
+export function createMcpClient(opts: { url: string; auth: McpAuth }): McpClient {
+ const trimmed = opts.url.replace(/\/+$/g, "");
+ const endpoint = new URL(new URL(trimmed).pathname === "/" ? `${trimmed}/mcp` : trimmed);
+ const { auth } = opts;
+ const authProvider =
+ auth.mode === "client-credentials"
+ ? new ClientCredentialsProvider({
+ clientId: auth.clientId,
+ clientSecret: auth.clientSecret,
+ expectedIssuer: new URL("/", endpoint).href,
+ })
+ : undefined;
+
+ async function session<T>(op: string, work: (client: Client) => Promise<T>): Promise<T> {
+ const transport = new StreamableHTTPClientTransport(endpoint, {
+ ...(authProvider ? { authProvider } : {}),
+ ...(auth.mode === "bearer" ? { requestInit: { headers: { authorization: `Bearer ${auth.token}` } } } : {}),
+ fetch: (url, init) => fetch(url, { ...init, redirect: "error" }),
});
- if (!res.ok) throw new Error(`mcp token mint failed (HTTP ${res.status})`);
- const body = (safeJson(await res.text()) ?? {}) as { access_token?: unknown; expires_in?: unknown };
- const accessToken = typeof body.access_token === "string" ? body.access_token : "";
- if (!accessToken) throw new Error("mcp token mint returned no access_token");
- const expiresIn = typeof body.expires_in === "number" ? body.expires_in : 0;
- cached = { accessToken, expiresAt: expiresIn > 0 ? now() + expiresIn * 1000 : Infinity };
- return accessToken;
- }
-
- async function authHeaders(): Promise<Record<string, string>> {
- const auth = opts.auth;
- if (auth.mode === "none") return {};
- if (auth.mode === "bearer") return { authorization: `Bearer ${auth.token}` };
- return { authorization: `Bearer ${await mintToken(auth.clientId, auth.clientSecret)}` };
- }
-
- async function rpc(method: string, params: Record<string, unknown>): Promise<unknown> {
- const id = ++rpcId;
- const res = await fetchImpl(endpoint, {
- method: "POST",
- headers: {
- ...(await authHeaders()),
- "content-type": "application/json",
- accept: MCP_ACCEPT,
- },
- body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
- });
- if (!res.ok) throw new Error(`mcp ${method} failed (HTTP ${res.status})`);
- const parsed = parseMcpEnvelope(await res.text(), res.headers?.get("content-type"), id);
- if (!parsed) throw new Error(`mcp ${method} returned non-JSON`);
- if (parsed.error) throw new Error(`mcp ${method} error: ${parsed.error.message ?? "unknown"}`);
- return parsed.result ?? {};
+ const client = new Client({ name: "qm", version: "1.0.0" });
+ try {
+ await client.connect(transport);
+ return await work(client);
+ } catch (e) {
+ const status = e instanceof StreamableHTTPError && (e.code ?? 0) > 0 ? ` (HTTP ${e.code})` : "";
+ throw new Error(`mcp ${op} failed${status}`, { cause: e });
+ } finally {
+ await transport.terminateSession().catch(swallowAs("mcp: end session", undefined));
+ await client.close();
+ }
}
return {
- base,
- host,
- async listTools() {
- const result = (await rpc("tools/list", {})) as { tools?: unknown };
- if (!Array.isArray(result.tools)) return [];
- const out: McpRemoteTool[] = [];
- for (const raw of result.tools) {
- const t = raw as { name?: unknown; description?: unknown; inputSchema?: unknown };
- if (typeof t.name !== "string" || !t.name) continue;
- out.push({
- name: t.name,
- description: typeof t.description === "string" ? t.description : "",
- inputSchema:
- t.inputSchema && typeof t.inputSchema === "object"
- ? (t.inputSchema as Record<string, unknown>)
- : { type: "object", properties: {} },
- });
- }
- return out;
- },
+ listTools: () =>
+ session("tools/list", async (client) => {
+ const tools: McpRemoteTool[] = [];
+ let cursor: string | undefined;
+ do {
+ const page = await client.listTools(cursor === undefined ? undefined : { cursor });
+ for (const t of page.tools)
+ tools.push({ name: t.name, description: t.description ?? "", inputSchema: t.inputSchema });
+ cursor = page.nextCursor;
+ } while (cursor && tools.length < MAX_TOOLS);
+ return tools.slice(0, MAX_TOOLS);
+ }),
async callTool(name, args) {
- const result = (await rpc("tools/call", { name, arguments: args })) as McpToolResult;
+ const result = (await session("tools/call", (client) =>
+ client.callTool({ name, arguments: args }, undefined, { timeout: CALL_TIMEOUT_MS }),
+ )) as CallToolResult;
if (result.isError) throw new Error(`mcp tool ${name} error: ${mcpResultText(result) || "(no detail)"}`);
return result;
},
diff --git a/src/mcp/mcp-tool-service.ts b/src/mcp/mcp-tool-service.ts
index b9f3c810d..c80c7e082 100644
--- a/src/mcp/mcp-tool-service.ts
+++ b/src/mcp/mcp-tool-service.ts
@@ -10,11 +10,10 @@ import type { ConnectorTokenStore } from "../credentials/keychain.ts";
import type { AuditLog } from "../audit/audit-log.ts";
import { errMessage, reportFailureAs } from "../util/errors.ts";
import { setPublicOAuthClients, type PublicOAuthClient } from "../connectors/oauth.ts";
-import { createMcpClient, mcpResultText, type McpAuth, type McpClient, type McpFetch } from "./mcp-client.ts";
+import { createMcpClient, mcpResultText, type McpAuth, type McpClient } from "./mcp-client.ts";
import type { McpServer, McpServerStore } from "./mcp-server-store.ts";
const REFRESH_INTERVAL_MS = 5 * 60_000;
-const MAX_TOOLS_PER_SERVER = 64;
const MAX_RESULT_CHARS = 60_000;
export function mcpPublicOAuthClients(servers: McpServer[]): PublicOAuthClient[] {
@@ -72,7 +71,6 @@ export function createMcpToolService(opts: {
servers: McpServerStore;
audit?: AuditLog;
userTokens?: Pick<ConnectorTokenStore, "connectorAccessToken">;
- fetchImpl?: McpFetch;
now?: () => number;
refreshIntervalMs?: number;
signInUrl?: (serverId: string) => string;
@@ -103,12 +101,7 @@ export function createMcpToolService(opts: {
function clientFor(server: McpServer): McpClient {
const cached = clients.get(server.id);
if (cached && JSON.stringify(cached.server) === JSON.stringify(server)) return cached.client;
- const client = createMcpClient({
- url: server.url,
- auth: authOf(server),
- ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),
- now,
- });
+ const client = createMcpClient({ url: server.url, auth: authOf(server) });
clients.set(server.id, { client, server });
return client;
}
@@ -128,12 +121,7 @@ export function createMcpToolService(opts: {
if (server.auth === "oauth-user") throw new SignInRequired(signInMessage(server));
throw new Error(`Connect your account for MCP server ${server.id} before using this tool`);
}
- return createMcpClient({
- url: server.url,
- auth: { mode: "bearer", token },
- ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),
- now,
- });
+ return createMcpClient({ url: server.url, auth: { mode: "bearer", token } });
}
async function refresh(): Promise<void> {
@@ -158,7 +146,7 @@ export function createMcpToolService(opts: {
});
continue;
}
- } else tools = (await clientFor(server).listTools()).slice(0, MAX_TOOLS_PER_SERVER);
+ } else tools = await clientFor(server).listTools();
for (const tool of tools) {
next.push({
name: `${server.id}_${tool.name}`.replace(/[^a-zA-Z0-9_-]/g, "_"),
@@ -197,7 +185,7 @@ export function createMcpToolService(opts: {
try {
const client = await callerClient(server, principalId);
if (def.signIn) {
- const tools = (await client.listTools()).slice(0, MAX_TOOLS_PER_SERVER);
+ const tools = await client.listTools();
const current = await opts.servers.get(server.id);
if (current) await opts.servers.put({ ...current, tools });
await refresh();
@@ -219,13 +207,7 @@ export function createMcpToolService(opts: {
},
refresh,
async probe(server) {
- const client = createMcpClient({
- url: server.url,
- auth: authOf(server),
- ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),
- now,
- });
- const tools = await client.listTools();
+ const tools = await createMcpClient({ url: server.url, auth: authOf(server) }).listTools();
return tools.map((t) => t.name);
},
close() {
diff --git a/src/mcp/oauth-discovery.ts b/src/mcp/oauth-discovery.ts
index 51cb79064..2fc96ea0c 100644
--- a/src/mcp/oauth-discovery.ts
+++ b/src/mcp/oauth-discovery.ts
@@ -1,3 +1,4 @@
+import { buildDiscoveryUrls } from "@modelcontextprotocol/sdk/client/auth.js";
import { errMessage } from "../util/errors.ts";
export function httpsUrl(v: unknown): string | undefined {
@@ -59,13 +60,8 @@ export async function discoverOAuth(resource: URL): Promise<DiscoveredOAuth> {
continue;
}
const scopes = parseScopes(meta?.scopes_supported);
- const base = new URL(issuer);
- const path = base.pathname.replace(/\/+$/, "");
- for (const candidate of [
- `${base.origin}/.well-known/oauth-authorization-server${path}`,
- `${base.origin}/.well-known/openid-configuration${path}`,
- ...(path ? [`${base.origin}${path}/.well-known/openid-configuration`] : []),
- ]) {
+ for (const { url } of buildDiscoveryUrls(issuer)) {
+ const candidate = url.href;
const server = await fetchMeta(candidate, errors);
if (!server) continue;
const authorize = httpsUrl(server.authorization_endpoint);
diff --git a/src/memory/mcp-memory-provider.ts b/src/memory/mcp-memory-provider.ts
index 412b9a610..5af142c12 100644
--- a/src/memory/mcp-memory-provider.ts
+++ b/src/memory/mcp-memory-provider.ts
@@ -1,4 +1,6 @@
-import { mcpResultText, type McpClient, type McpToolResult } from "../mcp/mcp-client.ts";
+import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
+import { mcpResultText, type McpClient } from "../mcp/mcp-client.ts";
+import { withTimeout } from "../util/async.ts";
import type { MemoryService } from "./memory-service.ts";
export interface McpMemoryOperation {
@@ -17,22 +19,7 @@ export interface McpMemoryOperation {
timeoutMs: number;
}
-async function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
- let timer: NodeJS.Timeout | undefined;
- try {
- return await Promise.race([
- promise,
- new Promise<never>((_, reject) => {
- timer = setTimeout(() => reject(new Error(`memory provider timed out after ${timeoutMs}ms`)), timeoutMs);
- timer.unref?.();
- }),
- ]);
- } finally {
- if (timer) clearTimeout(timer);
- }
-}
-
-function resultText(result: McpToolResult): string {
+function resultText(result: CallToolResult): string {
const text = mcpResultText(result);
if (text) return text;
return result.structuredContent == null ? "" : JSON.stringify(result.structuredContent);
@@ -45,7 +32,9 @@ export function createMcpMemoryProvider(opts: { read: McpMemoryOperation; write?
if (actorId) args[op.actorArg ?? "acting_user"] = actorId;
if (op.scopeArg) args[op.scopeArg] = scopeId;
if (maxChars && op.maxCharsArg) args[op.maxCharsArg] = maxChars;
- const text = resultText(await withTimeout(op.client.callTool(op.tool, args), op.timeoutMs));
+ const text = resultText(
+ await withTimeout(() => op.client.callTool(op.tool, args), op.timeoutMs, "memory provider"),
+ );
return maxChars && text.length > maxChars ? text.slice(0, maxChars) : text;
};
@@ -67,7 +56,7 @@ export function createMcpMemoryProvider(opts: { read: McpMemoryOperation; write?
const actorId = context?.actorId ?? author;
if (actorId) args[op.actorArg ?? "acting_user"] = actorId;
if (op.scopeArg) args[op.scopeArg] = scopeId;
- await withTimeout(op.client.callTool(op.tool, args), op.timeoutMs);
+ await withTimeout(() => op.client.callTool(op.tool, args), op.timeoutMs, "memory provider");
return facts.length;
},
diff --git a/src/memory/provider-factory.ts b/src/memory/provider-factory.ts
index 875d95ad0..fde411dc0 100644
--- a/src/memory/provider-factory.ts
+++ b/src/memory/provider-factory.ts
@@ -1,4 +1,3 @@
-import type { McpFetch } from "../mcp/mcp-client.ts";
import { createMcpClient } from "../mcp/mcp-client.ts";
import { errMessage } from "../util/errors.ts";
import { createMcpMemoryProvider, type McpMemoryOperation } from "./mcp-memory-provider.ts";
@@ -9,18 +8,9 @@ import { createMemorableMemoryProvider } from "./memorable/provider.ts";
import { createSecretValueMasker } from "../security/secret-masking.ts";
import type { SessionEntry } from "../types.ts";
-function operation(
- url: string,
- spec: McpMemoryOperationConfig,
- timeoutMs: number,
- fetchImpl?: McpFetch,
-): McpMemoryOperation {
+function operation(url: string, spec: McpMemoryOperationConfig, timeoutMs: number): McpMemoryOperation {
return {
- client: createMcpClient({
- url,
- auth: { mode: "client-credentials", ...spec.auth },
- ...(fetchImpl ? { fetchImpl } : {}),
- }),
+ client: createMcpClient({ url, auth: { mode: "client-credentials", ...spec.auth } }),
tool: spec.tool,
timeoutMs,
...(spec.queryArg ? { queryArg: spec.queryArg } : {}),
@@ -39,7 +29,6 @@ function operation(
export function createConfiguredMemoryService(opts: {
defaultMemory: MemoryService;
config?: MemoryProviderConfig;
- fetchImpl?: McpFetch;
/** Session trace access for providers that derive memory from tool-call history (currently "memorable"). */
sessionEntries?: (sessionId: string) => Promise<SessionEntry[]>;
onError?: (error: unknown, provider: string, operation: "recall" | "query" | "capture") => void;
@@ -61,8 +50,8 @@ export function createConfiguredMemoryService(opts: {
continue;
}
providers[provider.id] = createMcpMemoryProvider({
- read: operation(provider.url, provider.read, provider.timeoutMs, opts.fetchImpl),
- ...(provider.write ? { write: operation(provider.url, provider.write, provider.timeoutMs, opts.fetchImpl) } : {}),
+ read: operation(provider.url, provider.read, provider.timeoutMs),
+ ...(provider.write ? { write: operation(provider.url, provider.write, provider.timeoutMs) } : {}),
});
}
return createRoutedMemoryService({
diff --git a/test/e2e/memory-provider.e2e.test.ts b/test/e2e/memory-provider.e2e.test.ts
index b03384280..f9141ef1f 100644
--- a/test/e2e/memory-provider.e2e.test.ts
+++ b/test/e2e/memory-provider.e2e.test.ts
@@ -2,7 +2,7 @@ import "../support/auto-fake-sprites.ts";
import { describe, it, before, after } from "node:test";
import assert from "node:assert/strict";
-import { createServer, type Server } from "node:http";
+import type { Server } from "node:http";
import type { AddressInfo } from "node:net";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -11,6 +11,7 @@ import { buildApp } from "../../src/wiring.ts";
import { createInsecureTestServer } from "../../src/api/server.ts";
import { parseMemoryProviderConfig } from "../../src/memory/provider-config.ts";
import { testConfig } from "../support/test-config.ts";
+import { startMcpTestServer, type McpTestServer } from "../support/mcp-test-server.ts";
const NO_KEY = !process.env.ANTHROPIC_API_KEY;
@@ -22,62 +23,35 @@ interface WriteCall {
describe("memory provider e2e (live Pi + stub MCP)", { skip: NO_KEY ? "set ANTHROPIC_API_KEY" : false }, () => {
const facts: string[] = ["Josh's secret project codename is BLACKBEARD-42."];
const writes: WriteCall[] = [];
- let tokenMints = 0;
- let knowledge: Server;
+ let knowledge: McpTestServer;
+ const closeKnowledge: Array<() => Promise<void>> = [];
let server: Server;
let base: string;
before(async () => {
- knowledge = createServer((req, res) => {
- let body = "";
- req.on("data", (c) => (body += c));
- req.on("end", () => {
- if (req.url === "/token") {
- const params = new URLSearchParams(body);
- if (params.get("client_id") !== "knowledge-id" || params.get("client_secret") !== "knowledge-secret") {
- res.writeHead(401).end();
- return;
+ knowledge = await startMcpTestServer(
+ { after: (fn) => void closeKnowledge.push(fn) },
+ {
+ tools: ["search_knowledge", "write_knowledge"].map((name) => ({
+ name,
+ inputSchema: { type: "object" as const },
+ })),
+ clients: { "knowledge-id": "knowledge-secret" },
+ call: (name, args) => {
+ if (name === "write_knowledge") {
+ writes.push({ content: String(args.content), acting_user: args.acting_user as string | undefined });
+ facts.push(String(args.content));
+ return { content: [{ type: "text", text: "stored" }] };
}
- tokenMints++;
- res.writeHead(200, { "content-type": "application/json" });
- res.end(JSON.stringify({ access_token: "stub-token", expires_in: 3600 }));
- return;
- }
- if (req.url === "/mcp") {
- if (req.headers.authorization !== "Bearer stub-token") {
- res.writeHead(401).end();
- return;
- }
- const rpc = JSON.parse(body) as { id: number; method: string; params?: any };
- const reply = (result: unknown) => {
- res.writeHead(200, { "content-type": "application/json" });
- res.end(JSON.stringify({ jsonrpc: "2.0", id: rpc.id, result }));
- };
- if (rpc.method === "tools/call") {
- const { name, arguments: args } = rpc.params;
- if (name === "search_knowledge") {
- const q = String(args.query ?? "").toLowerCase();
- const hits = q
- ? facts.filter((f) => q.split(/\W+/).some((w) => w.length > 2 && f.toLowerCase().includes(w)))
- : facts;
- reply({ content: [{ type: "text", text: (hits.length ? hits : facts).join("\n") }] });
- return;
- }
- if (name === "write_knowledge") {
- writes.push({ content: String(args.content), acting_user: args.acting_user });
- facts.push(String(args.content));
- reply({ content: [{ type: "text", text: "stored" }] });
- return;
- }
- }
- reply({});
- return;
- }
- res.writeHead(404).end();
- });
- });
- await new Promise<void>((r) => knowledge.listen(0, r));
- const knowledgeUrl = `http://127.0.0.1:${(knowledge.address() as AddressInfo).port}`;
+ const q = String(args.query ?? "").toLowerCase();
+ const hits = q
+ ? facts.filter((f) => q.split(/\W+/).some((w) => w.length > 2 && f.toLowerCase().includes(w)))
+ : facts;
+ return { content: [{ type: "text", text: (hits.length ? hits : facts).join("\n") }] };
+ },
+ },
+ );
+ const knowledgeUrl = knowledge.url;
const providerJson = JSON.stringify({
providers: [
@@ -132,7 +106,7 @@ describe("memory provider e2e (live Pi + stub MCP)", { skip: NO_KEY ? "set ANTHR
after(async () => {
await new Promise<void>((r) => server.close(() => r()));
- await new Promise<void>((r) => knowledge.close(() => r()));
+ await Promise.all(closeKnowledge.map((close) => close()));
});
async function turn(text: string, threadRef: string): Promise<{ http: number; json: any }> {
@@ -154,7 +128,7 @@ describe("memory provider e2e (live Pi + stub MCP)", { skip: NO_KEY ? "set ANTHR
assert.equal(r.http, 200);
assert.equal(r.json.status, "ok");
assert.match(r.json.reply, /BLACKBEARD-42/i);
- assert.ok(tokenMints >= 1, "client-credentials token should have been minted");
+ assert.ok(knowledge.tokenRequests.length >= 1, "client-credentials token should have been minted");
});
it("explicit remember writes through to the external provider", { timeout: 180_000 }, async () => {
diff --git a/test/mcp-admin.test.ts b/test/mcp-admin.test.ts
index a47a785d3..2998e3e2a 100644
--- a/test/mcp-admin.test.ts
+++ b/test/mcp-admin.test.ts
@@ -12,6 +12,7 @@ import { buildApp } from "../src/wiring.ts";
import { testConfig } from "./support/test-config.ts";
import { createMcpServerStore, type McpServer } from "../src/mcp/mcp-server-store.ts";
import { createMemoryMap } from "../src/persistence/durable-map.ts";
+import { startMcpTestServer } from "./support/mcp-test-server.ts";
const ADMIN = { "content-type": "application/json", "x-admin-actor": "admin-alice@default-org" };
@@ -93,28 +94,13 @@ test("production wiring never uses operator fallback tokens for per-user MCP cal
const previous = process.env.VAULT_TOKEN_ACCOUNTS_EXAMPLE_COM;
process.env.VAULT_TOKEN_ACCOUNTS_EXAMPLE_COM = "operator-token";
const built = buildApp(testConfig({ dataDir: dir, egressServiceHosts: ["accounts.example.com"] }));
- let calls = 0;
- const remote = createServer(async (req, res) => {
- const chunks: Buffer[] = [];
- for await (const chunk of req) chunks.push(Buffer.from(chunk));
- const rpc = JSON.parse(Buffer.concat(chunks).toString());
- if (rpc.method === "tools/call") calls++;
- res.setHeader("content-type", "application/json");
- res.end(
- JSON.stringify({
- id: rpc.id,
- result:
- rpc.method === "tools/list"
- ? { tools: [{ name: "identity", inputSchema: { type: "object" } }] }
- : { content: [{ type: "text", text: req.headers.authorization }] },
- }),
- );
+ const remote = await startMcpTestServer(t, {
+ tools: [{ name: "identity", inputSchema: { type: "object" } }],
+ call: (_name, _args, authorization) => ({ content: [{ type: "text", text: authorization ?? "" }] }),
});
- remote.listen(0, "127.0.0.1");
- await once(remote, "listening");
+ const calls = () => remote.requests.filter((r) => r.rpc === "tools/call").length;
t.after(async () => {
built.mcpToolService.close();
- await new Promise<void>((resolve) => remote.close(() => resolve()));
if (previous === undefined) delete process.env.VAULT_TOKEN_ACCOUNTS_EXAMPLE_COM;
else process.env.VAULT_TOKEN_ACCOUNTS_EXAMPLE_COM = previous;
await rm(dir, { recursive: true, force: true });
@@ -122,7 +108,7 @@ test("production wiring never uses operator fallback tokens for per-user MCP cal
await built.mcpServers.put({
id: "crm",
name: "CRM",
- url: `http://127.0.0.1:${(remote.address() as AddressInfo).port}/mcp`,
+ url: `${remote.url}/mcp`,
auth: "none",
credentialScope: "per-user",
credentialHost: "accounts.example.com",
@@ -137,12 +123,12 @@ test("production wiring never uses operator fallback tokens for per-user MCP cal
"operator-token",
);
await assert.rejects(built.mcpToolService.call("crm_identity", {}, "internal:alice"), /Connect your account/);
- assert.equal(calls, 0);
+ assert.equal(calls(), 0);
await built.connectorTokens.setConnectorToken("accounts.example.com", "internal:alice", {
accessToken: "alice-only",
});
assert.equal(await built.mcpToolService.call("crm_identity", {}, "internal:alice"), "Bearer alice-only");
- assert.equal(calls, 1);
+ assert.equal(calls(), 1);
});
test("MCP admin accepts per-user OAuth servers, discovers endpoints from metadata, and never shadows built-in connectors", async (t) => {
diff --git a/test/mcp-connectors.test.ts b/test/mcp-connectors.test.ts
index 2815b0b4c..82f671ee9 100644
--- a/test/mcp-connectors.test.ts
+++ b/test/mcp-connectors.test.ts
@@ -1,6 +1,6 @@
import { test } from "node:test";
import assert from "node:assert/strict";
-import { createMcpClient, mcpResultText, type McpFetch } from "../src/mcp/mcp-client.ts";
+import { createMcpClient, mcpResultText } from "../src/mcp/mcp-client.ts";
import { createMcpServerStore, isValidMcpServerId, type McpServer } from "../src/mcp/mcp-server-store.ts";
import { createMcpToolService } from "../src/mcp/mcp-tool-service.ts";
import { createKeychain, type KeychainCredential } from "../src/credentials/keychain.ts";
@@ -9,39 +9,8 @@ import { createServer } from "node:http";
import { once } from "node:events";
import type { AddressInfo } from "node:net";
import { createMemoryMap } from "../src/persistence/durable-map.ts";
-
-function jsonResponse(body: unknown, status = 200, contentType = "application/json") {
- return {
- ok: status >= 200 && status < 300,
- status,
- text: async () => (typeof body === "string" ? body : JSON.stringify(body)),
- headers: { get: (n: string) => (n.toLowerCase() === "content-type" ? contentType : null) },
- };
-}
-
-const TOOLS = [
- { name: "query", description: "Run a query", inputSchema: { type: "object", properties: { q: { type: "string" } } } },
- { name: "update", description: "Write a record", inputSchema: { type: "object", properties: {} } },
-];
-
-function fakeServerFetch(opts?: { requireBearer?: string; sse?: boolean }): { fetch: McpFetch; calls: string[] } {
- const calls: string[] = [];
- const fetch: McpFetch = async (url, init) => {
- calls.push(url);
- if (opts?.requireBearer && init.headers.authorization !== `Bearer ${opts.requireBearer}`) {
- return jsonResponse({ error: "unauthorized" }, 401);
- }
- const req = JSON.parse(init.body) as { id: number; method: string; params: { name?: string } };
- const result =
- req.method === "tools/list" ? { tools: TOOLS } : { content: [{ type: "text", text: `ran ${req.params.name}` }] };
- const envelope = { jsonrpc: "2.0", id: req.id, result };
- if (opts?.sse) {
- return jsonResponse(`event: message\ndata: ${JSON.stringify(envelope)}\n\n`, 200, "text/event-stream");
- }
- return jsonResponse(envelope);
- };
- return { fetch, calls };
-}
+import { settle } from "./support/settle.ts";
+import { startMcpTestServer } from "./support/mcp-test-server.ts";
function server(partial?: Partial<McpServer>): McpServer {
return {
@@ -57,76 +26,109 @@ function server(partial?: Partial<McpServer>): McpServer {
};
}
-test("mcp client lists tools and calls one over plain JSON", async () => {
- const { fetch } = fakeServerFetch();
- const client = createMcpClient({ url: "https://mcp.example.com/mcp", auth: { mode: "none" }, fetchImpl: fetch });
- const tools = await client.listTools();
- assert.deepEqual(
- tools.map((t) => t.name),
- ["query", "update"],
- );
- const result = await client.callTool("query", { q: "hi" });
- assert.equal(mcpResultText(result), "ran query");
+test("mcp client lists every page of tools and calls one over JSON and SSE responses", async (t) => {
+ const tools = ["a", "b", "c"].map((name) => ({
+ name,
+ description: `tool ${name}`,
+ inputSchema: { type: "object" as const },
+ }));
+ for (const json of [true, false]) {
+ const mcp = await startMcpTestServer(t, { tools, pageSize: 1, json });
+ const client = createMcpClient({ url: `${mcp.url}/mcp`, auth: { mode: "none" } });
+ assert.deepEqual(await client.listTools(), [
+ { name: "a", description: "tool a", inputSchema: { type: "object" } },
+ { name: "b", description: "tool b", inputSchema: { type: "object" } },
+ { name: "c", description: "tool c", inputSchema: { type: "object" } },
+ ]);
+ assert.equal(mcpResultText(await client.callTool("b", {})), "ran b");
+ assert.equal(mcp.openSessions(), 0, "each operation ends its session");
+ }
});
-test("mcp client parses SSE-framed responses", async () => {
- const { fetch } = fakeServerFetch({ sse: true });
- const client = createMcpClient({ url: "https://mcp.example.com/mcp", auth: { mode: "none" }, fetchImpl: fetch });
- const tools = await client.listTools();
- assert.equal(tools.length, 2);
+test("mcp client caps a server's tool list", async (t) => {
+ const tools = Array.from({ length: 100 }, (_, i) => ({ name: `t${i}`, inputSchema: { type: "object" as const } }));
+ const mcp = await startMcpTestServer(t, { tools, pageSize: 40 });
+ const listed = await createMcpClient({ url: mcp.url, auth: { mode: "none" } }).listTools();
+ assert.equal(listed.length, 64);
+ assert.equal(listed.at(-1)?.name, "t63");
+ assert.equal(mcp.requests.filter((r) => r.rpc === "tools/list").length, 2);
});
-test("mcp client sends bearer auth", async () => {
- const { fetch } = fakeServerFetch({ requireBearer: "sekret" });
- const client = createMcpClient({
- url: "https://mcp.example.com/mcp",
- auth: { mode: "bearer", token: "sekret" },
- fetchImpl: fetch,
+test("mcp client surfaces tool errors and protocol errors", async (t) => {
+ const mcp = await startMcpTestServer(t, {
+ call: (name) => ({ isError: true, content: [{ type: "text", text: `${name} exploded` }] }),
});
- assert.equal((await client.listTools()).length, 2);
- const bad = createMcpClient({ url: "https://mcp.example.com/mcp", auth: { mode: "none" }, fetchImpl: fetch });
- await assert.rejects(() => bad.listTools(), /HTTP 401/);
+ const client = createMcpClient({ url: mcp.url, auth: { mode: "none" } });
+ await assert.rejects(client.callTool("query", {}), /^Error: mcp tool query error: query exploded$/);
+ await assert.rejects(
+ client.callTool("missing", {}),
+ (e: Error) => e.message === "mcp tools/call failed" && /Unknown tool: missing/.test(String(e.cause)),
+ );
+});
+
+test("mcp client starts a fresh session after the server forgets its sessions", async (t) => {
+ const mcp = await startMcpTestServer(t);
+ const client = createMcpClient({ url: mcp.url, auth: { mode: "none" } });
+ assert.equal(mcpResultText(await client.callTool("query", {})), "ran query");
+ await mcp.dropSessions();
+ assert.equal(mcpResultText(await client.callTool("query", {})), "ran query");
+ assert.equal(mcp.requests.filter((r) => r.rpc === "initialize").length, 2);
+});
+
+test("mcp client sends bearer auth", async (t) => {
+ const mcp = await startMcpTestServer(t, { authorize: (auth) => auth === "Bearer sekret" });
+ const good = createMcpClient({ url: mcp.url, auth: { mode: "bearer", token: "sekret" } });
+ assert.equal((await good.listTools()).length, 2);
+ const bad = createMcpClient({ url: mcp.url, auth: { mode: "none" } });
+ await assert.rejects(bad.listTools(), /^Error: mcp tools\/list failed \(HTTP 401\)$/);
});
-test("mcp client posts to the configured endpoint path", async () => {
+test("mcp client posts to the configured endpoint path", async (t) => {
+ const mcp = await startMcpTestServer(t);
const cases: Array<[string, string]> = [
- ["https://api.example.com/mcp/consumer", "https://api.example.com/mcp/consumer"],
- ["https://api.example.com/mcp/consumer/", "https://api.example.com/mcp/consumer"],
- ["https://mcp.example.com/mcp", "https://mcp.example.com/mcp"],
- ["https://mcp.example.com/mcp/", "https://mcp.example.com/mcp"],
- ["https://mcp.example.com", "https://mcp.example.com/mcp"],
- ["http://memory.internal:8080/", "http://memory.internal:8080/mcp"],
+ [`${mcp.url}/mcp/consumer`, "/mcp/consumer"],
+ [`${mcp.url}/mcp/consumer/`, "/mcp/consumer"],
+ [`${mcp.url}/mcp`, "/mcp"],
+ [`${mcp.url}/mcp/`, "/mcp"],
+ [mcp.url, "/mcp"],
+ [`${mcp.url}/`, "/mcp"],
];
for (const [url, expected] of cases) {
- const seen: string[] = [];
- const fetchImpl: McpFetch = async (target) => {
- seen.push(target);
- return {
- ok: true,
- status: 200,
- text: async () => JSON.stringify({ jsonrpc: "2.0", id: 1, result: { tools: [] } }),
- };
- };
- await createMcpClient({ url, auth: { mode: "none" }, fetchImpl }).listTools();
- assert.deepEqual(seen, [expected], url);
+ mcp.requests.length = 0;
+ await createMcpClient({ url, auth: { mode: "none" } }).listTools();
+ assert.deepEqual([...new Set(mcp.requests.map((r) => r.path))], [expected], url);
}
});
-test("mcp client mints client-credentials tokens beside the endpoint", async () => {
- const seen: string[] = [];
- const fetchImpl: McpFetch = async (target) => {
- seen.push(target);
- const body = target.endsWith("/token")
- ? { access_token: "minted", expires_in: 3600 }
- : { jsonrpc: "2.0", id: 1, result: { tools: [] } };
- return { ok: true, status: 200, text: async () => JSON.stringify(body) };
- };
- await createMcpClient({
- url: "https://mcp.example.com/mcp",
+test("mcp client mints client-credentials tokens on the server's origin and reuses them until rejected", async (t) => {
+ const mcp = await startMcpTestServer(t, { clients: { id: "secret" } });
+ const client = createMcpClient({
+ url: `${mcp.url}/mcp`,
+ auth: { mode: "client-credentials", clientId: "id", clientSecret: "secret" },
+ });
+ assert.equal((await client.listTools()).length, 2);
+ assert.equal(mcpResultText(await client.callTool("query", {})), "ran query");
+ assert.deepEqual(mcp.tokenRequests, ["id"]);
+ mcp.revokeTokens();
+ assert.equal(mcpResultText(await client.callTool("query", {})), "ran query");
+ assert.equal(mcp.tokenRequests.length, 2);
+ const wrong = createMcpClient({
+ url: mcp.url,
+ auth: { mode: "client-credentials", clientId: "id", clientSecret: "guess" },
+ });
+ await assert.rejects(wrong.listTools());
+});
+
+test("mcp client never sends client credentials to an authorization server on another origin", async (t) => {
+ const elsewhere = await startMcpTestServer(t, { clients: { id: "secret" } });
+ const mcp = await startMcpTestServer(t, { clients: { id: "secret" }, authorizationServer: elsewhere.url });
+ const client = createMcpClient({
+ url: mcp.url,
auth: { mode: "client-credentials", clientId: "id", clientSecret: "secret" },
- fetchImpl,
- }).listTools();
- assert.deepEqual(seen, ["https://mcp.example.com/token", "https://mcp.example.com/mcp"]);
+ });
+ await assert.rejects(client.listTools(), (e: Error) => /not presented to/.test(String(e.cause)));
+ assert.deepEqual(elsewhere.tokenRequests, []);
+ assert.deepEqual(mcp.tokenRequests, []);
});
test("server id validation", () => {
@@ -137,11 +139,11 @@ test("server id validation", () => {
assert.ok(!isValidMcpServerId("has space"));
});
-test("tool service exposes namespaced tools and calls through", async () => {
+test("tool service exposes namespaced tools and calls through", async (t) => {
+ const mcp = await startMcpTestServer(t);
const store = createMcpServerStore(createMemoryMap<McpServer>());
- const { fetch } = fakeServerFetch();
- const service = createMcpToolService({ servers: store, fetchImpl: fetch, refreshIntervalMs: 3600_000 });
- await store.put(server());
+ const service = createMcpToolService({ servers: store, refreshIntervalMs: 3600_000 });
+ await store.put(server({ url: `${mcp.url}/mcp` }));
await service.refresh();
const defs = service.toolDefs();
assert.deepEqual(defs.map((d) => d.name).sort(), ["crm_query", "crm_update"]);
@@ -151,14 +153,14 @@ test("tool service exposes namespaced tools and calls through", async () => {
service.close();
});
-test("disabled server's tools disappear and calls fail", async () => {
+test("disabled server's tools disappear and calls fail", async (t) => {
+ const mcp = await startMcpTestServer(t);
const store = createMcpServerStore(createMemoryMap<McpServer>());
- const { fetch } = fakeServerFetch();
- const service = createMcpToolService({ servers: store, fetchImpl: fetch, refreshIntervalMs: 3600_000 });
- await store.put(server());
+ const service = createMcpToolService({ servers: store, refreshIntervalMs: 3600_000 });
+ await store.put(server({ url: mcp.url }));
await service.refresh();
assert.equal(service.toolDefs().length, 2);
- await store.put(server({ enabled: false }));
+ await store.put(server({ url: mcp.url, enabled: false }));
await service.refresh();
assert.equal(service.toolDefs().length, 0);
service.close();
@@ -181,34 +183,30 @@ function tokenStore() {
}
test("per-user calls resolve only the caller's fresh token while discovery uses catalog auth", async (t) => {
+ const mcp = await startMcpTestServer(t, {
+ call: (_name, args) => ({ content: [{ type: "text", text: String(args.q) }] }),
+ });
const store = createMcpServerStore(createMemoryMap<McpServer>());
const users = tokenStore();
const host = "accounts.example.com";
await users.setConnectorToken(host, "internal:alice", { accessToken: "alice-token" });
await users.setConnectorToken(host, "internal:bob", { accessToken: "bob-token" });
- const catalogAuth: string[] = [];
- const callAuth: string[] = [];
- const service = createMcpToolService({
- servers: store,
- userTokens: users,
- fetchImpl: async (_url, init) => {
- const rpc = JSON.parse(init.body);
- if (rpc.method === "tools/list") {
- catalogAuth.push(init.headers.authorization!);
- return jsonResponse({ result: { tools: TOOLS } });
- }
- callAuth.push(init.headers.authorization!);
- return jsonResponse({ result: { content: [{ type: "text", text: rpc.params.arguments.q }] } });
- },
- });
+ const authFor = (rpc: string) => mcp.requests.filter((r) => r.rpc === rpc).map((r) => r.authorization);
+ const service = createMcpToolService({ servers: store, userTokens: users });
t.after(() => service.close());
await store.put(
- server({ auth: "bearer", bearerToken: "catalog-only", credentialScope: "per-user", credentialHost: host }),
+ server({
+ url: mcp.url,
+ auth: "bearer",
+ bearerToken: "catalog-only",
+ credentialScope: "per-user",
+ credentialHost: host,
+ }),
);
await service.refresh();
assert.deepEqual(await service.probe((await store.get("crm"))!), ["query", "update"]);
- assert.ok(catalogAuth.length > 0);
- assert.ok(catalogAuth.every((auth) => auth === "Bearer catalog-only"));
+ assert.ok(authFor("tools/list").length > 0);
+ assert.ok(authFor("tools/list").every((auth) => auth === "Bearer catalog-only"));
assert.deepEqual(
await Promise.all([
service.call("crm_query", { q: "alice" }, "internal:alice"),
@@ -216,10 +214,10 @@ test("per-user calls resolve only the caller's fresh token while discovery uses
]),
["alice", "bob"],
);
- assert.deepEqual(callAuth.sort(), ["Bearer alice-token", "Bearer bob-token"]);
+ assert.deepEqual(authFor("tools/call").sort(), ["Bearer alice-token", "Bearer bob-token"]);
await users.setConnectorToken(host, "internal:alice", { accessToken: "rotated-alice" });
await service.call("crm_query", { q: "rotated" }, "internal:alice");
- assert.equal(callAuth.at(-1), "Bearer rotated-alice");
+ assert.equal(authFor("tools/call").at(-1), "Bearer rotated-alice");
await users.deleteConnectorToken(host, "internal:alice");
await assert.rejects(service.call("crm_query", {}, "internal:alice"), /Connect your account/);
await assert.rejects(service.call("crm_query", {}), /requires a connected user/);
@@ -229,16 +227,17 @@ test("per-user calls resolve only the caller's fresh token while discovery uses
);
await users.setConnectorToken(host, "internal:bob", { accessToken: "expired", expiresAt: 1 });
await assert.rejects(service.call("crm_query", {}, "internal:bob"), /Connect your account/);
- assert.equal(callAuth.length, 3);
+ assert.equal(authFor("tools/call").length, 3);
});
test("per-user mode fails closed without a keychain and shared mode preserves existing behavior", async (t) => {
+ const mcp = await startMcpTestServer(t, { authorize: (auth) => auth === "Bearer shared-token" });
const store = createMcpServerStore(createMemoryMap<McpServer>());
- const { fetch, calls } = fakeServerFetch({ requireBearer: "shared-token" });
- const service = createMcpToolService({ servers: store, fetchImpl: fetch });
+ const service = createMcpToolService({ servers: store });
t.after(() => service.close());
await store.put(
server({
+ url: mcp.url,
auth: "bearer",
bearerToken: "shared-token",
credentialScope: "per-user",
@@ -246,10 +245,10 @@ test("per-user mode fails closed without a keychain and shared mode preserves ex
}),
);
await service.refresh();
- const count = calls.length;
+ const count = mcp.requests.length;
await assert.rejects(service.call("crm_query", {}, "internal:alice"), /requires a connected user/);
- assert.equal(calls.length, count);
- await store.put(server({ auth: "bearer", bearerToken: "shared-token", credentialScope: "shared" }));
+ assert.equal(mcp.requests.length, count);
+ await store.put(server({ url: mcp.url, auth: "bearer", bearerToken: "shared-token", credentialScope: "shared" }));
await service.refresh();
assert.equal(await service.call("crm_query", {}), "ran query");
});
@@ -286,11 +285,12 @@ test("per-user connectors select an explicit account slot without falling back t
const host = "accounts.example.com";
await users.setConnectorToken(host, "internal:alice", { accessToken: "default-token" });
await users.setConnectorToken(host, "internal:alice", { accessToken: "company-token" }, "company");
- const { fetch } = fakeServerFetch({ requireBearer: "company-token" });
- const service = createMcpToolService({ servers: store, userTokens: users, fetchImpl: fetch });
+ const mcp = await startMcpTestServer(t, { authorize: (auth) => auth === "Bearer company-token" });
+ const service = createMcpToolService({ servers: store, userTokens: users });
t.after(() => service.close());
await store.put(
server({
+ url: mcp.url,
auth: "bearer",
bearerToken: "company-token",
credentialScope: "per-user",
@@ -308,27 +308,27 @@ test("background MCP refresh contains registry failures at startup, on change, a
t.mock.timers.enable({ apis: ["setInterval"] });
const backing = createMemoryMap<McpServer>();
const store = createMcpServerStore(backing);
- const { fetch } = fakeServerFetch();
+ const mcp = await startMcpTestServer(t);
const list = t.mock.method(store, "list", async () => {
throw new Error("registry unavailable");
});
const errors = t.mock.method(console, "error", () => {});
- const service = createMcpToolService({ servers: store, fetchImpl: fetch, refreshIntervalMs: 100 });
+ const service = createMcpToolService({ servers: store, refreshIntervalMs: 100 });
t.after(() => service.close());
- const settle = () => new Promise<void>((resolve) => setImmediate(resolve));
- await settle();
+ const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
+ await tick();
assert.equal(list.mock.callCount(), 1);
- await store.put(server());
- await settle();
+ await store.put(server({ url: mcp.url }));
+ await tick();
assert.equal(list.mock.callCount(), 2);
t.mock.timers.tick(100);
- await settle();
+ await tick();
assert.equal(list.mock.callCount(), 3);
assert.equal(errors.mock.callCount(), 3);
await assert.rejects(service.refresh(), /registry unavailable/);
list.mock.restore();
t.mock.timers.tick(100);
- await settle();
+ await settle(async () => service.toolDefs().length > 0);
assert.deepEqual(
service.toolDefs().map((tool) => tool.name),
["crm_query", "crm_update"],
diff --git a/test/mcp-memory-provider.test.ts b/test/mcp-memory-provider.test.ts
index b8ad0ba8e..a2e62fb8e 100644
--- a/test/mcp-memory-provider.test.ts
+++ b/test/mcp-memory-provider.test.ts
@@ -6,8 +6,6 @@ import { recallText } from "./support/recall-text.ts";
function client(calls: Array<{ tool: string; args: Record<string, unknown> }>, text = "result"): McpClient {
return {
- base: "http://knowledge.internal",
- host: "knowledge.internal",
async listTools() {
return [];
},
@@ -59,8 +57,6 @@ test("MCP recall is locally bounded and times out", async () => {
assert.equal(recallText(await bounded.recall("org:acme", { maxChars: 4 })), "abcd");
const hanging: McpClient = {
- base: "http://knowledge.internal",
- host: "knowledge.internal",
async listTools() {
return [];
},
diff --git a/test/mcp-oauth-user.test.ts b/test/mcp-oauth-user.test.ts
index ad69267f3..0b67c66b1 100644
--- a/test/mcp-oauth-user.test.ts
+++ b/test/mcp-oauth-user.test.ts
@@ -11,6 +11,7 @@ import {
withPublicOAuthClients,
} from "../src/connectors/oauth.ts";
import { createMemoryMap } from "../src/persistence/durable-map.ts";
+import { startMcpTestServer } from "./support/mcp-test-server.ts";
const HOST = "mcp.example.com";
@@ -87,33 +88,28 @@ test("oauth-user servers register a PKCE public client that exchanges and refres
test("oauth-user tools offer a sign-in link until the caller connects, then use only their token", async (t) => {
const store = createMcpServerStore(createMemoryMap<McpServer>());
const tokens = new Map<string, string>();
- const auth: string[] = [];
+ const mcp = await startMcpTestServer(t, {
+ tools: [{ name: "search", description: "Search", inputSchema: { type: "object" } }],
+ call: (_name, args) => ({ content: [{ type: "text", text: `found ${String(args.q)}` }] }),
+ });
+ const auth = () => mcp.requests.filter((r) => r.rpc?.startsWith("tools/")).map((r) => r.authorization ?? "");
const service = createMcpToolService({
servers: store,
userTokens: { connectorAccessToken: async (_host, principalId) => tokens.get(principalId) ?? null },
signInUrl: (id) => `https://qm.example/connect/${id}/self-connect`,
- fetchImpl: async (_url, init) => {
- auth.push(init.headers.authorization ?? "");
- const rpc = JSON.parse(init.body) as { id: number; method: string; params: { arguments?: { q?: string } } };
- const result =
- rpc.method === "tools/list"
- ? { tools: [{ name: "search", description: "Search", inputSchema: { type: "object" } }] }
- : { content: [{ type: "text", text: `found ${rpc.params.arguments?.q}` }] };
- return { ok: true, status: 200, text: async () => JSON.stringify({ jsonrpc: "2.0", id: rpc.id, result }) };
- },
});
t.after(() => {
service.close();
setPublicOAuthClients([]);
});
- await store.put(oauthServer());
+ await store.put(oauthServer({ url: `${mcp.url}/mcp` }));
await service.refresh();
assert.ok(oauthProvider("orders")?.pkce, "refresh registers the server's OAuth client");
assert.deepEqual(
service.toolDefs().map((d) => d.name),
["orders_sign_in"],
);
- assert.equal(auth.length, 0, "no unauthenticated discovery");
+ assert.equal(mcp.requests.length, 0, "no unauthenticated discovery");
assert.match(
await service.call("orders_sign_in", {}, "internal:alice"),
/\[Connect Orders\]\(https:\/\/qm\.example\/connect\/orders\/self-connect\)/,
@@ -132,5 +128,5 @@ test("oauth-user tools offer a sign-in link until the caller connects, then use
);
assert.equal(await service.call("orders_search", { q: "tacos" }, "internal:alice"), "found tacos");
assert.match(await service.call("orders_search", { q: "x" }, "internal:bob"), /Connect Orders/);
- assert.deepEqual(auth, ["Bearer alice-token", "Bearer alice-token"]);
+ assert.deepEqual(auth(), ["Bearer alice-token", "Bearer alice-token"]);
});
diff --git a/test/memory-provider-factory.test.ts b/test/memory-provider-factory.test.ts
index faa5c0cd0..7c3fca01d 100644
--- a/test/memory-provider-factory.test.ts
+++ b/test/memory-provider-factory.test.ts
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
import { createConfiguredMemoryService } from "../src/memory/provider-factory.ts";
import { parseMemoryProviderConfig } from "../src/memory/provider-config.ts";
import type { MemoryService } from "../src/memory/memory-service.ts";
-import type { McpFetch } from "../src/mcp/mcp-client.ts";
+import { startMcpTestServer } from "./support/mcp-test-server.ts";
import { recallText } from "./support/recall-text.ts";
const defaultMemory: MemoryService = {
@@ -21,38 +21,18 @@ const defaultMemory: MemoryService = {
},
};
-function response(body: unknown) {
- return {
- ok: true,
- status: 200,
- headers: { get: () => "application/json" },
- async text() {
- return JSON.stringify(body);
- },
- };
-}
-
-test("configured provider runs OAuth MCP recall and explicit capture end to end", async () => {
- const calls: Array<{ url: string; body: string; authorization?: string }> = [];
- const fetchImpl: McpFetch = async (url, init) => {
- calls.push({ url, body: init.body, authorization: init.headers.authorization });
- if (url.endsWith("/token")) {
- const params = new URLSearchParams(init.body);
- return response({ access_token: `${params.get("client_id")}-token`, expires_in: 300 });
- }
- const rpc = JSON.parse(init.body) as { id: number; params: { name: string; arguments: Record<string, unknown> } };
- return response({
- jsonrpc: "2.0",
- id: rpc.id,
- result: { content: [{ type: "text", text: rpc.params.name === "search_knowledge" ? "org knowledge" : "ok" }] },
- });
- };
+test("configured provider runs OAuth MCP recall and explicit capture end to end", async (t) => {
+ const mcp = await startMcpTestServer(t, {
+ tools: ["search_knowledge", "write_knowledge"].map((name) => ({ name, inputSchema: { type: "object" as const } })),
+ clients: { ro: "x", rw: "y" },
+ call: (name) => ({ content: [{ type: "text", text: name === "search_knowledge" ? "org knowledge" : "ok" }] }),
+ });
const raw = JSON.stringify({
providers: [
{
id: "knowledge",
type: "mcp",
- url: "http://knowledge.internal:8080",
+ url: mcp.url,
read: { tool: "search_knowledge", clientIdEnv: "RO_ID", clientSecretEnv: "RO_SECRET" },
write: { tool: "write_knowledge", clientIdEnv: "RW_ID", clientSecretEnv: "RW_SECRET" },
},
@@ -65,7 +45,6 @@ test("configured provider runs OAuth MCP recall and explicit capture end to end"
const memory = createConfiguredMemoryService({
defaultMemory,
config: parseMemoryProviderConfig(raw, { RO_ID: "ro", RO_SECRET: "x", RW_ID: "rw", RW_SECRET: "y" }),
- fetchImpl,
});
assert.equal(recallText(await memory.recall("personal:u1", { query: "launch", actorId: "u1" })), "personal notebook");
@@ -73,10 +52,9 @@ test("configured provider runs OAuth MCP recall and explicit capture end to end"
assert.equal(await memory.capture("org:acme", ["decision"], 1, "u1", { mode: "automatic" }), 0);
assert.equal(await memory.capture("org:acme", ["decision"], 1, "u1", { mode: "explicit" }), 1);
- assert.equal(calls[0]?.url, "http://knowledge.internal:8080/token");
- assert.equal(calls[1]?.authorization, "Bearer ro-token");
- assert.match(calls[1]?.body ?? "", /search_knowledge/);
- assert.equal(calls[2]?.url, "http://knowledge.internal:8080/token");
- assert.equal(calls[3]?.authorization, "Bearer rw-token");
- assert.match(calls[3]?.body ?? "", /write_knowledge/);
+ assert.deepEqual(mcp.tokenRequests, ["ro", "rw"]);
+ assert.deepEqual(
+ mcp.requests.filter((r) => r.rpc === "tools/call").map((r) => r.authorization),
+ ["Bearer ro-token-1", "Bearer rw-token-2"],
+ );
});
diff --git a/test/support/mcp-test-server.ts b/test/support/mcp-test-server.ts
new file mode 100644
index 000000000..14360deba
--- /dev/null
+++ b/test/support/mcp-test-server.ts
@@ -0,0 +1,179 @@
+import { randomUUID } from "node:crypto";
+import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
+import type { AddressInfo } from "node:net";
+import { Server } from "@modelcontextprotocol/sdk/server/index.js";
+import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
+import {
+ CallToolRequestSchema,
+ ErrorCode,
+ ListToolsRequestSchema,
+ McpError,
+ type CallToolResult,
+ type Tool,
+} from "@modelcontextprotocol/sdk/types.js";
+
+interface McpRequest {
+ method: string;
+ path: string;
+ rpc?: string;
+ authorization?: string;
+}
+
+export interface McpTestServer {
+ url: string;
+ requests: McpRequest[];
+ tokenRequests: string[];
+ openSessions(): number;
+ dropSessions(): Promise<void>;
+ revokeTokens(): void;
+}
+
+const DEFAULT_TOOLS: Tool[] = [
+ { name: "query", description: "Run a query", inputSchema: { type: "object", properties: { q: { type: "string" } } } },
+ { name: "update", description: "Write a record", inputSchema: { type: "object", properties: {} } },
+];
+
+function readBody(req: IncomingMessage): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const chunks: Buffer[] = [];
+ req.on("data", (c: Buffer) => chunks.push(c));
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
+ req.on("error", reject);
+ });
+}
+
+function json(res: ServerResponse, status: number, body: unknown, headers: Record<string, string> = {}): void {
+ res.writeHead(status, { "content-type": "application/json", ...headers });
+ res.end(JSON.stringify(body));
+}
+
+export async function startMcpTestServer(
+ t: { after(fn: () => Promise<void>): void },
+ opts: {
+ tools?: Tool[];
+ pageSize?: number;
+ json?: boolean;
+ authorize?: (authorization: string | undefined) => boolean;
+ clients?: Record<string, string>;
+ authorizationServer?: string;
+ call?: (name: string, args: Record<string, unknown>, authorization?: string) => CallToolResult;
+ } = {},
+): Promise<McpTestServer> {
+ const tools = opts.tools ?? DEFAULT_TOOLS;
+ const pageSize = opts.pageSize ?? tools.length;
+ const sessions = new Map<string, StreamableHTTPServerTransport>();
+ const tokens = new Map<string, string>();
+ const requests: McpRequest[] = [];
+ const tokenRequests: string[] = [];
+
+ function mcpServer(): Server {
+ const server = new Server({ name: "qm-test", version: "1.0.0" }, { capabilities: { tools: {} } });
+ server.setRequestHandler(ListToolsRequestSchema, (req) => {
+ const start = Number(req.params?.cursor ?? 0);
+ const end = start + pageSize;
+ return { tools: tools.slice(start, end), ...(end < tools.length ? { nextCursor: String(end) } : {}) };
+ });
+ server.setRequestHandler(CallToolRequestSchema, (req, extra) => {
+ const { name } = req.params;
+ if (!tools.some((tool) => tool.name === name))
+ throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${name}`);
+ const authorization = extra.requestInfo?.headers.authorization;
+ const args = req.params.arguments ?? {};
+ return (
+ opts.call?.(name, args, typeof authorization === "string" ? authorization : undefined) ?? {
+ content: [{ type: "text", text: `ran ${name}` }],
+ }
+ );
+ });
+ return server;
+ }
+
+ function token(req: IncomingMessage, body: string, res: ServerResponse): void {
+ const form = new URLSearchParams(body);
+ const basic = req.headers.authorization?.match(/^Basic (.+)$/)?.[1];
+ const [clientId, secret] = basic
+ ? Buffer.from(basic, "base64").toString().split(":").map(decodeURIComponent)
+ : [form.get("client_id"), form.get("client_secret")];
+ if (form.get("grant_type") !== "client_credentials" || !clientId || opts.clients?.[clientId] !== secret) {
+ return json(res, 401, { error: "invalid_client" });
+ }
+ tokenRequests.push(clientId);
+ const accessToken = `${clientId}-token-${tokenRequests.length}`;
+ tokens.set(accessToken, clientId);
+ json(res, 200, { access_token: accessToken, token_type: "Bearer", expires_in: 3600 });
+ }
+
+ function authorized(authorization: string | undefined): boolean {
+ if (opts.clients) return tokens.has(authorization?.replace(/^Bearer /, "") ?? "");
+ return opts.authorize ? opts.authorize(authorization) : true;
+ }
+
+ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
+ const path = new URL(req.url ?? "/", "http://localhost").pathname;
+ const body = req.method === "POST" ? await readBody(req) : "";
+ if (path === "/token" && opts.clients) return token(req, body, res);
+ if (path.startsWith("/.well-known/oauth-protected-resource") && opts.authorizationServer) {
+ return json(res, 200, { resource: `${url}/mcp`, authorization_servers: [opts.authorizationServer] });
+ }
+ if (path.startsWith("/.well-known/")) return json(res, 404, { error: "not_found" });
+ const parsed = body ? (JSON.parse(body) as { method?: string }) : undefined;
+ const authorization = req.headers.authorization;
+ requests.push({
+ method: req.method ?? "",
+ path,
+ ...(parsed?.method ? { rpc: parsed.method } : {}),
+ ...(authorization ? { authorization } : {}),
+ });
+ if (!authorized(authorization)) {
+ return json(res, 401, { error: "unauthorized" }, { "www-authenticate": 'Bearer error="invalid_token"' });
+ }
+ const sessionId = req.headers["mcp-session-id"];
+ if (typeof sessionId === "string") {
+ const transport = sessions.get(sessionId);
+ if (!transport)
+ return json(res, 404, { jsonrpc: "2.0", error: { code: -32001, message: "Session not found" }, id: null });
+ return transport.handleRequest(req, res, parsed);
+ }
+ if (parsed?.method !== "initialize")
+ return json(res, 400, { jsonrpc: "2.0", error: { code: -32000, message: "No session" }, id: null });
+ const transport = new StreamableHTTPServerTransport({
+ sessionIdGenerator: randomUUID,
+ enableJsonResponse: opts.json ?? false,
+ onsessioninitialized: (id) => void sessions.set(id, transport),
+ });
+ transport.onclose = () => {
+ if (transport.sessionId) sessions.delete(transport.sessionId);
+ };
+ await mcpServer().connect(transport);
+ await transport.handleRequest(req, res, parsed);
+ }
+
+ const http = createServer((req, res) => {
+ handle(req, res).catch((e: unknown) => {
+ if (!res.headersSent) json(res, 500, { error: String(e) });
+ });
+ });
+ http.listen(0, "127.0.0.1");
+ await new Promise<void>((resolve) => http.once("listening", resolve));
+ const url = `http://127.0.0.1:${(http.address() as AddressInfo).port}`;
+
+ async function dropSessions(): Promise<void> {
+ await Promise.all([...sessions.values()].map((transport) => transport.close()));
+ sessions.clear();
+ }
+
+ t.after(async () => {
+ await dropSessions();
+ http.closeAllConnections();
+ await new Promise<void>((resolve) => http.close(() => resolve()));
+ });
+
+ return {
+ url,
+ requests,
+ tokenRequests,
+ openSessions: () => sessions.size,
+ dropSessions,
+ revokeTokens: () => tokens.clear(),
+ };
+}