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.

fix(mcp): open OAuth authorization requests (#156)

Leoc9473b6d2a02
diff --git a/apps/mobile/src/lib/openExternalUrl.ts b/apps/mobile/src/lib/openExternalUrl.ts
index 10e6378bc..27af28edb 100644
--- a/apps/mobile/src/lib/openExternalUrl.ts
+++ b/apps/mobile/src/lib/openExternalUrl.ts
@@ -1,7 +1,12 @@
import * as Schema from "effect/Schema";
import { Linking } from "react-native";
-const ExternalUrlTarget = Schema.Literals(["file-preview", "markdown-link", "pull-request"]);
+const ExternalUrlTarget = Schema.Literals([
+ "file-preview",
+ "markdown-link",
+ "mcp-oauth",
+ "pull-request",
+]);
export type ExternalUrlTarget = typeof ExternalUrlTarget.Type;
diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts
index dd7ace60a..042a21853 100644
--- a/apps/mobile/src/state/use-thread-composer-state.ts
+++ b/apps/mobile/src/state/use-thread-composer-state.ts
@@ -1,5 +1,5 @@
import { useAtomValue } from "@effect/atom-react";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Alert } from "react-native";
import * as Cause from "effect/Cause";
@@ -32,6 +32,7 @@ import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { scopedThreadKey } from "../lib/scopedEntities";
import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
import { buildThreadFeed } from "../lib/threadActivity";
+import { tryOpenExternalUrl } from "../lib/openExternalUrl";
import { appAtomRegistry } from "../state/atom-registry";
import {
appendComposerDraftAttachments,
@@ -88,6 +89,7 @@ export function useThreadDraftForThread(input: {
export function useThreadComposerState() {
const { selectedThread: selectedThreadShell, selectedEnvironmentRuntime } = useThreadSelection();
const selectedThreadDetail = useSelectedThreadDetail();
+ const openedAuthorizationActivitiesRef = useRef(new Set<string>());
const composerDrafts = useAtomValue(composerDraftsAtom);
const queuedMessagesByThreadKey = useThreadOutboxMessages();
const [feedbackSubmissionsByThreadKey, setFeedbackSubmissionsByThreadKey] = useState<
@@ -101,6 +103,24 @@ export function useThreadComposerState() {
ensureComposerDraftsLoaded();
}, []);
+ useEffect(() => {
+ for (const activity of selectedThreadDetail?.activities ?? []) {
+ if (activity.kind !== "mcp.oauth.authorization-required") continue;
+ if (openedAuthorizationActivitiesRef.current.has(activity.id)) continue;
+ if (!activity.payload || typeof activity.payload !== "object") continue;
+ const authorizationUrl = (activity.payload as Record<string, unknown>).authorizationUrl;
+ if (typeof authorizationUrl !== "string") continue;
+ try {
+ if (new URL(authorizationUrl).protocol !== "https:") continue;
+ } catch {
+ continue;
+ }
+ openedAuthorizationActivitiesRef.current.add(activity.id);
+ void tryOpenExternalUrl(authorizationUrl, "mcp-oauth");
+ break;
+ }
+ }, [selectedThreadDetail?.activities]);
+
const selectedThreadKey = selectedThreadShell
? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
: null;
diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
index 0e0e7fbfa..ea8b11b55 100644
--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
@@ -771,6 +771,26 @@ export function runtimeEventToActivities(
];
}
+ case "tool.receipt": {
+ if (event.payload.phase !== "progress" || !event.payload.authorizationUrl) return [];
+ return [
+ {
+ id: event.eventId,
+ createdAt: event.createdAt,
+ tone: "info",
+ kind: "mcp.oauth.authorization-required",
+ summary: event.payload.summary ?? "Authorize MCP server",
+ payload: {
+ authorizationUrl: event.payload.authorizationUrl,
+ toolCallId: event.payload.receiptId,
+ toolName: event.payload.toolId,
+ },
+ turnId: toTurnId(event.turnId) ?? null,
+ ...maybeSequence,
+ },
+ ];
+ }
+
case "task.completed": {
return [
{
diff --git a/apps/server/src/provider/AkeruCatalogToolHandlers.test.ts b/apps/server/src/provider/AkeruCatalogToolHandlers.test.ts
index 432675a21..eb3a53623 100644
--- a/apps/server/src/provider/AkeruCatalogToolHandlers.test.ts
+++ b/apps/server/src/provider/AkeruCatalogToolHandlers.test.ts
@@ -72,9 +72,9 @@ describe("Akeru catalog MCP tool handlers", () => {
...status,
authorizationUrl: "https://example.com/authorize",
});
- expect(emitProgress).toHaveBeenCalledWith(
- "Authorize MCP server 'search' at https://example.com/authorize",
- );
+ expect(emitProgress).toHaveBeenCalledWith("Authorize MCP server 'search'.", {
+ authorizationUrl: "https://example.com/authorize",
+ });
authenticateServer.mockResolvedValueOnce({
...status,
diff --git a/apps/server/src/provider/AkeruCatalogToolHandlers.ts b/apps/server/src/provider/AkeruCatalogToolHandlers.ts
index 1b5896d23..a0f09dc64 100644
--- a/apps/server/src/provider/AkeruCatalogToolHandlers.ts
+++ b/apps/server/src/provider/AkeruCatalogToolHandlers.ts
@@ -55,7 +55,10 @@ import type { RequestHealthStatus } from "../subscription-auth/service.ts";
export interface AkeruCatalogToolHandlerInput {
readonly input: unknown;
- readonly emitProgress: (summary: string) => void | Promise<void>;
+ readonly emitProgress: (
+ summary: string,
+ details?: { readonly authorizationUrl?: string },
+ ) => void | Promise<void>;
}
export type AkeruCatalogToolHandler = (input: AkeruCatalogToolHandlerInput) => Promise<unknown>;
@@ -465,7 +468,9 @@ export function createAkeruCatalogToolHandlers(
const status = await mcpManager.authenticateServer(serverId, {
onAuthorizationUrl: (url) => {
authorizationUrl = url;
- void emitProgress(`Authorize MCP server '${serverId}' at ${url}`);
+ void emitProgress(`Authorize MCP server '${serverId}'.`, {
+ authorizationUrl: url,
+ });
},
});
if (!status.connected) {
diff --git a/apps/server/src/provider/AkeruToolRuntime.ts b/apps/server/src/provider/AkeruToolRuntime.ts
index 9cf1af76b..32dcf3ee5 100644
--- a/apps/server/src/provider/AkeruToolRuntime.ts
+++ b/apps/server/src/provider/AkeruToolRuntime.ts
@@ -103,6 +103,7 @@ export interface AkeruToolRuntimeOptions {
readonly toolId: AkeruToolId;
readonly toolCallId: string;
readonly summary: string;
+ readonly authorizationUrl?: string;
}) => void | Promise<void>;
readonly now?: () => string;
}
@@ -519,12 +520,13 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): Akeru
failureCode = "internal";
result = await catalogHandler({
input: decoded,
- emitProgress: (summary: string) =>
+ emitProgress: (summary, details) =>
options?.onProgress?.({
threadId: input.threadId,
toolId: input.toolId as AkeruToolId,
toolCallId: input.toolCallId,
summary,
+ ...details,
}),
});
} else if (input.toolId === "SendToAgent" || input.toolId === "MessageAgent") {
diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.ts
index 0a3cf8830..c4cda9c13 100644
--- a/apps/server/src/provider/Layers/AgentController.ts
+++ b/apps/server/src/provider/Layers/AgentController.ts
@@ -617,7 +617,7 @@ const make = (options?: AgentControllerLiveOptions) =>
createdAt: receipt.createdAt,
});
},
- onProgress: ({ threadId, toolId, toolCallId, summary }) => {
+ onProgress: ({ threadId, toolId, toolCallId, summary, authorizationUrl }) => {
const active = sessions.get(threadId);
if (!active) return;
PubSub.publishUnsafe(runtimeEvents, {
@@ -630,6 +630,7 @@ const make = (options?: AgentControllerLiveOptions) =>
threadId: ThreadId.make(threadId),
...(active.toolSession.botId ? { botId: active.toolSession.botId } : {}),
summary,
+ ...(authorizationUrl ? { authorizationUrl } : {}),
fatalToThread: false,
createdAt: nowIso(),
},
diff --git a/apps/web/src/components/roster/botThreadRuntime.logic.test.ts b/apps/web/src/components/roster/botThreadRuntime.logic.test.ts
index 6df591b33..a0b07f6b5 100644
--- a/apps/web/src/components/roster/botThreadRuntime.logic.test.ts
+++ b/apps/web/src/components/roster/botThreadRuntime.logic.test.ts
@@ -7,10 +7,30 @@ import {
createBotTurnSubmissionQueue,
findLatestBotThreadTarget,
findLatestGroupThreadTarget,
+ findUnhandledMcpAuthorization,
joinOrStartThreadCreate,
} from "./botThreadRuntime.logic";
describe("bot thread runtime", () => {
+ it("finds each secure MCP authorization once and rejects unsafe URLs", () => {
+ const activities = [
+ {
+ id: "unsafe",
+ kind: "mcp.oauth.authorization-required",
+ payload: { authorizationUrl: "http://example.com" },
+ },
+ {
+ id: "oauth",
+ kind: "mcp.oauth.authorization-required",
+ payload: { authorizationUrl: "https://hoplite.example/authorize" },
+ },
+ ];
+ expect(findUnhandledMcpAuthorization(activities, new Set())).toEqual({
+ activityId: "oauth",
+ url: "https://hoplite.example/authorize",
+ });
+ expect(findUnhandledMcpAuthorization(activities, new Set(["oauth"]))).toBeNull();
+ });
it("queues rapid submissions without waiting for the active reply", async () => {
const queue = createBotTurnSubmissionQueue();
const order: string[] = [];
diff --git a/apps/web/src/components/roster/botThreadRuntime.logic.ts b/apps/web/src/components/roster/botThreadRuntime.logic.ts
index 349afb6ad..234e731d8 100644
--- a/apps/web/src/components/roster/botThreadRuntime.logic.ts
+++ b/apps/web/src/components/roster/botThreadRuntime.logic.ts
@@ -191,3 +191,28 @@ export function findLatestGroupThreadTarget(
)[0];
return latest ? { environmentId: latest.environmentId, threadId: latest.id } : null;
}
+
+export function findUnhandledMcpAuthorization(
+ activities: ReadonlyArray<{
+ readonly id: string;
+ readonly kind: string;
+ readonly payload: unknown;
+ }>,
+ handledIds: ReadonlySet<string>,
+): { readonly activityId: string; readonly url: string } | null {
+ for (const activity of activities) {
+ if (activity.kind !== "mcp.oauth.authorization-required" || handledIds.has(activity.id)) {
+ continue;
+ }
+ if (!activity.payload || typeof activity.payload !== "object") continue;
+ const authorizationUrl = (activity.payload as Record<string, unknown>).authorizationUrl;
+ if (typeof authorizationUrl !== "string") continue;
+ try {
+ const url = new URL(authorizationUrl);
+ if (url.protocol === "https:") return { activityId: activity.id, url: url.href };
+ } catch {
+ // Ignore malformed server data.
+ }
+ }
+ return null;
+}
diff --git a/apps/web/src/components/roster/useBotThreadRuntime.ts b/apps/web/src/components/roster/useBotThreadRuntime.ts
index 2bfdf6242..29635b684 100644
--- a/apps/web/src/components/roster/useBotThreadRuntime.ts
+++ b/apps/web/src/components/roster/useBotThreadRuntime.ts
@@ -41,11 +41,13 @@ import { resolveBotRuntimeMode } from "./botSandbox";
import {
buildBotTurnStartInput,
createBotTurnSubmissionQueue,
+ findUnhandledMcpAuthorization,
joinOrStartThreadCreate,
resolveBotThreadTarget,
} from "./botThreadRuntime.logic";
import { parseChatPath } from "./roster.logic";
import { useRosterStore } from "./rosterStore";
+import { ensureLocalApi } from "../../localApi";
const NO_ENVIRONMENT = "" as EnvironmentId;
@@ -118,6 +120,16 @@ export function useBotThreadRuntime(botId: string, effectiveModelSelection: Mode
}
const messages = useThreadMessages(linkedThreadRef);
const activities = useThreadActivities(linkedThreadRef);
+ const openedAuthorizationActivitiesRef = useRef(new Set<string>());
+ useEffect(() => {
+ const authorization = findUnhandledMcpAuthorization(
+ activities,
+ openedAuthorizationActivitiesRef.current,
+ );
+ if (!authorization) return;
+ openedAuthorizationActivitiesRef.current.add(authorization.activityId);
+ void ensureLocalApi().shell.openExternal(authorization.url);
+ }, [activities]);
const pendingApprovals = useMemo(() => derivePendingApprovals(activities), [activities]);
const pendingUserInputs = useMemo(() => derivePendingUserInputs(activities), [activities]);
const defaultProject = useMemo(
diff --git a/packages/contracts/src/akeruTools.ts b/packages/contracts/src/akeruTools.ts
index 8fa5387c6..77f183e1a 100644
--- a/packages/contracts/src/akeruTools.ts
+++ b/packages/contracts/src/akeruTools.ts
@@ -483,6 +483,7 @@ export const AkeruToolReceipt = Schema.Struct({
botId: Schema.optional(BotId),
handleId: Schema.optional(AkeruAwaitHandleId),
summary: Schema.optional(TrimmedNonEmptyString),
+ authorizationUrl: Schema.optional(TrimmedNonEmptyString),
progress: Schema.optional(NonNegativeInt),
approvalClass: Schema.optional(AkeruToolApprovalClass),
failureCode: Schema.optional(AkeruToolFailureCode),