Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

style: apply repo-wide formatting and connector-edit UX

Miguelon Peluchon5328bf24f651
diff --git a/channel-reader/package-lock.json b/channel-reader/package-lock.json
index 314434829..807c148c1 100644
--- a/channel-reader/package-lock.json
+++ b/channel-reader/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-channel-reader",
- "version": "0.1.82",
+ "version": "0.1.83",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-channel-reader",
- "version": "0.1.82",
+ "version": "0.1.83",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@kubernetes/client-node": "^1.0.0",
diff --git a/channel-reader/package.json b/channel-reader/package.json
index e2c717ac1..b3e9a0d2a 100644
--- a/channel-reader/package.json
+++ b/channel-reader/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-channel-reader",
- "version": "0.1.82",
+ "version": "0.1.83",
"description": "Watches CommunicationChannel CRDs and fetches messages from Telegram, Email, and Slack",
"main": "dist/main.js",
"engines": {
diff --git a/channel-reader/src/__tests__/progressFormatter.test.ts b/channel-reader/src/__tests__/progressFormatter.test.ts
index d8cdf91ed..5ad662f1c 100644
--- a/channel-reader/src/__tests__/progressFormatter.test.ts
+++ b/channel-reader/src/__tests__/progressFormatter.test.ts
@@ -1,83 +1,88 @@
-import { describe, it, expect } from "vitest";
-import { formatProgressUpdate, formatFinalMessage } from "../progressFormatter";
-import type { ProgressStep } from "../types";
+import { describe, expect, it } from 'vitest'
+import { formatFinalMessage, formatProgressUpdate } from '../progressFormatter'
+import type { ProgressStep } from '../types'
const step = (overrides: Partial<ProgressStep> = {}): ProgressStep => ({
- toolCallId: "c1",
- toolName: "mongodb-server__find",
- displayName: "Mongodb-server",
- intentSummary: "Using Mongodb-server...",
+ toolCallId: 'c1',
+ toolName: 'mongodb-server__find',
+ displayName: 'Mongodb-server',
+ intentSummary: 'Using Mongodb-server...',
iteration: 0,
stepIndex: 0,
totalSteps: 1,
- state: "completed",
+ state: 'completed',
durationMs: 340,
...overrides,
-});
+})
-describe("formatProgressUpdate", () => {
- it("shows running step with spinner", () => {
- const result = formatProgressUpdate([step({ state: "running", durationMs: undefined })]);
- expect(result).toContain("Processing");
- expect(result).toContain("●");
- expect(result).toContain("running...");
- });
+describe('formatProgressUpdate', () => {
+ it('shows running step with spinner', () => {
+ const result = formatProgressUpdate([step({ state: 'running', durationMs: undefined })])
+ expect(result).toContain('Processing')
+ expect(result).toContain('●')
+ expect(result).toContain('running...')
+ })
- it("shows completed step with checkmark and duration", () => {
- const result = formatProgressUpdate([step()]);
- expect(result).toContain("✓");
- expect(result).toContain("Mongodb-server");
- expect(result).toContain("find");
- expect(result).toContain("340ms");
- });
+ it('shows completed step with checkmark and duration', () => {
+ const result = formatProgressUpdate([step()])
+ expect(result).toContain('✓')
+ expect(result).toContain('Mongodb-server')
+ expect(result).toContain('find')
+ expect(result).toContain('340ms')
+ })
- it("shows error step with cross", () => {
- const result = formatProgressUpdate([step({ state: "error", errorSummary: "HTTP 404" })]);
- expect(result).toContain("✗");
- expect(result).toContain("HTTP 404");
- });
+ it('shows error step with cross', () => {
+ const result = formatProgressUpdate([step({ state: 'error', errorSummary: 'HTTP 404' })])
+ expect(result).toContain('✗')
+ expect(result).toContain('HTTP 404')
+ })
- it("shows iteration divider when iteration changes", () => {
- const steps = [
- step({ iteration: 0 }),
- step({ toolCallId: "c2", iteration: 1, stepIndex: 0 }),
- ];
- const result = formatProgressUpdate(steps);
- expect(result).toContain("Thinking further");
- });
+ it('shows iteration divider when iteration changes', () => {
+ const steps = [step({ iteration: 0 }), step({ toolCallId: 'c2', iteration: 1, stepIndex: 0 })]
+ const result = formatProgressUpdate(steps)
+ expect(result).toContain('Thinking further')
+ })
- it("shows tool function name for MCP tools", () => {
- const result = formatProgressUpdate([step()]);
- expect(result).toContain("find");
- });
+ it('shows tool function name for MCP tools', () => {
+ const result = formatProgressUpdate([step()])
+ expect(result).toContain('find')
+ })
- it("shows tool name for native tools with shared display name", () => {
- const result = formatProgressUpdate([step({ toolName: "memory_read", displayName: "Memory" })]);
- expect(result).toContain("memory_read");
- });
-});
+ it('shows tool name for native tools with shared display name', () => {
+ const result = formatProgressUpdate([step({ toolName: 'memory_read', displayName: 'Memory' })])
+ expect(result).toContain('memory_read')
+ })
+})
-describe("formatFinalMessage", () => {
- it("prefixes response with compact summary", () => {
- const steps = [step(), step({ toolCallId: "c2", toolName: "mongodb-server__aggregate", stepIndex: 1, totalSteps: 2 })];
- const result = formatFinalMessage(steps, "Here is your data.");
- expect(result).toContain("✓ 2 tools used");
- expect(result).toContain("Here is your data.");
- });
+describe('formatFinalMessage', () => {
+ it('prefixes response with compact summary', () => {
+ const steps = [
+ step(),
+ step({
+ toolCallId: 'c2',
+ toolName: 'mongodb-server__aggregate',
+ stepIndex: 1,
+ totalSteps: 2,
+ }),
+ ]
+ const result = formatFinalMessage(steps, 'Here is your data.')
+ expect(result).toContain('✓ 2 tools used')
+ expect(result).toContain('Here is your data.')
+ })
- it("returns just the response for zero-tool tasks", () => {
- const result = formatFinalMessage([], "Just a text response.");
- expect(result).toBe("Just a text response.");
- });
+ it('returns just the response for zero-tool tasks', () => {
+ const result = formatFinalMessage([], 'Just a text response.')
+ expect(result).toBe('Just a text response.')
+ })
- it("shows warning icon when errors occurred", () => {
- const result = formatFinalMessage([step({ state: "error" })], "Partial response.");
- expect(result).toContain("⚠");
- });
+ it('shows warning icon when errors occurred', () => {
+ const result = formatFinalMessage([step({ state: 'error' })], 'Partial response.')
+ expect(result).toContain('⚠')
+ })
- it("truncates summary if total exceeds 4096 chars", () => {
- const longResponse = "A".repeat(4090);
- const result = formatFinalMessage([step()], longResponse);
- expect(result.length).toBeLessThanOrEqual(4096);
- });
-});
+ it('truncates summary if total exceeds 4096 chars', () => {
+ const longResponse = 'A'.repeat(4090)
+ const result = formatFinalMessage([step()], longResponse)
+ expect(result.length).toBeLessThanOrEqual(4096)
+ })
+})
diff --git a/channel-reader/src/k8sClient.ts b/channel-reader/src/k8sClient.ts
index 4971a91e2..83936c476 100644
--- a/channel-reader/src/k8sClient.ts
+++ b/channel-reader/src/k8sClient.ts
@@ -1,60 +1,59 @@
/**
* Kubernetes client for watching CommunicationChannel CRDs.
*/
+import * as k8s from '@kubernetes/client-node'
+import { CommunicationChannelCRD, CommunicationChannelSpec } from './types'
-import * as k8s from "@kubernetes/client-node";
-import { CommunicationChannelCRD, CommunicationChannelSpec } from "./types";
-
-const CRD_GROUP = "clerum.io";
-const CRD_VERSION = "v1alpha1";
-const CRD_PLURAL = "communicationchannels";
+const CRD_GROUP = 'clerum.io'
+const CRD_VERSION = 'v1alpha1'
+const CRD_PLURAL = 'communicationchannels'
/** Delay before restarting the watch stream after a disconnect (ms). */
-const WATCH_RECONNECT_DELAY_MS = 5000;
+const WATCH_RECONNECT_DELAY_MS = 5000
-export type ChannelChangeCallback = (channels: CommunicationChannelCRD[]) => void;
+export type ChannelChangeCallback = (channels: CommunicationChannelCRD[]) => void
export class CommunicationChannelWatcher {
- private api: k8s.CustomObjectsApi;
- private watch: k8s.Watch;
- private kc: k8s.KubeConfig;
- private hostRef: string;
- private namespace: string;
- private onChangeCallback?: ChannelChangeCallback;
- private channels: Map<string, CommunicationChannelCRD> = new Map();
- private watchRequest?: { abort: () => void };
+ private api: k8s.CustomObjectsApi
+ private watch: k8s.Watch
+ private kc: k8s.KubeConfig
+ private hostRef: string
+ private namespace: string
+ private onChangeCallback?: ChannelChangeCallback
+ private channels: Map<string, CommunicationChannelCRD> = new Map()
+ private watchRequest?: { abort: () => void }
- constructor(hostRef: string, namespace: string = "") {
- this.hostRef = hostRef;
- this.namespace = namespace;
+ constructor(hostRef: string, namespace: string = '') {
+ this.hostRef = hostRef
+ this.namespace = namespace
- this.kc = new k8s.KubeConfig();
+ this.kc = new k8s.KubeConfig()
// Try in-cluster config first, fall back to default kubeconfig
try {
- this.kc.loadFromCluster();
- console.log("[K8s] Loaded in-cluster config");
+ this.kc.loadFromCluster()
+ console.log('[K8s] Loaded in-cluster config')
} catch {
- this.kc.loadFromDefault();
- console.log("[K8s] Loaded kubeconfig from default location");
+ this.kc.loadFromDefault()
+ console.log('[K8s] Loaded kubeconfig from default location')
}
- this.api = this.kc.makeApiClient(k8s.CustomObjectsApi);
- this.watch = new k8s.Watch(this.kc);
+ this.api = this.kc.makeApiClient(k8s.CustomObjectsApi)
+ this.watch = new k8s.Watch(this.kc)
}
/**
* Set callback for when channels change.
*/
onChange(callback: ChannelChangeCallback): void {
- this.onChangeCallback = callback;
+ this.onChangeCallback = callback
}
/**
* Get current channels matching hostRef.
*/
getChannels(): CommunicationChannelCRD[] {
- return Array.from(this.channels.values());
+ return Array.from(this.channels.values())
}
/**
@@ -62,39 +61,41 @@ export class CommunicationChannelWatcher {
*/
public async listChannels(): Promise<CommunicationChannelCRD[]> {
try {
- let response: { items?: unknown[] };
+ let response: { items?: unknown[] }
if (this.namespace) {
- response = await this.api.listNamespacedCustomObject({
+ response = (await this.api.listNamespacedCustomObject({
group: CRD_GROUP,
version: CRD_VERSION,
namespace: this.namespace,
plural: CRD_PLURAL,
- }) as { items?: unknown[] };
+ })) as { items?: unknown[] }
} else {
- response = await this.api.listClusterCustomObject({
+ response = (await this.api.listClusterCustomObject({
group: CRD_GROUP,
version: CRD_VERSION,
plural: CRD_PLURAL,
- }) as { items?: unknown[] };
+ })) as { items?: unknown[] }
}
- this.channels.clear();
+ this.channels.clear()
for (const item of response.items || []) {
- const channel = this.parseChannel(item as Record<string, unknown>);
+ const channel = this.parseChannel(item as Record<string, unknown>)
if (channel && channel.spec.hostRef === this.hostRef) {
- const key = `${channel.namespace}/${channel.name}`;
- this.channels.set(key, channel);
- console.log(`[K8s] Found channel: ${channel.name} (hostRef: ${channel.spec.hostRef})`);
+ const key = `${channel.namespace}/${channel.name}`
+ this.channels.set(key, channel)
+ console.log(`[K8s] Found channel: ${channel.name} (hostRef: ${channel.spec.hostRef})`)
}
}
- console.log(`[K8s] Found ${this.channels.size} CommunicationChannel(s) for hostRef "${this.hostRef}"`);
- return this.getChannels();
+ console.log(
+ `[K8s] Found ${this.channels.size} CommunicationChannel(s) for hostRef "${this.hostRef}"`
+ )
+ return this.getChannels()
} catch (error) {
- console.error("[K8s] Failed to list CommunicationChannels:", error);
- throw error;
+ console.error('[K8s] Failed to list CommunicationChannels:', error)
+ throw error
}
}
@@ -104,87 +105,85 @@ export class CommunicationChannelWatcher {
async startWatch(): Promise<void> {
const path = this.namespace
? `/apis/${CRD_GROUP}/${CRD_VERSION}/namespaces/${this.namespace}/${CRD_PLURAL}`
- : `/apis/${CRD_GROUP}/${CRD_VERSION}/${CRD_PLURAL}`;
+ : `/apis/${CRD_GROUP}/${CRD_VERSION}/${CRD_PLURAL}`
- console.log(`[K8s] Starting watch on ${path} for hostRef "${this.hostRef}"`);
+ console.log(`[K8s] Starting watch on ${path} for hostRef "${this.hostRef}"`)
const watchHandler = async (type: string, apiObj: unknown) => {
- const channel = this.parseChannel(apiObj as Record<string, unknown>);
- if (!channel) return;
+ const channel = this.parseChannel(apiObj as Record<string, unknown>)
+ if (!channel) return
- const key = `${channel.namespace}/${channel.name}`;
- const matchesHost = channel.spec.hostRef === this.hostRef;
+ const key = `${channel.namespace}/${channel.name}`
+ const matchesHost = channel.spec.hostRef === this.hostRef
- let changed = false;
+ let changed = false
switch (type) {
- case "ADDED":
- case "MODIFIED":
+ case 'ADDED':
+ case 'MODIFIED':
if (matchesHost) {
- const existing = this.channels.get(key);
+ const existing = this.channels.get(key)
if (!existing || JSON.stringify(existing) !== JSON.stringify(channel)) {
- this.channels.set(key, channel);
- changed = true;
- console.log(`[K8s] Channel ${type}: ${channel.name}`);
+ this.channels.set(key, channel)
+ changed = true
+ console.log(`[K8s] Channel ${type}: ${channel.name}`)
}
} else {
// hostRef changed away from us
if (this.channels.has(key)) {
- this.channels.delete(key);
- changed = true;
- console.log(`[K8s] Channel removed (hostRef changed): ${channel.name}`);
+ this.channels.delete(key)
+ changed = true
+ console.log(`[K8s] Channel removed (hostRef changed): ${channel.name}`)
}
}
- break;
+ break
- case "DELETED":
+ case 'DELETED':
if (this.channels.has(key)) {
- this.channels.delete(key);
- changed = true;
- console.log(`[K8s] Channel DELETED: ${channel.name}`);
+ this.channels.delete(key)
+ changed = true
+ console.log(`[K8s] Channel DELETED: ${channel.name}`)
}
- break;
+ break
}
if (changed && this.onChangeCallback) {
- this.onChangeCallback(this.getChannels());
+ this.onChangeCallback(this.getChannels())
}
- };
+ }
const startWatch = async () => {
try {
- this.watchRequest = await this.watch.watch(
- path,
- {},
- watchHandler,
- (err) => {
- if (err) {
- console.error("[K8s] Watch error:", err);
- }
- // Restart watch after error or disconnect. Before restarting the
- // stream, re-list all CommunicationChannels so events that arrived
- // during the reconnect gap are not silently missed. If the
- // re-listed set differs from the in-memory cache, fire onChange so
- // the poll loop schedules a restart.
- console.log("[K8s] Watch ended, resyncing channels then restarting in 5s...");
- setTimeout(async () => {
- try {
- await this.resyncChannels();
- await startWatch();
- } catch (reconnectErr) {
- console.error("[K8s] Reconnect callback failed, scheduling another reconnect:", reconnectErr);
- setTimeout(() => startWatch(), WATCH_RECONNECT_DELAY_MS);
- }
- }, WATCH_RECONNECT_DELAY_MS);
+ this.watchRequest = await this.watch.watch(path, {}, watchHandler, err => {
+ if (err) {
+ console.error('[K8s] Watch error:', err)
}
- );
+ // Restart watch after error or disconnect. Before restarting the
+ // stream, re-list all CommunicationChannels so events that arrived
+ // during the reconnect gap are not silently missed. If the
+ // re-listed set differs from the in-memory cache, fire onChange so
+ // the poll loop schedules a restart.
+ console.log('[K8s] Watch ended, resyncing channels then restarting in 5s...')
+ setTimeout(async () => {
+ try {
+ await this.resyncChannels()
+ await startWatch()
+ } catch (reconnectErr) {
+ console.error(
+ '[K8s] Reconnect callback failed, scheduling another reconnect:',
+ reconnectErr
+ )
+ setTimeout(() => startWatch(), WATCH_RECONNECT_DELAY_MS)
+ }
+ }, WATCH_RECONNECT_DELAY_MS)
+ })
} catch (error) {
- console.error("[K8s] Failed to start watch:", error);
- setTimeout(() => startWatch(), WATCH_RECONNECT_DELAY_MS);
+ console.error('[K8s] Failed to start watch:', error)
+ setTimeout(() => startWatch(), WATCH_RECONNECT_DELAY_MS)
}
- };
+ }
- await startWatch();
+ await startWatch()
}
/**
@@ -198,22 +197,22 @@ export class CommunicationChannelWatcher {
public async resyncChannels(): Promise<void> {
const before = JSON.stringify(
[...this.channels.entries()].sort(([a], [b]) => a.localeCompare(b))
- );
+ )
try {
- await this.listChannels();
+ await this.listChannels()
} catch (err) {
- console.error("[K8s] Resync listChannels failed:", err);
- return;
+ console.error('[K8s] Resync listChannels failed:', err)
+ return
}
const after = JSON.stringify(
[...this.channels.entries()].sort(([a], [b]) => a.localeCompare(b))
- );
+ )
if (before !== after && this.onChangeCallback) {
- console.log("[K8s] Channel set changed during resync, firing onChange");
- this.onChangeCallback(this.getChannels());
+ console.log('[K8s] Channel set changed during resync, firing onChange')
+ this.onChangeCallback(this.getChannels())
}
}
@@ -222,28 +221,28 @@ export class CommunicationChannelWatcher {
*/
stopWatch(): void {
if (this.watchRequest) {
- this.watchRequest.abort();
- this.watchRequest = undefined;
+ this.watchRequest.abort()
+ this.watchRequest = undefined
}
}
private parseChannel(item: Record<string, unknown>): CommunicationChannelCRD | null {
try {
- const metadata = item.metadata as Record<string, unknown>;
- const spec = item.spec as CommunicationChannelSpec;
+ const metadata = item.metadata as Record<string, unknown>
+ const spec = item.spec as CommunicationChannelSpec
if (!spec || !spec.hostRef) {
- return null;
+ return null
}
return {
- name: (metadata?.name as string) || "",
- namespace: (metadata?.namespace as string) || "default",
+ name: (metadata?.name as string) || '',
+ namespace: (metadata?.namespace as string) || 'default',
spec,
- };
+ }
} catch (error) {
- console.warn("[K8s] Failed to parse CommunicationChannel:", error);
- return null;
+ console.warn('[K8s] Failed to parse CommunicationChannel:', error)
+ return null
}
}
}
diff --git a/channel-reader/src/progressFormatter.ts b/channel-reader/src/progressFormatter.ts
index 83b3236a2..75fba2bc1 100644
--- a/channel-reader/src/progressFormatter.ts
+++ b/channel-reader/src/progressFormatter.ts
@@ -1,64 +1,64 @@
-import type { ProgressStep } from "./types";
+import type { ProgressStep } from './types'
-const MAX_MESSAGE_LENGTH = 4096;
+const MAX_MESSAGE_LENGTH = 4096
function toolFn(step: ProgressStep): string {
- const sep = step.toolName.indexOf("__");
- if (sep > 0) return step.toolName.substring(sep + 2);
- if (step.displayName !== step.toolName) return step.toolName;
- return "";
+ const sep = step.toolName.indexOf('__')
+ if (sep > 0) return step.toolName.substring(sep + 2)
+ if (step.displayName !== step.toolName) return step.toolName
+ return ''
}
function formatDuration(ms: number): string {
- if (ms < 1000) return `${ms}ms`;
- return `${(ms / 1000).toFixed(1)}s`;
+ if (ms < 1000) return `${ms}ms`
+ return `${(ms / 1000).toFixed(1)}s`
}
function formatStepLine(step: ProgressStep): string {
- const icon = step.state === "completed" ? "✓" : step.state === "running" ? "●" : "✗";
- const name = step.displayName;
- const fn = toolFn(step);
- const label = fn ? `${name} · ${fn}` : name;
+ const icon = step.state === 'completed' ? '✓' : step.state === 'running' ? '●' : '✗'
+ const name = step.displayName
+ const fn = toolFn(step)
+ const label = fn ? `${name} · ${fn}` : name
- if (step.state === "completed" && step.durationMs != null) {
- return `${icon} ${label} ${formatDuration(step.durationMs)}`;
+ if (step.state === 'completed' && step.durationMs != null) {
+ return `${icon} ${label} ${formatDuration(step.durationMs)}`
}
- if (step.state === "running") {
- return `${icon} ${label} running...`;
+ if (step.state === 'running') {
+ return `${icon} ${label} running...`
}
- return `${icon} ${label} ${step.errorSummary || "error"}`;
+ return `${icon} ${label} ${step.errorSummary || 'error'}`
}
export function formatProgressUpdate(steps: ProgressStep[]): string {
- const lines: string[] = ["⏳ Processing your request...", ""];
- let prevIteration: number | undefined;
+ const lines: string[] = ['⏳ Processing your request...', '']
+ let prevIteration: number | undefined
for (const step of steps) {
if (prevIteration !== undefined && step.iteration !== prevIteration) {
- lines.push("── Thinking further... ──");
+ lines.push('── Thinking further... ──')
}
- prevIteration = step.iteration;
- lines.push(formatStepLine(step));
+ prevIteration = step.iteration
+ lines.push(formatStepLine(step))
}
- return lines.join("\n");
+ return lines.join('\n')
}
export function formatFinalMessage(steps: ProgressStep[], response: string): string {
- if (steps.length === 0) return response;
+ if (steps.length === 0) return response
- const errorCount = steps.filter((s) => s.state === "error").length;
- const totalDuration = steps.reduce((sum, s) => sum + (s.durationMs ?? 0), 0);
- const toolNames = [...new Set(steps.map((s) => s.displayName))].join(", ");
- const icon = errorCount > 0 ? "⚠" : "✓";
+ const errorCount = steps.filter(s => s.state === 'error').length
+ const totalDuration = steps.reduce((sum, s) => sum + (s.durationMs ?? 0), 0)
+ const toolNames = [...new Set(steps.map(s => s.displayName))].join(', ')
+ const icon = errorCount > 0 ? '⚠' : '✓'
- const summary = `${icon} ${steps.length} tool${steps.length > 1 ? "s" : ""} used · ${toolNames} · ${formatDuration(totalDuration)}`;
- const full = `${summary}\n\n${response}`;
+ const summary = `${icon} ${steps.length} tool${steps.length > 1 ? 's' : ''} used · ${toolNames} · ${formatDuration(totalDuration)}`
+ const full = `${summary}\n\n${response}`
- if (full.length <= MAX_MESSAGE_LENGTH) return full;
+ if (full.length <= MAX_MESSAGE_LENGTH) return full
if (response.length > MAX_MESSAGE_LENGTH - 4) {
- return response.substring(0, MAX_MESSAGE_LENGTH - 3) + "...";
+ return response.substring(0, MAX_MESSAGE_LENGTH - 3) + '...'
}
- return response;
+ return response
}
diff --git a/channel-reader/test/watcherResync.test.ts b/channel-reader/test/watcherResync.test.ts
index e9211ce63..ba438750b 100644
--- a/channel-reader/test/watcherResync.test.ts
+++ b/channel-reader/test/watcherResync.test.ts
@@ -12,7 +12,6 @@
* The poll-loop tests (section 2) inject a mock watcher via ChannelReader's
* constructor path so no real k8s network call is made.
*/
-
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { CommunicationChannelCRD } from '../src/types'
@@ -62,7 +61,9 @@ describe('CommunicationChannelWatcher.resyncChannels()', () => {
} catch {
// Kubeconfig may not be present in CI — construct a minimal object that
// exercises the resyncChannels logic via prototype injection.
- watcher = Object.create(mod.CommunicationChannelWatcher.prototype) as InstanceType<typeof mod.CommunicationChannelWatcher>
+ watcher = Object.create(mod.CommunicationChannelWatcher.prototype) as InstanceType<
+ typeof mod.CommunicationChannelWatcher
+ >
;(watcher as any).channels = new Map()
;(watcher as any).hostRef = 'test-host'
;(watcher as any).namespace = 'channels'
@@ -74,9 +75,7 @@ describe('CommunicationChannelWatcher.resyncChannels()', () => {
it('calls listChannels() to refresh the in-memory cache', async () => {
const { watcher } = await makeRealWatcher()
- const listChannelsSpy = vi
- .spyOn(watcher, 'listChannels')
- .mockResolvedValue([])
+ const listChannelsSpy = vi.spyOn(watcher, 'listChannels').mockResolvedValue([])
await watcher.resyncChannels()
@@ -155,9 +154,9 @@ describe('CommunicationChannelWatcher.resyncChannels()', () => {
vi.useFakeTimers()
const { mod } = await makeRealWatcher()
- const watcher = Object.create(
- mod.CommunicationChannelWatcher.prototype
- ) as InstanceType<typeof mod.CommunicationChannelWatcher>
+ const watcher = Object.create(mod.CommunicationChannelWatcher.prototype) as InstanceType<
+ typeof mod.CommunicationChannelWatcher
+ >
;(watcher as any).channels = new Map()
;(watcher as any).hostRef = 'test-host'
;(watcher as any).namespace = 'channels'
@@ -166,23 +165,26 @@ describe('CommunicationChannelWatcher.resyncChannels()', () => {
// resyncChannels succeeds; startWatch always rejects (simulates transient API error).
vi.spyOn(watcher, 'resyncChannels').mockResolvedValue(undefined)
const startWatchError = new Error('transient api error')
- const startWatchSpy = vi
- .spyOn(watcher, 'startWatch')
- .mockRejectedValue(startWatchError)
+ const startWatchSpy = vi.spyOn(watcher, 'startWatch').mockRejectedValue(startWatchError)
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
// Replicate the guarded reconnect body from k8sClient.ts to assert it catches
// errors and schedules a retry rather than propagating an unhandled rejection.
let uncaughtError: unknown = undefined
- process.once('unhandledRejection', (reason) => { uncaughtError = reason })
+ process.once('unhandledRejection', reason => {
+ uncaughtError = reason
+ })
const reconnectBody = async () => {
try {
await watcher.resyncChannels()
await watcher.startWatch()
} catch (reconnectErr) {
- console.error('[K8s] Reconnect callback failed, scheduling another reconnect:', reconnectErr)
+ console.error(
+ '[K8s] Reconnect callback failed, scheduling another reconnect:',
+ reconnectErr
+ )
// Schedule another reconnect — mirroring the guarded code in k8sClient.ts.
setTimeout(() => watcher.startWatch(), 5000)
}
diff --git a/channel-reader/vitest.config.ts b/channel-reader/vitest.config.ts
index 37b473f54..8141ade9e 100644
--- a/channel-reader/vitest.config.ts
+++ b/channel-reader/vitest.config.ts
@@ -1,8 +1,8 @@
-import { defineConfig } from "vitest/config";
+import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
- include: ["src/**/*.test.ts", "src/**/__tests__/**/*.ts", "test/**/*.test.ts"],
- exclude: ["dist/**", "node_modules/**"],
+ include: ['src/**/*.test.ts', 'src/**/__tests__/**/*.ts', 'test/**/*.test.ts'],
+ exclude: ['dist/**', 'node_modules/**'],
},
-});
+})
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 51343e789..fe16fe281 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.414",
+ "version": "0.1.415",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.414",
+ "version": "0.1.415",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
"@clerum/llm-providers": "file:../packages/llm-providers",
diff --git a/control-api/package.json b/control-api/package.json
index da46fced8..8325700bf 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.414",
+ "version": "0.1.415",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/http/asyncHandler.ts b/control-api/src/http/asyncHandler.ts
index 461e34b6e..f78c1a484 100644
--- a/control-api/src/http/asyncHandler.ts
+++ b/control-api/src/http/asyncHandler.ts
@@ -1,9 +1,9 @@
-import { NextFunction, Request, Response } from "express";
+import { NextFunction, Request, Response } from 'express'
-export type AsyncHandler = (req: Request, res: Response, next: NextFunction) => Promise<void>;
+export type AsyncHandler = (req: Request, res: Response, next: NextFunction) => Promise<void>
export function asyncHandler(handler: AsyncHandler) {
return (req: Request, res: Response, next: NextFunction) => {
- handler(req, res, next).catch(next);
- };
+ handler(req, res, next).catch(next)
+ }
}
diff --git a/control-api/src/http/contentTypes.ts b/control-api/src/http/contentTypes.ts
index 0b4ac3ad8..7e1f90eab 100644
--- a/control-api/src/http/contentTypes.ts
+++ b/control-api/src/http/contentTypes.ts
@@ -5,10 +5,10 @@
* Falls back to application/octet-stream for unknown extensions.
*/
export const CONTENT_TYPES: Record<string, string> = {
- md: "text/markdown",
- pdf: "application/pdf",
- docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
- xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
- html: "text/html",
- txt: "text/plain",
-};
+ md: 'text/markdown',
+ pdf: 'application/pdf',
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ html: 'text/html',
+ txt: 'text/plain',
+}
diff --git a/control-api/src/http/namespaceAudit.ts b/control-api/src/http/namespaceAudit.ts
index 9dc59a95e..1a0abd592 100644
--- a/control-api/src/http/namespaceAudit.ts
+++ b/control-api/src/http/namespaceAudit.ts
@@ -1,4 +1,4 @@
-import type { Request, Response, NextFunction, RequestHandler } from "express";
+import type { NextFunction, Request, RequestHandler, Response } from 'express'
/**
* Audit and silently strip any namespace injection attempt from a request.
@@ -12,42 +12,41 @@ import type { Request, Response, NextFunction, RequestHandler } from "express";
* @param req - Express request to inspect
* @param configNs - The server-side canonical namespace for this resource
*/
-export function auditNamespaceAttempt(
- req: Request,
- configNs: string,
-): void {
- const body = req.body as
- | { metadata?: { namespace?: unknown }; namespace?: unknown }
- | undefined;
+export function auditNamespaceAttempt(req: Request, configNs: string): void {
+ const body = req.body as { metadata?: { namespace?: unknown }; namespace?: unknown } | undefined
- const source = req.ip ?? req.socket?.remoteAddress ?? "unknown";
+ const source = req.ip ?? req.socket?.remoteAddress ?? 'unknown'
// Detect namespace injection from three vectors
- const vectors: Array<{ vector: string; field?: string; value: unknown }> = [];
+ const vectors: Array<{ vector: string; field?: string; value: unknown }> = []
if (req.query.namespace !== undefined) {
- vectors.push({ vector: "query-param", value: req.query.namespace });
+ vectors.push({ vector: 'query-param', value: req.query.namespace })
}
if (body?.metadata?.namespace !== undefined) {
- vectors.push({ vector: "body-field", field: "metadata.namespace", value: body.metadata.namespace });
+ vectors.push({
+ vector: 'body-field',
+ field: 'metadata.namespace',
+ value: body.metadata.namespace,
+ })
}
if (body?.namespace !== undefined) {
- vectors.push({ vector: "body-field", field: "namespace", value: body.namespace });
+ vectors.push({ vector: 'body-field', field: 'namespace', value: body.namespace })
}
for (const { vector, field, value } of vectors) {
console.warn(
JSON.stringify({
- alert: "SECURITY",
- event: "namespace_injection",
+ alert: 'SECURITY',
+ event: 'namespace_injection',
vector,
...(field && { field }),
path: req.path,
attempted_ns: value,
expected_ns: configNs,
source_ip: source,
- }),
- );
+ })
+ )
}
}
@@ -59,20 +58,16 @@ export function auditNamespaceAttempt(
* expected namespace; this function logs the actual namespace used when it
* differs from the enforced one, for observability completeness.
*/
-export function auditNamespaceFallback(
- path: string,
- enforcedNs: string,
- actualNs: string,
-): void {
+export function auditNamespaceFallback(path: string, enforcedNs: string, actualNs: string): void {
console.info(
JSON.stringify({
- alert: "OBSERVABILITY",
- event: "namespace_fallback",
+ alert: 'OBSERVABILITY',
+ event: 'namespace_fallback',
path,
enforced_ns: enforcedNs,
actual_ns: actualNs,
- }),
- );
+ })
+ )
}
/**
@@ -112,35 +107,33 @@ export function auditNamespaceFallback(
*/
export function enforceNamespace(configNs: string): RequestHandler {
return (req: Request, res: Response, next: NextFunction) => {
- const body = req.body as
- | { metadata?: { namespace?: unknown }; namespace?: unknown }
- | undefined;
+ const body = req.body as { metadata?: { namespace?: unknown }; namespace?: unknown } | undefined
// Check metadata.namespace mismatch — absent and matching are both ok.
// This is the CRD body format; a non-empty mismatching value is rejected
// with 400 so callers learn they must omit the field.
- const metaNs = body?.metadata?.namespace;
- if (metaNs !== undefined && metaNs !== "" && metaNs !== configNs) {
- auditNamespaceAttempt(req, configNs);
+ const metaNs = body?.metadata?.namespace
+ if (metaNs !== undefined && metaNs !== '' && metaNs !== configNs) {
+ auditNamespaceAttempt(req, configNs)
res.status(400).json({
error:
- "namespace is server-determined; omit metadata.namespace from the request body, " +
+ 'namespace is server-determined; omit metadata.namespace from the request body, ' +
`or use the correct value ("${configNs}").`,
- });
- return;
+ })
+ return
}
// Audit any injection vectors (query-param, body fields) and strip namespace
// fields so downstream handlers always use the config value.
// Top-level body.namespace is silently stripped (non-CRD routes — e.g.
// Secret upsert — explicitly overwrite it anyway, so stripping here is safe).
- auditNamespaceAttempt(req, configNs);
- if (req.body && typeof req.body === "object") {
- if (req.body.metadata && typeof req.body.metadata === "object") {
- delete req.body.metadata.namespace;
+ auditNamespaceAttempt(req, configNs)
+ if (req.body && typeof req.body === 'object') {
+ if (req.body.metadata && typeof req.body.metadata === 'object') {
+ delete req.body.metadata.namespace
}
- delete req.body.namespace;
+ delete req.body.namespace
}
- next();
- };
+ next()
+ }
}
diff --git a/control-api/src/http/rfc1123.ts b/control-api/src/http/rfc1123.ts
index 4635fcd0e..424379f67 100644
--- a/control-api/src/http/rfc1123.ts
+++ b/control-api/src/http/rfc1123.ts
@@ -10,13 +10,12 @@
*/
/** DNS label: lowercase alphanumeric + hyphens, 1-63 chars, no leading/trailing hyphens. */
-export const RFC1123_RE = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
+export const RFC1123_RE = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/
/** DNS subdomain: same charset, up to 253 chars. */
-const DNS_SUBDOMAIN_RE = /^[a-z0-9]([a-z0-9-]{0,251}[a-z0-9])?$/;
+const DNS_SUBDOMAIN_RE = /^[a-z0-9]([a-z0-9-]{0,251}[a-z0-9])?$/
/** Validate a K8s resource name as a DNS subdomain (max 253 chars). */
export function isValidDNSSubdomain(name: string): boolean {
- return DNS_SUBDOMAIN_RE.test(name);
+ return DNS_SUBDOMAIN_RE.test(name)
}
-
diff --git a/control-api/src/middleware/policyAuth.ts b/control-api/src/middleware/policyAuth.ts
index 1a9362fc2..b564d8f6f 100644
--- a/control-api/src/middleware/policyAuth.ts
+++ b/control-api/src/middleware/policyAuth.ts
@@ -1,178 +1,178 @@
-import { NextFunction, Request, Response } from "express";
+import { NextFunction, Request, Response } from 'express'
-export type PolicyTokenType = "service" | "user";
+export type PolicyTokenType = 'service' | 'user'
export type PolicyAuthClaims = {
- iss: string;
- aud: string | string[];
- sub: string;
- typ: PolicyTokenType;
- scopes: string[];
- hostRefs?: string[];
- service?: string;
- teamId?: string;
- role?: string;
-};
+ iss: string
+ aud: string | string[]
+ sub: string
+ typ: PolicyTokenType
+ scopes: string[]
+ hostRefs?: string[]
+ service?: string
+ teamId?: string
+ role?: string
+}
export type PolicyAuthedRequest = Request & {
- auth?: PolicyAuthClaims;
-};
+ auth?: PolicyAuthClaims
+}
-export type VerifyPolicyToken = (token: string) => PolicyAuthClaims | null;
+export type VerifyPolicyToken = (token: string) => PolicyAuthClaims | null
export type ProtectedRoutePolicy = {
- requiredScope: string;
- allowedServices?: string[];
- hostParam?: string;
-};
+ requiredScope: string
+ allowedServices?: string[]
+ hostParam?: string
+}
const DEFAULT_ERROR_BODY = {
- unauthorized: { error: "Unauthorized" },
- forbidden: { error: "Forbidden" }
-};
+ unauthorized: { error: 'Unauthorized' },
+ forbidden: { error: 'Forbidden' },
+}
function extractBearerToken(req: Request): string {
- const raw = String(req.headers.authorization || "").trim();
- if (!raw) return "";
+ const raw = String(req.headers.authorization || '').trim()
+ if (!raw) return ''
if (/^bearer\s+/i.test(raw)) {
- return raw.replace(/^bearer\s+/i, "").trim();
+ return raw.replace(/^bearer\s+/i, '').trim()
}
- return "";
+ return ''
}
function extractServiceName(claims: PolicyAuthClaims): string {
- if (claims.service && claims.service.trim()) return claims.service.trim();
- if (claims.sub.startsWith("service:")) {
- return claims.sub.slice("service:".length).trim();
+ if (claims.service && claims.service.trim()) return claims.service.trim()
+ if (claims.sub.startsWith('service:')) {
+ return claims.sub.slice('service:'.length).trim()
}
- return "";
+ return ''
}
export function requireAuth(verifyToken: VerifyPolicyToken, maxTokenLength = 4096) {
return (req: PolicyAuthedRequest, res: Response, next: NextFunction): void => {
- const token = extractBearerToken(req);
+ const token = extractBearerToken(req)
if (!token || token.length > maxTokenLength) {
- res.status(401).json(DEFAULT_ERROR_BODY.unauthorized);
- return;
+ res.status(401).json(DEFAULT_ERROR_BODY.unauthorized)
+ return
}
- const claims = verifyToken(token);
+ const claims = verifyToken(token)
if (!claims) {
- res.status(401).json(DEFAULT_ERROR_BODY.unauthorized);
- return;
+ res.status(401).json(DEFAULT_ERROR_BODY.unauthorized)
+ return
}
- req.auth = claims;
- next();
- };
+ req.auth = claims
+ next()
+ }
}
export function requireScope(scope: string) {
return (req: PolicyAuthedRequest, res: Response, next: NextFunction): void => {
- const auth = req.auth;
+ const auth = req.auth
if (!auth) {
- res.status(401).json(DEFAULT_ERROR_BODY.unauthorized);
- return;
+ res.status(401).json(DEFAULT_ERROR_BODY.unauthorized)
+ return
}
if (!auth.scopes.includes(scope)) {
- res.status(403).json({ error: "Forbidden: missing scope" });
- return;
+ res.status(403).json({ error: 'Forbidden: missing scope' })
+ return
}
- next();
- };
+ next()
+ }
}
export function requireService(service: string | string[]) {
- const allowed = new Set(Array.isArray(service) ? service : [service]);
+ const allowed = new Set(Array.isArray(service) ? service : [service])
return (req: PolicyAuthedRequest, res: Response, next: NextFunction): void => {
- const auth = req.auth;
+ const auth = req.auth
if (!auth) {
- res.status(401).json(DEFAULT_ERROR_BODY.unauthorized);
- return;
+ res.status(401).json(DEFAULT_ERROR_BODY.unauthorized)
+ return
}
- if (auth.typ !== "service") {
- res.status(403).json({ error: "Forbidden: service token required" });
- return;
+ if (auth.typ !== 'service') {
+ res.status(403).json({ error: 'Forbidden: service token required' })
+ return
}
- const serviceName = extractServiceName(auth);
+ const serviceName = extractServiceName(auth)
if (!serviceName || !allowed.has(serviceName)) {
- res.status(403).json({ error: "Forbidden: service not allowed" });
- return;
+ res.status(403).json({ error: 'Forbidden: service not allowed' })
+ return
}
- next();
- };
+ next()
+ }
}
-export function requireHostAccess(hostParam = "host", allowWildcard = true) {
+export function requireHostAccess(hostParam = 'host', allowWildcard = true) {
return (req: PolicyAuthedRequest, res: Response, next: NextFunction): void => {
- const auth = req.auth;
+ const auth = req.auth
if (!auth) {
- res.status(401).json(DEFAULT_ERROR_BODY.unauthorized);
- return;
+ res.status(401).json(DEFAULT_ERROR_BODY.unauthorized)
+ return
}
- const requestedHost = String(req.params?.[hostParam] || req.body?.hostRef || "").trim();
+ const requestedHost = String(req.params?.[hostParam] || req.body?.hostRef || '').trim()
if (!requestedHost) {
- res.status(403).json({ error: "Forbidden: missing host reference" });
- return;
+ res.status(403).json({ error: 'Forbidden: missing host reference' })
+ return
}
- const hostRefs = Array.isArray(auth.hostRefs) ? auth.hostRefs : [];
+ const hostRefs = Array.isArray(auth.hostRefs) ? auth.hostRefs : []
if (hostRefs.includes(requestedHost)) {
- next();
- return;
+ next()
+ return
}
- if (allowWildcard && hostRefs.includes("*")) {
- next();
- return;
+ if (allowWildcard && hostRefs.includes('*')) {
+ next()
+ return
}
- res.status(403).json({ error: "Forbidden: host access denied" });
- };
+ res.status(403).json({ error: 'Forbidden: host access denied' })
+ }
}
export function requireMappedPolicy(getPolicy: (req: Request) => ProtectedRoutePolicy | null) {
return (req: PolicyAuthedRequest, res: Response, next: NextFunction): void => {
- const policy = getPolicy(req);
+ const policy = getPolicy(req)
if (!policy) {
- res.status(403).json({ error: "Forbidden: unmapped protected route" });
- return;
+ res.status(403).json({ error: 'Forbidden: unmapped protected route' })
+ return
}
- const auth = req.auth;
+ const auth = req.auth
if (!auth) {
- res.status(401).json(DEFAULT_ERROR_BODY.unauthorized);
- return;
+ res.status(401).json(DEFAULT_ERROR_BODY.unauthorized)
+ return
}
if (!auth.scopes.includes(policy.requiredScope)) {
- res.status(403).json({ error: "Forbidden: missing scope" });
- return;
+ res.status(403).json({ error: 'Forbidden: missing scope' })
+ return
}
if (policy.allowedServices && policy.allowedServices.length > 0) {
- if (auth.typ !== "service") {
- res.status(403).json({ error: "Forbidden: service token required" });
- return;
+ if (auth.typ !== 'service') {
+ res.status(403).json({ error: 'Forbidden: service token required' })
+ return
}
- const name = extractServiceName(auth);
+ const name = extractServiceName(auth)
if (!name || !policy.allowedServices.includes(name)) {
- res.status(403).json({ error: "Forbidden: service not allowed" });
- return;
+ res.status(403).json({ error: 'Forbidden: service not allowed' })
+ return
}
}
if (policy.hostParam) {
- const requestedHost = String(req.params?.[policy.hostParam] || req.body?.hostRef || "").trim();
- const hostRefs = Array.isArray(auth.hostRefs) ? auth.hostRefs : [];
- const hostAllowed = requestedHost && (hostRefs.includes(requestedHost) || hostRefs.includes("*"));
+ const requestedHost = String(req.params?.[policy.hostParam] || req.body?.hostRef || '').trim()
+ const hostRefs = Array.isArray(auth.hostRefs) ? auth.hostRefs : []
+ const hostAllowed =
+ requestedHost && (hostRefs.includes(requestedHost) || hostRefs.includes('*'))
if (!hostAllowed) {
- res.status(403).json({ error: "Forbidden: host access denied" });
- return;
+ res.status(403).json({ error: 'Forbidden: host access denied' })
+ return
}
}
- next();
- };
+ next()
+ }
}
-
diff --git a/control-api/src/oauth/callback.ts b/control-api/src/oauth/callback.ts
index 634978a9b..51cdcb77e 100644
--- a/control-api/src/oauth/callback.ts
+++ b/control-api/src/oauth/callback.ts
@@ -153,10 +153,7 @@ export async function handleOAuthCallback(
// ─── 3. Read clientId + clientSecret from K8s Secrets ─────────────────
let clientIdSecret: Record<string, string>
try {
- clientIdSecret = await deps.secretReader.read(
- clientDecl.clientIdRef.name,
- recipeNamespace
- )
+ clientIdSecret = await deps.secretReader.read(clientDecl.clientIdRef.name, recipeNamespace)
} catch (err) {
if (err instanceof SecretNotFoundError) {
return { kind: 'secret_missing', secret: clientDecl.clientIdRef.name }
diff --git a/control-api/src/oauth/store.ts b/control-api/src/oauth/store.ts
index c53c1eff0..61779bba9 100644
--- a/control-api/src/oauth/store.ts
+++ b/control-api/src/oauth/store.ts
@@ -272,7 +272,10 @@ export interface UserGrantSummary {
}
/** All of a user's grants across recipes (for the Profile UI "Connected accounts" list). */
-export async function listUserOAuthGrants(db: DbClient, userId: string): Promise<UserGrantSummary[]> {
+export async function listUserOAuthGrants(
+ db: DbClient,
+ userId: string
+): Promise<UserGrantSummary[]> {
const result = await db.query(
`SELECT recipe_namespace, recipe_name, oauth_client_id, provider, background, updated_at
FROM oauth_grants
diff --git a/control-api/src/routes/admin/context.ts b/control-api/src/routes/admin/context.ts
index ec778d87a..92afb6f21 100644
--- a/control-api/src/routes/admin/context.ts
+++ b/control-api/src/routes/admin/context.ts
@@ -1,24 +1,24 @@
-import { Router } from "express";
-import { listTeamsByContext, listUsersByContext } from "../../services/directory/index.js";
+import { Router } from 'express'
+import { listTeamsByContext, listUsersByContext } from '../../services/directory/index.js'
export function createAdminContextRouter(): Router {
- const router = Router();
+ const router = Router()
- router.get("/admin/contexts/:contextId/users", async (req, res, next) => {
+ router.get('/admin/contexts/:contextId/users', async (req, res, next) => {
try {
- res.status(200).json({ items: await listUsersByContext(req.params.contextId) });
+ res.status(200).json({ items: await listUsersByContext(req.params.contextId) })
} catch (error) {
- next(error);
+ next(error)
}
- });
+ })
- router.get("/admin/contexts/:contextId/teams", async (req, res, next) => {
+ router.get('/admin/contexts/:contextId/teams', async (req, res, next) => {
try {
- res.status(200).json({ items: await listTeamsByContext(req.params.contextId) });
+ res.status(200).json({ items: await listTeamsByContext(req.params.contextId) })
} catch (error) {
- next(error);
+ next(error)
}
- });
+ })
- return router;
+ return router
}
diff --git a/control-api/src/routes/admin/hostEnv.ts b/control-api/src/routes/admin/hostEnv.ts
index ab903ed85..29d071fe1 100644
--- a/control-api/src/routes/admin/hostEnv.ts
+++ b/control-api/src/routes/admin/hostEnv.ts
@@ -3,10 +3,7 @@ import { config } from '../../config.js'
import { asyncHandler } from '../../http/asyncHandler.js'
import { enforceNamespace } from '../../http/namespaceAudit.js'
import { K8sGateway } from '../../k8s.js'
-import {
- HostEnvServiceError,
- HostEnvWriteEntry,
-} from '../../services/hostEnvService.js'
+import { HostEnvServiceError, HostEnvWriteEntry } from '../../services/hostEnvService.js'
/**
* Admin endpoints for per-Host operator-managed env vars.
diff --git a/control-api/src/routes/external/directory.ts b/control-api/src/routes/external/directory.ts
index 7d6ba9af7..dd18cd1fe 100644
--- a/control-api/src/routes/external/directory.ts
+++ b/control-api/src/routes/external/directory.ts
@@ -1,23 +1,28 @@
-import { Router } from "express";
-import { requireExternalTeamParamMatch, requireValidExternalSessionToken } from "../../middleware/externalSessionAuth.js";
-import { searchDirectory } from "../../services/directory/index.js";
+import { Router } from 'express'
+import {
+ requireExternalTeamParamMatch,
+ requireValidExternalSessionToken,
+} from '../../middleware/externalSessionAuth.js'
+import { searchDirectory } from '../../services/directory/index.js'
export function createExternalDirectoryRouter(): Router {
- const router = Router();
- router.use("/external/directory", requireValidExternalSessionToken);
+ const router = Router()
+ router.use('/external/directory', requireValidExternalSessionToken)
- router.get("/external/directory/search",
- requireExternalTeamParamMatch(),
+ router.get(
+ '/external/directory/search',
+ requireExternalTeamParamMatch(),
async (req, res, next) => {
- try {
- const teamId = String(req.query.teamId || "").trim();
- const q = String(req.query.q || "").trim();
- if (!teamId) return res.status(400).json({ error: "teamId is required" });
- return res.status(200).json({ items: await searchDirectory(teamId, q) });
- } catch (error) {
- return next(error);
+ try {
+ const teamId = String(req.query.teamId || '').trim()
+ const q = String(req.query.q || '').trim()
+ if (!teamId) return res.status(400).json({ error: 'teamId is required' })
+ return res.status(200).json({ items: await searchDirectory(teamId, q) })
+ } catch (error) {
+ return next(error)
+ }
}
- });
+ )
- return router;
+ return router
}
diff --git a/control-api/src/routes/external/oauthGrants.ts b/control-api/src/routes/external/oauthGrants.ts
index 807cdcedd..d5a284dbe 100644
--- a/control-api/src/routes/external/oauthGrants.ts
+++ b/control-api/src/routes/external/oauthGrants.ts
@@ -1,8 +1,8 @@
import { Router } from 'express'
import { pool } from '../../db.js'
import {
- requireValidExternalSessionToken,
type ExternalAuthedRequest,
+ requireValidExternalSessionToken,
} from '../../middleware/externalSessionAuth.js'
import { deleteOAuthGrant, listUserOAuthGrants } from '../../oauth/store.js'
diff --git a/control-api/src/routes/internal/oauth.ts b/control-api/src/routes/internal/oauth.ts
index 444782d9b..a22e1a5ad 100644
--- a/control-api/src/routes/internal/oauth.ts
+++ b/control-api/src/routes/internal/oauth.ts
@@ -71,7 +71,8 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {
requireInternalService('rpc-proxy'),
async (req, res, next) => {
try {
- const { recipeNs, recipeName, oauthClientId, userId, redirectUri, background } = req.body ?? {}
+ const { recipeNs, recipeName, oauthClientId, userId, redirectUri, background } =
+ req.body ?? {}
if (
typeof recipeNs !== 'string' ||
typeof recipeName !== 'string' ||
diff --git a/control-api/src/routes/recipeOauth.ts b/control-api/src/routes/recipeOauth.ts
index c933c4343..bd74a44b6 100644
--- a/control-api/src/routes/recipeOauth.ts
+++ b/control-api/src/routes/recipeOauth.ts
@@ -198,8 +198,10 @@ export function createRecipeOauthRouter(gateway: K8sGateway): Router {
const oauthClientId = (req.body ?? {}).oauthClientId
const userId = (req.body ?? {}).userId
if (
- typeof oauthClientId !== 'string' || oauthClientId.length === 0 ||
- typeof userId !== 'string' || userId.length === 0
+ typeof oauthClientId !== 'string' ||
+ oauthClientId.length === 0 ||
+ typeof userId !== 'string' ||
+ userId.length === 0
) {
return res.status(400).json({ error: 'invalid_request' })
}
@@ -220,7 +222,14 @@ export function createRecipeOauthRouter(gateway: K8sGateway): Router {
}
const result = await getAccessToken(
- { grantKind: 'user', recipeNamespace, recipeName, userId, oauthClientId, requireBackground: true },
+ {
+ grantKind: 'user',
+ recipeNamespace,
+ recipeName,
+ userId,
+ oauthClientId,
+ requireBackground: true,
+ },
{
db: { query: (text, values) => pool.query(text, values) },
recipeReader,
@@ -232,7 +241,14 @@ export function createRecipeOauthRouter(gateway: K8sGateway): Router {
const audit = (outcome: string) =>
req.log?.info(
- { event: 'recipe_oauth_user_token_issued', recipeNamespace, recipeName, userId, oauthClientId, outcome },
+ {
+ event: 'recipe_oauth_user_token_issued',
+ recipeNamespace,
+ recipeName,
+ userId,
+ oauthClientId,
+ outcome,
+ },
'recipe oauth user token issued'
)
@@ -254,13 +270,17 @@ export function createRecipeOauthRouter(gateway: K8sGateway): Router {
return res.status(400).json({ error: 'unknown_oauth_client' })
case 'unsupported_provider':
audit('unsupported_provider')
- return res.status(400).json({ error: 'unsupported_provider', provider: result.provider })
+ return res
+ .status(400)
+ .json({ error: 'unsupported_provider', provider: result.provider })
case 'secret_missing':
audit('integration_not_configured')
return res.status(503).json(integrationNotConfigured(oauthClientId, result.secret))
case 'refresh_failed':
audit('refresh_failed')
- return res.status(502).json({ error: 'refresh_failed', status: result.status, detail: result.detail })
+ return res
+ .status(502)
+ .json({ error: 'refresh_failed', status: result.status, detail: result.detail })
}
} catch (err) {
next(err)
@@ -314,7 +334,13 @@ export function createRecipeOauthRouter(gateway: K8sGateway): Router {
)
req.log?.info(
- { event: 'recipe_oauth_users_listed', recipeNamespace, recipeName, oauthClientId, count: users.length },
+ {
+ event: 'recipe_oauth_users_listed',
+ recipeNamespace,
+ recipeName,
+ oauthClientId,
+ count: users.length,
+ },
'recipe oauth users listed'
)
return res.status(200).json({ users })
diff --git a/control-api/src/routes/rpc-access/teams.ts b/control-api/src/routes/rpc-access/teams.ts
index c8012a767..bf3c15bcb 100644
--- a/control-api/src/routes/rpc-access/teams.ts
+++ b/control-api/src/routes/rpc-access/teams.ts
@@ -1,25 +1,38 @@
-import { Router } from "express";
-import { requireRpcTokenTeamMatch, requireValidRpcAccessToken } from "../../middleware/rpcAccessAuth.js";
-import { getTeamAgents, getTeamContexts } from "../../services/directory/index.js";
+import { Router } from 'express'
+import {
+ requireRpcTokenTeamMatch,
+ requireValidRpcAccessToken,
+} from '../../middleware/rpcAccessAuth.js'
+import { getTeamAgents, getTeamContexts } from '../../services/directory/index.js'
export function createRpcAccessTeamsRouter(): Router {
- const router = Router();
+ const router = Router()
- router.get("/rpc/access/teams/:teamId/contexts", requireValidRpcAccessToken(), requireRpcTokenTeamMatch(), async (req, res, next) => {
- try {
- res.status(200).json(await getTeamContexts(req.params.teamId));
- } catch (error) {
- next(error);
+ router.get(
+ '/rpc/access/teams/:teamId/contexts',
+ requireValidRpcAccessToken(),
+ requireRpcTokenTeamMatch(),
+ async (req, res, next) => {
+ try {
+ res.status(200).json(await getTeamContexts(req.params.teamId))
+ } catch (error) {
+ next(error)
+ }
}
- });
+ )
- router.get("/rpc/access/teams/:teamId/agents", requireValidRpcAccessToken(), requireRpcTokenTeamMatch(), async (req, res, next) => {
- try {
- res.status(200).json(await getTeamAgents(req.params.teamId));
- } catch (error) {
- next(error);
+ router.get(
+ '/rpc/access/teams/:teamId/agents',
+ requireValidRpcAccessToken(),
+ requireRpcTokenTeamMatch(),
+ async (req, res, next) => {
+ try {
+ res.status(200).json(await getTeamAgents(req.params.teamId))
+ } catch (error) {
+ next(error)
+ }
}
- });
+ )
- return router;
+ return router
}
diff --git a/control-api/src/routes/workflows/shared/auth.ts b/control-api/src/routes/workflows/shared/auth.ts
index 1ddce023e..66cba0fe5 100644
--- a/control-api/src/routes/workflows/shared/auth.ts
+++ b/control-api/src/routes/workflows/shared/auth.ts
@@ -7,8 +7,8 @@ import {
type McpHostControlScope,
verifyMcpHostControlJwt,
} from '../../../utils/auth/mcpHostJwtToken.js'
-import { extractBearerToken } from '../../../utils/extractBearerToken.js'
import { CONTROL_UI_ADMIN_SESSION_COOKIE, readCookie } from '../../../utils/auth/sessionCookies.js'
+import { extractBearerToken } from '../../../utils/extractBearerToken.js'
function getUserSessionToken(req: Request): string {
return String(req.header('x-user-session-token') || '').trim()
diff --git a/control-api/src/services/hostEnvService.ts b/control-api/src/services/hostEnvService.ts
index 26b301f80..13e3adde9 100644
--- a/control-api/src/services/hostEnvService.ts
+++ b/control-api/src/services/hostEnvService.ts
@@ -139,19 +139,14 @@ export class HostEnvService {
* List names + metadata of all per-Host env vars. Never returns values.
*/
async list(hostRef: string): Promise<HostEnvEntry[]> {
- const [cm, secret] = await Promise.all([
- this.readCm(hostRef),
- this.readSecret(hostRef),
- ])
+ const [cm, secret] = await Promise.all([this.readCm(hostRef), this.readSecret(hostRef)])
const entries: HostEnvEntry[] = []
const cmTimestamp =
cm?.metadata?.annotations?.['clerum.io/last-updated'] ||
(cm?.metadata?.creationTimestamp ? String(cm.metadata.creationTimestamp) : undefined)
const secretTimestamp =
secret?.metadata?.annotations?.['clerum.io/last-updated'] ||
- (secret?.metadata?.creationTimestamp
- ? String(secret.metadata.creationTimestamp)
- : undefined)
+ (secret?.metadata?.creationTimestamp ? String(secret.metadata.creationTimestamp) : undefined)
for (const k of Object.keys(cm?.data ?? {})) {
entries.push({ key: k, secret: false, updatedAt: cmTimestamp })
}
diff --git a/control-api/src/services/hostOverviewService.ts b/control-api/src/services/hostOverviewService.ts
index 8699fb176..5cee4225a 100644
--- a/control-api/src/services/hostOverviewService.ts
+++ b/control-api/src/services/hostOverviewService.ts
@@ -1,67 +1,71 @@
-import { HostOverview } from "../types.js";
-import { ResourceService } from "./resourceService.js";
+import { HostOverview } from '../types.js'
+import { ResourceService } from './resourceService.js'
export class HostOverviewService {
- constructor(private readonly resources: ResourceService, private readonly defaultNamespace: string) {}
+ constructor(
+ private readonly resources: ResourceService,
+ private readonly defaultNamespace: string
+ ) {}
async getHostOverview(hostName: string, namespace?: string): Promise<HostOverview> {
- const host = (await this.resources.getResource("hosts", hostName, namespace)) as {
- metadata?: { name?: string };
- spec?: { host?: string; contextRef?: string };
- };
+ const host = (await this.resources.getResource('hosts', hostName, namespace)) as {
+ metadata?: { name?: string }
+ spec?: { host?: string; contextRef?: string }
+ }
- const allChannels = (await this.resources.listResource("communicationchannels", "*")) as Array<{
+ const allChannels = (await this.resources.listResource('communicationchannels', '*')) as Array<{
spec?: {
- hostRef?: string;
- telegram?: Array<{ userIds?: string[] }>;
- email?: Array<{ emails?: string[] }>;
- slack?: Array<{ userNames?: string[] }>;
- };
- }>;
+ hostRef?: string
+ telegram?: Array<{ userIds?: string[] }>
+ email?: Array<{ emails?: string[] }>
+ slack?: Array<{ userNames?: string[] }>
+ }
+ }>
const hostIdCandidates = new Set<string>(
[hostName, host.spec?.host].filter((v): v is string => Boolean(v))
- );
+ )
- const communicationChannels = allChannels.filter((ch) =>
- hostIdCandidates.has(ch.spec?.hostRef || "")
- );
+ const communicationChannels = allChannels.filter(ch =>
+ hostIdCandidates.has(ch.spec?.hostRef || '')
+ )
- let context = null as unknown;
- const contextRef = host.spec?.contextRef;
+ let context = null as unknown
+ const contextRef = host.spec?.contextRef
if (contextRef) {
try {
- context = await this.resources.getResource("contexts", contextRef, this.defaultNamespace);
+ context = await this.resources.getResource('contexts', contextRef, this.defaultNamespace)
} catch {
- const contexts = (await this.resources.listResource("contexts", "*")) as Array<{
- spec?: { contextId?: string };
- }>;
- context = contexts.find((c) => c.spec?.contextId === contextRef) || null;
+ const contexts = (await this.resources.listResource('contexts', '*')) as Array<{
+ spec?: { contextId?: string }
+ }>
+ context = contexts.find(c => c.spec?.contextId === contextRef) || null
}
}
- const allMcpServers = (await this.resources.listResource("mcpservers", "*")) as Array<{
- metadata?: { name?: string };
- }>;
+ const allMcpServers = (await this.resources.listResource('mcpservers', '*')) as Array<{
+ metadata?: { name?: string }
+ }>
const allowed = new Set<string>(
- ((context as { spec?: { mcpServers?: string[] } } | null)?.spec?.mcpServers || [])
- .filter((v): v is string => Boolean(v))
- );
- const mcpServers = allMcpServers.filter((s) => allowed.has(s.metadata?.name || ""));
+ ((context as { spec?: { mcpServers?: string[] } } | null)?.spec?.mcpServers || []).filter(
+ (v): v is string => Boolean(v)
+ )
+ )
+ const mcpServers = allMcpServers.filter(s => allowed.has(s.metadata?.name || ''))
- const telegramUserIds = new Set<string>();
- const emails = new Set<string>();
- const slackUserNames = new Set<string>();
+ const telegramUserIds = new Set<string>()
+ const emails = new Set<string>()
+ const slackUserNames = new Set<string>()
for (const ch of communicationChannels) {
for (const group of ch.spec?.telegram || []) {
- for (const id of group.userIds || []) telegramUserIds.add(id);
+ for (const id of group.userIds || []) telegramUserIds.add(id)
}
for (const group of ch.spec?.email || []) {
- for (const email of group.emails || []) emails.add(email);
+ for (const email of group.emails || []) emails.add(email)
}
for (const group of ch.spec?.slack || []) {
- for (const user of group.userNames || []) slackUserNames.add(user);
+ for (const user of group.userNames || []) slackUserNames.add(user)
}
}
@@ -75,6 +79,6 @@ export class HostOverviewService {
emails: [...emails].sort(),
slackUserNames: [...slackUserNames].sort(),
},
- };
+ }
}
}
diff --git a/control-api/src/utils/auth/googleAuth.ts b/control-api/src/utils/auth/googleAuth.ts
index d13dbe462..b96099625 100644
--- a/control-api/src/utils/auth/googleAuth.ts
+++ b/control-api/src/utils/auth/googleAuth.ts
@@ -1,26 +1,26 @@
-import { OAuth2Client } from "google-auth-library";
-import { config } from "../../config.js";
+import { OAuth2Client } from 'google-auth-library'
+import { config } from '../../config.js'
-const googleClient = new OAuth2Client(config.googleClientId);
+const googleClient = new OAuth2Client(config.googleClientId)
export type VerifiedGoogleProfile = {
- email: string;
- name?: string;
- picture?: string;
-};
+ email: string
+ name?: string
+ picture?: string
+}
export async function verifyGoogleIdToken(idToken: string): Promise<VerifiedGoogleProfile> {
const ticket = await googleClient.verifyIdToken({
idToken,
- audience: config.googleClientId
- });
- const payload = ticket.getPayload();
+ audience: config.googleClientId,
+ })
+ const payload = ticket.getPayload()
if (!payload?.email) {
- throw new Error("Google token has no email");
+ throw new Error('Google token has no email')
}
return {
email: payload.email.toLowerCase(),
name: payload.name,
- picture: payload.picture
- };
+ picture: payload.picture,
+ }
}
diff --git a/control-api/test/adminRecipeOauth.userGrants.test.ts b/control-api/test/adminRecipeOauth.userGrants.test.ts
index bef1ca65e..2c3295edf 100644
--- a/control-api/test/adminRecipeOauth.userGrants.test.ts
+++ b/control-api/test/adminRecipeOauth.userGrants.test.ts
@@ -102,9 +102,7 @@ describe('admin per-user grants', () => {
it('[SEC] GET forces namespace to sandbox-recipes (ignores any path-supplied namespace)', async () => {
storeMock.listUserGrantsForClient.mockResolvedValue([])
- await request(app)
- .get('/admin/recipes/leadforge/oauth/google-gmail/user-grants')
- .expect(200)
+ await request(app).get('/admin/recipes/leadforge/oauth/google-gmail/user-grants').expect(200)
const call = storeMock.listUserGrantsForClient.mock.calls[0] as unknown[]
const key = call[1] as { recipeNamespace: string }
expect(key.recipeNamespace).toBe(SANDBOX_NS)
diff --git a/control-api/test/middleware.policyAuth.test.ts b/control-api/test/middleware.policyAuth.test.ts
index f7dcd796e..babe73753 100644
--- a/control-api/test/middleware.policyAuth.test.ts
+++ b/control-api/test/middleware.policyAuth.test.ts
@@ -1,171 +1,170 @@
-import express from "express";
-import request from "supertest";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it } from 'vitest'
+import express from 'express'
+import request from 'supertest'
import {
PolicyAuthClaims,
requireAuth,
requireHostAccess,
requireMappedPolicy,
requireScope,
- requireService
-} from "../src/middleware/policyAuth.js";
+ requireService,
+} from '../src/middleware/policyAuth.js'
function buildApp(claims: PolicyAuthClaims | null) {
- const app = express();
- app.use(express.json());
+ const app = express()
+ app.use(express.json())
app.get(
- "/secured/hosts/:host",
+ '/secured/hosts/:host',
requireAuth(() => claims),
- requireScope("host:status:read"),
- requireService(["control-api", "rpc-proxy"]),
- requireHostAccess("host"),
+ requireScope('host:status:read'),
+ requireService(['control-api', 'rpc-proxy']),
+ requireHostAccess('host'),
(_req, res) => res.status(200).json({ ok: true })
- );
+ )
app.post(
- "/policy/hosts/:host",
+ '/policy/hosts/:host',
requireAuth(() => claims),
- requireMappedPolicy((req) => {
- if (req.method === "POST" && req.path.startsWith("/policy/hosts/")) {
+ requireMappedPolicy(req => {
+ if (req.method === 'POST' && req.path.startsWith('/policy/hosts/')) {
return {
- requiredScope: "host:policy:write",
- allowedServices: ["control-api"],
- hostParam: "host"
- };
+ requiredScope: 'host:policy:write',
+ allowedServices: ['control-api'],
+ hostParam: 'host',
+ }
}
- return null;
+ return null
}),
(_req, res) => res.status(200).json({ ok: true })
- );
+ )
app.post(
- "/policy/unmapped",
+ '/policy/unmapped',
requireAuth(() => claims),
requireMappedPolicy(() => null),
(_req, res) => res.status(200).json({ ok: true })
- );
+ )
- return app;
+ return app
}
-describe("middleware/policyAuth", () => {
- it("returns 401 when token is missing", async () => {
+describe('middleware/policyAuth', () => {
+ it('returns 401 when token is missing', async () => {
const app = buildApp({
- iss: "control-api",
- aud: "mcp-host",
- sub: "service:rpc-proxy",
- typ: "service",
- scopes: ["host:status:read"],
- hostRefs: ["chatllm"],
- service: "rpc-proxy"
- });
-
- await request(app).get("/secured/hosts/chatllm").expect(401);
- });
-
- it("returns 403 for missing scope", async () => {
+ iss: 'control-api',
+ aud: 'mcp-host',
+ sub: 'service:rpc-proxy',
+ typ: 'service',
+ scopes: ['host:status:read'],
+ hostRefs: ['chatllm'],
+ service: 'rpc-proxy',
+ })
+
+ await request(app).get('/secured/hosts/chatllm').expect(401)
+ })
+
+ it('returns 403 for missing scope', async () => {
const app = buildApp({
- iss: "control-api",
- aud: "mcp-host",
- sub: "service:rpc-proxy",
- typ: "service",
- scopes: ["host:health:read"],
- hostRefs: ["chatllm"],
- service: "rpc-proxy"
- });
+ iss: 'control-api',
+ aud: 'mcp-host',
+ sub: 'service:rpc-proxy',
+ typ: 'service',
+ scopes: ['host:health:read'],
+ hostRefs: ['chatllm'],
+ service: 'rpc-proxy',
+ })
await request(app)
- .get("/secured/hosts/chatllm")
- .set("authorization", "Bearer test-token")
- .expect(403);
- });
+ .get('/secured/hosts/chatllm')
+ .set('authorization', 'Bearer test-token')
+ .expect(403)
+ })
- it("returns 403 for disallowed service identity", async () => {
+ it('returns 403 for disallowed service identity', async () => {
const app = buildApp({
- iss: "control-api",
- aud: "mcp-host",
- sub: "service:channel-reader",
- typ: "service",
- scopes: ["host:status:read"],
- hostRefs: ["chatllm"],
- service: "channel-reader"
- });
+ iss: 'control-api',
+ aud: 'mcp-host',
+ sub: 'service:channel-reader',
+ typ: 'service',
+ scopes: ['host:status:read'],
+ hostRefs: ['chatllm'],
+ service: 'channel-reader',
+ })
await request(app)
- .get("/secured/hosts/chatllm")
- .set("authorization", "Bearer test-token")
- .expect(403);
- });
+ .get('/secured/hosts/chatllm')
+ .set('authorization', 'Bearer test-token')
+ .expect(403)
+ })
- it("returns 403 for host access denied", async () => {
+ it('returns 403 for host access denied', async () => {
const app = buildApp({
- iss: "control-api",
- aud: "mcp-host",
- sub: "service:rpc-proxy",
- typ: "service",
- scopes: ["host:status:read"],
- hostRefs: ["agent2"],
- service: "rpc-proxy"
- });
+ iss: 'control-api',
+ aud: 'mcp-host',
+ sub: 'service:rpc-proxy',
+ typ: 'service',
+ scopes: ['host:status:read'],
+ hostRefs: ['agent2'],
+ service: 'rpc-proxy',
+ })
await request(app)
- .get("/secured/hosts/chatllm")
- .set("authorization", "Bearer test-token")
- .expect(403);
- });
+ .get('/secured/hosts/chatllm')
+ .set('authorization', 'Bearer test-token')
+ .expect(403)
+ })
- it("allows request when auth, scope, service, and host access pass", async () => {
+ it('allows request when auth, scope, service, and host access pass', async () => {
const app = buildApp({
- iss: "control-api",
- aud: "mcp-host",
- sub: "service:rpc-proxy",
- typ: "service",
- scopes: ["host:status:read"],
- hostRefs: ["chatllm"],
- service: "rpc-proxy"
- });
+ iss: 'control-api',
+ aud: 'mcp-host',
+ sub: 'service:rpc-proxy',
+ typ: 'service',
+ scopes: ['host:status:read'],
+ hostRefs: ['chatllm'],
+ service: 'rpc-proxy',
+ })
await request(app)
- .get("/secured/hosts/chatllm")
- .set("authorization", "Bearer test-token")
- .expect(200);
- });
+ .get('/secured/hosts/chatllm')
+ .set('authorization', 'Bearer test-token')
+ .expect(200)
+ })
- it("denies unmapped protected policy route by default", async () => {
+ it('denies unmapped protected policy route by default', async () => {
const app = buildApp({
- iss: "control-api",
- aud: "control-api",
- sub: "service:control-api",
- typ: "service",
- scopes: ["host:policy:write"],
- hostRefs: ["chatllm"],
- service: "control-api"
- });
+ iss: 'control-api',
+ aud: 'control-api',
+ sub: 'service:control-api',
+ typ: 'service',
+ scopes: ['host:policy:write'],
+ hostRefs: ['chatllm'],
+ service: 'control-api',
+ })
await request(app)
- .post("/policy/unmapped")
- .set("authorization", "Bearer test-token")
+ .post('/policy/unmapped')
+ .set('authorization', 'Bearer test-token')
.send({})
- .expect(403);
- });
+ .expect(403)
+ })
- it("allows mapped protected policy route when requirements pass", async () => {
+ it('allows mapped protected policy route when requirements pass', async () => {
const app = buildApp({
- iss: "control-api",
- aud: "control-api",
- sub: "service:control-api",
- typ: "service",
- scopes: ["host:policy:write"],
- hostRefs: ["chatllm"],
- service: "control-api"
- });
+ iss: 'control-api',
+ aud: 'control-api',
+ sub: 'service:control-api',
+ typ: 'service',
+ scopes: ['host:policy:write'],
+ hostRefs: ['chatllm'],
+ service: 'control-api',
+ })
await request(app)
- .post("/policy/hosts/chatllm")
- .set("authorization", "Bearer test-token")
+ .post('/policy/hosts/chatllm')
+ .set('authorization', 'Bearer test-token')
.send({})
- .expect(200);
- });
-});
-
+ .expect(200)
+ })
+})
diff --git a/control-api/test/network.k8s.integration.test.ts b/control-api/test/network.k8s.integration.test.ts
index 8629bbc4f..c03ad92da 100644
--- a/control-api/test/network.k8s.integration.test.ts
+++ b/control-api/test/network.k8s.integration.test.ts
@@ -1,70 +1,71 @@
-import * as k8s from "@kubernetes/client-node";
-import { describe, expect, it, beforeAll } from "vitest";
-import { execSync } from "node:child_process";
-import { resolve } from "node:path";
+import { beforeAll, describe, expect, it } from 'vitest'
+import * as k8s from '@kubernetes/client-node'
+import { execSync } from 'node:child_process'
+import { resolve } from 'node:path'
-const runK8sIntegration = process.env.CONTROL_API_K8S_INTEGRATION === "true";
-const describeK8s = runK8sIntegration ? describe : describe.skip;
+const runK8sIntegration = process.env.CONTROL_API_K8S_INTEGRATION === 'true'
+const describeK8s = runK8sIntegration ? describe : describe.skip
-describeK8s("integration/k8s network boundary validation", () => {
+describeK8s('integration/k8s network boundary validation', () => {
beforeAll(() => {
// Self-bootstrap: apply required NetworkPolicy manifests so the test
// does not depend on a manual pre-deployment step.
- const deployDir = resolve(__dirname, "..", "deploy");
- const hccDeployDir = resolve(__dirname, "..", "..", "host-context-controller", "deploy");
- execSync(`kubectl apply -f ${deployDir}/networkpolicy.yaml`, { stdio: "pipe" });
- execSync(`kubectl apply -f ${hccDeployDir}/networkpolicy.yaml`, { stdio: "pipe" });
- });
+ const deployDir = resolve(__dirname, '..', 'deploy')
+ const hccDeployDir = resolve(__dirname, '..', '..', 'host-context-controller', 'deploy')
+ execSync(`kubectl apply -f ${deployDir}/networkpolicy.yaml`, { stdio: 'pipe' })
+ execSync(`kubectl apply -f ${hccDeployDir}/networkpolicy.yaml`, { stdio: 'pipe' })
+ })
- it("applies expected gateway network policies in cluster", async () => {
- const kc = new k8s.KubeConfig();
- kc.loadFromDefault();
- const networking = kc.makeApiClient(k8s.NetworkingV1Api);
+ it('applies expected gateway network policies in cluster', async () => {
+ const kc = new k8s.KubeConfig()
+ kc.loadFromDefault()
+ const networking = kc.makeApiClient(k8s.NetworkingV1Api)
const controlGatewayPolicy = await networking.readNamespacedNetworkPolicy({
- namespace: "control-plane",
- name: "control-api-rpc-gateway"
- });
- expect(controlGatewayPolicy.spec?.podSelector?.matchLabels?.app).toBe("control-api-rpc-gateway");
- expect(controlGatewayPolicy.spec?.ingress?.length || 0).toBeGreaterThan(0);
- expect(controlGatewayPolicy.spec?.egress?.length || 0).toBeGreaterThan(0);
+ namespace: 'control-plane',
+ name: 'control-api-rpc-gateway',
+ })
+ expect(controlGatewayPolicy.spec?.podSelector?.matchLabels?.app).toBe('control-api-rpc-gateway')
+ expect(controlGatewayPolicy.spec?.ingress?.length || 0).toBeGreaterThan(0)
+ expect(controlGatewayPolicy.spec?.egress?.length || 0).toBeGreaterThan(0)
const hccGatewayPolicy = await networking.readNamespacedNetworkPolicy({
- namespace: "control-plane",
- name: "host-context-controller-api-gateway"
- });
- expect(hccGatewayPolicy.spec?.podSelector?.matchLabels?.app).toBe("host-context-controller-api-gateway");
- expect(hccGatewayPolicy.spec?.ingress?.length || 0).toBeGreaterThan(0);
- });
+ namespace: 'control-plane',
+ name: 'host-context-controller-api-gateway',
+ })
+ expect(hccGatewayPolicy.spec?.podSelector?.matchLabels?.app).toBe(
+ 'host-context-controller-api-gateway'
+ )
+ expect(hccGatewayPolicy.spec?.ingress?.length || 0).toBeGreaterThan(0)
+ })
- it("keeps direct host-context-controller ingress locked to gateway", async () => {
- const kc = new k8s.KubeConfig();
- kc.loadFromDefault();
- const networking = kc.makeApiClient(k8s.NetworkingV1Api);
+ it('keeps direct host-context-controller ingress locked to gateway', async () => {
+ const kc = new k8s.KubeConfig()
+ kc.loadFromDefault()
+ const networking = kc.makeApiClient(k8s.NetworkingV1Api)
const directPolicy = await networking.readNamespacedNetworkPolicy({
- namespace: "control-plane",
- name: "host-context-controller-api-direct"
- });
+ namespace: 'control-plane',
+ name: 'host-context-controller-api-direct',
+ })
- const ingress = directPolicy.spec?.ingress || [];
- expect(ingress.length).toBeGreaterThan(0);
+ const ingress = directPolicy.spec?.ingress || []
+ expect(ingress.length).toBeGreaterThan(0)
// @kubernetes/client-node serializes "from" as "_from" because "from" is
// a JS reserved word. Access the raw property to read ingress sources.
- const rawIngress = ingress[0] as Record<string, unknown>;
+ const rawIngress = ingress[0] as Record<string, unknown>
const fromEntries = ((rawIngress._from ?? rawIngress.from) || []) as Array<{
- namespaceSelector?: { matchLabels?: Record<string, string> };
- podSelector?: { matchLabels?: Record<string, string> };
- }>;
- expect(fromEntries.length).toBeGreaterThan(0);
+ namespaceSelector?: { matchLabels?: Record<string, string> }
+ podSelector?: { matchLabels?: Record<string, string> }
+ }>
+ expect(fromEntries.length).toBeGreaterThan(0)
const hasGatewaySource = fromEntries.some(
- (entry) =>
- entry.namespaceSelector?.matchLabels?.["kubernetes.io/metadata.name"] === "control-plane" &&
- entry.podSelector?.matchLabels?.app === "host-context-controller-api-gateway"
- );
- expect(hasGatewaySource).toBe(true);
- });
-});
-
+ entry =>
+ entry.namespaceSelector?.matchLabels?.['kubernetes.io/metadata.name'] === 'control-plane' &&
+ entry.podSelector?.matchLabels?.app === 'host-context-controller-api-gateway'
+ )
+ expect(hasGatewaySource).toBe(true)
+ })
+})
diff --git a/control-api/test/oauth.authorizeUrl.background.test.ts b/control-api/test/oauth.authorizeUrl.background.test.ts
index 6454cd5a4..fd82e9310 100644
--- a/control-api/test/oauth.authorizeUrl.background.test.ts
+++ b/control-api/test/oauth.authorizeUrl.background.test.ts
@@ -1,13 +1,17 @@
-import { describe, it, expect } from 'vitest'
+import { describe, expect, it } from 'vitest'
import { buildAuthorizeUrl } from '../src/oauth/authorizeUrlHelper.js'
const recipe = {
spec: {
oauthClients: [
- { id: 'google-gmail', provider: 'google',
+ {
+ id: 'google-gmail',
+ provider: 'google',
clientIdRef: { name: 's', key: 'client-id' },
clientSecretRef: { name: 's', key: 'client-secret' },
- scopes: ['https://www.googleapis.com/auth/gmail.readonly'], backgroundAccess: true },
+ scopes: ['https://www.googleapis.com/auth/gmail.readonly'],
+ backgroundAccess: true,
+ },
],
},
}
@@ -20,9 +24,15 @@ const deps = {
describe('buildAuthorizeUrl background', () => {
it('encodes background=true into the signed state', async () => {
const result = await buildAuthorizeUrl(
- { recipeNamespace: 'sandbox-recipes', recipeName: 'leadforge',
- oauthClientId: 'google-gmail', userId: 'user-1', grantKind: 'user',
- redirectUri: 'https://api/cb', background: true },
+ {
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'leadforge',
+ oauthClientId: 'google-gmail',
+ userId: 'user-1',
+ grantKind: 'user',
+ redirectUri: 'https://api/cb',
+ background: true,
+ },
deps as never
)
expect(result.kind).toBe('ok')
@@ -36,10 +46,13 @@ describe('buildAuthorizeUrl background', () => {
const recipeNoBackgroundAccess = {
spec: {
oauthClients: [
- { id: 'google-gmail', provider: 'google',
+ {
+ id: 'google-gmail',
+ provider: 'google',
clientIdRef: { name: 's', key: 'client-id' },
clientSecretRef: { name: 's', key: 'client-secret' },
- scopes: ['https://www.googleapis.com/auth/gmail.readonly'] },
+ scopes: ['https://www.googleapis.com/auth/gmail.readonly'],
+ },
// NOTE: backgroundAccess is intentionally absent
],
},
@@ -53,9 +66,15 @@ const depsNoBackground = {
describe('buildAuthorizeUrl background_access_not_enabled guard', () => {
it('returns background_access_not_enabled for user grantKind with background:true when recipe lacks backgroundAccess', async () => {
const result = await buildAuthorizeUrl(
- { recipeNamespace: 'sandbox-recipes', recipeName: 'leadforge',
- oauthClientId: 'google-gmail', userId: 'user-1', grantKind: 'user',
- redirectUri: 'https://api/cb', background: true },
+ {
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'leadforge',
+ oauthClientId: 'google-gmail',
+ userId: 'user-1',
+ grantKind: 'user',
+ redirectUri: 'https://api/cb',
+ background: true,
+ },
depsNoBackground as never
)
expect(result.kind).toBe('background_access_not_enabled')
@@ -63,9 +82,15 @@ describe('buildAuthorizeUrl background_access_not_enabled guard', () => {
it('allows user grantKind with background:false (or omitted) when recipe lacks backgroundAccess', async () => {
const result = await buildAuthorizeUrl(
- { recipeNamespace: 'sandbox-recipes', recipeName: 'leadforge',
- oauthClientId: 'google-gmail', userId: 'user-1', grantKind: 'user',
- redirectUri: 'https://api/cb', background: false },
+ {
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'leadforge',
+ oauthClientId: 'google-gmail',
+ userId: 'user-1',
+ grantKind: 'user',
+ redirectUri: 'https://api/cb',
+ background: false,
+ },
depsNoBackground as never
)
expect(result.kind).toBe('ok')
diff --git a/control-api/test/oauth.callback.background.test.ts b/control-api/test/oauth.callback.background.test.ts
index 57232299b..f98cea9f9 100644
--- a/control-api/test/oauth.callback.background.test.ts
+++ b/control-api/test/oauth.callback.background.test.ts
@@ -1,16 +1,21 @@
-import { describe, it, expect, vi } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
import { handleOAuthCallback } from '../src/oauth/callback.js'
-import { renderSuccessHtml } from '../src/routes/external/oauthCallback.js'
import { signOAuthState } from '../src/oauth/state.js'
import * as store from '../src/oauth/store.js'
+import { renderSuccessHtml } from '../src/routes/external/oauthCallback.js'
const SECRET = 'x'.repeat(40)
const recipe = {
- spec: { oauthClients: [
- { id: 'google-gmail', provider: 'google',
- clientIdRef: { name: 's', key: 'client-id' },
- clientSecretRef: { name: 's', key: 'client-secret' } },
- ] },
+ spec: {
+ oauthClients: [
+ {
+ id: 'google-gmail',
+ provider: 'google',
+ clientIdRef: { name: 's', key: 'client-id' },
+ clientSecretRef: { name: 's', key: 'client-secret' },
+ },
+ ],
+ },
}
function deps(tokenJson: object) {
return {
@@ -24,10 +29,15 @@ function deps(tokenJson: object) {
}
const input = (background: boolean) => ({
oauthClientId: 'google-gmail',
- code: 'code', redirectUri: 'https://api/cb',
+ code: 'code',
+ redirectUri: 'https://api/cb',
state: signOAuthState(SECRET, {
- recipeNamespace: 'sandbox-recipes', recipeName: 'leadforge', userId: 'user-1',
- oauthClientId: 'google-gmail', grantKind: 'user', background,
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'leadforge',
+ userId: 'user-1',
+ oauthClientId: 'google-gmail',
+ grantKind: 'user',
+ background,
}),
})
@@ -35,14 +45,20 @@ describe('handleOAuthCallback background', () => {
it('sets background=true when consented AND a refresh token is returned', async () => {
const spy = vi.spyOn(store, 'setUserGrantBackground').mockResolvedValue()
vi.spyOn(store, 'upsertOAuthGrant').mockResolvedValue()
- const res = await handleOAuthCallback(input(true), deps({ access_token: 'a', refresh_token: 'r', expires_in: 3600 }))
+ const res = await handleOAuthCallback(
+ input(true),
+ deps({ access_token: 'a', refresh_token: 'r', expires_in: 3600 })
+ )
expect(res.kind).toBe('ok')
if (res.kind === 'ok') {
expect(res.backgroundRequested).toBe(true)
expect(res.backgroundEnabled).toBe(true)
}
- expect(spy).toHaveBeenCalledWith(expect.anything(),
- expect.objectContaining({ userId: 'user-1', oauthClientId: 'google-gmail' }), true)
+ expect(spy).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ userId: 'user-1', oauthClientId: 'google-gmail' }),
+ true
+ )
spy.mockRestore()
})
@@ -62,7 +78,10 @@ describe('handleOAuthCallback background', () => {
it('never sets background for a non-background (plain) connect', async () => {
const spy = vi.spyOn(store, 'setUserGrantBackground').mockResolvedValue()
vi.spyOn(store, 'upsertOAuthGrant').mockResolvedValue()
- const res = await handleOAuthCallback(input(false), deps({ access_token: 'a', refresh_token: 'r' }))
+ const res = await handleOAuthCallback(
+ input(false),
+ deps({ access_token: 'a', refresh_token: 'r' })
+ )
expect(res.kind).toBe('ok')
if (res.kind === 'ok') {
expect(res.backgroundRequested).toBe(false)
diff --git a/control-api/test/oauth.state.background.test.ts b/control-api/test/oauth.state.background.test.ts
index 0937186e6..b6877b3b4 100644
--- a/control-api/test/oauth.state.background.test.ts
+++ b/control-api/test/oauth.state.background.test.ts
@@ -1,5 +1,5 @@
+import { describe, expect, it } from 'vitest'
import { createHmac } from 'node:crypto'
-import { describe, it, expect } from 'vitest'
import { signOAuthState, verifyOAuthState } from '../src/oauth/state.js'
const SECRET = 'x'.repeat(40)
diff --git a/control-api/test/oauth.state.test.ts b/control-api/test/oauth.state.test.ts
index fd3e4021b..a285f3907 100644
--- a/control-api/test/oauth.state.test.ts
+++ b/control-api/test/oauth.state.test.ts
@@ -1,5 +1,5 @@
-import { createHmac } from 'node:crypto'
import { describe, expect, it } from 'vitest'
+import { createHmac } from 'node:crypto'
import { signOAuthState, verifyOAuthState, verifyOAuthStateSignature } from '../src/oauth/state.js'
const SECRET = 'unit-test-state-hmac-secret-32-bytes-pad'
@@ -181,6 +181,8 @@ describe('verifyOAuthStateSignature (signature-only, for the path-less callback)
})
).toString('base64url')
const sig = createHmac('sha256', SECRET).update(`${version}.${expired}`).digest('base64url')
- expect(verifyOAuthStateSignature(SECRET, [version, expired, sig].join('.')).kind).toBe('expired')
+ expect(verifyOAuthStateSignature(SECRET, [version, expired, sig].join('.')).kind).toBe(
+ 'expired'
+ )
})
})
diff --git a/control-api/test/oauth.store.background.test.ts b/control-api/test/oauth.store.background.test.ts
index ad63d9c17..e38a9a906 100644
--- a/control-api/test/oauth.store.background.test.ts
+++ b/control-api/test/oauth.store.background.test.ts
@@ -1,13 +1,16 @@
-import { describe, it, expect } from 'vitest'
+import { describe, expect, it } from 'vitest'
import type { DbClient } from '../src/db.js'
import {
- setUserGrantBackground,
- listBackgroundUserGrants,
getOAuthGrant,
+ listBackgroundUserGrants,
oauthGrantExists,
+ setUserGrantBackground,
} from '../src/oauth/store.js'
-function fakeDb(rows: unknown[] = []): { db: DbClient; calls: { text: string; values: unknown[] }[] } {
+function fakeDb(rows: unknown[] = []): {
+ db: DbClient
+ calls: { text: string; values: unknown[] }[]
+} {
const calls: { text: string; values: unknown[] }[] = []
const db: DbClient = {
query: async (text: string, values: unknown[] = []) => {
@@ -32,7 +35,11 @@ describe('store background', () => {
expect(calls[0].text).toContain('UPDATE oauth_grants')
expect(calls[0].text).toContain("grant_kind = 'user'")
expect(calls[0].values).toEqual([
- 'sandbox-recipes', 'leadforge', 'user-1', 'google-gmail', true,
+ 'sandbox-recipes',
+ 'leadforge',
+ 'user-1',
+ 'google-gmail',
+ true,
])
})
@@ -50,7 +57,11 @@ describe('store background', () => {
it('getOAuthGrant with requireBackground adds the background filter', async () => {
const { db, calls } = fakeDb([])
- await getOAuthGrant(db, Buffer.alloc(32), { ...KEY, grantKind: 'user', requireBackground: true })
+ await getOAuthGrant(db, Buffer.alloc(32), {
+ ...KEY,
+ grantKind: 'user',
+ requireBackground: true,
+ })
expect(calls[0].text).toContain('AND background = true')
})
diff --git a/control-api/test/oauth.store.list.test.ts b/control-api/test/oauth.store.list.test.ts
index 718a1668d..0db80c815 100644
--- a/control-api/test/oauth.store.list.test.ts
+++ b/control-api/test/oauth.store.list.test.ts
@@ -1,6 +1,6 @@
-import { describe, it, expect } from 'vitest'
+import { describe, expect, it } from 'vitest'
import type { DbClient } from '../src/db.js'
-import { listUserOAuthGrants, listUserGrantsForClient } from '../src/oauth/store.js'
+import { listUserGrantsForClient, listUserOAuthGrants } from '../src/oauth/store.js'
function fakeDb(rows: unknown[]): { db: DbClient; calls: { text: string; values: unknown[] }[] } {
const calls: { text: string; values: unknown[] }[] = []
@@ -39,7 +39,9 @@ describe('store list', () => {
})
it('listUserGrantsForClient scopes to recipe+client and returns userId+background', async () => {
- const { db, calls } = fakeDb([{ user_id: 'a', background: true, updated_at: new Date('2026-06-02') }])
+ const { db, calls } = fakeDb([
+ { user_id: 'a', background: true, updated_at: new Date('2026-06-02') },
+ ])
const out = await listUserGrantsForClient(db, {
recipeNamespace: 'sandbox-recipes',
recipeName: 'leadforge',
diff --git a/control-api/test/oauth.tokenHelper.background.test.ts b/control-api/test/oauth.tokenHelper.background.test.ts
index 24a604d5e..b1ca3c0ca 100644
--- a/control-api/test/oauth.tokenHelper.background.test.ts
+++ b/control-api/test/oauth.tokenHelper.background.test.ts
@@ -1,6 +1,6 @@
-import { describe, it, expect, vi } from 'vitest'
-import { getAccessToken } from '../src/oauth/tokenHelper.js'
+import { describe, expect, it, vi } from 'vitest'
import * as store from '../src/oauth/store.js'
+import { getAccessToken } from '../src/oauth/tokenHelper.js'
const deps = {
db: { query: async () => ({ rows: [] }) } as never,
diff --git a/control-api/test/recipeOauth.userToken.test.ts b/control-api/test/recipeOauth.userToken.test.ts
index e13ba6d19..30b90e318 100644
--- a/control-api/test/recipeOauth.userToken.test.ts
+++ b/control-api/test/recipeOauth.userToken.test.ts
@@ -110,7 +110,8 @@ describe('routes/recipe-oauth — POST /recipe-oauth/user-token (SEC-5)', () =>
// [SEC-5] verify the grant lookup was scoped to the correct recipe and userId
const grantQuery = mockPoolQuery.mock.calls.find(
- ([sql]) => typeof sql === 'string' && sql.includes('oauth_grants') && sql.includes('background = true')
+ ([sql]) =>
+ typeof sql === 'string' && sql.includes('oauth_grants') && sql.includes('background = true')
)
expect(grantQuery?.[1]).toEqual([SANDBOX_NS, 'leadforge', 'user-1', 'google-gmail'])
})
@@ -175,8 +176,12 @@ describe('routes/recipe-oauth — POST /recipe-oauth/user-token (SEC-5)', () =>
const res = await request(app)
.post('/api/v1/recipe-oauth/user-token')
.set('Authorization', `Bearer ${brokerToken('leadforge')}`)
- .send({ oauthClientId: 'google-gmail', userId: 'user-1',
- recipeName: 'victim', recipeNamespace: SANDBOX_NS })
+ .send({
+ oauthClientId: 'google-gmail',
+ userId: 'user-1',
+ recipeName: 'victim',
+ recipeNamespace: SANDBOX_NS,
+ })
// Grant lookup was scoped to "leadforge" — no grant seeded → no_grant
expect(res.status).toBe(404)
diff --git a/control-api/test/recipeOauth.users.test.ts b/control-api/test/recipeOauth.users.test.ts
index e7cae7169..31435e798 100644
--- a/control-api/test/recipeOauth.users.test.ts
+++ b/control-api/test/recipeOauth.users.test.ts
@@ -138,8 +138,7 @@ describe('routes/recipe-oauth — GET /recipe-oauth/users (SEC-6)', () => {
})
it('401 without a broker token', async () => {
- const res = await request(app)
- .get('/api/v1/recipe-oauth/users?oauthClientId=google-gmail')
+ const res = await request(app).get('/api/v1/recipe-oauth/users?oauthClientId=google-gmail')
expect(res.status).toBe(401)
})
diff --git a/control-api/test/routes.hostEnv.test.ts b/control-api/test/routes.hostEnv.test.ts
index b4015d5b6..d9c7685e2 100644
--- a/control-api/test/routes.hostEnv.test.ts
+++ b/control-api/test/routes.hostEnv.test.ts
@@ -1,6 +1,6 @@
+import { describe, expect, it, vi } from 'vitest'
import express from 'express'
import request from 'supertest'
-import { describe, expect, it, vi } from 'vitest'
import { createAdminHostEnvRouter } from '../src/routes/admin/hostEnv.js'
import { HostEnvService, HostEnvServiceError } from '../src/services/hostEnvService.js'
@@ -9,8 +9,14 @@ import { HostEnvService, HostEnvServiceError } from '../src/services/hostEnvServ
* to drive HostEnvService without spinning up a real cluster.
*/
function createFakeCoreApi() {
- const cms: Record<string, { metadata: { name: string; resourceVersion: string }; data?: Record<string, string> }> = {}
- const secrets: Record<string, { metadata: { name: string; resourceVersion: string }; data?: Record<string, string> }> = {}
+ const cms: Record<
+ string,
+ { metadata: { name: string; resourceVersion: string }; data?: Record<string, string> }
+ > = {}
+ const secrets: Record<
+ string,
+ { metadata: { name: string; resourceVersion: string }; data?: Record<string, string> }
+ > = {}
return {
state: { cms, secrets },
@@ -35,7 +41,10 @@ function createFakeCoreApi() {
const cur = cms[req.name]
if (!cur) throw { code: 404 }
cms[req.name] = {
- metadata: { name: req.name, resourceVersion: String(Number(cur.metadata.resourceVersion) + 1) },
+ metadata: {
+ name: req.name,
+ resourceVersion: String(Number(cur.metadata.resourceVersion) + 1),
+ },
data: req.body.data,
}
return cms[req.name]
@@ -48,7 +57,11 @@ function createFakeCoreApi() {
}),
createNamespacedSecret: vi.fn(
async (req: {
- body: { metadata: { name: string }; stringData?: Record<string, string>; data?: Record<string, string> }
+ body: {
+ metadata: { name: string }
+ stringData?: Record<string, string>
+ data?: Record<string, string>
+ }
}) => {
const name = req.body.metadata.name
if (secrets[name]) throw { code: 409 }
@@ -65,7 +78,11 @@ function createFakeCoreApi() {
replaceNamespacedSecret: vi.fn(
async (req: {
name: string
- body: { metadata: { name: string }; stringData?: Record<string, string>; data?: Record<string, string> }
+ body: {
+ metadata: { name: string }
+ stringData?: Record<string, string>
+ data?: Record<string, string>
+ }
}) => {
const cur = secrets[req.name]
if (!cur) throw { code: 404 }
@@ -75,7 +92,10 @@ function createFakeCoreApi() {
}
for (const [k, v] of Object.entries(req.body.data ?? {})) encoded[k] = v
secrets[req.name] = {
- metadata: { name: req.name, resourceVersion: String(Number(cur.metadata.resourceVersion) + 1) },
+ metadata: {
+ name: req.name,
+ resourceVersion: String(Number(cur.metadata.resourceVersion) + 1),
+ },
data: encoded,
}
return secrets[req.name]
@@ -86,7 +106,10 @@ function createFakeCoreApi() {
function buildApp() {
const fake = createFakeCoreApi()
- const service = new HostEnvService(fake as unknown as Parameters<typeof HostEnvService>[0], 'mcp-host')
+ const service = new HostEnvService(
+ fake as unknown as Parameters<typeof HostEnvService>[0],
+ 'mcp-host'
+ )
const gateway = { hostEnv: () => service } as never
const app = express()
app.use(express.json())
@@ -107,9 +130,7 @@ describe('routes/hostEnv', () => {
.put('/admin/hosts/trader/env')
.send([{ key: 'FEATURE_FLAG', value: 'on', secret: false }])
.expect(200)
- expect(res.body.keys).toEqual([
- expect.objectContaining({ key: 'FEATURE_FLAG', secret: false }),
- ])
+ expect(res.body.keys).toEqual([expect.objectContaining({ key: 'FEATURE_FLAG', secret: false })])
expect(res.body.showOnce).toEqual({})
expect(fake.state.cms['host-trader-env']).toBeDefined()
expect(fake.state.secrets['host-trader-env-secret']).toBeDefined() // upsert creates both even if empty
diff --git a/control-ui/app/constants/connectorEdit.ts b/control-ui/app/constants/connectorEdit.ts
new file mode 100644
index 000000000..dc60b27a7
--- /dev/null
+++ b/control-ui/app/constants/connectorEdit.ts
@@ -0,0 +1,10 @@
+export const CONNECTOR_EDIT_DEFAULT_TAB = 'egress'
+
+export const CONNECTOR_EDIT_TABS = ['egress', 'credentials'] as const
+
+export type ConnectorEditTab = (typeof CONNECTOR_EDIT_TABS)[number]
+
+export const CONNECTOR_EDIT_TAB_LABELS: Record<ConnectorEditTab, string> = {
+ egress: 'External Egress',
+ credentials: 'Credentials',
+}
diff --git a/control-ui/app/constants/routes.ts b/control-ui/app/constants/routes.ts
index 333dff0a9..20f4480ca 100644
--- a/control-ui/app/constants/routes.ts
+++ b/control-ui/app/constants/routes.ts
@@ -36,6 +36,7 @@ export const CONTROL_ROUTES = {
root: '/connectors',
new: '/connectors/new',
edit: (name: string) => `/connectors/${segment(name)}/edit`,
+ editTab: (name: string, tab: string) => `/connectors/${segment(name)}/edit/${segment(tab)}`,
},
contexts: {
root: '/contexts',
diff --git a/control-ui/app/mcp-servers/[name]/edit/[tab]/page.tsx b/control-ui/app/mcp-servers/[name]/edit/[tab]/page.tsx
new file mode 100644
index 000000000..0b4080d62
--- /dev/null
+++ b/control-ui/app/mcp-servers/[name]/edit/[tab]/page.tsx
@@ -0,0 +1,16 @@
+import { notFound } from 'next/navigation'
+import { CONNECTOR_EDIT_TABS, type ConnectorEditTab } from '@constants/connectorEdit'
+import EditMcpServerPage from '../page'
+
+interface ConnectorEditTabPageProps {
+ params: Promise<{ tab: string }>
+}
+
+export default async function ConnectorEditTabPage({ params }: ConnectorEditTabPageProps) {
+ const { tab } = await params
+ if (!CONNECTOR_EDIT_TABS.includes(tab as ConnectorEditTab)) {
+ notFound()
+ }
+
+ return <EditMcpServerPage />
+}
diff --git a/control-ui/app/mcp-servers/[name]/edit/page.tsx b/control-ui/app/mcp-servers/[name]/edit/page.tsx
index b7ba45e95..da2caa36a 100644
--- a/control-ui/app/mcp-servers/[name]/edit/page.tsx
+++ b/control-ui/app/mcp-servers/[name]/edit/page.tsx
@@ -4,13 +4,17 @@ import React, { useCallback, useEffect, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { AuthGate } from '@components/AuthGate'
import { FormSectionsSkeleton } from '@components/BodyLoadingSkeleton'
-import { CreateFlowPanel } from '@components/CreateFlowPanel'
-import { CreatePageHeader } from '@components/CreatePageHeader'
-import { DashboardLayout } from '@components/DashboardLayout'
+import { DetailPageShell } from '@components/DetailPageShell'
import { EgressEditor } from '@components/EgressEditor'
import { IconCable } from '@components/Sidebar/icons'
import { useToast } from '@components/Toast'
import { UpdateConnectorCredentials } from '@components/UpdateConnectorCredentials'
+import {
+ CONNECTOR_EDIT_DEFAULT_TAB,
+ CONNECTOR_EDIT_TABS,
+ CONNECTOR_EDIT_TAB_LABELS,
+ type ConnectorEditTab,
+} from '@constants/connectorEdit'
import { CONTROL_ROUTES } from '@constants/routes'
import { getMcpServer, updateMcpServer } from '@lib/api'
import type { EgressBinding, EnvSecret, EnvSecretKeyMapping, McpServerResource } from '@lib/api'
@@ -38,12 +42,19 @@ function resolveEnvSecret(spec: Record<string, unknown> | undefined): EnvSecret
return { name: candidate.name, keys }
}
+function parseConnectorEditTab(value: string | string[] | undefined): ConnectorEditTab {
+ const candidate = Array.isArray(value) ? value[0] : value
+ return CONNECTOR_EDIT_TABS.find(tab => tab === candidate) ?? CONNECTOR_EDIT_DEFAULT_TAB
+}
+
export default function EditMcpServerPage() {
const router = useRouter()
- const params = useParams<{ name: string }>()
+ const params = useParams<{ name: string; tab?: string | string[] }>()
const name = decodeURIComponent(params?.name ?? '')
const { showToast } = useToast()
+ const activeTab = parseConnectorEditTab(params?.tab)
+
const [server, setServer] = useState<McpServerResource | null>(null)
const [loading, setLoading] = useState(true)
const [loadError, setLoadError] = useState('')
@@ -56,6 +67,14 @@ export default function EditMcpServerPage() {
router.push(CONTROL_ROUTES.connectors.root)
}
+ function selectTab(next: ConnectorEditTab) {
+ if (next === CONNECTOR_EDIT_DEFAULT_TAB) {
+ router.replace(CONTROL_ROUTES.connectors.edit(name))
+ } else {
+ router.replace(CONTROL_ROUTES.connectors.editTab(name, next))
+ }
+ }
+
const handleEgressChange = useCallback(
(nextBindings: EgressBinding[] | undefined, nextStatus: EgressEditorStatus) => {
setEgressBindings(nextBindings)
@@ -110,91 +129,106 @@ export default function EditMcpServerPage() {
}
}
+ const envSecret = server?.spec
+ ? resolveEnvSecret(server.spec as Record<string, unknown>)
+ : undefined
+
return (
<AuthGate>
- <DashboardLayout isDetailPage>
- <CreateFlowPanel
- header={
- <CreatePageHeader
- icon={<IconCable />}
- title={`Edit Connector: ${name}`}
- subtitle="Update explicit external egress for this connector."
- backLabel="Back to connectors"
- onBack={backToList}
- />
- }
- >
- {loading ? (
- <FormSectionsSkeleton
- className="cu-connector-edit-form"
- label="Connector"
- primaryActionLabel="Save egress"
- sections={3}
- />
- ) : loadError ? (
- <div className="cu-connector-edit-form">
- <div className="cu-banner cu-banner--error" role="alert">
- {loadError}
- </div>
+ <DetailPageShell<ConnectorEditTab>
+ activeTab={activeTab}
+ backLabel="Back to connectors"
+ icon={<IconCable />}
+ onBack={backToList}
+ onTabChange={selectTab}
+ subtitle="Update external egress and rotate credentials for this connector."
+ tabAriaLabel="Connector edit sections"
+ tabClassName="cu-tabs--compact"
+ tabs={CONNECTOR_EDIT_TABS.map(tab => ({
+ value: tab,
+ label: CONNECTOR_EDIT_TAB_LABELS[tab],
+ href:
+ tab === CONNECTOR_EDIT_DEFAULT_TAB
+ ? CONTROL_ROUTES.connectors.edit(name)
+ : CONTROL_ROUTES.connectors.editTab(name, tab),
+ }))}
+ title={`Edit Connector: ${name}`}
+ error={loadError || undefined}
+ >
+ {loading ? (
+ activeTab === 'credentials' ? (
+ <div
+ role="status"
+ aria-busy="true"
+ aria-label="Loading connector credentials"
+ className="cu-body-loading-skeleton"
+ >
+ <section className="cu-body-loading-skeleton__section">
+ <span className="cu-skeleton cu-body-loading-skeleton__heading" />
+ <span className="cu-skeleton cu-body-loading-skeleton__line" />
+ <div className="cu-body-loading-skeleton__fields">
+ <span className="cu-skeleton cu-body-loading-skeleton__field" />
+ <span className="cu-skeleton cu-body-loading-skeleton__field" />
+ </div>
+ </section>
</div>
- ) : server ? (
- <div className="cu-connector-edit-form">
- <form className="cu-create-content cu-connector-edit-content" onSubmit={handleSave}>
- <div className="cu-connector-edit-meta">
- <div>
- <strong>Image:</strong>{' '}
- <code>{typeof server.spec?.image === 'string' ? server.spec.image : '-'}</code>
- </div>
- <div>
- <strong>Context:</strong>{' '}
- <code>
- {typeof server.spec?.contextRef === 'string' ? server.spec.contextRef : '-'}
- </code>
- </div>
+ ) : (
+ <FormSectionsSkeleton label="Connector" primaryActionLabel="Save egress" sections={2} />
+ )
+ ) : server ? (
+ activeTab === 'credentials' ? (
+ <UpdateConnectorCredentials serverName={name} envSecret={envSecret} />
+ ) : (
+ <form className="cu-connector-edit-content" onSubmit={handleSave}>
+ <div className="cu-connector-edit-meta">
+ <div>
+ <strong>Image:</strong>{' '}
+ <code>{typeof server.spec?.image === 'string' ? server.spec.image : '-'}</code>
</div>
-
- <EgressEditor
- allowCidr
- key={`${name}-${JSON.stringify(server.spec?.egressBindings ?? [])}`}
- initialBindings={server.spec?.egressBindings as EgressBinding[] | undefined}
- onChange={handleEgressChange}
- title="External Egress"
- description="Adjust only the external egress contract. Other connector settings are preserved."
- />
-
- {saveError ? (
- <div className="cu-banner cu-banner--error" role="alert">
- {saveError}
- </div>
- ) : null}
-
- <div className="cu-create-actions">
- <button
- type="button"
- className="cu-btn cu-btn--ghost"
- disabled={saving}
- onClick={backToList}
- >
- Cancel
- </button>
- <button
- type="submit"
- className="cu-btn cu-btn--primary"
- disabled={saving || Boolean(egressStatus?.errors.length)}
- >
- {saving ? 'Saving...' : 'Save egress'}
- </button>
+ <div>
+ <strong>Context:</strong>{' '}
+ <code>
+ {typeof server.spec?.contextRef === 'string' ? server.spec.contextRef : '-'}
+ </code>
</div>
- </form>
+ </div>
- <UpdateConnectorCredentials
- serverName={name}
- envSecret={resolveEnvSecret(server.spec as Record<string, unknown> | undefined)}
+ <EgressEditor
+ allowCidr
+ key={`${name}-${JSON.stringify(server.spec?.egressBindings ?? [])}`}
+ initialBindings={server.spec?.egressBindings as EgressBinding[] | undefined}
+ onChange={handleEgressChange}
+ title="External Egress"
+ description="Adjust only the external egress contract. Other connector settings are preserved."
/>
- </div>
- ) : null}
- </CreateFlowPanel>
- </DashboardLayout>
+
+ {saveError ? (
+ <div className="cu-banner cu-banner--error" role="alert">
+ {saveError}
+ </div>
+ ) : null}
+
+ <div className="cu-create-actions">
+ <button
+ type="button"
+ className="cu-btn cu-btn--ghost"
+ disabled={saving}
+ onClick={backToList}
+ >
+ Cancel
+ </button>
+ <button
+ type="submit"
+ className="cu-btn cu-btn--primary"
+ disabled={saving || Boolean(egressStatus?.errors.length)}
+ >
+ {saving ? 'Saving...' : 'Save egress'}
+ </button>
+ </div>
+ </form>
+ )
+ ) : null}
+ </DetailPageShell>
</AuthGate>
)
}
diff --git a/control-ui/components/CreateApiKeyModal.tsx b/control-ui/components/CreateApiKeyModal.tsx
index 00a9242f6..d3bf060ad 100644
--- a/control-ui/components/CreateApiKeyModal.tsx
+++ b/control-ui/components/CreateApiKeyModal.tsx
@@ -1,9 +1,18 @@
// control-ui/components/CreateApiKeyModal.tsx
'use client'
+
import { useEffect, useMemo, useRef, useState } from 'react'
import type { CreateRegistryApiKeyInput } from '../lib/api'
import { Button, CheckboxField, Field, TextInput } from './ui'
+// control-ui/components/CreateApiKeyModal.tsx
+
+// control-ui/components/CreateApiKeyModal.tsx
+
+// control-ui/components/CreateApiKeyModal.tsx
+
+// control-ui/components/CreateApiKeyModal.tsx
+
const SCOPES: { id: string; label: string; help: string; danger?: boolean }[] = [
{ id: 'registry:read', label: 'read', help: 'View org entries' },
{ id: 'registry:publish', label: 'publish', help: 'Publish new versions to @org/*' },
diff --git a/control-ui/components/RecipeIntegrationsPanel/index.tsx b/control-ui/components/RecipeIntegrationsPanel/index.tsx
index 7191b8b73..1d1e06dd9 100644
--- a/control-ui/components/RecipeIntegrationsPanel/index.tsx
+++ b/control-ui/components/RecipeIntegrationsPanel/index.tsx
@@ -417,7 +417,9 @@ export function RecipeIntegrationsPanel({ recipe }: { recipe: WorkflowRecipeReso
aria-label="Refresh user grants"
>
<IconRefresh
- className={ugState.loadState === 'loading' ? 'cu-spin' : undefined}
+ className={
+ ugState.loadState === 'loading' ? 'cu-spin' : undefined
+ }
width={14}
height={14}
/>
diff --git a/control-ui/components/RegistryCatalog.tsx b/control-ui/components/RegistryCatalog.tsx
index 6038ccefe..ee4819036 100644
--- a/control-ui/components/RegistryCatalog.tsx
+++ b/control-ui/components/RegistryCatalog.tsx
@@ -25,16 +25,31 @@ import { useRegistryCapability } from '../lib/hooks/useRegistryCapability'
import { trustBgColor, trustColor } from '../lib/trustLevel'
type MarketplaceTab = 'connectors' | 'plugins'
+type CatalogSortKey = 'name' | 'version'
+type SortDirection = 'asc' | 'desc'
const REGISTRY_COLUMNS: TableHeaderColumn[] = [
{ key: 'expand', ariaLabel: 'Expand Marketplace entry' },
{ key: 'name', label: 'Name' },
{ key: 'version', label: 'Version' },
- { key: 'visibility', label: 'Visibility' },
{ key: 'install', align: 'right', ariaLabel: 'Installation' },
{ key: 'actions', align: 'right', ariaLabel: 'Edit or remove' },
]
+function compareVersions(left: string, right: string): number {
+ const leftParts = left.split('.')
+ const rightParts = right.split('.')
+ for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) {
+ const leftPart = Number.parseInt(leftParts[index] ?? '0', 10)
+ const rightPart = Number.parseInt(rightParts[index] ?? '0', 10)
+ if (Number.isNaN(leftPart) || Number.isNaN(rightPart)) {
+ return left.localeCompare(right, undefined, { numeric: true, sensitivity: 'base' })
+ }
+ if (leftPart !== rightPart) return leftPart - rightPart
+ }
+ return left.localeCompare(right, undefined, { numeric: true, sensitivity: 'base' })
+}
+
export default function RegistryCatalog() {
const pathname = usePathname()
const router = useRouter()
@@ -53,6 +68,8 @@ export default function RegistryCatalog() {
const [installError, setInstallError] = useState('')
const [search, setSearch] = useState('')
const [categoryFilter, setCategoryFilter] = useState('all')
+ const [sortKey, setSortKey] = useState<CatalogSortKey | null>(null)
+ const [sortDirection, setSortDirection] = useState<SortDirection>('asc')
const [expandedKeys, setExpandedKeys] = useState<Set<string>>(new Set())
const [removeTarget, setRemoveTarget] = useState<RegistryEntry | null>(null)
const [removing, setRemoving] = useState(false)
@@ -69,7 +86,14 @@ export default function RegistryCatalog() {
const connectionState = capability?.connectionState ?? null
// Curators administer the shared catalog, so they keep inline edit/remove;
// everyone else manages their own entries from the ownership area (§5.4).
- const columns = isCurator ? REGISTRY_COLUMNS : REGISTRY_COLUMNS.filter(c => c.key !== 'actions')
+ const columns = (
+ isCurator ? REGISTRY_COLUMNS : REGISTRY_COLUMNS.filter(c => c.key !== 'actions')
+ ).map(column => {
+ if (column.key === 'name' || column.key === 'version') {
+ return { ...column, label: renderSortHeader(column.key, column.label as string) }
+ }
+ return column
+ })
useEffect(() => {
void loadData()
@@ -141,7 +165,8 @@ export default function RegistryCatalog() {
[activeEntryType, entries]
)
const filtered = useMemo(() => {
- return tabEntries.filter(entry => {
+ const visibleEntries = tabEntries.filter(entry => {
+ if (entry.visibility === 'private') return false
if (categoryFilter !== 'all' && entry.category !== categoryFilter) return false
if (!search) return true
const query = search.toLowerCase()
@@ -151,10 +176,52 @@ export default function RegistryCatalog() {
entry.tags.some(tag => tag.toLowerCase().includes(query))
)
})
- }, [categoryFilter, search, tabEntries])
+ if (!sortKey) return visibleEntries
+
+ const direction = sortDirection === 'asc' ? 1 : -1
+ return [...visibleEntries].sort((left, right) => {
+ const comparison =
+ sortKey === 'name'
+ ? left.name.localeCompare(right.name, undefined, { sensitivity: 'base' })
+ : compareVersions(left.version, right.version)
+ return comparison * direction
+ })
+ }, [categoryFilter, search, sortDirection, sortKey, tabEntries])
const isInitialLoad = loading && entries.length === 0
+ function toggleSort(key: CatalogSortKey) {
+ if (sortKey === key) {
+ setSortDirection(direction => (direction === 'asc' ? 'desc' : 'asc'))
+ return
+ }
+ setSortKey(key)
+ setSortDirection(key === 'version' ? 'desc' : 'asc')
+ }
+
+ function renderSortHeader(key: CatalogSortKey, label: string) {
+ const isActive = sortKey === key
+ const indicator = isActive ? (sortDirection === 'asc' ? '↑' : '↓') : ''
+ const nextDirection = isActive
+ ? sortDirection === 'asc'
+ ? 'descending'
+ : 'ascending'
+ : key === 'version'
+ ? 'descending'
+ : 'ascending'
+ return (
+ <button
+ type="button"
+ className={`cu-link cu-link--sm cu-table__sort-link${isActive ? ' is-active' : ''}`}
+ onClick={() => toggleSort(key)}
+ aria-label={`Sort by ${label.toLowerCase()} ${nextDirection}`}
+ aria-pressed={isActive}
+ >
+ {label} {indicator}
+ </button>
+ )
+ }
+
function isEntryInstalled(entry: RegistryEntry): boolean {
if (entry.entry_type === 'mcp-server') {
return (
@@ -397,17 +464,6 @@ export default function RegistryCatalog() {
) : null}
</td>
<td className="cu-code-text">{entry.version}</td>
- <td>
- {entry.visibility ? (
- <span
- className={`cu-registry-chip cu-registry-chip--visibility-${entry.visibility}`}
- >
- {entry.visibility === 'public' ? 'Public' : 'Private'}
- </span>
- ) : (
- <span className="cu-muted">—</span>
- )}
- </td>
<td
className="cu-table__cell-actions cu-marketplace-action-cell"
onClick={event => event.stopPropagation()}
diff --git a/control-ui/components/RegistryInstallForm/index.tsx b/control-ui/components/RegistryInstallForm/index.tsx
index 17a9606f6..ddb3a44d4 100644
--- a/control-ui/components/RegistryInstallForm/index.tsx
+++ b/control-ui/components/RegistryInstallForm/index.tsx
@@ -278,95 +278,97 @@ export function RegistryInstallForm({ entry, onCancel, onInstalled }: RegistryIn
<details className="cu-registry-install-configuration">
<summary>Configuration</summary>
<div className="cu-registry-install-configuration__body">
- <div className="cu-field cu-field--compact">
- <label htmlFor="ri-name">Server name</label>
- <input
- id="ri-name"
- className="cu-input"
- value={serverName}
- onChange={event =>
- setServerName(event.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))
- }
- placeholder="my-mcp-server"
- />
- {serverName && !nameValid ? (
- <p className="cu-field__error">
- Must be a valid K8s name (lowercase, alphanumeric, hyphens, max 63 chars).
- </p>
- ) : null}
- </div>
-
- <div className="cu-field cu-field--compact">
- <label htmlFor="ri-context">Context</label>
- <select
- id="ri-context"
- className="cu-input"
- value={contextRef}
- onChange={event => setContextRef(event.target.value)}
- >
- <option value="">Select a context...</option>
- {contexts.map(context => (
- <option key={context.name} value={context.name}>
- {context.name}
- </option>
- ))}
- </select>
- </div>
-
- {credHasKeys ? (
- <fieldset className="cu-form-section">
- <legend className="cu-section-title">
- Credentials ({credSchema!.authType}
- {credRequired ? '' : ' - optional'})
- </legend>
- {credSchema!.keys.map(key => (
- <div className="cu-field cu-field--compact" key={key.name}>
- <label htmlFor={`ri-cred-${key.name}`}>{key.label}</label>
- <input
- id={`ri-cred-${key.name}`}
- className="cu-input"
- type={
- key.kind === 'api-key' || key.kind === 'password' ? 'password' : 'text'
- }
- value={credValues[key.name] ?? ''}
- onChange={event =>
- setCredValues(previous => ({
- ...previous,
- [key.name]: event.target.value,
- }))
- }
- onPaste={event => pasteCredentialValue(key.name, event)}
- autoComplete="new-password"
- placeholder={key.description}
- />
- </div>
- ))}
- {credRequired ? (
- <div
- className={`cu-banner ${credStarted && !credComplete ? 'cu-banner--error' : 'cu-banner--info'}`}
- >
- {credStarted && !credComplete
- ? `Complete all credential fields or clear them all to install pending. Missing: ${missingCredentialKeys.join(', ')}.`
- : 'Leave all credential fields empty to install now and add this connector secret later from Secrets, or fill every field to create it during install.'}
- </div>
+ <div className="cu-field cu-field--compact">
+ <label htmlFor="ri-name">Server name</label>
+ <input
+ id="ri-name"
+ className="cu-input"
+ value={serverName}
+ onChange={event =>
+ setServerName(event.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))
+ }
+ placeholder="my-mcp-server"
+ />
+ {serverName && !nameValid ? (
+ <p className="cu-field__error">
+ Must be a valid K8s name (lowercase, alphanumeric, hyphens, max 63 chars).
+ </p>
) : null}
- </fieldset>
- ) : null}
- <EgressEditor
- allowCidr
- description="Review and adjust the egress contract that will be installed from this Marketplace entry. The final CRD is created from this selection, not from the Marketplace warning alone."
- initialBindings={registryInitialEgressBindings}
- key={`${entry.name}-${entry.version}-${JSON.stringify(registryInitialEgressBindings ?? [])}`}
- onChange={(nextBindings, status) => {
- setEgressBindings(nextBindings)
- setEgressStatus(status)
- }}
- />
- {remoteRequiresEgress && egressStatus?.mode === 'none' ? (
- <div className="cu-banner cu-banner--error" role="alert">
- Remote connectors must keep exact-host egress to the selected vendor endpoint.
</div>
- ) : null}
+
+ <div className="cu-field cu-field--compact">
+ <label htmlFor="ri-context">Context</label>
+ <select
+ id="ri-context"
+ className="cu-input"
+ value={contextRef}
+ onChange={event => setContextRef(event.target.value)}
+ >
+ <option value="">Select a context...</option>
+ {contexts.map(context => (
+ <option key={context.name} value={context.name}>
+ {context.name}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {credHasKeys ? (
+ <fieldset className="cu-form-section">
+ <legend className="cu-section-title">
+ Credentials ({credSchema!.authType}
+ {credRequired ? '' : ' - optional'})
+ </legend>
+ {credSchema!.keys.map(key => (
+ <div className="cu-field cu-field--compact" key={key.name}>
+ <label htmlFor={`ri-cred-${key.name}`}>{key.label}</label>
+ <input
+ id={`ri-cred-${key.name}`}
+ className="cu-input"
+ type={
+ key.kind === 'api-key' || key.kind === 'password'
+ ? 'password'
+ : 'text'
+ }
+ value={credValues[key.name] ?? ''}
+ onChange={event =>
+ setCredValues(previous => ({
+ ...previous,
+ [key.name]: event.target.value,
+ }))
+ }
+ onPaste={event => pasteCredentialValue(key.name, event)}
+ autoComplete="new-password"
+ placeholder={key.description}
+ />
+ </div>
+ ))}
+ {credRequired ? (
+ <div
+ className={`cu-banner ${credStarted && !credComplete ? 'cu-banner--error' : 'cu-banner--info'}`}
+ >
+ {credStarted && !credComplete
+ ? `Complete all credential fields or clear them all to install pending. Missing: ${missingCredentialKeys.join(', ')}.`
+ : 'Leave all credential fields empty to install now and add this connector secret later from Secrets, or fill every field to create it during install.'}
+ </div>
+ ) : null}
+ </fieldset>
+ ) : null}
+ <EgressEditor
+ allowCidr
+ description="Review and adjust the egress contract that will be installed from this Marketplace entry. The final CRD is created from this selection, not from the Marketplace warning alone."
+ initialBindings={registryInitialEgressBindings}
+ key={`${entry.name}-${entry.version}-${JSON.stringify(registryInitialEgressBindings ?? [])}`}
+ onChange={(nextBindings, status) => {
+ setEgressBindings(nextBindings)
+ setEgressStatus(status)
+ }}
+ />
+ {remoteRequiresEgress && egressStatus?.mode === 'none' ? (
+ <div className="cu-banner cu-banner--error" role="alert">
+ Remote connectors must keep exact-host egress to the selected vendor endpoint.
+ </div>
+ ) : null}
</div>
</details>
) : null}
diff --git a/control-ui/components/__tests__/McpServerTable.test.tsx b/control-ui/components/__tests__/McpServerTable.test.tsx
index fcf0e6598..7356714d3 100644
--- a/control-ui/components/__tests__/McpServerTable.test.tsx
+++ b/control-ui/components/__tests__/McpServerTable.test.tsx
@@ -20,6 +20,7 @@ function makeItem(overrides: {
image?: string
contextRef?: string
transportType?: 'sse' | 'streamableHttp' | 'stdio'
+ enabled?: boolean
conditions?: McpServerCondition[] | undefined
hasStatus?: boolean
}) {
@@ -28,6 +29,7 @@ function makeItem(overrides: {
spec: {
image: string
contextRef: string
+ enabled?: boolean
transport: { type: 'sse' | 'streamableHttp' | 'stdio'; url: string }
}
status?: { conditions?: McpServerCondition[] }
@@ -39,6 +41,7 @@ function makeItem(overrides: {
spec: {
image: overrides.image ?? 'ghcr.io/example/mcp:1.0',
contextRef: overrides.contextRef ?? 'context1',
+ enabled: overrides.enabled,
transport: {
type: overrides.transportType ?? 'streamableHttp',
url: 'http://brave-search.mcp-server.svc.cluster.local:3000/mcp',
@@ -138,6 +141,59 @@ describe('McpServerTable — search filter by condition text', () => {
})
})
+describe('McpServerTable — column sorting', () => {
+ it('sorts connectors by name, enabled state, and status from their headers', () => {
+ const items = [
+ makeItem({
+ name: 'zebra-server',
+ enabled: true,
+ conditions: [{ type: 'Ready', status: 'True' }],
+ }),
+ makeItem({ name: 'alpha-server', enabled: false, hasStatus: false }),
+ makeItem({
+ name: 'bravo-server',
+ enabled: true,
+ conditions: [{ type: 'SomeOther', status: 'Unknown' }],
+ }),
+ makeItem({
+ name: 'charlie-server',
+ enabled: false,
+ conditions: [{ type: 'SecretResolved', status: 'False' }],
+ }),
+ ]
+ render(<McpServerTable items={items} />)
+
+ const listedNames = () =>
+ Array.from(document.querySelectorAll('.cu-connectors-table .cu-expandable-row__name')).map(
+ element => element.textContent
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'Sort by name ascending' }))
+ expect(listedNames()).toEqual([
+ 'alpha-server',
+ 'bravo-server',
+ 'charlie-server',
+ 'zebra-server',
+ ])
+
+ fireEvent.click(screen.getByRole('button', { name: 'Sort by enabled ascending' }))
+ expect(listedNames()).toEqual([
+ 'alpha-server',
+ 'charlie-server',
+ 'zebra-server',
+ 'bravo-server',
+ ])
+
+ fireEvent.click(screen.getByRole('button', { name: 'Sort by status ascending' }))
+ expect(listedNames()).toEqual([
+ 'charlie-server',
+ 'bravo-server',
+ 'zebra-server',
+ 'alpha-server',
+ ])
+ })
+})
+
describe('McpServerTable — connector access summaries', () => {
it('exposes expandable rows as named buttons with their current state', () => {
const items = [makeItem({ name: 'airtable-server' })]
diff --git a/control-ui/components/__tests__/RecipeIntegrationsPanel.userGrants.test.tsx b/control-ui/components/__tests__/RecipeIntegrationsPanel.userGrants.test.tsx
index 88b91a899..e0d4a9e2a 100644
--- a/control-ui/components/__tests__/RecipeIntegrationsPanel.userGrants.test.tsx
+++ b/control-ui/components/__tests__/RecipeIntegrationsPanel.userGrants.test.tsx
@@ -10,6 +10,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { WorkflowRecipeResource } from '../../lib/api'
+import { RecipeIntegrationsPanel } from '../RecipeIntegrationsPanel'
import { ToastProvider } from '../Toast'
// ── Mock declarations ────────────────────────────────────────────────────────
@@ -50,8 +51,6 @@ vi.mock('../icons', () => ({
IconRefresh: () => <span data-testid="icon-refresh" />,
}))
-import { RecipeIntegrationsPanel } from '../RecipeIntegrationsPanel'
-
// ── Fixtures ─────────────────────────────────────────────────────────────────
const recipe: WorkflowRecipeResource = {
@@ -71,7 +70,7 @@ function renderPanel() {
...render(
<ToastProvider>
<RecipeIntegrationsPanel recipe={recipe} />
- </ToastProvider>,
+ </ToastProvider>
),
user,
}
diff --git a/control-ui/components/__tests__/RegistryCatalog.test.tsx b/control-ui/components/__tests__/RegistryCatalog.test.tsx
index 4d223ea1f..40ac05d03 100644
--- a/control-ui/components/__tests__/RegistryCatalog.test.tsx
+++ b/control-ui/components/__tests__/RegistryCatalog.test.tsx
@@ -73,7 +73,7 @@ const MOCK_RECIPE_ENTRY: RegistryEntry = {
tags: ['analytics', 'reporting'],
trust_level: 'mid',
quality_tier: 'unverified',
- visibility: 'private',
+ visibility: 'public',
status: 'published',
server_mode: null,
transport: null,
@@ -156,18 +156,29 @@ describe('RegistryCatalog tabs and columns', () => {
render(<RegistryCatalog />)
await screen.findByText('brave-search')
- for (const heading of ['Name', 'Version', 'Visibility']) {
+ for (const heading of ['Name', 'Version']) {
expect(screen.getByRole('columnheader', { name: heading })).toBeInTheDocument()
}
for (const actionHeading of ['Installation', 'Edit or remove']) {
expect(screen.getByRole('columnheader', { name: actionHeading })).toBeInTheDocument()
}
expect(screen.queryByRole('columnheader', { name: 'View details' })).not.toBeInTheDocument()
- for (const removed of ['Type', 'Category', 'Trust', 'Quality', 'Downloads']) {
+ for (const removed of ['Type', 'Category', 'Trust', 'Quality', 'Downloads', 'Visibility']) {
expect(screen.queryByRole('columnheader', { name: removed })).not.toBeInTheDocument()
}
})
+ it('excludes private entries from the Marketplace', async () => {
+ mockApiSuccess([
+ MOCK_MCP_ENTRY,
+ { ...MOCK_MCP_ENTRY, id: '3', name: 'private-search', visibility: 'private' },
+ ])
+ render(<RegistryCatalog />)
+
+ expect(await screen.findByText('brave-search')).toBeInTheDocument()
+ expect(screen.queryByText('private-search')).not.toBeInTheDocument()
+ })
+
it('shows the top-level Connectors tab, no public Plugins tab', async () => {
mockApiSuccess()
render(<RegistryCatalog />)
@@ -201,6 +212,30 @@ describe('RegistryCatalog tabs and columns', () => {
'/marketplace/entries/brave-search/1.0.0'
)
})
+
+ it('sorts connectors by name and version from their headers', async () => {
+ mockApiSuccess([
+ MOCK_MCP_ENTRY,
+ { ...MOCK_MCP_ENTRY, id: '3', name: 'zebra-search', version: '1.2.0' },
+ { ...MOCK_MCP_ENTRY, id: '4', name: 'alpha-search', version: '2.0.0' },
+ ])
+ render(<RegistryCatalog />)
+ await screen.findByText('brave-search')
+
+ const listedNames = () =>
+ Array.from(document.querySelectorAll('.cu-marketplace-table .cu-registry-name')).map(
+ element => element.textContent
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'Sort by name ascending' }))
+ expect(listedNames()).toEqual(['alpha-search', 'brave-search', 'zebra-search'])
+
+ fireEvent.click(screen.getByRole('button', { name: 'Sort by version descending' }))
+ expect(listedNames()).toEqual(['alpha-search', 'zebra-search', 'brave-search'])
+
+ fireEvent.click(screen.getByRole('button', { name: 'Sort by version ascending' }))
+ expect(listedNames()).toEqual(['brave-search', 'zebra-search', 'alpha-search'])
+ })
})
describe('RegistryCatalog expansion and actions', () => {
@@ -330,12 +365,12 @@ describe('RegistryCatalog state handling', () => {
it('renders a skeleton across the compact columns while capability is resolving', () => {
vi.mocked(api.getRegistryCatalog).mockReturnValue(new Promise(() => {}))
// Role is unknown while capability resolves, so the curator-only actions
- // column is absent and the six visible columns render 30 skeleton cells
+ // column is absent and the four visible columns render 20 skeleton cells
// across five rows.
vi.mocked(api.getPublishScope).mockReturnValue(new Promise(() => {}))
const { container } = render(<RegistryCatalog />)
- expect(container.querySelectorAll('.cu-skeleton')).toHaveLength(30)
+ expect(container.querySelectorAll('.cu-skeleton')).toHaveLength(20)
})
it('shows an API error', async () => {
diff --git a/control-ui/e2e/qa-recorder-connector-edit.spec.ts b/control-ui/e2e/qa-recorder-connector-edit.spec.ts
index 546af037b..3254e30c0 100644
--- a/control-ui/e2e/qa-recorder-connector-edit.spec.ts
+++ b/control-ui/e2e/qa-recorder-connector-edit.spec.ts
@@ -237,6 +237,14 @@ test.describe('optional QA recorder: Control UI connector edit', () => {
page.getByRole('heading', { name: `Edit Connector: ${connectorName}`, exact: true })
).toBeVisible({ timeout: 20_000 })
+ // The connector edit screen is split into tabs; the rotation flow lives
+ // on the Credentials tab — navigate there via the tab link.
+ await page.getByRole('tab', { name: 'Credentials', exact: true }).click()
+ await expect(page).toHaveURL(
+ new RegExp(`/connectors/${encodeURIComponent(connectorName)}/edit/credentials$`),
+ { timeout: 20_000 }
+ )
+
// The section names the Secret and the key -> env var mapping — names
// only, never the stored value.
await expect(page.getByText(secretName, { exact: true })).toBeVisible({ timeout: 20_000 })
diff --git a/control-ui/e2e/qa-recorder-connector-rotation-demo.spec.ts b/control-ui/e2e/qa-recorder-connector-rotation-demo.spec.ts
index 6dfbf5d33..e30c97003 100644
--- a/control-ui/e2e/qa-recorder-connector-rotation-demo.spec.ts
+++ b/control-ui/e2e/qa-recorder-connector-rotation-demo.spec.ts
@@ -19,7 +19,7 @@ import {
requireRecorderConfirm,
uniqueE2EName,
} from './qa-recorder-helpers'
-import { humanClick, humanPause, humanReveal, humanType } from './support/human'
+import { humanClick, humanPause, humanType } from './support/human'
const MOCK_MCP_IMAGE = process.env.TEST_MOCK_MCP_IMAGE ?? 'clerum/mock-mcp-server:test'
@@ -96,8 +96,11 @@ test.describe('demo: Control UI credential-rotation journey', () => {
await humanPause(page)
})
- await test.step('scroll to "Update credentials" and read the key mapping', async () => {
- await humanReveal(page, page.getByText('Update credentials', { exact: true }))
+ await test.step('open the Credentials tab and read the key mapping', async () => {
+ await humanClick(page, page.getByRole('tab', { name: 'Credentials', exact: true }))
+ await expect(page.getByText('Update credentials', { exact: true })).toBeVisible({
+ timeout: 20_000,
+ })
const input = page.locator(`#mcp-cred-${secretKey}`)
await expect(input).toBeVisible({ timeout: 20_000 })
// Names-only: masked, empty input; the screen never shows a stored value.
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index ef871d768..ddc127427 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.384",
+ "version": "0.1.385",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.384",
+ "version": "0.1.385",
"dependencies": {
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",
diff --git a/control-ui/package.json b/control-ui/package.json
index ccdef272f..b8c20a4bb 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.384",
+ "version": "0.1.385",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index 988f4e9d2..4d4879e54 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "evenfire",
- "version": "0.1.334",
+ "version": "0.1.335",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "evenfire",
- "version": "0.1.334",
+ "version": "0.1.335",
"license": "MPL-2.0",
"dependencies": {
"@clerum/desktop-app-links": "file:../packages/desktop-app-links",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index 734fef64c..65ce5d94f 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -1,7 +1,7 @@
{
"name": "evenfire",
"productName": "Evenfire",
- "version": "0.1.334",
+ "version": "0.1.335",
"private": true,
"license": "MPL-2.0",
"description": "Evenfire desktop client for secure agent and workflow access",
diff --git a/desktop-app/renderer/styles.css b/desktop-app/renderer/styles.css
index d64a7f266..d05bd0826 100644
--- a/desktop-app/renderer/styles.css
+++ b/desktop-app/renderer/styles.css
@@ -4,7 +4,12 @@
body {
margin: 0;
- font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
+ font-family:
+ system-ui,
+ -apple-system,
+ Segoe UI,
+ Roboto,
+ sans-serif;
background: #0e1118;
color: #e5ecff;
}
diff --git a/desktop-app/src/__tests__/appService.sandboxUiOauthConsent.test.ts b/desktop-app/src/__tests__/appService.sandboxUiOauthConsent.test.ts
index 86fbc18f1..e1177ec8b 100644
--- a/desktop-app/src/__tests__/appService.sandboxUiOauthConsent.test.ts
+++ b/desktop-app/src/__tests__/appService.sandboxUiOauthConsent.test.ts
@@ -20,7 +20,9 @@ const mocks = vi.hoisted(() => ({
requestSandboxUiOauthAuthorizeUrl: vi.fn(),
getOrIssue: vi.fn(),
rpcTokenManagerClear: vi.fn(),
- rpcTokenManagerGetMetadata: vi.fn().mockReturnValue({ expiresAtMs: null, scopes: [], hostRefs: [] }),
+ rpcTokenManagerGetMetadata: vi
+ .fn()
+ .mockReturnValue({ expiresAtMs: null, scopes: [], hostRefs: [] }),
}))
vi.mock('electron', () => ({
@@ -119,7 +121,11 @@ describe('AppService.requestSandboxUiOauthAuthorize', () => {
await svc.requestSandboxUiOauthAuthorize(RECIPE_NS, RECIPE_NAME, CLIENT_ID, true)
expect(mocks.requestSandboxUiOauthAuthorizeUrl).toHaveBeenCalledWith(
- 'rpc-token', RECIPE_NS, RECIPE_NAME, CLIENT_ID, true
+ 'rpc-token',
+ RECIPE_NS,
+ RECIPE_NAME,
+ CLIENT_ID,
+ true
)
expect(mocks.showMessageBox).toHaveBeenCalledOnce()
expect(mocks.openExternal).toHaveBeenCalledWith(AUTHORIZE_URL)
@@ -146,7 +152,11 @@ describe('AppService.requestSandboxUiOauthAuthorize', () => {
expect(mocks.showMessageBox).not.toHaveBeenCalled()
expect(mocks.requestSandboxUiOauthAuthorizeUrl).toHaveBeenCalledWith(
- 'rpc-token', RECIPE_NS, RECIPE_NAME, CLIENT_ID, false
+ 'rpc-token',
+ RECIPE_NS,
+ RECIPE_NAME,
+ CLIENT_ID,
+ false
)
expect(mocks.openExternal).toHaveBeenCalledWith(AUTHORIZE_URL)
})
@@ -166,7 +176,11 @@ describe('AppService.requestSandboxUiOauthAuthorize', () => {
expect(mocks.rpcTokenManagerClear).toHaveBeenCalledOnce()
expect(mocks.requestSandboxUiOauthAuthorizeUrl).toHaveBeenCalledTimes(2)
expect(mocks.requestSandboxUiOauthAuthorizeUrl).toHaveBeenLastCalledWith(
- 'rpc-token-new', RECIPE_NS, RECIPE_NAME, CLIENT_ID, true
+ 'rpc-token-new',
+ RECIPE_NS,
+ RECIPE_NAME,
+ CLIENT_ID,
+ true
)
expect(mocks.openExternal).toHaveBeenCalledWith(AUTHORIZE_URL)
})
diff --git a/desktop-app/test/e2e/vitest.config.ts b/desktop-app/test/e2e/vitest.config.ts
index 7473c2842..c4da5e3d0 100644
--- a/desktop-app/test/e2e/vitest.config.ts
+++ b/desktop-app/test/e2e/vitest.config.ts
@@ -1,17 +1,17 @@
-import { defineConfig } from "vitest/config";
-import path from "node:path";
-import { fileURLToPath } from "node:url";
+import { defineConfig } from 'vitest/config'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const __dirname = path.dirname(fileURLToPath(import.meta.url))
export default defineConfig({
test: {
root: __dirname,
- include: ["*.test.ts"],
+ include: ['*.test.ts'],
testTimeout: 60_000,
hookTimeout: 120_000,
fileParallelism: false,
sequence: { concurrent: false },
- reporters: ["verbose"],
+ reporters: ['verbose'],
},
-});
+})
diff --git a/desktop-app/test/rpcProxyClient.approval.test.ts b/desktop-app/test/rpcProxyClient.approval.test.ts
index 623168437..388bb2ad4 100644
--- a/desktop-app/test/rpcProxyClient.approval.test.ts
+++ b/desktop-app/test/rpcProxyClient.approval.test.ts
@@ -1,33 +1,32 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+// We do NOT mock httpClient here — approveToolCall/denyToolCall/listArtifacts/downloadArtifact
+// use raw `fetch` directly (not requestJson). We mock global fetch instead.
+
+import { RpcProxyClient } from '../src/rpcProxyClient.js'
// ── Mocks ─────────────────────────────────────────────────────────────────────
-vi.mock("../src/config.js", () => ({
+vi.mock('../src/config.js', () => ({
config: {
- rpcProxyBaseUrl: "http://localhost:8094",
+ rpcProxyBaseUrl: 'http://localhost:8094',
requestTimeoutMs: 5000,
},
-}));
-
-// We do NOT mock httpClient here — approveToolCall/denyToolCall/listArtifacts/downloadArtifact
-// use raw `fetch` directly (not requestJson). We mock global fetch instead.
-
-import { RpcProxyClient } from "../src/rpcProxyClient.js";
+}))
// ── Setup ─────────────────────────────────────────────────────────────────────
-let client: RpcProxyClient;
-let fetchSpy: ReturnType<typeof vi.fn>;
+let client: RpcProxyClient
+let fetchSpy: ReturnType<typeof vi.fn>
beforeEach(() => {
- client = new RpcProxyClient();
- fetchSpy = vi.fn();
- vi.stubGlobal("fetch", fetchSpy);
-});
+ client = new RpcProxyClient()
+ fetchSpy = vi.fn()
+ vi.stubGlobal('fetch', fetchSpy)
+})
afterEach(() => {
- vi.unstubAllGlobals();
-});
+ vi.unstubAllGlobals()
+})
// ── Helper ────────────────────────────────────────────────────────────────────
@@ -35,238 +34,236 @@ function okResponse(body?: unknown): Response {
return {
ok: true,
status: 200,
- statusText: "OK",
- text: () => Promise.resolve(body !== undefined ? JSON.stringify(body) : ""),
+ statusText: 'OK',
+ text: () => Promise.resolve(body !== undefined ? JSON.stringify(body) : ''),
json: () => Promise.resolve(body),
arrayBuffer: () => Promise.resolve(new ArrayBuffer(8)),
- } as unknown as Response;
+ } as unknown as Response
}
function errorResponse(status: number, body: string): Response {
return {
ok: false,
status,
- statusText: "Error",
+ statusText: 'Error',
text: () => Promise.resolve(body),
- json: () => Promise.reject(new Error("not json")),
- } as unknown as Response;
+ json: () => Promise.reject(new Error('not json')),
+ } as unknown as Response
}
// ── approveToolCall ───────────────────────────────────────────────────────────
-describe("RpcProxyClient — approveToolCall()", () => {
- it("sends POST to /approvals/approve with { taskId, toolCallId }", async () => {
- fetchSpy.mockResolvedValueOnce(okResponse());
+describe('RpcProxyClient — approveToolCall()', () => {
+ it('sends POST to /approvals/approve with { taskId, toolCallId }', async () => {
+ fetchSpy.mockResolvedValueOnce(okResponse())
- await client.approveToolCall("rpc-token", "chatllm", "task-123", "tc-456");
+ await client.approveToolCall('rpc-token', 'chatllm', 'task-123', 'tc-456')
- expect(fetchSpy).toHaveBeenCalledOnce();
- const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
+ expect(fetchSpy).toHaveBeenCalledOnce()
+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit]
- expect(url).toBe("http://localhost:8094/api/v1/rpc/hosts/chatllm/approvals/approve");
- expect(init.method).toBe("POST");
+ expect(url).toBe('http://localhost:8094/api/v1/rpc/hosts/chatllm/approvals/approve')
+ expect(init.method).toBe('POST')
expect(init.headers).toEqual(
expect.objectContaining({
- "content-type": "application/json",
- authorization: "Bearer rpc-token",
+ 'content-type': 'application/json',
+ authorization: 'Bearer rpc-token',
})
- );
+ )
expect(JSON.parse(init.body as string)).toEqual({
- taskId: "task-123",
- toolCallId: "tc-456",
- });
- });
+ taskId: 'task-123',
+ toolCallId: 'tc-456',
+ })
+ })
- it("URL-encodes hostRef with special characters", async () => {
- fetchSpy.mockResolvedValueOnce(okResponse());
+ it('URL-encodes hostRef with special characters', async () => {
+ fetchSpy.mockResolvedValueOnce(okResponse())
- await client.approveToolCall("tok", "host ref/v2", "t1", "tc1");
+ await client.approveToolCall('tok', 'host ref/v2', 't1', 'tc1')
- const [url] = fetchSpy.mock.calls[0] as [string];
- expect(url).toContain(encodeURIComponent("host ref/v2"));
- });
+ const [url] = fetchSpy.mock.calls[0] as [string]
+ expect(url).toContain(encodeURIComponent('host ref/v2'))
+ })
- it("throws on non-OK response with status and body", async () => {
- fetchSpy.mockResolvedValueOnce(errorResponse(403, "Missing scope: host:approval:write"));
+ it('throws on non-OK response with status and body', async () => {
+ fetchSpy.mockResolvedValueOnce(errorResponse(403, 'Missing scope: host:approval:write'))
await expect(
- client.approveToolCall("rpc-token", "chatllm", "task-123", "tc-456")
- ).rejects.toThrow("Approve failed (403): Missing scope: host:approval:write");
- });
+ client.approveToolCall('rpc-token', 'chatllm', 'task-123', 'tc-456')
+ ).rejects.toThrow('Approve failed (403): Missing scope: host:approval:write')
+ })
- it("throws on empty error body with status code", async () => {
- fetchSpy.mockResolvedValueOnce(errorResponse(500, ""));
+ it('throws on empty error body with status code', async () => {
+ fetchSpy.mockResolvedValueOnce(errorResponse(500, ''))
await expect(
- client.approveToolCall("rpc-token", "chatllm", "task-123", "tc-456")
- ).rejects.toThrow("Approve failed (500):");
- });
-});
+ client.approveToolCall('rpc-token', 'chatllm', 'task-123', 'tc-456')
+ ).rejects.toThrow('Approve failed (500):')
+ })
+})
// ── denyToolCall ──────────────────────────────────────────────────────────────
-describe("RpcProxyClient — denyToolCall()", () => {
- it("sends POST to /approvals/deny with { taskId, toolCallId, reason }", async () => {
- fetchSpy.mockResolvedValueOnce(okResponse());
+describe('RpcProxyClient — denyToolCall()', () => {
+ it('sends POST to /approvals/deny with { taskId, toolCallId, reason }', async () => {
+ fetchSpy.mockResolvedValueOnce(okResponse())
- await client.denyToolCall("rpc-token", "chatllm", "task-123", "tc-456", "Too dangerous");
+ await client.denyToolCall('rpc-token', 'chatllm', 'task-123', 'tc-456', 'Too dangerous')
- expect(fetchSpy).toHaveBeenCalledOnce();
- const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
+ expect(fetchSpy).toHaveBeenCalledOnce()
+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit]
- expect(url).toBe("http://localhost:8094/api/v1/rpc/hosts/chatllm/approvals/deny");
- expect(init.method).toBe("POST");
+ expect(url).toBe('http://localhost:8094/api/v1/rpc/hosts/chatllm/approvals/deny')
+ expect(init.method).toBe('POST')
expect(JSON.parse(init.body as string)).toEqual({
- taskId: "task-123",
- toolCallId: "tc-456",
- reason: "Too dangerous",
- });
- });
+ taskId: 'task-123',
+ toolCallId: 'tc-456',
+ reason: 'Too dangerous',
+ })
+ })
- it("includes authorization header", async () => {
- fetchSpy.mockResolvedValueOnce(okResponse());
+ it('includes authorization header', async () => {
+ fetchSpy.mockResolvedValueOnce(okResponse())
- await client.denyToolCall("my-token", "chatllm", "t1", "tc1", "no");
+ await client.denyToolCall('my-token', 'chatllm', 't1', 'tc1', 'no')
- const [, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
- const headers = init.headers as Record<string, string>;
- expect(headers.authorization).toBe("Bearer my-token");
- });
+ const [, init] = fetchSpy.mock.calls[0] as [string, RequestInit]
+ const headers = init.headers as Record<string, string>
+ expect(headers.authorization).toBe('Bearer my-token')
+ })
- it("throws on 401 unauthorized response", async () => {
- fetchSpy.mockResolvedValueOnce(errorResponse(401, "Token expired"));
+ it('throws on 401 unauthorized response', async () => {
+ fetchSpy.mockResolvedValueOnce(errorResponse(401, 'Token expired'))
await expect(
- client.denyToolCall("expired-tok", "chatllm", "t1", "tc1", "nope")
- ).rejects.toThrow("Deny failed (401): Token expired");
- });
+ client.denyToolCall('expired-tok', 'chatllm', 't1', 'tc1', 'nope')
+ ).rejects.toThrow('Deny failed (401): Token expired')
+ })
- it("URL-encodes hostRef", async () => {
- fetchSpy.mockResolvedValueOnce(okResponse());
+ it('URL-encodes hostRef', async () => {
+ fetchSpy.mockResolvedValueOnce(okResponse())
- await client.denyToolCall("tok", "my host", "t1", "tc1", "reason");
+ await client.denyToolCall('tok', 'my host', 't1', 'tc1', 'reason')
- const [url] = fetchSpy.mock.calls[0] as [string];
- expect(url).toContain(encodeURIComponent("my host"));
- });
-});
+ const [url] = fetchSpy.mock.calls[0] as [string]
+ expect(url).toContain(encodeURIComponent('my host'))
+ })
+})
// ── listArtifacts ─────────────────────────────────────────────────────────────
-describe("RpcProxyClient — listArtifacts()", () => {
+describe('RpcProxyClient — listArtifacts()', () => {
const sampleArtifacts = {
artifacts: [
- { name: "report.pdf", format: "pdf", sizeBytes: 4096, createdAt: "2026-03-27T10:00:00Z" },
- { name: "data.xlsx", format: "xlsx", sizeBytes: 8192, createdAt: "2026-03-27T10:01:00Z" },
+ { name: 'report.pdf', format: 'pdf', sizeBytes: 4096, createdAt: '2026-03-27T10:00:00Z' },
+ { name: 'data.xlsx', format: 'xlsx', sizeBytes: 8192, createdAt: '2026-03-27T10:01:00Z' },
],
- };
+ }
- it("calls GET /artifacts with Bearer token and parses response", async () => {
- fetchSpy.mockResolvedValueOnce(okResponse(sampleArtifacts));
+ it('calls GET /artifacts with Bearer token and parses response', async () => {
+ fetchSpy.mockResolvedValueOnce(okResponse(sampleArtifacts))
- const result = await client.listArtifacts("rpc-token", "chatllm");
+ const result = await client.listArtifacts('rpc-token', 'chatllm')
- expect(fetchSpy).toHaveBeenCalledOnce();
- const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
+ expect(fetchSpy).toHaveBeenCalledOnce()
+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit]
- expect(url).toBe("http://localhost:8094/api/v1/rpc/hosts/chatllm/artifacts");
- expect(init.method).toBeUndefined(); // fetch default = GET
- expect((init.headers as Record<string, string>).authorization).toBe("Bearer rpc-token");
+ expect(url).toBe('http://localhost:8094/api/v1/rpc/hosts/chatllm/artifacts')
+ expect(init.method).toBeUndefined() // fetch default = GET
+ expect((init.headers as Record<string, string>).authorization).toBe('Bearer rpc-token')
- expect(result.artifacts).toHaveLength(2);
- expect(result.artifacts[0]!.name).toBe("report.pdf");
- expect(result.artifacts[0]!.format).toBe("pdf");
- expect(result.artifacts[0]!.sizeBytes).toBe(4096);
- expect(result.artifacts[1]!.name).toBe("data.xlsx");
- });
+ expect(result.artifacts).toHaveLength(2)
+ expect(result.artifacts[0]!.name).toBe('report.pdf')
+ expect(result.artifacts[0]!.format).toBe('pdf')
+ expect(result.artifacts[0]!.sizeBytes).toBe(4096)
+ expect(result.artifacts[1]!.name).toBe('data.xlsx')
+ })
- it("parses empty artifacts list", async () => {
- fetchSpy.mockResolvedValueOnce(okResponse({ artifacts: [] }));
+ it('parses empty artifacts list', async () => {
+ fetchSpy.mockResolvedValueOnce(okResponse({ artifacts: [] }))
- const result = await client.listArtifacts("tok", "chatllm");
+ const result = await client.listArtifacts('tok', 'chatllm')
- expect(result.artifacts).toEqual([]);
- });
+ expect(result.artifacts).toEqual([])
+ })
- it("throws on non-OK response", async () => {
- fetchSpy.mockResolvedValueOnce(errorResponse(500, "Internal error"));
+ it('throws on non-OK response', async () => {
+ fetchSpy.mockResolvedValueOnce(errorResponse(500, 'Internal error'))
- await expect(client.listArtifacts("tok", "chatllm")).rejects.toThrow(
- "List artifacts failed (500): Internal error"
- );
- });
+ await expect(client.listArtifacts('tok', 'chatllm')).rejects.toThrow(
+ 'List artifacts failed (500): Internal error'
+ )
+ })
- it("URL-encodes hostRef", async () => {
- fetchSpy.mockResolvedValueOnce(okResponse({ artifacts: [] }));
+ it('URL-encodes hostRef', async () => {
+ fetchSpy.mockResolvedValueOnce(okResponse({ artifacts: [] }))
- await client.listArtifacts("tok", "host/ref");
+ await client.listArtifacts('tok', 'host/ref')
- const [url] = fetchSpy.mock.calls[0] as [string];
- expect(url).toContain(encodeURIComponent("host/ref"));
- });
-});
+ const [url] = fetchSpy.mock.calls[0] as [string]
+ expect(url).toContain(encodeURIComponent('host/ref'))
+ })
+})
// ── downloadArtifact ──────────────────────────────────────────────────────────
-describe("RpcProxyClient — downloadArtifact()", () => {
- it("calls GET /artifacts/:filename/download and returns Buffer", async () => {
- const fakeBytes = new Uint8Array([0x50, 0x4b, 0x03, 0x04]); // ZIP magic bytes
- const fakeArrayBuffer = fakeBytes.buffer;
+describe('RpcProxyClient — downloadArtifact()', () => {
+ it('calls GET /artifacts/:filename/download and returns Buffer', async () => {
+ const fakeBytes = new Uint8Array([0x50, 0x4b, 0x03, 0x04]) // ZIP magic bytes
+ const fakeArrayBuffer = fakeBytes.buffer
fetchSpy.mockResolvedValueOnce({
ok: true,
status: 200,
arrayBuffer: () => Promise.resolve(fakeArrayBuffer),
- } as unknown as Response);
+ } as unknown as Response)
- const result = await client.downloadArtifact("rpc-token", "chatllm", "report.pdf");
+ const result = await client.downloadArtifact('rpc-token', 'chatllm', 'report.pdf')
- expect(fetchSpy).toHaveBeenCalledOnce();
- const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
+ expect(fetchSpy).toHaveBeenCalledOnce()
+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit]
- expect(url).toBe(
- "http://localhost:8094/api/v1/rpc/hosts/chatllm/artifacts/report.pdf/download"
- );
- expect((init.headers as Record<string, string>).authorization).toBe("Bearer rpc-token");
+ expect(url).toBe('http://localhost:8094/api/v1/rpc/hosts/chatllm/artifacts/report.pdf/download')
+ expect((init.headers as Record<string, string>).authorization).toBe('Bearer rpc-token')
// Result should be a Buffer wrapping the ArrayBuffer
- expect(Buffer.isBuffer(result)).toBe(true);
- expect(result.length).toBe(4);
- expect(result[0]).toBe(0x50);
- });
+ expect(Buffer.isBuffer(result)).toBe(true)
+ expect(result.length).toBe(4)
+ expect(result[0]).toBe(0x50)
+ })
- it("URL-encodes both hostRef and filename", async () => {
+ it('URL-encodes both hostRef and filename', async () => {
fetchSpy.mockResolvedValueOnce({
ok: true,
status: 200,
arrayBuffer: () => Promise.resolve(new ArrayBuffer(0)),
- } as unknown as Response);
+ } as unknown as Response)
- await client.downloadArtifact("tok", "my host", "file name.pdf");
+ await client.downloadArtifact('tok', 'my host', 'file name.pdf')
- const [url] = fetchSpy.mock.calls[0] as [string];
- expect(url).toContain(encodeURIComponent("my host"));
- expect(url).toContain(encodeURIComponent("file name.pdf"));
- });
+ const [url] = fetchSpy.mock.calls[0] as [string]
+ expect(url).toContain(encodeURIComponent('my host'))
+ expect(url).toContain(encodeURIComponent('file name.pdf'))
+ })
- it("throws on non-OK response", async () => {
- fetchSpy.mockResolvedValueOnce(errorResponse(404, "Not found"));
+ it('throws on non-OK response', async () => {
+ fetchSpy.mockResolvedValueOnce(errorResponse(404, 'Not found'))
- await expect(
- client.downloadArtifact("tok", "chatllm", "missing.pdf")
- ).rejects.toThrow("Download artifact failed (404): Not found");
- });
+ await expect(client.downloadArtifact('tok', 'chatllm', 'missing.pdf')).rejects.toThrow(
+ 'Download artifact failed (404): Not found'
+ )
+ })
- it("returns empty buffer for empty file", async () => {
+ it('returns empty buffer for empty file', async () => {
fetchSpy.mockResolvedValueOnce({
ok: true,
status: 200,
arrayBuffer: () => Promise.resolve(new ArrayBuffer(0)),
- } as unknown as Response);
+ } as unknown as Response)
- const result = await client.downloadArtifact("tok", "chatllm", "empty.txt");
+ const result = await client.downloadArtifact('tok', 'chatllm', 'empty.txt')
- expect(Buffer.isBuffer(result)).toBe(true);
- expect(result.length).toBe(0);
- });
-});
+ expect(Buffer.isBuffer(result)).toBe(true)
+ expect(result.length).toBe(0)
+ })
+})
diff --git a/desktop-app/ui/src/gfs/__tests__/delegation.test.tsx b/desktop-app/ui/src/gfs/__tests__/delegation.test.tsx
index 4eedbcd08..090ff47a3 100644
--- a/desktop-app/ui/src/gfs/__tests__/delegation.test.tsx
+++ b/desktop-app/ui/src/gfs/__tests__/delegation.test.tsx
@@ -157,11 +157,7 @@ describe('GfsDelegationPanel', () => {
await screen.findByText('Some selected subjects are invalid and were rejected.')
expect(onGrant).toHaveBeenCalledTimes(1)
- expect(onGrant).toHaveBeenCalledWith(
- ['user:successful', 'team:blocked'],
- ['read'],
- false
- )
+ expect(onGrant).toHaveBeenCalledWith(['user:successful', 'team:blocked'], ['read'], false)
expect(screen.getByRole('button', { name: 'Remove Successful User' })).toBeTruthy()
expect(screen.getByRole('button', { name: 'Remove Blocked Team' })).toBeTruthy()
})
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx
index 0b1007986..ff8667aa0 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx
@@ -52,9 +52,7 @@ function createDeferred<T>(): Deferred<T> {
}
function createSessionState(authenticated: boolean, me = HARNESS_ME) {
- return authenticated
- ? { authenticated: true, me }
- : { authenticated: false, me: null }
+ return authenticated ? { authenticated: true, me } : { authenticated: false, me: null }
}
function createCatalog(agentNames: string[]) {
diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsx
index 6387bb1f9..d4f951866 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -986,7 +986,9 @@ export function FilesPage({ pushToast }: FilesPageProps) {
<GfsDelegationPanel
affordances={affordances}
subjectOptions={grantSubjectOptions}
- subjectOptionsLoading={teamDirectoryQuery.isFetching || myAgentsQuery.isFetching}
+ subjectOptionsLoading={
+ teamDirectoryQuery.isFetching || myAgentsQuery.isFetching
+ }
subjectOptionsError={mergeErrorMessages(
teamDirectoryQuery.error,
myAgentsQuery.error
diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index 99eb7dafe..d36a1f951 100644
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@ -710,7 +710,9 @@ describe('FilesPage', () => {
await openManageDialog('Team folder')
- const subjectPicker = await screen.findByRole('combobox', { name: 'Add people, teams, or agents' })
+ const subjectPicker = await screen.findByRole('combobox', {
+ name: 'Add people, teams, or agents',
+ })
await waitFor(() => expect(subjectPicker).toHaveProperty('disabled', false))
fireEvent.focus(subjectPicker)
const userLabel = await screen.findByText('Test Two')
@@ -872,7 +874,9 @@ describe('FilesPage', () => {
renderFilesPage(pushToast)
await openManageDialog('Team folder')
- const subjectPicker = await screen.findByRole('combobox', { name: 'Add people, teams, or agents' })
+ const subjectPicker = await screen.findByRole('combobox', {
+ name: 'Add people, teams, or agents',
+ })
fireEvent.focus(subjectPicker)
fireEvent.click(await screen.findByRole('option', { name: /Test Two/ }))
fireEvent.click(screen.getByRole('button', { name: 'Grant access' }))
@@ -945,7 +949,9 @@ describe('FilesPage', () => {
renderFilesPage(pushToast)
await openManageDialog('Team folder')
- const subjectPicker = await screen.findByRole('combobox', { name: 'Add people, teams, or agents' })
+ const subjectPicker = await screen.findByRole('combobox', {
+ name: 'Add people, teams, or agents',
+ })
fireEvent.focus(subjectPicker)
fireEvent.click(await screen.findByRole('option', { name: /Test Two/ }))
fireEvent.click(await screen.findByRole('option', { name: /Test Three/ }))
diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.css
index f333573d8..0e4eafb02 100644
--- a/desktop-app/ui/src/styles.css
+++ b/desktop-app/ui/src/styles.css
@@ -12590,21 +12590,56 @@ pre {
.composer-reference-submenu {
left: calc(100% + var(--space-1));
- bottom: auto;
- max-height: min(340px, 70vh);
- overflow: auto;
+ bottom: calc(var(--space-1) + 34px);
+ top: auto;
+ max-height: min(420px, 65vh);
+ overflow-y: auto;
+ scrollbar-width: thin;
+}
+
+.composer-reference-submenu::-webkit-scrollbar {
+ width: 8px;
+}
+
+.composer-reference-submenu::-webkit-scrollbar-thumb {
+ background: rgba(var(--edge-rgb), 0.4);
+ border-radius: 4px;
+}
+
+.composer-reference-submenu::-webkit-scrollbar-thumb:hover {
+ background: rgba(var(--edge-rgb), 0.6);
}
.composer-reference-submenu--plugins {
- top: var(--space-1);
+ bottom: calc(var(--space-1) + 68px);
}
.composer-reference-submenu--connectors {
- top: calc(var(--space-1) + 34px);
+ bottom: calc(var(--space-1) + 34px);
}
.composer-reference-submenu--agent-files {
+ bottom: var(--space-1);
+}
+
+.composer-inline .composer-reference-submenu {
+ bottom: auto;
+ top: var(--space-1);
+}
+
+.composer-inline .composer-reference-submenu--plugins {
+ top: var(--space-1);
+ bottom: auto;
+}
+
+.composer-inline .composer-reference-submenu--connectors {
+ top: calc(var(--space-1) + 34px);
+ bottom: auto;
+}
+
+.composer-inline .composer-reference-submenu--agent-files {
top: calc(var(--space-1) + 68px);
+ bottom: auto;
}
.composer-inline .composer-reference-menu-panel {
diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.json
index 9472695cf..4fb41b7a4 100644
--- a/external-rest-api/package-lock.json
+++ b/external-rest-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-external-rest-api",
- "version": "0.1.60",
+ "version": "0.1.61",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-external-rest-api",
- "version": "0.1.60",
+ "version": "0.1.61",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/external-rest-api/package.json b/external-rest-api/package.json
index 355c471dc..39f50f425 100644
--- a/external-rest-api/package.json
+++ b/external-rest-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-external-rest-api",
- "version": "0.1.60",
+ "version": "0.1.61",
"description": "External REST API for profile, team management, and RPC token brokerage",
"main": "dist/main.js",
"engines": {
diff --git a/external-rest-api/src/main.ts b/external-rest-api/src/main.ts
index ee7b2c9af..86a2a374a 100644
--- a/external-rest-api/src/main.ts
+++ b/external-rest-api/src/main.ts
@@ -1,26 +1,26 @@
-import { config } from "./config.js";
-import { createApp } from "./app.js";
+import { createApp } from './app.js'
+import { config } from './config.js'
async function main(): Promise<void> {
- console.log("[ProfileAPI] Starting...");
+ console.log('[ProfileAPI] Starting...')
- const app = createApp();
+ const app = createApp()
const server = app.listen(config.port, () => {
- console.log(`[ProfileAPI] Listening on port ${config.port}`);
- });
+ console.log(`[ProfileAPI] Listening on port ${config.port}`)
+ })
const shutdown = async () => {
- console.log("[ProfileAPI] Shutting down...");
+ console.log('[ProfileAPI] Shutting down...')
server.close(async () => {
- process.exit(0);
- });
- };
+ process.exit(0)
+ })
+ }
- process.on("SIGINT", shutdown);
- process.on("SIGTERM", shutdown);
+ process.on('SIGINT', shutdown)
+ process.on('SIGTERM', shutdown)
}
-main().catch((error) => {
- console.error("[ProfileAPI] Fatal error:", error);
- process.exit(1);
-});
+main().catch(error => {
+ console.error('[ProfileAPI] Fatal error:', error)
+ process.exit(1)
+})
diff --git a/external-rest-api/src/repositories/dbClient.ts b/external-rest-api/src/repositories/dbClient.ts
index 1c753d045..c387a6939 100644
--- a/external-rest-api/src/repositories/dbClient.ts
+++ b/external-rest-api/src/repositories/dbClient.ts
@@ -1,12 +1,12 @@
export type QueryResultRow = {
- [key: string]: unknown;
-};
+ [key: string]: unknown
+}
export type QueryResultLike<T extends QueryResultRow = QueryResultRow> = {
- rows: T[];
- rowCount: number | null;
-};
+ rows: T[]
+ rowCount: number | null
+}
export type DbClient = {
- query: (text: string, values?: unknown[]) => Promise<QueryResultLike>;
-};
+ query: (text: string, values?: unknown[]) => Promise<QueryResultLike>
+}
diff --git a/external-rest-api/src/repositories/directoryRepository.ts b/external-rest-api/src/repositories/directoryRepository.ts
index fb76ac04d..655f72095 100644
--- a/external-rest-api/src/repositories/directoryRepository.ts
+++ b/external-rest-api/src/repositories/directoryRepository.ts
@@ -1,12 +1,15 @@
-import { pool } from "../db.js";
+import { pool } from '../db.js'
-export async function searchTeamDirectory(teamId: string, query: string): Promise<
+export async function searchTeamDirectory(
+ teamId: string,
+ query: string
+): Promise<
Array<{
- id: string;
- email: string;
- name: string | null;
- display_name: string | null;
- channels: unknown;
+ id: string
+ email: string
+ name: string | null
+ display_name: string | null
+ channels: unknown
}>
> {
const rows = await pool.query(
@@ -24,13 +27,12 @@ export async function searchTeamDirectory(teamId: string, query: string): Promis
ORDER BY COALESCE(p.display_name, u.name, u.email) ASC
LIMIT 25`,
[teamId, `%${query}%`]
- );
+ )
return rows.rows as Array<{
- id: string;
- email: string;
- name: string | null;
- display_name: string | null;
- channels: unknown;
- }>;
+ id: string
+ email: string
+ name: string | null
+ display_name: string | null
+ channels: unknown
+ }>
}
-
diff --git a/external-rest-api/src/repositories/meRepository.ts b/external-rest-api/src/repositories/meRepository.ts
index 54b4a06cd..55eeeb5b1 100644
--- a/external-rest-api/src/repositories/meRepository.ts
+++ b/external-rest-api/src/repositories/meRepository.ts
@@ -1,34 +1,34 @@
-import { pool } from "../db.js";
+import { pool } from '../db.js'
export type TeamListRow = {
- id: string;
- name: string;
- role: string;
-};
+ id: string
+ name: string
+ role: string
+}
export type MembershipRow = {
- team_id: string;
- role: string;
- team_name: string;
-};
+ team_id: string
+ role: string
+ team_name: string
+}
export type MeRow = {
- id: string;
- email: string;
- name: string | null;
- picture: string | null;
- role: string | null;
- team_id: string | null;
- team_name: string | null;
- display_name: string | null;
- channels: unknown;
-};
+ id: string
+ email: string
+ name: string | null
+ picture: string | null
+ role: string | null
+ team_id: string | null
+ team_name: string | null
+ display_name: string | null
+ channels: unknown
+}
export type ProfileRow = {
- user_id: string;
- display_name: string | null;
- channels: unknown;
-};
+ user_id: string
+ display_name: string | null
+ channels: unknown
+}
export async function listActiveTeamsByUserId(userId: string): Promise<TeamListRow[]> {
const result = await pool.query(
@@ -39,11 +39,14 @@ export async function listActiveTeamsByUserId(userId: string): Promise<TeamListR
AND tm.status = 'active'
ORDER BY t.created_at ASC`,
[userId]
- );
- return result.rows as TeamListRow[];
+ )
+ return result.rows as TeamListRow[]
}
-export async function findMembership(userId: string, teamId: string): Promise<MembershipRow | null> {
+export async function findMembership(
+ userId: string,
+ teamId: string
+): Promise<MembershipRow | null> {
const result = await pool.query(
`SELECT tm.team_id, tm.role, t.name AS team_name
FROM team_members tm
@@ -53,8 +56,8 @@ export async function findMembership(userId: string, teamId: string): Promise<Me
AND tm.status = 'active'
LIMIT 1`,
[userId, teamId]
- );
- return (result.rows[0] as MembershipRow | undefined) || null;
+ )
+ return (result.rows[0] as MembershipRow | undefined) || null
}
export async function getMe(userId: string, teamId: string): Promise<MeRow | null> {
@@ -69,11 +72,15 @@ export async function getMe(userId: string, teamId: string): Promise<MeRow | nul
WHERE u.id = $1
LIMIT 1`,
[userId, teamId]
- );
- return (result.rows[0] as MeRow | undefined) || null;
+ )
+ return (result.rows[0] as MeRow | undefined) || null
}
-export async function upsertProfile(userId: string, displayName: string | null, channelsJson: string): Promise<ProfileRow> {
+export async function upsertProfile(
+ userId: string,
+ displayName: string | null,
+ channelsJson: string
+): Promise<ProfileRow> {
const result = await pool.query(
`INSERT INTO profiles(user_id, display_name, channels)
VALUES($1, $2, $3::jsonb)
@@ -84,7 +91,6 @@ export async function upsertProfile(userId: string, displayName: string | null,
updated_at = NOW()
RETURNING user_id, display_name, channels`,
[userId, displayName, channelsJson]
- );
- return result.rows[0] as ProfileRow;
+ )
+ return result.rows[0] as ProfileRow
}
-
diff --git a/external-rest-api/src/routes/__tests__/oauthGrants.test.ts b/external-rest-api/src/routes/__tests__/oauthGrants.test.ts
index c8b1867ab..ed9336442 100644
--- a/external-rest-api/src/routes/__tests__/oauthGrants.test.ts
+++ b/external-rest-api/src/routes/__tests__/oauthGrants.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
import * as client from '../../controlApiClient.js'
describe('oauth grants proxy', () => {
@@ -6,7 +6,9 @@ describe('oauth grants proxy', () => {
const spy = vi.spyOn(client, 'controlApiRequest').mockResolvedValue({ grants: [] } as never)
const { listOauthGrants } = await import('../../services/oauthGrantsService.js')
await listOauthGrants('SESSION_JWT')
- expect(spy).toHaveBeenCalledWith('GET', '/external/oauth/grants', { userSessionToken: 'SESSION_JWT' })
+ expect(spy).toHaveBeenCalledWith('GET', '/external/oauth/grants', {
+ userSessionToken: 'SESSION_JWT',
+ })
spy.mockRestore()
})
diff --git a/external-rest-api/src/routes/directory.ts b/external-rest-api/src/routes/directory.ts
index 1a809d999..ec39d867c 100644
--- a/external-rest-api/src/routes/directory.ts
+++ b/external-rest-api/src/routes/directory.ts
@@ -1,25 +1,25 @@
-import { Router } from "express";
-import { extractAuthToken, requireAuth, type AuthedRequest } from "../middleware/auth.js";
-import { searchDirectory } from "../services/directoryService.js";
+import { Router } from 'express'
+import { type AuthedRequest, extractAuthToken, requireAuth } from '../middleware/auth.js'
+import { searchDirectory } from '../services/directoryService.js'
export function createDirectoryRouter(): Router {
- const router = Router();
+ const router = Router()
- router.get("/directory/search", requireAuth, async (req: AuthedRequest, res, next) => {
+ router.get('/directory/search', requireAuth, async (req: AuthedRequest, res, next) => {
try {
- const auth = req.auth!;
- const sessionToken = extractAuthToken(req);
- const q = String(req.query.q || "").trim();
+ const auth = req.auth!
+ const sessionToken = extractAuthToken(req)
+ const q = String(req.query.q || '').trim()
if (!q) {
- res.status(200).json({ items: [] });
- return;
+ res.status(200).json({ items: [] })
+ return
}
- res.status(200).json(await searchDirectory(auth.teamId, q, sessionToken));
+ res.status(200).json(await searchDirectory(auth.teamId, q, sessionToken))
} catch (error) {
- next(error);
+ next(error)
}
- });
+ })
- return router;
+ return router
}
diff --git a/external-rest-api/src/routes/health.ts b/external-rest-api/src/routes/health.ts
index 6d72149b5..49cc0c87c 100644
--- a/external-rest-api/src/routes/health.ts
+++ b/external-rest-api/src/routes/health.ts
@@ -1,9 +1,9 @@
-import { Router } from "express";
+import { Router } from 'express'
export function createHealthRouter(): Router {
- const router = Router();
- router.get("/health", (_req, res) => {
- res.status(200).json({ status: "ok" });
- });
- return router;
+ const router = Router()
+ router.get('/health', (_req, res) => {
+ res.status(200).json({ status: 'ok' })
+ })
+ return router
}
diff --git a/external-rest-api/src/services/directoryService.ts b/external-rest-api/src/services/directoryService.ts
index dcb4f41ae..2e2e7c6bf 100644
--- a/external-rest-api/src/services/directoryService.ts
+++ b/external-rest-api/src/services/directoryService.ts
@@ -1,14 +1,14 @@
-import { controlApiRequest } from "../controlApiClient.js";
+import { controlApiRequest } from '../controlApiClient.js'
export async function searchDirectory(teamId: string, q: string, sessionToken: string) {
if (!q.trim()) {
- return { items: [] };
+ return { items: [] }
}
- return controlApiRequest<{ items: unknown[] }>("GET", "/external/directory/search", {
+ return controlApiRequest<{ items: unknown[] }>('GET', '/external/directory/search', {
query: {
teamId,
- q: q.trim()
+ q: q.trim(),
},
- userSessionToken: sessionToken
- });
+ userSessionToken: sessionToken,
+ })
}
diff --git a/external-rest-api/src/services/oauthGrantsService.ts b/external-rest-api/src/services/oauthGrantsService.ts
index c776ac139..c78a811be 100644
--- a/external-rest-api/src/services/oauthGrantsService.ts
+++ b/external-rest-api/src/services/oauthGrantsService.ts
@@ -9,7 +9,9 @@ export interface OauthGrantSummary {
updatedAt: string
}
-export async function listOauthGrants(sessionToken: string): Promise<{ grants: OauthGrantSummary[] }> {
+export async function listOauthGrants(
+ sessionToken: string
+): Promise<{ grants: OauthGrantSummary[] }> {
return controlApiRequest('GET', '/external/oauth/grants', { userSessionToken: sessionToken })
}
diff --git a/external-rest-api/test/routes.directory.test.ts b/external-rest-api/test/routes.directory.test.ts
index 72bd6caa9..63bcd29fb 100644
--- a/external-rest-api/test/routes.directory.test.ts
+++ b/external-rest-api/test/routes.directory.test.ts
@@ -1,76 +1,85 @@
-import express from "express";
-import request from "supertest";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+import { createDirectoryRouter } from '../src/routes/directory.js'
const controlApiMock = vi.hoisted(() => ({
- verifyToken: vi.fn()
-}));
+ verifyToken: vi.fn(),
+}))
const directoryServiceMock = vi.hoisted(() => ({
- searchDirectory: vi.fn()
-}));
+ searchDirectory: vi.fn(),
+}))
-vi.mock("../src/authToken.js", () => controlApiMock);
-vi.mock("../src/services/directoryService.js", () => directoryServiceMock);
+vi.mock('../src/authToken.js', () => controlApiMock)
+vi.mock('../src/services/directoryService.js', () => directoryServiceMock)
-import { createDirectoryRouter } from "../src/routes/directory.js";
-
-describe("routes/directory", () => {
+describe('routes/directory', () => {
const claims = {
- userId: "user-1",
- email: "[email protected]",
- teamId: "team-1",
- role: "member" as const,
- exp: 9999999999
- };
+ userId: 'user-1',
+ email: '[email protected]',
+ teamId: 'team-1',
+ role: 'member' as const,
+ exp: 9999999999,
+ }
beforeEach(() => {
- controlApiMock.verifyToken.mockReset();
- directoryServiceMock.searchDirectory.mockReset();
- });
+ controlApiMock.verifyToken.mockReset()
+ directoryServiceMock.searchDirectory.mockReset()
+ })
function makeApp() {
- const app = express();
- app.use(express.json());
- app.use(createDirectoryRouter());
- return app;
+ const app = express()
+ app.use(express.json())
+ app.use(createDirectoryRouter())
+ return app
}
- it("requires user authentication", async () => {
- const app = makeApp();
- await request(app).get("/directory/search?q=alice").expect(401);
- expect(directoryServiceMock.searchDirectory).not.toHaveBeenCalled();
- });
+ it('requires user authentication', async () => {
+ const app = makeApp()
+ await request(app).get('/directory/search?q=alice').expect(401)
+ expect(directoryServiceMock.searchDirectory).not.toHaveBeenCalled()
+ })
- it("rejects bad bearer token", async () => {
- controlApiMock.verifyToken.mockReturnValueOnce(null);
- const app = makeApp();
+ it('rejects bad bearer token', async () => {
+ controlApiMock.verifyToken.mockReturnValueOnce(null)
+ const app = makeApp()
- await request(app).get("/directory/search?q=alice").set("authorization", "Bearer bad-token").expect(401);
- expect(directoryServiceMock.searchDirectory).not.toHaveBeenCalled();
- });
+ await request(app)
+ .get('/directory/search?q=alice')
+ .set('authorization', 'Bearer bad-token')
+ .expect(401)
+ expect(directoryServiceMock.searchDirectory).not.toHaveBeenCalled()
+ })
- it("returns empty items when query is blank", async () => {
- controlApiMock.verifyToken.mockReturnValueOnce(claims);
- const app = makeApp();
+ it('returns empty items when query is blank', async () => {
+ controlApiMock.verifyToken.mockReturnValueOnce(claims)
+ const app = makeApp()
- const response = await request(app).get("/directory/search?q=").set("authorization", "Bearer good-token").expect(200);
+ const response = await request(app)
+ .get('/directory/search?q=')
+ .set('authorization', 'Bearer good-token')
+ .expect(200)
- expect(response.body).toEqual({ items: [] });
- expect(directoryServiceMock.searchDirectory).not.toHaveBeenCalled();
- });
+ expect(response.body).toEqual({ items: [] })
+ expect(directoryServiceMock.searchDirectory).not.toHaveBeenCalled()
+ })
- it("searches using authenticated teamId", async () => {
- controlApiMock.verifyToken.mockReturnValueOnce(claims);
- directoryServiceMock.searchDirectory.mockResolvedValueOnce({ items: [{ id: "u1" }] });
- const app = makeApp();
+ it('searches using authenticated teamId', async () => {
+ controlApiMock.verifyToken.mockReturnValueOnce(claims)
+ directoryServiceMock.searchDirectory.mockResolvedValueOnce({ items: [{ id: 'u1' }] })
+ const app = makeApp()
const response = await request(app)
- .get("/directory/search?q=alice&teamId=other-team")
- .set("authorization", "Bearer good-token")
- .expect(200);
-
- expect(response.body).toEqual({ items: [{ id: "u1" }] });
- expect(directoryServiceMock.searchDirectory).toHaveBeenCalledWith("team-1", "alice", "good-token");
- });
-});
+ .get('/directory/search?q=alice&teamId=other-team')
+ .set('authorization', 'Bearer good-token')
+ .expect(200)
+
+ expect(response.body).toEqual({ items: [{ id: 'u1' }] })
+ expect(directoryServiceMock.searchDirectory).toHaveBeenCalledWith(
+ 'team-1',
+ 'alice',
+ 'good-token'
+ )
+ })
+})
diff --git a/external-rest-api/test/services.rpc.test.ts b/external-rest-api/test/services.rpc.test.ts
index 93da81a71..b188b82ce 100644
--- a/external-rest-api/test/services.rpc.test.ts
+++ b/external-rest-api/test/services.rpc.test.ts
@@ -50,6 +50,8 @@ describe('rpcService.issueRpcAccessToken', () => {
})
)
- await expect(issueRpcAccessToken('session', ['host:message:invoke'], ['pro-agent'])).rejects.toThrow()
+ await expect(
+ issueRpcAccessToken('session', ['host:message:invoke'], ['pro-agent'])
+ ).rejects.toThrow()
})
})
diff --git a/external-rest-api/vitest.config.ts b/external-rest-api/vitest.config.ts
index 37b473f54..8141ade9e 100644
--- a/external-rest-api/vitest.config.ts
+++ b/external-rest-api/vitest.config.ts
@@ -1,8 +1,8 @@
-import { defineConfig } from "vitest/config";
+import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
- include: ["src/**/*.test.ts", "src/**/__tests__/**/*.ts", "test/**/*.test.ts"],
- exclude: ["dist/**", "node_modules/**"],
+ include: ['src/**/*.test.ts', 'src/**/__tests__/**/*.ts', 'test/**/*.test.ts'],
+ exclude: ['dist/**', 'node_modules/**'],
},
-});
+})
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 9a3aff834..21274e92f 100644
--- a/host-context-controller/package-lock.json
+++ b/host-context-controller/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-host-context-controller",
- "version": "0.1.160",
+ "version": "0.1.161",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.160",
+ "version": "0.1.161",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/host-context-controller/package.json b/host-context-controller/package.json
index 51dc2ded1..cdd4381c3 100644
--- a/host-context-controller/package.json
+++ b/host-context-controller/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-host-context-controller",
- "version": "0.1.160",
+ "version": "0.1.161",
"description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API",
"main": "dist/main.js",
"engines": {
diff --git a/host-context-controller/vitest.config.ts b/host-context-controller/vitest.config.ts
index b6b83c3bf..5674e9764 100644
--- a/host-context-controller/vitest.config.ts
+++ b/host-context-controller/vitest.config.ts
@@ -1,9 +1,9 @@
-import { defineConfig } from "vitest/config";
+import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
globals: false,
- environment: "node",
- exclude: ["dist/**", "node_modules/**"],
+ environment: 'node',
+ exclude: ['dist/**', 'node_modules/**'],
},
-});
+})
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index acd624289..d9881a75c 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.220",
+ "version": "0.1.221",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.220",
+ "version": "0.1.221",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 576ac3fa7..97668f9f5 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.220",
+ "version": "0.1.221",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/__tests__/activityHub.test.ts b/mcp-host/src/__tests__/activityHub.test.ts
index 502d25701..63614cfcf 100644
--- a/mcp-host/src/__tests__/activityHub.test.ts
+++ b/mcp-host/src/__tests__/activityHub.test.ts
@@ -1,75 +1,75 @@
-import { describe, expect, it } from "vitest";
-import { HostActivityHub } from "../activityHub";
+import { describe, expect, it } from 'vitest'
+import { HostActivityHub } from '../activityHub'
-describe("HostActivityHub", () => {
- it("creates required event fields with monotonic eventId", () => {
- const hub = new HostActivityHub(10, 4096);
+describe('HostActivityHub', () => {
+ it('creates required event fields with monotonic eventId', () => {
+ const hub = new HostActivityHub(10, 4096)
const first = hub.publish({
- hostRef: "chatllm",
- type: "task.queued",
- title: "Task queued",
- severity: "info",
- meta: { queueDepth: 1 }
- });
+ hostRef: 'chatllm',
+ type: 'task.queued',
+ title: 'Task queued',
+ severity: 'info',
+ meta: { queueDepth: 1 },
+ })
const second = hub.publish({
- hostRef: "chatllm",
- type: "task.started",
- title: "Task started",
- severity: "info"
- });
+ hostRef: 'chatllm',
+ type: 'task.started',
+ title: 'Task started',
+ severity: 'info',
+ })
- expect(first.version).toBe("1.0");
- expect(first.hostRef).toBe("chatllm");
- expect(first.ts).toMatch(/^\d{4}-\d{2}-\d{2}T/);
- expect(first.eventId < second.eventId).toBe(true);
- });
+ expect(first.version).toBe('1.0')
+ expect(first.hostRef).toBe('chatllm')
+ expect(first.ts).toMatch(/^\d{4}-\d{2}-\d{2}T/)
+ expect(first.eventId < second.eventId).toBe(true)
+ })
- it("enforces redactions and max event bytes", () => {
- const hub = new HostActivityHub(10, 220);
+ it('enforces redactions and max event bytes', () => {
+ const hub = new HostActivityHub(10, 220)
const event = hub.publish({
- hostRef: "chatllm",
- type: "task.failed",
- title: "Task failed",
- severity: "error",
+ hostRef: 'chatllm',
+ type: 'task.failed',
+ title: 'Task failed',
+ severity: 'error',
meta: {
- reasoning: "must-not-leak",
- prompt: "must-not-leak",
- small: "ok",
- huge: "x".repeat(1000)
- }
- });
+ reasoning: 'must-not-leak',
+ prompt: 'must-not-leak',
+ small: 'ok',
+ huge: 'x'.repeat(1000),
+ },
+ })
- expect(event.meta.reasoning).toBeUndefined();
- expect(event.meta.prompt).toBeUndefined();
- expect(event.redactions).toContain("reasoning");
- expect(event.redactions).toContain("prompt");
- expect(event.redactions).toContain("meta");
- });
+ expect(event.meta.reasoning).toBeUndefined()
+ expect(event.meta.prompt).toBeUndefined()
+ expect(event.redactions).toContain('reasoning')
+ expect(event.redactions).toContain('prompt')
+ expect(event.redactions).toContain('meta')
+ })
- it("supports snapshot pagination by limit and sinceEventId", () => {
- const hub = new HostActivityHub(20, 2048);
+ it('supports snapshot pagination by limit and sinceEventId', () => {
+ const hub = new HostActivityHub(20, 2048)
const e1 = hub.publish({
- hostRef: "chatllm",
- type: "task.queued",
- title: "queued",
- severity: "info"
- });
+ hostRef: 'chatllm',
+ type: 'task.queued',
+ title: 'queued',
+ severity: 'info',
+ })
hub.publish({
- hostRef: "chatllm",
- type: "task.started",
- title: "started",
- severity: "info"
- });
+ hostRef: 'chatllm',
+ type: 'task.started',
+ title: 'started',
+ severity: 'info',
+ })
const e3 = hub.publish({
- hostRef: "chatllm",
- type: "task.completed",
- title: "completed",
- severity: "info"
- });
+ hostRef: 'chatllm',
+ type: 'task.completed',
+ title: 'completed',
+ severity: 'info',
+ })
- const snap = hub.snapshot("chatllm", 10, e1.eventId);
- expect(snap.items).toHaveLength(2);
- expect(snap.items[1]?.eventId).toBe(e3.eventId);
- expect(snap.nextCursor).toBe(e3.eventId);
- });
-});
+ const snap = hub.snapshot('chatllm', 10, e1.eventId)
+ expect(snap.items).toHaveLength(2)
+ expect(snap.items[1]?.eventId).toBe(e3.eventId)
+ expect(snap.nextCursor).toBe(e3.eventId)
+ })
+})
diff --git a/mcp-host/src/__tests__/integration/errorFlow.test.ts b/mcp-host/src/__tests__/integration/errorFlow.test.ts
index eef97147d..339ce402b 100644
--- a/mcp-host/src/__tests__/integration/errorFlow.test.ts
+++ b/mcp-host/src/__tests__/integration/errorFlow.test.ts
@@ -1,10 +1,10 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { AgentStateMachine } from '../../agent'
import { LlmErrorCode } from '../../core/errors'
+import { NoopSafety } from '../../core/safety/__tests__/noopSafety.js'
import { TaskLifecycle } from '../../lifecycle/taskLifecycle'
import type { ClassifiedError, SingleTurnProvider } from '../../llm'
import { SseProgressReporter, progressReporterRegistry } from '../../progress/sseProgressReporter'
-import { NoopSafety } from '../../core/safety/__tests__/noopSafety.js'
import type { ProgressEvent } from '../../progress/types'
import { MessageQueue } from '../../queue'
diff --git a/mcp-host/src/__tests__/server.bodysize.test.ts b/mcp-host/src/__tests__/server.bodysize.test.ts
index 805f65ac5..00568b228 100644
--- a/mcp-host/src/__tests__/server.bodysize.test.ts
+++ b/mcp-host/src/__tests__/server.bodysize.test.ts
@@ -4,66 +4,65 @@
*
* Uses real listening server + fetch (same pattern as authMiddleware.test.ts).
*/
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import express from 'express'
+import type { Server } from 'http'
+import type { AddressInfo } from 'net'
-import { describe, it, expect, beforeAll, afterAll } from "vitest";
-import express from "express";
-import type { AddressInfo } from "net";
-import type { Server } from "http";
+const MAX_BODY_BYTES = 1 * 1024 * 1024 // 1 MB (matches RPCServer express.json({ limit: "1mb" }))
-const MAX_BODY_BYTES = 1 * 1024 * 1024; // 1 MB (matches RPCServer express.json({ limit: "1mb" }))
-
-let baseUrl: string;
-let server: Server;
+let baseUrl: string
+let server: Server
beforeAll(() => {
- const app = express();
- app.use(express.json({ limit: "1mb" }));
- app.post("/test", (req, res) => {
- res.status(200).json({ received: true });
- });
+ const app = express()
+ app.use(express.json({ limit: '1mb' }))
+ app.post('/test', (req, res) => {
+ res.status(200).json({ received: true })
+ })
- return new Promise<void>((resolve) => {
+ return new Promise<void>(resolve => {
server = app.listen(0, () => {
- const addr = server.address() as AddressInfo;
- baseUrl = `http://127.0.0.1:${addr.port}`;
- resolve();
- });
- });
-});
+ const addr = server.address() as AddressInfo
+ baseUrl = `http://127.0.0.1:${addr.port}`
+ resolve()
+ })
+ })
+})
afterAll(() => {
- server.close();
-});
+ server.close()
+})
-describe("server body size limit (1 MB)", () => {
- it("accepts body under MAX_BODY_BYTES (100 bytes)", async () => {
- const payload = JSON.stringify({ data: "x".repeat(50) });
+describe('server body size limit (1 MB)', () => {
+ it('accepts body under MAX_BODY_BYTES (100 bytes)', async () => {
+ const payload = JSON.stringify({ data: 'x'.repeat(50) })
const res = await fetch(`${baseUrl}/test`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
body: payload,
- });
- expect(res.status).toBe(200);
- });
+ })
+ expect(res.status).toBe(200)
+ })
- it("rejects body over MAX_BODY_BYTES (>1MB) with 413", async () => {
+ it('rejects body over MAX_BODY_BYTES (>1MB) with 413', async () => {
// Build a JSON payload slightly over 1 MB
- const bigPayload = JSON.stringify({ data: "x".repeat(MAX_BODY_BYTES + 1000) });
+ const bigPayload = JSON.stringify({ data: 'x'.repeat(MAX_BODY_BYTES + 1000) })
const res = await fetch(`${baseUrl}/test`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
body: bigPayload,
- });
- expect(res.status).toBe(413);
- });
+ })
+ expect(res.status).toBe(413)
+ })
- it("accepts body at exactly 512 KB (well under limit)", async () => {
- const halfMbPayload = JSON.stringify({ data: "a".repeat(512 * 1024) });
+ it('accepts body at exactly 512 KB (well under limit)', async () => {
+ const halfMbPayload = JSON.stringify({ data: 'a'.repeat(512 * 1024) })
const res = await fetch(`${baseUrl}/test`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
body: halfMbPayload,
- });
- expect(res.status).toBe(200);
- });
-});
+ })
+ expect(res.status).toBe(200)
+ })
+})
diff --git a/mcp-host/src/__tests__/taskResultIdempotent.test.ts b/mcp-host/src/__tests__/taskResultIdempotent.test.ts
index 29941e261..7083f224e 100644
--- a/mcp-host/src/__tests__/taskResultIdempotent.test.ts
+++ b/mcp-host/src/__tests__/taskResultIdempotent.test.ts
@@ -1,87 +1,87 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { ResultStore } from "../resultStore";
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { ResultStore } from '../resultStore'
interface TaskEntry {
- response: string;
- storedAt: number;
+ response: string
+ storedAt: number
}
function createStore(ttlMs: number = 5000): ResultStore<TaskEntry> {
- return new ResultStore<TaskEntry>(ttlMs, (e) => e.storedAt);
+ return new ResultStore<TaskEntry>(ttlMs, e => e.storedAt)
}
-describe("TaskResult idempotent read — get() vs getAndDelete()", () => {
+describe('TaskResult idempotent read — get() vs getAndDelete()', () => {
beforeEach(() => {
- vi.useFakeTimers();
- });
+ vi.useFakeTimers()
+ })
afterEach(() => {
- vi.useRealTimers();
- });
+ vi.useRealTimers()
+ })
- it("task result persists after first read via get()", () => {
- const store = createStore();
- const now = Date.now();
- store.set("task-1", { response: "Hello world", storedAt: now });
+ it('task result persists after first read via get()', () => {
+ const store = createStore()
+ const now = Date.now()
+ store.set('task-1', { response: 'Hello world', storedAt: now })
// First read — result should be present
- const first = store.get("task-1");
- expect(first).toBeDefined();
- expect(first!.response).toBe("Hello world");
+ const first = store.get('task-1')
+ expect(first).toBeDefined()
+ expect(first!.response).toBe('Hello world')
// Second read — result should STILL be present (idempotent)
- const second = store.get("task-1");
- expect(second).toBeDefined();
- expect(second!.response).toBe("Hello world");
+ const second = store.get('task-1')
+ expect(second).toBeDefined()
+ expect(second!.response).toBe('Hello world')
// Third read — still there
- const third = store.get("task-1");
- expect(third).toBeDefined();
- expect(third!.response).toBe("Hello world");
- });
+ const third = store.get('task-1')
+ expect(third).toBeDefined()
+ expect(third!.response).toBe('Hello world')
+ })
- it("task result is consumed by getAndDelete() (non-idempotent)", () => {
- const store = createStore();
- const now = Date.now();
- store.set("task-2", { response: "One-time result", storedAt: now });
+ it('task result is consumed by getAndDelete() (non-idempotent)', () => {
+ const store = createStore()
+ const now = Date.now()
+ store.set('task-2', { response: 'One-time result', storedAt: now })
// getAndDelete consumes the entry
- const result = store.getAndDelete("task-2");
- expect(result).toBeDefined();
- expect(result!.response).toBe("One-time result");
+ const result = store.getAndDelete('task-2')
+ expect(result).toBeDefined()
+ expect(result!.response).toBe('One-time result')
// Subsequent read returns undefined — entry was deleted
- expect(store.get("task-2")).toBeUndefined();
- expect(store.getAndDelete("task-2")).toBeUndefined();
- });
+ expect(store.get('task-2')).toBeUndefined()
+ expect(store.getAndDelete('task-2')).toBeUndefined()
+ })
- it("task result expires after TTL even with get() (no infinite retention)", () => {
- const ttlMs = 300_000; // 5 minutes
- const store = createStore(ttlMs);
- const now = Date.now();
- store.set("task-3", { response: "Expires eventually", storedAt: now });
+ it('task result expires after TTL even with get() (no infinite retention)', () => {
+ const ttlMs = 300_000 // 5 minutes
+ const store = createStore(ttlMs)
+ const now = Date.now()
+ store.set('task-3', { response: 'Expires eventually', storedAt: now })
// Within TTL — present
- vi.advanceTimersByTime(ttlMs - 1000);
- expect(store.get("task-3")).toBeDefined();
+ vi.advanceTimersByTime(ttlMs - 1000)
+ expect(store.get('task-3')).toBeDefined()
// Past TTL — evicted by cleanup
- vi.advanceTimersByTime(2000);
- expect(store.get("task-3")).toBeUndefined();
- });
+ vi.advanceTimersByTime(2000)
+ expect(store.get('task-3')).toBeUndefined()
+ })
- it("multiple reads within TTL all return the same result", () => {
- const ttlMs = 300_000;
- const store = createStore(ttlMs);
- const now = Date.now();
- store.set("task-4", { response: "Persistent", storedAt: now });
+ it('multiple reads within TTL all return the same result', () => {
+ const ttlMs = 300_000
+ const store = createStore(ttlMs)
+ const now = Date.now()
+ store.set('task-4', { response: 'Persistent', storedAt: now })
// Read at various points within the TTL window
for (let i = 0; i < 10; i++) {
- vi.advanceTimersByTime(20_000); // 20s increments (total 200s, within 300s TTL)
- const result = store.get("task-4");
- expect(result).toBeDefined();
- expect(result!.response).toBe("Persistent");
+ vi.advanceTimersByTime(20_000) // 20s increments (total 200s, within 300s TTL)
+ const result = store.get('task-4')
+ expect(result).toBeDefined()
+ expect(result!.response).toBe('Persistent')
}
- });
-});
+ })
+})
diff --git a/mcp-host/src/activityHub.ts b/mcp-host/src/activityHub.ts
index c776d539a..7dc240437 100644
--- a/mcp-host/src/activityHub.ts
+++ b/mcp-host/src/activityHub.ts
@@ -2,55 +2,58 @@ import type {
HostActivityEvent,
HostActivitySeverity,
HostActivitySnapshotResponse,
- HostActivityType
-} from "./server/types";
+ HostActivityType,
+} from './server/types'
type PublishInput = {
- hostRef: string;
- taskId?: string;
- type: HostActivityType;
- title: string;
- severity: HostActivitySeverity;
- meta?: Record<string, unknown>;
-};
+ hostRef: string
+ taskId?: string
+ type: HostActivityType
+ title: string
+ severity: HostActivitySeverity
+ meta?: Record<string, unknown>
+}
-type Subscriber = (event: HostActivityEvent) => void;
+type Subscriber = (event: HostActivityEvent) => void
const DISALLOWED_META_KEYS = new Set([
- "reasoning",
- "thought",
- "chainofthought",
- "cot",
- "prompt",
- "response",
- "content",
- "stack",
- "token",
- "authorization",
- "apikey",
- "secret",
- "internalurl",
- "url"
-]);
+ 'reasoning',
+ 'thought',
+ 'chainofthought',
+ 'cot',
+ 'prompt',
+ 'response',
+ 'content',
+ 'stack',
+ 'token',
+ 'authorization',
+ 'apikey',
+ 'secret',
+ 'internalurl',
+ 'url',
+])
-function redactMeta(input: Record<string, unknown>): { meta: Record<string, unknown>; redactions: string[] } {
- const redactions: string[] = [];
- const out: Record<string, unknown> = {};
+function redactMeta(input: Record<string, unknown>): {
+ meta: Record<string, unknown>
+ redactions: string[]
+} {
+ const redactions: string[] = []
+ const out: Record<string, unknown> = {}
for (const [key, value] of Object.entries(input)) {
- const normalized = key.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
+ const normalized = key.replace(/[^a-zA-Z0-9]/g, '').toLowerCase()
if (DISALLOWED_META_KEYS.has(normalized)) {
- redactions.push(key);
- continue;
+ redactions.push(key)
+ continue
}
- out[key] = value;
+ out[key] = value
}
- return { meta: out, redactions };
+ return { meta: out, redactions }
}
export class HostActivityHub {
- private readonly buffer: HostActivityEvent[] = [];
- private readonly subscribers = new Set<Subscriber>();
- private eventCounter = 0;
+ private readonly buffer: HostActivityEvent[] = []
+ private readonly subscribers = new Set<Subscriber>()
+ private eventCounter = 0
constructor(
private readonly maxBufferSize: number,
@@ -58,11 +61,11 @@ export class HostActivityHub {
) {}
publish(input: PublishInput): HostActivityEvent {
- const safeTitle = String(input.title || "Host activity").trim() || "Host activity";
- const { meta, redactions } = redactMeta(input.meta || {});
- const eventId = `evt_${String(++this.eventCounter).padStart(10, "0")}`;
+ const safeTitle = String(input.title || 'Host activity').trim() || 'Host activity'
+ const { meta, redactions } = redactMeta(input.meta || {})
+ const eventId = `evt_${String(++this.eventCounter).padStart(10, '0')}`
const event: HostActivityEvent = {
- version: "1.0",
+ version: '1.0',
eventId,
hostRef: input.hostRef,
ts: new Date().toISOString(),
@@ -71,51 +74,51 @@ export class HostActivityHub {
title: safeTitle.slice(0, 180),
severity: input.severity,
meta,
- redactions
- };
+ redactions,
+ }
- const serialized = JSON.stringify(event);
- if (Buffer.byteLength(serialized, "utf8") > this.maxEventBytes) {
- event.meta = {};
- event.redactions = Array.from(new Set([...event.redactions, "meta"]));
+ const serialized = JSON.stringify(event)
+ if (Buffer.byteLength(serialized, 'utf8') > this.maxEventBytes) {
+ event.meta = {}
+ event.redactions = Array.from(new Set([...event.redactions, 'meta']))
}
- this.buffer.push(event);
+ this.buffer.push(event)
if (this.buffer.length > this.maxBufferSize) {
- this.buffer.splice(0, this.buffer.length - this.maxBufferSize);
+ this.buffer.splice(0, this.buffer.length - this.maxBufferSize)
}
for (const subscriber of this.subscribers) {
- subscriber(event);
+ subscriber(event)
}
- return event;
+ return event
}
snapshot(hostRef: string, limit: number, sinceEventId?: string): HostActivitySnapshotResponse {
- const max = Math.min(Math.max(Number(limit) || 50, 1), 200);
- let minId = 0;
+ const max = Math.min(Math.max(Number(limit) || 50, 1), 200)
+ let minId = 0
if (sinceEventId) {
- const match = sinceEventId.match(/^evt_(\d+)$/);
- if (match) minId = Number(match[1]);
+ const match = sinceEventId.match(/^evt_(\d+)$/)
+ if (match) minId = Number(match[1])
}
- const filtered = this.buffer.filter((entry) => {
- const match = entry.eventId.match(/^evt_(\d+)$/);
- const num = match ? Number(match[1]) : 0;
- return num > minId;
- });
- const items = filtered.slice(-max);
+ const filtered = this.buffer.filter(entry => {
+ const match = entry.eventId.match(/^evt_(\d+)$/)
+ const num = match ? Number(match[1]) : 0
+ return num > minId
+ })
+ const items = filtered.slice(-max)
return {
hostRef,
- version: "1.0",
+ version: '1.0',
items,
- nextCursor: items.length ? items[items.length - 1]!.eventId : null
- };
+ nextCursor: items.length ? items[items.length - 1]!.eventId : null,
+ }
}
subscribe(handler: Subscriber): () => void {
- this.subscribers.add(handler);
+ this.subscribers.add(handler)
return () => {
- this.subscribers.delete(handler);
- };
+ this.subscribers.delete(handler)
+ }
}
}
diff --git a/mcp-host/src/agent/__tests__/stateMachineFailure.test.ts b/mcp-host/src/agent/__tests__/stateMachineFailure.test.ts
index 39216a660..f69f402c6 100644
--- a/mcp-host/src/agent/__tests__/stateMachineFailure.test.ts
+++ b/mcp-host/src/agent/__tests__/stateMachineFailure.test.ts
@@ -1,7 +1,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
+import { NoopSafety } from '../../core/safety/__tests__/noopSafety.js'
import { TaskLifecycle } from '../../lifecycle/taskLifecycle'
import { SseProgressReporter, progressReporterRegistry } from '../../progress/sseProgressReporter'
-import { NoopSafety } from '../../core/safety/__tests__/noopSafety.js'
import { MessageQueue } from '../../queue'
import type { TaskError } from '../../queue/types'
import { AgentStateMachine } from '../stateMachine'
diff --git a/mcp-host/src/capabilities/getCapabilitiesTool.test.ts b/mcp-host/src/capabilities/getCapabilitiesTool.test.ts
index 07cc96d7c..0226df384 100644
--- a/mcp-host/src/capabilities/getCapabilitiesTool.test.ts
+++ b/mcp-host/src/capabilities/getCapabilitiesTool.test.ts
@@ -1,9 +1,6 @@
import { describe, expect, it } from 'vitest'
import { CAPABILITY_MAP } from './capabilityMap'
-import {
- buildGetCapabilitiesResponse,
- createGetCapabilitiesTool,
-} from './getCapabilitiesTool'
+import { buildGetCapabilitiesResponse, createGetCapabilitiesTool } from './getCapabilitiesTool'
function envFrom(map: Record<string, string>): (key: string) => string | undefined {
return key => map[key]
diff --git a/mcp-host/src/core/__tests__/types.test.ts b/mcp-host/src/core/__tests__/types.test.ts
index 8e7b438fe..8fa0aebe4 100644
--- a/mcp-host/src/core/__tests__/types.test.ts
+++ b/mcp-host/src/core/__tests__/types.test.ts
@@ -1,159 +1,157 @@
-import { describe, it, expect } from "vitest";
+import { describe, expect, it } from 'vitest'
import {
- FinishReason,
+ type ChatMessage,
ConversationState,
+ FinishReason,
+ type LoopResult,
+ type PendingApproval,
type RespondResult,
type ToolCall,
- type PendingApproval,
- type LoopResult,
type ToolCompletionResponse,
- type ChatMessage,
-} from "../types";
+} from '../types'
-describe("FinishReason", () => {
- it("should have correct string values for JSON serialization", () => {
- expect(FinishReason.Stop).toBe("stop");
- expect(FinishReason.Length).toBe("length");
- expect(FinishReason.ToolUse).toBe("tool_use");
- expect(FinishReason.ContentFilter).toBe("content_filter");
- expect(FinishReason.Unknown).toBe("unknown");
- });
-});
+describe('FinishReason', () => {
+ it('should have correct string values for JSON serialization', () => {
+ expect(FinishReason.Stop).toBe('stop')
+ expect(FinishReason.Length).toBe('length')
+ expect(FinishReason.ToolUse).toBe('tool_use')
+ expect(FinishReason.ContentFilter).toBe('content_filter')
+ expect(FinishReason.Unknown).toBe('unknown')
+ })
+})
-describe("ConversationState", () => {
- it("should have correct string values", () => {
- expect(ConversationState.Idle).toBe("idle");
- expect(ConversationState.Processing).toBe("processing");
- expect(ConversationState.AwaitingApproval).toBe("awaiting_approval");
- });
+describe('ConversationState', () => {
+ it('should have correct string values', () => {
+ expect(ConversationState.Idle).toBe('idle')
+ expect(ConversationState.Processing).toBe('processing')
+ expect(ConversationState.AwaitingApproval).toBe('awaiting_approval')
+ })
- it("should have exactly 3 states (not more)", () => {
- const values = Object.values(ConversationState);
- expect(values).toHaveLength(3);
- });
-});
+ it('should have exactly 3 states (not more)', () => {
+ const values = Object.values(ConversationState)
+ expect(values).toHaveLength(3)
+ })
+})
-describe("RespondResult", () => {
+describe('RespondResult', () => {
it("should narrow to 'text' variant with content field", () => {
- const result: RespondResult = { type: "text", content: "Hello" };
- if (result.type === "text") {
- expect(result.content).toBe("Hello");
+ const result: RespondResult = { type: 'text', content: 'Hello' }
+ if (result.type === 'text') {
+ expect(result.content).toBe('Hello')
} else {
- throw new Error("Should have matched 'text'");
+ throw new Error("Should have matched 'text'")
}
- });
+ })
it("should narrow to 'tool_calls' variant with calls array", () => {
- const calls: ToolCall[] = [
- { id: "tc_1", name: "search", arguments: { query: "test" } },
- ];
- const result: RespondResult = { type: "tool_calls", calls };
- if (result.type === "tool_calls") {
- expect(result.calls).toHaveLength(1);
- expect(result.calls[0].name).toBe("search");
+ const calls: ToolCall[] = [{ id: 'tc_1', name: 'search', arguments: { query: 'test' } }]
+ const result: RespondResult = { type: 'tool_calls', calls }
+ if (result.type === 'tool_calls') {
+ expect(result.calls).toHaveLength(1)
+ expect(result.calls[0].name).toBe('search')
} else {
- throw new Error("Should have matched 'tool_calls'");
+ throw new Error("Should have matched 'tool_calls'")
}
- });
+ })
it("should narrow to 'need_approval' variant with PendingApproval", () => {
const approval: PendingApproval = {
- request_id: "req_1",
- tool_name: "shell_exec",
- parameters: { command: "ls" },
- description: "List files",
- tool_call_id: "tc_1",
+ request_id: 'req_1',
+ tool_name: 'shell_exec',
+ parameters: { command: 'ls' },
+ description: 'List files',
+ tool_call_id: 'tc_1',
context_snapshot: [],
- };
- const result: RespondResult = { type: "need_approval", approval };
- if (result.type === "need_approval") {
- expect(result.approval.tool_name).toBe("shell_exec");
- expect(result.approval.context_snapshot).toEqual([]);
+ }
+ const result: RespondResult = { type: 'need_approval', approval }
+ if (result.type === 'need_approval') {
+ expect(result.approval.tool_name).toBe('shell_exec')
+ expect(result.approval.context_snapshot).toEqual([])
} else {
- throw new Error("Should have matched 'need_approval'");
+ throw new Error("Should have matched 'need_approval'")
}
- });
+ })
it("should narrow to 'error' variant with Error instance", () => {
- const result: RespondResult = { type: "error", error: new Error("fail") };
- if (result.type === "error") {
- expect(result.error.message).toBe("fail");
+ const result: RespondResult = { type: 'error', error: new Error('fail') }
+ if (result.type === 'error') {
+ expect(result.error.message).toBe('fail')
} else {
- throw new Error("Should have matched 'error'");
+ throw new Error("Should have matched 'error'")
}
- });
-});
+ })
+})
-describe("LoopResult", () => {
- it("should represent a successful response with usage", () => {
+describe('LoopResult', () => {
+ it('should represent a successful response with usage', () => {
const result: LoopResult = {
- type: "response",
- content: "Done",
+ type: 'response',
+ content: 'Done',
usage: { input_tokens: 100, output_tokens: 50, total_tokens: 150 },
- };
- expect(result.type).toBe("response");
- if (result.type === "response") {
- expect(result.usage.total_tokens).toBe(150);
}
- });
+ expect(result.type).toBe('response')
+ if (result.type === 'response') {
+ expect(result.usage.total_tokens).toBe(150)
+ }
+ })
- it("should represent exhaustion with iteration count", () => {
+ it('should represent exhaustion with iteration count', () => {
const result: LoopResult = {
- type: "exhaustion",
- message: "Max iterations reached",
+ type: 'exhaustion',
+ message: 'Max iterations reached',
iterations: 10,
- };
- if (result.type === "exhaustion") {
- expect(result.iterations).toBe(10);
}
- });
-});
+ if (result.type === 'exhaustion') {
+ expect(result.iterations).toBe(10)
+ }
+ })
+})
-describe("ToolCompletionResponse", () => {
- it("should use null for tool_calls when no tools called (not empty array)", () => {
+describe('ToolCompletionResponse', () => {
+ it('should use null for tool_calls when no tools called (not empty array)', () => {
const response: ToolCompletionResponse = {
- content: "Hello",
+ content: 'Hello',
tool_calls: null,
usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 },
finish_reason: FinishReason.Stop,
- };
- expect(response.tool_calls).toBeNull();
- expect(response.tool_calls).not.toBeUndefined();
- expect(response.tool_calls).not.toEqual([]);
- });
-});
+ }
+ expect(response.tool_calls).toBeNull()
+ expect(response.tool_calls).not.toBeUndefined()
+ expect(response.tool_calls).not.toEqual([])
+ })
+})
-describe("ChatMessage", () => {
+describe('ChatMessage', () => {
it("should support 'tool' role with tool_call_id", () => {
const msg: ChatMessage = {
- role: "tool",
+ role: 'tool',
content: '{"result": "ok"}',
- tool_call_id: "tc_123",
- name: "search",
- };
- expect(msg.role).toBe("tool");
- expect(msg.tool_call_id).toBe("tc_123");
- });
+ tool_call_id: 'tc_123',
+ name: 'search',
+ }
+ expect(msg.role).toBe('tool')
+ expect(msg.tool_call_id).toBe('tc_123')
+ })
- it("should support assistant role with tool_calls array", () => {
+ it('should support assistant role with tool_calls array', () => {
const msg: ChatMessage = {
- role: "assistant",
+ role: 'assistant',
content: "I'll search for that.",
tool_calls: [
- { id: "tc_1", name: "search", arguments: { query: "test" } },
- { id: "tc_2", name: "read", arguments: { path: "/tmp" } },
+ { id: 'tc_1', name: 'search', arguments: { query: 'test' } },
+ { id: 'tc_2', name: 'read', arguments: { path: '/tmp' } },
],
- };
- expect(msg.tool_calls).toHaveLength(2);
- expect(msg.tool_calls![0].id).not.toBe(msg.tool_calls![1].id);
- });
+ }
+ expect(msg.tool_calls).toHaveLength(2)
+ expect(msg.tool_calls![0].id).not.toBe(msg.tool_calls![1].id)
+ })
- it("should use null (not undefined) for tool_calls when absent on assistant messages", () => {
+ it('should use null (not undefined) for tool_calls when absent on assistant messages', () => {
const msg: ChatMessage = {
- role: "assistant",
- content: "Just text",
+ role: 'assistant',
+ content: 'Just text',
tool_calls: null,
- };
- expect(msg.tool_calls).toBeNull();
- });
-});
+ }
+ expect(msg.tool_calls).toBeNull()
+ })
+})
diff --git a/mcp-host/src/core/adapters/__tests__/channelAndStorage.test.ts b/mcp-host/src/core/adapters/__tests__/channelAndStorage.test.ts
index bda107db4..1b715c318 100644
--- a/mcp-host/src/core/adapters/__tests__/channelAndStorage.test.ts
+++ b/mcp-host/src/core/adapters/__tests__/channelAndStorage.test.ts
@@ -1,56 +1,56 @@
-import { describe, it, expect } from "vitest";
-import { RpcChannelAdapter } from "../channelAdapter";
-import { InMemoryStorage } from "../storageAdapter";
-import { IncomingMessage, ConversationState } from "../../types";
+import { describe, expect, it } from 'vitest'
+import { ConversationState, IncomingMessage } from '../../types'
+import { RpcChannelAdapter } from '../channelAdapter'
+import { InMemoryStorage } from '../storageAdapter'
-describe("RpcChannelAdapter", () => {
- it("should yield pushed messages via receive()", async () => {
- const adapter = new RpcChannelAdapter();
+describe('RpcChannelAdapter', () => {
+ it('should yield pushed messages via receive()', async () => {
+ const adapter = new RpcChannelAdapter()
const msg: IncomingMessage = {
- id: "msg-1",
- channel: "telegram",
- user_id: "user-1",
- content: "Hello",
+ id: 'msg-1',
+ channel: 'telegram',
+ user_id: 'user-1',
+ content: 'Hello',
metadata: {},
received_at: new Date(),
- };
+ }
- adapter.pushMessage(msg);
+ adapter.pushMessage(msg)
// Consume one message from the async iterable
- const iterator = adapter.receive()[Symbol.asyncIterator]();
- const result = await iterator.next();
+ const iterator = adapter.receive()[Symbol.asyncIterator]()
+ const result = await iterator.next()
- expect(result.done).toBe(false);
- expect(result.value).toBe(msg);
- });
-});
+ expect(result.done).toBe(false)
+ expect(result.value).toBe(msg)
+ })
+})
-describe("InMemoryStorage", () => {
- it("should save and load conversations", async () => {
- const storage = new InMemoryStorage();
+describe('InMemoryStorage', () => {
+ it('should save and load conversations', async () => {
+ const storage = new InMemoryStorage()
const conversation = {
- id: "conv-1",
- user_id: "user-1",
+ id: 'conv-1',
+ user_id: 'user-1',
state: ConversationState.Idle,
turns: [],
auto_approved_tools: new Set<string>(),
created_at: new Date(),
updated_at: new Date(),
- };
+ }
- await storage.saveConversation(conversation);
- const loaded = await storage.loadConversation("conv-1");
+ await storage.saveConversation(conversation)
+ const loaded = await storage.loadConversation('conv-1')
- expect(loaded).toBe(conversation);
- });
+ expect(loaded).toBe(conversation)
+ })
- it("should return null for unknown conversation", async () => {
- const storage = new InMemoryStorage();
- const loaded = await storage.loadConversation("nonexistent");
+ it('should return null for unknown conversation', async () => {
+ const storage = new InMemoryStorage()
+ const loaded = await storage.loadConversation('nonexistent')
- expect(loaded).toBeNull();
- });
-});
+ expect(loaded).toBeNull()
+ })
+})
diff --git a/mcp-host/src/core/adapters/channelAdapter.ts b/mcp-host/src/core/adapters/channelAdapter.ts
index 6ae3f7297..55404db9f 100644
--- a/mcp-host/src/core/adapters/channelAdapter.ts
+++ b/mcp-host/src/core/adapters/channelAdapter.ts
@@ -1,5 +1,5 @@
-import { Channel } from "../interfaces";
-import { IncomingMessage, OutgoingResponse, StatusUpdate } from "../types";
+import { Channel } from '../interfaces'
+import { IncomingMessage, OutgoingResponse, StatusUpdate } from '../types'
/**
* Adapts the existing HTTP RPC interface to the spec's Channel interface.
@@ -12,8 +12,8 @@ import { IncomingMessage, OutgoingResponse, StatusUpdate } from "../types";
* - sendStatus(): logs status (no channel forwarding yet)
*/
export class RpcChannelAdapter implements Channel {
- private messageQueue: IncomingMessage[] = [];
- private resolvers: ((msg: IncomingMessage) => void)[] = [];
+ private messageQueue: IncomingMessage[] = []
+ private resolvers: ((msg: IncomingMessage) => void)[] = []
/**
* Push a message into the adapter (called by server.ts when
@@ -21,10 +21,10 @@ export class RpcChannelAdapter implements Channel {
*/
pushMessage(msg: IncomingMessage): void {
if (this.resolvers.length > 0) {
- const resolver = this.resolvers.shift()!;
- resolver(msg);
+ const resolver = this.resolvers.shift()!
+ resolver(msg)
} else {
- this.messageQueue.push(msg);
+ this.messageQueue.push(msg)
}
}
@@ -35,11 +35,11 @@ export class RpcChannelAdapter implements Channel {
async *receive(): AsyncIterable<IncomingMessage> {
while (true) {
if (this.messageQueue.length > 0) {
- yield this.messageQueue.shift()!;
+ yield this.messageQueue.shift()!
} else {
- yield new Promise<IncomingMessage>((resolve) => {
- this.resolvers.push(resolve);
- });
+ yield new Promise<IncomingMessage>(resolve => {
+ this.resolvers.push(resolve)
+ })
}
}
}
@@ -50,10 +50,7 @@ export class RpcChannelAdapter implements Channel {
* which was set when the message was enqueued.
* The actual response routing happens in the Agent Core.
*/
- async respond(
- _original: IncomingMessage,
- _response: OutgoingResponse,
- ): Promise<void> {
+ async respond(_original: IncomingMessage, _response: OutgoingResponse): Promise<void> {
// Handled by Task.responseCallback in AgentStateMachine.
// This method is a spec-compliance placeholder.
// The actual response path is:
@@ -61,8 +58,6 @@ export class RpcChannelAdapter implements Channel {
}
sendStatus(status: StatusUpdate): void {
- console.log(
- `[Channel] Status: ${status.type}${status.detail ? ` - ${status.detail}` : ""}`,
- );
+ console.log(`[Channel] Status: ${status.type}${status.detail ? ` - ${status.detail}` : ''}`)
}
}
diff --git a/mcp-host/src/core/adapters/index.ts b/mcp-host/src/core/adapters/index.ts
index 41fc102b0..c69a2e6fd 100644
--- a/mcp-host/src/core/adapters/index.ts
+++ b/mcp-host/src/core/adapters/index.ts
@@ -1,4 +1,4 @@
-export { LlmPortAdapter } from "./llmPortAdapter";
-export { McpToolRegistryAdapter, CompositeToolRegistry } from "./toolRegistryAdapter";
-export { RpcChannelAdapter } from "./channelAdapter";
-export { InMemoryStorage } from "./storageAdapter";
+export { LlmPortAdapter } from './llmPortAdapter'
+export { McpToolRegistryAdapter, CompositeToolRegistry } from './toolRegistryAdapter'
+export { RpcChannelAdapter } from './channelAdapter'
+export { InMemoryStorage } from './storageAdapter'
diff --git a/mcp-host/src/core/adapters/storageAdapter.ts b/mcp-host/src/core/adapters/storageAdapter.ts
index 532ecba32..96c1fa7fa 100644
--- a/mcp-host/src/core/adapters/storageAdapter.ts
+++ b/mcp-host/src/core/adapters/storageAdapter.ts
@@ -1,5 +1,5 @@
-import { Storage } from "../interfaces";
-import { Conversation } from "../types";
+import { Storage } from '../interfaces'
+import { Conversation } from '../types'
/**
* In-memory conversation storage.
@@ -11,22 +11,22 @@ import { Conversation } from "../types";
* - External database
*/
export class InMemoryStorage implements Storage {
- private conversations = new Map<string, Conversation>();
- private systemPrompt: string | null = null;
+ private conversations = new Map<string, Conversation>()
+ private systemPrompt: string | null = null
async loadConversation(id: string): Promise<Conversation | null> {
- return this.conversations.get(id) ?? null;
+ return this.conversations.get(id) ?? null
}
async saveConversation(conversation: Conversation): Promise<void> {
- this.conversations.set(conversation.id, conversation);
+ this.conversations.set(conversation.id, conversation)
}
async loadSystemPrompt(): Promise<string | null> {
- return this.systemPrompt;
+ return this.systemPrompt
}
setSystemPrompt(prompt: string): void {
- this.systemPrompt = prompt;
+ this.systemPrompt = prompt
}
}
diff --git a/mcp-host/src/core/extensions/__tests__/approvalResolver.test.ts b/mcp-host/src/core/extensions/__tests__/approvalResolver.test.ts
index 1c8459afd..a762f62a6 100644
--- a/mcp-host/src/core/extensions/__tests__/approvalResolver.test.ts
+++ b/mcp-host/src/core/extensions/__tests__/approvalResolver.test.ts
@@ -1,103 +1,103 @@
-import { describe, it, expect } from "vitest";
-import { ApprovalResolver } from "../approvalResolver";
-import type { ApprovalConfig } from "../approvalTypes";
+import { describe, expect, it } from 'vitest'
+import { ApprovalResolver } from '../approvalResolver'
+import type { ApprovalConfig } from '../approvalTypes'
-describe("ApprovalResolver", () => {
- const resolver = new ApprovalResolver();
+describe('ApprovalResolver', () => {
+ const resolver = new ApprovalResolver()
- it("should block channel users when policy is cli_only", () => {
+ it('should block channel users when policy is cli_only', () => {
const config: ApprovalConfig = {
- defaultPolicy: "cli_only",
+ defaultPolicy: 'cli_only',
channels: {
- telegram: { enabled: true, approvers: ["user-1"] },
+ telegram: { enabled: true, approvers: ['user-1'] },
},
- };
+ }
- expect(resolver.canUserApprove("user-1", "telegram", "chan-1", config)).toBe(false);
- });
+ expect(resolver.canUserApprove('user-1', 'telegram', 'chan-1', config)).toBe(false)
+ })
- it("should allow any user when policy is channel_users", () => {
+ it('should allow any user when policy is channel_users', () => {
const config: ApprovalConfig = {
- defaultPolicy: "channel_users",
+ defaultPolicy: 'channel_users',
channels: {
telegram: { enabled: true },
},
- };
+ }
- expect(resolver.canUserApprove("random-user", "telegram", "chan-1", config)).toBe(true);
- });
+ expect(resolver.canUserApprove('random-user', 'telegram', 'chan-1', config)).toBe(true)
+ })
- it("should allow listed user when policy is designated_approvers", () => {
+ it('should allow listed user when policy is designated_approvers', () => {
const config: ApprovalConfig = {
- defaultPolicy: "designated_approvers",
+ defaultPolicy: 'designated_approvers',
channels: {
- telegram: { enabled: true, approvers: ["user-1", "user-2"] },
+ telegram: { enabled: true, approvers: ['user-1', 'user-2'] },
},
- };
+ }
- expect(resolver.canUserApprove("user-1", "telegram", "chan-1", config)).toBe(true);
- expect(resolver.canUserApprove("user-2", "telegram", "chan-1", config)).toBe(true);
- });
+ expect(resolver.canUserApprove('user-1', 'telegram', 'chan-1', config)).toBe(true)
+ expect(resolver.canUserApprove('user-2', 'telegram', 'chan-1', config)).toBe(true)
+ })
- it("should block unlisted user when policy is designated_approvers", () => {
+ it('should block unlisted user when policy is designated_approvers', () => {
const config: ApprovalConfig = {
- defaultPolicy: "designated_approvers",
+ defaultPolicy: 'designated_approvers',
channels: {
- telegram: { enabled: true, approvers: ["user-1"] },
+ telegram: { enabled: true, approvers: ['user-1'] },
},
- };
+ }
- expect(resolver.canUserApprove("user-999", "telegram", "chan-1", config)).toBe(false);
- });
+ expect(resolver.canUserApprove('user-999', 'telegram', 'chan-1', config)).toBe(false)
+ })
- it("should block all users when channel is disabled", () => {
+ it('should block all users when channel is disabled', () => {
const config: ApprovalConfig = {
- defaultPolicy: "channel_users",
+ defaultPolicy: 'channel_users',
channels: {
telegram: { enabled: false },
},
- };
+ }
- expect(resolver.canUserApprove("user-1", "telegram", "chan-1", config)).toBe(false);
- });
+ expect(resolver.canUserApprove('user-1', 'telegram', 'chan-1', config)).toBe(false)
+ })
- it("should treat missing channel config as enabled (opt-out model)", () => {
+ it('should treat missing channel config as enabled (opt-out model)', () => {
const config: ApprovalConfig = {
- defaultPolicy: "channel_users",
+ defaultPolicy: 'channel_users',
channels: {},
- };
+ }
// Telegram not listed in channels -> treated as enabled
- expect(resolver.canUserApprove("user-1", "telegram", "chan-1", config)).toBe(true);
- });
+ expect(resolver.canUserApprove('user-1', 'telegram', 'chan-1', config)).toBe(true)
+ })
- it("should return false when no approval config is provided (default cli_only)", () => {
- expect(resolver.canUserApprove("user-1", "telegram", "chan-1", undefined)).toBe(false);
- });
+ it('should return false when no approval config is provided (default cli_only)', () => {
+ expect(resolver.canUserApprove('user-1', 'telegram', 'chan-1', undefined)).toBe(false)
+ })
- it("should block all when designated_approvers with empty approvers list", () => {
+ it('should block all when designated_approvers with empty approvers list', () => {
const config: ApprovalConfig = {
- defaultPolicy: "designated_approvers",
+ defaultPolicy: 'designated_approvers',
channels: {
telegram: { enabled: true, approvers: [] },
},
- };
+ }
- expect(resolver.canUserApprove("user-1", "telegram", "chan-1", config)).toBe(false);
- });
+ expect(resolver.canUserApprove('user-1', 'telegram', 'chan-1', config)).toBe(false)
+ })
- it("should always allow CLI users (channelType undefined) when config exists", () => {
+ it('should always allow CLI users (channelType undefined) when config exists', () => {
const config: ApprovalConfig = {
- defaultPolicy: "cli_only",
+ defaultPolicy: 'cli_only',
channels: {},
- };
+ }
// CLI users bypass all channel-level restrictions
- expect(resolver.canUserApprove("any-user", undefined, undefined, config)).toBe(true);
- });
+ expect(resolver.canUserApprove('any-user', undefined, undefined, config)).toBe(true)
+ })
- it("should deny CLI users when no config is provided", () => {
+ it('should deny CLI users when no config is provided', () => {
// Even CLI users are denied without any config (safest default)
- expect(resolver.canUserApprove("any-user", undefined, undefined, undefined)).toBe(false);
- });
-});
+ expect(resolver.canUserApprove('any-user', undefined, undefined, undefined)).toBe(false)
+ })
+})
diff --git a/mcp-host/src/core/extensions/__tests__/nudgeController.test.ts b/mcp-host/src/core/extensions/__tests__/nudgeController.test.ts
index 55a5bcc39..3d059e7bb 100644
--- a/mcp-host/src/core/extensions/__tests__/nudgeController.test.ts
+++ b/mcp-host/src/core/extensions/__tests__/nudgeController.test.ts
@@ -1,67 +1,67 @@
-import { describe, it, expect, beforeEach } from "vitest";
-import { NudgeController } from "../nudgeController";
-import { DefaultLoopController } from "../../orchestration/loopConfig";
+import { beforeEach, describe, expect, it } from 'vitest'
+import { DefaultLoopController } from '../../orchestration/loopConfig'
+import { NudgeController } from '../nudgeController'
-describe("NudgeController", () => {
- let delegate: DefaultLoopController;
- let controller: NudgeController;
+describe('NudgeController', () => {
+ let delegate: DefaultLoopController
+ let controller: NudgeController
beforeEach(() => {
- delegate = new DefaultLoopController();
- controller = new NudgeController(delegate, 3);
- });
+ delegate = new DefaultLoopController()
+ controller = new NudgeController(delegate, 3)
+ })
- it("should reject first text when no tools have been used (6.2a)", () => {
+ it('should reject first text when no tools have been used (6.2a)', () => {
// No tools executed, first text response -> reject
- expect(controller.shouldAccept("I think the answer is...", 0)).toBe(false);
- expect(controller.getNudgeCount()).toBe(0);
- });
+ expect(controller.shouldAccept('I think the answer is...', 0)).toBe(false)
+ expect(controller.getNudgeCount()).toBe(0)
+ })
- it("should inject nudge message when text is rejected (6.2a)", () => {
+ it('should inject nudge message when text is rejected (6.2a)', () => {
// Reject the text
- controller.shouldAccept("I think the answer is...", 0);
+ controller.shouldAccept('I think the answer is...', 0)
// Get the nudge message
- const nudge = controller.onTextRejected("I think the answer is...", 0);
- expect(nudge).not.toBeNull();
- expect(nudge!.role).toBe("user");
- expect(nudge!.content).toContain("tools available");
- expect(controller.getNudgeCount()).toBe(1);
- });
+ const nudge = controller.onTextRejected('I think the answer is...', 0)
+ expect(nudge).not.toBeNull()
+ expect(nudge!.role).toBe('user')
+ expect(nudge!.content).toContain('tools available')
+ expect(controller.getNudgeCount()).toBe(1)
+ })
- it("should accept text after maxNudges reached (Risk 6.2b)", () => {
+ it('should accept text after maxNudges reached (Risk 6.2b)', () => {
// Exhaust all nudges
for (let i = 0; i < 3; i++) {
- expect(controller.shouldAccept("text", i)).toBe(false);
- controller.onTextRejected("text", i);
+ expect(controller.shouldAccept('text', i)).toBe(false)
+ controller.onTextRejected('text', i)
}
// After 3 nudges, should accept
- expect(controller.getNudgeCount()).toBe(3);
- expect(controller.shouldAccept("final answer", 3)).toBe(true);
- });
+ expect(controller.getNudgeCount()).toBe(3)
+ expect(controller.shouldAccept('final answer', 3)).toBe(true)
+ })
- it("should accept text after tools have been executed (6.2c)", () => {
+ it('should accept text after tools have been executed (6.2c)', () => {
// Simulate a tool being called (beforeTool sets toolsExecutedInLoop)
- controller.beforeTool("my_tool", {});
- expect(controller.hasToolsExecuted()).toBe(true);
+ controller.beforeTool('my_tool', {})
+ expect(controller.hasToolsExecuted()).toBe(true)
// Now text should be accepted
- expect(controller.shouldAccept("Result from tool analysis...", 1)).toBe(true);
- });
+ expect(controller.shouldAccept('Result from tool analysis...', 1)).toBe(true)
+ })
- it("should start fresh when a new instance is created (replaces reset)", () => {
+ it('should start fresh when a new instance is created (replaces reset)', () => {
// Dirty up the state
- controller.beforeTool("my_tool", {});
- controller.onTextRejected("text", 0);
+ controller.beforeTool('my_tool', {})
+ controller.onTextRejected('text', 0)
- expect(controller.hasToolsExecuted()).toBe(true);
- expect(controller.getNudgeCount()).toBe(1);
+ expect(controller.hasToolsExecuted()).toBe(true)
+ expect(controller.getNudgeCount()).toBe(1)
// A new instance starts clean (no reset method needed)
- const fresh = new NudgeController(delegate, 3);
+ const fresh = new NudgeController(delegate, 3)
- expect(fresh.hasToolsExecuted()).toBe(false);
- expect(fresh.getNudgeCount()).toBe(0);
- });
-});
+ expect(fresh.hasToolsExecuted()).toBe(false)
+ expect(fresh.getNudgeCount()).toBe(0)
+ })
+})
diff --git a/mcp-host/src/core/extensions/approvalController.ts b/mcp-host/src/core/extensions/approvalController.ts
index 8e2cd8853..fd83add70 100644
--- a/mcp-host/src/core/extensions/approvalController.ts
+++ b/mcp-host/src/core/extensions/approvalController.ts
@@ -15,36 +15,29 @@
* Gate 2 (tool.requiresApproval() inside toolUseLoop) was REMOVED as part of
* the BUG-11 fix. All approval decisions now flow through this single gate.
*/
-
-import {
- LoopController,
-} from "../interfaces";
-import {
- ChatMessage,
- ToolDefinition,
- PendingApproval,
-} from "../types";
-import type { Conversation } from "../types";
-import { isMcpToolName, getMcpServerPrefix } from "./mcpApprovalGateController";
+import { LoopController } from '../interfaces'
+import { ChatMessage, PendingApproval, ToolDefinition } from '../types'
+import type { Conversation } from '../types'
+import { getMcpServerPrefix, isMcpToolName } from './mcpApprovalGateController'
/**
* Decorator that checks auto_approved_tools before delegating to base controller.
*/
export class ApprovalController implements LoopController {
- private readonly conversation: Conversation;
- private readonly delegate: LoopController;
+ private readonly conversation: Conversation
+ private readonly delegate: LoopController
constructor(conversation: Conversation, delegate: LoopController) {
- this.conversation = conversation;
- this.delegate = delegate;
+ this.conversation = conversation
+ this.delegate = delegate
}
shouldAccept(content: string, iteration: number): boolean {
- return this.delegate.shouldAccept(content, iteration);
+ return this.delegate.shouldAccept(content, iteration)
}
onTextRejected(content: string, iteration: number): ChatMessage | null {
- return this.delegate.onTextRejected(content, iteration);
+ return this.delegate.onTextRejected(content, iteration)
}
/**
@@ -59,22 +52,22 @@ export class ApprovalController implements LoopController {
*/
beforeTool(
toolName: string,
- params: Record<string, unknown>,
- ): "proceed" | "skip" | { type: "suspend"; approval: PendingApproval } {
+ params: Record<string, unknown>
+ ): 'proceed' | 'skip' | { type: 'suspend'; approval: PendingApproval } {
// "Approve once, run all" — user approved any tool in this turn, auto-approve rest
- if (this.conversation.auto_approved_tools.has("*")) {
- return "proceed";
+ if (this.conversation.auto_approved_tools.has('*')) {
+ return 'proceed'
}
// Check individual tool name
if (this.conversation.auto_approved_tools.has(toolName)) {
- return "proceed";
+ return 'proceed'
}
// Check MCP server-level approval (e.g., "airtable-server" approves all airtable-server__* tools)
- const serverPrefix = getMcpServerPrefix(toolName);
+ const serverPrefix = getMcpServerPrefix(toolName)
if (serverPrefix && this.conversation.auto_approved_tools.has(serverPrefix)) {
- return "proceed";
+ return 'proceed'
}
// One-shot: pending_approval was granted but not yet consumed
@@ -82,20 +75,18 @@ export class ApprovalController implements LoopController {
this.conversation.pending_approval &&
this.conversation.pending_approval.tool_name === toolName
) {
- this.conversation.pending_approval = undefined;
- return "proceed";
+ this.conversation.pending_approval = undefined
+ return 'proceed'
}
- return this.delegate.beforeTool(toolName, params);
+ return this.delegate.beforeTool(toolName, params)
}
onExhaustion(iteration: number): string {
- return this.delegate.onExhaustion(iteration);
+ return this.delegate.onExhaustion(iteration)
}
- async refreshTools(
- currentTools: ToolDefinition[],
- ): Promise<ToolDefinition[]> {
- return this.delegate.refreshTools(currentTools);
+ async refreshTools(currentTools: ToolDefinition[]): Promise<ToolDefinition[]> {
+ return this.delegate.refreshTools(currentTools)
}
}
diff --git a/mcp-host/src/core/extensions/approvalResolver.ts b/mcp-host/src/core/extensions/approvalResolver.ts
index cf552cb92..74781408e 100644
--- a/mcp-host/src/core/extensions/approvalResolver.ts
+++ b/mcp-host/src/core/extensions/approvalResolver.ts
@@ -10,8 +10,7 @@
* 4. Policy is channel_users -> true for any user
* 5. Policy is designated_approvers -> check approvers list
*/
-
-import type { ApprovalConfig } from "./approvalTypes";
+import type { ApprovalConfig } from './approvalTypes'
export class ApprovalResolver {
/**
@@ -27,55 +26,55 @@ export class ApprovalResolver {
userId: string,
channelType: string | undefined,
_channelId: string | undefined,
- config: ApprovalConfig | undefined,
+ config: ApprovalConfig | undefined
): boolean {
// 1. No config -> default to cli_only (safest)
if (!config) {
- return false;
+ return false
}
// CLI users (no channelType) always allowed -- they use /approve /deny endpoints directly
if (!channelType) {
- return true;
+ return true
}
// 2. Policy is cli_only -> block all channel users
- if (config.defaultPolicy === "cli_only") {
- return false;
+ if (config.defaultPolicy === 'cli_only') {
+ return false
}
// 3. Check channel-level enabled flag
- const channelKey = channelType as "telegram" | "email" | "slack";
- const channelConfig = config.channels[channelKey];
+ const channelKey = channelType as 'telegram' | 'email' | 'slack'
+ const channelConfig = config.channels[channelKey]
// If channel config exists and is explicitly disabled -> block
if (channelConfig && !channelConfig.enabled) {
- return false;
+ return false
}
// If channel config not specified -> treated as enabled (opt-out model)
// 4. Policy is channel_users -> any user can approve
- if (config.defaultPolicy === "channel_users") {
- return true;
+ if (config.defaultPolicy === 'channel_users') {
+ return true
}
// 5. Policy is designated_approvers -> check approvers list
- if (config.defaultPolicy === "designated_approvers") {
+ if (config.defaultPolicy === 'designated_approvers') {
if (!channelConfig || !channelConfig.approvers) {
// No approvers list defined -> block all
- return false;
+ return false
}
if (channelConfig.approvers.length === 0) {
// Empty approvers list -> block all
- return false;
+ return false
}
- return channelConfig.approvers.includes(userId);
+ return channelConfig.approvers.includes(userId)
}
// Unknown policy -> block by default
- return false;
+ return false
}
}
diff --git a/mcp-host/src/core/extensions/nudgeController.ts b/mcp-host/src/core/extensions/nudgeController.ts
index 5ca682355..75609ab18 100644
--- a/mcp-host/src/core/extensions/nudgeController.ts
+++ b/mcp-host/src/core/extensions/nudgeController.ts
@@ -14,24 +14,19 @@
* - After maxNudges: accept whatever text the LLM returns (safety valve)
* - After any tool is called: accept text responses (nudge served its purpose)
*/
-
-import { LoopController } from "../interfaces";
-import {
- ChatMessage,
- ToolDefinition,
- PendingApproval,
-} from "../types";
+import { LoopController } from '../interfaces'
+import { ChatMessage, PendingApproval, ToolDefinition } from '../types'
export class NudgeController implements LoopController {
- private readonly delegate: LoopController;
- private readonly maxNudges: number;
+ private readonly delegate: LoopController
+ private readonly maxNudges: number
- private toolsExecutedInLoop: boolean = false;
- private nudgeCount: number = 0;
+ private toolsExecutedInLoop: boolean = false
+ private nudgeCount: number = 0
constructor(delegate: LoopController, maxNudges: number = 3) {
- this.delegate = delegate;
- this.maxNudges = maxNudges;
+ this.delegate = delegate
+ this.maxNudges = maxNudges
}
/**
@@ -41,30 +36,30 @@ export class NudgeController implements LoopController {
shouldAccept(content: string, iteration: number): boolean {
// If tools were used, accept whatever the LLM says
if (this.toolsExecutedInLoop) {
- return this.delegate.shouldAccept(content, iteration);
+ return this.delegate.shouldAccept(content, iteration)
}
// Safety valve: if we've nudged enough, accept the text
if (this.nudgeCount >= this.maxNudges) {
- return this.delegate.shouldAccept(content, iteration);
+ return this.delegate.shouldAccept(content, iteration)
}
// No tools used and under max nudges -> reject
- return false;
+ return false
}
/**
* When text is rejected, inject a nudge message.
*/
onTextRejected(content: string, iteration: number): ChatMessage | null {
- this.nudgeCount++;
+ this.nudgeCount++
return {
- role: "user",
+ role: 'user',
content:
- "You have tools available. Please use the appropriate tool(s) to answer the question " +
- "rather than responding from memory alone. Check the available tools and try again.",
- };
+ 'You have tools available. Please use the appropriate tool(s) to answer the question ' +
+ 'rather than responding from memory alone. Check the available tools and try again.',
+ }
}
/**
@@ -72,29 +67,27 @@ export class NudgeController implements LoopController {
*/
beforeTool(
toolName: string,
- params: Record<string, unknown>,
- ): "proceed" | "skip" | { type: "suspend"; approval: PendingApproval } {
- this.toolsExecutedInLoop = true;
- return this.delegate.beforeTool(toolName, params);
+ params: Record<string, unknown>
+ ): 'proceed' | 'skip' | { type: 'suspend'; approval: PendingApproval } {
+ this.toolsExecutedInLoop = true
+ return this.delegate.beforeTool(toolName, params)
}
onExhaustion(iteration: number): string {
- return this.delegate.onExhaustion(iteration);
+ return this.delegate.onExhaustion(iteration)
}
- async refreshTools(
- currentTools: ToolDefinition[],
- ): Promise<ToolDefinition[]> {
- return this.delegate.refreshTools(currentTools);
+ async refreshTools(currentTools: ToolDefinition[]): Promise<ToolDefinition[]> {
+ return this.delegate.refreshTools(currentTools)
}
/** Test helper: get current nudge count */
getNudgeCount(): number {
- return this.nudgeCount;
+ return this.nudgeCount
}
/** Test helper: check if tools have been executed */
hasToolsExecuted(): boolean {
- return this.toolsExecutedInLoop;
+ return this.toolsExecutedInLoop
}
}
diff --git a/mcp-host/src/core/index.ts b/mcp-host/src/core/index.ts
index 00578d26c..fec17f16a 100644
--- a/mcp-host/src/core/index.ts
+++ b/mcp-host/src/core/index.ts
@@ -1,3 +1,3 @@
-export * from "./types";
-export * from "./interfaces";
-export * from "./errors";
+export * from './types'
+export * from './interfaces'
+export * from './errors'
diff --git a/mcp-host/src/core/orchestration/eventEmitter.ts b/mcp-host/src/core/orchestration/eventEmitter.ts
index 538b89379..1a6875080 100644
--- a/mcp-host/src/core/orchestration/eventEmitter.ts
+++ b/mcp-host/src/core/orchestration/eventEmitter.ts
@@ -1,5 +1,5 @@
-import { AgentEventEmitter } from "../interfaces";
-import { AgentEvent } from "../types";
+import { AgentEventEmitter } from '../interfaces'
+import { AgentEvent } from '../types'
/**
* Simple typed event emitter for agent lifecycle events.
@@ -8,29 +8,29 @@ import { AgentEvent } from "../types";
* and allow the interface to be implemented in non-Node contexts.
*/
export class SimpleEventEmitter implements AgentEventEmitter {
- private handlers = new Map<string, Set<(event: AgentEvent) => void>>();
+ private handlers = new Map<string, Set<(event: AgentEvent) => void>>()
emit(event: AgentEvent): void {
- const typeHandlers = this.handlers.get(event.type);
+ const typeHandlers = this.handlers.get(event.type)
if (typeHandlers) {
for (const handler of typeHandlers) {
try {
- handler(event);
+ handler(event)
} catch (err) {
- console.error(`[EventEmitter] Handler error for ${event.type}:`, err);
+ console.error(`[EventEmitter] Handler error for ${event.type}:`, err)
}
}
}
}
- on(type: AgentEvent["type"], handler: (event: AgentEvent) => void): void {
+ on(type: AgentEvent['type'], handler: (event: AgentEvent) => void): void {
if (!this.handlers.has(type)) {
- this.handlers.set(type, new Set());
+ this.handlers.set(type, new Set())
}
- this.handlers.get(type)!.add(handler);
+ this.handlers.get(type)!.add(handler)
}
- off(type: AgentEvent["type"], handler: (event: AgentEvent) => void): void {
- this.handlers.get(type)?.delete(handler);
+ off(type: AgentEvent['type'], handler: (event: AgentEvent) => void): void {
+ this.handlers.get(type)?.delete(handler)
}
}
diff --git a/mcp-host/src/core/orchestration/index.ts b/mcp-host/src/core/orchestration/index.ts
index e97b289f9..db92f74ec 100644
--- a/mcp-host/src/core/orchestration/index.ts
+++ b/mcp-host/src/core/orchestration/index.ts
@@ -1,4 +1,4 @@
-export { runToolUseLoop, validateToolLinkages } from "./toolUseLoop";
-export { buildLoopConfig, DefaultLoopController, DefaultContextManager } from "./loopConfig";
-export type { LoopConfig } from "./loopConfig";
-export { SimpleEventEmitter } from "./eventEmitter";
+export { runToolUseLoop, validateToolLinkages } from './toolUseLoop'
+export { buildLoopConfig, DefaultLoopController, DefaultContextManager } from './loopConfig'
+export type { LoopConfig } from './loopConfig'
+export { SimpleEventEmitter } from './eventEmitter'
diff --git a/mcp-host/src/core/reasoning/index.ts b/mcp-host/src/core/reasoning/index.ts
index 8821a9391..77f5b5057 100644
--- a/mcp-host/src/core/reasoning/index.ts
+++ b/mcp-host/src/core/reasoning/index.ts
@@ -1,9 +1,9 @@
-export { DefaultReasoningPort } from "./port";
-export { DefaultReasoningFactory } from "./factory";
-export { DefaultPromptBuilder } from "./promptBuilder";
+export { DefaultReasoningPort } from './port'
+export { DefaultReasoningFactory } from './factory'
+export { DefaultPromptBuilder } from './promptBuilder'
export {
cleanResponse,
stripThinkingTags,
stripReasoningPatterns,
extractJson,
-} from "./responseCleaner";
+} from './responseCleaner'
diff --git a/mcp-host/src/core/safety/__tests__/safety.test.ts b/mcp-host/src/core/safety/__tests__/safety.test.ts
index 6109e5969..76c9a658c 100644
--- a/mcp-host/src/core/safety/__tests__/safety.test.ts
+++ b/mcp-host/src/core/safety/__tests__/safety.test.ts
@@ -122,10 +122,7 @@ describe('BasicSafety', () => {
const s = new BasicSafety(() => [
{ name: 'OPENAI_API_KEY', value: 'totally-not-a-pattern-match-12345' },
])
- const result = s.sanitizeOutput(
- 'shell_exec',
- 'echoed key totally-not-a-pattern-match-12345'
- )
+ const result = s.sanitizeOutput('shell_exec', 'echoed key totally-not-a-pattern-match-12345')
expect(result.content).toContain('[REDACTED:OPENAI_API_KEY]')
expect(result.content).not.toContain('totally-not-a-pattern-match-12345')
@@ -162,9 +159,7 @@ describe('BasicSafety', () => {
})
it('reads from the provider on every call (hot reload)', () => {
- let entries: Array<{ name: string; value: string }> = [
- { name: 'TOK', value: 'rev-1-secret' },
- ]
+ let entries: Array<{ name: string; value: string }> = [{ name: 'TOK', value: 'rev-1-secret' }]
const s = new BasicSafety(() => entries)
const r1 = s.sanitizeOutput('shell_exec', 'echo rev-1-secret here')
diff --git a/mcp-host/src/core/safety/index.ts b/mcp-host/src/core/safety/index.ts
index d6c735f5d..7907cf241 100644
--- a/mcp-host/src/core/safety/index.ts
+++ b/mcp-host/src/core/safety/index.ts
@@ -1,2 +1,2 @@
-export { BasicSafety } from "./safety";
-export { DefaultToolOutputProcessor } from "./toolOutputProcessor";
+export { BasicSafety } from './safety'
+export { DefaultToolOutputProcessor } from './toolOutputProcessor'
diff --git a/mcp-host/src/core/safety/toolOutputProcessor.ts b/mcp-host/src/core/safety/toolOutputProcessor.ts
index ff5722340..36d9d4478 100644
--- a/mcp-host/src/core/safety/toolOutputProcessor.ts
+++ b/mcp-host/src/core/safety/toolOutputProcessor.ts
@@ -1,5 +1,5 @@
-import { ToolOutputProcessor, Safety } from "../interfaces";
-import { ToolOutput, ValidationResult } from "../types";
+import { Safety, ToolOutputProcessor } from '../interfaces'
+import { ToolOutput, ValidationResult } from '../types'
/**
* Default ToolOutputProcessor that delegates to Safety.
@@ -10,16 +10,13 @@ import { ToolOutput, ValidationResult } from "../types";
export class DefaultToolOutputProcessor implements ToolOutputProcessor {
constructor(private readonly safety: Safety) {}
- beforeExecution(
- toolName: string,
- params: Record<string, unknown>,
- ): ValidationResult {
- return this.safety.validateToolParams(toolName, params);
+ beforeExecution(toolName: string, params: Record<string, unknown>): ValidationResult {
+ return this.safety.validateToolParams(toolName, params)
}
afterExecution(toolName: string, output: ToolOutput): string {
// Safety sandwich: sanitize -> wrap
- const sanitized = this.safety.sanitizeOutput(toolName, output.content);
- return this.safety.wrapForLlm(toolName, sanitized.content, sanitized.was_modified);
+ const sanitized = this.safety.sanitizeOutput(toolName, output.content)
+ return this.safety.wrapForLlm(toolName, sanitized.content, sanitized.was_modified)
}
}
diff --git a/mcp-host/src/core/tools/__tests__/fileSecurity.test.ts b/mcp-host/src/core/tools/__tests__/fileSecurity.test.ts
index 863219286..dc1356499 100644
--- a/mcp-host/src/core/tools/__tests__/fileSecurity.test.ts
+++ b/mcp-host/src/core/tools/__tests__/fileSecurity.test.ts
@@ -1,129 +1,126 @@
-import { describe, it, expect, beforeEach, afterEach } from "vitest";
-import { mkdtemp, rm, writeFile, mkdir, symlink, readFile } from "fs/promises";
-import { tmpdir } from "os";
-import { join } from "path";
-import { FileReadTool } from "../fileRead";
-import { FileWriteTool } from "../fileWrite";
-import { validatePath, isWithinDirectory } from "../pathValidation";
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'fs/promises'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { FileReadTool } from '../fileRead'
+import { FileWriteTool } from '../fileWrite'
+import { isWithinDirectory, validatePath } from '../pathValidation'
-let workspacePath: string;
+let workspacePath: string
beforeEach(async () => {
- workspacePath = await mkdtemp(join(tmpdir(), "clerum-test-"));
-});
+ workspacePath = await mkdtemp(join(tmpdir(), 'clerum-test-'))
+})
afterEach(async () => {
- await rm(workspacePath, { recursive: true, force: true });
-});
+ await rm(workspacePath, { recursive: true, force: true })
+})
-describe("FileReadTool path security", () => {
- it("should reject parent directory traversal (Risk 3.5.1a)", async () => {
- const tool = new FileReadTool(workspacePath);
- const result = await tool.execute({ path: "../../etc/passwd" });
+describe('FileReadTool path security', () => {
+ it('should reject parent directory traversal (Risk 3.5.1a)', async () => {
+ const tool = new FileReadTool(workspacePath)
+ const result = await tool.execute({ path: '../../etc/passwd' })
- expect(result.is_error).toBe(true);
- expect(result.content).toContain("not allowed");
- });
+ expect(result.is_error).toBe(true)
+ expect(result.content).toContain('not allowed')
+ })
- it("should reject absolute paths (Risk 3.5.1b)", async () => {
- const tool = new FileReadTool(workspacePath);
- const result = await tool.execute({ path: "/etc/passwd" });
+ it('should reject absolute paths (Risk 3.5.1b)', async () => {
+ const tool = new FileReadTool(workspacePath)
+ const result = await tool.execute({ path: '/etc/passwd' })
- expect(result.is_error).toBe(true);
- expect(result.content).toContain("not allowed");
- });
+ expect(result.is_error).toBe(true)
+ expect(result.content).toContain('not allowed')
+ })
- it("should reject null bytes in path (Risk 3.5.1c)", async () => {
- const tool = new FileReadTool(workspacePath);
- const result = await tool.execute({ path: "file\0.txt" });
+ it('should reject null bytes in path (Risk 3.5.1c)', async () => {
+ const tool = new FileReadTool(workspacePath)
+ const result = await tool.execute({ path: 'file\0.txt' })
- expect(result.is_error).toBe(true);
- expect(result.content).toContain("null bytes");
- });
+ expect(result.is_error).toBe(true)
+ expect(result.content).toContain('null bytes')
+ })
- it("should reject symlinks pointing outside workspace (Risk 3.5.1d)", async () => {
+ it('should reject symlinks pointing outside workspace (Risk 3.5.1d)', async () => {
// Create a symlink inside workspace that points to /tmp
- await symlink("/tmp", join(workspacePath, "escape-link"));
+ await symlink('/tmp', join(workspacePath, 'escape-link'))
- const tool = new FileReadTool(workspacePath);
- const result = await tool.execute({ path: "escape-link" });
+ const tool = new FileReadTool(workspacePath)
+ const result = await tool.execute({ path: 'escape-link' })
- expect(result.is_error).toBe(true);
- expect(result.content).toContain("outside workspace");
- });
+ expect(result.is_error).toBe(true)
+ expect(result.content).toContain('outside workspace')
+ })
- it("should read valid relative paths within workspace (Risk 3.5.1e)", async () => {
+ it('should read valid relative paths within workspace (Risk 3.5.1e)', async () => {
// Create a file inside the workspace
- await mkdir(join(workspacePath, "src"), { recursive: true });
- await writeFile(
- join(workspacePath, "src/main.ts"),
- "console.log('hello');",
- );
-
- const tool = new FileReadTool(workspacePath);
- const result = await tool.execute({ path: "src/main.ts" });
-
- expect(result.is_error).toBe(false);
- expect(result.content).toBe("console.log('hello');");
- });
-
- it("should reject paths where workspace name is a prefix of another directory", async () => {
- const tool = new FileReadTool(workspacePath);
- const result = validatePath("test.txt", workspacePath);
- expect(result.valid).toBe(true);
- });
-});
-
-describe("isWithinDirectory", () => {
- it("should detect paths within directory", () => {
- expect(isWithinDirectory("/workspace/file.txt", "/workspace")).toBe(true);
- expect(isWithinDirectory("/workspace/sub/file.txt", "/workspace")).toBe(true);
- });
-
- it("should reject paths outside directory", () => {
- expect(isWithinDirectory("/workspace-evil/file.txt", "/workspace")).toBe(false);
- expect(isWithinDirectory("/other/file.txt", "/workspace")).toBe(false);
- });
-
- it("should reject parent traversal", () => {
- expect(isWithinDirectory("/workspace/../etc/passwd", "/workspace")).toBe(false);
- });
-
- it("should accept the directory itself", () => {
- expect(isWithinDirectory("/workspace", "/workspace")).toBe(true);
- });
-});
-
-describe("FileWriteTool path security", () => {
- it("should reject traversal and write within workspace", async () => {
- const tool = new FileWriteTool(workspacePath);
+ await mkdir(join(workspacePath, 'src'), { recursive: true })
+ await writeFile(join(workspacePath, 'src/main.ts'), "console.log('hello');")
+
+ const tool = new FileReadTool(workspacePath)
+ const result = await tool.execute({ path: 'src/main.ts' })
+
+ expect(result.is_error).toBe(false)
+ expect(result.content).toBe("console.log('hello');")
+ })
+
+ it('should reject paths where workspace name is a prefix of another directory', async () => {
+ const tool = new FileReadTool(workspacePath)
+ const result = validatePath('test.txt', workspacePath)
+ expect(result.valid).toBe(true)
+ })
+})
+
+describe('isWithinDirectory', () => {
+ it('should detect paths within directory', () => {
+ expect(isWithinDirectory('/workspace/file.txt', '/workspace')).toBe(true)
+ expect(isWithinDirectory('/workspace/sub/file.txt', '/workspace')).toBe(true)
+ })
+
+ it('should reject paths outside directory', () => {
+ expect(isWithinDirectory('/workspace-evil/file.txt', '/workspace')).toBe(false)
+ expect(isWithinDirectory('/other/file.txt', '/workspace')).toBe(false)
+ })
+
+ it('should reject parent traversal', () => {
+ expect(isWithinDirectory('/workspace/../etc/passwd', '/workspace')).toBe(false)
+ })
+
+ it('should accept the directory itself', () => {
+ expect(isWithinDirectory('/workspace', '/workspace')).toBe(true)
+ })
+})
+
+describe('FileWriteTool path security', () => {
+ it('should reject traversal and write within workspace', async () => {
+ const tool = new FileWriteTool(workspacePath)
// Traversal rejected
const bad = await tool.execute({
- path: "../escape.txt",
- content: "pwned",
- });
- expect(bad.is_error).toBe(true);
+ path: '../escape.txt',
+ content: 'pwned',
+ })
+ expect(bad.is_error).toBe(true)
// Valid write works
const good = await tool.execute({
- path: "output.txt",
- content: "safe",
- });
- expect(good.is_error).toBe(false);
+ path: 'output.txt',
+ content: 'safe',
+ })
+ expect(good.is_error).toBe(false)
// Verify file was actually written
- const content = await readFile(join(workspacePath, "output.txt"), "utf-8");
- expect(content).toBe("safe");
- });
+ const content = await readFile(join(workspacePath, 'output.txt'), 'utf-8')
+ expect(content).toBe('safe')
+ })
- it("should reject writes exceeding size limit", async () => {
- const tool = new FileWriteTool(workspacePath);
+ it('should reject writes exceeding size limit', async () => {
+ const tool = new FileWriteTool(workspacePath)
const result = await tool.execute({
- path: "large.txt",
- content: "x".repeat(6 * 1024 * 1024), // 6MB > 5MB limit
- });
- expect(result.is_error).toBe(true);
- expect(result.content).toContain("too large");
- });
-});
+ path: 'large.txt',
+ content: 'x'.repeat(6 * 1024 * 1024), // 6MB > 5MB limit
+ })
+ expect(result.is_error).toBe(true)
+ expect(result.content).toContain('too large')
+ })
+})
diff --git a/mcp-host/src/core/tools/index.ts b/mcp-host/src/core/tools/index.ts
index b432829d7..645217b9f 100644
--- a/mcp-host/src/core/tools/index.ts
+++ b/mcp-host/src/core/tools/index.ts
@@ -1,10 +1,15 @@
-export { FileReadTool } from "./fileRead";
-export { FileWriteTool } from "./fileWrite";
-export { ShellTool } from "./shell";
-export { HttpRequestTool, isPrivateIp } from "./httpRequest";
-export { SystemInfoTool } from "./systemInfo";
-export { JsonTransformTool } from "./jsonTransform";
-export { MemorySearchTool, PersistentMemoryWriteTool, PersistentMemoryReadTool, MemoryTreeTool } from "./memory";
-export { CronManageTool } from "./cronManage";
-export { NativeToolRegistry } from "./nativeToolRegistry";
-export { validatePath, isWithinDirectory } from "./pathValidation";
+export { FileReadTool } from './fileRead'
+export { FileWriteTool } from './fileWrite'
+export { ShellTool } from './shell'
+export { HttpRequestTool, isPrivateIp } from './httpRequest'
+export { SystemInfoTool } from './systemInfo'
+export { JsonTransformTool } from './jsonTransform'
+export {
+ MemorySearchTool,
+ PersistentMemoryWriteTool,
+ PersistentMemoryReadTool,
+ MemoryTreeTool,
+} from './memory'
+export { CronManageTool } from './cronManage'
+export { NativeToolRegistry } from './nativeToolRegistry'
+export { validatePath, isWithinDirectory } from './pathValidation'
diff --git a/mcp-host/src/core/tools/jsonTransform.ts b/mcp-host/src/core/tools/jsonTransform.ts
index 1cc9001a6..0376e22e8 100644
--- a/mcp-host/src/core/tools/jsonTransform.ts
+++ b/mcp-host/src/core/tools/jsonTransform.ts
@@ -1,110 +1,106 @@
-import { Tool } from "../interfaces";
-import { ToolOutput } from "../types";
+import { Tool } from '../interfaces'
+import { ToolOutput } from '../types'
export class JsonTransformTool implements Tool {
name() {
- return "json_transform";
+ return 'json_transform'
}
description() {
return (
- "Parse, query, and transform JSON data. " +
- "Supports parsing JSON strings, extracting nested values by dot-path, " +
- "and basic transformations (keys, values, filter, map)."
- );
+ 'Parse, query, and transform JSON data. ' +
+ 'Supports parsing JSON strings, extracting nested values by dot-path, ' +
+ 'and basic transformations (keys, values, filter, map).'
+ )
}
parametersSchema() {
return {
- type: "object",
+ type: 'object',
properties: {
- input: { type: "string", description: "JSON string to process" },
+ input: { type: 'string', description: 'JSON string to process' },
operation: {
- type: "string",
- enum: ["parse", "get", "keys", "values", "length", "stringify"],
- description: "Operation to perform",
+ type: 'string',
+ enum: ['parse', 'get', 'keys', 'values', 'length', 'stringify'],
+ description: 'Operation to perform',
},
path: {
- type: "string",
- description:
- "Dot-separated path for 'get' operation (e.g., 'data.items.0.name')",
+ type: 'string',
+ description: "Dot-separated path for 'get' operation (e.g., 'data.items.0.name')",
},
},
- required: ["input", "operation"],
- };
+ required: ['input', 'operation'],
+ }
}
requiresSanitization() {
- return false;
+ return false
}
requiresApproval() {
- return false;
+ return false
}
async execute(params: Record<string, unknown>): Promise<ToolOutput> {
- const startTime = Date.now();
- const input = params.input as string;
- const operation = params.operation as string;
- const dotPath = params.path as string | undefined;
+ const startTime = Date.now()
+ const input = params.input as string
+ const operation = params.operation as string
+ const dotPath = params.path as string | undefined
- let parsed: any;
+ let parsed: any
try {
- parsed = JSON.parse(input);
+ parsed = JSON.parse(input)
} catch (err) {
return {
content: `Error parsing JSON: ${(err as Error).message}`,
duration_ms: Date.now() - startTime,
is_error: true,
- };
+ }
}
try {
- let result: any;
+ let result: any
switch (operation) {
- case "parse":
- result = parsed;
- break;
- case "get":
- result = dotPath ? this.getByPath(parsed, dotPath) : parsed;
- break;
- case "keys":
- result = Object.keys(parsed);
- break;
- case "values":
- result = Object.values(parsed);
- break;
- case "length":
- result = Array.isArray(parsed)
- ? parsed.length
- : Object.keys(parsed).length;
- break;
- case "stringify":
- result = JSON.stringify(parsed, null, 2);
- break;
+ case 'parse':
+ result = parsed
+ break
+ case 'get':
+ result = dotPath ? this.getByPath(parsed, dotPath) : parsed
+ break
+ case 'keys':
+ result = Object.keys(parsed)
+ break
+ case 'values':
+ result = Object.values(parsed)
+ break
+ case 'length':
+ result = Array.isArray(parsed) ? parsed.length : Object.keys(parsed).length
+ break
+ case 'stringify':
+ result = JSON.stringify(parsed, null, 2)
+ break
default:
return {
content: `Unknown operation: ${operation}`,
duration_ms: Date.now() - startTime,
is_error: true,
- };
+ }
}
return {
- content:
- typeof result === "string" ? result : JSON.stringify(result, null, 2),
+ content: typeof result === 'string' ? result : JSON.stringify(result, null, 2),
duration_ms: Date.now() - startTime,
is_error: false,
- };
+ }
} catch (err) {
return {
content: `Transform error: ${(err as Error).message}`,
duration_ms: Date.now() - startTime,
is_error: true,
- };
+ }
}
}
private getByPath(obj: any, path: string): any {
- return path.split(".").reduce((current, key) => {
- if (current === undefined || current === null) return undefined;
- return current[key];
- }, obj);
+ return path.split('.').reduce((current, key) => {
+ if (current === undefined || current === null) return undefined
+ return current[key]
+ }, obj)
}
}
diff --git a/mcp-host/src/core/tools/pathValidation.ts b/mcp-host/src/core/tools/pathValidation.ts
index 250124c25..f5198b1da 100644
--- a/mcp-host/src/core/tools/pathValidation.ts
+++ b/mcp-host/src/core/tools/pathValidation.ts
@@ -1,9 +1,9 @@
-import * as path from "path";
-import * as fs from "fs";
+import * as fs from 'fs'
+import * as path from 'path'
export function isWithinDirectory(child: string, parent: string): boolean {
- const relative = path.relative(parent, child);
- return !relative.startsWith("..") && !path.isAbsolute(relative);
+ const relative = path.relative(parent, child)
+ return !relative.startsWith('..') && !path.isAbsolute(relative)
}
/**
@@ -17,69 +17,69 @@ export function isWithinDirectory(child: string, parent: string): boolean {
*/
export function validatePath(
requestedPath: string,
- workspacePath: string,
+ workspacePath: string
): { valid: boolean; resolved: string; error?: string } {
// Reject null bytes (Risk 3.5.1)
- if (requestedPath.includes("\0")) {
- return { valid: false, resolved: "", error: "Path contains null bytes" };
+ if (requestedPath.includes('\0')) {
+ return { valid: false, resolved: '', error: 'Path contains null bytes' }
}
// Reject absolute paths (Risk 3.5.1)
if (path.isAbsolute(requestedPath)) {
- return { valid: false, resolved: "", error: "Absolute paths not allowed" };
+ return { valid: false, resolved: '', error: 'Absolute paths not allowed' }
}
// Reject parent directory traversal (Risk 3.5.1)
- if (requestedPath.includes("..")) {
+ if (requestedPath.includes('..')) {
return {
valid: false,
- resolved: "",
- error: "Directory traversal (..) not allowed",
- };
+ resolved: '',
+ error: 'Directory traversal (..) not allowed',
+ }
}
// Resolve within workspace
- const resolved = path.resolve(workspacePath, requestedPath);
+ const resolved = path.resolve(workspacePath, requestedPath)
// Verify resolved path is within workspace (symlink protection)
- const realWorkspace = fs.realpathSync(workspacePath);
- let realResolved: string;
+ const realWorkspace = fs.realpathSync(workspacePath)
+ let realResolved: string
try {
- realResolved = fs.realpathSync(resolved);
+ realResolved = fs.realpathSync(resolved)
} catch {
// File doesn't exist yet (for writes) — walk up to the first existing
// ancestor and verify it's within the workspace. This supports creating
// files in nested directories that don't exist yet (e.g., "mathlib/utils.js").
- let ancestor = path.dirname(resolved);
+ let ancestor = path.dirname(resolved)
while (ancestor !== path.dirname(ancestor)) {
try {
- const realAncestor = fs.realpathSync(ancestor);
+ const realAncestor = fs.realpathSync(ancestor)
if (!isWithinDirectory(realAncestor, realWorkspace)) {
return {
valid: false,
- resolved: "",
- error: "Path resolves outside workspace",
- };
+ resolved: '',
+ error: 'Path resolves outside workspace',
+ }
}
- return { valid: true, resolved };
+ return { valid: true, resolved }
} catch {
- ancestor = path.dirname(ancestor);
+ ancestor = path.dirname(ancestor)
}
}
return {
valid: false,
- resolved: "",
- error: "No valid ancestor directory found within workspace",
- };
+ resolved: '',
+ error: 'No valid ancestor directory found within workspace',
+ }
}
if (!isWithinDirectory(realResolved, realWorkspace)) {
return {
valid: false,
- resolved: "",
- error: "Path resolves outside workspace (symlink)",
- };
+ resolved: '',
+ error: 'Path resolves outside workspace (symlink)',
+ }
}
- return { valid: true, resolved };
+ return { valid: true, resolved }
}
diff --git a/mcp-host/src/core/tools/systemInfo.ts b/mcp-host/src/core/tools/systemInfo.ts
index d6f348241..ae4759996 100644
--- a/mcp-host/src/core/tools/systemInfo.ts
+++ b/mcp-host/src/core/tools/systemInfo.ts
@@ -1,29 +1,29 @@
-import { Tool } from "../interfaces";
-import { ToolOutput } from "../types";
-import * as os from "os";
+import * as os from 'os'
+import { Tool } from '../interfaces'
+import { ToolOutput } from '../types'
export class SystemInfoTool implements Tool {
name() {
- return "system_info";
+ return 'system_info'
}
description() {
return (
- "Get current system information: date, time, timezone, " +
- "platform, hostname, and Node.js version."
- );
+ 'Get current system information: date, time, timezone, ' +
+ 'platform, hostname, and Node.js version.'
+ )
}
parametersSchema() {
- return { type: "object", properties: {} };
+ return { type: 'object', properties: {} }
}
requiresSanitization() {
- return false;
+ return false
}
requiresApproval() {
- return false;
+ return false
}
async execute(): Promise<ToolOutput> {
- const startTime = Date.now();
+ const startTime = Date.now()
const info = {
datetime: new Date().toISOString(),
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
@@ -32,11 +32,11 @@ export class SystemInfoTool implements Tool {
hostname: os.hostname(),
nodeVersion: process.version,
uptime: `${Math.floor(process.uptime())}s`,
- };
+ }
return {
content: JSON.stringify(info, null, 2),
duration_ms: Date.now() - startTime,
is_error: false,
- };
+ }
}
}
diff --git a/mcp-host/src/llm/__tests__/providerCleanup.test.ts b/mcp-host/src/llm/__tests__/providerCleanup.test.ts
index ac7facd0b..bb79186ad 100644
--- a/mcp-host/src/llm/__tests__/providerCleanup.test.ts
+++ b/mcp-host/src/llm/__tests__/providerCleanup.test.ts
@@ -5,102 +5,101 @@
* and types (OpenAITool, ClaudeTool, ToolCallHandler) have been removed,
* while SingleTurnProvider methods remain intact.
*/
-
-import { describe, it, expect, vi } from "vitest";
-import { OpenAIProvider } from "../openai";
-import { ClaudeProvider } from "../claude";
-
-describe("Provider cleanup — legacy methods removed", () => {
- it("OpenAIProvider should NOT have chat() method", () => {
- const client = { chat: { completions: { create: vi.fn() } } };
- const provider = new OpenAIProvider(client as any, "gpt-4o");
- expect((provider as any).chat).toBeUndefined();
- });
-
- it("OpenAIProvider should NOT have chatWithTools() method", () => {
- const client = { chat: { completions: { create: vi.fn() } } };
- const provider = new OpenAIProvider(client as any, "gpt-4o");
- expect((provider as any).chatWithTools).toBeUndefined();
- });
-
- it("OpenAIProvider should NOT have chatStream() method", () => {
- const client = { chat: { completions: { create: vi.fn() } } };
- const provider = new OpenAIProvider(client as any, "gpt-4o");
- expect((provider as any).chatStream).toBeUndefined();
- });
-
- it("ClaudeProvider should NOT have chat() method", () => {
- const client = { messages: { create: vi.fn() } };
- const provider = new ClaudeProvider(client as any, "claude-3-5-sonnet-20241022");
- expect((provider as any).chat).toBeUndefined();
- });
-
- it("ClaudeProvider should NOT have chatWithTools() method", () => {
- const client = { messages: { create: vi.fn() } };
- const provider = new ClaudeProvider(client as any, "claude-3-5-sonnet-20241022");
- expect((provider as any).chatWithTools).toBeUndefined();
- });
-
- it("ClaudeProvider should NOT have chatStream() method", () => {
- const client = { messages: { create: vi.fn() } };
- const provider = new ClaudeProvider(client as any, "claude-3-5-sonnet-20241022");
- expect((provider as any).chatStream).toBeUndefined();
- });
-});
-
-describe("Provider cleanup — SingleTurnProvider methods survive", () => {
- it("OpenAIProvider should retain completeSingleTurn()", () => {
- const client = { chat: { completions: { create: vi.fn() } } };
- const provider = new OpenAIProvider(client as any, "gpt-4o");
- expect(typeof provider.completeSingleTurn).toBe("function");
- });
-
- it("OpenAIProvider should retain completeSingleTurnWithTools()", () => {
- const client = { chat: { completions: { create: vi.fn() } } };
- const provider = new OpenAIProvider(client as any, "gpt-4o");
- expect(typeof provider.completeSingleTurnWithTools).toBe("function");
- });
-
- it("ClaudeProvider should retain completeSingleTurn()", () => {
- const client = { messages: { create: vi.fn() } };
- const provider = new ClaudeProvider(client as any, "claude-3-5-sonnet-20241022");
- expect(typeof provider.completeSingleTurn).toBe("function");
- });
-
- it("ClaudeProvider should retain completeSingleTurnWithTools()", () => {
- const client = { messages: { create: vi.fn() } };
- const provider = new ClaudeProvider(client as any, "claude-3-5-sonnet-20241022");
- expect(typeof provider.completeSingleTurnWithTools).toBe("function");
- });
-
- it("Both providers should retain getProviderType()", () => {
- const openaiClient = { chat: { completions: { create: vi.fn() } } };
- const claudeClient = { messages: { create: vi.fn() } };
- const openai = new OpenAIProvider(openaiClient as any, "gpt-4o");
- const claude = new ClaudeProvider(claudeClient as any, "claude-3-5-sonnet-20241022");
- expect(openai.getProviderType()).toBe("openai");
- expect(claude.getProviderType()).toBe("claude");
- });
-});
-
-describe("Provider cleanup — legacy types not exported", () => {
- it("should NOT export OpenAITool from llm/index", async () => {
- const llmModule = await import("../index");
- expect((llmModule as any).OpenAITool).toBeUndefined();
- });
-
- it("should NOT export ClaudeTool from llm/index", async () => {
- const llmModule = await import("../index");
- expect((llmModule as any).ClaudeTool).toBeUndefined();
- });
-
- it("should NOT export LLMProvider from llm/index", async () => {
- const llmModule = await import("../index");
- expect((llmModule as any).LLMProvider).toBeUndefined();
- });
-
- it("should NOT export ToolCallHandler from llm/index", async () => {
- const llmModule = await import("../index");
- expect((llmModule as any).ToolCallHandler).toBeUndefined();
- });
-});
+import { describe, expect, it, vi } from 'vitest'
+import { ClaudeProvider } from '../claude'
+import { OpenAIProvider } from '../openai'
+
+describe('Provider cleanup — legacy methods removed', () => {
+ it('OpenAIProvider should NOT have chat() method', () => {
+ const client = { chat: { completions: { create: vi.fn() } } }
+ const provider = new OpenAIProvider(client as any, 'gpt-4o')
+ expect((provider as any).chat).toBeUndefined()
+ })
+
+ it('OpenAIProvider should NOT have chatWithTools() method', () => {
+ const client = { chat: { completions: { create: vi.fn() } } }
+ const provider = new OpenAIProvider(client as any, 'gpt-4o')
+ expect((provider as any).chatWithTools).toBeUndefined()
+ })
+
+ it('OpenAIProvider should NOT have chatStream() method', () => {
+ const client = { chat: { completions: { create: vi.fn() } } }
+ const provider = new OpenAIProvider(client as any, 'gpt-4o')
+ expect((provider as any).chatStream).toBeUndefined()
+ })
+
+ it('ClaudeProvider should NOT have chat() method', () => {
+ const client = { messages: { create: vi.fn() } }
+ const provider = new ClaudeProvider(client as any, 'claude-3-5-sonnet-20241022')
+ expect((provider as any).chat).toBeUndefined()
+ })
+
+ it('ClaudeProvider should NOT have chatWithTools() method', () => {
+ const client = { messages: { create: vi.fn() } }
+ const provider = new ClaudeProvider(client as any, 'claude-3-5-sonnet-20241022')
+ expect((provider as any).chatWithTools).toBeUndefined()
+ })
+
+ it('ClaudeProvider should NOT have chatStream() method', () => {
+ const client = { messages: { create: vi.fn() } }
+ const provider = new ClaudeProvider(client as any, 'claude-3-5-sonnet-20241022')
+ expect((provider as any).chatStream).toBeUndefined()
+ })
+})
+
+describe('Provider cleanup — SingleTurnProvider methods survive', () => {
+ it('OpenAIProvider should retain completeSingleTurn()', () => {
+ const client = { chat: { completions: { create: vi.fn() } } }
+ const provider = new OpenAIProvider(client as any, 'gpt-4o')
+ expect(typeof provider.completeSingleTurn).toBe('function')
+ })
+
+ it('OpenAIProvider should retain completeSingleTurnWithTools()', () => {
+ const client = { chat: { completions: { create: vi.fn() } } }
+ const provider = new OpenAIProvider(client as any, 'gpt-4o')
+ expect(typeof provider.completeSingleTurnWithTools).toBe('function')
+ })
+
+ it('ClaudeProvider should retain completeSingleTurn()', () => {
+ const client = { messages: { create: vi.fn() } }
+ const provider = new ClaudeProvider(client as any, 'claude-3-5-sonnet-20241022')
+ expect(typeof provider.completeSingleTurn).toBe('function')
+ })
+
+ it('ClaudeProvider should retain completeSingleTurnWithTools()', () => {
+ const client = { messages: { create: vi.fn() } }
+ const provider = new ClaudeProvider(client as any, 'claude-3-5-sonnet-20241022')
+ expect(typeof provider.completeSingleTurnWithTools).toBe('function')
+ })
+
+ it('Both providers should retain getProviderType()', () => {
+ const openaiClient = { chat: { completions: { create: vi.fn() } } }
+ const claudeClient = { messages: { create: vi.fn() } }
+ const openai = new OpenAIProvider(openaiClient as any, 'gpt-4o')
+ const claude = new ClaudeProvider(claudeClient as any, 'claude-3-5-sonnet-20241022')
+ expect(openai.getProviderType()).toBe('openai')
+ expect(claude.getProviderType()).toBe('claude')
+ })
+})
+
+describe('Provider cleanup — legacy types not exported', () => {
+ it('should NOT export OpenAITool from llm/index', async () => {
+ const llmModule = await import('../index')
+ expect((llmModule as any).OpenAITool).toBeUndefined()
+ })
+
+ it('should NOT export ClaudeTool from llm/index', async () => {
+ const llmModule = await import('../index')
+ expect((llmModule as any).ClaudeTool).toBeUndefined()
+ })
+
+ it('should NOT export LLMProvider from llm/index', async () => {
+ const llmModule = await import('../index')
+ expect((llmModule as any).LLMProvider).toBeUndefined()
+ })
+
+ it('should NOT export ToolCallHandler from llm/index', async () => {
+ const llmModule = await import('../index')
+ expect((llmModule as any).ToolCallHandler).toBeUndefined()
+ })
+})
diff --git a/mcp-host/src/logger.ts b/mcp-host/src/logger.ts
index 9d08f78b0..027ecd7ea 100644
--- a/mcp-host/src/logger.ts
+++ b/mcp-host/src/logger.ts
@@ -14,48 +14,46 @@
* import "./logger";
*/
-const COMPONENT_RE = /^\[([^\]]+)\]\s*/;
+const COMPONENT_RE = /^\[([^\]]+)\]\s*/
-const originalLog = console.log.bind(console);
-const originalError = console.error.bind(console);
-const originalWarn = console.warn.bind(console);
+const originalLog = console.log.bind(console)
+const originalError = console.error.bind(console)
+const originalWarn = console.warn.bind(console)
function formatArgs(args: unknown[]): string {
- return args
- .map((a) => (typeof a === "string" ? a : JSON.stringify(a)))
- .join(" ");
+ return args.map(a => (typeof a === 'string' ? a : JSON.stringify(a))).join(' ')
}
function emit(level: string, args: unknown[]): void {
- const raw = formatArgs(args);
+ const raw = formatArgs(args)
// Skip empty lines and separator lines (====, ----)
- const trimmed = raw.trim();
- if (!trimmed || /^[=\-]{3,}$/.test(trimmed)) return;
+ const trimmed = raw.trim()
+ if (!trimmed || /^[=\-]{3,}$/.test(trimmed)) return
- let component = "";
- let msg = raw;
+ let component = ''
+ let msg = raw
- const match = raw.match(COMPONENT_RE);
+ const match = raw.match(COMPONENT_RE)
if (match) {
- component = match[1];
- msg = raw.slice(match[0].length);
+ component = match[1]
+ msg = raw.slice(match[0].length)
}
const entry: Record<string, string> = {
timestamp: new Date().toISOString(),
level,
msg: msg.trim(),
- };
+ }
if (component) {
- entry.component = component;
+ entry.component = component
}
- const writer = level === "error" ? originalError : originalLog;
- writer(JSON.stringify(entry));
+ const writer = level === 'error' ? originalError : originalLog
+ writer(JSON.stringify(entry))
}
-console.log = (...args: unknown[]) => emit("info", args);
-console.error = (...args: unknown[]) => emit("error", args);
-console.warn = (...args: unknown[]) => emit("warn", args);
+console.log = (...args: unknown[]) => emit('info', args)
+console.error = (...args: unknown[]) => emit('error', args)
+console.warn = (...args: unknown[]) => emit('warn', args)
diff --git a/mcp-host/src/mcp/__tests__/managerCleanup.test.ts b/mcp-host/src/mcp/__tests__/managerCleanup.test.ts
index 4293319e8..7ac2762f6 100644
--- a/mcp-host/src/mcp/__tests__/managerCleanup.test.ts
+++ b/mcp-host/src/mcp/__tests__/managerCleanup.test.ts
@@ -4,33 +4,32 @@
* Verifies that provider-specific tool format methods have been removed,
* while the generic getAllTools() and callTool() survive.
*/
+import { describe, expect, it } from 'vitest'
+import { McpManager } from '../manager'
-import { describe, it, expect } from "vitest";
-import { McpManager } from "../manager";
+describe('McpManager cleanup — provider-specific methods removed', () => {
+ it('should NOT have getToolsForOpenAI() method', () => {
+ const manager = new McpManager()
+ expect((manager as any).getToolsForOpenAI).toBeUndefined()
+ })
-describe("McpManager cleanup — provider-specific methods removed", () => {
- it("should NOT have getToolsForOpenAI() method", () => {
- const manager = new McpManager();
- expect((manager as any).getToolsForOpenAI).toBeUndefined();
- });
+ it('should NOT have getToolsForClaude() method', () => {
+ const manager = new McpManager()
+ expect((manager as any).getToolsForClaude).toBeUndefined()
+ })
+})
- it("should NOT have getToolsForClaude() method", () => {
- const manager = new McpManager();
- expect((manager as any).getToolsForClaude).toBeUndefined();
- });
-});
+describe('McpManager cleanup — generic methods survive', () => {
+ it('should retain getAllTools() method', () => {
+ const manager = new McpManager()
+ expect(typeof manager.getAllTools).toBe('function')
+ expect(manager.getAllTools()).toEqual([])
+ })
-describe("McpManager cleanup — generic methods survive", () => {
- it("should retain getAllTools() method", () => {
- const manager = new McpManager();
- expect(typeof manager.getAllTools).toBe("function");
- expect(manager.getAllTools()).toEqual([]);
- });
-
- it("should retain callTool() method", async () => {
- const manager = new McpManager();
- expect(typeof manager.callTool).toBe("function");
- const result = await manager.callTool("missing__tool", {});
- expect(result.isError).toBe(true);
- });
-});
+ it('should retain callTool() method', async () => {
+ const manager = new McpManager()
+ expect(typeof manager.callTool).toBe('function')
+ const result = await manager.callTool('missing__tool', {})
+ expect(result.isError).toBe(true)
+ })
+})
diff --git a/mcp-host/src/mcp/__tests__/proxyMode.test.ts b/mcp-host/src/mcp/__tests__/proxyMode.test.ts
index 79d276fbb..0b38b1aac 100644
--- a/mcp-host/src/mcp/__tests__/proxyMode.test.ts
+++ b/mcp-host/src/mcp/__tests__/proxyMode.test.ts
@@ -1,148 +1,147 @@
/**
* Phase 3 tests: MCP Proxy mode — URL strategy and feature flag behavior.
*/
+import { describe, expect, it, vi } from 'vitest'
+import { McpServerInfo } from '../../types'
+import { McpClient } from '../client'
+import { McpManager } from '../manager'
-import { describe, it, expect, vi } from "vitest";
-import { McpManager } from "../manager";
-import { McpClient } from "../client";
-import { McpServerInfo } from "../../types";
-
-function makeMockServer(name: string, url = "http://mock-server:3000/mcp"): McpServerInfo {
+function makeMockServer(name: string, url = 'http://mock-server:3000/mcp'): McpServerInfo {
return {
name,
description: `Mock ${name}`,
- contextRef: "test-context",
- transport: { type: "streamableHttp", url },
+ contextRef: 'test-context',
+ transport: { type: 'streamableHttp', url },
enabled: true,
status: { deployed: true, ready: true },
- };
+ }
}
-describe("McpClient — proxy URL resolution", () => {
- it("should use direct URL when no proxy configured", () => {
- const server = makeMockServer("mongodb", "http://mongodb.mcp-server:3000/mcp");
- const client = new McpClient(server);
+describe('McpClient — proxy URL resolution', () => {
+ it('should use direct URL when no proxy configured', () => {
+ const server = makeMockServer('mongodb', 'http://mongodb.mcp-server:3000/mcp')
+ const client = new McpClient(server)
// Access private resolveUrl via any cast
- const url = (client as any).resolveUrl();
- expect(url).toBe("http://mongodb.mcp-server:3000/mcp");
- });
-
- it("should use proxy URL when proxy configured", () => {
- const server = makeMockServer("mongodb", "http://mongodb.mcp-server:3000/mcp");
- const client = new McpClient(server, undefined, "http://mcp-proxy.mcp-server:8083");
- const url = (client as any).resolveUrl();
- expect(url).toBe("http://mcp-proxy.mcp-server:8083/servers/mongodb/mcp");
- });
-
- it("should include server name in proxy path", () => {
- const server = makeMockServer("mcp-redis-cache");
- const client = new McpClient(server, undefined, "http://proxy:8083");
- const url = (client as any).resolveUrl();
- expect(url).toBe("http://proxy:8083/servers/mcp-redis-cache/mcp");
- });
-
- it("should use StreamableHTTP transport when proxy is set (even for SSE servers)", () => {
- const server = makeMockServer("legacy-sse");
- server.transport.type = "sse";
- const client = new McpClient(server, undefined, "http://proxy:8083");
- const transport = (client as any).createTransport();
- expect(transport.constructor.name).toBe("StreamableHTTPClientTransport");
- });
-
- it("should use SSE transport for SSE servers without proxy", () => {
- const server = makeMockServer("legacy-sse", "http://sse-server:3000/sse");
- server.transport.type = "sse";
- const client = new McpClient(server);
- const transport = (client as any).createTransport();
- expect(transport.constructor.name).toBe("SSEClientTransport");
- });
-
- it("should preserve auth token through proxy", () => {
- const server = makeMockServer("authed-server");
- const client = new McpClient(server, "secret-token-123", "http://proxy:8083");
+ const url = (client as any).resolveUrl()
+ expect(url).toBe('http://mongodb.mcp-server:3000/mcp')
+ })
+
+ it('should use proxy URL when proxy configured', () => {
+ const server = makeMockServer('mongodb', 'http://mongodb.mcp-server:3000/mcp')
+ const client = new McpClient(server, undefined, 'http://mcp-proxy.mcp-server:8083')
+ const url = (client as any).resolveUrl()
+ expect(url).toBe('http://mcp-proxy.mcp-server:8083/servers/mongodb/mcp')
+ })
+
+ it('should include server name in proxy path', () => {
+ const server = makeMockServer('mcp-redis-cache')
+ const client = new McpClient(server, undefined, 'http://proxy:8083')
+ const url = (client as any).resolveUrl()
+ expect(url).toBe('http://proxy:8083/servers/mcp-redis-cache/mcp')
+ })
+
+ it('should use StreamableHTTP transport when proxy is set (even for SSE servers)', () => {
+ const server = makeMockServer('legacy-sse')
+ server.transport.type = 'sse'
+ const client = new McpClient(server, undefined, 'http://proxy:8083')
+ const transport = (client as any).createTransport()
+ expect(transport.constructor.name).toBe('StreamableHTTPClientTransport')
+ })
+
+ it('should use SSE transport for SSE servers without proxy', () => {
+ const server = makeMockServer('legacy-sse', 'http://sse-server:3000/sse')
+ server.transport.type = 'sse'
+ const client = new McpClient(server)
+ const transport = (client as any).createTransport()
+ expect(transport.constructor.name).toBe('SSEClientTransport')
+ })
+
+ it('should preserve auth token through proxy', () => {
+ const server = makeMockServer('authed-server')
+ const client = new McpClient(server, 'secret-token-123', 'http://proxy:8083')
// Verify the URL is correct (auth is handled at transport level)
- const url = (client as any).resolveUrl();
- expect(url).toBe("http://proxy:8083/servers/authed-server/mcp");
- });
-});
-
-describe("McpManager — proxy mode constructor", () => {
- it("should accept no arguments (backward compatible)", () => {
- const manager = new McpManager();
- expect(manager.getConnectedServers()).toEqual([]);
- });
-
- it("should accept proxy URL", () => {
- const manager = new McpManager("http://proxy:8083");
- expect(manager.getConnectedServers()).toEqual([]);
- });
-
- it("should accept undefined proxy URL (explicit direct mode)", () => {
- const manager = new McpManager(undefined);
- expect(manager.getConnectedServers()).toEqual([]);
- });
-
- it("should pass proxy URL to McpClient on addServer", async () => {
- const manager = new McpManager("http://proxy:8083");
- const server = makeMockServer("test-server");
+ const url = (client as any).resolveUrl()
+ expect(url).toBe('http://proxy:8083/servers/authed-server/mcp')
+ })
+})
+
+describe('McpManager — proxy mode constructor', () => {
+ it('should accept no arguments (backward compatible)', () => {
+ const manager = new McpManager()
+ expect(manager.getConnectedServers()).toEqual([])
+ })
+
+ it('should accept proxy URL', () => {
+ const manager = new McpManager('http://proxy:8083')
+ expect(manager.getConnectedServers()).toEqual([])
+ })
+
+ it('should accept undefined proxy URL (explicit direct mode)', () => {
+ const manager = new McpManager(undefined)
+ expect(manager.getConnectedServers()).toEqual([])
+ })
+
+ it('should pass proxy URL to McpClient on addServer', async () => {
+ const manager = new McpManager('http://proxy:8083')
+ const server = makeMockServer('test-server')
// Mock McpClient.connect to avoid real network calls
- const connectSpy = vi.spyOn(McpClient.prototype, "connect").mockResolvedValue();
- vi.spyOn(McpClient.prototype, "availableTools", "get").mockReturnValue([]);
+ const connectSpy = vi.spyOn(McpClient.prototype, 'connect').mockResolvedValue()
+ vi.spyOn(McpClient.prototype, 'availableTools', 'get').mockReturnValue([])
- await manager.addServer(server);
+ await manager.addServer(server)
- expect(connectSpy).toHaveBeenCalledTimes(1);
- expect(manager.getConnectedServers()).toEqual(["test-server"]);
+ expect(connectSpy).toHaveBeenCalledTimes(1)
+ expect(manager.getConnectedServers()).toEqual(['test-server'])
// Clean up
- vi.restoreAllMocks();
- await manager.disconnectAll();
- });
-});
-
-describe("McpManager — feature flag behavior", () => {
- it("MCP_PROXY_ENABLED=false uses no proxy (direct URLs)", () => {
- const proxyUrl = false ? "http://proxy:8083" : undefined;
- const manager = new McpManager(proxyUrl);
- expect((manager as any).proxyUrl).toBeUndefined();
- });
-
- it("MCP_PROXY_ENABLED=true uses proxy URL", () => {
- const proxyEnabled = true;
- const proxyUrl = proxyEnabled ? "http://proxy:8083" : undefined;
- const manager = new McpManager(proxyUrl);
- expect((manager as any).proxyUrl).toBe("http://proxy:8083");
- });
-});
-
-describe("McpManager — public API unchanged (regression guards)", () => {
- it("should expose getAllTools() method", () => {
- const manager = new McpManager("http://proxy:8083");
- expect(typeof manager.getAllTools).toBe("function");
- expect(manager.getAllTools()).toEqual([]);
- });
-
- it("should expose callTool() method with same signature", async () => {
- const manager = new McpManager("http://proxy:8083");
- const result = await manager.callTool("missing__tool", {});
- expect(result.isError).toBe(true);
- expect(result.result).toEqual({ error: "MCP server not found: missing" });
- });
-
- it("should expose getConnectedServers() method", () => {
- const manager = new McpManager("http://proxy:8083");
- expect(typeof manager.getConnectedServers).toBe("function");
- });
-
- it("should expose hasConnectedServers() method", () => {
- const manager = new McpManager("http://proxy:8083");
- expect(manager.hasConnectedServers()).toBe(false);
- });
-
- it("should expose describeCapabilities() method", () => {
- const manager = new McpManager("http://proxy:8083");
- expect(typeof manager.describeCapabilities).toBe("function");
- expect(manager.describeCapabilities()).toContain("No MCP servers");
- });
-});
+ vi.restoreAllMocks()
+ await manager.disconnectAll()
+ })
+})
+
+describe('McpManager — feature flag behavior', () => {
+ it('MCP_PROXY_ENABLED=false uses no proxy (direct URLs)', () => {
+ const proxyUrl = false ? 'http://proxy:8083' : undefined
+ const manager = new McpManager(proxyUrl)
+ expect((manager as any).proxyUrl).toBeUndefined()
+ })
+
+ it('MCP_PROXY_ENABLED=true uses proxy URL', () => {
+ const proxyEnabled = true
+ const proxyUrl = proxyEnabled ? 'http://proxy:8083' : undefined
+ const manager = new McpManager(proxyUrl)
+ expect((manager as any).proxyUrl).toBe('http://proxy:8083')
+ })
+})
+
+describe('McpManager — public API unchanged (regression guards)', () => {
+ it('should expose getAllTools() method', () => {
+ const manager = new McpManager('http://proxy:8083')
+ expect(typeof manager.getAllTools).toBe('function')
+ expect(manager.getAllTools()).toEqual([])
+ })
+
+ it('should expose callTool() method with same signature', async () => {
+ const manager = new McpManager('http://proxy:8083')
+ const result = await manager.callTool('missing__tool', {})
+ expect(result.isError).toBe(true)
+ expect(result.result).toEqual({ error: 'MCP server not found: missing' })
+ })
+
+ it('should expose getConnectedServers() method', () => {
+ const manager = new McpManager('http://proxy:8083')
+ expect(typeof manager.getConnectedServers).toBe('function')
+ })
+
+ it('should expose hasConnectedServers() method', () => {
+ const manager = new McpManager('http://proxy:8083')
+ expect(manager.hasConnectedServers()).toBe(false)
+ })
+
+ it('should expose describeCapabilities() method', () => {
+ const manager = new McpManager('http://proxy:8083')
+ expect(typeof manager.describeCapabilities).toBe('function')
+ expect(manager.describeCapabilities()).toContain('No MCP servers')
+ })
+})
diff --git a/mcp-host/src/mcp/__tests__/reconnectMutex.test.ts b/mcp-host/src/mcp/__tests__/reconnectMutex.test.ts
index 599a242fb..61a5f0916 100644
--- a/mcp-host/src/mcp/__tests__/reconnectMutex.test.ts
+++ b/mcp-host/src/mcp/__tests__/reconnectMutex.test.ts
@@ -1,71 +1,68 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { McpClient } from "../client";
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { McpClient } from '../client'
// Mock the MCP SDK transports with proper class constructors
-vi.mock("@modelcontextprotocol/sdk/client/index.js", () => ({
+vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
Client: class MockClient {
- connect = vi.fn().mockResolvedValue(undefined);
- close = vi.fn().mockResolvedValue(undefined);
- listTools = vi.fn().mockResolvedValue({ tools: [] });
- callTool = vi.fn().mockResolvedValue({ content: [{ type: "text", text: "ok" }] });
+ connect = vi.fn().mockResolvedValue(undefined)
+ close = vi.fn().mockResolvedValue(undefined)
+ listTools = vi.fn().mockResolvedValue({ tools: [] })
+ callTool = vi.fn().mockResolvedValue({ content: [{ type: 'text', text: 'ok' }] })
},
-}));
+}))
-vi.mock("@modelcontextprotocol/sdk/client/streamableHttp.js", () => ({
+vi.mock('@modelcontextprotocol/sdk/client/streamableHttp.js', () => ({
StreamableHTTPClientTransport: class MockStreamableHTTP {
- close = vi.fn().mockResolvedValue(undefined);
+ close = vi.fn().mockResolvedValue(undefined)
},
-}));
+}))
-vi.mock("@modelcontextprotocol/sdk/client/sse.js", () => ({
+vi.mock('@modelcontextprotocol/sdk/client/sse.js', () => ({
SSEClientTransport: class MockSSE {
- close = vi.fn().mockResolvedValue(undefined);
+ close = vi.fn().mockResolvedValue(undefined)
},
-}));
+}))
-describe("McpClient — reconnect deduplication", () => {
- let client: McpClient;
+describe('McpClient — reconnect deduplication', () => {
+ let client: McpClient
beforeEach(() => {
client = new McpClient(
{
- name: "test-server",
- description: "test",
- contextRef: "ctx",
- transport: { type: "streamableHttp", url: "http://localhost:3000/mcp" },
+ name: 'test-server',
+ description: 'test',
+ contextRef: 'ctx',
+ transport: { type: 'streamableHttp', url: 'http://localhost:3000/mcp' },
enabled: true,
status: { deployed: true, ready: true },
},
undefined,
undefined
- );
- });
+ )
+ })
- it("should deduplicate concurrent reconnect calls", async () => {
- await client.connect();
+ it('should deduplicate concurrent reconnect calls', async () => {
+ await client.connect()
// Spy on disconnect to count calls
- const disconnectSpy = vi.spyOn(client, "disconnect");
+ const disconnectSpy = vi.spyOn(client, 'disconnect')
// Fire two reconnects concurrently
- const [r1, r2] = await Promise.allSettled([
- client.reconnect(),
- client.reconnect(),
- ]);
+ const [r1, r2] = await Promise.allSettled([client.reconnect(), client.reconnect()])
- expect(r1.status).toBe("fulfilled");
- expect(r2.status).toBe("fulfilled");
+ expect(r1.status).toBe('fulfilled')
+ expect(r2.status).toBe('fulfilled')
// disconnect should only be called ONCE, not twice
- expect(disconnectSpy).toHaveBeenCalledTimes(1);
- });
+ expect(disconnectSpy).toHaveBeenCalledTimes(1)
+ })
- it("should allow reconnect after previous reconnect completes", async () => {
- await client.connect();
+ it('should allow reconnect after previous reconnect completes', async () => {
+ await client.connect()
- await client.reconnect();
- await client.reconnect();
+ await client.reconnect()
+ await client.reconnect()
// Both should succeed (serial, not concurrent)
- expect(client.isConnected).toBe(true);
- });
-});
+ expect(client.isConnected).toBe(true)
+ })
+})
diff --git a/mcp-host/src/progress/__tests__/intentExtraction.test.ts b/mcp-host/src/progress/__tests__/intentExtraction.test.ts
index 9d1fdfc8d..aa3ce05d7 100644
--- a/mcp-host/src/progress/__tests__/intentExtraction.test.ts
+++ b/mcp-host/src/progress/__tests__/intentExtraction.test.ts
@@ -1,96 +1,94 @@
-import { describe, it, expect } from "vitest";
-import { getDisplayName, sanitizeError, extractToolIntent } from "../intentExtraction.js";
+import { describe, expect, it } from 'vitest'
+import { extractToolIntent, getDisplayName, sanitizeError } from '../intentExtraction.js'
-describe("getDisplayName", () => {
- it("extracts and capitalizes MCP server name from double-underscore tool name", () => {
- expect(getDisplayName("mongodb__findDocuments")).toBe("Mongodb");
- expect(getDisplayName("airtable__getRecords")).toBe("Airtable");
- });
+describe('getDisplayName', () => {
+ it('extracts and capitalizes MCP server name from double-underscore tool name', () => {
+ expect(getDisplayName('mongodb__findDocuments')).toBe('Mongodb')
+ expect(getDisplayName('airtable__getRecords')).toBe('Airtable')
+ })
- it("maps native tools to human-friendly names", () => {
- expect(getDisplayName("file_read")).toBe("File System");
- expect(getDisplayName("file_write")).toBe("File System");
- expect(getDisplayName("shell_exec")).toBe("Shell");
- expect(getDisplayName("http_request")).toBe("HTTP");
- expect(getDisplayName("system_info")).toBe("System");
- expect(getDisplayName("json_transform")).toBe("Data Transform");
- expect(getDisplayName("memory_read")).toBe("Memory");
- expect(getDisplayName("memory_write")).toBe("Memory");
- });
+ it('maps native tools to human-friendly names', () => {
+ expect(getDisplayName('file_read')).toBe('File System')
+ expect(getDisplayName('file_write')).toBe('File System')
+ expect(getDisplayName('shell_exec')).toBe('Shell')
+ expect(getDisplayName('http_request')).toBe('HTTP')
+ expect(getDisplayName('system_info')).toBe('System')
+ expect(getDisplayName('json_transform')).toBe('Data Transform')
+ expect(getDisplayName('memory_read')).toBe('Memory')
+ expect(getDisplayName('memory_write')).toBe('Memory')
+ })
- it("falls back to raw name for unmapped tools without double-underscore", () => {
- expect(getDisplayName("unknown_tool")).toBe("unknown_tool");
- });
-});
+ it('falls back to raw name for unmapped tools without double-underscore', () => {
+ expect(getDisplayName('unknown_tool')).toBe('unknown_tool')
+ })
+})
-describe("sanitizeError", () => {
- it("returns simple error messages as-is", () => {
- expect(sanitizeError("Connection refused")).toBe("Connection refused");
- });
+describe('sanitizeError', () => {
+ it('returns simple error messages as-is', () => {
+ expect(sanitizeError('Connection refused')).toBe('Connection refused')
+ })
it("strips stack traces (lines starting with 'at ')", () => {
- const input = "Error: ECONNREFUSED\n at Socket.connect\n at TCPConnectWrap.afterConnect";
- expect(sanitizeError(input)).toBe("Error: ECONNREFUSED");
- });
+ const input = 'Error: ECONNREFUSED\n at Socket.connect\n at TCPConnectWrap.afterConnect'
+ expect(sanitizeError(input)).toBe('Error: ECONNREFUSED')
+ })
- it("strips lines containing file paths", () => {
- const input = "TypeError: x is not a function\n/usr/src/app/index.js:42:5";
- expect(sanitizeError(input)).toBe("TypeError: x is not a function");
- });
+ it('strips lines containing file paths', () => {
+ const input = 'TypeError: x is not a function\n/usr/src/app/index.js:42:5'
+ expect(sanitizeError(input)).toBe('TypeError: x is not a function')
+ })
- it("truncates to 200 characters", () => {
- const longMessage = "A".repeat(250);
- const result = sanitizeError(longMessage);
- expect(result.length).toBeLessThanOrEqual(200);
- });
+ it('truncates to 200 characters', () => {
+ const longMessage = 'A'.repeat(250)
+ const result = sanitizeError(longMessage)
+ expect(result.length).toBeLessThanOrEqual(200)
+ })
- it("strips XML/HTML tags like tool_output wrappers", () => {
- const input = '<tool_output name="http_request" sanitized="false"> HTTP 400 {"code":400,"message":"Unknown parameter"} </tool_output>';
- const result = sanitizeError(input);
- expect(result).not.toContain("<tool_output");
- expect(result).not.toContain("</tool_output>");
- expect(result).toContain("HTTP 400");
- expect(result).toContain("Unknown parameter");
- });
+ it('strips XML/HTML tags like tool_output wrappers', () => {
+ const input =
+ '<tool_output name="http_request" sanitized="false"> HTTP 400 {"code":400,"message":"Unknown parameter"} </tool_output>'
+ const result = sanitizeError(input)
+ expect(result).not.toContain('<tool_output')
+ expect(result).not.toContain('</tool_output>')
+ expect(result).toContain('HTTP 400')
+ expect(result).toContain('Unknown parameter')
+ })
- it("handles empty/null-like content", () => {
- expect(sanitizeError("")).toBe("");
- expect(sanitizeError(null as unknown as string)).toBe("");
- });
-});
+ it('handles empty/null-like content', () => {
+ expect(sanitizeError('')).toBe('')
+ expect(sanitizeError(null as unknown as string)).toBe('')
+ })
+})
-describe("extractToolIntent", () => {
- it("returns null when no LLM text content is provided", () => {
- expect(extractToolIntent(null, "mongodb__find")).toBeNull();
- expect(extractToolIntent("", "mongodb__find")).toBeNull();
- });
+describe('extractToolIntent', () => {
+ it('returns null when no LLM text content is provided', () => {
+ expect(extractToolIntent(null, 'mongodb__find')).toBeNull()
+ expect(extractToolIntent('', 'mongodb__find')).toBeNull()
+ })
it("extracts sentence mentioning the tool's server name", () => {
- const text = "Let me search MongoDB for your recent orders. I'll also check Airtable for inventory.";
- expect(extractToolIntent(text, "mongodb__findDocuments")).toBe(
- "Let me search MongoDB for your recent orders."
- );
- expect(extractToolIntent(text, "airtable__getRecords")).toBe(
+ const text =
+ "Let me search MongoDB for your recent orders. I'll also check Airtable for inventory."
+ expect(extractToolIntent(text, 'mongodb__findDocuments')).toBe(
+ 'Let me search MongoDB for your recent orders.'
+ )
+ expect(extractToolIntent(text, 'airtable__getRecords')).toBe(
"I'll also check Airtable for inventory."
- );
- });
+ )
+ })
- it("matches case-insensitively", () => {
- const text = "I'll query the mongodb database now.";
- expect(extractToolIntent(text, "mongodb__find")).toBe(
- "I'll query the mongodb database now."
- );
- });
+ it('matches case-insensitively', () => {
+ const text = "I'll query the mongodb database now."
+ expect(extractToolIntent(text, 'mongodb__find')).toBe("I'll query the mongodb database now.")
+ })
- it("returns null when no sentence matches the tool name", () => {
- const text = "Let me look that up for you.";
- expect(extractToolIntent(text, "mongodb__find")).toBeNull();
- });
+ it('returns null when no sentence matches the tool name', () => {
+ const text = 'Let me look that up for you.'
+ expect(extractToolIntent(text, 'mongodb__find')).toBeNull()
+ })
- it("handles native tool names by matching individual words from the tool name", () => {
- const text = "I'll read the file to check the contents.";
- expect(extractToolIntent(text, "file_read")).toBe(
- "I'll read the file to check the contents."
- );
- });
-});
+ it('handles native tool names by matching individual words from the tool name', () => {
+ const text = "I'll read the file to check the contents."
+ expect(extractToolIntent(text, 'file_read')).toBe("I'll read the file to check the contents.")
+ })
+})
diff --git a/mcp-host/src/progress/__tests__/reporterSubscribe.test.ts b/mcp-host/src/progress/__tests__/reporterSubscribe.test.ts
index f72d2d6e4..f9b245c6e 100644
--- a/mcp-host/src/progress/__tests__/reporterSubscribe.test.ts
+++ b/mcp-host/src/progress/__tests__/reporterSubscribe.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
+import { NoopSafety } from '../../core/safety/__tests__/noopSafety.js'
import { TaskLifecycle } from '../../lifecycle/taskLifecycle.js'
import { SseProgressReporter } from '../sseProgressReporter.js'
-import { NoopSafety } from '../../core/safety/__tests__/noopSafety.js'
import type { ProgressEvent, TerminalEvent } from '../types.js'
describe('SseProgressReporter TaskLifecycle subscription', () => {
diff --git a/mcp-host/src/progress/intentExtraction.ts b/mcp-host/src/progress/intentExtraction.ts
index adc3c3863..f50a8abfb 100644
--- a/mcp-host/src/progress/intentExtraction.ts
+++ b/mcp-host/src/progress/intentExtraction.ts
@@ -1,68 +1,63 @@
const NATIVE_TOOL_DISPLAY_NAMES: Record<string, string> = {
- file_read: "File System",
- file_write: "File System",
- shell_exec: "Shell",
- http_request: "HTTP",
- system_info: "System",
- json_transform: "Data Transform",
- memory_read: "Memory",
- memory_write: "Memory",
-};
+ file_read: 'File System',
+ file_write: 'File System',
+ shell_exec: 'Shell',
+ http_request: 'HTTP',
+ system_info: 'System',
+ json_transform: 'Data Transform',
+ memory_read: 'Memory',
+ memory_write: 'Memory',
+}
export function getDisplayName(toolName: string): string {
- const separatorIndex = toolName.indexOf("__");
+ const separatorIndex = toolName.indexOf('__')
if (separatorIndex > 0) {
- const serverName = toolName.substring(0, separatorIndex);
- return serverName.charAt(0).toUpperCase() + serverName.slice(1);
+ const serverName = toolName.substring(0, separatorIndex)
+ return serverName.charAt(0).toUpperCase() + serverName.slice(1)
}
- return NATIVE_TOOL_DISPLAY_NAMES[toolName] ?? toolName;
+ return NATIVE_TOOL_DISPLAY_NAMES[toolName] ?? toolName
}
-const MAX_ERROR_LENGTH = 200;
+const MAX_ERROR_LENGTH = 200
export function sanitizeError(content: string | null | undefined): string {
- if (!content) return "";
+ if (!content) return ''
// Strip XML/HTML tags (e.g. <tool_output ...>...</tool_output>)
- const stripped = content.replace(/<[^>]+>/g, "");
+ const stripped = content.replace(/<[^>]+>/g, '')
- const lines = stripped.split("\n");
+ const lines = stripped.split('\n')
const cleaned = lines.filter(
- (line) =>
- !line.trimStart().startsWith("at ") &&
- !/\/[\w.-]+\/[\w.-]+/.test(line),
- );
+ line => !line.trimStart().startsWith('at ') && !/\/[\w.-]+\/[\w.-]+/.test(line)
+ )
- const message = cleaned.join(" ").replace(/\s+/g, " ").trim();
- if (message.length <= MAX_ERROR_LENGTH) return message;
- return message.substring(0, MAX_ERROR_LENGTH - 3) + "...";
+ const message = cleaned.join(' ').replace(/\s+/g, ' ').trim()
+ if (message.length <= MAX_ERROR_LENGTH) return message
+ return message.substring(0, MAX_ERROR_LENGTH - 3) + '...'
}
-export function extractToolIntent(
- llmTextContent: string | null,
- toolName: string,
-): string | null {
- if (!llmTextContent?.trim()) return null;
+export function extractToolIntent(llmTextContent: string | null, toolName: string): string | null {
+ if (!llmTextContent?.trim()) return null
- const separatorIndex = toolName.indexOf("__");
- const keywords: string[] = [];
+ const separatorIndex = toolName.indexOf('__')
+ const keywords: string[] = []
if (separatorIndex > 0) {
- keywords.push(toolName.substring(0, separatorIndex));
+ keywords.push(toolName.substring(0, separatorIndex))
} else {
- keywords.push(...toolName.split("_").filter((w) => w.length > 2));
+ keywords.push(...toolName.split('_').filter(w => w.length > 2))
}
- keywords.push(toolName);
+ keywords.push(toolName)
- const sentences = llmTextContent.match(/[^.!?]+[.!?]+/g) ?? [llmTextContent];
+ const sentences = llmTextContent.match(/[^.!?]+[.!?]+/g) ?? [llmTextContent]
for (const sentence of sentences) {
- const lower = sentence.toLowerCase();
+ const lower = sentence.toLowerCase()
for (const keyword of keywords) {
if (lower.includes(keyword.toLowerCase())) {
- return sentence.trim();
+ return sentence.trim()
}
}
}
- return null;
+ return null
}
diff --git a/mcp-host/src/queue/__tests__/setLifecycleIdempotent.test.ts b/mcp-host/src/queue/__tests__/setLifecycleIdempotent.test.ts
index 890bfd589..6c7c1b3d4 100644
--- a/mcp-host/src/queue/__tests__/setLifecycleIdempotent.test.ts
+++ b/mcp-host/src/queue/__tests__/setLifecycleIdempotent.test.ts
@@ -4,7 +4,7 @@
* Verifies that calling setLifecycle more than once (same lifecycle or a different one)
* does not accumulate listeners on 'transition' or 'record:evicted'.
*/
-import { describe, it, expect } from 'vitest'
+import { describe, expect, it } from 'vitest'
import { TaskLifecycle } from '../../lifecycle/taskLifecycle'
import { MessageQueue } from '../messageQueue'
diff --git a/mcp-host/src/queue/index.ts b/mcp-host/src/queue/index.ts
index 79b19a7a3..32bd63010 100644
--- a/mcp-host/src/queue/index.ts
+++ b/mcp-host/src/queue/index.ts
@@ -2,5 +2,5 @@
* Queue module exports.
*/
-export * from "./types";
-export * from "./messageQueue";
+export * from './types'
+export * from './messageQueue'
diff --git a/mcp-host/src/session/__tests__/backgroundTask.test.ts b/mcp-host/src/session/__tests__/backgroundTask.test.ts
index afba6bd2f..bf6fe82fa 100644
--- a/mcp-host/src/session/__tests__/backgroundTask.test.ts
+++ b/mcp-host/src/session/__tests__/backgroundTask.test.ts
@@ -1,34 +1,34 @@
-import { describe, it, expect } from "vitest";
-import { parseBackgroundPrefix } from "../types";
+import { describe, expect, it } from 'vitest'
+import { parseBackgroundPrefix } from '../types'
-describe("parseBackgroundPrefix", () => {
- it("should detect /bg prefix and strip it", () => {
- const result = parseBackgroundPrefix("/bg research competitors");
- expect(result).toEqual({ isBackground: true, content: "research competitors" });
- });
+describe('parseBackgroundPrefix', () => {
+ it('should detect /bg prefix and strip it', () => {
+ const result = parseBackgroundPrefix('/bg research competitors')
+ expect(result).toEqual({ isBackground: true, content: 'research competitors' })
+ })
- it("should handle /bg with extra whitespace", () => {
- const result = parseBackgroundPrefix("/bg research competitors");
- expect(result).toEqual({ isBackground: true, content: "research competitors" });
- });
+ it('should handle /bg with extra whitespace', () => {
+ const result = parseBackgroundPrefix('/bg research competitors')
+ expect(result).toEqual({ isBackground: true, content: 'research competitors' })
+ })
- it("should return isBackground=false for normal messages", () => {
- const result = parseBackgroundPrefix("hello world");
- expect(result).toEqual({ isBackground: false, content: "hello world" });
- });
+ it('should return isBackground=false for normal messages', () => {
+ const result = parseBackgroundPrefix('hello world')
+ expect(result).toEqual({ isBackground: false, content: 'hello world' })
+ })
- it("should not match /bgfoo (must be /bg followed by space)", () => {
- const result = parseBackgroundPrefix("/bgfoo bar");
- expect(result).toEqual({ isBackground: false, content: "/bgfoo bar" });
- });
+ it('should not match /bgfoo (must be /bg followed by space)', () => {
+ const result = parseBackgroundPrefix('/bgfoo bar')
+ expect(result).toEqual({ isBackground: false, content: '/bgfoo bar' })
+ })
- it("should reject /bg with no instruction", () => {
- const result = parseBackgroundPrefix("/bg");
- expect(result).toEqual({ isBackground: false, content: "/bg" });
- });
+ it('should reject /bg with no instruction', () => {
+ const result = parseBackgroundPrefix('/bg')
+ expect(result).toEqual({ isBackground: false, content: '/bg' })
+ })
- it("should reject /bg with only whitespace after", () => {
- const result = parseBackgroundPrefix("/bg ");
- expect(result).toEqual({ isBackground: false, content: "/bg " });
- });
-});
+ it('should reject /bg with only whitespace after', () => {
+ const result = parseBackgroundPrefix('/bg ')
+ expect(result).toEqual({ isBackground: false, content: '/bg ' })
+ })
+})
diff --git a/mcp-host/src/session/__tests__/sessionKey.test.ts b/mcp-host/src/session/__tests__/sessionKey.test.ts
index 1231d85bd..39c196671 100644
--- a/mcp-host/src/session/__tests__/sessionKey.test.ts
+++ b/mcp-host/src/session/__tests__/sessionKey.test.ts
@@ -1,49 +1,72 @@
-import { describe, it, expect } from "vitest";
-import { serializeSessionKey, type SessionKey } from "../types";
+import { describe, expect, it } from 'vitest'
+import { type SessionKey, serializeSessionKey } from '../types'
-describe("serializeSessionKey", () => {
- it("should serialize key with all fields", () => {
+describe('serializeSessionKey', () => {
+ it('should serialize key with all fields', () => {
const key: SessionKey = {
- userId: "alice",
- channelType: "telegram",
- channelId: "chat-123",
- threadId: "topic-42",
- };
- expect(serializeSessionKey(key)).toBe("alice:telegram:chat-123:topic-42");
- });
+ userId: 'alice',
+ channelType: 'telegram',
+ channelId: 'chat-123',
+ threadId: 'topic-42',
+ }
+ expect(serializeSessionKey(key)).toBe('alice:telegram:chat-123:topic-42')
+ })
it("should use 'default' when threadId is undefined", () => {
const key: SessionKey = {
- userId: "alice",
- channelType: "telegram",
- channelId: "chat-123",
- };
- expect(serializeSessionKey(key)).toBe("alice:telegram:chat-123:default");
- });
+ userId: 'alice',
+ channelType: 'telegram',
+ channelId: 'chat-123',
+ }
+ expect(serializeSessionKey(key)).toBe('alice:telegram:chat-123:default')
+ })
- it("should produce different keys for different threads", () => {
- const key1: SessionKey = { userId: "alice", channelType: "slack", channelId: "C1", threadId: "t1" };
- const key2: SessionKey = { userId: "alice", channelType: "slack", channelId: "C1", threadId: "t2" };
- expect(serializeSessionKey(key1)).not.toBe(serializeSessionKey(key2));
- });
+ it('should produce different keys for different threads', () => {
+ const key1: SessionKey = {
+ userId: 'alice',
+ channelType: 'slack',
+ channelId: 'C1',
+ threadId: 't1',
+ }
+ const key2: SessionKey = {
+ userId: 'alice',
+ channelType: 'slack',
+ channelId: 'C1',
+ threadId: 't2',
+ }
+ expect(serializeSessionKey(key1)).not.toBe(serializeSessionKey(key2))
+ })
- it("should produce different keys for different channels", () => {
- const key1: SessionKey = { userId: "alice", channelType: "telegram", channelId: "chat-1" };
- const key2: SessionKey = { userId: "alice", channelType: "slack", channelId: "chat-1" };
- expect(serializeSessionKey(key1)).not.toBe(serializeSessionKey(key2));
- });
+ it('should produce different keys for different channels', () => {
+ const key1: SessionKey = { userId: 'alice', channelType: 'telegram', channelId: 'chat-1' }
+ const key2: SessionKey = { userId: 'alice', channelType: 'slack', channelId: 'chat-1' }
+ expect(serializeSessionKey(key1)).not.toBe(serializeSessionKey(key2))
+ })
- it("should treat empty string threadId same as undefined", () => {
- const keyEmpty: SessionKey = { userId: "alice", channelType: "telegram", channelId: "chat-1", threadId: "" };
- const keyUndefined: SessionKey = { userId: "alice", channelType: "telegram", channelId: "chat-1" };
- expect(serializeSessionKey(keyEmpty)).toBe(serializeSessionKey(keyUndefined));
- });
+ it('should treat empty string threadId same as undefined', () => {
+ const keyEmpty: SessionKey = {
+ userId: 'alice',
+ channelType: 'telegram',
+ channelId: 'chat-1',
+ threadId: '',
+ }
+ const keyUndefined: SessionKey = {
+ userId: 'alice',
+ channelType: 'telegram',
+ channelId: 'chat-1',
+ }
+ expect(serializeSessionKey(keyEmpty)).toBe(serializeSessionKey(keyUndefined))
+ })
it("should use 'default' when channelId is empty or undefined", () => {
- const keyEmpty: SessionKey = { userId: "alice", channelType: "rpc", channelId: "" };
- const keyUndefined: SessionKey = { userId: "alice", channelType: "rpc", channelId: undefined as unknown as string };
- const keyDefault: SessionKey = { userId: "alice", channelType: "rpc", channelId: "default" };
- expect(serializeSessionKey(keyEmpty)).toBe(serializeSessionKey(keyDefault));
- expect(serializeSessionKey(keyUndefined)).toBe(serializeSessionKey(keyDefault));
- });
-});
+ const keyEmpty: SessionKey = { userId: 'alice', channelType: 'rpc', channelId: '' }
+ const keyUndefined: SessionKey = {
+ userId: 'alice',
+ channelType: 'rpc',
+ channelId: undefined as unknown as string,
+ }
+ const keyDefault: SessionKey = { userId: 'alice', channelType: 'rpc', channelId: 'default' }
+ expect(serializeSessionKey(keyEmpty)).toBe(serializeSessionKey(keyDefault))
+ expect(serializeSessionKey(keyUndefined)).toBe(serializeSessionKey(keyDefault))
+ })
+})
diff --git a/mcp-host/src/shared/encoding.ts b/mcp-host/src/shared/encoding.ts
index 51e92c75a..aa234db71 100644
--- a/mcp-host/src/shared/encoding.ts
+++ b/mcp-host/src/shared/encoding.ts
@@ -20,10 +20,10 @@
* ```
*/
export function approxDecodedBytes(base64: string): number {
- const len = base64.length;
- if (len === 0) return 0;
- const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
- return Math.floor((len * 3) / 4) - padding;
+ const len = base64.length
+ if (len === 0) return 0
+ const padding = base64.endsWith('==') ? 2 : base64.endsWith('=') ? 1 : 0
+ return Math.floor((len * 3) / 4) - padding
}
/**
@@ -34,5 +34,5 @@ export function approxDecodedBytes(base64: string): number {
* @returns true if within limits, false otherwise
*/
export function isValidBase64Size(base64: string, maxBytes: number): boolean {
- return approxDecodedBytes(base64) <= maxBytes;
+ return approxDecodedBytes(base64) <= maxBytes
}
diff --git a/mcp-host/src/workspace/__tests__/search.test.ts b/mcp-host/src/workspace/__tests__/search.test.ts
index f30658258..92f1e72cb 100644
--- a/mcp-host/src/workspace/__tests__/search.test.ts
+++ b/mcp-host/src/workspace/__tests__/search.test.ts
@@ -1,130 +1,115 @@
-import { describe, it, expect, beforeEach, afterEach } from "vitest";
-import * as fs from "fs/promises";
-import * as os from "os";
-import * as path from "path";
-import { searchWorkspace } from "../search";
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import * as fs from 'fs/promises'
+import * as os from 'os'
+import * as path from 'path'
+import { searchWorkspace } from '../search'
async function makeTempDir(): Promise<string> {
- return fs.mkdtemp(path.join(os.tmpdir(), "clerum-search-test-"));
+ return fs.mkdtemp(path.join(os.tmpdir(), 'clerum-search-test-'))
}
-describe("searchWorkspace", () => {
- let tmpDir: string;
+describe('searchWorkspace', () => {
+ let tmpDir: string
beforeEach(async () => {
- tmpDir = await makeTempDir();
- });
+ tmpDir = await makeTempDir()
+ })
afterEach(async () => {
- await fs.rm(tmpDir, { recursive: true, force: true });
- });
-
- it("returns empty array when workspace is empty", async () => {
- const results = await searchWorkspace(tmpDir, "hello");
- expect(results).toEqual([]);
- });
-
- it("finds an exact keyword match", async () => {
- await fs.writeFile(path.join(tmpDir, "MEMORY.md"), "API design decisions were made on Tuesday.");
- const results = await searchWorkspace(tmpDir, "API design");
- expect(results.length).toBeGreaterThan(0);
- expect(results[0].content).toContain("API design");
- });
-
- it("scores full match higher than partial match", async () => {
- await fs.writeFile(
- path.join(tmpDir, "full.md"),
- "The API design decisions were documented.",
- );
- await fs.writeFile(
- path.join(tmpDir, "partial.md"),
- "The API endpoint was created last week.",
- );
-
- const results = await searchWorkspace(tmpDir, "API design decisions");
- expect(results.length).toBeGreaterThanOrEqual(2);
+ await fs.rm(tmpDir, { recursive: true, force: true })
+ })
+
+ it('returns empty array when workspace is empty', async () => {
+ const results = await searchWorkspace(tmpDir, 'hello')
+ expect(results).toEqual([])
+ })
+
+ it('finds an exact keyword match', async () => {
+ await fs.writeFile(path.join(tmpDir, 'MEMORY.md'), 'API design decisions were made on Tuesday.')
+ const results = await searchWorkspace(tmpDir, 'API design')
+ expect(results.length).toBeGreaterThan(0)
+ expect(results[0].content).toContain('API design')
+ })
+
+ it('scores full match higher than partial match', async () => {
+ await fs.writeFile(path.join(tmpDir, 'full.md'), 'The API design decisions were documented.')
+ await fs.writeFile(path.join(tmpDir, 'partial.md'), 'The API endpoint was created last week.')
+
+ const results = await searchWorkspace(tmpDir, 'API design decisions')
+ expect(results.length).toBeGreaterThanOrEqual(2)
// full.md matches 3/3 keywords; partial.md matches 1/3
- const fullResult = results.find((r) => r.path === "full.md");
- const partialResult = results.find((r) => r.path === "partial.md");
- expect(fullResult).toBeDefined();
- expect(partialResult).toBeDefined();
- expect(fullResult!.score).toBeGreaterThan(partialResult!.score);
- });
-
- it("applies recency boost to daily log files", async () => {
- await fs.mkdir(path.join(tmpDir, "daily"), { recursive: true });
- await fs.writeFile(
- path.join(tmpDir, "daily", "2026-02-25.md"),
- "The deployment was successful.",
- );
+ const fullResult = results.find(r => r.path === 'full.md')
+ const partialResult = results.find(r => r.path === 'partial.md')
+ expect(fullResult).toBeDefined()
+ expect(partialResult).toBeDefined()
+ expect(fullResult!.score).toBeGreaterThan(partialResult!.score)
+ })
+
+ it('applies recency boost to daily log files', async () => {
+ await fs.mkdir(path.join(tmpDir, 'daily'), { recursive: true })
await fs.writeFile(
- path.join(tmpDir, "notes.md"),
- "The deployment was successful.",
- );
-
- const results = await searchWorkspace(tmpDir, "deployment successful");
- const dailyResult = results.find((r) => r.path.startsWith("daily"));
- const notesResult = results.find((r) => r.path === "notes.md");
- expect(dailyResult).toBeDefined();
- expect(notesResult).toBeDefined();
+ path.join(tmpDir, 'daily', '2026-02-25.md'),
+ 'The deployment was successful.'
+ )
+ await fs.writeFile(path.join(tmpDir, 'notes.md'), 'The deployment was successful.')
+
+ const results = await searchWorkspace(tmpDir, 'deployment successful')
+ const dailyResult = results.find(r => r.path.startsWith('daily'))
+ const notesResult = results.find(r => r.path === 'notes.md')
+ expect(dailyResult).toBeDefined()
+ expect(notesResult).toBeDefined()
// Daily logs get 1.2x boost — score should be higher
- expect(dailyResult!.score).toBeGreaterThan(notesResult!.score);
- });
-
- it("applies identity boost to MEMORY.md", async () => {
- await fs.writeFile(
- path.join(tmpDir, "MEMORY.md"),
- "Database schema finalized.",
- );
- await fs.writeFile(
- path.join(tmpDir, "other.md"),
- "Database schema finalized.",
- );
-
- const results = await searchWorkspace(tmpDir, "database schema finalized");
- const memoryResult = results.find((r) => r.path === "MEMORY.md");
- const otherResult = results.find((r) => r.path === "other.md");
- expect(memoryResult).toBeDefined();
- expect(otherResult).toBeDefined();
- expect(memoryResult!.score).toBeGreaterThan(otherResult!.score);
- });
-
- it("respects the limit parameter", async () => {
+ expect(dailyResult!.score).toBeGreaterThan(notesResult!.score)
+ })
+
+ it('applies identity boost to MEMORY.md', async () => {
+ await fs.writeFile(path.join(tmpDir, 'MEMORY.md'), 'Database schema finalized.')
+ await fs.writeFile(path.join(tmpDir, 'other.md'), 'Database schema finalized.')
+
+ const results = await searchWorkspace(tmpDir, 'database schema finalized')
+ const memoryResult = results.find(r => r.path === 'MEMORY.md')
+ const otherResult = results.find(r => r.path === 'other.md')
+ expect(memoryResult).toBeDefined()
+ expect(otherResult).toBeDefined()
+ expect(memoryResult!.score).toBeGreaterThan(otherResult!.score)
+ })
+
+ it('respects the limit parameter', async () => {
for (let i = 0; i < 10; i++) {
- await fs.writeFile(path.join(tmpDir, `file${i}.md`), "keyword content here");
+ await fs.writeFile(path.join(tmpDir, `file${i}.md`), 'keyword content here')
}
- const results = await searchWorkspace(tmpDir, "keyword", { limit: 3 });
- expect(results.length).toBeLessThanOrEqual(3);
- });
-
- it("truncates long paragraphs to 500 chars", async () => {
- const longContent = "keyword " + "x".repeat(600);
- await fs.writeFile(path.join(tmpDir, "long.md"), longContent);
- const results = await searchWorkspace(tmpDir, "keyword");
- expect(results[0].content.length).toBeLessThanOrEqual(510); // 500 + "…"
- });
-
- it("returns results sorted by score descending", async () => {
- await fs.writeFile(path.join(tmpDir, "a.md"), "cats and dogs");
- await fs.writeFile(path.join(tmpDir, "b.md"), "cats dogs and birds");
-
- const results = await searchWorkspace(tmpDir, "cats dogs");
+ const results = await searchWorkspace(tmpDir, 'keyword', { limit: 3 })
+ expect(results.length).toBeLessThanOrEqual(3)
+ })
+
+ it('truncates long paragraphs to 500 chars', async () => {
+ const longContent = 'keyword ' + 'x'.repeat(600)
+ await fs.writeFile(path.join(tmpDir, 'long.md'), longContent)
+ const results = await searchWorkspace(tmpDir, 'keyword')
+ expect(results[0].content.length).toBeLessThanOrEqual(510) // 500 + "…"
+ })
+
+ it('returns results sorted by score descending', async () => {
+ await fs.writeFile(path.join(tmpDir, 'a.md'), 'cats and dogs')
+ await fs.writeFile(path.join(tmpDir, 'b.md'), 'cats dogs and birds')
+
+ const results = await searchWorkspace(tmpDir, 'cats dogs')
for (let i = 1; i < results.length; i++) {
- expect(results[i - 1].score).toBeGreaterThanOrEqual(results[i].score);
+ expect(results[i - 1].score).toBeGreaterThanOrEqual(results[i].score)
}
- });
-
- it("is case-insensitive", async () => {
- await fs.writeFile(path.join(tmpDir, "doc.md"), "The API Design is important.");
- const results = await searchWorkspace(tmpDir, "api design");
- expect(results.length).toBeGreaterThan(0);
- });
-
- it("only searches .md files", async () => {
- await fs.writeFile(path.join(tmpDir, "notes.txt"), "secret keyword here");
- await fs.writeFile(path.join(tmpDir, "notes.md"), "other content");
- const results = await searchWorkspace(tmpDir, "keyword");
- const txtResult = results.find((r) => r.path === "notes.txt");
- expect(txtResult).toBeUndefined();
- });
-});
+ })
+
+ it('is case-insensitive', async () => {
+ await fs.writeFile(path.join(tmpDir, 'doc.md'), 'The API Design is important.')
+ const results = await searchWorkspace(tmpDir, 'api design')
+ expect(results.length).toBeGreaterThan(0)
+ })
+
+ it('only searches .md files', async () => {
+ await fs.writeFile(path.join(tmpDir, 'notes.txt'), 'secret keyword here')
+ await fs.writeFile(path.join(tmpDir, 'notes.md'), 'other content')
+ const results = await searchWorkspace(tmpDir, 'keyword')
+ const txtResult = results.find(r => r.path === 'notes.txt')
+ expect(txtResult).toBeUndefined()
+ })
+})
diff --git a/mcp-host/src/workspace/index.ts b/mcp-host/src/workspace/index.ts
index a2feaffcb..1dba8f6d6 100644
--- a/mcp-host/src/workspace/index.ts
+++ b/mcp-host/src/workspace/index.ts
@@ -1,2 +1,2 @@
-export { WorkspaceService } from "./service";
-export type { WorkspaceEntry, SearchResult, SearchConfig } from "./types";
+export { WorkspaceService } from './service'
+export type { WorkspaceEntry, SearchResult, SearchConfig } from './types'
diff --git a/mcp-host/src/workspace/types.ts b/mcp-host/src/workspace/types.ts
index 80654677c..57ed3b93f 100644
--- a/mcp-host/src/workspace/types.ts
+++ b/mcp-host/src/workspace/types.ts
@@ -3,21 +3,21 @@
*/
export interface WorkspaceEntry {
- name: string;
- path: string;
- type: "file" | "directory";
- size?: number;
- modifiedAt?: string;
+ name: string
+ path: string
+ type: 'file' | 'directory'
+ size?: number
+ modifiedAt?: string
}
export interface SearchResult {
- path: string;
- content: string; // matched paragraph/chunk
- score: number; // 0.0–1.0 normalized
- lineNumber?: number;
+ path: string
+ content: string // matched paragraph/chunk
+ score: number // 0.0–1.0 normalized
+ lineNumber?: number
}
export interface SearchConfig {
- limit: number; // default: 10
- minScore: number; // default: 0.0
+ limit: number // default: 10
+ minScore: number // default: 0.0
}
diff --git a/mcp-proxy/README.md b/mcp-proxy/README.md
index c3030a9aa..3ad4dbdb6 100644
--- a/mcp-proxy/README.md
+++ b/mcp-proxy/README.md
@@ -31,18 +31,18 @@ MCP Server (e.g. mongodb-mcp:3000, stdio-bridge:3000)
## Environment Variables
-| Variable | Default | Description |
-|----------|---------|-------------|
-| `MCP_PROXY_PORT` | `8083` | HTTP listen port |
-| `HCC_API_URL` | `http://host-context-controller.control-plane:8081` | HCC API base URL |
-| `HCC_POLL_INTERVAL` | `30000` | Server discovery poll interval (ms) |
-| `HCC_CACHE_TTL` | `120000` | Cache staleness threshold (ms) -- health warns |
-| `HCC_CACHE_EXPIRY` | `300000` | Cache expiry threshold (ms) -- readiness fails |
-| `MCP_PROXY_REQUEST_TIMEOUT` | `30000` | Per-request forwarding timeout (ms) |
-| `MCP_PROXY_MAX_RESPONSE_SIZE` | `10485760` | Max response body size (10 MB) |
-| `CLERUM_DEV_MODE` | `false` | Dev mode: skip HCC polling, use static server list |
-| `MCP_PROXY_SERVERS` | `[]` | JSON array of `ServerRoute` objects (dev mode only) |
-| `LOG_LEVEL` | `info` | Log verbosity |
+| Variable | Default | Description |
+| ----------------------------- | --------------------------------------------------- | --------------------------------------------------- |
+| `MCP_PROXY_PORT` | `8083` | HTTP listen port |
+| `HCC_API_URL` | `http://host-context-controller.control-plane:8081` | HCC API base URL |
+| `HCC_POLL_INTERVAL` | `30000` | Server discovery poll interval (ms) |
+| `HCC_CACHE_TTL` | `120000` | Cache staleness threshold (ms) -- health warns |
+| `HCC_CACHE_EXPIRY` | `300000` | Cache expiry threshold (ms) -- readiness fails |
+| `MCP_PROXY_REQUEST_TIMEOUT` | `30000` | Per-request forwarding timeout (ms) |
+| `MCP_PROXY_MAX_RESPONSE_SIZE` | `10485760` | Max response body size (10 MB) |
+| `CLERUM_DEV_MODE` | `false` | Dev mode: skip HCC polling, use static server list |
+| `MCP_PROXY_SERVERS` | `[]` | JSON array of `ServerRoute` objects (dev mode only) |
+| `LOG_LEVEL` | `info` | Log verbosity |
## Local Development
diff --git a/mcp-proxy/package-lock.json b/mcp-proxy/package-lock.json
index 4b62e0ec9..7d372752c 100644
--- a/mcp-proxy/package-lock.json
+++ b/mcp-proxy/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-proxy",
- "version": "0.1.3",
+ "version": "0.1.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-proxy",
- "version": "0.1.3",
+ "version": "0.1.4",
"license": "SEE LICENSE IN LICENSE",
"devDependencies": {
"@types/node": "^20.10.0",
diff --git a/mcp-proxy/package.json b/mcp-proxy/package.json
index 1615f3ea9..96ccd4055 100644
--- a/mcp-proxy/package.json
+++ b/mcp-proxy/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-proxy",
- "version": "0.1.3",
+ "version": "0.1.4",
"description": "MCP Proxy - centralized HTTP router for MCP servers",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-proxy/src/hccClient.ts b/mcp-proxy/src/hccClient.ts
index 163a9f793..37724f1ab 100644
--- a/mcp-proxy/src/hccClient.ts
+++ b/mcp-proxy/src/hccClient.ts
@@ -1,100 +1,102 @@
-import http from "node:http";
-import { ServerRoute, HccServersResponse, ProxyConfig } from "./types";
+import http from 'node:http'
+import { HccServersResponse, ProxyConfig, ServerRoute } from './types'
export class HccClient {
- private config: ProxyConfig;
- private cache: ServerRoute[] = [];
- private lastSuccessfulPoll: number = 0;
+ private config: ProxyConfig
+ private cache: ServerRoute[] = []
+ private lastSuccessfulPoll: number = 0
constructor(config: ProxyConfig) {
- this.config = config;
+ this.config = config
}
async fetchServers(): Promise<ServerRoute[]> {
try {
const response = await this.httpGet<HccServersResponse>(
`${this.config.hccApiUrl}/api/v1/mcpservers`
- );
+ )
- this.cache = response.servers.map((s) => ({
+ this.cache = response.servers.map(s => ({
name: s.name,
url: s.transport.url || `http://${s.name}.mcp-server.svc.cluster.local:3000/mcp`,
contextRef: s.contextRef,
managed: s.enabled,
ready: s.status.ready,
- port: this.extractPort(s.transport.url || `http://${s.name}.mcp-server.svc.cluster.local:3000/mcp`),
- }));
+ port: this.extractPort(
+ s.transport.url || `http://${s.name}.mcp-server.svc.cluster.local:3000/mcp`
+ ),
+ }))
- this.lastSuccessfulPoll = Date.now();
- return this.cache;
+ this.lastSuccessfulPoll = Date.now()
+ return this.cache
} catch (err) {
- console.error(`[HccClient] Poll failed: ${err instanceof Error ? err.message : err}`);
- return this.cache;
+ console.error(`[HccClient] Poll failed: ${err instanceof Error ? err.message : err}`)
+ return this.cache
}
}
getCachedServers(): ServerRoute[] {
- return this.cache;
+ return this.cache
}
isCacheStale(): boolean {
- if (this.lastSuccessfulPoll === 0) return true;
- return Date.now() - this.lastSuccessfulPoll > this.config.hccCacheTTL;
+ if (this.lastSuccessfulPoll === 0) return true
+ return Date.now() - this.lastSuccessfulPoll > this.config.hccCacheTTL
}
isCacheExpired(): boolean {
- if (this.lastSuccessfulPoll === 0) return true;
- return Date.now() - this.lastSuccessfulPoll > this.config.hccCacheExpiry;
+ if (this.lastSuccessfulPoll === 0) return true
+ return Date.now() - this.lastSuccessfulPoll > this.config.hccCacheExpiry
}
getLastPollTime(): number {
- return this.lastSuccessfulPoll;
+ return this.lastSuccessfulPoll
}
private extractPort(url: string): number {
try {
- const parsed = new URL(url);
- return parseInt(parsed.port, 10) || (parsed.protocol === "https:" ? 443 : 80);
+ const parsed = new URL(url)
+ return parseInt(parsed.port, 10) || (parsed.protocol === 'https:' ? 443 : 80)
} catch {
- return 3000;
+ return 3000
}
}
private httpGet<T>(url: string): Promise<T> {
return new Promise((resolve, reject) => {
- const parsed = new URL(url);
+ const parsed = new URL(url)
const req = http.request(
{
hostname: parsed.hostname,
port: parsed.port || 80,
path: parsed.pathname + parsed.search,
- method: "GET",
+ method: 'GET',
timeout: 10000,
},
- (res) => {
- let body = "";
- res.on("data", (chunk: Buffer) => {
- body += chunk.toString();
- });
- res.on("end", () => {
+ res => {
+ let body = ''
+ res.on('data', (chunk: Buffer) => {
+ body += chunk.toString()
+ })
+ res.on('end', () => {
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
try {
- resolve(JSON.parse(body) as T);
+ resolve(JSON.parse(body) as T)
} catch {
- reject(new Error(`Invalid JSON from HCC: ${body.substring(0, 100)}`));
+ reject(new Error(`Invalid JSON from HCC: ${body.substring(0, 100)}`))
}
} else {
- reject(new Error(`HCC returned ${res.statusCode}: ${body.substring(0, 200)}`));
+ reject(new Error(`HCC returned ${res.statusCode}: ${body.substring(0, 200)}`))
}
- });
+ })
}
- );
- req.on("error", reject);
- req.on("timeout", () => {
- req.destroy();
- reject(new Error("HCC request timeout"));
- });
- req.end();
- });
+ )
+ req.on('error', reject)
+ req.on('timeout', () => {
+ req.destroy()
+ reject(new Error('HCC request timeout'))
+ })
+ req.end()
+ })
}
}
diff --git a/mcp-proxy/src/health.ts b/mcp-proxy/src/health.ts
index b70ccf103..b9d657a6b 100644
--- a/mcp-proxy/src/health.ts
+++ b/mcp-proxy/src/health.ts
@@ -1,55 +1,59 @@
-import { ServerResponse } from "node:http";
-import { Router } from "./router";
-import { HccClient } from "./hccClient";
+import { ServerResponse } from 'node:http'
+import { HccClient } from './hccClient'
+import { Router } from './router'
export class Health {
- private router: Router;
- private hccClient: HccClient;
- private alive: boolean = true;
+ private router: Router
+ private hccClient: HccClient
+ private alive: boolean = true
constructor(router: Router, hccClient: HccClient) {
- this.router = router;
- this.hccClient = hccClient;
+ this.router = router
+ this.hccClient = hccClient
}
handleHealth(res: ServerResponse): void {
if (this.alive) {
- const body: Record<string, unknown> = { status: "ok" };
+ const body: Record<string, unknown> = { status: 'ok' }
if (this.hccClient.isCacheStale()) {
- body.warning = "HCC cache stale";
+ body.warning = 'HCC cache stale'
}
- res.writeHead(200, { "Content-Type": "application/json" });
- res.end(JSON.stringify(body));
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify(body))
} else {
- res.writeHead(503, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ status: "shutting_down" }));
+ res.writeHead(503, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ status: 'shutting_down' }))
}
}
handleReady(res: ServerResponse): void {
if (this.hccClient.isCacheExpired()) {
- res.writeHead(503, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ status: "not_ready", reason: "HCC cache expired" }));
- return;
+ res.writeHead(503, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ status: 'not_ready', reason: 'HCC cache expired' }))
+ return
}
// An empty routing table after a successful HCC poll is a valid state
// (fresh cluster with no McpServer CRDs). Only require ready servers
// when the routing table is non-empty.
- const totalServers = this.router.size();
+ const totalServers = this.router.size()
if (totalServers === 0 || this.router.hasReadyServers()) {
- res.writeHead(200, { "Content-Type": "application/json" });
- res.end(JSON.stringify({
- status: "ready",
- servers: totalServers,
- }));
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end(
+ JSON.stringify({
+ status: 'ready',
+ servers: totalServers,
+ })
+ )
} else {
- res.writeHead(503, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ status: "not_ready", reason: "no servers ready", total: totalServers }));
+ res.writeHead(503, { 'Content-Type': 'application/json' })
+ res.end(
+ JSON.stringify({ status: 'not_ready', reason: 'no servers ready', total: totalServers })
+ )
}
}
setAlive(alive: boolean): void {
- this.alive = alive;
+ this.alive = alive
}
}
diff --git a/mcp-proxy/src/httpForwarder.ts b/mcp-proxy/src/httpForwarder.ts
index a75b47efb..35549d9d5 100644
--- a/mcp-proxy/src/httpForwarder.ts
+++ b/mcp-proxy/src/httpForwarder.ts
@@ -1,25 +1,21 @@
-import http, { IncomingMessage, ServerResponse } from "node:http";
+import http, { IncomingMessage, ServerResponse } from 'node:http'
export interface ForwarderConfig {
- requestTimeout: number;
- maxResponseSize: number;
- maxBufferSize: number; // Pre-commit buffer cap (bytes). Prevents unbounded memory during header-delay phase.
+ requestTimeout: number
+ maxResponseSize: number
+ maxBufferSize: number // Pre-commit buffer cap (bytes). Prevents unbounded memory during header-delay phase.
}
export class HttpForwarder {
- private config: ForwarderConfig;
+ private config: ForwarderConfig
constructor(config: ForwarderConfig) {
- this.config = config;
+ this.config = config
}
- async forward(
- req: IncomingMessage,
- res: ServerResponse,
- backendUrl: string
- ): Promise<void> {
+ async forward(req: IncomingMessage, res: ServerResponse, backendUrl: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
- const parsed = new URL(backendUrl);
+ const parsed = new URL(backendUrl)
const proxyReq = http.request(
{
@@ -30,129 +26,131 @@ export class HttpForwarder {
headers: this.buildHeaders(req, parsed.hostname),
timeout: this.config.requestTimeout,
},
- (proxyRes) => {
- const contentLength = parseInt(proxyRes.headers["content-length"] || "0", 10);
+ proxyRes => {
+ const contentLength = parseInt(proxyRes.headers['content-length'] || '0', 10)
// Known-length guard: reject immediately before sending any response bytes
if (contentLength > this.config.maxResponseSize) {
- res.writeHead(413, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ error: "Response too large" }));
- proxyReq.destroy();
- resolve();
- return;
+ res.writeHead(413, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: 'Response too large' }))
+ proxyReq.destroy()
+ resolve()
+ return
}
// For chunked/unknown-length responses, buffer initial chunks before
// committing to a status code. This prevents the silent-truncation bug
// where headers are sent as 200 and then the stream is destroyed mid-body.
- let headersSent = false;
- let totalSize = 0;
- const buffer: Buffer[] = [];
+ let headersSent = false
+ let totalSize = 0
+ const buffer: Buffer[] = []
- proxyRes.on("data", (chunk: Buffer) => {
- totalSize += chunk.length;
+ proxyRes.on('data', (chunk: Buffer) => {
+ totalSize += chunk.length
if (totalSize > this.config.maxResponseSize) {
- proxyRes.destroy();
+ proxyRes.destroy()
if (!headersSent) {
- headersSent = true;
- res.writeHead(413, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ error: "Response too large" }));
+ headersSent = true
+ res.writeHead(413, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: 'Response too large' }))
} else {
// Headers already sent — best we can do is terminate the stream.
// Client will see an incomplete response (unavoidable).
- res.end();
+ res.end()
}
- resolve();
- return;
+ resolve()
+ return
}
if (!headersSent) {
- buffer.push(chunk);
+ buffer.push(chunk)
// TM-2: Cap pre-commit buffer independently of maxResponseSize
- const bufferSize = buffer.reduce((sum, b) => sum + b.length, 0);
+ const bufferSize = buffer.reduce((sum, b) => sum + b.length, 0)
if (bufferSize >= this.config.maxBufferSize) {
- headersSent = true;
- res.writeHead(proxyRes.statusCode || 502, proxyRes.headers);
- for (const b of buffer) { res.write(b); }
- buffer.length = 0;
+ headersSent = true
+ res.writeHead(proxyRes.statusCode || 502, proxyRes.headers)
+ for (const b of buffer) {
+ res.write(b)
+ }
+ buffer.length = 0
}
} else {
- res.write(chunk);
+ res.write(chunk)
}
- });
+ })
// After first data event, flush buffer and commit headers on next tick.
// This gives us at least one chunk to check size before committing.
- proxyRes.once("data", () => {
- if (headersSent) return;
+ proxyRes.once('data', () => {
+ if (headersSent) return
process.nextTick(() => {
- if (headersSent) return;
- headersSent = true;
- res.writeHead(proxyRes.statusCode || 502, proxyRes.headers);
+ if (headersSent) return
+ headersSent = true
+ res.writeHead(proxyRes.statusCode || 502, proxyRes.headers)
for (const chunk of buffer) {
- res.write(chunk);
+ res.write(chunk)
}
- buffer.length = 0;
- });
- });
+ buffer.length = 0
+ })
+ })
- proxyRes.on("end", () => {
+ proxyRes.on('end', () => {
if (!headersSent) {
// Small response that finished within buffering phase
- headersSent = true;
- res.writeHead(proxyRes.statusCode || 502, proxyRes.headers);
+ headersSent = true
+ res.writeHead(proxyRes.statusCode || 502, proxyRes.headers)
for (const chunk of buffer) {
- res.write(chunk);
+ res.write(chunk)
}
}
- res.end();
- resolve();
- });
+ res.end()
+ resolve()
+ })
- proxyRes.on("error", (err) => {
+ proxyRes.on('error', err => {
if (!headersSent && !res.headersSent) {
- res.writeHead(502, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ error: "Backend error", message: err.message }));
+ res.writeHead(502, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: 'Backend error', message: err.message }))
} else {
- res.end();
+ res.end()
}
- resolve();
- });
+ resolve()
+ })
}
- );
+ )
- req.on("aborted", () => {
+ req.on('aborted', () => {
if (!proxyReq.destroyed) {
- proxyReq.destroy();
+ proxyReq.destroy()
}
- });
+ })
- proxyReq.on("error", (err) => {
+ proxyReq.on('error', err => {
if (!res.headersSent) {
- res.writeHead(502, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ error: "Proxy error", message: err.message }));
+ res.writeHead(502, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: 'Proxy error', message: err.message }))
}
- resolve();
- });
+ resolve()
+ })
- proxyReq.on("timeout", () => {
- proxyReq.destroy();
+ proxyReq.on('timeout', () => {
+ proxyReq.destroy()
if (!res.headersSent) {
- res.writeHead(504, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ error: "Gateway timeout" }));
+ res.writeHead(504, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: 'Gateway timeout' }))
}
- resolve();
- });
+ resolve()
+ })
- req.pipe(proxyReq);
- });
+ req.pipe(proxyReq)
+ })
}
private buildHeaders(
req: IncomingMessage,
backendHost: string
): Record<string, string | string[] | undefined> {
- const headers = { ...req.headers };
- headers.host = backendHost;
- delete headers["connection"];
- return headers;
+ const headers = { ...req.headers }
+ headers.host = backendHost
+ delete headers['connection']
+ return headers
}
}
diff --git a/mcp-proxy/src/main.ts b/mcp-proxy/src/main.ts
index 33d007517..ef7ac29fa 100644
--- a/mcp-proxy/src/main.ts
+++ b/mcp-proxy/src/main.ts
@@ -1,70 +1,70 @@
-import { loadConfig } from "./types";
-import { Router } from "./router";
-import { HccClient } from "./hccClient";
-import { HttpForwarder } from "./httpForwarder";
-import { Metrics } from "./metrics";
-import { Health } from "./health";
-import { ProxyServer } from "./server";
+import { HccClient } from './hccClient'
+import { Health } from './health'
+import { HttpForwarder } from './httpForwarder'
+import { Metrics } from './metrics'
+import { Router } from './router'
+import { ProxyServer } from './server'
+import { loadConfig } from './types'
async function main(): Promise<void> {
- const config = loadConfig();
- console.log(`[MCP Proxy] Starting (devMode=${config.devMode}, port=${config.port})`);
+ const config = loadConfig()
+ console.log(`[MCP Proxy] Starting (devMode=${config.devMode}, port=${config.port})`)
- const router = new Router();
- const hccClient = new HccClient(config);
+ const router = new Router()
+ const hccClient = new HccClient(config)
const forwarder = new HttpForwarder({
requestTimeout: config.requestTimeout,
maxResponseSize: config.maxResponseSize,
maxBufferSize: 65536, // 64KB — TM-2: cap pre-commit buffer independently
- });
- const metrics = new Metrics();
- const health = new Health(router, hccClient);
- const server = new ProxyServer(router, forwarder, metrics, health, config);
+ })
+ const metrics = new Metrics()
+ const health = new Health(router, hccClient)
+ const server = new ProxyServer(router, forwarder, metrics, health, config)
// Load initial routing table
if (config.devMode) {
- console.log(`[MCP Proxy] Dev mode: loading ${config.devServers.length} static servers`);
- router.update(config.devServers);
+ console.log(`[MCP Proxy] Dev mode: loading ${config.devServers.length} static servers`)
+ router.update(config.devServers)
} else {
- const servers = await hccClient.fetchServers();
- const { added } = router.update(servers);
- console.log(`[MCP Proxy] Initial routing table: ${added.length} servers`);
+ const servers = await hccClient.fetchServers()
+ const { added } = router.update(servers)
+ console.log(`[MCP Proxy] Initial routing table: ${added.length} servers`)
}
// Start HCC polling (production only)
- let pollInterval: ReturnType<typeof setInterval> | null = null;
+ let pollInterval: ReturnType<typeof setInterval> | null = null
if (!config.devMode) {
pollInterval = setInterval(async () => {
try {
- const servers = await hccClient.fetchServers();
- const { added, removed } = router.update(servers);
- if (added.length > 0) console.log(`[MCP Proxy] Servers added: ${added.join(", ")}`);
- if (removed.length > 0) console.log(`[MCP Proxy] Servers removed: ${removed.join(", ")}`);
+ const servers = await hccClient.fetchServers()
+ const { added, removed } = router.update(servers)
+ if (added.length > 0) console.log(`[MCP Proxy] Servers added: ${added.join(', ')}`)
+ if (removed.length > 0) console.log(`[MCP Proxy] Servers removed: ${removed.join(', ')}`)
for (const s of servers) {
- metrics.setServerHealth(s.name, s.ready);
+ metrics.setServerHealth(s.name, s.ready)
}
} catch (err) {
- console.error(`[MCP Proxy] Poll error: ${err instanceof Error ? err.message : err}`);
+ console.error(`[MCP Proxy] Poll error: ${err instanceof Error ? err.message : err}`)
}
- }, config.hccPollInterval);
+ }, config.hccPollInterval)
}
- await server.start();
+ await server.start()
// Graceful shutdown
const shutdown = async (signal: string) => {
- console.log(`[MCP Proxy] ${signal} received, shutting down...`);
- if (pollInterval) clearInterval(pollInterval);
- await server.stop();
- process.exit(0);
- };
+ console.log(`[MCP Proxy] ${signal} received, shutting down...`)
+ if (pollInterval) clearInterval(pollInterval)
+ await server.stop()
+ process.exit(0)
+ }
- process.on("SIGTERM", () => shutdown("SIGTERM"));
- process.on("SIGINT", () => shutdown("SIGINT"));
+ process.on('SIGTERM', () => shutdown('SIGTERM'))
+ process.on('SIGINT', () => shutdown('SIGINT'))
}
-main().catch((err) => {
- console.error("[MCP Proxy] Fatal error:", err);
- process.exit(1);
-});
+main().catch(err => {
+ console.error('[MCP Proxy] Fatal error:', err)
+ process.exit(1)
+})
diff --git a/mcp-proxy/src/metrics.ts b/mcp-proxy/src/metrics.ts
index c858ec3d2..446c5140f 100644
--- a/mcp-proxy/src/metrics.ts
+++ b/mcp-proxy/src/metrics.ts
@@ -1,83 +1,85 @@
export interface RequestMetric {
- server: string;
- method: string;
- status: number;
- durationMs: number;
+ server: string
+ method: string
+ status: number
+ durationMs: number
}
export class Metrics {
- private requestCounts: Map<string, number> = new Map();
- private requestDurations: Map<string, number[]> = new Map();
- private activeConnections: Map<string, number> = new Map();
- private serverHealthStatus: Map<string, boolean> = new Map();
+ private requestCounts: Map<string, number> = new Map()
+ private requestDurations: Map<string, number[]> = new Map()
+ private activeConnections: Map<string, number> = new Map()
+ private serverHealthStatus: Map<string, boolean> = new Map()
recordRequest(metric: RequestMetric): void {
- const countKey = `${metric.server}:${metric.method}:${metric.status}`;
- this.requestCounts.set(countKey, (this.requestCounts.get(countKey) || 0) + 1);
+ const countKey = `${metric.server}:${metric.method}:${metric.status}`
+ this.requestCounts.set(countKey, (this.requestCounts.get(countKey) || 0) + 1)
- const durations = this.requestDurations.get(metric.server) || [];
- durations.push(metric.durationMs);
- this.requestDurations.set(metric.server, durations);
+ const durations = this.requestDurations.get(metric.server) || []
+ durations.push(metric.durationMs)
+ this.requestDurations.set(metric.server, durations)
}
incrementActive(server: string): void {
- this.activeConnections.set(server, (this.activeConnections.get(server) || 0) + 1);
+ this.activeConnections.set(server, (this.activeConnections.get(server) || 0) + 1)
}
decrementActive(server: string): void {
- const current = this.activeConnections.get(server) || 0;
- this.activeConnections.set(server, Math.max(0, current - 1));
+ const current = this.activeConnections.get(server) || 0
+ this.activeConnections.set(server, Math.max(0, current - 1))
}
setServerHealth(server: string, healthy: boolean): void {
- this.serverHealthStatus.set(server, healthy);
+ this.serverHealthStatus.set(server, healthy)
}
getRequestCount(server: string, method: string, status: number): number {
- return this.requestCounts.get(`${server}:${method}:${status}`) || 0;
+ return this.requestCounts.get(`${server}:${method}:${status}`) || 0
}
getActiveConnections(server: string): number {
- return this.activeConnections.get(server) || 0;
+ return this.activeConnections.get(server) || 0
}
getTotalActiveConnections(): number {
- let total = 0;
+ let total = 0
for (const count of this.activeConnections.values()) {
- total += count;
+ total += count
}
- return total;
+ return total
}
toPrometheus(): string {
- const lines: string[] = [];
+ const lines: string[] = []
- lines.push("# HELP mcp_proxy_requests_total Total requests by server, method, status");
- lines.push("# TYPE mcp_proxy_requests_total counter");
+ lines.push('# HELP mcp_proxy_requests_total Total requests by server, method, status')
+ lines.push('# TYPE mcp_proxy_requests_total counter')
for (const [key, count] of this.requestCounts) {
- const [server, method, status] = key.split(":");
- lines.push(`mcp_proxy_requests_total{server="${server}",method="${method}",status="${status}"} ${count}`);
+ const [server, method, status] = key.split(':')
+ lines.push(
+ `mcp_proxy_requests_total{server="${server}",method="${method}",status="${status}"} ${count}`
+ )
}
- lines.push("# HELP mcp_proxy_active_connections Active connections by server");
- lines.push("# TYPE mcp_proxy_active_connections gauge");
+ lines.push('# HELP mcp_proxy_active_connections Active connections by server')
+ lines.push('# TYPE mcp_proxy_active_connections gauge')
for (const [server, count] of this.activeConnections) {
- lines.push(`mcp_proxy_active_connections{server="${server}"} ${count}`);
+ lines.push(`mcp_proxy_active_connections{server="${server}"} ${count}`)
}
- lines.push("# HELP mcp_proxy_server_health Server health status (1=healthy, 0=unhealthy)");
- lines.push("# TYPE mcp_proxy_server_health gauge");
+ lines.push('# HELP mcp_proxy_server_health Server health status (1=healthy, 0=unhealthy)')
+ lines.push('# TYPE mcp_proxy_server_health gauge')
for (const [server, healthy] of this.serverHealthStatus) {
- lines.push(`mcp_proxy_server_health{server="${server}"} ${healthy ? 1 : 0}`);
+ lines.push(`mcp_proxy_server_health{server="${server}"} ${healthy ? 1 : 0}`)
}
- return lines.join("\n") + "\n";
+ return lines.join('\n') + '\n'
}
reset(): void {
- this.requestCounts.clear();
- this.requestDurations.clear();
- this.activeConnections.clear();
- this.serverHealthStatus.clear();
+ this.requestCounts.clear()
+ this.requestDurations.clear()
+ this.activeConnections.clear()
+ this.serverHealthStatus.clear()
}
}
diff --git a/mcp-proxy/src/router.ts b/mcp-proxy/src/router.ts
index 199bdbd6a..5f609aa91 100644
--- a/mcp-proxy/src/router.ts
+++ b/mcp-proxy/src/router.ts
@@ -1,52 +1,52 @@
-import { ServerRoute } from "./types";
+import { ServerRoute } from './types'
export class Router {
- private routes: Map<string, ServerRoute> = new Map();
+ private routes: Map<string, ServerRoute> = new Map()
update(servers: ServerRoute[]): { added: string[]; removed: string[] } {
- const newNames = new Set(servers.map((s) => s.name));
- const oldNames = new Set(this.routes.keys());
+ const newNames = new Set(servers.map(s => s.name))
+ const oldNames = new Set(this.routes.keys())
- const added: string[] = [];
- const removed: string[] = [];
+ const added: string[] = []
+ const removed: string[] = []
for (const server of servers) {
if (!oldNames.has(server.name)) {
- added.push(server.name);
+ added.push(server.name)
}
- this.routes.set(server.name, server);
+ this.routes.set(server.name, server)
}
for (const name of oldNames) {
if (!newNames.has(name)) {
- this.routes.delete(name);
- removed.push(name);
+ this.routes.delete(name)
+ removed.push(name)
}
}
- return { added, removed };
+ return { added, removed }
}
resolve(serverName: string): ServerRoute | undefined {
- return this.routes.get(serverName);
+ return this.routes.get(serverName)
}
allRoutes(): ServerRoute[] {
- return Array.from(this.routes.values());
+ return Array.from(this.routes.values())
}
hasReadyServers(): boolean {
for (const route of this.routes.values()) {
- if (route.ready) return true;
+ if (route.ready) return true
}
- return false;
+ return false
}
size(): number {
- return this.routes.size;
+ return this.routes.size
}
clear(): void {
- this.routes.clear();
+ this.routes.clear()
}
}
diff --git a/mcp-proxy/src/server.ts b/mcp-proxy/src/server.ts
index 3e0f362f8..92db020a8 100644
--- a/mcp-proxy/src/server.ts
+++ b/mcp-proxy/src/server.ts
@@ -1,17 +1,17 @@
-import http, { IncomingMessage, ServerResponse } from "node:http";
-import { Router } from "./router";
-import { HttpForwarder } from "./httpForwarder";
-import { Metrics } from "./metrics";
-import { Health } from "./health";
-import { ProxyConfig } from "./types";
+import http, { IncomingMessage, ServerResponse } from 'node:http'
+import { Health } from './health'
+import { HttpForwarder } from './httpForwarder'
+import { Metrics } from './metrics'
+import { Router } from './router'
+import { ProxyConfig } from './types'
export class ProxyServer {
- private httpServer: http.Server | null = null;
- private router: Router;
- private forwarder: HttpForwarder;
- private metrics: Metrics;
- private health: Health;
- private config: ProxyConfig;
+ private httpServer: http.Server | null = null
+ private router: Router
+ private forwarder: HttpForwarder
+ private metrics: Metrics
+ private health: Health
+ private config: ProxyConfig
constructor(
router: Router,
@@ -20,83 +20,83 @@ export class ProxyServer {
health: Health,
config: ProxyConfig
) {
- this.router = router;
- this.forwarder = forwarder;
- this.metrics = metrics;
- this.health = health;
- this.config = config;
+ this.router = router
+ this.forwarder = forwarder
+ this.metrics = metrics
+ this.health = health
+ this.config = config
}
getPort(): number {
- const addr = this.httpServer?.address();
- if (addr && typeof addr !== "string") return addr.port;
- return this.config.port;
+ const addr = this.httpServer?.address()
+ if (addr && typeof addr !== 'string') return addr.port
+ return this.config.port
}
start(): Promise<void> {
- return new Promise((resolve) => {
+ return new Promise(resolve => {
this.httpServer = http.createServer((req, res) => {
- this.handleRequest(req, res);
- });
+ this.handleRequest(req, res)
+ })
this.httpServer.listen(this.config.port, () => {
- console.log(`[MCP Proxy] Listening on port ${this.getPort()}`);
- resolve();
- });
- });
+ console.log(`[MCP Proxy] Listening on port ${this.getPort()}`)
+ resolve()
+ })
+ })
}
async stop(): Promise<void> {
- this.health.setAlive(false);
+ this.health.setAlive(false)
- return new Promise((resolve) => {
+ return new Promise(resolve => {
if (!this.httpServer) {
- resolve();
- return;
+ resolve()
+ return
}
this.httpServer.close(() => {
- console.log("[MCP Proxy] Server stopped");
- resolve();
- });
+ console.log('[MCP Proxy] Server stopped')
+ resolve()
+ })
// Force close after 10s
setTimeout(() => {
- resolve();
- }, 10000);
- });
+ resolve()
+ }, 10000)
+ })
}
private async handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
- const url = req.url || "/";
- const method = req.method || "GET";
+ const url = req.url || '/'
+ const method = req.method || 'GET'
- if (url === "/health") {
- this.health.handleHealth(res);
- return;
+ if (url === '/health') {
+ this.health.handleHealth(res)
+ return
}
- if (url === "/ready") {
- this.health.handleReady(res);
- return;
+ if (url === '/ready') {
+ this.health.handleReady(res)
+ return
}
- if (url === "/metrics") {
- res.writeHead(200, { "Content-Type": "text/plain" });
- res.end(this.metrics.toPrometheus());
- return;
+ if (url === '/metrics') {
+ res.writeHead(200, { 'Content-Type': 'text/plain' })
+ res.end(this.metrics.toPrometheus())
+ return
}
// Route: POST /servers/{serverName}/mcp
- const match = url.match(/^\/servers\/([^/]+)\/mcp$/);
- if (match && method === "POST") {
- const serverName = match[1];
- await this.handleForward(req, res, serverName);
- return;
+ const match = url.match(/^\/servers\/([^/]+)\/mcp$/)
+ if (match && method === 'POST') {
+ const serverName = match[1]
+ await this.handleForward(req, res, serverName)
+ return
}
- res.writeHead(404, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ error: "Not found" }));
+ res.writeHead(404, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: 'Not found' }))
}
private async handleForward(
@@ -104,32 +104,32 @@ export class ProxyServer {
res: ServerResponse,
serverName: string
): Promise<void> {
- const route = this.router.resolve(serverName);
+ const route = this.router.resolve(serverName)
if (!route) {
- res.writeHead(404, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ error: `Server '${serverName}' not found` }));
- return;
+ res.writeHead(404, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: `Server '${serverName}' not found` }))
+ return
}
if (!route.ready) {
- res.writeHead(503, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ error: `Server '${serverName}' not ready` }));
- return;
+ res.writeHead(503, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: `Server '${serverName}' not ready` }))
+ return
}
- const startTime = Date.now();
- this.metrics.incrementActive(serverName);
+ const startTime = Date.now()
+ this.metrics.incrementActive(serverName)
try {
- await this.forwarder.forward(req, res, route.url);
+ await this.forwarder.forward(req, res, route.url)
this.metrics.recordRequest({
server: serverName,
- method: req.method || "POST",
+ method: req.method || 'POST',
status: res.statusCode || 200,
durationMs: Date.now() - startTime,
- });
+ })
} finally {
- this.metrics.decrementActive(serverName);
+ this.metrics.decrementActive(serverName)
}
}
}
diff --git a/mcp-proxy/src/types.ts b/mcp-proxy/src/types.ts
index b6d141227..29c883e0b 100644
--- a/mcp-proxy/src/types.ts
+++ b/mcp-proxy/src/types.ts
@@ -1,57 +1,57 @@
export interface ServerRoute {
- name: string;
- url: string;
- contextRef: string;
- managed: boolean;
- ready: boolean;
- port: number;
+ name: string
+ url: string
+ contextRef: string
+ managed: boolean
+ ready: boolean
+ port: number
}
export interface HccServerInfo {
- name: string;
- contextRef: string;
- transport: { type: string; url?: string };
- enabled: boolean;
- status: { deployed: boolean; ready: boolean };
+ name: string
+ contextRef: string
+ transport: { type: string; url?: string }
+ enabled: boolean
+ status: { deployed: boolean; ready: boolean }
}
export interface HccServersResponse {
- servers: HccServerInfo[];
- contextRef: string;
- timestamp: string;
+ servers: HccServerInfo[]
+ contextRef: string
+ timestamp: string
}
export interface ProxyConfig {
- port: number;
- hccApiUrl: string;
- hccPollInterval: number;
- hccCacheTTL: number;
- hccCacheExpiry: number;
- requestTimeout: number;
- maxResponseSize: number;
- devMode: boolean;
- devServers: ServerRoute[];
- logLevel: string;
+ port: number
+ hccApiUrl: string
+ hccPollInterval: number
+ hccCacheTTL: number
+ hccCacheExpiry: number
+ requestTimeout: number
+ maxResponseSize: number
+ devMode: boolean
+ devServers: ServerRoute[]
+ logLevel: string
}
export function loadConfig(): ProxyConfig {
- const devMode = process.env.CLERUM_DEV_MODE === "true";
+ const devMode = process.env.CLERUM_DEV_MODE === 'true'
- let devServers: ServerRoute[] = [];
+ let devServers: ServerRoute[] = []
if (devMode && process.env.MCP_PROXY_SERVERS) {
- devServers = JSON.parse(process.env.MCP_PROXY_SERVERS);
+ devServers = JSON.parse(process.env.MCP_PROXY_SERVERS)
}
return {
- port: parseInt(process.env.MCP_PROXY_PORT || "8083", 10),
- hccApiUrl: process.env.HCC_API_URL || "http://host-context-controller.control-plane:8081",
- hccPollInterval: parseInt(process.env.HCC_POLL_INTERVAL || "30000", 10),
- hccCacheTTL: parseInt(process.env.HCC_CACHE_TTL || "120000", 10),
- hccCacheExpiry: parseInt(process.env.HCC_CACHE_EXPIRY || "300000", 10),
- requestTimeout: parseInt(process.env.MCP_PROXY_REQUEST_TIMEOUT || "30000", 10),
- maxResponseSize: parseInt(process.env.MCP_PROXY_MAX_RESPONSE_SIZE || "10485760", 10),
+ port: parseInt(process.env.MCP_PROXY_PORT || '8083', 10),
+ hccApiUrl: process.env.HCC_API_URL || 'http://host-context-controller.control-plane:8081',
+ hccPollInterval: parseInt(process.env.HCC_POLL_INTERVAL || '30000', 10),
+ hccCacheTTL: parseInt(process.env.HCC_CACHE_TTL || '120000', 10),
+ hccCacheExpiry: parseInt(process.env.HCC_CACHE_EXPIRY || '300000', 10),
+ requestTimeout: parseInt(process.env.MCP_PROXY_REQUEST_TIMEOUT || '30000', 10),
+ maxResponseSize: parseInt(process.env.MCP_PROXY_MAX_RESPONSE_SIZE || '10485760', 10),
devMode,
devServers,
- logLevel: process.env.LOG_LEVEL || "info",
- };
+ logLevel: process.env.LOG_LEVEL || 'info',
+ }
}
diff --git a/mcp-proxy/test/hccClient.test.ts b/mcp-proxy/test/hccClient.test.ts
index 57e34596e..d19ada740 100644
--- a/mcp-proxy/test/hccClient.test.ts
+++ b/mcp-proxy/test/hccClient.test.ts
@@ -1,12 +1,12 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
-import http from "node:http";
-import { HccClient } from "../src/hccClient";
-import { ProxyConfig } from "../src/types";
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import http from 'node:http'
+import { HccClient } from '../src/hccClient'
+import { ProxyConfig } from '../src/types'
function makeConfig(overrides: Partial<ProxyConfig> = {}): ProxyConfig {
return {
port: 8083,
- hccApiUrl: "",
+ hccApiUrl: '',
hccPollInterval: 30000,
hccCacheTTL: 120000,
hccCacheExpiry: 300000,
@@ -14,145 +14,209 @@ function makeConfig(overrides: Partial<ProxyConfig> = {}): ProxyConfig {
maxResponseSize: 10485760,
devMode: false,
devServers: [],
- logLevel: "info",
+ logLevel: 'info',
...overrides,
- };
+ }
}
-describe("HccClient", () => {
- let mockServer: http.Server;
- let baseUrl: string;
- let responseBody: unknown;
- let responseStatus: number;
+describe('HccClient', () => {
+ let mockServer: http.Server
+ let baseUrl: string
+ let responseBody: unknown
+ let responseStatus: number
beforeEach(async () => {
- responseBody = { servers: [], contextRef: "*", timestamp: new Date().toISOString() };
- responseStatus = 200;
+ responseBody = { servers: [], contextRef: '*', timestamp: new Date().toISOString() }
+ responseStatus = 200
- await new Promise<void>((resolve) => {
+ await new Promise<void>(resolve => {
mockServer = http.createServer((_, res) => {
- res.writeHead(responseStatus, { "Content-Type": "application/json" });
- res.end(JSON.stringify(responseBody));
- });
+ res.writeHead(responseStatus, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify(responseBody))
+ })
mockServer.listen(0, () => {
- const addr = mockServer.address();
- if (addr && typeof addr !== "string") {
- baseUrl = `http://127.0.0.1:${addr.port}`;
+ const addr = mockServer.address()
+ if (addr && typeof addr !== 'string') {
+ baseUrl = `http://127.0.0.1:${addr.port}`
}
- resolve();
- });
- });
- });
+ resolve()
+ })
+ })
+ })
afterEach(async () => {
- await new Promise<void>((resolve) => mockServer.close(() => resolve()));
- });
-
- it("should fetch servers from HCC API", async () => {
- responseBody = { servers: [
- {
- name: "mongo-mcp",
- contextRef: "ctx1",
- transport: { type: "streamableHttp", url: "http://mongo.mcp-server:3000/mcp" },
- enabled: true,
- status: { deployed: true, ready: true },
- },
- ], contextRef: "*", timestamp: new Date().toISOString() };
-
- const client = new HccClient(makeConfig({ hccApiUrl: baseUrl }));
- const servers = await client.fetchServers();
-
- expect(servers).toHaveLength(1);
- expect(servers[0].name).toBe("mongo-mcp");
- expect(servers[0].port).toBe(3000);
- expect(servers[0].managed).toBe(true);
- });
-
- it("should use cache when HCC fails", async () => {
- responseBody = { servers: [
- {
- name: "server-a",
- contextRef: "ctx1",
- transport: { type: "streamableHttp", url: "http://a:3000/mcp" },
- enabled: true,
- status: { deployed: true, ready: true },
- },
- ], contextRef: "*", timestamp: new Date().toISOString() };
-
- const client = new HccClient(makeConfig({ hccApiUrl: baseUrl }));
- await client.fetchServers();
+ await new Promise<void>(resolve => mockServer.close(() => resolve()))
+ })
+
+ it('should fetch servers from HCC API', async () => {
+ responseBody = {
+ servers: [
+ {
+ name: 'mongo-mcp',
+ contextRef: 'ctx1',
+ transport: { type: 'streamableHttp', url: 'http://mongo.mcp-server:3000/mcp' },
+ enabled: true,
+ status: { deployed: true, ready: true },
+ },
+ ],
+ contextRef: '*',
+ timestamp: new Date().toISOString(),
+ }
+
+ const client = new HccClient(makeConfig({ hccApiUrl: baseUrl }))
+ const servers = await client.fetchServers()
+
+ expect(servers).toHaveLength(1)
+ expect(servers[0].name).toBe('mongo-mcp')
+ expect(servers[0].port).toBe(3000)
+ expect(servers[0].managed).toBe(true)
+ })
+
+ it('should use cache when HCC fails', async () => {
+ responseBody = {
+ servers: [
+ {
+ name: 'server-a',
+ contextRef: 'ctx1',
+ transport: { type: 'streamableHttp', url: 'http://a:3000/mcp' },
+ enabled: true,
+ status: { deployed: true, ready: true },
+ },
+ ],
+ contextRef: '*',
+ timestamp: new Date().toISOString(),
+ }
+
+ const client = new HccClient(makeConfig({ hccApiUrl: baseUrl }))
+ await client.fetchServers()
// Now make HCC fail
- responseStatus = 500;
- const servers = await client.fetchServers();
- expect(servers).toHaveLength(1);
- expect(servers[0].name).toBe("server-a");
- });
-
- it("should detect server addition", async () => {
- responseBody = { servers: [
- { name: "a", contextRef: "c", transport: { type: "streamableHttp", url: "http://a:3000/mcp" }, enabled: true, status: { deployed: true, ready: true } },
- ], contextRef: "*", timestamp: new Date().toISOString() };
-
- const client = new HccClient(makeConfig({ hccApiUrl: baseUrl }));
- let servers = await client.fetchServers();
- expect(servers).toHaveLength(1);
-
- responseBody = { servers: [
- { name: "a", contextRef: "c", transport: { type: "streamableHttp", url: "http://a:3000/mcp" }, enabled: true, status: { deployed: true, ready: true } },
- { name: "b", contextRef: "c", transport: { type: "streamableHttp", url: "http://b:3000/mcp" }, enabled: false, status: { deployed: true, ready: true } },
- ], contextRef: "*", timestamp: new Date().toISOString() };
-
- servers = await client.fetchServers();
- expect(servers).toHaveLength(2);
- });
-
- it("should report cache stale when TTL exceeded", async () => {
- const client = new HccClient(makeConfig({ hccApiUrl: baseUrl, hccCacheTTL: 1 }));
-
- responseBody = { servers: [
- { name: "a", contextRef: "c", transport: { type: "streamableHttp", url: "http://a:3000/mcp" }, enabled: true, status: { deployed: true, ready: true } },
- ], contextRef: "*", timestamp: new Date().toISOString() };
-
- await client.fetchServers();
+ responseStatus = 500
+ const servers = await client.fetchServers()
+ expect(servers).toHaveLength(1)
+ expect(servers[0].name).toBe('server-a')
+ })
+
+ it('should detect server addition', async () => {
+ responseBody = {
+ servers: [
+ {
+ name: 'a',
+ contextRef: 'c',
+ transport: { type: 'streamableHttp', url: 'http://a:3000/mcp' },
+ enabled: true,
+ status: { deployed: true, ready: true },
+ },
+ ],
+ contextRef: '*',
+ timestamp: new Date().toISOString(),
+ }
+
+ const client = new HccClient(makeConfig({ hccApiUrl: baseUrl }))
+ let servers = await client.fetchServers()
+ expect(servers).toHaveLength(1)
+
+ responseBody = {
+ servers: [
+ {
+ name: 'a',
+ contextRef: 'c',
+ transport: { type: 'streamableHttp', url: 'http://a:3000/mcp' },
+ enabled: true,
+ status: { deployed: true, ready: true },
+ },
+ {
+ name: 'b',
+ contextRef: 'c',
+ transport: { type: 'streamableHttp', url: 'http://b:3000/mcp' },
+ enabled: false,
+ status: { deployed: true, ready: true },
+ },
+ ],
+ contextRef: '*',
+ timestamp: new Date().toISOString(),
+ }
+
+ servers = await client.fetchServers()
+ expect(servers).toHaveLength(2)
+ })
+
+ it('should report cache stale when TTL exceeded', async () => {
+ const client = new HccClient(makeConfig({ hccApiUrl: baseUrl, hccCacheTTL: 1 }))
+
+ responseBody = {
+ servers: [
+ {
+ name: 'a',
+ contextRef: 'c',
+ transport: { type: 'streamableHttp', url: 'http://a:3000/mcp' },
+ enabled: true,
+ status: { deployed: true, ready: true },
+ },
+ ],
+ contextRef: '*',
+ timestamp: new Date().toISOString(),
+ }
+
+ await client.fetchServers()
// Wait for TTL to expire
- await new Promise((r) => setTimeout(r, 10));
- expect(client.isCacheStale()).toBe(true);
- });
-
- it("should report cache expired when expiry exceeded", async () => {
- const client = new HccClient(makeConfig({ hccApiUrl: baseUrl, hccCacheExpiry: 1 }));
-
- responseBody = { servers: [
- { name: "a", contextRef: "c", transport: { type: "streamableHttp", url: "http://a:3000/mcp" }, enabled: true, status: { deployed: true, ready: true } },
- ], contextRef: "*", timestamp: new Date().toISOString() };
-
- await client.fetchServers();
-
- await new Promise((r) => setTimeout(r, 10));
- expect(client.isCacheExpired()).toBe(true);
- });
-
- it("should report stale=true when no poll has occurred", () => {
- const client = new HccClient(makeConfig({ hccApiUrl: baseUrl }));
- expect(client.isCacheStale()).toBe(true);
- expect(client.isCacheExpired()).toBe(true);
- });
-
- it("should extract port from URL", async () => {
- responseBody = { servers: [
- { name: "custom-port", contextRef: "c", transport: { type: "streamableHttp", url: "http://x:8080/mcp" }, enabled: true, status: { deployed: true, ready: true } },
- ], contextRef: "*", timestamp: new Date().toISOString() };
-
- const client = new HccClient(makeConfig({ hccApiUrl: baseUrl }));
- const servers = await client.fetchServers();
- expect(servers[0].port).toBe(8080);
- });
-
- it("should handle connection refused gracefully", async () => {
- const client = new HccClient(makeConfig({ hccApiUrl: "http://127.0.0.1:1" }));
- const servers = await client.fetchServers();
- expect(servers).toEqual([]);
- });
-});
+ await new Promise(r => setTimeout(r, 10))
+ expect(client.isCacheStale()).toBe(true)
+ })
+
+ it('should report cache expired when expiry exceeded', async () => {
+ const client = new HccClient(makeConfig({ hccApiUrl: baseUrl, hccCacheExpiry: 1 }))
+
+ responseBody = {
+ servers: [
+ {
+ name: 'a',
+ contextRef: 'c',
+ transport: { type: 'streamableHttp', url: 'http://a:3000/mcp' },
+ enabled: true,
+ status: { deployed: true, ready: true },
+ },
+ ],
+ contextRef: '*',
+ timestamp: new Date().toISOString(),
+ }
+
+ await client.fetchServers()
+
+ await new Promise(r => setTimeout(r, 10))
+ expect(client.isCacheExpired()).toBe(true)
+ })
+
+ it('should report stale=true when no poll has occurred', () => {
+ const client = new HccClient(makeConfig({ hccApiUrl: baseUrl }))
+ expect(client.isCacheStale()).toBe(true)
+ expect(client.isCacheExpired()).toBe(true)
+ })
+
+ it('should extract port from URL', async () => {
+ responseBody = {
+ servers: [
+ {
+ name: 'custom-port',
+ contextRef: 'c',
+ transport: { type: 'streamableHttp', url: 'http://x:8080/mcp' },
+ enabled: true,
+ status: { deployed: true, ready: true },
+ },
+ ],
+ contextRef: '*',
+ timestamp: new Date().toISOString(),
+ }
+
+ const client = new HccClient(makeConfig({ hccApiUrl: baseUrl }))
+ const servers = await client.fetchServers()
+ expect(servers[0].port).toBe(8080)
+ })
+
+ it('should handle connection refused gracefully', async () => {
+ const client = new HccClient(makeConfig({ hccApiUrl: 'http://127.0.0.1:1' }))
+ const servers = await client.fetchServers()
+ expect(servers).toEqual([])
+ })
+})
diff --git a/mcp-proxy/test/httpForwarder.test.ts b/mcp-proxy/test/httpForwarder.test.ts
index 50993b701..6a557f947 100644
--- a/mcp-proxy/test/httpForwarder.test.ts
+++ b/mcp-proxy/test/httpForwarder.test.ts
@@ -1,33 +1,37 @@
-import { describe, it, expect, beforeEach, afterEach } from "vitest";
-import http from "node:http";
-import { HttpForwarder } from "../src/httpForwarder";
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import http from 'node:http'
+import { HttpForwarder } from '../src/httpForwarder'
-describe("HttpForwarder", () => {
- let backend: http.Server;
- let backendPort: number;
- let forwarder: HttpForwarder;
- let backendHandler: (req: http.IncomingMessage, res: http.ServerResponse) => void;
+describe('HttpForwarder', () => {
+ let backend: http.Server
+ let backendPort: number
+ let forwarder: HttpForwarder
+ let backendHandler: (req: http.IncomingMessage, res: http.ServerResponse) => void
beforeEach(async () => {
- forwarder = new HttpForwarder({ requestTimeout: 5000, maxResponseSize: 1048576, maxBufferSize: 65536 });
+ forwarder = new HttpForwarder({
+ requestTimeout: 5000,
+ maxResponseSize: 1048576,
+ maxBufferSize: 65536,
+ })
- await new Promise<void>((resolve) => {
+ await new Promise<void>(resolve => {
backend = http.createServer((req, res) => {
- backendHandler(req, res);
- });
+ backendHandler(req, res)
+ })
backend.listen(0, () => {
- const addr = backend.address();
- if (addr && typeof addr !== "string") {
- backendPort = addr.port;
+ const addr = backend.address()
+ if (addr && typeof addr !== 'string') {
+ backendPort = addr.port
}
- resolve();
- });
- });
- });
+ resolve()
+ })
+ })
+ })
afterEach(async () => {
- await new Promise<void>((resolve) => backend.close(() => resolve()));
- });
+ await new Promise<void>(resolve => backend.close(() => resolve()))
+ })
function forwardViaProxy(
method: string,
@@ -38,135 +42,139 @@ describe("HttpForwarder", () => {
// Create a temporary proxy server that uses our forwarder
const proxy = http.createServer(async (req, res) => {
try {
- await forwarder.forward(req, res, `http://127.0.0.1:${backendPort}/mcp`);
+ await forwarder.forward(req, res, `http://127.0.0.1:${backendPort}/mcp`)
} catch {
if (!res.headersSent) {
- res.writeHead(500);
- res.end("forward error");
+ res.writeHead(500)
+ res.end('forward error')
}
}
- });
+ })
proxy.listen(0, () => {
- const addr = proxy.address();
- if (!addr || typeof addr === "string") return reject(new Error("no addr"));
- const proxyPort = addr.port;
+ const addr = proxy.address()
+ if (!addr || typeof addr === 'string') return reject(new Error('no addr'))
+ const proxyPort = addr.port
const req = http.request(
- { hostname: "127.0.0.1", port: proxyPort, path: "/test", method, headers },
- (res) => {
- let data = "";
- res.on("data", (c: Buffer) => (data += c.toString()));
- res.on("end", () => {
- proxy.close();
- resolve({ status: res.statusCode || 0, body: data, headers: res.headers });
- });
+ { hostname: '127.0.0.1', port: proxyPort, path: '/test', method, headers },
+ res => {
+ let data = ''
+ res.on('data', (c: Buffer) => (data += c.toString()))
+ res.on('end', () => {
+ proxy.close()
+ resolve({ status: res.statusCode || 0, body: data, headers: res.headers })
+ })
}
- );
- req.on("error", (err) => {
- proxy.close();
- reject(err);
- });
- if (body) req.write(body);
- req.end();
- });
- });
+ )
+ req.on('error', err => {
+ proxy.close()
+ reject(err)
+ })
+ if (body) req.write(body)
+ req.end()
+ })
+ })
}
- it("should forward request to backend", async () => {
+ it('should forward request to backend', async () => {
backendHandler = (_, res) => {
- res.writeHead(200, { "Content-Type": "application/json" });
- res.end('{"ok":true}');
- };
+ res.writeHead(200, { 'Content-Type': 'application/json' })
+ res.end('{"ok":true}')
+ }
- const res = await forwardViaProxy("POST");
- expect(res.status).toBe(200);
- expect(JSON.parse(res.body)).toEqual({ ok: true });
- });
+ const res = await forwardViaProxy('POST')
+ expect(res.status).toBe(200)
+ expect(JSON.parse(res.body)).toEqual({ ok: true })
+ })
- it("should preserve request headers", async () => {
- let receivedHeaders: http.IncomingHttpHeaders = {};
+ it('should preserve request headers', async () => {
+ let receivedHeaders: http.IncomingHttpHeaders = {}
backendHandler = (req, res) => {
- receivedHeaders = req.headers;
- res.writeHead(200);
- res.end("ok");
- };
+ receivedHeaders = req.headers
+ res.writeHead(200)
+ res.end('ok')
+ }
- await forwardViaProxy("POST", {
- authorization: "Bearer test-token",
- "x-mcp-session": "session-123",
- });
+ await forwardViaProxy('POST', {
+ authorization: 'Bearer test-token',
+ 'x-mcp-session': 'session-123',
+ })
- expect(receivedHeaders["authorization"]).toBe("Bearer test-token");
- expect(receivedHeaders["x-mcp-session"]).toBe("session-123");
- });
+ expect(receivedHeaders['authorization']).toBe('Bearer test-token')
+ expect(receivedHeaders['x-mcp-session']).toBe('session-123')
+ })
- it("should preserve response headers", async () => {
+ it('should preserve response headers', async () => {
backendHandler = (_, res) => {
- res.writeHead(200, { "X-Custom-Header": "custom-value" });
- res.end("ok");
- };
+ res.writeHead(200, { 'X-Custom-Header': 'custom-value' })
+ res.end('ok')
+ }
- const res = await forwardViaProxy("POST");
- expect(res.headers["x-custom-header"]).toBe("custom-value");
- });
+ const res = await forwardViaProxy('POST')
+ expect(res.headers['x-custom-header']).toBe('custom-value')
+ })
- it("should pass through error status codes", async () => {
+ it('should pass through error status codes', async () => {
backendHandler = (_, res) => {
- res.writeHead(400, { "Content-Type": "application/json" });
- res.end('{"jsonrpc":"2.0","error":{"code":-32600,"message":"Invalid Request"}}');
- };
-
- const res = await forwardViaProxy("POST");
- expect(res.status).toBe(400);
- expect(JSON.parse(res.body).error.code).toBe(-32600);
- });
-
- it("should return 502 when backend is unreachable", async () => {
- const deadForwarder = new HttpForwarder({ requestTimeout: 1000, maxResponseSize: 1048576, maxBufferSize: 65536 });
+ res.writeHead(400, { 'Content-Type': 'application/json' })
+ res.end('{"jsonrpc":"2.0","error":{"code":-32600,"message":"Invalid Request"}}')
+ }
+
+ const res = await forwardViaProxy('POST')
+ expect(res.status).toBe(400)
+ expect(JSON.parse(res.body).error.code).toBe(-32600)
+ })
+
+ it('should return 502 when backend is unreachable', async () => {
+ const deadForwarder = new HttpForwarder({
+ requestTimeout: 1000,
+ maxResponseSize: 1048576,
+ maxBufferSize: 65536,
+ })
const res = await new Promise<{ status: number; body: string }>((resolve, reject) => {
const proxy = http.createServer(async (req, proxyRes) => {
- await deadForwarder.forward(req, proxyRes, "http://127.0.0.1:1/mcp");
- });
+ await deadForwarder.forward(req, proxyRes, 'http://127.0.0.1:1/mcp')
+ })
proxy.listen(0, () => {
- const addr = proxy.address();
- if (!addr || typeof addr === "string") return reject(new Error("no addr"));
+ const addr = proxy.address()
+ if (!addr || typeof addr === 'string') return reject(new Error('no addr'))
const req = http.request(
- { hostname: "127.0.0.1", port: addr.port, path: "/test", method: "POST" },
- (r) => {
- let data = "";
- r.on("data", (c: Buffer) => (data += c.toString()));
- r.on("end", () => {
- proxy.close();
- resolve({ status: r.statusCode || 0, body: data });
- });
+ { hostname: '127.0.0.1', port: addr.port, path: '/test', method: 'POST' },
+ r => {
+ let data = ''
+ r.on('data', (c: Buffer) => (data += c.toString()))
+ r.on('end', () => {
+ proxy.close()
+ resolve({ status: r.statusCode || 0, body: data })
+ })
}
- );
- req.on("error", (err) => {
- proxy.close();
- reject(err);
- });
- req.end();
- });
- });
-
- expect(res.status).toBe(502);
- });
-
- it("should stream chunked responses", async () => {
+ )
+ req.on('error', err => {
+ proxy.close()
+ reject(err)
+ })
+ req.end()
+ })
+ })
+
+ expect(res.status).toBe(502)
+ })
+
+ it('should stream chunked responses', async () => {
backendHandler = (_, res) => {
- res.writeHead(200, { "Transfer-Encoding": "chunked" });
- res.write("chunk1");
+ res.writeHead(200, { 'Transfer-Encoding': 'chunked' })
+ res.write('chunk1')
setTimeout(() => {
- res.write("chunk2");
- res.end();
- }, 50);
- };
-
- const res = await forwardViaProxy("POST");
- expect(res.status).toBe(200);
- expect(res.body).toBe("chunk1chunk2");
- });
-});
+ res.write('chunk2')
+ res.end()
+ }, 50)
+ }
+
+ const res = await forwardViaProxy('POST')
+ expect(res.status).toBe(200)
+ expect(res.body).toBe('chunk1chunk2')
+ })
+})
diff --git a/mcp-proxy/test/metrics.test.ts b/mcp-proxy/test/metrics.test.ts
index 224d04dbb..489976006 100644
--- a/mcp-proxy/test/metrics.test.ts
+++ b/mcp-proxy/test/metrics.test.ts
@@ -1,59 +1,59 @@
-import { describe, it, expect, beforeEach } from "vitest";
-import { Metrics } from "../src/metrics";
+import { beforeEach, describe, expect, it } from 'vitest'
+import { Metrics } from '../src/metrics'
-describe("Metrics", () => {
- let metrics: Metrics;
+describe('Metrics', () => {
+ let metrics: Metrics
beforeEach(() => {
- metrics = new Metrics();
- });
-
- it("should record request count", () => {
- metrics.recordRequest({ server: "s1", method: "POST", status: 200, durationMs: 50 });
- metrics.recordRequest({ server: "s1", method: "POST", status: 200, durationMs: 30 });
- expect(metrics.getRequestCount("s1", "POST", 200)).toBe(2);
- });
-
- it("should track per-server counts", () => {
- metrics.recordRequest({ server: "s1", method: "POST", status: 200, durationMs: 50 });
- metrics.recordRequest({ server: "s2", method: "POST", status: 200, durationMs: 30 });
- expect(metrics.getRequestCount("s1", "POST", 200)).toBe(1);
- expect(metrics.getRequestCount("s2", "POST", 200)).toBe(1);
- });
-
- it("should increment and decrement active connections", () => {
- metrics.incrementActive("s1");
- metrics.incrementActive("s1");
- expect(metrics.getActiveConnections("s1")).toBe(2);
- metrics.decrementActive("s1");
- expect(metrics.getActiveConnections("s1")).toBe(1);
- });
-
- it("should not go below zero on decrement", () => {
- metrics.decrementActive("s1");
- expect(metrics.getActiveConnections("s1")).toBe(0);
- });
-
- it("should track total active connections", () => {
- metrics.incrementActive("s1");
- metrics.incrementActive("s2");
- metrics.incrementActive("s2");
- expect(metrics.getTotalActiveConnections()).toBe(3);
- });
-
- it("should generate prometheus format", () => {
- metrics.recordRequest({ server: "s1", method: "POST", status: 200, durationMs: 50 });
- metrics.setServerHealth("s1", true);
- const output = metrics.toPrometheus();
- expect(output).toContain('mcp_proxy_requests_total{server="s1"');
- expect(output).toContain('mcp_proxy_server_health{server="s1"} 1');
- });
-
- it("should reset all metrics", () => {
- metrics.recordRequest({ server: "s1", method: "POST", status: 200, durationMs: 50 });
- metrics.incrementActive("s1");
- metrics.reset();
- expect(metrics.getRequestCount("s1", "POST", 200)).toBe(0);
- expect(metrics.getActiveConnections("s1")).toBe(0);
- });
-});
+ metrics = new Metrics()
+ })
+
+ it('should record request count', () => {
+ metrics.recordRequest({ server: 's1', method: 'POST', status: 200, durationMs: 50 })
+ metrics.recordRequest({ server: 's1', method: 'POST', status: 200, durationMs: 30 })
+ expect(metrics.getRequestCount('s1', 'POST', 200)).toBe(2)
+ })
+
+ it('should track per-server counts', () => {
+ metrics.recordRequest({ server: 's1', method: 'POST', status: 200, durationMs: 50 })
+ metrics.recordRequest({ server: 's2', method: 'POST', status: 200, durationMs: 30 })
+ expect(metrics.getRequestCount('s1', 'POST', 200)).toBe(1)
+ expect(metrics.getRequestCount('s2', 'POST', 200)).toBe(1)
+ })
+
+ it('should increment and decrement active connections', () => {
+ metrics.incrementActive('s1')
+ metrics.incrementActive('s1')
+ expect(metrics.getActiveConnections('s1')).toBe(2)
+ metrics.decrementActive('s1')
+ expect(metrics.getActiveConnections('s1')).toBe(1)
+ })
+
+ it('should not go below zero on decrement', () => {
+ metrics.decrementActive('s1')
+ expect(metrics.getActiveConnections('s1')).toBe(0)
+ })
+
+ it('should track total active connections', () => {
+ metrics.incrementActive('s1')
+ metrics.incrementActive('s2')
+ metrics.incrementActive('s2')
+ expect(metrics.getTotalActiveConnections()).toBe(3)
+ })
+
+ it('should generate prometheus format', () => {
+ metrics.recordRequest({ server: 's1', method: 'POST', status: 200, durationMs: 50 })
+ metrics.setServerHealth('s1', true)
+ const output = metrics.toPrometheus()
+ expect(output).toContain('mcp_proxy_requests_total{server="s1"')
+ expect(output).toContain('mcp_proxy_server_health{server="s1"} 1')
+ })
+
+ it('should reset all metrics', () => {
+ metrics.recordRequest({ server: 's1', method: 'POST', status: 200, durationMs: 50 })
+ metrics.incrementActive('s1')
+ metrics.reset()
+ expect(metrics.getRequestCount('s1', 'POST', 200)).toBe(0)
+ expect(metrics.getActiveConnections('s1')).toBe(0)
+ })
+})
diff --git a/mcp-proxy/test/router.test.ts b/mcp-proxy/test/router.test.ts
index 201548417..b7eb1a99b 100644
--- a/mcp-proxy/test/router.test.ts
+++ b/mcp-proxy/test/router.test.ts
@@ -1,80 +1,80 @@
-import { describe, it, expect, beforeEach } from "vitest";
-import { Router } from "../src/router";
-import { ServerRoute } from "../src/types";
+import { beforeEach, describe, expect, it } from 'vitest'
+import { Router } from '../src/router'
+import { ServerRoute } from '../src/types'
function makeRoute(name: string, overrides: Partial<ServerRoute> = {}): ServerRoute {
return {
name,
url: `http://${name}.mcp-server:3000/mcp`,
- contextRef: "context1",
+ contextRef: 'context1',
managed: true,
ready: true,
port: 3000,
...overrides,
- };
+ }
}
-describe("Router", () => {
- let router: Router;
+describe('Router', () => {
+ let router: Router
beforeEach(() => {
- router = new Router();
- });
+ router = new Router()
+ })
- it("should add routes from update", () => {
- const { added, removed } = router.update([makeRoute("server-a"), makeRoute("server-b")]);
- expect(added).toEqual(["server-a", "server-b"]);
- expect(removed).toEqual([]);
- expect(router.size()).toBe(2);
- });
+ it('should add routes from update', () => {
+ const { added, removed } = router.update([makeRoute('server-a'), makeRoute('server-b')])
+ expect(added).toEqual(['server-a', 'server-b'])
+ expect(removed).toEqual([])
+ expect(router.size()).toBe(2)
+ })
- it("should detect removed routes", () => {
- router.update([makeRoute("server-a"), makeRoute("server-b")]);
- const { added, removed } = router.update([makeRoute("server-a")]);
- expect(added).toEqual([]);
- expect(removed).toEqual(["server-b"]);
- expect(router.size()).toBe(1);
- });
+ it('should detect removed routes', () => {
+ router.update([makeRoute('server-a'), makeRoute('server-b')])
+ const { added, removed } = router.update([makeRoute('server-a')])
+ expect(added).toEqual([])
+ expect(removed).toEqual(['server-b'])
+ expect(router.size()).toBe(1)
+ })
- it("should update existing routes", () => {
- router.update([makeRoute("server-a", { ready: true })]);
- router.update([makeRoute("server-a", { ready: false })]);
- expect(router.resolve("server-a")!.ready).toBe(false);
- });
+ it('should update existing routes', () => {
+ router.update([makeRoute('server-a', { ready: true })])
+ router.update([makeRoute('server-a', { ready: false })])
+ expect(router.resolve('server-a')!.ready).toBe(false)
+ })
- it("should resolve by name", () => {
- router.update([makeRoute("server-a")]);
- const route = router.resolve("server-a");
- expect(route).toBeDefined();
- expect(route!.name).toBe("server-a");
- });
+ it('should resolve by name', () => {
+ router.update([makeRoute('server-a')])
+ const route = router.resolve('server-a')
+ expect(route).toBeDefined()
+ expect(route!.name).toBe('server-a')
+ })
- it("should return undefined for unknown server", () => {
- expect(router.resolve("nonexistent")).toBeUndefined();
- });
+ it('should return undefined for unknown server', () => {
+ expect(router.resolve('nonexistent')).toBeUndefined()
+ })
- it("should detect added routes on subsequent updates", () => {
- router.update([makeRoute("server-a")]);
- const { added } = router.update([makeRoute("server-a"), makeRoute("server-b")]);
- expect(added).toEqual(["server-b"]);
- });
+ it('should detect added routes on subsequent updates', () => {
+ router.update([makeRoute('server-a')])
+ const { added } = router.update([makeRoute('server-a'), makeRoute('server-b')])
+ expect(added).toEqual(['server-b'])
+ })
- it("should report hasReadyServers correctly", () => {
- expect(router.hasReadyServers()).toBe(false);
- router.update([makeRoute("server-a", { ready: false })]);
- expect(router.hasReadyServers()).toBe(false);
- router.update([makeRoute("server-a", { ready: true })]);
- expect(router.hasReadyServers()).toBe(true);
- });
+ it('should report hasReadyServers correctly', () => {
+ expect(router.hasReadyServers()).toBe(false)
+ router.update([makeRoute('server-a', { ready: false })])
+ expect(router.hasReadyServers()).toBe(false)
+ router.update([makeRoute('server-a', { ready: true })])
+ expect(router.hasReadyServers()).toBe(true)
+ })
- it("should list all routes", () => {
- router.update([makeRoute("server-a"), makeRoute("server-b")]);
- expect(router.allRoutes()).toHaveLength(2);
- });
+ it('should list all routes', () => {
+ router.update([makeRoute('server-a'), makeRoute('server-b')])
+ expect(router.allRoutes()).toHaveLength(2)
+ })
- it("should clear all routes", () => {
- router.update([makeRoute("server-a")]);
- router.clear();
- expect(router.size()).toBe(0);
- });
-});
+ it('should clear all routes', () => {
+ router.update([makeRoute('server-a')])
+ router.clear()
+ expect(router.size()).toBe(0)
+ })
+})
diff --git a/mcp-proxy/test/server.test.ts b/mcp-proxy/test/server.test.ts
index ef7468865..6039bcdaa 100644
--- a/mcp-proxy/test/server.test.ts
+++ b/mcp-proxy/test/server.test.ts
@@ -1,17 +1,17 @@
-import { describe, it, expect, beforeEach, afterEach } from "vitest";
-import http from "node:http";
-import { Router } from "../src/router";
-import { HttpForwarder } from "../src/httpForwarder";
-import { Metrics } from "../src/metrics";
-import { Health } from "../src/health";
-import { HccClient } from "../src/hccClient";
-import { ProxyServer } from "../src/server";
-import { ProxyConfig, ServerRoute } from "../src/types";
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import http from 'node:http'
+import { HccClient } from '../src/hccClient'
+import { Health } from '../src/health'
+import { HttpForwarder } from '../src/httpForwarder'
+import { Metrics } from '../src/metrics'
+import { Router } from '../src/router'
+import { ProxyServer } from '../src/server'
+import { ProxyConfig, ServerRoute } from '../src/types'
function makeConfig(port: number): ProxyConfig {
return {
port,
- hccApiUrl: "http://localhost:9999",
+ hccApiUrl: 'http://localhost:9999',
hccPollInterval: 30000,
hccCacheTTL: 120000,
hccCacheExpiry: 300000,
@@ -19,88 +19,96 @@ function makeConfig(port: number): ProxyConfig {
maxResponseSize: 10485760,
devMode: true,
devServers: [],
- logLevel: "info",
- };
+ logLevel: 'info',
+ }
}
function makeRoute(name: string, ready = true): ServerRoute {
- return { name, url: "", contextRef: "ctx1", managed: true, ready, port: 3000 };
+ return { name, url: '', contextRef: 'ctx1', managed: true, ready, port: 3000 }
}
-function httpRequest(port: number, path: string, method = "GET"): Promise<{ status: number; body: string }> {
+function httpRequest(
+ port: number,
+ path: string,
+ method = 'GET'
+): Promise<{ status: number; body: string }> {
return new Promise((resolve, reject) => {
- const req = http.request({ hostname: "127.0.0.1", port, path, method }, (res) => {
- let body = "";
- res.on("data", (c: Buffer) => (body += c.toString()));
- res.on("end", () => resolve({ status: res.statusCode || 0, body }));
- });
- req.on("error", reject);
- req.end();
- });
+ const req = http.request({ hostname: '127.0.0.1', port, path, method }, res => {
+ let body = ''
+ res.on('data', (c: Buffer) => (body += c.toString()))
+ res.on('end', () => resolve({ status: res.statusCode || 0, body }))
+ })
+ req.on('error', reject)
+ req.end()
+ })
}
-describe("ProxyServer", () => {
- let server: ProxyServer;
- let router: Router;
- let hccClient: HccClient;
- let actualPort: number;
+describe('ProxyServer', () => {
+ let server: ProxyServer
+ let router: Router
+ let hccClient: HccClient
+ let actualPort: number
beforeEach(async () => {
// Use port 0 for OS-assigned port to avoid conflicts
- const config = makeConfig(0);
- router = new Router();
- hccClient = new HccClient(config);
- const forwarder = new HttpForwarder({ requestTimeout: 5000, maxResponseSize: 10485760, maxBufferSize: 65536 });
- const metrics = new Metrics();
- const health = new Health(router, hccClient);
- server = new ProxyServer(router, forwarder, metrics, health, config);
- await server.start();
- actualPort = server.getPort();
- });
+ const config = makeConfig(0)
+ router = new Router()
+ hccClient = new HccClient(config)
+ const forwarder = new HttpForwarder({
+ requestTimeout: 5000,
+ maxResponseSize: 10485760,
+ maxBufferSize: 65536,
+ })
+ const metrics = new Metrics()
+ const health = new Health(router, hccClient)
+ server = new ProxyServer(router, forwarder, metrics, health, config)
+ await server.start()
+ actualPort = server.getPort()
+ })
afterEach(async () => {
- await server.stop();
- });
+ await server.stop()
+ })
- it("should respond 200 on /health", async () => {
- const res = await httpRequest(actualPort, "/health");
- expect(res.status).toBe(200);
- expect(JSON.parse(res.body).status).toBe("ok");
- });
+ it('should respond 200 on /health', async () => {
+ const res = await httpRequest(actualPort, '/health')
+ expect(res.status).toBe(200)
+ expect(JSON.parse(res.body).status).toBe('ok')
+ })
- it("should respond 503 on /ready when cache expired", async () => {
- const res = await httpRequest(actualPort, "/ready");
- expect(res.status).toBe(503);
- });
+ it('should respond 503 on /ready when cache expired', async () => {
+ const res = await httpRequest(actualPort, '/ready')
+ expect(res.status).toBe(503)
+ })
- it("should respond 200 on /ready when servers available and cache fresh", async () => {
+ it('should respond 200 on /ready when servers available and cache fresh', async () => {
// Simulate a successful poll
- (hccClient as any).lastSuccessfulPoll = Date.now();
- router.update([makeRoute("server-a")]);
- const res = await httpRequest(actualPort, "/ready");
- expect(res.status).toBe(200);
- });
+ ;(hccClient as any).lastSuccessfulPoll = Date.now()
+ router.update([makeRoute('server-a')])
+ const res = await httpRequest(actualPort, '/ready')
+ expect(res.status).toBe(200)
+ })
- it("should respond 200 on /metrics", async () => {
- const res = await httpRequest(actualPort, "/metrics");
- expect(res.status).toBe(200);
- expect(res.body).toContain("mcp_proxy");
- });
+ it('should respond 200 on /metrics', async () => {
+ const res = await httpRequest(actualPort, '/metrics')
+ expect(res.status).toBe(200)
+ expect(res.body).toContain('mcp_proxy')
+ })
- it("should respond 404 for unknown paths", async () => {
- const res = await httpRequest(actualPort, "/unknown");
- expect(res.status).toBe(404);
- });
+ it('should respond 404 for unknown paths', async () => {
+ const res = await httpRequest(actualPort, '/unknown')
+ expect(res.status).toBe(404)
+ })
- it("should respond 404 for unknown server in route dispatch", async () => {
- const res = await httpRequest(actualPort, "/servers/nonexistent/mcp", "POST");
- expect(res.status).toBe(404);
- expect(JSON.parse(res.body).error).toContain("nonexistent");
- });
+ it('should respond 404 for unknown server in route dispatch', async () => {
+ const res = await httpRequest(actualPort, '/servers/nonexistent/mcp', 'POST')
+ expect(res.status).toBe(404)
+ expect(JSON.parse(res.body).error).toContain('nonexistent')
+ })
- it("should respond 503 for unready server", async () => {
- router.update([makeRoute("server-a", false)]);
- const res = await httpRequest(actualPort, "/servers/server-a/mcp", "POST");
- expect(res.status).toBe(503);
- });
-});
+ it('should respond 503 for unready server', async () => {
+ router.update([makeRoute('server-a', false)])
+ const res = await httpRequest(actualPort, '/servers/server-a/mcp', 'POST')
+ expect(res.status).toBe(503)
+ })
+})
diff --git a/mcp-proxy/vitest.config.ts b/mcp-proxy/vitest.config.ts
index 37b473f54..8141ade9e 100644
--- a/mcp-proxy/vitest.config.ts
+++ b/mcp-proxy/vitest.config.ts
@@ -1,8 +1,8 @@
-import { defineConfig } from "vitest/config";
+import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
- include: ["src/**/*.test.ts", "src/**/__tests__/**/*.ts", "test/**/*.test.ts"],
- exclude: ["dist/**", "node_modules/**"],
+ include: ['src/**/*.test.ts', 'src/**/__tests__/**/*.ts', 'test/**/*.test.ts'],
+ exclude: ['dist/**', 'node_modules/**'],
},
-});
+})
diff --git a/mcp-servers/airtable/__tests__/airtable.api.test.ts b/mcp-servers/airtable/__tests__/airtable.api.test.ts
index 8871418da..d801b5876 100644
--- a/mcp-servers/airtable/__tests__/airtable.api.test.ts
+++ b/mcp-servers/airtable/__tests__/airtable.api.test.ts
@@ -11,27 +11,26 @@
* - Error handling simulation
* - Rate limiting behavior
*/
-
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
// =============================================================================
// Types
// =============================================================================
interface AirtableRecord {
- id: string;
- createdTime: string;
- fields: Record<string, any>;
+ id: string
+ createdTime: string
+ fields: Record<string, any>
}
interface AirtableListResponse {
- records: AirtableRecord[];
- offset?: string;
+ records: AirtableRecord[]
+ offset?: string
}
interface AirtableError {
- type: string;
- message: string;
+ type: string
+ message: string
}
// =============================================================================
@@ -39,41 +38,41 @@ interface AirtableError {
// =============================================================================
class MockAirtableClient {
- private baseUrl = 'https://api.airtable.com/v0';
- private mockData: Map<string, AirtableRecord[]> = new Map();
- private mockErrors: Map<string, AirtableError> = new Map();
- private rateLimitUntil: number | null = null;
+ private baseUrl = 'https://api.airtable.com/v0'
+ private mockData: Map<string, AirtableRecord[]> = new Map()
+ private mockErrors: Map<string, AirtableError> = new Map()
+ private rateLimitUntil: number | null = null
/**
* Set mock data for a table
*/
setMockData(baseId: string, tableId: string, records: AirtableRecord[]) {
- const key = `${baseId}/${tableId}`;
- this.mockData.set(key, records);
+ const key = `${baseId}/${tableId}`
+ this.mockData.set(key, records)
}
/**
* Set mock error for an operation
*/
setMockError(baseId: string, tableId: string, error: AirtableError) {
- const key = `${baseId}/${tableId}`;
- this.mockErrors.set(key, error);
+ const key = `${baseId}/${tableId}`
+ this.mockErrors.set(key, error)
}
/**
* Simulate rate limiting
*/
setRateLimit(durationMs: number) {
- this.rateLimitUntil = Date.now() + durationMs;
+ this.rateLimitUntil = Date.now() + durationMs
}
/**
* Clear all mocks
*/
clearMocks() {
- this.mockData.clear();
- this.mockErrors.clear();
- this.rateLimitUntil = null;
+ this.mockData.clear()
+ this.mockErrors.clear()
+ this.rateLimitUntil = null
}
/**
@@ -84,49 +83,45 @@ class MockAirtableClient {
tableId: string,
options?: { offset?: string; limit?: number }
): Promise<AirtableListResponse> {
- this.checkRateLimit();
+ this.checkRateLimit()
- const key = `${baseId}/${tableId}`;
+ const key = `${baseId}/${tableId}`
// Check for mock error
- const error = this.mockErrors.get(key);
+ const error = this.mockErrors.get(key)
if (error) {
- throw new Error(`Airtable API Error: ${error.type} - ${error.message}`);
+ throw new Error(`Airtable API Error: ${error.type} - ${error.message}`)
}
// Get mock data
- let records = this.mockData.get(key) || [];
+ let records = this.mockData.get(key) || []
// Apply pagination
if (options?.limit) {
- records = records.slice(0, options.limit);
+ records = records.slice(0, options.limit)
}
return {
records,
offset: records.length > 0 ? 'mock-offset' : undefined,
- };
+ }
}
/**
* Mock get record operation
*/
- async getRecord(
- baseId: string,
- tableId: string,
- recordId: string
- ): Promise<AirtableRecord> {
- this.checkRateLimit();
+ async getRecord(baseId: string, tableId: string, recordId: string): Promise<AirtableRecord> {
+ this.checkRateLimit()
- const key = `${baseId}/${tableId}`;
- const records = this.mockData.get(key) || [];
+ const key = `${baseId}/${tableId}`
+ const records = this.mockData.get(key) || []
- const record = records.find(r => r.id === recordId);
+ const record = records.find(r => r.id === recordId)
if (!record) {
- throw new Error('NOT_FOUND: Record not found');
+ throw new Error('NOT_FOUND: Record not found')
}
- return record;
+ return record
}
/**
@@ -137,21 +132,21 @@ class MockAirtableClient {
tableId: string,
fields: Record<string, any>
): Promise<AirtableRecord> {
- this.checkRateLimit();
+ this.checkRateLimit()
- const key = `${baseId}/${tableId}`;
- const records = this.mockData.get(key) || [];
+ const key = `${baseId}/${tableId}`
+ const records = this.mockData.get(key) || []
const newRecord: AirtableRecord = {
id: `rec${Date.now()}`,
createdTime: new Date().toISOString(),
fields,
- };
+ }
- records.push(newRecord);
- this.mockData.set(key, records);
+ records.push(newRecord)
+ this.mockData.set(key, records)
- return newRecord;
+ return newRecord
}
/**
@@ -163,18 +158,18 @@ class MockAirtableClient {
recordId: string,
fields: Record<string, any>
): Promise<AirtableRecord> {
- this.checkRateLimit();
+ this.checkRateLimit()
- const key = `${baseId}/${tableId}`;
- const records = this.mockData.get(key) || [];
+ const key = `${baseId}/${tableId}`
+ const records = this.mockData.get(key) || []
- const index = records.findIndex(r => r.id === recordId);
+ const index = records.findIndex(r => r.id === recordId)
if (index === -1) {
- throw new Error('NOT_FOUND: Record not found');
+ throw new Error('NOT_FOUND: Record not found')
}
- records[index].fields = { ...records[index].fields, ...fields };
- return records[index];
+ records[index].fields = { ...records[index].fields, ...fields }
+ return records[index]
}
/**
@@ -185,20 +180,20 @@ class MockAirtableClient {
tableId: string,
recordId: string
): Promise<{ id: string; deleted: boolean }> {
- this.checkRateLimit();
+ this.checkRateLimit()
- const key = `${baseId}/${tableId}`;
- const records = this.mockData.get(key) || [];
+ const key = `${baseId}/${tableId}`
+ const records = this.mockData.get(key) || []
- const index = records.findIndex(r => r.id === recordId);
+ const index = records.findIndex(r => r.id === recordId)
if (index === -1) {
- throw new Error('NOT_FOUND: Record not found');
+ throw new Error('NOT_FOUND: Record not found')
}
- records.splice(index, 1);
- this.mockData.set(key, records);
+ records.splice(index, 1)
+ this.mockData.set(key, records)
- return { id: recordId, deleted: true };
+ return { id: recordId, deleted: true }
}
/**
@@ -206,9 +201,9 @@ class MockAirtableClient {
*/
private checkRateLimit() {
if (this.rateLimitUntil && Date.now() < this.rateLimitUntil) {
- throw new Error('RATE_LIMITED: Too many requests');
+ throw new Error('RATE_LIMITED: Too many requests')
}
- this.rateLimitUntil = null;
+ this.rateLimitUntil = null
}
}
@@ -217,15 +212,15 @@ class MockAirtableClient {
// =============================================================================
describe('Airtable API Mock', () => {
- let client: MockAirtableClient;
+ let client: MockAirtableClient
beforeEach(() => {
- client = new MockAirtableClient();
- });
+ client = new MockAirtableClient()
+ })
afterEach(() => {
- client.clearMocks();
- });
+ client.clearMocks()
+ })
describe('Mock Data Setup', () => {
it('should set mock data for a table', () => {
@@ -235,27 +230,27 @@ describe('Airtable API Mock', () => {
createdTime: '2024-01-01T00:00:00.000Z',
fields: { Name: 'Test', Value: 100 },
},
- ];
+ ]
- client.setMockData('appBase123', 'tblTable1', records);
+ client.setMockData('appBase123', 'tblTable1', records)
// Verify by calling listRecords
- const result = client.listRecords('appBase123', 'tblTable1');
- expect(result).resolves.toHaveProperty('records');
- });
+ const result = client.listRecords('appBase123', 'tblTable1')
+ expect(result).resolves.toHaveProperty('records')
+ })
it('should set mock error for operations', async () => {
const error: AirtableError = {
type: 'AUTHENTICATION_REQUIRED',
message: 'Invalid API key',
- };
+ }
- client.setMockError('appBase123', 'tblTable1', error);
+ client.setMockError('appBase123', 'tblTable1', error)
- await expect(
- client.listRecords('appBase123', 'tblTable1')
- ).rejects.toThrow('AUTHENTICATION_REQUIRED');
- });
+ await expect(client.listRecords('appBase123', 'tblTable1')).rejects.toThrow(
+ 'AUTHENTICATION_REQUIRED'
+ )
+ })
it('should clear all mocks', () => {
const records: AirtableRecord[] = [
@@ -264,16 +259,16 @@ describe('Airtable API Mock', () => {
createdTime: '2024-01-01T00:00:00.000Z',
fields: { Name: 'Test' },
},
- ];
+ ]
- client.setMockData('appBase123', 'tblTable1', records);
- client.clearMocks();
+ client.setMockData('appBase123', 'tblTable1', records)
+ client.clearMocks()
// After clearing, should return empty array
- const result = client.listRecords('appBase123', 'tblTable1');
- expect(result).resolves.toEqual({ records: [] });
- });
- });
+ const result = client.listRecords('appBase123', 'tblTable1')
+ expect(result).resolves.toEqual({ records: [] })
+ })
+ })
describe('List Records', () => {
beforeEach(() => {
@@ -293,43 +288,43 @@ describe('Airtable API Mock', () => {
createdTime: '2024-01-03T00:00:00.000Z',
fields: { Name: 'Charlie', Age: 35 },
},
- ];
+ ]
- client.setMockData('appBase123', 'tblUsers', records);
- });
+ client.setMockData('appBase123', 'tblUsers', records)
+ })
it('should list all records', async () => {
- const result = await client.listRecords('appBase123', 'tblUsers');
+ const result = await client.listRecords('appBase123', 'tblUsers')
- expect(result.records).toHaveLength(3);
- expect(result.records[0].fields.Name).toBe('Alice');
- expect(result.records[1].fields.Name).toBe('Bob');
- expect(result.records[2].fields.Name).toBe('Charlie');
- });
+ expect(result.records).toHaveLength(3)
+ expect(result.records[0].fields.Name).toBe('Alice')
+ expect(result.records[1].fields.Name).toBe('Bob')
+ expect(result.records[2].fields.Name).toBe('Charlie')
+ })
it('should respect limit parameter', async () => {
const result = await client.listRecords('appBase123', 'tblUsers', {
limit: 2,
- });
+ })
- expect(result.records).toHaveLength(2);
- expect(result.records[0].fields.Name).toBe('Alice');
- expect(result.records[1].fields.Name).toBe('Bob');
- });
+ expect(result.records).toHaveLength(2)
+ expect(result.records[0].fields.Name).toBe('Alice')
+ expect(result.records[1].fields.Name).toBe('Bob')
+ })
it('should return empty array for non-existent table', async () => {
- const result = await client.listRecords('appBase123', 'tblNonExistent');
+ const result = await client.listRecords('appBase123', 'tblNonExistent')
- expect(result.records).toEqual([]);
- });
+ expect(result.records).toEqual([])
+ })
it('should include offset in response', async () => {
- const result = await client.listRecords('appBase123', 'tblUsers');
+ const result = await client.listRecords('appBase123', 'tblUsers')
- expect(result.offset).toBeDefined();
- expect(result.offset).toBe('mock-offset');
- });
- });
+ expect(result.offset).toBeDefined()
+ expect(result.offset).toBe('mock-offset')
+ })
+ })
describe('Get Record', () => {
beforeEach(() => {
@@ -339,46 +334,46 @@ describe('Airtable API Mock', () => {
createdTime: '2024-01-01T00:00:00.000Z',
fields: { Name: 'Alice', Age: 30 },
},
- ];
+ ]
- client.setMockData('appBase123', 'tblUsers', records);
- });
+ client.setMockData('appBase123', 'tblUsers', records)
+ })
it('should get a specific record', async () => {
- const record = await client.getRecord('appBase123', 'tblUsers', 'rec1');
+ const record = await client.getRecord('appBase123', 'tblUsers', 'rec1')
- expect(record.id).toBe('rec1');
- expect(record.fields.Name).toBe('Alice');
- expect(record.fields.Age).toBe(30);
- });
+ expect(record.id).toBe('rec1')
+ expect(record.fields.Name).toBe('Alice')
+ expect(record.fields.Age).toBe(30)
+ })
it('should throw error for non-existent record', async () => {
- await expect(
- client.getRecord('appBase123', 'tblUsers', 'recNonExistent')
- ).rejects.toThrow('NOT_FOUND');
- });
- });
+ await expect(client.getRecord('appBase123', 'tblUsers', 'recNonExistent')).rejects.toThrow(
+ 'NOT_FOUND'
+ )
+ })
+ })
describe('Create Record', () => {
it('should create a new record', async () => {
- const fields = { Name: 'David', Age: 28 };
+ const fields = { Name: 'David', Age: 28 }
- const record = await client.createRecord('appBase123', 'tblUsers', fields);
+ const record = await client.createRecord('appBase123', 'tblUsers', fields)
- expect(record.id).toMatch(/^rec\d+$/);
- expect(record.createdTime).toBeDefined();
- expect(record.fields.Name).toBe('David');
- expect(record.fields.Age).toBe(28);
- });
+ expect(record.id).toMatch(/^rec\d+$/)
+ expect(record.createdTime).toBeDefined()
+ expect(record.fields.Name).toBe('David')
+ expect(record.fields.Age).toBe(28)
+ })
it('should add record to mock data', async () => {
- await client.createRecord('appBase123', 'tblUsers', { Name: 'Eve' });
+ await client.createRecord('appBase123', 'tblUsers', { Name: 'Eve' })
- const result = await client.listRecords('appBase123', 'tblUsers');
- expect(result.records).toHaveLength(1);
- expect(result.records[0].fields.Name).toBe('Eve');
- });
- });
+ const result = await client.listRecords('appBase123', 'tblUsers')
+ expect(result.records).toHaveLength(1)
+ expect(result.records[0].fields.Name).toBe('Eve')
+ })
+ })
describe('Update Record', () => {
beforeEach(() => {
@@ -388,42 +383,37 @@ describe('Airtable API Mock', () => {
createdTime: '2024-01-01T00:00:00.000Z',
fields: { Name: 'Alice', Age: 30 },
},
- ];
+ ]
- client.setMockData('appBase123', 'tblUsers', records);
- });
+ client.setMockData('appBase123', 'tblUsers', records)
+ })
it('should update an existing record', async () => {
- const updated = await client.updateRecord(
- 'appBase123',
- 'tblUsers',
- 'rec1',
- { Age: 31 }
- );
+ const updated = await client.updateRecord('appBase123', 'tblUsers', 'rec1', { Age: 31 })
- expect(updated.fields.Age).toBe(31);
- expect(updated.fields.Name).toBe('Alice'); // Unchanged
- });
+ expect(updated.fields.Age).toBe(31)
+ expect(updated.fields.Name).toBe('Alice') // Unchanged
+ })
it('should merge fields on update', async () => {
await client.updateRecord('appBase123', 'tblUsers', 'rec1', {
City: 'NYC',
- });
+ })
- const record = await client.getRecord('appBase123', 'tblUsers', 'rec1');
- expect(record.fields.Name).toBe('Alice');
- expect(record.fields.Age).toBe(30);
- expect(record.fields.City).toBe('NYC');
- });
+ const record = await client.getRecord('appBase123', 'tblUsers', 'rec1')
+ expect(record.fields.Name).toBe('Alice')
+ expect(record.fields.Age).toBe(30)
+ expect(record.fields.City).toBe('NYC')
+ })
it('should throw error for non-existent record', async () => {
await expect(
client.updateRecord('appBase123', 'tblUsers', 'recNonExistent', {
Name: 'Test',
})
- ).rejects.toThrow('NOT_FOUND');
- });
- });
+ ).rejects.toThrow('NOT_FOUND')
+ })
+ })
describe('Delete Record', () => {
beforeEach(() => {
@@ -438,98 +428,86 @@ describe('Airtable API Mock', () => {
createdTime: '2024-01-02T00:00:00.000Z',
fields: { Name: 'Bob' },
},
- ];
+ ]
- client.setMockData('appBase123', 'tblUsers', records);
- });
+ client.setMockData('appBase123', 'tblUsers', records)
+ })
it('should delete a record', async () => {
- const result = await client.deleteRecord(
- 'appBase123',
- 'tblUsers',
- 'rec1'
- );
+ const result = await client.deleteRecord('appBase123', 'tblUsers', 'rec1')
- expect(result.id).toBe('rec1');
- expect(result.deleted).toBe(true);
- });
+ expect(result.id).toBe('rec1')
+ expect(result.deleted).toBe(true)
+ })
it('should remove record from mock data', async () => {
- await client.deleteRecord('appBase123', 'tblUsers', 'rec1');
+ await client.deleteRecord('appBase123', 'tblUsers', 'rec1')
- const listResult = await client.listRecords('appBase123', 'tblUsers');
- expect(listResult.records).toHaveLength(1);
- expect(listResult.records[0].id).toBe('rec2');
- });
+ const listResult = await client.listRecords('appBase123', 'tblUsers')
+ expect(listResult.records).toHaveLength(1)
+ expect(listResult.records[0].id).toBe('rec2')
+ })
it('should throw error for non-existent record', async () => {
- await expect(
- client.deleteRecord('appBase123', 'tblUsers', 'recNonExistent')
- ).rejects.toThrow('NOT_FOUND');
- });
- });
+ await expect(client.deleteRecord('appBase123', 'tblUsers', 'recNonExistent')).rejects.toThrow(
+ 'NOT_FOUND'
+ )
+ })
+ })
describe('Rate Limiting', () => {
it('should throw rate limit error when rate limited', async () => {
- client.setRateLimit(1000);
+ client.setRateLimit(1000)
- await expect(
- client.listRecords('appBase123', 'tblUsers')
- ).rejects.toThrow('RATE_LIMITED');
- });
+ await expect(client.listRecords('appBase123', 'tblUsers')).rejects.toThrow('RATE_LIMITED')
+ })
it('should allow requests after rate limit expires', async () => {
- client.setRateLimit(10); // 10ms rate limit
+ client.setRateLimit(10) // 10ms rate limit
- await expect(
- client.listRecords('appBase123', 'tblUsers')
- ).rejects.toThrow('RATE_LIMITED');
+ await expect(client.listRecords('appBase123', 'tblUsers')).rejects.toThrow('RATE_LIMITED')
// Wait for rate limit to expire
- await new Promise(resolve => setTimeout(resolve, 15));
+ await new Promise(resolve => setTimeout(resolve, 15))
// Should work now
- await expect(
- client.listRecords('appBase123', 'tblUsers')
- ).resolves.toBeDefined();
- });
- });
+ await expect(client.listRecords('appBase123', 'tblUsers')).resolves.toBeDefined()
+ })
+ })
describe('Error Handling', () => {
it('should return authentication error', async () => {
client.setMockError('appBase123', 'tblUsers', {
type: 'AUTHENTICATION_REQUIRED',
message: 'Invalid API key',
- });
+ })
- await expect(
- client.listRecords('appBase123', 'tblUsers')
- ).rejects.toThrow('AUTHENTICATION_REQUIRED');
- });
+ await expect(client.listRecords('appBase123', 'tblUsers')).rejects.toThrow(
+ 'AUTHENTICATION_REQUIRED'
+ )
+ })
it('should return permission error', async () => {
client.setMockError('appBase123', 'tblUsers', {
type: 'PERMISSION_DENIED',
message: 'You do not have access',
- });
+ })
- await expect(
- client.listRecords('appBase123', 'tblUsers')
- ).rejects.toThrow('PERMISSION_DENIED');
- });
+ await expect(client.listRecords('appBase123', 'tblUsers')).rejects.toThrow(
+ 'PERMISSION_DENIED'
+ )
+ })
it('should return not found error', async () => {
client.setMockError('appBase123', 'tblUsers', {
type: 'NOT_FOUND',
message: 'Table not found',
- });
+ })
- await expect(
- client.listRecords('appBase123', 'tblUsers')
- ).rejects.toThrow('NOT_FOUND');
- });
- });
-});
+ await expect(client.listRecords('appBase123', 'tblUsers')).rejects.toThrow('NOT_FOUND')
+ })
+ })
+})
// =============================================================================
// Vitest Mock Utilities
@@ -539,7 +517,7 @@ describe('Airtable API Mock', () => {
* Factory function to create a mock Airtable client for tests
*/
export function createMockAirtableClient(): MockAirtableClient {
- return new MockAirtableClient();
+ return new MockAirtableClient()
}
/**
@@ -551,8 +529,8 @@ export function setupMockAirtableData(
) {
switch (scenario) {
case 'empty':
- client.setMockData('appBase123', 'tblTest', []);
- break;
+ client.setMockData('appBase123', 'tblTest', [])
+ break
case 'single':
client.setMockData('appBase123', 'tblTest', [
@@ -561,8 +539,8 @@ export function setupMockAirtableData(
createdTime: '2024-01-01T00:00:00.000Z',
fields: { Name: 'Test Record' },
},
- ]);
- break;
+ ])
+ break
case 'multiple':
client.setMockData('appBase123', 'tblTest', [
@@ -581,7 +559,7 @@ export function setupMockAirtableData(
createdTime: '2024-01-03T00:00:00.000Z',
fields: { Name: 'Third' },
},
- ]);
- break;
+ ])
+ break
}
}
diff --git a/mcp-servers/airtable/__tests__/airtable.mcp.test.ts b/mcp-servers/airtable/__tests__/airtable.mcp.test.ts
index 1b0ac4e6b..9d1ffe89a 100644
--- a/mcp-servers/airtable/__tests__/airtable.mcp.test.ts
+++ b/mcp-servers/airtable/__tests__/airtable.mcp.test.ts
@@ -11,39 +11,38 @@
* - Response formatting
* - Error handling
*/
-
-import { describe, it, expect, beforeEach } from 'vitest';
-import { createMockAirtableClient } from './airtable.api.test';
+import { beforeEach, describe, expect, it } from 'vitest'
+import { createMockAirtableClient } from './airtable.api.test'
// =============================================================================
// Types
// =============================================================================
interface McpTool {
- name: string;
- description: string;
+ name: string
+ description: string
inputSchema: {
- type: 'object';
- properties: Record<string, any>;
- required?: string[];
- };
+ type: 'object'
+ properties: Record<string, any>
+ required?: string[]
+ }
}
interface McpToolsListResponse {
- tools: McpTool[];
+ tools: McpTool[]
}
interface McpToolCallRequest {
- name: string;
- arguments?: Record<string, any>;
+ name: string
+ arguments?: Record<string, any>
}
interface McpToolCallResponse {
content: Array<{
- type: string;
- text?: string;
- }>;
- isError?: boolean;
+ type: string
+ text?: string
+ }>
+ isError?: boolean
}
// =============================================================================
@@ -51,10 +50,10 @@ interface McpToolCallResponse {
// =============================================================================
class MockAirtableMcpServer {
- private airtableClient: ReturnType<typeof createMockAirtableClient>;
+ private airtableClient: ReturnType<typeof createMockAirtableClient>
constructor() {
- this.airtableClient = createMockAirtableClient();
+ this.airtableClient = createMockAirtableClient()
}
/**
@@ -179,7 +178,7 @@ class MockAirtableMcpServer {
},
},
],
- };
+ }
}
/**
@@ -187,33 +186,33 @@ class MockAirtableMcpServer {
* Execute an Airtable MCP tool
*/
async toolsCall(request: McpToolCallRequest): Promise<McpToolCallResponse> {
- const { name, arguments: args } = request;
+ const { name, arguments: args } = request
try {
switch (name) {
case 'airtable_list_bases':
- return await this.listBases();
+ return await this.listBases()
case 'airtable_list_tables':
- return await this.listTables(args!);
+ return await this.listTables(args!)
case 'airtable_list_records':
- return await this.listRecords(args!);
+ return await this.listRecords(args!)
case 'airtable_get_record':
- return await this.getRecord(args!);
+ return await this.getRecord(args!)
case 'airtable_create_record':
- return await this.createRecord(args!);
+ return await this.createRecord(args!)
case 'airtable_update_record':
- return await this.updateRecord(args!);
+ return await this.updateRecord(args!)
case 'airtable_delete_record':
- return await this.deleteRecord(args!);
+ return await this.deleteRecord(args!)
case 'airtable_query_records':
- return await this.queryRecords(args!);
+ return await this.queryRecords(args!)
default:
return {
@@ -224,7 +223,7 @@ class MockAirtableMcpServer {
},
],
isError: true,
- };
+ }
}
} catch (error: any) {
return {
@@ -235,7 +234,7 @@ class MockAirtableMcpServer {
},
],
isError: true,
- };
+ }
}
}
@@ -248,7 +247,7 @@ class MockAirtableMcpServer {
const bases = [
{ id: 'appBase123', name: 'Test Base 1' },
{ id: 'appBase456', name: 'Test Base 2' },
- ];
+ ]
return {
content: [
@@ -257,21 +256,21 @@ class MockAirtableMcpServer {
text: JSON.stringify(bases, null, 2),
},
],
- };
+ }
}
private async listTables(args: any): Promise<McpToolCallResponse> {
- const { baseId } = args;
+ const { baseId } = args
if (!baseId) {
- throw new Error('baseId is required');
+ throw new Error('baseId is required')
}
// Mock response
const tables = [
{ id: 'tblTable1', name: 'Users' },
{ id: 'tblTable2', name: 'Products' },
- ];
+ ]
return {
content: [
@@ -280,19 +279,19 @@ class MockAirtableMcpServer {
text: JSON.stringify(tables, null, 2),
},
],
- };
+ }
}
private async listRecords(args: any): Promise<McpToolCallResponse> {
- const { baseId, tableId, limit } = args;
+ const { baseId, tableId, limit } = args
if (!baseId || !tableId) {
- throw new Error('baseId and tableId are required');
+ throw new Error('baseId and tableId are required')
}
const result = await this.airtableClient.listRecords(baseId, tableId, {
limit,
- });
+ })
return {
content: [
@@ -301,17 +300,17 @@ class MockAirtableMcpServer {
text: JSON.stringify(result.records, null, 2),
},
],
- };
+ }
}
private async getRecord(args: any): Promise<McpToolCallResponse> {
- const { baseId, tableId, recordId } = args;
+ const { baseId, tableId, recordId } = args
if (!baseId || !tableId || !recordId) {
- throw new Error('baseId, tableId, and recordId are required');
+ throw new Error('baseId, tableId, and recordId are required')
}
- const record = await this.airtableClient.getRecord(baseId, tableId, recordId);
+ const record = await this.airtableClient.getRecord(baseId, tableId, recordId)
return {
content: [
@@ -320,17 +319,17 @@ class MockAirtableMcpServer {
text: JSON.stringify(record, null, 2),
},
],
- };
+ }
}
private async createRecord(args: any): Promise<McpToolCallResponse> {
- const { baseId, tableId, fields } = args;
+ const { baseId, tableId, fields } = args
if (!baseId || !tableId || !fields) {
- throw new Error('baseId, tableId, and fields are required');
+ throw new Error('baseId, tableId, and fields are required')
}
- const record = await this.airtableClient.createRecord(baseId, tableId, fields);
+ const record = await this.airtableClient.createRecord(baseId, tableId, fields)
return {
content: [
@@ -339,22 +338,17 @@ class MockAirtableMcpServer {
text: JSON.stringify(record, null, 2),
},
],
- };
+ }
}
private async updateRecord(args: any): Promise<McpToolCallResponse> {
- const { baseId, tableId, recordId, fields } = args;
+ const { baseId, tableId, recordId, fields } = args
if (!baseId || !tableId || !recordId || !fields) {
- throw new Error('baseId, tableId, recordId, and fields are required');
+ throw new Error('baseId, tableId, recordId, and fields are required')
}
- const record = await this.airtableClient.updateRecord(
- baseId,
- tableId,
- recordId,
- fields
- );
+ const record = await this.airtableClient.updateRecord(baseId, tableId, recordId, fields)
return {
content: [
@@ -363,21 +357,17 @@ class MockAirtableMcpServer {
text: JSON.stringify(record, null, 2),
},
],
- };
+ }
}
private async deleteRecord(args: any): Promise<McpToolCallResponse> {
- const { baseId, tableId, recordId } = args;
+ const { baseId, tableId, recordId } = args
if (!baseId || !tableId || !recordId) {
- throw new Error('baseId, tableId, and recordId are required');
+ throw new Error('baseId, tableId, and recordId are required')
}
- const result = await this.airtableClient.deleteRecord(
- baseId,
- tableId,
- recordId
- );
+ const result = await this.airtableClient.deleteRecord(baseId, tableId, recordId)
return {
content: [
@@ -386,21 +376,21 @@ class MockAirtableMcpServer {
text: JSON.stringify(result, null, 2),
},
],
- };
+ }
}
private async queryRecords(args: any): Promise<McpToolCallResponse> {
- const { baseId, tableId, filterByFormula, maxRecords } = args;
+ const { baseId, tableId, filterByFormula, maxRecords } = args
if (!baseId || !tableId) {
- throw new Error('baseId and tableId are required');
+ throw new Error('baseId and tableId are required')
}
// Mock query implementation
// In real implementation, would use filterByFormula
const result = await this.airtableClient.listRecords(baseId, tableId, {
limit: maxRecords,
- });
+ })
return {
content: [
@@ -409,7 +399,7 @@ class MockAirtableMcpServer {
text: JSON.stringify(result.records, null, 2),
},
],
- };
+ }
}
// =============================================================================
@@ -428,9 +418,9 @@ class MockAirtableMcpServer {
createdTime: '2024-01-02T00:00:00.000Z',
fields: { Name: 'Bob', Email: '[email protected]' },
},
- ];
+ ]
- (this.airtableClient as any).setMockData('appBase123', 'tblUsers', records);
+ ;(this.airtableClient as any).setMockData('appBase123', 'tblUsers', records)
}
}
@@ -439,66 +429,60 @@ class MockAirtableMcpServer {
// =============================================================================
describe('Airtable MCP Server - MCP Operations', () => {
- let server: MockAirtableMcpServer;
+ let server: MockAirtableMcpServer
beforeEach(() => {
- server = new MockAirtableMcpServer();
- server.setupMockData();
- });
+ server = new MockAirtableMcpServer()
+ server.setupMockData()
+ })
describe('tools/list', () => {
it('should return all available Airtable tools', async () => {
- const response = await server.toolsList();
+ const response = await server.toolsList()
- expect(response.tools).toBeDefined();
- expect(response.tools.length).toBeGreaterThan(0);
- });
+ expect(response.tools).toBeDefined()
+ expect(response.tools.length).toBeGreaterThan(0)
+ })
it('should include airtable_list_records tool', async () => {
- const response = await server.toolsList();
+ const response = await server.toolsList()
- const listRecordsTool = response.tools.find(
- t => t.name === 'airtable_list_records'
- );
- expect(listRecordsTool).toBeDefined();
- expect(listRecordsTool?.description).toContain('records');
- });
+ const listRecordsTool = response.tools.find(t => t.name === 'airtable_list_records')
+ expect(listRecordsTool).toBeDefined()
+ expect(listRecordsTool?.description).toContain('records')
+ })
it('should have correct input schema for list_records', async () => {
- const response = await server.toolsList();
+ const response = await server.toolsList()
- const listRecordsTool = response.tools.find(
- t => t.name === 'airtable_list_records'
- );
+ const listRecordsTool = response.tools.find(t => t.name === 'airtable_list_records')
- expect(listRecordsTool?.inputSchema.type).toBe('object');
- expect(listRecordsTool?.inputSchema.properties).toHaveProperty('baseId');
- expect(listRecordsTool?.inputSchema.properties).toHaveProperty('tableId');
- expect(listRecordsTool?.inputSchema.required).toEqual(['baseId', 'tableId']);
- });
+ expect(listRecordsTool?.inputSchema.type).toBe('object')
+ expect(listRecordsTool?.inputSchema.properties).toHaveProperty('baseId')
+ expect(listRecordsTool?.inputSchema.properties).toHaveProperty('tableId')
+ expect(listRecordsTool?.inputSchema.required).toEqual(['baseId', 'tableId'])
+ })
it('should include CRUD operations tools', async () => {
- const response = await server.toolsList();
+ const response = await server.toolsList()
- const toolNames = response.tools.map(t => t.name);
+ const toolNames = response.tools.map(t => t.name)
- expect(toolNames).toContain('airtable_create_record');
- expect(toolNames).toContain('airtable_get_record');
- expect(toolNames).toContain('airtable_update_record');
- expect(toolNames).toContain('airtable_delete_record');
- });
+ expect(toolNames).toContain('airtable_create_record')
+ expect(toolNames).toContain('airtable_get_record')
+ expect(toolNames).toContain('airtable_update_record')
+ expect(toolNames).toContain('airtable_delete_record')
+ })
it('should include query operation tool', async () => {
- const response = await server.toolsList();
+ const response = await server.toolsList()
- const queryTool = response.tools.find(
- t => t.name === 'airtable_query_records'
- );
+ const queryTool = response.tools.find(t => t.name === 'airtable_query_records')
- expect(queryTool).toBeDefined();
- expect(queryTool?.inputSchema.properties).toHaveProperty('filterByFormula');
- });
- });
+ expect(queryTool).toBeDefined()
+ expect(queryTool?.inputSchema.properties).toHaveProperty('filterByFormula')
+ })
+ })
describe('tools/call - airtable_list_records', () => {
it('should list records successfully', async () => {
@@ -508,16 +492,16 @@ describe('Airtable MCP Server - MCP Operations', () => {
baseId: 'appBase123',
tableId: 'tblUsers',
},
- });
+ })
- expect(response.isError).toBeUndefined();
- expect(response.content).toHaveLength(1);
- expect(response.content[0].type).toBe('text');
+ expect(response.isError).toBeUndefined()
+ expect(response.content).toHaveLength(1)
+ expect(response.content[0].type).toBe('text')
- const records = JSON.parse(response.content[0].text!);
- expect(records).toHaveLength(2);
- expect(records[0].fields.Name).toBe('Alice');
- });
+ const records = JSON.parse(response.content[0].text!)
+ expect(records).toHaveLength(2)
+ expect(records[0].fields.Name).toBe('Alice')
+ })
it('should respect limit parameter', async () => {
const response = await server.toolsCall({
@@ -527,11 +511,11 @@ describe('Airtable MCP Server - MCP Operations', () => {
tableId: 'tblUsers',
limit: 1,
},
- });
+ })
- const records = JSON.parse(response.content[0].text!);
- expect(records).toHaveLength(1);
- });
+ const records = JSON.parse(response.content[0].text!)
+ expect(records).toHaveLength(1)
+ })
it('should return error for missing baseId', async () => {
const response = await server.toolsCall({
@@ -539,11 +523,11 @@ describe('Airtable MCP Server - MCP Operations', () => {
arguments: {
tableId: 'tblUsers',
},
- });
+ })
- expect(response.isError).toBe(true);
- expect(response.content[0].text).toContain('baseId');
- });
+ expect(response.isError).toBe(true)
+ expect(response.content[0].text).toContain('baseId')
+ })
it('should return error for missing tableId', async () => {
const response = await server.toolsCall({
@@ -551,12 +535,12 @@ describe('Airtable MCP Server - MCP Operations', () => {
arguments: {
baseId: 'appBase123',
},
- });
+ })
- expect(response.isError).toBe(true);
- expect(response.content[0].text).toContain('tableId');
- });
- });
+ expect(response.isError).toBe(true)
+ expect(response.content[0].text).toContain('tableId')
+ })
+ })
describe('tools/call - airtable_get_record', () => {
it('should get a specific record', async () => {
@@ -567,14 +551,14 @@ describe('Airtable MCP Server - MCP Operations', () => {
tableId: 'tblUsers',
recordId: 'rec1',
},
- });
+ })
- expect(response.isError).toBeUndefined();
+ expect(response.isError).toBeUndefined()
- const record = JSON.parse(response.content[0].text!);
- expect(record.id).toBe('rec1');
- expect(record.fields.Name).toBe('Alice');
- });
+ const record = JSON.parse(response.content[0].text!)
+ expect(record.id).toBe('rec1')
+ expect(record.fields.Name).toBe('Alice')
+ })
it('should return error for non-existent record', async () => {
const response = await server.toolsCall({
@@ -584,12 +568,12 @@ describe('Airtable MCP Server - MCP Operations', () => {
tableId: 'tblUsers',
recordId: 'recNonExistent',
},
- });
+ })
- expect(response.isError).toBe(true);
- expect(response.content[0].text).toContain('NOT_FOUND');
- });
- });
+ expect(response.isError).toBe(true)
+ expect(response.content[0].text).toContain('NOT_FOUND')
+ })
+ })
describe('tools/call - airtable_create_record', () => {
it('should create a new record', async () => {
@@ -603,14 +587,14 @@ describe('Airtable MCP Server - MCP Operations', () => {
},
},
- });
+ })
- expect(response.isError).toBeUndefined();
+ expect(response.isError).toBeUndefined()
- const record = JSON.parse(response.content[0].text!);
- expect(record.fields.Name).toBe('Charlie');
- expect(record.id).toMatch(/^rec\d+$/);
- });
+ const record = JSON.parse(response.content[0].text!)
+ expect(record.fields.Name).toBe('Charlie')
+ expect(record.id).toMatch(/^rec\d+$/)
+ })
it('should return error for missing fields', async () => {
const response = await server.toolsCall({
@@ -619,12 +603,12 @@ describe('Airtable MCP Server - MCP Operations', () => {
baseId: 'appBase123',
tableId: 'tblUsers',
},
- });
+ })
- expect(response.isError).toBe(true);
- expect(response.content[0].text).toContain('fields');
- });
- });
+ expect(response.isError).toBe(true)
+ expect(response.content[0].text).toContain('fields')
+ })
+ })
describe('tools/call - airtable_update_record', () => {
it('should update an existing record', async () => {
@@ -638,15 +622,15 @@ describe('Airtable MCP Server - MCP Operations', () => {
},
},
- });
+ })
- expect(response.isError).toBeUndefined();
+ expect(response.isError).toBeUndefined()
- const record = JSON.parse(response.content[0].text!);
- expect(record.fields.Name).toBe('Alice'); // Unchanged
- expect(record.fields.Email).toBe('[email protected]');
- });
- });
+ const record = JSON.parse(response.content[0].text!)
+ expect(record.fields.Name).toBe('Alice') // Unchanged
+ expect(record.fields.Email).toBe('[email protected]')
+ })
+ })
describe('tools/call - airtable_delete_record', () => {
it('should delete a record', async () => {
@@ -657,27 +641,27 @@ describe('Airtable MCP Server - MCP Operations', () => {
tableId: 'tblUsers',
recordId: 'rec1',
},
- });
+ })
- expect(response.isError).toBeUndefined();
+ expect(response.isError).toBeUndefined()
- const result = JSON.parse(response.content[0].text!);
- expect(result.deleted).toBe(true);
- expect(result.id).toBe('rec1');
- });
- });
+ const result = JSON.parse(response.content[0].text!)
+ expect(result.deleted).toBe(true)
+ expect(result.id).toBe('rec1')
+ })
+ })
describe('tools/call - unknown tool', () => {
it('should return error for unknown tool', async () => {
const response = await server.toolsCall({
name: 'unknown_tool',
arguments: {},
- });
+ })
- expect(response.isError).toBe(true);
- expect(response.content[0].text).toContain('Unknown tool');
- });
- });
+ expect(response.isError).toBe(true)
+ expect(response.content[0].text).toContain('Unknown tool')
+ })
+ })
describe('Response Format', () => {
it('should return content array', async () => {
@@ -687,10 +671,10 @@ describe('Airtable MCP Server - MCP Operations', () => {
baseId: 'appBase123',
tableId: 'tblUsers',
},
- });
+ })
- expect(Array.isArray(response.content)).toBe(true);
- });
+ expect(Array.isArray(response.content)).toBe(true)
+ })
it('should include text type in content', async () => {
const response = await server.toolsCall({
@@ -699,11 +683,11 @@ describe('Airtable MCP Server - MCP Operations', () => {
baseId: 'appBase123',
tableId: 'tblUsers',
},
- });
+ })
- expect(response.content[0].type).toBe('text');
- expect(response.content[0].text).toBeDefined();
- });
+ expect(response.content[0].type).toBe('text')
+ expect(response.content[0].text).toBeDefined()
+ })
it('should return valid JSON in text field', async () => {
const response = await server.toolsCall({
@@ -712,11 +696,11 @@ describe('Airtable MCP Server - MCP Operations', () => {
baseId: 'appBase123',
tableId: 'tblUsers',
},
- });
+ })
expect(() => {
- JSON.parse(response.content[0].text!);
- }).not.toThrow();
- });
- });
-});
+ JSON.parse(response.content[0].text!)
+ }).not.toThrow()
+ })
+ })
+})
diff --git a/mcp-servers/airtable/example.secret.yaml b/mcp-servers/airtable/example.secret.yaml
index 17c514683..cbe284d81 100644
--- a/mcp-servers/airtable/example.secret.yaml
+++ b/mcp-servers/airtable/example.secret.yaml
@@ -9,4 +9,4 @@ type: Opaque
data:
# Base64-encoded Airtable personal access token
# To encode: echo -n "patXXX.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" | base64
- api-key: "<BASE64_ENCODED_AIRTABLE_API_KEY>"
+ api-key: '<BASE64_ENCODED_AIRTABLE_API_KEY>'
diff --git a/mcp-servers/doc-generator/package-lock.json b/mcp-servers/doc-generator/package-lock.json
index 96f5e608a..1ce69afcb 100644
--- a/mcp-servers/doc-generator/package-lock.json
+++ b/mcp-servers/doc-generator/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@clerum/doc-generator-mcp",
- "version": "1.0.5",
+ "version": "1.0.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@clerum/doc-generator-mcp",
- "version": "1.0.5",
+ "version": "1.0.6",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"exceljs": "^4.4.0",
diff --git a/mcp-servers/doc-generator/package.json b/mcp-servers/doc-generator/package.json
index 5d087dd7f..3116a65c7 100644
--- a/mcp-servers/doc-generator/package.json
+++ b/mcp-servers/doc-generator/package.json
@@ -1,6 +1,6 @@
{
"name": "@clerum/doc-generator-mcp",
- "version": "1.0.5",
+ "version": "1.0.6",
"type": "module",
"main": "dist/index.js",
"scripts": {
diff --git a/mcp-servers/doc-generator/src/index.ts b/mcp-servers/doc-generator/src/index.ts
index ccb79b0b7..b945e9c90 100644
--- a/mcp-servers/doc-generator/src/index.ts
+++ b/mcp-servers/doc-generator/src/index.ts
@@ -11,26 +11,25 @@
* Health check: GET /health on the same port.
* MCP endpoint: POST /mcp
*/
-
-import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
-import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
-import { IncomingMessage, ServerResponse, createServer } from "http";
-import { randomUUID } from "crypto";
-import { z } from "zod";
-import fs from "fs";
-import path from "path";
-import MarkdownIt from "markdown-it";
-import ExcelJS from "exceljs";
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
+import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'
+import { randomUUID } from 'crypto'
+import ExcelJS from 'exceljs'
+import fs from 'fs'
+import { IncomingMessage, ServerResponse, createServer } from 'http'
+import MarkdownIt from 'markdown-it'
+import path from 'path'
+import { z } from 'zod'
// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------
-const PORT = parseInt(process.env.PORT || "3000", 10);
-const OUTPUT_DIR = process.env.OUTPUT_DIR || "/output";
+const PORT = parseInt(process.env.PORT || '3000', 10)
+const OUTPUT_DIR = process.env.OUTPUT_DIR || '/output'
// Ensure output directory exists on startup
-fs.mkdirSync(OUTPUT_DIR, { recursive: true });
+fs.mkdirSync(OUTPUT_DIR, { recursive: true })
// ---------------------------------------------------------------------------
// Helpers
@@ -40,35 +39,33 @@ fs.mkdirSync(OUTPUT_DIR, { recursive: true });
function sanitizeFilename(title: string): string {
return title
.toLowerCase()
- .replace(/[^a-z0-9]+/g, "-")
- .replace(/^-|-$/g, "")
- .slice(0, 100);
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-|-$/g, '')
+ .slice(0, 100)
}
/** Strip HTML tags from a string to produce plain text. */
function stripHtml(html: string): string {
return html
- .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "")
- .replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "")
- .replace(/<[^>]+>/g, "")
- .replace(/&nbsp;/g, " ")
- .replace(/&amp;/g, "&")
- .replace(/&lt;/g, "<")
- .replace(/&gt;/g, ">")
+ .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
+ .replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
+ .replace(/<[^>]+>/g, '')
+ .replace(/&nbsp;/g, ' ')
+ .replace(/&amp;/g, '&')
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'")
- .replace(/\n{3,}/g, "\n\n")
- .trim();
+ .replace(/\n{3,}/g, '\n\n')
+ .trim()
}
/**
* Wrap HTML body content in a full, print-ready HTML document with professional
* CSS styling (fonts, margins, headers, page-break rules).
*/
-function wrapHtmlDocument(title: string, bodyHtml: string, format: "a4" | "letter"): string {
- const pageSize = format === "a4"
- ? "210mm 297mm"
- : "8.5in 11in";
+function wrapHtmlDocument(title: string, bodyHtml: string, format: 'a4' | 'letter'): string {
+ const pageSize = format === 'a4' ? '210mm 297mm' : '8.5in 11in'
return `<!DOCTYPE html>
<html lang="en">
@@ -215,22 +212,22 @@ function wrapHtmlDocument(title: string, bodyHtml: string, format: "a4" | "lette
<body>
<div class="doc-header">
<h1>${escapeHtml(title)}</h1>
- <div class="meta">Generated on ${new Date().toISOString().split("T")[0]} by Clerum Doc Generator</div>
+ <div class="meta">Generated on ${new Date().toISOString().split('T')[0]} by Clerum Doc Generator</div>
</div>
<div class="doc-content">
${bodyHtml}
</div>
</body>
-</html>`;
+</html>`
}
/** Basic HTML entity escaping. */
function escapeHtml(str: string): string {
return str
- .replace(/&/g, "&amp;")
- .replace(/</g, "&lt;")
- .replace(/>/g, "&gt;")
- .replace(/"/g, "&quot;");
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
}
// ---------------------------------------------------------------------------
@@ -239,163 +236,168 @@ function escapeHtml(str: string): string {
function createDocGeneratorServer(): McpServer {
const server = new McpServer({
- name: "doc-generator",
- version: "1.0.0",
- });
+ name: 'doc-generator',
+ version: '1.0.0',
+ })
- const md = new MarkdownIt({ html: true, linkify: true, typographer: true });
+ const md = new MarkdownIt({ html: true, linkify: true, typographer: true })
// ---- Tool 1: generate_pdf (HTML output) --------------------------------
server.tool(
- "generate_pdf",
- "Converts markdown content to a professional, print-ready HTML document. Also writes a plain-text version. Returns the file path and size.",
+ 'generate_pdf',
+ 'Converts markdown content to a professional, print-ready HTML document. Also writes a plain-text version. Returns the file path and size.',
{
- content: z.string().describe("Markdown content to convert"),
- title: z.string().describe("Document title"),
- format: z
- .enum(["a4", "letter"])
- .default("a4")
- .describe("Page format (a4 or letter)"),
+ content: z.string().describe('Markdown content to convert'),
+ title: z.string().describe('Document title'),
+ format: z.enum(['a4', 'letter']).default('a4').describe('Page format (a4 or letter)'),
},
- async ({ content, title, format }: { content: string; title: string; format: "a4" | "letter" }) => {
- const safeName = sanitizeFilename(title);
- const htmlPath = path.join(OUTPUT_DIR, `${safeName}.html`);
- const txtPath = path.join(OUTPUT_DIR, `${safeName}.txt`);
+ async ({
+ content,
+ title,
+ format,
+ }: {
+ content: string
+ title: string
+ format: 'a4' | 'letter'
+ }) => {
+ const safeName = sanitizeFilename(title)
+ const htmlPath = path.join(OUTPUT_DIR, `${safeName}.html`)
+ const txtPath = path.join(OUTPUT_DIR, `${safeName}.txt`)
// Render markdown to HTML body
- const bodyHtml = md.render(content);
+ const bodyHtml = md.render(content)
// Wrap in full styled document
- const fullHtml = wrapHtmlDocument(title, bodyHtml, format);
+ const fullHtml = wrapHtmlDocument(title, bodyHtml, format)
// Write HTML
- fs.writeFileSync(htmlPath, fullHtml, "utf-8");
+ fs.writeFileSync(htmlPath, fullHtml, 'utf-8')
// Write plain text version
- const plainText = `${title}\n${"=".repeat(title.length)}\n\n${stripHtml(bodyHtml)}`;
- fs.writeFileSync(txtPath, plainText, "utf-8");
+ const plainText = `${title}\n${'='.repeat(title.length)}\n\n${stripHtml(bodyHtml)}`
+ fs.writeFileSync(txtPath, plainText, 'utf-8')
- const stats = fs.statSync(htmlPath);
+ const stats = fs.statSync(htmlPath)
return {
content: [
{
- type: "text" as const,
+ type: 'text' as const,
text: JSON.stringify({
filePath: htmlPath,
textFilePath: txtPath,
sizeBytes: stats.size,
- format: "html",
+ format: 'html',
}),
},
],
- };
+ }
}
- );
+ )
// ---- Tool 2: generate_excel --------------------------------------------
server.tool(
- "generate_excel",
- "Creates an Excel (.xlsx) workbook with styled sheets. Supports multiple sheets with headers and rows, bold headers, auto-width columns, and alternating row colors.",
+ 'generate_excel',
+ 'Creates an Excel (.xlsx) workbook with styled sheets. Supports multiple sheets with headers and rows, bold headers, auto-width columns, and alternating row colors.',
{
sheets: z
.array(
z.object({
- name: z.string().describe("Worksheet name"),
- headers: z.array(z.string()).describe("Column headers"),
- rows: z.array(z.array(z.string())).describe("Row data (array of arrays)"),
+ name: z.string().describe('Worksheet name'),
+ headers: z.array(z.string()).describe('Column headers'),
+ rows: z.array(z.array(z.string())).describe('Row data (array of arrays)'),
})
)
- .describe("Array of sheet definitions"),
- title: z.string().describe("Workbook filename title"),
+ .describe('Array of sheet definitions'),
+ title: z.string().describe('Workbook filename title'),
},
async ({
sheets,
title,
}: {
- sheets: Array<{ name: string; headers: string[]; rows: string[][] }>;
- title: string;
+ sheets: Array<{ name: string; headers: string[]; rows: string[][] }>
+ title: string
}) => {
- const safeName = sanitizeFilename(title);
- const xlsxPath = path.join(OUTPUT_DIR, `${safeName}.xlsx`);
+ const safeName = sanitizeFilename(title)
+ const xlsxPath = path.join(OUTPUT_DIR, `${safeName}.xlsx`)
- const workbook = new ExcelJS.Workbook();
- workbook.creator = "Clerum Doc Generator";
- workbook.created = new Date();
+ const workbook = new ExcelJS.Workbook()
+ workbook.creator = 'Clerum Doc Generator'
+ workbook.created = new Date()
for (const sheet of sheets) {
- const ws = workbook.addWorksheet(sheet.name);
+ const ws = workbook.addWorksheet(sheet.name)
// Set columns with headers and auto-width estimation
- ws.columns = sheet.headers.map((header) => {
+ ws.columns = sheet.headers.map(header => {
// Estimate width: max of header length and longest cell in that column
- const colIndex = sheet.headers.indexOf(header);
+ const colIndex = sheet.headers.indexOf(header)
const maxDataLen = sheet.rows.reduce((max, row) => {
- const cellLen = (row[colIndex] || "").length;
- return cellLen > max ? cellLen : max;
- }, 0);
- const width = Math.max(header.length, maxDataLen, 10) + 4;
+ const cellLen = (row[colIndex] || '').length
+ return cellLen > max ? cellLen : max
+ }, 0)
+ const width = Math.max(header.length, maxDataLen, 10) + 4
- return { header, key: header, width: Math.min(width, 50) };
- });
+ return { header, key: header, width: Math.min(width, 50) }
+ })
// Style header row: bold, white text on dark background
- const headerRow = ws.getRow(1);
- headerRow.font = { bold: true, color: { argb: "FFFFFFFF" }, size: 11 };
+ const headerRow = ws.getRow(1)
+ headerRow.font = { bold: true, color: { argb: 'FFFFFFFF' }, size: 11 }
headerRow.fill = {
- type: "pattern",
- pattern: "solid",
- fgColor: { argb: "FF16213E" },
- };
- headerRow.alignment = { vertical: "middle", horizontal: "left" };
- headerRow.height = 24;
+ type: 'pattern',
+ pattern: 'solid',
+ fgColor: { argb: 'FF16213E' },
+ }
+ headerRow.alignment = { vertical: 'middle', horizontal: 'left' }
+ headerRow.height = 24
// Add data rows
for (let rowIdx = 0; rowIdx < sheet.rows.length; rowIdx++) {
- const dataRow = sheet.rows[rowIdx];
- const rowObj: Record<string, string> = {};
+ const dataRow = sheet.rows[rowIdx]
+ const rowObj: Record<string, string> = {}
sheet.headers.forEach((h, i) => {
- rowObj[h] = dataRow[i] || "";
- });
- const excelRow = ws.addRow(rowObj);
+ rowObj[h] = dataRow[i] || ''
+ })
+ const excelRow = ws.addRow(rowObj)
// Alternating row colors
if (rowIdx % 2 === 0) {
excelRow.fill = {
- type: "pattern",
- pattern: "solid",
- fgColor: { argb: "FFF9FAFB" },
- };
+ type: 'pattern',
+ pattern: 'solid',
+ fgColor: { argb: 'FFF9FAFB' },
+ }
}
- excelRow.alignment = { vertical: "middle" };
+ excelRow.alignment = { vertical: 'middle' }
}
// Add thin borders to all cells with data
- const lastRow = ws.rowCount;
- const lastCol = sheet.headers.length;
+ const lastRow = ws.rowCount
+ const lastCol = sheet.headers.length
for (let r = 1; r <= lastRow; r++) {
for (let c = 1; c <= lastCol; c++) {
- const cell = ws.getCell(r, c);
+ const cell = ws.getCell(r, c)
cell.border = {
- top: { style: "thin", color: { argb: "FFE5E7EB" } },
- bottom: { style: "thin", color: { argb: "FFE5E7EB" } },
- left: { style: "thin", color: { argb: "FFE5E7EB" } },
- right: { style: "thin", color: { argb: "FFE5E7EB" } },
- };
+ top: { style: 'thin', color: { argb: 'FFE5E7EB' } },
+ bottom: { style: 'thin', color: { argb: 'FFE5E7EB' } },
+ left: { style: 'thin', color: { argb: 'FFE5E7EB' } },
+ right: { style: 'thin', color: { argb: 'FFE5E7EB' } },
+ }
}
}
}
- await workbook.xlsx.writeFile(xlsxPath);
- const stats = fs.statSync(xlsxPath);
+ await workbook.xlsx.writeFile(xlsxPath)
+ const stats = fs.statSync(xlsxPath)
return {
content: [
{
- type: "text" as const,
+ type: 'text' as const,
text: JSON.stringify({
filePath: xlsxPath,
sizeBytes: stats.size,
@@ -403,105 +405,105 @@ function createDocGeneratorServer(): McpServer {
}),
},
],
- };
+ }
}
- );
+ )
// ---- Tool 3: list_artifacts --------------------------------------------
server.tool(
- "list_artifacts",
- "Lists all generated files in the output directory with name, path, size, and creation date.",
+ 'list_artifacts',
+ 'Lists all generated files in the output directory with name, path, size, and creation date.',
{},
async () => {
- let entries: string[];
+ let entries: string[]
try {
- entries = fs.readdirSync(OUTPUT_DIR);
+ entries = fs.readdirSync(OUTPUT_DIR)
} catch {
- entries = [];
+ entries = []
}
const files = entries
- .map((name) => {
- const filePath = path.join(OUTPUT_DIR, name);
+ .map(name => {
+ const filePath = path.join(OUTPUT_DIR, name)
try {
- const stats = fs.statSync(filePath);
- if (!stats.isFile()) return null;
+ const stats = fs.statSync(filePath)
+ if (!stats.isFile()) return null
return {
name,
path: filePath,
sizeBytes: stats.size,
createdAt: stats.birthtime.toISOString(),
- };
+ }
} catch {
- return null;
+ return null
}
})
- .filter((f) => f !== null);
+ .filter(f => f !== null)
return {
content: [
{
- type: "text" as const,
+ type: 'text' as const,
text: JSON.stringify({ files }),
},
],
- };
+ }
}
- );
+ )
- return server;
+ return server
}
// ---------------------------------------------------------------------------
// StreamableHTTP Transport (raw http, matching mock-mcp-server pattern)
// ---------------------------------------------------------------------------
-const transports = new Map<string, StreamableHTTPServerTransport>();
+const transports = new Map<string, StreamableHTTPServerTransport>()
async function handleMcp(req: IncomingMessage, res: ServerResponse) {
- const sessionId = req.headers["mcp-session-id"] as string | undefined;
+ const sessionId = req.headers['mcp-session-id'] as string | undefined
// Existing session
if (sessionId && transports.has(sessionId)) {
- const transport = transports.get(sessionId)!;
- await transport.handleRequest(req, res);
- return;
+ const transport = transports.get(sessionId)!
+ await transport.handleRequest(req, res)
+ return
}
// New POST = new session (initialize)
- if (req.method === "POST") {
+ if (req.method === 'POST') {
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: () => randomUUID(),
- });
+ })
// Connect a fresh McpServer to this transport BEFORE handling the request.
- const server = createDocGeneratorServer();
- await server.connect(transport);
+ const server = createDocGeneratorServer()
+ await server.connect(transport)
// Handle the incoming initialize request.
- await transport.handleRequest(req, res);
+ await transport.handleRequest(req, res)
// Extract session ID assigned by the transport.
- const assignedSessionId = (transport as any).sessionId as string | undefined;
+ const assignedSessionId = (transport as any).sessionId as string | undefined
if (assignedSessionId) {
- transports.set(assignedSessionId, transport);
- console.log(`[DocGenerator] New session: ${assignedSessionId}`);
+ transports.set(assignedSessionId, transport)
+ console.log(`[DocGenerator] New session: ${assignedSessionId}`)
}
transport.onclose = () => {
if (assignedSessionId) {
- transports.delete(assignedSessionId);
- console.log(`[DocGenerator] Session closed: ${assignedSessionId}`);
+ transports.delete(assignedSessionId)
+ console.log(`[DocGenerator] Session closed: ${assignedSessionId}`)
}
- };
+ }
- return;
+ return
}
// Non-POST without session
- res.writeHead(400, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ error: "Bad request - send POST to initialize" }));
+ res.writeHead(400, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: 'Bad request - send POST to initialize' }))
}
// ---------------------------------------------------------------------------
@@ -510,40 +512,40 @@ async function handleMcp(req: IncomingMessage, res: ServerResponse) {
const httpServer = createServer(async (req, res) => {
// Health check
- if (req.url === "/health" && req.method === "GET") {
- res.writeHead(200, { "Content-Type": "application/json" });
+ if (req.url === '/health' && req.method === 'GET') {
+ res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(
JSON.stringify({
- status: "ok",
- tools: ["generate_pdf", "generate_excel", "list_artifacts"],
+ status: 'ok',
+ tools: ['generate_pdf', 'generate_excel', 'list_artifacts'],
outputDir: OUTPUT_DIR,
})
- );
- return;
+ )
+ return
}
// MCP endpoint
- if (req.url === "/mcp") {
+ if (req.url === '/mcp') {
try {
- await handleMcp(req, res);
+ await handleMcp(req, res)
} catch (e) {
- console.error("[DocGenerator] Error:", e);
+ console.error('[DocGenerator] Error:', e)
if (!res.headersSent) {
- res.writeHead(500, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ error: String(e) }));
+ res.writeHead(500, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: String(e) }))
}
}
- return;
+ return
}
// Not found
- res.writeHead(404, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ error: "Not found" }));
-});
-
-httpServer.listen(PORT, "0.0.0.0", () => {
- console.log(`[DocGenerator] StreamableHTTP server listening on port ${PORT}`);
- console.log(`[DocGenerator] Output directory: ${OUTPUT_DIR}`);
- console.log(`[DocGenerator] Health check: GET http://0.0.0.0:${PORT}/health`);
- console.log(`[DocGenerator] MCP endpoint: POST http://0.0.0.0:${PORT}/mcp`);
-});
+ res.writeHead(404, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify({ error: 'Not found' }))
+})
+
+httpServer.listen(PORT, '0.0.0.0', () => {
+ console.log(`[DocGenerator] StreamableHTTP server listening on port ${PORT}`)
+ console.log(`[DocGenerator] Output directory: ${OUTPUT_DIR}`)
+ console.log(`[DocGenerator] Health check: GET http://0.0.0.0:${PORT}/health`)
+ console.log(`[DocGenerator] MCP endpoint: POST http://0.0.0.0:${PORT}/mcp`)
+})
diff --git a/mcp-servers/mongodb/__tests__/mongodb.config.test.ts b/mcp-servers/mongodb/__tests__/mongodb.config.test.ts
index a3b8f6e2a..7c7ca685d 100644
--- a/mcp-servers/mongodb/__tests__/mongodb.config.test.ts
+++ b/mcp-servers/mongodb/__tests__/mongodb.config.test.ts
@@ -12,76 +12,75 @@
* - Secret references
* - Health check configuration
*/
-
-import { describe, it, expect, beforeEach } from 'vitest';
-import { readFileSync } from 'fs';
-import { join } from 'path';
-import { loadYaml } from '../../utils/yaml-loader';
+import { beforeEach, describe, expect, it } from 'vitest'
+import { readFileSync } from 'fs'
+import { join } from 'path'
+import { loadYaml } from '../../utils/yaml-loader'
// =============================================================================
// Test Data
// =============================================================================
-const MCP_SERVER_YAML = join(__dirname, '../mcpserver.yaml');
-const EXAMPLE_SECRET_YAML = join(__dirname, '../example.secret.yaml');
+const MCP_SERVER_YAML = join(__dirname, '../mcpserver.yaml')
+const EXAMPLE_SECRET_YAML = join(__dirname, '../example.secret.yaml')
// =============================================================================
// Types
// =============================================================================
interface McpServerSpec {
- contextRef: string;
- description: string;
- image: string;
- imagePullPolicy: string;
+ contextRef: string
+ description: string
+ image: string
+ imagePullPolicy: string
transport: {
- type: string;
- url: string;
- port: number;
- };
+ type: string
+ url: string
+ port: number
+ }
healthCheck?: {
- port: number;
- };
+ port: number
+ }
serverConfig: {
- readOnly: boolean;
- loggers: string;
- telemetry: string;
- };
+ readOnly: boolean
+ loggers: string
+ telemetry: string
+ }
envMapping: {
- transport: string;
- httpHost: string;
- httpPort: string;
- healthCheckHost: string;
- healthCheckPort: string;
- readOnly: string;
- loggers: string;
- telemetry: string;
- };
+ transport: string
+ httpHost: string
+ httpPort: string
+ healthCheckHost: string
+ healthCheckPort: string
+ readOnly: string
+ loggers: string
+ telemetry: string
+ }
envSecret: {
- name: string;
+ name: string
keys: Array<{
- secretKey: string;
- envVar: string;
- }>;
- };
+ secretKey: string
+ envVar: string
+ }>
+ }
resources: {
- requests: { memory: string; cpu: string };
- limits: { memory: string; cpu: string };
- };
+ requests: { memory: string; cpu: string }
+ limits: { memory: string; cpu: string }
+ }
auth: {
- type: string;
- };
- enabled: boolean;
+ type: string
+ }
+ enabled: boolean
}
interface McpServerCrd {
- apiVersion: string;
- kind: string;
+ apiVersion: string
+ kind: string
metadata: {
- name: string;
- namespace: string;
- };
- spec: McpServerSpec;
+ name: string
+ namespace: string
+ }
+ spec: McpServerSpec
}
// =============================================================================
@@ -89,13 +88,13 @@ interface McpServerCrd {
// =============================================================================
function loadMcpServerCrd(): McpServerCrd {
- const content = readFileSync(MCP_SERVER_YAML, 'utf-8');
- return loadYaml(content) as McpServerCrd;
+ const content = readFileSync(MCP_SERVER_YAML, 'utf-8')
+ return loadYaml(content) as McpServerCrd
}
function loadExampleSecret(): any {
- const content = readFileSync(EXAMPLE_SECRET_YAML, 'utf-8');
- return loadYaml(content);
+ const content = readFileSync(EXAMPLE_SECRET_YAML, 'utf-8')
+ return loadYaml(content)
}
// =============================================================================
@@ -103,432 +102,424 @@ function loadExampleSecret(): any {
// =============================================================================
describe('MongoDB MCP Server - CRD Configuration', () => {
- let crd: McpServerCrd;
+ let crd: McpServerCrd
beforeEach(() => {
- crd = loadMcpServerCrd();
- });
+ crd = loadMcpServerCrd()
+ })
describe('Metadata', () => {
it('should have correct API version', () => {
- expect(crd.apiVersion).toBe('clerum.io/v1alpha1');
- });
+ expect(crd.apiVersion).toBe('clerum.io/v1alpha1')
+ })
it('should be McpServer kind', () => {
- expect(crd.kind).toBe('McpServer');
- });
+ expect(crd.kind).toBe('McpServer')
+ })
it('should have correct server name', () => {
- expect(crd.metadata.name).toBe('mongodb-server');
- });
+ expect(crd.metadata.name).toBe('mongodb-server')
+ })
it('should be in mcp-server namespace', () => {
- expect(crd.metadata.namespace).toBe('mcp-server');
- });
- });
+ expect(crd.metadata.namespace).toBe('mcp-server')
+ })
+ })
describe('Context Reference', () => {
it('should reference context1', () => {
- expect(crd.spec.contextRef).toBe('context1');
- });
- });
+ expect(crd.spec.contextRef).toBe('context1')
+ })
+ })
describe('Description', () => {
it('should have a description', () => {
- expect(crd.spec.description).toBeDefined();
- expect(crd.spec.description.length).toBeGreaterThan(0);
- });
+ expect(crd.spec.description).toBeDefined()
+ expect(crd.spec.description.length).toBeGreaterThan(0)
+ })
it('should mention MongoDB in description', () => {
- expect(crd.spec.description.toLowerCase()).toContain('mongodb');
- });
+ expect(crd.spec.description.toLowerCase()).toContain('mongodb')
+ })
it('should describe available capabilities', () => {
- const desc = crd.spec.description.toLowerCase();
- expect(desc).toMatch(/querying|aggregation|schema|indexes|atlas/);
- });
- });
+ const desc = crd.spec.description.toLowerCase()
+ expect(desc).toMatch(/querying|aggregation|schema|indexes|atlas/)
+ })
+ })
describe('Image Configuration', () => {
it('should use official MongoDB image', () => {
- expect(crd.spec.image).toBe('mongodb/mongodb-mcp-server:latest');
- });
+ expect(crd.spec.image).toBe('mongodb/mongodb-mcp-server:latest')
+ })
it('should have Never pull policy for local images', () => {
// Local image build for minikube/E2E — no registry pull needed
- expect(crd.spec.imagePullPolicy).toBe('Never');
- });
+ expect(crd.spec.imagePullPolicy).toBe('Never')
+ })
it('should use Docker Hub official image', () => {
- expect(crd.spec.image).toMatch(/^mongodb\//);
- });
- });
+ expect(crd.spec.image).toMatch(/^mongodb\//)
+ })
+ })
describe('Transport Configuration', () => {
it('should use streamableHttp transport type', () => {
- expect(crd.spec.transport.type).toBe('streamableHttp');
- });
+ expect(crd.spec.transport.type).toBe('streamableHttp')
+ })
it('should have correct service URL', () => {
expect(crd.spec.transport.url).toBe(
'http://mongodb-server.mcp-server.svc.cluster.local:3000/mcp'
- );
- });
+ )
+ })
it('should use port 3000', () => {
- expect(crd.spec.transport.port).toBe(3000);
- });
+ expect(crd.spec.transport.port).toBe(3000)
+ })
it('should follow K8s service naming convention', () => {
- const url = crd.spec.transport.url;
- expect(url).toMatch(/\.svc\.cluster\.local/);
- expect(url).toContain('mongodb-server');
- });
- });
+ const url = crd.spec.transport.url
+ expect(url).toMatch(/\.svc\.cluster\.local/)
+ expect(url).toContain('mongodb-server')
+ })
+ })
describe('Health Check Configuration', () => {
it('should have health check port configured', () => {
- expect(crd.spec.healthCheck).toBeDefined();
- expect(crd.spec.healthCheck?.port).toBe(3001);
- });
+ expect(crd.spec.healthCheck).toBeDefined()
+ expect(crd.spec.healthCheck?.port).toBe(3001)
+ })
it('should use different port from MCP transport', () => {
- expect(crd.spec.healthCheck?.port).not.toBe(crd.spec.transport.port);
- });
+ expect(crd.spec.healthCheck?.port).not.toBe(crd.spec.transport.port)
+ })
it('should use port 3001 for health checks', () => {
- expect(crd.spec.healthCheck?.port).toBe(3001);
- });
- });
+ expect(crd.spec.healthCheck?.port).toBe(3001)
+ })
+ })
describe('Server Configuration', () => {
it('should have readOnly mode disabled for development', () => {
// readOnly is false to allow E2E write operations during testing
- expect(crd.spec.serverConfig.readOnly).toBe(false);
- });
+ expect(crd.spec.serverConfig.readOnly).toBe(false)
+ })
it('should configure stderr logging', () => {
- expect(crd.spec.serverConfig.loggers).toBe('stderr');
- });
+ expect(crd.spec.serverConfig.loggers).toBe('stderr')
+ })
it('should have telemetry disabled', () => {
- expect(crd.spec.serverConfig.telemetry).toBe('disabled');
- });
+ expect(crd.spec.serverConfig.telemetry).toBe('disabled')
+ })
it('should have configurable read-only mode', () => {
// readOnly is configurable — false for dev/E2E, true for production
- expect(typeof crd.spec.serverConfig.readOnly).toBe('boolean');
- });
- });
+ expect(typeof crd.spec.serverConfig.readOnly).toBe('boolean')
+ })
+ })
describe('Environment Variable Mapping', () => {
it('should map transport env var', () => {
- expect(crd.spec.envMapping.transport).toBe('MDB_MCP_TRANSPORT');
- });
+ expect(crd.spec.envMapping.transport).toBe('MDB_MCP_TRANSPORT')
+ })
it('should map HTTP host env var', () => {
- expect(crd.spec.envMapping.httpHost).toBe('MDB_MCP_HTTP_HOST');
- });
+ expect(crd.spec.envMapping.httpHost).toBe('MDB_MCP_HTTP_HOST')
+ })
it('should map HTTP port env var', () => {
- expect(crd.spec.envMapping.httpPort).toBe('MDB_MCP_HTTP_PORT');
- });
+ expect(crd.spec.envMapping.httpPort).toBe('MDB_MCP_HTTP_PORT')
+ })
it('should map health check host env var', () => {
- expect(crd.spec.envMapping.healthCheckHost).toBe(
- 'MDB_MCP_HEALTH_CHECK_HOST'
- );
- });
+ expect(crd.spec.envMapping.healthCheckHost).toBe('MDB_MCP_HEALTH_CHECK_HOST')
+ })
it('should map health check port env var', () => {
- expect(crd.spec.envMapping.healthCheckPort).toBe(
- 'MDB_MCP_HEALTH_CHECK_PORT'
- );
- });
+ expect(crd.spec.envMapping.healthCheckPort).toBe('MDB_MCP_HEALTH_CHECK_PORT')
+ })
it('should map readOnly env var', () => {
- expect(crd.spec.envMapping.readOnly).toBe('MDB_MCP_READ_ONLY');
- });
+ expect(crd.spec.envMapping.readOnly).toBe('MDB_MCP_READ_ONLY')
+ })
it('should map loggers env var', () => {
- expect(crd.spec.envMapping.loggers).toBe('MDB_MCP_LOGGERS');
- });
+ expect(crd.spec.envMapping.loggers).toBe('MDB_MCP_LOGGERS')
+ })
it('should map telemetry env var', () => {
- expect(crd.spec.envMapping.telemetry).toBe('MDB_MCP_TELEMETRY');
- });
+ expect(crd.spec.envMapping.telemetry).toBe('MDB_MCP_TELEMETRY')
+ })
it('should use MDB_MCP_ prefix for all env vars', () => {
- const allKeys = Object.values(crd.spec.envMapping);
+ const allKeys = Object.values(crd.spec.envMapping)
allKeys.forEach(key => {
- expect(key).toMatch(/^MDB_MCP_/);
- });
- });
- });
+ expect(key).toMatch(/^MDB_MCP_/)
+ })
+ })
+ })
describe('Secret Configuration', () => {
it('should reference mcp-mongodb-credentials secret', () => {
- expect(crd.spec.envSecret.name).toBe('mcp-mongodb-credentials');
- });
+ expect(crd.spec.envSecret.name).toBe('mcp-mongodb-credentials')
+ })
it('should map connection-string to MDB_MCP_CONNECTION_STRING env var', () => {
- const keyMapping = crd.spec.envSecret.keys.find(
- k => k.secretKey === 'connection-string'
- );
- expect(keyMapping?.envVar).toBe('MDB_MCP_CONNECTION_STRING');
- });
+ const keyMapping = crd.spec.envSecret.keys.find(k => k.secretKey === 'connection-string')
+ expect(keyMapping?.envVar).toBe('MDB_MCP_CONNECTION_STRING')
+ })
it('should have exactly one secret key mapping', () => {
- expect(crd.spec.envSecret.keys).toHaveLength(1);
- });
+ expect(crd.spec.envSecret.keys).toHaveLength(1)
+ })
it('should use correct secret key name', () => {
- expect(crd.spec.envSecret.keys[0].secretKey).toBe('connection-string');
- });
- });
+ expect(crd.spec.envSecret.keys[0].secretKey).toBe('connection-string')
+ })
+ })
describe('Resource Requirements', () => {
it('should have memory request', () => {
- expect(crd.spec.resources.requests.memory).toBeDefined();
- expect(crd.spec.resources.requests.memory).toMatch(/\d+Mi/);
- });
+ expect(crd.spec.resources.requests.memory).toBeDefined()
+ expect(crd.spec.resources.requests.memory).toMatch(/\d+Mi/)
+ })
it('should have CPU request', () => {
- expect(crd.spec.resources.requests.cpu).toBeDefined();
- expect(crd.spec.resources.requests.cpu).toMatch(/\d+m/);
- });
+ expect(crd.spec.resources.requests.cpu).toBeDefined()
+ expect(crd.spec.resources.requests.cpu).toMatch(/\d+m/)
+ })
it('should have memory limit', () => {
- expect(crd.spec.resources.limits.memory).toBeDefined();
- expect(crd.spec.resources.limits.memory).toMatch(/\d+Mi/);
- });
+ expect(crd.spec.resources.limits.memory).toBeDefined()
+ expect(crd.spec.resources.limits.memory).toMatch(/\d+Mi/)
+ })
it('should have CPU limit', () => {
- expect(crd.spec.resources.limits.cpu).toBeDefined();
- expect(crd.spec.resources.limits.cpu).toMatch(/\d+m/);
- });
+ expect(crd.spec.resources.limits.cpu).toBeDefined()
+ expect(crd.spec.resources.limits.cpu).toMatch(/\d+m/)
+ })
it('should have higher limits than requests', () => {
- const reqMem = parseInt(crd.spec.resources.requests.memory);
- const limMem = parseInt(crd.spec.resources.limits.memory);
- expect(limMem).toBeGreaterThan(reqMem);
+ const reqMem = parseInt(crd.spec.resources.requests.memory)
+ const limMem = parseInt(crd.spec.resources.limits.memory)
+ expect(limMem).toBeGreaterThan(reqMem)
- const reqCpu = parseInt(crd.spec.resources.requests.cpu);
- const limCpu = parseInt(crd.spec.resources.limits.cpu);
- expect(limCpu).toBeGreaterThan(reqCpu);
- });
+ const reqCpu = parseInt(crd.spec.resources.requests.cpu)
+ const limCpu = parseInt(crd.spec.resources.limits.cpu)
+ expect(limCpu).toBeGreaterThan(reqCpu)
+ })
it('should use reasonable resource limits for MCP server', () => {
- expect(parseInt(crd.spec.resources.limits.memory)).toBeLessThanOrEqual(256);
- expect(parseInt(crd.spec.resources.limits.cpu)).toBeLessThanOrEqual(500);
- });
- });
+ expect(parseInt(crd.spec.resources.limits.memory)).toBeLessThanOrEqual(256)
+ expect(parseInt(crd.spec.resources.limits.cpu)).toBeLessThanOrEqual(500)
+ })
+ })
describe('Authentication', () => {
it('should use none auth type', () => {
- expect(crd.spec.auth.type).toBe('none');
- });
+ expect(crd.spec.auth.type).toBe('none')
+ })
it('should rely on connection string for auth', () => {
// MongoDB authentication is via connection string
- expect(crd.spec.envSecret).toBeDefined();
- expect(crd.spec.envSecret.keys[0].secretKey).toBe('connection-string');
- });
- });
+ expect(crd.spec.envSecret).toBeDefined()
+ expect(crd.spec.envSecret.keys[0].secretKey).toBe('connection-string')
+ })
+ })
describe('Server State', () => {
it('should be enabled by default', () => {
- expect(crd.spec.enabled).toBe(true);
- });
- });
-});
+ expect(crd.spec.enabled).toBe(true)
+ })
+ })
+})
describe('MongoDB MCP Server - Example Secret Template', () => {
- let secret: any;
+ let secret: any
beforeEach(() => {
- secret = loadExampleSecret();
- });
+ secret = loadExampleSecret()
+ })
describe('Secret Metadata', () => {
it('should have correct secret name', () => {
- expect(secret.metadata.name).toBe('mcp-mongodb-credentials');
- });
+ expect(secret.metadata.name).toBe('mcp-mongodb-credentials')
+ })
it('should be in mcp-server namespace', () => {
- expect(secret.metadata.namespace).toBe('mcp-server');
- });
+ expect(secret.metadata.namespace).toBe('mcp-server')
+ })
it('should have app label', () => {
- expect(secret.metadata.labels?.app).toBe('mcp-mongodb');
- });
+ expect(secret.metadata.labels?.app).toBe('mcp-mongodb')
+ })
it('should be Opaque type', () => {
- expect(secret.type).toBe('Opaque');
- });
- });
+ expect(secret.type).toBe('Opaque')
+ })
+ })
describe('Secret Data Structure', () => {
it('should have connection-string field', () => {
- expect(secret.data).toHaveProperty('connection-string');
- });
+ expect(secret.data).toHaveProperty('connection-string')
+ })
it('should have placeholder for base64 encoded string', () => {
- expect(secret.data['connection-string']).toContain(
- '<BASE64_ENCODED_CONNECTION_STRING>'
- );
- });
+ expect(secret.data['connection-string']).toContain('<BASE64_ENCODED_CONNECTION_STRING>')
+ })
it('should include encoding instructions in comment', () => {
- const content = readFileSync(EXAMPLE_SECRET_YAML, 'utf-8');
- expect(content).toContain('base64');
- expect(content).toContain('echo -n');
- expect(content).toContain('mongodb');
- });
+ const content = readFileSync(EXAMPLE_SECRET_YAML, 'utf-8')
+ expect(content).toContain('base64')
+ expect(content).toContain('echo -n')
+ expect(content).toContain('mongodb')
+ })
it('should show mongodb+srv:// example format', () => {
- const content = readFileSync(EXAMPLE_SECRET_YAML, 'utf-8');
- expect(content).toContain('mongodb+srv://');
- });
- });
-});
+ const content = readFileSync(EXAMPLE_SECRET_YAML, 'utf-8')
+ expect(content).toContain('mongodb+srv://')
+ })
+ })
+})
describe('MongoDB MCP Server - Configuration Validation', () => {
- let crd: McpServerCrd;
+ let crd: McpServerCrd
beforeEach(() => {
- crd = loadMcpServerCrd();
- });
+ crd = loadMcpServerCrd()
+ })
it('should match Context CRD server reference', () => {
- expect(crd.metadata.name).toBe('mongodb-server');
- });
+ expect(crd.metadata.name).toBe('mongodb-server')
+ })
it('should be compatible with StreamableHTTP transport', () => {
- expect(['streamableHttp', 'sse', 'stdio']).toContain(crd.spec.transport.type);
+ expect(['streamableHttp', 'sse', 'stdio']).toContain(crd.spec.transport.type)
if (crd.spec.transport.type === 'streamableHttp') {
- expect(crd.spec.transport.url).toBeDefined();
- expect(crd.spec.transport.url).toMatch(/^https?:\/\//);
+ expect(crd.spec.transport.url).toBeDefined()
+ expect(crd.spec.transport.url).toMatch(/^https?:\/\//)
}
- });
+ })
it('should have separate health check endpoint', () => {
// MongoDB MCP has separate health check port
- expect(crd.spec.healthCheck).toBeDefined();
- expect(crd.spec.healthCheck?.port).not.toBe(crd.spec.transport.port);
- });
+ expect(crd.spec.healthCheck).toBeDefined()
+ expect(crd.spec.healthCheck?.port).not.toBe(crd.spec.transport.port)
+ })
it('should have readOnly mode configurable via env mapping', () => {
// readOnly is false for dev/E2E; env mapping allows runtime override
- expect(typeof crd.spec.serverConfig.readOnly).toBe('boolean');
- expect(crd.spec.envMapping.readOnly).toBe('MDB_MCP_READ_ONLY');
- });
+ expect(typeof crd.spec.serverConfig.readOnly).toBe('boolean')
+ expect(crd.spec.envMapping.readOnly).toBe('MDB_MCP_READ_ONLY')
+ })
it('should have all required fields for context-mapper reconciliation', () => {
- expect(crd.spec.image).toBeDefined();
- expect(crd.spec.transport).toBeDefined();
- expect(crd.spec.envMapping).toBeDefined();
- expect(crd.spec.envSecret).toBeDefined();
- expect(crd.spec.resources).toBeDefined();
- });
+ expect(crd.spec.image).toBeDefined()
+ expect(crd.spec.transport).toBeDefined()
+ expect(crd.spec.envMapping).toBeDefined()
+ expect(crd.spec.envSecret).toBeDefined()
+ expect(crd.spec.resources).toBeDefined()
+ })
it('should use MongoDB-specific env var prefix', () => {
- const allValues = Object.values(crd.spec.envMapping);
+ const allValues = Object.values(crd.spec.envMapping)
allValues.forEach(value => {
- expect(value).toMatch(/^MDB_MCP_/);
- });
- });
+ expect(value).toMatch(/^MDB_MCP_/)
+ })
+ })
it('should support connection string authentication', () => {
// MongoDB uses connection string for auth (username/password)
- expect(crd.spec.envSecret.keys[0].secretKey).toBe('connection-string');
- expect(crd.spec.envSecret.keys[0].envVar).toBe('MDB_MCP_CONNECTION_STRING');
- });
-});
+ expect(crd.spec.envSecret.keys[0].secretKey).toBe('connection-string')
+ expect(crd.spec.envSecret.keys[0].envVar).toBe('MDB_MCP_CONNECTION_STRING')
+ })
+})
describe('MongoDB MCP Server - Security Configuration', () => {
- let crd: McpServerCrd;
+ let crd: McpServerCrd
beforeEach(() => {
- crd = loadMcpServerCrd();
- });
+ crd = loadMcpServerCrd()
+ })
it('should have readOnly mode mapped for runtime control', () => {
// readOnly is configurable via MDB_MCP_READ_ONLY env var
// Default is false for dev/E2E; set to true in production deployments
- expect(crd.spec.envMapping.readOnly).toBe('MDB_MCP_READ_ONLY');
- });
+ expect(crd.spec.envMapping.readOnly).toBe('MDB_MCP_READ_ONLY')
+ })
it('should have telemetry disabled', () => {
// Reduces attack surface, no data exfiltration via telemetry
- expect(crd.spec.serverConfig.telemetry).toBe('disabled');
- });
+ expect(crd.spec.serverConfig.telemetry).toBe('disabled')
+ })
it('should have minimal resource footprint', () => {
// Limit blast radius if compromised
- expect(parseInt(crd.spec.resources.limits.memory)).toBeLessThanOrEqual(256);
- expect(parseInt(crd.spec.resources.limits.cpu)).toBeLessThanOrEqual(500);
- });
+ expect(parseInt(crd.spec.resources.limits.memory)).toBeLessThanOrEqual(256)
+ expect(parseInt(crd.spec.resources.limits.cpu)).toBeLessThanOrEqual(500)
+ })
it('should use connection string for auth (least privilege)', () => {
// Connection string should have minimal required permissions
- expect(crd.spec.envSecret.keys).toHaveLength(1);
- expect(crd.spec.envSecret.keys[0].secretKey).toBe('connection-string');
- });
+ expect(crd.spec.envSecret.keys).toHaveLength(1)
+ expect(crd.spec.envSecret.keys[0].secretKey).toBe('connection-string')
+ })
it('should not have additional credentials', () => {
// Only connection string needed (no separate username/password)
- expect(crd.spec.envSecret.keys).toHaveLength(1);
- });
-});
+ expect(crd.spec.envSecret.keys).toHaveLength(1)
+ })
+})
describe('MongoDB vs Airtable - Configuration Comparison', () => {
- let mongoCrd: McpServerCrd;
- let airtableCrd: McpServerCrd;
+ let mongoCrd: McpServerCrd
+ let airtableCrd: McpServerCrd
beforeEach(() => {
- mongoCrd = loadMcpServerCrd();
+ mongoCrd = loadMcpServerCrd()
// Load Airtable CRD for comparison
- const airtablePath = join(__dirname, '../../airtable/mcpserver.yaml');
- const airtableContent = readFileSync(airtablePath, 'utf-8');
- airtableCrd = loadYaml(airtableContent) as McpServerCrd;
- });
+ const airtablePath = join(__dirname, '../../airtable/mcpserver.yaml')
+ const airtableContent = readFileSync(airtablePath, 'utf-8')
+ airtableCrd = loadYaml(airtableContent) as McpServerCrd
+ })
it('should use different env var prefixes', () => {
// MongoDB: MDB_MCP_*
- const mongoEnvVars = Object.values(mongoCrd.spec.envMapping);
+ const mongoEnvVars = Object.values(mongoCrd.spec.envMapping)
mongoEnvVars.forEach(v => {
- expect(v).toMatch(/^MDB_MCP_/);
- });
+ expect(v).toMatch(/^MDB_MCP_/)
+ })
// Airtable: MCP_TRANSPORT, PORT (no prefix for these)
- const airtableTransport = airtableCrd.spec.envMapping.transport;
- expect(airtableTransport).not.toMatch(/^MDB_MCP_/);
- });
+ const airtableTransport = airtableCrd.spec.envMapping.transport
+ expect(airtableTransport).not.toMatch(/^MDB_MCP_/)
+ })
it('should have health check (Airtable does not)', () => {
- expect(mongoCrd.spec.healthCheck).toBeDefined();
+ expect(mongoCrd.spec.healthCheck).toBeDefined()
// Airtable CRD doesn't have healthCheck field
- });
+ })
it('should have serverConfig (Airtable does not)', () => {
- expect(mongoCrd.spec.serverConfig).toBeDefined();
- expect(mongoCrd.spec.serverConfig).toHaveProperty('readOnly');
- expect(mongoCrd.spec.serverConfig).toHaveProperty('loggers');
- expect(mongoCrd.spec.serverConfig).toHaveProperty('telemetry');
- });
+ expect(mongoCrd.spec.serverConfig).toBeDefined()
+ expect(mongoCrd.spec.serverConfig).toHaveProperty('readOnly')
+ expect(mongoCrd.spec.serverConfig).toHaveProperty('loggers')
+ expect(mongoCrd.spec.serverConfig).toHaveProperty('telemetry')
+ })
it('both should use same transport type', () => {
- expect(mongoCrd.spec.transport.type).toBe(airtableCrd.spec.transport.type);
- });
+ expect(mongoCrd.spec.transport.type).toBe(airtableCrd.spec.transport.type)
+ })
it('both should have similar resource requirements', () => {
- const mongoMem = parseInt(mongoCrd.spec.resources.limits.memory);
- const airtableMem = parseInt(airtableCrd.spec.resources.limits.memory);
+ const mongoMem = parseInt(mongoCrd.spec.resources.limits.memory)
+ const airtableMem = parseInt(airtableCrd.spec.resources.limits.memory)
// Both should be within similar range
- expect(Math.abs(mongoMem - airtableMem)).toBeLessThanOrEqual(128);
- });
-});
+ expect(Math.abs(mongoMem - airtableMem)).toBeLessThanOrEqual(128)
+ })
+})
diff --git a/mcp-servers/mongodb/__tests__/mongodb.connection.test.ts b/mcp-servers/mongodb/__tests__/mongodb.connection.test.ts
index d02bc66e5..fcbf48f47 100644
--- a/mcp-servers/mongodb/__tests__/mongodb.connection.test.ts
+++ b/mcp-servers/mongodb/__tests__/mongodb.connection.test.ts
@@ -12,37 +12,36 @@
* - Connection pooling simulation
* - Error handling
*/
-
-import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
// =============================================================================
// Types
// =============================================================================
interface MongoDocument {
- _id: string;
- [key: string]: any;
+ _id: string
+ [key: string]: any
}
interface MongoQuery {
- filter?: Record<string, any>;
- projection?: Record<string, number | boolean | object>;
- sort?: Record<string, number>;
- limit?: number;
- skip?: number;
+ filter?: Record<string, any>
+ projection?: Record<string, number | boolean | object>
+ sort?: Record<string, number>
+ limit?: number
+ skip?: number
}
interface MongoAggregatePipeline {
- $match?: Record<string, any>;
- $group?: Record<string, any>;
- $project?: Record<string, any>;
- $sort?: Record<string, number>;
- $limit?: number;
+ $match?: Record<string, any>
+ $group?: Record<string, any>
+ $project?: Record<string, any>
+ $sort?: Record<string, number>
+ $limit?: number
}
interface MongoError {
- code: number;
- message: string;
+ code: number
+ message: string
}
// =============================================================================
@@ -50,164 +49,160 @@ interface MongoError {
// =============================================================================
class MockMongoClient {
- private isConnected: boolean = false;
- private collections: Map<string, MongoDocument[]> = new Map();
- private mockErrors: Map<string, MongoError> = new Map();
- private queryLog: Array<{ operation: string; collection: string; query: any }> =
- [];
+ private isConnected: boolean = false
+ private collections: Map<string, MongoDocument[]> = new Map()
+ private mockErrors: Map<string, MongoError> = new Map()
+ private queryLog: Array<{ operation: string; collection: string; query: any }> = []
/**
* Simulate connecting to MongoDB
*/
async connect(connectionString: string): Promise<void> {
// Simulate connection delay
- await new Promise(resolve => setTimeout(resolve, 10));
+ await new Promise(resolve => setTimeout(resolve, 10))
if (!connectionString || !connectionString.startsWith('mongodb')) {
- throw new Error('Invalid connection string format');
+ throw new Error('Invalid connection string format')
}
- this.isConnected = true;
+ this.isConnected = true
}
/**
* Simulate disconnecting from MongoDB
*/
async disconnect(): Promise<void> {
- this.isConnected = false;
+ this.isConnected = false
}
/**
* Check if connected
*/
connected(): boolean {
- return this.isConnected;
+ return this.isConnected
}
/**
* Set mock data for a collection
*/
setCollectionData(collectionName: string, documents: MongoDocument[]): void {
- this.collections.set(collectionName, documents);
+ this.collections.set(collectionName, documents)
}
/**
* Set mock error for an operation
*/
setMockError(collectionName: string, error: MongoError): void {
- this.mockErrors.set(collectionName, error);
+ this.mockErrors.set(collectionName, error)
}
/**
* Clear all mocks and logs
*/
clearMocks(): void {
- this.collections.clear();
- this.mockErrors.clear();
- this.queryLog = [];
+ this.collections.clear()
+ this.mockErrors.clear()
+ this.queryLog = []
}
/**
* Get query log
*/
getQueryLog(): Array<{ operation: string; collection: string; query: any }> {
- return [...this.queryLog];
+ return [...this.queryLog]
}
/**
* Mock find operation
*/
async find(collectionName: string, query: MongoQuery): Promise<MongoDocument[]> {
- this.checkConnected();
- this.logQuery('find', collectionName, query);
+ this.checkConnected()
+ this.logQuery('find', collectionName, query)
- this.checkError(collectionName);
+ this.checkError(collectionName)
- let documents = this.collections.get(collectionName) || [];
+ let documents = this.collections.get(collectionName) || []
// Apply filter
if (query.filter) {
- documents = this.applyFilter(documents, query.filter);
+ documents = this.applyFilter(documents, query.filter)
}
// Apply sort
if (query.sort) {
- documents = this.applySort(documents, query.sort);
+ documents = this.applySort(documents, query.sort)
}
// Apply skip
if (query.skip) {
- documents = documents.slice(query.skip);
+ documents = documents.slice(query.skip)
}
// Apply limit
if (query.limit) {
- documents = documents.slice(0, query.limit);
+ documents = documents.slice(0, query.limit)
}
// Apply projection
if (query.projection) {
- documents = this.applyProjection(documents, query.projection);
+ documents = this.applyProjection(documents, query.projection)
}
- return documents;
+ return documents
}
/**
* Mock aggregate operation
*/
- async aggregate(
- collectionName: string,
- pipeline: MongoAggregatePipeline[]
- ): Promise<any[]> {
- this.checkConnected();
- this.logQuery('aggregate', collectionName, pipeline);
+ async aggregate(collectionName: string, pipeline: MongoAggregatePipeline[]): Promise<any[]> {
+ this.checkConnected()
+ this.logQuery('aggregate', collectionName, pipeline)
- this.checkError(collectionName);
+ this.checkError(collectionName)
- let documents = this.collections.get(collectionName) || [];
+ let documents = this.collections.get(collectionName) || []
// Apply pipeline stages
for (const stage of pipeline) {
if (stage.$match) {
- documents = this.applyFilter(documents, stage.$match);
+ documents = this.applyFilter(documents, stage.$match)
}
if (stage.$group) {
- documents = this.applyGroup(documents, stage.$group);
+ documents = this.applyGroup(documents, stage.$group)
}
if (stage.$project) {
- documents = this.applyProjection(documents, stage.$project);
+ documents = this.applyProjection(documents, stage.$project)
}
if (stage.$sort) {
- documents = this.applySort(documents, stage.$sort);
+ documents = this.applySort(documents, stage.$sort)
}
if (stage.$limit) {
- documents = documents.slice(0, stage.$limit);
+ documents = documents.slice(0, stage.$limit)
}
}
- return documents;
+ return documents
}
/**
* Mock insert operation
*/
async insertOne(collectionName: string, document: any): Promise<{ insertedId: string }> {
- this.checkConnected();
- this.logQuery('insertOne', collectionName, document);
+ this.checkConnected()
+ this.logQuery('insertOne', collectionName, document)
- this.checkError(collectionName);
+ this.checkError(collectionName)
const newDocument: MongoDocument = {
_id: this.generateId(),
...document,
- };
+ }
- const collection = this.collections.get(collectionName) || [];
- collection.push(newDocument);
- this.collections.set(collectionName, collection);
+ const collection = this.collections.get(collectionName) || []
+ collection.push(newDocument)
+ this.collections.set(collectionName, collection)
- return { insertedId: newDocument._id };
+ return { insertedId: newDocument._id }
}
/**
@@ -218,24 +213,24 @@ class MockMongoClient {
filter: Record<string, any>,
update: Record<string, any>
): Promise<{ matchedCount: number; modifiedCount: number }> {
- this.checkConnected();
- this.logQuery('updateOne', collectionName, { filter, update });
+ this.checkConnected()
+ this.logQuery('updateOne', collectionName, { filter, update })
- this.checkError(collectionName);
+ this.checkError(collectionName)
- const collection = this.collections.get(collectionName) || [];
- const index = collection.findIndex(doc => this.matchesFilter(doc, filter));
+ const collection = this.collections.get(collectionName) || []
+ const index = collection.findIndex(doc => this.matchesFilter(doc, filter))
if (index === -1) {
- return { matchedCount: 0, modifiedCount: 0 };
+ return { matchedCount: 0, modifiedCount: 0 }
}
// Apply $set operations
if (update.$set) {
- collection[index] = { ...collection[index], ...update.$set };
+ collection[index] = { ...collection[index], ...update.$set }
}
- return { matchedCount: 1, modifiedCount: 1 };
+ return { matchedCount: 1, modifiedCount: 1 }
}
/**
@@ -245,40 +240,40 @@ class MockMongoClient {
collectionName: string,
filter: Record<string, any>
): Promise<{ deletedCount: number }> {
- this.checkConnected();
- this.logQuery('deleteOne', collectionName, filter);
+ this.checkConnected()
+ this.logQuery('deleteOne', collectionName, filter)
- this.checkError(collectionName);
+ this.checkError(collectionName)
- const collection = this.collections.get(collectionName) || [];
- const index = collection.findIndex(doc => this.matchesFilter(doc, filter));
+ const collection = this.collections.get(collectionName) || []
+ const index = collection.findIndex(doc => this.matchesFilter(doc, filter))
if (index === -1) {
- return { deletedCount: 0 };
+ return { deletedCount: 0 }
}
- collection.splice(index, 1);
- this.collections.set(collectionName, collection);
+ collection.splice(index, 1)
+ this.collections.set(collectionName, collection)
- return { deletedCount: 1 };
+ return { deletedCount: 1 }
}
/**
* Mock count operation
*/
async count(collectionName: string, filter?: Record<string, any>): Promise<number> {
- this.checkConnected();
- this.logQuery('count', collectionName, { filter });
+ this.checkConnected()
+ this.logQuery('count', collectionName, { filter })
- this.checkError(collectionName);
+ this.checkError(collectionName)
- let documents = this.collections.get(collectionName) || [];
+ let documents = this.collections.get(collectionName) || []
if (filter) {
- documents = this.applyFilter(documents, filter);
+ documents = this.applyFilter(documents, filter)
}
- return documents.length;
+ return documents.length
}
// =============================================================================
@@ -287,78 +282,78 @@ class MockMongoClient {
private checkConnected(): void {
if (!this.isConnected) {
- throw new Error('MongoNotConnectedError: Client is not connected');
+ throw new Error('MongoNotConnectedError: Client is not connected')
}
}
private checkError(collectionName: string): void {
- const error = this.mockErrors.get(collectionName);
+ const error = this.mockErrors.get(collectionName)
if (error) {
- throw new Error(`MongoError: ${error.code} - ${error.message}`);
+ throw new Error(`MongoError: ${error.code} - ${error.message}`)
}
}
private logQuery(operation: string, collection: string, query: any): void {
- this.queryLog.push({ operation, collection, query });
+ this.queryLog.push({ operation, collection, query })
}
private applyFilter(documents: MongoDocument[], filter: Record<string, any>): MongoDocument[] {
- return documents.filter(doc => this.matchesFilter(doc, filter));
+ return documents.filter(doc => this.matchesFilter(doc, filter))
}
private matchesFilter(doc: MongoDocument, filter: Record<string, any>): boolean {
for (const [key, value] of Object.entries(filter)) {
- const docValue = doc[key];
+ const docValue = doc[key]
if (value === null) {
- if (docValue !== null) return false;
+ if (docValue !== null) return false
} else if (typeof value === 'object' && value !== null) {
// MongoDB query operators
if (value.$regex) {
// Regex match
- const regex = new RegExp(value.$regex, value.$options || '');
- if (!regex.test(docValue)) return false;
+ const regex = new RegExp(value.$regex, value.$options || '')
+ if (!regex.test(docValue)) return false
} else if (value.$in) {
// $in operator
- if (!value.$in.includes(docValue)) return false;
+ if (!value.$in.includes(docValue)) return false
} else if (value.$gte !== undefined) {
// $gte (greater than or equal)
- if (!(docValue >= value.$gte)) return false;
+ if (!(docValue >= value.$gte)) return false
} else if (value.$gt !== undefined) {
// $gt (greater than)
- if (!(docValue > value.$gt)) return false;
+ if (!(docValue > value.$gt)) return false
} else if (value.$lte !== undefined) {
// $lte (less than or equal)
- if (!(docValue <= value.$lte)) return false;
+ if (!(docValue <= value.$lte)) return false
} else if (value.$lt !== undefined) {
// $lt (less than)
- if (!(docValue < value.$lt)) return false;
+ if (!(docValue < value.$lt)) return false
} else if (value.$ne !== undefined) {
// $ne (not equal)
- if (docValue === value.$ne) return false;
+ if (docValue === value.$ne) return false
} else {
// Nested object
- return false;
+ return false
}
} else if (value !== docValue) {
- return false;
+ return false
}
}
- return true;
+ return true
}
private applySort(documents: MongoDocument[], sort: Record<string, number>): MongoDocument[] {
return [...documents].sort((a, b) => {
for (const [key, direction] of Object.entries(sort)) {
- const aVal = a[key];
- const bVal = b[key];
+ const aVal = a[key]
+ const bVal = b[key]
// direction: 1 = ascending, -1 = descending
- if (aVal < bVal) return direction === 1 ? -1 : 1;
- if (aVal > bVal) return direction === 1 ? 1 : -1;
+ if (aVal < bVal) return direction === 1 ? -1 : 1
+ if (aVal > bVal) return direction === 1 ? 1 : -1
}
- return 0;
- });
+ return 0
+ })
}
private applyProjection(
@@ -366,68 +361,73 @@ class MockMongoClient {
projection: Record<string, number | boolean | object>
): MongoDocument[] {
return documents.map(doc => {
- const projected: any = { _id: doc._id };
+ const projected: any = { _id: doc._id }
for (const [key, value] of Object.entries(projection)) {
if (value === 1 || value === true) {
- projected[key] = doc[key];
+ projected[key] = doc[key]
} else if (value === 0 || value === false) {
// Exclude field (already not in projected object)
}
}
- return projected;
- });
+ return projected
+ })
}
private applyGroup(documents: MongoDocument[], group: Record<string, any>): any[] {
// Simplified $group implementation
- const groups: Map<string, any> = new Map();
+ const groups: Map<string, any> = new Map()
for (const doc of documents) {
// Calculate group key based on _id field
- let groupKey: string;
+ let groupKey: string
if (typeof group._id === 'string' && group._id.startsWith('$')) {
// _id is a field reference like '$city'
- const fieldName = group._id.substring(1);
- groupKey = String(doc[fieldName] || 'null');
+ const fieldName = group._id.substring(1)
+ groupKey = String(doc[fieldName] || 'null')
} else {
// _id is a literal value or expression
- groupKey = JSON.stringify(group._id);
+ groupKey = JSON.stringify(group._id)
}
if (!groups.has(groupKey)) {
groups.set(groupKey, {
- _id: groupKey === 'null' ? group._id : (group._id.startsWith?.('$') ? doc[group._id.substring(1)] : groupKey),
- });
+ _id:
+ groupKey === 'null'
+ ? group._id
+ : group._id.startsWith?.('$')
+ ? doc[group._id.substring(1)]
+ : groupKey,
+ })
}
- const groupDoc = groups.get(groupKey)!;
+ const groupDoc = groups.get(groupKey)!
// Handle $sum, $avg, etc.
for (const [key, value] of Object.entries(group)) {
- if (key === '_id') continue;
+ if (key === '_id') continue
if (typeof value === 'object' && value.$sum !== undefined) {
- if (!groupDoc[key]) groupDoc[key] = 0;
+ if (!groupDoc[key]) groupDoc[key] = 0
if (typeof value.$sum === 'number') {
// $sum: 1 means count documents
- groupDoc[key] += value.$sum;
+ groupDoc[key] += value.$sum
} else if (typeof value.$sum === 'string' && value.$sum.startsWith('$')) {
// $sum: '$fieldName' means sum the field values
- const fieldName = value.$sum.substring(1);
- groupDoc[key] += doc[fieldName] || 0;
+ const fieldName = value.$sum.substring(1)
+ groupDoc[key] += doc[fieldName] || 0
}
}
}
}
- return Array.from(groups.values());
+ return Array.from(groups.values())
}
private generateId(): string {
- return `ObjectId(${Date.now().toString(16)}${Math.random().toString(16).slice(2, 18)})`;
+ return `ObjectId(${Date.now().toString(16)}${Math.random().toString(16).slice(2, 18)})`
}
}
@@ -436,219 +436,213 @@ class MockMongoClient {
// =============================================================================
describe('MongoDB Connection Mock', () => {
- let client: MockMongoClient;
+ let client: MockMongoClient
beforeEach(() => {
- client = new MockMongoClient();
- });
+ client = new MockMongoClient()
+ })
afterEach(() => {
- client.clearMocks();
- });
+ client.clearMocks()
+ })
describe('Connection Management', () => {
it('should connect successfully with valid connection string', async () => {
- await client.connect('mongodb://localhost:27017/test');
+ await client.connect('mongodb://localhost:27017/test')
- expect(client.connected()).toBe(true);
- });
+ expect(client.connected()).toBe(true)
+ })
it('should connect with mongodb+srv:// connection string', async () => {
- await client.connect(
- 'mongodb+srv://user:[email protected]/test'
- );
+ await client.connect('mongodb+srv://user:[email protected]/test')
- expect(client.connected()).toBe(true);
- });
+ expect(client.connected()).toBe(true)
+ })
it('should reject invalid connection string', async () => {
- await expect(
- client.connect('invalid://connection-string')
- ).rejects.toThrow('Invalid connection string format');
- });
+ await expect(client.connect('invalid://connection-string')).rejects.toThrow(
+ 'Invalid connection string format'
+ )
+ })
it('should reject empty connection string', async () => {
- await expect(client.connect('')).rejects.toThrow(
- 'Invalid connection string format'
- );
- });
+ await expect(client.connect('')).rejects.toThrow('Invalid connection string format')
+ })
it('should disconnect successfully', async () => {
- await client.connect('mongodb://localhost:27017/test');
- await client.disconnect();
+ await client.connect('mongodb://localhost:27017/test')
+ await client.disconnect()
- expect(client.connected()).toBe(false);
- });
+ expect(client.connected()).toBe(false)
+ })
it('should not allow operations when disconnected', async () => {
- await expect(
- client.find('test', {})
- ).rejects.toThrow('MongoNotConnectedError');
- });
- });
+ await expect(client.find('test', {})).rejects.toThrow('MongoNotConnectedError')
+ })
+ })
describe('Collection Data Management', () => {
beforeEach(async () => {
- await client.connect('mongodb://localhost:27017/test');
- });
+ await client.connect('mongodb://localhost:27017/test')
+ })
it('should set collection data', async () => {
const documents = [
{ _id: '1', name: 'Alice', age: 30 },
{ _id: '2', name: 'Bob', age: 25 },
- ];
+ ]
- client.setCollectionData('users', documents);
+ client.setCollectionData('users', documents)
- const result = await client.find('users', {});
- expect(result).toHaveLength(2);
- });
+ const result = await client.find('users', {})
+ expect(result).toHaveLength(2)
+ })
it('should clear all mocks', async () => {
- client.setCollectionData('users', [{ _id: '1', name: 'Alice' }]);
- client.setMockError('users', { code: 1, message: 'Test error' });
+ client.setCollectionData('users', [{ _id: '1', name: 'Alice' }])
+ client.setMockError('users', { code: 1, message: 'Test error' })
- client.clearMocks();
+ client.clearMocks()
- const result = await client.find('users', {});
- expect(result).toHaveLength(0);
- });
- });
+ const result = await client.find('users', {})
+ expect(result).toHaveLength(0)
+ })
+ })
describe('Query Logging', () => {
beforeEach(async () => {
- await client.connect('mongodb://localhost:27017/test');
+ await client.connect('mongodb://localhost:27017/test')
client.setCollectionData('users', [
{ _id: '1', name: 'Alice' },
{ _id: '2', name: 'Bob' },
- ]);
- });
+ ])
+ })
it('should log find queries', async () => {
- await client.find('users', { filter: { name: 'Alice' } });
+ await client.find('users', { filter: { name: 'Alice' } })
- const log = client.getQueryLog();
- expect(log).toHaveLength(1);
- expect(log[0].operation).toBe('find');
- expect(log[0].collection).toBe('users');
- });
+ const log = client.getQueryLog()
+ expect(log).toHaveLength(1)
+ expect(log[0].operation).toBe('find')
+ expect(log[0].collection).toBe('users')
+ })
it('should log multiple queries', async () => {
- await client.find('users', { filter: { name: 'Alice' } });
- await client.count('users');
- await client.insertOne('users', { name: 'Charlie' });
+ await client.find('users', { filter: { name: 'Alice' } })
+ await client.count('users')
+ await client.insertOne('users', { name: 'Charlie' })
- const log = client.getQueryLog();
- expect(log).toHaveLength(3);
- });
+ const log = client.getQueryLog()
+ expect(log).toHaveLength(3)
+ })
it('should clear log on clearMocks', async () => {
- await client.find('users', {});
- client.clearMocks();
+ await client.find('users', {})
+ client.clearMocks()
- const log = client.getQueryLog();
- expect(log).toHaveLength(0);
- });
- });
-});
+ const log = client.getQueryLog()
+ expect(log).toHaveLength(0)
+ })
+ })
+})
describe('MongoDB Query Operations', () => {
- let client: MockMongoClient;
+ let client: MockMongoClient
beforeEach(async () => {
- client = new MockMongoClient();
- await client.connect('mongodb://localhost:27017/test');
+ client = new MockMongoClient()
+ await client.connect('mongodb://localhost:27017/test')
const documents = [
{ _id: '1', name: 'Alice', age: 30, city: 'NYC', status: 'active' },
{ _id: '2', name: 'Bob', age: 25, city: 'LA', status: 'active' },
{ _id: '3', name: 'Charlie', age: 35, city: 'NYC', status: 'inactive' },
{ _id: '4', name: 'David', age: 28, city: 'SF', status: 'active' },
- ];
+ ]
- client.setCollectionData('users', documents);
- });
+ client.setCollectionData('users', documents)
+ })
describe('Find Operations', () => {
it('should find all documents', async () => {
- const result = await client.find('users', {});
+ const result = await client.find('users', {})
- expect(result).toHaveLength(4);
- });
+ expect(result).toHaveLength(4)
+ })
it('should filter documents', async () => {
const result = await client.find('users', {
filter: { city: 'NYC' },
- });
+ })
- expect(result).toHaveLength(2);
- expect(result.every(doc => doc.city === 'NYC')).toBe(true);
- });
+ expect(result).toHaveLength(2)
+ expect(result.every(doc => doc.city === 'NYC')).toBe(true)
+ })
it('should sort documents', async () => {
const result = await client.find('users', {
sort: { age: 1 },
- });
+ })
- expect(result[0].age).toBe(25); // Bob
- expect(result[3].age).toBe(35); // Charlie
- });
+ expect(result[0].age).toBe(25) // Bob
+ expect(result[3].age).toBe(35) // Charlie
+ })
it('should limit results', async () => {
const result = await client.find('users', {
limit: 2,
- });
+ })
- expect(result).toHaveLength(2);
- });
+ expect(result).toHaveLength(2)
+ })
it('should skip results', async () => {
const result = await client.find('users', {
skip: 2,
limit: 2,
- });
+ })
- expect(result).toHaveLength(2);
- expect(result[0].name).toBe('Charlie');
- });
+ expect(result).toHaveLength(2)
+ expect(result[0].name).toBe('Charlie')
+ })
it('should project fields', async () => {
const result = await client.find('users', {
projection: { name: 1, age: 1 },
- });
+ })
- expect(result[0]).toHaveProperty('_id');
- expect(result[0]).toHaveProperty('name');
- expect(result[0]).toHaveProperty('age');
- expect(result[0]).not.toHaveProperty('city');
- });
+ expect(result[0]).toHaveProperty('_id')
+ expect(result[0]).toHaveProperty('name')
+ expect(result[0]).toHaveProperty('age')
+ expect(result[0]).not.toHaveProperty('city')
+ })
it('should support regex filter', async () => {
const result = await client.find('users', {
filter: { name: { $regex: /^A/i } },
- });
+ })
- expect(result).toHaveLength(1);
- expect(result[0].name).toBe('Alice');
- });
+ expect(result).toHaveLength(1)
+ expect(result[0].name).toBe('Alice')
+ })
it('should support $in operator', async () => {
const result = await client.find('users', {
filter: { city: { $in: ['NYC', 'LA'] } },
- });
+ })
- expect(result).toHaveLength(3);
- });
- });
+ expect(result).toHaveLength(3)
+ })
+ })
describe('Aggregate Operations', () => {
it('should support $match stage', async () => {
- const pipeline = [{ $match: { status: 'active' } }];
+ const pipeline = [{ $match: { status: 'active' } }]
- const result = await client.aggregate('users', pipeline);
+ const result = await client.aggregate('users', pipeline)
- expect(result).toHaveLength(3);
- });
+ expect(result).toHaveLength(3)
+ })
it('should support $group stage', async () => {
const pipeline = [
@@ -658,175 +652,163 @@ describe('MongoDB Query Operations', () => {
count: { $sum: 1 },
},
},
- ];
+ ]
- const result = await client.aggregate('users', pipeline);
+ const result = await client.aggregate('users', pipeline)
- expect(result.length).toBeGreaterThan(0);
- expect(result[0]).toHaveProperty('_id');
- expect(result[0]).toHaveProperty('count');
- });
+ expect(result.length).toBeGreaterThan(0)
+ expect(result[0]).toHaveProperty('_id')
+ expect(result[0]).toHaveProperty('count')
+ })
it('should support $sort stage', async () => {
- const pipeline = [{ $sort: { age: -1 } }];
+ const pipeline = [{ $sort: { age: -1 } }]
- const result = await client.aggregate('users', pipeline);
+ const result = await client.aggregate('users', pipeline)
- expect(result[0].age).toBe(35);
- });
+ expect(result[0].age).toBe(35)
+ })
it('should support $limit stage', async () => {
- const pipeline = [{ $limit: 2 }];
+ const pipeline = [{ $limit: 2 }]
- const result = await client.aggregate('users', pipeline);
+ const result = await client.aggregate('users', pipeline)
- expect(result).toHaveLength(2);
- });
+ expect(result).toHaveLength(2)
+ })
it('should support multi-stage pipeline', async () => {
- const pipeline = [
- { $match: { status: 'active' } },
- { $sort: { age: 1 } },
- { $limit: 2 },
- ];
+ const pipeline = [{ $match: { status: 'active' } }, { $sort: { age: 1 } }, { $limit: 2 }]
- const result = await client.aggregate('users', pipeline);
+ const result = await client.aggregate('users', pipeline)
- expect(result).toHaveLength(2);
- expect(result[0].age).toBe(25); // Bob (youngest active)
- });
- });
+ expect(result).toHaveLength(2)
+ expect(result[0].age).toBe(25) // Bob (youngest active)
+ })
+ })
describe('Count Operations', () => {
it('should count all documents', async () => {
- const count = await client.count('users');
+ const count = await client.count('users')
- expect(count).toBe(4);
- });
+ expect(count).toBe(4)
+ })
it('should count with filter', async () => {
- const count = await client.count('users', { city: 'NYC' });
+ const count = await client.count('users', { city: 'NYC' })
- expect(count).toBe(2);
- });
- });
-});
+ expect(count).toBe(2)
+ })
+ })
+})
describe('MongoDB Write Operations', () => {
- let client: MockMongoClient;
+ let client: MockMongoClient
beforeEach(async () => {
- client = new MockMongoClient();
- await client.connect('mongodb://localhost:27017/test');
- });
+ client = new MockMongoClient()
+ await client.connect('mongodb://localhost:27017/test')
+ })
describe('Insert Operations', () => {
it('should insert a document', async () => {
const result = await client.insertOne('users', {
name: 'Eve',
age: 27,
- });
+ })
- expect(result.insertedId).toBeDefined();
- expect(result.insertedId).toMatch(/^ObjectId\(/);
- });
+ expect(result.insertedId).toBeDefined()
+ expect(result.insertedId).toMatch(/^ObjectId\(/)
+ })
it('should add document to collection', async () => {
- await client.insertOne('users', { name: 'Frank' });
+ await client.insertOne('users', { name: 'Frank' })
- const documents = await client.find('users', {});
- expect(documents).toHaveLength(1);
- });
- });
+ const documents = await client.find('users', {})
+ expect(documents).toHaveLength(1)
+ })
+ })
describe('Update Operations', () => {
beforeEach(async () => {
- await client.insertOne('users', { name: 'Grace', age: 30, city: 'NYC' });
- });
+ await client.insertOne('users', { name: 'Grace', age: 30, city: 'NYC' })
+ })
it('should update a document', async () => {
- const result = await client.updateOne(
- 'users',
- { name: 'Grace' },
- { $set: { age: 31 } }
- );
+ const result = await client.updateOne('users', { name: 'Grace' }, { $set: { age: 31 } })
- expect(result.matchedCount).toBe(1);
- expect(result.modifiedCount).toBe(1);
- });
+ expect(result.matchedCount).toBe(1)
+ expect(result.modifiedCount).toBe(1)
+ })
it('should reflect changes in find', async () => {
- await client.updateOne('users', { name: 'Grace' }, { $set: { age: 31 } });
+ await client.updateOne('users', { name: 'Grace' }, { $set: { age: 31 } })
- const documents = await client.find('users', {});
- expect(documents[0].age).toBe(31);
- });
+ const documents = await client.find('users', {})
+ expect(documents[0].age).toBe(31)
+ })
it('should return zero matches for non-existent document', async () => {
- const result = await client.updateOne(
- 'users',
- { name: 'NonExistent' },
- { $set: { age: 30 } }
- );
+ const result = await client.updateOne('users', { name: 'NonExistent' }, { $set: { age: 30 } })
- expect(result.matchedCount).toBe(0);
- expect(result.modifiedCount).toBe(0);
- });
- });
+ expect(result.matchedCount).toBe(0)
+ expect(result.modifiedCount).toBe(0)
+ })
+ })
describe('Delete Operations', () => {
beforeEach(async () => {
- await client.insertOne('users', { name: 'Henry', age: 40 });
- });
+ await client.insertOne('users', { name: 'Henry', age: 40 })
+ })
it('should delete a document', async () => {
- const result = await client.deleteOne('users', { name: 'Henry' });
+ const result = await client.deleteOne('users', { name: 'Henry' })
- expect(result.deletedCount).toBe(1);
- });
+ expect(result.deletedCount).toBe(1)
+ })
it('should remove document from collection', async () => {
- await client.deleteOne('users', { name: 'Henry' });
+ await client.deleteOne('users', { name: 'Henry' })
- const documents = await client.find('users', {});
- expect(documents).toHaveLength(0);
- });
+ const documents = await client.find('users', {})
+ expect(documents).toHaveLength(0)
+ })
it('should return zero for non-existent document', async () => {
const result = await client.deleteOne('users', {
name: 'NonExistent',
- });
+ })
- expect(result.deletedCount).toBe(0);
- });
- });
-});
+ expect(result.deletedCount).toBe(0)
+ })
+ })
+})
describe('MongoDB Error Handling', () => {
- let client: MockMongoClient;
+ let client: MockMongoClient
beforeEach(async () => {
- client = new MockMongoClient();
- await client.connect('mongodb://localhost:27017/test');
- });
+ client = new MockMongoClient()
+ await client.connect('mongodb://localhost:27017/test')
+ })
it('should throw configured error', async () => {
- client.setMockError('users', { code: 11000, message: 'Duplicate key error' });
+ client.setMockError('users', { code: 11000, message: 'Duplicate key error' })
- await expect(client.find('users', {})).rejects.toThrow('MongoError: 11000');
- });
+ await expect(client.find('users', {})).rejects.toThrow('MongoError: 11000')
+ })
it('should allow error clearing', async () => {
- client.setMockError('users', { code: 1, message: 'Test error' });
+ client.setMockError('users', { code: 1, message: 'Test error' })
- await expect(client.find('users', {})).rejects.toThrow();
+ await expect(client.find('users', {})).rejects.toThrow()
- client.clearMocks();
+ client.clearMocks()
- const result = await client.find('users', {});
- expect(result).toHaveLength(0);
- });
-});
+ const result = await client.find('users', {})
+ expect(result).toHaveLength(0)
+ })
+})
// =============================================================================
// Vitest Mock Utilities
@@ -836,7 +818,7 @@ describe('MongoDB Error Handling', () => {
* Factory function to create a mock MongoDB client for tests
*/
export function createMockMongoClient(): MockMongoClient {
- return new MockMongoClient();
+ return new MockMongoClient()
}
/**
@@ -848,19 +830,19 @@ export function setupMockMongoData(
) {
switch (scenario) {
case 'empty':
- client.setCollectionData('test', []);
- break;
+ client.setCollectionData('test', [])
+ break
case 'single':
- client.setCollectionData('test', [{ _id: '1', name: 'Test Document' }]);
- break;
+ client.setCollectionData('test', [{ _id: '1', name: 'Test Document' }])
+ break
case 'multiple':
client.setCollectionData('test', [
{ _id: '1', name: 'First', value: 100 },
{ _id: '2', name: 'Second', value: 200 },
{ _id: '3', name: 'Third', value: 300 },
- ]);
- break;
+ ])
+ break
}
}
diff --git a/mcp-servers/mongodb/__tests__/mongodb.mcp.test.ts b/mcp-servers/mongodb/__tests__/mongodb.mcp.test.ts
index a87f6470b..d9d275f5e 100644
--- a/mcp-servers/mongodb/__tests__/mongodb.mcp.test.ts
+++ b/mcp-servers/mongodb/__tests__/mongodb.mcp.test.ts
@@ -12,39 +12,38 @@
* - Error handling
* - Read-only mode enforcement
*/
-
-import { describe, it, expect, beforeEach } from 'vitest';
-import { createMockMongoClient, setupMockMongoData } from './mongodb.connection.test';
+import { beforeEach, describe, expect, it } from 'vitest'
+import { createMockMongoClient, setupMockMongoData } from './mongodb.connection.test'
// =============================================================================
// Types
// =============================================================================
interface McpTool {
- name: string;
- description: string;
+ name: string
+ description: string
inputSchema: {
- type: 'object';
- properties: Record<string, any>;
- required?: string[];
- };
+ type: 'object'
+ properties: Record<string, any>
+ required?: string[]
+ }
}
interface McpToolsListResponse {
- tools: McpTool[];
+ tools: McpTool[]
}
interface McpToolCallRequest {
- name: string;
- arguments?: Record<string, any>;
+ name: string
+ arguments?: Record<string, any>
}
interface McpToolCallResponse {
content: Array<{
- type: string;
- text?: string;
- }>;
- isError?: boolean;
+ type: string
+ text?: string
+ }>
+ isError?: boolean
}
// =============================================================================
@@ -52,25 +51,25 @@ interface McpToolCallResponse {
// =============================================================================
class MockMongoMcpServer {
- private mongoClient: ReturnType<typeof createMockMongoClient>;
- private readOnlyMode: boolean = true;
+ private mongoClient: ReturnType<typeof createMockMongoClient>
+ private readOnlyMode: boolean = true
constructor() {
- this.mongoClient = createMockMongoClient();
+ this.mongoClient = createMockMongoClient()
}
/**
* Initialize connection
*/
async initialize(connectionString: string): Promise<void> {
- await this.mongoClient.connect(connectionString);
+ await this.mongoClient.connect(connectionString)
}
/**
* Set read-only mode
*/
setReadOnlyMode(readOnly: boolean): void {
- this.readOnlyMode = readOnly;
+ this.readOnlyMode = readOnly
}
/**
@@ -220,7 +219,7 @@ class MockMongoMcpServer {
},
},
],
- };
+ }
}
/**
@@ -228,36 +227,36 @@ class MockMongoMcpServer {
* Execute a MongoDB MCP tool
*/
async toolsCall(request: McpToolCallRequest): Promise<McpToolCallResponse> {
- const { name, arguments: args } = request;
+ const { name, arguments: args } = request
try {
switch (name) {
case 'mongodb_find':
- return await this.find(args!);
+ return await this.find(args!)
case 'mongodb_aggregate':
- return await this.aggregate(args!);
+ return await this.aggregate(args!)
case 'mongodb_count':
- return await this.count(args!);
+ return await this.count(args!)
case 'mongodb_distinct':
- return await this.distinct(args!);
+ return await this.distinct(args!)
case 'mongodb_insert_one':
- return await this.insertOne(args!);
+ return await this.insertOne(args!)
case 'mongodb_update_one':
- return await this.updateOne(args!);
+ return await this.updateOne(args!)
case 'mongodb_delete_one':
- return await this.deleteOne(args!);
+ return await this.deleteOne(args!)
case 'mongodb_list_collections':
- return await this.listCollections(args!);
+ return await this.listCollections(args!)
case 'mongodb_list_databases':
- return await this.listDatabases();
+ return await this.listDatabases()
default:
return {
@@ -268,7 +267,7 @@ class MockMongoMcpServer {
},
],
isError: true,
- };
+ }
}
} catch (error: any) {
return {
@@ -279,7 +278,7 @@ class MockMongoMcpServer {
},
],
isError: true,
- };
+ }
}
}
@@ -288,7 +287,7 @@ class MockMongoMcpServer {
// =============================================================================
private async find(args: any): Promise<McpToolCallResponse> {
- const { database, collection, filter = {}, projection, limit, sort } = args;
+ const { database, collection, filter = {}, projection, limit, sort } = args
// Validate required parameters
if (!database || !collection) {
@@ -300,7 +299,7 @@ class MockMongoMcpServer {
},
],
isError: true,
- };
+ }
}
const documents = await this.mongoClient.find(collection, {
@@ -308,7 +307,7 @@ class MockMongoMcpServer {
projection,
limit,
sort,
- });
+ })
return {
content: [
@@ -317,11 +316,11 @@ class MockMongoMcpServer {
text: JSON.stringify(documents, null, 2),
},
],
- };
+ }
}
private async aggregate(args: any): Promise<McpToolCallResponse> {
- const { database, collection, pipeline } = args;
+ const { database, collection, pipeline } = args
// Validate required parameters
if (!database || !collection || !pipeline) {
@@ -333,10 +332,10 @@ class MockMongoMcpServer {
},
],
isError: true,
- };
+ }
}
- const documents = await this.mongoClient.aggregate(collection, pipeline);
+ const documents = await this.mongoClient.aggregate(collection, pipeline)
return {
content: [
@@ -345,13 +344,13 @@ class MockMongoMcpServer {
text: JSON.stringify(documents, null, 2),
},
],
- };
+ }
}
private async count(args: any): Promise<McpToolCallResponse> {
- const { database, collection, filter = {} } = args;
+ const { database, collection, filter = {} } = args
- const count = await this.mongoClient.count(collection, filter);
+ const count = await this.mongoClient.count(collection, filter)
return {
content: [
@@ -360,17 +359,15 @@ class MockMongoMcpServer {
text: JSON.stringify({ count }, null, 2),
},
],
- };
+ }
}
private async distinct(args: any): Promise<McpToolCallResponse> {
- const { database, collection, field, filter = {} } = args;
+ const { database, collection, field, filter = {} } = args
// Simplified distinct implementation
- const documents = await this.mongoClient.find(collection, { filter });
- const distinctValues = Array.from(
- new Set(documents.map(doc => doc[field]))
- );
+ const documents = await this.mongoClient.find(collection, { filter })
+ const distinctValues = Array.from(new Set(documents.map(doc => doc[field])))
return {
content: [
@@ -379,15 +376,15 @@ class MockMongoMcpServer {
text: JSON.stringify(distinctValues, null, 2),
},
],
- };
+ }
}
private async insertOne(args: any): Promise<McpToolCallResponse> {
- this.enforceReadOnly('insert_one');
+ this.enforceReadOnly('insert_one')
- const { database, collection, document } = args;
+ const { database, collection, document } = args
- const result = await this.mongoClient.insertOne(collection, document);
+ const result = await this.mongoClient.insertOne(collection, document)
return {
content: [
@@ -396,15 +393,15 @@ class MockMongoMcpServer {
text: JSON.stringify(result, null, 2),
},
],
- };
+ }
}
private async updateOne(args: any): Promise<McpToolCallResponse> {
- this.enforceReadOnly('update_one');
+ this.enforceReadOnly('update_one')
- const { database, collection, filter, update } = args;
+ const { database, collection, filter, update } = args
- const result = await this.mongoClient.updateOne(collection, filter, update);
+ const result = await this.mongoClient.updateOne(collection, filter, update)
return {
content: [
@@ -413,15 +410,15 @@ class MockMongoMcpServer {
text: JSON.stringify(result, null, 2),
},
],
- };
+ }
}
private async deleteOne(args: any): Promise<McpToolCallResponse> {
- this.enforceReadOnly('delete_one');
+ this.enforceReadOnly('delete_one')
- const { database, collection, filter } = args;
+ const { database, collection, filter } = args
- const result = await this.mongoClient.deleteOne(collection, filter);
+ const result = await this.mongoClient.deleteOne(collection, filter)
return {
content: [
@@ -430,14 +427,14 @@ class MockMongoMcpServer {
text: JSON.stringify(result, null, 2),
},
],
- };
+ }
}
private async listCollections(args: any): Promise<McpToolCallResponse> {
- const { database } = args;
+ const { database } = args
// Mock response
- const collections = ['users', 'products', 'orders'];
+ const collections = ['users', 'products', 'orders']
return {
content: [
@@ -446,12 +443,12 @@ class MockMongoMcpServer {
text: JSON.stringify(collections, null, 2),
},
],
- };
+ }
}
private async listDatabases(): Promise<McpToolCallResponse> {
// Mock response
- const databases = ['admin', 'config', 'test'];
+ const databases = ['admin', 'config', 'test']
return {
content: [
@@ -460,7 +457,7 @@ class MockMongoMcpServer {
text: JSON.stringify(databases, null, 2),
},
],
- };
+ }
}
// =============================================================================
@@ -469,9 +466,7 @@ class MockMongoMcpServer {
private enforceReadOnly(operation: string): void {
if (this.readOnlyMode) {
- throw new Error(
- `Write operation '${operation}' blocked in read-only mode`
- );
+ throw new Error(`Write operation '${operation}' blocked in read-only mode`)
}
}
@@ -480,7 +475,7 @@ class MockMongoMcpServer {
// =============================================================================
setupMockData() {
- setupMockMongoData(this.mongoClient, 'multiple');
+ setupMockMongoData(this.mongoClient, 'multiple')
// Override for MongoDB specific tests
const documents = [
@@ -488,9 +483,9 @@ class MockMongoMcpServer {
{ _id: '2', name: 'Bob', age: 25, department: 'Sales' },
{ _id: '3', name: 'Charlie', age: 35, department: 'Engineering' },
{ _id: '4', name: 'Diana', age: 28, department: 'Marketing' },
- ];
+ ]
- (this.mongoClient as any).setCollectionData('users', documents);
+ ;(this.mongoClient as any).setCollectionData('users', documents)
}
}
@@ -499,58 +494,56 @@ class MockMongoMcpServer {
// =============================================================================
describe('MongoDB MCP Server - MCP Operations', () => {
- let server: MockMongoMcpServer;
+ let server: MockMongoMcpServer
beforeEach(async () => {
- server = new MockMongoMcpServer();
- await server.initialize('mongodb://localhost:27017/test');
- server.setupMockData();
- });
+ server = new MockMongoMcpServer()
+ await server.initialize('mongodb://localhost:27017/test')
+ server.setupMockData()
+ })
describe('tools/list', () => {
it('should return all available MongoDB tools', async () => {
- const response = await server.toolsList();
+ const response = await server.toolsList()
- expect(response.tools).toBeDefined();
- expect(response.tools.length).toBeGreaterThan(0);
- });
+ expect(response.tools).toBeDefined()
+ expect(response.tools.length).toBeGreaterThan(0)
+ })
it('should include mongodb_find tool', async () => {
- const response = await server.toolsList();
+ const response = await server.toolsList()
- const findTool = response.tools.find(t => t.name === 'mongodb_find');
- expect(findTool).toBeDefined();
- expect(findTool?.description).toContain('Find');
- });
+ const findTool = response.tools.find(t => t.name === 'mongodb_find')
+ expect(findTool).toBeDefined()
+ expect(findTool?.description).toContain('Find')
+ })
it('should include mongodb_aggregate tool', async () => {
- const response = await server.toolsList();
+ const response = await server.toolsList()
- const aggregateTool = response.tools.find(
- t => t.name === 'mongodb_aggregate'
- );
- expect(aggregateTool).toBeDefined();
- });
+ const aggregateTool = response.tools.find(t => t.name === 'mongodb_aggregate')
+ expect(aggregateTool).toBeDefined()
+ })
it('should include write operation tools', async () => {
- const response = await server.toolsList();
+ const response = await server.toolsList()
- const toolNames = response.tools.map(t => t.name);
+ const toolNames = response.tools.map(t => t.name)
- expect(toolNames).toContain('mongodb_insert_one');
- expect(toolNames).toContain('mongodb_update_one');
- expect(toolNames).toContain('mongodb_delete_one');
- });
+ expect(toolNames).toContain('mongodb_insert_one')
+ expect(toolNames).toContain('mongodb_update_one')
+ expect(toolNames).toContain('mongodb_delete_one')
+ })
it('should have database and collection as required for find', async () => {
- const response = await server.toolsList();
+ const response = await server.toolsList()
- const findTool = response.tools.find(t => t.name === 'mongodb_find');
+ const findTool = response.tools.find(t => t.name === 'mongodb_find')
- expect(findTool?.inputSchema.required).toContain('database');
- expect(findTool?.inputSchema.required).toContain('collection');
- });
- });
+ expect(findTool?.inputSchema.required).toContain('database')
+ expect(findTool?.inputSchema.required).toContain('collection')
+ })
+ })
describe('tools/call - mongodb_find', () => {
it('should find documents successfully', async () => {
@@ -561,14 +554,14 @@ describe('MongoDB MCP Server - MCP Operations', () => {
collection: 'users',
filter: { department: 'Engineering' },
},
- });
+ })
- expect(response.isError).toBeUndefined();
+ expect(response.isError).toBeUndefined()
- const documents = JSON.parse(response.content[0].text!);
- expect(documents).toHaveLength(2);
- expect(documents[0].department).toBe('Engineering');
- });
+ const documents = JSON.parse(response.content[0].text!)
+ expect(documents).toHaveLength(2)
+ expect(documents[0].department).toBe('Engineering')
+ })
it('should support limit parameter', async () => {
const response = await server.toolsCall({
@@ -578,11 +571,11 @@ describe('MongoDB MCP Server - MCP Operations', () => {
collection: 'users',
limit: 2,
},
- });
+ })
- const documents = JSON.parse(response.content[0].text!);
- expect(documents).toHaveLength(2);
- });
+ const documents = JSON.parse(response.content[0].text!)
+ expect(documents).toHaveLength(2)
+ })
it('should support sort parameter', async () => {
const response = await server.toolsCall({
@@ -592,12 +585,12 @@ describe('MongoDB MCP Server - MCP Operations', () => {
collection: 'users',
sort: { age: 1 },
},
- });
+ })
- const documents = JSON.parse(response.content[0].text!);
- expect(documents[0].age).toBe(25); // Bob (youngest)
- expect(documents[3].age).toBe(35); // Charlie (oldest)
- });
+ const documents = JSON.parse(response.content[0].text!)
+ expect(documents[0].age).toBe(25) // Bob (youngest)
+ expect(documents[3].age).toBe(35) // Charlie (oldest)
+ })
it('should return error for missing database', async () => {
const response = await server.toolsCall({
@@ -605,11 +598,11 @@ describe('MongoDB MCP Server - MCP Operations', () => {
arguments: {
collection: 'users',
},
- });
+ })
- expect(response.isError).toBe(true);
- });
- });
+ expect(response.isError).toBe(true)
+ })
+ })
describe('tools/call - mongodb_aggregate', () => {
it('should execute aggregation pipeline', async () => {
@@ -620,13 +613,13 @@ describe('MongoDB MCP Server - MCP Operations', () => {
collection: 'users',
pipeline: [{ $match: { department: 'Engineering' } }],
},
- });
+ })
- expect(response.isError).toBeUndefined();
+ expect(response.isError).toBeUndefined()
- const documents = JSON.parse(response.content[0].text!);
- expect(documents.length).toBeGreaterThan(0);
- });
+ const documents = JSON.parse(response.content[0].text!)
+ expect(documents.length).toBeGreaterThan(0)
+ })
it('should support multiple pipeline stages', async () => {
const response = await server.toolsCall({
@@ -634,18 +627,14 @@ describe('MongoDB MCP Server - MCP Operations', () => {
arguments: {
database: 'test',
collection: 'users',
- pipeline: [
- { $match: { age: { $gte: 30 } } },
- { $sort: { age: -1 } },
- { $limit: 2 },
- ],
+ pipeline: [{ $match: { age: { $gte: 30 } } }, { $sort: { age: -1 } }, { $limit: 2 }],
},
- });
+ })
- const documents = JSON.parse(response.content[0].text!);
- expect(documents).toHaveLength(2);
- });
- });
+ const documents = JSON.parse(response.content[0].text!)
+ expect(documents).toHaveLength(2)
+ })
+ })
describe('tools/call - mongodb_count', () => {
it('should count documents', async () => {
@@ -655,13 +644,13 @@ describe('MongoDB MCP Server - MCP Operations', () => {
database: 'test',
collection: 'users',
},
- });
+ })
- expect(response.isError).toBeUndefined();
+ expect(response.isError).toBeUndefined()
- const result = JSON.parse(response.content[0].text!);
- expect(result.count).toBe(4);
- });
+ const result = JSON.parse(response.content[0].text!)
+ expect(result.count).toBe(4)
+ })
it('should count with filter', async () => {
const response = await server.toolsCall({
@@ -671,17 +660,17 @@ describe('MongoDB MCP Server - MCP Operations', () => {
collection: 'users',
filter: { department: 'Engineering' },
},
- });
+ })
- const result = JSON.parse(response.content[0].text!);
- expect(result.count).toBe(2);
- });
- });
+ const result = JSON.parse(response.content[0].text!)
+ expect(result.count).toBe(2)
+ })
+ })
describe('Read-Only Mode Enforcement', () => {
beforeEach(() => {
- server.setReadOnlyMode(true);
- });
+ server.setReadOnlyMode(true)
+ })
it('should block insert operations in read-only mode', async () => {
const response = await server.toolsCall({
@@ -691,11 +680,11 @@ describe('MongoDB MCP Server - MCP Operations', () => {
collection: 'users',
document: { name: 'Test', age: 25 },
},
- });
+ })
- expect(response.isError).toBe(true);
- expect(response.content[0].text).toContain('read-only mode');
- });
+ expect(response.isError).toBe(true)
+ expect(response.content[0].text).toContain('read-only mode')
+ })
it('should block update operations in read-only mode', async () => {
const response = await server.toolsCall({
@@ -706,11 +695,11 @@ describe('MongoDB MCP Server - MCP Operations', () => {
filter: { name: 'Alice' },
update: { $set: { age: 31 } },
},
- });
+ })
- expect(response.isError).toBe(true);
- expect(response.content[0].text).toContain('read-only mode');
- });
+ expect(response.isError).toBe(true)
+ expect(response.content[0].text).toContain('read-only mode')
+ })
it('should block delete operations in read-only mode', async () => {
const response = await server.toolsCall({
@@ -720,11 +709,11 @@ describe('MongoDB MCP Server - MCP Operations', () => {
collection: 'users',
filter: { name: 'Alice' },
},
- });
+ })
- expect(response.isError).toBe(true);
- expect(response.content[0].text).toContain('read-only mode');
- });
+ expect(response.isError).toBe(true)
+ expect(response.content[0].text).toContain('read-only mode')
+ })
it('should allow find operations in read-only mode', async () => {
const response = await server.toolsCall({
@@ -733,10 +722,10 @@ describe('MongoDB MCP Server - MCP Operations', () => {
database: 'test',
collection: 'users',
},
- });
+ })
- expect(response.isError).toBeUndefined();
- });
+ expect(response.isError).toBeUndefined()
+ })
it('should allow aggregate operations in read-only mode', async () => {
const response = await server.toolsCall({
@@ -746,16 +735,16 @@ describe('MongoDB MCP Server - MCP Operations', () => {
collection: 'users',
pipeline: [],
},
- });
+ })
- expect(response.isError).toBeUndefined();
- });
- });
+ expect(response.isError).toBeUndefined()
+ })
+ })
describe('Write Operations (when read-only disabled)', () => {
beforeEach(() => {
- server.setReadOnlyMode(false);
- });
+ server.setReadOnlyMode(false)
+ })
it('should insert a document', async () => {
const response = await server.toolsCall({
@@ -765,13 +754,13 @@ describe('MongoDB MCP Server - MCP Operations', () => {
collection: 'users',
document: { name: 'Eve', age: 27, department: 'Sales' },
},
- });
+ })
- expect(response.isError).toBeUndefined();
+ expect(response.isError).toBeUndefined()
- const result = JSON.parse(response.content[0].text!);
- expect(result.insertedId).toBeDefined();
- });
+ const result = JSON.parse(response.content[0].text!)
+ expect(result.insertedId).toBeDefined()
+ })
it('should update a document', async () => {
const response = await server.toolsCall({
@@ -782,13 +771,13 @@ describe('MongoDB MCP Server - MCP Operations', () => {
filter: { name: 'Alice' },
update: { $set: { age: 31 } },
},
- });
+ })
- expect(response.isError).toBeUndefined();
+ expect(response.isError).toBeUndefined()
- const result = JSON.parse(response.content[0].text!);
- expect(result.matchedCount).toBe(1);
- });
+ const result = JSON.parse(response.content[0].text!)
+ expect(result.matchedCount).toBe(1)
+ })
it('should delete a document', async () => {
const response = await server.toolsCall({
@@ -798,14 +787,14 @@ describe('MongoDB MCP Server - MCP Operations', () => {
collection: 'users',
filter: { name: 'Alice' },
},
- });
+ })
- expect(response.isError).toBeUndefined();
+ expect(response.isError).toBeUndefined()
- const result = JSON.parse(response.content[0].text!);
- expect(result.deletedCount).toBe(1);
- });
- });
+ const result = JSON.parse(response.content[0].text!)
+ expect(result.deletedCount).toBe(1)
+ })
+ })
describe('Response Format', () => {
it('should return content array', async () => {
@@ -815,10 +804,10 @@ describe('MongoDB MCP Server - MCP Operations', () => {
database: 'test',
collection: 'users',
},
- });
+ })
- expect(Array.isArray(response.content)).toBe(true);
- });
+ expect(Array.isArray(response.content)).toBe(true)
+ })
it('should include text type in content', async () => {
const response = await server.toolsCall({
@@ -827,11 +816,11 @@ describe('MongoDB MCP Server - MCP Operations', () => {
database: 'test',
collection: 'users',
},
- });
+ })
- expect(response.content[0].type).toBe('text');
- expect(response.content[0].text).toBeDefined();
- });
+ expect(response.content[0].type).toBe('text')
+ expect(response.content[0].text).toBeDefined()
+ })
it('should return valid JSON in text field', async () => {
const response = await server.toolsCall({
@@ -840,22 +829,22 @@ describe('MongoDB MCP Server - MCP Operations', () => {
database: 'test',
collection: 'users',
},
- });
+ })
- expect(() => JSON.parse(response.content[0].text!)).not.toThrow();
- });
- });
+ expect(() => JSON.parse(response.content[0].text!)).not.toThrow()
+ })
+ })
describe('Error Handling', () => {
it('should return error for unknown tool', async () => {
const response = await server.toolsCall({
name: 'unknown_tool',
arguments: {},
- });
+ })
- expect(response.isError).toBe(true);
- expect(response.content[0].text).toContain('Unknown tool');
- });
+ expect(response.isError).toBe(true)
+ expect(response.content[0].text).toContain('Unknown tool')
+ })
it('should handle missing required parameters', async () => {
const response = await server.toolsCall({
@@ -863,9 +852,9 @@ describe('MongoDB MCP Server - MCP Operations', () => {
arguments: {
// Missing required 'database' and 'collection'
},
- });
+ })
- expect(response.isError).toBe(true);
- });
- });
-});
+ expect(response.isError).toBe(true)
+ })
+ })
+})
diff --git a/mcp-servers/mongodb/__tests__/mongodb.statefulset.test.ts b/mcp-servers/mongodb/__tests__/mongodb.statefulset.test.ts
index 184ee6757..f3bb8b0d3 100644
--- a/mcp-servers/mongodb/__tests__/mongodb.statefulset.test.ts
+++ b/mcp-servers/mongodb/__tests__/mongodb.statefulset.test.ts
@@ -12,107 +12,106 @@
* - Volume mounting
* - Context-mapper reconciliation
*/
-
-import { describe, it, expect, beforeEach } from 'vitest';
-import { readFileSync } from 'fs';
-import { join } from 'path';
-import { loadYaml } from '../../utils/yaml-loader';
+import { beforeEach, describe, expect, it } from 'vitest'
+import { readFileSync } from 'fs'
+import { join } from 'path'
+import { loadYaml } from '../../utils/yaml-loader'
// =============================================================================
// Types
// =============================================================================
interface K8sStatefulSet {
- apiVersion: string;
- kind: string;
+ apiVersion: string
+ kind: string
metadata: {
- name: string;
- namespace: string;
- labels: Record<string, string>;
- };
+ name: string
+ namespace: string
+ labels: Record<string, string>
+ }
spec: {
- replicas: number;
- serviceName: string;
+ replicas: number
+ serviceName: string
selector: {
- matchLabels: Record<string, string>;
- };
+ matchLabels: Record<string, string>
+ }
template: {
metadata: {
- labels: Record<string, string>;
- };
+ labels: Record<string, string>
+ }
spec: {
containers: Array<{
- name: string;
- image: string;
- ports: Array<{ containerPort: number; name?: string }>;
+ name: string
+ image: string
+ ports: Array<{ containerPort: number; name?: string }>
env: Array<{
- name: string;
- value?: string;
+ name: string
+ value?: string
valueFrom?: {
secretKeyRef: {
- name: string;
- key: string;
- };
- };
- }>;
+ name: string
+ key: string
+ }
+ }
+ }>
resources?: {
- requests?: { memory?: string; cpu?: string };
- limits?: { memory?: string; cpu?: string };
- };
+ requests?: { memory?: string; cpu?: string }
+ limits?: { memory?: string; cpu?: string }
+ }
volumeMounts?: Array<{
- name: string;
- mountPath: string;
- }>;
- }>;
+ name: string
+ mountPath: string
+ }>
+ }>
volumes?: Array<{
- name: string;
+ name: string
persistentVolumeClaim?: {
- claimName: string;
- };
- }>;
- };
- };
+ claimName: string
+ }
+ }>
+ }
+ }
volumeClaimTemplates: Array<{
metadata: {
- name: string;
- };
+ name: string
+ }
spec: {
- accessModes: string[];
+ accessModes: string[]
resources: {
requests: {
- storage: string;
- };
- };
- };
- }>;
- };
+ storage: string
+ }
+ }
+ }
+ }>
+ }
}
interface K8sHeadlessService {
- apiVersion: string;
- kind: string;
+ apiVersion: string
+ kind: string
metadata: {
- name: string;
- namespace: string;
- };
+ name: string
+ namespace: string
+ }
spec: {
- clusterIP: string;
- selector: Record<string, string>;
+ clusterIP: string
+ selector: Record<string, string>
ports: Array<{
- name: string;
- port: number;
- targetPort: number;
- protocol: string;
- }>;
- publishNotReadyAddresses: boolean;
- };
+ name: string
+ port: number
+ targetPort: number
+ protocol: string
+ }>
+ publishNotReadyAddresses: boolean
+ }
}
// =============================================================================
// Test Data
// =============================================================================
-const MCP_SERVER_YAML = join(__dirname, '../mcpserver.yaml');
+const MCP_SERVER_YAML = join(__dirname, '../mcpserver.yaml')
// =============================================================================
// Helper Functions
@@ -126,7 +125,7 @@ function generateExpectedStatefulSet(): K8sStatefulSet {
name: 'mongodb-server',
namespace: 'mcp-server',
labels: {
- 'app': 'mongodb-mcp',
+ app: 'mongodb-mcp',
'clerum.io/mcp-server': 'mongodb-server',
'clerum.io/managed-by': 'context-mapper',
},
@@ -136,14 +135,14 @@ function generateExpectedStatefulSet(): K8sStatefulSet {
serviceName: 'mongodb-server',
selector: {
matchLabels: {
- 'app': 'mongodb-mcp',
+ app: 'mongodb-mcp',
'clerum.io/mcp-server': 'mongodb-server',
},
},
template: {
metadata: {
labels: {
- 'app': 'mongodb-mcp',
+ app: 'mongodb-mcp',
'clerum.io/mcp-server': 'mongodb-server',
},
},
@@ -221,7 +220,7 @@ function generateExpectedStatefulSet(): K8sStatefulSet {
},
],
},
- };
+ }
}
function generateExpectedHeadlessService(): K8sHeadlessService {
@@ -235,7 +234,7 @@ function generateExpectedHeadlessService(): K8sHeadlessService {
spec: {
clusterIP: 'None',
selector: {
- 'app': 'mongodb-mcp',
+ app: 'mongodb-mcp',
'clerum.io/mcp-server': 'mongodb-server',
},
ports: [
@@ -254,7 +253,7 @@ function generateExpectedHeadlessService(): K8sHeadlessService {
],
publishNotReadyAddresses: true,
},
- };
+ }
}
// =============================================================================
@@ -263,156 +262,156 @@ function generateExpectedHeadlessService(): K8sHeadlessService {
describe('MongoDB MCP Server - StatefulSet Deployment', () => {
describe('Expected StatefulSet Configuration', () => {
- let sts: K8sStatefulSet;
+ let sts: K8sStatefulSet
beforeEach(() => {
- sts = generateExpectedStatefulSet();
- });
+ sts = generateExpectedStatefulSet()
+ })
describe('StatefulSet Metadata', () => {
it('should have correct StatefulSet name', () => {
- expect(sts.metadata.name).toBe('mongodb-server');
- });
+ expect(sts.metadata.name).toBe('mongodb-server')
+ })
it('should be in mcp-server namespace', () => {
- expect(sts.metadata.namespace).toBe('mcp-server');
- });
+ expect(sts.metadata.namespace).toBe('mcp-server')
+ })
it('should have clerum.io labels for operator tracking', () => {
- expect(sts.metadata.labels).toHaveProperty('clerum.io/mcp-server', 'mongodb-server');
- expect(sts.metadata.labels).toHaveProperty('clerum.io/managed-by', 'context-mapper');
- });
- });
+ expect(sts.metadata.labels).toHaveProperty('clerum.io/mcp-server', 'mongodb-server')
+ expect(sts.metadata.labels).toHaveProperty('clerum.io/managed-by', 'context-mapper')
+ })
+ })
describe('StatefulSet vs Deployment', () => {
it('should be StatefulSet kind (not Deployment)', () => {
- expect(sts.kind).toBe('StatefulSet');
- expect(sts.kind).not.toBe('Deployment');
- });
+ expect(sts.kind).toBe('StatefulSet')
+ expect(sts.kind).not.toBe('Deployment')
+ })
it('should have serviceName for headless service', () => {
- expect(sts.spec.serviceName).toBe('mongodb-server');
- });
- });
+ expect(sts.spec.serviceName).toBe('mongodb-server')
+ })
+ })
describe('Replica Configuration', () => {
it('should run single replica', () => {
- expect(sts.spec.replicas).toBe(1);
- });
- });
+ expect(sts.spec.replicas).toBe(1)
+ })
+ })
describe('Container Configuration', () => {
- let container: K8sStatefulSet['spec']['template']['spec']['containers'][0];
+ let container: K8sStatefulSet['spec']['template']['spec']['containers'][0]
beforeEach(() => {
- container = sts.spec.template.spec.containers[0];
- });
+ container = sts.spec.template.spec.containers[0]
+ })
it('should use official MongoDB image', () => {
- expect(container.image).toBe('mongodb/mongodb-mcp-server:latest');
- });
+ expect(container.image).toBe('mongodb/mongodb-mcp-server:latest')
+ })
it('should expose two ports (http and health)', () => {
- expect(container.ports).toHaveLength(2);
- const httpPort = container.ports.find(p => p.name === 'http');
- expect(httpPort?.containerPort).toBe(3000);
- const healthPort = container.ports.find(p => p.name === 'health');
- expect(healthPort?.containerPort).toBe(3001);
- });
+ expect(container.ports).toHaveLength(2)
+ const httpPort = container.ports.find(p => p.name === 'http')
+ expect(httpPort?.containerPort).toBe(3000)
+ const healthPort = container.ports.find(p => p.name === 'health')
+ expect(healthPort?.containerPort).toBe(3001)
+ })
it('should mount data volume', () => {
- expect(container.volumeMounts).toBeDefined();
- expect(container.volumeMounts).toHaveLength(1);
- const dataMount = container.volumeMounts?.find(vm => vm.name === 'data');
- expect(dataMount?.mountPath).toBe('/data/db');
- });
- });
+ expect(container.volumeMounts).toBeDefined()
+ expect(container.volumeMounts).toHaveLength(1)
+ const dataMount = container.volumeMounts?.find(vm => vm.name === 'data')
+ expect(dataMount?.mountPath).toBe('/data/db')
+ })
+ })
describe('Volume Management', () => {
it('should have volumeClaimTemplates for PVC', () => {
- expect(sts.spec.volumeClaimTemplates).toBeDefined();
- expect(sts.spec.volumeClaimTemplates).toHaveLength(1);
- });
+ expect(sts.spec.volumeClaimTemplates).toBeDefined()
+ expect(sts.spec.volumeClaimTemplates).toHaveLength(1)
+ })
it('should create data PVC template', () => {
- const pvcTemplate = sts.spec.volumeClaimTemplates[0];
- expect(pvcTemplate.metadata.name).toBe('data');
- expect(pvcTemplate.spec.accessModes).toContain('ReadWriteOnce');
- expect(pvcTemplate.spec.resources.requests.storage).toBe('1Gi');
- });
+ const pvcTemplate = sts.spec.volumeClaimTemplates[0]
+ expect(pvcTemplate.metadata.name).toBe('data')
+ expect(pvcTemplate.spec.accessModes).toContain('ReadWriteOnce')
+ expect(pvcTemplate.spec.resources.requests.storage).toBe('1Gi')
+ })
it('should mount PVC in container', () => {
- const volumes = sts.spec.template.spec.volumes;
- const dataVolume = volumes?.find(v => v.name === 'data');
- expect(dataVolume).toBeDefined();
- expect(dataVolume?.persistentVolumeClaim).toBeDefined();
- });
- });
- });
+ const volumes = sts.spec.template.spec.volumes
+ const dataVolume = volumes?.find(v => v.name === 'data')
+ expect(dataVolume).toBeDefined()
+ expect(dataVolume?.persistentVolumeClaim).toBeDefined()
+ })
+ })
+ })
describe('Expected Headless Service Configuration', () => {
- let svc: K8sHeadlessService;
+ let svc: K8sHeadlessService
beforeEach(() => {
- svc = generateExpectedHeadlessService();
- });
+ svc = generateExpectedHeadlessService()
+ })
it('should be headless (ClusterIP: None)', () => {
- expect(svc.spec.clusterIP).toBe('None');
- });
+ expect(svc.spec.clusterIP).toBe('None')
+ })
it('should publish not ready addresses for DNS', () => {
- expect(svc.spec.publishNotReadyAddresses).toBe(true);
- });
- });
+ expect(svc.spec.publishNotReadyAddresses).toBe(true)
+ })
+ })
describe('PVC Data Retention', () => {
it('should create PVC without ownerRef', () => {
- const sts = generateExpectedStatefulSet();
- const pvcTemplate = sts.spec.volumeClaimTemplates[0];
- expect(pvcTemplate.metadata).not.toHaveProperty('ownerReferences');
- });
+ const sts = generateExpectedStatefulSet()
+ const pvcTemplate = sts.spec.volumeClaimTemplates[0]
+ expect(pvcTemplate.metadata).not.toHaveProperty('ownerReferences')
+ })
it('should retain data when pod is deleted', () => {
- const sts = generateExpectedStatefulSet();
- const pvcName = 'mongodb-server-mongodb-server-0';
- expect(pvcName).toContain('mongodb-server-0');
- });
- });
-});
+ const sts = generateExpectedStatefulSet()
+ const pvcName = 'mongodb-server-mongodb-server-0'
+ expect(pvcName).toContain('mongodb-server-0')
+ })
+ })
+})
describe('MongoDB MCP Server - Operational Considerations', () => {
it('should have stable DNS names for pods', () => {
- const podName = 'mongodb-server-0';
- const serviceName = 'mongodb-server';
- const namespace = 'mcp-server';
- const dnsName = `${podName}.${serviceName}.${namespace}.svc.cluster.local`;
- expect(dnsName).toBe('mongodb-server-0.mongodb-server.mcp-server.svc.cluster.local');
- });
+ const podName = 'mongodb-server-0'
+ const serviceName = 'mongodb-server'
+ const namespace = 'mcp-server'
+ const dnsName = `${podName}.${serviceName}.${namespace}.svc.cluster.local`
+ expect(dnsName).toBe('mongodb-server-0.mongodb-server.mcp-server.svc.cluster.local')
+ })
it('should maintain data across pod restarts', () => {
- const sts = generateExpectedStatefulSet();
- const pvcTemplate = sts.spec.volumeClaimTemplates[0];
- expect(pvcTemplate.spec.accessModes).toContain('ReadWriteOnce');
- expect(pvcTemplate.spec.resources.requests.storage).toBe('1Gi');
- });
-});
+ const sts = generateExpectedStatefulSet()
+ const pvcTemplate = sts.spec.volumeClaimTemplates[0]
+ expect(pvcTemplate.spec.accessModes).toContain('ReadWriteOnce')
+ expect(pvcTemplate.spec.resources.requests.storage).toBe('1Gi')
+ })
+})
describe('MongoDB vs Airtable - Deployment Comparison', () => {
it('should use StatefulSet vs Deployment', () => {
- const mongoSts = generateExpectedStatefulSet();
- expect(mongoSts.kind).toBe('StatefulSet');
- });
+ const mongoSts = generateExpectedStatefulSet()
+ expect(mongoSts.kind).toBe('StatefulSet')
+ })
it('should have PVC vs no PVC', () => {
- const mongoSts = generateExpectedStatefulSet();
- expect(mongoSts.spec.volumeClaimTemplates).toBeDefined();
- });
+ const mongoSts = generateExpectedStatefulSet()
+ expect(mongoSts.spec.volumeClaimTemplates).toBeDefined()
+ })
it('both should have similar resource requirements', () => {
- const mongoSts = generateExpectedStatefulSet();
- const mongoResources = mongoSts.spec.template.spec.containers[0].resources!;
- expect(mongoResources.requests.memory).toBe('128Mi');
- expect(mongoResources.limits.memory).toBe('256Mi');
- });
-});
+ const mongoSts = generateExpectedStatefulSet()
+ const mongoResources = mongoSts.spec.template.spec.containers[0].resources!
+ expect(mongoResources.requests.memory).toBe('128Mi')
+ expect(mongoResources.limits.memory).toBe('256Mi')
+ })
+})
diff --git a/mcp-servers/mongodb/example.secret.yaml b/mcp-servers/mongodb/example.secret.yaml
index 38afea3ac..84a670a04 100644
--- a/mcp-servers/mongodb/example.secret.yaml
+++ b/mcp-servers/mongodb/example.secret.yaml
@@ -9,4 +9,4 @@ type: Opaque
data:
# Base64-encoded MongoDB connection string
# To encode: echo -n "mongodb+srv://user:[email protected]/mydb" | base64
- connection-string: "<BASE64_ENCODED_CONNECTION_STRING>"
+ connection-string: '<BASE64_ENCODED_CONNECTION_STRING>'
diff --git a/mcp-servers/mongodb/mcpserver.yaml b/mcp-servers/mongodb/mcpserver.yaml
index 0825f22f6..fb1793174 100644
--- a/mcp-servers/mongodb/mcpserver.yaml
+++ b/mcp-servers/mongodb/mcpserver.yaml
@@ -23,8 +23,8 @@ spec:
port: 3001
serverConfig:
readOnly: false
- loggers: "stderr"
- telemetry: "disabled"
+ loggers: 'stderr'
+ telemetry: 'disabled'
envMapping:
transport: MDB_MCP_TRANSPORT
httpHost: MDB_MCP_HTTP_HOST
@@ -41,11 +41,11 @@ spec:
envVar: MDB_MCP_CONNECTION_STRING
resources:
requests:
- memory: "128Mi"
- cpu: "100m"
+ memory: '128Mi'
+ cpu: '100m'
limits:
- memory: "256Mi"
- cpu: "500m"
+ memory: '256Mi'
+ cpu: '500m'
auth:
type: none
enabled: true
diff --git a/mcp-servers/package-lock.json b/mcp-servers/package-lock.json
index de8c21cd5..b0b589bb8 100644
--- a/mcp-servers/package-lock.json
+++ b/mcp-servers/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@clerum/mcp-servers",
- "version": "1.0.7",
+ "version": "1.0.8",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@clerum/mcp-servers",
- "version": "1.0.7",
+ "version": "1.0.8",
"dependencies": {
"js-yaml": "^4.1.1"
},
diff --git a/mcp-servers/package.json b/mcp-servers/package.json
index 7be36056c..a044ec5e4 100644
--- a/mcp-servers/package.json
+++ b/mcp-servers/package.json
@@ -1,6 +1,6 @@
{
"name": "@clerum/mcp-servers",
- "version": "1.0.7",
+ "version": "1.0.8",
"description": "MCP servers for Clerum testing",
"type": "module",
"main": "index.ts",
diff --git a/mcp-servers/playwright/mcpserver.yaml b/mcp-servers/playwright/mcpserver.yaml
index dd4be7678..13fe738f9 100644
--- a/mcp-servers/playwright/mcpserver.yaml
+++ b/mcp-servers/playwright/mcpserver.yaml
@@ -21,9 +21,9 @@ spec:
- --host
- 0.0.0.0
- --port
- - "8931"
+ - '8931'
- --allowed-hosts
- - "*"
+ - '*'
transport:
type: streamableHttp
url: http://playwright-server.mcp-server.svc.cluster.local:8931/mcp
@@ -32,9 +32,9 @@ spec:
type: none
resources:
requests:
- memory: "512Mi"
- cpu: "250m"
+ memory: '512Mi'
+ cpu: '250m'
limits:
- memory: "1Gi"
- cpu: "1000m"
+ memory: '1Gi'
+ cpu: '1000m'
enabled: true
diff --git a/mcp-servers/utils/yaml-loader.ts b/mcp-servers/utils/yaml-loader.ts
index 2d69cda70..94f8cb9c9 100644
--- a/mcp-servers/utils/yaml-loader.ts
+++ b/mcp-servers/utils/yaml-loader.ts
@@ -3,17 +3,18 @@
*
* Uses js-yaml for robust YAML parsing of test fixtures.
*/
-
-import yaml from 'js-yaml';
+import yaml from 'js-yaml'
/**
* Load and parse a YAML string
*/
export function loadYaml(content: string): any {
try {
- return yaml.load(content);
+ return yaml.load(content)
} catch (error) {
- throw new Error(`Failed to parse YAML: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ throw new Error(
+ `Failed to parse YAML: ${error instanceof Error ? error.message : 'Unknown error'}`
+ )
}
}
@@ -21,7 +22,7 @@ export function loadYaml(content: string): any {
* Load and parse a YAML file
*/
export async function loadYamlFile(path: string): Promise<any> {
- const { readFile } = await import('fs/promises');
- const content = await readFile(path, 'utf-8');
- return loadYaml(content);
+ const { readFile } = await import('fs/promises')
+ const content = await readFile(path, 'utf-8')
+ return loadYaml(content)
}
diff --git a/mcp-servers/vitest.config.ts b/mcp-servers/vitest.config.ts
index 728fb23b0..9ee49f3e3 100644
--- a/mcp-servers/vitest.config.ts
+++ b/mcp-servers/vitest.config.ts
@@ -1,4 +1,4 @@
-import { defineConfig } from 'vitest/config';
+import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
@@ -13,4 +13,4 @@ export default defineConfig({
exclude: ['**/__tests__/**', '**/node_modules/**', '**/dist/**'],
},
},
-});
+})
diff --git a/mcp-servers/web-search/package-lock.json b/mcp-servers/web-search/package-lock.json
index 16e02a0fa..bf892e16b 100644
--- a/mcp-servers/web-search/package-lock.json
+++ b/mcp-servers/web-search/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@clerum/web-search-mcp",
- "version": "1.0.5",
+ "version": "1.0.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@clerum/web-search-mcp",
- "version": "1.0.5",
+ "version": "1.0.6",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.12.1",
"express": "^4.21.2"
diff --git a/mcp-servers/web-search/package.json b/mcp-servers/web-search/package.json
index e3c96fa14..2ba276891 100644
--- a/mcp-servers/web-search/package.json
+++ b/mcp-servers/web-search/package.json
@@ -1,6 +1,6 @@
{
"name": "@clerum/web-search-mcp",
- "version": "1.0.5",
+ "version": "1.0.6",
"type": "module",
"main": "dist/index.js",
"scripts": {
diff --git a/mcp-servers/web-search/src/index.ts b/mcp-servers/web-search/src/index.ts
index dd89c8185..c6ba824b9 100644
--- a/mcp-servers/web-search/src/index.ts
+++ b/mcp-servers/web-search/src/index.ts
@@ -11,103 +11,99 @@
* - SEARCH_API_KEY: Brave Search API subscription token
* - PORT: HTTP port (default 3000)
*/
+import express, { Request, Response } from 'express'
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
+import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'
+import { randomUUID } from 'crypto'
+import { z } from 'zod'
-import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
-import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
-import express, { Request, Response } from "express";
-import { randomUUID } from "crypto";
-import { z } from "zod";
+const PORT = parseInt(process.env.PORT || '3000', 10)
+const SEARCH_API_KEY = process.env.SEARCH_API_KEY || ''
-const PORT = parseInt(process.env.PORT || "3000", 10);
-const SEARCH_API_KEY = process.env.SEARCH_API_KEY || "";
-
-const BRAVE_SEARCH_BASE = "https://api.search.brave.com/res/v1";
+const BRAVE_SEARCH_BASE = 'https://api.search.brave.com/res/v1'
// ---------------------------------------------------------------------------
// Brave Search API helpers
// ---------------------------------------------------------------------------
interface WebResult {
- title: string;
- url: string;
- snippet: string;
+ title: string
+ url: string
+ snippet: string
}
interface NewsResult {
- title: string;
- url: string;
- date: string;
- snippet: string;
+ title: string
+ url: string
+ date: string
+ snippet: string
}
-async function braveWebSearch(
- query: string,
- maxResults: number,
-): Promise<WebResult[]> {
+async function braveWebSearch(query: string, maxResults: number): Promise<WebResult[]> {
const params = new URLSearchParams({
q: query,
count: String(maxResults),
- });
+ })
const res = await fetch(`${BRAVE_SEARCH_BASE}/web/search?${params}`, {
headers: {
- Accept: "application/json",
- "X-Subscription-Token": SEARCH_API_KEY,
+ Accept: 'application/json',
+ 'X-Subscription-Token': SEARCH_API_KEY,
},
- });
+ })
if (!res.ok) {
- throw new Error(`Brave Search API error: ${res.status} ${res.statusText}`);
+ throw new Error(`Brave Search API error: ${res.status} ${res.statusText}`)
}
const data = (await res.json()) as {
- web?: { results?: Array<{ title: string; url: string; description: string }> };
- };
+ web?: { results?: Array<{ title: string; url: string; description: string }> }
+ }
- return (data.web?.results ?? []).slice(0, maxResults).map((r) => ({
+ return (data.web?.results ?? []).slice(0, maxResults).map(r => ({
title: r.title,
url: r.url,
snippet: r.description,
- }));
+ }))
}
async function braveNewsSearch(
query: string,
- freshness: "day" | "week" | "month",
- maxResults: number,
+ freshness: 'day' | 'week' | 'month',
+ maxResults: number
): Promise<NewsResult[]> {
const params = new URLSearchParams({
q: query,
count: String(maxResults),
freshness,
- });
+ })
const res = await fetch(`${BRAVE_SEARCH_BASE}/news/search?${params}`, {
headers: {
- Accept: "application/json",
- "X-Subscription-Token": SEARCH_API_KEY,
+ Accept: 'application/json',
+ 'X-Subscription-Token': SEARCH_API_KEY,
},
- });
+ })
if (!res.ok) {
- throw new Error(`Brave News API error: ${res.status} ${res.statusText}`);
+ throw new Error(`Brave News API error: ${res.status} ${res.statusText}`)
}
const data = (await res.json()) as {
results?: Array<{
- title: string;
- url: string;
- age: string;
- description: string;
- }>;
- };
-
- return (data.results ?? []).slice(0, maxResults).map((r) => ({
+ title: string
+ url: string
+ age: string
+ description: string
+ }>
+ }
+
+ return (data.results ?? []).slice(0, maxResults).map(r => ({
title: r.title,
url: r.url,
date: r.age,
snippet: r.description,
- }));
+ }))
}
// ---------------------------------------------------------------------------
@@ -116,9 +112,9 @@ async function braveNewsSearch(
function stripHtml(html: string): string {
return html
- .replace(/<[^>]*>/g, " ")
- .replace(/\s+/g, " ")
- .trim();
+ .replace(/<[^>]*>/g, ' ')
+ .replace(/\s+/g, ' ')
+ .trim()
}
// ---------------------------------------------------------------------------
@@ -127,17 +123,17 @@ function stripHtml(html: string): string {
function createMcpServer(): McpServer {
const server = new McpServer({
- name: "web-search",
- version: "1.0.0",
- });
+ name: 'web-search',
+ version: '1.0.0',
+ })
// -- Tool 1: web_search --------------------------------------------------
server.tool(
- "web_search",
- "Search the web using the Brave Search API. Returns titles, URLs, and snippets.",
+ 'web_search',
+ 'Search the web using the Brave Search API. Returns titles, URLs, and snippets.',
{
- query: z.string().describe("The search query"),
+ query: z.string().describe('The search query'),
maxResults: z
.number()
.int()
@@ -145,57 +141,57 @@ function createMcpServer(): McpServer {
.max(20)
.optional()
.default(5)
- .describe("Maximum number of results to return (default 5)"),
+ .describe('Maximum number of results to return (default 5)'),
},
async ({ query, maxResults }: { query: string; maxResults: number }) => {
if (!SEARCH_API_KEY) {
return {
content: [
{
- type: "text" as const,
+ type: 'text' as const,
text: JSON.stringify(
[
{
- title: "SEARCH_API_KEY not configured",
- url: "https://brave.com/search/api/",
+ title: 'SEARCH_API_KEY not configured',
+ url: 'https://brave.com/search/api/',
snippet:
- "Set the SEARCH_API_KEY environment variable with a valid Brave Search API subscription token to enable real web search.",
+ 'Set the SEARCH_API_KEY environment variable with a valid Brave Search API subscription token to enable real web search.',
},
],
null,
- 2,
+ 2
),
},
],
- };
+ }
}
try {
- const results = await braveWebSearch(query, maxResults);
+ const results = await braveWebSearch(query, maxResults)
return {
- content: [{ type: "text" as const, text: JSON.stringify(results, null, 2) }],
- };
+ content: [{ type: 'text' as const, text: JSON.stringify(results, null, 2) }],
+ }
} catch (err) {
return {
content: [
{
- type: "text" as const,
+ type: 'text' as const,
text: `Error performing web search: ${err instanceof Error ? err.message : String(err)}`,
},
],
isError: true,
- };
+ }
}
- },
- );
+ }
+ )
// -- Tool 2: fetch_page --------------------------------------------------
server.tool(
- "fetch_page",
- "Fetch a web page and return its text content with HTML tags stripped.",
+ 'fetch_page',
+ 'Fetch a web page and return its text content with HTML tags stripped.',
{
- url: z.string().url().describe("The URL to fetch"),
+ url: z.string().url().describe('The URL to fetch'),
maxChars: z
.number()
.int()
@@ -203,221 +199,212 @@ function createMcpServer(): McpServer {
.max(100000)
.optional()
.default(10000)
- .describe("Maximum characters to return (default 10000)"),
+ .describe('Maximum characters to return (default 10000)'),
},
async ({ url, maxChars }: { url: string; maxChars: number }) => {
try {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 15000);
+ const controller = new AbortController()
+ const timeout = setTimeout(() => controller.abort(), 15000)
const res = await fetch(url, {
headers: {
- "User-Agent":
- "Mozilla/5.0 (compatible; ClerumWebSearch/1.0; +https://clerum.io)",
- Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
+ 'User-Agent': 'Mozilla/5.0 (compatible; ClerumWebSearch/1.0; +https://clerum.io)',
+ Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
},
signal: controller.signal,
- redirect: "follow",
- });
+ redirect: 'follow',
+ })
- clearTimeout(timeout);
+ clearTimeout(timeout)
if (!res.ok) {
return {
content: [
{
- type: "text" as const,
+ type: 'text' as const,
text: `Error fetching page: HTTP ${res.status} ${res.statusText}`,
},
],
isError: true,
- };
+ }
}
- const html = await res.text();
+ const html = await res.text()
// Extract title from <title> tag
- const titleMatch = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
- const title = titleMatch ? stripHtml(titleMatch[1]) : "";
+ const titleMatch = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)
+ const title = titleMatch ? stripHtml(titleMatch[1]) : ''
// Strip HTML and truncate
- const content = stripHtml(html).slice(0, maxChars);
+ const content = stripHtml(html).slice(0, maxChars)
return {
content: [
{
- type: "text" as const,
+ type: 'text' as const,
text: JSON.stringify({ title, content }, null, 2),
},
],
- };
+ }
} catch (err) {
const message =
- err instanceof Error && err.name === "AbortError"
- ? "Request timed out after 15 seconds"
+ err instanceof Error && err.name === 'AbortError'
+ ? 'Request timed out after 15 seconds'
: err instanceof Error
? err.message
- : String(err);
+ : String(err)
return {
- content: [
- { type: "text" as const, text: `Error fetching page: ${message}` },
- ],
+ content: [{ type: 'text' as const, text: `Error fetching page: ${message}` }],
isError: true,
- };
+ }
}
- },
- );
+ }
+ )
// -- Tool 3: search_news -------------------------------------------------
server.tool(
- "search_news",
- "Search recent news using the Brave Search API. Returns titles, URLs, dates, and snippets.",
+ 'search_news',
+ 'Search recent news using the Brave Search API. Returns titles, URLs, dates, and snippets.',
{
- query: z.string().describe("The news search query"),
+ query: z.string().describe('The news search query'),
freshness: z
- .enum(["day", "week", "month"])
+ .enum(['day', 'week', 'month'])
.optional()
- .default("week")
+ .default('week')
.describe('How recent the news should be: "day", "week", or "month" (default "week")'),
},
- async ({
- query,
- freshness,
- }: {
- query: string;
- freshness: "day" | "week" | "month";
- }) => {
+ async ({ query, freshness }: { query: string; freshness: 'day' | 'week' | 'month' }) => {
if (!SEARCH_API_KEY) {
return {
content: [
{
- type: "text" as const,
+ type: 'text' as const,
text: JSON.stringify(
[
{
- title: "SEARCH_API_KEY not configured",
- url: "https://brave.com/search/api/",
- date: "N/A",
+ title: 'SEARCH_API_KEY not configured',
+ url: 'https://brave.com/search/api/',
+ date: 'N/A',
snippet:
- "Set the SEARCH_API_KEY environment variable with a valid Brave Search API subscription token to enable real news search.",
+ 'Set the SEARCH_API_KEY environment variable with a valid Brave Search API subscription token to enable real news search.',
},
],
null,
- 2,
+ 2
),
},
],
- };
+ }
}
try {
- const results = await braveNewsSearch(query, freshness, 10);
+ const results = await braveNewsSearch(query, freshness, 10)
return {
- content: [{ type: "text" as const, text: JSON.stringify(results, null, 2) }],
- };
+ content: [{ type: 'text' as const, text: JSON.stringify(results, null, 2) }],
+ }
} catch (err) {
return {
content: [
{
- type: "text" as const,
+ type: 'text' as const,
text: `Error performing news search: ${err instanceof Error ? err.message : String(err)}`,
},
],
isError: true,
- };
+ }
}
- },
- );
+ }
+ )
- return server;
+ return server
}
// ---------------------------------------------------------------------------
// Express + StreamableHTTP Transport
// ---------------------------------------------------------------------------
-const app = express();
+const app = express()
-const transports = new Map<string, StreamableHTTPServerTransport>();
+const transports = new Map<string, StreamableHTTPServerTransport>()
// Health endpoint
-app.get("/health", (_req: Request, res: Response) => {
+app.get('/health', (_req: Request, res: Response) => {
res.json({
- status: "ok",
- tools: ["web_search", "fetch_page", "search_news"],
+ status: 'ok',
+ tools: ['web_search', 'fetch_page', 'search_news'],
searchApiConfigured: !!SEARCH_API_KEY,
- });
-});
+ })
+})
// MCP StreamableHTTP endpoint
-app.post("/mcp", async (req: Request, res: Response) => {
+app.post('/mcp', async (req: Request, res: Response) => {
try {
- const sessionId = req.headers["mcp-session-id"] as string | undefined;
+ const sessionId = req.headers['mcp-session-id'] as string | undefined
// Existing session
if (sessionId && transports.has(sessionId)) {
- const transport = transports.get(sessionId)!;
- await transport.handleRequest(req, res);
- return;
+ const transport = transports.get(sessionId)!
+ await transport.handleRequest(req, res)
+ return
}
// New session (initialize)
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: () => randomUUID(),
- });
+ })
- const server = createMcpServer();
- await server.connect(transport);
+ const server = createMcpServer()
+ await server.connect(transport)
- await transport.handleRequest(req, res);
+ await transport.handleRequest(req, res)
- const assignedSessionId = (transport as any).sessionId as string | undefined;
+ const assignedSessionId = (transport as any).sessionId as string | undefined
if (assignedSessionId) {
- transports.set(assignedSessionId, transport);
- console.log(`[WebSearch] New session: ${assignedSessionId}`);
+ transports.set(assignedSessionId, transport)
+ console.log(`[WebSearch] New session: ${assignedSessionId}`)
}
transport.onclose = () => {
if (assignedSessionId) {
- transports.delete(assignedSessionId);
- console.log(`[WebSearch] Session closed: ${assignedSessionId}`);
+ transports.delete(assignedSessionId)
+ console.log(`[WebSearch] Session closed: ${assignedSessionId}`)
}
- };
+ }
} catch (err) {
- console.error("[WebSearch] Error handling MCP request:", err);
+ console.error('[WebSearch] Error handling MCP request:', err)
if (!res.headersSent) {
- res.status(500).json({ error: String(err) });
+ res.status(500).json({ error: String(err) })
}
}
-});
+})
// GET /mcp for SSE session resumption
-app.get("/mcp", async (req: Request, res: Response) => {
- const sessionId = req.headers["mcp-session-id"] as string | undefined;
+app.get('/mcp', async (req: Request, res: Response) => {
+ const sessionId = req.headers['mcp-session-id'] as string | undefined
if (sessionId && transports.has(sessionId)) {
- const transport = transports.get(sessionId)!;
- await transport.handleRequest(req, res);
- return;
+ const transport = transports.get(sessionId)!
+ await transport.handleRequest(req, res)
+ return
}
- res.status(400).json({ error: "Bad request — send POST to initialize" });
-});
+ res.status(400).json({ error: 'Bad request — send POST to initialize' })
+})
// DELETE /mcp to close a session
-app.delete("/mcp", async (req: Request, res: Response) => {
- const sessionId = req.headers["mcp-session-id"] as string | undefined;
+app.delete('/mcp', async (req: Request, res: Response) => {
+ const sessionId = req.headers['mcp-session-id'] as string | undefined
if (sessionId && transports.has(sessionId)) {
- const transport = transports.get(sessionId)!;
- await transport.handleRequest(req, res);
- return;
+ const transport = transports.get(sessionId)!
+ await transport.handleRequest(req, res)
+ return
}
- res.status(400).json({ error: "No active session to close" });
-});
+ res.status(400).json({ error: 'No active session to close' })
+})
-app.listen(PORT, "0.0.0.0", () => {
- console.log(`[WebSearch] StreamableHTTP MCP server listening on port ${PORT}`);
+app.listen(PORT, '0.0.0.0', () => {
+ console.log(`[WebSearch] StreamableHTTP MCP server listening on port ${PORT}`)
console.log(
- `[WebSearch] Brave Search API: ${SEARCH_API_KEY ? "configured" : "NOT configured (mock responses enabled)"}`,
- );
-});
+ `[WebSearch] Brave Search API: ${SEARCH_API_KEY ? 'configured' : 'NOT configured (mock responses enabled)'}`
+ )
+})
diff --git a/packages/workflow-sdk/README.md b/packages/workflow-sdk/README.md
index b818b2fd0..ff32c35ff 100644
--- a/packages/workflow-sdk/README.md
+++ b/packages/workflow-sdk/README.md
@@ -82,7 +82,7 @@ stubbed in — replace `runStep` with your own logic).
```ts
// coordinator.ts
-import { WorkflowSDK, emitLog, type StepSpec } from '@clerum/workflow-sdk'
+import { type StepSpec, WorkflowSDK, emitLog } from '@clerum/workflow-sdk'
async function runStep(step: StepSpec): Promise<unknown> {
// Your deterministic business logic, or delegate agentic work to
@@ -158,28 +158,28 @@ if (result.status === 'failed') {
## Public API reference
-| Export | Kind | Purpose |
-| --- | --- | --- |
-| `WorkflowSDK` | class | Top-level façade; `static fromEnvironment()` builds and wires everything. |
-| `WorkflowSDK.fromEnvironment()` | static method | `Promise<WorkflowSDK>` — the single init call. |
-| `sdk.config` (`ConfigLoader`) | class | Loads config from env; `getConfig()`, `getSpec()`. |
-| `sdk.coordinator` (`StepCoordinator`) | class | `resolveOrder()`, `injectSignal()`, `runWorkflow()`. |
-| `sdk.status` (`StatusReporter`) | class | `reportStepStatus()`, `reportWorkflowStatus()`, `getWorkflowStatus()`. |
-| `sdk.signals` (`SignalPoller`) | class | `pollSignals()`, `pushSignal()`, `hasSignal()`, `consumeSignal()`, `stop()`. |
-| `sdk.mcpHost` / `requireMcpHost()` (`McpHostClient`) | class | `executeAgentStep()`, `healthCheck()`. |
-| `updatePhase()` / `updateStepState()` / `shutdown()` | methods | Mirror local REST state; graceful teardown. |
-| `renderPrompt()` | function | Interpolates `{{...}}` placeholders in a prompt template. |
-| `loadSoul()` | function | Reads a `SOUL.md` artifact from `/etc/workflow/souls` (path-traversal guarded). |
-| `requestModelInjection()` | function | POSTs a `{stepId, provider, model}` model binding to WRC. |
-| `createFileRuntimeTokenProvider()` / `createStaticRuntimeTokenProvider()` / `requireRuntimeToken()` | functions | Build / resolve runtime token providers. |
-| `withRetry()` / `computeBackoff()` | functions | Retry helper and exponential backoff (capped at 300s). |
-| `emitLog()` / `initLogger()` | functions | Structured JSON logging to stdout. |
-| `createServer()` / `start()` / `stop()` / `safeEqual()` | functions | REST server helpers (health/status/signal routes; constant-time compare). |
-| `WorkflowSDKInitError` / `CycleDetectedError` / `McpHostNotConfiguredError` | error classes | Init, DAG-cycle, and unconfigured-mcp-host failures. |
-| `RegistryClient` and registry types | interfaces/types | Registry connection contract (defined in this package). |
-| Config/spec types | types | `WorkflowConfig`, `WorkflowRecipeSpec`, `StepSpec`, `AgentSpec`, `ToolScope`, `PromptSpec`, `WorkflowPhase`, `StepPhase`, `Signal`. |
-| mcp-host types | types | `AgentStepRequest`, `AgentStepResult`, `StepMcpServerRef`, `AllowedToolsConfig`. |
-| Misc types | types | `StepContext`, `StepExecutor`, `WorkflowStateRef`, `RetryOptions`, `PromptContext`, `SignalCallback`, `RuntimeTokenProvider`. |
+| Export | Kind | Purpose |
+| --------------------------------------------------------------------------------------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
+| `WorkflowSDK` | class | Top-level façade; `static fromEnvironment()` builds and wires everything. |
+| `WorkflowSDK.fromEnvironment()` | static method | `Promise<WorkflowSDK>` — the single init call. |
+| `sdk.config` (`ConfigLoader`) | class | Loads config from env; `getConfig()`, `getSpec()`. |
+| `sdk.coordinator` (`StepCoordinator`) | class | `resolveOrder()`, `injectSignal()`, `runWorkflow()`. |
+| `sdk.status` (`StatusReporter`) | class | `reportStepStatus()`, `reportWorkflowStatus()`, `getWorkflowStatus()`. |
+| `sdk.signals` (`SignalPoller`) | class | `pollSignals()`, `pushSignal()`, `hasSignal()`, `consumeSignal()`, `stop()`. |
+| `sdk.mcpHost` / `requireMcpHost()` (`McpHostClient`) | class | `executeAgentStep()`, `healthCheck()`. |
+| `updatePhase()` / `updateStepState()` / `shutdown()` | methods | Mirror local REST state; graceful teardown. |
+| `renderPrompt()` | function | Interpolates `{{...}}` placeholders in a prompt template. |
+| `loadSoul()` | function | Reads a `SOUL.md` artifact from `/etc/workflow/souls` (path-traversal guarded). |
+| `requestModelInjection()` | function | POSTs a `{stepId, provider, model}` model binding to WRC. |
+| `createFileRuntimeTokenProvider()` / `createStaticRuntimeTokenProvider()` / `requireRuntimeToken()` | functions | Build / resolve runtime token providers. |
+| `withRetry()` / `computeBackoff()` | functions | Retry helper and exponential backoff (capped at 300s). |
+| `emitLog()` / `initLogger()` | functions | Structured JSON logging to stdout. |
+| `createServer()` / `start()` / `stop()` / `safeEqual()` | functions | REST server helpers (health/status/signal routes; constant-time compare). |
+| `WorkflowSDKInitError` / `CycleDetectedError` / `McpHostNotConfiguredError` | error classes | Init, DAG-cycle, and unconfigured-mcp-host failures. |
+| `RegistryClient` and registry types | interfaces/types | Registry connection contract (defined in this package). |
+| Config/spec types | types | `WorkflowConfig`, `WorkflowRecipeSpec`, `StepSpec`, `AgentSpec`, `ToolScope`, `PromptSpec`, `WorkflowPhase`, `StepPhase`, `Signal`. |
+| mcp-host types | types | `AgentStepRequest`, `AgentStepResult`, `StepMcpServerRef`, `AllowedToolsConfig`. |
+| Misc types | types | `StepContext`, `StepExecutor`, `WorkflowStateRef`, `RetryOptions`, `PromptContext`, `SignalCallback`, `RuntimeTokenProvider`. |
## Building a coordinator image
diff --git a/packages/workflow-sdk/package-lock.json b/packages/workflow-sdk/package-lock.json
index 63904e765..2364371c0 100644
--- a/packages/workflow-sdk/package-lock.json
+++ b/packages/workflow-sdk/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@clerum/workflow-sdk",
- "version": "1.0.29-beta.0",
+ "version": "1.0.30-beta.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@clerum/workflow-sdk",
- "version": "1.0.29-beta.0",
+ "version": "1.0.30-beta.0",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@clerum/workflow-runtime-core": "file:../workflow-runtime-core"
diff --git a/packages/workflow-sdk/package.json b/packages/workflow-sdk/package.json
index 0b816e3b8..49cc03aab 100644
--- a/packages/workflow-sdk/package.json
+++ b/packages/workflow-sdk/package.json
@@ -1,6 +1,6 @@
{
"name": "@clerum/workflow-sdk",
- "version": "1.0.29-beta.0",
+ "version": "1.0.30-beta.0",
"description": "Clerum Workflow SDK — TypeScript library for workflow coordinator Pods",
"main": "dist/index.js",
"types": "dist/index.d.ts",
diff --git a/packages/workflow-sdk/vitest.config.ts b/packages/workflow-sdk/vitest.config.ts
index 1ef805c50..2fe3fcfe9 100644
--- a/packages/workflow-sdk/vitest.config.ts
+++ b/packages/workflow-sdk/vitest.config.ts
@@ -1,10 +1,10 @@
-import { defineConfig } from "vitest/config";
+import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
globals: false,
- environment: "node",
- include: ["tests/**/*.test.ts"],
- exclude: ["node_modules/**", "dist/**"],
+ environment: 'node',
+ include: ['tests/**/*.test.ts'],
+ exclude: ['node_modules/**', 'dist/**'],
},
-});
+})
diff --git a/profile-ui/package-lock.json b/profile-ui/package-lock.json
index fd3ab49e8..5ce0f97a9 100644
--- a/profile-ui/package-lock.json
+++ b/profile-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-profile-ui",
- "version": "0.1.117",
+ "version": "0.1.118",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-profile-ui",
- "version": "0.1.117",
+ "version": "0.1.118",
"dependencies": {
"@clerum/desktop-app-links": "file:../packages/desktop-app-links",
"next": "16.2.11",
diff --git a/profile-ui/package.json b/profile-ui/package.json
index c12958d9a..9d32f672b 100644
--- a/profile-ui/package.json
+++ b/profile-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-profile-ui",
- "version": "0.1.117",
+ "version": "0.1.118",
"private": true,
"scripts": {
"dev": "next dev",
diff --git a/profile-ui/test/profileSettings.test.ts b/profile-ui/test/profileSettings.test.ts
index 7d927608d..210f29405 100644
--- a/profile-ui/test/profileSettings.test.ts
+++ b/profile-ui/test/profileSettings.test.ts
@@ -27,7 +27,10 @@ test('normalizeProfileChannels fills missing social network keys', () => {
})
test('uniqueTrimmed removes blanks and exact duplicates while preserving order', () => {
- assert.deepEqual(uniqueTrimmed([' @testuser ', '', '@testuser', '@other']), ['@testuser', '@other'])
+ assert.deepEqual(uniqueTrimmed([' @testuser ', '', '@testuser', '@other']), [
+ '@testuser',
+ '@other',
+ ])
})
test('normalizeProfileChannels stores Telegram handles with @ prefix', () => {
diff --git a/rpc-proxy/README.md b/rpc-proxy/README.md
index ef5bdddf7..e05b33961 100644
--- a/rpc-proxy/README.md
+++ b/rpc-proxy/README.md
@@ -40,16 +40,17 @@ External-facing user-scoped JSON-RPC proxy for MCP servers and MCP hosts.
Host runtime routes in `rpc-proxy` are REST-oriented and scope-specific. The status stream is a read-only telemetry channel.
-| Endpoint | Method | Required Scope | Access Type | Transport |
-| --- | --- | --- | --- | --- |
-| `/api/v1/rpc/hosts/:hostRef/messages` | `POST` | `host:message:invoke` | Write | REST |
-| `/api/v1/rpc/hosts/:hostRef/activity` | `GET` | `host:activity:read` | Read | REST |
-| `/api/v1/rpc/hosts/:hostRef/activity/stream` | `GET` | `host:activity:read` | Read-only | SSE |
-| `/api/v1/rpc/hosts/:hostRef/status` | `GET` | `host:status:read` | Read | REST |
-| `/api/v1/rpc/hosts/:hostRef/health` | `GET` | `host:health:read` | Read | REST |
-| `/api/v1/rpc/hosts/:hostRef/status/stream` | `GET` | `host:status:read` | Read-only | SSE |
+| Endpoint | Method | Required Scope | Access Type | Transport |
+| -------------------------------------------- | ------ | --------------------- | ----------- | --------- |
+| `/api/v1/rpc/hosts/:hostRef/messages` | `POST` | `host:message:invoke` | Write | REST |
+| `/api/v1/rpc/hosts/:hostRef/activity` | `GET` | `host:activity:read` | Read | REST |
+| `/api/v1/rpc/hosts/:hostRef/activity/stream` | `GET` | `host:activity:read` | Read-only | SSE |
+| `/api/v1/rpc/hosts/:hostRef/status` | `GET` | `host:status:read` | Read | REST |
+| `/api/v1/rpc/hosts/:hostRef/health` | `GET` | `host:health:read` | Read | REST |
+| `/api/v1/rpc/hosts/:hostRef/status/stream` | `GET` | `host:status:read` | Read-only | SSE |
Notes:
+
- `status/stream` does not accept request bodies and must not be used for message submission.
- `activity/stream` is read-only telemetry and never accepts message submission payloads.
- `activity` and `activity/stream` never include chain-of-thought/internal reasoning text.
@@ -126,6 +127,7 @@ Critical variables:
- `RPC_PROXY_CONTROL_API_CACHE_TTL_MS`
Required in production:
+
- `RPC_PROXY_CONTROL_API_SERVICE_TOKEN`
`RPC_PROXY_JWT_PUBLIC_KEY` must match the public key for `CONTROL_API_RPC_JWT_PRIVATE_KEY`.
diff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.json
index fae2c8dd2..26bef05e7 100644
--- a/rpc-proxy/package-lock.json
+++ b/rpc-proxy/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.51",
+ "version": "0.1.52",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-rpc-proxy",
- "version": "0.1.51",
+ "version": "0.1.52",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/rpc-proxy/package.json b/rpc-proxy/package.json
index 93641a581..d0951fe4e 100644
--- a/rpc-proxy/package.json
+++ b/rpc-proxy/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.51",
+ "version": "0.1.52",
"description": "External-facing RPC proxy for tenant-scoped MCP access",
"main": "dist/main.js",
"engines": {
diff --git a/rpc-proxy/src/routes/health.ts b/rpc-proxy/src/routes/health.ts
index 6d72149b5..49cc0c87c 100644
--- a/rpc-proxy/src/routes/health.ts
+++ b/rpc-proxy/src/routes/health.ts
@@ -1,9 +1,9 @@
-import { Router } from "express";
+import { Router } from 'express'
export function createHealthRouter(): Router {
- const router = Router();
- router.get("/health", (_req, res) => {
- res.status(200).json({ status: "ok" });
- });
- return router;
+ const router = Router()
+ router.get('/health', (_req, res) => {
+ res.status(200).json({ status: 'ok' })
+ })
+ return router
}
diff --git a/rpc-proxy/src/routes/sandboxUi.test.ts b/rpc-proxy/src/routes/sandboxUi.test.ts
index f6aa82338..d74d76b31 100644
--- a/rpc-proxy/src/routes/sandboxUi.test.ts
+++ b/rpc-proxy/src/routes/sandboxUi.test.ts
@@ -365,9 +365,11 @@ describe('POST /api/v1/sandbox-ui/:ns/:name/oauth/authorize-url', () => {
})
it('includes background:true in the control-api payload when the body sets it', async () => {
- fetchSpy.mockResolvedValueOnce(jsonResponse(200, REGISTRY_OK)).mockResolvedValueOnce(
- jsonResponse(200, { authorizeUrl: 'https://accounts.google.com/oauth?...' })
- )
+ fetchSpy
+ .mockResolvedValueOnce(jsonResponse(200, REGISTRY_OK))
+ .mockResolvedValueOnce(
+ jsonResponse(200, { authorizeUrl: 'https://accounts.google.com/oauth?...' })
+ )
await request(makeApp())
.post('/api/v1/sandbox-ui/sandbox-recipes/r1/oauth/authorize-url')
@@ -384,9 +386,11 @@ describe('POST /api/v1/sandbox-ui/:ns/:name/oauth/authorize-url', () => {
})
it('includes background:false in the control-api payload when background is omitted', async () => {
- fetchSpy.mockResolvedValueOnce(jsonResponse(200, REGISTRY_OK)).mockResolvedValueOnce(
- jsonResponse(200, { authorizeUrl: 'https://accounts.google.com/oauth?...' })
- )
+ fetchSpy
+ .mockResolvedValueOnce(jsonResponse(200, REGISTRY_OK))
+ .mockResolvedValueOnce(
+ jsonResponse(200, { authorizeUrl: 'https://accounts.google.com/oauth?...' })
+ )
await request(makeApp())
.post('/api/v1/sandbox-ui/sandbox-recipes/r1/oauth/authorize-url')
diff --git a/rpc-proxy/src/routes/sandboxUi.ts b/rpc-proxy/src/routes/sandboxUi.ts
index 717bde50a..a2f6b442e 100644
--- a/rpc-proxy/src/routes/sandboxUi.ts
+++ b/rpc-proxy/src/routes/sandboxUi.ts
@@ -359,7 +359,7 @@ export function createSandboxUiSessionRouter(): Router {
recipeNs,
recipeName,
oauthClientId,
- userId, // from req.auth.sub — never the body
+ userId, // from req.auth.sub — never the body
redirectUri,
background,
}),
diff --git a/rpc-proxy/test/routes.rpcHostActivityStream.test.ts b/rpc-proxy/test/routes.rpcHostActivityStream.test.ts
index ebfb87eb1..531a92ac1 100644
--- a/rpc-proxy/test/routes.rpcHostActivityStream.test.ts
+++ b/rpc-proxy/test/routes.rpcHostActivityStream.test.ts
@@ -1,20 +1,19 @@
-import express from "express";
-import request from "supertest";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+import { config } from '../src/config.js'
+import { createRpcHostActivityStreamRouter } from '../src/routes/rpcHostActivityStream.js'
const authTokenMock = vi.hoisted(() => ({
- verifyRpcToken: vi.fn()
-}));
+ verifyRpcToken: vi.fn(),
+}))
const serviceMock = vi.hoisted(() => ({
- resolveHostConnectionForUser: vi.fn()
-}));
+ resolveHostConnectionForUser: vi.fn(),
+}))
-vi.mock("../src/authToken.js", () => authTokenMock);
-vi.mock("../src/services/mcpProxyService.js", () => serviceMock);
-
-import { config } from "../src/config.js";
-import { createRpcHostActivityStreamRouter } from "../src/routes/rpcHostActivityStream.js";
+vi.mock('../src/authToken.js', () => authTokenMock)
+vi.mock('../src/services/mcpProxyService.js', () => serviceMock)
const defaultConfig = {
activityStreamMaxConcurrent: config.activityStreamMaxConcurrent,
@@ -22,148 +21,163 @@ const defaultConfig = {
activityStreamMaxPerUserHost: config.activityStreamMaxPerUserHost,
activityStreamMaxLifetimeMs: config.activityStreamMaxLifetimeMs,
activityStreamKeepaliveMs: config.activityStreamKeepaliveMs,
- activityStreamIdleTimeoutMs: config.activityStreamIdleTimeoutMs
-};
+ activityStreamIdleTimeoutMs: config.activityStreamIdleTimeoutMs,
+}
function makeApp() {
- const app = express();
- app.use(createRpcHostActivityStreamRouter());
- return app;
+ const app = express()
+ app.use(createRpcHostActivityStreamRouter())
+ return app
}
-describe("routes/rpcHostActivityStream", () => {
+describe('routes/rpcHostActivityStream', () => {
beforeEach(() => {
- authTokenMock.verifyRpcToken.mockReset();
- serviceMock.resolveHostConnectionForUser.mockReset();
- Object.assign(config, defaultConfig);
- vi.restoreAllMocks();
- });
+ authTokenMock.verifyRpcToken.mockReset()
+ serviceMock.resolveHostConnectionForUser.mockReset()
+ Object.assign(config, defaultConfig)
+ vi.restoreAllMocks()
+ })
- it("returns 401 without token", async () => {
- const app = makeApp();
- await request(app).get("/rpc/hosts/agent2/activity/stream").expect(401);
- });
+ it('returns 401 without token', async () => {
+ const app = makeApp()
+ await request(app).get('/rpc/hosts/agent2/activity/stream').expect(401)
+ })
- it("returns 403 without host:activity:read scope", async () => {
+ it('returns 403 without host:activity:read scope', async () => {
authTokenMock.verifyRpcToken.mockReturnValue({
- sub: "user-1",
- typ: "user",
- teamId: "team-1",
- scopes: ["host:status:read"],
- hostRefs: ["agent2"],
- jti: "j1",
+ sub: 'user-1',
+ typ: 'user',
+ teamId: 'team-1',
+ scopes: ['host:status:read'],
+ hostRefs: ['agent2'],
+ jti: 'j1',
iat: 1,
- exp: 9999999999
- });
- const app = makeApp();
- await request(app).get("/rpc/hosts/agent2/activity/stream").set("authorization", "Bearer token").expect(403);
- });
+ exp: 9999999999,
+ })
+ const app = makeApp()
+ await request(app)
+ .get('/rpc/hosts/agent2/activity/stream')
+ .set('authorization', 'Bearer token')
+ .expect(403)
+ })
- it("returns 403 for unauthorized host", async () => {
+ it('returns 403 for unauthorized host', async () => {
authTokenMock.verifyRpcToken.mockReturnValue({
- sub: "user-1",
- typ: "user",
- teamId: "team-1",
- scopes: ["host:activity:read"],
- hostRefs: ["agent2"],
- jti: "j1",
+ sub: 'user-1',
+ typ: 'user',
+ teamId: 'team-1',
+ scopes: ['host:activity:read'],
+ hostRefs: ['agent2'],
+ jti: 'j1',
iat: 1,
- exp: 9999999999
- });
- serviceMock.resolveHostConnectionForUser.mockResolvedValue(null);
- const app = makeApp();
- await request(app).get("/rpc/hosts/nope/activity/stream").set("authorization", "Bearer token").expect(403);
- });
+ exp: 9999999999,
+ })
+ serviceMock.resolveHostConnectionForUser.mockResolvedValue(null)
+ const app = makeApp()
+ await request(app)
+ .get('/rpc/hosts/nope/activity/stream')
+ .set('authorization', 'Bearer token')
+ .expect(403)
+ })
- it("returns 429 when stream limits are exceeded", async () => {
- config.activityStreamMaxConcurrent = 0;
+ it('returns 429 when stream limits are exceeded', async () => {
+ config.activityStreamMaxConcurrent = 0
authTokenMock.verifyRpcToken.mockReturnValue({
- sub: "user-1",
- typ: "user",
- teamId: "team-1",
- scopes: ["host:activity:read"],
- hostRefs: ["agent2"],
- jti: "j1",
+ sub: 'user-1',
+ typ: 'user',
+ teamId: 'team-1',
+ scopes: ['host:activity:read'],
+ hostRefs: ['agent2'],
+ jti: 'j1',
iat: 1,
- exp: 9999999999
- });
+ exp: 9999999999,
+ })
serviceMock.resolveHostConnectionForUser.mockResolvedValue({
- name: "agent2",
- url: "http://host.local",
- headers: {}
- });
- const app = makeApp();
- await request(app).get("/rpc/hosts/agent2/activity/stream").set("authorization", "Bearer token").expect(429);
- });
+ name: 'agent2',
+ url: 'http://host.local',
+ headers: {},
+ })
+ const app = makeApp()
+ await request(app)
+ .get('/rpc/hosts/agent2/activity/stream')
+ .set('authorization', 'Bearer token')
+ .expect(429)
+ })
- it("emits only allowed event names and sanitizes upstream errors", async () => {
- config.activityStreamMaxLifetimeMs = 25;
- config.activityStreamKeepaliveMs = 5;
- config.activityStreamIdleTimeoutMs = 100;
+ it('emits only allowed event names and sanitizes upstream errors', async () => {
+ config.activityStreamMaxLifetimeMs = 25
+ config.activityStreamKeepaliveMs = 5
+ config.activityStreamIdleTimeoutMs = 100
authTokenMock.verifyRpcToken.mockReturnValue({
- sub: "user-1",
- typ: "user",
- teamId: "team-1",
- scopes: ["host:activity:read"],
- hostRefs: ["agent2"],
- jti: "j1",
+ sub: 'user-1',
+ typ: 'user',
+ teamId: 'team-1',
+ scopes: ['host:activity:read'],
+ hostRefs: ['agent2'],
+ jti: 'j1',
iat: 1,
- exp: 9999999999
- });
+ exp: 9999999999,
+ })
serviceMock.resolveHostConnectionForUser.mockResolvedValue({
- name: "agent2",
- url: "http://host.local",
- headers: {}
- });
+ name: 'agent2',
+ url: 'http://host.local',
+ headers: {},
+ })
const streamPayload = [
- "event: open",
- `data: ${JSON.stringify({ hostRef: "agent2", observedAt: new Date().toISOString() })}`,
- "",
- "event: activity",
+ 'event: open',
+ `data: ${JSON.stringify({ hostRef: 'agent2', observedAt: new Date().toISOString() })}`,
+ '',
+ 'event: activity',
`data: ${JSON.stringify({
- version: "1.0",
- eventId: "evt_1",
- hostRef: "agent2",
+ version: '1.0',
+ eventId: 'evt_1',
+ hostRef: 'agent2',
ts: new Date().toISOString(),
- type: "task.started",
- title: "started",
- severity: "info",
+ type: 'task.started',
+ title: 'started',
+ severity: 'info',
meta: {},
- redactions: []
+ redactions: [],
})}`,
- "",
- "event: message",
- `data: ${JSON.stringify({ should: "be ignored" })}`,
- "",
- "event: error",
- `data: ${JSON.stringify({ message: "http://internal.local/secret-token" })}`,
- "",
- "event: closed",
- `data: ${JSON.stringify({ reason: "done" })}`,
- ""
- ].join("\n");
+ '',
+ 'event: message',
+ `data: ${JSON.stringify({ should: 'be ignored' })}`,
+ '',
+ 'event: error',
+ `data: ${JSON.stringify({ message: 'http://internal.local/secret-token' })}`,
+ '',
+ 'event: closed',
+ `data: ${JSON.stringify({ reason: 'done' })}`,
+ '',
+ ].join('\n')
- vi.spyOn(globalThis, "fetch").mockResolvedValue(
- new Response(new ReadableStream({
- start(controller) {
- controller.enqueue(new TextEncoder().encode(streamPayload));
- controller.close();
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ new Response(
+ new ReadableStream({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode(streamPayload))
+ controller.close()
+ },
+ }),
+ {
+ status: 200,
+ headers: { 'content-type': 'text/event-stream' },
}
- }), {
- status: 200,
- headers: { "content-type": "text/event-stream" }
- })
- );
+ )
+ )
- const app = makeApp();
- const response = await request(app).get("/rpc/hosts/agent2/activity/stream").set("authorization", "Bearer token").expect(200);
- expect(response.text).toContain("event: open");
- expect(response.text).toContain("event: activity");
- expect(response.text).toContain("event: error");
- expect(response.text).toContain("Activity temporarily unavailable");
- expect(response.text).toContain("event: closed");
- expect(response.text).not.toContain("event: message");
- expect(response.text).not.toContain("internal.local");
- expect(response.text).not.toContain("secret-token");
- });
-});
+ const app = makeApp()
+ const response = await request(app)
+ .get('/rpc/hosts/agent2/activity/stream')
+ .set('authorization', 'Bearer token')
+ .expect(200)
+ expect(response.text).toContain('event: open')
+ expect(response.text).toContain('event: activity')
+ expect(response.text).toContain('event: error')
+ expect(response.text).toContain('Activity temporarily unavailable')
+ expect(response.text).toContain('event: closed')
+ expect(response.text).not.toContain('event: message')
+ expect(response.text).not.toContain('internal.local')
+ expect(response.text).not.toContain('secret-token')
+ })
+})
diff --git a/rpc-proxy/vitest.config.ts b/rpc-proxy/vitest.config.ts
index 37b473f54..8141ade9e 100644
--- a/rpc-proxy/vitest.config.ts
+++ b/rpc-proxy/vitest.config.ts
@@ -1,8 +1,8 @@
-import { defineConfig } from "vitest/config";
+import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
- include: ["src/**/*.test.ts", "src/**/__tests__/**/*.ts", "test/**/*.test.ts"],
- exclude: ["dist/**", "node_modules/**"],
+ include: ['src/**/*.test.ts', 'src/**/__tests__/**/*.ts', 'test/**/*.test.ts'],
+ exclude: ['dist/**', 'node_modules/**'],
},
-});
+})
diff --git a/stdio-bridge/README.md b/stdio-bridge/README.md
index c2d9eeeb5..52e2b093d 100644
--- a/stdio-bridge/README.md
+++ b/stdio-bridge/README.md
@@ -32,17 +32,17 @@ caller
## Environment Variables
-| Variable | Default | Description |
-|----------|---------|-------------|
-| `STDIO_COMMAND` | *(required)* | Command to spawn (e.g., `node`, `npx`) |
-| `STDIO_ARGS` | `[]` | JSON array of arguments (e.g., `["dist/index.js"]`) |
-| `BRIDGE_PORT` | `3000` | HTTP listen port |
-| `BRIDGE_HEALTH_PATH` | `/health` | Health endpoint path |
-| `STDIO_RESTART_MAX` | `3` | Max auto-restart attempts |
-| `STDIO_RESTART_DELAY` | `5000` | Base restart delay (ms) |
-| `STDIO_INIT_TIMEOUT` | `30000` | Process init timeout (ms) |
-| `STDIO_SHUTDOWN_TIMEOUT` | `10000` | Graceful shutdown timeout (ms) |
-| `LOG_LEVEL` | `info` | Log verbosity |
+| Variable | Default | Description |
+| ------------------------ | ------------ | --------------------------------------------------- |
+| `STDIO_COMMAND` | _(required)_ | Command to spawn (e.g., `node`, `npx`) |
+| `STDIO_ARGS` | `[]` | JSON array of arguments (e.g., `["dist/index.js"]`) |
+| `BRIDGE_PORT` | `3000` | HTTP listen port |
+| `BRIDGE_HEALTH_PATH` | `/health` | Health endpoint path |
+| `STDIO_RESTART_MAX` | `3` | Max auto-restart attempts |
+| `STDIO_RESTART_DELAY` | `5000` | Base restart delay (ms) |
+| `STDIO_INIT_TIMEOUT` | `30000` | Process init timeout (ms) |
+| `STDIO_SHUTDOWN_TIMEOUT` | `10000` | Graceful shutdown timeout (ms) |
+| `LOG_LEVEL` | `info` | Log verbosity |
## Local Development
diff --git a/stdio-bridge/package-lock.json b/stdio-bridge/package-lock.json
index 9ebf54ce4..1fd9d6365 100644
--- a/stdio-bridge/package-lock.json
+++ b/stdio-bridge/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-stdio-bridge",
- "version": "0.1.6",
+ "version": "0.1.7",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-stdio-bridge",
- "version": "0.1.6",
+ "version": "0.1.7",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.0.0"
diff --git a/stdio-bridge/package.json b/stdio-bridge/package.json
index b6989eb48..7e97a355c 100644
--- a/stdio-bridge/package.json
+++ b/stdio-bridge/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-stdio-bridge",
- "version": "0.1.6",
+ "version": "0.1.7",
"description": "stdio-to-StreamableHTTP bridge sidecar for MCP servers",
"main": "dist/main.js",
"engines": {
diff --git a/stdio-bridge/src/main.ts b/stdio-bridge/src/main.ts
index 1a716543c..834ef32f4 100644
--- a/stdio-bridge/src/main.ts
+++ b/stdio-bridge/src/main.ts
@@ -1,24 +1,24 @@
-import { loadConfig } from "./types";
-import { StdioBridge } from "./bridge";
+import { StdioBridge } from './bridge'
+import { loadConfig } from './types'
async function main(): Promise<void> {
- const config = loadConfig();
- console.log(`[stdio-bridge] Starting: ${config.command} ${config.args.join(" ")}`);
+ const config = loadConfig()
+ console.log(`[stdio-bridge] Starting: ${config.command} ${config.args.join(' ')}`)
- const bridge = new StdioBridge(config);
- await bridge.start();
+ const bridge = new StdioBridge(config)
+ await bridge.start()
const shutdown = async (signal: string) => {
- console.log(`[stdio-bridge] ${signal} received`);
- await bridge.stop();
- process.exit(0);
- };
+ console.log(`[stdio-bridge] ${signal} received`)
+ await bridge.stop()
+ process.exit(0)
+ }
- process.on("SIGTERM", () => shutdown("SIGTERM"));
- process.on("SIGINT", () => shutdown("SIGINT"));
+ process.on('SIGTERM', () => shutdown('SIGTERM'))
+ process.on('SIGINT', () => shutdown('SIGINT'))
}
-main().catch((err) => {
- console.error("[stdio-bridge] Fatal:", err);
- process.exit(1);
-});
+main().catch(err => {
+ console.error('[stdio-bridge] Fatal:', err)
+ process.exit(1)
+})
diff --git a/stdio-bridge/src/types.ts b/stdio-bridge/src/types.ts
index eef05cf6b..b14597e2a 100644
--- a/stdio-bridge/src/types.ts
+++ b/stdio-bridge/src/types.ts
@@ -1,30 +1,30 @@
export interface BridgeConfig {
- command: string;
- args: string[];
- port: number;
- healthPath: string;
- restartMax: number;
- restartDelay: number;
- initTimeout: number;
- shutdownTimeout: number;
- logLevel: string;
+ command: string
+ args: string[]
+ port: number
+ healthPath: string
+ restartMax: number
+ restartDelay: number
+ initTimeout: number
+ shutdownTimeout: number
+ logLevel: string
}
export function loadConfig(): BridgeConfig {
- const command = process.env.STDIO_COMMAND;
+ const command = process.env.STDIO_COMMAND
if (!command) {
- throw new Error("STDIO_COMMAND is required");
+ throw new Error('STDIO_COMMAND is required')
}
return {
command,
- args: JSON.parse(process.env.STDIO_ARGS || "[]"),
- port: parseInt(process.env.BRIDGE_PORT || "3000", 10),
- healthPath: process.env.BRIDGE_HEALTH_PATH || "/health",
- restartMax: parseInt(process.env.STDIO_RESTART_MAX || "3", 10),
- restartDelay: parseInt(process.env.STDIO_RESTART_DELAY || "5000", 10),
- initTimeout: parseInt(process.env.STDIO_INIT_TIMEOUT || "30000", 10),
- shutdownTimeout: parseInt(process.env.STDIO_SHUTDOWN_TIMEOUT || "10000", 10),
- logLevel: process.env.LOG_LEVEL || "info",
- };
+ args: JSON.parse(process.env.STDIO_ARGS || '[]'),
+ port: parseInt(process.env.BRIDGE_PORT || '3000', 10),
+ healthPath: process.env.BRIDGE_HEALTH_PATH || '/health',
+ restartMax: parseInt(process.env.STDIO_RESTART_MAX || '3', 10),
+ restartDelay: parseInt(process.env.STDIO_RESTART_DELAY || '5000', 10),
+ initTimeout: parseInt(process.env.STDIO_INIT_TIMEOUT || '30000', 10),
+ shutdownTimeout: parseInt(process.env.STDIO_SHUTDOWN_TIMEOUT || '10000', 10),
+ logLevel: process.env.LOG_LEVEL || 'info',
+ }
}
diff --git a/stdio-bridge/vitest.config.ts b/stdio-bridge/vitest.config.ts
index 37b473f54..8141ade9e 100644
--- a/stdio-bridge/vitest.config.ts
+++ b/stdio-bridge/vitest.config.ts
@@ -1,8 +1,8 @@
-import { defineConfig } from "vitest/config";
+import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
- include: ["src/**/*.test.ts", "src/**/__tests__/**/*.ts", "test/**/*.test.ts"],
- exclude: ["dist/**", "node_modules/**"],
+ include: ['src/**/*.test.ts', 'src/**/__tests__/**/*.ts', 'test/**/*.test.ts'],
+ exclude: ['dist/**', 'node_modules/**'],
},
-});
+})
diff --git a/tests/e2e/benchmark/helpers.ts b/tests/e2e/benchmark/helpers.ts
index b7f639a1a..646dda1ed 100644
--- a/tests/e2e/benchmark/helpers.ts
+++ b/tests/e2e/benchmark/helpers.ts
@@ -4,53 +4,52 @@
* Reuses shared helpers from the parent e2e directory and adds benchmark-specific
* functionality for live provider swapping via Host CRD patches.
*/
-
-import { execSync } from "child_process";
-import { writeFileSync, mkdirSync, existsSync } from "fs";
+import { execSync } from 'child_process'
+import { existsSync, mkdirSync, writeFileSync } from 'fs'
import {
- sendMessage,
- waitForIdle,
+ MCP_HOST_URL,
+ fetchJson,
+ getPodLogs,
getStatus,
getTaskResult,
- fetchJson,
kubectl,
- getPodLogs,
+ sendMessage,
sleep,
- MCP_HOST_URL,
-} from "../helpers.js";
-import type { Category, Difficulty } from "./prompts.js";
+ waitForIdle,
+} from '../helpers.js'
+import type { Category, Difficulty } from './prompts.js'
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export interface ProviderConfig {
- provider: "openai" | "claude" | "zai" | "bailian";
- model: string;
- label: string;
+ provider: 'openai' | 'claude' | 'zai' | 'bailian'
+ model: string
+ label: string
}
export interface BenchmarkResult {
- provider: string;
- model: string;
- testId: string;
- category: Category;
- difficulty: Difficulty;
- prompt: string;
- label: string;
- response: string | null;
- latencyMs: number;
- toolCallCount: number;
- score: number;
- success: boolean;
- error?: string;
+ provider: string
+ model: string
+ testId: string
+ category: Category
+ difficulty: Difficulty
+ prompt: string
+ label: string
+ response: string | null
+ latencyMs: number
+ toolCallCount: number
+ score: number
+ success: boolean
+ error?: string
}
export interface BenchmarkSummary {
- timestamp: string;
- providers: ProviderConfig[];
- totalTests: number;
- results: BenchmarkResult[];
+ timestamp: string
+ providers: ProviderConfig[]
+ totalTests: number
+ results: BenchmarkResult[]
}
// ---------------------------------------------------------------------------
@@ -58,34 +57,34 @@ export interface BenchmarkSummary {
// ---------------------------------------------------------------------------
export const PROVIDERS: ProviderConfig[] = [
- { provider: "openai", model: "gpt-4o", label: "GPT-4o" },
+ { provider: 'openai', model: 'gpt-4o', label: 'GPT-4o' },
{
- provider: "claude",
- model: "claude-sonnet-4-20250514",
- label: "Claude Sonnet 4",
+ provider: 'claude',
+ model: 'claude-sonnet-4-20250514',
+ label: 'Claude Sonnet 4',
},
- { provider: "zai", model: "glm-5", label: "GLM-5 (ZAI)" },
+ { provider: 'zai', model: 'glm-5', label: 'GLM-5 (ZAI)' },
{
- provider: "bailian",
- model: "qwen3-coder-plus",
- label: "Qwen3 Coder+ (Bailian)",
+ provider: 'bailian',
+ model: 'qwen3-coder-plus',
+ label: 'Qwen3 Coder+ (Bailian)',
},
-];
+]
/** Allow filtering providers via env var (comma-separated). */
export function getActiveProviders(): ProviderConfig[] {
- const filter = process.env.BENCHMARK_PROVIDERS;
- if (!filter) return PROVIDERS;
- const names = filter.split(",").map((s) => s.trim().toLowerCase());
- return PROVIDERS.filter((p) => names.includes(p.provider));
+ const filter = process.env.BENCHMARK_PROVIDERS
+ if (!filter) return PROVIDERS
+ const names = filter.split(',').map(s => s.trim().toLowerCase())
+ return PROVIDERS.filter(p => names.includes(p.provider))
}
// ---------------------------------------------------------------------------
// Host CRD: provider namespace
// ---------------------------------------------------------------------------
-const HOST_CRD_NAME = "chatllm";
-const HOST_CRD_NAMESPACE = process.env.HOST_CRD_NAMESPACE || "mcp-host";
+const HOST_CRD_NAME = 'chatllm'
+const HOST_CRD_NAMESPACE = process.env.HOST_CRD_NAMESPACE || 'mcp-host'
// ---------------------------------------------------------------------------
// Provider switching
@@ -97,32 +96,30 @@ const HOST_CRD_NAMESPACE = process.env.HOST_CRD_NAMESPACE || "mcp-host";
* We verify by checking logs for the provider initialization message.
*/
export async function switchProvider(cfg: ProviderConfig): Promise<void> {
- console.log(
- `\n[Benchmark] Switching to ${cfg.label} (${cfg.provider}/${cfg.model})...`,
- );
+ console.log(`\n[Benchmark] Switching to ${cfg.label} (${cfg.provider}/${cfg.model})...`)
// Patch Host CRD
kubectl(
`patch host ${HOST_CRD_NAME} -n ${HOST_CRD_NAMESPACE} --type=merge ` +
- `-p '{"spec":{"model":{"provider":"${cfg.provider}","name":"${cfg.model}"}}}'`,
- );
+ `-p '{"spec":{"model":{"provider":"${cfg.provider}","name":"${cfg.model}"}}}'`
+ )
// Wait for mcp-host to detect the change and reinitialize
- const maxWaitMs = 15_000;
- const start = Date.now();
- let detected = false;
+ const maxWaitMs = 15_000
+ const start = Date.now()
+ let detected = false
while (Date.now() - start < maxWaitMs) {
- await sleep(2000);
+ await sleep(2000)
try {
- const logs = getPodLogs("mcp-host", "mcp-host", 20);
+ const logs = getPodLogs('mcp-host', 'mcp-host', 20)
if (
- logs.includes("Host configuration changed") ||
+ logs.includes('Host configuration changed') ||
logs.includes(`provider: ${cfg.provider}`) ||
logs.includes(`Using ${cfg.provider}`)
) {
- detected = true;
- break;
+ detected = true
+ break
}
} catch {
// Pod logs might not be available immediately
@@ -131,13 +128,13 @@ export async function switchProvider(cfg: ProviderConfig): Promise<void> {
if (!detected) {
console.warn(
- `[Benchmark] Warning: Could not confirm provider switch in logs (proceeding anyway)`,
- );
+ `[Benchmark] Warning: Could not confirm provider switch in logs (proceeding anyway)`
+ )
}
// Verify health
- await waitForIdle(10_000).catch(() => {});
- console.log(`[Benchmark] Provider switched to ${cfg.label}`);
+ await waitForIdle(10_000).catch(() => {})
+ console.log(`[Benchmark] Provider switched to ${cfg.label}`)
}
// ---------------------------------------------------------------------------
@@ -151,14 +148,14 @@ export async function switchProvider(cfg: ProviderConfig): Promise<void> {
export function cleanWorkspace(): void {
try {
const pod = kubectl(
- "get pods -n mcp-host -l app=mcp-host -o jsonpath='{.items[0].metadata.name}'",
- );
+ "get pods -n mcp-host -l app=mcp-host -o jsonpath='{.items[0].metadata.name}'"
+ )
kubectl(
- `exec ${pod} -n mcp-host -- sh -c "rm -rf /workspace/benchmark/* 2>/dev/null; mkdir -p /workspace/benchmark"`,
- );
- console.log("[Benchmark] Workspace cleaned");
+ `exec ${pod} -n mcp-host -- sh -c "rm -rf /workspace/benchmark/* 2>/dev/null; mkdir -p /workspace/benchmark"`
+ )
+ console.log('[Benchmark] Workspace cleaned')
} catch (e) {
- console.warn("[Benchmark] Workspace cleanup failed:", e);
+ console.warn('[Benchmark] Workspace cleanup failed:', e)
}
}
@@ -167,16 +164,13 @@ export function cleanWorkspace(): void {
// ---------------------------------------------------------------------------
/** Auto-incrementing counter for unique userIds per benchmark call. */
-let benchCounter = 0;
+let benchCounter = 0
/**
* Delay between tests to avoid rate limiting (configurable via env).
* Default: 8 seconds — enough for most providers' TPM limits.
*/
-const INTER_TEST_DELAY_MS = parseInt(
- process.env.BENCHMARK_DELAY_MS ?? "8000",
- 10,
-);
+const INTER_TEST_DELAY_MS = parseInt(process.env.BENCHMARK_DELAY_MS ?? '8000', 10)
/**
* Send a prompt to the agent, wait for completion, and return timing + result.
@@ -187,49 +181,49 @@ const INTER_TEST_DELAY_MS = parseInt(
* 3. As fallback, check /status for last completed task info
*/
export async function runBenchmarkPrompt(opts: {
- prompt: string;
- testId: string;
- category: Category;
- difficulty: Difficulty;
- label: string;
- provider: ProviderConfig;
- timeoutMs?: number;
+ prompt: string
+ testId: string
+ category: Category
+ difficulty: Difficulty
+ label: string
+ provider: ProviderConfig
+ timeoutMs?: number
}): Promise<BenchmarkResult> {
- benchCounter++;
- const userId = `bench-${opts.provider.provider}-${opts.testId}-${benchCounter}`;
- const timeout = opts.timeoutMs ?? 180_000;
+ benchCounter++
+ const userId = `bench-${opts.provider.provider}-${opts.testId}-${benchCounter}`
+ const timeout = opts.timeoutMs ?? 180_000
// Rate-limit protection: wait between tests
if (benchCounter > 1) {
- await sleep(INTER_TEST_DELAY_MS);
+ await sleep(INTER_TEST_DELAY_MS)
}
- const startTime = Date.now();
+ const startTime = Date.now()
try {
// Get initial tool call count
- const statusBefore = await getStatus();
- const toolsBefore = statusBefore.agent?.totalToolCalls ?? 0;
+ const statusBefore = await getStatus()
+ const toolsBefore = statusBefore.agent?.totalToolCalls ?? 0
// Send message
- const res = await sendMessage(opts.prompt, { userId });
+ const res = await sendMessage(opts.prompt, { userId })
- let response: string | null = null;
- const taskId: string | undefined = res.data?.taskId;
+ let response: string | null = null
+ const taskId: string | undefined = res.data?.taskId
if (res.data.success && res.data.response) {
// Agent completed within HTTP timeout — response is inline
- response = res.data.response;
- await waitForIdle(10_000).catch(() => {});
+ response = res.data.response
+ await waitForIdle(10_000).catch(() => {})
} else {
// Wait for agent to finish processing
- await waitForIdle(timeout);
+ await waitForIdle(timeout)
// Strategy 1: poll /task/:id/result if we have a taskId
if (taskId) {
try {
- const taskRes = await getTaskResult(taskId, 15_000);
- response = taskRes.data?.response ?? null;
+ const taskRes = await getTaskResult(taskId, 15_000)
+ response = taskRes.data?.response ?? null
} catch {
// Task result endpoint might not have the response
}
@@ -238,9 +232,9 @@ export async function runBenchmarkPrompt(opts: {
// Strategy 2: if still no response, try fetching status for last result
if (!response) {
try {
- const statusNow = await getStatus();
+ const statusNow = await getStatus()
if (statusNow.lastTaskResult?.response) {
- response = statusNow.lastTaskResult.response;
+ response = statusNow.lastTaskResult.response
}
} catch {
// Ignore
@@ -248,12 +242,12 @@ export async function runBenchmarkPrompt(opts: {
}
}
- const endTime = Date.now();
+ const endTime = Date.now()
// Get tool call count after
- const statusAfter = await getStatus();
- const toolsAfter = statusAfter.agent?.totalToolCalls ?? 0;
- const toolCallCount = toolsAfter - toolsBefore;
+ const statusAfter = await getStatus()
+ const toolsAfter = statusAfter.agent?.totalToolCalls ?? 0
+ const toolCallCount = toolsAfter - toolsBefore
return {
provider: opts.provider.provider,
@@ -268,9 +262,9 @@ export async function runBenchmarkPrompt(opts: {
toolCallCount: Math.max(0, toolCallCount),
score: 0, // Scored later by scoring.ts
success: !!response,
- };
+ }
} catch (error) {
- const endTime = Date.now();
+ const endTime = Date.now()
return {
provider: opts.provider.provider,
model: opts.provider.model,
@@ -285,7 +279,7 @@ export async function runBenchmarkPrompt(opts: {
score: 0,
success: false,
error: error instanceof Error ? error.message : String(error),
- };
+ }
}
}
@@ -293,30 +287,30 @@ export async function runBenchmarkPrompt(opts: {
// Results persistence
// ---------------------------------------------------------------------------
-const RESULTS_DIR = new URL("./results/", import.meta.url).pathname;
+const RESULTS_DIR = new URL('./results/', import.meta.url).pathname
/**
* Save benchmark results to a timestamped JSON file.
*/
export function saveResults(results: BenchmarkResult[]): string {
if (!existsSync(RESULTS_DIR)) {
- mkdirSync(RESULTS_DIR, { recursive: true });
+ mkdirSync(RESULTS_DIR, { recursive: true })
}
- const ts = new Date().toISOString().replace(/[:.]/g, "-");
- const filename = `benchmark-${ts}.json`;
- const filepath = `${RESULTS_DIR}${filename}`;
+ const ts = new Date().toISOString().replace(/[:.]/g, '-')
+ const filename = `benchmark-${ts}.json`
+ const filepath = `${RESULTS_DIR}${filename}`
const summary: BenchmarkSummary = {
timestamp: new Date().toISOString(),
providers: getActiveProviders(),
totalTests: results.length,
results,
- };
+ }
- writeFileSync(filepath, JSON.stringify(summary, null, 2));
- console.log(`\n[Benchmark] Results saved to ${filepath}`);
- return filepath;
+ writeFileSync(filepath, JSON.stringify(summary, null, 2))
+ console.log(`\n[Benchmark] Results saved to ${filepath}`)
+ return filepath
}
// ---------------------------------------------------------------------------
@@ -327,101 +321,89 @@ export function saveResults(results: BenchmarkResult[]): string {
* Print a summary table to the console.
*/
export function printSummaryTable(results: BenchmarkResult[]): void {
- console.log("\n" + "=".repeat(120));
- console.log("LLM PROVIDER BENCHMARK RESULTS");
- console.log("=".repeat(120));
+ console.log('\n' + '='.repeat(120))
+ console.log('LLM PROVIDER BENCHMARK RESULTS')
+ console.log('='.repeat(120))
// Group by provider
- const byProvider = new Map<string, BenchmarkResult[]>();
+ const byProvider = new Map<string, BenchmarkResult[]>()
for (const r of results) {
- const key = `${r.provider}/${r.model}`;
- if (!byProvider.has(key)) byProvider.set(key, []);
- byProvider.get(key)!.push(r);
+ const key = `${r.provider}/${r.model}`
+ if (!byProvider.has(key)) byProvider.set(key, [])
+ byProvider.get(key)!.push(r)
}
// Header
console.log(
- padRight("Test ID", 12) +
- padRight("Category", 22) +
- padRight("Difficulty", 12) +
- [...byProvider.keys()]
- .map((k) => padRight(k, 28))
- .join(""),
- );
- console.log("-".repeat(120));
+ padRight('Test ID', 12) +
+ padRight('Category', 22) +
+ padRight('Difficulty', 12) +
+ [...byProvider.keys()].map(k => padRight(k, 28)).join('')
+ )
+ console.log('-'.repeat(120))
// Collect all test IDs
- const testIds = [...new Set(results.map((r) => r.testId))];
+ const testIds = [...new Set(results.map(r => r.testId))]
for (const testId of testIds) {
- const first = results.find((r) => r.testId === testId)!;
- let line =
- padRight(testId, 12) +
- padRight(first.category, 22) +
- padRight(first.difficulty, 12);
+ const first = results.find(r => r.testId === testId)!
+ let line = padRight(testId, 12) + padRight(first.category, 22) + padRight(first.difficulty, 12)
for (const [, provResults] of byProvider) {
- const r = provResults.find((pr) => pr.testId === testId);
+ const r = provResults.find(pr => pr.testId === testId)
if (r) {
- const status = r.success ? `${r.score}/100` : "FAIL";
- const latency = `${(r.latencyMs / 1000).toFixed(1)}s`;
- line += padRight(`${status} (${latency}, ${r.toolCallCount}t)`, 28);
+ const status = r.success ? `${r.score}/100` : 'FAIL'
+ const latency = `${(r.latencyMs / 1000).toFixed(1)}s`
+ line += padRight(`${status} (${latency}, ${r.toolCallCount}t)`, 28)
} else {
- line += padRight("--", 28);
+ line += padRight('--', 28)
}
}
- console.log(line);
+ console.log(line)
}
- console.log("-".repeat(120));
+ console.log('-'.repeat(120))
// Provider averages
- console.log("\nProvider Averages:");
+ console.log('\nProvider Averages:')
for (const [key, provResults] of byProvider) {
- const scored = provResults.filter((r) => r.success);
- const avgScore =
- scored.length > 0
- ? scored.reduce((s, r) => s + r.score, 0) / scored.length
- : 0;
+ const scored = provResults.filter(r => r.success)
+ const avgScore = scored.length > 0 ? scored.reduce((s, r) => s + r.score, 0) / scored.length : 0
const avgLatency =
- scored.length > 0
- ? scored.reduce((s, r) => s + r.latencyMs, 0) / scored.length / 1000
- : 0;
+ scored.length > 0 ? scored.reduce((s, r) => s + r.latencyMs, 0) / scored.length / 1000 : 0
const passRate =
- provResults.length > 0
- ? ((scored.length / provResults.length) * 100).toFixed(0)
- : "0";
+ provResults.length > 0 ? ((scored.length / provResults.length) * 100).toFixed(0) : '0'
console.log(
- ` ${key}: avg score=${avgScore.toFixed(1)}, avg latency=${avgLatency.toFixed(1)}s, pass rate=${passRate}%`,
- );
+ ` ${key}: avg score=${avgScore.toFixed(1)}, avg latency=${avgLatency.toFixed(1)}s, pass rate=${passRate}%`
+ )
}
// Category breakdown
- console.log("\nBest Provider by Category:");
- const categories = [...new Set(results.map((r) => r.category))];
+ console.log('\nBest Provider by Category:')
+ const categories = [...new Set(results.map(r => r.category))]
for (const cat of categories) {
- const catResults = results.filter((r) => r.category === cat && r.success);
- const byProv = new Map<string, number[]>();
+ const catResults = results.filter(r => r.category === cat && r.success)
+ const byProv = new Map<string, number[]>()
for (const r of catResults) {
- const key = `${r.provider}/${r.model}`;
- if (!byProv.has(key)) byProv.set(key, []);
- byProv.get(key)!.push(r.score);
+ const key = `${r.provider}/${r.model}`
+ if (!byProv.has(key)) byProv.set(key, [])
+ byProv.get(key)!.push(r.score)
}
- let best = "";
- let bestAvg = 0;
+ let best = ''
+ let bestAvg = 0
for (const [key, scores] of byProv) {
- const avg = scores.reduce((a, b) => a + b, 0) / scores.length;
+ const avg = scores.reduce((a, b) => a + b, 0) / scores.length
if (avg > bestAvg) {
- bestAvg = avg;
- best = key;
+ bestAvg = avg
+ best = key
}
}
- console.log(` ${cat}: ${best || "N/A"} (avg ${bestAvg.toFixed(1)})`);
+ console.log(` ${cat}: ${best || 'N/A'} (avg ${bestAvg.toFixed(1)})`)
}
- console.log("=".repeat(120));
+ console.log('='.repeat(120))
}
function padRight(s: string, len: number): string {
- return s.length >= len ? s : s + " ".repeat(len - s.length);
+ return s.length >= len ? s : s + ' '.repeat(len - s.length)
}
diff --git a/tests/e2e/benchmark/prompts.ts b/tests/e2e/benchmark/prompts.ts
index cfe8db6bd..3ac68b2b3 100644
--- a/tests/e2e/benchmark/prompts.ts
+++ b/tests/e2e/benchmark/prompts.ts
@@ -5,23 +5,23 @@
* based on deterministic checks (regex, keyword matching, format validation).
*/
-export type Difficulty = "easy" | "medium" | "hard";
+export type Difficulty = 'easy' | 'medium' | 'hard'
export type Category =
- | "reasoning"
- | "tool_single"
- | "tool_chain"
- | "mcp_tool"
- | "instruction_following";
+ | 'reasoning'
+ | 'tool_single'
+ | 'tool_chain'
+ | 'mcp_tool'
+ | 'instruction_following'
export interface BenchmarkPrompt {
- id: string;
- category: Category;
- difficulty: Difficulty;
- prompt: string;
+ id: string
+ category: Category
+ difficulty: Difficulty
+ prompt: string
/** Short description for test names */
- label: string;
+ label: string
/** Deterministic validator — returns score 0-100 */
- validate: (response: string) => number;
+ validate: (response: string) => number
}
// ---------------------------------------------------------------------------
@@ -30,54 +30,53 @@ export interface BenchmarkPrompt {
const reasoning: BenchmarkPrompt[] = [
{
- id: "R-EASY",
- category: "reasoning",
- difficulty: "easy",
- prompt: "What is 17 * 23? Show your work and give the final answer.",
- label: "simple multiplication",
- validate: (r) => (r.includes("391") ? 100 : 0),
+ id: 'R-EASY',
+ category: 'reasoning',
+ difficulty: 'easy',
+ prompt: 'What is 17 * 23? Show your work and give the final answer.',
+ label: 'simple multiplication',
+ validate: r => (r.includes('391') ? 100 : 0),
},
{
- id: "R-MED",
- category: "reasoning",
- difficulty: "medium",
+ id: 'R-MED',
+ category: 'reasoning',
+ difficulty: 'medium',
prompt:
- "A farmer has 3 fields. Field A is twice the size of Field B. Field C is 10 acres more than Field B. The total area is 70 acres. What is the size of each field in acres? Give exact numbers.",
- label: "word problem algebra",
- validate: (r) => {
+ 'A farmer has 3 fields. Field A is twice the size of Field B. Field C is 10 acres more than Field B. The total area is 70 acres. What is the size of each field in acres? Give exact numbers.',
+ label: 'word problem algebra',
+ validate: r => {
// B=15, A=30, C=25
- const hasB = /15/.test(r);
- const hasA = /30/.test(r);
- const hasC = /25/.test(r);
- if (hasA && hasB && hasC) return 100;
- if ((hasA && hasB) || (hasA && hasC) || (hasB && hasC)) return 60;
- if (hasA || hasB || hasC) return 30;
- return 0;
+ const hasB = /15/.test(r)
+ const hasA = /30/.test(r)
+ const hasC = /25/.test(r)
+ if (hasA && hasB && hasC) return 100
+ if ((hasA && hasB) || (hasA && hasC) || (hasB && hasC)) return 60
+ if (hasA || hasB || hasC) return 30
+ return 0
},
},
{
- id: "R-HARD",
- category: "reasoning",
- difficulty: "hard",
+ id: 'R-HARD',
+ category: 'reasoning',
+ difficulty: 'hard',
prompt:
- "You have 8 identical-looking balls. One is slightly heavier than the rest. You have a two-pan balance scale. What is the minimum number of weighings needed to guarantee finding the heavier ball? Describe the strategy step by step.",
- label: "balance scale puzzle",
- validate: (r) => {
- const lower = r.toLowerCase();
+ 'You have 8 identical-looking balls. One is slightly heavier than the rest. You have a two-pan balance scale. What is the minimum number of weighings needed to guarantee finding the heavier ball? Describe the strategy step by step.',
+ label: 'balance scale puzzle',
+ validate: r => {
+ const lower = r.toLowerCase()
// Answer is 2 weighings
- const hasAnswer = /\b2\b/.test(r) && /weigh/i.test(r);
+ const hasAnswer = /\b2\b/.test(r) && /weigh/i.test(r)
// Should mention dividing into groups of 3
- const hasStrategy =
- /group/i.test(r) || /divid/i.test(r) || /split/i.test(r);
- const hasThrees = /\b3\b/.test(r);
- let score = 0;
- if (hasAnswer) score += 50;
- if (hasStrategy) score += 25;
- if (hasThrees) score += 25;
- return score;
+ const hasStrategy = /group/i.test(r) || /divid/i.test(r) || /split/i.test(r)
+ const hasThrees = /\b3\b/.test(r)
+ let score = 0
+ if (hasAnswer) score += 50
+ if (hasStrategy) score += 25
+ if (hasThrees) score += 25
+ return score
},
},
-];
+]
// ---------------------------------------------------------------------------
// Category 2: Tool Use — Single Tool (native tools)
@@ -85,56 +84,55 @@ const reasoning: BenchmarkPrompt[] = [
const toolSingle: BenchmarkPrompt[] = [
{
- id: "TS-EASY",
- category: "tool_single",
- difficulty: "easy",
- prompt: "Use the system_info tool to tell me the current hostname of this system.",
- label: "system_info hostname",
- validate: (r) => {
+ id: 'TS-EASY',
+ category: 'tool_single',
+ difficulty: 'easy',
+ prompt: 'Use the system_info tool to tell me the current hostname of this system.',
+ label: 'system_info hostname',
+ validate: r => {
// Should contain some hostname string (not empty)
- const lower = r.toLowerCase();
- if (lower.includes("hostname") || lower.includes("host")) return 100;
+ const lower = r.toLowerCase()
+ if (lower.includes('hostname') || lower.includes('host')) return 100
// If it returned any system info, partial credit
- if (r.length > 20) return 50;
- return 0;
+ if (r.length > 20) return 50
+ return 0
},
},
{
- id: "TS-MED",
- category: "tool_single",
- difficulty: "medium",
+ id: 'TS-MED',
+ category: 'tool_single',
+ difficulty: 'medium',
prompt:
"Write a file at /workspace/benchmark/hello.txt with the exact content 'Hello Benchmark' (no quotes). Then read the file back and confirm its content.",
- label: "file write + read",
- validate: (r) => {
- const lower = r.toLowerCase();
- const hasWrite = /writ|creat/i.test(r);
- const hasRead = /read|content|hello benchmark/i.test(r);
- const hasConfirm =
- /confirm|verified|matches|correct|success/i.test(r);
- let score = 0;
- if (hasWrite) score += 30;
- if (hasRead) score += 40;
- if (hasConfirm) score += 30;
- return score;
+ label: 'file write + read',
+ validate: r => {
+ const lower = r.toLowerCase()
+ const hasWrite = /writ|creat/i.test(r)
+ const hasRead = /read|content|hello benchmark/i.test(r)
+ const hasConfirm = /confirm|verified|matches|correct|success/i.test(r)
+ let score = 0
+ if (hasWrite) score += 30
+ if (hasRead) score += 40
+ if (hasConfirm) score += 30
+ return score
},
},
{
- id: "TS-HARD",
- category: "tool_single",
- difficulty: "hard",
+ id: 'TS-HARD',
+ category: 'tool_single',
+ difficulty: 'hard',
prompt:
"Use shell_exec to create a directory /workspace/benchmark/project. Then use file_write to create /workspace/benchmark/project/package.json with a valid JSON object containing name 'bench-test' and version '1.0.0'. Finally use file_read to read it back and use json_transform to extract the version field. Report the extracted version.",
- label: "multi-tool orchestration",
- validate: (r) => {
- let score = 0;
- if (/bench-test/i.test(r)) score += 25;
- if (/1\.0\.0/.test(r)) score += 50;
- if (/version/i.test(r)) score += 25;
- return score;
+ label: 'multi-tool orchestration',
+ validate: r => {
+ let score = 0
+ if (/bench-test/i.test(r)) score += 25
+ if (/1\.0\.0/.test(r)) score += 50
+ if (/version/i.test(r)) score += 25
+ return score
},
},
-];
+]
// ---------------------------------------------------------------------------
// Category 3: Tool Use — Multi-step Chain (native tools)
@@ -142,59 +140,58 @@ const toolSingle: BenchmarkPrompt[] = [
const toolChain: BenchmarkPrompt[] = [
{
- id: "TC-EASY",
- category: "tool_chain",
- difficulty: "easy",
+ id: 'TC-EASY',
+ category: 'tool_chain',
+ difficulty: 'easy',
prompt:
- "Write the number 42 to a file at /workspace/benchmark/num.txt, read it back, and confirm the content matches what you wrote.",
- label: "write-read-confirm",
- validate: (r) => {
- const has42 = /42/.test(r);
- const hasConfirm = /confirm|match|correct|verified|success/i.test(r);
- return has42 && hasConfirm ? 100 : has42 ? 60 : 0;
+ 'Write the number 42 to a file at /workspace/benchmark/num.txt, read it back, and confirm the content matches what you wrote.',
+ label: 'write-read-confirm',
+ validate: r => {
+ const has42 = /42/.test(r)
+ const hasConfirm = /confirm|match|correct|verified|success/i.test(r)
+ return has42 && hasConfirm ? 100 : has42 ? 60 : 0
},
},
{
- id: "TC-MED",
- category: "tool_chain",
- difficulty: "medium",
+ id: 'TC-MED',
+ category: 'tool_chain',
+ difficulty: 'medium',
prompt:
- "Create a bash script at /workspace/benchmark/fib.sh that prints the first 10 Fibonacci numbers (one per line, starting from 0). Make it executable and run it with shell_exec. Report the output.",
- label: "fibonacci script",
- validate: (r) => {
+ 'Create a bash script at /workspace/benchmark/fib.sh that prints the first 10 Fibonacci numbers (one per line, starting from 0). Make it executable and run it with shell_exec. Report the output.',
+ label: 'fibonacci script',
+ validate: r => {
// First 10 Fibonacci: 0 1 1 2 3 5 8 13 21 34
- const fibs = ["0", "1", "1", "2", "3", "5", "8", "13", "21", "34"];
- let found = 0;
+ const fibs = ['0', '1', '1', '2', '3', '5', '8', '13', '21', '34']
+ let found = 0
for (const f of fibs) {
- if (r.includes(f)) found++;
+ if (r.includes(f)) found++
}
// Need at least the later unique ones to confirm correctness
- const hasKey = /13/.test(r) && /21/.test(r) && /34/.test(r);
- if (hasKey && found >= 8) return 100;
- if (hasKey) return 70;
- if (found >= 5) return 50;
- return found >= 3 ? 30 : 0;
+ const hasKey = /13/.test(r) && /21/.test(r) && /34/.test(r)
+ if (hasKey && found >= 8) return 100
+ if (hasKey) return 70
+ if (found >= 5) return 50
+ return found >= 3 ? 30 : 0
},
},
{
- id: "TC-HARD",
- category: "tool_chain",
- difficulty: "hard",
+ id: 'TC-HARD',
+ category: 'tool_chain',
+ difficulty: 'hard',
prompt:
"Create a Node.js project at /workspace/benchmark/calc/: 1) Write package.json with name 'calc' and version '1.0.0'. 2) Write index.js that exports functions add(a,b) and multiply(a,b). 3) Write test.js that requires index.js and tests: add(2,3)===5, multiply(4,5)===20 — printing PASS or FAIL for each. 4) Run 'node test.js' with shell_exec and report the results.",
- label: "node project create+test",
- validate: (r) => {
- const lower = r.toLowerCase();
- let score = 0;
- if (/pass/i.test(r)) score += 50;
- if (/add.*5|5.*add/i.test(r) || /2.*3.*5/.test(r)) score += 15;
- if (/multiply.*20|20.*multiply/i.test(r) || /4.*5.*20/.test(r))
- score += 15;
- if (/node\s+test/i.test(r) || /ran|execut/i.test(r)) score += 20;
- return Math.min(score, 100);
+ label: 'node project create+test',
+ validate: r => {
+ const lower = r.toLowerCase()
+ let score = 0
+ if (/pass/i.test(r)) score += 50
+ if (/add.*5|5.*add/i.test(r) || /2.*3.*5/.test(r)) score += 15
+ if (/multiply.*20|20.*multiply/i.test(r) || /4.*5.*20/.test(r)) score += 15
+ if (/node\s+test/i.test(r) || /ran|execut/i.test(r)) score += 20
+ return Math.min(score, 100)
},
},
-];
+]
// ---------------------------------------------------------------------------
// Category 4: MCP Tool Use (requires mock-mcp-server with echo/add)
@@ -202,44 +199,44 @@ const toolChain: BenchmarkPrompt[] = [
const mcpTool: BenchmarkPrompt[] = [
{
- id: "MCP-EASY",
- category: "mcp_tool",
- difficulty: "easy",
+ id: 'MCP-EASY',
+ category: 'mcp_tool',
+ difficulty: 'easy',
prompt: "Use the echo tool to echo the text 'benchmark test'. Return the echoed result.",
- label: "echo tool",
- validate: (r) => (/benchmark test/i.test(r) ? 100 : 0),
+ label: 'echo tool',
+ validate: r => (/benchmark test/i.test(r) ? 100 : 0),
},
{
- id: "MCP-MED",
- category: "mcp_tool",
- difficulty: "medium",
+ id: 'MCP-MED',
+ category: 'mcp_tool',
+ difficulty: 'medium',
prompt:
- "Use the add tool to compute 123 + 456. Then use the echo tool to echo the result. What is the final answer?",
- label: "add then echo",
- validate: (r) => {
- const has579 = /579/.test(r);
- return has579 ? 100 : 0;
+ 'Use the add tool to compute 123 + 456. Then use the echo tool to echo the result. What is the final answer?',
+ label: 'add then echo',
+ validate: r => {
+ const has579 = /579/.test(r)
+ return has579 ? 100 : 0
},
},
{
- id: "MCP-HARD",
- category: "mcp_tool",
- difficulty: "hard",
+ id: 'MCP-HARD',
+ category: 'mcp_tool',
+ difficulty: 'hard',
prompt:
"Use the add tool to compute these three sums: (10+20), (30+40), (50+60). Then use the echo tool to echo all three results as a comma-separated string like '30,70,110'. Report the final echoed string.",
- label: "multi-add then echo",
- validate: (r) => {
- const has30 = /\b30\b/.test(r);
- const has70 = /\b70\b/.test(r);
- const has110 = /\b110\b/.test(r);
- let score = 0;
- if (has30) score += 33;
- if (has70) score += 33;
- if (has110) score += 34;
- return score;
+ label: 'multi-add then echo',
+ validate: r => {
+ const has30 = /\b30\b/.test(r)
+ const has70 = /\b70\b/.test(r)
+ const has110 = /\b110\b/.test(r)
+ let score = 0
+ if (has30) score += 33
+ if (has70) score += 33
+ if (has110) score += 34
+ return score
},
},
-];
+]
// ---------------------------------------------------------------------------
// Category 5: Instruction Following (precision/format)
@@ -247,104 +244,104 @@ const mcpTool: BenchmarkPrompt[] = [
const instructionFollowing: BenchmarkPrompt[] = [
{
- id: "IF-EASY",
- category: "instruction_following",
- difficulty: "easy",
+ id: 'IF-EASY',
+ category: 'instruction_following',
+ difficulty: 'easy',
prompt:
- "List exactly 5 programming languages, one per line, numbered 1 through 5. Do not include any other text.",
- label: "numbered list",
- validate: (r) => {
+ 'List exactly 5 programming languages, one per line, numbered 1 through 5. Do not include any other text.',
+ label: 'numbered list',
+ validate: r => {
const lines = r
.trim()
- .split("\n")
- .filter((l) => l.trim().length > 0);
+ .split('\n')
+ .filter(l => l.trim().length > 0)
// Check for numbered lines
- let numberedCount = 0;
+ let numberedCount = 0
for (let i = 1; i <= 5; i++) {
- if (lines.some((l) => l.trim().startsWith(`${i}`))) numberedCount++;
+ if (lines.some(l => l.trim().startsWith(`${i}`))) numberedCount++
}
- if (numberedCount === 5 && lines.length <= 7) return 100;
- if (numberedCount >= 3) return 60;
- return 0;
+ if (numberedCount === 5 && lines.length <= 7) return 100
+ if (numberedCount >= 3) return 60
+ return 0
},
},
{
- id: "IF-MED",
- category: "instruction_following",
- difficulty: "medium",
+ id: 'IF-MED',
+ category: 'instruction_following',
+ difficulty: 'medium',
prompt:
'Generate a JSON object with exactly these keys: "name" (a string), "age" (a number), "hobbies" (an array of exactly 3 strings). Output ONLY the raw JSON. No explanation, no code blocks, no markdown.',
- label: "strict JSON output",
- validate: (r) => {
- let score = 0;
+ label: 'strict JSON output',
+ validate: r => {
+ let score = 0
// Try to extract JSON from the response
- const jsonMatch = r.match(/\{[\s\S]*\}/);
- if (!jsonMatch) return 0;
+ const jsonMatch = r.match(/\{[\s\S]*\}/)
+ if (!jsonMatch) return 0
try {
- const obj = JSON.parse(jsonMatch[0]);
- if (typeof obj.name === "string") score += 25;
- if (typeof obj.age === "number") score += 25;
+ const obj = JSON.parse(jsonMatch[0])
+ if (typeof obj.name === 'string') score += 25
+ if (typeof obj.age === 'number') score += 25
if (
Array.isArray(obj.hobbies) &&
obj.hobbies.length === 3 &&
- obj.hobbies.every((h: unknown) => typeof h === "string")
+ obj.hobbies.every((h: unknown) => typeof h === 'string')
)
- score += 25;
+ score += 25
// Bonus: was it clean JSON without extra text?
- const trimmed = r.trim();
- if (trimmed.startsWith("{") && trimmed.endsWith("}")) score += 25;
+ const trimmed = r.trim()
+ if (trimmed.startsWith('{') && trimmed.endsWith('}')) score += 25
} catch {
- return 10; // Had something JSON-like but invalid
+ return 10 // Had something JSON-like but invalid
}
- return score;
+ return score
},
},
{
- id: "IF-HARD",
- category: "instruction_following",
- difficulty: "hard",
+ id: 'IF-HARD',
+ category: 'instruction_following',
+ difficulty: 'hard',
prompt:
- "Write a CSV with headers: id,name,score. Add exactly 5 data rows. Each score must be an integer between 70 and 100 inclusive. Output ONLY the raw CSV content. No code blocks, no explanation, no markdown formatting.",
- label: "strict CSV output",
- validate: (r) => {
- let score = 0;
+ 'Write a CSV with headers: id,name,score. Add exactly 5 data rows. Each score must be an integer between 70 and 100 inclusive. Output ONLY the raw CSV content. No code blocks, no explanation, no markdown formatting.',
+ label: 'strict CSV output',
+ validate: r => {
+ let score = 0
// Strip potential code block markers
const clean = r
- .replace(/```[\s\S]*?```/g, "")
- .replace(/```/g, "")
- .trim();
- const lines = clean.split("\n").filter((l) => l.trim().length > 0);
+ .replace(/```[\s\S]*?```/g, '')
+ .replace(/```/g, '')
+ .trim()
+ const lines = clean.split('\n').filter(l => l.trim().length > 0)
// Check header
if (lines.length > 0 && /^id,name,score$/i.test(lines[0].trim())) {
- score += 20;
+ score += 20
}
// Check data rows
- let validRows = 0;
+ let validRows = 0
for (let i = 1; i < lines.length; i++) {
- const parts = lines[i].split(",");
+ const parts = lines[i].split(',')
if (parts.length === 3) {
- const s = parseInt(parts[2].trim(), 10);
- if (!isNaN(s) && s >= 70 && s <= 100) validRows++;
+ const s = parseInt(parts[2].trim(), 10)
+ if (!isNaN(s) && s >= 70 && s <= 100) validRows++
}
}
- if (validRows === 5) score += 50;
- else if (validRows >= 3) score += 30;
- else if (validRows >= 1) score += 10;
+ if (validRows === 5) score += 50
+ else if (validRows >= 3) score += 30
+ else if (validRows >= 1) score += 10
// Exact row count (header + 5 data = 6 lines)
- if (lines.length === 6) score += 15;
+ if (lines.length === 6) score += 15
// Clean output (no extra text)
- const trimmed = r.trim();
- if (!trimmed.includes("```") && !trimmed.includes("Here")) score += 15;
+ const trimmed = r.trim()
+ if (!trimmed.includes('```') && !trimmed.includes('Here')) score += 15
- return Math.min(score, 100);
+ return Math.min(score, 100)
},
},
-];
+]
// ---------------------------------------------------------------------------
// Export all prompts
@@ -356,26 +353,26 @@ export const ALL_PROMPTS: BenchmarkPrompt[] = [
...toolChain,
...mcpTool,
...instructionFollowing,
-];
+]
export const CATEGORIES: Category[] = [
- "reasoning",
- "tool_single",
- "tool_chain",
- "mcp_tool",
- "instruction_following",
-];
+ 'reasoning',
+ 'tool_single',
+ 'tool_chain',
+ 'mcp_tool',
+ 'instruction_following',
+]
-export const DIFFICULTIES: Difficulty[] = ["easy", "medium", "hard"];
+export const DIFFICULTIES: Difficulty[] = ['easy', 'medium', 'hard']
/** Get prompts filtered by category and/or difficulty. */
export function getPrompts(opts?: {
- category?: Category;
- difficulty?: Difficulty;
+ category?: Category
+ difficulty?: Difficulty
}): BenchmarkPrompt[] {
return ALL_PROMPTS.filter(
- (p) =>
+ p =>
(!opts?.category || p.category === opts.category) &&
- (!opts?.difficulty || p.difficulty === opts.difficulty),
- );
+ (!opts?.difficulty || p.difficulty === opts.difficulty)
+ )
}
diff --git a/tests/e2e/benchmark/report.ts b/tests/e2e/benchmark/report.ts
index 74da65c11..5573f8fc9 100644
--- a/tests/e2e/benchmark/report.ts
+++ b/tests/e2e/benchmark/report.ts
@@ -7,15 +7,14 @@
*
* If no file is provided, reads the most recent file from results/.
*/
+import { readFileSync, readdirSync } from 'fs'
+import { dirname, resolve } from 'path'
+import { fileURLToPath } from 'url'
+import type { BenchmarkResult, BenchmarkSummary } from './helpers.js'
+import { aggregateByCategory, aggregateByProvider } from './scoring.js'
-import { readFileSync, readdirSync } from "fs";
-import { resolve, dirname } from "path";
-import { fileURLToPath } from "url";
-import type { BenchmarkSummary, BenchmarkResult } from "./helpers.js";
-import { aggregateByProvider, aggregateByCategory } from "./scoring.js";
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-const RESULTS_DIR = resolve(__dirname, "results");
+const __dirname = dirname(fileURLToPath(import.meta.url))
+const RESULTS_DIR = resolve(__dirname, 'results')
// ---------------------------------------------------------------------------
// Load results
@@ -23,21 +22,21 @@ const RESULTS_DIR = resolve(__dirname, "results");
function loadResults(filepath?: string): BenchmarkSummary {
if (filepath) {
- return JSON.parse(readFileSync(filepath, "utf-8"));
+ return JSON.parse(readFileSync(filepath, 'utf-8'))
}
const files = readdirSync(RESULTS_DIR)
- .filter((f) => f.startsWith("benchmark-") && f.endsWith(".json"))
+ .filter(f => f.startsWith('benchmark-') && f.endsWith('.json'))
.sort()
- .reverse();
+ .reverse()
if (files.length === 0) {
- throw new Error(`No benchmark results found in ${RESULTS_DIR}`);
+ throw new Error(`No benchmark results found in ${RESULTS_DIR}`)
}
- const latest = resolve(RESULTS_DIR, files[0]);
- console.log(`Loading: ${latest}\n`);
- return JSON.parse(readFileSync(latest, "utf-8"));
+ const latest = resolve(RESULTS_DIR, files[0])
+ console.log(`Loading: ${latest}\n`)
+ return JSON.parse(readFileSync(latest, 'utf-8'))
}
// ---------------------------------------------------------------------------
@@ -45,125 +44,119 @@ function loadResults(filepath?: string): BenchmarkSummary {
// ---------------------------------------------------------------------------
function generateMarkdown(summary: BenchmarkSummary): string {
- const { results, timestamp, providers } = summary;
- const lines: string[] = [];
+ const { results, timestamp, providers } = summary
+ const lines: string[] = []
- lines.push("# LLM Provider Benchmark Report");
- lines.push("");
- lines.push(`**Date:** ${timestamp}`);
- lines.push(`**Providers:** ${providers.map((p) => `${p.label} (${p.model})`).join(", ")}`);
- lines.push(`**Total tests:** ${results.length}`);
- lines.push("");
+ lines.push('# LLM Provider Benchmark Report')
+ lines.push('')
+ lines.push(`**Date:** ${timestamp}`)
+ lines.push(`**Providers:** ${providers.map(p => `${p.label} (${p.model})`).join(', ')}`)
+ lines.push(`**Total tests:** ${results.length}`)
+ lines.push('')
// ---- Overall Summary ----
- lines.push("## Overall Summary");
- lines.push("");
+ lines.push('## Overall Summary')
+ lines.push('')
- const provAgg = aggregateByProvider(results);
- lines.push("| Provider | Model | Avg Score | Avg Latency | Pass Rate | Tests |");
- lines.push("|----------|-------|-----------|-------------|-----------|-------|");
+ const provAgg = aggregateByProvider(results)
+ lines.push('| Provider | Model | Avg Score | Avg Latency | Pass Rate | Tests |')
+ lines.push('|----------|-------|-----------|-------------|-----------|-------|')
for (const [key, stats] of provAgg) {
- const [prov, model] = key.split("/");
+ const [prov, model] = key.split('/')
lines.push(
- `| ${prov} | ${model} | ${stats.avgScore.toFixed(1)} | ${(stats.avgLatency / 1000).toFixed(1)}s | ${(stats.passRate * 100).toFixed(0)}% | ${stats.count} |`,
- );
+ `| ${prov} | ${model} | ${stats.avgScore.toFixed(1)} | ${(stats.avgLatency / 1000).toFixed(1)}s | ${(stats.passRate * 100).toFixed(0)}% | ${stats.count} |`
+ )
}
- lines.push("");
+ lines.push('')
// ---- Category Breakdown ----
- lines.push("## By Category");
- lines.push("");
+ lines.push('## By Category')
+ lines.push('')
- const catAgg = aggregateByCategory(results);
+ const catAgg = aggregateByCategory(results)
for (const [cat, provMap] of catAgg) {
- lines.push(`### ${formatCategory(cat)}`);
- lines.push("");
- lines.push("| Provider | Avg Score | Avg Latency | Tests |");
- lines.push("|----------|-----------|-------------|-------|");
+ lines.push(`### ${formatCategory(cat)}`)
+ lines.push('')
+ lines.push('| Provider | Avg Score | Avg Latency | Tests |')
+ lines.push('|----------|-----------|-------------|-------|')
for (const [prov, stats] of provMap) {
lines.push(
- `| ${prov} | ${stats.avgScore.toFixed(1)} | ${(stats.avgLatency / 1000).toFixed(1)}s | ${stats.count} |`,
- );
+ `| ${prov} | ${stats.avgScore.toFixed(1)} | ${(stats.avgLatency / 1000).toFixed(1)}s | ${stats.count} |`
+ )
}
- lines.push("");
+ lines.push('')
}
// ---- Detailed Results ----
- lines.push("## Detailed Results");
- lines.push("");
+ lines.push('## Detailed Results')
+ lines.push('')
- const providerKeys = [...provAgg.keys()];
+ const providerKeys = [...provAgg.keys()]
const header =
- "| Test ID | Difficulty | " +
- providerKeys.map((k) => `${k} Score`).join(" | ") +
- " | " +
- providerKeys.map((k) => `${k} Latency`).join(" | ") +
- " |";
+ '| Test ID | Difficulty | ' +
+ providerKeys.map(k => `${k} Score`).join(' | ') +
+ ' | ' +
+ providerKeys.map(k => `${k} Latency`).join(' | ') +
+ ' |'
const sep =
- "|---------|------------|" +
- providerKeys.map(() => "----------").join("|") +
- "|" +
- providerKeys.map(() => "----------").join("|") +
- "|";
+ '|---------|------------|' +
+ providerKeys.map(() => '----------').join('|') +
+ '|' +
+ providerKeys.map(() => '----------').join('|') +
+ '|'
- lines.push(header);
- lines.push(sep);
+ lines.push(header)
+ lines.push(sep)
- const testIds = [...new Set(results.map((r) => r.testId))];
+ const testIds = [...new Set(results.map(r => r.testId))]
for (const testId of testIds) {
- const first = results.find((r) => r.testId === testId)!;
- let row = `| ${testId} | ${first.difficulty} |`;
+ const first = results.find(r => r.testId === testId)!
+ let row = `| ${testId} | ${first.difficulty} |`
for (const key of providerKeys) {
- const r = results.find(
- (res) => res.testId === testId && `${res.provider}/${res.model}` === key,
- );
- row += ` ${r ? (r.success ? r.score.toString() : "FAIL") : "--"} |`;
+ const r = results.find(res => res.testId === testId && `${res.provider}/${res.model}` === key)
+ row += ` ${r ? (r.success ? r.score.toString() : 'FAIL') : '--'} |`
}
for (const key of providerKeys) {
- const r = results.find(
- (res) => res.testId === testId && `${res.provider}/${res.model}` === key,
- );
- row += ` ${r ? `${(r.latencyMs / 1000).toFixed(1)}s` : "--"} |`;
+ const r = results.find(res => res.testId === testId && `${res.provider}/${res.model}` === key)
+ row += ` ${r ? `${(r.latencyMs / 1000).toFixed(1)}s` : '--'} |`
}
- lines.push(row);
+ lines.push(row)
}
- lines.push("");
+ lines.push('')
// ---- Best Provider per Category ----
- lines.push("## Best Provider by Category");
- lines.push("");
- lines.push("| Category | Best Provider | Avg Score |");
- lines.push("|----------|---------------|-----------|");
+ lines.push('## Best Provider by Category')
+ lines.push('')
+ lines.push('| Category | Best Provider | Avg Score |')
+ lines.push('|----------|---------------|-----------|')
for (const [cat, provMap] of catAgg) {
- let best = "";
- let bestScore = 0;
+ let best = ''
+ let bestScore = 0
for (const [prov, stats] of provMap) {
if (stats.avgScore > bestScore) {
- bestScore = stats.avgScore;
- best = prov;
+ bestScore = stats.avgScore
+ best = prov
}
}
- lines.push(
- `| ${formatCategory(cat)} | ${best || "N/A"} | ${bestScore.toFixed(1)} |`,
- );
+ lines.push(`| ${formatCategory(cat)} | ${best || 'N/A'} | ${bestScore.toFixed(1)} |`)
}
- lines.push("");
+ lines.push('')
- return lines.join("\n");
+ return lines.join('\n')
}
function formatCategory(cat: string): string {
return cat
- .split("_")
- .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
- .join(" ");
+ .split('_')
+ .map(w => w.charAt(0).toUpperCase() + w.slice(1))
+ .join(' ')
}
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
-const arg = process.argv[2];
-const summary = loadResults(arg);
-const markdown = generateMarkdown(summary);
-console.log(markdown);
+const arg = process.argv[2]
+const summary = loadResults(arg)
+const markdown = generateMarkdown(summary)
+console.log(markdown)
diff --git a/tests/e2e/benchmark/scoring.ts b/tests/e2e/benchmark/scoring.ts
index a96e4c27e..c3c1d3240 100644
--- a/tests/e2e/benchmark/scoring.ts
+++ b/tests/e2e/benchmark/scoring.ts
@@ -4,9 +4,8 @@
* All scoring is deterministic (regex/keyword/format checks).
* No LLM-based evaluation to keep results reproducible.
*/
-
-import type { BenchmarkResult } from "./helpers.js";
-import { ALL_PROMPTS, type BenchmarkPrompt } from "./prompts.js";
+import type { BenchmarkResult } from './helpers.js'
+import { ALL_PROMPTS, type BenchmarkPrompt } from './prompts.js'
/**
* Score a single benchmark result using the validator from its prompt definition.
@@ -14,29 +13,29 @@ import { ALL_PROMPTS, type BenchmarkPrompt } from "./prompts.js";
*/
export function scoreResult(result: BenchmarkResult): number {
if (!result.response || !result.success) {
- result.score = 0;
- return 0;
+ result.score = 0
+ return 0
}
- const prompt = ALL_PROMPTS.find((p) => p.id === result.testId);
+ const prompt = ALL_PROMPTS.find(p => p.id === result.testId)
if (!prompt) {
- console.warn(`[Scoring] No prompt found for testId: ${result.testId}`);
- result.score = 0;
- return 0;
+ console.warn(`[Scoring] No prompt found for testId: ${result.testId}`)
+ result.score = 0
+ return 0
}
try {
- const score = prompt.validate(result.response);
- result.score = Math.max(0, Math.min(100, score));
+ const score = prompt.validate(result.response)
+ result.score = Math.max(0, Math.min(100, score))
} catch (e) {
console.warn(
`[Scoring] Validator threw for ${result.testId}:`,
- e instanceof Error ? e.message : e,
- );
- result.score = 0;
+ e instanceof Error ? e.message : e
+ )
+ result.score = 0
}
- return result.score;
+ return result.score
}
/**
@@ -44,7 +43,7 @@ export function scoreResult(result: BenchmarkResult): number {
*/
export function scoreAll(results: BenchmarkResult[]): void {
for (const r of results) {
- scoreResult(r);
+ scoreResult(r)
}
}
@@ -52,89 +51,72 @@ export function scoreAll(results: BenchmarkResult[]): void {
* Compute aggregate scores grouped by provider.
*/
export function aggregateByProvider(
- results: BenchmarkResult[],
+ results: BenchmarkResult[]
): Map<string, { avgScore: number; avgLatency: number; passRate: number; count: number }> {
- const grouped = new Map<string, BenchmarkResult[]>();
+ const grouped = new Map<string, BenchmarkResult[]>()
for (const r of results) {
- const key = `${r.provider}/${r.model}`;
- if (!grouped.has(key)) grouped.set(key, []);
- grouped.get(key)!.push(r);
+ const key = `${r.provider}/${r.model}`
+ if (!grouped.has(key)) grouped.set(key, [])
+ grouped.get(key)!.push(r)
}
const agg = new Map<
string,
{ avgScore: number; avgLatency: number; passRate: number; count: number }
- >();
+ >()
for (const [key, provResults] of grouped) {
- const passed = provResults.filter((r) => r.success);
- const avgScore =
- passed.length > 0
- ? passed.reduce((s, r) => s + r.score, 0) / passed.length
- : 0;
+ const passed = provResults.filter(r => r.success)
+ const avgScore = passed.length > 0 ? passed.reduce((s, r) => s + r.score, 0) / passed.length : 0
const avgLatency =
- passed.length > 0
- ? passed.reduce((s, r) => s + r.latencyMs, 0) / passed.length
- : 0;
- const passRate =
- provResults.length > 0 ? passed.length / provResults.length : 0;
+ passed.length > 0 ? passed.reduce((s, r) => s + r.latencyMs, 0) / passed.length : 0
+ const passRate = provResults.length > 0 ? passed.length / provResults.length : 0
agg.set(key, {
avgScore,
avgLatency,
passRate,
count: provResults.length,
- });
+ })
}
- return agg;
+ return agg
}
/**
* Compute aggregate scores grouped by category.
*/
export function aggregateByCategory(
- results: BenchmarkResult[],
-): Map<
- string,
- Map<string, { avgScore: number; avgLatency: number; count: number }>
-> {
- const byCat = new Map<string, Map<string, BenchmarkResult[]>>();
+ results: BenchmarkResult[]
+): Map<string, Map<string, { avgScore: number; avgLatency: number; count: number }>> {
+ const byCat = new Map<string, Map<string, BenchmarkResult[]>>()
for (const r of results) {
- if (!byCat.has(r.category)) byCat.set(r.category, new Map());
- const provMap = byCat.get(r.category)!;
- const key = `${r.provider}/${r.model}`;
- if (!provMap.has(key)) provMap.set(key, []);
- provMap.get(key)!.push(r);
+ if (!byCat.has(r.category)) byCat.set(r.category, new Map())
+ const provMap = byCat.get(r.category)!
+ const key = `${r.provider}/${r.model}`
+ if (!provMap.has(key)) provMap.set(key, [])
+ provMap.get(key)!.push(r)
}
const result = new Map<
string,
Map<string, { avgScore: number; avgLatency: number; count: number }>
- >();
+ >()
for (const [cat, provMap] of byCat) {
- const catAgg = new Map<
- string,
- { avgScore: number; avgLatency: number; count: number }
- >();
+ const catAgg = new Map<string, { avgScore: number; avgLatency: number; count: number }>()
for (const [prov, rs] of provMap) {
- const passed = rs.filter((r) => r.success);
+ const passed = rs.filter(r => r.success)
catAgg.set(prov, {
- avgScore:
- passed.length > 0
- ? passed.reduce((s, r) => s + r.score, 0) / passed.length
- : 0,
+ avgScore: passed.length > 0 ? passed.reduce((s, r) => s + r.score, 0) / passed.length : 0,
avgLatency:
- passed.length > 0
- ? passed.reduce((s, r) => s + r.latencyMs, 0) / passed.length
- : 0,
+ passed.length > 0 ? passed.reduce((s, r) => s + r.latencyMs, 0) / passed.length : 0,
count: rs.length,
- });
+ })
}
- result.set(cat, catAgg);
+ result.set(cat, catAgg)
}
- return result;
+ return result
}
diff --git a/tests/e2e/external-rest-api/helpers/ports.ts b/tests/e2e/external-rest-api/helpers/ports.ts
index f45e9efbf..047cf7bd1 100644
--- a/tests/e2e/external-rest-api/helpers/ports.ts
+++ b/tests/e2e/external-rest-api/helpers/ports.ts
@@ -1,18 +1,18 @@
-import { createServer } from "node:net";
+import { createServer } from 'node:net'
export async function getFreePort(): Promise<number> {
return await new Promise<number>((resolve, reject) => {
- const server = createServer();
- server.listen(0, "127.0.0.1", () => {
- const addr = server.address();
- if (!addr || typeof addr === "string") {
- server.close();
- reject(new Error("Unable to determine free TCP port"));
- return;
+ const server = createServer()
+ server.listen(0, '127.0.0.1', () => {
+ const addr = server.address()
+ if (!addr || typeof addr === 'string') {
+ server.close()
+ reject(new Error('Unable to determine free TCP port'))
+ return
}
- const port = addr.port;
- server.close((error) => (error ? reject(error) : resolve(port)));
- });
- server.on("error", reject);
- });
+ const port = addr.port
+ server.close(error => (error ? reject(error) : resolve(port)))
+ })
+ server.on('error', reject)
+ })
}
diff --git a/tests/e2e/fixtures/mailpit.yaml b/tests/e2e/fixtures/mailpit.yaml
index 462d44c5f..b929fbd87 100644
--- a/tests/e2e/fixtures/mailpit.yaml
+++ b/tests/e2e/fixtures/mailpit.yaml
@@ -14,22 +14,22 @@ spec:
app: mailpit
spec:
containers:
- - name: mailpit
- image: axllent/mailpit:latest
- ports:
- - containerPort: 1025
- name: smtp
- - containerPort: 1143
- name: imap
- - containerPort: 8025
- name: web
- resources:
- requests:
- memory: "64Mi"
- cpu: "50m"
- limits:
- memory: "128Mi"
- cpu: "200m"
+ - name: mailpit
+ image: axllent/mailpit:latest
+ ports:
+ - containerPort: 1025
+ name: smtp
+ - containerPort: 1143
+ name: imap
+ - containerPort: 8025
+ name: web
+ resources:
+ requests:
+ memory: '64Mi'
+ cpu: '50m'
+ limits:
+ memory: '128Mi'
+ cpu: '200m'
---
apiVersion: v1
kind: Service
@@ -40,12 +40,12 @@ spec:
selector:
app: mailpit
ports:
- - name: smtp
- port: 1025
- targetPort: 1025
- - name: imap
- port: 1143
- targetPort: 1143
- - name: web
- port: 8025
- targetPort: 8025
+ - name: smtp
+ port: 1025
+ targetPort: 1025
+ - name: imap
+ port: 1143
+ targetPort: 1143
+ - name: web
+ port: 8025
+ targetPort: 8025
diff --git a/tests/e2e/fixtures/mock-stdio-mcp-server/package-lock.json b/tests/e2e/fixtures/mock-stdio-mcp-server/package-lock.json
index b08e62faa..cdc263d5a 100644
--- a/tests/e2e/fixtures/mock-stdio-mcp-server/package-lock.json
+++ b/tests/e2e/fixtures/mock-stdio-mcp-server/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "mock-stdio-mcp-server",
- "version": "0.1.3",
+ "version": "0.1.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "mock-stdio-mcp-server",
- "version": "0.1.3",
+ "version": "0.1.4",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.0.0",
"zod": "^3.23.0"
diff --git a/tests/e2e/fixtures/mock-stdio-mcp-server/package.json b/tests/e2e/fixtures/mock-stdio-mcp-server/package.json
index a77b21673..82019882d 100644
--- a/tests/e2e/fixtures/mock-stdio-mcp-server/package.json
+++ b/tests/e2e/fixtures/mock-stdio-mcp-server/package.json
@@ -1,6 +1,6 @@
{
"name": "mock-stdio-mcp-server",
- "version": "0.1.3",
+ "version": "0.1.4",
"private": true,
"type": "module",
"scripts": {
diff --git a/tests/e2e/fixtures/mock-stdio-mcp-server/src/index.ts b/tests/e2e/fixtures/mock-stdio-mcp-server/src/index.ts
index b66c61400..a0543198e 100644
--- a/tests/e2e/fixtures/mock-stdio-mcp-server/src/index.ts
+++ b/tests/e2e/fixtures/mock-stdio-mcp-server/src/index.ts
@@ -1,31 +1,31 @@
-import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
-import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
-import { z } from "zod";
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
+import { z } from 'zod'
const server = new McpServer({
- name: "mock-stdio-mcp-server",
- version: "0.1.0",
-});
+ name: 'mock-stdio-mcp-server',
+ version: '0.1.0',
+})
-server.tool("echo", { text: z.string() }, async ({ text }) => ({
- content: [{ type: "text", text: `Echo: ${text}` }],
-}));
+server.tool('echo', { text: z.string() }, async ({ text }) => ({
+ content: [{ type: 'text', text: `Echo: ${text}` }],
+}))
-server.tool("add", { a: z.number(), b: z.number() }, async ({ a, b }) => ({
- content: [{ type: "text", text: String(a + b) }],
-}));
+server.tool('add', { a: z.number(), b: z.number() }, async ({ a, b }) => ({
+ content: [{ type: 'text', text: String(a + b) }],
+}))
-server.tool("multiply", { a: z.number(), b: z.number() }, async ({ a, b }) => ({
- content: [{ type: "text", text: String(a * b) }],
-}));
+server.tool('multiply', { a: z.number(), b: z.number() }, async ({ a, b }) => ({
+ content: [{ type: 'text', text: String(a * b) }],
+}))
-server.tool("get_time", {}, async () => ({
- content: [{ type: "text", text: new Date().toISOString() }],
-}));
+server.tool('get_time', {}, async () => ({
+ content: [{ type: 'text', text: new Date().toISOString() }],
+}))
-server.tool("read_env", { name: z.string() }, async ({ name }) => ({
- content: [{ type: "text", text: process.env[name] ?? `<${name} not set>` }],
-}));
+server.tool('read_env', { name: z.string() }, async ({ name }) => ({
+ content: [{ type: 'text', text: process.env[name] ?? `<${name} not set>` }],
+}))
-const transport = new StdioServerTransport();
-await server.connect(transport);
+const transport = new StdioServerTransport()
+await server.connect(transport)
diff --git a/tests/e2e/fixtures/package-lock.json b/tests/e2e/fixtures/package-lock.json
index 2d5bc553d..ca1aff470 100644
--- a/tests/e2e/fixtures/package-lock.json
+++ b/tests/e2e/fixtures/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@clerum/e2e-test-fixtures",
- "version": "1.0.50",
+ "version": "1.0.51",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@clerum/e2e-test-fixtures",
- "version": "1.0.50",
+ "version": "1.0.51",
"dependencies": {
"@kubernetes/client-node": "^1.0.0"
},
diff --git a/tests/e2e/fixtures/package.json b/tests/e2e/fixtures/package.json
index 521c90436..8e03149f1 100644
--- a/tests/e2e/fixtures/package.json
+++ b/tests/e2e/fixtures/package.json
@@ -1,6 +1,6 @@
{
"name": "@clerum/e2e-test-fixtures",
- "version": "1.0.50",
+ "version": "1.0.51",
"description": "E2E test fixtures and utilities for Clerum testing",
"type": "module",
"main": "index.ts",
diff --git a/tests/e2e/fixtures/secret-manager.ts b/tests/e2e/fixtures/secret-manager.ts
index 00d04affd..ab59160ef 100644
--- a/tests/e2e/fixtures/secret-manager.ts
+++ b/tests/e2e/fixtures/secret-manager.ts
@@ -22,55 +22,54 @@
* await cleanupTestSecret('mcp-mongodb-credentials', 'mcp-server');
* ```
*/
-
-import { execSync } from 'child_process';
-import { KubeConfig, CoreV1Api } from '@kubernetes/client-node';
+import { CoreV1Api, KubeConfig } from '@kubernetes/client-node'
+import { execSync } from 'child_process'
// =============================================================================
// Types
// =============================================================================
export interface SecretCredentials {
- [key: string]: string;
+ [key: string]: string
}
export interface TestSecretOptions {
- namespace?: string;
- labels?: Record<string, string>;
- annotations?: Record<string, string>;
+ namespace?: string
+ labels?: Record<string, string>
+ annotations?: Record<string, string>
}
export interface SecretMountInfo {
- secretName: string;
- namespace: string;
+ secretName: string
+ namespace: string
envVars: Array<{
- name: string;
+ name: string
secretKeyRef: {
- name: string;
- key: string;
- };
- }>;
+ name: string
+ key: string
+ }
+ }>
volumes: Array<{
- name: string;
+ name: string
secret: {
- secretName: string;
- };
- }>;
+ secretName: string
+ }
+ }>
}
// =============================================================================
// Kubernetes Client Setup
// =============================================================================
-let k8sCoreApi: CoreV1Api | null = null;
+let k8sCoreApi: CoreV1Api | null = null
function getK8sCoreApi(): CoreV1Api {
if (!k8sCoreApi) {
- const kc = new KubeConfig();
- kc.loadFromDefault(); // Uses ~/.kube/config or minikube config
- k8sCoreApi = kc.makeApiClient(CoreV1Api);
+ const kc = new KubeConfig()
+ kc.loadFromDefault() // Uses ~/.kube/config or minikube config
+ k8sCoreApi = kc.makeApiClient(CoreV1Api)
}
- return k8sCoreApi;
+ return k8sCoreApi
}
// =============================================================================
@@ -96,17 +95,17 @@ export async function createTestSecret(
credentials: SecretCredentials,
options: TestSecretOptions = {}
): Promise<void> {
- const { namespace = 'mcp-server', labels = {}, annotations = {} } = options;
+ const { namespace = 'mcp-server', labels = {}, annotations = {} } = options
// Derive secret name from server name
- const secretName = `mcp-${serverName}-credentials`;
+ const secretName = `mcp-${serverName}-credentials`
// Create metadata with standard labels
const metadata: Record<string, any> = {
name: secretName,
namespace,
labels: {
- 'app': `mcp-${serverName}`,
+ app: `mcp-${serverName}`,
'clerum.io/test': 'true',
'clerum.io/e2e': 'true',
...labels,
@@ -115,12 +114,12 @@ export async function createTestSecret(
'clerum.io/generated-by': 'secret-manager.ts',
...annotations,
},
- };
+ }
// Build secret data (values must be base64 encoded)
- const data: Record<string, string> = {};
+ const data: Record<string, string> = {}
for (const [key, value] of Object.entries(credentials)) {
- data[key] = Buffer.from(value, 'utf-8').toString('base64');
+ data[key] = Buffer.from(value, 'utf-8').toString('base64')
}
const secret = {
@@ -129,20 +128,20 @@ export async function createTestSecret(
type: 'Opaque',
metadata,
data,
- };
+ }
try {
- const api = getK8sCoreApi();
- await api.createNamespacedSecret(namespace, secret);
- console.log(`[SecretManager] Created secret: ${secretName} in namespace ${namespace}`);
+ const api = getK8sCoreApi()
+ await api.createNamespacedSecret(namespace, secret)
+ console.log(`[SecretManager] Created secret: ${secretName} in namespace ${namespace}`)
} catch (error: any) {
if (error.statusCode === 409) {
// Secret already exists - update it
- const api = getK8sCoreApi();
- await api.replaceNamespacedSecret(secretName, namespace, secret);
- console.log(`[SecretManager] Updated secret: ${secretName} in namespace ${namespace}`);
+ const api = getK8sCoreApi()
+ await api.replaceNamespacedSecret(secretName, namespace, secret)
+ console.log(`[SecretManager] Updated secret: ${secretName} in namespace ${namespace}`)
} else {
- throw new Error(`Failed to create secret ${secretName}: ${error.message}`);
+ throw new Error(`Failed to create secret ${secretName}: ${error.message}`)
}
}
}
@@ -167,8 +166,8 @@ export async function createMultipleSecrets(
): Promise<void> {
const promises = Object.entries(servers).map(([serverName, credentials]) =>
createTestSecret(serverName, credentials, options)
- );
- await Promise.all(promises);
+ )
+ await Promise.all(promises)
}
// =============================================================================
@@ -185,9 +184,13 @@ export async function createMongoTestSecret(
connectionString: string = 'mongodb://localhost:27017/test',
options: TestSecretOptions = {}
): Promise<void> {
- await createTestSecret('mongodb-server', {
- 'connection-string': connectionString,
- }, options);
+ await createTestSecret(
+ 'mongodb-server',
+ {
+ 'connection-string': connectionString,
+ },
+ options
+ )
}
/**
@@ -200,9 +203,13 @@ export async function createAirtableTestSecret(
apiKey: string = 'patDummyDummyDummyDummyDummyDummyDummyDummyDummyDummyDummy',
options: TestSecretOptions = {}
): Promise<void> {
- await createTestSecret('airtable-server', {
- 'api-key': apiKey,
- }, options);
+ await createTestSecret(
+ 'airtable-server',
+ {
+ 'api-key': apiKey,
+ },
+ options
+ )
}
/**
@@ -210,13 +217,11 @@ export async function createAirtableTestSecret(
*
* @param options - Optional configuration applied to all secrets
*/
-export async function createAllMcpTestSecrets(
- options: TestSecretOptions = {}
-): Promise<void> {
+export async function createAllMcpTestSecrets(options: TestSecretOptions = {}): Promise<void> {
await Promise.all([
createMongoTestSecret(undefined, options),
createAirtableTestSecret(undefined, options),
- ]);
+ ])
}
// =============================================================================
@@ -236,14 +241,14 @@ export async function verifySecretExists(
namespace: string = 'mcp-server'
): Promise<boolean> {
try {
- const api = getK8sCoreApi();
- await api.readNamespacedSecret(secretName, namespace);
- return true;
+ const api = getK8sCoreApi()
+ await api.readNamespacedSecret(secretName, namespace)
+ return true
} catch (error: any) {
if (error.statusCode === 404) {
- return false;
+ return false
}
- throw error;
+ throw error
}
}
@@ -259,17 +264,17 @@ export async function getSecretContents(
secretName: string,
namespace: string = 'mcp-server'
): Promise<Record<string, string>> {
- const api = getK8sCoreApi();
- const { body } = await api.readNamespacedSecret(secretName, namespace);
+ const api = getK8sCoreApi()
+ const { body } = await api.readNamespacedSecret(secretName, namespace)
- const decoded: Record<string, string> = {};
+ const decoded: Record<string, string> = {}
if (body.data) {
for (const [key, value] of Object.entries(body.data)) {
- decoded[key] = Buffer.from(value as string, 'base64').toString('utf-8');
+ decoded[key] = Buffer.from(value as string, 'base64').toString('utf-8')
}
}
- return decoded;
+ return decoded
}
/**
@@ -290,18 +295,18 @@ export async function verifySecretMounted(
secretName: string,
namespace: string = 'mcp-server'
): Promise<SecretMountInfo> {
- const api = getK8sCoreApi();
- const { body: pod } = await api.readNamespacedPod(podName, namespace);
+ const api = getK8sCoreApi()
+ const { body: pod } = await api.readNamespacedPod(podName, namespace)
const mountInfo: SecretMountInfo = {
secretName,
namespace,
envVars: [],
volumes: [],
- };
+ }
// Check containers for envFrom and env secretKeyRef
- const containers = pod.spec?.containers || [];
+ const containers = pod.spec?.containers || []
for (const container of containers) {
// Check envFrom
if (container.envFrom) {
@@ -313,7 +318,7 @@ export async function verifySecretMounted(
name: secretName,
key: '*',
},
- });
+ })
}
}
}
@@ -325,32 +330,32 @@ export async function verifySecretMounted(
mountInfo.envVars.push({
name: env.name,
secretKeyRef: env.valueFrom.secretKeyRef as any,
- });
+ })
}
}
}
}
// Check volumes
- const volumes = pod.spec?.volumes || [];
+ const volumes = pod.spec?.volumes || []
for (const volume of volumes) {
if (volume.secret?.secretName === secretName) {
mountInfo.volumes.push({
name: volume.name,
secret: volume.secret as any,
- });
+ })
}
}
- const isMounted = mountInfo.envVars.length > 0 || mountInfo.volumes.length > 0;
+ const isMounted = mountInfo.envVars.length > 0 || mountInfo.volumes.length > 0
console.log(`[SecretManager] Secret ${secretName} mount check:`, {
mounted: isMounted,
envVars: mountInfo.envVars.length,
volumes: mountInfo.volumes.length,
- });
+ })
- return mountInfo;
+ return mountInfo
}
// =============================================================================
@@ -368,13 +373,13 @@ export async function cleanupTestSecret(
namespace: string = 'mcp-server'
): Promise<void> {
try {
- const api = getK8sCoreApi();
- await api.deleteNamespacedSecret(secretName, namespace);
- console.log(`[SecretManager] Deleted secret: ${secretName} from namespace ${namespace}`);
+ const api = getK8sCoreApi()
+ await api.deleteNamespacedSecret(secretName, namespace)
+ console.log(`[SecretManager] Deleted secret: ${secretName} from namespace ${namespace}`)
} catch (error: any) {
if (error.statusCode !== 404) {
// Ignore 404 (already deleted), throw other errors
- throw new Error(`Failed to delete secret ${secretName}: ${error.message}`);
+ throw new Error(`Failed to delete secret ${secretName}: ${error.message}`)
}
}
}
@@ -386,10 +391,8 @@ export async function cleanupTestSecret(
*
* @param namespace - Namespace to clean up
*/
-export async function cleanupAllTestSecrets(
- namespace: string = 'mcp-server'
-): Promise<void> {
- const api = getK8sCoreApi();
+export async function cleanupAllTestSecrets(namespace: string = 'mcp-server'): Promise<void> {
+ const api = getK8sCoreApi()
const { body } = await api.listNamespacedSecret(
namespace,
undefined, // pretty
@@ -398,14 +401,14 @@ export async function cleanupAllTestSecrets(
undefined, // fieldSelector
undefined, // labelSelector
'clerum.io/test=true' // labelSelector to filter test secrets
- );
+ )
const deletePromises = body.items.map(secret =>
cleanupTestSecret(secret.metadata!.name!, namespace)
- );
+ )
- await Promise.all(deletePromises);
- console.log(`[SecretManager] Cleaned up ${deletePromises.length} test secret(s)`);
+ await Promise.all(deletePromises)
+ console.log(`[SecretManager] Cleaned up ${deletePromises.length} test secret(s)`)
}
// =============================================================================
@@ -428,24 +431,25 @@ export function createMcpTestSecretsBeforeEach(
options: TestSecretOptions = {}
): () => Promise<void> {
return async () => {
- const secrets: Record<string, SecretCredentials> = {};
+ const secrets: Record<string, SecretCredentials> = {}
if (servers.includes('mongodb-server')) {
secrets['mongodb-server'] = {
- 'connection-string': process.env.MONGODB_CONNECTION_STRING ||
- 'mongodb://localhost:27017/test',
- };
+ 'connection-string':
+ process.env.MONGODB_CONNECTION_STRING || 'mongodb://localhost:27017/test',
+ }
}
if (servers.includes('airtable-server')) {
secrets['airtable-server'] = {
- 'api-key': process.env.AIRTABLE_API_KEY ||
+ 'api-key':
+ process.env.AIRTABLE_API_KEY ||
'patDummyDummyDummyDummyDummyDummyDummyDummyDummyDummyDummy',
- };
+ }
}
- await createMultipleSecrets(secrets, options);
- };
+ await createMultipleSecrets(secrets, options)
+ }
}
/**
@@ -465,10 +469,10 @@ export function cleanupMcpTestSecretsAfterEach(
): () => Promise<void> {
return async () => {
for (const server of servers) {
- const secretName = `mcp-${server}-credentials`;
- await cleanupTestSecret(secretName, namespace);
+ const secretName = `mcp-${server}-credentials`
+ await cleanupTestSecret(secretName, namespace)
}
- };
+ }
}
// =============================================================================
@@ -483,7 +487,7 @@ export function cleanupMcpTestSecretsAfterEach(
* @returns Base64-encoded string
*/
export function encodeSecretValue(value: string): string {
- return Buffer.from(value, 'utf-8').toString('base64');
+ return Buffer.from(value, 'utf-8').toString('base64')
}
/**
@@ -494,7 +498,7 @@ export function encodeSecretValue(value: string): string {
* @returns Decoded string value
*/
export function decodeSecretValue(encodedValue: string): string {
- return Buffer.from(encodedValue, 'base64').toString('utf-8');
+ return Buffer.from(encodedValue, 'base64').toString('utf-8')
}
/**
@@ -509,9 +513,9 @@ function kubectl(...args: string[]): string {
return execSync(`kubectl ${args.join(' ')}`, {
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
- });
+ })
} catch (error: any) {
- throw new Error(`kubectl command failed: ${error.message}`);
+ throw new Error(`kubectl command failed: ${error.message}`)
}
}
@@ -527,23 +531,30 @@ export function createTestSecretKubectl(
credentials: SecretCredentials,
namespace: string = 'mcp-server'
): void {
- const secretName = `mcp-${serverName}-credentials`;
+ const secretName = `mcp-${serverName}-credentials`
// Build --from-literal arguments
const literalArgs = Object.entries(credentials)
.map(([key, value]) => `--from-literal=${key}=${value}`)
- .join(' ');
+ .join(' ')
const command = [
- 'create', 'secret', 'generic', secretName,
+ 'create',
+ 'secret',
+ 'generic',
+ secretName,
`--namespace=${namespace}`,
literalArgs,
'--dry-run=client',
- '-o', 'yaml',
+ '-o',
+ 'yaml',
'|',
- 'kubectl', 'apply', '-f', '-',
- ].join(' ');
-
- kubectl(command);
- console.log(`[SecretManager] Created secret via kubectl: ${secretName}`);
+ 'kubectl',
+ 'apply',
+ '-f',
+ '-',
+ ].join(' ')
+
+ kubectl(command)
+ console.log(`[SecretManager] Created secret via kubectl: ${secretName}`)
}
diff --git a/tests/e2e/integration/contracts.test.ts b/tests/e2e/integration/contracts.test.ts
index 760b972ea..195d1ad2d 100644
--- a/tests/e2e/integration/contracts.test.ts
+++ b/tests/e2e/integration/contracts.test.ts
@@ -6,142 +6,141 @@
* but can also validate response shapes from static fixtures when the
* cluster is not up.
*/
-
-import { describe, it, expect, beforeAll } from "vitest";
+import { beforeAll, describe, expect, it } from 'vitest'
import {
- EXTERNAL_REST_API_URL,
CONTROL_API_URL,
+ EXTERNAL_REST_API_URL,
MCP_HOST_URL,
- isServiceUp,
fetchJson,
-} from "./helpers.integration.js";
+ isServiceUp,
+} from './helpers.integration.js'
// ── Schema validators (pure, no cluster needed) ───────────────────────────────
function isValidLoginResult(data: unknown): boolean {
- if (!data || typeof data !== "object") return false;
- const d = data as Record<string, unknown>;
- return typeof d["token"] === "string" && d["token"].length > 0;
+ if (!data || typeof data !== 'object') return false
+ const d = data as Record<string, unknown>
+ return typeof d['token'] === 'string' && d['token'].length > 0
}
function isValidHealthResponse(data: unknown): boolean {
- if (!data || typeof data !== "object") return false;
- const d = data as Record<string, unknown>;
- return typeof d["status"] === "string";
+ if (!data || typeof data !== 'object') return false
+ const d = data as Record<string, unknown>
+ return typeof d['status'] === 'string'
}
function isValidMessageResponse(data: unknown): boolean {
- if (!data || typeof data !== "object") return false;
- const d = data as Record<string, unknown>;
- return typeof d["success"] === "boolean";
+ if (!data || typeof data !== 'object') return false
+ const d = data as Record<string, unknown>
+ return typeof d['success'] === 'boolean'
}
// ── Pure schema tests (no cluster needed) ─────────────────────────────────────
-describe("Contracts — schema validators (pure)", () => {
- it("isValidLoginResult accepts valid token response", () => {
- expect(isValidLoginResult({ token: "abc123", user: {} })).toBe(true);
- });
-
- it("isValidLoginResult rejects response without token", () => {
- expect(isValidLoginResult({ error: "invalid" })).toBe(false);
- expect(isValidLoginResult(null)).toBe(false);
- expect(isValidLoginResult({ token: "" })).toBe(false);
- });
-
- it("isValidHealthResponse accepts { status: string }", () => {
- expect(isValidHealthResponse({ status: "ok" })).toBe(true);
- expect(isValidHealthResponse({ status: "degraded" })).toBe(true);
- });
-
- it("isValidHealthResponse rejects missing status field", () => {
- expect(isValidHealthResponse({})).toBe(false);
- expect(isValidHealthResponse({ healthy: true })).toBe(false);
- });
-
- it("isValidMessageResponse accepts { success: boolean }", () => {
- expect(isValidMessageResponse({ success: true, status: "completed" })).toBe(true);
- expect(isValidMessageResponse({ success: false, error: "timeout" })).toBe(true);
- });
-
- it("isValidMessageResponse rejects missing success field", () => {
- expect(isValidMessageResponse({ status: "ok" })).toBe(false);
- expect(isValidMessageResponse(null)).toBe(false);
- });
-});
+describe('Contracts — schema validators (pure)', () => {
+ it('isValidLoginResult accepts valid token response', () => {
+ expect(isValidLoginResult({ token: 'abc123', user: {} })).toBe(true)
+ })
+
+ it('isValidLoginResult rejects response without token', () => {
+ expect(isValidLoginResult({ error: 'invalid' })).toBe(false)
+ expect(isValidLoginResult(null)).toBe(false)
+ expect(isValidLoginResult({ token: '' })).toBe(false)
+ })
+
+ it('isValidHealthResponse accepts { status: string }', () => {
+ expect(isValidHealthResponse({ status: 'ok' })).toBe(true)
+ expect(isValidHealthResponse({ status: 'degraded' })).toBe(true)
+ })
+
+ it('isValidHealthResponse rejects missing status field', () => {
+ expect(isValidHealthResponse({})).toBe(false)
+ expect(isValidHealthResponse({ healthy: true })).toBe(false)
+ })
+
+ it('isValidMessageResponse accepts { success: boolean }', () => {
+ expect(isValidMessageResponse({ success: true, status: 'completed' })).toBe(true)
+ expect(isValidMessageResponse({ success: false, error: 'timeout' })).toBe(true)
+ })
+
+ it('isValidMessageResponse rejects missing success field', () => {
+ expect(isValidMessageResponse({ status: 'ok' })).toBe(false)
+ expect(isValidMessageResponse(null)).toBe(false)
+ })
+})
// ── Live contract tests (require cluster) ─────────────────────────────────────
-describe("Contracts — external-rest-api /health shape", () => {
- it("returns { status: string } matching contract", async () => {
- const up = await isServiceUp(EXTERNAL_REST_API_URL);
- if (!up) return;
-
- const { status, data } = await fetchJson(`${EXTERNAL_REST_API_URL}/health`);
- expect(status).toBe(200);
- expect(isValidHealthResponse(data)).toBe(true);
- });
-});
-
-describe("Contracts — control-api /health shape", () => {
- it("returns { status: string } matching contract", async () => {
- const up = await isServiceUp(CONTROL_API_URL);
- if (!up) return;
-
- const { status, data } = await fetchJson(`${CONTROL_API_URL}/health`);
- expect(status).toBe(200);
- expect(isValidHealthResponse(data)).toBe(true);
- });
-});
-
-describe("Contracts — mcp-host /v1/runtime/messages response shape", () => {
- it("accepts message (contract: non-5xx, 2xx if LLM responds within 8s)", async () => {
- const up = await isServiceUp(MCP_HOST_URL);
- if (!up) return;
+describe('Contracts — external-rest-api /health shape', () => {
+ it('returns { status: string } matching contract', async () => {
+ const up = await isServiceUp(EXTERNAL_REST_API_URL)
+ if (!up) return
+
+ const { status, data } = await fetchJson(`${EXTERNAL_REST_API_URL}/health`)
+ expect(status).toBe(200)
+ expect(isValidHealthResponse(data)).toBe(true)
+ })
+})
+
+describe('Contracts — control-api /health shape', () => {
+ it('returns { status: string } matching contract', async () => {
+ const up = await isServiceUp(CONTROL_API_URL)
+ if (!up) return
+
+ const { status, data } = await fetchJson(`${CONTROL_API_URL}/health`)
+ expect(status).toBe(200)
+ expect(isValidHealthResponse(data)).toBe(true)
+ })
+})
+
+describe('Contracts — mcp-host /v1/runtime/messages response shape', () => {
+ it('accepts message (contract: non-5xx, 2xx if LLM responds within 8s)', async () => {
+ const up = await isServiceUp(MCP_HOST_URL)
+ if (!up) return
// Use short AbortSignal — mcp-host is synchronous with LLM, which can take >120s.
// We verify the endpoint accepts the request (non-5xx), not LLM completion.
try {
const res = await fetch(`${MCP_HOST_URL}/v1/runtime/messages`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
- content: "contract test",
- hostRef: "chatllm",
- channelId: "contract-test",
- sender: "contract-user",
- channelType: "telegram",
+ content: 'contract test',
+ hostRef: 'chatllm',
+ channelId: 'contract-test',
+ sender: 'contract-user',
+ channelType: 'telegram',
timestamp: new Date().toISOString(),
messageId: `contract-${Date.now()}`,
}),
signal: AbortSignal.timeout(8000),
- });
+ })
// If LLM responds within 8s, validate the contract shape
- expect(res.status).toBeLessThan(500);
+ expect(res.status).toBeLessThan(500)
if (res.status === 200) {
- const data = await res.json();
- expect(isValidMessageResponse(data)).toBe(true);
+ const data = await res.json()
+ expect(isValidMessageResponse(data)).toBe(true)
}
} catch (err: unknown) {
- if (err instanceof Error && (err.name === "AbortError" || err.name === "TimeoutError")) {
+ if (err instanceof Error && (err.name === 'AbortError' || err.name === 'TimeoutError')) {
// LLM took > 8s — endpoint accepted the connection, contract is OK
- return;
+ return
}
- throw err;
+ throw err
}
- });
-});
+ })
+})
-describe("Contracts — external-rest-api 401 shape on protected routes", () => {
- it("returns { error: string } on 401 responses", async () => {
- const up = await isServiceUp(EXTERNAL_REST_API_URL);
- if (!up) return;
+describe('Contracts — external-rest-api 401 shape on protected routes', () => {
+ it('returns { error: string } on 401 responses', async () => {
+ const up = await isServiceUp(EXTERNAL_REST_API_URL)
+ if (!up) return
const { status, data } = await fetchJson<{ error?: string }>(
`${EXTERNAL_REST_API_URL}/api/v1/me`
- );
- expect(status).toBe(401);
+ )
+ expect(status).toBe(401)
// Should have some error indicator
- expect(data).toBeTruthy();
- });
-});
+ expect(data).toBeTruthy()
+ })
+})
diff --git a/tests/e2e/integration/mcp-proxy-routing.test.ts b/tests/e2e/integration/mcp-proxy-routing.test.ts
index 216128604..7ba94383f 100644
--- a/tests/e2e/integration/mcp-proxy-routing.test.ts
+++ b/tests/e2e/integration/mcp-proxy-routing.test.ts
@@ -6,61 +6,59 @@
*
* Note: MCP_PROXY_ENABLED=true must be set on mcp-host for proxy routing.
*/
+import { beforeAll, describe, expect, it } from 'vitest'
+import { MCP_PROXY_URL, bearer, fetchJson, isServiceUp, postJson } from './helpers.integration.js'
-import { describe, it, expect, beforeAll } from "vitest";
-import { MCP_PROXY_URL, isServiceUp, fetchJson, postJson, bearer } from "./helpers.integration.js";
-
-let proxyUp = false;
+let proxyUp = false
beforeAll(async () => {
- proxyUp = await isServiceUp(MCP_PROXY_URL);
+ proxyUp = await isServiceUp(MCP_PROXY_URL)
if (!proxyUp) {
- console.log("[mcp-proxy-routing] mcp-proxy not available — tests will be skipped");
+ console.log('[mcp-proxy-routing] mcp-proxy not available — tests will be skipped')
}
-});
+})
-describe("MCP Proxy — health", () => {
- it("returns 200 on /health", async () => {
- if (!proxyUp) return;
+describe('MCP Proxy — health', () => {
+ it('returns 200 on /health', async () => {
+ if (!proxyUp) return
- const { status } = await fetchJson(`${MCP_PROXY_URL}/health`);
- expect(status).toBe(200);
- });
-});
+ const { status } = await fetchJson(`${MCP_PROXY_URL}/health`)
+ expect(status).toBe(200)
+ })
+})
-describe("MCP Proxy — server list", () => {
- it("GET /servers returns 401 without auth token", async () => {
- if (!proxyUp) return;
+describe('MCP Proxy — server list', () => {
+ it('GET /servers returns 401 without auth token', async () => {
+ if (!proxyUp) return
- const { status } = await fetchJson(`${MCP_PROXY_URL}/servers`);
- expect([401, 403]).toContain(status);
- });
+ const { status } = await fetchJson(`${MCP_PROXY_URL}/servers`)
+ expect([401, 403]).toContain(status)
+ })
- it("GET /servers with valid token returns array (may be empty)", async () => {
- const testToken = process.env.TEST_MCP_PROXY_TOKEN;
- if (!proxyUp || !testToken) return;
+ it('GET /servers with valid token returns array (may be empty)', async () => {
+ const testToken = process.env.TEST_MCP_PROXY_TOKEN
+ if (!proxyUp || !testToken) return
- const { status, data } = await fetchJson<unknown[]>(
- `${MCP_PROXY_URL}/servers`,
- { headers: bearer(testToken) }
- );
- expect(status).toBe(200);
- expect(Array.isArray(data)).toBe(true);
- });
-});
+ const { status, data } = await fetchJson<unknown[]>(`${MCP_PROXY_URL}/servers`, {
+ headers: bearer(testToken),
+ })
+ expect(status).toBe(200)
+ expect(Array.isArray(data)).toBe(true)
+ })
+})
-describe("MCP Proxy — server routing", () => {
- it("POST to non-existent server returns 404", async () => {
- if (!proxyUp) return;
+describe('MCP Proxy — server routing', () => {
+ it('POST to non-existent server returns 404', async () => {
+ if (!proxyUp) return
- const testToken = process.env.TEST_MCP_PROXY_TOKEN;
- if (!testToken) return;
+ const testToken = process.env.TEST_MCP_PROXY_TOKEN
+ if (!testToken) return
const { status } = await postJson(
`${MCP_PROXY_URL}/servers/non-existent-server/mcp`,
- { jsonrpc: "2.0", id: "1", method: "tools/list" },
+ { jsonrpc: '2.0', id: '1', method: 'tools/list' },
bearer(testToken)
- );
- expect([404, 503]).toContain(status);
- });
-});
+ )
+ expect([404, 503]).toContain(status)
+ })
+})
diff --git a/tests/e2e/integration/profiles-chain.test.ts b/tests/e2e/integration/profiles-chain.test.ts
index 44eadbbee..d9769e4d8 100644
--- a/tests/e2e/integration/profiles-chain.test.ts
+++ b/tests/e2e/integration/profiles-chain.test.ts
@@ -18,7 +18,8 @@ import {
} from './helpers.integration.js'
const TEST_EMAIL = process.env.E2E_DEV_LOGIN_EMAIL || '[email protected]'
-const TEST_PASSWORD = process.env.E2E_DESKTOP_PASSWORD || process.env.ADMIN_PASSWORD || 'changeme123!'
+const TEST_PASSWORD =
+ process.env.E2E_DESKTOP_PASSWORD || process.env.ADMIN_PASSWORD || 'changeme123!'
let sessionToken = ''
let clusterAvailable = false
diff --git a/tests/e2e/mcp-host/extension-config.test.ts b/tests/e2e/mcp-host/extension-config.test.ts
index 0a23e43dd..6af40167c 100644
--- a/tests/e2e/mcp-host/extension-config.test.ts
+++ b/tests/e2e/mcp-host/extension-config.test.ts
@@ -5,48 +5,42 @@
* CLERUM_ENABLE_PRESSURE_COMPACTION) are recognized and that the approval endpoints
* are properly wired to the agent.
*/
-import { describe, it, expect } from "vitest";
-import {
- approveRequest,
- denyRequest,
- sendMessage,
- waitForIdle,
- getPodLogs,
-} from "../helpers.js";
+import { describe, expect, it } from 'vitest'
+import { approveRequest, denyRequest, getPodLogs, sendMessage, waitForIdle } from '../helpers.js'
-describe("Extension Configuration (Phase 6)", () => {
- it("mcp-host starts with approval system enabled by default", () => {
- const logs = getPodLogs("mcp-host", "mcp-host", 500);
+describe('Extension Configuration (Phase 6)', () => {
+ it('mcp-host starts with approval system enabled by default', () => {
+ const logs = getPodLogs('mcp-host', 'mcp-host', 500)
// Approval system defaults to enabled (CLERUM_ENABLE_APPROVAL defaults to true)
- expect(logs).toContain("Approval system: ENABLED");
- expect(logs).not.toContain("Nudge controller: ENABLED");
- });
+ expect(logs).toContain('Approval system: ENABLED')
+ expect(logs).not.toContain('Nudge controller: ENABLED')
+ })
- it("mcp-host logs show extension configuration on startup", () => {
- const logs = getPodLogs("mcp-host", "mcp-host", 500);
+ it('mcp-host logs show extension configuration on startup', () => {
+ const logs = getPodLogs('mcp-host', 'mcp-host', 500)
// Agent should log its startup — verify basic agent initialization
- expect(logs).toContain("[Agent]");
- });
+ expect(logs).toContain('[Agent]')
+ })
- it("POST /approve endpoint is wired (returns 200, not 501)", async () => {
- const res = await approveRequest("test-user", "req-wiring-check");
+ it('POST /approve endpoint is wired (returns 200, not 501)', async () => {
+ const res = await approveRequest('test-user', 'req-wiring-check')
// 200 means the handler is wired (even if no pending approval)
// 501 would mean the handler was never registered
- expect(res.status).toBe(200);
- expect(res.data).toHaveProperty("success");
- });
+ expect(res.status).toBe(200)
+ expect(res.data).toHaveProperty('success')
+ })
- it("POST /deny endpoint is wired (returns 200, not 501)", async () => {
- const res = await denyRequest("test-user", "req-wiring-check");
- expect(res.status).toBe(200);
- expect(res.data).toHaveProperty("success");
- });
+ it('POST /deny endpoint is wired (returns 200, not 501)', async () => {
+ const res = await denyRequest('test-user', 'req-wiring-check')
+ expect(res.status).toBe(200)
+ expect(res.data).toHaveProperty('success')
+ })
- it("agent processes messages without approval gate when disabled", async () => {
- await sendMessage("extension config test message");
- const status = await waitForIdle(30_000);
- expect(status.agent.state).toBe("idle");
+ it('agent processes messages without approval gate when disabled', async () => {
+ await sendMessage('extension config test message')
+ const status = await waitForIdle(30_000)
+ expect(status.agent.state).toBe('idle')
// Message should process without pausing for approval
- expect(status.agent.tasksProcessed).toBeGreaterThanOrEqual(1);
- });
-});
+ expect(status.agent.tasksProcessed).toBeGreaterThanOrEqual(1)
+ })
+})
diff --git a/tests/e2e/mcp-host/legacy-removal.test.ts b/tests/e2e/mcp-host/legacy-removal.test.ts
index 6113e60e1..72bdadfec 100644
--- a/tests/e2e/mcp-host/legacy-removal.test.ts
+++ b/tests/e2e/mcp-host/legacy-removal.test.ts
@@ -5,60 +5,54 @@
* no dual-path routing, and no legacy provider methods. These tests confirm
* the cleanup via pod logs and HTTP responses.
*/
-import { describe, it, expect } from "vitest";
-import {
- sendMessage,
- waitForIdle,
- getPodLogs,
- fetchJson,
- MCP_HOST_URL,
-} from "../helpers.js";
+import { describe, expect, it } from 'vitest'
+import { MCP_HOST_URL, fetchJson, getPodLogs, sendMessage, waitForIdle } from '../helpers.js'
-describe("Legacy Removal (Phase 7)", () => {
+describe('Legacy Removal (Phase 7)', () => {
it("mcp-host startup logs do not contain 'USE_NEW_AGENT_LOOP'", () => {
- const logs = getPodLogs("mcp-host", "mcp-host", 300);
- expect(logs).not.toContain("USE_NEW_AGENT_LOOP");
- });
+ const logs = getPodLogs('mcp-host', 'mcp-host', 300)
+ expect(logs).not.toContain('USE_NEW_AGENT_LOOP')
+ })
it("mcp-host startup logs do not contain '(new pipeline)' marker", () => {
- const logs = getPodLogs("mcp-host", "mcp-host", 300);
+ const logs = getPodLogs('mcp-host', 'mcp-host', 300)
// The "(new pipeline)" marker was a temporary indicator during Phase 5-6;
// it should be removed now that there's only one pipeline
- expect(logs).not.toContain("(new pipeline)");
- });
+ expect(logs).not.toContain('(new pipeline)')
+ })
it("mcp-host startup logs do not contain 'legacy' or 'Legacy' references", () => {
- const logs = getPodLogs("mcp-host", "mcp-host", 300);
- const lower = logs.toLowerCase();
- expect(lower).not.toContain("legacy pipeline");
- expect(lower).not.toContain("legacy path");
- expect(lower).not.toContain("executeTaskLegacy".toLowerCase());
- });
+ const logs = getPodLogs('mcp-host', 'mcp-host', 300)
+ const lower = logs.toLowerCase()
+ expect(lower).not.toContain('legacy pipeline')
+ expect(lower).not.toContain('legacy path')
+ expect(lower).not.toContain('executeTaskLegacy'.toLowerCase())
+ })
- it("mcp-host processes task via single pipeline", async () => {
- await sendMessage("legacy removal validation");
- await waitForIdle(30_000);
+ it('mcp-host processes task via single pipeline', async () => {
+ await sendMessage('legacy removal validation')
+ await waitForIdle(30_000)
- const logs = getPodLogs("mcp-host", "mcp-host", 200);
+ const logs = getPodLogs('mcp-host', 'mcp-host', 200)
// Single pipeline logs "Processing task" without branching markers
- expect(logs).toContain("[Agent] Processing task");
- });
+ expect(logs).toContain('[Agent] Processing task')
+ })
- it("GET / API info does not mention feature flags", async () => {
- const res = await fetchJson(`${MCP_HOST_URL}/`);
- expect(res.status).toBe(200);
- const body = JSON.stringify(res.data);
- expect(body).not.toContain("feature");
- expect(body).not.toContain("flag");
- expect(body).not.toContain("USE_NEW_AGENT_LOOP");
- });
+ it('GET / API info does not mention feature flags', async () => {
+ const res = await fetchJson(`${MCP_HOST_URL}/`)
+ expect(res.status).toBe(200)
+ const body = JSON.stringify(res.data)
+ expect(body).not.toContain('feature')
+ expect(body).not.toContain('flag')
+ expect(body).not.toContain('USE_NEW_AGENT_LOOP')
+ })
- it("mcp-host runs without CLERUM_USE_NEW_AGENT_LOOP env var set", () => {
+ it('mcp-host runs without CLERUM_USE_NEW_AGENT_LOOP env var set', () => {
// Verify the pod is running (we got this far) and has no reference to the flag
- const logs = getPodLogs("mcp-host", "mcp-host", 300);
+ const logs = getPodLogs('mcp-host', 'mcp-host', 300)
// Agent should be initialized and running
- expect(logs).toContain("[Agent]");
+ expect(logs).toContain('[Agent]')
// No feature flag env var should appear
- expect(logs).not.toContain("CLERUM_USE_NEW_AGENT_LOOP");
- });
-});
+ expect(logs).not.toContain('CLERUM_USE_NEW_AGENT_LOOP')
+ })
+})
diff --git a/tests/e2e/mcp-host/tool-discovery.test.ts b/tests/e2e/mcp-host/tool-discovery.test.ts
index 65464cba7..c2e01c167 100644
--- a/tests/e2e/mcp-host/tool-discovery.test.ts
+++ b/tests/e2e/mcp-host/tool-discovery.test.ts
@@ -4,41 +4,41 @@
* Checks both the context-mapper API and mcp-host startup logs to confirm
* MCP tools are registered and used during message processing.
*/
-import { describe, it, expect } from "vitest";
-import { getMcpServers, sendMessage, waitForIdle, getPodLogs } from "../helpers.js";
+import { describe, expect, it } from 'vitest'
+import { getMcpServers, getPodLogs, sendMessage, waitForIdle } from '../helpers.js'
-describe("Tool Discovery", () => {
- it("context-mapper reports mock-server with 2 tools", async () => {
- const data = await getMcpServers("context1");
- const mock = data.servers.find((s: any) => s.name === "mock-server");
- expect(mock).toBeDefined();
- expect(mock.status.ready).toBe(true);
- });
+describe('Tool Discovery', () => {
+ it('context-mapper reports mock-server with 2 tools', async () => {
+ const data = await getMcpServers('context1')
+ const mock = data.servers.find((s: any) => s.name === 'mock-server')
+ expect(mock).toBeDefined()
+ expect(mock.status.ready).toBe(true)
+ })
- it("mcp-host connected to mock-server and found tools", async () => {
+ it('mcp-host connected to mock-server and found tools', async () => {
// These log lines are emitted by MCP connection logic (shared by both pipelines)
- const logs = getPodLogs("mcp-host", "mcp-host", 500);
- expect(logs).toContain("[MCP:mock-server] Connected successfully");
- expect(logs).toContain("[MCP:mock-server] Found 2 tool(s):");
- expect(logs).toContain("echo: Echoes back the provided text");
- expect(logs).toContain("add: Adds two numbers together");
- });
+ const logs = getPodLogs('mcp-host', 'mcp-host', 500)
+ expect(logs).toContain('[MCP:mock-server] Connected successfully')
+ expect(logs).toContain('[MCP:mock-server] Found 2 tool(s):')
+ expect(logs).toContain('echo: Echoes back the provided text')
+ expect(logs).toContain('add: Adds two numbers together')
+ })
it("mcp-host reports total tools available (at least mock-server's 2)", async () => {
- const logs = getPodLogs("mcp-host", "mcp-host", 500);
+ const logs = getPodLogs('mcp-host', 'mcp-host', 500)
// Cluster may have additional MCP servers beyond mock-server;
// verify the log line exists and reports >= 2 tools
- const match = logs.match(/\[Main\] Total tools available: (\d+)/);
- expect(match).not.toBeNull();
- expect(Number(match![1])).toBeGreaterThanOrEqual(2);
- });
+ const match = logs.match(/\[Main\] Total tools available: (\d+)/)
+ expect(match).not.toBeNull()
+ expect(Number(match![1])).toBeGreaterThanOrEqual(2)
+ })
- it("mcp-host processes messages via single pipeline", async () => {
- await sendMessage("tool discovery test");
- await waitForIdle(30_000);
+ it('mcp-host processes messages via single pipeline', async () => {
+ await sendMessage('tool discovery test')
+ await waitForIdle(30_000)
- const logs = getPodLogs("mcp-host", "mcp-host", 200);
+ const logs = getPodLogs('mcp-host', 'mcp-host', 200)
// Single pipeline — verify the task was processed
- expect(logs).toContain("[Agent] Processing task");
- });
-});
+ expect(logs).toContain('[Agent] Processing task')
+ })
+})
diff --git a/tests/e2e/package-lock.json b/tests/e2e/package-lock.json
index 6284891d7..62930fee6 100644
--- a/tests/e2e/package-lock.json
+++ b/tests/e2e/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-e2e-tests",
- "version": "0.1.61",
+ "version": "0.1.62",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-e2e-tests",
- "version": "0.1.61",
+ "version": "0.1.62",
"devDependencies": {
"@types/jsonwebtoken": "^9.0.10",
"@types/node": "^22.0.0",
diff --git a/tests/e2e/package.json b/tests/e2e/package.json
index 0131122ca..0357c0ddd 100644
--- a/tests/e2e/package.json
+++ b/tests/e2e/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-e2e-tests",
- "version": "0.1.61",
+ "version": "0.1.62",
"private": true,
"type": "module",
"scripts": {
diff --git a/tests/e2e/rpc-proxy/helpers/jwt.ts b/tests/e2e/rpc-proxy/helpers/jwt.ts
index 9fdb3cf60..670e2f875 100644
--- a/tests/e2e/rpc-proxy/helpers/jwt.ts
+++ b/tests/e2e/rpc-proxy/helpers/jwt.ts
@@ -1,5 +1,5 @@
-import { generateKeyPairSync } from "node:crypto";
-import jwt from "jsonwebtoken";
+import jwt from 'jsonwebtoken'
+import { generateKeyPairSync } from 'node:crypto'
export const TEST_JWT_PRIVATE_KEY = `-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCsIhgYd6Ew+kYp
@@ -28,7 +28,7 @@ NULFwlycLyM8zKKDg6Y9uzo/JgEuHsQlezqLjsECgYAboHrpwXg/SBatigtBvj0E
1ccXGGLgN2dhDbAlZoSKDITOxGiOw48bOX1lT25c06muru+2mCNrsN2lMs07VGk8
PSRsIuFZis/4vrRtjoxUB4OQ29+mfVgqGsABPugCmi/r22gWrvl1aqEEqstg3m7x
sKRpFxViv5P5TmnxLggnhw==
------END PRIVATE KEY-----`;
+-----END PRIVATE KEY-----`
export const TEST_JWT_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArCIYGHehMPpGKePxaKQa
@@ -38,50 +38,50 @@ QkEabepekZTMQyExmCIn/dHJ15B+4A9tiiephYOQNr3GcnW9eDomMt6NJLypikbr
xJO6O7Ar0G+raTbflth8EQzWnGF+WgQW4iiM3wsFhpaE0mUlEbMGDGTMAZy1KfxA
RRu+QZm3Lo+5AiCaHkijDCglHsXLhqsYi2AdRiavD1Gk9LKP/ztKw7q/D6fYFzmO
QwIDAQAB
------END PUBLIC KEY-----`;
+-----END PUBLIC KEY-----`
type RpcJwtOptions = {
- sub?: string;
- typ?: "user" | "service";
- teamId?: string;
- scopes?: string[];
- hostRefs?: string[];
- iss?: string;
- aud?: string;
- expiresInSeconds?: number;
- now?: number;
- privateKey?: string;
- jti?: string;
-};
+ sub?: string
+ typ?: 'user' | 'service'
+ teamId?: string
+ scopes?: string[]
+ hostRefs?: string[]
+ iss?: string
+ aud?: string
+ expiresInSeconds?: number
+ now?: number
+ privateKey?: string
+ jti?: string
+}
export function signRpcJwt(opts: RpcJwtOptions = {}): string {
- const now = opts.now ?? Math.floor(Date.now() / 1000);
- const exp = now + (opts.expiresInSeconds ?? 300);
+ const now = opts.now ?? Math.floor(Date.now() / 1000)
+ const exp = now + (opts.expiresInSeconds ?? 300)
return jwt.sign(
{
- sub: opts.sub ?? "e2e-user",
- typ: opts.typ ?? "user",
- teamId: opts.teamId ?? "e2e-team",
- scopes: opts.scopes ?? ["mcp:servers:list", "mcp:server:invoke"],
- hostRefs: opts.hostRefs ?? ["agent2"],
+ sub: opts.sub ?? 'e2e-user',
+ typ: opts.typ ?? 'user',
+ teamId: opts.teamId ?? 'e2e-team',
+ scopes: opts.scopes ?? ['mcp:servers:list', 'mcp:server:invoke'],
+ hostRefs: opts.hostRefs ?? ['agent2'],
jti: opts.jti ?? `e2e-${now}`,
iat: now,
- exp
+ exp,
},
opts.privateKey ?? TEST_JWT_PRIVATE_KEY,
{
- algorithm: "RS256",
- issuer: opts.iss ?? "control-api",
- audience: opts.aud ?? "rpc-proxy"
+ algorithm: 'RS256',
+ issuer: opts.iss ?? 'control-api',
+ audience: opts.aud ?? 'rpc-proxy',
}
- );
+ )
}
-export function signWithWrongKey(opts: Omit<RpcJwtOptions, "privateKey"> = {}): string {
- const { privateKey } = generateKeyPairSync("rsa", {
+export function signWithWrongKey(opts: Omit<RpcJwtOptions, 'privateKey'> = {}): string {
+ const { privateKey } = generateKeyPairSync('rsa', {
modulusLength: 2048,
- privateKeyEncoding: { format: "pem", type: "pkcs8" },
- publicKeyEncoding: { format: "pem", type: "spki" }
- });
- return signRpcJwt({ ...opts, privateKey });
+ privateKeyEncoding: { format: 'pem', type: 'pkcs8' },
+ publicKeyEncoding: { format: 'pem', type: 'spki' },
+ })
+ return signRpcJwt({ ...opts, privateKey })
}
diff --git a/tests/e2e/rpc-proxy/helpers/ports.ts b/tests/e2e/rpc-proxy/helpers/ports.ts
index ed3879a79..6de4c5e7a 100644
--- a/tests/e2e/rpc-proxy/helpers/ports.ts
+++ b/tests/e2e/rpc-proxy/helpers/ports.ts
@@ -1,18 +1,18 @@
-import { createServer } from "node:net";
+import { createServer } from 'node:net'
export async function getFreePort(): Promise<number> {
return await new Promise<number>((resolve, reject) => {
- const server = createServer();
- server.listen(0, "127.0.0.1", () => {
- const addr = server.address();
- if (!addr || typeof addr === "string") {
- server.close();
- reject(new Error("Unable to resolve ephemeral TCP port"));
- return;
+ const server = createServer()
+ server.listen(0, '127.0.0.1', () => {
+ const addr = server.address()
+ if (!addr || typeof addr === 'string') {
+ server.close()
+ reject(new Error('Unable to resolve ephemeral TCP port'))
+ return
}
- const port = addr.port;
- server.close((error) => (error ? reject(error) : resolve(port)));
- });
- server.on("error", reject);
- });
+ const port = addr.port
+ server.close(error => (error ? reject(error) : resolve(port)))
+ })
+ server.on('error', reject)
+ })
}