Elffuss BraidHub

kikocis/continue public

169e4d970312 · 6.4 KiBRawPermalink
1import {
2 OAuthClientProvider,
3 auth,
4} from "@modelcontextprotocol/sdk/client/auth.js";
5import {
6 OAuthClientInformationFull,
7 OAuthClientInformationSchema,
8 OAuthTokens,
9 OAuthTokensSchema,
10} from "@modelcontextprotocol/sdk/shared/auth.js";
11import { IDE, MCPServerStatus, SSEOptions } from "../..";
12
13import http from "http";
14import url from "url";
15import { GlobalContext, GlobalContextType } from "../../util/GlobalContext";
16
17let authenticatingMCPContext = null as {
18 authenticatingServer: MCPServerStatus;
19 ide: IDE;
20} | null;
21
22const PORT = 3000;
23
24const server = http.createServer((req, res) => {
25 try {
26 if (!req.url) {
27 throw new Error("no url found");
28 }
29
30 const parsedUrl = url.parse(req.url, true);
31 if (!parsedUrl.query["code"]) {
32 throw new Error("no query params found");
33 }
34
35 void handleMCPOauthCode(parsedUrl.query["code"] as string);
36
37 const html = `
38<!DOCTYPE html>
39<html>
40<head><title>Authentication Complete</title></head>
41<body>Authentication Complete. You can close this page now.</body>
42</html>`;
43
44 res.writeHead(200, {
45 "Content-Type": "text/html",
46 });
47 res.end(html);
48 } catch (error) {
49 res.writeHead(400, { "Content-Type": "text/plain" });
50 res.end(`Unexpected redirect error: ${(error as Error).message}`);
51 }
52});
53
54type MCPOauthStorage = GlobalContextType["mcpOauthStorage"][string];
55type MCPOauthStorageKey = keyof MCPOauthStorage;
56
57class MCPConnectionOauthProvider implements OAuthClientProvider {
58 private globalContext: GlobalContext;
59
60 constructor(
61 public oauthServerUrl: string,
62 private ide: IDE,
63 ) {
64 this.globalContext = new GlobalContext();
65 }
66
67 get redirectUrl() {
68 return `http://localhost:${PORT}`; // TODO: this has to be a hub url or should we spin up a server?
69 }
70
71 get clientMetadata() {
72 return {
73 redirect_uris: [this.redirectUrl],
74 token_endpoint_auth_method: "none",
75 grant_types: ["authorization_code", "refresh_token"],
76 response_types: ["code"],
77 client_name: "Continue Dev, Inc", // get this from package.json?
78 client_uri: "https://continue.dev", // get this from package.json?
79 };
80 }
81
82 private _getOauthStorage<K extends MCPOauthStorageKey>(key: K) {
83 return this.globalContext.get("mcpOauthStorage")?.[this.oauthServerUrl]?.[
84 key
85 ];
86 }
87
88 private _updateOauthStorage<K extends MCPOauthStorageKey>(
89 key: K,
90 value: MCPOauthStorage[K],
91 ) {
92 const existingStorage = this.globalContext.get("mcpOauthStorage") ?? {};
93 const existingServerStorage = existingStorage[this.oauthServerUrl] ?? {};
94
95 this.globalContext.update("mcpOauthStorage", {
96 ...existingStorage,
97 [this.oauthServerUrl]: {
98 ...existingServerStorage,
99 [key]: value,
100 },
101 });
102 }
103
104 private _clearOauthStorage() {
105 const existingStorage = this.globalContext.get("mcpOauthStorage") ?? {};
106 delete existingStorage[this.oauthServerUrl];
107 this.globalContext.update("mcpOauthStorage", existingStorage);
108 }
109
110 saveClientInformation(clientInformation: OAuthClientInformationFull) {
111 this._updateOauthStorage("clientInformation", clientInformation);
112 }
113
114 async clientInformation() {
115 const existingClientInformation =
116 this._getOauthStorage("clientInformation");
117 if (!existingClientInformation) {
118 return undefined;
119 }
120 return await OAuthClientInformationSchema.parseAsync(
121 existingClientInformation,
122 );
123 }
124
125 async tokens() {
126 const existingTokens = this._getOauthStorage("tokens");
127 if (!existingTokens) {
128 return undefined;
129 }
130 return await OAuthTokensSchema.parseAsync(existingTokens);
131 }
132
133 saveTokens(tokens: OAuthTokens) {
134 this._updateOauthStorage("tokens", tokens);
135 }
136
137 codeVerifier(): string | Promise<string> {
138 const existingCodeVerifier = this._getOauthStorage("codeVerifier");
139 if (!existingCodeVerifier) {
140 return "";
141 }
142 return existingCodeVerifier;
143 }
144
145 saveCodeVerifier(codeVerifier: string) {
146 this._updateOauthStorage("codeVerifier", codeVerifier);
147 }
148
149 clear() {
150 this._clearOauthStorage();
151 }
152
153 async redirectToAuthorization(authorizationUrl: URL) {
154 if (!server.listening) {
155 server.listen(PORT, () => {
156 console.debug(
157 `Server started for MCP Oauth process at http://localhost:${PORT}/`,
158 );
159 });
160 }
161 void this.ide.openUrl(authorizationUrl.toString());
162 }
163}
164
165export async function getOauthToken(mcpServerUrl: string, ide: IDE) {
166 const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
167 const tokens = await authProvider.tokens();
168 return tokens?.access_token;
169}
170
171/**
172 * checks if the authentication is already done for the current server
173 * if not, starts the authentication process by opening a webpage url
174 */
175export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) {
176 const mcpServerUrl = (mcpServer.transport as SSEOptions).url;
177 const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
178 authenticatingMCPContext = {
179 authenticatingServer: mcpServer,
180 ide,
181 };
182 return await auth(authProvider, {
183 serverUrl: mcpServerUrl,
184 });
185}
186
187/**
188 * handle the authentication code received from the oauth redirect
189 */
190async function handleMCPOauthCode(authorizationCode: string) {
191 if (!authenticatingMCPContext) {
192 return;
193 }
194 const { ide, authenticatingServer } = authenticatingMCPContext;
195 const serverUrl = (authenticatingServer.transport as SSEOptions).url;
196
197 if (!serverUrl) {
198 void ide.showToast("error", "No MCP server url found for authentication");
199 return;
200 }
201 if (!authorizationCode) {
202 void ide.showToast(
203 "error",
204 `No MCP authorization code found for ${serverUrl}`,
205 );
206 return;
207 }
208 server.close(() => console.debug("Server for MCP Oauth process was closed"));
209 const authProvider = new MCPConnectionOauthProvider(serverUrl, ide);
210 const authStatus = await auth(authProvider, {
211 serverUrl,
212 authorizationCode,
213 });
214 if (authStatus === "AUTHORIZED") {
215 const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports
216 await MCPManagerSingleton.getInstance().refreshConnection(
217 authenticatingServer.id,
218 );
219 }
220 authenticatingMCPContext = null;
221}
222
223export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) {
224 const mcpServerUrl = (mcpServer.transport as SSEOptions).url;
225 const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
226 authProvider.clear();
227}