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): let bots install URL plugins (#82)
Leo0dd3cb9b8f3c
diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.tsindex 589918291..c152a287e 100644--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts@@ -6,6 +6,7 @@ import {CommandId,EventId,type ModelSelection,+ type McpServer,type OrchestrationEvent,ProviderDriverKind,type ProjectId,@@ -341,6 +342,12 @@ const make = Effect.gen(function* () {const serverSettingsService = yield* ServerSettingsService;const botUsageLedger = yield* BotUsageLedger;const runPromise = Effect.runPromiseWith(yield* Effect.context<never>());+ if (agentController.configurePluginRuntime) {+ yield* agentController.configurePluginRuntime({+ readSnapshot: () => runPromise(projectionSnapshotQuery.getCommandReadModel()),+ dispatch: (command) => runPromise(orchestrationEngine.dispatch(command)),+ });+ }const failDelegation = (threadId: ThreadId, error: string) =>agentController.failDelegation?.({ threadId, error }) ?? Effect.void;if (agentController.configureDelegation) {@@ -367,6 +374,7 @@ const make = Effect.gen(function* () {const threadModelSelections = new Map<string, ModelSelection>();const threadBotWorkspaceKeys = new Map<string, string>();+ const threadMcpServers = new Map<string, readonly McpServer[]>();const appendProviderFailureActivity = (input: {readonly threadId: ThreadId;@@ -809,10 +817,13 @@ const make = Effect.gen(function* () {preferredProvider === "claudeAgent" &&effectiveRequestedModelSelection !== undefined &&!Equal.equals(previousModelSelection, effectiveRequestedModelSelection);- const mcpServersChanged = !Equal.equals(- activeSession?.mcpServerIds ?? [],- mcpServers.map((server) => server.id),- );+ const previousMcpServers = threadMcpServers.get(threadId);+ const mcpServersChanged = previousMcpServers+ ? !Equal.equals(previousMcpServers, mcpServers)+ : !Equal.equals(+ activeSession?.mcpServerIds ?? [],+ mcpServers.map((server) => server.id),+ );const previousBotWorkspaceKey = threadBotWorkspaceKeys.get(threadId);const botWorkspaceChanged =previousBotWorkspaceKey !== undefined && previousBotWorkspaceKey !== botWorkspaceKey;@@ -838,6 +849,7 @@ const make = Effect.gen(function* () {!botWorkspaceChanged) {threadBotWorkspaceKeys.set(threadId, botWorkspaceKey);+ threadMcpServers.set(threadId, mcpServers);return { threadId: existingSessionThreadId, engine: desiredEngine };}@@ -883,12 +895,14 @@ const make = Effect.gen(function* () {});yield* bindSessionToThread(restartedSession);threadBotWorkspaceKeys.set(threadId, botWorkspaceKey);+ threadMcpServers.set(threadId, mcpServers);return { threadId: restartedSession.threadId, engine: desiredEngine };}const startedSession = yield* startProviderSession(undefined);yield* bindSessionToThread(startedSession);threadBotWorkspaceKeys.set(threadId, botWorkspaceKey);+ threadMcpServers.set(threadId, mcpServers);return { threadId: startedSession.threadId, engine: desiredEngine };});diff --git a/apps/server/src/provider/AkeruCatalogToolHandlers.test.ts b/apps/server/src/provider/AkeruCatalogToolHandlers.test.tsindex d805e7335..30bbb74f8 100644--- a/apps/server/src/provider/AkeruCatalogToolHandlers.test.ts+++ b/apps/server/src/provider/AkeruCatalogToolHandlers.test.ts@@ -1,7 +1,11 @@import type { McpManager } from "@mastra/code-sdk/mcp/index";+import type { OrchestrationCommand } from "@t3tools/contracts";import { describe, expect, it, vi } from "vite-plus/test";-import { createAkeruCatalogToolHandlers } from "./AkeruCatalogToolHandlers.ts";+import {+ createAkeruCatalogToolHandlers,+ createAkeruPluginRuntime,+} from "./AkeruCatalogToolHandlers.ts";describe("Akeru catalog MCP tool handlers", () => {it("authenticates through the session manager and reports the authorization URL", async () => {@@ -82,4 +86,81 @@ describe("Akeru catalog MCP tool handlers", () => {it("omits every catalog handler when no production manager exists", () => {expect(createAkeruCatalogToolHandlers()).toEqual({});});++ it("persists and enables URL plugins through orchestration commands", async () => {+ const dispatch = vi.fn<(command: OrchestrationCommand) => Promise<void>>(async () => undefined);+ const install = createAkeruPluginRuntime({+ readSnapshot: async () =>+ ({+ mcpServers: [+ {+ id: "builtin-search",+ name: "Old search",+ transport: "url",+ url: "https://old.example.com/mcp",+ enabled: false,+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ },+ ],+ }) as never,+ dispatch,+ id: () => "test-id",+ });++ await expect(+ install({+ pluginId: "search",+ name: "Search",+ url: "https://example.com/mcp",+ authentication: "oauth",+ }),+ ).resolves.toEqual({+ mcpServerId: "builtin-search",+ enabled: true,+ authenticationRequired: true,+ });+ expect(dispatch.mock.calls.map(([command]) => command.type)).toEqual([+ "mcp-server.update",+ "mcp-server.enable",+ ]);+ expect(dispatch.mock.calls[0]?.[0]).toMatchObject({+ name: "Search",+ url: "https://example.com/mcp",+ });+ });++ it("creates enabled plugins and rejects credential-bearing URLs before persistence", async () => {+ const dispatch = vi.fn<(command: OrchestrationCommand) => Promise<void>>(async () => undefined);+ const install = createAkeruPluginRuntime({+ readSnapshot: async () => ({ mcpServers: [] }) as never,+ dispatch,+ now: () => "2026-01-01T00:00:00.000Z",+ id: () => "test-id",+ });++ await install({+ pluginId: "public-search",+ name: "Public search",+ url: "https://example.com/mcp",+ authentication: "none",+ });+ expect(dispatch).toHaveBeenCalledWith(+ expect.objectContaining({+ type: "mcp-server.create",+ mcpServerId: "builtin-public-search",+ enabled: true,+ }),+ );++ await expect(+ install({+ pluginId: "secret-search",+ name: "Secret search",+ url: "https://[email protected]/mcp",+ authentication: "oauth",+ }),+ ).rejects.toThrow("must not contain credentials");+ expect(dispatch).toHaveBeenCalledOnce();+ });});diff --git a/apps/server/src/provider/AkeruCatalogToolHandlers.ts b/apps/server/src/provider/AkeruCatalogToolHandlers.tsindex 31214dc26..27247e555 100644--- a/apps/server/src/provider/AkeruCatalogToolHandlers.ts+++ b/apps/server/src/provider/AkeruCatalogToolHandlers.ts@@ -1,5 +1,15 @@+import * as NodeCrypto from "node:crypto";+import type { McpManager } from "@mastra/code-sdk/mcp/index";-import type { AkeruToolId } from "@t3tools/contracts";+import {+ CommandId,+ McpServerId,+ type AkeruToolId,+ type AkeruToolInputSchemas,+ type OrchestrationCommand,+ type OrchestrationReadModel,+} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";export interface AkeruCatalogToolHandlerInput {readonly input: unknown;@@ -8,6 +18,61 @@ export interface AkeruCatalogToolHandlerInput {export type AkeruCatalogToolHandler = (input: AkeruCatalogToolHandlerInput) => Promise<unknown>;+export interface AkeruPluginRuntimeOptions {+ readonly readSnapshot: () => Promise<OrchestrationReadModel>;+ readonly dispatch: (command: OrchestrationCommand) => Promise<unknown>;+ readonly now?: () => string;+ readonly id?: () => string;+}++export function createAkeruPluginRuntime(options: AkeruPluginRuntimeOptions) {+ const now = options.now ?? (() => DateTime.formatIso(DateTime.nowUnsafe()));+ const id = options.id ?? (() => NodeCrypto.randomUUID());+ return async (input: (typeof AkeruToolInputSchemas.InstallPlugin)["Type"]) => {+ const url = new URL(input.url);+ if ((url.protocol !== "http:" && url.protocol !== "https:") || url.username || url.password) {+ throw new Error("Plugin URL must be HTTP or HTTPS and must not contain credentials.");+ }+ const mcpServerId = McpServerId.make(`builtin-${input.pluginId}`);+ const existing = ((await options.readSnapshot()).mcpServers ?? []).find(+ (server) => server.id === mcpServerId,+ );+ await options.dispatch(+ existing+ ? {+ type: "mcp-server.update",+ commandId: CommandId.make(`plugin:update:${id()}`),+ mcpServerId,+ name: input.name,+ transport: "url",+ url: input.url,+ }+ : {+ type: "mcp-server.create",+ commandId: CommandId.make(`plugin:create:${id()}`),+ mcpServerId,+ name: input.name,+ transport: "url",+ url: input.url,+ enabled: true,+ createdAt: now(),+ },+ );+ if (existing && !existing.enabled) {+ await options.dispatch({+ type: "mcp-server.enable",+ commandId: CommandId.make(`plugin:enable:${id()}`),+ mcpServerId,+ });+ }+ return {+ mcpServerId,+ enabled: true,+ authenticationRequired: input.authentication !== "none",+ };+ };+}+function field(value: unknown, key: string): unknown {if (typeof value !== "object" || value === null) return undefined;return Object.getOwnPropertyDescriptor(value, key)?.value;@@ -23,43 +88,56 @@ function requiredString(value: unknown, key: string): string {export function createAkeruCatalogToolHandlers(mcpManager?: McpManager,+ installPlugin?: ReturnType<typeof createAkeruPluginRuntime>,): 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.`);+ ...(installPlugin+ ? {+ InstallPlugin: async ({ input, emitProgress }) => {+ const name = requiredString(input, "name");+ await emitProgress(`Installing plugin '${name}'.`);+ return installPlugin(input as (typeof AkeruToolInputSchemas.InstallPlugin)["Type"]);+ },+ }+ : {}),+ ...(mcpManager+ ? {+ 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 };+ },}- servers.push(status);- }- return { servers };- },+ : {}),};}diff --git a/apps/server/src/provider/AkeruToolRuntime.ts b/apps/server/src/provider/AkeruToolRuntime.tsindex 808fcb77a..6637eea93 100644--- a/apps/server/src/provider/AkeruToolRuntime.ts+++ b/apps/server/src/provider/AkeruToolRuntime.ts@@ -120,6 +120,7 @@ const BACKEND_NAMES: Record<| "CreateChannel"| "UpdateChannel"| "SendToUser"+ | "InstallPlugin"| "AuthenticateMcpServer"| "RestartMcpServers">,diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.tsindex 2dd039d82..8cb3b6334 100644--- a/apps/server/src/provider/Layers/AgentController.ts+++ b/apps/server/src/provider/Layers/AgentController.ts@@ -68,7 +68,11 @@ import {type AkeruDelegationChildOutcome,type AkeruDelegationRuntime,} from "../AkeruDelegationRuntime.ts";-import { createAkeruCatalogToolHandlers } from "../AkeruCatalogToolHandlers.ts";+import {+ createAkeruCatalogToolHandlers,+ createAkeruPluginRuntime,+ type AkeruPluginRuntimeOptions,+} from "../AkeruCatalogToolHandlers.ts";import {createAkeruToolRuntime,isMemoryToolId,@@ -318,6 +322,7 @@ const make = (options?: AgentControllerLiveOptions) =>const sessions = new Map<string, ActiveSession>();let delegationRuntime: AkeruDelegationRuntime | undefined;let channelRuntime: AkeruChannelRuntime | undefined;+ let pluginRuntime: ReturnType<typeof createAkeruPluginRuntime> | undefined;const childWaiters = new Map<string,{ readonly resolve: (outcome: AkeruDelegationChildOutcome) => void }@@ -958,7 +963,10 @@ const make = (options?: AgentControllerLiveOptions) =>workspace: resources.botWorkspace,...(userComputerWorkspace ? { userComputerWorkspace } : {}),...(registeredMemoryHandlers ? { memoryHandlers: registeredMemoryHandlers } : {}),- catalogHandlers: createAkeruCatalogToolHandlers(sessionResources.getMcpManager(key)),+ catalogHandlers: createAkeruCatalogToolHandlers(+ sessionResources.getMcpManager(key),+ pluginRuntime,+ ),...(input.botId && delegationRuntime? {sendToUser: async (request) => {@@ -1377,6 +1385,10 @@ const make = (options?: AgentControllerLiveOptions) =>);return AgentController.of({+ configurePluginRuntime: (input: AkeruPluginRuntimeOptions) =>+ Effect.sync(() => {+ pluginRuntime = createAkeruPluginRuntime(input);+ }),configureDelegation: (input) =>Effect.sync(() => {channelRuntime = createAkeruChannelRuntime(input);diff --git a/apps/server/src/provider/Services/AgentController.ts b/apps/server/src/provider/Services/AgentController.tsindex bbd45cbe8..e48239108 100644--- a/apps/server/src/provider/Services/AgentController.ts+++ b/apps/server/src/provider/Services/AgentController.ts@@ -38,6 +38,10 @@ export interface AgentControllerEngineSelection extends AgentControllerAvailable}export interface AgentControllerShape {+ readonly configurePluginRuntime?: (input: {+ readonly readSnapshot: () => Promise<OrchestrationReadModel>;+ readonly dispatch: (command: OrchestrationCommand) => Promise<unknown>;+ }) => Effect.Effect<void>;readonly configureDelegation?: (input: {readonly readSnapshot: () => Promise<OrchestrationReadModel>;readonly dispatch: (command: OrchestrationCommand) => Promise<unknown>;diff --git a/packages/contracts/src/akeruTools.test.ts b/packages/contracts/src/akeruTools.test.tsindex f1b6fc815..15e352276 100644--- a/packages/contracts/src/akeruTools.test.ts+++ b/packages/contracts/src/akeruTools.test.ts@@ -40,6 +40,9 @@ describe("Akeru tool contracts", () => {expect(AKERU_TOOL_CATALOG.find((tool) => tool.id === "RestartMcpServers")?.approval).toBe("production",);+ expect(AKERU_TOOL_CATALOG.find((tool) => tool.id === "InstallPlugin")?.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.tsindex bab4f68c1..5ccff794d 100644--- a/packages/contracts/src/akeruTools.ts+++ b/packages/contracts/src/akeruTools.ts@@ -9,6 +9,7 @@ import {ThreadId,TrimmedNonEmptyString,} from "./baseSchemas.ts";+import { McpServerUrl } from "./mcpServer.ts";export const AKERU_COMMAND_MAX_CHARS = 32_000;export const AKERU_PATH_MAX_CHARS = 512;@@ -60,6 +61,12 @@ export const AkeruToolInputSchemas = {SendToUser: Schema.Struct({message: TrimmedNonEmptyString.check(Schema.isMaxLength(AKERU_COMMAND_MAX_CHARS)),}),+ InstallPlugin: Schema.Struct({+ pluginId: TrimmedNonEmptyString,+ name: TrimmedNonEmptyString,+ url: McpServerUrl,+ authentication: Schema.Literals(["none", "oauth", "optional-oauth"]),+ }),AuthenticateMcpServer: McpServerIdInput,RestartMcpServers: Schema.Struct({serverIds: Schema.optional(Schema.Array(TrimmedNonEmptyString)),@@ -200,6 +207,9 @@ export const AKERU_TOOL_CATALOG = [define("SendToUser", "bot-workspace", "Send a message into the current Akeru thread.", {approval: "send",}),+ define("InstallPlugin", "bot-workspace", "Install or update a URL MCP plugin.", {+ approval: "production",+ }),define("AuthenticateMcpServer", "bot-workspace", "Authenticate an MCP server.", {approval: "secrets",}),