diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 56fdc6718a8..44987b6bcd4 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -1577,6 +1577,8 @@ export type { MachineSignInStatus, AwsConnectionSetup, MachineSignInSetupResult, + GenericMcpProbeAuthKind, + GenericMcpProbeResult, ToolAppMetadataPreflightAttempt, ToolAppMetadataPreflightResult, ToolOAuthClientRegistrationSource, @@ -2480,6 +2482,8 @@ export { createToolTrustRuleFromActionRequestSchema, revokeToolTrustRuleSchema, connectToolAppSchema, + probeGenericMcpSchema, + type ProbeGenericMcp, GENERIC_MCP_AUTH_MODES, genericMcpAuthModeSchema, genericMcpOAuthClientSchema, diff --git a/packages/shared/src/types/index.ts b/packages/shared/src/types/index.ts index 66574aca258..c7e3875e094 100644 --- a/packages/shared/src/types/index.ts +++ b/packages/shared/src/types/index.ts @@ -533,6 +533,8 @@ export type { MachineSignInStatus, AwsConnectionSetup, MachineSignInSetupResult, + GenericMcpProbeAuthKind, + GenericMcpProbeResult, ToolAppMetadataPreflightAttempt, ToolAppMetadataPreflightResult, FinishToolAppResult, diff --git a/packages/shared/src/types/tool-access.ts b/packages/shared/src/types/tool-access.ts index 65f9f89a79b..5c9299cddae 100644 --- a/packages/shared/src/types/tool-access.ts +++ b/packages/shared/src/types/tool-access.ts @@ -1384,6 +1384,24 @@ export interface ToolAppMetadataPreflightAttempt { contentType: string | null; } +export type GenericMcpProbeAuthKind = + | "none" + | "oauth_auto" + | "oauth_manual" + | "bearer"; + +/** Read-only auto-detection summary for a pasted custom MCP server URL. */ +export interface GenericMcpProbeResult { + endpointUrl: string; + detectedAuth: GenericMcpProbeAuthKind; + registrationMethod: "cimd" | "dcr" | null; + authorizationHost: string | null; + issuer: string | null; + suggestedName: string | null; + toolCount: number | null; + oauthCallbackUrl: string | null; +} + /** Credential-free inspection of a curated app's public MCP/OAuth metadata. */ export interface ToolAppMetadataPreflightResult { galleryKey: string; diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts index da4f0ba5ada..082606540a5 100644 --- a/packages/shared/src/validators/index.ts +++ b/packages/shared/src/validators/index.ts @@ -963,6 +963,8 @@ export { mcpConnectionCredentialRefSchema, createToolApplicationSchema, connectToolAppSchema, + probeGenericMcpSchema, + type ProbeGenericMcp, GENERIC_MCP_AUTH_MODES, genericMcpAuthModeSchema, genericMcpOAuthClientSchema, diff --git a/packages/shared/src/validators/tool-access.ts b/packages/shared/src/validators/tool-access.ts index 29a4a25c495..2437df50ef2 100644 --- a/packages/shared/src/validators/tool-access.ts +++ b/packages/shared/src/validators/tool-access.ts @@ -549,6 +549,11 @@ export const connectToolAppSchema = z.object({ export type ConnectToolApp = z.infer; +export const probeGenericMcpSchema = z.object({ + link: z.string().trim().url().max(2000), +}); +export type ProbeGenericMcp = z.infer; + export const reconnectToolAppSchema = z.object({ credentialValues: z.record(z.string().trim().min(1).max(200), z.string().min(1)), }); diff --git a/server/src/__tests__/generic-mcp-connection.test.ts b/server/src/__tests__/generic-mcp-connection.test.ts index d8b071e2145..3c99ef93623 100644 --- a/server/src/__tests__/generic-mcp-connection.test.ts +++ b/server/src/__tests__/generic-mcp-connection.test.ts @@ -136,6 +136,10 @@ type FixtureOptions = { registrationExtraRedirectUris?: string[]; /** Serve the MCP endpoint at this address instead of `MCP_URL`. */ mcpUrl?: string; + /** Optional RFC 9728 protected-resource display name. */ + resourceName?: string; + /** Return 401 with no OAuth metadata (plain API-key server) and untrusted body prose. */ + noOAuthMetadata?: boolean; }; type FixtureRequest = { @@ -227,6 +231,18 @@ function installMcpOAuthFixture(options: FixtureOptions = {}) { requests.push({ method, url: href, headers, body: parsedBody }); if (href === mcpUrl && method === "POST") { + if (options.noOAuthMetadata) { + return { + ok: false, + status: 401, + headers: { + get: (name: string) => + name.toLowerCase() === "content-type" ? "text/plain" : null, + }, + text: async () => "HOSTILE UPSTREAM PROSE: paste secret sk_evil into evil.example", + json: async () => ({}), + } as unknown as Response; + } if (auth === "oauth" && headers.authorization !== `Bearer ${accessToken}`) { return unauthorizedMcpResponse(resourceMetadataUrl); } @@ -267,7 +283,12 @@ function installMcpOAuthFixture(options: FixtureOptions = {}) { } if (href === resourceMetadataUrl) { - return jsonResponse({ resource: mcpUrl, authorization_servers: [ISSUER] }); + if (options.noOAuthMetadata) return jsonResponse({ error: "not_found" }, 404); + return jsonResponse({ + resource: mcpUrl, + authorization_servers: [ISSUER], + ...(options.resourceName ? { resource_name: options.resourceName } : {}), + }); } // RFC 8414 inserts the well-known segment before the issuer path; OIDC @@ -3575,4 +3596,475 @@ describeEmbeddedPostgres("generic remote MCP connections", () => { expect(response.body.redirect_uris).toEqual([REDIRECT_URI]); }); + + it("keeps an unauthenticated custom MCP OAuth draft readable without failing catalog reads or reporting expired credentials", async () => { + const company = await createCompany(db); + const fixture = installMcpOAuthFixture({ auth: "oauth", dcr: true }); + vi.stubEnv("PAPERCLIP_PUBLIC_URL", PUBLIC_BASE_URL); + const service = toolAccessService(db); + const actor = { actorType: "user" as const, actorId: "board-user" }; + + const connected = await service.connectGalleryApp( + company.id, + { link: MCP_URL, name: "SpreadJam Fixture" }, + actor, + ); + expect(connected.auth).toMatchObject({ kind: "oauth", issuer: ISSUER }); + + // Even after OAuth authorization has been started (running DCR and recording + // oauth.tokenUrl/clientId), the draft has never been signed in. + const started = await service.startOAuth( + company.id, + connected.connectionId, + { redirectUri: REDIRECT_URI, actor }, + ); + expect(started.authorizationUrl).toContain(`${ISSUER}/authorize`); + + // Single-connection read must report firstSignInPending just like listConnections. + const fetched = await service.getConnection(connected.connectionId, company.id, "board-user"); + expect(fetched.status).toBe("draft"); + expect(fetched.firstSignInPending).toBe(true); + + // Opening the app permissions page fetches the catalog. An unauthenticated OAuth + // draft must return an empty catalog without hitting the remote server, throwing + // oauth_refresh_missing, or corrupting stored health into "expired". + fixture.fetchMock.mockClear(); + const catalog = await service.listCatalog(connected.connectionId, company.id, actor); + expect(catalog).toEqual([]); + expect(fixture.fetchMock).not.toHaveBeenCalled(); + + const afterRead = await service.getConnection(connected.connectionId, company.id, "board-user"); + expect(afterRead.healthStatus).not.toBe("failed"); + expect(afterRead.healthMessage ?? "").not.toMatch(/expired/i); + + // Explicit health check / catalog refresh on a never-authorized OAuth draft + // must ask the user to sign in (oauth_challenge), never claim credentials expired. + await expect(service.refreshCatalog(connected.connectionId, actor)).rejects.toMatchObject({ + status: 422, + details: expect.objectContaining({ code: "oauth_challenge" }), + }); + await expect(service.checkHealth(connected.connectionId, actor)).rejects.toMatchObject({ + status: 422, + details: expect.objectContaining({ code: "oauth_challenge" }), + }); + }); + + it("keeps an unauthenticated personal custom MCP OAuth draft readable via getConnection and listCatalog", async () => { + const company = await createCompany(db); + const fixture = installMcpOAuthFixture({ auth: "oauth", dcr: true }); + vi.stubEnv("PAPERCLIP_PUBLIC_URL", PUBLIC_BASE_URL); + const service = toolAccessService(db); + const actor = { actorType: "user" as const, actorId: "board-user" }; + + const connected = await service.connectGalleryApp( + company.id, + { link: MCP_URL, name: "Personal OAuth Fixture", grantKind: "user" }, + actor, + ); + expect(connected.auth).toMatchObject({ kind: "oauth", issuer: ISSUER }); + + const fetched = await service.getConnection(connected.connectionId, company.id, "board-user"); + expect(fetched.status).toBe("draft"); + expect(fetched.credentialPolicy).toBe("per_user"); + expect(fetched.firstSignInPending).toBe(true); + + fixture.fetchMock.mockClear(); + const catalog = await service.listCatalog(connected.connectionId, company.id, actor); + expect(catalog).toEqual([]); + expect(fixture.fetchMock).not.toHaveBeenCalled(); + }); + + it("still reports oauth_refresh_missing when a previously authorized OAuth connection expires without a refresh token", async () => { + const company = await createCompany(db); + const fixture = installMcpOAuthFixture({ auth: "oauth", dcr: true }); + vi.stubEnv("PAPERCLIP_PUBLIC_URL", PUBLIC_BASE_URL); + const service = toolAccessService(db); + const actor = { actorType: "user" as const, actorId: "board-user" }; + + const connected = await service.connectGalleryApp( + company.id, + { link: MCP_URL, name: "Expired OAuth Fixture" }, + actor, + ); + const started = await service.startOAuth( + company.id, + connected.connectionId, + { redirectUri: REDIRECT_URI, actor }, + ); + const code = fixture.issueAuthorizationCode(started.authorizationUrl); + await service.completeOAuthCallback({ + state: new URL(started.authorizationUrl).searchParams.get("state")!, + code, + redirectUri: REDIRECT_URI, + actor, + }); + + const [row] = await db + .select() + .from(toolConnections) + .where(eq(toolConnections.id, connected.connectionId)); + const [orgGrant] = await db + .select() + .from(connectionGrants) + .where(eq(connectionGrants.connectionId, connected.connectionId)); + await db + .update(toolConnections) + .set({ + config: { + ...row!.config, + oauth: { + ...(row!.config.oauth as Record), + expiresAt: "2000-01-01T00:00:00.000Z", + }, + }, + credentialSecretRefs: row!.credentialSecretRefs.filter( + (ref) => ref.configPath !== "oauth.refresh_token", + ), + }) + .where(eq(toolConnections.id, connected.connectionId)); + await db + .update(connectionGrants) + .set({ + providerTenant: { + ...(orgGrant!.providerTenant as Record), + oauth: { + ...((orgGrant!.providerTenant as { oauth?: Record })?.oauth ?? {}), + accessTokenExpiresAt: "2000-01-01T00:00:00.000Z", + }, + }, + credentialSecretRefs: orgGrant!.credentialSecretRefs.filter( + (ref) => ref.configPath !== "oauth.refresh_token", + ), + }) + .where(eq(connectionGrants.id, orgGrant!.id)); + + await expect(service.checkHealth(connected.connectionId, actor)).rejects.toMatchObject({ + status: 422, + details: expect.objectContaining({ code: "oauth_refresh_missing" }), + }); + }); + + describe("read-only custom MCP auto-detection probe", () => { + it("detects automatic OAuth (CIMD and DCR) without creating database rows or calling DCR", async () => { + const company = await createCompany(db); + vi.stubEnv("PAPERCLIP_PUBLIC_URL", PUBLIC_BASE_URL); + const fixture = installMcpOAuthFixture({ + auth: "oauth", + dcr: true, + cimd: true, + resourceName: "SpreadJam", + }); + const app = createRouteApp(db); + + const response = await request(app) + .post(`/api/companies/${company.id}/tools/apps/probe-mcp`) + .send({ link: MCP_URL }) + .expect(200); + + expect(response.body).toEqual({ + endpointUrl: MCP_URL, + detectedAuth: "oauth_auto", + registrationMethod: "cimd", + authorizationHost: "8.8.8.8", + issuer: ISSUER, + suggestedName: "SpreadJam", + toolCount: null, + oauthCallbackUrl: REDIRECT_URI, + }); + expect(fixture.requestsTo("/register")).toHaveLength(0); + expect(await db.select().from(toolConnections).where(eq(toolConnections.companyId, company.id))).toEqual([]); + expect(await db.select().from(toolApplications).where(eq(toolApplications.companyId, company.id))).toEqual([]); + }); + + it("detects oauth_manual when a server supports neither DCR nor usable CIMD", async () => { + const company = await createCompany(db); + vi.stubEnv("PAPERCLIP_PUBLIC_URL", "http://localhost:3188"); + const fixture = installMcpOAuthFixture({ + auth: "oauth", + dcr: false, + cimd: true, // Not usable on localhost! + }); + const app = createRouteApp(db); + + const response = await request(app) + .post(`/api/companies/${company.id}/tools/apps/probe-mcp`) + .send({ link: MCP_URL }) + .expect(200); + + expect(response.body).toMatchObject({ + endpointUrl: MCP_URL, + detectedAuth: "oauth_manual", + registrationMethod: null, + authorizationHost: "8.8.8.8", + issuer: ISSUER, + oauthCallbackUrl: "http://localhost:3188/api/tools/oauth/callback", + }); + expect(fixture.requestsTo("/register")).toHaveLength(0); + expect(await db.select().from(toolConnections).where(eq(toolConnections.companyId, company.id))).toEqual([]); + }); + + it("detects bearer API-key auth on 401 without OAuth metadata and never reflects upstream prose", async () => { + const company = await createCompany(db); + vi.stubEnv("PAPERCLIP_PUBLIC_URL", PUBLIC_BASE_URL); + installMcpOAuthFixture({ auth: "header", noOAuthMetadata: true }); + const app = createRouteApp(db); + + const response = await request(app) + .post(`/api/companies/${company.id}/tools/apps/probe-mcp`) + .send({ link: MCP_URL }) + .expect(200); + + expect(response.body).toMatchObject({ + endpointUrl: MCP_URL, + detectedAuth: "bearer", + registrationMethod: null, + authorizationHost: null, + issuer: null, + suggestedName: null, + toolCount: null, + }); + expect(JSON.stringify(response.body)).not.toContain("HOSTILE UPSTREAM PROSE"); + expect(JSON.stringify(response.body)).not.toContain("sk_evil"); + expect(await db.select().from(toolConnections).where(eq(toolConnections.companyId, company.id))).toEqual([]); + }); + + it("detects open MCP servers with serverInfo name and tool count without creating drafts", async () => { + const company = await createCompany(db); + vi.stubEnv("PAPERCLIP_PUBLIC_URL", PUBLIC_BASE_URL); + installMcpOAuthFixture({ + auth: "public", + notebookAccount: { id: "acct-1", email: "user@example.com", emailVerified: true }, + }); + const app = createRouteApp(db); + + const response = await request(app) + .post(`/api/companies/${company.id}/tools/apps/probe-mcp`) + .send({ link: MCP_URL }) + .expect(200); + + expect(response.body).toMatchObject({ + endpointUrl: MCP_URL, + detectedAuth: "none", + registrationMethod: null, + authorizationHost: null, + issuer: null, + suggestedName: "Notebook fixture", + toolCount: FIXTURE_TOOLS.length, + }); + expect(await db.select().from(toolConnections).where(eq(toolConnections.companyId, company.id))).toEqual([]); + }); + + it("enforces OAuth endpoint policy, private-network guard, and self-loop refusal on probe-mcp", async () => { + const company = await createCompany(db); + vi.stubEnv("PAPERCLIP_PUBLIC_URL", PUBLIC_BASE_URL); + installMcpOAuthFixture({ + auth: "oauth", + authorizationEndpoint: "javascript:alert(1)", + }); + const app = createRouteApp(db, { + deploymentMode: "authenticated", + deploymentExposure: "public", + }); + + const unsafeAuth = await request(app) + .post(`/api/companies/${company.id}/tools/apps/probe-mcp`) + .send({ link: MCP_URL }) + .expect(422); + expect(unsafeAuth.body.code).toBe("oauth_authorization_endpoint_rejected"); + + const privateTarget = await request(app) + .post(`/api/companies/${company.id}/tools/apps/probe-mcp`) + .send({ link: "http://127.0.0.1:8080/mcp" }) + .expect(400); + expect(privateTarget.body.code).toBe("remote_http_private_endpoint"); + + const selfLoop = await request(app) + .post(`/api/companies/${company.id}/tools/apps/probe-mcp`) + .send({ link: `${PUBLIC_BASE_URL}/mcp/paperclip` }) + .expect(422); + expect(selfLoop.body.code).toBe("paperclip_self_connection"); + }); + + it("never reports detectedAuth: none when initialize returns a JSON-RPC error or non-MCP 200 and tools/list also fails", async () => { + const company = await createCompany(db); + vi.stubEnv("PAPERCLIP_PUBLIC_URL", PUBLIC_BASE_URL); + vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => { + const body = JSON.parse(String(init?.body ?? "{}")) as { id?: string; method?: string }; + if (body.method === "initialize") { + return jsonResponse({ + jsonrpc: "2.0", + id: body.id, + error: { code: -32001, message: "MCP session failed" }, + }); + } + return jsonResponse({ error: "server_error" }, 500); + }); + const app = createRouteApp(db); + + const failedRpc = await request(app) + .post(`/api/companies/${company.id}/tools/apps/probe-mcp`) + .send({ link: MCP_URL }) + .expect(502); + expect(failedRpc.body.detectedAuth).toBeUndefined(); + + // HTTP 200 HTML / non-MCP body on both initialize and tools/list must also fail closed. + vi.spyOn(globalThis, "fetch").mockImplementation(async () => + new Response("Not an MCP server", { + status: 200, + headers: { "content-type": "text/html" }, + })); + + const nonMcp = await request(app) + .post(`/api/companies/${company.id}/tools/apps/probe-mcp`) + .send({ link: MCP_URL }) + .expect(422); + expect(nonMcp.body.details).toMatchObject({ code: "mcp_endpoint_invalid" }); + expect(nonMcp.body.detectedAuth).toBeUndefined(); + + // Strip Unicode bidi/zero-width spoofing characters from untrusted serverInfo.name. + vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => { + const body = JSON.parse(String(init?.body ?? "{}")) as { id?: string; method?: string }; + if (body.method === "initialize") { + return jsonResponse({ + jsonrpc: "2.0", + id: body.id, + result: { serverInfo: { name: "Safe\u202e\u200bName" } }, + }); + } + return jsonResponse({ + jsonrpc: "2.0", + id: body.id, + result: { tools: FIXTURE_TOOLS }, + }); + }); + const bidi = await request(app) + .post(`/api/companies/${company.id}/tools/apps/probe-mcp`) + .send({ link: MCP_URL }) + .expect(200); + expect(bidi.body.suggestedName).toBe("SafeName"); + }); + + it("negotiates modern stateless MCP (2026-07-28) via server/discover before probing tools/list", async () => { + const company = await createCompany(db); + vi.stubEnv("PAPERCLIP_PUBLIC_URL", PUBLIC_BASE_URL); + const seenRequests: Array<{ method: string; version: string | null; hasMeta: boolean }> = []; + vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => { + const headers = new Headers(init?.headers); + const body = JSON.parse(String(init?.body ?? "{}")) as { + id?: string; + method?: string; + params?: { _meta?: Record }; + }; + const version = headers.get("mcp-protocol-version"); + seenRequests.push({ + method: body.method ?? "", + version, + hasMeta: Boolean(body.params?._meta?.["io.modelcontextprotocol/protocolVersion"]), + }); + if (body.method === "server/discover" && version === "2026-07-28") { + return jsonResponse({ + jsonrpc: "2.0", + id: body.id, + result: { supportedVersions: ["2026-07-28"], capabilities: {} }, + }); + } + if (body.method === "tools/list") { + if (version !== "2026-07-28" || !body.params?._meta?.["io.modelcontextprotocol/protocolVersion"]) { + return jsonResponse({ + jsonrpc: "2.0", + id: body.id, + error: { code: -32022, message: "Unsupported protocol version" }, + }, 400); + } + return jsonResponse({ + jsonrpc: "2.0", + id: body.id, + result: { tools: FIXTURE_TOOLS }, + }); + } + return jsonResponse({ error: "method_not_allowed" }, 405); + }); + const app = createRouteApp(db); + + const response = await request(app) + .post(`/api/companies/${company.id}/tools/apps/probe-mcp`) + .send({ link: MCP_URL }) + .expect(200); + + expect(response.body).toMatchObject({ + endpointUrl: MCP_URL, + detectedAuth: "none", + toolCount: FIXTURE_TOOLS.length, + }); + expect(seenRequests).toEqual([ + { method: "server/discover", version: "2026-07-28", hasMeta: true }, + { method: "tools/list", version: "2026-07-28", hasMeta: true }, + ]); + }); + + it("preserves saved agent bindings and Ask-first policies when switching an active custom MCP connection's sign-in method", async () => { + const company = await createCompany(db); + const [agent] = await db + .insert(agents) + .values({ + companyId: company.id, + name: "Scoped Agent", + role: "engineer", + status: "idle", + adapterType: "process", + adapterConfig: {}, + runtimeConfig: {}, + }) + .returning(); + vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => { + const body = JSON.parse(String(init?.body ?? "{}")) as { id?: string; method?: string }; + if (body.method === "notifications/initialized") return new Response(null, { status: 202 }); + if (body.method === "initialize") { + return jsonResponse({ jsonrpc: "2.0", id: body.id, result: { protocolVersion: "2025-11-25" } }); + } + if (body.method === "tools/list") { + return jsonResponse({ jsonrpc: "2.0", id: body.id, result: { tools: FIXTURE_TOOLS } }); + } + return jsonResponse({ error: "not_found" }, 404); + }); + const svc = toolAccessService(db); + const connected = await svc.connectGalleryApp(company.id, { + link: MCP_URL, + name: "Scoped MCP", + authMode: "none", + }); + const entryIds = [ + ...connected.actions.readOnly.map((a) => a.catalogEntryId), + ...connected.actions.canMakeChanges.map((a) => a.catalogEntryId), + ]; + const askFirstId = connected.actions.canMakeChanges[0]?.catalogEntryId ?? entryIds[0]!; + await svc.finishGalleryAppConnection(company.id, connected.connectionId, { + enabledCatalogEntryIds: entryIds, + askFirstCatalogEntryIds: [askFirstId], + access: { agentIds: [agent!.id] }, + }); + + // Switch sign-in method from none -> bearer on the active connection. + const switched = await svc.connectGalleryApp(company.id, { + link: MCP_URL, + name: "Scoped MCP", + authMode: "bearer", + reconnectConnectionId: connected.connectionId, + credentialValues: { "credentials.authorization": "new-api-key" }, + }); + expect(switched.connection.config?.mcpPreserveAccess).toBe(true); + + // Even if a client calls finishGalleryAppConnection with default all_agents / empty askFirst, + // the server must preserve the existing agent bindings and Ask-first policies. + const finished = await svc.finishGalleryAppConnection(company.id, switched.connectionId, { + enabledCatalogEntryIds: entryIds, + askFirstCatalogEntryIds: [], + access: "all_agents", + }); + expect(finished.profileBindings).toEqual([ + expect.objectContaining({ targetType: "agent", targetId: agent!.id }), + ]); + expect(finished.policies.length).toBeGreaterThanOrEqual(1); + }); + }); }); diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index d07459bda05..3f155d142b1 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -313,6 +313,7 @@ import { workspaceFileResourceQuerySchema, // Tool access connectToolAppSchema, + probeGenericMcpSchema, createMachineSignInSchema, testMachineSignInSchema, rotateMachineSignInSchema, @@ -12682,6 +12683,23 @@ registerCurrentRoute({ }, }); +registerCurrentRoute({ + "x-paperclip-transport": "rest", + "x-paperclip-connection-management": "connections:configure", + method: "post", + path: "/api/companies/{companyId}/tools/apps/probe-mcp", + tags: ["tool-access"], + summary: "Probe a custom remote MCP endpoint for authentication and server metadata", + body: probeGenericMcpSchema, + responses: { + 200: r.ok(), + 400: r.badRequest, + 401: r.unauthorized, + 403: r.forbidden, + 422: r.unprocessable, + }, +}); + registerCurrentRoute({ "x-paperclip-transport": "rest", "x-paperclip-connection-management": "connections:configure", diff --git a/server/src/routes/tool-access.ts b/server/src/routes/tool-access.ts index b0dba41b372..636fba17c07 100644 --- a/server/src/routes/tool-access.ts +++ b/server/src/routes/tool-access.ts @@ -25,6 +25,7 @@ import { type ToolConnection, type ToolConnectionCreateCapabilities, connectToolAppSchema, + probeGenericMcpSchema, createMachineSignInSchema, testMachineSignInSchema, rotateMachineSignInSchema, @@ -1136,6 +1137,28 @@ function connectorEnrollmentPrincipal(req: Request): string { } }); + router.post( + "/companies/:companyId/tools/apps/probe-mcp", + managementGuard("connections:configure", "POST /companies/:companyId/tools/apps/probe-mcp"), + validate(probeGenericMcpSchema), + async (req, res) => { + const companyId = req.params.companyId as string; + assertToolAppMutationAccess(req, companyId); + assertNotThisPaperclip(req, req.body.link); + let redirectUri: string | null = null; + try { + redirectUri = oauthRedirectUri(req, true); + } catch { + redirectUri = null; + } + const result = await svc.probeGenericMcpEndpoint(companyId, { + link: req.body.link, + redirectUri, + }); + res.json(result); + }, + ); + // Machine sign-in (MCP OAuth client credentials): organization connections // that authenticate as a registered client, with no person signing in. router.post("/companies/:companyId/tools/machine-sign-in", managementGuard("connections:configure", "POST /companies/:companyId/tools/machine-sign-in"), validate(createMachineSignInSchema), async (req, res) => { diff --git a/server/src/services/tool-access.ts b/server/src/services/tool-access.ts index 318e74c4624..dc1a5de2584 100644 --- a/server/src/services/tool-access.ts +++ b/server/src/services/tool-access.ts @@ -13,7 +13,8 @@ import { createConnectionCredentialValidation } from "./tool-access/connections/ import { createConnectionGrants } from "./tool-access/connections/grants.js"; import { createConnectionInstalls } from "./tool-access/connections/installs.js"; import { createConnectionRemoval } from "./tool-access/connections/removal.js"; -import { createFirstSignInDrafts } from "./tool-access/connections/first-sign-in.js"; +import { connectionHasOAuthCredential, createFirstSignInDrafts } from "./tool-access/connections/first-sign-in.js"; +import { createGenericMcpProbe } from "./tool-access/connections/probe-mcp.js"; import { createToolRemoteHttp } from "./tool-access/remote-http.js"; import { classifyRisk, normalizeToolDescriptor, type McpToolDescriptor } from "./tool-access/catalog/descriptors.js"; export { classifyRisk, isGmailToolPermanentlyBlocked, isGoogleWorkspaceToolAllowed, type McpToolDescriptor } from "./tool-access/catalog/descriptors.js"; @@ -750,6 +751,12 @@ export function toolAccessService( const { oauthEndpointsForConnection, discoverOAuthEndpoints, preflightConnectionMetadata } = createOAuthDiscovery({ fetchRemoteHttpUrl, assertRemoteEndpointAllowed, assertOAuthEndpointUrl, safeOAuthEndpointUrl, }); + const probeGenericMcpEndpoint = createGenericMcpProbe({ + assertRemoteEndpointAllowed, + requestRemoteHttpEndpoint, + discoverOAuthEndpoints, + remoteHttpEndpointLookup: options.remoteHttpEndpointLookup, + }); const { requestOAuthClientRegistration, exchangeOAuthToken } = createOAuthClientProtocol({ fetchRemoteHttpUrl, assertOAuthEndpointUrl, }); @@ -2298,6 +2305,26 @@ export function toolAccessService( : {}), } : {}; + const retainedCustomMcpHasSavedProfile = Boolean( + !galleryEntry + && retainedConnection + && retainedConnection.status !== "archived" + && ( + retainedConnection.status === "active" + || asRecord(retainedConnection.config).mcpPreserveAccess === true + || (retainedConnection.status === "draft" && connectionHasOAuthCredential(retainedConnection, [])) + ) + && (await db + .select({ id: toolProfiles.id }) + .from(toolProfiles) + .where( + and( + eq(toolProfiles.companyId, companyId), + eq(toolProfiles.profileKey, `app:${retainedConnection.id}`), + ), + ) + .limit(1))[0], + ); let config: Record = galleryEntry ? { ...baseConfig, @@ -2346,6 +2373,7 @@ export function toolAccessService( ...preservedAccessMarkers, quarantineNewEntries: false, unverifiedServer: true, + ...(retainedCustomMcpHasSavedProfile ? { mcpPreserveAccess: true } : {}), // Peer tool prefix, fixed when the identity is created. A retained // identity keeps whatever it had, so tool names that saved rules and // approvals refer to never change on reconnect or rename. @@ -3426,27 +3454,39 @@ export function toolAccessService( await assertConnectorConnectionSetupEnabled(connection); if (connection.status === "archived") throw conflict("Archived app connections cannot be finished"); - if (connection.config.mcpPreserveAccess === true && isRemoteMcpConnectorMethod(connection.config.sourceTemplateKey, connection.config.connectionMethodKey)) { + const preservesCustomMcpAccess = + connection.config.mcpPreserveAccess === true + && connection.transport === "mcp_remote" + && !connection.config.sourceTemplateKey; + if ( + connection.config.mcpPreserveAccess === true + && ( + isRemoteMcpConnectorMethod(connection.config.sourceTemplateKey, connection.config.connectionMethodKey) + || preservesCustomMcpAccess + ) + ) { const [profile] = await db.select().from(toolProfiles).where(and( eq(toolProfiles.companyId, companyId), eq(toolProfiles.profileKey, `app:${connection.id}`), )).limit(1); - if (!profile) throw conflict("The saved connection permissions could not be found"); - const config = { ...connection.config }; - delete config.mcpPreserveAccess; - const updated = await db.transaction(async (tx) => { - await tx.select({ id: toolApplications.id }).from(toolApplications) - .where(and(eq(toolApplications.id, connection.applicationId), eq(toolApplications.companyId, companyId))) - .for("update"); - await notifyGitHubCredentialChange(tx, connection); - await notifyToolConnectionHealth(tx, connection); - const [row] = await tx.update(toolConnections).set({ config, transportConfig: config, status: "active", enabled: true, ...(input.agentInstructions !== undefined ? { agentInstructions: input.agentInstructions } : {}), updatedAt: new Date() }) - .where(and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, companyId))).returning(); - await tx.update(toolApplications).set({ status: "active", updatedAt: new Date() }).where(and(eq(toolApplications.id, connection.applicationId), eq(toolApplications.companyId, companyId))); - return row; - }); - const details = await profileDetails(profile.id, companyId); - const policies = (await db.select().from(toolPolicies).where(eq(toolPolicies.companyId, companyId))).filter((policy) => asRecord(policy.config).connectionId === connection.id); - return { connection: toConnection(updated), profile: toProfile(profile), profileEntries: details.entries, profileBindings: details.bindings, policies: policies.map(toPolicy) }; + if (profile || !preservesCustomMcpAccess) { + if (!profile) throw conflict("The saved connection permissions could not be found"); + const config = { ...connection.config }; + delete config.mcpPreserveAccess; + const updated = await db.transaction(async (tx) => { + await tx.select({ id: toolApplications.id }).from(toolApplications) + .where(and(eq(toolApplications.id, connection.applicationId), eq(toolApplications.companyId, companyId))) + .for("update"); + await notifyGitHubCredentialChange(tx, connection); + await notifyToolConnectionHealth(tx, connection); + const [row] = await tx.update(toolConnections).set({ config, transportConfig: config, status: "active", enabled: true, ...(input.agentInstructions !== undefined ? { agentInstructions: input.agentInstructions } : {}), updatedAt: new Date() }) + .where(and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, companyId))).returning(); + await tx.update(toolApplications).set({ status: "active", updatedAt: new Date() }).where(and(eq(toolApplications.id, connection.applicationId), eq(toolApplications.companyId, companyId))); + return row; + }); + const details = await profileDetails(profile.id, companyId); + const policies = (await db.select().from(toolPolicies).where(eq(toolPolicies.companyId, companyId))).filter((policy) => asRecord(policy.config).connectionId === connection.id); + return { connection: toConnection(updated), profile: toProfile(profile), profileEntries: details.entries, profileBindings: details.bindings, policies: policies.map(toPolicy) }; + } } const enabledIds = [ ...new Set([ @@ -3822,8 +3862,8 @@ export function toolAccessService( ? '{"agentAccessConfigured":true,"mcpAgentAccessConfigured":true}' : '{"agentAccessConfigured":true}'; return { - config: sql`${toolConnections.config} || ${accessMarker}::jsonb`, - transportConfig: sql`${toolConnections.transportConfig} || ${accessMarker}::jsonb`, + config: sql`(${toolConnections.config} - 'mcpPreserveAccess') || ${accessMarker}::jsonb`, + transportConfig: sql`(${toolConnections.transportConfig} - 'mcpPreserveAccess') || ${accessMarker}::jsonb`, }; })() : {}), ...(input.agentInstructions !== undefined ? { agentInstructions: input.agentInstructions } : {}), @@ -5007,13 +5047,17 @@ export function toolAccessService( companyId?: string, viewerUserId?: string, ): Promise => { - const connection = toConnection( - await getConnectionRow(connectionId, companyId), - ); + const row = await getConnectionRow(connectionId, companyId); + const connection = toConnection(row); connection.installs = await listConnectionInstalls( connection.id, connection.companyId, ); + await firstSignInDrafts.annotateFirstSignInPending( + row.companyId, + [row], + [connection], + ); await annotateAiGrantHealth([connection]); await annotateGitHubAuthorization([connection], viewerUserId); await annotateSavedOAuthClientSecret([connection], viewerUserId); @@ -5256,6 +5300,8 @@ export function toolAccessService( return toConnection(connection); }, + probeGenericMcpEndpoint, + ensureNoDuplicateNameError: (error: unknown) => { const maybeRecord = typeof error === "object" && error !== null diff --git a/server/src/services/tool-access/catalog/publication.ts b/server/src/services/tool-access/catalog/publication.ts index 4565ec65659..c7cd1e68a6c 100644 --- a/server/src/services/tool-access/catalog/publication.ts +++ b/server/src/services/tool-access/catalog/publication.ts @@ -369,7 +369,10 @@ export function createToolCatalogPublication(db: Db, { now, audit, getConnection (entry) => entry.status === "active", ); const preserveMcpAccess = connection.config.mcpPreserveAccess === true - && isRemoteMcpConnectorMethod(connection.config.sourceTemplateKey, connection.config.connectionMethodKey); + && ( + isRemoteMcpConnectorMethod(connection.config.sourceTemplateKey, connection.config.connectionMethodKey) + || (connection.transport === "mcp_remote" && !connection.config.sourceTemplateKey) + ); if (!refreshOptions.skipDefaultProfileSync || preserveMcpAccess) { await publish(tx => enableCatalogEntriesByDefault({ connection: updatedConnection, diff --git a/server/src/services/tool-access/catalog/reader.ts b/server/src/services/tool-access/catalog/reader.ts index ec9433bc1f2..f92414e652c 100644 --- a/server/src/services/tool-access/catalog/reader.ts +++ b/server/src/services/tool-access/catalog/reader.ts @@ -8,6 +8,7 @@ import type { Db } from "@paperclipai/db"; import { toolCatalogEntries, toolConnections } from "@paperclipai/db"; import type { ToolCatalogEntry } from "@paperclipai/shared"; +import { isConnectionAwaitingFirstSignIn } from "../connections/first-sign-in.js"; import type { RefreshConnectionCatalog } from "./contracts.js"; export function createToolCatalogReader(db: Db, options: { catalogCacheTtlMs?: number }, now: () => Date, getConnectionRow: (idOrUid: string, companyId?: string) => Promise, refreshCatalog: RefreshConnectionCatalog, toCatalogEntryForConnection: (row: typeof toolCatalogEntries.$inferSelect, connection: typeof toolConnections.$inferSelect) => ToolCatalogEntry) { const catalogRefreshFlights = new Map>(); @@ -48,7 +49,12 @@ export function createToolCatalogReader(db: Db, options: { catalogCacheTtlMs?: n return !existing || !restConnector.isCurrent(existing); }) ); + const awaitingFirstSignIn = + connection.transport === "mcp_remote" && + rows.length === 0 && + (await isConnectionAwaitingFirstSignIn(db, connection)); const cacheExpired = nativeCatalogChanged || restCatalogChanged || ( + !awaitingFirstSignIn && connection.transport === "mcp_remote" && connection.status !== "archived" && (rows.length === 0 || diff --git a/server/src/services/tool-access/connections/first-sign-in.ts b/server/src/services/tool-access/connections/first-sign-in.ts index 33b0dcfa072..0a302278b01 100644 --- a/server/src/services/tool-access/connections/first-sign-in.ts +++ b/server/src/services/tool-access/connections/first-sign-in.ts @@ -79,6 +79,17 @@ async function grantEvidence(db: ToolAccessMutationDb, companyId: string, connec .where(and(eq(connectionGrants.companyId, companyId), inArray(connectionGrants.connectionId, connectionIds))); } +export async function isConnectionAwaitingFirstSignIn( + db: ToolAccessMutationDb, + connection: ConnectionRow, +): Promise { + if (!connectionAwaitsFirstSignIn(connection, [])) return false; + return connectionAwaitsFirstSignIn( + connection, + await grantEvidence(db, connection.companyId, [connection.id]), + ); +} + class KeptConnection { row: ConnectionRow | null = null; } diff --git a/server/src/services/tool-access/connections/probe-mcp.ts b/server/src/services/tool-access/connections/probe-mcp.ts new file mode 100644 index 00000000000..727a8a2faa5 --- /dev/null +++ b/server/src/services/tool-access/connections/probe-mcp.ts @@ -0,0 +1,385 @@ +import type { GenericMcpProbeResult } from "@paperclipai/shared"; +import { unprocessable } from "../../../errors.js"; +import { + McpHttpInitializationError, + MCP_PROTOCOL_VERSION, + isModernMcpProtocolVersion, + mcpHttpRequestInit, + negotiateMcpProtocolVersion, + readMcpHttpResponse, +} from "../../mcp-http.js"; +import { + mcpDiscoveryHttpFailure, + withMcpConnectionFailure, +} from "../../mcp-connection-failure.js"; +import type { RemoteHttpEndpointLookup } from "../../remote-http-endpoint-guard.js"; +import { isOAuthEndpointRejection } from "../catalog/failures.js"; +import { resolveOAuthClientIdMetadataDocumentUrl } from "../oauth/client-metadata.js"; +import type { OAuthConnectionSettings, OAuthProviderEndpoints } from "../oauth/types.js"; + +function asRecord(value: unknown): Record { + if (value && typeof value === "object" && !Array.isArray(value)) { + return value as Record; + } + return {}; +} + +/** + * Only adopt a plain, single-line, short display name from an unverified remote + * MCP server — reject URLs, markup, control characters, or instruction-like strings. + */ +function sanitizeSuggestedServerName(raw: unknown): string | null { + if (typeof raw !== "string") return null; + const normalized = raw + .replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2060-\u206f\ufeff]+/g, "") + .replace(/\s+/g, " ") + .trim(); + if (normalized.length < 2 || normalized.length > 60) return null; + if (/https?:\/\//i.test(normalized)) return null; + if (/[<>`[\]{}]/.test(normalized)) return null; + return normalized; +} + +type ProbeDependencies = { + assertRemoteEndpointAllowed: (config: Record) => Promise; + requestRemoteHttpEndpoint: (url: URL, init: RequestInit) => Promise; + discoverOAuthEndpoints: ( + connection: OAuthConnectionSettings, + challenge?: string | null, + firstPartyOrigin?: string | null, + ) => Promise; + remoteHttpEndpointLookup?: RemoteHttpEndpointLookup; +}; + +export function createGenericMcpProbe({ + assertRemoteEndpointAllowed, + requestRemoteHttpEndpoint, + discoverOAuthEndpoints, + remoteHttpEndpointLookup, +}: ProbeDependencies) { + return async function probeGenericMcpEndpoint( + companyId: string, + input: { + link: string; + redirectUri?: string | null; + }, + ): Promise { + const endpointUrl = await assertRemoteEndpointAllowed({ url: input.link }); + const parsedEndpoint = new URL(endpointUrl); + const oauthCallbackUrl = input.redirectUri ?? null; + + const syntheticConnection: OAuthConnectionSettings = { + companyId, + transport: "mcp_remote", + ownership: "customer", + config: { url: endpointUrl }, + }; + + const sendProbe = ( + id: string, + method: string, + params: Record, + extraHeaders: Record = {}, + protocolVersion: string = MCP_PROTOCOL_VERSION, + ) => + withMcpConnectionFailure(() => + requestRemoteHttpEndpoint( + parsedEndpoint, + mcpHttpRequestInit( + { "MCP-Protocol-Version": protocolVersion, ...extraHeaders }, + { id, method, params }, + ), + ), + ); + + const classifyAuthChallenge = async ( + response: Response, + ): Promise => { + const authenticate = response.headers.get("www-authenticate") ?? ""; + await response.body?.cancel().catch(() => undefined); + const endpoints = await discoverOAuthEndpoints( + syntheticConnection, + authenticate, + ).catch((error: unknown) => { + if (isOAuthEndpointRejection(error)) throw error; + return null; + }); + if (!endpoints) { + return { + endpointUrl, + detectedAuth: "bearer", + registrationMethod: null, + authorizationHost: null, + issuer: null, + suggestedName: null, + toolCount: null, + oauthCallbackUrl, + }; + } + const cimdUrl = + endpoints.clientIdMetadataDocumentSupported && oauthCallbackUrl + ? await resolveOAuthClientIdMetadataDocumentUrl( + oauthCallbackUrl, + remoteHttpEndpointLookup, + ) + : null; + const registrationMethod = cimdUrl + ? "cimd" + : endpoints.registrationUrl + ? "dcr" + : null; + let authorizationHost: string | null = null; + try { + authorizationHost = new URL(endpoints.authorizationUrl).host; + } catch { + authorizationHost = null; + } + return { + endpointUrl, + detectedAuth: registrationMethod ? "oauth_auto" : "oauth_manual", + registrationMethod, + authorizationHost, + issuer: endpoints.issuer ?? null, + suggestedName: sanitizeSuggestedServerName(endpoints.resourceName), + toolCount: null, + oauthCallbackUrl, + }; + }; + + const parseMcpJsonRpcResult = async ( + response: Response, + requestId: string, + ): Promise< + | { ok: true; result: Record } + | { ok: false; errorMessage: string | null } + > => { + try { + const payload = asRecord( + await readMcpHttpResponse(response, requestId, { maxBytes: 256 * 1024 }), + ); + if (payload.error !== undefined) { + const errObj = asRecord(payload.error); + const msg = typeof errObj.message === "string" && errObj.message.trim() + ? errObj.message.trim() + : null; + return { ok: false, errorMessage: msg }; + } + if ( + payload.result === undefined + || payload.result === null + || typeof payload.result !== "object" + || Array.isArray(payload.result) + ) { + return { ok: false, errorMessage: null }; + } + return { ok: true, result: payload.result as Record }; + } catch (error) { + return { + ok: false, + errorMessage: error instanceof Error && error.message.trim() ? error.message.trim() : null, + }; + } + }; + + const invalidMcpEndpointError = (detail?: string | null) => + unprocessable( + detail + ? `This URL did not return a valid MCP response (${detail}). Check the endpoint URL and try again.` + : "This URL did not return a valid MCP response. Check the endpoint URL and try again.", + { code: "mcp_endpoint_invalid" }, + ); + + let negotiatedVersion: string = MCP_PROTOCOL_VERSION; + try { + negotiatedVersion = await negotiateMcpProtocolVersion({ + requestId: "paperclip-mcp-probe", + headers: {}, + send: (init) => + withMcpConnectionFailure(() => + requestRemoteHttpEndpoint(parsedEndpoint, init), + ), + }); + } catch (error) { + if ( + error instanceof McpHttpInitializationError + && (error.status === 401 || error.status === 403) + && error.response + ) { + return classifyAuthChallenge(error.response); + } + throw error; + } + + if (isModernMcpProtocolVersion(negotiatedVersion)) { + const listId = "paperclip-catalog-refresh"; + const listResponse = await sendProbe( + listId, + "tools/list", + {}, + {}, + negotiatedVersion, + ); + if (listResponse.status === 401 || listResponse.status === 403) { + return classifyAuthChallenge(listResponse); + } + if (listResponse.ok) { + const listParsed = await parseMcpJsonRpcResult(listResponse, listId); + if (!listParsed.ok || !Array.isArray(listParsed.result.tools)) { + throw invalidMcpEndpointError(listParsed.ok ? null : listParsed.errorMessage); + } + return { + endpointUrl, + detectedAuth: "none", + registrationMethod: null, + authorizationHost: null, + issuer: null, + suggestedName: null, + toolCount: listParsed.result.tools.length, + oauthCallbackUrl, + }; + } + await listResponse.body?.cancel().catch(() => undefined); + throw mcpDiscoveryHttpFailure( + listResponse, + `Remote app returned HTTP ${listResponse.status}`, + ); + } + + const initId = "paperclip-mcp-probe-init"; + const initResponse = await sendProbe( + initId, + "initialize", + { + protocolVersion: negotiatedVersion, + capabilities: {}, + clientInfo: { name: "Paperclip", version: "1.0.0" }, + }, + {}, + negotiatedVersion, + ); + + if (initResponse.status === 401 || initResponse.status === 403) { + return classifyAuthChallenge(initResponse); + } + + if (initResponse.ok) { + const sessionId = initResponse.headers.get("mcp-session-id"); + let suggestedName: string | null = null; + let toolCount: number | null = null; + let initConfirmed = false; + let initError: string | null = null; + + const initParsed = await parseMcpJsonRpcResult(initResponse, initId); + if (initParsed.ok) { + initConfirmed = true; + const serverInfo = asRecord(initParsed.result.serverInfo); + suggestedName = sanitizeSuggestedServerName(serverInfo.name); + if (Array.isArray(initParsed.result.tools)) { + toolCount = initParsed.result.tools.length; + } + } else { + initError = initParsed.errorMessage; + } + + let listConfirmed = false; + let listError: string | null = null; + let listFailureResponse: Response | null = null; + + if (toolCount === null) { + const listId = "paperclip-catalog-refresh"; + const sessionHeaders: Record = sessionId + ? { "Mcp-Session-Id": sessionId } + : {}; + const listResponse = await sendProbe( + listId, + "tools/list", + {}, + sessionHeaders, + negotiatedVersion, + ).catch(() => null); + if (listResponse) { + if (listResponse.status === 401 || listResponse.status === 403) { + return classifyAuthChallenge(listResponse); + } + if (listResponse.ok) { + const listParsed = await parseMcpJsonRpcResult(listResponse, listId); + if (listParsed.ok && Array.isArray(listParsed.result.tools)) { + listConfirmed = true; + toolCount = listParsed.result.tools.length; + } else { + listError = listParsed.ok ? null : listParsed.errorMessage; + } + } else { + listFailureResponse = listResponse; + await listResponse.body?.cancel().catch(() => undefined); + } + } + } + + if (!initConfirmed && !listConfirmed) { + if (listFailureResponse) { + throw mcpDiscoveryHttpFailure( + listFailureResponse, + `Remote app returned HTTP ${listFailureResponse.status}`, + ); + } + throw invalidMcpEndpointError(listError ?? initError); + } + + return { + endpointUrl, + detectedAuth: "none", + registrationMethod: null, + authorizationHost: null, + issuer: null, + suggestedName, + toolCount, + oauthCallbackUrl, + }; + } + + // Some stateless legacy MCP endpoints reject `initialize` with 400/405. + // Probe `tools/list` directly before failing. + if (initResponse.status === 400 || initResponse.status === 405) { + await initResponse.body?.cancel().catch(() => undefined); + const listId = "paperclip-catalog-refresh"; + const listResponse = await sendProbe( + listId, + "tools/list", + {}, + {}, + negotiatedVersion, + ); + if (listResponse.status === 401 || listResponse.status === 403) { + return classifyAuthChallenge(listResponse); + } + if (listResponse.ok) { + const listParsed = await parseMcpJsonRpcResult(listResponse, listId); + if (!listParsed.ok || !Array.isArray(listParsed.result.tools)) { + throw invalidMcpEndpointError(listParsed.ok ? null : listParsed.errorMessage); + } + return { + endpointUrl, + detectedAuth: "none", + registrationMethod: null, + authorizationHost: null, + issuer: null, + suggestedName: null, + toolCount: listParsed.result.tools.length, + oauthCallbackUrl, + }; + } + await listResponse.body?.cancel().catch(() => undefined); + throw mcpDiscoveryHttpFailure( + listResponse, + `Remote app returned HTTP ${listResponse.status}`, + ); + } + + await initResponse.body?.cancel().catch(() => undefined); + throw mcpDiscoveryHttpFailure( + initResponse, + `Remote app returned HTTP ${initResponse.status}`, + ); + }; +} diff --git a/server/src/services/tool-access/oauth/connection-refresh.ts b/server/src/services/tool-access/oauth/connection-refresh.ts index aa23c2a9723..c813dfd5846 100644 --- a/server/src/services/tool-access/oauth/connection-refresh.ts +++ b/server/src/services/tool-access/oauth/connection-refresh.ts @@ -2,6 +2,7 @@ import { writeToolConnectionHealthChange } from "../../tool-connection-health-no import type { ActorInfo } from "../types.js"; import { createOAuthClientProtocol, storedOAuthTokenEndpointAuthMethod } from "./client.js"; import { deleteGoogleContentWhenAccessEnds } from "../connections/google-content-retention.js"; +import { connectionHasOAuthCredential } from "../connections/first-sign-in.js"; import { oauthConfig, normalizeOauthScopes } from "./metadata.js"; import { emitConnectionUpdated } from "../../connector-telemetry.js"; import { and, eq, sql } from "drizzle-orm"; @@ -138,6 +139,13 @@ const oauthRefreshFlights = new Map>(); : ("refresh_token" as const); const refreshRef = oauthSecretRef(connection, "oauth.refresh_token"); if (grantType !== "client_credentials" && !refreshRef) { + if (!connectionHasOAuthCredential(connection, [])) { + throw unprocessable("This app needs you to sign in.", { + code: "oauth_challenge", + setupUrl: connectionSetupUrl(connection), + reconnectUrl: connectionReconnectUrl(connection), + }); + } throw new HttpError( 422, "OAuth credentials have expired and no refresh token is available", diff --git a/server/src/services/tool-access/oauth/discovery.ts b/server/src/services/tool-access/oauth/discovery.ts index c8ac53332a1..89493724a6a 100644 --- a/server/src/services/tool-access/oauth/discovery.ts +++ b/server/src/services/tool-access/oauth/discovery.ts @@ -122,6 +122,10 @@ export function createOAuthDiscovery({ fetchRemoteHttpUrl, assertRemoteEndpointA typeof metadata.resource === "string" && metadata.resource.trim() ? metadata.resource.trim() : null; + const resourceName = + typeof metadata.resource_name === "string" && metadata.resource_name.trim() + ? metadata.resource_name.trim() + : null; for (const candidate of authServerMetadataUrls(metadata)) { const authMetadata = await fetchJsonRecord(candidate.metadataUrl); if (!authMetadata) continue; @@ -209,6 +213,7 @@ export function createOAuthDiscovery({ fetchRemoteHttpUrl, assertRemoteEndpointA metadataUrl, issuer, resource, + ...(resourceName ? { resourceName } : {}), clientIdMetadataDocumentSupported, issParameterSupported, }; diff --git a/server/src/services/tool-access/oauth/grant-refresh.ts b/server/src/services/tool-access/oauth/grant-refresh.ts index 639feac8a81..d95f8eb20e0 100644 --- a/server/src/services/tool-access/oauth/grant-refresh.ts +++ b/server/src/services/tool-access/oauth/grant-refresh.ts @@ -7,6 +7,7 @@ import { oauthConfig, normalizeOauthScopes, resolveGrantedOauthScopes } from "./ import { GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE, googleWorkspaceEffectiveScopes, googleWorkspaceSubmittedScopesIn, isGoogleWorkspaceScopeGrant } from "@paperclipai/shared"; import { emitConnectionUpdated } from "../../connector-telemetry.js"; import { deleteGoogleContentWhenAccessEnds } from "../connections/google-content-retention.js"; +import { connectionHasOAuthCredential } from "../connections/first-sign-in.js"; import { and, eq, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { connectionGrants, companySecrets, toolConnections } from "@paperclipai/db"; @@ -17,7 +18,7 @@ import { isPaperclipCloudConnectorStrategy, PaperclipCloudConnectorError, type P import { actorForSecret, type OAuthCredentialStore } from "./credential-store.js"; import { withoutOAuthRefreshLease, type OAuthRefreshLeases } from "./refresh-leases.js"; -import { managedConnectorProfile, managedConnectorSubject, oauthGrantConfig, oauthGrantExpiresAtMs } from "./client-settings.js"; +import { managedConnectorProfile, managedConnectorSubject, oauthGrantConfig, oauthGrantExpiresAtMs, oauthSecretRef } from "./client-settings.js"; import { connectionSetupUrl, connectionReconnectUrl } from "../identifiers.js"; import { singleFlight } from "../single-flight.js"; import { usesClientCredentials } from "./client-credentials.js"; @@ -325,6 +326,13 @@ export function createOAuthGrantRefresh(db: Db, { now, store, leases, currentClo (ref) => ref.configPath === "oauth.refresh_token", ); if (!machineSignIn && !refreshRef) { + if (!connectionHasOAuthCredential(connection, [grant])) { + throw unprocessable("This app needs you to sign in.", { + code: "oauth_challenge", + setupUrl: connectionSetupUrl(connection), + reconnectUrl: connectionReconnectUrl(connection), + }); + } throw unprocessable( "OAuth credentials have expired and no refresh token is available", { diff --git a/server/src/services/tool-access/oauth/types.ts b/server/src/services/tool-access/oauth/types.ts index 3ae58a4c666..9cec3ad675e 100644 --- a/server/src/services/tool-access/oauth/types.ts +++ b/server/src/services/tool-access/oauth/types.ts @@ -26,6 +26,8 @@ export type OAuthProviderEndpoints = { * has ever connected. */ resource?: string | null; + /** Optional display name from RFC 9728 protected-resource metadata (`resource_name`). */ + resourceName?: string | null; /** The authorization server advertised support for Client ID Metadata Documents. */ clientIdMetadataDocumentSupported?: boolean; /** RFC 9207: the authorization server says every authorization response carries `iss`. */ diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 81063a7bced..92dfc711ece 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -291,7 +291,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "56fdc6718a8af98006752d587afea8a1cd53d790", + "packages/shared/src/index.ts": "44987b6bcd430cd264728f6925f29bfcf5925259", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -462,7 +462,7 @@ "packages/shared/src/types/inbox-agent-policy.ts": "cb9d41d9681e80b834889268ad96015a39df92f6", "packages/shared/src/types/inbox-dismissal.ts": "58fb7013847396ac9971eb5799dd0bf0486e0371", "packages/shared/src/types/inbox-mine.ts": "1d302b531d34842189704abd2f75f8743d09490d", - "packages/shared/src/types/index.ts": "66574aca258c08267c036a747cb16669b9fedfd4", + "packages/shared/src/types/index.ts": "c7e3875e094f0f74fd9c0a4abc43e7630493cb63", "packages/shared/src/types/instance.ts": "406736718fa7e8f788d4e963291943d38c16a368", "packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df", "packages/shared/src/types/issue.ts": "c926a6a56874b18b3a61e22defaf9aca54172ca7", @@ -487,7 +487,7 @@ "packages/shared/src/types/tailscale.ts": "d02a917945d7779009a2dea4c4b535e9478e0680", "packages/shared/src/types/task-workspace.ts": "a23afa13d2cb58dc2eb72692ed28c16ed6fb84fb", "packages/shared/src/types/teams-catalog.ts": "632fe75f8e5a4cfc455843c2a1a2daff28a022be", - "packages/shared/src/types/tool-access.ts": "65f9f89a79bb7cceff634499b858a4689fb2f553", + "packages/shared/src/types/tool-access.ts": "5c9299cddaedb1073513e6cb12941f39ec45d874", "packages/shared/src/types/user-profile.ts": "1ac26e033a79fab21dc267fd983959814c8b680f", "packages/shared/src/types/voice-sessions.ts": "95e3b62cdd51f62290e68536728ddd7297bc0459", "packages/shared/src/types/work-product.ts": "26f9129f606a207ce7a218ccef40f96747283086", @@ -543,7 +543,7 @@ "packages/shared/src/validators/folder.ts": "b486444ab09ec3d5a9afec7dbd2e71c1bc2beb67", "packages/shared/src/validators/goal.ts": "602724134915e1e83c50115abba36b288c0abd3d", "packages/shared/src/validators/inbox-agent-policy.ts": "29cef157f4d9b564fd813868038aa8c813df4a7b", - "packages/shared/src/validators/index.ts": "da4f0ba5ada6714241599bac06172ecf3c2d2ef3", + "packages/shared/src/validators/index.ts": "082606540a52396fa8613672ce37e21dcf785a9a", "packages/shared/src/validators/instance.test.ts": "a8eac3e9a6eed97d6aa4f54e14e77c44720600af", "packages/shared/src/validators/instance.ts": "9cfe716ebf4dc1e24324e162ca096cdacbe97c4a", "packages/shared/src/validators/issue-chat-bootstrap.test.ts": "e1ebb9aa94da22c825bc3ddd32ce2cfc98bfe645", @@ -581,7 +581,7 @@ "packages/shared/src/validators/teams-catalog.ts": "7bddf40c091a52aaa54e79de784bea5ae496f9aa", "packages/shared/src/validators/text.ts": "74c430fe17cdcfd4b56dd08a4c57cd3d567670a8", "packages/shared/src/validators/tool-access.test.ts": "ed01e972998730e91c97b5086badf7131bd0264e", - "packages/shared/src/validators/tool-access.ts": "29a4a25c4954402f83c9da77e24706175f90e718", + "packages/shared/src/validators/tool-access.ts": "2437df50ef2123146ee93282cfc45371f27069e7", "packages/shared/src/validators/trust-policy.test.ts": "1fc4818984eb0e14f034d56ad147600224496d4e", "packages/shared/src/validators/trust-policy.ts": "f16b002db940b06bd882d51df8b5712c576e1d7b", "packages/shared/src/validators/voice-sessions.ts": "018a71f9ac544645041ac3cc9919e59c95fbe998", diff --git a/ui/src/api/tools.ts b/ui/src/api/tools.ts index b78f63c3307..2b00aa69fae 100644 --- a/ui/src/api/tools.ts +++ b/ui/src/api/tools.ts @@ -327,6 +327,11 @@ export const toolsApi = { }, connectApp: (companyId: string, input: ConnectToolApp) => api.post(`/companies/${companyId}/tools/apps/connect`, input), + probeGenericMcp: (companyId: string, input: { link: string }) => + api.post( + `/companies/${companyId}/tools/apps/probe-mcp`, + input, + ), createMachineSignIn: (companyId: string, input: import("@paperclipai/shared").CreateMachineSignIn) => api.post(`/companies/${companyId}/tools/machine-sign-in`, input), getAwsSetup: (connectionId: string, accessLevel?: "read_only" | "full") => diff --git a/ui/src/features/connections/ConnectionSetupFlow.generic-mcp.test.tsx b/ui/src/features/connections/ConnectionSetupFlow.generic-mcp.test.tsx index 7535f1799e0..7bba087edf2 100644 --- a/ui/src/features/connections/ConnectionSetupFlow.generic-mcp.test.tsx +++ b/ui/src/features/connections/ConnectionSetupFlow.generic-mcp.test.tsx @@ -18,7 +18,10 @@ const fixture = vi.hoisted(() => ({ listApplications: vi.fn(), listConnections: vi.fn(), connectApp: vi.fn(), + finishApp: vi.fn(), + probeGenericMcp: vi.fn(), startOAuth: vi.fn(), + getConnection: vi.fn(), putConnectionInstalls: vi.fn(), listAgents: vi.fn(), })); @@ -62,9 +65,11 @@ vi.mock("@/api/tools", () => ({ listApplications: (...args: unknown[]) => fixture.listApplications(...args), listConnections: (...args: unknown[]) => fixture.listConnections(...args), connectApp: (...args: unknown[]) => fixture.connectApp(...args), + finishApp: (...args: unknown[]) => fixture.finishApp(...args), + probeGenericMcp: (...args: unknown[]) => fixture.probeGenericMcp(...args), startOAuth: (...args: unknown[]) => fixture.startOAuth(...args), putConnectionInstalls: (...args: unknown[]) => fixture.putConnectionInstalls(...args), - getConnection: vi.fn(), + getConnection: (...args: unknown[]) => fixture.getConnection(...args), getCloudConnectorEnrollment: vi.fn(), startCloudConnectorEnrollment: vi.fn(), }, @@ -156,11 +161,11 @@ async function settle() { } } -async function renderFlow() { +async function renderFlow(props: Partial> = {}) { await act(async () => { root.render( - + , ); }); @@ -200,6 +205,7 @@ beforeEach(() => { fixture.listConnections.mockResolvedValue({ connections: [] }); fixture.listAgents.mockResolvedValue([]); fixture.putConnectionInstalls.mockResolvedValue({}); + fixture.probeGenericMcp.mockImplementation(() => new Promise(() => undefined)); vi.spyOn(window, "open").mockReturnValue({ close: vi.fn(), closed: false, @@ -366,4 +372,279 @@ describe("ConnectionSetupFlow — generic MCP OAuth recovery and draft resume", await settle(); expect((fixture.connectApp.mock.calls[4]?.[1] as Record).resumeConnectionId).toBeUndefined(); }); + + it("auto-detects OAuth in the background, pre-fills editable display name, and submits the edited name", async () => { + fixture.search = `link=${encodeURIComponent("https://api.spreadjam.com/mcp")}`; + fixture.probeGenericMcp.mockResolvedValue({ + endpointUrl: "https://api.spreadjam.com/mcp", + detectedAuth: "oauth_auto", + registrationMethod: "dcr", + authorizationHost: "api.spreadjam.com", + issuer: "https://api.spreadjam.com", + suggestedName: "Jam", + toolCount: null, + oauthCallbackUrl: CALLBACK_URL, + }); + fixture.connectApp.mockResolvedValue(oauthConnectResult("conn-jam-1", "shared", "https://api.spreadjam.com/oauth/authorize")); + + await renderFlow({ byoOnly: true }); + + expect(fixture.probeGenericMcp).toHaveBeenCalledWith("company-1", { link: "https://api.spreadjam.com/mcp" }); + expect(container.textContent).toContain("Browser sign-in detected at api.spreadjam.com"); + expect(container.textContent).toContain("Server URL"); + expect(container.textContent).not.toContain("Pick app"); + + const nameInput = container.querySelector("#generic-mcp-name"); + expect(nameInput).toBeTruthy(); + expect(nameInput?.value).toBe("Jam"); + + await setInputValue(nameInput!, "SpreadJam"); + await act(async () => { + findButton("Check link").click(); + }); + await settle(); + + expect(fixture.connectApp).toHaveBeenCalledWith( + "company-1", + expect.objectContaining({ + link: "https://api.spreadjam.com/mcp", + name: "SpreadJam for the organization", + }), + ); + }); + + it("auto-reveals the key input when the background probe detects bearer auth", async () => { + fixture.probeGenericMcp.mockResolvedValue({ + endpointUrl: DREAMDATA_URL, + detectedAuth: "bearer", + registrationMethod: null, + authorizationHost: null, + issuer: null, + suggestedName: null, + toolCount: null, + oauthCallbackUrl: CALLBACK_URL, + }); + + await renderFlow({ byoOnly: true }); + + expect(container.querySelector("#generic-mcp-key")).toBeTruthy(); + expect(container.textContent).toContain("key or token"); + }); + + it("resumes a saved custom MCP draft via ?resume=&editAuth=1 without a gallery entry", async () => { + const savedDraft = draftConnection("conn-saved-1", "shared"); + savedDraft.name = "SpreadJam"; + savedDraft.config = { url: "https://api.spreadjam.com/mcp", unverifiedServer: true }; + fixture.search = "resume=conn-saved-1&editAuth=1"; + fixture.getConnection.mockResolvedValue(savedDraft); + fixture.listConnections.mockResolvedValue({ connections: [savedDraft] }); + fixture.listApplications.mockResolvedValue({ + applications: [{ id: savedDraft.applicationId, companyId: "company-1", name: "SpreadJam", type: "mcp_remote", status: "draft" }], + }); + fixture.connectApp.mockResolvedValue({ + connectionId: savedDraft.id, + connection: { ...savedDraft, status: "active", enabled: true }, + application: { id: savedDraft.applicationId, name: "SpreadJam" }, + auth: null, + actions: { readOnly: [], canMakeChanges: [] }, + }); + + await renderFlow({ byoOnly: true }); + + expect(container.textContent).toContain("https://api.spreadjam.com/mcp"); + expect(container.textContent).toContain("How does this server sign in?"); + expect(container.textContent).not.toContain("This setup can’t be resumed"); + + // Switch to Key or token and enter an API key; submit resumes the exact draft. + const keyOption = [...container.querySelectorAll('[role="radio"]')].find((el) => + el.textContent?.includes("Key or token"), + ); + expect(keyOption).toBeTruthy(); + await act(async () => { + keyOption!.click(); + }); + const keyInput = container.querySelector("#generic-mcp-key"); + expect(keyInput).toBeTruthy(); + await setInputValue(keyInput!, "sk_live_test"); + await act(async () => { + findButton("Check link").click(); + }); + await settle(); + + expect(fixture.connectApp).toHaveBeenCalledWith( + "company-1", + expect.objectContaining({ + link: "https://api.spreadjam.com/mcp", + authMode: "bearer", + resumeConnectionId: "conn-saved-1", + }), + ); + }); + + it("renders a clean OAuth waiting screen without duplicate unverified badges and polls after opening in a new tab", async () => { + vi.useFakeTimers(); + try { + fixture.search = `link=${encodeURIComponent("https://api.spreadjam.com/mcp")}`; + fixture.connectApp.mockResolvedValue( + oauthConnectResult("conn-poll-1", "shared", "https://api.spreadjam.com/oauth/authorize"), + ); + fixture.getConnection + .mockResolvedValueOnce({ ...draftConnection("conn-poll-1", "shared"), status: "draft", firstSignInPending: true }) + .mockResolvedValueOnce({ ...draftConnection("conn-poll-1", "shared"), status: "active", enabled: true, firstSignInPending: false }); + + await act(async () => { + root.render( + + + , + ); + }); + await act(async () => { await Promise.resolve(); }); + await act(async () => { await Promise.resolve(); }); + + await act(async () => { + findButton("Check link").click(); + }); + await act(async () => { await Promise.resolve(); }); + await act(async () => { await Promise.resolve(); }); + + // Must show Unverified server badge only ONCE, not duplicated. + const unverifiedMatches = (container.textContent ?? "").match(/Unverified server/g) ?? []; + expect(unverifiedMatches).toHaveLength(1); + // Must not talk about choosing a workspace for generic MCP servers. + expect(container.textContent).not.toContain("choose a workspace"); + // Must not render a dead disabled "Opening …" button alongside the new-tab link. + expect(container.textContent).not.toMatch(/Opening .*\u2026/); + + const newTabLink = [...container.querySelectorAll("a")].find((a) => + a.textContent?.includes("Open sign-in in a new tab"), + ); + expect(newTabLink).toBeTruthy(); + + // Clicking "Open sign-in in a new tab" drops the popup ref; polling must STILL detect activation. + await act(async () => { + newTabLink!.click(); + }); + await act(async () => { + await vi.advanceTimersByTimeAsync(2500); + }); + await act(async () => { + await vi.advanceTimersByTimeAsync(2500); + }); + + expect(fixture.getConnection).toHaveBeenCalledWith("conn-poll-1", { fresh: true }); + expect(fixture.navigate).toHaveBeenCalledWith("/apps/conn-poll-1/permissions"); + } finally { + vi.useRealTimers(); + } + }); + + it("keeps Check link enabled in auto mode when reconnecting an archived api_key connection without editAuth=1", async () => { + fixture.search = "byo=1&applicationId=app-1&reconnect=conn-archived-1"; + const archivedConnection = { + ...draftConnection("conn-archived-1", "shared"), + applicationId: "app-1", + status: "archived", + authKind: "api_key", + name: "Bla", + config: { url: "https://api.example.com/mcp", unverifiedServer: true }, + transportConfig: { url: "https://api.example.com/mcp", unverifiedServer: true }, + }; + fixture.listApplications.mockResolvedValue({ + applications: [{ id: "app-1", applicationKey: "app-gallery:link:app-1", name: "Bla" }], + }); + fixture.listConnections.mockResolvedValue({ connections: [archivedConnection] }); + fixture.getConnection.mockResolvedValue(archivedConnection); + fixture.probeGenericMcp.mockResolvedValue({ + endpointUrl: "https://api.example.com/mcp", + detectedAuth: "none", + registrationMethod: null, + authorizationHost: null, + issuer: null, + suggestedName: "Bla", + toolCount: 1, + oauthCallbackUrl: CALLBACK_URL, + }); + + await act(async () => { + root.render( + + + , + ); + }); + await settle(); + + const checkButton = findButton("Check link") as HTMLButtonElement; + expect(checkButton.disabled).toBe(false); + }); + + it("preserves existing agent installs and passes preserveExistingAccess when changing sign-in method on an active custom MCP connection", async () => { + fixture.search = "byo=1&reconnect=conn-active-1&editAuth=1"; + const activeConnection = { + ...draftConnection("conn-active-1", "shared"), + applicationId: "app-active-1", + status: "active", + enabled: true, + firstSignInPending: false, + authKind: "oauth", + name: "SpreadJam", + config: { url: "https://api.spreadjam.com/mcp", unverifiedServer: true }, + transportConfig: { url: "https://api.spreadjam.com/mcp", unverifiedServer: true }, + }; + fixture.listApplications.mockResolvedValue({ + applications: [{ id: "app-active-1", applicationKey: "app-gallery:link:app-active-1", name: "SpreadJam" }], + }); + fixture.listConnections.mockResolvedValue({ connections: [activeConnection] }); + fixture.getConnection.mockResolvedValue(activeConnection); + fixture.connectApp.mockResolvedValue({ + connectionId: "conn-active-1", + connection: { + ...activeConnection, + authKind: "api_key", + config: { ...activeConnection.config, mcpPreserveAccess: true }, + }, + application: { id: "app-active-1", name: "SpreadJam" }, + auth: { kind: "api_key", startUrl: null, manualClientRequired: false }, + actions: { readOnly: [{ catalogEntryId: "entry-1", name: "get_me" }], canMakeChanges: [] }, + catalog: [{ id: "entry-1", name: "get_me", status: "active" }], + }); + fixture.finishApp.mockResolvedValue({ connection: activeConnection }); + + await act(async () => { + root.render( + + + , + ); + }); + await settle(); + + expect(container.textContent).toContain("Your existing agent access and action permissions will stay unchanged."); + + const bearerRadio = [...container.querySelectorAll('[role="radio"]')].find((el) => + el.textContent?.includes("Key or token"), + ) as HTMLElement | undefined; + expect(bearerRadio).toBeDefined(); + await act(async () => { + bearerRadio!.click(); + }); + await settle(); + + const keyInput = container.querySelector("#generic-mcp-key"); + expect(keyInput).not.toBeNull(); + await setInputValue(keyInput!, "sk_live_replacement"); + + await act(async () => { + findButton("Check link").click(); + }); + await settle(); + + expect(fixture.finishApp).toHaveBeenCalledWith( + "company-1", + "conn-active-1", + expect.objectContaining({ preserveExistingAccess: true }), + ); + expect(fixture.putConnectionInstalls).not.toHaveBeenCalled(); + }); }); diff --git a/ui/src/features/connections/ConnectionSetupFlow.tsx b/ui/src/features/connections/ConnectionSetupFlow.tsx index 1408c032466..948968b2362 100644 --- a/ui/src/features/connections/ConnectionSetupFlow.tsx +++ b/ui/src/features/connections/ConnectionSetupFlow.tsx @@ -19,7 +19,7 @@ export { import { bindAccount } from "@/lib/account-scope"; import { StepHeader } from "./ConnectionSetupHeader"; import { GoogleWorkspaceServicesDialog } from "./GoogleWorkspaceServices"; -import type { GoogleWorkspaceServiceSelection } from "@paperclipai/shared"; +import type { GenericMcpProbeResult, GoogleWorkspaceServiceSelection } from "@paperclipai/shared"; export { StepHeader } from "./ConnectionSetupHeader"; import { ConnectionInstructionsEditor } from "./ConnectionInstructions"; import { connectionInstructionsConfig, defaultConnectionAgentInstructions, type ConnectionAgentInstructions } from "@paperclipai/shared"; @@ -298,8 +298,12 @@ export function retainedReconnectMatches(input: { return retainedApplicationMatches(input.reconnectApplication, input.reconnectConnection, input.requestedAppKey); } // Generic MCP applications intentionally have no provider slug. Their - // reconnect URL instead carries the exact retained application identity. - return input.byo && input.applicationId === input.reconnectApplication.id; + // reconnect URL instead carries the exact retained application identity, + // or omits applicationId when linking directly from the custom MCP detail page. + return input.byo + && (!input.reconnectConnection.transport || input.reconnectConnection.transport === "mcp_remote") + && !appConnectionSourceSlug(input.reconnectConnection) + && (!input.applicationId || input.applicationId === input.reconnectApplication.id); } export function isVercelConnectUnavailable(input: { @@ -373,6 +377,7 @@ type AppAccessSelection = "all_agents" | { agentIds: string[] }; // a default, stated in one line above the primary action, and changed either in // the Advanced disclosure on this screen or on the Permissions tab afterwards. const STEP_LABELS = ["Pick app", "Connect"]; +const BYO_STEP_LABELS = ["Server URL", "Connect"]; const STEP_INDEX: Record, number> = { gallery: 0, key: 1, @@ -719,6 +724,7 @@ function StandardConnectionSetupFlow({ const routeStage = searchParams.get("stage")?.trim() || null; const requestedMethodKey = searchParams.get("method")?.trim() || null; const resumeConnectionId = searchParams.get("resume")?.trim() || null; + const editAuthRequested = searchParams.get("editAuth") === "1"; const oauthCallbackOutcome = searchParams.get("oauth"); const oauthCallbackCode = searchParams.get("code"); const oauthCallbackProviderError = allowlistedOAuthProviderError(searchParams.get("provider_error")); @@ -781,8 +787,13 @@ function StandardConnectionSetupFlow({ const [linkHeaders, setLinkHeaders] = useState(() => [newCustomHeaderRow()]); const [linkOAuthClientId, setLinkOAuthClientId] = useState(""); const [linkOAuthClientSecret, setLinkOAuthClientSecret] = useState(""); - const [linkAdvancedOpen, setLinkAdvancedOpen] = useState(false); + const [linkAdvancedOpen, setLinkAdvancedOpen] = useState(editAuthRequested); const [linkGuidance, setLinkGuidance] = useState(null); + const [linkProbing, setLinkProbing] = useState(false); + const [linkProbeResult, setLinkProbeResult] = useState(null); + const linkNameEditedRef = useRef(Boolean(prefill.name)); + const linkAuthManuallyChangedRef = useRef(false); + const probeGuidanceActiveRef = useRef(false); const [genericOAuthPending, setGenericOAuthPending] = useState(false); const [credentials, setCredentials] = useState>({}); const [curatedOAuthClientId, setCuratedOAuthClientId] = useState(""); @@ -1062,11 +1073,46 @@ function StandardConnectionSetupFlow({ if (connectionIntentId || !dialogOAuthConnectionId) return; let cancelled = false; let checking = false; + let detachedTicks = 0; + const finishIfActivated = async (popupToClose: Window | null) => { + checking = true; + try { + const connection = await toolsApi.getConnection(dialogOAuthConnectionId, { fresh: true }); + if (!cancelled && connection.status === "active" && connection.firstSignInPending !== true) { + setDialogOAuthConnectionId(null); + setAuthorizationFallbackUrl(null); + popupToClose?.close(); + if (selectedCompanyId) { + queryClient.invalidateQueries({ queryKey: queryKeys.tools.connection(connection.id) }); + queryClient.invalidateQueries({ queryKey: queryKeys.tools.connections(selectedCompanyId) }); + queryClient.invalidateQueries({ queryKey: queryKeys.apps.attention(selectedCompanyId) }); + } + if (onComplete) onComplete({ connectionId: connection.id }); + else navigate(`/apps/${connection.id}/permissions`); + return true; + } + } catch { + if (!cancelled && popupToClose) { + setDialogOAuthConnectionId(null); + setOAuthPhase("error"); + setOAuthError("Could not confirm the connection. Try again."); + } + } finally { + checking = false; + } + return false; + }; const timer = window.setInterval(async () => { if (checking || cancelled) return; const popup = oauthPopupRef.current; - // Native fallback links have no Window handle; leave their saved flow available. - if (!popup) return; + // When the user opened sign-in via the native new-tab link, there is no + // Window handle to inspect; poll the connection record directly instead. + if (!popup) { + detachedTicks += 1; + if (detachedTicks % 2 !== 0) return; + await finishIfActivated(null); + return; + } if (popup.closed) { setDialogOAuthConnectionId(null); setAuthorizationFallbackUrl(null); @@ -1088,25 +1134,10 @@ function StandardConnectionSetupFlow({ ); return; } - checking = true; - try { - const connection = await toolsApi.getConnection(dialogOAuthConnectionId); - if (!cancelled && connection.status === "active") { - setDialogOAuthConnectionId(null); - popup.close(); - if (onComplete) onComplete({ connectionId: connection.id }); - else navigate(`/apps/${connection.id}/permissions`); - } - } catch { - if (!cancelled) { - setDialogOAuthConnectionId(null); - setOAuthPhase("error"); - setOAuthError("Could not confirm the connection. Try again."); - } - } finally { checking = false; } + await finishIfActivated(popup); }, 1000); return () => { cancelled = true; window.clearInterval(timer); }; - }, [connectionIntentId, dialogOAuthConnectionId, host, onComplete]); + }, [connectionIntentId, dialogOAuthConnectionId, host, navigate, onComplete, queryClient, selectedCompanyId]); const resetGenericAuthState = () => { setLinkAuthMode("auto"); @@ -1425,7 +1456,20 @@ function StandardConnectionSetupFlow({ resumeApplication, completedResumeConnectionId: completedResumeConnectionId ?? completedRouteResumeConnectionId, }) - : false; + : Boolean( + byo + && resumeConnection + && resumeApplication + && resumeConnection.transport === "mcp_remote" + && !appConnectionSourceSlug(resumeConnection) + && !appApplicationSourceSlug(resumeApplication) + && resumeConnection.applicationId === resumeApplication.id + && resumeConnection.companyId === resumeApplication.companyId + && ( + resumeConnection.status === "draft" + || (resumeConnection.status === "active" && resumeConnection.id === (completedResumeConnectionId ?? completedRouteResumeConnectionId)) + ), + ); const identityConnection = resumeConnection ?? reconnectConnection; useEffect(() => { workspaceSelectionRef.current = null; @@ -2030,6 +2074,123 @@ function StandardConnectionSetupFlow({ setHydratedResumeConnectionId(null); }, [resumeConnectionId]); + useEffect(() => { + const savedConnection = resumeConnection ?? reconnectConnection; + if ( + !savedConnection + || requestedAppKey + || !byo + || savedConnection.transport !== "mcp_remote" + || hydratedResumeConnectionIdRef.current === savedConnection.id + ) return; + const savedUrl = savedConnection.config?.url + ?? savedConnection.transportConfig?.url + ?? savedConnection.config?.endpoint + ?? savedConnection.transportConfig?.endpoint + ?? savedConnection.config?.remoteUrl + ?? savedConnection.transportConfig?.remoteUrl; + if (typeof savedUrl === "string" && /^https?:\/\//i.test(savedUrl.trim())) { + setLinkUrl(savedUrl.trim()); + } + if (savedConnection.name?.trim()) { + setLinkName(savedConnection.name.trim()); + linkNameEditedRef.current = true; + } + const hasCustomHeaderRefs = (savedConnection.credentialRefs ?? []).some( + (ref) => ref.placement === "header" && ref.key?.toLowerCase() !== "authorization", + ); + const shouldPrefillExplicitAuth = editAuthRequested || savedConnection.status === "draft"; + const mappedAuth: GenericMcpAuthMode = savedConnection.authKind === "oauth" + ? "oauth" + : shouldPrefillExplicitAuth && hasCustomHeaderRefs + ? "custom_headers" + : shouldPrefillExplicitAuth && savedConnection.authKind === "api_key" + ? "bearer" + : shouldPrefillExplicitAuth && savedConnection.authKind === "none" + ? "none" + : "auto"; + setLinkAuthMode(mappedAuth); + linkAuthManuallyChangedRef.current = mappedAuth !== "auto"; + const oauthRecord = savedConnection.config?.oauth && typeof savedConnection.config.oauth === "object" + ? (savedConnection.config.oauth as { clientId?: unknown; clientRegistrationSource?: unknown }) + : null; + if (oauthRecord?.clientRegistrationSource === "manual" && typeof oauthRecord.clientId === "string") { + setLinkOAuthClientId(oauthRecord.clientId); + } + setGrantKind(grantKindFromConnection(savedConnection)); + if (editAuthRequested) setLinkAdvancedOpen(true); + setStep("key"); + hydratedResumeConnectionIdRef.current = savedConnection.id; + setHydratedResumeConnectionId(savedConnection.id); + }, [byo, editAuthRequested, reconnectConnection, requestedAppKey, resumeConnection]); + + // Read-only background probe for pasted custom MCP URLs: detects OAuth, + // manual OAuth client requirements, bearer keys, or open servers upfront + // without writing any draft rows or triggering dynamic client registration. + useEffect(() => { + const trimmedLink = linkUrl.trim(); + const isValidHttpUrl = (() => { + if (!trimmedLink) return false; + try { + const parsed = new URL(trimmedLink); + return (parsed.protocol === "https:" || parsed.protocol === "http:") && Boolean(parsed.hostname); + } catch { + return false; + } + })(); + if ( + step !== "key" + || entry + || zapierSource + || !isValidHttpUrl + || !selectedCompanyId + || typeof toolsApi.probeGenericMcp !== "function" + ) { + setLinkProbing(false); + return; + } + let cancelled = false; + setLinkProbing(true); + setLinkProbeResult(null); + void toolsApi + .probeGenericMcp(selectedCompanyId, { link: trimmedLink }) + .then((result) => { + if (cancelled || !result) return; + setLinkProbeResult(result); + if (probeGuidanceActiveRef.current) { + probeGuidanceActiveRef.current = false; + setLinkGuidance(null); + } + if (result.suggestedName && !linkNameEditedRef.current) { + setLinkName(result.suggestedName); + } + if (!linkAuthManuallyChangedRef.current) { + if (result.detectedAuth === "bearer") { + setLinkNeedsKey(true); + } else if (result.detectedAuth === "oauth_manual") { + probeGuidanceActiveRef.current = true; + applyGenericConnectGuidance(genericConnectGuidance("oauth_manual_client_required", null)); + } + } + }) + .catch((error) => { + if (cancelled) return; + const { code, providerError, upstreamStatus } = readOAuthApiErrorDetails(error); + const guidance = genericConnectGuidance(code, describeError(error).body, { providerError, upstreamStatus }); + setLinkGuidance((current) => { + if (current) return current; + probeGuidanceActiveRef.current = true; + return guidance; + }); + }) + .finally(() => { + if (!cancelled) setLinkProbing(false); + }); + return () => { + cancelled = true; + }; + }, [entry, linkUrl, selectedCompanyId, step, zapierSource]); + useEffect(() => { const savedConnection = resumeConnection ?? reconnectConnection; if ( @@ -2128,14 +2289,25 @@ function StandardConnectionSetupFlow({ const selection: AppAccessSelection = installChoice === "all" && effectiveGrantKind !== "agent" ? "all_agents" : { agentIds: Array.from(installAgentIds) }; + const preservingSavedAccess = Boolean( + connected.connection.config?.mcpPreserveAccess === true + || ( + editAuthRequested + && reconnectConnection + && reconnectConnection.status !== "archived" + && reconnectConnection.firstSignInPending !== true + ), + ); const finished = await toolsApi.finishApp(selectedCompanyId!, connected.connectionId, { enabledCatalogEntryIds: enabledIds, askFirstCatalogEntryIds: askFirstIds, ...(instructionValue ? { agentInstructions: instructionValue } : {}), access: selection, - ...(requestedAgentId ? { preserveExistingAccess: true } : {}), + ...(requestedAgentId || preservingSavedAccess ? { preserveExistingAccess: true } : {}), }); - await applyAccessInstalls(connected.connectionId); + if (!preservingSavedAccess) { + await applyAccessInstalls(connected.connectionId); + } return finished; }, onSuccess: async (_finished, input) => { @@ -2303,7 +2475,7 @@ function StandardConnectionSetupFlow({ if (resumeConnectionId && ( !connectionsQuery.isFetchedAfterMount || galleryQuery.isLoading - || !entry + || (Boolean(requestedAppKey) && !entry) || hydratedResumeConnectionId !== resumeConnection?.id )) { return ( @@ -2669,9 +2841,9 @@ function StandardConnectionSetupFlow({ name: linkName.trim() || endpointHost(linkUrl) || "this server", unverifiedHost: endpointHost(linkUrl), }} - // A pasted endpoint walks the generic three-step wizard, so keep that - // model rather than dropping to the curated two-step one. - steps={{ labels: STEP_LABELS, activeIndex: STEP_INDEX.key }} + // A pasted endpoint walks the generic wizard, so keep that model rather + // than dropping to the curated one. + steps={{ labels: byo ? BYO_STEP_LABELS : STEP_LABELS, activeIndex: STEP_INDEX.key }} phase={oauthPhase} error={oauthError} authorizationHost={authorizationHost} @@ -2754,6 +2926,8 @@ function StandardConnectionSetupFlow({ ? ["Share sheet"] : entry ? ["Add your key"] + : byo + ? BYO_STEP_LABELS : STEP_LABELS; const stepIndex = reconnectConnection?.connectionPurpose === "ai" ? 0 : (zapierSource || entry) && step !== "gallery" && step !== "success" ? SELECTED_APP_STEP_INDEX[step] @@ -2809,6 +2983,9 @@ function StandardConnectionSetupFlow({ setEntry(null); setGalleryName(""); setLinkUrl(url); + linkNameEditedRef.current = Boolean(matchedEntry?.name); + linkAuthManuallyChangedRef.current = false; + setLinkProbeResult(null); setLinkName(matchedEntry?.name ?? defaultGenericMcpName(url) ?? ""); setLinkNeedsKey(false); setLinkKey(""); @@ -3035,11 +3212,16 @@ function StandardConnectionSetupFlow({ { + linkNameEditedRef.current = true; + setLinkName(next); + }} needsKey={linkNeedsKey} keyValue={linkKey} onKeyChange={setLinkKey} authMode={linkAuthMode} onAuthModeChange={(next) => { + linkAuthManuallyChangedRef.current = next !== "auto"; setLinkAuthMode(next); setLinkGuidance(null); // Leaving the simple path means the explicit choice governs; drop the @@ -3056,14 +3238,25 @@ function StandardConnectionSetupFlow({ onOAuthClientIdChange={setLinkOAuthClientId} oauthClientSecret={linkOAuthClientSecret} onOAuthClientSecretChange={setLinkOAuthClientSecret} - callbackUrl={callbackUrlForSetup} + callbackUrl={linkProbeResult?.oauthCallbackUrl ?? callbackUrlForSetup} advancedOpen={linkAdvancedOpen} onAdvancedOpenChange={setLinkAdvancedOpen} guidance={linkGuidance} + probing={linkProbing} + probeResult={linkProbeResult} matchedEntry={linkMatchedEntry} onUseMatchedEntry={linkMatchedEntry ? () => useMatchedGalleryEntry(linkMatchedEntry) : undefined} submitting={connectMutation.isPending || genericOAuthPending} - defaults={connectionDefaults} + defaults={ + editAuthRequested + && reconnectConnection + && reconnectConnection.status !== "archived" + && reconnectConnection.firstSignInPending !== true + ?

+ Your existing agent access and action permissions will stay unchanged. +

+ : connectionDefaults + } onBack={backToGallery} onConnect={() => { setLinkGuidance(null); @@ -3174,6 +3367,7 @@ export function OAuthConnectStateScreen({ }) { const serverName = entry?.name ?? identity?.name ?? "this server"; const unverifiedHost = entry ? null : identity?.unverifiedHost ?? null; + const approvalAction = entry ? "choose a workspace and approve access" : "sign in and approve access"; const status = phase === "entry" ? { title: resuming @@ -3181,7 +3375,7 @@ export function OAuthConnectStateScreen({ : `Connect ${serverName} to Paperclip`, body: resuming ? `Your connection is saved. Continue in ${serverName} to approve access; its identity and agent access will stay the same.` - : `Paperclip will open ${serverName} so you can choose a workspace and approve access.`, + : `Paperclip will open ${serverName} so you can ${approvalAction}.`, } : phase === "starting" ? { @@ -3190,10 +3384,10 @@ export function OAuthConnectStateScreen({ } : phase === "redirecting" ? { - title: `Opening ${serverName}`, + title: `Waiting for ${serverName}`, body: authorizationHost - ? `Continue at ${authorizationHost} to choose a workspace and approve access. Only approve access if you recognize that address.` - : `Continue in ${serverName} to choose a workspace and approve access.`, + ? `Continue at ${authorizationHost} to ${approvalAction}. Only approve access if you recognize that address.` + : `Continue in ${serverName} to ${approvalAction}.`, } : { title: `${serverName} couldn’t connect`, @@ -3225,7 +3419,6 @@ export function OAuthConnectStateScreen({

{status.title}

{status.body}

- {unverifiedHost ? : null}
@@ -3252,7 +3445,7 @@ export function OAuthConnectStateScreen({ ) : null} -
+
{phase === "error" || phase === "entry" ? ( + ) : phase === "redirecting" && authorizationUrl ? ( + ) : ( )} - {authorizationUrl ? : null} + {authorizationUrl && (phase === "error" || phase === "entry") ? ( + + ) : null}
@@ -3516,7 +3722,7 @@ function GalleryStep({ {zapierSource ? "Paste the complete MCP URL Zapier gives you, including its token." : byo - ? "Paste your MCP server’s URL and every discovered tool will be available immediately." + ? "Paste your MCP server’s URL. Paperclip detects how it signs in and discovers its tools." : "Paste a setup link from an app that is not listed here."}

{!zapierSource && ( diff --git a/ui/src/features/connections/GenericMcpConnectStep.tsx b/ui/src/features/connections/GenericMcpConnectStep.tsx index c1244bae8af..0b56a38354d 100644 --- a/ui/src/features/connections/GenericMcpConnectStep.tsx +++ b/ui/src/features/connections/GenericMcpConnectStep.tsx @@ -1,6 +1,6 @@ import { useState, type KeyboardEvent, type ReactNode } from "react"; import { Check, Copy, Loader2, Plus, X } from "lucide-react"; -import type { AppDefinition, ConnectToolAppResult } from "@paperclipai/shared"; +import type { AppDefinition, ConnectToolAppResult, GenericMcpProbeResult } from "@paperclipai/shared"; import { InlineBanner } from "@/components/InlineBanner"; import { Button } from "@/components/ui/button"; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; @@ -59,6 +59,7 @@ export function genericMcpAuthSummary(input: { authMode: GenericMcpAuthMode; headers: CustomHeaderRow[]; oauthClientId: string; + probeResult?: GenericMcpProbeResult | null; }): string { switch (input.authMode) { case "none": @@ -75,8 +76,30 @@ export function genericMcpAuthSummary(input: { return input.oauthClientId.trim() ? "You’ll sign in at the provider, using your own client ID." : "You’ll sign in at the provider."; - default: + default: { + const probe = input.probeResult; + if (probe) { + if (probe.detectedAuth === "oauth_auto") { + return probe.authorizationHost + ? `Browser sign-in detected at ${probe.authorizationHost}.` + : "Browser sign-in detected."; + } + if (probe.detectedAuth === "oauth_manual") { + return probe.authorizationHost + ? `Browser sign-in at ${probe.authorizationHost} needs a client ID.` + : "Browser sign-in needs a client ID."; + } + if (probe.detectedAuth === "bearer") { + return "Detected key or token authentication."; + } + if (probe.detectedAuth === "none") { + return probe.toolCount != null + ? `No sign-in needed · ${probe.toolCount} ${probe.toolCount === 1 ? "tool" : "tools"} found.` + : "No sign-in needed. Ready to connect."; + } + } return "Paperclip asks the server how to sign in."; + } } } @@ -96,6 +119,7 @@ export function genericMcpAuthSummary(input: { export function GenericMcpConnectStep({ link, name, + onNameChange, needsKey, keyValue, onKeyChange, @@ -111,6 +135,8 @@ export function GenericMcpConnectStep({ advancedOpen, onAdvancedOpenChange, guidance, + probing = false, + probeResult = null, matchedEntry, onUseMatchedEntry, submitting, @@ -121,6 +147,7 @@ export function GenericMcpConnectStep({ }: { link: string; name: string; + onNameChange?: (next: string) => void; /** Set by the server's probe after a credential challenge, never guessed. */ needsKey: boolean; keyValue: string; @@ -137,6 +164,8 @@ export function GenericMcpConnectStep({ advancedOpen: boolean; onAdvancedOpenChange: (next: boolean) => void; guidance: GenericConnectGuidance | null; + probing?: boolean; + probeResult?: GenericMcpProbeResult | null; /** A curated app whose endpoint matches, offered as a convenience only. */ matchedEntry?: AppDefinition | null; onUseMatchedEntry?: () => void; @@ -365,6 +394,23 @@ export function GenericMcpConnectStep({

{displayedLink}

+ {onNameChange ? ( +
+ + onNameChange(event.target.value)} + placeholder="Name for this connection" + autoComplete="off" + className="mt-2 h-10" + disabled={submitting} + /> +
+ ) : null} + {matchedEntry && onUseMatchedEntry ? (
@@ -392,8 +438,17 @@ export function GenericMcpConnectStep({ className="mt-6 rounded-lg border border-border bg-muted/30 px-4 py-3" >
-

- {expanded ? "How does this server sign in?" : genericMcpAuthSummary({ authMode, headers, oauthClientId })} +

+ {!expanded && probing && authMode === "auto" && !probeResult ? ( + <> +

: null; - return { reserve, open, cancel, fallback, windowRef: popup }; + return { reserve, open, cancel, fallback, fallbackUrl, windowRef: popup }; } diff --git a/ui/src/pages/apps/AppDetail.test.tsx b/ui/src/pages/apps/AppDetail.test.tsx new file mode 100644 index 00000000000..e95d9feea5e --- /dev/null +++ b/ui/src/pages/apps/AppDetail.test.tsx @@ -0,0 +1,571 @@ +// @vitest-environment jsdom +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { MemoryRouter, Route, Routes } from "react-router-dom"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { ConnectionGrantsResponse, ToolConnection } from "@paperclipai/shared"; +import { ApiError } from "@/api/client"; +import { toolsApi } from "@/api/tools"; +import { agentsApi } from "@/api/agents"; +import { accessApi } from "@/api/access"; +import { AppDetail } from "./AppDetail"; + +vi.mock("@/lib/router", async () => { + const actual = await vi.importActual("react-router-dom"); + return { + Link: actual.Link, + Navigate: actual.Navigate, + useNavigate: actual.useNavigate, + useParams: actual.useParams, + useSearchParams: actual.useSearchParams, + }; +}); + +vi.mock("@/context/CompanyContext", () => ({ + useCompany: () => ({ selectedCompanyId: "company-1" }), +})); + +vi.mock("@/context/BreadcrumbContext", () => ({ + useBreadcrumbs: () => ({ setBreadcrumbs: vi.fn() }), +})); + +const pushToastMock = vi.fn(); +vi.mock("@/context/ToastContext", () => ({ + useToast: () => ({ pushToast: pushToastMock }), +})); + +const authReserveMock = vi.fn(); +const authOpenMock = vi.fn().mockResolvedValue({ kind: "authorization", url: "https://api.spreadjam.com/oauth/authorize" }); +const authCancelMock = vi.fn(); +const authWindowMock = { + reserve: authReserveMock, + open: authOpenMock, + cancel: authCancelMock, + fallback: null, + fallbackUrl: null, + windowRef: { current: null }, +}; +vi.mock("@/hooks/useAuthorizationWindow", () => ({ + useAuthorizationWindow: () => authWindowMock, +})); + +vi.mock("@/features/connections/GoogleWorkspaceServices", () => ({ + useGoogleWorkspaceServiceGate: () => ({ + dialog: null, + run: (_connection: unknown, next: () => void) => next(), + }), +})); + +function makeCustomMcpConnection(overrides: Partial = {}): ToolConnection { + const now = new Date("2026-12-04T20:00:00.000Z"); + return { + id: "conn-spreadjam-1", + uid: "app-gallery:link:app-1/spreadjam", + companyId: "company-1", + applicationId: "app-1", + name: "SpreadJam", + transport: "mcp_remote", + authKind: "oauth", + ownership: "customer", + credentialSource: "paperclip_vault", + credentialPolicy: "shared", + connectionPurpose: "tool", + status: "draft", + enabled: false, + firstSignInPending: true, + healthStatus: "error", + healthMessage: "This app needs you to sign in.", + lastError: "This app needs you to sign in.", + healthCheckedAt: now, + lastHealthAt: now, + lastCatalogRefreshAt: null, + config: { + url: "https://api.spreadjam.com/mcp", + unverifiedServer: true, + oauth: { + provider: "api_spreadjam_com", + issuer: "https://api.spreadjam.com", + authorizationUrl: "https://api.spreadjam.com/oauth/authorize", + tokenUrl: "https://api.spreadjam.com/oauth/token", + }, + }, + transportConfig: { + url: "https://api.spreadjam.com/mcp", + unverifiedServer: true, + }, + credentialRefs: [], + credentialSecretRefs: [], + installs: [], + createdByAgentId: null, + createdByUserId: "user-1", + createdAt: now, + updatedAt: now, + ...overrides, + } as ToolConnection; +} + +function makeGrantsResponse(overrides: Partial = {}): ConnectionGrantsResponse { + return { + connection: { id: "conn-spreadjam-1", uid: "app-gallery:link:app-1/spreadjam" }, + grants: [ + { + id: "grant-org-1", + companyId: "company-1", + connectionId: "conn-spreadjam-1", + kind: "organization", + subjectUserId: null, + subjectAgentId: null, + providerTenant: { oauth: {} }, + credentialSecretRefs: [], + externalCredential: null, + status: "active", + isDefault: true, + createdByAgentId: null, + createdByUserId: null, + revokedAt: null, + revokedByAgentId: null, + revokedByUserId: null, + lastUsedAt: null, + createdAt: new Date("2026-12-04T20:00:00.000Z"), + updatedAt: new Date("2026-12-04T20:00:00.000Z"), + members: [], + delegations: [], + capabilities: { canRevoke: true, canEditAudience: true }, + }, + ], + capabilities: { + canConfigure: true, + canCreateOrganizationGrant: true, + canSetCompanyInstall: true, + canConnectAsCurrentUser: true, + canManageAgentInstalls: true, + canViewOtherPersonalIdentities: true, + editableAgentIds: [], + }, + currentUserId: "user-1", + members: [{ userId: "user-1", name: "Dotta", email: "dotta@example.com" }], + dedicatedAgentIds: [], + canShareDedicatedIdentity: false, + ...overrides, + } as ConnectionGrantsResponse; +} + +let container: HTMLDivElement | null = null; +let root: ReturnType | null = null; + +async function flush() { + for (let i = 0; i < 6; i += 1) { + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + } +} + +async function renderAppDetail(initialEntry: string) { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + const queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false }, + mutations: { retry: false }, + }, + }); + await act(async () => { + root!.render( + + + + } /> + + + , + ); + }); + await flush(); + return container; +} + +function setupDefaultMocks(connection: ToolConnection, options: { + catalogError?: Error; + grants?: ConnectionGrantsResponse; +} = {}) { + vi.spyOn(toolsApi, "getConnection").mockResolvedValue(connection); + vi.spyOn(toolsApi, "listApplications").mockResolvedValue({ + applications: [{ id: "app-1", companyId: "company-1", name: "SpreadJam", type: "mcp_remote", status: "draft" }], + } as never); + vi.spyOn(toolsApi, "getConnectionInstalls").mockResolvedValue({ connectionId: connection.id, installs: [] }); + vi.spyOn(toolsApi, "listGallery").mockResolvedValue({ + apps: [], + capabilities: { canCreateOrganizationGrant: true, organizationGrantReason: null, canSetCompanyInstall: true, companyInstallReason: null }, + credentialSources: { vercelConnect: { available: false, enabled: false, authentication: null, manageUrl: "", reason: null } }, + } as never); + if (options.catalogError) { + vi.spyOn(toolsApi, "listCatalog").mockRejectedValue(options.catalogError); + } else { + vi.spyOn(toolsApi, "listCatalog").mockResolvedValue({ catalog: [] }); + } + vi.spyOn(toolsApi, "listConnectionProfileConfiguration").mockResolvedValue({ profiles: [] } as never); + vi.spyOn(toolsApi, "listPolicies").mockResolvedValue({ policies: [] }); + vi.spyOn(toolsApi, "getConnectionReviewCounts").mockResolvedValue({ + pendingActionRequestCount: 0, + quarantinedCatalogEntryCount: 0, + } as never); + vi.spyOn(toolsApi, "listConnectionGrants").mockResolvedValue(options.grants ?? makeGrantsResponse()); + vi.spyOn(agentsApi, "list").mockResolvedValue([]); + vi.spyOn(accessApi, "listUserDirectory").mockResolvedValue({ + users: [{ principalId: "user-1", user: { id: "user-1", name: "Dotta", email: "dotta@example.com", image: null } }], + } as never); +} + +describe("AppDetail custom MCP draft setup and error recovery", () => { + beforeEach(() => { + pushToastMock.mockReset(); + }); + + afterEach(async () => { + await act(async () => { + root?.unmount(); + }); + container?.remove(); + container = null; + root = null; + vi.restoreAllMocks(); + }); + + it("renders Setup incomplete with Sign in, Change sign-in method, and Remove for a shared custom MCP OAuth draft", async () => { + const connection = makeCustomMcpConnection(); + setupDefaultMocks(connection); + const startOAuthSpy = vi.spyOn(toolsApi, "startOAuth").mockResolvedValue({ + connectionId: connection.id, + provider: "api_spreadjam_com", + authorizationUrl: "https://api.spreadjam.com/oauth/authorize", + expiresAt: null, + }); + + const el = await renderAppDetail(`/apps/${connection.id}/permissions`); + + expect(el.textContent).toContain("Setup incomplete"); + expect(el.textContent).not.toContain("Paused"); + expect(el.textContent).not.toContain("Couldn't load tools for this app"); + expect(el.textContent).toContain("api.spreadjam.com"); + + const signInButton = Array.from(el.querySelectorAll("button")).find((button) => + /Sign in/i.test(button.textContent ?? ""), + ); + expect(signInButton).toBeTruthy(); + + await act(async () => { + signInButton!.click(); + }); + await flush(); + expect(startOAuthSpy).toHaveBeenCalledWith(connection.id, undefined); + + const changeAuthLink = Array.from(el.querySelectorAll("a")).find((link) => + /Change sign-in method/i.test(link.textContent ?? ""), + ); + expect(changeAuthLink).toBeTruthy(); + expect(changeAuthLink?.getAttribute("href")).toContain(`/apps/byo?resume=${connection.id}`); + expect(changeAuthLink?.getAttribute("href")).toContain("editAuth=1"); + + const removeButton = Array.from(el.querySelectorAll("button")).find((button) => + /Remove/i.test(button.textContent ?? ""), + ); + expect(removeButton).toBeTruthy(); + }); + + it("starts personal OAuth when signing in to a personal custom MCP OAuth draft", async () => { + const connection = makeCustomMcpConnection({ credentialPolicy: "per_user" }); + setupDefaultMocks(connection, { grants: makeGrantsResponse({ grants: [] }) }); + const startPersonalSpy = vi.spyOn(toolsApi, "startPersonalAuthorization").mockResolvedValue({ + url: "https://api.spreadjam.com/oauth/authorize", + } as never); + + const el = await renderAppDetail(`/apps/${connection.id}/permissions`); + + const signInButton = Array.from(el.querySelectorAll("button")).find((button) => + /Sign in/i.test(button.textContent ?? ""), + ); + expect(signInButton).toBeTruthy(); + await act(async () => { + signInButton!.click(); + }); + await flush(); + expect(startPersonalSpy).toHaveBeenCalledWith( + "company-1", + connection.id, + expect.objectContaining({ subjectUserId: "user-1" }), + ); + }); + + it("shows an actionable recovery message when redirected back with oauth=failed query params", async () => { + const connection = makeCustomMcpConnection(); + setupDefaultMocks(connection); + + const el = await renderAppDetail( + `/apps/${connection.id}/permissions?oauth=failed&code=oauth_token_exchange_failed&provider_error=invalid_redirect_uri`, + ); + + expect(el.textContent).toContain("callback URL"); + const changeAuthLink = Array.from(el.querySelectorAll("a")).find((link) => + /Change sign-in method/i.test(link.textContent ?? ""), + ); + expect(changeAuthLink).toBeTruthy(); + }); + + it("keeps recovery controls visible when catalog loading fails with an expired-credential error", async () => { + const connection = makeCustomMcpConnection({ + status: "active", + enabled: false, + firstSignInPending: false, + healthStatus: "failed", + healthMessage: "OAuth credentials have expired and need to be reconnected.", + }); + const catalogError = new ApiError( + "OAuth credentials have expired and need to be reconnected.", + 422, + { code: "oauth_refresh_missing" }, + ); + setupDefaultMocks(connection, { catalogError }); + + const el = await renderAppDetail(`/apps/${connection.id}/permissions`); + + expect(el.textContent).toContain("Reconnect required"); + expect(el.textContent).not.toContain("Couldn't load tools for this app"); + const reconnectButtons = Array.from(el.querySelectorAll("button")).filter((button) => + /Reconnect/i.test(button.textContent ?? ""), + ); + expect(reconnectButtons.length).toBeGreaterThan(0); + const changeAuthLinks = Array.from(el.querySelectorAll("a")).filter((link) => + /Change sign-in method/i.test(link.textContent ?? ""), + ); + expect(changeAuthLinks.length).toBeGreaterThan(0); + }); + + it("renders connection details and danger zone controls for an active custom remote MCP connection", async () => { + const connection = makeCustomMcpConnection({ + status: "active", + enabled: true, + firstSignInPending: false, + healthStatus: "ok", + healthMessage: "Tool catalog refreshed.", + }); + setupDefaultMocks(connection); + + const el = await renderAppDetail(`/apps/${connection.id}/permissions`); + + expect(el.textContent).toContain("Connected"); + expect(el.textContent).toContain("Connection details"); + expect(el.textContent).toContain("Danger zone"); + const changeAuthLink = Array.from(el.querySelectorAll("a")).find((link) => + /Change sign-in method/i.test(link.textContent ?? ""), + ); + expect(changeAuthLink).toBeTruthy(); + expect(changeAuthLink?.getAttribute("href")).toContain(`/apps/byo?reconnect=${connection.id}`); + }); + + it("requires choosing an agent before starting OAuth on a first-time per_agent draft", async () => { + const connection = makeCustomMcpConnection({ + credentialPolicy: "per_agent", + }); + setupDefaultMocks(connection); + vi.spyOn(agentsApi, "list").mockResolvedValue([ + { + id: "agent-1", + name: "Growth Agent", + title: "SEO", + icon: null, + } as unknown as Awaited>[number], + ]); + const startOAuthSpy = vi.spyOn(toolsApi, "startOAuth").mockResolvedValue({ + connectionId: connection.id, + provider: "api_spreadjam_com", + authorizationUrl: "https://api.spreadjam.com/oauth/authorize", + expiresAt: "2099-01-01T00:00:00.000Z", + }); + + const el = await renderAppDetail(`/apps/${connection.id}/permissions`); + + expect(el.textContent).toContain("Agent for this connection"); + const signInButton = Array.from(el.querySelectorAll("button")).find((button) => + button.textContent?.includes("Sign in to SpreadJam"), + ) as HTMLButtonElement | undefined; + expect(signInButton).toBeTruthy(); + expect(signInButton?.disabled).toBe(true); + expect(startOAuthSpy).not.toHaveBeenCalled(); + + // Open the AgentSelect popover and choose Growth Agent. + const pickerTrigger = el.querySelector("#draft-dedicated-agent"); + expect(pickerTrigger).toBeTruthy(); + await act(async () => { + pickerTrigger!.click(); + }); + const agentOption = Array.from(document.body.querySelectorAll("button")).find((button) => + button.textContent?.includes("Growth Agent"), + ); + expect(agentOption).toBeTruthy(); + await act(async () => { + agentOption!.click(); + }); + + expect(signInButton?.disabled).toBe(false); + await act(async () => { + signInButton!.click(); + }); + + expect(startOAuthSpy).toHaveBeenCalledWith(connection.id, { asAgentId: "agent-1" }); + }); + + it("does not prematurely cancel consent when adding a personal identity to an already-active connection", async () => { + authCancelMock.mockClear(); + const connection = makeCustomMcpConnection({ + status: "active", + enabled: true, + firstSignInPending: false, + healthStatus: "ok", + credentialPolicy: "per_user", + }); + setupDefaultMocks(connection, { + grants: makeGrantsResponse({ grants: [] }), + }); + vi.spyOn(toolsApi, "startPersonalAuthorization").mockResolvedValue({ + url: "https://api.spreadjam.com/oauth/authorize", + }); + const listGrantsSpy = vi.spyOn(toolsApi, "listConnectionGrants") + .mockResolvedValueOnce(makeGrantsResponse({ grants: [] })) + .mockResolvedValueOnce(makeGrantsResponse({ grants: [] })) + .mockResolvedValue( + makeGrantsResponse({ + grants: [ + { + id: "grant-user-1", + companyId: "company-1", + connectionId: connection.id, + kind: "user", + status: "active", + subjectUserId: "user-1", + subjectAgentId: null, + isDefault: false, + providerTenant: null, + updatedAt: new Date("2026-12-04T20:05:00.000Z"), + createdAt: new Date("2026-12-04T20:05:00.000Z"), + } as unknown as ConnectionGrantsResponse["grants"][number], + ], + }), + ); + + const el = await renderAppDetail(`/apps/${connection.id}/permissions`); + const connectAsMe = Array.from(el.querySelectorAll("button")).find((button) => + /Connect (your account|as me)/i.test(button.textContent ?? ""), + ); + expect(connectAsMe).toBeTruthy(); + + vi.useFakeTimers(); + try { + await act(async () => { + connectAsMe!.click(); + await Promise.resolve(); + await Promise.resolve(); + }); + + // After first poll tick (grant still missing), consent MUST stay open. + await act(async () => { + await vi.advanceTimersByTimeAsync(2_600); + }); + expect(authCancelMock).not.toHaveBeenCalled(); + expect(el.textContent).toContain("Waiting for sign-in to finish"); + + // Once the user's new active grant appears on a later poll, sign-in completes cleanly. + await act(async () => { + await vi.advanceTimersByTimeAsync(2_600); + }); + expect(listGrantsSpy).toHaveBeenCalled(); + expect(authCancelMock).toHaveBeenCalledTimes(1); + } finally { + vi.useRealTimers(); + } + }); + + it("stops waiting when a callback failure arrives over BroadcastChannel or when cancelled", async () => { + const channels: Array<{ name: string; onmessage: ((event: MessageEvent) => void) | null; postMessage: (data: unknown) => void; close: () => void }> = []; + class MockBroadcastChannel { + onmessage: ((event: MessageEvent) => void) | null = null; + constructor(public name: string) { + channels.push(this); + } + postMessage(data: unknown) { + for (const ch of channels) { + if (ch !== this && ch.name === this.name) { + ch.onmessage?.({ data } as MessageEvent); + } + } + } + close() { + const idx = channels.indexOf(this); + if (idx >= 0) channels.splice(idx, 1); + } + } + vi.stubGlobal("BroadcastChannel", MockBroadcastChannel); + try { + authCancelMock.mockClear(); + const connection = makeCustomMcpConnection(); + setupDefaultMocks(connection); + vi.spyOn(toolsApi, "startOAuth").mockResolvedValue({ + connectionId: connection.id, + provider: "api_spreadjam_com", + authorizationUrl: "https://api.spreadjam.com/oauth/authorize", + expiresAt: "2099-01-01T00:00:00.000Z", + }); + + const el = await renderAppDetail(`/apps/${connection.id}/permissions`); + const signInButton = Array.from(el.querySelectorAll("button")).find((button) => + button.textContent?.includes("Sign in to SpreadJam"), + ); + expect(signInButton).toBeTruthy(); + + await act(async () => { + signInButton!.click(); + await Promise.resolve(); + await Promise.resolve(); + }); + expect(el.textContent).toContain("Waiting for sign-in to finish"); + + // Simulate the callback tab announcing a denied OAuth return. + await act(async () => { + const sender = new MockBroadcastChannel("paperclip.app-oauth-outcome"); + sender.postMessage({ + connectionId: connection.id, + outcome: "denied", + code: null, + providerError: "access_denied", + }); + sender.close(); + }); + + expect(el.textContent).not.toContain("Waiting for sign-in to finish"); + expect(authCancelMock).toHaveBeenCalledTimes(1); + expect(el.querySelector('[role="alert"]')?.textContent).toBeTruthy(); + } finally { + vi.unstubAllGlobals(); + } + }); + + it("keeps Identities, Permissions, and Danger zone accessible when a previously authorized connection returns to draft for reauthorization", async () => { + const connection = makeCustomMcpConnection({ + status: "draft", + enabled: false, + firstSignInPending: false, + healthStatus: "error", + healthMessage: "Access to this app ended. Reconnect to continue.", + }); + setupDefaultMocks(connection); + + const el = await renderAppDetail(`/apps/${connection.id}/permissions`); + + expect(el.textContent).toContain("Needs attention"); + expect(el.textContent).toContain("Reconnect required"); + expect(el.textContent).not.toContain("Finish connecting SpreadJam"); + expect(el.textContent).toContain("Danger zone"); + }); +}); diff --git a/ui/src/pages/apps/AppDetail.tsx b/ui/src/pages/apps/AppDetail.tsx index 96c4c7320fc..f81edba0037 100644 --- a/ui/src/pages/apps/AppDetail.tsx +++ b/ui/src/pages/apps/AppDetail.tsx @@ -71,21 +71,75 @@ import { actionPermissionMutation } from "./app-detail/action-permissions"; import { RailwayAccessPanel } from "./app-detail/RailwayAccessPanel"; import { ReviewPanel } from "./app-detail/ReviewPanel"; import { AccessRetryBanner } from "./app-detail/AccessRetryBanner"; +import { CatalogErrorActions, FinishSetupCard } from "./app-detail/DraftAndErrorCards"; import { StoredContentDeletionRow } from "./app-detail/StoredContentDeletion"; import { + AdvancedPanel, ReconnectCard, DangerZone, + TechnicalDetails, connectionAddress, connectionTransportLabel, } from "./app-detail/AdvancedPanel"; +import { + oauthCallbackErrorMessage, + oauthStartFailureMessage, + readOAuthApiErrorDetails, +} from "@/features/connections/oauthFailureMessages"; import type { AccessDraft } from "./app-detail/types"; import { connectionDisplayNameForOwner, connectionOwnerProfile, } from "./connection-owner"; -import { describeError } from "@/api/errors"; +import { describeError, errorStatus } from "@/api/errors"; import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +const APP_OAUTH_OUTCOME_CHANNEL = "paperclip.app-oauth-outcome"; +const OAUTH_POLL_TIMEOUT_MS = 5 * 60 * 1000; +const OAUTH_MAX_CONSECUTIVE_POLL_ERRORS = 3; + +type PendingOAuthAttempt = + | { kind: "activate_connection"; startedAt: number } + | { + kind: "reconnect_connection"; + startedAt: number; + baselineUpdatedAt: string | null; + baselineWasAttention: boolean; + } + | { + kind: "personal_grant"; + startedAt: number; + subjectUserId: string; + baselineGrantId: string | null; + baselineGrantStatus: string | null; + baselineGrantUpdatedAt: string | null; + } + | { + kind: "agent_grant"; + startedAt: number; + subjectAgentId: string; + baselineGrantId: string | null; + baselineGrantStatus: string | null; + baselineGrantUpdatedAt: string | null; + }; + +type OAuthOutcomeBroadcast = { + connectionId: string; + outcome: "connected" | "failed" | "denied"; + code: string | null; + providerError: string | null; +}; + +function toTimestampString(value: Date | string | null | undefined): string | null { + if (value instanceof Date) return value.toISOString(); + return typeof value === "string" && value.trim() ? value : null; +} + +function isFirstSignInDraft(connection: ToolConnection): boolean { + return connection.status === "draft" + && (connection.firstSignInPending === true || connection.authKind !== "oauth"); +} + export { connectionAddress, connectionTransportLabel }; export function AppDetail(props: { renderActions?: (connection: ToolConnection) => ReactNode; renderAgentSettings?: (connection: ToolConnection) => ReactNode; renderConnectionSettings?: (connection: ToolConnection) => ReactNode; onReconnect?: (connection: ToolConnection) => void } = {}) { @@ -367,25 +421,148 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio }); const authorization = useAuthorizationWindow(); + const { cancel: cancelAuthorization } = authorization; const workspaceGate = useGoogleWorkspaceServiceGate(); + const [signInError, setSignInError] = useState(null); + const [draftDedicatedAgentId, setDraftDedicatedAgentId] = useState(""); + const [pendingOAuthAttempt, setPendingOAuthAttempt] = useState(null); + const [dismissedOAuthNotice, setDismissedOAuthNotice] = useState(false); + const oauthOutcome = searchParams.get("oauth"); + const oauthCode = searchParams.get("code"); + const oauthProviderError = searchParams.get("provider_error"); + const oauthReturnMessage = + !dismissedOAuthNotice && (oauthOutcome === "failed" || oauthOutcome === "denied") + ? oauthCallbackErrorMessage(oauthOutcome, oauthCode, oauthProviderError) + : null; + + // Broadcast callback outcomes across same-origin tabs so a waiting opener + // stops immediately on denial/failure even when COOP severs window.opener. + useEffect(() => { + if (!connectionId) return; + if (oauthOutcome !== "connected" && oauthOutcome !== "failed" && oauthOutcome !== "denied") return; + setPendingOAuthAttempt(null); + if (typeof BroadcastChannel === "undefined") return; + try { + const channel = new BroadcastChannel(APP_OAUTH_OUTCOME_CHANNEL); + const message: OAuthOutcomeBroadcast = { + connectionId, + outcome: oauthOutcome, + code: oauthCode, + providerError: oauthProviderError, + }; + channel.postMessage(message); + channel.close(); + } catch { + // BroadcastChannel may be unavailable in restricted contexts. + } + }, [connectionId, oauthCode, oauthOutcome, oauthProviderError]); + + const clearOAuthReturnParams = useCallback(() => { + setDismissedOAuthNotice(true); + if (searchParams.has("oauth") || searchParams.has("code") || searchParams.has("provider_error")) { + navigate(appTabHref(connectionId, "permissions"), { replace: true }); + } + }, [connectionId, navigate, searchParams]); + + const cancelPendingOAuth = useCallback(() => { + setPendingOAuthAttempt(null); + cancelAuthorization(); + }, [cancelAuthorization]); + + const buildOAuthAttempt = useCallback((options?: { asAgentId?: string; asPersonalUserId?: string }): PendingOAuthAttempt => { + const startedAt = Date.now(); + if (connection && isFirstSignInDraft(connection)) { + return { kind: "activate_connection", startedAt }; + } + if (options?.asPersonalUserId) { + const existing = grantRows.find( + (grant) => grant.kind === "user" && grant.subjectUserId === options.asPersonalUserId, + ) ?? null; + return { + kind: "personal_grant", + startedAt, + subjectUserId: options.asPersonalUserId, + baselineGrantId: existing?.id ?? null, + baselineGrantStatus: existing?.status ?? null, + baselineGrantUpdatedAt: toTimestampString(existing?.updatedAt), + }; + } + if (options?.asAgentId) { + const existing = grantRows.find( + (grant) => grant.kind === "agent" && grant.subjectAgentId === options.asAgentId, + ) ?? null; + return { + kind: "agent_grant", + startedAt, + subjectAgentId: options.asAgentId, + baselineGrantId: existing?.id ?? null, + baselineGrantStatus: existing?.status ?? null, + baselineGrantUpdatedAt: toTimestampString(existing?.updatedAt), + }; + } + return { + kind: "reconnect_connection", + startedAt, + baselineUpdatedAt: toTimestampString(connection?.updatedAt), + baselineWasAttention: Boolean( + connection && (isAttentionHealthStatus(connection.healthStatus) || connection.requiresReauthorization), + ), + }; + }, [connection, grantRows]); + + const toggleConnection = useMutation({ + mutationFn: () => + toolsApi.updateConnection(connectionId, { + enabled: !(connection?.enabled ?? true), + }), + onSuccess: (updated) => { + queryClient.invalidateQueries({ queryKey: queryKeys.tools.connection(connectionId) }); + queryClient.invalidateQueries({ queryKey: queryKeys.tools.connections(selectedCompanyId!) }); + queryClient.invalidateQueries({ queryKey: queryKeys.apps.attention(selectedCompanyId!) }); + pushToast({ + title: updated.enabled ? `${appName} resumed` : `${appName} paused`, + body: updated.enabled + ? "Agents can use this app again." + : "Agents can’t use this app while it’s paused.", + tone: "success", + }); + }, + onError: (error) => + pushToast({ + title: "Couldn't update the connection", + body: describeError(error).body, + tone: "error", + }), + }); + const startOAuth = useMutation({ - mutationFn: (input?: { asAgentId?: string; workspaceServices?: GoogleWorkspaceServiceSelection }) => toolsApi.startOAuth(connectionId, input), - onSuccess: async (start) => { + mutationFn: (input?: { asAgentId?: string; workspaceServices?: GoogleWorkspaceServiceSelection }) => { + setSignInError(null); + clearOAuthReturnParams(); + return toolsApi.startOAuth(connectionId, input); + }, + onSuccess: async (start, variables) => { try { await authorization.open(start); + setPendingOAuthAttempt(buildOAuthAttempt({ asAgentId: variables?.asAgentId })); } catch (error) { + const message = oauthStartFailureMessage(error, describeError(error).body); + setSignInError(message); pushToast({ title: "Couldn't start sign-in", - body: describeError(error).body, + body: message, tone: "error", }); } }, onError: (error) => { authorization.cancel(); + setPendingOAuthAttempt(null); + const message = oauthStartFailureMessage(error, describeError(error).body); + setSignInError(message); pushToast({ title: "Couldn't start sign-in", - body: describeError(error).body, + body: message, tone: "error", }); }, @@ -402,36 +579,162 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio * there is no path here to start consent on a coworker's behalf. */ const startPersonalAuth = useMutation({ - mutationFn: (scopes?: string[]) => { + mutationFn: async (scopes?: string[]) => { + setSignInError(null); + clearOAuthReturnParams(); const subjectUserId = grantsQuery.data?.currentUserId; if (!subjectUserId) throw new Error("Sign in again to connect your own account."); - return toolsApi.startPersonalAuthorization(selectedCompanyId!, connectionId, { + const start = await toolsApi.startPersonalAuthorization(selectedCompanyId!, connectionId, { subjectUserId, returnTo: appTabHref(connectionId, "permissions"), ...(scopes ? { scopes } : {}), }); + return { ...start, subjectUserId }; }, - onSuccess: async ({ url, handoff }) => { + onSuccess: async ({ url, handoff, subjectUserId }) => { try { await authorization.open({ authorizationUrl: url, handoff }); + setPendingOAuthAttempt(buildOAuthAttempt({ asPersonalUserId: subjectUserId })); } catch (error) { + const message = oauthStartFailureMessage(error, describeError(error).body); + setSignInError(message); pushToast({ title: "Couldn't start sign-in", - body: describeError(error).body, + body: message, tone: "error", }); } }, onError: (error) => { authorization.cancel(); + setPendingOAuthAttempt(null); + const message = oauthStartFailureMessage(error, describeError(error).body); + setSignInError(message); pushToast({ title: "Couldn't start sign-in", - body: describeError(error).body, + body: message, tone: "error", }); }, }); + useEffect(() => { + if (!pendingOAuthAttempt || !connectionId || !selectedCompanyId) return; + let cancelled = false; + let consecutiveErrors = 0; + + const completeSignIn = () => { + setPendingOAuthAttempt(null); + setSignInError(null); + cancelAuthorization(); + queryClient.invalidateQueries({ queryKey: queryKeys.tools.connection(connectionId) }); + queryClient.invalidateQueries({ queryKey: queryKeys.tools.catalog(connectionId) }); + queryClient.invalidateQueries({ queryKey: queryKeys.tools.connectionGrants(connectionId) }); + queryClient.invalidateQueries({ queryKey: queryKeys.tools.connectionProfileConfiguration(selectedCompanyId, connectionId) }); + queryClient.invalidateQueries({ queryKey: queryKeys.tools.policies(selectedCompanyId) }); + queryClient.invalidateQueries({ queryKey: queryKeys.tools.connections(selectedCompanyId) }); + queryClient.invalidateQueries({ queryKey: queryKeys.apps.attention(selectedCompanyId) }); + pushToast({ + title: `${appName} connected`, + body: "Sign-in finished and tools are ready.", + tone: "success", + }); + }; + + const failWaiting = (message: string) => { + setPendingOAuthAttempt(null); + cancelAuthorization(); + setSignInError(message); + }; + + const poll = async () => { + if (cancelled) return; + if (Date.now() - pendingOAuthAttempt.startedAt >= OAUTH_POLL_TIMEOUT_MS) { + failWaiting("Sign-in timed out before completing. Try signing in again."); + return; + } + try { + if (pendingOAuthAttempt.kind === "personal_grant" || pendingOAuthAttempt.kind === "agent_grant") { + const response = await toolsApi.listConnectionGrants(connectionId); + if (cancelled) return; + consecutiveErrors = 0; + const matchingGrant = pendingOAuthAttempt.kind === "personal_grant" + ? response.grants.find( + (grant) => grant.kind === "user" && grant.subjectUserId === pendingOAuthAttempt.subjectUserId, + ) + : response.grants.find( + (grant) => grant.kind === "agent" && grant.subjectAgentId === pendingOAuthAttempt.subjectAgentId, + ); + const updatedAt = toTimestampString(matchingGrant?.updatedAt); + const grantReady = Boolean( + matchingGrant + && matchingGrant.status === "active" + && ( + pendingOAuthAttempt.baselineGrantStatus !== "active" + || matchingGrant.id !== pendingOAuthAttempt.baselineGrantId + || updatedAt !== pendingOAuthAttempt.baselineGrantUpdatedAt + ), + ); + if (grantReady) completeSignIn(); + return; + } + + const latest = await toolsApi.getConnection(connectionId, { fresh: true }); + if (cancelled) return; + consecutiveErrors = 0; + const healthyActive = + latest.status === "active" + && latest.firstSignInPending !== true + && !isAttentionHealthStatus(latest.healthStatus); + if (pendingOAuthAttempt.kind === "activate_connection") { + if (healthyActive) completeSignIn(); + return; + } + const reconnected = + healthyActive + && latest.requiresReauthorization !== true + && ( + pendingOAuthAttempt.baselineWasAttention + || toTimestampString(latest.updatedAt) !== pendingOAuthAttempt.baselineUpdatedAt + ); + if (reconnected) completeSignIn(); + } catch (error) { + if (cancelled) return; + consecutiveErrors += 1; + const status = errorStatus(error); + if (status === 401 || status === 403 || status === 404 || consecutiveErrors >= OAUTH_MAX_CONSECUTIVE_POLL_ERRORS) { + failWaiting(describeError(error).body); + } + } + }; + + let channel: BroadcastChannel | null = null; + if (typeof BroadcastChannel !== "undefined") { + try { + channel = new BroadcastChannel(APP_OAUTH_OUTCOME_CHANNEL); + channel.onmessage = (event: MessageEvent) => { + if (cancelled) return; + const payload = event.data; + if (!payload || payload.connectionId !== connectionId) return; + if (payload.outcome === "failed" || payload.outcome === "denied") { + failWaiting(oauthCallbackErrorMessage(payload.outcome, payload.code, payload.providerError)); + } else if (payload.outcome === "connected") { + void poll(); + } + }; + } catch { + channel = null; + } + } + + const timer = window.setInterval(() => { void poll(); }, 2_500); + return () => { + cancelled = true; + window.clearInterval(timer); + channel?.close(); + }; + }, [appName, cancelAuthorization, connectionId, pendingOAuthAttempt, pushToast, queryClient, selectedCompanyId]); + // A denied or conflicting audience save keeps the dialog open with the // selection intact, so the error is surfaced inline rather than as a toast. const [audienceError, setAudienceError] = useState(null); @@ -580,24 +883,99 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio const aiGrantRevoked = connection.connectionPurpose === "ai" && grantRows.length > 0 && grantRows.every((grant) => grant.status === "revoked"); + const isSetupIncomplete = isFirstSignInDraft(connection); + const isCustomRemoteMcp = + connection.transport === "mcp_remote" + && !logoEntry + && !managesRemoteMcpAccess + && !connection.config?.sourceTemplateKey + && !connection.transportConfig?.sourceTemplateKey; + const customMcpChangeAuthHref = isCustomRemoteMcp + ? customMcpSetupHref(connection, isSetupIncomplete ? "resume" : "reconnect", true) + : null; + const customMcpContinueHref = isCustomRemoteMcp + ? customMcpSetupHref(connection, "resume", false) + : null; + const dedicatedGrantAgentId = managedIdentityGrant?.kind === "agent" + ? managedIdentityGrant.subjectAgentId ?? null + : null; + const requiresDedicatedAgentSelection = connection.credentialPolicy === "per_agent" && !dedicatedGrantAgentId; + const selectedDedicatedAgentId = dedicatedGrantAgentId ?? (draftDedicatedAgentId.trim() || null); + const canSignInDraft = connection.credentialPolicy === "per_user" + ? grantsQuery.data?.capabilities.canConnectAsCurrentUser === true + && (!connection.createdByUserId || connection.createdByUserId === grantsQuery.data?.currentUserId) + : grantsQuery.data?.capabilities.canConfigure === true; + const startSignInForConnection = () => { + if (onReconnect) { + onReconnect(connection); + return; + } + if (connection.credentialPolicy === "per_user") { + workspaceGate.run(connection, (services) => { + authorization.reserve(); + startPersonalAuth.mutate(services ? googleWorkspaceSelectedScopes(services) : undefined); + }); + return; + } + if (connection.credentialPolicy === "per_agent") { + const agentId = selectedDedicatedAgentId; + if (!agentId) { + setSignInError("Choose which agent owns this connection before signing in."); + return; + } + workspaceGate.run(connection, (services) => { + authorization.reserve(); + startOAuth.mutate({ asAgentId: agentId, ...(services ? { workspaceServices: services } : {}) }); + }); + return; + } + workspaceGate.run(connection, (services) => { + authorization.reserve(); + startOAuth.mutate(services ? { workspaceServices: services } : undefined); + }); + }; const status: StatusInfo = aiGrantRevoked ? { label: "Revoked", tone: "attention" } : statusFor(connection); - const needsReconnect = connection.requiresReauthorization - ?? (status.tone === "attention" && connection.healthStatus !== "unknown"); - const actionsContent = renderActions?.(connection) ?? (connection.connectionPurpose === "ai" ? : undefined); - const actionCount = actionsContent !== undefined ? null : catalogQuery.data ? active.length : null; + const catalogAuthFailure = catalogView.kind === "error" && isCatalogAuthError(catalogView.error); + const needsReconnect = !isSetupIncomplete && ( + connection.requiresReauthorization + ?? ( + (status.tone === "attention" && connection.healthStatus !== "unknown") + || isAttentionHealthStatus(connection.healthStatus) + || catalogAuthFailure + ) + ); + const actionsContent = renderActions?.(connection) + ?? (connection.connectionPurpose === "ai" + ? + : catalogView.kind === "error" + ? { + catalogView.retry(); + void catalogQuery.refetch(); + }} + /> + : undefined); + const actionCount = isSetupIncomplete || actionsContent !== undefined ? null : catalogQuery.data ? active.length : null; const reviewViews = [catalogView, profilesView, policiesView]; - const permissionsViews = [...reviewViews, installsView, agentsView]; + const permissionsCoreViews = [profilesView, policiesView, installsView, agentsView]; const reviewLoading = catalogQuery.isLoading || profilesQuery.isLoading || policiesQuery.isLoading || reviewViews.some((view) => view.kind === "reconnecting"); - const permissionsLoading = reviewLoading || installsQuery.isLoading || agentsQuery.isLoading - || permissionsViews.some((view) => view.kind === "reconnecting"); - // Only a real failure replaces the panel; a transient refetch failure keeps the loaded tools. + const permissionsLoading = (!isSetupIncomplete && catalogQuery.isLoading) + || profilesQuery.isLoading || policiesQuery.isLoading || installsQuery.isLoading || agentsQuery.isLoading + || permissionsCoreViews.some((view) => view.kind === "reconnecting"); + // Only a real failure in core permissions data replaces the panel; catalog errors stay scoped to Actions. const reviewFailure = reviewViews.find((view) => view.kind === "error"); - const permissionsFailure = permissionsViews.find((view) => view.kind === "error"); + const permissionsFailure = permissionsCoreViews.find((view) => view.kind === "error"); return (
- {authorization.fallback} {workspaceGate.dialog}
@@ -627,7 +1005,7 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio
- {status.tone === "attention" && connection.requiresReauthorization === false && ( + {!isSetupIncomplete && status.tone === "attention" && connection.requiresReauthorization === false && ( refreshGitHubAccess.mutate()} /> )} + {!isSetupIncomplete && (signInError ?? oauthReturnMessage) && ( +
+

{signInError ?? oauthReturnMessage}

+
+ {canReconnect && connection.authKind === "oauth" ? ( + + ) : null} + {canReconnect && customMcpChangeAuthHref ? ( + + ) : null} + +
+
+ )} + {!isSetupIncomplete && (pendingOAuthAttempt || authorization.fallbackUrl) && ( +
+
+ + Waiting for sign-in to finish in the new tab… +
+
+ {authorization.fallback} + +
+
+ )} {needsReconnect && ( setPendingOAuthAttempt( + buildOAuthAttempt( + connection.credentialPolicy === "per_user" && grantsQuery.data?.currentUserId + ? { asPersonalUserId: grantsQuery.data.currentUserId } + : undefined, + ), + )} onReconnect={onReconnect ? () => onReconnect(connection) : (connection.connectionPurpose === "ai" || isRemoteMcpConnectorMethod(connection.config?.sourceTemplateKey, connection.config?.connectionMethodKey)) ? () => navigate(`/apps/connect?source=${aiConnectionSourceSlug(connection) ?? connection.config?.sourceTemplateKey}&reconnect=${connection.id}`) : undefined} onReconnected={() => { queryClient.invalidateQueries({ queryKey: queryKeys.tools.connection(connectionId) }); + queryClient.invalidateQueries({ queryKey: queryKeys.tools.catalog(connectionId) }); queryClient.invalidateQueries({ queryKey: queryKeys.tools.connections(selectedCompanyId) }); queryClient.invalidateQueries({ queryKey: queryKeys.apps.attention(selectedCompanyId) }); }} @@ -651,7 +1076,11 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio )} {activeTab === "review" && ( - reviewFailure + isSetupIncomplete + ?
+ Finish connecting {baseAppName} on the Permissions tab before reviewing its actions. +
+ : reviewFailure ? { void catalogQuery.refetch(); void profilesQuery.refetch(); @@ -667,7 +1096,40 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio /> )} {activeTab === "permissions" && ( - permissionsFailure + isSetupIncomplete + ?
+ { + setDraftDedicatedAgentId(agentId); + setSignInError(null); + }, + } : null} + removing={disconnectRemote.isPending} + onSignIn={startSignInForConnection} + onCancelWaiting={cancelPendingOAuth} + onRemove={() => disconnectRemote.mutate()} + /> +
+ +
+
+ : permissionsFailure ? { void catalogQuery.refetch(); void profilesQuery.refetch(); @@ -775,6 +1237,32 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio )} + {isCustomRemoteMcp && grantsQuery.data?.capabilities.canConfigure === true && ( + disconnectRemote.mutate()} + onReplaced={() => { + queryClient.invalidateQueries({ queryKey: queryKeys.tools.connection(connectionId) }); + queryClient.invalidateQueries({ queryKey: queryKeys.tools.catalog(connectionId) }); + queryClient.invalidateQueries({ queryKey: queryKeys.tools.connections(selectedCompanyId) }); + queryClient.invalidateQueries({ queryKey: queryKeys.apps.attention(selectedCompanyId) }); + }} + canReplaceCredential={canReconnect} + credentialUnavailableMessage={reconnectUnavailableMessage} + appToggleDisabled={toggleConnection.isPending} + onToggleApp={() => toggleConnection.mutate()} + changeAuthHref={customMcpChangeAuthHref} + identityGrant={managedIdentityGrant} + identityCurrentUserId={grantsQuery.data?.currentUserId ?? null} + identityProviderName={baseAppName} + credentialPolicy={connection.credentialPolicy} + identityActionPending={startOAuth.isPending || startPersonalAuth.isPending} + onReconnectIdentity={connection.authKind === "oauth" ? startSignInForConnection : undefined} + /> + )} }
)} @@ -962,9 +1450,70 @@ function unverifiedRemoteHost(connection: ToolConnection): string | null { } } +function customMcpUrlOf(connection: ToolConnection): string | null { + const value = connection.config?.url + ?? connection.config?.endpoint + ?? connection.config?.remoteUrl + ?? connection.transportConfig.url + ?? connection.transportConfig.endpoint + ?? connection.transportConfig.remoteUrl; + return typeof value === "string" && value.trim() ? value.trim() : null; +} + +function customMcpSetupHref( + connection: ToolConnection, + mode: "resume" | "reconnect", + editAuth: boolean, +): string { + const params = new URLSearchParams(); + params.set(mode, connection.id); + if (connection.applicationId) params.set("applicationId", connection.applicationId); + const url = customMcpUrlOf(connection); + if (url) params.set("link", url); + if (editAuth) params.set("editAuth", "1"); + return `/apps/byo?${params.toString()}`; +} + +function oauthAuthorizationHost(connection: ToolConnection): string | null { + const oauth = connection.config?.oauth; + if (!oauth || typeof oauth !== "object" || Array.isArray(oauth)) return null; + const record = oauth as { authorizationUrl?: unknown; issuer?: unknown }; + const candidate = typeof record.authorizationUrl === "string" + ? record.authorizationUrl + : typeof record.issuer === "string" + ? record.issuer + : null; + if (!candidate) return null; + try { + return new URL(candidate).host || null; + } catch { + return null; + } +} + +const CATALOG_AUTH_ERROR_CODES = new Set([ + "oauth_refresh_missing", + "oauth_reauthorization_required", + "oauth_challenge", + "user_authorization_required", + "grant_credential_invalid", + "oauth_insufficient_scope", +]); + +function isCatalogAuthError(error: unknown): boolean { + const code = readOAuthApiErrorDetails(error).code; + return Boolean(code && CATALOG_AUTH_ERROR_CODES.has(code)); +} + type StatusInfo = { label: string; tone: "connected" | "attention" | "paused" }; function statusFor(connection: ToolConnection): StatusInfo { + if (isFirstSignInDraft(connection)) { + return { label: "Setup incomplete", tone: "attention" }; + } + if (connection.status === "draft") { + return { label: "Needs attention", tone: "attention" }; + } if (connection.enabled === false || connection.status === "disabled") { return { label: "Paused", tone: "paused" }; } diff --git a/ui/src/pages/apps/Connections.tsx b/ui/src/pages/apps/Connections.tsx index 03f76f1d381..cd1b1bc8f2b 100644 --- a/ui/src/pages/apps/Connections.tsx +++ b/ui/src/pages/apps/Connections.tsx @@ -62,7 +62,7 @@ const BROWSE_HREF = "/apps"; type StatusFilter = "all" | "attention"; type AppStatus = { - label: "Healthy" | "Needs attention" | "Paused" | "Not connected" | "Retired"; + label: "Healthy" | "Needs attention" | "Setup incomplete" | "Paused" | "Not connected" | "Retired"; tone: "connected" | "attention" | "paused" | "not_connected"; }; @@ -90,6 +90,12 @@ function statusFor(application: ToolApplication, connections: ToolConnection[]): if (connections.length === 0) { return { label: "Not connected", tone: "not_connected" }; } + if (connections.every((connection) => connection.status === "draft" && (connection.firstSignInPending === true || connection.authKind !== "oauth"))) { + return { label: "Setup incomplete", tone: "attention" }; + } + if (connections.every((connection) => connection.status === "draft")) { + return { label: "Needs attention", tone: "attention" }; + } if ( application.status === "disabled" || application.status === "archived" || diff --git a/ui/src/pages/apps/app-detail/AdvancedPanel.tsx b/ui/src/pages/apps/app-detail/AdvancedPanel.tsx index 246753ec0ed..3dbf119c706 100644 --- a/ui/src/pages/apps/app-detail/AdvancedPanel.tsx +++ b/ui/src/pages/apps/app-detail/AdvancedPanel.tsx @@ -27,6 +27,7 @@ import { Link } from "@/lib/router"; import type { AppDetailSectionProps } from "./types"; import { RevokeGrantDialog } from "./IdentitiesSection"; import { GOOGLE_CONTENT_DELETION_NOTICE } from "@/features/connections/googleAccessRemoval"; +import { oauthStartFailureMessage } from "@/features/connections/oauthFailureMessages"; import { describeError } from "@/api/errors"; import { useGoogleWorkspaceServiceGate } from "@/features/connections/GoogleWorkspaceServices"; @@ -41,6 +42,7 @@ export function AdvancedPanel({ credentialUnavailableMessage = "You don't have permission to replace this identity's credential.", appToggleDisabled, onToggleApp, + changeAuthHref = null, identityGrant = null, identityCurrentUserId = null, identityProviderName, @@ -56,6 +58,7 @@ export function AdvancedPanel({ credentialUnavailableMessage?: string; appToggleDisabled: boolean; onToggleApp: () => void; + changeAuthHref?: string | null; identityGrant?: ConnectionGrant | null; identityCurrentUserId?: string | null; identityProviderName?: string; @@ -67,6 +70,19 @@ export function AdvancedPanel({ return (
+ {changeAuthHref ? ( +
+
+

Sign-in method

+

+ Switch between browser sign-in, an API key, custom headers, or no sign-in. +

+
+ +
+ ) : null} void; onReconnect?: () => void; + onSignInStarted?: () => void; + changeAuthHref?: string | null; canReconnect?: boolean; reconnectUnavailableMessage?: string; }) { const { pushToast } = useToast(); const authorization = useAuthorizationWindow(); const workspaceGate = useGoogleWorkspaceServiceGate(); + const [startError, setStartError] = useState(null); const reconnectOAuth = useMutation({ // Reconnect is not a new identity choice. Personal-only connections must // put the replacement token back on the signed-in user's existing grant; // shared and legacy fallback connections keep using the organization slot. mutationFn: (workspaceServices?: GoogleWorkspaceServiceSelection) => { + setStartError(null); const services = workspaceServices ? { workspaceServices } : {}; return connection.credentialPolicy === "per_user" ? toolsApi.startOAuth(connection.id, { asCurrentUser: true, ...services }) @@ -179,19 +201,24 @@ export function ReconnectCard({ onSuccess: async (start) => { try { await authorization.open(start); + onSignInStarted?.(); } catch (error) { + const message = oauthStartFailureMessage(error, describeError(error).body); + setStartError(message); pushToast({ title: "Couldn’t start sign-in", - body: describeError(error).body, + body: message, tone: "error", }); } }, onError: (error) => { authorization.cancel(); + const message = oauthStartFailureMessage(error, describeError(error).body); + setStartError(message); pushToast({ title: "Couldn’t start sign-in", - body: describeError(error).body, + body: message, tone: "error", }); }, @@ -225,14 +252,15 @@ export function ReconnectCard({ {methodUnavailable ? "Connection no longer supported" : oauth ? "Reconnect required" : "This app needs reconnecting"}

- {methodUnavailable - ? "Add a supported connection from Connectors, then remove this connection." - : connection.healthMessage?.trim() || (oauth - ? "Authorization expired or was revoked. Sign in again to restore access." - : "The key stopped working. Paste a new one to get it back online.")} + {startError + ?? (methodUnavailable + ? "Add a supported connection from Connectors, then remove this connection." + : connection.healthMessage?.trim() || (oauth + ? "Authorization expired or was revoked. Sign in again to restore access." + : "The key stopped working. Paste a new one to get it back online."))}

-
+
{!canReconnect ? (

{reconnectUnavailableMessage ?? "You don't have permission to reconnect this identity."} @@ -275,6 +303,11 @@ export function ReconnectCard({ ) : ( )} + {canReconnect && changeAuthHref ? ( + + ) : null}

); @@ -413,7 +446,11 @@ function ReconnectForm({ ); } -function TechnicalDetails({ connection }: { connection: ToolConnection }) { +export function TechnicalDetails({ + connection, +}: { + connection: ToolConnection; +}) { const [open, setOpen] = useState(false); return ( diff --git a/ui/src/pages/apps/app-detail/DraftAndErrorCards.tsx b/ui/src/pages/apps/app-detail/DraftAndErrorCards.tsx new file mode 100644 index 00000000000..b7cdc57ec4e --- /dev/null +++ b/ui/src/pages/apps/app-detail/DraftAndErrorCards.tsx @@ -0,0 +1,243 @@ +import { useState, type ReactNode } from "react"; +import { Loader2 } from "lucide-react"; +import type { ToolConnection } from "@paperclipai/shared"; +import { Link } from "@/lib/router"; +import { AgentSelect, type AgentMultiSelectOption } from "@/components/AgentMultiSelect"; +import { Button } from "@/components/ui/button"; +import { describeError } from "@/api/errors"; + +export function FinishSetupCard({ + appName, + connection, + oauthHost, + permissionsLoading = false, + canSignIn, + canRemove, + signInUnavailableMessage, + signInPending, + awaitingCompletion, + fallbackAction, + errorMessage, + continueHref, + changeAuthHref, + dedicatedAgentSelect = null, + removing, + onSignIn, + onCancelWaiting, + onRemove, +}: { + appName: string; + connection: ToolConnection; + oauthHost: string | null; + permissionsLoading?: boolean; + canSignIn: boolean; + canRemove: boolean; + signInUnavailableMessage: string; + signInPending: boolean; + awaitingCompletion: boolean; + fallbackAction: ReactNode; + errorMessage: string | null; + continueHref: string | null; + changeAuthHref: string | null; + dedicatedAgentSelect?: { + agents: AgentMultiSelectOption[]; + value: string; + onChange: (agentId: string) => void; + } | null; + removing: boolean; + onSignIn: () => void; + onCancelWaiting: () => void; + onRemove: () => void; +}) { + const [confirmRemove, setConfirmRemove] = useState(false); + const isOAuth = connection.authKind === "oauth"; + const missingDedicatedAgent = Boolean(dedicatedAgentSelect && !dedicatedAgentSelect.value.trim()); + + return ( +
+
+

+ Finish connecting {appName} +

+

+ {isOAuth + ? oauthHost + ? `Sign in at ${oauthHost} to connect ${appName} and load its tools for your agents.` + : `Sign in to connect ${appName} and load its tools for your agents.` + : `Complete setup for ${appName} to verify the server and load its tools.`} +

+
+ + {isOAuth && dedicatedAgentSelect ? ( +
+ + +

+ This connection uses a dedicated agent identity. Choose which agent owns it before signing in. +

+
+ ) : null} + + {errorMessage ? ( +
+ {errorMessage} +
+ ) : null} + + {awaitingCompletion ? ( +
+
+ + Waiting for sign-in to finish in the new tab… +
+
+ {fallbackAction} + +
+
+ ) : null} + +
+
+ {isOAuth ? ( + permissionsLoading ? ( + + ) : canSignIn ? ( + + ) : ( +

{signInUnavailableMessage}

+ ) + ) : continueHref ? ( + + ) : null} + + {changeAuthHref ? ( + + ) : null} +
+ + {canRemove ? ( + confirmRemove ? ( +
+ + +
+ ) : ( + + ) + ) : null} +
+
+ ); +} + +export function CatalogErrorActions({ + error, + authFailure, + canReconnect, + reconnectPending, + retrying, + changeAuthHref, + onReconnect, + onRetry, +}: { + error: unknown; + authFailure: boolean; + canReconnect: boolean; + reconnectPending: boolean; + retrying: boolean; + changeAuthHref: string | null; + onReconnect?: () => void; + onRetry: () => void; +}) { + const summary = describeError(error).body; + return ( +
+
+

+ {authFailure ? "Actions are unavailable until you reconnect" : "Couldn’t load actions"} +

+

{summary}

+
+
+ {authFailure && canReconnect && onReconnect ? ( + + ) : ( + + )} + {changeAuthHref ? ( + + ) : null} +
+
+ ); +}