The open-source agent harness - the runtime layer that turns an LLM into a working agent.
feat: redirect to success/error page on oauth callback (#50)
Sujai Kumar Gupta300657be94fe
diff --git a/fern/openapi/openapi.json b/fern/openapi/openapi.jsonindex 73c5599fe..d65693152 100644--- a/fern/openapi/openapi.json+++ b/fern/openapi/openapi.json@@ -3289,7 +3289,10 @@}}},- "description": "Token exchanged successfully; no browser redirect."+ "description": "Token exchanged successfully and no `redirect_url` was given at authorize time."+ },+ "302": {+ "description": "Redirect to the `redirect_url` given at authorize time, with `isSuccess` (and `reason` when it failed) appended to its existing query params."},"400": {"content": {@@ -4344,7 +4347,7 @@},"/api/v1/settings/mcp-servers/{name}/authorize": {"get": {- "description": "For servers without auth returns not_required, and for header credentials returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional redirect_url is stored for a future FE landing redirect (callback currently returns JSON only).",+ "description": "For servers without auth returns not_required, and for header credentials returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional redirect_url is where the OAuth callback then redirects the browser; without it the callback returns JSON.","parameters": [{"description": "Configured MCP server name.",@@ -4358,12 +4361,12 @@}},{- "description": "Optional FE landing URL after OAuth (stored on pending auth; callback does not redirect yet).",+ "description": "Optional FE landing URL the OAuth callback redirects to, with `isSuccess`/`reason` appended.","in": "query","name": "redirect_url","required": false,"schema": {- "description": "Optional FE landing URL after OAuth (stored on pending auth; callback does not redirect yet).",+ "description": "Optional FE landing URL the OAuth callback redirects to, with `isSuccess`/`reason` appended.","format": "uri","type": "string"}diff --git a/packages/harness/src/core/index.ts b/packages/harness/src/core/index.tsindex 38fad7aa4..82c32d30b 100644--- a/packages/harness/src/core/index.ts+++ b/packages/harness/src/core/index.ts@@ -164,12 +164,7 @@ export {resolveMcpAuth,validateRedirectUris,} from './mcp/auth';-export type {- CompleteMcpAuthorizationResult,- McpAuthRequiredResult,- McpAuthResolvedResult,- ResolveMcpAuthResult,-} from './mcp/auth';+export type { McpAuthRequiredResult, McpAuthResolvedResult, ResolveMcpAuthResult } from './mcp/auth';// Sandbox (concrete implementation; provider details exported for composition)export { DaytonaSandboxProvider } from './sandbox/provider/DaytonaProvider';diff --git a/packages/harness/src/core/mcp/auth/index.ts b/packages/harness/src/core/mcp/auth/index.tsindex 11b3fc362..ea9cca1df 100644--- a/packages/harness/src/core/mcp/auth/index.ts+++ b/packages/harness/src/core/mcp/auth/index.ts@@ -6,12 +6,7 @@ export {isMcpAuthRequired,resolveMcpAuth,} from './mcpDcr';-export type {- CompleteMcpAuthorizationResult,- McpAuthRequiredResult,- McpAuthResolvedResult,- ResolveMcpAuthResult,-} from './mcpDcr';+export type { McpAuthRequiredResult, McpAuthResolvedResult, ResolveMcpAuthResult } from './mcpDcr';export {DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS,MCP_OAUTH_CALLBACK_PATH,diff --git a/packages/harness/src/core/mcp/auth/mcpDcr.ts b/packages/harness/src/core/mcp/auth/mcpDcr.tsindex be2620798..4f4c71558 100644--- a/packages/harness/src/core/mcp/auth/mcpDcr.ts+++ b/packages/harness/src/core/mcp/auth/mcpDcr.ts@@ -14,7 +14,7 @@ import type {} from '@modelcontextprotocol/sdk/shared/auth.js';import { randomBytes } from 'node:crypto';import type { IOAuthClientStore, OAuthClientRecord } from '../../auth/IOAuthClientStore';-import type { IOAuthTokenStore } from '../../auth/IOAuthTokenStore';+import type { IOAuthTokenStore, OAuthPendingAuthorization } from '../../auth/IOAuthTokenStore';import { isOAuthAccessTokenUsable } from '../../auth/oauthToken';import { McpConnectionError, McpDcrConfigurationError } from '../../errors';import {@@ -39,13 +39,6 @@ export function isMcpAuthRequired(result: ResolveMcpAuthResult): result is McpAureturn 'authUrl' in result;}-/** Result of a successful `completeMcpAuthorization` (token saved, pending cleared). */-export interface CompleteMcpAuthorizationResult {- serverId: string;- /** FE post-OAuth landing URL from the original authorize call. */- redirectUrl: string | null;-}-/*** Prefer `client_secret_post` (confidential). Authorization servers that only issue public* clients or only accept other methods can reject that; retry once without the field (same as@@ -287,24 +280,20 @@ export async function resolveMcpAuth(params: {}/**- * OAuth callback: exchange `code` for tokens. Route must already reject IdP `error` params.- * Claims pending state atomically (`consumePendingAuthorization`) so duplicate callbacks lose- * the race; `mcpServerUrl` for the RFC 8707 `resource` comes from that pending row.+ * OAuth callback: exchange `code` for tokens against an already-claimed `pending` row. The caller+ * claims it with `consumePendingAuthorization` (so duplicate callbacks lose the race) and keeps it+ * for its FE landing URL; `mcpServerUrl` for the RFC 8707 `resource` comes from that row.+ * Route must already reject IdP `error` params.* On `invalid_client`, clears stored client + token so the next authorize re-registers.*/export async function completeMcpAuthorization(params: {tokenStore: IOAuthTokenStore;mcpServerStore: IOAuthClientStore;- state: string;+ pending: OAuthPendingAuthorization;code: string;-}): Promise<CompleteMcpAuthorizationResult> {+}): Promise<void> {const nowMs = Date.now();-- // Consume first so a concurrent/duplicate callback cannot redeem the same state.- const pending = await params.tokenStore.consumePendingAuthorization({ state: params.state });- if (!pending) {- throw new McpConnectionError('Unknown or expired OAuth state', 400);- }+ const { pending } = params;const client = await params.mcpServerStore.getClient({ id: pending.id });if (!client) {@@ -346,6 +335,4 @@ export async function completeMcpAuthorization(params: {id: pending.id,token: oauthTokensToOAuthToken(tokens, nowMs, null),});-- return { serverId: pending.id, redirectUrl: pending.redirectUrl };}diff --git a/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts b/packages/harness/tests/core/mcp/auth/mcpOAuth.test.tsindex e1b717be9..23143f276 100644--- a/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts+++ b/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts@@ -593,7 +593,7 @@ describe('end-to-end DCR + authorize with normalised MCP URL', () => {});describe('completeMcpAuthorization', () => {- it('exchanges the code, saves the token, clears pending, and returns redirectUrl', async () => {+ it('exchanges the code and saves the token for the claimed pending row', async () => {const stores = newStores();await stores.mcpServerStore.saveClient({ id: SERVER_ID, record: sampleClient });@@ -612,20 +612,22 @@ describe('completeMcpAuthorization', () => {},});+ const pending = await stores.tokenStore.consumePendingAuthorization({ state });+ if (!pending) {+ throw new Error('expected buildMcpAuthorizationUrl to save a pending authorization');+ }+ expect(pending.redirectUrl).toBe('https://app.example.com/connected');+const beforeMs = Date.now();- const result = await completeMcpAuthorization({+ await completeMcpAuthorization({tokenStore: stores.tokenStore,mcpServerStore: stores.mcpServerStore,- state,+ pending,code: 'auth-code-1',});const afterMs = Date.now();- expect(result).toEqual({- serverId: SERVER_ID,- redirectUrl: 'https://app.example.com/connected',- });- // Complete claimed the pending row; a second callback would fail.+ // The row was claimed once; a duplicate callback finds nothing left to redeem.expect(await stores.tokenStore.consumePendingAuthorization({ state })).toBeUndefined();const saved = await stores.tokenStore.getToken({ id: SERVER_ID });expect(saved?.accessToken).toBe('exchanged-access');@@ -641,18 +643,24 @@ describe('completeMcpAuthorization', () => {expect(tokenBody.get('resource')).toBe(resourceUrlFromServerUrl(SERVER_URL).href);});- it('throws on unknown state', async () => {+ it('throws when the pending row has no registered OAuth client', async () => {const stores = newStores();await expect(completeMcpAuthorization({tokenStore: stores.tokenStore,mcpServerStore: stores.mcpServerStore,- state: 'missing-state',+ pending: {+ state: 'state-1',+ id: SERVER_ID,+ mcpServerUrl: SERVER_URL,+ codeVerifier: 'verifier-1',+ redirectUrl: null,+ },code: 'code',}),).rejects.toMatchObject({name: 'McpConnectionError',- message: expect.stringContaining('Unknown or expired'),+ message: expect.stringContaining('No OAuth client registered'),});});@@ -673,11 +681,16 @@ describe('completeMcpAuthorization', () => {return new Response(`unexpected url: ${url}`, { status: 404 });}) as typeof fetch;+ const pending = await stores.tokenStore.consumePendingAuthorization({ state });+ if (!pending) {+ throw new Error('expected buildMcpAuthorizationUrl to save a pending authorization');+ }+await expect(completeMcpAuthorization({tokenStore: stores.tokenStore,mcpServerStore: stores.mcpServerStore,- state,+ pending,code: 'auth-code-1',}),).rejects.toMatchObject({diff --git a/packages/sdk/.fern/metadata.json b/packages/sdk/.fern/metadata.jsonindex 41e64fdf2..2f513b746 100644--- a/packages/sdk/.fern/metadata.json+++ b/packages/sdk/.fern/metadata.json@@ -27,8 +27,8 @@"streamType": "web","useDefaultRequestParameterValues": true},- "originGitCommit": "b60a3797aa2313e20f023e5965c000387d7ccbcd",- "originGitCommitIsDirty": false,+ "originGitCommit": "2fa4d1229e085b8dab98f45717ebd82db9311e5c",+ "originGitCommitIsDirty": true,"invokedBy": "ci","requestedVersion": "0.0.0","ciProvider": "github",diff --git a/packages/sdk/reference.md b/packages/sdk/reference.mdindex 7612ca1be..9e401b6a4 100644--- a/packages/sdk/reference.md+++ b/packages/sdk/reference.md@@ -1262,7 +1262,7 @@ await client.settings.mcpServers.catalog();<dl><dd>-For servers without auth returns not_required, and for header credentials returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional redirect_url is stored for a future FE landing redirect (callback currently returns JSON only).+For servers without auth returns not_required, and for header credentials returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional redirect_url is where the OAuth callback then redirects the browser; without it the callback returns JSON.</dd></dl></dd>diff --git a/packages/sdk/src/api/resources/settings/resources/mcpServers/client/Client.ts b/packages/sdk/src/api/resources/settings/resources/mcpServers/client/Client.tsindex 4b52208c6..6e34def90 100644--- a/packages/sdk/src/api/resources/settings/resources/mcpServers/client/Client.ts+++ b/packages/sdk/src/api/resources/settings/resources/mcpServers/client/Client.ts@@ -244,7 +244,7 @@ export class McpServersClient {}/**- * For servers without auth returns not_required, and for header credentials returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional redirect_url is stored for a future FE landing redirect (callback currently returns JSON only).+ * For servers without auth returns not_required, and for header credentials returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional redirect_url is where the OAuth callback then redirects the browser; without it the callback returns JSON.** @param {string} name - Configured MCP server name.* @param {TrueHarness.settings.AuthorizeMcpServersRequest} requestdiff --git a/packages/sdk/src/api/resources/settings/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.ts b/packages/sdk/src/api/resources/settings/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.tsindex 417ced069..dae9b1e8b 100644--- a/packages/sdk/src/api/resources/settings/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.ts+++ b/packages/sdk/src/api/resources/settings/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.ts@@ -5,6 +5,6 @@* {}*/export interface AuthorizeMcpServersRequest {- /** Optional FE landing URL after OAuth (stored on pending auth; callback does not redirect yet). */+ /** Optional FE landing URL the OAuth callback redirects to, with `isSuccess`/`reason` appended. */redirectUrl?: string;}diff --git a/packages/server/src/apis/mcpOAuth.ts b/packages/server/src/apis/mcpOAuth.tsindex 13798abf1..a053422f3 100644--- a/packages/server/src/apis/mcpOAuth.ts+++ b/packages/server/src/apis/mcpOAuth.ts@@ -5,6 +5,7 @@ import {McpConnectionError,type IOAuthClientStore,type IOAuthTokenStore,+ type OAuthPendingAuthorization,} from '@truefoundry/utils-core/core';import type { Logger } from 'winston';import { mcpOAuthCallbackRoute } from '../routes/mcpOAuthRoutes';@@ -15,37 +16,84 @@ export interface McpOAuthRouterDeps {logger: Logger;}+type McpOAuthCallbackContext = Parameters<RouteHandler<typeof mcpOAuthCallbackRoute>>[0];++/** Landing URL with the outcome appended to whatever query params it already carries. */+function callbackLandingUrl(params: { redirectUrl: string; isSuccess: boolean; reason?: string }): string {+ const url = new URL(params.redirectUrl);+ url.searchParams.set('isSuccess', String(params.isSuccess));+ if (params.reason) {+ url.searchParams.set('reason', params.reason);+ }+ return url.href;+}++/**+ * JSON is the answer whenever there is no landing URL to return to: authorize was called without+ * `redirect_url`, or the pending row that carried it is gone (TTL expired, already redeemed, unknown+ * `state`) — the OAuth callback URL is never a page we send the user to on purpose.+ */+function callbackSuccess(params: { c: McpOAuthCallbackContext; pending: OAuthPendingAuthorization }) {+ const redirectUrl = params.pending.redirectUrl;+ if (redirectUrl) {+ return params.c.redirect(callbackLandingUrl({ redirectUrl, isSuccess: true }), 302);+ }+ return params.c.json({ success: true as const }, 200);+}++function callbackFailure(params: {+ c: McpOAuthCallbackContext;+ pending: OAuthPendingAuthorization | undefined;+ message: string;+ jsonStatus?: 400 | 500;+}) {+ const redirectUrl = params.pending?.redirectUrl;+ if (redirectUrl) {+ return params.c.redirect(callbackLandingUrl({ redirectUrl, isSuccess: false, reason: params.message }), 302);+ }+ return params.c.json({ error: { message: params.message } }, params.jsonStatus ?? 400);+}+/** Shared OAuth callback (mounted at /api/v1/mcp-servers/oauth). */export function createMcpOAuthRouter(deps: McpOAuthRouterDeps) {const callbackHandler: RouteHandler<typeof mcpOAuthCallbackRoute> = async c => {const { state, code, error, error_description: errorDescription } = c.req.valid('query');+ // Claimed up front: this row carries the FE landing URL every branch below returns to, and+ // claiming it atomically means a duplicate callback loses the race.+ const pending = await deps.tokenStore.consumePendingAuthorization({ state });+ if (!pending) {+ deps.logger.warn('MCP OAuth callback has no pending authorization', { state, error, errorDescription });+ return callbackFailure({ c, pending, message: 'Unknown or expired OAuth state' });+ }+if (error) {deps.logger.warn('MCP OAuth callback returned an error', { state, error, errorDescription });- await deps.tokenStore.consumePendingAuthorization({ state });- return c.json({ error: { message: errorDescription ? `${error}: ${errorDescription}` : error } }, 400);+ return callbackFailure({ c, pending, message: error });}if (!code) {- return c.json({ error: { message: 'OAuth callback is missing both `code` and `error`' } }, 400);+ return callbackFailure({ c, pending, message: 'OAuth callback is missing both `code` and `error`' });}try {await completeMcpAuthorization({tokenStore: deps.tokenStore,mcpServerStore: deps.mcpServerStore,- state,+ pending,code,});- return c.json({ success: true as const }, 200);} catch (err) {+ // Only a known MCP failure is safe to show the user; anything else gets a generic reason.if (err instanceof McpConnectionError) {deps.logger.warn('MCP OAuth callback token exchange failed', extractErrorLogFields(err));- return c.json({ error: { message: err.message } }, 400);+ return callbackFailure({ c, pending, message: err.message });}deps.logger.error('MCP OAuth callback unexpected failure', extractErrorLogFields(err));- return c.json({ error: { message: 'Internal server error' } }, 500);+ return callbackFailure({ c, pending, message: 'Internal server error', jsonStatus: 500 });}++ return callbackSuccess({ c, pending });};const router = new OpenAPIHono();diff --git a/packages/server/src/routes/mcpOAuthRoutes.ts b/packages/server/src/routes/mcpOAuthRoutes.tsindex 007212ca1..cd2d644cd 100644--- a/packages/server/src/routes/mcpOAuthRoutes.ts+++ b/packages/server/src/routes/mcpOAuthRoutes.ts@@ -32,7 +32,11 @@ export const mcpOAuthCallbackRoute = createRoute({responses: {200: {content: { 'application/json': { schema: McpOAuthCallbackSuccessSchema } },- description: 'Token exchanged successfully; no browser redirect.',+ description: 'Token exchanged successfully and no `redirect_url` was given at authorize time.',+ },+ 302: {+ description:+ 'Redirect to the `redirect_url` given at authorize time, with `isSuccess` (and `reason` when it failed) appended to its existing query params.',},400: {content: { 'application/json': { schema: RequestErrorResponseSchema } },diff --git a/packages/server/src/routes/mcpServerRoutes.ts b/packages/server/src/routes/mcpServerRoutes.tsindex 7c2c12e82..203a0e9b3 100644--- a/packages/server/src/routes/mcpServerRoutes.ts+++ b/packages/server/src/routes/mcpServerRoutes.ts@@ -143,7 +143,7 @@ const McpAuthorizeQuerySchema = z.object({redirect_url: z.url().optional()- .describe('Optional FE landing URL after OAuth (stored on pending auth; callback does not redirect yet).'),+ .describe('Optional FE landing URL the OAuth callback redirects to, with `isSuccess`/`reason` appended.'),});export const authorizeConfiguredMcpServerRoute = createRoute({@@ -157,7 +157,7 @@ export const authorizeConfiguredMcpServerRoute = createRoute({'For servers without auth returns not_required, and for header credentials returns authenticated ' +'(no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token ' +'exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. ' +- 'Optional redirect_url is stored for a future FE landing redirect (callback currently returns JSON only).',+ 'Optional redirect_url is where the OAuth callback then redirects the browser; without it the callback returns JSON.',request: {params: McpServerNameParamsSchema,query: McpAuthorizeQuerySchema,diff --git a/packages/server/tests/unit/apis/mcpOAuth.test.ts b/packages/server/tests/unit/apis/mcpOAuth.test.tsindex ec8e6210d..01d768bf3 100644--- a/packages/server/tests/unit/apis/mcpOAuth.test.ts+++ b/packages/server/tests/unit/apis/mcpOAuth.test.ts@@ -100,6 +100,25 @@ describe('MCP OAuth authorize + callback', () => {globalThis.fetch = realFetch;});+ /** Registers a dcr server and authorizes it, returning the pending authorization's `state`. */+ async function pendingState(name: string, redirectUrl?: string): Promise<string> {+ const put = await settingsRouter.request('/', {+ method: 'PUT',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ type: 'remote', name, url: MCP_URL, auth: { type: 'dcr' } }),+ });+ expect(put.status).toBe(200);++ let query = '';+ if (redirectUrl) {+ query = `?redirect_url=${encodeURIComponent(redirectUrl)}`;+ }+ const authorize = await settingsRouter.request(`/${name}/authorize${query}`);+ expect(authorize.status).toBe(200);+ const body = (await authorize.json()) as { authorization_url?: string };+ return new URL(body.authorization_url ?? '').searchParams.get('state') ?? '';+ }+it('authorize runs DCR and returns an authorization URL; callback exchanges the code', async () => {const put = await settingsRouter.request('/', {method: 'PUT',@@ -128,8 +147,8 @@ describe('MCP OAuth authorize + callback', () => {expect(state).toBeTruthy();const callback = await oauthRouter.request(`/callback?state=${encodeURIComponent(state ?? '')}&code=auth-code-1`);- expect(callback.status).toBe(200);- expect(await callback.json()).toEqual({ success: true });+ expect(callback.status).toBe(302);+ expect(callback.headers.get('location')).toBe(`${FE_REDIRECT}?isSuccess=true`);const record = await mcpServerStore.getServer({ tenant_id: 'default', name: 'oauth-mcp' });expect(record).toBeDefined();@@ -144,12 +163,33 @@ describe('MCP OAuth authorize + callback', () => {expect(await reauthorize.json()).toEqual({ status: 'authenticated' });});- it('callback returns 400 for unknown state and IdP error', async () => {+ it('callback returns 400 JSON when the pending row is gone, since its landing URL went with it', async () => {const unknown = await oauthRouter.request('/callback?state=no-such-state&code=x');expect(unknown.status).toBe(400);+ expect(await unknown.json()).toEqual({ error: { message: 'Unknown or expired OAuth state' } });+ // The missing row is the reason reported, even when the IdP also sent an `error`.const denied = await oauthRouter.request('/callback?state=any&error=access_denied&error_description=user%20denied');expect(denied.status).toBe(400);- expect(await denied.json()).toEqual({ error: { message: 'access_denied: user denied' } });+ expect(await denied.json()).toEqual({ error: { message: 'Unknown or expired OAuth state' } });+ });++ it('callback redirects with the failure reason when the IdP denies consent', async () => {+ const landing = 'https://app.example.com/mcp/connected?tab=mcp';+ const state = await pendingState('oauth-mcp-denied', landing);++ const denied = await oauthRouter.request(+ `/callback?state=${encodeURIComponent(state)}&error=access_denied&error_description=user%20denied`,+ );+ expect(denied.status).toBe(302);+ expect(denied.headers.get('location')).toBe(`${landing}&isSuccess=false&reason=access_denied`);+ });++ it('callback returns success JSON when authorize supplied no redirect_url', async () => {+ const state = await pendingState('oauth-mcp-no-redirect');++ const callback = await oauthRouter.request(`/callback?state=${encodeURIComponent(state)}&code=auth-code-1`);+ expect(callback.status).toBe(200);+ expect(await callback.json()).toEqual({ success: true });});});