@dudko.dev/agent-web-react 0.0.18 → 0.0.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -4
- package/dist/index.cjs +290 -792
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +144 -271
- package/dist/index.d.ts +144 -271
- package/dist/index.js +278 -764
- package/dist/index.js.map +1 -1
- package/dist/mcp.cjs +711 -0
- package/dist/mcp.cjs.map +1 -0
- package/dist/mcp.d.cts +265 -0
- package/dist/mcp.d.ts +265 -0
- package/dist/mcp.js +668 -0
- package/dist/mcp.js.map +1 -0
- package/dist/styles.css +99 -0
- package/package.json +13 -3
package/dist/mcp.cjs
ADDED
|
@@ -0,0 +1,711 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/mcp.ts
|
|
31
|
+
var mcp_exports = {};
|
|
32
|
+
__export(mcp_exports, {
|
|
33
|
+
claimOAuthCallback: () => claimOAuthCallback,
|
|
34
|
+
describeMcpResult: () => describeMcpResult,
|
|
35
|
+
isUnauthorizedError: () => isUnauthorizedError,
|
|
36
|
+
readCallbackParams: () => readCallbackParams,
|
|
37
|
+
stripOAuthParams: () => stripOAuthParams,
|
|
38
|
+
useMcp: () => useMcp,
|
|
39
|
+
useMcpServers: () => useMcpServers
|
|
40
|
+
});
|
|
41
|
+
module.exports = __toCommonJS(mcp_exports);
|
|
42
|
+
|
|
43
|
+
// src/hooks/use-mcp.ts
|
|
44
|
+
var import_react = require("react");
|
|
45
|
+
var OAUTH_UNSUPPORTED = "The installed @dudko.dev/agent-web has no MCP OAuth support. Upgrade the core to a version exporting BrowserOAuthProvider, or use a static Authorization header.";
|
|
46
|
+
var PENDING_KEY = "agent-web-react:mcp:pending";
|
|
47
|
+
var OAUTH_KEY = "agent-web-react:mcp:oauth";
|
|
48
|
+
var PENDING_TTL_MS = 10 * 60 * 1e3;
|
|
49
|
+
var modulePromise;
|
|
50
|
+
var loadMcp = () => {
|
|
51
|
+
modulePromise ??= import("@dudko.dev/agent-web/mcp").then((m) => m).catch((err) => {
|
|
52
|
+
modulePromise = void 0;
|
|
53
|
+
throw err;
|
|
54
|
+
});
|
|
55
|
+
return modulePromise;
|
|
56
|
+
};
|
|
57
|
+
var describeMcpResult = (result) => {
|
|
58
|
+
if (!result) return { status: "error", error: "The connector returned no result for the server" };
|
|
59
|
+
if (result.connected) return { status: "connected" };
|
|
60
|
+
if (result.needsAuthorization) return { status: "needs-authorization" };
|
|
61
|
+
return { status: "error", error: result.error ?? "Could not connect to the MCP server" };
|
|
62
|
+
};
|
|
63
|
+
var OAUTH_PARAMS = ["code", "state", "error", "error_description", "iss"];
|
|
64
|
+
var readCallbackParams = (href) => {
|
|
65
|
+
const target = href ?? (typeof globalThis.location !== "undefined" ? globalThis.location.href : void 0);
|
|
66
|
+
if (!target) return void 0;
|
|
67
|
+
let url;
|
|
68
|
+
try {
|
|
69
|
+
url = new URL(target);
|
|
70
|
+
} catch {
|
|
71
|
+
return void 0;
|
|
72
|
+
}
|
|
73
|
+
const params = new URLSearchParams(url.search);
|
|
74
|
+
const hash = url.hash.startsWith("#") ? url.hash.slice(1) : url.hash;
|
|
75
|
+
const q = hash.indexOf("?");
|
|
76
|
+
if (q >= 0) {
|
|
77
|
+
for (const [k, v] of new URLSearchParams(hash.slice(q + 1))) {
|
|
78
|
+
if (!params.has(k)) params.set(k, v);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const code = params.get("code") ?? void 0;
|
|
82
|
+
const error = params.get("error") ?? void 0;
|
|
83
|
+
if (!code && !error) return void 0;
|
|
84
|
+
return {
|
|
85
|
+
code,
|
|
86
|
+
state: params.get("state") ?? void 0,
|
|
87
|
+
error,
|
|
88
|
+
errorDescription: params.get("error_description") ?? void 0
|
|
89
|
+
};
|
|
90
|
+
};
|
|
91
|
+
var stripOAuthParams = (href) => {
|
|
92
|
+
const url = new URL(href);
|
|
93
|
+
for (const key of OAUTH_PARAMS) url.searchParams.delete(key);
|
|
94
|
+
const hash = url.hash.startsWith("#") ? url.hash.slice(1) : url.hash;
|
|
95
|
+
const q = hash.indexOf("?");
|
|
96
|
+
if (q >= 0) {
|
|
97
|
+
const params = new URLSearchParams(hash.slice(q + 1));
|
|
98
|
+
for (const key of OAUTH_PARAMS) params.delete(key);
|
|
99
|
+
const rest = params.toString();
|
|
100
|
+
url.hash = rest ? `${hash.slice(0, q)}?${rest}` : hash.slice(0, q);
|
|
101
|
+
}
|
|
102
|
+
return url.toString();
|
|
103
|
+
};
|
|
104
|
+
var claimedCallbacks = /* @__PURE__ */ new Set();
|
|
105
|
+
var claimOAuthCallback = (callback) => {
|
|
106
|
+
const key = `${callback.code ?? ""}|${callback.state ?? ""}|${callback.error ?? ""}`;
|
|
107
|
+
if (claimedCallbacks.has(key)) return false;
|
|
108
|
+
claimedCallbacks.add(key);
|
|
109
|
+
return true;
|
|
110
|
+
};
|
|
111
|
+
var readRecord = (key) => {
|
|
112
|
+
try {
|
|
113
|
+
const raw = globalThis.localStorage?.getItem(key);
|
|
114
|
+
return raw ? JSON.parse(raw) : void 0;
|
|
115
|
+
} catch {
|
|
116
|
+
return void 0;
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
var writeRecord = (key, value) => {
|
|
120
|
+
try {
|
|
121
|
+
if (value) globalThis.localStorage?.setItem(key, JSON.stringify(value));
|
|
122
|
+
else globalThis.localStorage?.removeItem(key);
|
|
123
|
+
} catch {
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
var defaultRedirectUrl = () => typeof globalThis.location === "undefined" ? "" : `${globalThis.location.origin}${globalThis.location.pathname}`;
|
|
127
|
+
var isUnauthorizedError = (err, mod) => {
|
|
128
|
+
if (!(err instanceof Error)) return false;
|
|
129
|
+
if (mod?.UnauthorizedError && err instanceof mod.UnauthorizedError) return true;
|
|
130
|
+
return err.constructor?.name === "UnauthorizedError";
|
|
131
|
+
};
|
|
132
|
+
var watchAuthorization = (tools, mod, onUnauthorized) => {
|
|
133
|
+
const entries = Object.entries(tools).map(([name, value]) => {
|
|
134
|
+
const tool = value;
|
|
135
|
+
if (typeof tool.execute !== "function") return [name, value];
|
|
136
|
+
const execute = tool.execute.bind(tool);
|
|
137
|
+
const watched = (args, options) => {
|
|
138
|
+
try {
|
|
139
|
+
const out = execute(args, options);
|
|
140
|
+
if (out && typeof out.then === "function") {
|
|
141
|
+
return out.then(void 0, (err) => {
|
|
142
|
+
if (isUnauthorizedError(err, mod)) onUnauthorized();
|
|
143
|
+
throw err;
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
} catch (err) {
|
|
148
|
+
if (isUnauthorizedError(err, mod)) onUnauthorized();
|
|
149
|
+
throw err;
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
return [name, { ...value, execute: watched }];
|
|
153
|
+
});
|
|
154
|
+
return Object.fromEntries(entries);
|
|
155
|
+
};
|
|
156
|
+
var useMcp = (options = {}) => {
|
|
157
|
+
const [status, setStatus] = (0, import_react.useState)("idle");
|
|
158
|
+
const [tools, setTools] = (0, import_react.useState)(void 0);
|
|
159
|
+
const [catalog, setCatalog] = (0, import_react.useState)([]);
|
|
160
|
+
const [error, setError] = (0, import_react.useState)(void 0);
|
|
161
|
+
const [authorizationUrl, setAuthorizationUrl] = (0, import_react.useState)(void 0);
|
|
162
|
+
const [oauthSupported, setOauthSupported] = (0, import_react.useState)(void 0);
|
|
163
|
+
const [completingAuthorization, setCompletingAuthorization] = (0, import_react.useState)(
|
|
164
|
+
() => readCallbackParams() !== void 0
|
|
165
|
+
);
|
|
166
|
+
const connectionRef = (0, import_react.useRef)(void 0);
|
|
167
|
+
const providerRef = (0, import_react.useRef)(void 0);
|
|
168
|
+
const epochRef = (0, import_react.useRef)(0);
|
|
169
|
+
const optionsRef = (0, import_react.useRef)(options);
|
|
170
|
+
optionsRef.current = options;
|
|
171
|
+
const closeConnection = (0, import_react.useCallback)(async () => {
|
|
172
|
+
const open = connectionRef.current;
|
|
173
|
+
connectionRef.current = void 0;
|
|
174
|
+
if (open) await open.close().catch(() => {
|
|
175
|
+
});
|
|
176
|
+
}, []);
|
|
177
|
+
const checkOAuthSupport = (0, import_react.useCallback)(async () => {
|
|
178
|
+
try {
|
|
179
|
+
const mod = await loadMcp();
|
|
180
|
+
const supported = typeof mod.BrowserOAuthProvider === "function";
|
|
181
|
+
setOauthSupported(supported);
|
|
182
|
+
return supported;
|
|
183
|
+
} catch {
|
|
184
|
+
setOauthSupported(false);
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
}, []);
|
|
188
|
+
const connect = (0, import_react.useCallback)(
|
|
189
|
+
async (opts) => {
|
|
190
|
+
const epoch = ++epochRef.current;
|
|
191
|
+
const current = () => epochRef.current === epoch;
|
|
192
|
+
await closeConnection();
|
|
193
|
+
if (!current()) return;
|
|
194
|
+
setStatus("connecting");
|
|
195
|
+
setError(void 0);
|
|
196
|
+
setAuthorizationUrl(void 0);
|
|
197
|
+
setTools(void 0);
|
|
198
|
+
setCatalog([]);
|
|
199
|
+
try {
|
|
200
|
+
const mod = await loadMcp();
|
|
201
|
+
setOauthSupported(typeof mod.BrowserOAuthProvider === "function");
|
|
202
|
+
const name = opts.name ?? "mcp";
|
|
203
|
+
let authProvider;
|
|
204
|
+
if (opts.oauth) {
|
|
205
|
+
if (!mod.BrowserOAuthProvider) throw new Error(OAUTH_UNSUPPORTED);
|
|
206
|
+
const oauth = typeof opts.oauth === "object" ? opts.oauth : {};
|
|
207
|
+
const record = {
|
|
208
|
+
url: opts.url,
|
|
209
|
+
name,
|
|
210
|
+
redirectUrl: oauth.redirectUrl ?? defaultRedirectUrl(),
|
|
211
|
+
scope: oauth.scope,
|
|
212
|
+
clientName: oauth.clientName ?? optionsRef.current.clientName,
|
|
213
|
+
startedAt: Date.now()
|
|
214
|
+
};
|
|
215
|
+
authProvider = new mod.BrowserOAuthProvider({
|
|
216
|
+
serverUrl: record.url,
|
|
217
|
+
redirectUrl: record.redirectUrl,
|
|
218
|
+
clientName: record.clientName,
|
|
219
|
+
scope: record.scope
|
|
220
|
+
});
|
|
221
|
+
providerRef.current = authProvider;
|
|
222
|
+
writeRecord(PENDING_KEY, record);
|
|
223
|
+
writeRecord(OAUTH_KEY, record);
|
|
224
|
+
} else {
|
|
225
|
+
providerRef.current = void 0;
|
|
226
|
+
}
|
|
227
|
+
const connection = await mod.connectMcpHttp(
|
|
228
|
+
{
|
|
229
|
+
[name]: {
|
|
230
|
+
url: opts.url,
|
|
231
|
+
headers: opts.oauth ? void 0 : opts.headers,
|
|
232
|
+
authProvider
|
|
233
|
+
}
|
|
234
|
+
},
|
|
235
|
+
{ clientName: optionsRef.current.clientName, onLog: optionsRef.current.onLog }
|
|
236
|
+
);
|
|
237
|
+
if (!current()) {
|
|
238
|
+
await connection.close().catch(() => {
|
|
239
|
+
});
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
const outcome = describeMcpResult(connection.results[0]);
|
|
243
|
+
if (outcome.status !== "connected") {
|
|
244
|
+
await connection.close().catch(() => {
|
|
245
|
+
});
|
|
246
|
+
if (outcome.status === "needs-authorization") {
|
|
247
|
+
const url = authProvider?.authorizationUrl;
|
|
248
|
+
setAuthorizationUrl(url ? String(url) : void 0);
|
|
249
|
+
setStatus("needs-authorization");
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
throw new Error(outcome.error);
|
|
253
|
+
}
|
|
254
|
+
connectionRef.current = connection;
|
|
255
|
+
writeRecord(PENDING_KEY, void 0);
|
|
256
|
+
setTools(
|
|
257
|
+
watchAuthorization(connection.tools, mod, () => {
|
|
258
|
+
if (!current()) return;
|
|
259
|
+
const url = providerRef.current?.authorizationUrl;
|
|
260
|
+
if (url) setAuthorizationUrl(String(url));
|
|
261
|
+
setStatus("needs-authorization");
|
|
262
|
+
})
|
|
263
|
+
);
|
|
264
|
+
setCatalog(connection.catalog);
|
|
265
|
+
setStatus("connected");
|
|
266
|
+
} catch (err) {
|
|
267
|
+
if (!current()) return;
|
|
268
|
+
setError(err instanceof Error ? err.message : String(err));
|
|
269
|
+
setStatus("error");
|
|
270
|
+
}
|
|
271
|
+
},
|
|
272
|
+
[closeConnection]
|
|
273
|
+
);
|
|
274
|
+
const disconnect = (0, import_react.useCallback)(async () => {
|
|
275
|
+
epochRef.current++;
|
|
276
|
+
await closeConnection();
|
|
277
|
+
setTools(void 0);
|
|
278
|
+
setCatalog([]);
|
|
279
|
+
setAuthorizationUrl(void 0);
|
|
280
|
+
setError(void 0);
|
|
281
|
+
setStatus("idle");
|
|
282
|
+
}, [closeConnection]);
|
|
283
|
+
const authorize = (0, import_react.useCallback)(() => {
|
|
284
|
+
if (authorizationUrl && typeof globalThis.location !== "undefined") {
|
|
285
|
+
globalThis.location.href = authorizationUrl;
|
|
286
|
+
}
|
|
287
|
+
}, [authorizationUrl]);
|
|
288
|
+
const forgetAuthorization = (0, import_react.useCallback)(async () => {
|
|
289
|
+
const record = readRecord(OAUTH_KEY);
|
|
290
|
+
writeRecord(PENDING_KEY, void 0);
|
|
291
|
+
writeRecord(OAUTH_KEY, void 0);
|
|
292
|
+
let provider = providerRef.current;
|
|
293
|
+
if (!provider && record) {
|
|
294
|
+
const mod = await loadMcp().catch(() => void 0);
|
|
295
|
+
if (mod?.BrowserOAuthProvider) {
|
|
296
|
+
provider = new mod.BrowserOAuthProvider({
|
|
297
|
+
serverUrl: record.url,
|
|
298
|
+
redirectUrl: record.redirectUrl,
|
|
299
|
+
clientName: record.clientName,
|
|
300
|
+
scope: record.scope
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
await provider?.reset().catch(() => {
|
|
305
|
+
});
|
|
306
|
+
providerRef.current = void 0;
|
|
307
|
+
await disconnect();
|
|
308
|
+
}, [disconnect]);
|
|
309
|
+
(0, import_react.useEffect)(() => {
|
|
310
|
+
const callback = readCallbackParams();
|
|
311
|
+
if (!callback) {
|
|
312
|
+
setCompletingAuthorization(false);
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
const pending = readRecord(PENDING_KEY);
|
|
316
|
+
const fresh = pending !== void 0 && (pending.startedAt === void 0 || Date.now() - pending.startedAt < PENDING_TTL_MS);
|
|
317
|
+
if (!pending || !fresh) {
|
|
318
|
+
if (pending) writeRecord(PENDING_KEY, void 0);
|
|
319
|
+
setCompletingAuthorization(false);
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
if (!claimOAuthCallback(callback)) {
|
|
323
|
+
setCompletingAuthorization(false);
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
if (typeof globalThis.history !== "undefined") {
|
|
327
|
+
globalThis.history.replaceState(null, "", stripOAuthParams(globalThis.location.href));
|
|
328
|
+
}
|
|
329
|
+
void (async () => {
|
|
330
|
+
try {
|
|
331
|
+
const mod = await loadMcp();
|
|
332
|
+
setOauthSupported(typeof mod.BrowserOAuthProvider === "function");
|
|
333
|
+
if (!mod.BrowserOAuthProvider || !mod.finishMcpOAuth) throw new Error(OAUTH_UNSUPPORTED);
|
|
334
|
+
const provider = new mod.BrowserOAuthProvider({
|
|
335
|
+
serverUrl: pending.url,
|
|
336
|
+
redirectUrl: pending.redirectUrl ?? defaultRedirectUrl(),
|
|
337
|
+
clientName: pending.clientName,
|
|
338
|
+
scope: pending.scope
|
|
339
|
+
});
|
|
340
|
+
providerRef.current = provider;
|
|
341
|
+
await mod.finishMcpOAuth(provider, callback);
|
|
342
|
+
writeRecord(PENDING_KEY, void 0);
|
|
343
|
+
setCompletingAuthorization(false);
|
|
344
|
+
await connect({ url: pending.url, name: pending.name, oauth: true });
|
|
345
|
+
} catch (err) {
|
|
346
|
+
writeRecord(PENDING_KEY, void 0);
|
|
347
|
+
setError(err instanceof Error ? err.message : String(err));
|
|
348
|
+
setStatus("error");
|
|
349
|
+
} finally {
|
|
350
|
+
setCompletingAuthorization(false);
|
|
351
|
+
}
|
|
352
|
+
})();
|
|
353
|
+
}, [connect]);
|
|
354
|
+
(0, import_react.useEffect)(
|
|
355
|
+
() => () => {
|
|
356
|
+
epochRef.current++;
|
|
357
|
+
void closeConnection();
|
|
358
|
+
},
|
|
359
|
+
[closeConnection]
|
|
360
|
+
);
|
|
361
|
+
return {
|
|
362
|
+
status,
|
|
363
|
+
tools,
|
|
364
|
+
catalog,
|
|
365
|
+
error,
|
|
366
|
+
authorizationUrl,
|
|
367
|
+
oauthSupported,
|
|
368
|
+
completingAuthorization,
|
|
369
|
+
connect,
|
|
370
|
+
disconnect,
|
|
371
|
+
authorize,
|
|
372
|
+
forgetAuthorization,
|
|
373
|
+
checkOAuthSupport
|
|
374
|
+
};
|
|
375
|
+
};
|
|
376
|
+
|
|
377
|
+
// src/hooks/use-mcp-servers.ts
|
|
378
|
+
var import_react2 = require("react");
|
|
379
|
+
var DEFAULT_KEY = "agent-web-react:mcp-servers";
|
|
380
|
+
var sanitize = (s) => s.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 32) || "mcp";
|
|
381
|
+
var view = (s, patch = {}) => ({
|
|
382
|
+
name: s.name,
|
|
383
|
+
url: s.url,
|
|
384
|
+
auth: s.auth,
|
|
385
|
+
status: "idle",
|
|
386
|
+
catalog: [],
|
|
387
|
+
...patch
|
|
388
|
+
});
|
|
389
|
+
var useMcpServers = (options = {}) => {
|
|
390
|
+
const storageKey = options.storageKey ?? DEFAULT_KEY;
|
|
391
|
+
const pendingKey = `${storageKey}:pending`;
|
|
392
|
+
const persist = options.persist !== false;
|
|
393
|
+
const [servers, setServers] = (0, import_react2.useState)(
|
|
394
|
+
() => persist ? (readRecord(storageKey) ?? []).map((s) => view(s)) : []
|
|
395
|
+
);
|
|
396
|
+
const [oauthSupported, setOauthSupported] = (0, import_react2.useState)(void 0);
|
|
397
|
+
const [completingAuthorization, setCompleting] = (0, import_react2.useState)(
|
|
398
|
+
() => readCallbackParams() !== void 0 && readRecord(pendingKey) !== void 0
|
|
399
|
+
);
|
|
400
|
+
const [toolsVersion, setToolsVersion] = (0, import_react2.useState)(0);
|
|
401
|
+
const liveRef = (0, import_react2.useRef)(/* @__PURE__ */ new Map());
|
|
402
|
+
const specsRef = (0, import_react2.useRef)(/* @__PURE__ */ new Map());
|
|
403
|
+
if (specsRef.current.size === 0 && servers.length > 0) {
|
|
404
|
+
for (const s of servers)
|
|
405
|
+
specsRef.current.set(s.name, { name: s.name, url: s.url, auth: s.auth });
|
|
406
|
+
}
|
|
407
|
+
const optionsRef = (0, import_react2.useRef)(options);
|
|
408
|
+
optionsRef.current = options;
|
|
409
|
+
const unmountedRef = (0, import_react2.useRef)(false);
|
|
410
|
+
const saveList = (0, import_react2.useCallback)(() => {
|
|
411
|
+
if (!persist) return;
|
|
412
|
+
writeRecord(storageKey, [...specsRef.current.values()]);
|
|
413
|
+
}, [persist, storageKey]);
|
|
414
|
+
const patch = (0, import_react2.useCallback)((name, p) => {
|
|
415
|
+
if (unmountedRef.current) return;
|
|
416
|
+
setServers((list) => list.map((s) => s.name === name ? { ...s, ...p } : s));
|
|
417
|
+
}, []);
|
|
418
|
+
const live = (name) => {
|
|
419
|
+
let l = liveRef.current.get(name);
|
|
420
|
+
if (!l) {
|
|
421
|
+
l = { epoch: 0 };
|
|
422
|
+
liveRef.current.set(name, l);
|
|
423
|
+
}
|
|
424
|
+
return l;
|
|
425
|
+
};
|
|
426
|
+
const closeServer = (0, import_react2.useCallback)(async (name) => {
|
|
427
|
+
const l = liveRef.current.get(name);
|
|
428
|
+
if (!l) return;
|
|
429
|
+
l.epoch += 1;
|
|
430
|
+
const open = l.connection;
|
|
431
|
+
l.connection = void 0;
|
|
432
|
+
if (l.tools) {
|
|
433
|
+
l.tools = void 0;
|
|
434
|
+
setToolsVersion((v) => v + 1);
|
|
435
|
+
}
|
|
436
|
+
if (open) await open.close().catch(() => {
|
|
437
|
+
});
|
|
438
|
+
}, []);
|
|
439
|
+
const providerFor = (mod, spec) => {
|
|
440
|
+
if (!mod.BrowserOAuthProvider) throw new Error(OAUTH_UNSUPPORTED);
|
|
441
|
+
return new mod.BrowserOAuthProvider({
|
|
442
|
+
serverUrl: spec.url,
|
|
443
|
+
redirectUrl: spec.oauth?.redirectUrl ?? defaultRedirectUrl(),
|
|
444
|
+
clientName: spec.oauth?.clientName ?? optionsRef.current.clientName,
|
|
445
|
+
scope: spec.oauth?.scope
|
|
446
|
+
});
|
|
447
|
+
};
|
|
448
|
+
const connectServer = (0, import_react2.useCallback)(
|
|
449
|
+
async (name) => {
|
|
450
|
+
const spec = specsRef.current.get(name);
|
|
451
|
+
if (!spec) return;
|
|
452
|
+
await closeServer(name);
|
|
453
|
+
const l = live(name);
|
|
454
|
+
const epoch = ++l.epoch;
|
|
455
|
+
const current = () => !unmountedRef.current && l.epoch === epoch;
|
|
456
|
+
if (spec.auth === "bearer" && !l.token) {
|
|
457
|
+
patch(name, { status: "idle", error: "Enter the bearer token to connect." });
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
patch(name, {
|
|
461
|
+
status: "connecting",
|
|
462
|
+
error: void 0,
|
|
463
|
+
authorizationUrl: void 0,
|
|
464
|
+
catalog: []
|
|
465
|
+
});
|
|
466
|
+
try {
|
|
467
|
+
const mod = await loadMcp();
|
|
468
|
+
setOauthSupported(typeof mod.BrowserOAuthProvider === "function");
|
|
469
|
+
let provider;
|
|
470
|
+
if (spec.auth === "oauth") {
|
|
471
|
+
provider = providerFor(mod, spec);
|
|
472
|
+
l.provider = provider;
|
|
473
|
+
}
|
|
474
|
+
const connection = await mod.connectMcpHttp(
|
|
475
|
+
{
|
|
476
|
+
[name]: {
|
|
477
|
+
url: spec.url,
|
|
478
|
+
headers: spec.auth === "bearer" && l.token ? { Authorization: `Bearer ${l.token}` } : void 0,
|
|
479
|
+
authProvider: provider,
|
|
480
|
+
connectTimeoutMs: optionsRef.current.connectTimeoutMs
|
|
481
|
+
}
|
|
482
|
+
},
|
|
483
|
+
{
|
|
484
|
+
clientName: optionsRef.current.clientName,
|
|
485
|
+
onLog: optionsRef.current.onLog,
|
|
486
|
+
connectTimeoutMs: optionsRef.current.connectTimeoutMs
|
|
487
|
+
}
|
|
488
|
+
);
|
|
489
|
+
if (!current()) {
|
|
490
|
+
await connection.close().catch(() => {
|
|
491
|
+
});
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
const outcome = describeMcpResult(connection.results[0]);
|
|
495
|
+
if (outcome.status !== "connected") {
|
|
496
|
+
await connection.close().catch(() => {
|
|
497
|
+
});
|
|
498
|
+
if (outcome.status === "needs-authorization") {
|
|
499
|
+
const url = provider?.authorizationUrl;
|
|
500
|
+
patch(name, {
|
|
501
|
+
status: "needs-authorization",
|
|
502
|
+
authorizationUrl: url ? String(url) : void 0
|
|
503
|
+
});
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
throw new Error(outcome.error);
|
|
507
|
+
}
|
|
508
|
+
l.connection = connection;
|
|
509
|
+
l.tools = watchAuthorization(connection.tools, mod, () => {
|
|
510
|
+
if (!current()) return;
|
|
511
|
+
const url = l.provider?.authorizationUrl;
|
|
512
|
+
patch(name, {
|
|
513
|
+
status: "needs-authorization",
|
|
514
|
+
authorizationUrl: url ? String(url) : void 0
|
|
515
|
+
});
|
|
516
|
+
});
|
|
517
|
+
setToolsVersion((v) => v + 1);
|
|
518
|
+
patch(name, { status: "connected", catalog: connection.catalog });
|
|
519
|
+
} catch (err) {
|
|
520
|
+
if (!current()) return;
|
|
521
|
+
patch(name, { status: "error", error: err instanceof Error ? err.message : String(err) });
|
|
522
|
+
}
|
|
523
|
+
},
|
|
524
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
525
|
+
[closeServer, patch, pendingKey]
|
|
526
|
+
);
|
|
527
|
+
const add = (0, import_react2.useCallback)(
|
|
528
|
+
async (input) => {
|
|
529
|
+
let name = sanitize(input.name);
|
|
530
|
+
const taken = specsRef.current.get(name);
|
|
531
|
+
if (taken && taken.url !== input.url) {
|
|
532
|
+
let n = 2;
|
|
533
|
+
while (specsRef.current.has(`${name}_${n}`)) n += 1;
|
|
534
|
+
name = `${name}_${n}`;
|
|
535
|
+
}
|
|
536
|
+
const spec = {
|
|
537
|
+
name,
|
|
538
|
+
url: input.url,
|
|
539
|
+
auth: input.auth ?? "none",
|
|
540
|
+
...input.oauth ? { oauth: input.oauth } : {}
|
|
541
|
+
};
|
|
542
|
+
specsRef.current.set(name, spec);
|
|
543
|
+
live(name).token = input.auth === "bearer" ? input.token : void 0;
|
|
544
|
+
setServers(
|
|
545
|
+
(list) => list.some((s) => s.name === name) ? list.map((s) => s.name === name ? view(spec) : s) : [...list, view(spec)]
|
|
546
|
+
);
|
|
547
|
+
saveList();
|
|
548
|
+
await connectServer(name);
|
|
549
|
+
return name;
|
|
550
|
+
},
|
|
551
|
+
[connectServer, saveList]
|
|
552
|
+
);
|
|
553
|
+
const remove = (0, import_react2.useCallback)(
|
|
554
|
+
async (name) => {
|
|
555
|
+
await closeServer(name);
|
|
556
|
+
liveRef.current.delete(name);
|
|
557
|
+
specsRef.current.delete(name);
|
|
558
|
+
saveList();
|
|
559
|
+
setServers((list) => list.filter((s) => s.name !== name));
|
|
560
|
+
},
|
|
561
|
+
[closeServer, saveList]
|
|
562
|
+
);
|
|
563
|
+
const reconnect = (0, import_react2.useCallback)(
|
|
564
|
+
async (name, token) => {
|
|
565
|
+
if (token !== void 0) live(name).token = token;
|
|
566
|
+
await connectServer(name);
|
|
567
|
+
},
|
|
568
|
+
[connectServer]
|
|
569
|
+
);
|
|
570
|
+
const authorize = (0, import_react2.useCallback)(
|
|
571
|
+
(name) => {
|
|
572
|
+
const url = servers.find((s) => s.name === name)?.authorizationUrl;
|
|
573
|
+
const spec = specsRef.current.get(name);
|
|
574
|
+
if (!url || !spec || typeof globalThis.location === "undefined") return;
|
|
575
|
+
const pending = {
|
|
576
|
+
name,
|
|
577
|
+
url: spec.url,
|
|
578
|
+
redirectUrl: spec.oauth?.redirectUrl ?? defaultRedirectUrl(),
|
|
579
|
+
scope: spec.oauth?.scope,
|
|
580
|
+
clientName: spec.oauth?.clientName ?? optionsRef.current.clientName,
|
|
581
|
+
startedAt: Date.now()
|
|
582
|
+
};
|
|
583
|
+
writeRecord(pendingKey, pending);
|
|
584
|
+
globalThis.location.href = url;
|
|
585
|
+
},
|
|
586
|
+
[servers, pendingKey]
|
|
587
|
+
);
|
|
588
|
+
const forgetAuthorization = (0, import_react2.useCallback)(
|
|
589
|
+
async (name) => {
|
|
590
|
+
const spec = specsRef.current.get(name);
|
|
591
|
+
const l = liveRef.current.get(name);
|
|
592
|
+
let provider = l?.provider;
|
|
593
|
+
if (!provider && spec?.auth === "oauth") {
|
|
594
|
+
const mod = await loadMcp().catch(() => void 0);
|
|
595
|
+
if (mod?.BrowserOAuthProvider) provider = providerFor(mod, spec);
|
|
596
|
+
}
|
|
597
|
+
await provider?.reset().catch(() => {
|
|
598
|
+
});
|
|
599
|
+
if (l) l.provider = void 0;
|
|
600
|
+
const pending = readRecord(pendingKey);
|
|
601
|
+
if (pending?.name === name) writeRecord(pendingKey, void 0);
|
|
602
|
+
await closeServer(name);
|
|
603
|
+
patch(name, { status: "idle", authorizationUrl: void 0, catalog: [], error: void 0 });
|
|
604
|
+
},
|
|
605
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
606
|
+
[closeServer, patch, pendingKey]
|
|
607
|
+
);
|
|
608
|
+
const checkOAuthSupport = (0, import_react2.useCallback)(async () => {
|
|
609
|
+
try {
|
|
610
|
+
const mod = await loadMcp();
|
|
611
|
+
const supported = typeof mod.BrowserOAuthProvider === "function";
|
|
612
|
+
setOauthSupported(supported);
|
|
613
|
+
return supported;
|
|
614
|
+
} catch {
|
|
615
|
+
setOauthSupported(false);
|
|
616
|
+
return false;
|
|
617
|
+
}
|
|
618
|
+
}, []);
|
|
619
|
+
(0, import_react2.useEffect)(() => {
|
|
620
|
+
unmountedRef.current = false;
|
|
621
|
+
const callback = readCallbackParams();
|
|
622
|
+
const pending = readRecord(pendingKey);
|
|
623
|
+
const fresh = pending !== void 0 && Date.now() - pending.startedAt < PENDING_TTL_MS;
|
|
624
|
+
const ours = Boolean(callback && pending && fresh && claimOAuthCallback(callback));
|
|
625
|
+
if (callback && pending && !fresh) writeRecord(pendingKey, void 0);
|
|
626
|
+
if (ours && typeof globalThis.history !== "undefined") {
|
|
627
|
+
globalThis.history.replaceState(null, "", stripOAuthParams(globalThis.location.href));
|
|
628
|
+
}
|
|
629
|
+
const autoConnect = optionsRef.current.autoConnect !== false;
|
|
630
|
+
void (async () => {
|
|
631
|
+
if (ours && pending && callback) {
|
|
632
|
+
try {
|
|
633
|
+
const mod = await loadMcp();
|
|
634
|
+
setOauthSupported(typeof mod.BrowserOAuthProvider === "function");
|
|
635
|
+
if (!mod.finishMcpOAuth) throw new Error(OAUTH_UNSUPPORTED);
|
|
636
|
+
const spec = specsRef.current.get(pending.name) ?? {
|
|
637
|
+
name: pending.name,
|
|
638
|
+
url: pending.url,
|
|
639
|
+
auth: "oauth"
|
|
640
|
+
};
|
|
641
|
+
if (!specsRef.current.has(spec.name)) {
|
|
642
|
+
specsRef.current.set(spec.name, spec);
|
|
643
|
+
setServers((list) => [...list, view(spec)]);
|
|
644
|
+
saveList();
|
|
645
|
+
}
|
|
646
|
+
const provider = providerFor(mod, {
|
|
647
|
+
...spec,
|
|
648
|
+
oauth: {
|
|
649
|
+
redirectUrl: pending.redirectUrl,
|
|
650
|
+
scope: pending.scope,
|
|
651
|
+
clientName: pending.clientName
|
|
652
|
+
}
|
|
653
|
+
});
|
|
654
|
+
live(spec.name).provider = provider;
|
|
655
|
+
await mod.finishMcpOAuth(provider, callback);
|
|
656
|
+
writeRecord(pendingKey, void 0);
|
|
657
|
+
} catch (err) {
|
|
658
|
+
writeRecord(pendingKey, void 0);
|
|
659
|
+
patch(pending.name, {
|
|
660
|
+
status: "error",
|
|
661
|
+
error: err instanceof Error ? err.message : String(err)
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
setCompleting(false);
|
|
666
|
+
if (autoConnect || ours) {
|
|
667
|
+
await Promise.all(
|
|
668
|
+
[...specsRef.current.keys()].filter((name) => autoConnect || name === pending?.name).map((name) => connectServer(name))
|
|
669
|
+
);
|
|
670
|
+
}
|
|
671
|
+
})();
|
|
672
|
+
return () => {
|
|
673
|
+
unmountedRef.current = true;
|
|
674
|
+
for (const name of liveRef.current.keys()) void closeServer(name);
|
|
675
|
+
};
|
|
676
|
+
}, []);
|
|
677
|
+
const tools = (0, import_react2.useMemo)(() => {
|
|
678
|
+
const merged = {};
|
|
679
|
+
for (const l of liveRef.current.values()) if (l.tools) Object.assign(merged, l.tools);
|
|
680
|
+
return merged;
|
|
681
|
+
}, [toolsVersion]);
|
|
682
|
+
const catalog = (0, import_react2.useMemo)(
|
|
683
|
+
() => servers.filter((s) => s.status === "connected").flatMap((s) => s.catalog),
|
|
684
|
+
[servers]
|
|
685
|
+
);
|
|
686
|
+
return {
|
|
687
|
+
servers,
|
|
688
|
+
tools,
|
|
689
|
+
catalog,
|
|
690
|
+
connectedCount: servers.filter((s) => s.status === "connected").length,
|
|
691
|
+
completingAuthorization,
|
|
692
|
+
oauthSupported,
|
|
693
|
+
checkOAuthSupport,
|
|
694
|
+
add,
|
|
695
|
+
remove,
|
|
696
|
+
reconnect,
|
|
697
|
+
authorize,
|
|
698
|
+
forgetAuthorization
|
|
699
|
+
};
|
|
700
|
+
};
|
|
701
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
702
|
+
0 && (module.exports = {
|
|
703
|
+
claimOAuthCallback,
|
|
704
|
+
describeMcpResult,
|
|
705
|
+
isUnauthorizedError,
|
|
706
|
+
readCallbackParams,
|
|
707
|
+
stripOAuthParams,
|
|
708
|
+
useMcp,
|
|
709
|
+
useMcpServers
|
|
710
|
+
});
|
|
711
|
+
//# sourceMappingURL=mcp.cjs.map
|