Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ const startupDependencies = Layer.mergeAll(
),
AnalyticsService.layerTest,
Layer.succeed(AgentController.AgentController, {
authenticateMcpServer: () => Effect.die("unused"),
resolveEngine: () => Effect.die("unused"),
inspectEngine: () => Effect.die("unused"),
startSession: () => Effect.die("unused"),
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/auth/RpcAuthorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.subscriptionAuthCancel]: AuthOrchestrationOperateScope,
[WS_METHODS.subscriptionAuthLogout]: AuthOrchestrationOperateScope,
[WS_METHODS.subscriptionAuthHealthTest]: AuthOrchestrationOperateScope,
[WS_METHODS.mcpServerAuthenticate]: AuthOrchestrationOperateScope,
[WS_METHODS.botInboxList]: AuthOrchestrationReadScope,
[WS_METHODS.botInboxResolve]: AuthOrchestrationOperateScope,
[WS_METHODS.voiceCallGet]: AuthOrchestrationReadScope,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ function createAgentControllerHarness(
] satisfies ReadonlyArray<ProviderSession>)
: Effect.succeed([] as ReadonlyArray<ProviderSession>);
const service: AgentControllerShape = {
authenticateMcpServer: () => unsupported(),
resolveEngine: () => unsupported(),
inspectEngine: () => unsupported(),
startSession: () => unsupported(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,7 @@ describe("ProviderCommandReactor", () => {
},
);
const service: AgentControllerShape = {
authenticateMcpServer: () => Effect.die("unused"),
resolveEngine,
inspectEngine,
startSession: startSession as AgentControllerShape["startSession"],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ function createAgentControllerHarness() {

const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
const service: AgentControllerShape = {
authenticateMcpServer: () => unsupported(),
resolveEngine: () => unsupported(),
inspectEngine: () => unsupported(),
startSession: () => unsupported(),
Expand Down
6 changes: 6 additions & 0 deletions apps/server/src/provider/AkeruSessionResources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,12 @@ export class AkeruSessionResources {
return this.mcpManagers.get(threadId);
}

getMcpManagersForServer(serverId: string): readonly McpManager[] {
return [...this.mcpManagers.values()].filter((manager) =>
Object.hasOwn(manager.getConfig().mcpServers ?? {}, serverId),
);
}

getWorkspace(threadId: string): Workspace | undefined {
return (
this.userComputerWorkspaceLeases.get(threadId)?.workspace.workspace ??
Expand Down
30 changes: 30 additions & 0 deletions apps/server/src/provider/Layers/AgentController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ import {
} from "../AkeruToolRuntime.ts";
import type { BotBrowser, BotBrowserAttachment, CreateBotBrowserInput } from "../botBrowser.ts";
import { AkeruSessionResources } from "../AkeruSessionResources.ts";
import { authenticateMcpServer } from "../McpServerAuthentication.ts";
import {
isCodexComputerUseServer,
isCodexComputerUseTool,
Expand Down Expand Up @@ -2527,6 +2528,35 @@ const make = (options?: AgentControllerLiveOptions) =>
}),
failDelegation: ({ threadId, error }) =>
Effect.sync(() => resolveChildWaiter(threadId, { state: "failed", turnId: null, error })),
authenticateMcpServer: ({ server, onAuthorizationUrl }) =>
Effect.tryPromise({
try: async (signal) => {
const status = await authenticateMcpServer({
server,
managers: sessionResources.getMcpManagersForServer(String(server.id)),
createManager: () =>
(options?.makeMcpManager ?? createMcpManager)(
NodePath.join(config.stateDir, "bot-mcp-runtime"),
".akeru-runtime",
toMcpServerConfigs([server]),
),
onAuthorizationUrl,
signal,
recordSuccess: (serverId) => subscriptionAuth.recordMcpRequestSuccess(serverId),
recordFailure: (serverId, message) =>
subscriptionAuth.recordMcpRequestFailure(serverId, message),
recordReconnectFailure: (serverId, message) =>
subscriptionAuth.recordMcpRequestFailure(serverId, message),
});
return { toolCount: status.toolCount };
},
catch: (cause) =>
new AgentControllerRuntimeError({
operation: "mcp.authenticate",
detail: failureDetail(cause),
cause,
}),
}),
readConversationMemory: (threadId) =>
bundle.readObservationalMemory
? runMastra("memory.read", () =>
Expand Down
169 changes: 169 additions & 0 deletions apps/server/src/provider/McpServerAuthentication.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
import type { McpManager, McpServerStatus } from "@mastra/code-sdk/mcp/index";
import { McpServerId, type McpServer } from "@t3tools/contracts";
import { describe, expect, it, vi } from "vite-plus/test";

import { authenticateMcpServer } from "./McpServerAuthentication.ts";

const server: McpServer = {
id: McpServerId.make("builtin-hoplite"),
name: "Hoplite",
transport: "url",
url: "https://mcp.hoplite.ai",
enabled: true,
createdAt: "2026-09-03T00:00:00.000Z",
updatedAt: "2026-09-03T00:00:00.000Z",
};

function status(overrides: Partial<McpServerStatus> = {}): McpServerStatus {
return {
name: "builtin-hoplite",
connected: false,
needsAuth: true,
toolCount: 0,
toolNames: [],
transport: "http",
...overrides,
};
}

describe("MCP server authentication", () => {
it("opens OAuth, waits for connection, and reconnects other live managers", async () => {
const authorizationUrl = "https://hoplite.ai/oauth/authorize";
const first = {
reconnectServer: vi.fn(async () => status()),
authenticateServer: vi.fn(async (_name, options) => {
options?.onAuthorizationUrl?.(authorizationUrl);
return status({ connected: true, needsAuth: false, toolCount: 4 });
}),
} as unknown as McpManager;
const second = {
reconnectServer: vi.fn(async () =>
status({ connected: true, needsAuth: false, toolCount: 4 }),
),
} as unknown as McpManager;
const onAuthorizationUrl = vi.fn();
const recordSuccess = vi.fn();
const result = await authenticateMcpServer({
server,
managers: [first, second],
createManager: vi.fn(),
onAuthorizationUrl,
recordSuccess,
recordFailure: vi.fn(),
recordReconnectFailure: vi.fn(),
});

expect(result.connected).toBe(true);
expect(onAuthorizationUrl).toHaveBeenCalledWith(authorizationUrl);
expect(second.reconnectServer).toHaveBeenCalledWith("builtin-hoplite");
expect(recordSuccess).toHaveBeenCalledWith(server.id);
});

it("records the real authentication failure", async () => {
const manager = {
reconnectServer: vi.fn(async () => status()),
authenticateServer: vi.fn(async () => status({ error: "Authentication cancelled." })),
} as unknown as McpManager;
const recordFailure = vi.fn();
await expect(
authenticateMcpServer({
server,
managers: [manager],
createManager: vi.fn(),
onAuthorizationUrl: vi.fn(),
recordSuccess: vi.fn(),
recordFailure,
recordReconnectFailure: vi.fn(),
}),
).rejects.toThrow("Authentication cancelled.");
expect(recordFailure).toHaveBeenCalledWith(server.id, "Authentication cancelled.");
});

it("initializes and closes a temporary manager when no thread is active", async () => {
const manager = {
init: vi.fn(async () => undefined),
reconnectServer: vi.fn(async () =>
status({ connected: true, needsAuth: false, toolCount: 2 }),
),
disconnect: vi.fn(async () => undefined),
} as unknown as McpManager;
const createManager = vi.fn(() => manager);

await authenticateMcpServer({
server,
managers: [],
createManager,
onAuthorizationUrl: vi.fn(),
recordSuccess: vi.fn(),
recordFailure: vi.fn(),
recordReconnectFailure: vi.fn(),
});

expect(createManager).toHaveBeenCalledOnce();
expect(manager.init).toHaveBeenCalledOnce();
expect(manager.disconnect).toHaveBeenCalledOnce();
});

it("cancels a pending manager authentication when the request stops", async () => {
const controller = new AbortController();
let finishAuthentication!: (value: McpServerStatus) => void;
const manager = {
reconnectServer: vi.fn(async () => status()),
authenticateServer: vi.fn(
async () =>
await new Promise<McpServerStatus>((resolve) => {
finishAuthentication = resolve;
}),
),
cancelServerAuthentication: vi.fn(async () => {
finishAuthentication(status({ cancelled: true, error: "Authentication cancelled." }));
}),
} as unknown as McpManager;

const authentication = authenticateMcpServer({
server,
managers: [manager],
createManager: vi.fn(),
onAuthorizationUrl: vi.fn(),
signal: controller.signal,
recordSuccess: vi.fn(),
recordFailure: vi.fn(),
recordReconnectFailure: vi.fn(),
});
await vi.waitFor(() => expect(manager.authenticateServer).toHaveBeenCalledOnce());
controller.abort();

await expect(authentication).rejects.toThrow("Authentication cancelled.");
expect(manager.cancelServerAuthentication).toHaveBeenCalledWith("builtin-hoplite");
});

it("keeps OAuth successful when a secondary manager cannot reconnect", async () => {
const primary = {
reconnectServer: vi.fn(async () => status()),
authenticateServer: vi.fn(async () =>
status({ connected: true, needsAuth: false, toolCount: 4 }),
),
} as unknown as McpManager;
const secondary = {
reconnectServer: vi.fn(async () => status({ error: "Secondary session failed." })),
} as unknown as McpManager;
const recordSuccess = vi.fn();
const recordFailure = vi.fn();
const recordReconnectFailure = vi.fn();

const result = await authenticateMcpServer({
server,
managers: [primary, secondary],
createManager: vi.fn(),
onAuthorizationUrl: vi.fn(),
recordSuccess,
recordFailure,
recordReconnectFailure,
});

expect(result.connected).toBe(true);
expect(recordSuccess).toHaveBeenCalledWith(server.id);
expect(recordFailure).not.toHaveBeenCalled();
expect(recordReconnectFailure).toHaveBeenCalledWith(server.id, "Secondary session failed.");
});
});
66 changes: 66 additions & 0 deletions apps/server/src/provider/McpServerAuthentication.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import type { McpManager, McpServerStatus } from "@mastra/code-sdk/mcp/index";
import type { McpServer, McpServerId } from "@t3tools/contracts";

interface AuthenticateMcpServerOptions {
readonly server: McpServer;
readonly managers: readonly McpManager[];
readonly createManager: () => McpManager;
readonly onAuthorizationUrl: (url: string) => void;
readonly signal?: AbortSignal;
readonly recordSuccess: (serverId: McpServerId) => void;
readonly recordFailure: (serverId: McpServerId, message: string) => void;
readonly recordReconnectFailure: (serverId: McpServerId, message: string) => void;
}

function failureMessage(cause: unknown): string {
return cause instanceof Error ? cause.message : String(cause);
}

function requireConnected(status: McpServerStatus): McpServerStatus {
if (status.connected) return status;
throw new Error(status.error ?? `MCP server '${status.name}' did not connect.`);
}

export async function authenticateMcpServer(
options: AuthenticateMcpServerOptions,
): Promise<McpServerStatus> {
const temporary = options.managers.length === 0;
const manager = options.managers[0] ?? options.createManager();
const serverId = String(options.server.id);
const cancelAuthentication = () => {
void manager.cancelServerAuthentication(serverId).catch(() => undefined);
};
options.signal?.addEventListener("abort", cancelAuthentication, { once: true });

try {
let connected: McpServerStatus;
try {
if (temporary) await manager.init();

const reconnectStatus = await manager.reconnectServer(serverId);
const authenticatedStatus = reconnectStatus.connected
? reconnectStatus
: await manager.authenticateServer(serverId, {
onAuthorizationUrl: options.onAuthorizationUrl,
});
connected = requireConnected(authenticatedStatus);
options.recordSuccess(options.server.id);
} catch (cause) {
options.recordFailure(options.server.id, failureMessage(cause));
throw cause;
}

for (const other of options.managers.slice(1)) {
try {
requireConnected(await other.reconnectServer(serverId));
} catch (cause) {
options.recordReconnectFailure(options.server.id, failureMessage(cause));
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
}
}

return connected;
} finally {
options.signal?.removeEventListener("abort", cancelAuthentication);
if (temporary) await manager.disconnect().catch(() => undefined);
}
}
6 changes: 6 additions & 0 deletions apps/server/src/provider/Services/AgentController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
BotEngine,
BotId,
ModelSelection,
McpServer,
ProviderInteractionMode,
ProviderInterruptTurnInput,
ProviderRespondToRequestInput,
Expand Down Expand Up @@ -61,6 +62,11 @@ export interface AgentControllerShape {
readonly error: string;
}) => Effect.Effect<void>;

readonly authenticateMcpServer: (input: {
readonly server: McpServer;
readonly onAuthorizationUrl: (url: string) => void;
}) => Effect.Effect<{ readonly toolCount: number }, AgentControllerError>;

readonly readConversationMemory?: (
threadId: ThreadId,
) => Effect.Effect<AkeruConversationMemorySnapshot, AgentControllerError>;
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/serverRuntimeStartup.reconcile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ const makeThread = (

const makeAgentController = (liveThreadIds: ReadonlyArray<ThreadId> = []) =>
({
authenticateMcpServer: () => Effect.die("unused"),
resolveEngine: () => Effect.die("unused"),
inspectEngine: () => Effect.die("unused"),
startSession: () => Effect.die("unused"),
Expand Down
Loading
Loading