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.
fix(plugins): complete OAuth connections (#162)
Leo3d9a974b169f
diff --git a/apps/server/integration/orphanedProviderSessionStartup.integration.test.ts b/apps/server/integration/orphanedProviderSessionStartup.integration.test.tsindex 2e378563c..223bc4461 100644--- a/apps/server/integration/orphanedProviderSessionStartup.integration.test.ts+++ b/apps/server/integration/orphanedProviderSessionStartup.integration.test.ts@@ -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"),diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.tsindex 071081079..f0eb42431 100644--- a/apps/server/src/auth/RpcAuthorization.ts+++ b/apps/server/src/auth/RpcAuthorization.ts@@ -50,6 +50,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,diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.tsindex b3b45f863..76aa535ed 100644--- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts+++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts@@ -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(),diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.tsindex ed475d27a..964f00024 100644--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts@@ -416,6 +416,7 @@ describe("ProviderCommandReactor", () => {},);const service: AgentControllerShape = {+ authenticateMcpServer: () => Effect.die("unused"),resolveEngine,inspectEngine,startSession: startSession as AgentControllerShape["startSession"],diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.tsindex 52f3591e8..c0f91d997 100644--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts@@ -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(),diff --git a/apps/server/src/provider/AkeruSessionResources.ts b/apps/server/src/provider/AkeruSessionResources.tsindex dcb01932a..449faa41d 100644--- a/apps/server/src/provider/AkeruSessionResources.ts+++ b/apps/server/src/provider/AkeruSessionResources.ts@@ -314,6 +314,18 @@ export class AkeruSessionResources {return this.mcpManagers.get(threadId);}+ getMcpManagersForServer(serverId: string): readonly McpManager[] {+ return this.getMcpManagerSessionsForServer(serverId).map(({ manager }) => manager);+ }++ getMcpManagerSessionsForServer(+ serverId: string,+ ): readonly { readonly threadId: string; readonly manager: McpManager }[] {+ return [...this.mcpManagers.entries()]+ .filter(([, manager]) => Object.hasOwn(manager.getConfig().mcpServers ?? {}, serverId))+ .map(([threadId, manager]) => ({ threadId, manager }));+ }+getWorkspace(threadId: string): Workspace | undefined {return (this.userComputerWorkspaceLeases.get(threadId)?.workspace.workspace ??diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.tsindex e76d767dd..83a0361c7 100644--- a/apps/server/src/provider/Layers/AgentController.ts+++ b/apps/server/src/provider/Layers/AgentController.ts@@ -111,6 +111,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,@@ -2530,6 +2531,47 @@ 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 recoveryFailures: string[] = [];+ const managerSessions = sessionResources.getMcpManagerSessionsForServer(+ String(server.id),+ );+ const status = await authenticateMcpServer({+ server,+ managers: managerSessions.map(({ manager }) => manager),+ managerThreadIds: managerSessions.map(({ threadId }) => threadId),+ 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),+ recordRecoveryFailure: (serverId, message) => {+ recoveryFailures.push(message);+ void runPromise(+ Effect.logWarning("MCP session recovery failed after authentication.", {+ serverId,+ error: message,+ }),+ );+ },+ });+ return { toolCount: status.toolCount, recoveryFailures };+ },+ catch: (cause) =>+ new AgentControllerRuntimeError({+ operation: "mcp.authenticate",+ detail: failureDetail(cause),+ cause,+ }),+ }),readConversationMemory: (threadId) =>bundle.readObservationalMemory? runMastra("memory.read", () =>diff --git a/apps/server/src/provider/McpServerAuthentication.test.ts b/apps/server/src/provider/McpServerAuthentication.test.tsnew file mode 100644index 000000000..700159f8a--- /dev/null+++ b/apps/server/src/provider/McpServerAuthentication.test.ts@@ -0,0 +1,170 @@+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(),+ });++ 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,+ }),+ ).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(),+ });++ 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(),+ });+ 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 recordRecoveryFailure = vi.fn();++ const result = await authenticateMcpServer({+ server,+ managers: [primary, secondary],+ managerThreadIds: ["thread-primary", "thread-secondary"],+ createManager: vi.fn(),+ onAuthorizationUrl: vi.fn(),+ recordSuccess,+ recordFailure,+ recordRecoveryFailure,+ });++ expect(result.connected).toBe(true);+ expect(recordSuccess).toHaveBeenCalledWith(server.id);+ expect(recordFailure).not.toHaveBeenCalled();+ expect(recordRecoveryFailure).toHaveBeenCalledWith(+ server.id,+ "MCP session for thread 'thread-secondary' did not reconnect: Secondary session failed.",+ );+ expect(secondary.reconnectServer).toHaveBeenCalledWith("builtin-hoplite");+ });+});diff --git a/apps/server/src/provider/McpServerAuthentication.ts b/apps/server/src/provider/McpServerAuthentication.tsnew file mode 100644index 000000000..3c17d6cc7--- /dev/null+++ b/apps/server/src/provider/McpServerAuthentication.ts@@ -0,0 +1,71 @@+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 managerThreadIds?: readonly string[];+ readonly createManager: () => McpManager;+ readonly onAuthorizationUrl: (url: string) => void;+ readonly signal?: AbortSignal;+ readonly recordSuccess: (serverId: McpServerId) => void;+ readonly recordFailure: (serverId: McpServerId, message: string) => void;+ readonly recordRecoveryFailure?: (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 [index, other] of options.managers.slice(1).entries()) {+ try {+ requireConnected(await other.reconnectServer(serverId));+ } catch (cause) {+ const threadId = options.managerThreadIds?.[index + 1];+ options.recordRecoveryFailure?.(+ options.server.id,+ `${threadId ? `MCP session for thread '${threadId}'` : `Active MCP session ${index + 2}`} did not reconnect: ${failureMessage(cause)}`,+ );+ }+ }++ return connected;+ } finally {+ options.signal?.removeEventListener("abort", cancelAuthentication);+ if (temporary) await manager.disconnect().catch(() => undefined);+ }+}diff --git a/apps/server/src/provider/Services/AgentController.ts b/apps/server/src/provider/Services/AgentController.tsindex dafb83fe0..b90c59508 100644--- a/apps/server/src/provider/Services/AgentController.ts+++ b/apps/server/src/provider/Services/AgentController.ts@@ -5,6 +5,7 @@ import type {BotEngine,BotId,ModelSelection,+ McpServer,ProviderInteractionMode,ProviderInterruptTurnInput,ProviderRespondToRequestInput,@@ -69,6 +70,14 @@ 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; readonly recoveryFailures: readonly string[] },+ AgentControllerError+ >;+readonly readConversationMemory?: (threadId: ThreadId,) => Effect.Effect<AkeruConversationMemorySnapshot, AgentControllerError>;diff --git a/apps/server/src/serverRuntimeStartup.reconcile.test.ts b/apps/server/src/serverRuntimeStartup.reconcile.test.tsindex 57b1f6bae..228d64f7d 100644--- a/apps/server/src/serverRuntimeStartup.reconcile.test.ts+++ b/apps/server/src/serverRuntimeStartup.reconcile.test.ts@@ -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"),diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex dc4219084..9e96a3b12 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -67,6 +67,7 @@ import {AssetWorkspaceContextResolutionError,RpcClientId,EnvironmentAuthorizationError,+ McpServerAuthenticationError,SubscriptionAuthError,ThreadId,type TerminalAttachStreamEvent,@@ -175,6 +176,7 @@ import * as PairingGrantStore from "./auth/PairingGrantStore.ts";import * as SessionStore from "./auth/SessionStore.ts";import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);+const isMcpServerAuthenticationError = Schema.is(McpServerAuthenticationError);const nowIso = Effect.map(DateTime.now, DateTime.formatIso);const CONFIG_DISCOVERY_TIMEOUT = Duration.seconds(5);@@ -2401,6 +2403,66 @@ const makeWsRpcLayer = (observeRpcEffect(WS_METHODS.subscriptionAuthList, getAccessHealthSnapshot(), {"rpc.aggregate": "server",}),+ [WS_METHODS.mcpServerAuthenticate]: ({ mcpServerId }) =>+ observeRpcStream(+ WS_METHODS.mcpServerAuthenticate,+ Stream.callback((queue) =>+ Effect.gen(function* () {+ const snapshot = yield* projectionSnapshotQuery.getShellSnapshot();+ const server = snapshot.mcpServers?.find(+ (candidate) => candidate.id === mcpServerId,+ );+ if (!server) {+ return yield* new McpServerAuthenticationError({+ mcpServerId,+ reason: "The MCP server does not exist.",+ });+ }+ if (!server.enabled) {+ return yield* new McpServerAuthenticationError({+ mcpServerId,+ reason: "Enable the MCP server before authentication.",+ });+ }+ if (server.transport === "stdio") {+ return yield* new McpServerAuthenticationError({+ mcpServerId,+ reason: "Local MCP servers do not support OAuth authentication.",+ });+ }++ const result = yield* agentController.authenticateMcpServer({+ server,+ onAuthorizationUrl: (authorizationUrl) => {+ Queue.offerUnsafe(queue, {+ type: "authorization-required",+ authorizationUrl,+ });+ },+ });+ yield* Queue.offer(queue, {+ type: "connected",+ toolCount: result.toolCount,+ recoveryFailures: result.recoveryFailures,+ });+ }).pipe(+ Effect.mapError((cause) =>+ isMcpServerAuthenticationError(cause)+ ? cause+ : new McpServerAuthenticationError({+ mcpServerId,+ reason: cause instanceof Error ? cause.message : String(cause),+ }),+ ),+ Effect.catchTag("McpServerAuthenticationError", (error) =>+ Queue.fail(queue, error),+ ),+ Effect.andThen(Queue.end(queue)),+ Effect.forkScoped,+ ),+ ),+ { "rpc.aggregate": "provider" },+ ),[WS_METHODS.botInboxList]: (_input) =>observeRpcEffect(WS_METHODS.botInboxList,diff --git a/apps/web/src/components/plugins/PluginDetails.tsx b/apps/web/src/components/plugins/PluginDetails.tsxindex 57b475bff..c2f11060b 100644--- a/apps/web/src/components/plugins/PluginDetails.tsx+++ b/apps/web/src/components/plugins/PluginDetails.tsx@@ -44,7 +44,7 @@ export function PluginDetailsContent({onViewSource,onOpenSkill,}: PluginDetailsContentProps) {- const action = pluginPrimaryAction(plugin, server);+ const action = pluginPrimaryAction(plugin, server, accessStatus);const blocker = pluginBlocker(plugin);const brokerName = pluginBrokerName(plugin);const connectionDetails = brokerName@@ -112,7 +112,7 @@ export function PluginDetailsContent({aria-label={`${action.label} ${plugin.title}`}className="h-8 min-w-16 rounded-full px-3 text-xs"size="sm"- variant={server?.enabled ? "secondary" : "default"}+ variant={action.enable === false ? "secondary" : "default"}disabled={pending || action.enable === null}title={action.blocker}onClick={() => action.enable !== null && onToggle(action.enable)}diff --git a/apps/web/src/components/plugins/PluginsCatalog.tsx b/apps/web/src/components/plugins/PluginsCatalog.tsxindex 6eb2eba69..fc11e03d9 100644--- a/apps/web/src/components/plugins/PluginsCatalog.tsx+++ b/apps/web/src/components/plugins/PluginsCatalog.tsx@@ -1,4 +1,4 @@-import type { ComposioToolkit, McpServer } from "@t3tools/contracts";+import type { ComposioToolkit, McpServer, ProviderAccessStatus } from "@t3tools/contracts";import { CheckIcon, ChevronRightIcon, PencilIcon, PlusIcon, Trash2Icon } from "lucide-react";import type { PluginDirectoryDefinition } from "../../../../../plugins";import { Badge } from "../ui/badge";@@ -42,25 +42,30 @@ export function PluginLogoImage({interface PluginsCatalogProps {readonly sections: readonly PluginSection[];readonly servers: readonly McpServer[];+ readonly accessStatuses?: readonly ProviderAccessStatus[];readonly pendingServerId: string | null;readonly onToggle: (plugin: PluginDirectoryDefinition, enabled: boolean) => void;readonly onOpen: (plugin: PluginDirectoryDefinition) => void;}+const EMPTY_PROVIDER_ACCESS_STATUSES: readonly ProviderAccessStatus[] = [];+function PluginRow({plugin,server,+ accessStatus,pending,onToggle,onOpen,}: {readonly plugin: PluginDirectoryDefinition;readonly server: McpServer | undefined;+ readonly accessStatus: ProviderAccessStatus | undefined;readonly pending: boolean;readonly onToggle: (enabled: boolean) => void;readonly onOpen: () => void;}) {- const action = pluginPrimaryAction(plugin, server);+ const action = pluginPrimaryAction(plugin, server, accessStatus);const brokerName = pluginBrokerName(plugin);return (<article@@ -119,6 +124,7 @@ function PluginRow({export function PluginsCatalog({sections,servers,+ accessStatuses = EMPTY_PROVIDER_ACCESS_STATUSES,pendingServerId,onToggle,onOpen,@@ -144,6 +150,7 @@ export function PluginsCatalog({key={`${section.title}:${plugin.id}`}plugin={plugin}server={server}+ accessStatus={accessStatuses.find((status) => status.pluginId === plugin.id)}pending={pendingServerId === pluginMcpServerId(plugin)}onToggle={(enabled) => onToggle(plugin, enabled)}onOpen={() => onOpen(plugin)}diff --git a/apps/web/src/components/plugins/PluginsDialog.test.tsx b/apps/web/src/components/plugins/PluginsDialog.test.tsxindex 4388361ab..dde5cf017 100644--- a/apps/web/src/components/plugins/PluginsDialog.test.tsx+++ b/apps/web/src/components/plugins/PluginsDialog.test.tsx@@ -15,6 +15,7 @@ import {PLUGIN_DIALOG_CLASS_NAME,PLUGIN_DIRECTORY_HEADER_CLASS_NAME,PLUGIN_DIRECTORY_PANEL_CLASS_NAME,+ pluginRecoveryNotice,resolvePluginDialogServers,validateMcpServerDraft,} from "./PluginsDialog";@@ -83,6 +84,20 @@ const removedBuiltinServer: McpServer = {const noop = () => undefined;describe("Plugins dialog content", () => {+ it("gives the user a recovery action when an active session does not reconnect", () => {+ expect(+ pluginRecoveryNotice("Hoplite", [+ "MCP session for thread 'thread-secondary' did not reconnect: Secondary session failed.",+ ]),+ ).toEqual({+ type: "warning",+ title: "Hoplite connected with a session issue",+ description:+ "MCP session for thread 'thread-secondary' did not reconnect: Secondary session failed. Restart the affected agent session to retry.",+ });+ expect(pluginRecoveryNotice("Hoplite", [])).toBeNull();+ });+it("lists Gmail as an app connected through Composio", () => {const gmail = COMPOSIO_APPS[0];const markup = renderToStaticMarkup(@@ -287,6 +302,36 @@ describe("Plugins dialog content", () => {expect(markup).not.toContain("secret-access");});+ it("offers reconnect when an enabled OAuth plugin failed its first request", () => {+ const markup = renderToStaticMarkup(+ <PluginDetailsContent+ plugin={firecrawl}+ server={firecrawlServer}+ accessStatus={{+ id: "mcp-builtin-firecrawl",+ label: "Firecrawl",+ accessMethod: "mcp",+ health: "failed-first-request",+ apiAccess: "not-applicable",+ nextAction: "Reconnect Firecrawl.",+ serverId: "builtin-firecrawl",+ pluginId: "firecrawl",+ dependentBots: [],+ dependentRoutines: [],+ }}+ activeDependentBotNames={[]}+ pending={false}+ onToggle={noop}+ onRemove={noop}+ onViewDocumentation={noop}+ onViewSource={noop}+ onOpenSkill={noop}+ />,+ );+ expect(markup).toContain('aria-label="Reconnect Firecrawl"');+ expect(markup).not.toContain('aria-label="Disable Firecrawl"');+ });+it("blocks approval-pending connection and names the blocker in details", () => {const markup = renderToStaticMarkup(<PluginDetailsContentdiff --git a/apps/web/src/components/plugins/PluginsDialog.tsx b/apps/web/src/components/plugins/PluginsDialog.tsxindex 95b8b56db..6f77cf41d 100644--- a/apps/web/src/components/plugins/PluginsDialog.tsx+++ b/apps/web/src/components/plugins/PluginsDialog.tsx@@ -50,6 +50,7 @@ import {RemovedBuiltinServers,} from "./PluginsCatalog";import { PluginDetails } from "./PluginDetails";+import { runPluginEnablePlan } from "./pluginConnection";import {findPluginServer,isBuiltinMcpServer,@@ -91,6 +92,15 @@ export const PLUGIN_DIALOG_CLASS_NAME = "h-[min(48rem,90dvh)] max-w-5xl flex-colexport const PLUGIN_DIRECTORY_HEADER_CLASS_NAME = "shrink-0 gap-3 px-6 pt-5 pb-4";export const PLUGIN_DIRECTORY_PANEL_CLASS_NAME = "space-y-8 px-5 pt-5! pb-5 sm:px-6";+export function pluginRecoveryNotice(pluginTitle: string, recoveryFailures: readonly string[]) {+ if (recoveryFailures.length === 0) return null;+ return {+ type: "warning" as const,+ title: `${pluginTitle} connected with a session issue`,+ description: `${recoveryFailures.join(" ")} Restart the affected agent session to retry.`,+ };+}+export interface McpServerDraft {readonly name: string;readonly transport: "stdio" | "url";@@ -167,6 +177,9 @@ function PluginsDialogForEnvironment({ environmentId }: { readonly environmentIdconst deleteServer = useAtomCommand(mcpServerEnvironment.delete, { reportFailure: false });const enableServer = useAtomCommand(mcpServerEnvironment.enable, { reportFailure: false });const disableServer = useAtomCommand(mcpServerEnvironment.disable, { reportFailure: false });+ const authenticateServer = useAtomCommand(serverEnvironment.authenticateMcpServer, {+ reportFailure: false,+ });const [query, setQuery] = useState("");const deferredQuery = useDeferredValue(query.trim());const [filter, setFilter] = useState<PluginFilter>("All");@@ -327,39 +340,87 @@ function PluginsDialogForEnvironment({ environmentId }: { readonly environmentIdcomposioStatus.refresh();return;}- let plan;- if (enabled) {- if (!isInstallablePlugin(plugin)) return;- plan = planPluginToggle(plugin, servers, true);- } else {- plan = { action: "disable" as const, mcpServerId: pluginMcpServerId(plugin) };+ if (!enabled) {+ const mcpServerId = pluginMcpServerId(plugin);+ setPendingServerId(mcpServerId);+ const result = await disableServer({ environmentId, input: { mcpServerId } });+ setPendingServerId(null);+ reportFailure(`Could not disable ${plugin.title}`, result);+ return;}+ if (!isInstallablePlugin(plugin)) return;++ const plan = planPluginToggle(plugin, servers, true);+ if (plan.action === "disable") return;setPendingServerId(plan.mcpServerId);- if (plan.action === "refresh-and-enable") {- const updateResult = await updateServer({- environmentId,- input: { mcpServerId: plan.mcpServerId, ...plan.configuration },+ const commandSucceeded = (title: string, result: Awaited<ReturnType<typeof createServer>>) => {+ if (result._tag === "Success") return true;+ reportFailure(title, result);+ return false;+ };+ const shouldAuthenticate =+ plugin.authentication === "oauth" || plugin.authentication === "optional-oauth";++ try {+ await runPluginEnablePlan(plan, {+ create: async (mcpServerId, configuration) =>+ commandSucceeded(+ `Could not enable ${plugin.title}`,+ await createServer({+ environmentId,+ input: { mcpServerId, ...configuration },+ }),+ ),+ update: async (mcpServerId, configuration) =>+ commandSucceeded(+ `Could not update ${plugin.title}`,+ await updateServer({+ environmentId,+ input: { mcpServerId, ...configuration },+ }),+ ),+ enable: async (mcpServerId) =>+ commandSucceeded(+ `Could not enable ${plugin.title}`,+ await enableServer({ environmentId, input: { mcpServerId } }),+ ),+ ...(shouldAuthenticate+ ? {+ authenticate: async (mcpServerId, onAuthorizationUrl) => {+ const result = await authenticateServer({+ environmentId,+ mcpServerId,+ onAuthorizationUrl,+ });+ if (result._tag === "Success") {+ const notice = pluginRecoveryNotice(plugin.title, result.value.recoveryFailures);+ if (notice) toastManager.add(notice);+ return true;+ }+ if (!isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);+ toastManager.add({+ type: "error",+ title: `Could not connect ${plugin.title}`,+ description: error instanceof Error ? error.message : "Authentication failed.",+ });+ }+ return false;+ },+ }+ : {}),+ openAuthorizationUrl: async (url) => {+ const authorizationUrl = new URL(url);+ if (authorizationUrl.protocol !== "https:") {+ throw new Error("The authorization URL must use HTTPS.");+ }+ await ensureLocalApi().shell.openExternal(authorizationUrl.toString());+ },});- if (reportFailure(`Could not update ${plugin.title}`, updateResult)) {- setPendingServerId(null);- return;- }+ } finally {+ setPendingServerId(null);+ subscriptionAuth.refresh();}- const result =- plan.action === "create"- ? await createServer({- environmentId,- input: { mcpServerId: plan.mcpServerId, ...plan.configuration },- })- : await (plan.action === "refresh-and-enable" ? enableServer : disableServer)({- environmentId,- input: { mcpServerId: plan.mcpServerId },- });- setPendingServerId(null);- reportFailure(- enabled ? `Could not enable ${plugin.title}` : `Could not disable ${plugin.title}`,- result,- );};const connectComposioToolkit = async (toolkit: ComposioToolkit) => {@@ -559,6 +620,7 @@ function PluginsDialogForEnvironment({ environmentId }: { readonly environmentId<PluginsCatalogsections={sections}servers={displayServers}+ accessStatuses={subscriptionAuth.data?.access ?? []}pendingServerId={pendingServerId}onToggle={(plugin, enabled) => void togglePlugin(plugin, enabled)}onOpen={openPlugin}diff --git a/apps/web/src/components/plugins/pluginConnection.test.ts b/apps/web/src/components/plugins/pluginConnection.test.tsnew file mode 100644index 000000000..68dbcdbec--- /dev/null+++ b/apps/web/src/components/plugins/pluginConnection.test.ts@@ -0,0 +1,92 @@+import { McpServerId } from "@t3tools/contracts";+import { describe, expect, it, vi } from "vite-plus/test";++import { runPluginEnablePlan } from "./pluginConnection";++const mcpServerId = McpServerId.make("builtin-hoplite");++describe("plugin connection", () => {+ it("creates an OAuth plugin before it authenticates the real MCP connection", async () => {+ const calls: string[] = [];+ const openAuthorizationUrl = vi.fn(async () => undefined);++ const connected = await runPluginEnablePlan(+ {+ action: "create",+ mcpServerId,+ configuration: { name: "Hoplite", transport: "url", url: "https://mcp.hoplite.ai" },+ },+ {+ create: async () => {+ calls.push("create");+ return true;+ },+ update: async () => true,+ enable: async () => true,+ authenticate: async (_serverId, onAuthorizationUrl) => {+ calls.push("authenticate");+ await onAuthorizationUrl("https://hoplite.ai/oauth/authorize");+ return true;+ },+ openAuthorizationUrl,+ },+ );++ expect(connected).toBe(true);+ expect(calls).toEqual(["create", "authenticate"]);+ expect(openAuthorizationUrl).toHaveBeenCalledWith("https://hoplite.ai/oauth/authorize");+ });++ it("refreshes and enables a disabled plugin before authenticating it", async () => {+ const calls: string[] = [];++ const connected = await runPluginEnablePlan(+ {+ action: "refresh-and-enable",+ mcpServerId,+ configuration: { name: "Hoplite", transport: "url", url: "https://mcp.hoplite.ai" },+ },+ {+ create: async () => true,+ update: async () => {+ calls.push("update");+ return true;+ },+ enable: async () => {+ calls.push("enable");+ return true;+ },+ authenticate: async () => {+ calls.push("authenticate");+ return true;+ },+ openAuthorizationUrl: async () => undefined,+ },+ );++ expect(connected).toBe(true);+ expect(calls).toEqual(["update", "enable", "authenticate"]);+ });++ it("does not claim a connection or start OAuth when registration fails", async () => {+ const authenticate = vi.fn(async () => true);++ const connected = await runPluginEnablePlan(+ {+ action: "create",+ mcpServerId,+ configuration: { name: "Hoplite", transport: "url", url: "https://mcp.hoplite.ai" },+ },+ {+ create: async () => false,+ update: async () => true,+ enable: async () => true,+ authenticate,+ openAuthorizationUrl: async () => undefined,+ },+ );++ expect(connected).toBe(false);+ expect(authenticate).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/components/plugins/pluginConnection.ts b/apps/web/src/components/plugins/pluginConnection.tsnew file mode 100644index 000000000..8cb46ef14--- /dev/null+++ b/apps/web/src/components/plugins/pluginConnection.ts@@ -0,0 +1,36 @@+import type { McpServerId, McpServerConfiguration } from "@t3tools/contracts";++import type { PluginTogglePlan } from "./pluginRegistry";++interface PluginEnableOperations {+ readonly create: (+ mcpServerId: McpServerId,+ configuration: McpServerConfiguration,+ ) => Promise<boolean>;+ readonly update: (+ mcpServerId: McpServerId,+ configuration: McpServerConfiguration,+ ) => Promise<boolean>;+ readonly enable: (mcpServerId: McpServerId) => Promise<boolean>;+ readonly authenticate?: (+ mcpServerId: McpServerId,+ onAuthorizationUrl: (url: string) => Promise<void>,+ ) => Promise<boolean>;+ readonly openAuthorizationUrl: (url: string) => Promise<void>;+}++export async function runPluginEnablePlan(+ plan: Exclude<PluginTogglePlan, { readonly action: "disable" }>,+ operations: PluginEnableOperations,+): Promise<boolean> {+ if (plan.action === "create") {+ if (!(await operations.create(plan.mcpServerId, plan.configuration))) return false;+ } else {+ if (!(await operations.update(plan.mcpServerId, plan.configuration))) return false;+ if (!(await operations.enable(plan.mcpServerId))) return false;+ }++ return operations.authenticate+ ? operations.authenticate(plan.mcpServerId, operations.openAuthorizationUrl)+ : true;+}diff --git a/apps/web/src/components/plugins/pluginPresentation.test.ts b/apps/web/src/components/plugins/pluginPresentation.test.tsindex d78223a5d..36cfc811f 100644--- a/apps/web/src/components/plugins/pluginPresentation.test.ts+++ b/apps/web/src/components/plugins/pluginPresentation.test.ts@@ -221,6 +221,19 @@ describe("plugin presentation", () => {enable: true,});expect(pluginPrimaryAction(firecrawl, server(true)).label).toBe("Disable");+ expect(+ pluginPrimaryAction(firecrawl, server(true), {+ id: "mcp-builtin-firecrawl",+ label: "Firecrawl",+ accessMethod: "mcp",+ health: "failed-first-request",+ apiAccess: "not-applicable",+ nextAction: "Reconnect Firecrawl.",+ pluginId: "firecrawl",+ dependentBots: [],+ dependentRoutines: [],+ }),+ ).toEqual({ label: "Reconnect", enable: true });expect(pluginPrimaryAction(firecrawl, server(false)).label).toBe("Reconnect");expect(pluginConnectionLabel(firecrawl)).toBe("OAuth");});diff --git a/apps/web/src/components/plugins/pluginPresentation.ts b/apps/web/src/components/plugins/pluginPresentation.tsindex 3e6169123..8bade7de4 100644--- a/apps/web/src/components/plugins/pluginPresentation.ts+++ b/apps/web/src/components/plugins/pluginPresentation.ts@@ -1,4 +1,4 @@-import type { McpServer, OrchestrationBot } from "@t3tools/contracts";+import type { McpServer, OrchestrationBot, ProviderAccessStatus } from "@t3tools/contracts";import {PLUGIN_CATEGORIES,type PluginCategory,@@ -104,8 +104,13 @@ export function pluginBlocker(plugin: PluginDirectoryDefinition): string | nullexport function pluginPrimaryAction(plugin: PluginDirectoryDefinition,server: McpServer | undefined,+ accessStatus?: ProviderAccessStatus,): PluginPrimaryAction {- if (server?.enabled) return { label: "Disable", enable: false };+ const needsReconnect =+ (plugin.authentication === "oauth" || plugin.authentication === "optional-oauth") &&+ accessStatus !== undefined &&+ ["expired", "revoked", "failed", "failed-first-request"].includes(accessStatus.health);+ if (server?.enabled && !needsReconnect) return { label: "Disable", enable: false };const blocker = pluginBlocker(plugin);if (blocker) return { label: "Connect", enable: null, blocker };if (server) return { label: "Reconnect", enable: true };diff --git a/docs/user/plugins.md b/docs/user/plugins.mdindex 4fd328257..9e0ca6d4e 100644--- a/docs/user/plugins.md+++ b/docs/user/plugins.md@@ -18,7 +18,7 @@ connection works. A routine can require an enabled connector.- **Connect** starts OAuth.- **Add key** stores a required key in the host environment.- **Disable** stops the plugin without deleting it.-- **Reconnect** repairs and enables a disabled plugin.+- **Reconnect** repairs a failed OAuth connection or enables a disabled plugin.- **Remove** deletes the registration.A plugin waiting for publisher approval stays visible, but **Connect** remains disabled. A plugindiff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.tsindex c1d4cd549..4c91f588e 100644--- a/packages/client-runtime/src/rpc/client.ts+++ b/packages/client-runtime/src/rpc/client.ts@@ -56,6 +56,7 @@ export type EnvironmentSubscriptionRpcTag =export type EnvironmentStreamCommandRpcTag =| typeof WS_METHODS.serverUpdateServerWithProgress+ | typeof WS_METHODS.mcpServerAuthenticate| typeof WS_METHODS.gitRunStackedAction;export type EnvironmentStreamRpcTag =diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.tsindex 9f10387d0..b826c347e 100644--- a/packages/client-runtime/src/state/server.ts+++ b/packages/client-runtime/src/state/server.ts@@ -1,5 +1,6 @@import {type EnvironmentId,+ type McpServerId,type ServerConfig,type ServerConfigStreamEvent,type ServerLifecycleWelcomePayload,@@ -65,6 +66,12 @@ export interface ServerUpdateTarget {readonly input: EnvironmentRpcInput<typeof WS_METHODS.serverUpdateServer>;}+export interface McpServerAuthenticationTarget {+ readonly environmentId: EnvironmentId;+ readonly mcpServerId: McpServerId;+ readonly onAuthorizationUrl: (url: string) => void | Promise<void>;+}+export function voiceCallHangupConcurrencyKey(input: {readonly environmentId: EnvironmentId;readonly input: EnvironmentRpcInput<typeof WS_METHODS.voiceCallHangup>;@@ -118,6 +125,11 @@ export class ServerUpdateTerminalError extends Schema.TaggedErrorClass<ServerUpd}}+export class McpServerAuthenticationClientError extends Schema.TaggedErrorClass<McpServerAuthenticationClientError>()(+ "McpServerAuthenticationClientError",+ { message: Schema.String, cause: Schema.optional(Schema.Defect()) },+) {}+// Covers the 120-second trial deadline and a final restart of the previous// version when the trial rolls back.const SERVER_UPDATE_RESUME_TIMEOUT = Duration.minutes(4);@@ -690,6 +702,53 @@ export function createServerEnvironmentAtoms<R, E>();},});+ const authenticateMcpServer = createRuntimeCommand(runtime, {+ label: "environment-data:server:authenticate-mcp-server",+ concurrency: {+ mode: "singleFlight",+ key: (target: McpServerAuthenticationTarget) =>+ `${target.environmentId}:${target.mcpServerId}`,+ },+ execute: (target: McpServerAuthenticationTarget) =>+ Effect.gen(function* () {+ const environmentRegistry = yield* EnvironmentRegistry;+ let toolCount: number | undefined;+ let recoveryFailures: readonly string[] = [];+ yield* environmentRegistry+ .runStream(+ target.environmentId,+ runStream(WS_METHODS.mcpServerAuthenticate, {+ mcpServerId: target.mcpServerId,+ }),+ )+ .pipe(+ Stream.runForEach((event) =>+ event.type === "authorization-required"+ ? Effect.tryPromise({+ try: () => Promise.resolve(target.onAuthorizationUrl(event.authorizationUrl)),+ catch: (cause) =>+ new McpServerAuthenticationClientError({+ message:+ cause instanceof Error+ ? cause.message+ : "Could not open the authorization URL.",+ cause,+ }),+ })+ : Effect.sync(() => {+ toolCount = event.toolCount;+ recoveryFailures = event.recoveryFailures;+ }),+ ),+ );+ if (toolCount === undefined) {+ return yield* new McpServerAuthenticationClientError({+ message: "MCP authentication ended before the server connected.",+ });+ }+ return { toolCount, recoveryFailures };+ }),+ });const settingsValueAtom = Atom.family((environmentId: EnvironmentId) =>Atom.make((get) => get(configValueAtom(environmentId))?.settings ?? null).pipe(Atom.withLabel(`environment-data:server:settings:${environmentId}`),@@ -779,6 +838,7 @@ export function createServerEnvironmentAtoms<R, E>(concurrency: configConcurrency,}),updateServer,+ authenticateMcpServer,upsertKeybinding: createEnvironmentRpcCommand(runtime, {label: "environment-data:server:upsert-keybinding",tag: WS_METHODS.serverUpsertKeybinding,diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex 8c9a48330..a17c7125f 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -181,6 +181,9 @@ import { ServerSettings, ServerSettingsError, ServerSettingsRpcPatch } from "./simport {BotInboxItem,BotInboxResolveInput,+ McpServerAuthenticateInput,+ McpServerAuthenticationError,+ McpServerAuthenticationProgress,SubscriptionAuthCompleteInput,SubscriptionAuthError,SubscriptionAuthHealthTestInput,@@ -316,6 +319,7 @@ export const WS_METHODS = {subscriptionAuthCancel: "subscriptionAuth.cancel",subscriptionAuthLogout: "subscriptionAuth.logout",subscriptionAuthHealthTest: "subscriptionAuth.healthTest",+ mcpServerAuthenticate: "mcpServer.authenticate",botInboxList: "botInbox.list",botInboxResolve: "botInbox.resolve",voiceCallGet: "voiceCall.get",@@ -511,6 +515,13 @@ export const WsSubscriptionAuthHealthTestRpc = Rpc.make(WS_METHODS.subscriptionAerror: Schema.Union([SubscriptionAuthError, EnvironmentAuthorizationError]),});+export const WsMcpServerAuthenticateRpc = Rpc.make(WS_METHODS.mcpServerAuthenticate, {+ payload: McpServerAuthenticateInput,+ success: McpServerAuthenticationProgress,+ error: Schema.Union([McpServerAuthenticationError, EnvironmentAuthorizationError]),+ stream: true,+});+export const WsBotInboxListRpc = Rpc.make(WS_METHODS.botInboxList, {payload: Schema.Struct({}),success: Schema.Array(BotInboxItem),@@ -1100,6 +1111,7 @@ export const WsRpcGroup = RpcGroup.make(WsSubscriptionAuthCancelRpc,WsSubscriptionAuthLogoutRpc,WsSubscriptionAuthHealthTestRpc,+ WsMcpServerAuthenticateRpc,WsBotInboxListRpc,WsBotInboxResolveRpc,WsVoiceCallGetRpc,diff --git a/packages/contracts/src/subscriptionAuth.ts b/packages/contracts/src/subscriptionAuth.tsindex 5a7575107..1bf9d3ade 100644--- a/packages/contracts/src/subscriptionAuth.ts+++ b/packages/contracts/src/subscriptionAuth.ts@@ -8,7 +8,8 @@*/import * as Effect from "effect/Effect";import * as Schema from "effect/Schema";-import { BotId, IsoDateTime, TrimmedNonEmptyString } from "./baseSchemas.ts";+import { BotId, IsoDateTime, NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts";+import { McpServerId } from "./mcpServer.ts";export const SubscriptionProviderId = Schema.Literals(["anthropic",@@ -202,3 +203,33 @@ export class SubscriptionAuthError extends Schema.TaggedErrorClass<SubscriptionAreturn this.reason;}}++export const McpServerAuthenticateInput = Schema.Struct({+ mcpServerId: McpServerId,+});+export type McpServerAuthenticateInput = typeof McpServerAuthenticateInput.Type;++export const McpServerAuthenticationProgress = Schema.Union([+ Schema.Struct({+ type: Schema.Literal("authorization-required"),+ authorizationUrl: TrimmedNonEmptyString,+ }),+ Schema.Struct({+ type: Schema.Literal("connected"),+ toolCount: NonNegativeInt,+ recoveryFailures: Schema.Array(TrimmedNonEmptyString),+ }),+]);+export type McpServerAuthenticationProgress = typeof McpServerAuthenticationProgress.Type;++export class McpServerAuthenticationError extends Schema.TaggedErrorClass<McpServerAuthenticationError>()(+ "McpServerAuthenticationError",+ {+ mcpServerId: McpServerId,+ reason: TrimmedNonEmptyString,+ },+) {+ override get message(): string {+ return this.reason;+ }+}