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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,639 @@
1
+ interface ClientToolParameter {
2
+ type: string;
3
+ description?: string;
4
+ required?: boolean;
5
+ enum?: string[];
6
+ items?: ClientToolParameter;
7
+ properties?: Record<string, ClientToolParameter>;
8
+ additionalProperties?: boolean | ClientToolParameter;
9
+ }
10
+ interface ClientToolDefinition {
11
+ description: string;
12
+ parameters: Record<string, ClientToolParameter>;
13
+ selection?: ClientToolSelection;
14
+ execute: (params: Record<string, unknown>) => Promise<unknown>;
15
+ }
16
+ type ClientToolsMap = Record<string, ClientToolDefinition>;
17
+ interface ClientToolSelection {
18
+ categories?: string[];
19
+ alwaysInclude?: boolean;
20
+ includeWhen?: string[];
21
+ risk?: 'low' | 'medium' | 'high' | string;
22
+ serverPreferred?: boolean;
23
+ }
24
+ interface McpStackEmbeddedAuthIdentity {
25
+ subject?: string;
26
+ email?: string;
27
+ organizationId?: string;
28
+ displayName?: string;
29
+ avatarUrl?: string;
30
+ }
31
+ interface McpStackEmbeddedAuthConfig {
32
+ hostIdentity?: McpStackEmbeddedAuthIdentity;
33
+ mismatchPolicy: 'block_with_switch';
34
+ }
35
+ interface McpStackAppTokenAuthConfig {
36
+ mode: 'app-token';
37
+ appId?: string;
38
+ getToken: () => Promise<string | undefined> | string | undefined;
39
+ }
40
+ interface McpStackStorageLike {
41
+ getItem(key: string): string | null;
42
+ setItem(key: string, value: string): void;
43
+ removeItem(key: string): void;
44
+ }
45
+ interface AudioTurnDetectionConfig {
46
+ /**
47
+ * Enables SDK-side end-of-speech detection. Defaults to true.
48
+ * When enabled, the SDK commits microphone input after the user has spoken
49
+ * and then paused for `silenceDurationMs`.
50
+ */
51
+ enabled?: boolean;
52
+ /**
53
+ * Whether detected end-of-speech should automatically submit the transcript.
54
+ * Defaults to true. Set false for push-to-talk/manual-stop experiences.
55
+ */
56
+ autoSubmit?: boolean;
57
+ /**
58
+ * Trailing silence required before the SDK commits audio, in milliseconds.
59
+ * Defaults to 850ms.
60
+ */
61
+ silenceDurationMs?: number;
62
+ /**
63
+ * Minimum detected speech duration before a turn is considered real speech.
64
+ * Defaults to 180ms to ignore clicks and short bumps.
65
+ */
66
+ minSpeechDurationMs?: number;
67
+ /**
68
+ * Time to keep listening before speech starts, in milliseconds.
69
+ * Defaults to 12000ms. Set to 0 to disable.
70
+ */
71
+ noSpeechTimeoutMs?: number;
72
+ /**
73
+ * Absolute RMS threshold from 0 to 1. Defaults to 0.012.
74
+ * The SDK also adapts to the ambient noise floor.
75
+ */
76
+ speechThreshold?: number;
77
+ /**
78
+ * Multiplier applied to the measured ambient noise floor. Defaults to 2.4.
79
+ */
80
+ noiseMultiplier?: number;
81
+ }
82
+ interface McpStackAudioInputConfig {
83
+ /**
84
+ * SDK-owned turn detection configuration. Consumer apps can tune it, but
85
+ * they do not need to implement their own microphone VAD.
86
+ */
87
+ turnDetection?: AudioTurnDetectionConfig;
88
+ }
89
+ interface McpStackAgentConfig {
90
+ /** API key for authenticating with the MCP Stack API */
91
+ apiKey: string;
92
+ /** Agent ID from the MCP Stack dashboard */
93
+ agentId: string;
94
+ /** MCP Stack API URL. Defaults to https://api.mcpstack.com */
95
+ agentServiceUrl?: string;
96
+ /**
97
+ * Callback URL used by the standalone popup OAuth flow.
98
+ * Defaults to the hosted MCP Stack callback page so downstream auth servers
99
+ * only need to allow a single redirect URI.
100
+ */
101
+ oauthCallbackUrl?: string;
102
+ /**
103
+ * Public URL for this client's hosted metadata document when using
104
+ * Client ID Metadata Documents (CIMD).
105
+ */
106
+ oauthClientMetadataUrl?: string;
107
+ /**
108
+ * Callback to get the auth token for MCP Stack API requests.
109
+ * If provided, called before each chat API request.
110
+ * Use this when your session token may expire and needs refresh (e.g., dashboard playground).
111
+ * If not provided, uses the static `apiKey` value.
112
+ */
113
+ getAuthToken?: () => Promise<string | undefined>;
114
+ /**
115
+ * Host app auth-session boundary for persisted MCP auth state.
116
+ * Use the current app session id so logging out forces MCP reconnect,
117
+ * even when the same browser later signs back in as the same user.
118
+ */
119
+ authSessionKey?: string | null;
120
+ /**
121
+ * Embedded popup auth settings.
122
+ * Use this to tell MCP Stack which host-app user is currently signed in so
123
+ * the built-in popup flow can prefer the same downstream account.
124
+ */
125
+ embeddedAuth?: McpStackEmbeddedAuthConfig;
126
+ /**
127
+ * App-owned MCP auth for embedded products.
128
+ * Use this when your app already authenticated the user and can return a
129
+ * short-lived app access token. The SDK exchanges that token at Gateway for
130
+ * an MCP-facing token without opening a second sign-in window.
131
+ */
132
+ auth?: McpStackAppTokenAuthConfig;
133
+ /**
134
+ * If true, MCP server calls include cookies (for cookie-based auth).
135
+ * Default: false
136
+ */
137
+ useCookies?: boolean;
138
+ /**
139
+ * Called when an MCP server requires authentication and the built-in
140
+ * popup flow is not being used. The SDK will invoke this so the
141
+ * integrator can trigger a custom login flow.
142
+ *
143
+ * Return the token response on success, or undefined to cancel.
144
+ * The SDK stores the token and handles refresh automatically.
145
+ */
146
+ onAuthRequired?: (mcpServerUrl: string, authConfig: McpServerAuthConfig) => Promise<OAuthTokenResponse | undefined>;
147
+ /** Optional: external user ID to associate with conversations */
148
+ externalUserId?: string;
149
+ /** Optional: additional context sent with each message */
150
+ context?: Record<string, unknown>;
151
+ /** Optional: microphone input behavior. */
152
+ audioInput?: McpStackAudioInputConfig;
153
+ /**
154
+ * Optional: resume an existing server-side conversation on init.
155
+ * Use this with persisted conversation ids in the host app.
156
+ */
157
+ initialConversationId?: string | null;
158
+ /**
159
+ * Page size for conversation replay bootstrap and older-message loading.
160
+ * Default: 50
161
+ */
162
+ conversationHistoryPageSize?: number;
163
+ /**
164
+ * Client tools — execute locally in browser, exposed to LLM.
165
+ * The agent can call these to interact with the host app (e.g. fill forms, read page state).
166
+ */
167
+ clientTools?: ClientToolsMap;
168
+ /**
169
+ * Optional persistent storage override used for MCP auth/session artifacts.
170
+ * If omitted, the runtime falls back to `localStorage` when available.
171
+ */
172
+ storage?: McpStackStorageLike | null;
173
+ }
174
+ interface ChatMessage {
175
+ id: string;
176
+ role: 'user' | 'assistant' | 'tool_call' | 'tool_result' | 'error';
177
+ content: string;
178
+ toolName?: string;
179
+ toolLabel?: string;
180
+ toolCallId?: string;
181
+ timestamp: Date;
182
+ toolCallStatus?: 'calling' | 'completed' | 'error';
183
+ toolCallStartTime?: number;
184
+ toolCallDuration?: number;
185
+ toolResult?: string;
186
+ toolError?: string;
187
+ errorCode?: string;
188
+ metadataJson?: string | null;
189
+ }
190
+ interface ConversationReplayMessage {
191
+ id: string;
192
+ sequenceNumber: number;
193
+ role: ChatMessage['role'];
194
+ content?: string | null;
195
+ createdAt: string;
196
+ toolName?: string | null;
197
+ toolLabel?: string | null;
198
+ toolCallId?: string | null;
199
+ toolCallStatus?: 'calling' | 'completed' | 'error' | null;
200
+ toolCallDurationMs?: number | null;
201
+ toolArgumentsJson?: string | null;
202
+ toolResultJson?: string | null;
203
+ toolError?: string | null;
204
+ errorCode?: string | null;
205
+ metadataJson?: string | null;
206
+ }
207
+ interface ConversationMessagesPage {
208
+ conversationId: string;
209
+ messages: ConversationReplayMessage[];
210
+ pageSize: number;
211
+ nextCursor?: string | null;
212
+ hasNextPage: boolean;
213
+ }
214
+ type ConversationFeedbackSentiment = 'up' | 'down';
215
+ interface SubmitConversationFeedbackRequest {
216
+ sentiment: ConversationFeedbackSentiment;
217
+ comment?: string;
218
+ source?: string;
219
+ toolCallId?: string;
220
+ conversationMessageId?: string;
221
+ metadata?: Record<string, unknown>;
222
+ }
223
+ interface ConversationFeedback {
224
+ id: string;
225
+ conversationId: string;
226
+ sentiment: ConversationFeedbackSentiment;
227
+ comment?: string | null;
228
+ source: string;
229
+ toolCallId?: string | null;
230
+ conversationMessageId?: string | null;
231
+ metadataJson?: string | null;
232
+ createdAt: string;
233
+ }
234
+ interface McpServerAuthConfig {
235
+ authType: 'none' | 'apiKey' | 'bearer' | 'oauth2';
236
+ issuer?: string;
237
+ authorizationServerUrl?: string;
238
+ authorizationServerMetadataUrl?: string;
239
+ authorizationEndpoint?: string;
240
+ loginUrl?: string;
241
+ tokenEndpoint?: string;
242
+ tokenUrl?: string;
243
+ registrationEndpoint?: string;
244
+ clientId?: string;
245
+ scopes?: string[];
246
+ resource?: string;
247
+ callbackUrl?: string;
248
+ protectedResourceMetadataUrl?: string;
249
+ clientIdMetadataDocumentSupported?: boolean;
250
+ resourceParameterSupported?: boolean;
251
+ registrationPreference?: McpClientRegistrationPreference;
252
+ clientMode?: McpResolvedClientMode;
253
+ authRecipe?: McpAuthRecipe;
254
+ manualOverrides?: string[];
255
+ discovered?: boolean;
256
+ }
257
+ type McpAuthRecipe = 'sqlos' | 'auth0' | 'entra' | 'workos' | 'manual';
258
+ type McpClientRegistrationPreference = 'auto' | 'preregistered' | 'cimd' | 'dcr' | 'manual';
259
+ type McpResolvedClientMode = 'preregistered' | 'cimd' | 'dcr' | 'manual';
260
+ /** OAuth token response from token endpoint */
261
+ interface OAuthTokenResponse {
262
+ accessToken: string;
263
+ refreshToken?: string;
264
+ expiresIn?: number;
265
+ tokenType?: string;
266
+ resolvedAuthConfig?: McpServerAuthConfig;
267
+ }
268
+ interface McpServerInfo {
269
+ id: string;
270
+ name: string;
271
+ url: string;
272
+ authStatus: 'connected' | 'needs_auth';
273
+ authConfig?: McpServerAuthConfig | null;
274
+ }
275
+ interface AgentConfigResponse {
276
+ agentId: string;
277
+ name: string;
278
+ conversationResumeVersion: string;
279
+ /** @deprecated Use mcpServers instead */
280
+ mcpServerUrl?: string;
281
+ mcpServers: McpServerInfo[];
282
+ widgetConfig?: WidgetConfig | null;
283
+ modelConfig?: AgentPublicModelConfig | null;
284
+ audio?: AgentPublicAudioConfig | null;
285
+ }
286
+ interface AgentModelCapabilities {
287
+ textInput?: boolean;
288
+ textOutput?: boolean;
289
+ audioInput?: boolean;
290
+ audioOutput?: boolean;
291
+ realtime?: boolean;
292
+ toolCalls?: boolean;
293
+ text?: boolean;
294
+ realtimeAudioInput?: boolean;
295
+ realtimeAudioOutput?: boolean;
296
+ transcription?: boolean;
297
+ translation?: boolean;
298
+ }
299
+ interface AgentPublicModelConfig {
300
+ id: string;
301
+ provider: string;
302
+ displayName: string;
303
+ capabilities: AgentModelCapabilities;
304
+ }
305
+ interface AgentPublicAudioConfig {
306
+ inputEnabled: boolean;
307
+ outputEnabled: boolean;
308
+ maxSessionSeconds: number;
309
+ transcriptionModel?: string | null;
310
+ }
311
+ interface WidgetConfig {
312
+ theme?: string;
313
+ position?: string;
314
+ title?: string;
315
+ placeholder?: string;
316
+ welcomeMessage?: string;
317
+ }
318
+ interface SseContentDelta {
319
+ text: string;
320
+ }
321
+ interface SseToolCall {
322
+ toolCallId: string;
323
+ toolName: string;
324
+ toolLabel?: string;
325
+ arguments: Record<string, unknown>;
326
+ mcpServerUrl?: string;
327
+ mcpServerName?: string;
328
+ /** When 'client', execute locally via clientTools; when 'mcp' or absent with mcpServerUrl, use MCP */
329
+ source?: 'client' | 'mcp';
330
+ }
331
+ interface SseMessageEnd {
332
+ inputTokens: number;
333
+ outputTokens: number;
334
+ toolCalls: number;
335
+ }
336
+ interface AgentBudgetSnapshot {
337
+ enabled: boolean;
338
+ currency: string;
339
+ identityType: 'identified' | 'anonymous' | string;
340
+ externalUserId: string;
341
+ displayName: string;
342
+ budgetSource: 'explicit' | 'default_user' | 'anonymous' | 'none' | string;
343
+ windowStartUtc: string;
344
+ windowEndUtc: string;
345
+ agentMonthlyBudgetUsd?: number | null;
346
+ agentCurrentMonthSpendUsd: number;
347
+ agentRemainingBudgetUsd?: number | null;
348
+ userMonthlyBudgetUsd?: number | null;
349
+ userCurrentMonthSpendUsd: number;
350
+ userRemainingBudgetUsd?: number | null;
351
+ organizationCreditsRemainingUsd?: number | null;
352
+ effectiveRemainingUsd?: number | null;
353
+ status: 'healthy' | 'warning' | 'blocked' | 'disabled' | string;
354
+ }
355
+ interface SseError {
356
+ code: string;
357
+ message: string;
358
+ budget?: AgentBudgetSnapshot | null;
359
+ }
360
+ type AudioInputStatus = 'idle' | 'requesting_permission' | 'connecting' | 'listening' | 'transcribing' | 'sending' | 'error';
361
+ interface AudioInputState {
362
+ status: AudioInputStatus;
363
+ isSupported: boolean;
364
+ isEnabled: boolean;
365
+ transcript: string;
366
+ partialTranscript: string;
367
+ error: SseError | null;
368
+ sessionId?: string | null;
369
+ conversationId?: string | null;
370
+ maxSessionSeconds?: number | null;
371
+ inputLevel?: number;
372
+ isSpeaking?: boolean;
373
+ speechMs?: number;
374
+ silenceMs?: number;
375
+ autoSubmitEnabled?: boolean;
376
+ }
377
+ interface AudioTranscriptDeltaEvent {
378
+ text: string;
379
+ transcript: string;
380
+ isFinal: false;
381
+ }
382
+ interface AudioTranscriptFinalEvent {
383
+ text: string;
384
+ transcript: string;
385
+ conversationId: string;
386
+ }
387
+ interface AudioActivityEvent {
388
+ inputLevel: number;
389
+ noiseFloor: number;
390
+ isSpeaking: boolean;
391
+ speechMs: number;
392
+ silenceMs: number;
393
+ }
394
+ interface McpAuthStatusEvent {
395
+ mcpServerUrl: string;
396
+ mcpServerName: string;
397
+ authStatus: 'connected' | 'needs_auth';
398
+ }
399
+ type McpStackAgentEventMap = {
400
+ message: ChatMessage;
401
+ content_delta: SseContentDelta;
402
+ tool_call: SseToolCall;
403
+ tool_result: {
404
+ toolCallId: string;
405
+ result: unknown;
406
+ duration: number;
407
+ };
408
+ tool_error: {
409
+ toolCallId: string;
410
+ error: string;
411
+ duration: number;
412
+ };
413
+ message_end: SseMessageEnd;
414
+ budget_snapshot: AgentBudgetSnapshot;
415
+ error: SseError;
416
+ loading: boolean;
417
+ thinking: boolean;
418
+ mcp_auth_status: McpAuthStatusEvent;
419
+ audio_state: AudioInputState;
420
+ audio_activity: AudioActivityEvent;
421
+ audio_transcript_delta: AudioTranscriptDeltaEvent;
422
+ audio_transcript_final: AudioTranscriptFinalEvent;
423
+ };
424
+ type McpStackAgentEvent = keyof McpStackAgentEventMap;
425
+
426
+ type EventHandler<T> = (data: T) => void;
427
+ /**
428
+ * Core orchestration class for the MCP Stack Agent SDK.
429
+ * Framework-agnostic — works in any JavaScript environment.
430
+ *
431
+ * Handles:
432
+ * - Communication with the MCP Stack chat API (SSE streaming)
433
+ * - Tool execution via MCP server (browser-side, with user's auth token)
434
+ * - Conversation state management
435
+ * - Event emission for UI updates
436
+ */
437
+ declare class McpStackAgent {
438
+ private config;
439
+ private agentConfig;
440
+ private budgetSnapshot;
441
+ private conversationId;
442
+ private messages;
443
+ private historyCursor;
444
+ private hasOlderMessages;
445
+ private isLoadingHistory;
446
+ private abortController;
447
+ private isLoading;
448
+ private listeners;
449
+ /** Per-server MCP session tracking */
450
+ private mcpSessions;
451
+ /** OAuth tokens per MCP server URL (standalone mode only) */
452
+ private oauthTokens;
453
+ /** Servers explicitly disconnected by the user and awaiting manual re-auth */
454
+ private manuallySignedOutServers;
455
+ private audioState;
456
+ private audioStream;
457
+ private audioContext;
458
+ private audioSource;
459
+ private audioProcessor;
460
+ private audioSilentGain;
461
+ private audioSocket;
462
+ private audioSessionTimer;
463
+ private audioSessionStopRequested;
464
+ private audioFinalTranscript;
465
+ private audioTurnState;
466
+ constructor(config: McpStackAgentConfig);
467
+ private resolveAuthToken;
468
+ /** Initialize: fetch agent config (tools, widget settings, MCP servers) */
469
+ init(): Promise<AgentConfigResponse>;
470
+ /** Get current MCP server auth statuses */
471
+ getMcpServers(): Array<{
472
+ url: string;
473
+ name: string;
474
+ authStatus: 'connected' | 'needs_auth';
475
+ canSignOut: boolean;
476
+ }>;
477
+ /** Send a message and process the full orchestration loop (including tool calls) */
478
+ sendMessage(message: string): Promise<void>;
479
+ /** Start a new conversation */
480
+ newConversation(): void;
481
+ /** Cancel the current in-flight request */
482
+ cancel(): void;
483
+ /** Get all messages in the current conversation */
484
+ getMessages(): ChatMessage[];
485
+ /** Get the current conversation ID */
486
+ getConversationId(): string | null;
487
+ getHasOlderMessages(): boolean;
488
+ getIsLoadingHistory(): boolean;
489
+ /** Get the loaded agent config */
490
+ getAgentConfig(): AgentConfigResponse | null;
491
+ getAudioInputState(): AudioInputState;
492
+ startVoiceInput(): Promise<void>;
493
+ stopVoiceInput(): Promise<void>;
494
+ cancelVoiceInput(): void;
495
+ loadConversation(conversationId: string, pageSize?: number): Promise<ConversationMessagesPage>;
496
+ loadOlderMessages(pageSize?: number): Promise<ConversationMessagesPage | null>;
497
+ submitFeedback(input: SubmitConversationFeedbackRequest): Promise<ConversationFeedback>;
498
+ /** Convert client tools to the API schema format. */
499
+ private clientToolsToSchemas;
500
+ private resolveExternalUserId;
501
+ private buildExternalUserContext;
502
+ /** Latest runtime budget snapshot for the current SDK identity. */
503
+ getBudgetSnapshot(): AgentBudgetSnapshot | null;
504
+ /** Refresh the current SDK identity's budget snapshot from the API. */
505
+ refreshBudgetSnapshot(): Promise<AgentBudgetSnapshot | null>;
506
+ /** Whether a request is currently in flight */
507
+ getIsLoading(): boolean;
508
+ /** Update the per-turn app context sent with each chat request. */
509
+ setAppContext(context: Record<string, unknown> | undefined): void;
510
+ /** Update the client tools exposed to the agent without recreating the session. */
511
+ setClientTools(clientTools: ClientToolsMap | undefined): void;
512
+ /**
513
+ * Proactively authenticate with an MCP server before sending a message.
514
+ * If a token response is provided directly, it is stored immediately.
515
+ * Otherwise, this uses the configured OAuth flow and verifies via MCP init.
516
+ *
517
+ * @param mcpServerUrl - The MCP server URL to authenticate with
518
+ * @param tokenResponse - Optional: provide token response directly (from OAuth popup)
519
+ */
520
+ authenticate(mcpServerUrl: string, tokenResponse?: OAuthTokenResponse): Promise<boolean>;
521
+ /** Disconnect from an MCP server and require explicit re-authentication before reuse. */
522
+ signOutMcpServer(mcpServerUrl: string): Promise<void>;
523
+ /** Get the auth config for an MCP server (from agent config) */
524
+ getServerAuthConfig(mcpServerUrl: string): McpServerAuthConfig | null;
525
+ getOAuthCallbackUrl(): string;
526
+ getOAuthClientMetadataUrl(): string;
527
+ private getDefaultAuthRequiredHandler;
528
+ setOnAuthRequired(onAuthRequired: McpStackAgentConfig['onAuthRequired']): void;
529
+ private isAudioInputSupported;
530
+ private isAudioInputEnabled;
531
+ private isAudioAutoSubmitEnabled;
532
+ private getAudioTurnDetectionConfig;
533
+ private clampNumber;
534
+ private buildAudioState;
535
+ private setAudioState;
536
+ private getAudioContextConstructor;
537
+ private createRealtimeTranscriptionSession;
538
+ private buildApiError;
539
+ private openAudioSocket;
540
+ private normalizeAudioSocketUrl;
541
+ private bindAudioSocket;
542
+ private handleAudioSocketMessage;
543
+ private commitVoiceInput;
544
+ private stopVoiceInputWithoutTranscript;
545
+ private createAudioTurnState;
546
+ private analyzeAudioFrame;
547
+ private processAudioTurnActivity;
548
+ private updateNoiseFloor;
549
+ private emitAudioActivity;
550
+ private startAudioCapture;
551
+ private resampleToPcm16;
552
+ private floatToPcm16;
553
+ private pcm16ToBase64;
554
+ private cleanupAudioCapture;
555
+ private clearAudioSessionTimer;
556
+ private extractErrorCode;
557
+ private getPersistentStorage;
558
+ private resolveOAuthClientRegistration;
559
+ /** Subscribe to events */
560
+ on<K extends McpStackAgentEvent>(event: K, handler: EventHandler<McpStackAgentEventMap[K]>): void;
561
+ /** Unsubscribe from events */
562
+ off<K extends McpStackAgentEvent>(event: K, handler: EventHandler<McpStackAgentEventMap[K]>): void;
563
+ private buildProtectedResourceMetadataCandidates;
564
+ private hasSameOrigin;
565
+ private extractQuotedHeaderValue;
566
+ private buildAuthorizationServerMetadataCandidates;
567
+ private hasExplicitManualOverride;
568
+ private pickAuthConfigValue;
569
+ private pickAuthConfigArrayValue;
570
+ private mergeAuthConfigs;
571
+ private discoverAuthConfig;
572
+ private resolveServerAuthConfig;
573
+ private ensureServerAuthConfig;
574
+ private updateServerAuthConfig;
575
+ private emit;
576
+ /** Generate the legacy token cache suffix used before auth-aware keying. */
577
+ private hashUrl;
578
+ private getLegacyTokenStorageKey;
579
+ private getAuthSessionKey;
580
+ private getTokenStorageKey;
581
+ private getTokenStorageCandidates;
582
+ /** Load OAuth token from memory/persistent storage using auth-aware cache keying. */
583
+ private loadOAuthToken;
584
+ /** Check if we have a valid (non-expired) OAuth token */
585
+ private hasValidOAuthToken;
586
+ /** Store OAuth token to memory and persistent storage */
587
+ private storeOAuthToken;
588
+ /** Clear OAuth token from memory and persistent storage */
589
+ private clearOAuthToken;
590
+ /** Refresh OAuth token using refresh token */
591
+ private refreshOAuthToken;
592
+ /**
593
+ * Resolve the auth token for an MCP server.
594
+ * - OAuth mode: Checks stored token, refreshes if expired, triggers auth if needed
595
+ */
596
+ private resolveToken;
597
+ /**
598
+ * The core orchestration loop:
599
+ * 1. Send message to chat API
600
+ * 2. Stream response
601
+ * 3. If tool_call → execute tool via MCP → send result → continue
602
+ * 4. If message_end → done
603
+ */
604
+ private runChatLoop;
605
+ private callChatApi;
606
+ private fetchConversationMessages;
607
+ private applyConversationPage;
608
+ private mapReplayMessage;
609
+ /**
610
+ * Process an SSE stream from the chat API.
611
+ * Returns when the stream ends (either message_end or tool_call).
612
+ */
613
+ private processSseStream;
614
+ /** Build headers for MCP server requests */
615
+ private getMcpHeaders;
616
+ /** Best-effort MCP session teardown so reconnect starts cleanly after sign-out. */
617
+ private closeMcpSession;
618
+ /** Initialize the MCP session for a specific server (required before tools/call) */
619
+ private initMcpSession;
620
+ /** Update auth status for an MCP server and emit event */
621
+ private updateMcpAuthStatus;
622
+ /** Parse a JSON-RPC response from either JSON or SSE format */
623
+ private parseMcpResponse;
624
+ private executeTool;
625
+ }
626
+
627
+ type PersistedStateStorage = McpStackStorageLike & Pick<Storage, 'key' | 'length'>;
628
+ interface ClearPersistedMcpAuthStateOptions {
629
+ /** Session scope to clear. Ignored when `clearAll` is true. */
630
+ authSessionKey?: string | null;
631
+ /** Clear all persisted MCP auth state, regardless of scope. */
632
+ clearAll?: boolean;
633
+ /** Test hook for injecting a storage implementation. */
634
+ storage?: PersistedStateStorage | null;
635
+ }
636
+ declare function clearPersistedMcpAuthState(options?: ClearPersistedMcpAuthStateOptions): void;
637
+ declare function clearPersistedMcpAuth(): void;
638
+
639
+ export { type AgentBudgetSnapshot, type AgentConfigResponse, type ChatMessage, type ClearPersistedMcpAuthStateOptions, type ClientToolDefinition, type ClientToolParameter, type ClientToolsMap, type ConversationFeedback, type ConversationFeedbackSentiment, type ConversationMessagesPage, type ConversationReplayMessage, type McpAuthStatusEvent, type McpServerAuthConfig, type McpServerInfo, McpStackAgent, type McpStackAgentConfig, type McpStackAgentEvent, type McpStackAgentEventMap, type McpStackAppTokenAuthConfig, type McpStackEmbeddedAuthConfig, type McpStackEmbeddedAuthIdentity, type McpStackStorageLike, type OAuthTokenResponse, type PersistedStateStorage, type SseContentDelta, type SseError, type SseMessageEnd, type SseToolCall, type SubmitConversationFeedbackRequest, type WidgetConfig, clearPersistedMcpAuth, clearPersistedMcpAuthState };