@mcpstack/agent-sdk 1.0.0-pr.16.7572c080abaa.13.1

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.
@@ -0,0 +1,4700 @@
1
+ // src/react-app/index.tsx
2
+ import { createContext, useContext, useEffect as useEffect3, useMemo as useMemo3, useRef as useRef3 } from "react";
3
+
4
+ // src/framework/useAppAgentBinding.tsx
5
+ import {
6
+ useEffect,
7
+ useMemo,
8
+ useRef,
9
+ useSyncExternalStore
10
+ } from "react";
11
+
12
+ // src/core/sse-client.ts
13
+ function* parseEventBlocks(input) {
14
+ const normalized = input.replace(/\r\n/g, "\n");
15
+ const eventBlocks = normalized.split("\n\n");
16
+ for (const eventBlock of eventBlocks) {
17
+ if (!eventBlock.trim()) continue;
18
+ let eventType = "";
19
+ const dataLines = [];
20
+ for (const line of eventBlock.split("\n")) {
21
+ if (line.startsWith("event: ")) {
22
+ eventType = line.slice("event: ".length);
23
+ } else if (line.startsWith("data: ")) {
24
+ dataLines.push(line.slice("data: ".length));
25
+ } else if (line === "data:") {
26
+ dataLines.push("");
27
+ }
28
+ }
29
+ if (!eventType || dataLines.length === 0) {
30
+ continue;
31
+ }
32
+ try {
33
+ const parsed = JSON.parse(dataLines.join("\n"));
34
+ yield { type: eventType, data: parsed };
35
+ } catch {
36
+ }
37
+ }
38
+ }
39
+ async function* parseSseStream(response, signal) {
40
+ const reader = response.body?.getReader();
41
+ if (!reader) {
42
+ const text = await response.text().catch(() => "");
43
+ yield* parseEventBlocks(text);
44
+ return;
45
+ }
46
+ const decoder = new TextDecoder();
47
+ let buffer = "";
48
+ try {
49
+ while (true) {
50
+ if (signal?.aborted) break;
51
+ const { done, value } = await reader.read();
52
+ if (done) break;
53
+ buffer += decoder.decode(value, { stream: true });
54
+ const normalized = buffer.replace(/\r\n/g, "\n");
55
+ const events = normalized.split("\n\n");
56
+ buffer = events.pop() ?? "";
57
+ for (const eventBlock of events) {
58
+ yield* parseEventBlocks(eventBlock);
59
+ }
60
+ }
61
+ if (buffer.trim()) {
62
+ yield* parseEventBlocks(buffer);
63
+ }
64
+ } finally {
65
+ reader.releaseLock();
66
+ }
67
+ }
68
+
69
+ // src/core/auth/registration.ts
70
+ var REGISTRATION_STORAGE_PREFIX = "mcpstack_oauth_registration_";
71
+ function getStorage(storage) {
72
+ if (storage) {
73
+ return storage;
74
+ }
75
+ try {
76
+ return typeof localStorage === "undefined" ? null : localStorage;
77
+ } catch {
78
+ return null;
79
+ }
80
+ }
81
+ function encodeCacheKey(raw) {
82
+ return btoa(raw).replace(/[^a-zA-Z0-9]/g, "");
83
+ }
84
+ function getPreferredRegistrationPreference(authConfig) {
85
+ return authConfig?.registrationPreference ?? "auto";
86
+ }
87
+ function getEffectiveCallbackUrl(authConfig, fallbackCallbackUrl) {
88
+ const configuredCallbackUrl = authConfig?.callbackUrl?.trim();
89
+ if (!configuredCallbackUrl) {
90
+ return fallbackCallbackUrl;
91
+ }
92
+ if (isNativeCallbackUrl(fallbackCallbackUrl) && !isNativeCallbackUrl(configuredCallbackUrl)) {
93
+ return fallbackCallbackUrl;
94
+ }
95
+ return configuredCallbackUrl;
96
+ }
97
+ function buildRegistrationCacheKey(authConfig, callbackUrl, requestedMode) {
98
+ const raw = [
99
+ authConfig.authorizationServerUrl ?? "",
100
+ authConfig.authorizationServerMetadataUrl ?? "",
101
+ authConfig.resource ?? "",
102
+ callbackUrl,
103
+ requestedMode
104
+ ].join("|");
105
+ return encodeCacheKey(raw);
106
+ }
107
+ function buildTokenCacheKey(authConfig, mcpServerUrl) {
108
+ if (!authConfig) {
109
+ return encodeCacheKey(`legacy|${mcpServerUrl}`);
110
+ }
111
+ const callbackUrl = authConfig.callbackUrl ?? "";
112
+ const clientMode = authConfig.clientMode ?? "manual";
113
+ const raw = [
114
+ authConfig.authorizationServerUrl ?? mcpServerUrl,
115
+ authConfig.resource ?? "",
116
+ callbackUrl,
117
+ clientMode
118
+ ].join("|");
119
+ return encodeCacheKey(raw);
120
+ }
121
+ function loadStoredRegistration(cacheKey, storage) {
122
+ const targetStorage = getStorage(storage);
123
+ if (!targetStorage) return null;
124
+ try {
125
+ const raw = targetStorage.getItem(`${REGISTRATION_STORAGE_PREFIX}${cacheKey}`);
126
+ if (!raw) return null;
127
+ return JSON.parse(raw);
128
+ } catch {
129
+ return null;
130
+ }
131
+ }
132
+ function saveStoredRegistration(registration, storage) {
133
+ const targetStorage = getStorage(storage);
134
+ if (!targetStorage) return;
135
+ try {
136
+ targetStorage.setItem(
137
+ `${REGISTRATION_STORAGE_PREFIX}${registration.key}`,
138
+ JSON.stringify(registration)
139
+ );
140
+ } catch {
141
+ }
142
+ }
143
+ function clearStoredRegistration(cacheKey, storage) {
144
+ const targetStorage = getStorage(storage);
145
+ if (!targetStorage) return;
146
+ try {
147
+ targetStorage.removeItem(`${REGISTRATION_STORAGE_PREFIX}${cacheKey}`);
148
+ } catch {
149
+ }
150
+ }
151
+ function applyResolvedRegistration(authConfig, registration) {
152
+ return {
153
+ ...authConfig,
154
+ callbackUrl: registration.callbackUrl,
155
+ clientId: registration.clientId ?? authConfig.clientId,
156
+ clientMode: registration.mode,
157
+ resource: registration.resource ?? authConfig.resource,
158
+ authorizationServerUrl: registration.authorizationServerUrl ?? authConfig.authorizationServerUrl,
159
+ authorizationServerMetadataUrl: registration.authorizationServerMetadataUrl ?? authConfig.authorizationServerMetadataUrl,
160
+ registrationEndpoint: registration.registrationEndpoint ?? authConfig.registrationEndpoint
161
+ };
162
+ }
163
+ function createResolvedRegistration(authConfig, mode, callbackUrl, clientId, clientMetadataUrl) {
164
+ return {
165
+ cacheKey: buildRegistrationCacheKey(authConfig, callbackUrl, mode),
166
+ mode,
167
+ clientId,
168
+ callbackUrl,
169
+ resource: authConfig.resource,
170
+ authorizationServerUrl: authConfig.authorizationServerUrl,
171
+ authorizationServerMetadataUrl: authConfig.authorizationServerMetadataUrl,
172
+ registrationEndpoint: authConfig.registrationEndpoint,
173
+ clientMetadataUrl
174
+ };
175
+ }
176
+ function shouldAttemptMode(preferred, candidate) {
177
+ return preferred === "auto" || preferred === candidate;
178
+ }
179
+ function isLoopbackHost(hostname) {
180
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
181
+ }
182
+ function isNativeCallbackUrl(callbackUrl) {
183
+ try {
184
+ const url = new URL(callbackUrl);
185
+ return url.protocol !== "http:" && url.protocol !== "https:";
186
+ } catch {
187
+ return !callbackUrl.startsWith("http://") && !callbackUrl.startsWith("https://");
188
+ }
189
+ }
190
+ function inferApplicationType(callbackUrl) {
191
+ try {
192
+ const url = new URL(callbackUrl);
193
+ if (url.protocol === "http:" || url.protocol === "https:") {
194
+ return isLoopbackHost(url.hostname) ? "native" : "web";
195
+ }
196
+ return "native";
197
+ } catch {
198
+ return "native";
199
+ }
200
+ }
201
+ async function registerPublicClient(authConfig, options) {
202
+ const fetchImpl = options.fetchImpl ?? fetch;
203
+ const callbackUrl = options.callbackUrl;
204
+ const registration = createResolvedRegistration(authConfig, "dcr", callbackUrl);
205
+ if (!authConfig.registrationEndpoint) {
206
+ throw new Error("Dynamic client registration is not available for this server.");
207
+ }
208
+ const existing = loadStoredRegistration(registration.cacheKey, options.storage);
209
+ if (existing?.clientId) {
210
+ return {
211
+ ...registration,
212
+ clientId: existing.clientId
213
+ };
214
+ }
215
+ const requestBody = {
216
+ client_name: options.clientName ?? "MCP Stack MCP Client",
217
+ application_type: inferApplicationType(callbackUrl),
218
+ redirect_uris: [callbackUrl],
219
+ grant_types: ["authorization_code", "refresh_token"],
220
+ response_types: ["code"],
221
+ token_endpoint_auth_method: "none",
222
+ scope: authConfig.scopes?.join(" "),
223
+ client_uri: options.clientUri
224
+ };
225
+ const response = await fetchImpl(authConfig.registrationEndpoint, {
226
+ method: "POST",
227
+ headers: {
228
+ Accept: "application/json",
229
+ "Content-Type": "application/json"
230
+ },
231
+ body: JSON.stringify(requestBody)
232
+ });
233
+ if (!response.ok) {
234
+ const errorText = await response.text().catch(() => "Dynamic client registration failed.");
235
+ throw new Error(`Dynamic client registration failed (${response.status}): ${errorText}`);
236
+ }
237
+ const payload = await response.json();
238
+ if (!payload.client_id) {
239
+ throw new Error("Dynamic client registration response did not include a client_id.");
240
+ }
241
+ saveStoredRegistration({
242
+ key: registration.cacheKey,
243
+ mode: "dcr",
244
+ authorizationServerUrl: authConfig.authorizationServerUrl ?? "",
245
+ authorizationServerMetadataUrl: authConfig.authorizationServerMetadataUrl,
246
+ registrationEndpoint: authConfig.registrationEndpoint,
247
+ clientId: payload.client_id,
248
+ callbackUrl,
249
+ resource: authConfig.resource,
250
+ createdAt: Date.now(),
251
+ updatedAt: Date.now()
252
+ }, options.storage);
253
+ return {
254
+ ...registration,
255
+ clientId: payload.client_id
256
+ };
257
+ }
258
+ async function resolveOAuthRegistration(authConfig, options) {
259
+ const callbackUrl = getEffectiveCallbackUrl(authConfig, options.callbackUrl);
260
+ const preferred = getPreferredRegistrationPreference(authConfig);
261
+ const preregClientId = authConfig.clientId?.trim();
262
+ if (preregClientId && shouldAttemptMode(preferred, "preregistered")) {
263
+ return createResolvedRegistration(
264
+ authConfig,
265
+ "preregistered",
266
+ callbackUrl,
267
+ preregClientId
268
+ );
269
+ }
270
+ if (authConfig.clientIdMetadataDocumentSupported && options.oauthClientMetadataUrl && shouldAttemptMode(preferred, "cimd")) {
271
+ return createResolvedRegistration(
272
+ authConfig,
273
+ "cimd",
274
+ callbackUrl,
275
+ options.oauthClientMetadataUrl,
276
+ options.oauthClientMetadataUrl
277
+ );
278
+ }
279
+ if (authConfig.registrationEndpoint && shouldAttemptMode(preferred, "dcr")) {
280
+ return registerPublicClient(authConfig, {
281
+ ...options,
282
+ callbackUrl
283
+ });
284
+ }
285
+ return createResolvedRegistration(
286
+ authConfig,
287
+ preregClientId ? "preregistered" : "manual",
288
+ callbackUrl,
289
+ preregClientId
290
+ );
291
+ }
292
+
293
+ // src/core/auth-storage.ts
294
+ var LEGACY_OAUTH_TOKEN_STORAGE_PREFIX = "mcpstack_oauth_";
295
+ var SCOPED_OAUTH_TOKEN_STORAGE_PREFIX = "mcpstack_oauth_session_";
296
+ function hashAuthSessionKey(value) {
297
+ let hash = 2166136261;
298
+ for (let index = 0; index < value.length; index += 1) {
299
+ hash ^= value.charCodeAt(index);
300
+ hash = Math.imul(hash, 16777619);
301
+ }
302
+ return (hash >>> 0).toString(36);
303
+ }
304
+ function normalizeAuthSessionKey(value) {
305
+ if (typeof value !== "string") {
306
+ return null;
307
+ }
308
+ const normalized = value.trim();
309
+ return normalized || null;
310
+ }
311
+ function resolveExplicitAuthSessionKey(config) {
312
+ return normalizeAuthSessionKey(config.authSessionKey);
313
+ }
314
+ function buildScopedOAuthTokenStoragePrefix(authSessionKey) {
315
+ const normalizedSessionKey = normalizeAuthSessionKey(authSessionKey);
316
+ if (!normalizedSessionKey) {
317
+ return LEGACY_OAUTH_TOKEN_STORAGE_PREFIX;
318
+ }
319
+ return `${SCOPED_OAUTH_TOKEN_STORAGE_PREFIX}${hashAuthSessionKey(normalizedSessionKey)}_`;
320
+ }
321
+ function buildScopedOAuthTokenStorageKey(cacheKey, authSessionKey) {
322
+ return `${buildScopedOAuthTokenStoragePrefix(authSessionKey)}${cacheKey}`;
323
+ }
324
+
325
+ // src/core/EmcyAgent.ts
326
+ var DEFAULT_MCP_PROTOCOL_VERSION = "2025-11-25";
327
+ var DEFAULT_LOCAL_PUBLIC_APP_PORT = "3100";
328
+ var DEFAULT_OAUTH_CALLBACK_URL = "https://mcpstack.com/oauth/callback";
329
+ var DEFAULT_OAUTH_CLIENT_METADATA_URL = "https://mcpstack.com/.well-known/oauth-client-metadata.json";
330
+ var DEFAULT_AUDIO_TURN_DETECTION = {
331
+ enabled: true,
332
+ autoSubmit: true,
333
+ silenceDurationMs: 850,
334
+ minSpeechDurationMs: 180,
335
+ noSpeechTimeoutMs: 12e3,
336
+ speechThreshold: 0.012,
337
+ noiseMultiplier: 2.4
338
+ };
339
+ var AUDIO_ACTIVITY_EMIT_INTERVAL_MS = 120;
340
+ var MIN_AUDIO_LEVEL_DELTA_FOR_STATE = 0.03;
341
+ function isLocalhostHost(hostname) {
342
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
343
+ }
344
+ function getDefaultOAuthHelperOrigin(agentServiceUrl) {
345
+ if (!agentServiceUrl) {
346
+ return DEFAULT_OAUTH_CALLBACK_URL.replace(/\/oauth\/callback$/, "");
347
+ }
348
+ try {
349
+ const url = new URL(agentServiceUrl);
350
+ if (isLocalhostHost(url.hostname)) {
351
+ return `${url.protocol}//${url.hostname}:${DEFAULT_LOCAL_PUBLIC_APP_PORT}`;
352
+ }
353
+ } catch {
354
+ }
355
+ return DEFAULT_OAUTH_CALLBACK_URL.replace(/\/oauth\/callback$/, "");
356
+ }
357
+ function getDefaultOAuthCallbackUrl(agentServiceUrl) {
358
+ return `${getDefaultOAuthHelperOrigin(agentServiceUrl)}/oauth/callback`;
359
+ }
360
+ function getDefaultOAuthClientMetadataUrl(agentServiceUrl) {
361
+ return `${getDefaultOAuthHelperOrigin(agentServiceUrl)}/.well-known/oauth-client-metadata.json`;
362
+ }
363
+ function buildEmbeddedExchangeUrl(mcpServerUrl) {
364
+ const url = new URL(mcpServerUrl);
365
+ if (/\/mcp\/?$/i.test(url.pathname)) {
366
+ url.pathname = url.pathname.replace(/\/mcp\/?$/i, "/embedded/exchange");
367
+ } else {
368
+ url.pathname = `${url.pathname.replace(/\/$/, "")}/embedded/exchange`;
369
+ }
370
+ return url.toString();
371
+ }
372
+ function normalizeOAuthTokenResponse(payload, authConfig) {
373
+ const accessToken = typeof payload.accessToken === "string" ? payload.accessToken : typeof payload.access_token === "string" ? payload.access_token : "";
374
+ if (!accessToken) {
375
+ return void 0;
376
+ }
377
+ return {
378
+ accessToken,
379
+ refreshToken: typeof payload.refreshToken === "string" ? payload.refreshToken : typeof payload.refresh_token === "string" ? payload.refresh_token : void 0,
380
+ expiresIn: typeof payload.expiresIn === "number" ? payload.expiresIn : typeof payload.expires_in === "number" ? payload.expires_in : void 0,
381
+ tokenType: typeof payload.tokenType === "string" ? payload.tokenType : typeof payload.token_type === "string" ? payload.token_type : "Bearer",
382
+ resolvedAuthConfig: authConfig
383
+ };
384
+ }
385
+ function createAppTokenAuthHandler(agentId, auth) {
386
+ return async (mcpServerUrl, authConfig) => {
387
+ const appToken = await auth.getToken();
388
+ const trimmedToken = appToken?.trim();
389
+ if (!trimmedToken) {
390
+ return void 0;
391
+ }
392
+ const headers = {
393
+ "Content-Type": "application/json",
394
+ Authorization: `Bearer ${trimmedToken}`
395
+ };
396
+ if (auth.appId?.trim()) {
397
+ headers["x-mcpstack-embedded-app-id"] = auth.appId.trim();
398
+ }
399
+ const body = {
400
+ agentId,
401
+ resource: authConfig.resource ?? mcpServerUrl,
402
+ scopes: authConfig.scopes
403
+ };
404
+ if (auth.appId?.trim()) {
405
+ body.appId = auth.appId.trim();
406
+ }
407
+ const response = await fetch(buildEmbeddedExchangeUrl(mcpServerUrl), {
408
+ method: "POST",
409
+ headers,
410
+ body: JSON.stringify(body)
411
+ });
412
+ const payload = await response.json().catch(() => null);
413
+ if (!response.ok) {
414
+ const description = typeof payload?.error_description === "string" ? payload.error_description : typeof payload?.error === "string" ? payload.error : `App token exchange failed (${response.status}).`;
415
+ throw new Error(description);
416
+ }
417
+ return normalizeOAuthTokenResponse(payload ?? {}, authConfig);
418
+ };
419
+ }
420
+ function extractErrorMessage(payload) {
421
+ if (typeof payload === "string") {
422
+ const message = payload.trim();
423
+ return message || null;
424
+ }
425
+ if (!payload || typeof payload !== "object") {
426
+ return null;
427
+ }
428
+ const record = payload;
429
+ for (const key of ["error", "message", "detail"]) {
430
+ const value = record[key];
431
+ if (typeof value === "string" && value.trim()) {
432
+ return value.trim();
433
+ }
434
+ }
435
+ return null;
436
+ }
437
+ async function getResponseErrorMessage(response) {
438
+ const fallback = `HTTP ${response.status}`;
439
+ try {
440
+ const payload = await response.clone().json();
441
+ const message = extractErrorMessage(payload);
442
+ if (message) {
443
+ return message;
444
+ }
445
+ } catch {
446
+ }
447
+ const text = await response.text().catch(() => "");
448
+ return text.trim() || fallback;
449
+ }
450
+ function parameterToJsonSchema(parameter) {
451
+ const schema = {
452
+ type: parameter.type
453
+ };
454
+ if (parameter.description) {
455
+ schema.description = parameter.description;
456
+ }
457
+ if (parameter.enum) {
458
+ schema.enum = parameter.enum;
459
+ }
460
+ if (parameter.type === "array") {
461
+ schema.items = parameter.items ? parameterToJsonSchema(parameter.items) : { type: "string" };
462
+ }
463
+ if (parameter.type === "object" && parameter.properties) {
464
+ const properties = {};
465
+ const required = [];
466
+ for (const [key, child] of Object.entries(parameter.properties)) {
467
+ properties[key] = parameterToJsonSchema(child);
468
+ if (child.required) required.push(key);
469
+ }
470
+ schema.properties = properties;
471
+ schema.required = required;
472
+ }
473
+ if (parameter.additionalProperties !== void 0) {
474
+ schema.additionalProperties = typeof parameter.additionalProperties === "boolean" ? parameter.additionalProperties : parameterToJsonSchema(parameter.additionalProperties);
475
+ }
476
+ return schema;
477
+ }
478
+ function parametersToJsonSchema(params) {
479
+ const properties = {};
480
+ const required = [];
481
+ for (const [key, p] of Object.entries(params)) {
482
+ properties[key] = parameterToJsonSchema(p);
483
+ if (p.required) required.push(key);
484
+ }
485
+ return { type: "object", properties, required };
486
+ }
487
+ var McpStackAgent = class {
488
+ constructor(config) {
489
+ this.agentConfig = null;
490
+ this.budgetSnapshot = null;
491
+ this.conversationId = null;
492
+ this.messages = [];
493
+ this.historyCursor = null;
494
+ this.hasOlderMessages = false;
495
+ this.isLoadingHistory = false;
496
+ this.abortController = null;
497
+ this.isLoading = false;
498
+ this.listeners = /* @__PURE__ */ new Map();
499
+ /** Per-server MCP session tracking */
500
+ this.mcpSessions = /* @__PURE__ */ new Map();
501
+ /** OAuth tokens per MCP server URL (standalone mode only) */
502
+ this.oauthTokens = /* @__PURE__ */ new Map();
503
+ /** Servers explicitly disconnected by the user and awaiting manual re-auth */
504
+ this.manuallySignedOutServers = /* @__PURE__ */ new Set();
505
+ this.audioState = {
506
+ status: "idle",
507
+ isSupported: false,
508
+ isEnabled: false,
509
+ transcript: "",
510
+ partialTranscript: "",
511
+ error: null
512
+ };
513
+ this.audioStream = null;
514
+ this.audioContext = null;
515
+ this.audioSource = null;
516
+ this.audioProcessor = null;
517
+ this.audioSilentGain = null;
518
+ this.audioSocket = null;
519
+ this.audioSessionTimer = null;
520
+ this.audioSessionStopRequested = false;
521
+ this.audioFinalTranscript = "";
522
+ this.audioTurnState = null;
523
+ const appTokenAuthHandler = config.auth?.mode === "app-token" ? createAppTokenAuthHandler(config.agentId, config.auth) : void 0;
524
+ this.config = {
525
+ ...config,
526
+ agentServiceUrl: config.agentServiceUrl ?? "https://api.mcpstack.com",
527
+ oauthCallbackUrl: config.oauthCallbackUrl ?? getDefaultOAuthCallbackUrl(config.agentServiceUrl),
528
+ oauthClientMetadataUrl: config.oauthClientMetadataUrl ?? getDefaultOAuthClientMetadataUrl(config.agentServiceUrl),
529
+ onAuthRequired: config.onAuthRequired ?? appTokenAuthHandler
530
+ };
531
+ this.audioState = this.buildAudioState({ status: "idle" });
532
+ }
533
+ async resolveAuthToken() {
534
+ if (this.config.getAuthToken) {
535
+ const token = await this.config.getAuthToken();
536
+ if (token) return token;
537
+ }
538
+ return this.config.apiKey;
539
+ }
540
+ /** Initialize: fetch agent config (tools, widget settings, MCP servers) */
541
+ async init() {
542
+ const token = await this.resolveAuthToken();
543
+ const response = await fetch(
544
+ `${this.config.agentServiceUrl}/api/v1/agents/${this.config.agentId}/config`,
545
+ {
546
+ headers: {
547
+ Authorization: `Bearer ${token}`
548
+ }
549
+ }
550
+ );
551
+ if (!response.ok) {
552
+ throw new Error(await getResponseErrorMessage(response));
553
+ }
554
+ this.agentConfig = await response.json();
555
+ this.audioState = this.buildAudioState({ status: "idle" });
556
+ this.emit("audio_state", this.audioState);
557
+ await this.refreshBudgetSnapshot().catch(() => void 0);
558
+ if (this.agentConfig?.mcpServers?.length) {
559
+ await Promise.all(
560
+ this.agentConfig.mcpServers.map(async (server) => {
561
+ server.authConfig = await this.resolveServerAuthConfig(server.url, server.authConfig ?? null);
562
+ })
563
+ );
564
+ }
565
+ if (this.agentConfig?.mcpServers) {
566
+ for (const server of this.agentConfig.mcpServers) {
567
+ if (!this.mcpSessions.has(server.url)) {
568
+ let authStatus;
569
+ if (server.authConfig?.authType === "oauth2") {
570
+ authStatus = server.authStatus === "connected" || this.hasValidOAuthToken(server.url) ? "connected" : "needs_auth";
571
+ } else {
572
+ authStatus = server.authStatus || "connected";
573
+ }
574
+ this.mcpSessions.set(server.url, { sessionId: null, authStatus });
575
+ }
576
+ }
577
+ }
578
+ if (this.config.initialConversationId) {
579
+ await this.loadConversation(this.config.initialConversationId);
580
+ }
581
+ return this.agentConfig;
582
+ }
583
+ /** Get current MCP server auth statuses */
584
+ getMcpServers() {
585
+ if (!this.agentConfig?.mcpServers) return [];
586
+ return this.agentConfig.mcpServers.map((server) => ({
587
+ url: server.url,
588
+ name: server.name,
589
+ authStatus: this.mcpSessions.get(server.url)?.authStatus ?? server.authStatus ?? "connected",
590
+ canSignOut: (server.authConfig?.authType ?? "none") !== "none"
591
+ }));
592
+ }
593
+ /** Send a message and process the full orchestration loop (including tool calls) */
594
+ async sendMessage(message) {
595
+ if (!this.agentConfig) {
596
+ await this.init();
597
+ }
598
+ this.isLoading = true;
599
+ this.emit("loading", true);
600
+ const userMsg = {
601
+ id: crypto.randomUUID(),
602
+ role: "user",
603
+ content: message,
604
+ timestamp: /* @__PURE__ */ new Date()
605
+ };
606
+ this.messages.push(userMsg);
607
+ this.emit("message", userMsg);
608
+ try {
609
+ await this.runChatLoop(message);
610
+ } catch (err) {
611
+ const errorMsg = err instanceof Error ? err.message : "Unknown error";
612
+ this.emit("error", { code: "sdk_error", message: errorMsg });
613
+ } finally {
614
+ this.isLoading = false;
615
+ this.emit("loading", false);
616
+ this.emit("thinking", false);
617
+ }
618
+ }
619
+ /** Start a new conversation */
620
+ newConversation() {
621
+ this.conversationId = null;
622
+ this.messages = [];
623
+ this.historyCursor = null;
624
+ this.hasOlderMessages = false;
625
+ this.isLoadingHistory = false;
626
+ }
627
+ /** Cancel the current in-flight request */
628
+ cancel() {
629
+ this.abortController?.abort();
630
+ this.abortController = null;
631
+ }
632
+ /** Get all messages in the current conversation */
633
+ getMessages() {
634
+ return [...this.messages];
635
+ }
636
+ /** Get the current conversation ID */
637
+ getConversationId() {
638
+ return this.conversationId;
639
+ }
640
+ getHasOlderMessages() {
641
+ return this.hasOlderMessages;
642
+ }
643
+ getIsLoadingHistory() {
644
+ return this.isLoadingHistory;
645
+ }
646
+ /** Get the loaded agent config */
647
+ getAgentConfig() {
648
+ return this.agentConfig;
649
+ }
650
+ getAudioInputState() {
651
+ return { ...this.audioState };
652
+ }
653
+ async startVoiceInput() {
654
+ if (!this.agentConfig) {
655
+ await this.init();
656
+ }
657
+ if (!this.isAudioInputSupported()) {
658
+ this.setAudioState({
659
+ status: "error",
660
+ error: {
661
+ code: "unsupported_browser",
662
+ message: "Microphone input is not supported in this browser."
663
+ }
664
+ });
665
+ return;
666
+ }
667
+ if (!this.isAudioInputEnabled()) {
668
+ this.setAudioState({
669
+ status: "error",
670
+ error: {
671
+ code: "audio_not_enabled",
672
+ message: "Microphone input is not enabled for this agent."
673
+ }
674
+ });
675
+ return;
676
+ }
677
+ if (this.audioState.status === "requesting_permission" || this.audioState.status === "connecting" || this.audioState.status === "listening" || this.audioState.status === "transcribing") {
678
+ return;
679
+ }
680
+ this.audioSessionStopRequested = false;
681
+ this.audioFinalTranscript = "";
682
+ this.audioTurnState = null;
683
+ this.setAudioState({
684
+ status: "requesting_permission",
685
+ transcript: "",
686
+ partialTranscript: "",
687
+ error: null,
688
+ sessionId: null,
689
+ conversationId: this.conversationId,
690
+ inputLevel: 0,
691
+ isSpeaking: false,
692
+ speechMs: 0,
693
+ silenceMs: 0,
694
+ autoSubmitEnabled: this.getAudioTurnDetectionConfig().enabled && this.getAudioTurnDetectionConfig().autoSubmit
695
+ });
696
+ let stream = null;
697
+ try {
698
+ stream = await navigator.mediaDevices.getUserMedia({
699
+ audio: {
700
+ channelCount: 1,
701
+ echoCancellation: true,
702
+ noiseSuppression: true,
703
+ autoGainControl: true
704
+ }
705
+ });
706
+ } catch (error) {
707
+ this.setAudioState({
708
+ status: "error",
709
+ error: {
710
+ code: "microphone_permission_denied",
711
+ message: error instanceof Error ? error.message : "Microphone permission was denied."
712
+ }
713
+ });
714
+ return;
715
+ }
716
+ try {
717
+ this.audioStream = stream;
718
+ this.setAudioState({ status: "connecting" });
719
+ const session = await this.createRealtimeTranscriptionSession();
720
+ this.conversationId = session.conversationId;
721
+ this.setAudioState({
722
+ sessionId: session.sessionId,
723
+ conversationId: session.conversationId,
724
+ maxSessionSeconds: session.maxSessionSeconds
725
+ });
726
+ const socket = await this.openAudioSocket(session.webSocketUrl);
727
+ this.audioSocket = socket;
728
+ this.bindAudioSocket(socket);
729
+ await this.startAudioCapture(stream, socket);
730
+ const maxSessionMs = Math.max(1, session.maxSessionSeconds) * 1e3;
731
+ this.audioSessionTimer = setTimeout(() => {
732
+ void this.commitVoiceInput();
733
+ }, maxSessionMs);
734
+ this.setAudioState({ status: "listening" });
735
+ } catch (error) {
736
+ this.cleanupAudioCapture();
737
+ this.setAudioState({
738
+ status: "error",
739
+ error: {
740
+ code: this.extractErrorCode(error) ?? "audio_start_failed",
741
+ message: error instanceof Error ? error.message : "Could not start microphone input."
742
+ }
743
+ });
744
+ }
745
+ }
746
+ async stopVoiceInput() {
747
+ await this.commitVoiceInput();
748
+ }
749
+ cancelVoiceInput() {
750
+ this.audioSessionStopRequested = true;
751
+ this.cleanupAudioCapture();
752
+ this.audioTurnState = null;
753
+ this.setAudioState({
754
+ status: "idle",
755
+ transcript: "",
756
+ partialTranscript: "",
757
+ error: null,
758
+ sessionId: null,
759
+ inputLevel: 0,
760
+ isSpeaking: false,
761
+ speechMs: 0,
762
+ silenceMs: 0
763
+ });
764
+ }
765
+ async loadConversation(conversationId, pageSize = this.config.conversationHistoryPageSize ?? 50) {
766
+ this.isLoadingHistory = true;
767
+ try {
768
+ const page = await this.fetchConversationMessages(conversationId, void 0, pageSize);
769
+ this.applyConversationPage(page, false);
770
+ return page;
771
+ } finally {
772
+ this.isLoadingHistory = false;
773
+ }
774
+ }
775
+ async loadOlderMessages(pageSize = this.config.conversationHistoryPageSize ?? 50) {
776
+ if (!this.conversationId || !this.historyCursor || !this.hasOlderMessages) {
777
+ return null;
778
+ }
779
+ this.isLoadingHistory = true;
780
+ try {
781
+ const page = await this.fetchConversationMessages(this.conversationId, this.historyCursor, pageSize);
782
+ this.applyConversationPage(page, true);
783
+ return page;
784
+ } finally {
785
+ this.isLoadingHistory = false;
786
+ }
787
+ }
788
+ async submitFeedback(input) {
789
+ if (!this.conversationId) {
790
+ throw new Error("No active conversation to rate.");
791
+ }
792
+ const token = await this.resolveAuthToken();
793
+ const response = await fetch(
794
+ `${this.config.agentServiceUrl}/api/v1/chat/conversations/${encodeURIComponent(this.conversationId)}/feedback`,
795
+ {
796
+ method: "POST",
797
+ headers: {
798
+ "Content-Type": "application/json",
799
+ Authorization: `Bearer ${token}`
800
+ },
801
+ body: JSON.stringify(input)
802
+ }
803
+ );
804
+ if (!response.ok) {
805
+ throw new Error(await getResponseErrorMessage(response));
806
+ }
807
+ return await response.json();
808
+ }
809
+ /** Convert client tools to the API schema format. */
810
+ clientToolsToSchemas() {
811
+ if (!this.config.clientTools) return [];
812
+ return Object.entries(this.config.clientTools).map(([name, def]) => ({
813
+ name,
814
+ description: def.description,
815
+ inputSchema: parametersToJsonSchema(def.parameters),
816
+ selection: def.selection
817
+ }));
818
+ }
819
+ resolveExternalUserId() {
820
+ const hostIdentity = this.config.embeddedAuth?.hostIdentity;
821
+ return this.config.externalUserId ?? hostIdentity?.subject ?? hostIdentity?.email ?? void 0;
822
+ }
823
+ buildExternalUserContext() {
824
+ const hostIdentity = this.config.embeddedAuth?.hostIdentity;
825
+ const id = this.resolveExternalUserId();
826
+ const externalUser = {};
827
+ if (id) externalUser.id = id;
828
+ if (hostIdentity?.email) externalUser.email = hostIdentity.email;
829
+ if (hostIdentity?.displayName) externalUser.displayName = hostIdentity.displayName;
830
+ if (hostIdentity?.avatarUrl) externalUser.avatarUrl = hostIdentity.avatarUrl;
831
+ if (hostIdentity?.organizationId) externalUser.organizationId = hostIdentity.organizationId;
832
+ return Object.keys(externalUser).length > 0 ? externalUser : void 0;
833
+ }
834
+ /** Latest runtime budget snapshot for the current SDK identity. */
835
+ getBudgetSnapshot() {
836
+ return this.budgetSnapshot;
837
+ }
838
+ /** Refresh the current SDK identity's budget snapshot from the API. */
839
+ async refreshBudgetSnapshot() {
840
+ const token = await this.resolveAuthToken();
841
+ const params = new URLSearchParams();
842
+ const externalUserId = this.resolveExternalUserId();
843
+ if (externalUserId) {
844
+ params.set("externalUserId", externalUserId);
845
+ }
846
+ const query = params.toString();
847
+ const response = await fetch(
848
+ `${this.config.agentServiceUrl}/api/v1/agents/${this.config.agentId}/budget${query ? `?${query}` : ""}`,
849
+ {
850
+ headers: {
851
+ Authorization: `Bearer ${token}`
852
+ }
853
+ }
854
+ );
855
+ if (!response.ok) {
856
+ throw new Error(await getResponseErrorMessage(response));
857
+ }
858
+ this.budgetSnapshot = await response.json();
859
+ this.emit("budget_snapshot", this.budgetSnapshot);
860
+ return this.budgetSnapshot;
861
+ }
862
+ /** Whether a request is currently in flight */
863
+ getIsLoading() {
864
+ return this.isLoading;
865
+ }
866
+ /** Update the per-turn app context sent with each chat request. */
867
+ setAppContext(context) {
868
+ this.config = {
869
+ ...this.config,
870
+ context
871
+ };
872
+ }
873
+ /** Update the client tools exposed to the agent without recreating the session. */
874
+ setClientTools(clientTools) {
875
+ this.config = {
876
+ ...this.config,
877
+ clientTools
878
+ };
879
+ }
880
+ /**
881
+ * Proactively authenticate with an MCP server before sending a message.
882
+ * If a token response is provided directly, it is stored immediately.
883
+ * Otherwise, this uses the configured OAuth flow and verifies via MCP init.
884
+ *
885
+ * @param mcpServerUrl - The MCP server URL to authenticate with
886
+ * @param tokenResponse - Optional: provide token response directly (from OAuth popup)
887
+ */
888
+ async authenticate(mcpServerUrl, tokenResponse) {
889
+ const wasManuallySignedOut = this.manuallySignedOutServers.delete(mcpServerUrl);
890
+ try {
891
+ if (tokenResponse?.accessToken) {
892
+ if (tokenResponse.resolvedAuthConfig) {
893
+ this.updateServerAuthConfig(mcpServerUrl, tokenResponse.resolvedAuthConfig);
894
+ }
895
+ this.storeOAuthToken(mcpServerUrl, tokenResponse);
896
+ this.updateMcpAuthStatus(mcpServerUrl, "connected");
897
+ return true;
898
+ }
899
+ const token = await this.resolveToken(mcpServerUrl);
900
+ if (!token) {
901
+ if (wasManuallySignedOut) {
902
+ this.manuallySignedOutServers.add(mcpServerUrl);
903
+ }
904
+ return false;
905
+ }
906
+ this.updateMcpAuthStatus(mcpServerUrl, "connected");
907
+ try {
908
+ await this.initMcpSession(mcpServerUrl);
909
+ return true;
910
+ } catch {
911
+ return true;
912
+ }
913
+ } catch {
914
+ if (wasManuallySignedOut) {
915
+ this.manuallySignedOutServers.add(mcpServerUrl);
916
+ }
917
+ this.updateMcpAuthStatus(mcpServerUrl, "needs_auth");
918
+ return false;
919
+ }
920
+ }
921
+ /** Disconnect from an MCP server and require explicit re-authentication before reuse. */
922
+ async signOutMcpServer(mcpServerUrl) {
923
+ this.manuallySignedOutServers.add(mcpServerUrl);
924
+ await this.closeMcpSession(mcpServerUrl);
925
+ this.clearOAuthToken(mcpServerUrl);
926
+ this.updateMcpAuthStatus(mcpServerUrl, "needs_auth");
927
+ }
928
+ /** Get the auth config for an MCP server (from agent config) */
929
+ getServerAuthConfig(mcpServerUrl) {
930
+ const server = this.agentConfig?.mcpServers?.find((s) => s.url === mcpServerUrl);
931
+ return server?.authConfig ?? null;
932
+ }
933
+ getOAuthCallbackUrl() {
934
+ return this.config.oauthCallbackUrl ?? DEFAULT_OAUTH_CALLBACK_URL;
935
+ }
936
+ getOAuthClientMetadataUrl() {
937
+ return this.config.oauthClientMetadataUrl ?? DEFAULT_OAUTH_CLIENT_METADATA_URL;
938
+ }
939
+ getDefaultAuthRequiredHandler() {
940
+ return this.config.auth?.mode === "app-token" ? createAppTokenAuthHandler(this.config.agentId, this.config.auth) : void 0;
941
+ }
942
+ setOnAuthRequired(onAuthRequired) {
943
+ this.config = {
944
+ ...this.config,
945
+ onAuthRequired: onAuthRequired ?? this.getDefaultAuthRequiredHandler()
946
+ };
947
+ }
948
+ isAudioInputSupported() {
949
+ const audioContextCtor = this.getAudioContextConstructor();
950
+ return typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getUserMedia) && typeof WebSocket !== "undefined" && Boolean(audioContextCtor) && typeof crypto !== "undefined";
951
+ }
952
+ isAudioInputEnabled() {
953
+ const capabilities = this.agentConfig?.modelConfig?.capabilities;
954
+ return Boolean(
955
+ this.agentConfig?.audio?.inputEnabled && (capabilities?.audioInput ?? capabilities?.realtimeAudioInput)
956
+ );
957
+ }
958
+ isAudioAutoSubmitEnabled() {
959
+ const turnDetection = this.getAudioTurnDetectionConfig();
960
+ return turnDetection.enabled && turnDetection.autoSubmit;
961
+ }
962
+ getAudioTurnDetectionConfig() {
963
+ const override = this.config.audioInput?.turnDetection ?? {};
964
+ return {
965
+ enabled: override.enabled ?? DEFAULT_AUDIO_TURN_DETECTION.enabled,
966
+ autoSubmit: override.autoSubmit ?? DEFAULT_AUDIO_TURN_DETECTION.autoSubmit,
967
+ silenceDurationMs: this.clampNumber(
968
+ override.silenceDurationMs,
969
+ 250,
970
+ 3e3,
971
+ DEFAULT_AUDIO_TURN_DETECTION.silenceDurationMs
972
+ ),
973
+ minSpeechDurationMs: this.clampNumber(
974
+ override.minSpeechDurationMs,
975
+ 80,
976
+ 1e3,
977
+ DEFAULT_AUDIO_TURN_DETECTION.minSpeechDurationMs
978
+ ),
979
+ noSpeechTimeoutMs: this.clampNumber(
980
+ override.noSpeechTimeoutMs,
981
+ 0,
982
+ 6e4,
983
+ DEFAULT_AUDIO_TURN_DETECTION.noSpeechTimeoutMs
984
+ ),
985
+ speechThreshold: this.clampNumber(
986
+ override.speechThreshold,
987
+ 2e-3,
988
+ 0.2,
989
+ DEFAULT_AUDIO_TURN_DETECTION.speechThreshold
990
+ ),
991
+ noiseMultiplier: this.clampNumber(
992
+ override.noiseMultiplier,
993
+ 1.2,
994
+ 8,
995
+ DEFAULT_AUDIO_TURN_DETECTION.noiseMultiplier
996
+ )
997
+ };
998
+ }
999
+ clampNumber(value, min, max, fallback) {
1000
+ if (typeof value !== "number" || !Number.isFinite(value)) {
1001
+ return fallback;
1002
+ }
1003
+ return Math.min(max, Math.max(min, value));
1004
+ }
1005
+ buildAudioState(patch) {
1006
+ const hasPatch = (key) => Object.prototype.hasOwnProperty.call(patch, key);
1007
+ return {
1008
+ status: patch.status ?? this.audioState.status,
1009
+ isSupported: this.isAudioInputSupported(),
1010
+ isEnabled: this.isAudioInputEnabled(),
1011
+ transcript: patch.transcript ?? this.audioState.transcript,
1012
+ partialTranscript: patch.partialTranscript ?? this.audioState.partialTranscript,
1013
+ error: hasPatch("error") ? patch.error ?? null : this.audioState.error,
1014
+ sessionId: hasPatch("sessionId") ? patch.sessionId ?? null : this.audioState.sessionId ?? null,
1015
+ conversationId: hasPatch("conversationId") ? patch.conversationId ?? null : this.audioState.conversationId ?? this.conversationId,
1016
+ maxSessionSeconds: hasPatch("maxSessionSeconds") ? patch.maxSessionSeconds ?? null : this.audioState.maxSessionSeconds ?? this.agentConfig?.audio?.maxSessionSeconds ?? null,
1017
+ inputLevel: hasPatch("inputLevel") ? patch.inputLevel ?? 0 : this.audioState.inputLevel ?? 0,
1018
+ isSpeaking: hasPatch("isSpeaking") ? patch.isSpeaking ?? false : this.audioState.isSpeaking ?? false,
1019
+ speechMs: hasPatch("speechMs") ? patch.speechMs ?? 0 : this.audioState.speechMs ?? 0,
1020
+ silenceMs: hasPatch("silenceMs") ? patch.silenceMs ?? 0 : this.audioState.silenceMs ?? 0,
1021
+ autoSubmitEnabled: hasPatch("autoSubmitEnabled") ? patch.autoSubmitEnabled ?? false : this.audioState.autoSubmitEnabled ?? this.isAudioAutoSubmitEnabled()
1022
+ };
1023
+ }
1024
+ setAudioState(patch) {
1025
+ this.audioState = this.buildAudioState(patch);
1026
+ this.emit("audio_state", this.audioState);
1027
+ }
1028
+ getAudioContextConstructor() {
1029
+ if (typeof window === "undefined") {
1030
+ return null;
1031
+ }
1032
+ return window.AudioContext ?? window.webkitAudioContext ?? null;
1033
+ }
1034
+ async createRealtimeTranscriptionSession() {
1035
+ const token = await this.resolveAuthToken();
1036
+ const externalUser = this.buildExternalUserContext();
1037
+ const response = await fetch(
1038
+ `${this.config.agentServiceUrl}/api/v1/agents/${encodeURIComponent(this.config.agentId)}/realtime/transcription-sessions`,
1039
+ {
1040
+ method: "POST",
1041
+ headers: {
1042
+ "Content-Type": "application/json",
1043
+ Authorization: `Bearer ${token}`
1044
+ },
1045
+ body: JSON.stringify({
1046
+ conversationId: this.conversationId,
1047
+ externalUserId: this.resolveExternalUserId(),
1048
+ externalUser
1049
+ })
1050
+ }
1051
+ );
1052
+ if (!response.ok) {
1053
+ throw await this.buildApiError(response);
1054
+ }
1055
+ return await response.json();
1056
+ }
1057
+ async buildApiError(response) {
1058
+ let code = null;
1059
+ let message = null;
1060
+ try {
1061
+ const payload = await response.clone().json();
1062
+ if (payload && typeof payload === "object") {
1063
+ const record = payload;
1064
+ code = typeof record.code === "string" ? record.code : null;
1065
+ message = extractErrorMessage(payload);
1066
+ }
1067
+ } catch {
1068
+ }
1069
+ const error = new Error(message ?? await getResponseErrorMessage(response));
1070
+ if (code) {
1071
+ error.code = code;
1072
+ }
1073
+ return error;
1074
+ }
1075
+ async openAudioSocket(url) {
1076
+ return new Promise((resolve, reject) => {
1077
+ const socket = new WebSocket(this.normalizeAudioSocketUrl(url));
1078
+ const cleanup = () => {
1079
+ socket.removeEventListener("open", handleOpen);
1080
+ socket.removeEventListener("error", handleError);
1081
+ };
1082
+ const handleOpen = () => {
1083
+ cleanup();
1084
+ resolve(socket);
1085
+ };
1086
+ const handleError = () => {
1087
+ cleanup();
1088
+ reject(new Error("Could not connect to the realtime microphone service."));
1089
+ };
1090
+ socket.addEventListener("open", handleOpen);
1091
+ socket.addEventListener("error", handleError);
1092
+ });
1093
+ }
1094
+ normalizeAudioSocketUrl(url) {
1095
+ if (typeof window === "undefined") {
1096
+ return url;
1097
+ }
1098
+ try {
1099
+ const parsed = new URL(url, window.location.href);
1100
+ if (window.location.protocol === "https:" && parsed.protocol === "ws:") {
1101
+ parsed.protocol = "wss:";
1102
+ }
1103
+ return parsed.toString();
1104
+ } catch {
1105
+ return url;
1106
+ }
1107
+ }
1108
+ bindAudioSocket(socket) {
1109
+ socket.addEventListener("message", (event) => {
1110
+ void this.handleAudioSocketMessage(event);
1111
+ });
1112
+ socket.addEventListener("close", () => {
1113
+ if (this.audioSocket !== socket) {
1114
+ return;
1115
+ }
1116
+ this.audioSocket = null;
1117
+ this.clearAudioSessionTimer();
1118
+ if (this.audioState.status === "listening" || this.audioState.status === "transcribing" || this.audioState.status === "connecting") {
1119
+ this.cleanupAudioCapture(false);
1120
+ this.audioTurnState = null;
1121
+ this.setAudioState({
1122
+ status: "idle",
1123
+ inputLevel: 0,
1124
+ isSpeaking: false,
1125
+ speechMs: 0,
1126
+ silenceMs: 0
1127
+ });
1128
+ }
1129
+ });
1130
+ socket.addEventListener("error", () => {
1131
+ if (this.audioSocket !== socket) {
1132
+ return;
1133
+ }
1134
+ this.cleanupAudioCapture();
1135
+ this.audioTurnState = null;
1136
+ this.setAudioState({
1137
+ status: "error",
1138
+ error: {
1139
+ code: "audio_socket_error",
1140
+ message: "The realtime microphone connection failed."
1141
+ },
1142
+ inputLevel: 0,
1143
+ isSpeaking: false,
1144
+ speechMs: 0,
1145
+ silenceMs: 0
1146
+ });
1147
+ });
1148
+ }
1149
+ async handleAudioSocketMessage(event) {
1150
+ const raw = typeof event.data === "string" ? event.data : event.data instanceof Blob ? await event.data.text() : "";
1151
+ if (!raw) {
1152
+ return;
1153
+ }
1154
+ let payload;
1155
+ try {
1156
+ payload = JSON.parse(raw);
1157
+ } catch {
1158
+ return;
1159
+ }
1160
+ const type = typeof payload.type === "string" ? payload.type : "";
1161
+ if (type === "transcript_delta") {
1162
+ const text = typeof payload.text === "string" ? payload.text : "";
1163
+ if (!text) {
1164
+ return;
1165
+ }
1166
+ this.audioFinalTranscript += text;
1167
+ this.setAudioState({
1168
+ partialTranscript: this.audioFinalTranscript,
1169
+ transcript: this.audioFinalTranscript
1170
+ });
1171
+ this.emit("audio_transcript_delta", {
1172
+ text,
1173
+ transcript: this.audioFinalTranscript,
1174
+ isFinal: false
1175
+ });
1176
+ return;
1177
+ }
1178
+ if (type === "transcript_final") {
1179
+ const finalText = (typeof payload.text === "string" && payload.text.trim() ? payload.text : this.audioFinalTranscript).trim();
1180
+ this.cleanupAudioCapture();
1181
+ this.audioTurnState = null;
1182
+ if (!finalText) {
1183
+ this.setAudioState({
1184
+ status: "idle",
1185
+ transcript: "",
1186
+ partialTranscript: "",
1187
+ inputLevel: 0,
1188
+ isSpeaking: false,
1189
+ speechMs: 0,
1190
+ silenceMs: 0
1191
+ });
1192
+ return;
1193
+ }
1194
+ this.setAudioState({
1195
+ status: "sending",
1196
+ transcript: finalText,
1197
+ partialTranscript: "",
1198
+ error: null,
1199
+ inputLevel: 0,
1200
+ isSpeaking: false
1201
+ });
1202
+ this.emit("audio_transcript_final", {
1203
+ text: finalText,
1204
+ transcript: finalText,
1205
+ conversationId: this.conversationId ?? ""
1206
+ });
1207
+ await this.sendMessage(finalText);
1208
+ this.setAudioState({
1209
+ status: "idle",
1210
+ transcript: finalText,
1211
+ partialTranscript: "",
1212
+ sessionId: null,
1213
+ inputLevel: 0,
1214
+ isSpeaking: false,
1215
+ speechMs: 0,
1216
+ silenceMs: 0
1217
+ });
1218
+ return;
1219
+ }
1220
+ if (type === "error") {
1221
+ const code = typeof payload.code === "string" ? payload.code : "audio_error";
1222
+ const message = typeof payload.message === "string" ? payload.message : "Microphone input failed.";
1223
+ this.cleanupAudioCapture();
1224
+ this.audioTurnState = null;
1225
+ this.setAudioState({
1226
+ status: "error",
1227
+ error: { code, message },
1228
+ inputLevel: 0,
1229
+ isSpeaking: false,
1230
+ speechMs: 0,
1231
+ silenceMs: 0
1232
+ });
1233
+ }
1234
+ }
1235
+ async commitVoiceInput() {
1236
+ if (this.audioSessionStopRequested || this.audioState.status !== "listening" && this.audioState.status !== "connecting") {
1237
+ return;
1238
+ }
1239
+ this.audioSessionStopRequested = true;
1240
+ this.cleanupAudioCapture(false);
1241
+ if (this.audioSocket?.readyState === WebSocket.OPEN) {
1242
+ this.audioSocket.send(JSON.stringify({ type: "audio.commit" }));
1243
+ this.setAudioState({
1244
+ status: "transcribing",
1245
+ inputLevel: 0,
1246
+ isSpeaking: false,
1247
+ silenceMs: this.audioTurnState?.silenceMs ?? this.audioState.silenceMs ?? 0,
1248
+ speechMs: this.audioTurnState?.speechMs ?? this.audioState.speechMs ?? 0
1249
+ });
1250
+ return;
1251
+ }
1252
+ this.audioTurnState = null;
1253
+ this.setAudioState({
1254
+ status: "idle",
1255
+ inputLevel: 0,
1256
+ isSpeaking: false,
1257
+ speechMs: 0,
1258
+ silenceMs: 0
1259
+ });
1260
+ }
1261
+ stopVoiceInputWithoutTranscript(message) {
1262
+ this.audioSessionStopRequested = true;
1263
+ this.cleanupAudioCapture();
1264
+ this.audioTurnState = null;
1265
+ this.setAudioState({
1266
+ status: "idle",
1267
+ transcript: "",
1268
+ partialTranscript: "",
1269
+ sessionId: null,
1270
+ inputLevel: 0,
1271
+ isSpeaking: false,
1272
+ speechMs: 0,
1273
+ silenceMs: 0,
1274
+ error: {
1275
+ code: "no_speech_detected",
1276
+ message
1277
+ }
1278
+ });
1279
+ }
1280
+ createAudioTurnState(nowMs) {
1281
+ return {
1282
+ startedAtMs: nowMs,
1283
+ lastFrameAtMs: nowMs,
1284
+ speechStartedAtMs: null,
1285
+ lastSpeechAtMs: null,
1286
+ speechMs: 0,
1287
+ silenceMs: 0,
1288
+ noiseFloor: DEFAULT_AUDIO_TURN_DETECTION.speechThreshold / 2,
1289
+ isSpeaking: false,
1290
+ autoCommitted: false,
1291
+ lastActivityEmitMs: 0
1292
+ };
1293
+ }
1294
+ analyzeAudioFrame(input, durationMs) {
1295
+ if (input.length === 0) {
1296
+ return { rms: 0, peak: 0, inputLevel: 0, durationMs };
1297
+ }
1298
+ let sumSquares = 0;
1299
+ let peak = 0;
1300
+ for (let index = 0; index < input.length; index += 1) {
1301
+ const sample = input[index];
1302
+ const abs = Math.abs(sample);
1303
+ sumSquares += sample * sample;
1304
+ if (abs > peak) {
1305
+ peak = abs;
1306
+ }
1307
+ }
1308
+ const rms = Math.sqrt(sumSquares / input.length);
1309
+ return {
1310
+ rms,
1311
+ peak,
1312
+ inputLevel: Math.min(1, rms * 14),
1313
+ durationMs
1314
+ };
1315
+ }
1316
+ processAudioTurnActivity(activity, nowMs) {
1317
+ const config = this.getAudioTurnDetectionConfig();
1318
+ if (!config.enabled) {
1319
+ this.emitAudioActivity(activity, nowMs, false, 0, 0, DEFAULT_AUDIO_TURN_DETECTION.speechThreshold / 2);
1320
+ return;
1321
+ }
1322
+ const state = this.audioTurnState ?? this.createAudioTurnState(nowMs);
1323
+ this.audioTurnState = state;
1324
+ const frameGapMs = Math.max(1, nowMs - state.lastFrameAtMs);
1325
+ const frameDurationMs = Math.max(activity.durationMs, frameGapMs);
1326
+ state.lastFrameAtMs = nowMs;
1327
+ const adaptiveThreshold = Math.max(
1328
+ config.speechThreshold,
1329
+ Math.min(0.08, state.noiseFloor * config.noiseMultiplier)
1330
+ );
1331
+ const peakThreshold = Math.max(adaptiveThreshold * 2.2, config.speechThreshold * 2.5);
1332
+ const speechCandidate = activity.rms >= adaptiveThreshold || activity.rms >= adaptiveThreshold * 0.72 && activity.peak >= peakThreshold;
1333
+ if (speechCandidate) {
1334
+ if (state.speechStartedAtMs === null) {
1335
+ state.speechStartedAtMs = nowMs;
1336
+ state.speechMs = 0;
1337
+ }
1338
+ state.lastSpeechAtMs = nowMs;
1339
+ state.speechMs += frameDurationMs;
1340
+ state.silenceMs = 0;
1341
+ state.isSpeaking = true;
1342
+ } else {
1343
+ state.noiseFloor = this.updateNoiseFloor(state.noiseFloor, activity.rms);
1344
+ state.isSpeaking = false;
1345
+ if (state.lastSpeechAtMs !== null) {
1346
+ state.silenceMs = nowMs - state.lastSpeechAtMs;
1347
+ }
1348
+ }
1349
+ if (state.speechStartedAtMs !== null && state.speechMs < config.minSpeechDurationMs && state.silenceMs >= config.silenceDurationMs) {
1350
+ state.speechStartedAtMs = null;
1351
+ state.lastSpeechAtMs = null;
1352
+ state.speechMs = 0;
1353
+ state.silenceMs = 0;
1354
+ }
1355
+ this.emitAudioActivity(
1356
+ activity,
1357
+ nowMs,
1358
+ state.isSpeaking,
1359
+ state.speechMs,
1360
+ state.silenceMs,
1361
+ state.noiseFloor
1362
+ );
1363
+ const noSpeechElapsedMs = nowMs - state.startedAtMs;
1364
+ if (config.noSpeechTimeoutMs > 0 && state.speechStartedAtMs === null && noSpeechElapsedMs >= config.noSpeechTimeoutMs && !state.autoCommitted) {
1365
+ state.autoCommitted = true;
1366
+ this.stopVoiceInputWithoutTranscript("No speech was detected. Try again when you are ready to speak.");
1367
+ return;
1368
+ }
1369
+ if (config.autoSubmit && state.speechStartedAtMs !== null && state.speechMs >= config.minSpeechDurationMs && state.silenceMs >= config.silenceDurationMs && !state.autoCommitted) {
1370
+ state.autoCommitted = true;
1371
+ void this.commitVoiceInput();
1372
+ }
1373
+ }
1374
+ updateNoiseFloor(currentNoiseFloor, rms) {
1375
+ const sample = Math.max(15e-4, Math.min(0.08, rms));
1376
+ const smoothing = sample > currentNoiseFloor ? 0.02 : 0.12;
1377
+ return currentNoiseFloor * (1 - smoothing) + sample * smoothing;
1378
+ }
1379
+ emitAudioActivity(activity, nowMs, isSpeaking, speechMs, silenceMs, noiseFloor) {
1380
+ const state = this.audioTurnState;
1381
+ const shouldEmitState = !state || nowMs - state.lastActivityEmitMs >= AUDIO_ACTIVITY_EMIT_INTERVAL_MS || isSpeaking !== this.audioState.isSpeaking || Math.abs(activity.inputLevel - (this.audioState.inputLevel ?? 0)) >= MIN_AUDIO_LEVEL_DELTA_FOR_STATE;
1382
+ if (!shouldEmitState) {
1383
+ return;
1384
+ }
1385
+ if (state) {
1386
+ state.lastActivityEmitMs = nowMs;
1387
+ }
1388
+ const roundedLevel = Number(activity.inputLevel.toFixed(3));
1389
+ const roundedNoiseFloor = Number(noiseFloor.toFixed(5));
1390
+ this.setAudioState({
1391
+ inputLevel: roundedLevel,
1392
+ isSpeaking,
1393
+ speechMs: Math.round(speechMs),
1394
+ silenceMs: Math.round(silenceMs),
1395
+ autoSubmitEnabled: this.isAudioAutoSubmitEnabled()
1396
+ });
1397
+ this.emit("audio_activity", {
1398
+ inputLevel: roundedLevel,
1399
+ noiseFloor: roundedNoiseFloor,
1400
+ isSpeaking,
1401
+ speechMs: Math.round(speechMs),
1402
+ silenceMs: Math.round(silenceMs)
1403
+ });
1404
+ }
1405
+ async startAudioCapture(stream, socket) {
1406
+ const AudioContextCtor = this.getAudioContextConstructor();
1407
+ if (!AudioContextCtor) {
1408
+ throw new Error("Audio capture is not available in this browser.");
1409
+ }
1410
+ const context = new AudioContextCtor();
1411
+ if (context.state === "suspended") {
1412
+ await context.resume();
1413
+ }
1414
+ const source = context.createMediaStreamSource(stream);
1415
+ const processor = context.createScriptProcessor(4096, 1, 1);
1416
+ const silentGain = context.createGain();
1417
+ silentGain.gain.value = 0;
1418
+ this.audioTurnState = this.createAudioTurnState(performance.now());
1419
+ processor.onaudioprocess = (event) => {
1420
+ if (this.audioSessionStopRequested || socket.readyState !== WebSocket.OPEN || this.audioState.status !== "listening") {
1421
+ return;
1422
+ }
1423
+ const input = event.inputBuffer.getChannelData(0);
1424
+ const durationMs = input.length / context.sampleRate * 1e3;
1425
+ this.processAudioTurnActivity(
1426
+ this.analyzeAudioFrame(input, durationMs),
1427
+ performance.now()
1428
+ );
1429
+ if (this.audioSessionStopRequested) {
1430
+ return;
1431
+ }
1432
+ const resampled = this.resampleToPcm16(input, context.sampleRate, 24e3);
1433
+ if (resampled.length === 0) {
1434
+ return;
1435
+ }
1436
+ socket.send(JSON.stringify({
1437
+ type: "audio.append",
1438
+ audio: this.pcm16ToBase64(resampled)
1439
+ }));
1440
+ };
1441
+ source.connect(processor);
1442
+ processor.connect(silentGain);
1443
+ silentGain.connect(context.destination);
1444
+ this.audioContext = context;
1445
+ this.audioSource = source;
1446
+ this.audioProcessor = processor;
1447
+ this.audioSilentGain = silentGain;
1448
+ }
1449
+ resampleToPcm16(input, inputSampleRate, outputSampleRate) {
1450
+ if (inputSampleRate === outputSampleRate) {
1451
+ return this.floatToPcm16(input);
1452
+ }
1453
+ const ratio = inputSampleRate / outputSampleRate;
1454
+ const outputLength = Math.floor(input.length / ratio);
1455
+ const output = new Float32Array(outputLength);
1456
+ for (let index = 0; index < outputLength; index += 1) {
1457
+ const inputIndex = index * ratio;
1458
+ const lower = Math.floor(inputIndex);
1459
+ const upper = Math.min(lower + 1, input.length - 1);
1460
+ const weight = inputIndex - lower;
1461
+ output[index] = input[lower] * (1 - weight) + input[upper] * weight;
1462
+ }
1463
+ return this.floatToPcm16(output);
1464
+ }
1465
+ floatToPcm16(input) {
1466
+ const output = new Int16Array(input.length);
1467
+ for (let index = 0; index < input.length; index += 1) {
1468
+ const sample = Math.max(-1, Math.min(1, input[index]));
1469
+ output[index] = sample < 0 ? sample * 32768 : sample * 32767;
1470
+ }
1471
+ return output;
1472
+ }
1473
+ pcm16ToBase64(input) {
1474
+ const bytes = new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
1475
+ let binary = "";
1476
+ const chunkSize = 32768;
1477
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) {
1478
+ const chunk = bytes.subarray(offset, offset + chunkSize);
1479
+ binary += String.fromCharCode(...chunk);
1480
+ }
1481
+ return btoa(binary);
1482
+ }
1483
+ cleanupAudioCapture(closeSocket = true) {
1484
+ this.clearAudioSessionTimer();
1485
+ this.audioProcessor?.disconnect();
1486
+ this.audioSource?.disconnect();
1487
+ this.audioSilentGain?.disconnect();
1488
+ this.audioProcessor = null;
1489
+ this.audioSource = null;
1490
+ this.audioSilentGain = null;
1491
+ if (this.audioContext) {
1492
+ void this.audioContext.close().catch(() => void 0);
1493
+ this.audioContext = null;
1494
+ }
1495
+ this.audioStream?.getTracks().forEach((track) => track.stop());
1496
+ this.audioStream = null;
1497
+ if (closeSocket && this.audioSocket) {
1498
+ const socket = this.audioSocket;
1499
+ this.audioSocket = null;
1500
+ if (socket.readyState === WebSocket.OPEN) {
1501
+ socket.send(JSON.stringify({ type: "audio.close" }));
1502
+ socket.close();
1503
+ } else if (socket.readyState === WebSocket.CONNECTING) {
1504
+ socket.close();
1505
+ }
1506
+ }
1507
+ }
1508
+ clearAudioSessionTimer() {
1509
+ if (!this.audioSessionTimer) {
1510
+ return;
1511
+ }
1512
+ clearTimeout(this.audioSessionTimer);
1513
+ this.audioSessionTimer = null;
1514
+ }
1515
+ extractErrorCode(error) {
1516
+ if (error && typeof error === "object" && "code" in error) {
1517
+ const code = error.code;
1518
+ return typeof code === "string" ? code : null;
1519
+ }
1520
+ return null;
1521
+ }
1522
+ getPersistentStorage() {
1523
+ return this.config.storage ?? null;
1524
+ }
1525
+ async resolveOAuthClientRegistration(authConfig) {
1526
+ if (!authConfig || authConfig.authType !== "oauth2") {
1527
+ return authConfig ?? null;
1528
+ }
1529
+ const registration = await resolveOAuthRegistration(authConfig, {
1530
+ callbackUrl: this.getOAuthCallbackUrl(),
1531
+ oauthClientMetadataUrl: this.config.oauthClientMetadataUrl,
1532
+ clientName: "MCP Stack MCP Client",
1533
+ clientUri: "https://mcpstack.com",
1534
+ storage: this.getPersistentStorage()
1535
+ });
1536
+ return applyResolvedRegistration(authConfig, registration);
1537
+ }
1538
+ /** Subscribe to events */
1539
+ on(event, handler) {
1540
+ if (!this.listeners.has(event)) {
1541
+ this.listeners.set(event, /* @__PURE__ */ new Set());
1542
+ }
1543
+ this.listeners.get(event).add(handler);
1544
+ }
1545
+ /** Unsubscribe from events */
1546
+ off(event, handler) {
1547
+ this.listeners.get(event)?.delete(handler);
1548
+ }
1549
+ // ================================================================
1550
+ // Private methods
1551
+ // ================================================================
1552
+ buildProtectedResourceMetadataCandidates(mcpServerUrl) {
1553
+ const url = new URL(mcpServerUrl);
1554
+ const candidates = /* @__PURE__ */ new Set();
1555
+ const normalizedPath = url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname;
1556
+ if (!normalizedPath || normalizedPath === "/") {
1557
+ candidates.add(`${url.origin}/.well-known/oauth-protected-resource`);
1558
+ return [...candidates];
1559
+ }
1560
+ candidates.add(`${url.origin}/.well-known/oauth-protected-resource${normalizedPath}`);
1561
+ candidates.add(`${url.origin}${normalizedPath}/.well-known/oauth-protected-resource`);
1562
+ candidates.add(`${url.origin}/.well-known/oauth-protected-resource`);
1563
+ return [...candidates];
1564
+ }
1565
+ hasSameOrigin(left, right) {
1566
+ try {
1567
+ const leftUrl = new URL(left);
1568
+ const rightUrl = new URL(right);
1569
+ return leftUrl.origin === rightUrl.origin;
1570
+ } catch {
1571
+ return false;
1572
+ }
1573
+ }
1574
+ extractQuotedHeaderValue(header, key) {
1575
+ const match = header.match(new RegExp(`${key}="([^"]+)"`, "i"));
1576
+ return match?.[1] ?? null;
1577
+ }
1578
+ buildAuthorizationServerMetadataCandidates(issuerOrMetadataUrl) {
1579
+ const candidates = /* @__PURE__ */ new Set();
1580
+ if (issuerOrMetadataUrl.includes("/.well-known/oauth-authorization-server") || issuerOrMetadataUrl.includes("/.well-known/openid-configuration")) {
1581
+ candidates.add(issuerOrMetadataUrl);
1582
+ return [...candidates];
1583
+ }
1584
+ const url = new URL(issuerOrMetadataUrl);
1585
+ const normalizedPath = url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname;
1586
+ if (!normalizedPath || normalizedPath === "/") {
1587
+ candidates.add(`${url.origin}/.well-known/oauth-authorization-server`);
1588
+ candidates.add(`${url.origin}/.well-known/openid-configuration`);
1589
+ return [...candidates];
1590
+ }
1591
+ candidates.add(`${url.origin}/.well-known/oauth-authorization-server${normalizedPath}`);
1592
+ candidates.add(`${url.origin}/.well-known/openid-configuration${normalizedPath}`);
1593
+ candidates.add(`${url.origin}${normalizedPath}/.well-known/openid-configuration`);
1594
+ return [...candidates];
1595
+ }
1596
+ hasExplicitManualOverride(manualConfig, field) {
1597
+ return manualConfig?.manualOverrides?.includes(field) ?? false;
1598
+ }
1599
+ pickAuthConfigValue(field, manualConfig, manualValue, discoveredValue) {
1600
+ if (this.hasExplicitManualOverride(manualConfig, field) && manualValue != null) {
1601
+ return manualValue;
1602
+ }
1603
+ return discoveredValue ?? manualValue;
1604
+ }
1605
+ pickAuthConfigArrayValue(field, manualConfig, manualValue, discoveredValue) {
1606
+ if (this.hasExplicitManualOverride(manualConfig, field) && manualValue?.length) {
1607
+ return manualValue;
1608
+ }
1609
+ if (discoveredValue?.length) {
1610
+ return discoveredValue;
1611
+ }
1612
+ return manualValue?.length ? manualValue : void 0;
1613
+ }
1614
+ mergeAuthConfigs(manualConfig, discoveredConfig) {
1615
+ if (!manualConfig && !discoveredConfig) return null;
1616
+ const manualOverrides = new Set(manualConfig?.manualOverrides ?? []);
1617
+ const authorizationEndpoint = this.pickAuthConfigValue(
1618
+ "authorizationEndpoint",
1619
+ manualConfig,
1620
+ manualConfig?.authorizationEndpoint ?? manualConfig?.loginUrl,
1621
+ discoveredConfig?.authorizationEndpoint ?? discoveredConfig?.loginUrl
1622
+ );
1623
+ const tokenEndpoint = this.pickAuthConfigValue(
1624
+ "tokenEndpoint",
1625
+ manualConfig,
1626
+ manualConfig?.tokenEndpoint ?? manualConfig?.tokenUrl,
1627
+ discoveredConfig?.tokenEndpoint ?? discoveredConfig?.tokenUrl
1628
+ );
1629
+ const callbackUrl = this.pickAuthConfigValue(
1630
+ "callbackUrl",
1631
+ manualConfig,
1632
+ manualConfig?.callbackUrl,
1633
+ discoveredConfig?.callbackUrl
1634
+ ) ?? this.getOAuthCallbackUrl();
1635
+ const merged = {
1636
+ authType: manualConfig?.authType ?? discoveredConfig?.authType ?? "oauth2",
1637
+ issuer: discoveredConfig?.issuer ?? manualConfig?.issuer,
1638
+ authorizationServerUrl: this.pickAuthConfigValue(
1639
+ "authorizationServerUrl",
1640
+ manualConfig,
1641
+ manualConfig?.authorizationServerUrl,
1642
+ discoveredConfig?.authorizationServerUrl
1643
+ ),
1644
+ authorizationServerMetadataUrl: this.pickAuthConfigValue(
1645
+ "authorizationServerMetadataUrl",
1646
+ manualConfig,
1647
+ manualConfig?.authorizationServerMetadataUrl,
1648
+ discoveredConfig?.authorizationServerMetadataUrl
1649
+ ),
1650
+ authorizationEndpoint,
1651
+ loginUrl: authorizationEndpoint,
1652
+ tokenEndpoint,
1653
+ tokenUrl: tokenEndpoint,
1654
+ registrationEndpoint: this.pickAuthConfigValue(
1655
+ "registrationEndpoint",
1656
+ manualConfig,
1657
+ manualConfig?.registrationEndpoint,
1658
+ discoveredConfig?.registrationEndpoint
1659
+ ),
1660
+ clientId: this.pickAuthConfigValue(
1661
+ "clientId",
1662
+ manualConfig,
1663
+ manualConfig?.clientId,
1664
+ discoveredConfig?.clientId
1665
+ ),
1666
+ scopes: this.pickAuthConfigArrayValue(
1667
+ "scopes",
1668
+ manualConfig,
1669
+ manualConfig?.scopes,
1670
+ discoveredConfig?.scopes
1671
+ ),
1672
+ resource: this.pickAuthConfigValue(
1673
+ "resource",
1674
+ manualConfig,
1675
+ manualConfig?.resource,
1676
+ discoveredConfig?.resource
1677
+ ),
1678
+ callbackUrl,
1679
+ protectedResourceMetadataUrl: discoveredConfig?.protectedResourceMetadataUrl ?? manualConfig?.protectedResourceMetadataUrl,
1680
+ clientIdMetadataDocumentSupported: discoveredConfig?.clientIdMetadataDocumentSupported ?? manualConfig?.clientIdMetadataDocumentSupported,
1681
+ resourceParameterSupported: discoveredConfig?.resourceParameterSupported ?? manualConfig?.resourceParameterSupported,
1682
+ registrationPreference: manualConfig?.registrationPreference ?? discoveredConfig?.registrationPreference ?? "auto",
1683
+ clientMode: discoveredConfig?.clientMode ?? manualConfig?.clientMode,
1684
+ authRecipe: manualConfig?.authRecipe ?? discoveredConfig?.authRecipe,
1685
+ manualOverrides: manualOverrides.size ? [...manualOverrides] : void 0,
1686
+ discovered: discoveredConfig?.discovered ?? false
1687
+ };
1688
+ return merged;
1689
+ }
1690
+ async discoverAuthConfig(mcpServerUrl, manualConfig) {
1691
+ let protectedResourceUrl = null;
1692
+ let protectedResource = null;
1693
+ const protectedResourceCandidates = /* @__PURE__ */ new Set();
1694
+ if (manualConfig?.protectedResourceMetadataUrl) {
1695
+ protectedResourceCandidates.add(manualConfig.protectedResourceMetadataUrl);
1696
+ }
1697
+ for (const candidate of this.buildProtectedResourceMetadataCandidates(mcpServerUrl)) {
1698
+ protectedResourceCandidates.add(candidate);
1699
+ }
1700
+ for (const candidate of protectedResourceCandidates) {
1701
+ try {
1702
+ const response = await fetch(candidate, {
1703
+ method: "GET",
1704
+ headers: { Accept: "application/json" }
1705
+ });
1706
+ if (response.ok) {
1707
+ protectedResource = await response.json();
1708
+ protectedResourceUrl = candidate;
1709
+ break;
1710
+ }
1711
+ const authenticateHeader = response.headers.get("www-authenticate");
1712
+ if (authenticateHeader) {
1713
+ const resourceMetadataUrl = this.extractQuotedHeaderValue(authenticateHeader, "resource_metadata");
1714
+ if (resourceMetadataUrl && this.hasSameOrigin(candidate, resourceMetadataUrl)) {
1715
+ const metadataResponse = await fetch(resourceMetadataUrl, {
1716
+ method: "GET",
1717
+ headers: { Accept: "application/json" }
1718
+ });
1719
+ if (metadataResponse.ok) {
1720
+ protectedResource = await metadataResponse.json();
1721
+ protectedResourceUrl = resourceMetadataUrl;
1722
+ break;
1723
+ }
1724
+ }
1725
+ }
1726
+ } catch {
1727
+ }
1728
+ }
1729
+ const authServerUrl = protectedResource?.authorization_servers?.[0] ?? protectedResource?.authorization_server ?? manualConfig?.authorizationServerUrl;
1730
+ try {
1731
+ let metadata = null;
1732
+ let metadataUrl = manualConfig?.authorizationServerMetadataUrl ?? null;
1733
+ const metadataCandidates = /* @__PURE__ */ new Set();
1734
+ if (manualConfig?.authorizationServerMetadataUrl) {
1735
+ metadataCandidates.add(manualConfig.authorizationServerMetadataUrl);
1736
+ }
1737
+ if (authServerUrl) {
1738
+ for (const candidate of this.buildAuthorizationServerMetadataCandidates(authServerUrl)) {
1739
+ metadataCandidates.add(candidate);
1740
+ }
1741
+ }
1742
+ for (const candidate of metadataCandidates) {
1743
+ try {
1744
+ const response = await fetch(candidate, {
1745
+ method: "GET",
1746
+ headers: { Accept: "application/json" }
1747
+ });
1748
+ if (response.ok) {
1749
+ metadata = await response.json();
1750
+ metadataUrl = candidate;
1751
+ break;
1752
+ }
1753
+ } catch {
1754
+ }
1755
+ }
1756
+ if (!metadata && !protectedResource && !manualConfig) {
1757
+ return null;
1758
+ }
1759
+ return {
1760
+ authType: "oauth2",
1761
+ issuer: metadata?.issuer ?? authServerUrl ?? manualConfig?.issuer,
1762
+ authorizationServerUrl: authServerUrl ?? manualConfig?.authorizationServerUrl,
1763
+ authorizationServerMetadataUrl: metadataUrl ?? void 0,
1764
+ authorizationEndpoint: metadata?.authorization_endpoint ?? manualConfig?.authorizationEndpoint ?? manualConfig?.loginUrl,
1765
+ loginUrl: metadata?.authorization_endpoint ?? manualConfig?.loginUrl ?? manualConfig?.authorizationEndpoint,
1766
+ tokenEndpoint: metadata?.token_endpoint ?? manualConfig?.tokenEndpoint ?? manualConfig?.tokenUrl,
1767
+ tokenUrl: metadata?.token_endpoint ?? manualConfig?.tokenUrl ?? manualConfig?.tokenEndpoint,
1768
+ registrationEndpoint: metadata?.registration_endpoint ?? manualConfig?.registrationEndpoint,
1769
+ clientId: manualConfig?.clientId,
1770
+ scopes: protectedResource?.scopes_supported?.length ? protectedResource.scopes_supported : metadata?.scopes_supported ?? manualConfig?.scopes,
1771
+ resource: protectedResource?.resource ?? manualConfig?.resource,
1772
+ callbackUrl: getEffectiveCallbackUrl(manualConfig, this.getOAuthCallbackUrl()),
1773
+ protectedResourceMetadataUrl: protectedResourceUrl ?? manualConfig?.protectedResourceMetadataUrl,
1774
+ clientIdMetadataDocumentSupported: metadata?.client_id_metadata_document_supported ?? manualConfig?.clientIdMetadataDocumentSupported,
1775
+ resourceParameterSupported: metadata?.resource_parameter_supported ?? manualConfig?.resourceParameterSupported,
1776
+ registrationPreference: manualConfig?.registrationPreference ?? "auto",
1777
+ authRecipe: manualConfig?.authRecipe,
1778
+ discovered: Boolean(protectedResource || metadata)
1779
+ };
1780
+ } catch {
1781
+ return manualConfig ? {
1782
+ ...manualConfig,
1783
+ callbackUrl: getEffectiveCallbackUrl(manualConfig, this.getOAuthCallbackUrl()),
1784
+ protectedResourceMetadataUrl: protectedResourceUrl ?? manualConfig.protectedResourceMetadataUrl,
1785
+ resource: protectedResource?.resource ?? manualConfig.resource,
1786
+ scopes: protectedResource?.scopes_supported?.length ? protectedResource.scopes_supported : manualConfig.scopes,
1787
+ discovered: Boolean(protectedResource)
1788
+ } : null;
1789
+ }
1790
+ }
1791
+ async resolveServerAuthConfig(mcpServerUrl, manualConfig) {
1792
+ const discoveredConfig = await this.discoverAuthConfig(mcpServerUrl, manualConfig);
1793
+ return this.mergeAuthConfigs(manualConfig, discoveredConfig);
1794
+ }
1795
+ async ensureServerAuthConfig(mcpServerUrl) {
1796
+ const server = this.agentConfig?.mcpServers?.find((item) => item.url === mcpServerUrl);
1797
+ if (!server) {
1798
+ return null;
1799
+ }
1800
+ if (server.authConfig && (server.authConfig.authType !== "oauth2" || server.authConfig.discovered || !!server.authConfig.authorizationEndpoint || !!server.authConfig.tokenEndpoint || !!server.authConfig.tokenUrl || !!server.authConfig.registrationEndpoint || !!server.authConfig.resource)) {
1801
+ return server.authConfig;
1802
+ }
1803
+ server.authConfig = await this.resolveServerAuthConfig(mcpServerUrl, server.authConfig ?? null);
1804
+ return server.authConfig;
1805
+ }
1806
+ updateServerAuthConfig(mcpServerUrl, authConfig) {
1807
+ const server = this.agentConfig?.mcpServers?.find((item) => item.url === mcpServerUrl);
1808
+ if (server) {
1809
+ server.authConfig = authConfig;
1810
+ }
1811
+ }
1812
+ emit(event, data) {
1813
+ this.listeners.get(event)?.forEach((handler) => handler(data));
1814
+ }
1815
+ // ================================================================
1816
+ // OAuth Token Storage (standalone mode only)
1817
+ // ================================================================
1818
+ /** Generate the legacy token cache suffix used before auth-aware keying. */
1819
+ hashUrl(url) {
1820
+ return btoa(url).replace(/[^a-zA-Z0-9]/g, "").slice(0, 32);
1821
+ }
1822
+ getLegacyTokenStorageKey(mcpServerUrl) {
1823
+ return buildScopedOAuthTokenStorageKey(this.hashUrl(mcpServerUrl));
1824
+ }
1825
+ getAuthSessionKey() {
1826
+ return resolveExplicitAuthSessionKey(this.config);
1827
+ }
1828
+ getTokenStorageKey(mcpServerUrl, authConfig) {
1829
+ return buildScopedOAuthTokenStorageKey(
1830
+ buildTokenCacheKey(authConfig, mcpServerUrl),
1831
+ this.getAuthSessionKey()
1832
+ );
1833
+ }
1834
+ getTokenStorageCandidates(mcpServerUrl) {
1835
+ const currentAuthConfig = this.getServerAuthConfig(mcpServerUrl);
1836
+ const hasExplicitAuthSessionKey = this.getAuthSessionKey() !== null;
1837
+ if (!currentAuthConfig) {
1838
+ return hasExplicitAuthSessionKey ? [{
1839
+ storageKey: this.getTokenStorageKey(mcpServerUrl, null),
1840
+ authConfig: null
1841
+ }] : [{
1842
+ storageKey: this.getLegacyTokenStorageKey(mcpServerUrl),
1843
+ authConfig: null
1844
+ }];
1845
+ }
1846
+ const callbackUrl = getEffectiveCallbackUrl(currentAuthConfig, this.getOAuthCallbackUrl());
1847
+ const candidates = [currentAuthConfig];
1848
+ if (currentAuthConfig.authType === "oauth2") {
1849
+ candidates.push({
1850
+ ...currentAuthConfig,
1851
+ clientMode: "manual",
1852
+ callbackUrl
1853
+ });
1854
+ if (currentAuthConfig.clientId) {
1855
+ candidates.push({
1856
+ ...currentAuthConfig,
1857
+ clientMode: "preregistered",
1858
+ callbackUrl
1859
+ });
1860
+ }
1861
+ if (currentAuthConfig.clientIdMetadataDocumentSupported && this.config.oauthClientMetadataUrl) {
1862
+ candidates.push({
1863
+ ...currentAuthConfig,
1864
+ clientId: this.config.oauthClientMetadataUrl,
1865
+ clientMode: "cimd",
1866
+ callbackUrl
1867
+ });
1868
+ }
1869
+ if (currentAuthConfig.registrationEndpoint) {
1870
+ const cacheKey = buildRegistrationCacheKey(currentAuthConfig, callbackUrl, "dcr");
1871
+ const storedRegistration = loadStoredRegistration(cacheKey, this.getPersistentStorage());
1872
+ if (storedRegistration?.clientId) {
1873
+ candidates.push(applyResolvedRegistration(currentAuthConfig, {
1874
+ cacheKey,
1875
+ mode: "dcr",
1876
+ clientId: storedRegistration.clientId,
1877
+ callbackUrl,
1878
+ resource: currentAuthConfig.resource,
1879
+ authorizationServerUrl: currentAuthConfig.authorizationServerUrl,
1880
+ authorizationServerMetadataUrl: currentAuthConfig.authorizationServerMetadataUrl,
1881
+ registrationEndpoint: currentAuthConfig.registrationEndpoint
1882
+ }));
1883
+ }
1884
+ }
1885
+ }
1886
+ const seen = /* @__PURE__ */ new Set();
1887
+ const resolved = candidates.map((candidate) => ({
1888
+ storageKey: this.getTokenStorageKey(mcpServerUrl, candidate),
1889
+ authConfig: candidate
1890
+ })).filter((candidate) => {
1891
+ if (seen.has(candidate.storageKey)) return false;
1892
+ seen.add(candidate.storageKey);
1893
+ return true;
1894
+ });
1895
+ if (!hasExplicitAuthSessionKey) {
1896
+ resolved.push({
1897
+ storageKey: this.getLegacyTokenStorageKey(mcpServerUrl),
1898
+ authConfig: currentAuthConfig
1899
+ });
1900
+ }
1901
+ return resolved;
1902
+ }
1903
+ /** Load OAuth token from memory/persistent storage using auth-aware cache keying. */
1904
+ loadOAuthToken(mcpServerUrl) {
1905
+ for (const candidate of this.getTokenStorageCandidates(mcpServerUrl)) {
1906
+ const cached = this.oauthTokens.get(candidate.storageKey);
1907
+ if (cached) {
1908
+ if (candidate.authConfig) {
1909
+ this.updateServerAuthConfig(mcpServerUrl, candidate.authConfig);
1910
+ }
1911
+ return cached;
1912
+ }
1913
+ }
1914
+ try {
1915
+ const storage = this.getPersistentStorage() ?? (typeof localStorage !== "undefined" ? localStorage : null);
1916
+ if (storage) {
1917
+ for (const candidate of this.getTokenStorageCandidates(mcpServerUrl)) {
1918
+ const stored = storage.getItem(candidate.storageKey);
1919
+ if (stored) {
1920
+ const data = JSON.parse(stored);
1921
+ if (data.accessToken && data.expiresAt) {
1922
+ this.oauthTokens.set(candidate.storageKey, data);
1923
+ if (candidate.authConfig) {
1924
+ this.updateServerAuthConfig(mcpServerUrl, candidate.authConfig);
1925
+ }
1926
+ return data;
1927
+ }
1928
+ }
1929
+ }
1930
+ }
1931
+ } catch {
1932
+ }
1933
+ return null;
1934
+ }
1935
+ /** Check if we have a valid (non-expired) OAuth token */
1936
+ hasValidOAuthToken(mcpServerUrl) {
1937
+ const token = this.loadOAuthToken(mcpServerUrl);
1938
+ if (!token) return false;
1939
+ return token.expiresAt > Date.now() || !!token.refreshToken;
1940
+ }
1941
+ /** Store OAuth token to memory and persistent storage */
1942
+ storeOAuthToken(mcpServerUrl, tokenResponse) {
1943
+ const resolvedAuthConfig = tokenResponse.resolvedAuthConfig ?? this.getServerAuthConfig(mcpServerUrl);
1944
+ const storageKey = this.getTokenStorageKey(mcpServerUrl, resolvedAuthConfig);
1945
+ const expiresIn = tokenResponse.expiresIn ?? 3600;
1946
+ const expiresAt = Date.now() + expiresIn * 1e3 - 60 * 1e3;
1947
+ const data = {
1948
+ accessToken: tokenResponse.accessToken,
1949
+ refreshToken: tokenResponse.refreshToken,
1950
+ expiresAt
1951
+ };
1952
+ this.oauthTokens.set(storageKey, data);
1953
+ try {
1954
+ const storage = this.getPersistentStorage() ?? (typeof localStorage !== "undefined" ? localStorage : null);
1955
+ if (storage) {
1956
+ storage.setItem(storageKey, JSON.stringify(data));
1957
+ }
1958
+ } catch {
1959
+ }
1960
+ }
1961
+ /** Clear OAuth token from memory and persistent storage */
1962
+ clearOAuthToken(mcpServerUrl) {
1963
+ for (const candidate of this.getTokenStorageCandidates(mcpServerUrl)) {
1964
+ this.oauthTokens.delete(candidate.storageKey);
1965
+ }
1966
+ try {
1967
+ const storage = this.getPersistentStorage() ?? (typeof localStorage !== "undefined" ? localStorage : null);
1968
+ if (storage) {
1969
+ for (const candidate of this.getTokenStorageCandidates(mcpServerUrl)) {
1970
+ storage.removeItem(candidate.storageKey);
1971
+ }
1972
+ }
1973
+ } catch {
1974
+ }
1975
+ }
1976
+ /** Refresh OAuth token using refresh token */
1977
+ async refreshOAuthToken(mcpServerUrl, refreshToken) {
1978
+ const authConfig = await this.ensureServerAuthConfig(mcpServerUrl);
1979
+ const tokenUrl = authConfig?.tokenEndpoint ?? authConfig?.tokenUrl;
1980
+ if (!tokenUrl) return void 0;
1981
+ try {
1982
+ const body = new URLSearchParams({
1983
+ grant_type: "refresh_token",
1984
+ refresh_token: refreshToken
1985
+ });
1986
+ if (authConfig?.clientId) body.set("client_id", authConfig.clientId);
1987
+ if (authConfig?.resource) body.set("resource", authConfig.resource);
1988
+ const response = await fetch(tokenUrl, {
1989
+ method: "POST",
1990
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
1991
+ body
1992
+ });
1993
+ if (response.ok) {
1994
+ const data = await response.json();
1995
+ if (data.access_token) {
1996
+ const tokenResponse = {
1997
+ accessToken: data.access_token,
1998
+ refreshToken: data.refresh_token ?? refreshToken,
1999
+ expiresIn: data.expires_in,
2000
+ resolvedAuthConfig: authConfig ?? void 0
2001
+ };
2002
+ this.storeOAuthToken(mcpServerUrl, tokenResponse);
2003
+ return data.access_token;
2004
+ }
2005
+ }
2006
+ } catch {
2007
+ }
2008
+ return void 0;
2009
+ }
2010
+ // ================================================================
2011
+ // Token Resolution
2012
+ // ================================================================
2013
+ /**
2014
+ * Resolve the auth token for an MCP server.
2015
+ * - OAuth mode: Checks stored token, refreshes if expired, triggers auth if needed
2016
+ */
2017
+ async resolveToken(mcpServerUrl) {
2018
+ if (this.manuallySignedOutServers.has(mcpServerUrl)) {
2019
+ return void 0;
2020
+ }
2021
+ const authConfig = await this.ensureServerAuthConfig(mcpServerUrl);
2022
+ const stored = this.loadOAuthToken(mcpServerUrl);
2023
+ if (stored) {
2024
+ if (stored.expiresAt > Date.now()) {
2025
+ return stored.accessToken;
2026
+ }
2027
+ if (stored.refreshToken) {
2028
+ const refreshed = await this.refreshOAuthToken(mcpServerUrl, stored.refreshToken);
2029
+ if (refreshed) return refreshed;
2030
+ }
2031
+ this.clearOAuthToken(mcpServerUrl);
2032
+ }
2033
+ if (this.config.onAuthRequired) {
2034
+ if (authConfig) {
2035
+ const isBuiltInPopupAuth = this.config.onAuthRequired.__mcpStackBuiltinPopupAuth === true;
2036
+ const isAppTokenAuth = this.config.auth?.mode === "app-token";
2037
+ const authConfigForHandler = authConfig.authType === "oauth2" && !isBuiltInPopupAuth && !isAppTokenAuth ? await this.resolveOAuthClientRegistration(authConfig) : authConfig;
2038
+ if (authConfigForHandler) {
2039
+ this.updateServerAuthConfig(mcpServerUrl, authConfigForHandler);
2040
+ }
2041
+ const tokenResponse = await this.config.onAuthRequired(
2042
+ mcpServerUrl,
2043
+ authConfigForHandler ?? authConfig
2044
+ );
2045
+ if (tokenResponse?.accessToken) {
2046
+ if (tokenResponse.resolvedAuthConfig) {
2047
+ this.updateServerAuthConfig(mcpServerUrl, tokenResponse.resolvedAuthConfig);
2048
+ }
2049
+ this.storeOAuthToken(mcpServerUrl, tokenResponse);
2050
+ return tokenResponse.accessToken;
2051
+ }
2052
+ }
2053
+ }
2054
+ return void 0;
2055
+ }
2056
+ // ================================================================
2057
+ // Chat Loop
2058
+ // ================================================================
2059
+ /**
2060
+ * The core orchestration loop:
2061
+ * 1. Send message to chat API
2062
+ * 2. Stream response
2063
+ * 3. If tool_call → execute tool via MCP → send result → continue
2064
+ * 4. If message_end → done
2065
+ */
2066
+ async runChatLoop(message) {
2067
+ this.abortController = new AbortController();
2068
+ this.emit("thinking", true);
2069
+ const chatBody = {
2070
+ agentId: this.config.agentId,
2071
+ conversationId: this.conversationId,
2072
+ message,
2073
+ externalUserId: this.resolveExternalUserId(),
2074
+ context: this.config.context
2075
+ };
2076
+ const externalUser = this.buildExternalUserContext();
2077
+ if (externalUser) {
2078
+ chatBody.externalUser = externalUser;
2079
+ }
2080
+ const clientToolSchemas = this.clientToolsToSchemas();
2081
+ if (clientToolSchemas.length > 0) {
2082
+ chatBody.clientTools = clientToolSchemas;
2083
+ }
2084
+ let response = await this.callChatApi(chatBody, "chat");
2085
+ while (true) {
2086
+ const result = await this.processSseStream(response);
2087
+ if (result.type === "message_end") {
2088
+ break;
2089
+ }
2090
+ if (result.type === "tool_call") {
2091
+ const toolCall = result.data;
2092
+ const startTime = Date.now();
2093
+ try {
2094
+ const toolResult = await this.executeTool(toolCall);
2095
+ const duration = Date.now() - startTime;
2096
+ const toolCallMsg = this.messages.find(
2097
+ (m) => m.role === "tool_call" && m.toolCallId === toolCall.toolCallId
2098
+ );
2099
+ if (toolCallMsg) {
2100
+ toolCallMsg.toolCallStatus = "completed";
2101
+ toolCallMsg.toolCallDuration = duration;
2102
+ toolCallMsg.toolResult = typeof toolResult === "string" ? toolResult : JSON.stringify(toolResult);
2103
+ }
2104
+ this.emit("tool_result", { toolCallId: toolCall.toolCallId, result: toolResult, duration });
2105
+ const toolResultMsg = {
2106
+ id: crypto.randomUUID(),
2107
+ role: "tool_result",
2108
+ content: typeof toolResult === "string" ? toolResult : JSON.stringify(toolResult),
2109
+ toolCallId: toolCall.toolCallId,
2110
+ toolName: toolCall.toolName,
2111
+ timestamp: /* @__PURE__ */ new Date()
2112
+ };
2113
+ this.messages.push(toolResultMsg);
2114
+ this.emit("thinking", true);
2115
+ const toolResultBody = {
2116
+ conversationId: this.conversationId,
2117
+ toolCallId: toolCall.toolCallId,
2118
+ result: toolResult,
2119
+ durationMs: duration,
2120
+ context: this.config.context
2121
+ };
2122
+ const clientToolSchemas2 = this.clientToolsToSchemas();
2123
+ if (clientToolSchemas2.length > 0) {
2124
+ toolResultBody.clientTools = clientToolSchemas2;
2125
+ }
2126
+ response = await this.callChatApi(toolResultBody, "chat/tool-result");
2127
+ } catch (err) {
2128
+ const duration = Date.now() - startTime;
2129
+ const errorMsg = err instanceof Error ? err.message : "Tool execution failed";
2130
+ const toolCallMsg = this.messages.find(
2131
+ (m) => m.role === "tool_call" && m.toolCallId === toolCall.toolCallId
2132
+ );
2133
+ if (toolCallMsg) {
2134
+ toolCallMsg.toolCallStatus = "error";
2135
+ toolCallMsg.toolCallDuration = duration;
2136
+ toolCallMsg.toolError = errorMsg;
2137
+ }
2138
+ this.emit("tool_error", { toolCallId: toolCall.toolCallId, error: errorMsg, duration });
2139
+ const errorResult = `Error: ${errorMsg}`;
2140
+ const toolResultMsg = {
2141
+ id: crypto.randomUUID(),
2142
+ role: "tool_result",
2143
+ content: errorResult,
2144
+ toolCallId: toolCall.toolCallId,
2145
+ toolName: toolCall.toolName,
2146
+ timestamp: /* @__PURE__ */ new Date()
2147
+ };
2148
+ this.messages.push(toolResultMsg);
2149
+ this.emit("thinking", true);
2150
+ try {
2151
+ const toolResultBody = {
2152
+ conversationId: this.conversationId,
2153
+ toolCallId: toolCall.toolCallId,
2154
+ result: errorResult,
2155
+ isError: true,
2156
+ durationMs: duration,
2157
+ context: this.config.context
2158
+ };
2159
+ const clientToolSchemas2 = this.clientToolsToSchemas();
2160
+ if (clientToolSchemas2.length > 0) {
2161
+ toolResultBody.clientTools = clientToolSchemas2;
2162
+ }
2163
+ response = await this.callChatApi(toolResultBody, "chat/tool-result");
2164
+ } catch {
2165
+ this.emit("error", { code: "tool_error", message: errorMsg });
2166
+ break;
2167
+ }
2168
+ }
2169
+ }
2170
+ if (result.type === "error") {
2171
+ break;
2172
+ }
2173
+ }
2174
+ }
2175
+ async callChatApi(body, endpoint) {
2176
+ const token = await this.resolveAuthToken();
2177
+ const response = await fetch(
2178
+ `${this.config.agentServiceUrl}/api/v1/${endpoint}`,
2179
+ {
2180
+ method: "POST",
2181
+ headers: {
2182
+ "Content-Type": "application/json",
2183
+ Authorization: `Bearer ${token}`
2184
+ },
2185
+ body: JSON.stringify(body),
2186
+ signal: this.abortController?.signal
2187
+ }
2188
+ );
2189
+ if (!response.ok) {
2190
+ throw new Error(await getResponseErrorMessage(response));
2191
+ }
2192
+ return response;
2193
+ }
2194
+ async fetchConversationMessages(conversationId, cursor, pageSize = 50) {
2195
+ const token = await this.resolveAuthToken();
2196
+ const params = new URLSearchParams();
2197
+ params.set("pageSize", String(pageSize));
2198
+ if (cursor) {
2199
+ params.set("cursor", cursor);
2200
+ }
2201
+ const response = await fetch(
2202
+ `${this.config.agentServiceUrl}/api/v1/chat/conversations/${encodeURIComponent(conversationId)}/messages?${params.toString()}`,
2203
+ {
2204
+ headers: {
2205
+ Authorization: `Bearer ${token}`
2206
+ }
2207
+ }
2208
+ );
2209
+ if (!response.ok) {
2210
+ throw new Error(await getResponseErrorMessage(response));
2211
+ }
2212
+ return await response.json();
2213
+ }
2214
+ applyConversationPage(page, prepend) {
2215
+ const mappedMessages = page.messages.map((message) => this.mapReplayMessage(message));
2216
+ this.conversationId = page.conversationId;
2217
+ this.historyCursor = page.nextCursor ?? null;
2218
+ this.hasOlderMessages = page.hasNextPage;
2219
+ this.messages = prepend ? [...mappedMessages, ...this.messages] : mappedMessages;
2220
+ }
2221
+ mapReplayMessage(message) {
2222
+ const timestamp = new Date(message.createdAt);
2223
+ return {
2224
+ id: message.id,
2225
+ role: message.role,
2226
+ content: message.content ?? "",
2227
+ toolName: message.toolName ?? void 0,
2228
+ toolLabel: message.toolLabel ?? void 0,
2229
+ toolCallId: message.toolCallId ?? void 0,
2230
+ timestamp,
2231
+ toolCallStatus: message.toolCallStatus ?? void 0,
2232
+ toolCallStartTime: message.toolCallDurationMs != null ? timestamp.getTime() - message.toolCallDurationMs : void 0,
2233
+ toolCallDuration: message.toolCallDurationMs ?? void 0,
2234
+ toolResult: message.toolResultJson ?? void 0,
2235
+ toolError: message.toolError ?? void 0,
2236
+ errorCode: message.errorCode ?? void 0,
2237
+ metadataJson: message.metadataJson ?? null
2238
+ };
2239
+ }
2240
+ /**
2241
+ * Process an SSE stream from the chat API.
2242
+ * Returns when the stream ends (either message_end or tool_call).
2243
+ */
2244
+ async processSseStream(response) {
2245
+ let assistantContent = "";
2246
+ let lastToolCall = null;
2247
+ let emittedThinkingFalse = false;
2248
+ for await (const event of parseSseStream(response, this.abortController?.signal)) {
2249
+ switch (event.type) {
2250
+ case "message_start": {
2251
+ const data = event.data;
2252
+ this.conversationId = data.conversationId;
2253
+ break;
2254
+ }
2255
+ case "content_delta": {
2256
+ const data = event.data;
2257
+ if (!emittedThinkingFalse) {
2258
+ this.emit("thinking", false);
2259
+ emittedThinkingFalse = true;
2260
+ }
2261
+ assistantContent += data.text;
2262
+ this.emit("content_delta", data);
2263
+ break;
2264
+ }
2265
+ case "tool_call": {
2266
+ const data = event.data;
2267
+ if (!emittedThinkingFalse) {
2268
+ this.emit("thinking", false);
2269
+ emittedThinkingFalse = true;
2270
+ }
2271
+ lastToolCall = data;
2272
+ const toolCallMsg = {
2273
+ id: crypto.randomUUID(),
2274
+ role: "tool_call",
2275
+ content: `Calling ${data.toolLabel ?? data.toolName}...`,
2276
+ toolName: data.toolName,
2277
+ toolLabel: data.toolLabel,
2278
+ toolCallId: data.toolCallId,
2279
+ timestamp: /* @__PURE__ */ new Date(),
2280
+ toolCallStatus: "calling",
2281
+ toolCallStartTime: Date.now()
2282
+ };
2283
+ this.messages.push(toolCallMsg);
2284
+ this.emit("tool_call", data);
2285
+ break;
2286
+ }
2287
+ case "message_end": {
2288
+ const data = event.data;
2289
+ if (assistantContent) {
2290
+ const assistantMsg = {
2291
+ id: crypto.randomUUID(),
2292
+ role: "assistant",
2293
+ content: assistantContent,
2294
+ timestamp: /* @__PURE__ */ new Date()
2295
+ };
2296
+ this.messages.push(assistantMsg);
2297
+ this.emit("message", assistantMsg);
2298
+ }
2299
+ this.emit("message_end", data);
2300
+ return { type: "message_end", data };
2301
+ }
2302
+ case "budget_snapshot": {
2303
+ const data = event.data;
2304
+ this.budgetSnapshot = data;
2305
+ this.emit("budget_snapshot", data);
2306
+ break;
2307
+ }
2308
+ case "error": {
2309
+ const data = event.data;
2310
+ if (data.budget) {
2311
+ this.budgetSnapshot = data.budget;
2312
+ this.emit("budget_snapshot", data.budget);
2313
+ }
2314
+ const errorMsg = {
2315
+ id: crypto.randomUUID(),
2316
+ role: "error",
2317
+ content: data.message,
2318
+ timestamp: /* @__PURE__ */ new Date(),
2319
+ errorCode: data.code
2320
+ };
2321
+ this.messages.push(errorMsg);
2322
+ this.emit("message", errorMsg);
2323
+ this.emit("error", data);
2324
+ return { type: "error", data };
2325
+ }
2326
+ }
2327
+ }
2328
+ if (lastToolCall) {
2329
+ if (assistantContent) {
2330
+ const assistantMsg = {
2331
+ id: crypto.randomUUID(),
2332
+ role: "assistant",
2333
+ content: assistantContent,
2334
+ timestamp: /* @__PURE__ */ new Date()
2335
+ };
2336
+ this.messages.push(assistantMsg);
2337
+ this.emit("message", assistantMsg);
2338
+ }
2339
+ return { type: "tool_call", data: lastToolCall };
2340
+ }
2341
+ if (assistantContent) {
2342
+ const assistantMsg = {
2343
+ id: crypto.randomUUID(),
2344
+ role: "assistant",
2345
+ content: assistantContent,
2346
+ timestamp: /* @__PURE__ */ new Date()
2347
+ };
2348
+ this.messages.push(assistantMsg);
2349
+ this.emit("message", assistantMsg);
2350
+ }
2351
+ return { type: "message_end" };
2352
+ }
2353
+ // ================================================================
2354
+ // MCP Session Management
2355
+ // ================================================================
2356
+ /** Build headers for MCP server requests */
2357
+ getMcpHeaders(mcpServerUrl) {
2358
+ const headers = {
2359
+ "Content-Type": "application/json",
2360
+ "Accept": "application/json, text/event-stream"
2361
+ };
2362
+ const session = this.mcpSessions.get(mcpServerUrl);
2363
+ if (session?.sessionId) {
2364
+ headers["Mcp-Session-Id"] = session.sessionId;
2365
+ }
2366
+ return headers;
2367
+ }
2368
+ /** Best-effort MCP session teardown so reconnect starts cleanly after sign-out. */
2369
+ async closeMcpSession(mcpServerUrl) {
2370
+ const session = this.mcpSessions.get(mcpServerUrl);
2371
+ if (!session?.sessionId) return;
2372
+ const headers = {
2373
+ "Accept": "application/json, text/event-stream",
2374
+ "Mcp-Session-Id": session.sessionId
2375
+ };
2376
+ const storedToken = this.loadOAuthToken(mcpServerUrl);
2377
+ if (storedToken?.accessToken) {
2378
+ headers["Authorization"] = `Bearer ${storedToken.accessToken}`;
2379
+ }
2380
+ try {
2381
+ await fetch(mcpServerUrl, {
2382
+ method: "DELETE",
2383
+ headers,
2384
+ credentials: this.config.useCookies ? "include" : "omit"
2385
+ });
2386
+ } catch {
2387
+ }
2388
+ this.mcpSessions.set(mcpServerUrl, {
2389
+ sessionId: null,
2390
+ authStatus: session.authStatus
2391
+ });
2392
+ }
2393
+ /** Initialize the MCP session for a specific server (required before tools/call) */
2394
+ async initMcpSession(mcpServerUrl) {
2395
+ const session = this.mcpSessions.get(mcpServerUrl);
2396
+ if (session?.sessionId) return;
2397
+ const headers = this.getMcpHeaders(mcpServerUrl);
2398
+ await this.ensureServerAuthConfig(mcpServerUrl);
2399
+ const token = await this.resolveToken(mcpServerUrl);
2400
+ if (token) headers["Authorization"] = `Bearer ${token}`;
2401
+ const initPayload = JSON.stringify({
2402
+ jsonrpc: "2.0",
2403
+ id: 1,
2404
+ method: "initialize",
2405
+ params: {
2406
+ protocolVersion: DEFAULT_MCP_PROTOCOL_VERSION,
2407
+ capabilities: {},
2408
+ clientInfo: { name: "mcpstack-agent-sdk", version: "0.1.0" }
2409
+ }
2410
+ });
2411
+ const initResponse = await fetch(mcpServerUrl, {
2412
+ method: "POST",
2413
+ headers,
2414
+ credentials: this.config.useCookies ? "include" : "omit",
2415
+ body: initPayload
2416
+ });
2417
+ if (initResponse.status === 401) {
2418
+ this.clearOAuthToken(mcpServerUrl);
2419
+ this.updateMcpAuthStatus(mcpServerUrl, "needs_auth");
2420
+ const freshToken = await this.resolveToken(mcpServerUrl);
2421
+ if (freshToken) {
2422
+ headers["Authorization"] = `Bearer ${freshToken}`;
2423
+ const retryResponse = await fetch(mcpServerUrl, {
2424
+ method: "POST",
2425
+ headers,
2426
+ credentials: this.config.useCookies ? "include" : "omit",
2427
+ body: initPayload
2428
+ });
2429
+ if (retryResponse.ok) {
2430
+ const sessionId2 = retryResponse.headers.get("mcp-session-id");
2431
+ this.mcpSessions.set(mcpServerUrl, { sessionId: sessionId2, authStatus: "connected" });
2432
+ this.updateMcpAuthStatus(mcpServerUrl, "connected");
2433
+ await retryResponse.text().catch(() => {
2434
+ });
2435
+ const notifyHeaders2 = this.getMcpHeaders(mcpServerUrl);
2436
+ notifyHeaders2["Authorization"] = `Bearer ${freshToken}`;
2437
+ await fetch(mcpServerUrl, {
2438
+ method: "POST",
2439
+ headers: notifyHeaders2,
2440
+ credentials: this.config.useCookies ? "include" : "omit",
2441
+ body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })
2442
+ });
2443
+ return;
2444
+ }
2445
+ }
2446
+ throw new Error("MCP initialization failed (401): Authentication required");
2447
+ }
2448
+ if (!initResponse.ok) {
2449
+ const errorText = await initResponse.text().catch(() => "MCP init error");
2450
+ throw new Error(`MCP initialization failed (${initResponse.status}): ${errorText}`);
2451
+ }
2452
+ const sessionId = initResponse.headers.get("mcp-session-id");
2453
+ this.mcpSessions.set(mcpServerUrl, { sessionId, authStatus: "connected" });
2454
+ this.updateMcpAuthStatus(mcpServerUrl, "connected");
2455
+ await initResponse.text().catch(() => {
2456
+ });
2457
+ const notifyHeaders = this.getMcpHeaders(mcpServerUrl);
2458
+ if (token) notifyHeaders["Authorization"] = `Bearer ${token}`;
2459
+ await fetch(mcpServerUrl, {
2460
+ method: "POST",
2461
+ headers: notifyHeaders,
2462
+ credentials: this.config.useCookies ? "include" : "omit",
2463
+ body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })
2464
+ });
2465
+ }
2466
+ /** Update auth status for an MCP server and emit event */
2467
+ updateMcpAuthStatus(mcpServerUrl, authStatus) {
2468
+ const session = this.mcpSessions.get(mcpServerUrl);
2469
+ if (session) {
2470
+ session.authStatus = authStatus;
2471
+ } else {
2472
+ this.mcpSessions.set(mcpServerUrl, { sessionId: null, authStatus });
2473
+ }
2474
+ const serverInfo = this.agentConfig?.mcpServers?.find((s) => s.url === mcpServerUrl);
2475
+ this.emit("mcp_auth_status", {
2476
+ mcpServerUrl,
2477
+ mcpServerName: serverInfo?.name ?? mcpServerUrl,
2478
+ authStatus
2479
+ });
2480
+ }
2481
+ /** Parse a JSON-RPC response from either JSON or SSE format */
2482
+ async parseMcpResponse(response) {
2483
+ const contentType = (response.headers.get("content-type") || "").toLowerCase();
2484
+ if (contentType.includes("text/event-stream")) {
2485
+ const text = await response.text();
2486
+ const lines = text.split("\n");
2487
+ let jsonData = "";
2488
+ for (const line of lines) {
2489
+ if (line.startsWith("data: ")) {
2490
+ jsonData += line.slice(6);
2491
+ }
2492
+ }
2493
+ if (!jsonData) {
2494
+ throw new Error("No data received from MCP server SSE response");
2495
+ }
2496
+ return JSON.parse(jsonData);
2497
+ }
2498
+ return response.json();
2499
+ }
2500
+ // ================================================================
2501
+ // Tool Execution
2502
+ // ================================================================
2503
+ async executeTool(toolCall) {
2504
+ const isClientTool = toolCall.source === "client" || !toolCall.mcpServerUrl;
2505
+ if (isClientTool && this.config.clientTools) {
2506
+ const def = this.config.clientTools[toolCall.toolName];
2507
+ if (def) {
2508
+ const result2 = await def.execute(toolCall.arguments ?? {});
2509
+ return result2;
2510
+ }
2511
+ throw new Error(`Unknown client tool: ${toolCall.toolName}`);
2512
+ }
2513
+ const mcpServerUrl = toolCall.mcpServerUrl || this.agentConfig?.mcpServerUrl;
2514
+ if (!mcpServerUrl) {
2515
+ throw new Error("No MCP server URL for tool call");
2516
+ }
2517
+ await this.initMcpSession(mcpServerUrl);
2518
+ const token = await this.resolveToken(mcpServerUrl);
2519
+ const headers = this.getMcpHeaders(mcpServerUrl);
2520
+ if (token) headers["Authorization"] = `Bearer ${token}`;
2521
+ const toolCallBody = JSON.stringify({
2522
+ jsonrpc: "2.0",
2523
+ id: 2,
2524
+ method: "tools/call",
2525
+ params: { name: toolCall.toolName, arguments: toolCall.arguments }
2526
+ });
2527
+ let response = await fetch(mcpServerUrl, {
2528
+ method: "POST",
2529
+ headers,
2530
+ credentials: this.config.useCookies ? "include" : "omit",
2531
+ body: toolCallBody,
2532
+ signal: this.abortController?.signal
2533
+ });
2534
+ const session = this.mcpSessions.get(mcpServerUrl);
2535
+ if (response.status === 404 && session?.sessionId) {
2536
+ this.mcpSessions.set(mcpServerUrl, { ...session, sessionId: null });
2537
+ await this.initMcpSession(mcpServerUrl);
2538
+ const retryHeaders = this.getMcpHeaders(mcpServerUrl);
2539
+ if (token) retryHeaders["Authorization"] = `Bearer ${token}`;
2540
+ response = await fetch(mcpServerUrl, {
2541
+ method: "POST",
2542
+ headers: retryHeaders,
2543
+ credentials: this.config.useCookies ? "include" : "omit",
2544
+ body: toolCallBody,
2545
+ signal: this.abortController?.signal
2546
+ });
2547
+ }
2548
+ if (response.status === 401) {
2549
+ this.clearOAuthToken(mcpServerUrl);
2550
+ this.updateMcpAuthStatus(mcpServerUrl, "needs_auth");
2551
+ const freshToken = await this.resolveToken(mcpServerUrl);
2552
+ if (freshToken) {
2553
+ const authHeaders = this.getMcpHeaders(mcpServerUrl);
2554
+ authHeaders["Authorization"] = `Bearer ${freshToken}`;
2555
+ response = await fetch(mcpServerUrl, {
2556
+ method: "POST",
2557
+ headers: authHeaders,
2558
+ credentials: this.config.useCookies ? "include" : "omit",
2559
+ body: toolCallBody,
2560
+ signal: this.abortController?.signal
2561
+ });
2562
+ if (response.ok) {
2563
+ this.updateMcpAuthStatus(mcpServerUrl, "connected");
2564
+ }
2565
+ }
2566
+ if (!response.ok) {
2567
+ const errorText = await response.text().catch(() => "Authentication required");
2568
+ throw new Error(`Tool execution failed (401): ${errorText}`);
2569
+ }
2570
+ }
2571
+ if (!response.ok) {
2572
+ const errorText = await response.text().catch(() => "MCP server error");
2573
+ throw new Error(`Tool execution failed (${response.status}): ${errorText}`);
2574
+ }
2575
+ const currentSession = this.mcpSessions.get(mcpServerUrl);
2576
+ if (currentSession?.authStatus === "needs_auth") {
2577
+ this.updateMcpAuthStatus(mcpServerUrl, "connected");
2578
+ }
2579
+ const result = await this.parseMcpResponse(response);
2580
+ if (result.error) {
2581
+ throw new Error(`MCP error (${result.error.code}): ${result.error.message}`);
2582
+ }
2583
+ if (result.result?.content) {
2584
+ const textContent = result.result.content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
2585
+ return textContent || result.result;
2586
+ }
2587
+ return result.result ?? result;
2588
+ }
2589
+ };
2590
+
2591
+ // src/app/types.ts
2592
+ var APP_AGENT_APPROVAL_ACTION = "requestApproval";
2593
+ var APP_AGENT_INPUT_ACTION = "requestInput";
2594
+
2595
+ // src/app/presentation.ts
2596
+ function isAssistantMessage(message) {
2597
+ return message.role === "assistant";
2598
+ }
2599
+ function isUserMessage(message) {
2600
+ return message.role === "user";
2601
+ }
2602
+ function isErrorMessage(message) {
2603
+ return message.role === "error";
2604
+ }
2605
+ function isToolCallMessage(message) {
2606
+ return message.role === "tool_call";
2607
+ }
2608
+ function deriveVisibleMessages(messages) {
2609
+ return messages.filter(
2610
+ (message) => isAssistantMessage(message) || isUserMessage(message) || isErrorMessage(message) || isToolCallMessage(message)
2611
+ );
2612
+ }
2613
+ function deriveConversationMessages(messages) {
2614
+ return messages.filter(
2615
+ (message) => isUserMessage(message) || isAssistantMessage(message) || isErrorMessage(message)
2616
+ );
2617
+ }
2618
+ function deriveToolMessages(messages) {
2619
+ return messages.filter(isToolCallMessage);
2620
+ }
2621
+ function getLatestAssistantMessage(messages) {
2622
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
2623
+ const message = messages[index];
2624
+ if (message && isAssistantMessage(message)) {
2625
+ return message;
2626
+ }
2627
+ }
2628
+ return null;
2629
+ }
2630
+ function getLatestUserMessage(messages) {
2631
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
2632
+ const message = messages[index];
2633
+ if (message && isUserMessage(message)) {
2634
+ return message;
2635
+ }
2636
+ }
2637
+ return null;
2638
+ }
2639
+ function getLatestToolMessage(messages) {
2640
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
2641
+ const message = messages[index];
2642
+ if (message && isToolCallMessage(message)) {
2643
+ return message;
2644
+ }
2645
+ }
2646
+ return null;
2647
+ }
2648
+ function createInlinePendingTurnState(prompt, messages) {
2649
+ return {
2650
+ prompt,
2651
+ baselineAssistantId: getLatestAssistantMessage(messages)?.id ?? null,
2652
+ baselineToolCount: deriveToolMessages(messages).length
2653
+ };
2654
+ }
2655
+ function applyUserMessageOverrides(messages, overrides) {
2656
+ return messages.map(
2657
+ (message) => message.role === "user" && overrides[message.id] ? { ...message, content: overrides[message.id] } : message
2658
+ );
2659
+ }
2660
+ function buildRenderedNodes(messages) {
2661
+ const nodes = [];
2662
+ let toolBuffer = [];
2663
+ const flushTools = (id) => {
2664
+ if (toolBuffer.length > 0) {
2665
+ nodes.push({ kind: "tools", id: `tools-${id}`, tools: toolBuffer });
2666
+ toolBuffer = [];
2667
+ }
2668
+ };
2669
+ messages.forEach((message) => {
2670
+ if (isToolCallMessage(message)) {
2671
+ toolBuffer.push(message);
2672
+ return;
2673
+ }
2674
+ if (message.role === "tool_result") {
2675
+ return;
2676
+ }
2677
+ flushTools(message.id);
2678
+ if (message.role === "user") {
2679
+ nodes.push({ kind: "user", id: message.id, content: message.content });
2680
+ return;
2681
+ }
2682
+ if (message.role === "assistant") {
2683
+ nodes.push({ kind: "assistant", id: message.id, content: message.content });
2684
+ }
2685
+ });
2686
+ if (toolBuffer.length > 0) {
2687
+ nodes.push({ kind: "tools", id: "tools-tail", tools: toolBuffer });
2688
+ }
2689
+ return nodes;
2690
+ }
2691
+ function deriveConversationStatusLabel(options) {
2692
+ const {
2693
+ isReady,
2694
+ isLoading,
2695
+ isThinking,
2696
+ streamingContent,
2697
+ hasError = false,
2698
+ hasIssue = false,
2699
+ hasAttention = false,
2700
+ readyLabel = "Ready",
2701
+ loadingLabel = "Working\u2026",
2702
+ thinkingLabel = "Thinking\u2026",
2703
+ streamingLabel = "Responding\u2026",
2704
+ attentionLabel = "Needs auth",
2705
+ issueLabel = "Needs attention",
2706
+ reconnectingLabel = "Reconnecting\u2026",
2707
+ connectingLabel = "Connecting\u2026"
2708
+ } = options;
2709
+ if (isReady) {
2710
+ if (isLoading) {
2711
+ return loadingLabel;
2712
+ }
2713
+ if (isThinking) {
2714
+ return thinkingLabel;
2715
+ }
2716
+ if (streamingContent && streamingContent.length > 0) {
2717
+ return streamingLabel;
2718
+ }
2719
+ if (hasAttention) {
2720
+ return attentionLabel;
2721
+ }
2722
+ if (hasIssue || hasError) {
2723
+ return issueLabel;
2724
+ }
2725
+ return readyLabel;
2726
+ }
2727
+ return hasIssue || hasError ? reconnectingLabel : connectingLabel;
2728
+ }
2729
+ function deriveLastTurnSummary(messages) {
2730
+ const lastUser = getLatestUserMessage(messages);
2731
+ if (!lastUser) {
2732
+ return null;
2733
+ }
2734
+ const lastUserIndex = messages.findIndex((message) => message.id === lastUser.id);
2735
+ if (lastUserIndex < 0) {
2736
+ return null;
2737
+ }
2738
+ const after = messages.slice(lastUserIndex + 1);
2739
+ const tools = deriveToolMessages(after);
2740
+ const lastToolEndedAt = tools.map((tool) => (tool.toolCallDuration ?? 0) + (tool.timestamp ? tool.timestamp.getTime() : 0)).reduce((max, value) => max === null || value > max ? value : max, null);
2741
+ const userStartedAt = lastUser.timestamp ? lastUser.timestamp.getTime() : null;
2742
+ return {
2743
+ prompt: lastUser.content.trim(),
2744
+ toolsUsed: tools.length,
2745
+ durationMs: lastToolEndedAt && userStartedAt ? Math.max(0, lastToolEndedAt - userStartedAt) : null
2746
+ };
2747
+ }
2748
+ function deriveInlineFeedState(options) {
2749
+ const {
2750
+ pendingTurn,
2751
+ toolMessages,
2752
+ latestAssistantMessage,
2753
+ streamingContent = "",
2754
+ isLoading,
2755
+ isThinking,
2756
+ maxRecentTools = 4
2757
+ } = options;
2758
+ const startIndex = pendingTurn ? Math.max(
2759
+ pendingTurn.baselineToolCount,
2760
+ toolMessages.length - maxRecentTools
2761
+ ) : Math.max(toolMessages.length - maxRecentTools, 0);
2762
+ const recentTools = toolMessages.slice(startIndex);
2763
+ const hasFreshAssistantReply = Boolean(
2764
+ latestAssistantMessage && (!pendingTurn || latestAssistantMessage.id !== pendingTurn.baselineAssistantId)
2765
+ );
2766
+ const previewText = streamingContent || (hasFreshAssistantReply ? latestAssistantMessage.content : null);
2767
+ const waitingForActivity = Boolean(pendingTurn) && recentTools.length === 0 && !streamingContent && (isLoading || isThinking);
2768
+ const isActive = Boolean(isLoading || isThinking || streamingContent.length > 0);
2769
+ return {
2770
+ isActive,
2771
+ pendingPrompt: pendingTurn?.prompt ?? null,
2772
+ recentTools,
2773
+ previewText,
2774
+ waitingForActivity
2775
+ };
2776
+ }
2777
+
2778
+ // src/app/oauth.ts
2779
+ function normalizeOptionalValue(value) {
2780
+ if (!value) {
2781
+ return void 0;
2782
+ }
2783
+ const trimmed = value.trim();
2784
+ return trimmed || void 0;
2785
+ }
2786
+ function isGatewayAuthorizeUrl(authorizationEndpoint) {
2787
+ try {
2788
+ const url = new URL(authorizationEndpoint);
2789
+ return /\/api\/v1\/gateway\/[^/]+\/authorize$/i.test(url.pathname);
2790
+ } catch {
2791
+ return false;
2792
+ }
2793
+ }
2794
+ function base64UrlEncode(bytes) {
2795
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2796
+ }
2797
+ async function randomToken(length) {
2798
+ const bytes = new Uint8Array(length);
2799
+ crypto.getRandomValues(bytes);
2800
+ return base64UrlEncode(bytes);
2801
+ }
2802
+ async function createCodeChallenge(verifier) {
2803
+ const encoder = new TextEncoder();
2804
+ const data = encoder.encode(verifier);
2805
+ const hash = await crypto.subtle.digest("SHA-256", data);
2806
+ return base64UrlEncode(new Uint8Array(hash));
2807
+ }
2808
+ function createPlatformAuthHandler(options) {
2809
+ return async (_mcpServerUrl, authConfig) => {
2810
+ if (!options.platform.auth) {
2811
+ return void 0;
2812
+ }
2813
+ const authorizationEndpoint = authConfig.authorizationEndpoint ?? authConfig.loginUrl;
2814
+ const tokenEndpoint = authConfig.tokenEndpoint ?? authConfig.tokenUrl;
2815
+ const clientId = authConfig.clientId;
2816
+ const redirectUri = authConfig.callbackUrl ?? options.oauthCallbackUrl;
2817
+ if (!authorizationEndpoint || !tokenEndpoint || !clientId || !redirectUri) {
2818
+ return void 0;
2819
+ }
2820
+ const verifier = await randomToken(48);
2821
+ const state = await randomToken(24);
2822
+ const challenge = await createCodeChallenge(verifier);
2823
+ const authorizeUrl = new URL(authorizationEndpoint);
2824
+ authorizeUrl.searchParams.set("response_type", "code");
2825
+ authorizeUrl.searchParams.set("client_id", clientId);
2826
+ authorizeUrl.searchParams.set("redirect_uri", redirectUri);
2827
+ authorizeUrl.searchParams.set("state", state);
2828
+ authorizeUrl.searchParams.set("code_challenge", challenge);
2829
+ authorizeUrl.searchParams.set("code_challenge_method", "S256");
2830
+ if (authConfig.scopes?.length) {
2831
+ authorizeUrl.searchParams.set("scope", authConfig.scopes.join(" "));
2832
+ }
2833
+ if (authConfig.resource) {
2834
+ authorizeUrl.searchParams.set("resource", authConfig.resource);
2835
+ }
2836
+ if (options.userIdentity && isGatewayAuthorizeUrl(authorizationEndpoint)) {
2837
+ const subject = normalizeOptionalValue(options.userIdentity.subject);
2838
+ const email = normalizeOptionalValue(options.userIdentity.email);
2839
+ const organizationId = normalizeOptionalValue(options.userIdentity.organizationId);
2840
+ const displayName = normalizeOptionalValue(options.userIdentity.displayName);
2841
+ if (subject) {
2842
+ authorizeUrl.searchParams.set("mcpstack_host_subject", subject);
2843
+ }
2844
+ if (email) {
2845
+ authorizeUrl.searchParams.set("mcpstack_host_email", email);
2846
+ }
2847
+ if (organizationId) {
2848
+ authorizeUrl.searchParams.set("mcpstack_host_organization_id", organizationId);
2849
+ }
2850
+ if (displayName) {
2851
+ authorizeUrl.searchParams.set("mcpstack_host_display_name", displayName);
2852
+ }
2853
+ authorizeUrl.searchParams.set("mcpstack_mismatch_policy", "block_with_switch");
2854
+ }
2855
+ const result = await options.platform.auth.openOAuthSession({
2856
+ authorizeUrl: authorizeUrl.toString(),
2857
+ redirectUri,
2858
+ preferEphemeralSession: true
2859
+ });
2860
+ if (result.type !== "success" || !result.url) {
2861
+ return void 0;
2862
+ }
2863
+ const callback = new URL(result.url);
2864
+ const returnedState = callback.searchParams.get("state");
2865
+ const code = callback.searchParams.get("code");
2866
+ if (returnedState !== state || !code) {
2867
+ const errorDescription = callback.searchParams.get("error_description");
2868
+ const errorCode = callback.searchParams.get("error");
2869
+ throw new Error(errorDescription ?? (errorCode ? `OAuth error: ${errorCode}` : "Could not complete OAuth login."));
2870
+ }
2871
+ const tokenResponse = await fetch(tokenEndpoint, {
2872
+ method: "POST",
2873
+ headers: {
2874
+ "Content-Type": "application/x-www-form-urlencoded"
2875
+ },
2876
+ body: new URLSearchParams({
2877
+ grant_type: "authorization_code",
2878
+ client_id: clientId,
2879
+ redirect_uri: redirectUri,
2880
+ code,
2881
+ code_verifier: verifier,
2882
+ ...authConfig.resource ? { resource: authConfig.resource } : {}
2883
+ }).toString()
2884
+ });
2885
+ const payload = await tokenResponse.json().catch(() => null);
2886
+ if (!tokenResponse.ok) {
2887
+ throw new Error(
2888
+ payload?.error_description ?? payload?.error ?? `OAuth sign in failed (${tokenResponse.status}).`
2889
+ );
2890
+ }
2891
+ return {
2892
+ accessToken: payload?.access_token ?? payload?.accessToken,
2893
+ refreshToken: payload?.refresh_token ?? payload?.refreshToken,
2894
+ expiresIn: payload?.expires_in ?? payload?.expiresIn,
2895
+ tokenType: payload?.token_type ?? payload?.tokenType,
2896
+ resolvedAuthConfig: { ...authConfig, callbackUrl: redirectUri }
2897
+ };
2898
+ };
2899
+ }
2900
+
2901
+ // src/app/platform.ts
2902
+ function createBrowserKeyValueStore(storage) {
2903
+ const resolvedStorage = storage ?? (() => {
2904
+ try {
2905
+ return typeof localStorage === "undefined" ? null : localStorage;
2906
+ } catch {
2907
+ return null;
2908
+ }
2909
+ })();
2910
+ return {
2911
+ getItem(key) {
2912
+ return resolvedStorage?.getItem(key) ?? null;
2913
+ },
2914
+ setItem(key, value) {
2915
+ resolvedStorage?.setItem(key, value);
2916
+ },
2917
+ removeItem(key) {
2918
+ resolvedStorage?.removeItem(key);
2919
+ }
2920
+ };
2921
+ }
2922
+ function createBrowserAppAgentPlatform(storage) {
2923
+ return {
2924
+ storage: {
2925
+ durable: createBrowserKeyValueStore(storage)
2926
+ }
2927
+ };
2928
+ }
2929
+ async function resolveStoreValue(value) {
2930
+ return await Promise.resolve(value);
2931
+ }
2932
+
2933
+ // src/app/controller.ts
2934
+ function createId(prefix) {
2935
+ return `${prefix}_${Date.now()}_${Math.random().toString(16).slice(2, 8)}`;
2936
+ }
2937
+ function normalizeSteps(value) {
2938
+ return Array.isArray(value) ? value.filter((entry) => typeof entry === "string" && entry.trim().length > 0) : [];
2939
+ }
2940
+ function normalizeInputFields(value) {
2941
+ if (!Array.isArray(value)) {
2942
+ return [];
2943
+ }
2944
+ return value.flatMap((entry) => {
2945
+ if (!entry || typeof entry !== "object") {
2946
+ return [];
2947
+ }
2948
+ const record = entry;
2949
+ const key = typeof record.key === "string" ? record.key.trim() : "";
2950
+ const label = typeof record.label === "string" ? record.label.trim() : "";
2951
+ const kind = typeof record.kind === "string" ? record.kind : "text";
2952
+ if (!key || !label) {
2953
+ return [];
2954
+ }
2955
+ return [{
2956
+ key,
2957
+ label,
2958
+ kind: kind === "textarea" || kind === "number" || kind === "select" || kind === "boolean" ? kind : "text",
2959
+ required: Boolean(record.required),
2960
+ placeholder: typeof record.placeholder === "string" ? record.placeholder : void 0,
2961
+ options: Array.isArray(record.options) ? record.options.flatMap((option) => {
2962
+ if (!option || typeof option !== "object") {
2963
+ return [];
2964
+ }
2965
+ const optionRecord = option;
2966
+ const optionLabel = typeof optionRecord.label === "string" ? optionRecord.label.trim() : "";
2967
+ const optionValue = typeof optionRecord.value === "string" ? optionRecord.value : "";
2968
+ return optionLabel && optionValue ? [{ label: optionLabel, value: optionValue }] : [];
2969
+ }) : void 0
2970
+ }];
2971
+ });
2972
+ }
2973
+ function isToolRoutingResetError(error) {
2974
+ return error.code === "tool_routing_error" && /tool not found/i.test(error.message);
2975
+ }
2976
+ function mapConnections(agent) {
2977
+ return agent.getMcpServers().map((server) => ({
2978
+ url: server.url,
2979
+ name: server.name,
2980
+ authStatus: server.authStatus,
2981
+ canSignOut: server.canSignOut
2982
+ }));
2983
+ }
2984
+ function normalizeConnections(connections) {
2985
+ if (!connections?.length) {
2986
+ return [];
2987
+ }
2988
+ const byUrl = /* @__PURE__ */ new Map();
2989
+ for (const connection of connections) {
2990
+ const url = connection.url?.trim();
2991
+ if (!url) {
2992
+ continue;
2993
+ }
2994
+ byUrl.set(url, {
2995
+ ...connection,
2996
+ url,
2997
+ name: connection.name?.trim() || url
2998
+ });
2999
+ }
3000
+ return Array.from(byUrl.values());
3001
+ }
3002
+ function mergeConnections(runtimeConnections, existingConnections) {
3003
+ const byUrl = /* @__PURE__ */ new Map();
3004
+ for (const connection of existingConnections) {
3005
+ byUrl.set(connection.url, connection);
3006
+ }
3007
+ for (const connection of runtimeConnections) {
3008
+ byUrl.set(connection.url, connection);
3009
+ }
3010
+ return Array.from(byUrl.values());
3011
+ }
3012
+ var AppAgentController = class {
3013
+ constructor(config) {
3014
+ this.config = config;
3015
+ this.listeners = /* @__PURE__ */ new Set();
3016
+ this.recoveredConversationIds = /* @__PURE__ */ new Set();
3017
+ this.approvalResolvers = /* @__PURE__ */ new Map();
3018
+ this.inputResolvers = /* @__PURE__ */ new Map();
3019
+ this.pendingToolCallsByAction = /* @__PURE__ */ new Map();
3020
+ this.lifecycleUnsubscribers = [];
3021
+ this.userMessageDisplayOverrides = /* @__PURE__ */ new Map();
3022
+ this.started = false;
3023
+ this.disposed = false;
3024
+ this.initializationPromise = null;
3025
+ this.pendingDisplayText = null;
3026
+ this.getSnapshot = () => this.snapshot;
3027
+ this.handleMessage = (message) => {
3028
+ if (message.role === "user" && this.pendingDisplayText) {
3029
+ this.userMessageDisplayOverrides.set(message.id, this.pendingDisplayText);
3030
+ this.pendingDisplayText = null;
3031
+ }
3032
+ this.setState((current) => ({
3033
+ ...current,
3034
+ conversation: {
3035
+ ...current.conversation,
3036
+ messages: [...current.conversation.messages, message],
3037
+ id: this.agent.getConversationId(),
3038
+ streamingContent: "",
3039
+ hasOlderMessages: this.agent.getHasOlderMessages(),
3040
+ pendingTurnSawActivity: current.conversation.pendingTurn ? true : current.conversation.pendingTurnSawActivity
3041
+ }
3042
+ }));
3043
+ void this.persistResumeRecord();
3044
+ this.finalizePendingTurnIfSettled();
3045
+ };
3046
+ this.handleContentDelta = (delta) => {
3047
+ this.setState((current) => ({
3048
+ ...current,
3049
+ conversation: {
3050
+ ...current.conversation,
3051
+ streamingContent: current.conversation.streamingContent + delta.text,
3052
+ pendingTurnSawActivity: current.conversation.pendingTurn ? true : current.conversation.pendingTurnSawActivity
3053
+ }
3054
+ }));
3055
+ };
3056
+ this.handleToolCall = (toolCall) => {
3057
+ if (toolCall.toolName === APP_AGENT_APPROVAL_ACTION || toolCall.toolName === APP_AGENT_INPUT_ACTION) {
3058
+ const queue = this.pendingToolCallsByAction.get(toolCall.toolName) ?? [];
3059
+ queue.push(toolCall.toolCallId);
3060
+ this.pendingToolCallsByAction.set(toolCall.toolName, queue);
3061
+ }
3062
+ this.setState((current) => ({
3063
+ ...current,
3064
+ conversation: {
3065
+ ...current.conversation,
3066
+ id: this.agent.getConversationId(),
3067
+ messages: [
3068
+ ...current.conversation.messages,
3069
+ {
3070
+ id: crypto.randomUUID(),
3071
+ role: "tool_call",
3072
+ content: `Calling ${toolCall.toolLabel ?? toolCall.toolName}...`,
3073
+ toolName: toolCall.toolName,
3074
+ toolLabel: toolCall.toolLabel,
3075
+ toolCallId: toolCall.toolCallId,
3076
+ timestamp: /* @__PURE__ */ new Date(),
3077
+ toolCallStatus: "calling",
3078
+ toolCallStartTime: Date.now()
3079
+ }
3080
+ ],
3081
+ pendingTurnSawActivity: current.conversation.pendingTurn ? true : current.conversation.pendingTurnSawActivity
3082
+ }
3083
+ }));
3084
+ };
3085
+ this.handleToolResult = (data) => {
3086
+ this.setState((current) => ({
3087
+ ...current,
3088
+ conversation: {
3089
+ ...current.conversation,
3090
+ messages: current.conversation.messages.map(
3091
+ (message) => message.role === "tool_call" && message.toolCallId === data.toolCallId ? {
3092
+ ...message,
3093
+ toolCallStatus: "completed",
3094
+ toolCallDuration: data.duration,
3095
+ toolResult: typeof data.result === "string" ? data.result : JSON.stringify(data.result)
3096
+ } : message
3097
+ )
3098
+ }
3099
+ }));
3100
+ this.finalizePendingTurnIfSettled();
3101
+ };
3102
+ this.handleToolError = (data) => {
3103
+ this.setState((current) => ({
3104
+ ...current,
3105
+ conversation: {
3106
+ ...current.conversation,
3107
+ messages: current.conversation.messages.map(
3108
+ (message) => message.role === "tool_call" && message.toolCallId === data.toolCallId ? {
3109
+ ...message,
3110
+ toolCallStatus: "error",
3111
+ toolCallDuration: data.duration,
3112
+ toolError: data.error
3113
+ } : message
3114
+ )
3115
+ }
3116
+ }));
3117
+ this.finalizePendingTurnIfSettled();
3118
+ };
3119
+ this.handleThinking = (thinking) => {
3120
+ this.setState((current) => ({
3121
+ ...current,
3122
+ conversation: {
3123
+ ...current.conversation,
3124
+ isThinking: thinking
3125
+ }
3126
+ }));
3127
+ this.finalizePendingTurnIfSettled();
3128
+ };
3129
+ this.handleLoading = (loading) => {
3130
+ this.setState((current) => ({
3131
+ ...current,
3132
+ conversation: {
3133
+ ...current.conversation,
3134
+ isLoading: loading,
3135
+ error: loading ? null : current.conversation.error,
3136
+ streamingContent: loading ? "" : current.conversation.streamingContent
3137
+ }
3138
+ }));
3139
+ this.finalizePendingTurnIfSettled();
3140
+ };
3141
+ this.handleError = (error) => {
3142
+ this.setState((current) => ({
3143
+ ...current,
3144
+ budget: error.budget ?? current.budget,
3145
+ conversation: {
3146
+ ...current.conversation,
3147
+ error,
3148
+ pendingTurn: null,
3149
+ pendingTurnSawActivity: false
3150
+ }
3151
+ }));
3152
+ if (isToolRoutingResetError(error)) {
3153
+ const conversationId = this.agent.getConversationId();
3154
+ if (conversationId && !this.recoveredConversationIds.has(conversationId)) {
3155
+ this.recoveredConversationIds.add(conversationId);
3156
+ void this.handleStaleConversation(error);
3157
+ return;
3158
+ }
3159
+ }
3160
+ this.setState((current) => ({
3161
+ ...current,
3162
+ conversation: {
3163
+ ...current.conversation,
3164
+ issue: {
3165
+ code: "runtime_error",
3166
+ message: error.message,
3167
+ recoverable: false
3168
+ }
3169
+ }
3170
+ }));
3171
+ };
3172
+ this.handleBudgetSnapshot = (budget) => {
3173
+ this.setState((current) => ({
3174
+ ...current,
3175
+ budget
3176
+ }));
3177
+ };
3178
+ this.handleMcpAuthStatus = () => {
3179
+ this.setState((current) => ({
3180
+ ...current,
3181
+ connections: {
3182
+ items: mergeConnections(mapConnections(this.agent), current.connections.items)
3183
+ }
3184
+ }));
3185
+ };
3186
+ this.handleAudioState = (voice) => {
3187
+ this.setState((current) => ({
3188
+ ...current,
3189
+ voice
3190
+ }));
3191
+ };
3192
+ this.platform = config.platform ?? createBrowserAppAgentPlatform();
3193
+ const onAuthRequired = config.onAuthRequired ?? (!config.auth && this.platform.auth ? createPlatformAuthHandler({
3194
+ platform: this.platform,
3195
+ userIdentity: config.userIdentity,
3196
+ oauthCallbackUrl: config.oauthCallbackUrl ?? ""
3197
+ }) : void 0);
3198
+ this.agent = new McpStackAgent({
3199
+ apiKey: config.apiKey,
3200
+ agentId: config.agentId,
3201
+ agentServiceUrl: config.serviceUrl,
3202
+ oauthCallbackUrl: config.oauthCallbackUrl,
3203
+ oauthClientMetadataUrl: config.oauthClientMetadataUrl,
3204
+ getAuthToken: config.getAuthToken,
3205
+ authSessionKey: config.appSessionKey,
3206
+ auth: config.auth,
3207
+ embeddedAuth: config.userIdentity ? {
3208
+ hostIdentity: config.userIdentity,
3209
+ mismatchPolicy: "block_with_switch"
3210
+ } : void 0,
3211
+ useCookies: config.useCookies,
3212
+ onAuthRequired,
3213
+ externalUserId: config.externalUserId ?? config.userIdentity?.subject ?? config.userIdentity?.email,
3214
+ context: config.appContext,
3215
+ clientTools: this.buildClientTools(config.clientTools),
3216
+ conversationHistoryPageSize: config.conversation?.historyPageSize ?? 50,
3217
+ storage: config.storage
3218
+ });
3219
+ this.state = {
3220
+ runtime: {
3221
+ agentConfig: null
3222
+ },
3223
+ conversation: {
3224
+ id: null,
3225
+ messages: [],
3226
+ streamingContent: "",
3227
+ pendingTurn: null,
3228
+ pendingTurnSawActivity: false,
3229
+ statusLabel: "Connecting\u2026",
3230
+ resumeKey: this.getResumeStorageKey(),
3231
+ isReady: false,
3232
+ isLoading: false,
3233
+ isLoadingHistory: false,
3234
+ isThinking: false,
3235
+ hasOlderMessages: false,
3236
+ error: null,
3237
+ issue: null
3238
+ },
3239
+ connections: {
3240
+ items: normalizeConnections(config.initialConnections)
3241
+ },
3242
+ approvals: {
3243
+ pending: []
3244
+ },
3245
+ requests: {
3246
+ pending: []
3247
+ },
3248
+ feedback: {
3249
+ isSubmitting: false,
3250
+ error: null,
3251
+ lastSubmittedAt: null,
3252
+ lastFeedback: null
3253
+ },
3254
+ voice: this.agent.getAudioInputState(),
3255
+ budget: this.agent.getBudgetSnapshot()
3256
+ };
3257
+ this.recomputeDerivedState();
3258
+ this.snapshot = this.buildSnapshot();
3259
+ }
3260
+ getAgent() {
3261
+ return this.agent;
3262
+ }
3263
+ buildSnapshot() {
3264
+ const messages = applyUserMessageOverrides(
3265
+ this.state.conversation.messages,
3266
+ Object.fromEntries(this.userMessageDisplayOverrides)
3267
+ );
3268
+ const visibleMessages = deriveVisibleMessages(messages);
3269
+ const conversationMessages = deriveConversationMessages(messages);
3270
+ const toolMessages = deriveToolMessages(visibleMessages);
3271
+ const latestAssistantMessage = getLatestAssistantMessage(visibleMessages);
3272
+ const latestToolMessage = getLatestToolMessage(toolMessages);
3273
+ const latestUserMessage = getLatestUserMessage(visibleMessages);
3274
+ const lastTurn = deriveLastTurnSummary(messages);
3275
+ const renderedNodes = buildRenderedNodes(messages);
3276
+ const inlineFeed = deriveInlineFeedState({
3277
+ pendingTurn: this.state.conversation.pendingTurn,
3278
+ toolMessages,
3279
+ latestAssistantMessage: latestAssistantMessage ? { id: latestAssistantMessage.id, content: latestAssistantMessage.content } : null,
3280
+ streamingContent: this.state.conversation.streamingContent,
3281
+ isLoading: this.state.conversation.isLoading,
3282
+ isThinking: this.state.conversation.isThinking
3283
+ });
3284
+ return {
3285
+ runtime: {
3286
+ agent: this.agent,
3287
+ agentConfig: this.state.runtime.agentConfig
3288
+ },
3289
+ conversation: {
3290
+ ...this.state.conversation,
3291
+ messages,
3292
+ visibleMessages,
3293
+ conversationMessages,
3294
+ toolMessages,
3295
+ renderedNodes,
3296
+ latestAssistantMessage,
3297
+ latestToolMessage,
3298
+ latestUserMessage,
3299
+ lastTurn,
3300
+ pendingTurn: this.state.conversation.pendingTurn,
3301
+ inlineFeed
3302
+ },
3303
+ connections: {
3304
+ ...this.state.connections,
3305
+ needsAttention: this.state.connections.items.some((item) => item.authStatus === "needs_auth")
3306
+ },
3307
+ approvals: {
3308
+ pending: this.state.approvals.pending
3309
+ },
3310
+ requests: {
3311
+ pending: this.state.requests.pending
3312
+ },
3313
+ feedback: this.state.feedback,
3314
+ budget: this.state.budget,
3315
+ voice: this.state.voice
3316
+ };
3317
+ }
3318
+ subscribe(listener) {
3319
+ this.listeners.add(listener);
3320
+ return () => {
3321
+ this.listeners.delete(listener);
3322
+ };
3323
+ }
3324
+ start() {
3325
+ if (this.started || this.disposed) {
3326
+ return;
3327
+ }
3328
+ this.started = true;
3329
+ this.bindLifecycleSignals();
3330
+ this.bindRuntimeEvents();
3331
+ this.initializationPromise = this.initialize();
3332
+ }
3333
+ dispose() {
3334
+ if (this.disposed) {
3335
+ return;
3336
+ }
3337
+ this.disposed = true;
3338
+ this.started = false;
3339
+ this.agent.off("message", this.handleMessage);
3340
+ this.agent.off("content_delta", this.handleContentDelta);
3341
+ this.agent.off("tool_call", this.handleToolCall);
3342
+ this.agent.off("tool_result", this.handleToolResult);
3343
+ this.agent.off("tool_error", this.handleToolError);
3344
+ this.agent.off("thinking", this.handleThinking);
3345
+ this.agent.off("loading", this.handleLoading);
3346
+ this.agent.off("error", this.handleError);
3347
+ this.agent.off("mcp_auth_status", this.handleMcpAuthStatus);
3348
+ this.agent.off("audio_state", this.handleAudioState);
3349
+ this.lifecycleUnsubscribers.splice(0).forEach((unsubscribe) => unsubscribe());
3350
+ this.agent.cancelVoiceInput();
3351
+ this.agent.cancel();
3352
+ this.approvalResolvers.clear();
3353
+ this.inputResolvers.clear();
3354
+ this.listeners.clear();
3355
+ }
3356
+ updateDynamicConfig(config) {
3357
+ this.config = {
3358
+ ...this.config,
3359
+ ...config
3360
+ };
3361
+ this.agent.setAppContext(this.config.appContext);
3362
+ this.agent.setClientTools(this.buildClientTools(this.config.clientTools));
3363
+ }
3364
+ setAuthRequiredHandler(onAuthRequired) {
3365
+ this.config = {
3366
+ ...this.config,
3367
+ onAuthRequired
3368
+ };
3369
+ this.agent.setOnAuthRequired(onAuthRequired);
3370
+ }
3371
+ async send(prompt, options) {
3372
+ const trimmed = prompt.trim();
3373
+ if (!trimmed) {
3374
+ return;
3375
+ }
3376
+ const displayText = (options?.displayText ?? trimmed).trim() || trimmed;
3377
+ this.pendingDisplayText = displayText;
3378
+ this.setState((current) => ({
3379
+ ...current,
3380
+ conversation: {
3381
+ ...current.conversation,
3382
+ pendingTurn: createInlinePendingTurnState(displayText, current.conversation.messages),
3383
+ pendingTurnSawActivity: false,
3384
+ issue: null
3385
+ }
3386
+ }));
3387
+ try {
3388
+ await this.agent.sendMessage(trimmed);
3389
+ } catch (error) {
3390
+ this.pendingDisplayText = null;
3391
+ const message = error instanceof Error ? error.message : "Could not send message.";
3392
+ this.setState((current) => ({
3393
+ ...current,
3394
+ conversation: {
3395
+ ...current.conversation,
3396
+ pendingTurn: null,
3397
+ pendingTurnSawActivity: false,
3398
+ error: {
3399
+ code: "send_message_error",
3400
+ message
3401
+ },
3402
+ issue: {
3403
+ code: "runtime_error",
3404
+ message,
3405
+ recoverable: false
3406
+ }
3407
+ }
3408
+ }));
3409
+ throw error;
3410
+ }
3411
+ }
3412
+ cancel() {
3413
+ this.agent.cancel();
3414
+ }
3415
+ async startVoiceInput() {
3416
+ await this.agent.startVoiceInput();
3417
+ }
3418
+ async stopVoiceInput() {
3419
+ await this.agent.stopVoiceInput();
3420
+ }
3421
+ cancelVoiceInput() {
3422
+ this.agent.cancelVoiceInput();
3423
+ }
3424
+ async loadMore() {
3425
+ this.setState((current) => ({
3426
+ ...current,
3427
+ conversation: {
3428
+ ...current.conversation,
3429
+ isLoadingHistory: true
3430
+ }
3431
+ }));
3432
+ try {
3433
+ const page = await this.agent.loadOlderMessages();
3434
+ if (!page) {
3435
+ return;
3436
+ }
3437
+ this.syncFromRuntime();
3438
+ } finally {
3439
+ this.setState((current) => ({
3440
+ ...current,
3441
+ conversation: {
3442
+ ...current.conversation,
3443
+ isLoadingHistory: false
3444
+ }
3445
+ }));
3446
+ }
3447
+ }
3448
+ async resetConversation() {
3449
+ this.agent.newConversation();
3450
+ await this.clearResumeRecord();
3451
+ this.recoveredConversationIds.clear();
3452
+ this.pendingToolCallsByAction.clear();
3453
+ this.approvalResolvers.clear();
3454
+ this.inputResolvers.clear();
3455
+ this.userMessageDisplayOverrides.clear();
3456
+ this.pendingDisplayText = null;
3457
+ this.setState((current) => ({
3458
+ ...current,
3459
+ conversation: {
3460
+ ...current.conversation,
3461
+ id: null,
3462
+ messages: [],
3463
+ streamingContent: "",
3464
+ pendingTurn: null,
3465
+ pendingTurnSawActivity: false,
3466
+ hasOlderMessages: false,
3467
+ error: null,
3468
+ issue: null
3469
+ },
3470
+ approvals: {
3471
+ pending: []
3472
+ },
3473
+ requests: {
3474
+ pending: []
3475
+ }
3476
+ }));
3477
+ }
3478
+ async connect(serverUrl) {
3479
+ await this.ensureInitialized();
3480
+ const result = await this.agent.authenticate(serverUrl);
3481
+ this.setState((current) => ({
3482
+ ...current,
3483
+ connections: {
3484
+ items: mergeConnections(mapConnections(this.agent), current.connections.items)
3485
+ },
3486
+ budget: this.agent.getBudgetSnapshot()
3487
+ }));
3488
+ return result;
3489
+ }
3490
+ async disconnect(serverUrl) {
3491
+ await this.agent.signOutMcpServer(serverUrl);
3492
+ this.setState((current) => ({
3493
+ ...current,
3494
+ connections: {
3495
+ items: mergeConnections(mapConnections(this.agent), current.connections.items)
3496
+ }
3497
+ }));
3498
+ }
3499
+ async submitFeedback(input) {
3500
+ this.setState((current) => ({
3501
+ ...current,
3502
+ feedback: {
3503
+ ...current.feedback,
3504
+ isSubmitting: true,
3505
+ error: null
3506
+ }
3507
+ }));
3508
+ try {
3509
+ const feedback = await this.agent.submitFeedback({
3510
+ ...input,
3511
+ source: this.config.feedbackSource ?? "app-agent"
3512
+ });
3513
+ this.setState((current) => ({
3514
+ ...current,
3515
+ feedback: {
3516
+ isSubmitting: false,
3517
+ error: null,
3518
+ lastSubmittedAt: feedback.createdAt,
3519
+ lastFeedback: feedback
3520
+ }
3521
+ }));
3522
+ return feedback;
3523
+ } catch (error) {
3524
+ const message = error instanceof Error ? error.message : "Could not save feedback.";
3525
+ this.setState((current) => ({
3526
+ ...current,
3527
+ feedback: {
3528
+ ...current.feedback,
3529
+ isSubmitting: false,
3530
+ error: message
3531
+ }
3532
+ }));
3533
+ throw error;
3534
+ }
3535
+ }
3536
+ resolveApproval(id, approved) {
3537
+ const resolver = this.approvalResolvers.get(id);
3538
+ if (!resolver) {
3539
+ return;
3540
+ }
3541
+ this.approvalResolvers.delete(id);
3542
+ this.setState((current) => ({
3543
+ ...current,
3544
+ approvals: {
3545
+ pending: current.approvals.pending.filter((approval) => approval.id !== id)
3546
+ }
3547
+ }));
3548
+ resolver.resolve({ approved });
3549
+ }
3550
+ submitRequest(id, values) {
3551
+ const resolver = this.inputResolvers.get(id);
3552
+ if (!resolver) {
3553
+ return;
3554
+ }
3555
+ this.inputResolvers.delete(id);
3556
+ this.setState((current) => ({
3557
+ ...current,
3558
+ requests: {
3559
+ pending: current.requests.pending.filter((request) => request.id !== id)
3560
+ }
3561
+ }));
3562
+ resolver.resolve({ submitted: true, values });
3563
+ }
3564
+ cancelRequest(id) {
3565
+ const resolver = this.inputResolvers.get(id);
3566
+ if (!resolver) {
3567
+ return;
3568
+ }
3569
+ this.inputResolvers.delete(id);
3570
+ this.setState((current) => ({
3571
+ ...current,
3572
+ requests: {
3573
+ pending: current.requests.pending.filter((request) => request.id !== id)
3574
+ }
3575
+ }));
3576
+ resolver.resolve({ submitted: false });
3577
+ }
3578
+ async initialize() {
3579
+ try {
3580
+ const agentConfig = await this.agent.init();
3581
+ if (this.disposed) {
3582
+ return;
3583
+ }
3584
+ this.setState((current) => ({
3585
+ ...current,
3586
+ runtime: {
3587
+ agentConfig
3588
+ },
3589
+ conversation: {
3590
+ ...current.conversation,
3591
+ isReady: true
3592
+ },
3593
+ connections: {
3594
+ items: mergeConnections(mapConnections(this.agent), current.connections.items)
3595
+ },
3596
+ budget: this.agent.getBudgetSnapshot()
3597
+ }));
3598
+ const resumeRecord = await this.readResumeRecord();
3599
+ if (resumeRecord && resumeRecord.agentId === this.config.agentId && resumeRecord.appSessionKey === (this.config.appSessionKey ?? null) && resumeRecord.conversationResumeVersion === agentConfig.conversationResumeVersion) {
3600
+ this.setState((current) => ({
3601
+ ...current,
3602
+ conversation: {
3603
+ ...current.conversation,
3604
+ isLoadingHistory: true
3605
+ }
3606
+ }));
3607
+ try {
3608
+ await this.agent.loadConversation(
3609
+ resumeRecord.conversationId,
3610
+ this.config.conversation?.historyPageSize ?? 50
3611
+ );
3612
+ } catch (error) {
3613
+ this.setState((current) => ({
3614
+ ...current,
3615
+ conversation: {
3616
+ ...current.conversation,
3617
+ error: {
3618
+ code: "conversation_history_error",
3619
+ message: error instanceof Error ? error.message : "Failed to load conversation history."
3620
+ }
3621
+ }
3622
+ }));
3623
+ await this.clearResumeRecord();
3624
+ } finally {
3625
+ this.syncFromRuntime();
3626
+ this.setState((current) => ({
3627
+ ...current,
3628
+ conversation: {
3629
+ ...current.conversation,
3630
+ isLoadingHistory: false
3631
+ }
3632
+ }));
3633
+ }
3634
+ } else {
3635
+ this.syncFromRuntime();
3636
+ }
3637
+ } catch (error) {
3638
+ const message = error instanceof Error && error.message.trim() ? error.message.trim() : "Failed to load agent configuration.";
3639
+ this.setState((current) => ({
3640
+ ...current,
3641
+ conversation: {
3642
+ ...current.conversation,
3643
+ error: {
3644
+ code: /api key|unauthorized|401/i.test(message) ? "agent_config_auth_error" : "agent_config_error",
3645
+ message
3646
+ },
3647
+ issue: {
3648
+ code: "config_error",
3649
+ message,
3650
+ recoverable: false
3651
+ }
3652
+ }
3653
+ }));
3654
+ }
3655
+ }
3656
+ async ensureInitialized() {
3657
+ if (this.state.runtime.agentConfig) {
3658
+ return;
3659
+ }
3660
+ this.initializationPromise ?? (this.initializationPromise = this.initialize());
3661
+ await this.initializationPromise;
3662
+ }
3663
+ bindRuntimeEvents() {
3664
+ this.agent.on("message", this.handleMessage);
3665
+ this.agent.on("content_delta", this.handleContentDelta);
3666
+ this.agent.on("tool_call", this.handleToolCall);
3667
+ this.agent.on("tool_result", this.handleToolResult);
3668
+ this.agent.on("tool_error", this.handleToolError);
3669
+ this.agent.on("thinking", this.handleThinking);
3670
+ this.agent.on("loading", this.handleLoading);
3671
+ this.agent.on("error", this.handleError);
3672
+ this.agent.on("mcp_auth_status", this.handleMcpAuthStatus);
3673
+ this.agent.on("audio_state", this.handleAudioState);
3674
+ this.agent.on("budget_snapshot", this.handleBudgetSnapshot);
3675
+ }
3676
+ async handleStaleConversation(error) {
3677
+ await this.clearResumeRecord();
3678
+ this.agent.newConversation();
3679
+ this.pendingToolCallsByAction.clear();
3680
+ this.approvalResolvers.clear();
3681
+ this.inputResolvers.clear();
3682
+ this.userMessageDisplayOverrides.clear();
3683
+ this.pendingDisplayText = null;
3684
+ this.setState((current) => ({
3685
+ ...current,
3686
+ conversation: {
3687
+ ...current.conversation,
3688
+ id: null,
3689
+ messages: [],
3690
+ streamingContent: "",
3691
+ pendingTurn: null,
3692
+ pendingTurnSawActivity: false,
3693
+ hasOlderMessages: false,
3694
+ issue: {
3695
+ code: "stale_conversation",
3696
+ message: error.message,
3697
+ recoverable: true
3698
+ }
3699
+ },
3700
+ approvals: {
3701
+ pending: []
3702
+ },
3703
+ requests: {
3704
+ pending: []
3705
+ }
3706
+ }));
3707
+ }
3708
+ bindLifecycleSignals() {
3709
+ const lifecycle = this.platform.lifecycle;
3710
+ if (!lifecycle) {
3711
+ return;
3712
+ }
3713
+ const foregroundUnsubscribe = lifecycle.onForegroundChange?.(() => {
3714
+ this.emit();
3715
+ });
3716
+ if (foregroundUnsubscribe) {
3717
+ this.lifecycleUnsubscribers.push(foregroundUnsubscribe);
3718
+ }
3719
+ const connectivityUnsubscribe = lifecycle.onConnectivityChange?.(() => {
3720
+ this.emit();
3721
+ });
3722
+ if (connectivityUnsubscribe) {
3723
+ this.lifecycleUnsubscribers.push(connectivityUnsubscribe);
3724
+ }
3725
+ }
3726
+ buildClientTools(clientTools) {
3727
+ const approvalAction = {
3728
+ description: "Ask the host app to approve a multi-step plan before you continue.",
3729
+ selection: {
3730
+ categories: ["approval"],
3731
+ alwaysInclude: true,
3732
+ risk: "medium"
3733
+ },
3734
+ parameters: {
3735
+ title: { type: "string", description: "Short title for the approval request.", required: true },
3736
+ rationale: { type: "string", description: "Optional reason for the plan." },
3737
+ steps: { type: "array", description: "Ordered steps that need approval.", required: true },
3738
+ confirmLabel: { type: "string", description: "Optional label for the approve action." },
3739
+ cancelLabel: { type: "string", description: "Optional label for the reject action." }
3740
+ },
3741
+ execute: async (params) => {
3742
+ const approvalId = createId("approval");
3743
+ const toolCallId = this.shiftPendingToolCallId(APP_AGENT_APPROVAL_ACTION);
3744
+ const approval = {
3745
+ id: approvalId,
3746
+ title: typeof params.title === "string" ? params.title : "Approval required",
3747
+ rationale: typeof params.rationale === "string" ? params.rationale : void 0,
3748
+ steps: normalizeSteps(params.steps),
3749
+ toolCallId,
3750
+ confirmLabel: typeof params.confirmLabel === "string" ? params.confirmLabel : void 0,
3751
+ cancelLabel: typeof params.cancelLabel === "string" ? params.cancelLabel : void 0
3752
+ };
3753
+ this.setState((current) => ({
3754
+ ...current,
3755
+ approvals: {
3756
+ pending: [...current.approvals.pending, approval]
3757
+ }
3758
+ }));
3759
+ return await new Promise((resolve) => {
3760
+ this.approvalResolvers.set(approvalId, { resolve });
3761
+ });
3762
+ }
3763
+ };
3764
+ return {
3765
+ ...clientTools ?? {},
3766
+ [APP_AGENT_APPROVAL_ACTION]: {
3767
+ ...approvalAction
3768
+ },
3769
+ [APP_AGENT_INPUT_ACTION]: {
3770
+ description: "Ask the host app for structured user input before you continue.",
3771
+ selection: {
3772
+ categories: ["approval"],
3773
+ alwaysInclude: true,
3774
+ risk: "medium"
3775
+ },
3776
+ parameters: {
3777
+ title: { type: "string", description: "Short title for the input request.", required: true },
3778
+ prompt: { type: "string", description: "Optional explainer shown above the fields." },
3779
+ fields: { type: "array", description: "Structured fields to collect.", required: true },
3780
+ submitLabel: { type: "string", description: "Optional submit button label." },
3781
+ cancelLabel: { type: "string", description: "Optional cancel button label." }
3782
+ },
3783
+ execute: async (params) => {
3784
+ const requestId = createId("input");
3785
+ const toolCallId = this.shiftPendingToolCallId(APP_AGENT_INPUT_ACTION);
3786
+ const request = {
3787
+ id: requestId,
3788
+ title: typeof params.title === "string" ? params.title : "Input required",
3789
+ prompt: typeof params.prompt === "string" ? params.prompt : void 0,
3790
+ fields: normalizeInputFields(params.fields),
3791
+ toolCallId,
3792
+ submitLabel: typeof params.submitLabel === "string" ? params.submitLabel : void 0,
3793
+ cancelLabel: typeof params.cancelLabel === "string" ? params.cancelLabel : void 0
3794
+ };
3795
+ this.setState((current) => ({
3796
+ ...current,
3797
+ requests: {
3798
+ pending: [...current.requests.pending, request]
3799
+ }
3800
+ }));
3801
+ return await new Promise((resolve) => {
3802
+ this.inputResolvers.set(requestId, { resolve });
3803
+ });
3804
+ }
3805
+ }
3806
+ };
3807
+ }
3808
+ shiftPendingToolCallId(actionName) {
3809
+ const queue = this.pendingToolCallsByAction.get(actionName) ?? [];
3810
+ const next = queue.shift() ?? null;
3811
+ if (queue.length === 0) {
3812
+ this.pendingToolCallsByAction.delete(actionName);
3813
+ } else {
3814
+ this.pendingToolCallsByAction.set(actionName, queue);
3815
+ }
3816
+ return next;
3817
+ }
3818
+ syncFromRuntime() {
3819
+ this.setState((current) => ({
3820
+ ...current,
3821
+ conversation: {
3822
+ ...current.conversation,
3823
+ id: this.agent.getConversationId(),
3824
+ messages: this.agent.getMessages(),
3825
+ hasOlderMessages: this.agent.getHasOlderMessages()
3826
+ },
3827
+ connections: {
3828
+ items: mergeConnections(mapConnections(this.agent), current.connections.items)
3829
+ }
3830
+ }));
3831
+ void this.persistResumeRecord();
3832
+ }
3833
+ finalizePendingTurnIfSettled() {
3834
+ const current = this.state.conversation;
3835
+ if (current.pendingTurn && current.pendingTurnSawActivity && !current.isLoading && !current.isThinking && !current.streamingContent) {
3836
+ this.setState((state) => ({
3837
+ ...state,
3838
+ conversation: {
3839
+ ...state.conversation,
3840
+ pendingTurn: null,
3841
+ pendingTurnSawActivity: false
3842
+ }
3843
+ }));
3844
+ }
3845
+ }
3846
+ getResumeStorageKey() {
3847
+ const durable = this.platform.storage?.durable;
3848
+ if (!durable) {
3849
+ return null;
3850
+ }
3851
+ const namespace = this.config.conversation?.namespace ?? "mcpstack.app-agent.resume";
3852
+ const sessionKey = this.config.appSessionKey?.trim() || "anonymous";
3853
+ return `${namespace}:${this.config.agentId}:${sessionKey}`;
3854
+ }
3855
+ async readResumeRecord() {
3856
+ const durable = this.platform.storage?.durable;
3857
+ const resumeKey = this.getResumeStorageKey();
3858
+ if (!durable || !resumeKey) {
3859
+ return null;
3860
+ }
3861
+ try {
3862
+ const raw = await resolveStoreValue(durable.getItem(resumeKey));
3863
+ if (!raw) {
3864
+ return null;
3865
+ }
3866
+ return JSON.parse(raw);
3867
+ } catch {
3868
+ return null;
3869
+ }
3870
+ }
3871
+ async persistResumeRecord() {
3872
+ const durable = this.platform.storage?.durable;
3873
+ const resumeKey = this.getResumeStorageKey();
3874
+ const conversationId = this.agent.getConversationId();
3875
+ const agentConfig = this.state.runtime.agentConfig;
3876
+ if (!durable || !resumeKey || !conversationId || !agentConfig) {
3877
+ return;
3878
+ }
3879
+ const record = {
3880
+ conversationId,
3881
+ agentId: this.config.agentId,
3882
+ appSessionKey: this.config.appSessionKey ?? null,
3883
+ conversationResumeVersion: agentConfig.conversationResumeVersion,
3884
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
3885
+ };
3886
+ try {
3887
+ await resolveStoreValue(durable.setItem(resumeKey, JSON.stringify(record)));
3888
+ } catch {
3889
+ }
3890
+ }
3891
+ async clearResumeRecord() {
3892
+ const durable = this.platform.storage?.durable;
3893
+ const resumeKey = this.getResumeStorageKey();
3894
+ if (!durable || !resumeKey) {
3895
+ return;
3896
+ }
3897
+ try {
3898
+ await resolveStoreValue(durable.removeItem(resumeKey));
3899
+ } catch {
3900
+ }
3901
+ }
3902
+ setState(update) {
3903
+ if (this.disposed) {
3904
+ return;
3905
+ }
3906
+ this.state = update(this.state);
3907
+ this.recomputeDerivedState();
3908
+ this.snapshot = this.buildSnapshot();
3909
+ this.emit();
3910
+ }
3911
+ recomputeDerivedState() {
3912
+ const hasAttention = this.state.connections.items.some((item) => item.authStatus === "needs_auth");
3913
+ this.state.conversation.statusLabel = deriveConversationStatusLabel({
3914
+ isReady: this.state.conversation.isReady,
3915
+ isLoading: this.state.conversation.isLoading,
3916
+ isThinking: this.state.conversation.isThinking,
3917
+ streamingContent: this.state.conversation.streamingContent,
3918
+ hasError: this.state.conversation.error != null,
3919
+ hasIssue: this.state.conversation.issue != null,
3920
+ hasAttention
3921
+ });
3922
+ this.state.conversation.resumeKey = this.getResumeStorageKey();
3923
+ }
3924
+ emit() {
3925
+ for (const listener of this.listeners) {
3926
+ listener();
3927
+ }
3928
+ }
3929
+ };
3930
+
3931
+ // src/framework/useAppAgentBinding.tsx
3932
+ function useAppAgentBinding(config, options, auth = {}) {
3933
+ const enabled = options?.enabled ?? true;
3934
+ const disposeTimerRef = useRef(null);
3935
+ const controller = useMemo(() => new AppAgentController({
3936
+ ...config,
3937
+ onAuthRequired: auth.onAuthRequired ?? config.onAuthRequired
3938
+ }), [
3939
+ auth.onAuthRequired,
3940
+ config.agentId,
3941
+ config.apiKey,
3942
+ config.appSessionKey,
3943
+ config.auth?.appId,
3944
+ config.auth?.getToken,
3945
+ config.auth?.mode,
3946
+ config.conversation?.historyPageSize,
3947
+ config.conversation?.namespace,
3948
+ config.externalUserId,
3949
+ config.getAuthToken,
3950
+ config.oauthCallbackUrl,
3951
+ config.oauthClientMetadataUrl,
3952
+ config.onAuthRequired,
3953
+ config.platform,
3954
+ config.serviceUrl,
3955
+ config.storage,
3956
+ config.useCookies,
3957
+ config.userIdentity?.subject,
3958
+ enabled
3959
+ ]);
3960
+ useEffect(() => {
3961
+ if (disposeTimerRef.current) {
3962
+ clearTimeout(disposeTimerRef.current);
3963
+ disposeTimerRef.current = null;
3964
+ }
3965
+ return () => {
3966
+ disposeTimerRef.current = setTimeout(() => {
3967
+ controller.dispose();
3968
+ disposeTimerRef.current = null;
3969
+ }, 0);
3970
+ };
3971
+ }, [controller]);
3972
+ useEffect(() => {
3973
+ controller.updateDynamicConfig({
3974
+ appContext: config.appContext,
3975
+ clientTools: config.clientTools,
3976
+ feedbackSource: config.feedbackSource
3977
+ });
3978
+ }, [config.appContext, config.clientTools, config.feedbackSource, controller]);
3979
+ useEffect(() => {
3980
+ controller.setAuthRequiredHandler(auth.onAuthRequired ?? config.onAuthRequired);
3981
+ }, [auth.onAuthRequired, config.onAuthRequired, controller]);
3982
+ useEffect(() => {
3983
+ if (!enabled) {
3984
+ return;
3985
+ }
3986
+ controller.start();
3987
+ }, [controller, enabled]);
3988
+ const snapshot = useSyncExternalStore(
3989
+ controller.subscribe.bind(controller),
3990
+ controller.getSnapshot,
3991
+ controller.getSnapshot
3992
+ );
3993
+ return {
3994
+ controller,
3995
+ runtime: snapshot.runtime,
3996
+ conversation: {
3997
+ ...snapshot.conversation,
3998
+ loadMore: () => controller.loadMore(),
3999
+ reset: () => controller.resetConversation()
4000
+ },
4001
+ composer: {
4002
+ send: (prompt, sendOptions) => controller.send(prompt, sendOptions),
4003
+ cancel: () => controller.cancel()
4004
+ },
4005
+ connections: {
4006
+ ...snapshot.connections,
4007
+ connect: (serverUrl) => controller.connect(serverUrl),
4008
+ disconnect: (serverUrl) => controller.disconnect(serverUrl)
4009
+ },
4010
+ approvals: {
4011
+ ...snapshot.approvals,
4012
+ resolve: (id, approved) => controller.resolveApproval(id, approved)
4013
+ },
4014
+ requests: {
4015
+ ...snapshot.requests,
4016
+ submit: (id, values) => controller.submitRequest(id, values),
4017
+ cancel: (id) => controller.cancelRequest(id)
4018
+ },
4019
+ feedback: {
4020
+ ...snapshot.feedback,
4021
+ submit: (input) => controller.submitFeedback(input)
4022
+ },
4023
+ budget: snapshot.budget,
4024
+ voice: {
4025
+ ...snapshot.voice,
4026
+ start: () => controller.startVoiceInput(),
4027
+ stop: () => controller.stopVoiceInput(),
4028
+ cancel: () => controller.cancelVoiceInput()
4029
+ },
4030
+ popupAuthState: auth.popupAuthState ?? null,
4031
+ startOrRetryPopupAuth: auth.startOrRetryPopupAuth ?? (() => void 0),
4032
+ cancelPopupAuth: auth.cancelPopupAuth ?? (() => void 0)
4033
+ };
4034
+ }
4035
+
4036
+ // src/react/usePopupOAuthController.ts
4037
+ import { useCallback, useEffect as useEffect2, useMemo as useMemo2, useRef as useRef2, useState } from "react";
4038
+ var OAUTH_CALLBACK_CHANNEL_NAME = "mcpstack-oauth";
4039
+ var OAUTH_CALLBACK_STORAGE_PREFIX = "mcpstack-oauth-callback:";
4040
+ function generateCodeVerifier() {
4041
+ const array = new Uint8Array(32);
4042
+ crypto.getRandomValues(array);
4043
+ return btoa(String.fromCharCode(...array)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
4044
+ }
4045
+ async function generateCodeChallenge(verifier) {
4046
+ const encoder = new TextEncoder();
4047
+ const data = encoder.encode(verifier);
4048
+ const hash = await crypto.subtle.digest("SHA-256", data);
4049
+ return btoa(String.fromCharCode(...new Uint8Array(hash))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
4050
+ }
4051
+ function createPopupState(request, phase, statusMessage, errorMessage) {
4052
+ return {
4053
+ serverName: request.serverName,
4054
+ serverUrl: request.serverUrl,
4055
+ phase,
4056
+ statusMessage: statusMessage ?? null,
4057
+ errorMessage: errorMessage ?? null,
4058
+ hostIdentityLabel: request.hostIdentityLabel ?? null
4059
+ };
4060
+ }
4061
+ function normalizeOptionalValue2(value) {
4062
+ if (!value) {
4063
+ return void 0;
4064
+ }
4065
+ const trimmed = value.trim();
4066
+ return trimmed || void 0;
4067
+ }
4068
+ function formatUserIdentityLabel(identity) {
4069
+ if (!identity) {
4070
+ return null;
4071
+ }
4072
+ return normalizeOptionalValue2(identity.displayName) ?? normalizeOptionalValue2(identity.email) ?? normalizeOptionalValue2(identity.subject) ?? null;
4073
+ }
4074
+ function isGatewayAuthorizeUrl2(authConfig) {
4075
+ const loginUrl = authConfig.authorizationEndpoint ?? authConfig.loginUrl;
4076
+ if (!loginUrl) {
4077
+ return false;
4078
+ }
4079
+ try {
4080
+ const url = new URL(loginUrl);
4081
+ return /\/api\/v1\/gateway\/[^/]+\/authorize$/i.test(url.pathname);
4082
+ } catch {
4083
+ return false;
4084
+ }
4085
+ }
4086
+ function usePopupOAuthController(options) {
4087
+ const [popupState, setPopupState] = useState(null);
4088
+ const popupStateRef = useRef2(null);
4089
+ const activeRequestRef = useRef2(null);
4090
+ const mountedRef = useRef2(true);
4091
+ const optionsRef = useRef2(options);
4092
+ const authSessionKeyRef = useRef2(normalizeAuthSessionKey(options.appSessionKey));
4093
+ useEffect2(() => {
4094
+ popupStateRef.current = popupState;
4095
+ }, [popupState]);
4096
+ useEffect2(() => {
4097
+ optionsRef.current = options;
4098
+ }, [options]);
4099
+ const getCallbackUrl = useCallback((config) => config.callbackUrl ?? optionsRef.current.oauthCallbackUrl, []);
4100
+ const clearStoredCallbackPayload = useCallback((state) => {
4101
+ if (!state) {
4102
+ return;
4103
+ }
4104
+ try {
4105
+ localStorage.removeItem(`${OAUTH_CALLBACK_STORAGE_PREFIX}${state}`);
4106
+ } catch {
4107
+ }
4108
+ }, []);
4109
+ const clearPollTimer = useCallback((request) => {
4110
+ if (request?.pollTimer) {
4111
+ clearInterval(request.pollTimer);
4112
+ request.pollTimer = void 0;
4113
+ }
4114
+ }, []);
4115
+ const dismissPopupState = useCallback((serverUrl) => {
4116
+ if (!mountedRef.current) {
4117
+ return;
4118
+ }
4119
+ if (!popupStateRef.current && !activeRequestRef.current) {
4120
+ return;
4121
+ }
4122
+ setPopupState((currentState) => {
4123
+ if (!currentState) {
4124
+ popupStateRef.current = null;
4125
+ return null;
4126
+ }
4127
+ if (!serverUrl || currentState.serverUrl === serverUrl) {
4128
+ popupStateRef.current = null;
4129
+ return null;
4130
+ }
4131
+ return currentState;
4132
+ });
4133
+ }, []);
4134
+ const closePopupWindow = useCallback((request) => {
4135
+ if (request?.popupWindow && !request.popupWindow.closed) {
4136
+ request.popupWindow.close();
4137
+ }
4138
+ if (request) {
4139
+ request.popupWindow = null;
4140
+ }
4141
+ }, []);
4142
+ useEffect2(() => {
4143
+ const previousAuthSessionKey = authSessionKeyRef.current;
4144
+ const nextAuthSessionKey = normalizeAuthSessionKey(options.appSessionKey);
4145
+ authSessionKeyRef.current = nextAuthSessionKey;
4146
+ if (previousAuthSessionKey === nextAuthSessionKey) {
4147
+ return;
4148
+ }
4149
+ const request = activeRequestRef.current;
4150
+ if (!request) {
4151
+ if (mountedRef.current) {
4152
+ setPopupState(null);
4153
+ }
4154
+ return;
4155
+ }
4156
+ clearPollTimer(request);
4157
+ closePopupWindow(request);
4158
+ clearStoredCallbackPayload(request.state);
4159
+ activeRequestRef.current = null;
4160
+ request.resolve(void 0);
4161
+ if (mountedRef.current) {
4162
+ setPopupState(null);
4163
+ }
4164
+ }, [
4165
+ clearPollTimer,
4166
+ clearStoredCallbackPayload,
4167
+ closePopupWindow,
4168
+ options.appSessionKey
4169
+ ]);
4170
+ const resolveAndClearActiveRequest = useCallback((tokenResponse) => {
4171
+ const request = activeRequestRef.current;
4172
+ if (!request) {
4173
+ dismissPopupState();
4174
+ return;
4175
+ }
4176
+ clearPollTimer(request);
4177
+ closePopupWindow(request);
4178
+ clearStoredCallbackPayload(request.state);
4179
+ activeRequestRef.current = null;
4180
+ request.resolve(tokenResponse);
4181
+ dismissPopupState(request.serverUrl);
4182
+ }, [clearPollTimer, clearStoredCallbackPayload, closePopupWindow, dismissPopupState]);
4183
+ const transitionActiveRequest = useCallback((phase, errorMessage, statusMessage) => {
4184
+ const request = activeRequestRef.current;
4185
+ if (!request) {
4186
+ return;
4187
+ }
4188
+ clearPollTimer(request);
4189
+ closePopupWindow(request);
4190
+ request.handledCallback = false;
4191
+ if (mountedRef.current) {
4192
+ setPopupState(createPopupState(request, phase, statusMessage, errorMessage));
4193
+ }
4194
+ }, [clearPollTimer, closePopupWindow]);
4195
+ const setActivePopupPhase = useCallback((phase, errorMessage, statusMessage) => {
4196
+ const request = activeRequestRef.current;
4197
+ if (!request) {
4198
+ return;
4199
+ }
4200
+ clearPollTimer(request);
4201
+ closePopupWindow(request);
4202
+ if (mountedRef.current) {
4203
+ setPopupState(createPopupState(request, phase, statusMessage, errorMessage));
4204
+ }
4205
+ }, [clearPollTimer, closePopupWindow]);
4206
+ const exchangeCodeForToken = useCallback(async (code) => {
4207
+ const request = activeRequestRef.current;
4208
+ if (!request) {
4209
+ return;
4210
+ }
4211
+ const effectiveAuthConfig = request.resolvedAuthConfig;
4212
+ const callbackUrl = getCallbackUrl(effectiveAuthConfig);
4213
+ const tokenUrl = effectiveAuthConfig.tokenEndpoint ?? effectiveAuthConfig.tokenUrl;
4214
+ if (!tokenUrl) {
4215
+ request.handledCallback = false;
4216
+ transitionActiveRequest("error", "This MCP server is missing a token endpoint.");
4217
+ return;
4218
+ }
4219
+ if (mountedRef.current) {
4220
+ setPopupState(
4221
+ createPopupState(
4222
+ request,
4223
+ "exchanging",
4224
+ "Exchanging authorization code..."
4225
+ )
4226
+ );
4227
+ }
4228
+ try {
4229
+ const body = new URLSearchParams({
4230
+ grant_type: "authorization_code",
4231
+ code,
4232
+ code_verifier: request.codeVerifier,
4233
+ redirect_uri: callbackUrl
4234
+ });
4235
+ if (effectiveAuthConfig.clientId) {
4236
+ body.set("client_id", effectiveAuthConfig.clientId);
4237
+ }
4238
+ if (effectiveAuthConfig.resource) {
4239
+ body.set("resource", effectiveAuthConfig.resource);
4240
+ }
4241
+ const response = await fetch(tokenUrl, {
4242
+ method: "POST",
4243
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
4244
+ body
4245
+ });
4246
+ if (response.ok) {
4247
+ const data = await response.json();
4248
+ if (data.access_token) {
4249
+ resolveAndClearActiveRequest({
4250
+ accessToken: data.access_token,
4251
+ refreshToken: data.refresh_token,
4252
+ expiresIn: data.expires_in,
4253
+ tokenType: data.token_type,
4254
+ resolvedAuthConfig: effectiveAuthConfig
4255
+ });
4256
+ return;
4257
+ }
4258
+ }
4259
+ const errorMessage = await response.text().catch(() => "Token exchange failed.");
4260
+ if (effectiveAuthConfig.clientMode === "dcr") {
4261
+ clearStoredRegistration(
4262
+ buildRegistrationCacheKey(effectiveAuthConfig, callbackUrl, "dcr")
4263
+ );
4264
+ }
4265
+ request.handledCallback = false;
4266
+ transitionActiveRequest("error", errorMessage || "Token exchange failed.");
4267
+ } catch {
4268
+ request.handledCallback = false;
4269
+ transitionActiveRequest("error", "Token exchange failed. Please try again.");
4270
+ }
4271
+ }, [getCallbackUrl, resolveAndClearActiveRequest, transitionActiveRequest]);
4272
+ const handleAuthPayload = useCallback((payload) => {
4273
+ const request = activeRequestRef.current;
4274
+ if (!request || !payload || typeof payload !== "object") {
4275
+ return;
4276
+ }
4277
+ const data = payload;
4278
+ const responseState = typeof data.state === "string" ? data.state : "";
4279
+ if (!request.state || responseState !== request.state || request.handledCallback) {
4280
+ return;
4281
+ }
4282
+ request.handledCallback = true;
4283
+ clearPollTimer(request);
4284
+ clearStoredCallbackPayload(responseState);
4285
+ if (data.type === "mcpstack-oauth-callback" && typeof data.token === "string") {
4286
+ resolveAndClearActiveRequest({
4287
+ accessToken: data.token,
4288
+ resolvedAuthConfig: request.resolvedAuthConfig
4289
+ });
4290
+ return;
4291
+ }
4292
+ if (data.type === "mcpstack-oauth-callback" && typeof data.accessToken === "string") {
4293
+ resolveAndClearActiveRequest({
4294
+ accessToken: data.accessToken,
4295
+ refreshToken: typeof data.refreshToken === "string" ? data.refreshToken : void 0,
4296
+ expiresIn: typeof data.expiresIn === "number" ? data.expiresIn : void 0,
4297
+ tokenType: typeof data.tokenType === "string" ? data.tokenType : void 0,
4298
+ resolvedAuthConfig: request.resolvedAuthConfig
4299
+ });
4300
+ return;
4301
+ }
4302
+ if (data.type === "mcpstack-oauth-code" && typeof data.code === "string") {
4303
+ void exchangeCodeForToken(data.code);
4304
+ return;
4305
+ }
4306
+ if (data.type === "mcpstack-oauth-error" && typeof data.error === "string") {
4307
+ const description = typeof data.errorDescription === "string" ? data.errorDescription : typeof data.error_description === "string" ? data.error_description : "Sign in could not be completed.";
4308
+ setActivePopupPhase(
4309
+ data.error === "access_denied" ? "canceled" : "error",
4310
+ description
4311
+ );
4312
+ return;
4313
+ }
4314
+ request.handledCallback = false;
4315
+ }, [
4316
+ clearStoredCallbackPayload,
4317
+ exchangeCodeForToken,
4318
+ resolveAndClearActiveRequest,
4319
+ setActivePopupPhase
4320
+ ]);
4321
+ const startOrRetryPopupAuth = useCallback(async () => {
4322
+ const request = activeRequestRef.current;
4323
+ if (!request) {
4324
+ return;
4325
+ }
4326
+ const width = 500;
4327
+ const height = 600;
4328
+ const left = window.screenX + (window.outerWidth - width) / 2;
4329
+ const top = window.screenY + (window.outerHeight - height) / 2;
4330
+ const popupWindow = window.open(
4331
+ "about:blank",
4332
+ "mcpstack-auth-popup",
4333
+ `popup=yes,width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`
4334
+ );
4335
+ if (!popupWindow) {
4336
+ transitionActiveRequest(
4337
+ "blocked",
4338
+ "Your browser blocked the sign-in popup. Allow popups and try again."
4339
+ );
4340
+ return;
4341
+ }
4342
+ request.popupWindow = popupWindow;
4343
+ request.popupWindow.focus?.();
4344
+ clearStoredCallbackPayload(request.state);
4345
+ clearPollTimer(request);
4346
+ request.codeVerifier = generateCodeVerifier();
4347
+ request.state = crypto.randomUUID();
4348
+ request.handledCallback = false;
4349
+ const popupContext = encodeURIComponent(JSON.stringify({
4350
+ openerOrigin: window.location.origin,
4351
+ expectedState: request.state
4352
+ }));
4353
+ try {
4354
+ request.popupWindow.name = `mcpstack-auth:${popupContext}`;
4355
+ } catch {
4356
+ closePopupWindow(request);
4357
+ transitionActiveRequest(
4358
+ "error",
4359
+ "The sign-in popup could not be opened. Try again."
4360
+ );
4361
+ return;
4362
+ }
4363
+ if (mountedRef.current) {
4364
+ setPopupState(
4365
+ createPopupState(request, "preparing", "Preparing secure sign in...")
4366
+ );
4367
+ }
4368
+ let effectiveAuthConfig = request.authConfig;
4369
+ try {
4370
+ if (effectiveAuthConfig.authType === "oauth2" && !effectiveAuthConfig.clientMode) {
4371
+ const registration = await resolveOAuthRegistration(effectiveAuthConfig, {
4372
+ callbackUrl: getCallbackUrl(effectiveAuthConfig),
4373
+ oauthClientMetadataUrl: optionsRef.current.oauthClientMetadataUrl,
4374
+ clientName: "MCP Stack MCP Client",
4375
+ clientUri: window.location.origin
4376
+ });
4377
+ effectiveAuthConfig = applyResolvedRegistration(effectiveAuthConfig, registration);
4378
+ }
4379
+ request.resolvedAuthConfig = effectiveAuthConfig;
4380
+ } catch (error) {
4381
+ closePopupWindow(request);
4382
+ transitionActiveRequest(
4383
+ "error",
4384
+ error instanceof Error ? error.message : "Failed to prepare OAuth sign in for this MCP server."
4385
+ );
4386
+ return;
4387
+ }
4388
+ const callbackUrl = getCallbackUrl(effectiveAuthConfig);
4389
+ const loginUrl = effectiveAuthConfig.authorizationEndpoint ?? effectiveAuthConfig.loginUrl;
4390
+ if (!loginUrl) {
4391
+ closePopupWindow(request);
4392
+ transitionActiveRequest("error", "This MCP server is missing an authorization endpoint.");
4393
+ return;
4394
+ }
4395
+ const codeVerifier = request.codeVerifier;
4396
+ let authUrl = "";
4397
+ if (effectiveAuthConfig.tokenEndpoint ?? effectiveAuthConfig.tokenUrl) {
4398
+ const codeChallenge = await generateCodeChallenge(codeVerifier);
4399
+ const params = new URLSearchParams({
4400
+ response_type: "code",
4401
+ code_challenge: codeChallenge,
4402
+ code_challenge_method: "S256",
4403
+ state: request.state,
4404
+ redirect_uri: callbackUrl
4405
+ });
4406
+ if (effectiveAuthConfig.clientId) {
4407
+ params.set("client_id", effectiveAuthConfig.clientId);
4408
+ }
4409
+ if (effectiveAuthConfig.scopes?.length) {
4410
+ params.set("scope", effectiveAuthConfig.scopes.join(" "));
4411
+ }
4412
+ if (effectiveAuthConfig.resource) {
4413
+ params.set("resource", effectiveAuthConfig.resource);
4414
+ }
4415
+ if (request.userIdentity && isGatewayAuthorizeUrl2(effectiveAuthConfig)) {
4416
+ const subject = normalizeOptionalValue2(request.userIdentity.subject);
4417
+ const email = normalizeOptionalValue2(request.userIdentity.email);
4418
+ const organizationId = normalizeOptionalValue2(request.userIdentity.organizationId);
4419
+ const displayName = normalizeOptionalValue2(request.userIdentity.displayName);
4420
+ if (subject) {
4421
+ params.set("mcpstack_host_subject", subject);
4422
+ }
4423
+ if (email) {
4424
+ params.set("mcpstack_host_email", email);
4425
+ }
4426
+ if (organizationId) {
4427
+ params.set("mcpstack_host_organization_id", organizationId);
4428
+ }
4429
+ if (displayName) {
4430
+ params.set("mcpstack_host_display_name", displayName);
4431
+ }
4432
+ params.set(
4433
+ "mcpstack_mismatch_policy",
4434
+ "block_with_switch"
4435
+ );
4436
+ }
4437
+ authUrl = `${loginUrl}${loginUrl.includes("?") ? "&" : "?"}${params.toString()}`;
4438
+ } else {
4439
+ const params = new URLSearchParams({
4440
+ state: request.state,
4441
+ redirect_uri: callbackUrl,
4442
+ mode: "popup"
4443
+ });
4444
+ if (effectiveAuthConfig.clientId) {
4445
+ params.set("client_id", effectiveAuthConfig.clientId);
4446
+ }
4447
+ if (effectiveAuthConfig.resource) {
4448
+ params.set("resource", effectiveAuthConfig.resource);
4449
+ }
4450
+ authUrl = `${loginUrl}${loginUrl.includes("?") ? "&" : "?"}${params.toString()}`;
4451
+ }
4452
+ if (request.popupWindow.closed) {
4453
+ transitionActiveRequest(
4454
+ "canceled",
4455
+ "The sign-in window was closed before authentication completed."
4456
+ );
4457
+ return;
4458
+ }
4459
+ try {
4460
+ request.popupWindow.location.replace(authUrl);
4461
+ } catch {
4462
+ closePopupWindow(request);
4463
+ transitionActiveRequest(
4464
+ "error",
4465
+ "The sign-in popup could not be opened. Try again."
4466
+ );
4467
+ return;
4468
+ }
4469
+ request.popupWindow.focus?.();
4470
+ request.pollTimer = setInterval(() => {
4471
+ const activeRequest = activeRequestRef.current;
4472
+ if (!activeRequest || activeRequest !== request) {
4473
+ clearPollTimer(request);
4474
+ return;
4475
+ }
4476
+ if (request.popupWindow?.closed) {
4477
+ clearPollTimer(request);
4478
+ if (mountedRef.current) {
4479
+ setPopupState(
4480
+ createPopupState(
4481
+ request,
4482
+ "canceled",
4483
+ null,
4484
+ "The sign-in window was closed before authentication completed."
4485
+ )
4486
+ );
4487
+ }
4488
+ }
4489
+ }, 500);
4490
+ if (mountedRef.current) {
4491
+ setPopupState(
4492
+ createPopupState(
4493
+ request,
4494
+ "waiting",
4495
+ "Finish sign in in the popup window to connect your account."
4496
+ )
4497
+ );
4498
+ }
4499
+ }, [
4500
+ clearPollTimer,
4501
+ clearStoredCallbackPayload,
4502
+ closePopupWindow,
4503
+ getCallbackUrl,
4504
+ transitionActiveRequest
4505
+ ]);
4506
+ const cancelPopupAuth = useCallback(() => {
4507
+ if (!activeRequestRef.current) {
4508
+ dismissPopupState();
4509
+ return;
4510
+ }
4511
+ resolveAndClearActiveRequest(void 0);
4512
+ }, [dismissPopupState, resolveAndClearActiveRequest]);
4513
+ const handleServerAuthStatus = useCallback((serverUrl, authStatus) => {
4514
+ if (authStatus !== "connected") {
4515
+ return;
4516
+ }
4517
+ const request = activeRequestRef.current;
4518
+ if (request && request.serverUrl === serverUrl) {
4519
+ clearPollTimer(request);
4520
+ closePopupWindow(request);
4521
+ clearStoredCallbackPayload(request.state);
4522
+ activeRequestRef.current = null;
4523
+ }
4524
+ dismissPopupState(serverUrl);
4525
+ }, [clearPollTimer, clearStoredCallbackPayload, closePopupWindow, dismissPopupState]);
4526
+ const requestAuth = useCallback((serverUrl, authConfig) => {
4527
+ const activeRequest = activeRequestRef.current;
4528
+ if (activeRequest) {
4529
+ if (activeRequest.serverUrl === serverUrl) {
4530
+ return activeRequest.promise;
4531
+ }
4532
+ if (mountedRef.current) {
4533
+ setPopupState((currentState) => currentState ? {
4534
+ ...currentState,
4535
+ errorMessage: "Another MCP server sign-in is already in progress. Finish or cancel it first."
4536
+ } : createPopupState(
4537
+ activeRequest,
4538
+ "error",
4539
+ null,
4540
+ "Another MCP server sign-in is already in progress. Finish or cancel it first."
4541
+ ));
4542
+ }
4543
+ return Promise.reject(
4544
+ new Error("Another MCP server sign-in is already in progress. Finish or cancel it first.")
4545
+ );
4546
+ }
4547
+ const serverName = optionsRef.current.resolveServerName(serverUrl);
4548
+ let resolvePromise = () => {
4549
+ };
4550
+ const promise = new Promise((resolve) => {
4551
+ resolvePromise = resolve;
4552
+ });
4553
+ const request = {
4554
+ serverName,
4555
+ serverUrl,
4556
+ authConfig,
4557
+ resolvedAuthConfig: authConfig,
4558
+ promise,
4559
+ resolve: resolvePromise,
4560
+ state: "",
4561
+ codeVerifier: "",
4562
+ handledCallback: false,
4563
+ popupWindow: null,
4564
+ userIdentity: optionsRef.current.userIdentity,
4565
+ hostIdentityLabel: formatUserIdentityLabel(optionsRef.current.userIdentity)
4566
+ };
4567
+ activeRequestRef.current = request;
4568
+ setPopupState(createPopupState(request, "prompt"));
4569
+ return promise;
4570
+ }, []);
4571
+ useEffect2(() => {
4572
+ const handleMessage = (event) => {
4573
+ const request = activeRequestRef.current;
4574
+ if (!request) {
4575
+ return;
4576
+ }
4577
+ try {
4578
+ const callbackOrigin = new URL(getCallbackUrl(request.resolvedAuthConfig)).origin;
4579
+ if (event.origin !== callbackOrigin) {
4580
+ return;
4581
+ }
4582
+ } catch {
4583
+ return;
4584
+ }
4585
+ handleAuthPayload(event.data);
4586
+ };
4587
+ const handleStorage = (event) => {
4588
+ if (!event.key?.startsWith(OAUTH_CALLBACK_STORAGE_PREFIX) || !event.newValue) {
4589
+ return;
4590
+ }
4591
+ try {
4592
+ const parsed = JSON.parse(event.newValue);
4593
+ handleAuthPayload(parsed);
4594
+ } catch {
4595
+ }
4596
+ };
4597
+ const channel = typeof BroadcastChannel !== "undefined" ? new BroadcastChannel(OAUTH_CALLBACK_CHANNEL_NAME) : null;
4598
+ if (channel) {
4599
+ channel.onmessage = (event) => {
4600
+ handleAuthPayload(event.data);
4601
+ };
4602
+ }
4603
+ window.addEventListener("message", handleMessage);
4604
+ window.addEventListener("storage", handleStorage);
4605
+ return () => {
4606
+ window.removeEventListener("message", handleMessage);
4607
+ window.removeEventListener("storage", handleStorage);
4608
+ channel?.close();
4609
+ };
4610
+ }, [getCallbackUrl, handleAuthPayload]);
4611
+ useEffect2(() => () => {
4612
+ mountedRef.current = false;
4613
+ const request = activeRequestRef.current;
4614
+ if (!request) {
4615
+ return;
4616
+ }
4617
+ clearPollTimer(request);
4618
+ closePopupWindow(request);
4619
+ clearStoredCallbackPayload(request.state);
4620
+ activeRequestRef.current = null;
4621
+ request.resolve(void 0);
4622
+ }, [clearPollTimer, clearStoredCallbackPayload, closePopupWindow]);
4623
+ return useMemo2(() => ({
4624
+ popupState,
4625
+ requestAuth,
4626
+ startOrRetryPopupAuth,
4627
+ cancelPopupAuth,
4628
+ handleServerAuthStatus
4629
+ }), [
4630
+ cancelPopupAuth,
4631
+ handleServerAuthStatus,
4632
+ popupState,
4633
+ requestAuth,
4634
+ startOrRetryPopupAuth
4635
+ ]);
4636
+ }
4637
+
4638
+ // src/react-app/index.tsx
4639
+ import { jsx } from "react/jsx-runtime";
4640
+ var AppAgentContext = createContext(null);
4641
+ function useAppAgent(config, options) {
4642
+ const shouldUseBuiltInPopupAuth = !config.onAuthRequired && !config.auth;
4643
+ const popupRequestAuthRef = useRef3(null);
4644
+ const builtInPopupAuthHandler = useMemo3(() => {
4645
+ const handler = (serverUrl, authConfig) => popupRequestAuthRef.current?.(serverUrl, authConfig) ?? Promise.resolve(void 0);
4646
+ handler.__mcpStackBuiltinPopupAuth = true;
4647
+ return handler;
4648
+ }, []);
4649
+ const base = useAppAgentBinding(
4650
+ config,
4651
+ options,
4652
+ shouldUseBuiltInPopupAuth ? { onAuthRequired: builtInPopupAuthHandler } : void 0
4653
+ );
4654
+ const popup = usePopupOAuthController({
4655
+ resolveServerName: (serverUrl) => base.runtime.agentConfig?.mcpServers.find((server) => server.url === serverUrl)?.name ?? "MCP Server",
4656
+ oauthCallbackUrl: base.runtime.agent.getOAuthCallbackUrl(),
4657
+ oauthClientMetadataUrl: base.runtime.agent.getOAuthClientMetadataUrl(),
4658
+ userIdentity: config.userIdentity,
4659
+ appSessionKey: config.appSessionKey
4660
+ });
4661
+ popupRequestAuthRef.current = popup.requestAuth;
4662
+ useEffect3(() => {
4663
+ if (!shouldUseBuiltInPopupAuth) {
4664
+ return;
4665
+ }
4666
+ base.controller.setAuthRequiredHandler(builtInPopupAuthHandler);
4667
+ }, [base.controller, builtInPopupAuthHandler, shouldUseBuiltInPopupAuth]);
4668
+ useEffect3(() => {
4669
+ base.connections.items.forEach((server) => {
4670
+ popup.handleServerAuthStatus(server.url, server.authStatus);
4671
+ });
4672
+ }, [base.connections.items, popup.handleServerAuthStatus]);
4673
+ const visiblePopupState = shouldUseBuiltInPopupAuth && popup.popupState ? base.connections.items.find((server) => server.url === popup.popupState?.serverUrl)?.authStatus === "connected" ? null : popup.popupState : null;
4674
+ return {
4675
+ ...base,
4676
+ popupAuthState: visiblePopupState,
4677
+ startOrRetryPopupAuth: popup.startOrRetryPopupAuth,
4678
+ cancelPopupAuth: popup.cancelPopupAuth
4679
+ };
4680
+ }
4681
+ function AppAgentProvider({
4682
+ children,
4683
+ ...config
4684
+ }) {
4685
+ const value = useAppAgent(config);
4686
+ return /* @__PURE__ */ jsx(AppAgentContext.Provider, { value, children });
4687
+ }
4688
+ function useAppAgentContext() {
4689
+ const context = useContext(AppAgentContext);
4690
+ if (!context) {
4691
+ throw new Error("useAppAgentContext must be used within an AppAgentProvider.");
4692
+ }
4693
+ return context;
4694
+ }
4695
+ export {
4696
+ AppAgentProvider,
4697
+ useAppAgent,
4698
+ useAppAgentContext
4699
+ };
4700
+ //# sourceMappingURL=index.mjs.map