-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathauthenticate-connection.ts
More file actions
82 lines (77 loc) · 2.57 KB
/
authenticate-connection.ts
File metadata and controls
82 lines (77 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { authenticateMcp } from "@/web/lib/mcp-oauth";
import { KEYS } from "@/web/lib/query-keys";
import type { QueryClient } from "@tanstack/react-query";
import type { useConnectionActions } from "@decocms/mesh-sdk";
import { toast } from "sonner";
/**
* Runs the full OAuth authentication flow for an MCP connection:
* 1. Opens the OAuth popup via authenticateMcp()
* 2. Saves the token via the OAuth endpoint (or falls back to connection_token)
* 3. Invalidates auth-related queries so the UI refreshes
*
* Returns true on success, false on failure.
*/
export async function authenticateConnection(
connectionId: string,
connectionActions: ReturnType<typeof useConnectionActions>,
queryClient: QueryClient,
): Promise<boolean> {
const { token, tokenInfo, error } = await authenticateMcp({ connectionId });
if (error || !token) {
toast.error(`Authentication failed: ${error}`);
return false;
}
if (tokenInfo) {
try {
const response = await fetch(
`/api/connections/${connectionId}/oauth-token`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({
accessToken: tokenInfo.accessToken,
refreshToken: tokenInfo.refreshToken,
expiresIn: tokenInfo.expiresIn,
scope: tokenInfo.scope,
clientId: tokenInfo.clientId,
clientSecret: tokenInfo.clientSecret,
tokenEndpoint: tokenInfo.tokenEndpoint,
}),
},
);
if (!response.ok) {
console.error("Failed to save OAuth token:", await response.text());
await connectionActions.update.mutateAsync({
id: connectionId,
data: { connection_token: token },
});
} else {
try {
await connectionActions.update.mutateAsync({
id: connectionId,
data: {},
});
} catch (err) {
console.warn("Failed to refresh connection tools after OAuth:", err);
}
}
} catch (err) {
console.error("Error saving OAuth token:", err);
await connectionActions.update.mutateAsync({
id: connectionId,
data: { connection_token: token },
});
}
} else {
await connectionActions.update.mutateAsync({
id: connectionId,
data: { connection_token: token },
});
}
const mcpProxyUrl = new URL(`/mcp/${connectionId}`, window.location.origin);
await queryClient.invalidateQueries({
queryKey: KEYS.isMCPAuthenticated(mcpProxyUrl.href, null),
});
return true;
}