@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.
package/dist/index.js ADDED
@@ -0,0 +1,2649 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ McpStackAgent: () => McpStackAgent,
24
+ clearPersistedMcpAuth: () => clearPersistedMcpAuth,
25
+ clearPersistedMcpAuthState: () => clearPersistedMcpAuthState
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+
29
+ // src/core/sse-client.ts
30
+ function* parseEventBlocks(input) {
31
+ const normalized = input.replace(/\r\n/g, "\n");
32
+ const eventBlocks = normalized.split("\n\n");
33
+ for (const eventBlock of eventBlocks) {
34
+ if (!eventBlock.trim()) continue;
35
+ let eventType = "";
36
+ const dataLines = [];
37
+ for (const line of eventBlock.split("\n")) {
38
+ if (line.startsWith("event: ")) {
39
+ eventType = line.slice("event: ".length);
40
+ } else if (line.startsWith("data: ")) {
41
+ dataLines.push(line.slice("data: ".length));
42
+ } else if (line === "data:") {
43
+ dataLines.push("");
44
+ }
45
+ }
46
+ if (!eventType || dataLines.length === 0) {
47
+ continue;
48
+ }
49
+ try {
50
+ const parsed = JSON.parse(dataLines.join("\n"));
51
+ yield { type: eventType, data: parsed };
52
+ } catch {
53
+ }
54
+ }
55
+ }
56
+ async function* parseSseStream(response, signal) {
57
+ const reader = response.body?.getReader();
58
+ if (!reader) {
59
+ const text = await response.text().catch(() => "");
60
+ yield* parseEventBlocks(text);
61
+ return;
62
+ }
63
+ const decoder = new TextDecoder();
64
+ let buffer = "";
65
+ try {
66
+ while (true) {
67
+ if (signal?.aborted) break;
68
+ const { done, value } = await reader.read();
69
+ if (done) break;
70
+ buffer += decoder.decode(value, { stream: true });
71
+ const normalized = buffer.replace(/\r\n/g, "\n");
72
+ const events = normalized.split("\n\n");
73
+ buffer = events.pop() ?? "";
74
+ for (const eventBlock of events) {
75
+ yield* parseEventBlocks(eventBlock);
76
+ }
77
+ }
78
+ if (buffer.trim()) {
79
+ yield* parseEventBlocks(buffer);
80
+ }
81
+ } finally {
82
+ reader.releaseLock();
83
+ }
84
+ }
85
+
86
+ // src/core/auth/registration.ts
87
+ var REGISTRATION_STORAGE_PREFIX = "mcpstack_oauth_registration_";
88
+ function getStorage(storage) {
89
+ if (storage) {
90
+ return storage;
91
+ }
92
+ try {
93
+ return typeof localStorage === "undefined" ? null : localStorage;
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+ function encodeCacheKey(raw) {
99
+ return btoa(raw).replace(/[^a-zA-Z0-9]/g, "");
100
+ }
101
+ function getPreferredRegistrationPreference(authConfig) {
102
+ return authConfig?.registrationPreference ?? "auto";
103
+ }
104
+ function getEffectiveCallbackUrl(authConfig, fallbackCallbackUrl) {
105
+ const configuredCallbackUrl = authConfig?.callbackUrl?.trim();
106
+ if (!configuredCallbackUrl) {
107
+ return fallbackCallbackUrl;
108
+ }
109
+ if (isNativeCallbackUrl(fallbackCallbackUrl) && !isNativeCallbackUrl(configuredCallbackUrl)) {
110
+ return fallbackCallbackUrl;
111
+ }
112
+ return configuredCallbackUrl;
113
+ }
114
+ function buildRegistrationCacheKey(authConfig, callbackUrl, requestedMode) {
115
+ const raw = [
116
+ authConfig.authorizationServerUrl ?? "",
117
+ authConfig.authorizationServerMetadataUrl ?? "",
118
+ authConfig.resource ?? "",
119
+ callbackUrl,
120
+ requestedMode
121
+ ].join("|");
122
+ return encodeCacheKey(raw);
123
+ }
124
+ function buildTokenCacheKey(authConfig, mcpServerUrl) {
125
+ if (!authConfig) {
126
+ return encodeCacheKey(`legacy|${mcpServerUrl}`);
127
+ }
128
+ const callbackUrl = authConfig.callbackUrl ?? "";
129
+ const clientMode = authConfig.clientMode ?? "manual";
130
+ const raw = [
131
+ authConfig.authorizationServerUrl ?? mcpServerUrl,
132
+ authConfig.resource ?? "",
133
+ callbackUrl,
134
+ clientMode
135
+ ].join("|");
136
+ return encodeCacheKey(raw);
137
+ }
138
+ function loadStoredRegistration(cacheKey, storage) {
139
+ const targetStorage = getStorage(storage);
140
+ if (!targetStorage) return null;
141
+ try {
142
+ const raw = targetStorage.getItem(`${REGISTRATION_STORAGE_PREFIX}${cacheKey}`);
143
+ if (!raw) return null;
144
+ return JSON.parse(raw);
145
+ } catch {
146
+ return null;
147
+ }
148
+ }
149
+ function saveStoredRegistration(registration, storage) {
150
+ const targetStorage = getStorage(storage);
151
+ if (!targetStorage) return;
152
+ try {
153
+ targetStorage.setItem(
154
+ `${REGISTRATION_STORAGE_PREFIX}${registration.key}`,
155
+ JSON.stringify(registration)
156
+ );
157
+ } catch {
158
+ }
159
+ }
160
+ function applyResolvedRegistration(authConfig, registration) {
161
+ return {
162
+ ...authConfig,
163
+ callbackUrl: registration.callbackUrl,
164
+ clientId: registration.clientId ?? authConfig.clientId,
165
+ clientMode: registration.mode,
166
+ resource: registration.resource ?? authConfig.resource,
167
+ authorizationServerUrl: registration.authorizationServerUrl ?? authConfig.authorizationServerUrl,
168
+ authorizationServerMetadataUrl: registration.authorizationServerMetadataUrl ?? authConfig.authorizationServerMetadataUrl,
169
+ registrationEndpoint: registration.registrationEndpoint ?? authConfig.registrationEndpoint
170
+ };
171
+ }
172
+ function createResolvedRegistration(authConfig, mode, callbackUrl, clientId, clientMetadataUrl) {
173
+ return {
174
+ cacheKey: buildRegistrationCacheKey(authConfig, callbackUrl, mode),
175
+ mode,
176
+ clientId,
177
+ callbackUrl,
178
+ resource: authConfig.resource,
179
+ authorizationServerUrl: authConfig.authorizationServerUrl,
180
+ authorizationServerMetadataUrl: authConfig.authorizationServerMetadataUrl,
181
+ registrationEndpoint: authConfig.registrationEndpoint,
182
+ clientMetadataUrl
183
+ };
184
+ }
185
+ function shouldAttemptMode(preferred, candidate) {
186
+ return preferred === "auto" || preferred === candidate;
187
+ }
188
+ function isLoopbackHost(hostname) {
189
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
190
+ }
191
+ function isNativeCallbackUrl(callbackUrl) {
192
+ try {
193
+ const url = new URL(callbackUrl);
194
+ return url.protocol !== "http:" && url.protocol !== "https:";
195
+ } catch {
196
+ return !callbackUrl.startsWith("http://") && !callbackUrl.startsWith("https://");
197
+ }
198
+ }
199
+ function inferApplicationType(callbackUrl) {
200
+ try {
201
+ const url = new URL(callbackUrl);
202
+ if (url.protocol === "http:" || url.protocol === "https:") {
203
+ return isLoopbackHost(url.hostname) ? "native" : "web";
204
+ }
205
+ return "native";
206
+ } catch {
207
+ return "native";
208
+ }
209
+ }
210
+ async function registerPublicClient(authConfig, options) {
211
+ const fetchImpl = options.fetchImpl ?? fetch;
212
+ const callbackUrl = options.callbackUrl;
213
+ const registration = createResolvedRegistration(authConfig, "dcr", callbackUrl);
214
+ if (!authConfig.registrationEndpoint) {
215
+ throw new Error("Dynamic client registration is not available for this server.");
216
+ }
217
+ const existing = loadStoredRegistration(registration.cacheKey, options.storage);
218
+ if (existing?.clientId) {
219
+ return {
220
+ ...registration,
221
+ clientId: existing.clientId
222
+ };
223
+ }
224
+ const requestBody = {
225
+ client_name: options.clientName ?? "MCP Stack MCP Client",
226
+ application_type: inferApplicationType(callbackUrl),
227
+ redirect_uris: [callbackUrl],
228
+ grant_types: ["authorization_code", "refresh_token"],
229
+ response_types: ["code"],
230
+ token_endpoint_auth_method: "none",
231
+ scope: authConfig.scopes?.join(" "),
232
+ client_uri: options.clientUri
233
+ };
234
+ const response = await fetchImpl(authConfig.registrationEndpoint, {
235
+ method: "POST",
236
+ headers: {
237
+ Accept: "application/json",
238
+ "Content-Type": "application/json"
239
+ },
240
+ body: JSON.stringify(requestBody)
241
+ });
242
+ if (!response.ok) {
243
+ const errorText = await response.text().catch(() => "Dynamic client registration failed.");
244
+ throw new Error(`Dynamic client registration failed (${response.status}): ${errorText}`);
245
+ }
246
+ const payload = await response.json();
247
+ if (!payload.client_id) {
248
+ throw new Error("Dynamic client registration response did not include a client_id.");
249
+ }
250
+ saveStoredRegistration({
251
+ key: registration.cacheKey,
252
+ mode: "dcr",
253
+ authorizationServerUrl: authConfig.authorizationServerUrl ?? "",
254
+ authorizationServerMetadataUrl: authConfig.authorizationServerMetadataUrl,
255
+ registrationEndpoint: authConfig.registrationEndpoint,
256
+ clientId: payload.client_id,
257
+ callbackUrl,
258
+ resource: authConfig.resource,
259
+ createdAt: Date.now(),
260
+ updatedAt: Date.now()
261
+ }, options.storage);
262
+ return {
263
+ ...registration,
264
+ clientId: payload.client_id
265
+ };
266
+ }
267
+ async function resolveOAuthRegistration(authConfig, options) {
268
+ const callbackUrl = getEffectiveCallbackUrl(authConfig, options.callbackUrl);
269
+ const preferred = getPreferredRegistrationPreference(authConfig);
270
+ const preregClientId = authConfig.clientId?.trim();
271
+ if (preregClientId && shouldAttemptMode(preferred, "preregistered")) {
272
+ return createResolvedRegistration(
273
+ authConfig,
274
+ "preregistered",
275
+ callbackUrl,
276
+ preregClientId
277
+ );
278
+ }
279
+ if (authConfig.clientIdMetadataDocumentSupported && options.oauthClientMetadataUrl && shouldAttemptMode(preferred, "cimd")) {
280
+ return createResolvedRegistration(
281
+ authConfig,
282
+ "cimd",
283
+ callbackUrl,
284
+ options.oauthClientMetadataUrl,
285
+ options.oauthClientMetadataUrl
286
+ );
287
+ }
288
+ if (authConfig.registrationEndpoint && shouldAttemptMode(preferred, "dcr")) {
289
+ return registerPublicClient(authConfig, {
290
+ ...options,
291
+ callbackUrl
292
+ });
293
+ }
294
+ return createResolvedRegistration(
295
+ authConfig,
296
+ preregClientId ? "preregistered" : "manual",
297
+ callbackUrl,
298
+ preregClientId
299
+ );
300
+ }
301
+
302
+ // src/core/auth-storage.ts
303
+ var LEGACY_OAUTH_TOKEN_STORAGE_PREFIX = "mcpstack_oauth_";
304
+ var REGISTRATION_STORAGE_PREFIX2 = "mcpstack_oauth_registration_";
305
+ var SCOPED_OAUTH_TOKEN_STORAGE_PREFIX = "mcpstack_oauth_session_";
306
+ var OAUTH_CALLBACK_STORAGE_PREFIX = "mcpstack-oauth-callback:";
307
+ function hashAuthSessionKey(value) {
308
+ let hash = 2166136261;
309
+ for (let index = 0; index < value.length; index += 1) {
310
+ hash ^= value.charCodeAt(index);
311
+ hash = Math.imul(hash, 16777619);
312
+ }
313
+ return (hash >>> 0).toString(36);
314
+ }
315
+ function normalizeAuthSessionKey(value) {
316
+ if (typeof value !== "string") {
317
+ return null;
318
+ }
319
+ const normalized = value.trim();
320
+ return normalized || null;
321
+ }
322
+ function resolveExplicitAuthSessionKey(config) {
323
+ return normalizeAuthSessionKey(config.authSessionKey);
324
+ }
325
+ function buildScopedOAuthTokenStoragePrefix(authSessionKey) {
326
+ const normalizedSessionKey = normalizeAuthSessionKey(authSessionKey);
327
+ if (!normalizedSessionKey) {
328
+ return LEGACY_OAUTH_TOKEN_STORAGE_PREFIX;
329
+ }
330
+ return `${SCOPED_OAUTH_TOKEN_STORAGE_PREFIX}${hashAuthSessionKey(normalizedSessionKey)}_`;
331
+ }
332
+ function buildScopedOAuthTokenStorageKey(cacheKey, authSessionKey) {
333
+ return `${buildScopedOAuthTokenStoragePrefix(authSessionKey)}${cacheKey}`;
334
+ }
335
+ function getStorage2(storage) {
336
+ if (storage) {
337
+ return storage;
338
+ }
339
+ try {
340
+ return typeof localStorage === "undefined" ? null : localStorage;
341
+ } catch {
342
+ return null;
343
+ }
344
+ }
345
+ function clearPersistedMcpAuthState(options = {}) {
346
+ const storage = getStorage2(options.storage);
347
+ if (!storage) {
348
+ return;
349
+ }
350
+ const scopedPrefix = buildScopedOAuthTokenStoragePrefix(
351
+ options.authSessionKey
352
+ );
353
+ const tokenPrefixes = options.clearAll ? [LEGACY_OAUTH_TOKEN_STORAGE_PREFIX, SCOPED_OAUTH_TOKEN_STORAGE_PREFIX] : [scopedPrefix];
354
+ try {
355
+ for (let index = storage.length - 1; index >= 0; index -= 1) {
356
+ const key = storage.key(index);
357
+ if (!key) {
358
+ continue;
359
+ }
360
+ if (key.startsWith(OAUTH_CALLBACK_STORAGE_PREFIX)) {
361
+ storage.removeItem(key);
362
+ continue;
363
+ }
364
+ if (key.startsWith(REGISTRATION_STORAGE_PREFIX2)) {
365
+ continue;
366
+ }
367
+ if (tokenPrefixes.some((prefix) => key.startsWith(prefix))) {
368
+ storage.removeItem(key);
369
+ }
370
+ }
371
+ } catch {
372
+ }
373
+ }
374
+ function clearPersistedMcpAuth() {
375
+ clearPersistedMcpAuthState({ clearAll: true });
376
+ }
377
+
378
+ // src/core/EmcyAgent.ts
379
+ var DEFAULT_MCP_PROTOCOL_VERSION = "2025-11-25";
380
+ var DEFAULT_LOCAL_PUBLIC_APP_PORT = "3100";
381
+ var DEFAULT_OAUTH_CALLBACK_URL = "https://mcpstack.com/oauth/callback";
382
+ var DEFAULT_OAUTH_CLIENT_METADATA_URL = "https://mcpstack.com/.well-known/oauth-client-metadata.json";
383
+ var DEFAULT_AUDIO_TURN_DETECTION = {
384
+ enabled: true,
385
+ autoSubmit: true,
386
+ silenceDurationMs: 850,
387
+ minSpeechDurationMs: 180,
388
+ noSpeechTimeoutMs: 12e3,
389
+ speechThreshold: 0.012,
390
+ noiseMultiplier: 2.4
391
+ };
392
+ var AUDIO_ACTIVITY_EMIT_INTERVAL_MS = 120;
393
+ var MIN_AUDIO_LEVEL_DELTA_FOR_STATE = 0.03;
394
+ function isLocalhostHost(hostname) {
395
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
396
+ }
397
+ function getDefaultOAuthHelperOrigin(agentServiceUrl) {
398
+ if (!agentServiceUrl) {
399
+ return DEFAULT_OAUTH_CALLBACK_URL.replace(/\/oauth\/callback$/, "");
400
+ }
401
+ try {
402
+ const url = new URL(agentServiceUrl);
403
+ if (isLocalhostHost(url.hostname)) {
404
+ return `${url.protocol}//${url.hostname}:${DEFAULT_LOCAL_PUBLIC_APP_PORT}`;
405
+ }
406
+ } catch {
407
+ }
408
+ return DEFAULT_OAUTH_CALLBACK_URL.replace(/\/oauth\/callback$/, "");
409
+ }
410
+ function getDefaultOAuthCallbackUrl(agentServiceUrl) {
411
+ return `${getDefaultOAuthHelperOrigin(agentServiceUrl)}/oauth/callback`;
412
+ }
413
+ function getDefaultOAuthClientMetadataUrl(agentServiceUrl) {
414
+ return `${getDefaultOAuthHelperOrigin(agentServiceUrl)}/.well-known/oauth-client-metadata.json`;
415
+ }
416
+ function buildEmbeddedExchangeUrl(mcpServerUrl) {
417
+ const url = new URL(mcpServerUrl);
418
+ if (/\/mcp\/?$/i.test(url.pathname)) {
419
+ url.pathname = url.pathname.replace(/\/mcp\/?$/i, "/embedded/exchange");
420
+ } else {
421
+ url.pathname = `${url.pathname.replace(/\/$/, "")}/embedded/exchange`;
422
+ }
423
+ return url.toString();
424
+ }
425
+ function normalizeOAuthTokenResponse(payload, authConfig) {
426
+ const accessToken = typeof payload.accessToken === "string" ? payload.accessToken : typeof payload.access_token === "string" ? payload.access_token : "";
427
+ if (!accessToken) {
428
+ return void 0;
429
+ }
430
+ return {
431
+ accessToken,
432
+ refreshToken: typeof payload.refreshToken === "string" ? payload.refreshToken : typeof payload.refresh_token === "string" ? payload.refresh_token : void 0,
433
+ expiresIn: typeof payload.expiresIn === "number" ? payload.expiresIn : typeof payload.expires_in === "number" ? payload.expires_in : void 0,
434
+ tokenType: typeof payload.tokenType === "string" ? payload.tokenType : typeof payload.token_type === "string" ? payload.token_type : "Bearer",
435
+ resolvedAuthConfig: authConfig
436
+ };
437
+ }
438
+ function createAppTokenAuthHandler(agentId, auth) {
439
+ return async (mcpServerUrl, authConfig) => {
440
+ const appToken = await auth.getToken();
441
+ const trimmedToken = appToken?.trim();
442
+ if (!trimmedToken) {
443
+ return void 0;
444
+ }
445
+ const headers = {
446
+ "Content-Type": "application/json",
447
+ Authorization: `Bearer ${trimmedToken}`
448
+ };
449
+ if (auth.appId?.trim()) {
450
+ headers["x-mcpstack-embedded-app-id"] = auth.appId.trim();
451
+ }
452
+ const body = {
453
+ agentId,
454
+ resource: authConfig.resource ?? mcpServerUrl,
455
+ scopes: authConfig.scopes
456
+ };
457
+ if (auth.appId?.trim()) {
458
+ body.appId = auth.appId.trim();
459
+ }
460
+ const response = await fetch(buildEmbeddedExchangeUrl(mcpServerUrl), {
461
+ method: "POST",
462
+ headers,
463
+ body: JSON.stringify(body)
464
+ });
465
+ const payload = await response.json().catch(() => null);
466
+ if (!response.ok) {
467
+ const description = typeof payload?.error_description === "string" ? payload.error_description : typeof payload?.error === "string" ? payload.error : `App token exchange failed (${response.status}).`;
468
+ throw new Error(description);
469
+ }
470
+ return normalizeOAuthTokenResponse(payload ?? {}, authConfig);
471
+ };
472
+ }
473
+ function extractErrorMessage(payload) {
474
+ if (typeof payload === "string") {
475
+ const message = payload.trim();
476
+ return message || null;
477
+ }
478
+ if (!payload || typeof payload !== "object") {
479
+ return null;
480
+ }
481
+ const record = payload;
482
+ for (const key of ["error", "message", "detail"]) {
483
+ const value = record[key];
484
+ if (typeof value === "string" && value.trim()) {
485
+ return value.trim();
486
+ }
487
+ }
488
+ return null;
489
+ }
490
+ async function getResponseErrorMessage(response) {
491
+ const fallback = `HTTP ${response.status}`;
492
+ try {
493
+ const payload = await response.clone().json();
494
+ const message = extractErrorMessage(payload);
495
+ if (message) {
496
+ return message;
497
+ }
498
+ } catch {
499
+ }
500
+ const text = await response.text().catch(() => "");
501
+ return text.trim() || fallback;
502
+ }
503
+ function parameterToJsonSchema(parameter) {
504
+ const schema = {
505
+ type: parameter.type
506
+ };
507
+ if (parameter.description) {
508
+ schema.description = parameter.description;
509
+ }
510
+ if (parameter.enum) {
511
+ schema.enum = parameter.enum;
512
+ }
513
+ if (parameter.type === "array") {
514
+ schema.items = parameter.items ? parameterToJsonSchema(parameter.items) : { type: "string" };
515
+ }
516
+ if (parameter.type === "object" && parameter.properties) {
517
+ const properties = {};
518
+ const required = [];
519
+ for (const [key, child] of Object.entries(parameter.properties)) {
520
+ properties[key] = parameterToJsonSchema(child);
521
+ if (child.required) required.push(key);
522
+ }
523
+ schema.properties = properties;
524
+ schema.required = required;
525
+ }
526
+ if (parameter.additionalProperties !== void 0) {
527
+ schema.additionalProperties = typeof parameter.additionalProperties === "boolean" ? parameter.additionalProperties : parameterToJsonSchema(parameter.additionalProperties);
528
+ }
529
+ return schema;
530
+ }
531
+ function parametersToJsonSchema(params) {
532
+ const properties = {};
533
+ const required = [];
534
+ for (const [key, p] of Object.entries(params)) {
535
+ properties[key] = parameterToJsonSchema(p);
536
+ if (p.required) required.push(key);
537
+ }
538
+ return { type: "object", properties, required };
539
+ }
540
+ var McpStackAgent = class {
541
+ constructor(config) {
542
+ this.agentConfig = null;
543
+ this.budgetSnapshot = null;
544
+ this.conversationId = null;
545
+ this.messages = [];
546
+ this.historyCursor = null;
547
+ this.hasOlderMessages = false;
548
+ this.isLoadingHistory = false;
549
+ this.abortController = null;
550
+ this.isLoading = false;
551
+ this.listeners = /* @__PURE__ */ new Map();
552
+ /** Per-server MCP session tracking */
553
+ this.mcpSessions = /* @__PURE__ */ new Map();
554
+ /** OAuth tokens per MCP server URL (standalone mode only) */
555
+ this.oauthTokens = /* @__PURE__ */ new Map();
556
+ /** Servers explicitly disconnected by the user and awaiting manual re-auth */
557
+ this.manuallySignedOutServers = /* @__PURE__ */ new Set();
558
+ this.audioState = {
559
+ status: "idle",
560
+ isSupported: false,
561
+ isEnabled: false,
562
+ transcript: "",
563
+ partialTranscript: "",
564
+ error: null
565
+ };
566
+ this.audioStream = null;
567
+ this.audioContext = null;
568
+ this.audioSource = null;
569
+ this.audioProcessor = null;
570
+ this.audioSilentGain = null;
571
+ this.audioSocket = null;
572
+ this.audioSessionTimer = null;
573
+ this.audioSessionStopRequested = false;
574
+ this.audioFinalTranscript = "";
575
+ this.audioTurnState = null;
576
+ const appTokenAuthHandler = config.auth?.mode === "app-token" ? createAppTokenAuthHandler(config.agentId, config.auth) : void 0;
577
+ this.config = {
578
+ ...config,
579
+ agentServiceUrl: config.agentServiceUrl ?? "https://api.mcpstack.com",
580
+ oauthCallbackUrl: config.oauthCallbackUrl ?? getDefaultOAuthCallbackUrl(config.agentServiceUrl),
581
+ oauthClientMetadataUrl: config.oauthClientMetadataUrl ?? getDefaultOAuthClientMetadataUrl(config.agentServiceUrl),
582
+ onAuthRequired: config.onAuthRequired ?? appTokenAuthHandler
583
+ };
584
+ this.audioState = this.buildAudioState({ status: "idle" });
585
+ }
586
+ async resolveAuthToken() {
587
+ if (this.config.getAuthToken) {
588
+ const token = await this.config.getAuthToken();
589
+ if (token) return token;
590
+ }
591
+ return this.config.apiKey;
592
+ }
593
+ /** Initialize: fetch agent config (tools, widget settings, MCP servers) */
594
+ async init() {
595
+ const token = await this.resolveAuthToken();
596
+ const response = await fetch(
597
+ `${this.config.agentServiceUrl}/api/v1/agents/${this.config.agentId}/config`,
598
+ {
599
+ headers: {
600
+ Authorization: `Bearer ${token}`
601
+ }
602
+ }
603
+ );
604
+ if (!response.ok) {
605
+ throw new Error(await getResponseErrorMessage(response));
606
+ }
607
+ this.agentConfig = await response.json();
608
+ this.audioState = this.buildAudioState({ status: "idle" });
609
+ this.emit("audio_state", this.audioState);
610
+ await this.refreshBudgetSnapshot().catch(() => void 0);
611
+ if (this.agentConfig?.mcpServers?.length) {
612
+ await Promise.all(
613
+ this.agentConfig.mcpServers.map(async (server) => {
614
+ server.authConfig = await this.resolveServerAuthConfig(server.url, server.authConfig ?? null);
615
+ })
616
+ );
617
+ }
618
+ if (this.agentConfig?.mcpServers) {
619
+ for (const server of this.agentConfig.mcpServers) {
620
+ if (!this.mcpSessions.has(server.url)) {
621
+ let authStatus;
622
+ if (server.authConfig?.authType === "oauth2") {
623
+ authStatus = server.authStatus === "connected" || this.hasValidOAuthToken(server.url) ? "connected" : "needs_auth";
624
+ } else {
625
+ authStatus = server.authStatus || "connected";
626
+ }
627
+ this.mcpSessions.set(server.url, { sessionId: null, authStatus });
628
+ }
629
+ }
630
+ }
631
+ if (this.config.initialConversationId) {
632
+ await this.loadConversation(this.config.initialConversationId);
633
+ }
634
+ return this.agentConfig;
635
+ }
636
+ /** Get current MCP server auth statuses */
637
+ getMcpServers() {
638
+ if (!this.agentConfig?.mcpServers) return [];
639
+ return this.agentConfig.mcpServers.map((server) => ({
640
+ url: server.url,
641
+ name: server.name,
642
+ authStatus: this.mcpSessions.get(server.url)?.authStatus ?? server.authStatus ?? "connected",
643
+ canSignOut: (server.authConfig?.authType ?? "none") !== "none"
644
+ }));
645
+ }
646
+ /** Send a message and process the full orchestration loop (including tool calls) */
647
+ async sendMessage(message) {
648
+ if (!this.agentConfig) {
649
+ await this.init();
650
+ }
651
+ this.isLoading = true;
652
+ this.emit("loading", true);
653
+ const userMsg = {
654
+ id: crypto.randomUUID(),
655
+ role: "user",
656
+ content: message,
657
+ timestamp: /* @__PURE__ */ new Date()
658
+ };
659
+ this.messages.push(userMsg);
660
+ this.emit("message", userMsg);
661
+ try {
662
+ await this.runChatLoop(message);
663
+ } catch (err) {
664
+ const errorMsg = err instanceof Error ? err.message : "Unknown error";
665
+ this.emit("error", { code: "sdk_error", message: errorMsg });
666
+ } finally {
667
+ this.isLoading = false;
668
+ this.emit("loading", false);
669
+ this.emit("thinking", false);
670
+ }
671
+ }
672
+ /** Start a new conversation */
673
+ newConversation() {
674
+ this.conversationId = null;
675
+ this.messages = [];
676
+ this.historyCursor = null;
677
+ this.hasOlderMessages = false;
678
+ this.isLoadingHistory = false;
679
+ }
680
+ /** Cancel the current in-flight request */
681
+ cancel() {
682
+ this.abortController?.abort();
683
+ this.abortController = null;
684
+ }
685
+ /** Get all messages in the current conversation */
686
+ getMessages() {
687
+ return [...this.messages];
688
+ }
689
+ /** Get the current conversation ID */
690
+ getConversationId() {
691
+ return this.conversationId;
692
+ }
693
+ getHasOlderMessages() {
694
+ return this.hasOlderMessages;
695
+ }
696
+ getIsLoadingHistory() {
697
+ return this.isLoadingHistory;
698
+ }
699
+ /** Get the loaded agent config */
700
+ getAgentConfig() {
701
+ return this.agentConfig;
702
+ }
703
+ getAudioInputState() {
704
+ return { ...this.audioState };
705
+ }
706
+ async startVoiceInput() {
707
+ if (!this.agentConfig) {
708
+ await this.init();
709
+ }
710
+ if (!this.isAudioInputSupported()) {
711
+ this.setAudioState({
712
+ status: "error",
713
+ error: {
714
+ code: "unsupported_browser",
715
+ message: "Microphone input is not supported in this browser."
716
+ }
717
+ });
718
+ return;
719
+ }
720
+ if (!this.isAudioInputEnabled()) {
721
+ this.setAudioState({
722
+ status: "error",
723
+ error: {
724
+ code: "audio_not_enabled",
725
+ message: "Microphone input is not enabled for this agent."
726
+ }
727
+ });
728
+ return;
729
+ }
730
+ if (this.audioState.status === "requesting_permission" || this.audioState.status === "connecting" || this.audioState.status === "listening" || this.audioState.status === "transcribing") {
731
+ return;
732
+ }
733
+ this.audioSessionStopRequested = false;
734
+ this.audioFinalTranscript = "";
735
+ this.audioTurnState = null;
736
+ this.setAudioState({
737
+ status: "requesting_permission",
738
+ transcript: "",
739
+ partialTranscript: "",
740
+ error: null,
741
+ sessionId: null,
742
+ conversationId: this.conversationId,
743
+ inputLevel: 0,
744
+ isSpeaking: false,
745
+ speechMs: 0,
746
+ silenceMs: 0,
747
+ autoSubmitEnabled: this.getAudioTurnDetectionConfig().enabled && this.getAudioTurnDetectionConfig().autoSubmit
748
+ });
749
+ let stream = null;
750
+ try {
751
+ stream = await navigator.mediaDevices.getUserMedia({
752
+ audio: {
753
+ channelCount: 1,
754
+ echoCancellation: true,
755
+ noiseSuppression: true,
756
+ autoGainControl: true
757
+ }
758
+ });
759
+ } catch (error) {
760
+ this.setAudioState({
761
+ status: "error",
762
+ error: {
763
+ code: "microphone_permission_denied",
764
+ message: error instanceof Error ? error.message : "Microphone permission was denied."
765
+ }
766
+ });
767
+ return;
768
+ }
769
+ try {
770
+ this.audioStream = stream;
771
+ this.setAudioState({ status: "connecting" });
772
+ const session = await this.createRealtimeTranscriptionSession();
773
+ this.conversationId = session.conversationId;
774
+ this.setAudioState({
775
+ sessionId: session.sessionId,
776
+ conversationId: session.conversationId,
777
+ maxSessionSeconds: session.maxSessionSeconds
778
+ });
779
+ const socket = await this.openAudioSocket(session.webSocketUrl);
780
+ this.audioSocket = socket;
781
+ this.bindAudioSocket(socket);
782
+ await this.startAudioCapture(stream, socket);
783
+ const maxSessionMs = Math.max(1, session.maxSessionSeconds) * 1e3;
784
+ this.audioSessionTimer = setTimeout(() => {
785
+ void this.commitVoiceInput();
786
+ }, maxSessionMs);
787
+ this.setAudioState({ status: "listening" });
788
+ } catch (error) {
789
+ this.cleanupAudioCapture();
790
+ this.setAudioState({
791
+ status: "error",
792
+ error: {
793
+ code: this.extractErrorCode(error) ?? "audio_start_failed",
794
+ message: error instanceof Error ? error.message : "Could not start microphone input."
795
+ }
796
+ });
797
+ }
798
+ }
799
+ async stopVoiceInput() {
800
+ await this.commitVoiceInput();
801
+ }
802
+ cancelVoiceInput() {
803
+ this.audioSessionStopRequested = true;
804
+ this.cleanupAudioCapture();
805
+ this.audioTurnState = null;
806
+ this.setAudioState({
807
+ status: "idle",
808
+ transcript: "",
809
+ partialTranscript: "",
810
+ error: null,
811
+ sessionId: null,
812
+ inputLevel: 0,
813
+ isSpeaking: false,
814
+ speechMs: 0,
815
+ silenceMs: 0
816
+ });
817
+ }
818
+ async loadConversation(conversationId, pageSize = this.config.conversationHistoryPageSize ?? 50) {
819
+ this.isLoadingHistory = true;
820
+ try {
821
+ const page = await this.fetchConversationMessages(conversationId, void 0, pageSize);
822
+ this.applyConversationPage(page, false);
823
+ return page;
824
+ } finally {
825
+ this.isLoadingHistory = false;
826
+ }
827
+ }
828
+ async loadOlderMessages(pageSize = this.config.conversationHistoryPageSize ?? 50) {
829
+ if (!this.conversationId || !this.historyCursor || !this.hasOlderMessages) {
830
+ return null;
831
+ }
832
+ this.isLoadingHistory = true;
833
+ try {
834
+ const page = await this.fetchConversationMessages(this.conversationId, this.historyCursor, pageSize);
835
+ this.applyConversationPage(page, true);
836
+ return page;
837
+ } finally {
838
+ this.isLoadingHistory = false;
839
+ }
840
+ }
841
+ async submitFeedback(input) {
842
+ if (!this.conversationId) {
843
+ throw new Error("No active conversation to rate.");
844
+ }
845
+ const token = await this.resolveAuthToken();
846
+ const response = await fetch(
847
+ `${this.config.agentServiceUrl}/api/v1/chat/conversations/${encodeURIComponent(this.conversationId)}/feedback`,
848
+ {
849
+ method: "POST",
850
+ headers: {
851
+ "Content-Type": "application/json",
852
+ Authorization: `Bearer ${token}`
853
+ },
854
+ body: JSON.stringify(input)
855
+ }
856
+ );
857
+ if (!response.ok) {
858
+ throw new Error(await getResponseErrorMessage(response));
859
+ }
860
+ return await response.json();
861
+ }
862
+ /** Convert client tools to the API schema format. */
863
+ clientToolsToSchemas() {
864
+ if (!this.config.clientTools) return [];
865
+ return Object.entries(this.config.clientTools).map(([name, def]) => ({
866
+ name,
867
+ description: def.description,
868
+ inputSchema: parametersToJsonSchema(def.parameters),
869
+ selection: def.selection
870
+ }));
871
+ }
872
+ resolveExternalUserId() {
873
+ const hostIdentity = this.config.embeddedAuth?.hostIdentity;
874
+ return this.config.externalUserId ?? hostIdentity?.subject ?? hostIdentity?.email ?? void 0;
875
+ }
876
+ buildExternalUserContext() {
877
+ const hostIdentity = this.config.embeddedAuth?.hostIdentity;
878
+ const id = this.resolveExternalUserId();
879
+ const externalUser = {};
880
+ if (id) externalUser.id = id;
881
+ if (hostIdentity?.email) externalUser.email = hostIdentity.email;
882
+ if (hostIdentity?.displayName) externalUser.displayName = hostIdentity.displayName;
883
+ if (hostIdentity?.avatarUrl) externalUser.avatarUrl = hostIdentity.avatarUrl;
884
+ if (hostIdentity?.organizationId) externalUser.organizationId = hostIdentity.organizationId;
885
+ return Object.keys(externalUser).length > 0 ? externalUser : void 0;
886
+ }
887
+ /** Latest runtime budget snapshot for the current SDK identity. */
888
+ getBudgetSnapshot() {
889
+ return this.budgetSnapshot;
890
+ }
891
+ /** Refresh the current SDK identity's budget snapshot from the API. */
892
+ async refreshBudgetSnapshot() {
893
+ const token = await this.resolveAuthToken();
894
+ const params = new URLSearchParams();
895
+ const externalUserId = this.resolveExternalUserId();
896
+ if (externalUserId) {
897
+ params.set("externalUserId", externalUserId);
898
+ }
899
+ const query = params.toString();
900
+ const response = await fetch(
901
+ `${this.config.agentServiceUrl}/api/v1/agents/${this.config.agentId}/budget${query ? `?${query}` : ""}`,
902
+ {
903
+ headers: {
904
+ Authorization: `Bearer ${token}`
905
+ }
906
+ }
907
+ );
908
+ if (!response.ok) {
909
+ throw new Error(await getResponseErrorMessage(response));
910
+ }
911
+ this.budgetSnapshot = await response.json();
912
+ this.emit("budget_snapshot", this.budgetSnapshot);
913
+ return this.budgetSnapshot;
914
+ }
915
+ /** Whether a request is currently in flight */
916
+ getIsLoading() {
917
+ return this.isLoading;
918
+ }
919
+ /** Update the per-turn app context sent with each chat request. */
920
+ setAppContext(context) {
921
+ this.config = {
922
+ ...this.config,
923
+ context
924
+ };
925
+ }
926
+ /** Update the client tools exposed to the agent without recreating the session. */
927
+ setClientTools(clientTools) {
928
+ this.config = {
929
+ ...this.config,
930
+ clientTools
931
+ };
932
+ }
933
+ /**
934
+ * Proactively authenticate with an MCP server before sending a message.
935
+ * If a token response is provided directly, it is stored immediately.
936
+ * Otherwise, this uses the configured OAuth flow and verifies via MCP init.
937
+ *
938
+ * @param mcpServerUrl - The MCP server URL to authenticate with
939
+ * @param tokenResponse - Optional: provide token response directly (from OAuth popup)
940
+ */
941
+ async authenticate(mcpServerUrl, tokenResponse) {
942
+ const wasManuallySignedOut = this.manuallySignedOutServers.delete(mcpServerUrl);
943
+ try {
944
+ if (tokenResponse?.accessToken) {
945
+ if (tokenResponse.resolvedAuthConfig) {
946
+ this.updateServerAuthConfig(mcpServerUrl, tokenResponse.resolvedAuthConfig);
947
+ }
948
+ this.storeOAuthToken(mcpServerUrl, tokenResponse);
949
+ this.updateMcpAuthStatus(mcpServerUrl, "connected");
950
+ return true;
951
+ }
952
+ const token = await this.resolveToken(mcpServerUrl);
953
+ if (!token) {
954
+ if (wasManuallySignedOut) {
955
+ this.manuallySignedOutServers.add(mcpServerUrl);
956
+ }
957
+ return false;
958
+ }
959
+ this.updateMcpAuthStatus(mcpServerUrl, "connected");
960
+ try {
961
+ await this.initMcpSession(mcpServerUrl);
962
+ return true;
963
+ } catch {
964
+ return true;
965
+ }
966
+ } catch {
967
+ if (wasManuallySignedOut) {
968
+ this.manuallySignedOutServers.add(mcpServerUrl);
969
+ }
970
+ this.updateMcpAuthStatus(mcpServerUrl, "needs_auth");
971
+ return false;
972
+ }
973
+ }
974
+ /** Disconnect from an MCP server and require explicit re-authentication before reuse. */
975
+ async signOutMcpServer(mcpServerUrl) {
976
+ this.manuallySignedOutServers.add(mcpServerUrl);
977
+ await this.closeMcpSession(mcpServerUrl);
978
+ this.clearOAuthToken(mcpServerUrl);
979
+ this.updateMcpAuthStatus(mcpServerUrl, "needs_auth");
980
+ }
981
+ /** Get the auth config for an MCP server (from agent config) */
982
+ getServerAuthConfig(mcpServerUrl) {
983
+ const server = this.agentConfig?.mcpServers?.find((s) => s.url === mcpServerUrl);
984
+ return server?.authConfig ?? null;
985
+ }
986
+ getOAuthCallbackUrl() {
987
+ return this.config.oauthCallbackUrl ?? DEFAULT_OAUTH_CALLBACK_URL;
988
+ }
989
+ getOAuthClientMetadataUrl() {
990
+ return this.config.oauthClientMetadataUrl ?? DEFAULT_OAUTH_CLIENT_METADATA_URL;
991
+ }
992
+ getDefaultAuthRequiredHandler() {
993
+ return this.config.auth?.mode === "app-token" ? createAppTokenAuthHandler(this.config.agentId, this.config.auth) : void 0;
994
+ }
995
+ setOnAuthRequired(onAuthRequired) {
996
+ this.config = {
997
+ ...this.config,
998
+ onAuthRequired: onAuthRequired ?? this.getDefaultAuthRequiredHandler()
999
+ };
1000
+ }
1001
+ isAudioInputSupported() {
1002
+ const audioContextCtor = this.getAudioContextConstructor();
1003
+ return typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getUserMedia) && typeof WebSocket !== "undefined" && Boolean(audioContextCtor) && typeof crypto !== "undefined";
1004
+ }
1005
+ isAudioInputEnabled() {
1006
+ const capabilities = this.agentConfig?.modelConfig?.capabilities;
1007
+ return Boolean(
1008
+ this.agentConfig?.audio?.inputEnabled && (capabilities?.audioInput ?? capabilities?.realtimeAudioInput)
1009
+ );
1010
+ }
1011
+ isAudioAutoSubmitEnabled() {
1012
+ const turnDetection = this.getAudioTurnDetectionConfig();
1013
+ return turnDetection.enabled && turnDetection.autoSubmit;
1014
+ }
1015
+ getAudioTurnDetectionConfig() {
1016
+ const override = this.config.audioInput?.turnDetection ?? {};
1017
+ return {
1018
+ enabled: override.enabled ?? DEFAULT_AUDIO_TURN_DETECTION.enabled,
1019
+ autoSubmit: override.autoSubmit ?? DEFAULT_AUDIO_TURN_DETECTION.autoSubmit,
1020
+ silenceDurationMs: this.clampNumber(
1021
+ override.silenceDurationMs,
1022
+ 250,
1023
+ 3e3,
1024
+ DEFAULT_AUDIO_TURN_DETECTION.silenceDurationMs
1025
+ ),
1026
+ minSpeechDurationMs: this.clampNumber(
1027
+ override.minSpeechDurationMs,
1028
+ 80,
1029
+ 1e3,
1030
+ DEFAULT_AUDIO_TURN_DETECTION.minSpeechDurationMs
1031
+ ),
1032
+ noSpeechTimeoutMs: this.clampNumber(
1033
+ override.noSpeechTimeoutMs,
1034
+ 0,
1035
+ 6e4,
1036
+ DEFAULT_AUDIO_TURN_DETECTION.noSpeechTimeoutMs
1037
+ ),
1038
+ speechThreshold: this.clampNumber(
1039
+ override.speechThreshold,
1040
+ 2e-3,
1041
+ 0.2,
1042
+ DEFAULT_AUDIO_TURN_DETECTION.speechThreshold
1043
+ ),
1044
+ noiseMultiplier: this.clampNumber(
1045
+ override.noiseMultiplier,
1046
+ 1.2,
1047
+ 8,
1048
+ DEFAULT_AUDIO_TURN_DETECTION.noiseMultiplier
1049
+ )
1050
+ };
1051
+ }
1052
+ clampNumber(value, min, max, fallback) {
1053
+ if (typeof value !== "number" || !Number.isFinite(value)) {
1054
+ return fallback;
1055
+ }
1056
+ return Math.min(max, Math.max(min, value));
1057
+ }
1058
+ buildAudioState(patch) {
1059
+ const hasPatch = (key) => Object.prototype.hasOwnProperty.call(patch, key);
1060
+ return {
1061
+ status: patch.status ?? this.audioState.status,
1062
+ isSupported: this.isAudioInputSupported(),
1063
+ isEnabled: this.isAudioInputEnabled(),
1064
+ transcript: patch.transcript ?? this.audioState.transcript,
1065
+ partialTranscript: patch.partialTranscript ?? this.audioState.partialTranscript,
1066
+ error: hasPatch("error") ? patch.error ?? null : this.audioState.error,
1067
+ sessionId: hasPatch("sessionId") ? patch.sessionId ?? null : this.audioState.sessionId ?? null,
1068
+ conversationId: hasPatch("conversationId") ? patch.conversationId ?? null : this.audioState.conversationId ?? this.conversationId,
1069
+ maxSessionSeconds: hasPatch("maxSessionSeconds") ? patch.maxSessionSeconds ?? null : this.audioState.maxSessionSeconds ?? this.agentConfig?.audio?.maxSessionSeconds ?? null,
1070
+ inputLevel: hasPatch("inputLevel") ? patch.inputLevel ?? 0 : this.audioState.inputLevel ?? 0,
1071
+ isSpeaking: hasPatch("isSpeaking") ? patch.isSpeaking ?? false : this.audioState.isSpeaking ?? false,
1072
+ speechMs: hasPatch("speechMs") ? patch.speechMs ?? 0 : this.audioState.speechMs ?? 0,
1073
+ silenceMs: hasPatch("silenceMs") ? patch.silenceMs ?? 0 : this.audioState.silenceMs ?? 0,
1074
+ autoSubmitEnabled: hasPatch("autoSubmitEnabled") ? patch.autoSubmitEnabled ?? false : this.audioState.autoSubmitEnabled ?? this.isAudioAutoSubmitEnabled()
1075
+ };
1076
+ }
1077
+ setAudioState(patch) {
1078
+ this.audioState = this.buildAudioState(patch);
1079
+ this.emit("audio_state", this.audioState);
1080
+ }
1081
+ getAudioContextConstructor() {
1082
+ if (typeof window === "undefined") {
1083
+ return null;
1084
+ }
1085
+ return window.AudioContext ?? window.webkitAudioContext ?? null;
1086
+ }
1087
+ async createRealtimeTranscriptionSession() {
1088
+ const token = await this.resolveAuthToken();
1089
+ const externalUser = this.buildExternalUserContext();
1090
+ const response = await fetch(
1091
+ `${this.config.agentServiceUrl}/api/v1/agents/${encodeURIComponent(this.config.agentId)}/realtime/transcription-sessions`,
1092
+ {
1093
+ method: "POST",
1094
+ headers: {
1095
+ "Content-Type": "application/json",
1096
+ Authorization: `Bearer ${token}`
1097
+ },
1098
+ body: JSON.stringify({
1099
+ conversationId: this.conversationId,
1100
+ externalUserId: this.resolveExternalUserId(),
1101
+ externalUser
1102
+ })
1103
+ }
1104
+ );
1105
+ if (!response.ok) {
1106
+ throw await this.buildApiError(response);
1107
+ }
1108
+ return await response.json();
1109
+ }
1110
+ async buildApiError(response) {
1111
+ let code = null;
1112
+ let message = null;
1113
+ try {
1114
+ const payload = await response.clone().json();
1115
+ if (payload && typeof payload === "object") {
1116
+ const record = payload;
1117
+ code = typeof record.code === "string" ? record.code : null;
1118
+ message = extractErrorMessage(payload);
1119
+ }
1120
+ } catch {
1121
+ }
1122
+ const error = new Error(message ?? await getResponseErrorMessage(response));
1123
+ if (code) {
1124
+ error.code = code;
1125
+ }
1126
+ return error;
1127
+ }
1128
+ async openAudioSocket(url) {
1129
+ return new Promise((resolve, reject) => {
1130
+ const socket = new WebSocket(this.normalizeAudioSocketUrl(url));
1131
+ const cleanup = () => {
1132
+ socket.removeEventListener("open", handleOpen);
1133
+ socket.removeEventListener("error", handleError);
1134
+ };
1135
+ const handleOpen = () => {
1136
+ cleanup();
1137
+ resolve(socket);
1138
+ };
1139
+ const handleError = () => {
1140
+ cleanup();
1141
+ reject(new Error("Could not connect to the realtime microphone service."));
1142
+ };
1143
+ socket.addEventListener("open", handleOpen);
1144
+ socket.addEventListener("error", handleError);
1145
+ });
1146
+ }
1147
+ normalizeAudioSocketUrl(url) {
1148
+ if (typeof window === "undefined") {
1149
+ return url;
1150
+ }
1151
+ try {
1152
+ const parsed = new URL(url, window.location.href);
1153
+ if (window.location.protocol === "https:" && parsed.protocol === "ws:") {
1154
+ parsed.protocol = "wss:";
1155
+ }
1156
+ return parsed.toString();
1157
+ } catch {
1158
+ return url;
1159
+ }
1160
+ }
1161
+ bindAudioSocket(socket) {
1162
+ socket.addEventListener("message", (event) => {
1163
+ void this.handleAudioSocketMessage(event);
1164
+ });
1165
+ socket.addEventListener("close", () => {
1166
+ if (this.audioSocket !== socket) {
1167
+ return;
1168
+ }
1169
+ this.audioSocket = null;
1170
+ this.clearAudioSessionTimer();
1171
+ if (this.audioState.status === "listening" || this.audioState.status === "transcribing" || this.audioState.status === "connecting") {
1172
+ this.cleanupAudioCapture(false);
1173
+ this.audioTurnState = null;
1174
+ this.setAudioState({
1175
+ status: "idle",
1176
+ inputLevel: 0,
1177
+ isSpeaking: false,
1178
+ speechMs: 0,
1179
+ silenceMs: 0
1180
+ });
1181
+ }
1182
+ });
1183
+ socket.addEventListener("error", () => {
1184
+ if (this.audioSocket !== socket) {
1185
+ return;
1186
+ }
1187
+ this.cleanupAudioCapture();
1188
+ this.audioTurnState = null;
1189
+ this.setAudioState({
1190
+ status: "error",
1191
+ error: {
1192
+ code: "audio_socket_error",
1193
+ message: "The realtime microphone connection failed."
1194
+ },
1195
+ inputLevel: 0,
1196
+ isSpeaking: false,
1197
+ speechMs: 0,
1198
+ silenceMs: 0
1199
+ });
1200
+ });
1201
+ }
1202
+ async handleAudioSocketMessage(event) {
1203
+ const raw = typeof event.data === "string" ? event.data : event.data instanceof Blob ? await event.data.text() : "";
1204
+ if (!raw) {
1205
+ return;
1206
+ }
1207
+ let payload;
1208
+ try {
1209
+ payload = JSON.parse(raw);
1210
+ } catch {
1211
+ return;
1212
+ }
1213
+ const type = typeof payload.type === "string" ? payload.type : "";
1214
+ if (type === "transcript_delta") {
1215
+ const text = typeof payload.text === "string" ? payload.text : "";
1216
+ if (!text) {
1217
+ return;
1218
+ }
1219
+ this.audioFinalTranscript += text;
1220
+ this.setAudioState({
1221
+ partialTranscript: this.audioFinalTranscript,
1222
+ transcript: this.audioFinalTranscript
1223
+ });
1224
+ this.emit("audio_transcript_delta", {
1225
+ text,
1226
+ transcript: this.audioFinalTranscript,
1227
+ isFinal: false
1228
+ });
1229
+ return;
1230
+ }
1231
+ if (type === "transcript_final") {
1232
+ const finalText = (typeof payload.text === "string" && payload.text.trim() ? payload.text : this.audioFinalTranscript).trim();
1233
+ this.cleanupAudioCapture();
1234
+ this.audioTurnState = null;
1235
+ if (!finalText) {
1236
+ this.setAudioState({
1237
+ status: "idle",
1238
+ transcript: "",
1239
+ partialTranscript: "",
1240
+ inputLevel: 0,
1241
+ isSpeaking: false,
1242
+ speechMs: 0,
1243
+ silenceMs: 0
1244
+ });
1245
+ return;
1246
+ }
1247
+ this.setAudioState({
1248
+ status: "sending",
1249
+ transcript: finalText,
1250
+ partialTranscript: "",
1251
+ error: null,
1252
+ inputLevel: 0,
1253
+ isSpeaking: false
1254
+ });
1255
+ this.emit("audio_transcript_final", {
1256
+ text: finalText,
1257
+ transcript: finalText,
1258
+ conversationId: this.conversationId ?? ""
1259
+ });
1260
+ await this.sendMessage(finalText);
1261
+ this.setAudioState({
1262
+ status: "idle",
1263
+ transcript: finalText,
1264
+ partialTranscript: "",
1265
+ sessionId: null,
1266
+ inputLevel: 0,
1267
+ isSpeaking: false,
1268
+ speechMs: 0,
1269
+ silenceMs: 0
1270
+ });
1271
+ return;
1272
+ }
1273
+ if (type === "error") {
1274
+ const code = typeof payload.code === "string" ? payload.code : "audio_error";
1275
+ const message = typeof payload.message === "string" ? payload.message : "Microphone input failed.";
1276
+ this.cleanupAudioCapture();
1277
+ this.audioTurnState = null;
1278
+ this.setAudioState({
1279
+ status: "error",
1280
+ error: { code, message },
1281
+ inputLevel: 0,
1282
+ isSpeaking: false,
1283
+ speechMs: 0,
1284
+ silenceMs: 0
1285
+ });
1286
+ }
1287
+ }
1288
+ async commitVoiceInput() {
1289
+ if (this.audioSessionStopRequested || this.audioState.status !== "listening" && this.audioState.status !== "connecting") {
1290
+ return;
1291
+ }
1292
+ this.audioSessionStopRequested = true;
1293
+ this.cleanupAudioCapture(false);
1294
+ if (this.audioSocket?.readyState === WebSocket.OPEN) {
1295
+ this.audioSocket.send(JSON.stringify({ type: "audio.commit" }));
1296
+ this.setAudioState({
1297
+ status: "transcribing",
1298
+ inputLevel: 0,
1299
+ isSpeaking: false,
1300
+ silenceMs: this.audioTurnState?.silenceMs ?? this.audioState.silenceMs ?? 0,
1301
+ speechMs: this.audioTurnState?.speechMs ?? this.audioState.speechMs ?? 0
1302
+ });
1303
+ return;
1304
+ }
1305
+ this.audioTurnState = null;
1306
+ this.setAudioState({
1307
+ status: "idle",
1308
+ inputLevel: 0,
1309
+ isSpeaking: false,
1310
+ speechMs: 0,
1311
+ silenceMs: 0
1312
+ });
1313
+ }
1314
+ stopVoiceInputWithoutTranscript(message) {
1315
+ this.audioSessionStopRequested = true;
1316
+ this.cleanupAudioCapture();
1317
+ this.audioTurnState = null;
1318
+ this.setAudioState({
1319
+ status: "idle",
1320
+ transcript: "",
1321
+ partialTranscript: "",
1322
+ sessionId: null,
1323
+ inputLevel: 0,
1324
+ isSpeaking: false,
1325
+ speechMs: 0,
1326
+ silenceMs: 0,
1327
+ error: {
1328
+ code: "no_speech_detected",
1329
+ message
1330
+ }
1331
+ });
1332
+ }
1333
+ createAudioTurnState(nowMs) {
1334
+ return {
1335
+ startedAtMs: nowMs,
1336
+ lastFrameAtMs: nowMs,
1337
+ speechStartedAtMs: null,
1338
+ lastSpeechAtMs: null,
1339
+ speechMs: 0,
1340
+ silenceMs: 0,
1341
+ noiseFloor: DEFAULT_AUDIO_TURN_DETECTION.speechThreshold / 2,
1342
+ isSpeaking: false,
1343
+ autoCommitted: false,
1344
+ lastActivityEmitMs: 0
1345
+ };
1346
+ }
1347
+ analyzeAudioFrame(input, durationMs) {
1348
+ if (input.length === 0) {
1349
+ return { rms: 0, peak: 0, inputLevel: 0, durationMs };
1350
+ }
1351
+ let sumSquares = 0;
1352
+ let peak = 0;
1353
+ for (let index = 0; index < input.length; index += 1) {
1354
+ const sample = input[index];
1355
+ const abs = Math.abs(sample);
1356
+ sumSquares += sample * sample;
1357
+ if (abs > peak) {
1358
+ peak = abs;
1359
+ }
1360
+ }
1361
+ const rms = Math.sqrt(sumSquares / input.length);
1362
+ return {
1363
+ rms,
1364
+ peak,
1365
+ inputLevel: Math.min(1, rms * 14),
1366
+ durationMs
1367
+ };
1368
+ }
1369
+ processAudioTurnActivity(activity, nowMs) {
1370
+ const config = this.getAudioTurnDetectionConfig();
1371
+ if (!config.enabled) {
1372
+ this.emitAudioActivity(activity, nowMs, false, 0, 0, DEFAULT_AUDIO_TURN_DETECTION.speechThreshold / 2);
1373
+ return;
1374
+ }
1375
+ const state = this.audioTurnState ?? this.createAudioTurnState(nowMs);
1376
+ this.audioTurnState = state;
1377
+ const frameGapMs = Math.max(1, nowMs - state.lastFrameAtMs);
1378
+ const frameDurationMs = Math.max(activity.durationMs, frameGapMs);
1379
+ state.lastFrameAtMs = nowMs;
1380
+ const adaptiveThreshold = Math.max(
1381
+ config.speechThreshold,
1382
+ Math.min(0.08, state.noiseFloor * config.noiseMultiplier)
1383
+ );
1384
+ const peakThreshold = Math.max(adaptiveThreshold * 2.2, config.speechThreshold * 2.5);
1385
+ const speechCandidate = activity.rms >= adaptiveThreshold || activity.rms >= adaptiveThreshold * 0.72 && activity.peak >= peakThreshold;
1386
+ if (speechCandidate) {
1387
+ if (state.speechStartedAtMs === null) {
1388
+ state.speechStartedAtMs = nowMs;
1389
+ state.speechMs = 0;
1390
+ }
1391
+ state.lastSpeechAtMs = nowMs;
1392
+ state.speechMs += frameDurationMs;
1393
+ state.silenceMs = 0;
1394
+ state.isSpeaking = true;
1395
+ } else {
1396
+ state.noiseFloor = this.updateNoiseFloor(state.noiseFloor, activity.rms);
1397
+ state.isSpeaking = false;
1398
+ if (state.lastSpeechAtMs !== null) {
1399
+ state.silenceMs = nowMs - state.lastSpeechAtMs;
1400
+ }
1401
+ }
1402
+ if (state.speechStartedAtMs !== null && state.speechMs < config.minSpeechDurationMs && state.silenceMs >= config.silenceDurationMs) {
1403
+ state.speechStartedAtMs = null;
1404
+ state.lastSpeechAtMs = null;
1405
+ state.speechMs = 0;
1406
+ state.silenceMs = 0;
1407
+ }
1408
+ this.emitAudioActivity(
1409
+ activity,
1410
+ nowMs,
1411
+ state.isSpeaking,
1412
+ state.speechMs,
1413
+ state.silenceMs,
1414
+ state.noiseFloor
1415
+ );
1416
+ const noSpeechElapsedMs = nowMs - state.startedAtMs;
1417
+ if (config.noSpeechTimeoutMs > 0 && state.speechStartedAtMs === null && noSpeechElapsedMs >= config.noSpeechTimeoutMs && !state.autoCommitted) {
1418
+ state.autoCommitted = true;
1419
+ this.stopVoiceInputWithoutTranscript("No speech was detected. Try again when you are ready to speak.");
1420
+ return;
1421
+ }
1422
+ if (config.autoSubmit && state.speechStartedAtMs !== null && state.speechMs >= config.minSpeechDurationMs && state.silenceMs >= config.silenceDurationMs && !state.autoCommitted) {
1423
+ state.autoCommitted = true;
1424
+ void this.commitVoiceInput();
1425
+ }
1426
+ }
1427
+ updateNoiseFloor(currentNoiseFloor, rms) {
1428
+ const sample = Math.max(15e-4, Math.min(0.08, rms));
1429
+ const smoothing = sample > currentNoiseFloor ? 0.02 : 0.12;
1430
+ return currentNoiseFloor * (1 - smoothing) + sample * smoothing;
1431
+ }
1432
+ emitAudioActivity(activity, nowMs, isSpeaking, speechMs, silenceMs, noiseFloor) {
1433
+ const state = this.audioTurnState;
1434
+ 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;
1435
+ if (!shouldEmitState) {
1436
+ return;
1437
+ }
1438
+ if (state) {
1439
+ state.lastActivityEmitMs = nowMs;
1440
+ }
1441
+ const roundedLevel = Number(activity.inputLevel.toFixed(3));
1442
+ const roundedNoiseFloor = Number(noiseFloor.toFixed(5));
1443
+ this.setAudioState({
1444
+ inputLevel: roundedLevel,
1445
+ isSpeaking,
1446
+ speechMs: Math.round(speechMs),
1447
+ silenceMs: Math.round(silenceMs),
1448
+ autoSubmitEnabled: this.isAudioAutoSubmitEnabled()
1449
+ });
1450
+ this.emit("audio_activity", {
1451
+ inputLevel: roundedLevel,
1452
+ noiseFloor: roundedNoiseFloor,
1453
+ isSpeaking,
1454
+ speechMs: Math.round(speechMs),
1455
+ silenceMs: Math.round(silenceMs)
1456
+ });
1457
+ }
1458
+ async startAudioCapture(stream, socket) {
1459
+ const AudioContextCtor = this.getAudioContextConstructor();
1460
+ if (!AudioContextCtor) {
1461
+ throw new Error("Audio capture is not available in this browser.");
1462
+ }
1463
+ const context = new AudioContextCtor();
1464
+ if (context.state === "suspended") {
1465
+ await context.resume();
1466
+ }
1467
+ const source = context.createMediaStreamSource(stream);
1468
+ const processor = context.createScriptProcessor(4096, 1, 1);
1469
+ const silentGain = context.createGain();
1470
+ silentGain.gain.value = 0;
1471
+ this.audioTurnState = this.createAudioTurnState(performance.now());
1472
+ processor.onaudioprocess = (event) => {
1473
+ if (this.audioSessionStopRequested || socket.readyState !== WebSocket.OPEN || this.audioState.status !== "listening") {
1474
+ return;
1475
+ }
1476
+ const input = event.inputBuffer.getChannelData(0);
1477
+ const durationMs = input.length / context.sampleRate * 1e3;
1478
+ this.processAudioTurnActivity(
1479
+ this.analyzeAudioFrame(input, durationMs),
1480
+ performance.now()
1481
+ );
1482
+ if (this.audioSessionStopRequested) {
1483
+ return;
1484
+ }
1485
+ const resampled = this.resampleToPcm16(input, context.sampleRate, 24e3);
1486
+ if (resampled.length === 0) {
1487
+ return;
1488
+ }
1489
+ socket.send(JSON.stringify({
1490
+ type: "audio.append",
1491
+ audio: this.pcm16ToBase64(resampled)
1492
+ }));
1493
+ };
1494
+ source.connect(processor);
1495
+ processor.connect(silentGain);
1496
+ silentGain.connect(context.destination);
1497
+ this.audioContext = context;
1498
+ this.audioSource = source;
1499
+ this.audioProcessor = processor;
1500
+ this.audioSilentGain = silentGain;
1501
+ }
1502
+ resampleToPcm16(input, inputSampleRate, outputSampleRate) {
1503
+ if (inputSampleRate === outputSampleRate) {
1504
+ return this.floatToPcm16(input);
1505
+ }
1506
+ const ratio = inputSampleRate / outputSampleRate;
1507
+ const outputLength = Math.floor(input.length / ratio);
1508
+ const output = new Float32Array(outputLength);
1509
+ for (let index = 0; index < outputLength; index += 1) {
1510
+ const inputIndex = index * ratio;
1511
+ const lower = Math.floor(inputIndex);
1512
+ const upper = Math.min(lower + 1, input.length - 1);
1513
+ const weight = inputIndex - lower;
1514
+ output[index] = input[lower] * (1 - weight) + input[upper] * weight;
1515
+ }
1516
+ return this.floatToPcm16(output);
1517
+ }
1518
+ floatToPcm16(input) {
1519
+ const output = new Int16Array(input.length);
1520
+ for (let index = 0; index < input.length; index += 1) {
1521
+ const sample = Math.max(-1, Math.min(1, input[index]));
1522
+ output[index] = sample < 0 ? sample * 32768 : sample * 32767;
1523
+ }
1524
+ return output;
1525
+ }
1526
+ pcm16ToBase64(input) {
1527
+ const bytes = new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
1528
+ let binary = "";
1529
+ const chunkSize = 32768;
1530
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) {
1531
+ const chunk = bytes.subarray(offset, offset + chunkSize);
1532
+ binary += String.fromCharCode(...chunk);
1533
+ }
1534
+ return btoa(binary);
1535
+ }
1536
+ cleanupAudioCapture(closeSocket = true) {
1537
+ this.clearAudioSessionTimer();
1538
+ this.audioProcessor?.disconnect();
1539
+ this.audioSource?.disconnect();
1540
+ this.audioSilentGain?.disconnect();
1541
+ this.audioProcessor = null;
1542
+ this.audioSource = null;
1543
+ this.audioSilentGain = null;
1544
+ if (this.audioContext) {
1545
+ void this.audioContext.close().catch(() => void 0);
1546
+ this.audioContext = null;
1547
+ }
1548
+ this.audioStream?.getTracks().forEach((track) => track.stop());
1549
+ this.audioStream = null;
1550
+ if (closeSocket && this.audioSocket) {
1551
+ const socket = this.audioSocket;
1552
+ this.audioSocket = null;
1553
+ if (socket.readyState === WebSocket.OPEN) {
1554
+ socket.send(JSON.stringify({ type: "audio.close" }));
1555
+ socket.close();
1556
+ } else if (socket.readyState === WebSocket.CONNECTING) {
1557
+ socket.close();
1558
+ }
1559
+ }
1560
+ }
1561
+ clearAudioSessionTimer() {
1562
+ if (!this.audioSessionTimer) {
1563
+ return;
1564
+ }
1565
+ clearTimeout(this.audioSessionTimer);
1566
+ this.audioSessionTimer = null;
1567
+ }
1568
+ extractErrorCode(error) {
1569
+ if (error && typeof error === "object" && "code" in error) {
1570
+ const code = error.code;
1571
+ return typeof code === "string" ? code : null;
1572
+ }
1573
+ return null;
1574
+ }
1575
+ getPersistentStorage() {
1576
+ return this.config.storage ?? null;
1577
+ }
1578
+ async resolveOAuthClientRegistration(authConfig) {
1579
+ if (!authConfig || authConfig.authType !== "oauth2") {
1580
+ return authConfig ?? null;
1581
+ }
1582
+ const registration = await resolveOAuthRegistration(authConfig, {
1583
+ callbackUrl: this.getOAuthCallbackUrl(),
1584
+ oauthClientMetadataUrl: this.config.oauthClientMetadataUrl,
1585
+ clientName: "MCP Stack MCP Client",
1586
+ clientUri: "https://mcpstack.com",
1587
+ storage: this.getPersistentStorage()
1588
+ });
1589
+ return applyResolvedRegistration(authConfig, registration);
1590
+ }
1591
+ /** Subscribe to events */
1592
+ on(event, handler) {
1593
+ if (!this.listeners.has(event)) {
1594
+ this.listeners.set(event, /* @__PURE__ */ new Set());
1595
+ }
1596
+ this.listeners.get(event).add(handler);
1597
+ }
1598
+ /** Unsubscribe from events */
1599
+ off(event, handler) {
1600
+ this.listeners.get(event)?.delete(handler);
1601
+ }
1602
+ // ================================================================
1603
+ // Private methods
1604
+ // ================================================================
1605
+ buildProtectedResourceMetadataCandidates(mcpServerUrl) {
1606
+ const url = new URL(mcpServerUrl);
1607
+ const candidates = /* @__PURE__ */ new Set();
1608
+ const normalizedPath = url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname;
1609
+ if (!normalizedPath || normalizedPath === "/") {
1610
+ candidates.add(`${url.origin}/.well-known/oauth-protected-resource`);
1611
+ return [...candidates];
1612
+ }
1613
+ candidates.add(`${url.origin}/.well-known/oauth-protected-resource${normalizedPath}`);
1614
+ candidates.add(`${url.origin}${normalizedPath}/.well-known/oauth-protected-resource`);
1615
+ candidates.add(`${url.origin}/.well-known/oauth-protected-resource`);
1616
+ return [...candidates];
1617
+ }
1618
+ hasSameOrigin(left, right) {
1619
+ try {
1620
+ const leftUrl = new URL(left);
1621
+ const rightUrl = new URL(right);
1622
+ return leftUrl.origin === rightUrl.origin;
1623
+ } catch {
1624
+ return false;
1625
+ }
1626
+ }
1627
+ extractQuotedHeaderValue(header, key) {
1628
+ const match = header.match(new RegExp(`${key}="([^"]+)"`, "i"));
1629
+ return match?.[1] ?? null;
1630
+ }
1631
+ buildAuthorizationServerMetadataCandidates(issuerOrMetadataUrl) {
1632
+ const candidates = /* @__PURE__ */ new Set();
1633
+ if (issuerOrMetadataUrl.includes("/.well-known/oauth-authorization-server") || issuerOrMetadataUrl.includes("/.well-known/openid-configuration")) {
1634
+ candidates.add(issuerOrMetadataUrl);
1635
+ return [...candidates];
1636
+ }
1637
+ const url = new URL(issuerOrMetadataUrl);
1638
+ const normalizedPath = url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname;
1639
+ if (!normalizedPath || normalizedPath === "/") {
1640
+ candidates.add(`${url.origin}/.well-known/oauth-authorization-server`);
1641
+ candidates.add(`${url.origin}/.well-known/openid-configuration`);
1642
+ return [...candidates];
1643
+ }
1644
+ candidates.add(`${url.origin}/.well-known/oauth-authorization-server${normalizedPath}`);
1645
+ candidates.add(`${url.origin}/.well-known/openid-configuration${normalizedPath}`);
1646
+ candidates.add(`${url.origin}${normalizedPath}/.well-known/openid-configuration`);
1647
+ return [...candidates];
1648
+ }
1649
+ hasExplicitManualOverride(manualConfig, field) {
1650
+ return manualConfig?.manualOverrides?.includes(field) ?? false;
1651
+ }
1652
+ pickAuthConfigValue(field, manualConfig, manualValue, discoveredValue) {
1653
+ if (this.hasExplicitManualOverride(manualConfig, field) && manualValue != null) {
1654
+ return manualValue;
1655
+ }
1656
+ return discoveredValue ?? manualValue;
1657
+ }
1658
+ pickAuthConfigArrayValue(field, manualConfig, manualValue, discoveredValue) {
1659
+ if (this.hasExplicitManualOverride(manualConfig, field) && manualValue?.length) {
1660
+ return manualValue;
1661
+ }
1662
+ if (discoveredValue?.length) {
1663
+ return discoveredValue;
1664
+ }
1665
+ return manualValue?.length ? manualValue : void 0;
1666
+ }
1667
+ mergeAuthConfigs(manualConfig, discoveredConfig) {
1668
+ if (!manualConfig && !discoveredConfig) return null;
1669
+ const manualOverrides = new Set(manualConfig?.manualOverrides ?? []);
1670
+ const authorizationEndpoint = this.pickAuthConfigValue(
1671
+ "authorizationEndpoint",
1672
+ manualConfig,
1673
+ manualConfig?.authorizationEndpoint ?? manualConfig?.loginUrl,
1674
+ discoveredConfig?.authorizationEndpoint ?? discoveredConfig?.loginUrl
1675
+ );
1676
+ const tokenEndpoint = this.pickAuthConfigValue(
1677
+ "tokenEndpoint",
1678
+ manualConfig,
1679
+ manualConfig?.tokenEndpoint ?? manualConfig?.tokenUrl,
1680
+ discoveredConfig?.tokenEndpoint ?? discoveredConfig?.tokenUrl
1681
+ );
1682
+ const callbackUrl = this.pickAuthConfigValue(
1683
+ "callbackUrl",
1684
+ manualConfig,
1685
+ manualConfig?.callbackUrl,
1686
+ discoveredConfig?.callbackUrl
1687
+ ) ?? this.getOAuthCallbackUrl();
1688
+ const merged = {
1689
+ authType: manualConfig?.authType ?? discoveredConfig?.authType ?? "oauth2",
1690
+ issuer: discoveredConfig?.issuer ?? manualConfig?.issuer,
1691
+ authorizationServerUrl: this.pickAuthConfigValue(
1692
+ "authorizationServerUrl",
1693
+ manualConfig,
1694
+ manualConfig?.authorizationServerUrl,
1695
+ discoveredConfig?.authorizationServerUrl
1696
+ ),
1697
+ authorizationServerMetadataUrl: this.pickAuthConfigValue(
1698
+ "authorizationServerMetadataUrl",
1699
+ manualConfig,
1700
+ manualConfig?.authorizationServerMetadataUrl,
1701
+ discoveredConfig?.authorizationServerMetadataUrl
1702
+ ),
1703
+ authorizationEndpoint,
1704
+ loginUrl: authorizationEndpoint,
1705
+ tokenEndpoint,
1706
+ tokenUrl: tokenEndpoint,
1707
+ registrationEndpoint: this.pickAuthConfigValue(
1708
+ "registrationEndpoint",
1709
+ manualConfig,
1710
+ manualConfig?.registrationEndpoint,
1711
+ discoveredConfig?.registrationEndpoint
1712
+ ),
1713
+ clientId: this.pickAuthConfigValue(
1714
+ "clientId",
1715
+ manualConfig,
1716
+ manualConfig?.clientId,
1717
+ discoveredConfig?.clientId
1718
+ ),
1719
+ scopes: this.pickAuthConfigArrayValue(
1720
+ "scopes",
1721
+ manualConfig,
1722
+ manualConfig?.scopes,
1723
+ discoveredConfig?.scopes
1724
+ ),
1725
+ resource: this.pickAuthConfigValue(
1726
+ "resource",
1727
+ manualConfig,
1728
+ manualConfig?.resource,
1729
+ discoveredConfig?.resource
1730
+ ),
1731
+ callbackUrl,
1732
+ protectedResourceMetadataUrl: discoveredConfig?.protectedResourceMetadataUrl ?? manualConfig?.protectedResourceMetadataUrl,
1733
+ clientIdMetadataDocumentSupported: discoveredConfig?.clientIdMetadataDocumentSupported ?? manualConfig?.clientIdMetadataDocumentSupported,
1734
+ resourceParameterSupported: discoveredConfig?.resourceParameterSupported ?? manualConfig?.resourceParameterSupported,
1735
+ registrationPreference: manualConfig?.registrationPreference ?? discoveredConfig?.registrationPreference ?? "auto",
1736
+ clientMode: discoveredConfig?.clientMode ?? manualConfig?.clientMode,
1737
+ authRecipe: manualConfig?.authRecipe ?? discoveredConfig?.authRecipe,
1738
+ manualOverrides: manualOverrides.size ? [...manualOverrides] : void 0,
1739
+ discovered: discoveredConfig?.discovered ?? false
1740
+ };
1741
+ return merged;
1742
+ }
1743
+ async discoverAuthConfig(mcpServerUrl, manualConfig) {
1744
+ let protectedResourceUrl = null;
1745
+ let protectedResource = null;
1746
+ const protectedResourceCandidates = /* @__PURE__ */ new Set();
1747
+ if (manualConfig?.protectedResourceMetadataUrl) {
1748
+ protectedResourceCandidates.add(manualConfig.protectedResourceMetadataUrl);
1749
+ }
1750
+ for (const candidate of this.buildProtectedResourceMetadataCandidates(mcpServerUrl)) {
1751
+ protectedResourceCandidates.add(candidate);
1752
+ }
1753
+ for (const candidate of protectedResourceCandidates) {
1754
+ try {
1755
+ const response = await fetch(candidate, {
1756
+ method: "GET",
1757
+ headers: { Accept: "application/json" }
1758
+ });
1759
+ if (response.ok) {
1760
+ protectedResource = await response.json();
1761
+ protectedResourceUrl = candidate;
1762
+ break;
1763
+ }
1764
+ const authenticateHeader = response.headers.get("www-authenticate");
1765
+ if (authenticateHeader) {
1766
+ const resourceMetadataUrl = this.extractQuotedHeaderValue(authenticateHeader, "resource_metadata");
1767
+ if (resourceMetadataUrl && this.hasSameOrigin(candidate, resourceMetadataUrl)) {
1768
+ const metadataResponse = await fetch(resourceMetadataUrl, {
1769
+ method: "GET",
1770
+ headers: { Accept: "application/json" }
1771
+ });
1772
+ if (metadataResponse.ok) {
1773
+ protectedResource = await metadataResponse.json();
1774
+ protectedResourceUrl = resourceMetadataUrl;
1775
+ break;
1776
+ }
1777
+ }
1778
+ }
1779
+ } catch {
1780
+ }
1781
+ }
1782
+ const authServerUrl = protectedResource?.authorization_servers?.[0] ?? protectedResource?.authorization_server ?? manualConfig?.authorizationServerUrl;
1783
+ try {
1784
+ let metadata = null;
1785
+ let metadataUrl = manualConfig?.authorizationServerMetadataUrl ?? null;
1786
+ const metadataCandidates = /* @__PURE__ */ new Set();
1787
+ if (manualConfig?.authorizationServerMetadataUrl) {
1788
+ metadataCandidates.add(manualConfig.authorizationServerMetadataUrl);
1789
+ }
1790
+ if (authServerUrl) {
1791
+ for (const candidate of this.buildAuthorizationServerMetadataCandidates(authServerUrl)) {
1792
+ metadataCandidates.add(candidate);
1793
+ }
1794
+ }
1795
+ for (const candidate of metadataCandidates) {
1796
+ try {
1797
+ const response = await fetch(candidate, {
1798
+ method: "GET",
1799
+ headers: { Accept: "application/json" }
1800
+ });
1801
+ if (response.ok) {
1802
+ metadata = await response.json();
1803
+ metadataUrl = candidate;
1804
+ break;
1805
+ }
1806
+ } catch {
1807
+ }
1808
+ }
1809
+ if (!metadata && !protectedResource && !manualConfig) {
1810
+ return null;
1811
+ }
1812
+ return {
1813
+ authType: "oauth2",
1814
+ issuer: metadata?.issuer ?? authServerUrl ?? manualConfig?.issuer,
1815
+ authorizationServerUrl: authServerUrl ?? manualConfig?.authorizationServerUrl,
1816
+ authorizationServerMetadataUrl: metadataUrl ?? void 0,
1817
+ authorizationEndpoint: metadata?.authorization_endpoint ?? manualConfig?.authorizationEndpoint ?? manualConfig?.loginUrl,
1818
+ loginUrl: metadata?.authorization_endpoint ?? manualConfig?.loginUrl ?? manualConfig?.authorizationEndpoint,
1819
+ tokenEndpoint: metadata?.token_endpoint ?? manualConfig?.tokenEndpoint ?? manualConfig?.tokenUrl,
1820
+ tokenUrl: metadata?.token_endpoint ?? manualConfig?.tokenUrl ?? manualConfig?.tokenEndpoint,
1821
+ registrationEndpoint: metadata?.registration_endpoint ?? manualConfig?.registrationEndpoint,
1822
+ clientId: manualConfig?.clientId,
1823
+ scopes: protectedResource?.scopes_supported?.length ? protectedResource.scopes_supported : metadata?.scopes_supported ?? manualConfig?.scopes,
1824
+ resource: protectedResource?.resource ?? manualConfig?.resource,
1825
+ callbackUrl: getEffectiveCallbackUrl(manualConfig, this.getOAuthCallbackUrl()),
1826
+ protectedResourceMetadataUrl: protectedResourceUrl ?? manualConfig?.protectedResourceMetadataUrl,
1827
+ clientIdMetadataDocumentSupported: metadata?.client_id_metadata_document_supported ?? manualConfig?.clientIdMetadataDocumentSupported,
1828
+ resourceParameterSupported: metadata?.resource_parameter_supported ?? manualConfig?.resourceParameterSupported,
1829
+ registrationPreference: manualConfig?.registrationPreference ?? "auto",
1830
+ authRecipe: manualConfig?.authRecipe,
1831
+ discovered: Boolean(protectedResource || metadata)
1832
+ };
1833
+ } catch {
1834
+ return manualConfig ? {
1835
+ ...manualConfig,
1836
+ callbackUrl: getEffectiveCallbackUrl(manualConfig, this.getOAuthCallbackUrl()),
1837
+ protectedResourceMetadataUrl: protectedResourceUrl ?? manualConfig.protectedResourceMetadataUrl,
1838
+ resource: protectedResource?.resource ?? manualConfig.resource,
1839
+ scopes: protectedResource?.scopes_supported?.length ? protectedResource.scopes_supported : manualConfig.scopes,
1840
+ discovered: Boolean(protectedResource)
1841
+ } : null;
1842
+ }
1843
+ }
1844
+ async resolveServerAuthConfig(mcpServerUrl, manualConfig) {
1845
+ const discoveredConfig = await this.discoverAuthConfig(mcpServerUrl, manualConfig);
1846
+ return this.mergeAuthConfigs(manualConfig, discoveredConfig);
1847
+ }
1848
+ async ensureServerAuthConfig(mcpServerUrl) {
1849
+ const server = this.agentConfig?.mcpServers?.find((item) => item.url === mcpServerUrl);
1850
+ if (!server) {
1851
+ return null;
1852
+ }
1853
+ 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)) {
1854
+ return server.authConfig;
1855
+ }
1856
+ server.authConfig = await this.resolveServerAuthConfig(mcpServerUrl, server.authConfig ?? null);
1857
+ return server.authConfig;
1858
+ }
1859
+ updateServerAuthConfig(mcpServerUrl, authConfig) {
1860
+ const server = this.agentConfig?.mcpServers?.find((item) => item.url === mcpServerUrl);
1861
+ if (server) {
1862
+ server.authConfig = authConfig;
1863
+ }
1864
+ }
1865
+ emit(event, data) {
1866
+ this.listeners.get(event)?.forEach((handler) => handler(data));
1867
+ }
1868
+ // ================================================================
1869
+ // OAuth Token Storage (standalone mode only)
1870
+ // ================================================================
1871
+ /** Generate the legacy token cache suffix used before auth-aware keying. */
1872
+ hashUrl(url) {
1873
+ return btoa(url).replace(/[^a-zA-Z0-9]/g, "").slice(0, 32);
1874
+ }
1875
+ getLegacyTokenStorageKey(mcpServerUrl) {
1876
+ return buildScopedOAuthTokenStorageKey(this.hashUrl(mcpServerUrl));
1877
+ }
1878
+ getAuthSessionKey() {
1879
+ return resolveExplicitAuthSessionKey(this.config);
1880
+ }
1881
+ getTokenStorageKey(mcpServerUrl, authConfig) {
1882
+ return buildScopedOAuthTokenStorageKey(
1883
+ buildTokenCacheKey(authConfig, mcpServerUrl),
1884
+ this.getAuthSessionKey()
1885
+ );
1886
+ }
1887
+ getTokenStorageCandidates(mcpServerUrl) {
1888
+ const currentAuthConfig = this.getServerAuthConfig(mcpServerUrl);
1889
+ const hasExplicitAuthSessionKey = this.getAuthSessionKey() !== null;
1890
+ if (!currentAuthConfig) {
1891
+ return hasExplicitAuthSessionKey ? [{
1892
+ storageKey: this.getTokenStorageKey(mcpServerUrl, null),
1893
+ authConfig: null
1894
+ }] : [{
1895
+ storageKey: this.getLegacyTokenStorageKey(mcpServerUrl),
1896
+ authConfig: null
1897
+ }];
1898
+ }
1899
+ const callbackUrl = getEffectiveCallbackUrl(currentAuthConfig, this.getOAuthCallbackUrl());
1900
+ const candidates = [currentAuthConfig];
1901
+ if (currentAuthConfig.authType === "oauth2") {
1902
+ candidates.push({
1903
+ ...currentAuthConfig,
1904
+ clientMode: "manual",
1905
+ callbackUrl
1906
+ });
1907
+ if (currentAuthConfig.clientId) {
1908
+ candidates.push({
1909
+ ...currentAuthConfig,
1910
+ clientMode: "preregistered",
1911
+ callbackUrl
1912
+ });
1913
+ }
1914
+ if (currentAuthConfig.clientIdMetadataDocumentSupported && this.config.oauthClientMetadataUrl) {
1915
+ candidates.push({
1916
+ ...currentAuthConfig,
1917
+ clientId: this.config.oauthClientMetadataUrl,
1918
+ clientMode: "cimd",
1919
+ callbackUrl
1920
+ });
1921
+ }
1922
+ if (currentAuthConfig.registrationEndpoint) {
1923
+ const cacheKey = buildRegistrationCacheKey(currentAuthConfig, callbackUrl, "dcr");
1924
+ const storedRegistration = loadStoredRegistration(cacheKey, this.getPersistentStorage());
1925
+ if (storedRegistration?.clientId) {
1926
+ candidates.push(applyResolvedRegistration(currentAuthConfig, {
1927
+ cacheKey,
1928
+ mode: "dcr",
1929
+ clientId: storedRegistration.clientId,
1930
+ callbackUrl,
1931
+ resource: currentAuthConfig.resource,
1932
+ authorizationServerUrl: currentAuthConfig.authorizationServerUrl,
1933
+ authorizationServerMetadataUrl: currentAuthConfig.authorizationServerMetadataUrl,
1934
+ registrationEndpoint: currentAuthConfig.registrationEndpoint
1935
+ }));
1936
+ }
1937
+ }
1938
+ }
1939
+ const seen = /* @__PURE__ */ new Set();
1940
+ const resolved = candidates.map((candidate) => ({
1941
+ storageKey: this.getTokenStorageKey(mcpServerUrl, candidate),
1942
+ authConfig: candidate
1943
+ })).filter((candidate) => {
1944
+ if (seen.has(candidate.storageKey)) return false;
1945
+ seen.add(candidate.storageKey);
1946
+ return true;
1947
+ });
1948
+ if (!hasExplicitAuthSessionKey) {
1949
+ resolved.push({
1950
+ storageKey: this.getLegacyTokenStorageKey(mcpServerUrl),
1951
+ authConfig: currentAuthConfig
1952
+ });
1953
+ }
1954
+ return resolved;
1955
+ }
1956
+ /** Load OAuth token from memory/persistent storage using auth-aware cache keying. */
1957
+ loadOAuthToken(mcpServerUrl) {
1958
+ for (const candidate of this.getTokenStorageCandidates(mcpServerUrl)) {
1959
+ const cached = this.oauthTokens.get(candidate.storageKey);
1960
+ if (cached) {
1961
+ if (candidate.authConfig) {
1962
+ this.updateServerAuthConfig(mcpServerUrl, candidate.authConfig);
1963
+ }
1964
+ return cached;
1965
+ }
1966
+ }
1967
+ try {
1968
+ const storage = this.getPersistentStorage() ?? (typeof localStorage !== "undefined" ? localStorage : null);
1969
+ if (storage) {
1970
+ for (const candidate of this.getTokenStorageCandidates(mcpServerUrl)) {
1971
+ const stored = storage.getItem(candidate.storageKey);
1972
+ if (stored) {
1973
+ const data = JSON.parse(stored);
1974
+ if (data.accessToken && data.expiresAt) {
1975
+ this.oauthTokens.set(candidate.storageKey, data);
1976
+ if (candidate.authConfig) {
1977
+ this.updateServerAuthConfig(mcpServerUrl, candidate.authConfig);
1978
+ }
1979
+ return data;
1980
+ }
1981
+ }
1982
+ }
1983
+ }
1984
+ } catch {
1985
+ }
1986
+ return null;
1987
+ }
1988
+ /** Check if we have a valid (non-expired) OAuth token */
1989
+ hasValidOAuthToken(mcpServerUrl) {
1990
+ const token = this.loadOAuthToken(mcpServerUrl);
1991
+ if (!token) return false;
1992
+ return token.expiresAt > Date.now() || !!token.refreshToken;
1993
+ }
1994
+ /** Store OAuth token to memory and persistent storage */
1995
+ storeOAuthToken(mcpServerUrl, tokenResponse) {
1996
+ const resolvedAuthConfig = tokenResponse.resolvedAuthConfig ?? this.getServerAuthConfig(mcpServerUrl);
1997
+ const storageKey = this.getTokenStorageKey(mcpServerUrl, resolvedAuthConfig);
1998
+ const expiresIn = tokenResponse.expiresIn ?? 3600;
1999
+ const expiresAt = Date.now() + expiresIn * 1e3 - 60 * 1e3;
2000
+ const data = {
2001
+ accessToken: tokenResponse.accessToken,
2002
+ refreshToken: tokenResponse.refreshToken,
2003
+ expiresAt
2004
+ };
2005
+ this.oauthTokens.set(storageKey, data);
2006
+ try {
2007
+ const storage = this.getPersistentStorage() ?? (typeof localStorage !== "undefined" ? localStorage : null);
2008
+ if (storage) {
2009
+ storage.setItem(storageKey, JSON.stringify(data));
2010
+ }
2011
+ } catch {
2012
+ }
2013
+ }
2014
+ /** Clear OAuth token from memory and persistent storage */
2015
+ clearOAuthToken(mcpServerUrl) {
2016
+ for (const candidate of this.getTokenStorageCandidates(mcpServerUrl)) {
2017
+ this.oauthTokens.delete(candidate.storageKey);
2018
+ }
2019
+ try {
2020
+ const storage = this.getPersistentStorage() ?? (typeof localStorage !== "undefined" ? localStorage : null);
2021
+ if (storage) {
2022
+ for (const candidate of this.getTokenStorageCandidates(mcpServerUrl)) {
2023
+ storage.removeItem(candidate.storageKey);
2024
+ }
2025
+ }
2026
+ } catch {
2027
+ }
2028
+ }
2029
+ /** Refresh OAuth token using refresh token */
2030
+ async refreshOAuthToken(mcpServerUrl, refreshToken) {
2031
+ const authConfig = await this.ensureServerAuthConfig(mcpServerUrl);
2032
+ const tokenUrl = authConfig?.tokenEndpoint ?? authConfig?.tokenUrl;
2033
+ if (!tokenUrl) return void 0;
2034
+ try {
2035
+ const body = new URLSearchParams({
2036
+ grant_type: "refresh_token",
2037
+ refresh_token: refreshToken
2038
+ });
2039
+ if (authConfig?.clientId) body.set("client_id", authConfig.clientId);
2040
+ if (authConfig?.resource) body.set("resource", authConfig.resource);
2041
+ const response = await fetch(tokenUrl, {
2042
+ method: "POST",
2043
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
2044
+ body
2045
+ });
2046
+ if (response.ok) {
2047
+ const data = await response.json();
2048
+ if (data.access_token) {
2049
+ const tokenResponse = {
2050
+ accessToken: data.access_token,
2051
+ refreshToken: data.refresh_token ?? refreshToken,
2052
+ expiresIn: data.expires_in,
2053
+ resolvedAuthConfig: authConfig ?? void 0
2054
+ };
2055
+ this.storeOAuthToken(mcpServerUrl, tokenResponse);
2056
+ return data.access_token;
2057
+ }
2058
+ }
2059
+ } catch {
2060
+ }
2061
+ return void 0;
2062
+ }
2063
+ // ================================================================
2064
+ // Token Resolution
2065
+ // ================================================================
2066
+ /**
2067
+ * Resolve the auth token for an MCP server.
2068
+ * - OAuth mode: Checks stored token, refreshes if expired, triggers auth if needed
2069
+ */
2070
+ async resolveToken(mcpServerUrl) {
2071
+ if (this.manuallySignedOutServers.has(mcpServerUrl)) {
2072
+ return void 0;
2073
+ }
2074
+ const authConfig = await this.ensureServerAuthConfig(mcpServerUrl);
2075
+ const stored = this.loadOAuthToken(mcpServerUrl);
2076
+ if (stored) {
2077
+ if (stored.expiresAt > Date.now()) {
2078
+ return stored.accessToken;
2079
+ }
2080
+ if (stored.refreshToken) {
2081
+ const refreshed = await this.refreshOAuthToken(mcpServerUrl, stored.refreshToken);
2082
+ if (refreshed) return refreshed;
2083
+ }
2084
+ this.clearOAuthToken(mcpServerUrl);
2085
+ }
2086
+ if (this.config.onAuthRequired) {
2087
+ if (authConfig) {
2088
+ const isBuiltInPopupAuth = this.config.onAuthRequired.__mcpStackBuiltinPopupAuth === true;
2089
+ const isAppTokenAuth = this.config.auth?.mode === "app-token";
2090
+ const authConfigForHandler = authConfig.authType === "oauth2" && !isBuiltInPopupAuth && !isAppTokenAuth ? await this.resolveOAuthClientRegistration(authConfig) : authConfig;
2091
+ if (authConfigForHandler) {
2092
+ this.updateServerAuthConfig(mcpServerUrl, authConfigForHandler);
2093
+ }
2094
+ const tokenResponse = await this.config.onAuthRequired(
2095
+ mcpServerUrl,
2096
+ authConfigForHandler ?? authConfig
2097
+ );
2098
+ if (tokenResponse?.accessToken) {
2099
+ if (tokenResponse.resolvedAuthConfig) {
2100
+ this.updateServerAuthConfig(mcpServerUrl, tokenResponse.resolvedAuthConfig);
2101
+ }
2102
+ this.storeOAuthToken(mcpServerUrl, tokenResponse);
2103
+ return tokenResponse.accessToken;
2104
+ }
2105
+ }
2106
+ }
2107
+ return void 0;
2108
+ }
2109
+ // ================================================================
2110
+ // Chat Loop
2111
+ // ================================================================
2112
+ /**
2113
+ * The core orchestration loop:
2114
+ * 1. Send message to chat API
2115
+ * 2. Stream response
2116
+ * 3. If tool_call → execute tool via MCP → send result → continue
2117
+ * 4. If message_end → done
2118
+ */
2119
+ async runChatLoop(message) {
2120
+ this.abortController = new AbortController();
2121
+ this.emit("thinking", true);
2122
+ const chatBody = {
2123
+ agentId: this.config.agentId,
2124
+ conversationId: this.conversationId,
2125
+ message,
2126
+ externalUserId: this.resolveExternalUserId(),
2127
+ context: this.config.context
2128
+ };
2129
+ const externalUser = this.buildExternalUserContext();
2130
+ if (externalUser) {
2131
+ chatBody.externalUser = externalUser;
2132
+ }
2133
+ const clientToolSchemas = this.clientToolsToSchemas();
2134
+ if (clientToolSchemas.length > 0) {
2135
+ chatBody.clientTools = clientToolSchemas;
2136
+ }
2137
+ let response = await this.callChatApi(chatBody, "chat");
2138
+ while (true) {
2139
+ const result = await this.processSseStream(response);
2140
+ if (result.type === "message_end") {
2141
+ break;
2142
+ }
2143
+ if (result.type === "tool_call") {
2144
+ const toolCall = result.data;
2145
+ const startTime = Date.now();
2146
+ try {
2147
+ const toolResult = await this.executeTool(toolCall);
2148
+ const duration = Date.now() - startTime;
2149
+ const toolCallMsg = this.messages.find(
2150
+ (m) => m.role === "tool_call" && m.toolCallId === toolCall.toolCallId
2151
+ );
2152
+ if (toolCallMsg) {
2153
+ toolCallMsg.toolCallStatus = "completed";
2154
+ toolCallMsg.toolCallDuration = duration;
2155
+ toolCallMsg.toolResult = typeof toolResult === "string" ? toolResult : JSON.stringify(toolResult);
2156
+ }
2157
+ this.emit("tool_result", { toolCallId: toolCall.toolCallId, result: toolResult, duration });
2158
+ const toolResultMsg = {
2159
+ id: crypto.randomUUID(),
2160
+ role: "tool_result",
2161
+ content: typeof toolResult === "string" ? toolResult : JSON.stringify(toolResult),
2162
+ toolCallId: toolCall.toolCallId,
2163
+ toolName: toolCall.toolName,
2164
+ timestamp: /* @__PURE__ */ new Date()
2165
+ };
2166
+ this.messages.push(toolResultMsg);
2167
+ this.emit("thinking", true);
2168
+ const toolResultBody = {
2169
+ conversationId: this.conversationId,
2170
+ toolCallId: toolCall.toolCallId,
2171
+ result: toolResult,
2172
+ durationMs: duration,
2173
+ context: this.config.context
2174
+ };
2175
+ const clientToolSchemas2 = this.clientToolsToSchemas();
2176
+ if (clientToolSchemas2.length > 0) {
2177
+ toolResultBody.clientTools = clientToolSchemas2;
2178
+ }
2179
+ response = await this.callChatApi(toolResultBody, "chat/tool-result");
2180
+ } catch (err) {
2181
+ const duration = Date.now() - startTime;
2182
+ const errorMsg = err instanceof Error ? err.message : "Tool execution failed";
2183
+ const toolCallMsg = this.messages.find(
2184
+ (m) => m.role === "tool_call" && m.toolCallId === toolCall.toolCallId
2185
+ );
2186
+ if (toolCallMsg) {
2187
+ toolCallMsg.toolCallStatus = "error";
2188
+ toolCallMsg.toolCallDuration = duration;
2189
+ toolCallMsg.toolError = errorMsg;
2190
+ }
2191
+ this.emit("tool_error", { toolCallId: toolCall.toolCallId, error: errorMsg, duration });
2192
+ const errorResult = `Error: ${errorMsg}`;
2193
+ const toolResultMsg = {
2194
+ id: crypto.randomUUID(),
2195
+ role: "tool_result",
2196
+ content: errorResult,
2197
+ toolCallId: toolCall.toolCallId,
2198
+ toolName: toolCall.toolName,
2199
+ timestamp: /* @__PURE__ */ new Date()
2200
+ };
2201
+ this.messages.push(toolResultMsg);
2202
+ this.emit("thinking", true);
2203
+ try {
2204
+ const toolResultBody = {
2205
+ conversationId: this.conversationId,
2206
+ toolCallId: toolCall.toolCallId,
2207
+ result: errorResult,
2208
+ isError: true,
2209
+ durationMs: duration,
2210
+ context: this.config.context
2211
+ };
2212
+ const clientToolSchemas2 = this.clientToolsToSchemas();
2213
+ if (clientToolSchemas2.length > 0) {
2214
+ toolResultBody.clientTools = clientToolSchemas2;
2215
+ }
2216
+ response = await this.callChatApi(toolResultBody, "chat/tool-result");
2217
+ } catch {
2218
+ this.emit("error", { code: "tool_error", message: errorMsg });
2219
+ break;
2220
+ }
2221
+ }
2222
+ }
2223
+ if (result.type === "error") {
2224
+ break;
2225
+ }
2226
+ }
2227
+ }
2228
+ async callChatApi(body, endpoint) {
2229
+ const token = await this.resolveAuthToken();
2230
+ const response = await fetch(
2231
+ `${this.config.agentServiceUrl}/api/v1/${endpoint}`,
2232
+ {
2233
+ method: "POST",
2234
+ headers: {
2235
+ "Content-Type": "application/json",
2236
+ Authorization: `Bearer ${token}`
2237
+ },
2238
+ body: JSON.stringify(body),
2239
+ signal: this.abortController?.signal
2240
+ }
2241
+ );
2242
+ if (!response.ok) {
2243
+ throw new Error(await getResponseErrorMessage(response));
2244
+ }
2245
+ return response;
2246
+ }
2247
+ async fetchConversationMessages(conversationId, cursor, pageSize = 50) {
2248
+ const token = await this.resolveAuthToken();
2249
+ const params = new URLSearchParams();
2250
+ params.set("pageSize", String(pageSize));
2251
+ if (cursor) {
2252
+ params.set("cursor", cursor);
2253
+ }
2254
+ const response = await fetch(
2255
+ `${this.config.agentServiceUrl}/api/v1/chat/conversations/${encodeURIComponent(conversationId)}/messages?${params.toString()}`,
2256
+ {
2257
+ headers: {
2258
+ Authorization: `Bearer ${token}`
2259
+ }
2260
+ }
2261
+ );
2262
+ if (!response.ok) {
2263
+ throw new Error(await getResponseErrorMessage(response));
2264
+ }
2265
+ return await response.json();
2266
+ }
2267
+ applyConversationPage(page, prepend) {
2268
+ const mappedMessages = page.messages.map((message) => this.mapReplayMessage(message));
2269
+ this.conversationId = page.conversationId;
2270
+ this.historyCursor = page.nextCursor ?? null;
2271
+ this.hasOlderMessages = page.hasNextPage;
2272
+ this.messages = prepend ? [...mappedMessages, ...this.messages] : mappedMessages;
2273
+ }
2274
+ mapReplayMessage(message) {
2275
+ const timestamp = new Date(message.createdAt);
2276
+ return {
2277
+ id: message.id,
2278
+ role: message.role,
2279
+ content: message.content ?? "",
2280
+ toolName: message.toolName ?? void 0,
2281
+ toolLabel: message.toolLabel ?? void 0,
2282
+ toolCallId: message.toolCallId ?? void 0,
2283
+ timestamp,
2284
+ toolCallStatus: message.toolCallStatus ?? void 0,
2285
+ toolCallStartTime: message.toolCallDurationMs != null ? timestamp.getTime() - message.toolCallDurationMs : void 0,
2286
+ toolCallDuration: message.toolCallDurationMs ?? void 0,
2287
+ toolResult: message.toolResultJson ?? void 0,
2288
+ toolError: message.toolError ?? void 0,
2289
+ errorCode: message.errorCode ?? void 0,
2290
+ metadataJson: message.metadataJson ?? null
2291
+ };
2292
+ }
2293
+ /**
2294
+ * Process an SSE stream from the chat API.
2295
+ * Returns when the stream ends (either message_end or tool_call).
2296
+ */
2297
+ async processSseStream(response) {
2298
+ let assistantContent = "";
2299
+ let lastToolCall = null;
2300
+ let emittedThinkingFalse = false;
2301
+ for await (const event of parseSseStream(response, this.abortController?.signal)) {
2302
+ switch (event.type) {
2303
+ case "message_start": {
2304
+ const data = event.data;
2305
+ this.conversationId = data.conversationId;
2306
+ break;
2307
+ }
2308
+ case "content_delta": {
2309
+ const data = event.data;
2310
+ if (!emittedThinkingFalse) {
2311
+ this.emit("thinking", false);
2312
+ emittedThinkingFalse = true;
2313
+ }
2314
+ assistantContent += data.text;
2315
+ this.emit("content_delta", data);
2316
+ break;
2317
+ }
2318
+ case "tool_call": {
2319
+ const data = event.data;
2320
+ if (!emittedThinkingFalse) {
2321
+ this.emit("thinking", false);
2322
+ emittedThinkingFalse = true;
2323
+ }
2324
+ lastToolCall = data;
2325
+ const toolCallMsg = {
2326
+ id: crypto.randomUUID(),
2327
+ role: "tool_call",
2328
+ content: `Calling ${data.toolLabel ?? data.toolName}...`,
2329
+ toolName: data.toolName,
2330
+ toolLabel: data.toolLabel,
2331
+ toolCallId: data.toolCallId,
2332
+ timestamp: /* @__PURE__ */ new Date(),
2333
+ toolCallStatus: "calling",
2334
+ toolCallStartTime: Date.now()
2335
+ };
2336
+ this.messages.push(toolCallMsg);
2337
+ this.emit("tool_call", data);
2338
+ break;
2339
+ }
2340
+ case "message_end": {
2341
+ const data = event.data;
2342
+ if (assistantContent) {
2343
+ const assistantMsg = {
2344
+ id: crypto.randomUUID(),
2345
+ role: "assistant",
2346
+ content: assistantContent,
2347
+ timestamp: /* @__PURE__ */ new Date()
2348
+ };
2349
+ this.messages.push(assistantMsg);
2350
+ this.emit("message", assistantMsg);
2351
+ }
2352
+ this.emit("message_end", data);
2353
+ return { type: "message_end", data };
2354
+ }
2355
+ case "budget_snapshot": {
2356
+ const data = event.data;
2357
+ this.budgetSnapshot = data;
2358
+ this.emit("budget_snapshot", data);
2359
+ break;
2360
+ }
2361
+ case "error": {
2362
+ const data = event.data;
2363
+ if (data.budget) {
2364
+ this.budgetSnapshot = data.budget;
2365
+ this.emit("budget_snapshot", data.budget);
2366
+ }
2367
+ const errorMsg = {
2368
+ id: crypto.randomUUID(),
2369
+ role: "error",
2370
+ content: data.message,
2371
+ timestamp: /* @__PURE__ */ new Date(),
2372
+ errorCode: data.code
2373
+ };
2374
+ this.messages.push(errorMsg);
2375
+ this.emit("message", errorMsg);
2376
+ this.emit("error", data);
2377
+ return { type: "error", data };
2378
+ }
2379
+ }
2380
+ }
2381
+ if (lastToolCall) {
2382
+ if (assistantContent) {
2383
+ const assistantMsg = {
2384
+ id: crypto.randomUUID(),
2385
+ role: "assistant",
2386
+ content: assistantContent,
2387
+ timestamp: /* @__PURE__ */ new Date()
2388
+ };
2389
+ this.messages.push(assistantMsg);
2390
+ this.emit("message", assistantMsg);
2391
+ }
2392
+ return { type: "tool_call", data: lastToolCall };
2393
+ }
2394
+ if (assistantContent) {
2395
+ const assistantMsg = {
2396
+ id: crypto.randomUUID(),
2397
+ role: "assistant",
2398
+ content: assistantContent,
2399
+ timestamp: /* @__PURE__ */ new Date()
2400
+ };
2401
+ this.messages.push(assistantMsg);
2402
+ this.emit("message", assistantMsg);
2403
+ }
2404
+ return { type: "message_end" };
2405
+ }
2406
+ // ================================================================
2407
+ // MCP Session Management
2408
+ // ================================================================
2409
+ /** Build headers for MCP server requests */
2410
+ getMcpHeaders(mcpServerUrl) {
2411
+ const headers = {
2412
+ "Content-Type": "application/json",
2413
+ "Accept": "application/json, text/event-stream"
2414
+ };
2415
+ const session = this.mcpSessions.get(mcpServerUrl);
2416
+ if (session?.sessionId) {
2417
+ headers["Mcp-Session-Id"] = session.sessionId;
2418
+ }
2419
+ return headers;
2420
+ }
2421
+ /** Best-effort MCP session teardown so reconnect starts cleanly after sign-out. */
2422
+ async closeMcpSession(mcpServerUrl) {
2423
+ const session = this.mcpSessions.get(mcpServerUrl);
2424
+ if (!session?.sessionId) return;
2425
+ const headers = {
2426
+ "Accept": "application/json, text/event-stream",
2427
+ "Mcp-Session-Id": session.sessionId
2428
+ };
2429
+ const storedToken = this.loadOAuthToken(mcpServerUrl);
2430
+ if (storedToken?.accessToken) {
2431
+ headers["Authorization"] = `Bearer ${storedToken.accessToken}`;
2432
+ }
2433
+ try {
2434
+ await fetch(mcpServerUrl, {
2435
+ method: "DELETE",
2436
+ headers,
2437
+ credentials: this.config.useCookies ? "include" : "omit"
2438
+ });
2439
+ } catch {
2440
+ }
2441
+ this.mcpSessions.set(mcpServerUrl, {
2442
+ sessionId: null,
2443
+ authStatus: session.authStatus
2444
+ });
2445
+ }
2446
+ /** Initialize the MCP session for a specific server (required before tools/call) */
2447
+ async initMcpSession(mcpServerUrl) {
2448
+ const session = this.mcpSessions.get(mcpServerUrl);
2449
+ if (session?.sessionId) return;
2450
+ const headers = this.getMcpHeaders(mcpServerUrl);
2451
+ await this.ensureServerAuthConfig(mcpServerUrl);
2452
+ const token = await this.resolveToken(mcpServerUrl);
2453
+ if (token) headers["Authorization"] = `Bearer ${token}`;
2454
+ const initPayload = JSON.stringify({
2455
+ jsonrpc: "2.0",
2456
+ id: 1,
2457
+ method: "initialize",
2458
+ params: {
2459
+ protocolVersion: DEFAULT_MCP_PROTOCOL_VERSION,
2460
+ capabilities: {},
2461
+ clientInfo: { name: "mcpstack-agent-sdk", version: "0.1.0" }
2462
+ }
2463
+ });
2464
+ const initResponse = await fetch(mcpServerUrl, {
2465
+ method: "POST",
2466
+ headers,
2467
+ credentials: this.config.useCookies ? "include" : "omit",
2468
+ body: initPayload
2469
+ });
2470
+ if (initResponse.status === 401) {
2471
+ this.clearOAuthToken(mcpServerUrl);
2472
+ this.updateMcpAuthStatus(mcpServerUrl, "needs_auth");
2473
+ const freshToken = await this.resolveToken(mcpServerUrl);
2474
+ if (freshToken) {
2475
+ headers["Authorization"] = `Bearer ${freshToken}`;
2476
+ const retryResponse = await fetch(mcpServerUrl, {
2477
+ method: "POST",
2478
+ headers,
2479
+ credentials: this.config.useCookies ? "include" : "omit",
2480
+ body: initPayload
2481
+ });
2482
+ if (retryResponse.ok) {
2483
+ const sessionId2 = retryResponse.headers.get("mcp-session-id");
2484
+ this.mcpSessions.set(mcpServerUrl, { sessionId: sessionId2, authStatus: "connected" });
2485
+ this.updateMcpAuthStatus(mcpServerUrl, "connected");
2486
+ await retryResponse.text().catch(() => {
2487
+ });
2488
+ const notifyHeaders2 = this.getMcpHeaders(mcpServerUrl);
2489
+ notifyHeaders2["Authorization"] = `Bearer ${freshToken}`;
2490
+ await fetch(mcpServerUrl, {
2491
+ method: "POST",
2492
+ headers: notifyHeaders2,
2493
+ credentials: this.config.useCookies ? "include" : "omit",
2494
+ body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })
2495
+ });
2496
+ return;
2497
+ }
2498
+ }
2499
+ throw new Error("MCP initialization failed (401): Authentication required");
2500
+ }
2501
+ if (!initResponse.ok) {
2502
+ const errorText = await initResponse.text().catch(() => "MCP init error");
2503
+ throw new Error(`MCP initialization failed (${initResponse.status}): ${errorText}`);
2504
+ }
2505
+ const sessionId = initResponse.headers.get("mcp-session-id");
2506
+ this.mcpSessions.set(mcpServerUrl, { sessionId, authStatus: "connected" });
2507
+ this.updateMcpAuthStatus(mcpServerUrl, "connected");
2508
+ await initResponse.text().catch(() => {
2509
+ });
2510
+ const notifyHeaders = this.getMcpHeaders(mcpServerUrl);
2511
+ if (token) notifyHeaders["Authorization"] = `Bearer ${token}`;
2512
+ await fetch(mcpServerUrl, {
2513
+ method: "POST",
2514
+ headers: notifyHeaders,
2515
+ credentials: this.config.useCookies ? "include" : "omit",
2516
+ body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })
2517
+ });
2518
+ }
2519
+ /** Update auth status for an MCP server and emit event */
2520
+ updateMcpAuthStatus(mcpServerUrl, authStatus) {
2521
+ const session = this.mcpSessions.get(mcpServerUrl);
2522
+ if (session) {
2523
+ session.authStatus = authStatus;
2524
+ } else {
2525
+ this.mcpSessions.set(mcpServerUrl, { sessionId: null, authStatus });
2526
+ }
2527
+ const serverInfo = this.agentConfig?.mcpServers?.find((s) => s.url === mcpServerUrl);
2528
+ this.emit("mcp_auth_status", {
2529
+ mcpServerUrl,
2530
+ mcpServerName: serverInfo?.name ?? mcpServerUrl,
2531
+ authStatus
2532
+ });
2533
+ }
2534
+ /** Parse a JSON-RPC response from either JSON or SSE format */
2535
+ async parseMcpResponse(response) {
2536
+ const contentType = (response.headers.get("content-type") || "").toLowerCase();
2537
+ if (contentType.includes("text/event-stream")) {
2538
+ const text = await response.text();
2539
+ const lines = text.split("\n");
2540
+ let jsonData = "";
2541
+ for (const line of lines) {
2542
+ if (line.startsWith("data: ")) {
2543
+ jsonData += line.slice(6);
2544
+ }
2545
+ }
2546
+ if (!jsonData) {
2547
+ throw new Error("No data received from MCP server SSE response");
2548
+ }
2549
+ return JSON.parse(jsonData);
2550
+ }
2551
+ return response.json();
2552
+ }
2553
+ // ================================================================
2554
+ // Tool Execution
2555
+ // ================================================================
2556
+ async executeTool(toolCall) {
2557
+ const isClientTool = toolCall.source === "client" || !toolCall.mcpServerUrl;
2558
+ if (isClientTool && this.config.clientTools) {
2559
+ const def = this.config.clientTools[toolCall.toolName];
2560
+ if (def) {
2561
+ const result2 = await def.execute(toolCall.arguments ?? {});
2562
+ return result2;
2563
+ }
2564
+ throw new Error(`Unknown client tool: ${toolCall.toolName}`);
2565
+ }
2566
+ const mcpServerUrl = toolCall.mcpServerUrl || this.agentConfig?.mcpServerUrl;
2567
+ if (!mcpServerUrl) {
2568
+ throw new Error("No MCP server URL for tool call");
2569
+ }
2570
+ await this.initMcpSession(mcpServerUrl);
2571
+ const token = await this.resolveToken(mcpServerUrl);
2572
+ const headers = this.getMcpHeaders(mcpServerUrl);
2573
+ if (token) headers["Authorization"] = `Bearer ${token}`;
2574
+ const toolCallBody = JSON.stringify({
2575
+ jsonrpc: "2.0",
2576
+ id: 2,
2577
+ method: "tools/call",
2578
+ params: { name: toolCall.toolName, arguments: toolCall.arguments }
2579
+ });
2580
+ let response = await fetch(mcpServerUrl, {
2581
+ method: "POST",
2582
+ headers,
2583
+ credentials: this.config.useCookies ? "include" : "omit",
2584
+ body: toolCallBody,
2585
+ signal: this.abortController?.signal
2586
+ });
2587
+ const session = this.mcpSessions.get(mcpServerUrl);
2588
+ if (response.status === 404 && session?.sessionId) {
2589
+ this.mcpSessions.set(mcpServerUrl, { ...session, sessionId: null });
2590
+ await this.initMcpSession(mcpServerUrl);
2591
+ const retryHeaders = this.getMcpHeaders(mcpServerUrl);
2592
+ if (token) retryHeaders["Authorization"] = `Bearer ${token}`;
2593
+ response = await fetch(mcpServerUrl, {
2594
+ method: "POST",
2595
+ headers: retryHeaders,
2596
+ credentials: this.config.useCookies ? "include" : "omit",
2597
+ body: toolCallBody,
2598
+ signal: this.abortController?.signal
2599
+ });
2600
+ }
2601
+ if (response.status === 401) {
2602
+ this.clearOAuthToken(mcpServerUrl);
2603
+ this.updateMcpAuthStatus(mcpServerUrl, "needs_auth");
2604
+ const freshToken = await this.resolveToken(mcpServerUrl);
2605
+ if (freshToken) {
2606
+ const authHeaders = this.getMcpHeaders(mcpServerUrl);
2607
+ authHeaders["Authorization"] = `Bearer ${freshToken}`;
2608
+ response = await fetch(mcpServerUrl, {
2609
+ method: "POST",
2610
+ headers: authHeaders,
2611
+ credentials: this.config.useCookies ? "include" : "omit",
2612
+ body: toolCallBody,
2613
+ signal: this.abortController?.signal
2614
+ });
2615
+ if (response.ok) {
2616
+ this.updateMcpAuthStatus(mcpServerUrl, "connected");
2617
+ }
2618
+ }
2619
+ if (!response.ok) {
2620
+ const errorText = await response.text().catch(() => "Authentication required");
2621
+ throw new Error(`Tool execution failed (401): ${errorText}`);
2622
+ }
2623
+ }
2624
+ if (!response.ok) {
2625
+ const errorText = await response.text().catch(() => "MCP server error");
2626
+ throw new Error(`Tool execution failed (${response.status}): ${errorText}`);
2627
+ }
2628
+ const currentSession = this.mcpSessions.get(mcpServerUrl);
2629
+ if (currentSession?.authStatus === "needs_auth") {
2630
+ this.updateMcpAuthStatus(mcpServerUrl, "connected");
2631
+ }
2632
+ const result = await this.parseMcpResponse(response);
2633
+ if (result.error) {
2634
+ throw new Error(`MCP error (${result.error.code}): ${result.error.message}`);
2635
+ }
2636
+ if (result.result?.content) {
2637
+ const textContent = result.result.content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
2638
+ return textContent || result.result;
2639
+ }
2640
+ return result.result ?? result;
2641
+ }
2642
+ };
2643
+ // Annotate the CommonJS export names for ESM import in node:
2644
+ 0 && (module.exports = {
2645
+ McpStackAgent,
2646
+ clearPersistedMcpAuth,
2647
+ clearPersistedMcpAuthState
2648
+ });
2649
+ //# sourceMappingURL=index.js.map