Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(server): manage MCP connections from bots (#75)

Leo58ea4e06a929
diff --git a/apps/server/src/provider/AkeruCatalogToolHandlers.test.ts b/apps/server/src/provider/AkeruCatalogToolHandlers.test.ts
new file mode 100644
index 000000000..d805e7335
--- /dev/null
+++ b/apps/server/src/provider/AkeruCatalogToolHandlers.test.ts
@@ -0,0 +1,85 @@
+import type { McpManager } from "@mastra/code-sdk/mcp/index";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import { createAkeruCatalogToolHandlers } from "./AkeruCatalogToolHandlers.ts";
+
+describe("Akeru catalog MCP tool handlers", () => {
+ it("authenticates through the session manager and reports the authorization URL", async () => {
+ const status = {
+ name: "search",
+ connected: true,
+ toolCount: 1,
+ toolNames: ["search_web"],
+ transport: "http" as const,
+ };
+ const authenticateServer = vi.fn<McpManager["authenticateServer"]>(
+ async (_serverId, options) => {
+ options?.onAuthorizationUrl?.("https://example.com/authorize");
+ return status;
+ },
+ );
+ const handlers = createAkeruCatalogToolHandlers({
+ authenticateServer,
+ } as unknown as McpManager);
+ const emitProgress = vi.fn();
+
+ await expect(
+ handlers.AuthenticateMcpServer!({ input: { serverId: "search" }, emitProgress }),
+ ).resolves.toEqual({
+ ...status,
+ authorizationUrl: "https://example.com/authorize",
+ });
+ expect(emitProgress).toHaveBeenCalledWith(
+ "Authorize MCP server 'search' at https://example.com/authorize",
+ );
+
+ authenticateServer.mockResolvedValueOnce({
+ ...status,
+ connected: false,
+ error: "Authentication cancelled.",
+ });
+ await expect(
+ handlers.AuthenticateMcpServer!({ input: { serverId: "search" }, emitProgress }),
+ ).rejects.toThrow("Authentication cancelled");
+ });
+
+ it("restarts all or selected servers and fails on a disconnected server", async () => {
+ const status = {
+ name: "search",
+ connected: true,
+ toolCount: 1,
+ toolNames: ["search_web"],
+ transport: "http" as const,
+ };
+ const reload = vi.fn(async () => undefined);
+ const reconnectServer = vi.fn<McpManager["reconnectServer"]>(async () => status);
+ const manager = {
+ reload,
+ reconnectServer,
+ getServerStatuses: () => [status],
+ } as unknown as McpManager;
+ const handler = createAkeruCatalogToolHandlers(manager).RestartMcpServers!;
+ const emitProgress = vi.fn();
+
+ await expect(handler({ input: {}, emitProgress })).resolves.toEqual({ servers: [status] });
+ expect(reload).toHaveBeenCalledOnce();
+ await expect(
+ handler({ input: { serverIds: ["search", "search"] }, emitProgress }),
+ ).resolves.toEqual({ servers: [status] });
+ expect(reconnectServer).toHaveBeenCalledOnce();
+
+ reconnectServer.mockResolvedValueOnce({
+ ...status,
+ name: "broken",
+ connected: false,
+ error: "Connection failed.",
+ });
+ await expect(handler({ input: { serverIds: ["broken"] }, emitProgress })).rejects.toThrow(
+ "Connection failed",
+ );
+ });
+
+ it("omits every catalog handler when no production manager exists", () => {
+ expect(createAkeruCatalogToolHandlers()).toEqual({});
+ });
+});
diff --git a/apps/server/src/provider/AkeruCatalogToolHandlers.ts b/apps/server/src/provider/AkeruCatalogToolHandlers.ts
new file mode 100644
index 000000000..31214dc26
--- /dev/null
+++ b/apps/server/src/provider/AkeruCatalogToolHandlers.ts
@@ -0,0 +1,65 @@
+import type { McpManager } from "@mastra/code-sdk/mcp/index";
+import type { AkeruToolId } from "@t3tools/contracts";
+
+export interface AkeruCatalogToolHandlerInput {
+ readonly input: unknown;
+ readonly emitProgress: (summary: string) => void | Promise<void>;
+}
+
+export type AkeruCatalogToolHandler = (input: AkeruCatalogToolHandlerInput) => Promise<unknown>;
+
+function field(value: unknown, key: string): unknown {
+ if (typeof value !== "object" || value === null) return undefined;
+ return Object.getOwnPropertyDescriptor(value, key)?.value;
+}
+
+function requiredString(value: unknown, key: string): string {
+ const candidate = field(value, key);
+ if (typeof candidate !== "string" || candidate.length === 0) {
+ throw new Error(`Tool input field '${key}' is required.`);
+ }
+ return candidate;
+}
+
+export function createAkeruCatalogToolHandlers(
+ mcpManager?: McpManager,
+): Partial<Record<AkeruToolId, AkeruCatalogToolHandler>> {
+ if (!mcpManager) return {};
+ return {
+ AuthenticateMcpServer: async ({ input, emitProgress }) => {
+ const serverId = requiredString(input, "serverId");
+ let authorizationUrl: string | undefined;
+ const status = await mcpManager.authenticateServer(serverId, {
+ onAuthorizationUrl: (url) => {
+ authorizationUrl = url;
+ void emitProgress(`Authorize MCP server '${serverId}' at ${url}`);
+ },
+ });
+ if (!status.connected) {
+ throw new Error(status.error ?? `MCP server '${serverId}' was not authenticated.`);
+ }
+ return { ...status, authorizationUrl: authorizationUrl ?? null };
+ },
+ RestartMcpServers: async ({ input, emitProgress }) => {
+ const requested = field(input, "serverIds");
+ const serverIds = Array.isArray(requested)
+ ? requested.filter((value): value is string => typeof value === "string")
+ : [];
+ if (serverIds.length === 0) {
+ await emitProgress("Restarting MCP servers.");
+ await mcpManager.reload();
+ return { servers: mcpManager.getServerStatuses() };
+ }
+ const servers = [];
+ for (const serverId of new Set(serverIds)) {
+ await emitProgress(`Restarting MCP server '${serverId}'.`);
+ const status = await mcpManager.reconnectServer(serverId);
+ if (!status.connected) {
+ throw new Error(status.error ?? `MCP server '${serverId}' did not reconnect.`);
+ }
+ servers.push(status);
+ }
+ return { servers };
+ },
+ };
+}
diff --git a/apps/server/src/provider/AkeruSessionResources.ts b/apps/server/src/provider/AkeruSessionResources.ts
index f61b8c8c5..88253e910 100644
--- a/apps/server/src/provider/AkeruSessionResources.ts
+++ b/apps/server/src/provider/AkeruSessionResources.ts
@@ -222,6 +222,10 @@ export class AkeruSessionResources {
};
}
+ getMcpManager(threadId: string): McpManager | undefined {
+ return this.mcpManagers.get(threadId);
+ }
+
getWorkspace(threadId: string): Workspace | undefined {
return (
this.userComputerWorkspaceLeases.get(threadId)?.workspace.workspace ??
diff --git a/apps/server/src/provider/AkeruToolRuntime.test.ts b/apps/server/src/provider/AkeruToolRuntime.test.ts
index fd427e062..e1fc08a82 100644
--- a/apps/server/src/provider/AkeruToolRuntime.test.ts
+++ b/apps/server/src/provider/AkeruToolRuntime.test.ts
@@ -151,6 +151,39 @@ describe("AkeruToolRuntime", () => {
await expect(runtime.execute(execution)).rejects.toThrow("requires approval");
});
+ it("requires approval before catalog MCP handlers run and forwards progress", async () => {
+ const handler = vi.fn(async ({ emitProgress }) => {
+ await emitProgress("Restarting MCP server 'search'.");
+ return { servers: [{ name: "search", connected: true }] };
+ });
+ const onProgress = vi.fn();
+ const runtime = createAkeruToolRuntime({ onProgress });
+ runtime.registerSession("thread-mcp", {
+ runtimeMode: "full-access",
+ workspaceType: "none",
+ catalogHandlers: { RestartMcpServers: handler },
+ });
+ const execution = {
+ threadId: "thread-mcp",
+ toolId: "RestartMcpServers" as const,
+ toolCallId: "tool-restart",
+ input: { serverIds: ["search"] },
+ approvalMode: "require-grant" as const,
+ };
+
+ await expect(runtime.execute(execution)).rejects.toThrow("requires approval");
+ runtime.grantApproval(execution);
+ await expect(runtime.execute(execution)).resolves.toEqual({
+ servers: [{ name: "search", connected: true }],
+ });
+ expect(onProgress).toHaveBeenCalledWith({
+ threadId: "thread-mcp",
+ toolId: "RestartMcpServers",
+ toolCallId: "tool-restart",
+ summary: "Restarting MCP server 'search'.",
+ });
+ });
+
it("copies files only when both boundaries are registered", async () => {
const runtime = createAkeruToolRuntime();
const bot = workspace("copy-bot");
diff --git a/apps/server/src/provider/AkeruToolRuntime.ts b/apps/server/src/provider/AkeruToolRuntime.ts
index b2efeed8e..808fcb77a 100644
--- a/apps/server/src/provider/AkeruToolRuntime.ts
+++ b/apps/server/src/provider/AkeruToolRuntime.ts
@@ -23,6 +23,7 @@ import {
type AkeruMemoryToolHandler,
type AkeruMemoryToolId,
} from "../memory/MemoryToolHandlers.ts";
+import type { AkeruCatalogToolHandler } from "./AkeruCatalogToolHandlers.ts";
export type AkeruRuntimeToolId = AkeruToolId | AkeruMemoryToolId;
@@ -73,10 +74,17 @@ export interface AkeruToolSession {
readonly sendToUser?: (
input: (typeof AkeruToolInputSchemas.SendToUser)["Type"],
) => Promise<AkeruToolReceipt>;
+ readonly catalogHandlers?: Partial<Record<AkeruToolId, AkeruCatalogToolHandler>>;
}
export interface AkeruToolRuntimeOptions {
readonly onUserActionRequired?: (input: UserActionIncidentInput) => void | Promise<void>;
+ readonly onProgress?: (input: {
+ readonly threadId: string;
+ readonly toolId: AkeruToolId;
+ readonly toolCallId: string;
+ readonly summary: string;
+ }) => void | Promise<void>;
readonly now?: () => string;
}
@@ -112,6 +120,8 @@ const BACKEND_NAMES: Record<
| "CreateChannel"
| "UpdateChannel"
| "SendToUser"
+ | "AuthenticateMcpServer"
+ | "RestartMcpServers"
>,
ReadonlyArray<string>
> = {
@@ -211,6 +221,9 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): Akeru
tools.add("UpdateChannel");
}
if (session.sendToUser) tools.add("SendToUser");
+ for (const toolId of Object.keys(session.catalogHandlers ?? {}) as AkeruToolId[]) {
+ tools.add(toolId);
+ }
return tools;
};
@@ -314,6 +327,20 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): Akeru
return handler({ ...input, toolId: input.toolId, input: decoded });
}
+ const catalogHandler = session.catalogHandlers?.[input.toolId];
+ if (catalogHandler) {
+ return catalogHandler({
+ input: decoded,
+ emitProgress: (summary) =>
+ options?.onProgress?.({
+ threadId: input.threadId,
+ toolId: input.toolId as AkeruToolId,
+ toolCallId: input.toolCallId,
+ summary,
+ }),
+ });
+ }
+
if (input.toolId === "SendToAgent") {
if (!session.delegation) throw new Error("Delegation is not available for this session.");
const delegationInput = decodeAkeruToolInput("SendToAgent", decoded);
@@ -425,7 +452,8 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): Akeru
const workspace = workspaceForTool(input.toolId, session);
const backends = await toolsForWorkspace(workspace);
- const backendName = BACKEND_NAMES[input.toolId].find((name) => executable(backends[name]));
+ const backendNames = BACKEND_NAMES[input.toolId as keyof typeof BACKEND_NAMES] ?? [];
+ const backendName = backendNames.find((name) => executable(backends[name]));
const backend = backendName ? backends[backendName] : undefined;
if (!executable(backend)) throw new Error(`Tool '${input.toolId}' has no backend.`);
const backendInput =
diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.ts
index 10277fdef..f17e4eec4 100644
--- a/apps/server/src/provider/Layers/AgentController.ts
+++ b/apps/server/src/provider/Layers/AgentController.ts
@@ -26,7 +26,7 @@ import {
type ProviderRuntimeEvent,
type ProviderSession,
type RuntimeMode,
- type ThreadId,
+ ThreadId,
AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
type AkeruMemoryThreadAccess,
} from "@t3tools/contracts";
@@ -68,6 +68,7 @@ import {
type AkeruDelegationChildOutcome,
type AkeruDelegationRuntime,
} from "../AkeruDelegationRuntime.ts";
+import { createAkeruCatalogToolHandlers } from "../AkeruCatalogToolHandlers.ts";
import {
createAkeruToolRuntime,
isMemoryToolId,
@@ -357,6 +358,24 @@ const make = (options?: AgentControllerLiveOptions) =>
onUserActionRequired: (input) => {
recordUserActionIncident(botInbox, input);
},
+ onProgress: ({ threadId, toolId, toolCallId, summary }) => {
+ const active = sessions.get(threadId);
+ if (!active) return;
+ PubSub.publishUnsafe(runtimeEvents, {
+ ...baseEvent(ThreadId.make(threadId), active, active.activeTurn?.turnId),
+ type: "tool.receipt",
+ payload: {
+ receiptId: toolCallId,
+ toolId,
+ phase: "progress",
+ threadId: ThreadId.make(threadId),
+ ...(active.toolSession.botId ? { botId: active.toolSession.botId } : {}),
+ summary,
+ fatalToThread: false,
+ createdAt: nowIso(),
+ },
+ });
+ },
});
const memoryHandlers = (access: AkeruMemoryThreadAccess | undefined) =>
access && options?.entityMemoryRepository && options.memoryCandidateRepository
@@ -920,6 +939,7 @@ const make = (options?: AgentControllerLiveOptions) =>
workspace: resources.botWorkspace,
...(userComputerWorkspace ? { userComputerWorkspace } : {}),
...(registeredMemoryHandlers ? { memoryHandlers: registeredMemoryHandlers } : {}),
+ catalogHandlers: createAkeruCatalogToolHandlers(sessionResources.getMcpManager(key)),
...(input.botId && delegationRuntime
? {
sendToUser: async (request) => {
diff --git a/packages/contracts/src/akeruTools.test.ts b/packages/contracts/src/akeruTools.test.ts
index 1fb85301f..f1b6fc815 100644
--- a/packages/contracts/src/akeruTools.test.ts
+++ b/packages/contracts/src/akeruTools.test.ts
@@ -34,7 +34,12 @@ describe("Akeru tool contracts", () => {
implementedTools: new Set(["Shell", "ExternalShell", "CopyToBox"]),
}).map((tool) => tool.id),
).toEqual(["Shell"]);
- expect(AKERU_TOOL_CATALOG.map((tool) => tool.id)).not.toContain("RestartMcpServers");
+ expect(AKERU_TOOL_CATALOG.find((tool) => tool.id === "AuthenticateMcpServer")?.approval).toBe(
+ "secrets",
+ );
+ expect(AKERU_TOOL_CATALOG.find((tool) => tool.id === "RestartMcpServers")?.approval).toBe(
+ "production",
+ );
});
it("decodes SendToAgent input and rejects server-owned fields", () => {
diff --git a/packages/contracts/src/akeruTools.ts b/packages/contracts/src/akeruTools.ts
index 8e758de5d..bab4f68c1 100644
--- a/packages/contracts/src/akeruTools.ts
+++ b/packages/contracts/src/akeruTools.ts
@@ -28,6 +28,7 @@ const CommandInput = Schema.Struct({
});
const PathInput = Schema.Struct({ path: PathText });
const CopyInput = Schema.Struct({ sourcePath: PathText, destinationPath: PathText });
+const McpServerIdInput = Schema.Struct({ serverId: TrimmedNonEmptyString });
export const AkeruToolInputSchemas = {
Shell: CommandInput,
@@ -59,6 +60,10 @@ export const AkeruToolInputSchemas = {
SendToUser: Schema.Struct({
message: TrimmedNonEmptyString.check(Schema.isMaxLength(AKERU_COMMAND_MAX_CHARS)),
}),
+ AuthenticateMcpServer: McpServerIdInput,
+ RestartMcpServers: Schema.Struct({
+ serverIds: Schema.optional(Schema.Array(TrimmedNonEmptyString)),
+ }),
} as const;
export type AkeruToolId = keyof typeof AkeruToolInputSchemas;
@@ -195,6 +200,12 @@ export const AKERU_TOOL_CATALOG = [
define("SendToUser", "bot-workspace", "Send a message into the current Akeru thread.", {
approval: "send",
}),
+ define("AuthenticateMcpServer", "bot-workspace", "Authenticate an MCP server.", {
+ approval: "secrets",
+ }),
+ define("RestartMcpServers", "bot-workspace", "Restart MCP servers.", {
+ approval: "production",
+ }),
] satisfies ReadonlyArray<AkeruToolDefinition>;
export interface AkeruToolAvailabilityContext {