diff --git a/docs/contributing/architecture/mcp-client-servers.md b/docs/contributing/architecture/mcp-client-servers.md index 376d31e6db..fe1e31d7ca 100644 --- a/docs/contributing/architecture/mcp-client-servers.md +++ b/docs/contributing/architecture/mcp-client-servers.md @@ -33,11 +33,14 @@ the `/mcp` endpoint (where Kody is the server) and complements remote connectors ## OAuth flow 1. `addServer` registers the server with a callback URL of - `/account/mcp-servers/oauth/callback` and starts connecting. + `/account/mcp-servers/oauth/callback` (from + `APP_BASE_URL`, not the request host) and starts connecting. 2. If the server requires OAuth, the SDK performs dynamic client registration and the connection parks in state `authenticating` with an `authUrl`. 3. The user opens `authUrl` in the browser (surfaced in the account UI and by - the `mcp_server_add` / `mcp_server_list` capabilities). + the `mcp_server_add` / `mcp_server_list` capabilities). The authorize link + uses `rel="noopener noreferrer"` so browser Referer does not send Kody's + origin to providers that enforce authorized-origin allowlists on Referer. 4. The provider redirects back to the callback route. The worker authenticates the browser session cookie, forwards the full callback URL to that user's hub DO, and the SDK exchanges the code (matching the `state` parameter to the @@ -46,8 +49,10 @@ the `/mcp` endpoint (where Kody is the server) and complements remote connectors `ready`. If the Agents SDK reports `authSuccess` but the connection stays in `authenticating` (including the stuck case with no stored auth URL after the SDK clears it), the route redirects with `auth=error` and a concrete reason. - Reconnect also recovers that stuck state by invalidating unusable tokens and - requesting a fresh authorization URL. + Origin and redirect-URI rejection messages are enriched with Kody's + `oauthClientOrigin` and `oauthCallbackUrl`. Reconnect also recovers that + stuck state by invalidating unusable tokens and requesting a fresh + authorization URL. 6. The route redirects to `/account/mcp-servers/:serverId?auth=success|error` when the callback resolves to a server (including failures), or `/account/mcp-servers?auth=error` when it does not, for user feedback. Tokens @@ -57,6 +62,10 @@ Because the callback is resolved through the session cookie, the OAuth state is always looked up in the hub belonging to the signed-in user — cross-user callback replay finds no matching state. +Providers that allowlist client origins or redirect URIs must permit the +canonical app origin and the callback path above. See +[Connect remote MCP servers](../../use/mcp-client-servers.md). + ## Capability synthesis and invocation - Registry: `getCapabilityRegistryForContext` loads enabled server refs from D1 diff --git a/docs/use/index.md b/docs/use/index.md index 052cad09e4..ce5e535e1a 100644 --- a/docs/use/index.md +++ b/docs/use/index.md @@ -21,6 +21,8 @@ Read in order for a full tour, or jump to a topic. prompt for people (and agents) deciding whether Kody fits, before any setup - [Connect your agent](./connect-your-agent.md) — add `{origin}/mcp`, complete OAuth, and use the setup prompt +- [Connect remote MCP servers](./mcp-client-servers.md) — add external MCP + servers so Kody can call their tools (`kody.mcp[...]`) - [First steps — what to ask Kody to do](./first-steps.md) - [Search](./search.md) - [Execute and workflows](./execute.md) — includes per-user MCP instruction diff --git a/docs/use/mcp-client-servers.md b/docs/use/mcp-client-servers.md new file mode 100644 index 0000000000..fbfd05a5e0 --- /dev/null +++ b/docs/use/mcp-client-servers.md @@ -0,0 +1,50 @@ +# Connect remote MCP servers to Kody + +Kody can act as an **MCP client**: you add a remote MCP server, and its tools +become callable as `kody.mcp["server-name"].tool_name(...)`. + +This is the inverse of [connecting your agent to Kody](./connect-your-agent.md) +(where Kody is the MCP _server_). + +## Add a server + +1. Open [`/account/mcp-servers`](https://heykody.app/account/mcp-servers), or + ask your agent to use `mcp_server_add` with a short kebab-case `name` and the + server `url` (https required). +2. If the server needs OAuth, Kody returns an authorization link. Open it, sign + in at the provider, and approve access. +3. Confirm with `mcp_server_list` (or refresh the account page). Connected tools + show up in `search` under a `mcp:` domain. + +## OAuth allowlists (common failure) + +When Kody connects, it registers as an OAuth client using: + +- **Client origin:** the deployment's canonical app origin (for hosted Kody, + `https://heykody.app`) +- **Redirect URI:** `{origin}/account/mcp-servers/oauth/callback` + +Many authorization servers (including FusionAuth "authorized origins" / redirect +URI settings, and other providers with similar allowlists) reject the authorize +step unless those values are permitted. + +If authorization fails with a message like `Invalid origin uri https://…` or an +invalid redirect URI error: + +1. In the remote MCP server's identity provider, allow Kody's client origin and + register the exact redirect URI shown on `/account/mcp-servers` (also + returned as `oauthClientOrigin` / `oauthCallbackUrl` from `mcp_server_add` + and `mcp_server_list`). +2. Remove and re-add the server in Kody (or reconnect) so client registration + picks up the allowlisted values. +3. Authorize again. + +Kody itself does not maintain a per-provider allowlist for this flow — the +remote authorization server does. + +Servers that do not use OAuth connect immediately and do not need these steps. + +## Related + +- [Architecture: MCP client servers](../contributing/architecture/mcp-client-servers.md) +- [Troubleshooting](./troubleshooting.md) diff --git a/docs/use/troubleshooting.md b/docs/use/troubleshooting.md index 1d7f7369b2..6375e2ee48 100644 --- a/docs/use/troubleshooting.md +++ b/docs/use/troubleshooting.md @@ -15,6 +15,15 @@ authorization. Open the verification link sent at signup, or sign in and use authorize page. Keep an open `/oauth/authorize` tab so you can continue the same OAuth request after verifying in another tab, then reconnect or approve again. +## Adding a remote MCP server fails with `Invalid origin uri` or redirect URI errors + +That message comes from the **remote** authorization server, not from Kody being +unreachable. Kody registers as an OAuth client from the deployment origin and +redirects to `{origin}/account/mcp-servers/oauth/callback`. Allow those values +in the MCP server's identity provider (authorized origins / redirect URIs), then +remove and re-add the server. See +[Connect remote MCP servers](./mcp-client-servers.md). + ## Search returns no good matches - **Rephrase the query** using domain vocabulary from the search tool’s domain diff --git a/packages/worker/client/routes/account-mcp-servers.tsx b/packages/worker/client/routes/account-mcp-servers.tsx index 75c8b98523..3132b26f16 100644 --- a/packages/worker/client/routes/account-mcp-servers.tsx +++ b/packages/worker/client/routes/account-mcp-servers.tsx @@ -1,6 +1,7 @@ import { type Handle, css } from 'remix/ui' import { on } from '#client/event-mixin.ts' import { navigate, readCurrentRouterHref } from '#client/client-router.tsx' +import { CopyTextButton } from '#client/copy-text-button.tsx' import { createDoubleCheck } from '#client/double-check.ts' import { createListDetailRoute } from '#client/list-detail-route.ts' import { createRouteLoadLatch } from '#client/route-load-latch.ts' @@ -68,6 +69,8 @@ type AccountMcpServersPayload = { ok: true email: string username: string + oauthClientOrigin: string + oauthCallbackUrl: string servers: Array selectedServerId?: string } @@ -184,6 +187,8 @@ export function AccountMcpServersRoute(handle: Handle) { let status: AccountStatus = 'loading' let actionState: 'idle' | 'busy' = 'idle' let servers: Array = [] + let oauthClientOrigin = '' + let oauthCallbackUrl = '' let addName = '' let addUrl = '' let message: string | null = null @@ -226,6 +231,8 @@ export function AccountMcpServersRoute(handle: Handle) { function applyPayload(payload: AccountMcpServersPayload) { servers = payload.servers + oauthClientOrigin = payload.oauthClientOrigin + oauthCallbackUrl = payload.oauthCallbackUrl deleteServerCheck.reset() } @@ -426,6 +433,51 @@ export function AccountMcpServersRoute(handle: Handle) { } /> + {oauthCallbackUrl ? ( +
+
+ OAuth redirect URI +

+ If a remote MCP server's identity provider allowlists + client origins or redirect URIs (for example FusionAuth), add + {oauthClientOrigin ? ` ${oauthClientOrigin} and` : ''} this + exact callback before authorizing. +

+
+ + {oauthCallbackUrl} + +
+ +
+
+ ) : null} + {status === 'loading' ? (

Loading MCP servers... @@ -662,6 +714,7 @@ export function AccountMcpServersRoute(handle: Handle) {

> @@ -13,8 +16,13 @@ type AuthenticatedUser = NonNullable< export async function loadAccountMcpServersData(input: { env: Env user: AuthenticatedUser + requestUrl?: string | URL | null }): Promise { const userId = input.user.mcpUser.userId + const oauth = resolveMcpServerOAuthClientUrls({ + env: input.env, + requestUrl: input.requestUrl, + }) const settings = await listMcpServerSettings({ env: input.env, userId }) const snapshot = settings.length > 0 @@ -24,12 +32,16 @@ export async function loadAccountMcpServersData(input: { ok: true, email: input.user.email, username: input.user.username, + oauthClientOrigin: oauth.clientOrigin, + oauthCallbackUrl: oauth.callbackUrl, servers: settings.map((setting) => buildMcpServerStatusView({ setting, snapshot: snapshot?.servers.find((server) => server.serverId === setting.id) ?? null, + oauthCallbackUrl: oauth.callbackUrl, + oauthClientOrigin: oauth.clientOrigin, }), ), } diff --git a/packages/worker/src/app/handlers/account-mcp-servers.node.test.ts b/packages/worker/src/app/handlers/account-mcp-servers.node.test.ts index 540dc565f0..4f7dfefd99 100644 --- a/packages/worker/src/app/handlers/account-mcp-servers.node.test.ts +++ b/packages/worker/src/app/handlers/account-mcp-servers.node.test.ts @@ -117,6 +117,19 @@ vi.mock('#worker/mcp-client/settings-service.ts', () => ({ mockModule.setMcpServerEnabled(...args), deleteMcpServer: (...args: Array) => mockModule.deleteMcpServer(...args), + resolveMcpServerOAuthClientUrls: (input: { + env: { APP_BASE_URL?: string | null } + requestUrl?: string | URL | null + }) => { + const configured = input.env.APP_BASE_URL?.trim() + const clientOrigin = configured + ? new URL(configured).origin + : new URL(String(input.requestUrl ?? 'https://heykody.app')).origin + return { + clientOrigin, + callbackUrl: `${clientOrigin}/account/mcp-servers/oauth/callback`, + } + }, })) vi.mock('#worker/mcp-client/hub-client.ts', () => ({ @@ -153,6 +166,8 @@ test('MCP servers API lists servers with live hub status', async () => { ok: true, email: 'user@example.com', username: 'test-user', + oauthClientOrigin: 'https://example.com', + oauthCallbackUrl: 'https://example.com/account/mcp-servers/oauth/callback', servers: [ { id: 'server-1', @@ -172,7 +187,7 @@ test('MCP servers API lists servers with live hub status', async () => { }) }) -test('MCP servers API add action forwards the request-derived callback origin', async () => { +test('MCP servers API add action uses the canonical OAuth callback origin', async () => { const handler = createAccountMcpServersApiHandler(createEnv()) const addResponse = await handler.handler({ @@ -279,6 +294,30 @@ test('MCP servers OAuth callback redirects with the auth outcome', async () => { expect(failureLocation.searchParams.get('auth')).toBe('error') expect(failureLocation.searchParams.get('reason')).toBe('Invalid state.') + mockModule.handleOAuthCallback.mockResolvedValueOnce({ + serverId: 'server-1', + authSuccess: false, + authError: 'Invalid origin uri https://example.com', + serverName: 'linear', + }) + const originFailureResponse = await handler.handler({ + request: new Request( + 'https://example.com/account/mcp-servers/oauth/callback?error=invalid_origin', + ), + params: {}, + } as never) + expect(originFailureResponse.status).toBe(303) + const originFailureLocation = new URL( + originFailureResponse.headers.get('Location') ?? '', + ) + expect(originFailureLocation.searchParams.get('auth')).toBe('error') + expect(originFailureLocation.searchParams.get('reason')).toContain( + 'Invalid origin uri https://example.com', + ) + expect(originFailureLocation.searchParams.get('reason')).toContain( + '/account/mcp-servers/oauth/callback', + ) + mockModule.handleOAuthCallback.mockResolvedValueOnce({ serverId: 'server-1', authSuccess: false, diff --git a/packages/worker/src/app/handlers/account-mcp-servers.ts b/packages/worker/src/app/handlers/account-mcp-servers.ts index 334465523b..7879364984 100644 --- a/packages/worker/src/app/handlers/account-mcp-servers.ts +++ b/packages/worker/src/app/handlers/account-mcp-servers.ts @@ -7,12 +7,13 @@ import { requireAuthenticatedPageUser } from '#app/page-auth.ts' import { readTrimmedStringOrEmpty } from '#app/request-body.ts' import { renderAppPage } from '#app/ssr-render.tsx' import { type routes } from '#universal/routes.ts' -import { getAppBaseUrl } from '#worker/app-base-url.ts' import { createMcpClientHubClient } from '#worker/mcp-client/hub-client.ts' +import { enrichMcpOAuthProviderError } from '#worker/mcp-client/oauth-provider-error.ts' import { addMcpServer, deleteMcpServer, getMcpServerSettingById, + resolveMcpServerOAuthClientUrls, setMcpServerEnabled, } from '#worker/mcp-client/settings-service.ts' @@ -29,7 +30,11 @@ export function createAccountMcpServersHandler(env: Env) { return user } - const accountMcpServers = await loadAccountMcpServersData({ env, user }) + const accountMcpServers = await loadAccountMcpServersData({ + env, + user, + requestUrl: request.url, + }) return renderAppPage({ request, env, @@ -54,7 +59,13 @@ export function createAccountMcpServersApiHandler(env: Env) { } if (request.method === 'GET') { - return jsonResponse(await loadAccountMcpServersData({ env, user })) + return jsonResponse( + await loadAccountMcpServersData({ + env, + user, + requestUrl: request.url, + }), + ) } if (request.method !== 'POST') { @@ -76,6 +87,7 @@ export function createAccountMcpServersApiHandler(env: Env) { env, user, body, + request, kind: 'reconnect', }) } @@ -84,14 +96,15 @@ export function createAccountMcpServersApiHandler(env: Env) { env, user, body, + request, kind: 'refresh', }) } if (action === 'set-enabled') { - return await handleSetEnabledAction({ env, user, body }) + return await handleSetEnabledAction({ env, user, body, request }) } if (action === 'delete') { - return await handleDeleteAction({ env, user, body }) + return await handleDeleteAction({ env, user, body, request }) } } catch (error) { return jsonResponse( @@ -143,6 +156,14 @@ export function createAccountMcpServersOauthCallbackHandler(env: Env) { authError = getErrorMessage(error) } + const oauth = resolveMcpServerOAuthClientUrls({ + env, + requestUrl: request.url, + }) + if (authError) { + authError = enrichMcpOAuthProviderError(authError, oauth) + } + const target = serverId ? new URL( `/account/mcp-servers/${encodeURIComponent(serverId)}`, @@ -169,19 +190,21 @@ async function handleAddAction(input: { body: object request: Request }) { + const oauth = resolveMcpServerOAuthClientUrls({ + env: input.env, + requestUrl: input.request.url, + }) const { setting } = await addMcpServer({ env: input.env, userId: input.user.mcpUser.userId, name: readTrimmedStringOrEmpty(input.body, 'name'), url: readTrimmedStringOrEmpty(input.body, 'url'), - baseUrl: getAppBaseUrl({ - env: input.env, - requestUrl: input.request.url, - }), + baseUrl: oauth.clientOrigin, }) const payload = await loadAccountMcpServersData({ env: input.env, user: input.user, + requestUrl: input.request.url, }) return jsonResponse({ ...payload, @@ -193,6 +216,7 @@ async function handleConnectionAction(input: { env: Env user: AuthenticatedUser body: object + request: Request kind: 'reconnect' | 'refresh' }) { const setting = await requireSetting(input) @@ -208,6 +232,7 @@ async function handleConnectionAction(input: { const payload = await loadAccountMcpServersData({ env: input.env, user: input.user, + requestUrl: input.request.url, }) return jsonResponse({ ...payload, @@ -219,6 +244,7 @@ async function handleSetEnabledAction(input: { env: Env user: AuthenticatedUser body: object + request: Request }) { const setting = await requireSetting(input) const updated = await setMcpServerEnabled({ @@ -230,6 +256,7 @@ async function handleSetEnabledAction(input: { const payload = await loadAccountMcpServersData({ env: input.env, user: input.user, + requestUrl: input.request.url, }) return jsonResponse({ ...payload, @@ -241,6 +268,7 @@ async function handleDeleteAction(input: { env: Env user: AuthenticatedUser body: object + request: Request }) { const setting = await requireSetting(input) const deleted = await deleteMcpServer({ @@ -255,6 +283,7 @@ async function handleDeleteAction(input: { await loadAccountMcpServersData({ env: input.env, user: input.user, + requestUrl: input.request.url, }), ) } diff --git a/packages/worker/src/mcp-client/oauth-provider-error.node.test.ts b/packages/worker/src/mcp-client/oauth-provider-error.node.test.ts new file mode 100644 index 0000000000..22d2a5de48 --- /dev/null +++ b/packages/worker/src/mcp-client/oauth-provider-error.node.test.ts @@ -0,0 +1,33 @@ +import { expect, test } from 'vitest' +import { enrichMcpOAuthProviderError } from './oauth-provider-error.ts' + +const callback = { + callbackUrl: 'https://heykody.app/account/mcp-servers/oauth/callback', + clientOrigin: 'https://heykody.app', +} + +test('enrichMcpOAuthProviderError explains FusionAuth-style origin rejection', () => { + const enriched = enrichMcpOAuthProviderError( + 'Invalid origin uri https://heykody.app', + callback, + ) + expect(enriched).toContain('Invalid origin uri https://heykody.app') + expect(enriched).toContain('https://heykody.app') + expect(enriched).toContain(callback.callbackUrl) + expect(enriched).toContain('operate this MCP server') +}) + +test('enrichMcpOAuthProviderError explains redirect URI rejection', () => { + const enriched = enrichMcpOAuthProviderError( + 'invalid_redirect_uri: redirect_uri mismatch', + callback, + ) + expect(enriched).toContain(callback.callbackUrl) +}) + +test('enrichMcpOAuthProviderError leaves unrelated errors unchanged', () => { + expect(enrichMcpOAuthProviderError('Invalid state format', callback)).toBe( + 'Invalid state format', + ) + expect(enrichMcpOAuthProviderError(' ', callback)).toBe('') +}) diff --git a/packages/worker/src/mcp-client/oauth-provider-error.ts b/packages/worker/src/mcp-client/oauth-provider-error.ts new file mode 100644 index 0000000000..68bfc32485 --- /dev/null +++ b/packages/worker/src/mcp-client/oauth-provider-error.ts @@ -0,0 +1,40 @@ +/** + * Turn opaque third-party OAuth/AS errors into actionable guidance when Kody + * is the MCP *client* (user-added servers). + * + * Providers such as FusionAuth reject authorize requests whose browser + * Origin/Referer is not on an authorized-origins allowlist, producing messages + * like `Invalid origin uri https://heykody.app`. Redirect-URI mismatches are a + * related class. Both are configured on the remote authorization server, not + * in Kody. + */ +export function enrichMcpOAuthProviderError( + message: string, + input: { callbackUrl: string; clientOrigin: string }, +): string { + const trimmed = message.trim() + if (!trimmed) return trimmed + + const lower = trimmed.toLowerCase() + const looksLikeOriginRejection = + lower.includes('invalid origin') || + lower.includes('unauthorized origin') || + lower.includes('origin uri') || + lower.includes('authorized origin') + const looksLikeRedirectRejection = + lower.includes('invalid redirect') || + lower.includes('redirect_uri') || + lower.includes('redirect uri') + + if (!looksLikeOriginRejection && !looksLikeRedirectRejection) { + return trimmed + } + + const parts = [ + trimmed, + `Kody authorizes as an OAuth client from ${input.clientOrigin}.`, + `If you operate this MCP server (or its identity provider), allow that origin and register this exact redirect URI: ${input.callbackUrl}.`, + 'Then remove and re-add the server in Kody (or reconnect) so registration uses the allowlisted values.', + ] + return parts.join(' ') +} diff --git a/packages/worker/src/mcp-client/settings-service.node.test.ts b/packages/worker/src/mcp-client/settings-service.node.test.ts index ff685c01ac..2639ae2fcf 100644 --- a/packages/worker/src/mcp-client/settings-service.node.test.ts +++ b/packages/worker/src/mcp-client/settings-service.node.test.ts @@ -39,6 +39,7 @@ const { clearEnabledMcpServerRefsCacheForTests, enabledMcpServerRefsCacheTtlMs, listEnabledMcpServerRefsCached, + resolveMcpServerOAuthClientUrls, setMcpServerEnabled, } = await import('./settings-service.ts') @@ -100,3 +101,25 @@ test('listEnabledMcpServerRefsCached warms per user, expires, and invalidates on expect(afterDisable).toEqual([]) expect(mockModule.listEnabledMcpServerSettingRows).toHaveBeenCalledTimes(4) }) + +test('resolveMcpServerOAuthClientUrls prefers APP_BASE_URL over the request host', () => { + expect( + resolveMcpServerOAuthClientUrls({ + env: { APP_BASE_URL: 'https://heykody.app/' }, + requestUrl: 'https://heykody.dev/account/mcp-servers', + }), + ).toEqual({ + clientOrigin: 'https://heykody.app', + callbackUrl: 'https://heykody.app/account/mcp-servers/oauth/callback', + }) + + expect( + resolveMcpServerOAuthClientUrls({ + env: {}, + requestUrl: 'https://preview.example/account/mcp-servers', + }), + ).toEqual({ + clientOrigin: 'https://preview.example', + callbackUrl: 'https://preview.example/account/mcp-servers/oauth/callback', + }) +}) diff --git a/packages/worker/src/mcp-client/settings-service.ts b/packages/worker/src/mcp-client/settings-service.ts index 6052a99b5e..3cdb03698b 100644 --- a/packages/worker/src/mcp-client/settings-service.ts +++ b/packages/worker/src/mcp-client/settings-service.ts @@ -5,6 +5,7 @@ import { validateMcpServerUrl, type McpServerRef, } from '@kody-internal/shared/mcp-servers.ts' +import { getCanonicalAppBaseUrl } from '#worker/app-base-url.ts' import { PromiseLruCache } from '#worker/package-registry/published-package-cache.ts' import { createMcpClientHubClient } from './hub-client.ts' import { @@ -29,6 +30,27 @@ export function buildMcpServerOAuthCallbackUrl(baseUrl: string) { return `${origin}${mcpServerOAuthCallbackPath}` } +/** + * Stable OAuth client origin + callback for user-added MCP servers. + * + * Prefer the configured canonical `APP_BASE_URL` (not the request host) so + * dynamic client registration always advertises one allowlistable redirect URI + * during dual-host domain migrations. + */ +export function resolveMcpServerOAuthClientUrls(input: { + env: { APP_BASE_URL?: string | null; PACKAGE_APP_BASE_URL?: string | null } + requestUrl?: string | URL | null +}) { + const clientOrigin = getCanonicalAppBaseUrl({ + env: input.env, + requestUrl: input.requestUrl, + }) + return { + clientOrigin, + callbackUrl: buildMcpServerOAuthCallbackUrl(clientOrigin), + } +} + function toMetadata(row: McpServerSettingRow): McpServerSettingMetadata { return { id: row.id, diff --git a/packages/worker/src/mcp/capabilities/mcp-servers/mcp-server-add.ts b/packages/worker/src/mcp/capabilities/mcp-servers/mcp-server-add.ts index 383802f6a6..65e0aa3812 100644 --- a/packages/worker/src/mcp/capabilities/mcp-servers/mcp-server-add.ts +++ b/packages/worker/src/mcp/capabilities/mcp-servers/mcp-server-add.ts @@ -3,8 +3,11 @@ import { defineDomainCapability } from '#mcp/capabilities/define-domain-capabili import { capabilityDomainNames } from '#mcp/capabilities/domain-metadata.ts' import { requireMcpUser } from '#mcp/capabilities/meta/require-user.ts' import { type CapabilityContext } from '#mcp/capabilities/types.ts' -import { addMcpServer } from '#worker/mcp-client/settings-service.ts' -import { getAppBaseUrl } from '#worker/app-base-url.ts' +import { enrichMcpOAuthProviderError } from '#worker/mcp-client/oauth-provider-error.ts' +import { + addMcpServer, + resolveMcpServerOAuthClientUrls, +} from '#worker/mcp-client/settings-service.ts' const outputSchema = z.object({ id: z.string(), @@ -14,6 +17,8 @@ const outputSchema = z.object({ toolCount: z.number().int().nonnegative(), authUrl: z.string().nullable(), error: z.string().nullable(), + oauthClientOrigin: z.string(), + oauthCallbackUrl: z.string(), nextStep: z.string(), }) @@ -22,7 +27,7 @@ export const mcpServerAddCapability = defineDomainCapability( { name: 'mcp_server_add', description: - 'Add a remote MCP server for the signed-in user and connect to it. Servers that require OAuth return an authUrl the user must open to authorize Kody; other servers connect immediately. Connected server tools become kody.mcp["server-name"].tool_name(...) capabilities.', + 'Add a remote MCP server for the signed-in user and connect to it. Servers that require OAuth return an authUrl the user must open to authorize Kody; other servers connect immediately. Connected server tools become kody.mcp["server-name"].tool_name(...) capabilities. When OAuth fails with origin or redirect URI errors, the remote authorization server must allow Kody\'s oauthClientOrigin and oauthCallbackUrl.', keywords: [ 'mcp', 'server', @@ -54,21 +59,28 @@ export const mcpServerAddCapability = defineDomainCapability( outputSchema, async handler(args: { name: string; url: string }, ctx: CapabilityContext) { const user = requireMcpUser(ctx.callerContext) - const baseUrl = - ctx.callerContext.baseUrl || getAppBaseUrl({ env: ctx.env }) + const oauth = resolveMcpServerOAuthClientUrls({ + env: ctx.env, + requestUrl: ctx.callerContext.baseUrl, + }) const { setting, connection } = await addMcpServer({ env: ctx.env, userId: user.userId, name: args.name, url: args.url, - baseUrl, + baseUrl: oauth.clientOrigin, }) + const error = connection.error + ? enrichMcpOAuthProviderError(connection.error, oauth) + : null const nextStep = connection.state === 'authenticating' && connection.authUrl - ? `The server requires OAuth authorization. Ask the user to open ${connection.authUrl} (also available from ${baseUrl}/account/mcp-servers) to authorize Kody, then check mcp_server_list.` + ? `The server requires OAuth authorization. Ask the user to open ${connection.authUrl} (also available from ${oauth.clientOrigin}/account/mcp-servers) to authorize Kody. If the provider rejects Kody's origin or redirect URI, they must allow ${oauth.clientOrigin} and ${oauth.callbackUrl}, then remove and re-add the server. After authorizing, check mcp_server_list.` : connection.state === 'ready' ? `Connected with ${connection.toolCount} tool(s). Use search or meta_list_capabilities to discover kody.mcp["${setting.name}"] capabilities.` - : `Connection state is "${connection.state}". Check mcp_server_list and use mcp_server_reconnect if it does not become ready.` + : error + ? `Connection state is "${connection.state}": ${error}` + : `Connection state is "${connection.state}". Check mcp_server_list and use mcp_server_reconnect if it does not become ready.` return { id: setting.id, name: setting.name, @@ -76,7 +88,9 @@ export const mcpServerAddCapability = defineDomainCapability( state: connection.state, toolCount: connection.toolCount, authUrl: connection.authUrl, - error: connection.error, + error, + oauthClientOrigin: oauth.clientOrigin, + oauthCallbackUrl: oauth.callbackUrl, nextStep, } }, diff --git a/packages/worker/src/mcp/capabilities/mcp-servers/mcp-server-list.ts b/packages/worker/src/mcp/capabilities/mcp-servers/mcp-server-list.ts index 58ed9c7589..46c6754f7c 100644 --- a/packages/worker/src/mcp/capabilities/mcp-servers/mcp-server-list.ts +++ b/packages/worker/src/mcp/capabilities/mcp-servers/mcp-server-list.ts @@ -6,7 +6,10 @@ import { emptyCapabilityInputSchema, type CapabilityContext, } from '#mcp/capabilities/types.ts' -import { listMcpServerSettings } from '#worker/mcp-client/settings-service.ts' +import { + listMcpServerSettings, + resolveMcpServerOAuthClientUrls, +} from '#worker/mcp-client/settings-service.ts' import { buildMcpServerStatusView, loadMcpClientHubSnapshotOrNull, @@ -14,6 +17,8 @@ import { } from './shared.ts' const outputSchema = z.object({ + oauthClientOrigin: z.string(), + oauthCallbackUrl: z.string(), servers: z.array(mcpServerStatusSchema), }) @@ -39,11 +44,17 @@ export const mcpServerListCapability = defineDomainCapability( outputSchema, async handler(_args, ctx: CapabilityContext) { const user = requireMcpUser(ctx.callerContext) + const oauth = resolveMcpServerOAuthClientUrls({ + env: ctx.env, + requestUrl: ctx.callerContext.baseUrl, + }) const [settings, hubSnapshot] = await Promise.all([ listMcpServerSettings({ env: ctx.env, userId: user.userId }), loadMcpClientHubSnapshotOrNull({ env: ctx.env, userId: user.userId }), ]) return { + oauthClientOrigin: oauth.clientOrigin, + oauthCallbackUrl: oauth.callbackUrl, servers: settings.map((setting) => buildMcpServerStatusView({ setting, @@ -51,6 +62,8 @@ export const mcpServerListCapability = defineDomainCapability( hubSnapshot?.servers.find( (server) => server.serverId === setting.id, ) ?? null, + oauthCallbackUrl: oauth.callbackUrl, + oauthClientOrigin: oauth.clientOrigin, }), ), } diff --git a/packages/worker/src/mcp/capabilities/mcp-servers/mcp-server-reconnect.ts b/packages/worker/src/mcp/capabilities/mcp-servers/mcp-server-reconnect.ts index 5122284dd4..ea4a6ab05a 100644 --- a/packages/worker/src/mcp/capabilities/mcp-servers/mcp-server-reconnect.ts +++ b/packages/worker/src/mcp/capabilities/mcp-servers/mcp-server-reconnect.ts @@ -4,6 +4,8 @@ import { capabilityDomainNames } from '#mcp/capabilities/domain-metadata.ts' import { requireMcpUser } from '#mcp/capabilities/meta/require-user.ts' import { type CapabilityContext } from '#mcp/capabilities/types.ts' import { createMcpClientHubClient } from '#worker/mcp-client/hub-client.ts' +import { enrichMcpOAuthProviderError } from '#worker/mcp-client/oauth-provider-error.ts' +import { resolveMcpServerOAuthClientUrls } from '#worker/mcp-client/settings-service.ts' import { resolveMcpServerSetting } from './shared.ts' const outputSchema = z.object({ @@ -13,6 +15,8 @@ const outputSchema = z.object({ toolCount: z.number().int().nonnegative(), authUrl: z.string().nullable(), error: z.string().nullable(), + oauthClientOrigin: z.string(), + oauthCallbackUrl: z.string(), }) export const mcpServerReconnectCapability = defineDomainCapability( @@ -36,6 +40,10 @@ export const mcpServerReconnectCapability = defineDomainCapability( userId: user.userId, server: args.server, }) + const oauth = resolveMcpServerOAuthClientUrls({ + env: ctx.env, + requestUrl: ctx.callerContext.baseUrl, + }) const hub = createMcpClientHubClient({ env: ctx.env, userId: user.userId, @@ -47,7 +55,11 @@ export const mcpServerReconnectCapability = defineDomainCapability( state: result.state, toolCount: result.toolCount, authUrl: result.authUrl, - error: result.error, + error: result.error + ? enrichMcpOAuthProviderError(result.error, oauth) + : null, + oauthClientOrigin: oauth.clientOrigin, + oauthCallbackUrl: oauth.callbackUrl, } }, }, diff --git a/packages/worker/src/mcp/capabilities/mcp-servers/shared.ts b/packages/worker/src/mcp/capabilities/mcp-servers/shared.ts index ae52ff81ea..fc50d3bea3 100644 --- a/packages/worker/src/mcp/capabilities/mcp-servers/shared.ts +++ b/packages/worker/src/mcp/capabilities/mcp-servers/shared.ts @@ -2,6 +2,7 @@ import { z } from 'zod' import { normalizeMcpServerName } from '@kody-internal/shared/mcp-servers.ts' import { McpCallerError } from '#mcp/caller-error.ts' import { getCachedMcpClientHubSnapshot } from '#worker/mcp-client/hub-client.ts' +import { enrichMcpOAuthProviderError } from '#worker/mcp-client/oauth-provider-error.ts' import { getMcpServerSettingById, listMcpServerSettings, @@ -29,9 +30,19 @@ export type McpServerStatusView = z.infer export function buildMcpServerStatusView(input: { setting: McpServerSettingMetadata snapshot: McpServerSnapshot | null + oauthCallbackUrl?: string + oauthClientOrigin?: string }): McpServerStatusView { const { setting, snapshot } = input const connected = snapshot?.state === 'ready' + const rawError = snapshot?.error ?? null + const error = + rawError && input.oauthCallbackUrl && input.oauthClientOrigin + ? enrichMcpOAuthProviderError(rawError, { + callbackUrl: input.oauthCallbackUrl, + clientOrigin: input.oauthClientOrigin, + }) + : rawError return { id: setting.id, name: setting.name, @@ -41,7 +52,7 @@ export function buildMcpServerStatusView(input: { connected, toolCount: connected ? (snapshot?.tools.length ?? 0) : 0, authUrl: snapshot?.authUrl ?? null, - error: snapshot?.error ?? null, + error, tools: connected ? (snapshot?.tools.map((tool) => tool.name) ?? []) : [], createdAt: setting.createdAt, updatedAt: setting.updatedAt, diff --git a/packages/worker/universal/loader-data.ts b/packages/worker/universal/loader-data.ts index f4db12aa95..b9db58ff12 100644 --- a/packages/worker/universal/loader-data.ts +++ b/packages/worker/universal/loader-data.ts @@ -822,6 +822,10 @@ export type AccountMcpServersLoaderData = { ok: true email: string username: string + /** Canonical origin Kody registers as the OAuth client_uri. */ + oauthClientOrigin: string + /** Exact redirect URI remote authorization servers must allow. */ + oauthCallbackUrl: string servers: Array }